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