Added logger statement
[appc.git] / appc-core / appc-common-bundle / src / main / java / org / onap / appc / pool / CachedElement.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Modifications Copyright (C) 2019 IBM
10  * =============================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  * 
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  * 
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  * 
23  * ============LICENSE_END=========================================================
24  */
25
26 package org.onap.appc.pool;
27
28 import java.io.Closeable;
29 import java.io.IOException;
30 import java.lang.reflect.InvocationHandler;
31 import java.lang.reflect.Method;
32 import java.lang.reflect.Proxy;
33 import java.util.concurrent.atomic.AtomicBoolean;
34 import com.att.eelf.configuration.EELFLogger;
35 import com.att.eelf.configuration.EELFManager;
36
37 /**
38  * This class is used as a "wrapper" for any closeable elements that are cached in a pool. It is
39  * implemented as a dynamic proxy, so that it appears to be the same class of object to the client
40  * as the interface being cached. The generic type being cached MUST be an interface.
41  * 
42  * @param <T> The generic type that we create a cached element for. This type is used to wrap
43  *        instances of this type and expose access to the {@link java.io.Closeable} interface by
44  *        using a dynamic proxy.
45  */
46
47 public class CachedElement<T extends Closeable>
48         implements Closeable, InvocationHandler, CacheManagement {
49         private static final EELFLogger LOG = EELFManager.getInstance().getLogger(CachedElement.class);
50
51     /**
52      * The pool that is managing this cached element
53      */
54     private Pool<T> pool;
55
56     /**
57      * The element that we are caching in the pool
58      */
59     private T element;
60
61     /**
62      * A thread-safe atomic indicator that tells us that the wrapped element has been released to
63      * the pool already, and not to do it again.
64      */
65     private AtomicBoolean released = new AtomicBoolean(false);
66
67     /**
68      * Create a new instance of a cached element dynamic proxy for use in the pool.
69      * <p>
70      * This returns an instance of the proxy to the caller that appears to be the same interface(s)
71      * as the object being cached. The dynamic proxy then intercepts all open and close semantics
72      * and directs that element to the pool.
73      * </p>
74      * <p>
75      * If the object being proxied does not implement the {@link CacheManagement} interface, then
76      * that interface is added to the dynamic proxy being created. This interface is actually
77      * implemented by the invocation handler (this object) for the proxy and allows direct access to
78      * the wrapped object inside the proxy.
79      * </p>
80      *
81      * @param pool The pool that we are caching these elements within
82      * @param element The element actually being cached
83      * @param interfaces The interface list of interfaces the element must implement (usually one)
84      * @return The dynamic proxy
85      */
86     @SuppressWarnings("unchecked")
87     public static <T extends Closeable> T newInstance(Pool<T> pool, T element,
88             Class<?>[] interfaces) {
89         ClassLoader cl = element.getClass().getClassLoader();
90         CachedElement<T> ce = new CachedElement<>(pool, element);
91         boolean found = false;
92         for (Class<?> intf : interfaces) {
93             if (intf.getName().equals(CacheManagement.class.getName())) {
94                 found = true;
95                 break;
96             }
97         }
98
99         int length = found ? interfaces.length : interfaces.length + 1;
100         Class<?>[] proxyInterfaces = new Class[length];
101         System.arraycopy(interfaces, 0, proxyInterfaces, 0, interfaces.length);
102
103         if (!found) {
104             proxyInterfaces[interfaces.length] = CacheManagement.class;
105         }
106
107         return (T) Proxy.newProxyInstance(cl, proxyInterfaces, ce);
108     }
109
110     /**
111      * Construct a cached element and assign it to the pool as a free element
112      *
113      * @param pool The pool that the element will be managed within
114      * @param element The element we are caching
115      */
116     @SuppressWarnings("unchecked")
117     public CachedElement(Pool<T> pool, T element) {
118         this.pool = pool;
119         this.element = element;
120
121         try {
122             pool.release((T) this);
123         } catch (PoolDrainedException e) {
124             LOG.error("Pool is empty", e);
125         }
126     }
127
128     /**
129      * This method delegates the close call to the actual wrapped element.
130      * <p>
131      * NOTE: This is not the same method that is called by the dynamic proxy. This method is in
132      * place to satisfy the signature of the {@link java.io.Closeable} interface. If it were to be
133      * called directly, then we will delegate the close to the underlying context. However, when the
134      * cached element is called as a synamic proxy, entry is in the
135      * {@link #invoke(Object, Method, Object[])} method.
136      * </p>
137      * 
138      * @see java.io.Closeable#close()
139      */
140     @Override
141     public void close() throws IOException {
142         element.close();
143     }
144
145     /**
146      * This method is the magic part of dynamic proxies. When the caller makes a method call based
147      * on the interface being proxied, this method is given control. This informs us of the method
148      * and arguments of the call. The object reference is that of the dynamic proxy itself, which is
149      * us.
150      * <p>
151      * Here we will check to see if the user is trying to close the "element" (the dynamic proxy
152      * acts like the wrapped element). If he is, then we don't really close it, but instead release
153      * the element that we are wrapping back to the free pool. Once this has happened, we mark the
154      * element as "closed" (from the perspective of this dynamic proxy) so that we wont try to
155      * release it again.
156      * </p>
157      * <p>
158      * If the method is the <code>equals</code> method then we assume that we are comparing the
159      * cached element in one dynamic proxy to the cached element in another. We execute the
160      * comparison between the cached elements, and not the dynamic proxies themselves. This
161      * preserves the allusion to the caller that the dynamic proxy is the object being wrapped.
162      * </p>
163      * <p>
164      * For convenience, we also implement the <code>getWrappedObject</code> method so that the
165      * dynamic proxy can be called to obtain the actual wrapped object if desired. Note, to use this
166      * method, the caller would have to invoke it through reflection.
167      * </p>
168      * <p>
169      * If the method being invoked is not one that we intercept, then we simply delegate that method
170      * onto the wrapped object.
171      * </p>
172      * 
173      * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method,
174      *      java.lang.Object[])
175      */
176     @SuppressWarnings({"unchecked", "nls"})
177     @Override
178     public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
179         Object result = null;
180
181         switch (method.getName()) {
182             case "close":
183                 if (released.compareAndSet(false, true)) {
184                     if (!pool.isDrained()) {
185                         pool.release((T) proxy);
186                     }
187                 }
188                 break;
189             case "equals":
190                 CacheManagement cm = (CacheManagement) proxy;
191                 T other = (T) cm.getWrappedObject();
192                 result = element.equals(other);
193                 break;
194             case "getWrappedObject":
195                 return element;
196             default:
197                 result = method.invoke(element, args);
198                 break;
199         }
200
201         return result;
202     }
203
204     /**
205      * This method is used to be able to access the wrapped object underneath the dynamic proxy
206      * 
207      * @see org.onap.appc.pool.CacheManagement#getWrappedObject()
208      */
209     @Override
210     public T getWrappedObject() {
211         return element;
212     }
213
214     @SuppressWarnings("nls")
215     @Override
216     public String toString() {
217         return element == null ? "null" : element.toString();
218     }
219 }