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