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