Organize Imports to be Checkstyle compliant in utils
[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      * 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      *
89      * Loads class using this supplied classloader.
90      *
91      *
92      * @param cls
93      * @param name String name of class.
94      * @return
95      * @throws ClassNotFoundException
96      */
97     public static Class<?> loadClass(final ClassLoader cls, final String name) throws ClassNotFoundException {
98         if ("byte[]".equals(name)) {
99             return byte[].class;
100         }
101         if ("char[]".equals(name)) {
102             return char[].class;
103         }
104         return loadClass0(cls,name);
105     }
106
107     private static Class<?> loadClass0(final ClassLoader cls, final String name) throws ClassNotFoundException {
108         try {
109             return cls.loadClass(name);
110         } catch (final ClassNotFoundException e) {
111             final List<String> components = DOT_SPLITTER.splitToList(name);
112
113             if (isInnerClass(components)) {
114                 final int length = components.size() - 1;
115                 final String outerName = Joiner.on(".").join(components.subList(0, length));
116                 final String innerName = outerName + "$" + components.get(length);
117                 return cls.loadClass(innerName);
118             } else {
119                 throw e;
120             }
121         }
122     }
123
124     private static boolean isInnerClass(final List<String> components) {
125         final int length = components.size();
126         if (length < 2) {
127             return false;
128         }
129
130         final String potentialOuter = components.get(length - 2);
131         if (potentialOuter == null) {
132             return false;
133         }
134         return Character.isUpperCase(potentialOuter.charAt(0));
135     }
136
137     public static Class<?> loadClassWithTCCL(final String name) throws ClassNotFoundException {
138         return loadClass(Thread.currentThread().getContextClassLoader(), name);
139     }
140
141     public static Class<?> tryToLoadClassWithTCCL(final String fullyQualifiedName) {
142         try {
143             return loadClassWithTCCL(fullyQualifiedName);
144         } catch (final ClassNotFoundException e) {
145             LOG.debug("Failed to load class {}", fullyQualifiedName, e);
146             return null;
147         }
148     }
149
150     public static <S,G,P> Class<P> findFirstGenericArgument(final Class<S> scannedClass, final Class<G> genericType) {
151         return withClassLoader(scannedClass.getClassLoader(), ClassLoaderUtils.findFirstGenericArgumentTask(scannedClass, genericType));
152     }
153
154     private static <S,G,P> Supplier<Class<P>> findFirstGenericArgumentTask(final Class<S> scannedClass, final Class<G> genericType) {
155         return new Supplier<Class<P>>() {
156             @Override
157             @SuppressWarnings("unchecked")
158             public Class<P> get() {
159                 final ParameterizedType augmentationGeneric = findParameterizedType(scannedClass, genericType);
160                 if (augmentationGeneric != null) {
161                     return (Class<P>) augmentationGeneric.getActualTypeArguments()[0];
162                 }
163                 return null;
164             }
165         };
166     }
167
168     public static ParameterizedType findParameterizedType(final Class<?> subclass, final Class<?> genericType) {
169         Preconditions.checkNotNull(subclass);
170         Preconditions.checkNotNull(genericType);
171
172         for (final Type type : subclass.getGenericInterfaces()) {
173             if (type instanceof ParameterizedType && genericType.equals(((ParameterizedType) type).getRawType())) {
174                 return (ParameterizedType) type;
175             }
176         }
177
178         LOG.debug("Class {} does not declare interface {}", subclass, genericType);
179         return null;
180     }
181
182     public static Type getFirstGenericParameter(final Type type) {
183         if (type instanceof ParameterizedType) {
184             return ((ParameterizedType) type).getActualTypeArguments()[0];
185         }
186         return null;
187     }
188 }