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