Fix for Bug 144, Bug 147, 148 - improved codec
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / sal / binding / impl / util / ClassLoaderUtils.java
1 package org.opendaylight.controller.sal.binding.impl.util;
2
3
4
5 import java.util.concurrent.Callable;
6 import java.util.concurrent.locks.Lock;
7
8 import static com.google.common.base.Preconditions.*;
9
10 import java.lang.reflect.Constructor;
11 import java.lang.reflect.InvocationTargetException;
12 import java.util.ArrayList;
13
14 import com.google.common.base.Optional;
15
16 public class ClassLoaderUtils {
17     
18     public static <V> V withClassLoader(ClassLoader cls,Callable<V> function) throws Exception {
19         return withClassLoaderAndLock(cls, Optional.<Lock>absent(), function);
20     }
21     
22     public static <V> V withClassLoaderAndLock(ClassLoader cls,Lock lock,Callable<V> function) throws Exception {
23         checkNotNull(lock,"Lock should not be null");
24         return withClassLoaderAndLock(cls, Optional.of(lock), function);
25     }
26     
27     public static <V> V withClassLoaderAndLock(ClassLoader cls,Optional<Lock> lock,Callable<V> function) throws Exception {
28         checkNotNull(cls, "Classloader should not be null");
29         checkNotNull(function,"Function should not be null");
30         if(lock.isPresent()) {
31             lock.get().lock();
32         }
33         ClassLoader oldCls = Thread.currentThread().getContextClassLoader();
34         try {
35             Thread.currentThread().setContextClassLoader(cls);
36             V result = function.call();
37             return result;
38         }  finally {
39             Thread.currentThread().setContextClassLoader(oldCls);
40             if(lock.isPresent()) {
41                 lock.get().unlock();
42             }
43         }
44     }
45
46     public static Object construct(Constructor<? extends Object> constructor, ArrayList<Object> objects) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
47     Object[] initargs = objects.toArray(new Object[]{});
48     return constructor.newInstance(initargs);
49     }
50     
51     
52     public static Class<?> loadClassWithTCCL(String name) throws ClassNotFoundException {
53         if("byte[]".equals(name)) {
54             return byte[].class;
55         }
56         
57         return Thread.currentThread().getContextClassLoader().loadClass(name);
58     }
59 }