6e65b03658f58b55b3268dd03d9af9fffb49fbc7
[yangtools.git] / common / util / src / main / java / org / opendaylight / yangtools / util / ClassLoaderUtils.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.yangtools.util;
9
10 import static com.google.common.base.Preconditions.checkNotNull;
11
12 import com.google.common.base.Joiner;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Splitter;
15 import com.google.common.base.Supplier;
16 import java.lang.reflect.Constructor;
17 import java.lang.reflect.InvocationTargetException;
18 import java.lang.reflect.ParameterizedType;
19 import java.lang.reflect.Type;
20 import java.util.List;
21 import java.util.concurrent.Callable;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24
25 public final class ClassLoaderUtils {
26     private static final Logger LOG = LoggerFactory.getLogger(ClassLoaderUtils.class);
27     private static final Splitter DOT_SPLITTER = Splitter.on('.');
28
29     private ClassLoaderUtils() {
30         throw new UnsupportedOperationException("Utility class");
31     }
32
33     /**
34      * Runs {@link Supplier} with provided {@link ClassLoader}.
35      *
36      * <p>Invokes supplies function and makes sure that original {@link ClassLoader}
37      * is context {@link ClassLoader} after execution.
38      *
39      * @param cls {@link ClassLoader} to be used.
40      * @param function Function to be executed.
41      * @return Result of supplier invocation.
42      */
43     public static <V> V withClassLoader(final ClassLoader cls, final Supplier<V> function) {
44         checkNotNull(cls, "Classloader should not be null");
45         checkNotNull(function, "Function should not be null");
46
47         final Thread currentThread = Thread.currentThread();
48         final ClassLoader oldCls = currentThread.getContextClassLoader();
49         try {
50             currentThread.setContextClassLoader(cls);
51             return function.get();
52         } finally {
53             currentThread.setContextClassLoader(oldCls);
54         }
55     }
56
57     /**
58      * Runs {@link Callable} with provided {@link ClassLoader}.
59      *
60      * Invokes supplies function and makes sure that original {@link ClassLoader}
61      * is context {@link ClassLoader} after execution.
62      *
63      * @param cls {@link ClassLoader} to be used.
64      * @param function Function to be executed.
65      * @return Result of callable invocation.
66      */
67     public static <V> V withClassLoader(final ClassLoader cls, final Callable<V> function) throws Exception {
68         checkNotNull(cls, "Classloader should not be null");
69         checkNotNull(function, "Function should not be null");
70
71         final Thread currentThread = Thread.currentThread();
72         final ClassLoader oldCls = currentThread.getContextClassLoader();
73         try {
74             currentThread.setContextClassLoader(cls);
75             return function.call();
76         } finally {
77             currentThread.setContextClassLoader(oldCls);
78         }
79     }
80
81     public static Object construct(final Constructor<?> constructor, final List<Object> objects)
82             throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
83         final Object[] initargs = objects.toArray();
84         return constructor.newInstance(initargs);
85     }
86
87     /**
88      * Loads class using this supplied classloader.
89      *
90      * @param name String name of class.
91      */
92     public static Class<?> loadClass(final ClassLoader cls, final String name) throws ClassNotFoundException {
93         if ("byte[]".equals(name)) {
94             return byte[].class;
95         }
96         if ("char[]".equals(name)) {
97             return char[].class;
98         }
99         return loadClass0(cls,name);
100     }
101
102     private static Class<?> loadClass0(final ClassLoader cls, final String name) throws ClassNotFoundException {
103         try {
104             return cls.loadClass(name);
105         } catch (final ClassNotFoundException e) {
106             final List<String> components = DOT_SPLITTER.splitToList(name);
107
108             if (isInnerClass(components)) {
109                 final int length = components.size() - 1;
110                 final String outerName = Joiner.on(".").join(components.subList(0, length));
111                 final String innerName = outerName + "$" + components.get(length);
112                 return cls.loadClass(innerName);
113             }
114
115             throw e;
116         }
117     }
118
119     private static boolean isInnerClass(final List<String> components) {
120         final int length = components.size();
121         if (length < 2) {
122             return false;
123         }
124
125         final String potentialOuter = components.get(length - 2);
126         if (potentialOuter == null) {
127             return false;
128         }
129         return Character.isUpperCase(potentialOuter.charAt(0));
130     }
131
132     public static Class<?> loadClassWithTCCL(final String name) throws ClassNotFoundException {
133         return loadClass(Thread.currentThread().getContextClassLoader(), name);
134     }
135
136     public static Class<?> tryToLoadClassWithTCCL(final String fullyQualifiedName) {
137         try {
138             return loadClassWithTCCL(fullyQualifiedName);
139         } catch (final ClassNotFoundException e) {
140             LOG.debug("Failed to load class {}", fullyQualifiedName, e);
141             return null;
142         }
143     }
144
145     public static <S,G,P> Class<P> findFirstGenericArgument(final Class<S> scannedClass, final Class<G> genericType) {
146         return withClassLoader(scannedClass.getClassLoader(), findFirstGenericArgumentTask(scannedClass, genericType));
147     }
148
149     @SuppressWarnings("unchecked")
150     private static <S, G, P> Supplier<Class<P>> findFirstGenericArgumentTask(final Class<S> scannedClass,
151             final Class<G> genericType) {
152         return () -> {
153             final ParameterizedType augmentationGeneric = findParameterizedType(scannedClass, genericType);
154             if (augmentationGeneric != null) {
155                 return (Class<P>) augmentationGeneric.getActualTypeArguments()[0];
156             }
157             return null;
158         };
159     }
160
161     public static ParameterizedType findParameterizedType(final Class<?> subclass, final Class<?> genericType) {
162         Preconditions.checkNotNull(subclass);
163         Preconditions.checkNotNull(genericType);
164
165         for (final Type type : subclass.getGenericInterfaces()) {
166             if (type instanceof ParameterizedType && genericType.equals(((ParameterizedType) type).getRawType())) {
167                 return (ParameterizedType) type;
168             }
169         }
170
171         LOG.debug("Class {} does not declare interface {}", subclass, genericType);
172         return null;
173     }
174
175     public static Type getFirstGenericParameter(final Type type) {
176         if (type instanceof ParameterizedType) {
177             return ((ParameterizedType) type).getActualTypeArguments()[0];
178         }
179         return null;
180     }
181 }