Bug 6859 #3 Binding generator v1 refactoring
[mdsal.git] / binding / mdsal-binding-generator-impl / src / main / java / org / opendaylight / mdsal / binding / generator / util / JavassistUtils.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.mdsal.binding.generator.util;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Preconditions;
12 import java.util.Collection;
13 import java.util.Map;
14 import java.util.WeakHashMap;
15 import javassist.CannotCompileException;
16 import javassist.ClassClassPath;
17 import javassist.ClassPath;
18 import javassist.ClassPool;
19 import javassist.CtClass;
20 import javassist.CtField;
21 import javassist.CtMethod;
22 import javassist.LoaderClassPath;
23 import javassist.Modifier;
24 import javassist.NotFoundException;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 /**
29  * Users of this utility class are expected to synchronize on this instance
30  * it they need to ensure atomic operations on it.
31  */
32 public final class JavassistUtils {
33     private static final Logger LOG = LoggerFactory.getLogger(JavassistUtils.class);
34
35     private static final Map<ClassPool, JavassistUtils> INSTANCES = new WeakHashMap<>();
36     private final Map<ClassLoader, ClassPath> loaderClassPaths = new WeakHashMap<>();
37     private final ClassPool classPool;
38
39     private JavassistUtils(final ClassPool pool) {
40         classPool = Preconditions.checkNotNull(pool);
41     }
42
43     /**
44      * Get a utility instance for a particular class pool. A new instance is
45      * created if this is a new pool. If an instance already exists, is is
46      * returned.
47      *
48      * @param pool Backing class pool
49      * @return shared utility instance for specified pool
50      */
51     public static synchronized JavassistUtils forClassPool(final ClassPool pool) {
52         JavassistUtils ret = INSTANCES.get(Preconditions.checkNotNull(pool));
53         if (ret == null) {
54             ret = new JavassistUtils(pool);
55             INSTANCES.put(pool, ret);
56         }
57         return ret;
58     }
59
60     public void method(final CtClass it, final Class<?> returnType, final String name,
61             final Class<?> parameter, final MethodGenerator function1) throws CannotCompileException {
62         final CtClass[] pa = new CtClass[] { asCtClass(parameter) };
63         final CtMethod method = new CtMethod(asCtClass(returnType), name, pa, it);
64
65         function1.process(method);
66         it.addMethod(method);
67     }
68
69     public void method(final CtClass it, final Class<?> returnType, final String name,
70             final Collection<? extends Class<?>> parameters, final MethodGenerator function1) throws CannotCompileException {
71         final CtClass[] pa = new CtClass[parameters.size()];
72
73         int i = 0;
74         for (Class<?> parameter : parameters) {
75             pa[i] = asCtClass(parameter);
76             ++i;
77         }
78
79         final CtMethod method = new CtMethod(asCtClass(returnType), name, pa, it);
80         function1.process(method);
81         it.addMethod(method);
82     }
83
84     public void staticMethod(final CtClass it, final Class<?> returnType, final String name,
85             final Class<?> parameter, final MethodGenerator function1) throws CannotCompileException {
86         final CtClass[] pa = new CtClass[] { asCtClass(parameter) };
87         final CtMethod method = new CtMethod(asCtClass(returnType), name, pa, it);
88         function1.process(method);
89         it.addMethod(method);
90     }
91
92     public void implementMethodsFrom(final CtClass target, final CtClass source, final MethodGenerator function1) throws CannotCompileException {
93         for (CtMethod method : source.getMethods()) {
94             if (method.getDeclaringClass() == source) {
95                 CtMethod redeclaredMethod = new CtMethod(method, target, null);
96                 function1.process(redeclaredMethod);
97                 target.addMethod(redeclaredMethod);
98             }
99         }
100     }
101
102     public CtClass createClass(final String fqn, final ClassGenerator cls) throws CannotCompileException {
103         CtClass target = classPool.makeClass(fqn);
104         cls.process(target);
105         return target;
106     }
107
108     public CtClass createClass(final String fqn, final CtClass superInterface, final ClassGenerator cls) throws CannotCompileException {
109         CtClass target = classPool.makeClass(fqn);
110         implementsType(target, superInterface);
111         cls.process(target);
112         return target;
113     }
114
115     /**
116      * Instantiate a new class based on a prototype. The class is set to automatically
117      * prune.
118      *
119      * @param prototype Prototype class fully qualified name
120      * @param fqn Target class fully qualified name
121      * @param customizer Customization callback to be invoked on the new class
122      * @return An instance of the new class
123      * @throws NotFoundException when the prototype class is not found
124      */
125     @Beta
126     public synchronized CtClass instantiatePrototype(final String prototype, final String fqn, final ClassCustomizer customizer) throws NotFoundException {
127         final CtClass result = classPool.getAndRename(prototype, fqn);
128         try {
129             customizer.customizeClass(result);
130         } catch (Exception e) {
131             LOG.warn("Failed to customize {} from prototype {}", fqn, prototype, e);
132             result.detach();
133             throw new IllegalStateException(String.format("Failed to instantiate prototype %s as %s", prototype, fqn), e);
134         }
135
136         result.stopPruning(false);
137         return result;
138     }
139
140     public void implementsType(final CtClass it, final CtClass supertype) {
141         Preconditions.checkArgument(supertype.isInterface(), "Supertype must be interface");
142         it.addInterface(supertype);
143     }
144
145     public CtClass asCtClass(final Class<?> class1) {
146         return get(this.classPool, class1);
147     }
148
149     public CtField field(final CtClass it, final String name, final Class<?> returnValue) throws CannotCompileException {
150         final CtField field = new CtField(asCtClass(returnValue), name, it);
151         field.setModifiers(Modifier.PUBLIC);
152         it.addField(field);
153         return field;
154     }
155
156     public CtField staticField(final CtClass it, final String name, final Class<?> returnValue) throws CannotCompileException {
157         return staticField(it, name, returnValue, null);
158     }
159
160     public CtField staticField(final CtClass it, final String name,
161             final Class<?> returnValue,
162             final SourceCodeGenerator sourceGenerator) throws CannotCompileException {
163         final CtField field = new CtField(asCtClass(returnValue), name, it);
164         field.setModifiers(Modifier.PUBLIC + Modifier.STATIC);
165         it.addField(field);
166
167         if (sourceGenerator != null) {
168             sourceGenerator.appendField(field, null);
169         }
170
171         return field;
172     }
173
174     public CtClass get(final ClassPool pool, final Class<? extends Object> cls) {
175         try {
176             return pool.get(cls.getName());
177         } catch (NotFoundException nfe1) {
178             appendClassLoaderIfMissing(cls.getClassLoader());
179             try {
180                 return pool.get(cls.getName());
181             } catch (final NotFoundException nfe2) {
182                 LOG.warn("Appending ClassClassPath for {}", cls, nfe2);
183                 pool.appendClassPath(new ClassClassPath(cls));
184                 try {
185                     return pool.get(cls.getName());
186                 } catch (NotFoundException e) {
187                     LOG.warn("Failed to load class {} from pool {}", cls, pool, e);
188                     throw new IllegalStateException("Failed to load class", e);
189                 }
190             }
191         }
192     }
193
194     public synchronized void appendClassLoaderIfMissing(final ClassLoader loader) {
195         if (!loaderClassPaths.containsKey(loader)) {
196             final ClassPath ctLoader = new LoaderClassPath(loader);
197             classPool.appendClassPath(ctLoader);
198             loaderClassPaths.put(loader, ctLoader);
199         }
200     }
201
202     public void ensureClassLoader(final Class<?> child) {
203         appendClassLoaderIfMissing(child.getClassLoader());
204     }
205 }