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