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