Пример #1
1
 private Connection openConnection(Class<? extends Driver> driverClass, Properties properties)
     throws Exception {
   assert properties != null;
   try {
     return DriverManager.getConnection(url, properties);
   } catch (Exception e) {
     // if the current class loader can not access the driver class, create driver class directly
     try {
       Driver driverObject = driverClass.getConstructor().newInstance();
       Connection connection = driverObject.connect(url, properties);
       if (connection == null) {
         throw new IllegalStateException(
             MessageFormat.format(
                 "Driver class {0} may not support {1}", driverClass.getName(), url));
       }
       return connection;
     } catch (RuntimeException inner) {
       LOG.debug(
           MessageFormat.format(
               "Failed to resolve driver class (internal error): {0} (on {1})",
               driverClass.getName(), driverClass.getClassLoader()),
           e);
     } catch (Exception inner) {
       LOG.debug(
           MessageFormat.format(
               "Failed to resolve driver class: {0} (on {1})",
               driverClass.getName(), driverClass.getClassLoader()),
           e);
     }
     throw e;
   }
 }
Пример #2
1
  @StubMethod
  public static ClassMirror getCallerClassMirror(int depth) {
    // Filter out any non-holographic frames
    int nativeDepth = 1;
    Class<?> klass = sun.reflect.Reflection.getCallerClass(nativeDepth);
    while (klass != null) {
      ClassLoader loader = klass.getClassLoader();
      if (loader instanceof HologramClassLoader) {
        if (depth == 0) {
          HologramClassLoader hologramClassLoader = (HologramClassLoader) klass.getClassLoader();
          String className = HologramClassGenerator.getOriginalBinaryClassName(klass.getName());
          return hologramClassLoader.loadOriginalClassMirror(className);
        }
        depth--;
      }
      nativeDepth++;
      klass = sun.reflect.Reflection.getCallerClass(nativeDepth);
    }

    // Off the top of the holographic stack, so refer to the original stack.
    ThreadMirror currentThread = ThreadHolograph.currentThreadMirror();
    List<FrameMirror> stack = currentThread.getStackTrace();
    int frameIndex = stack.size() - 1 - depth;
    if (frameIndex < 0) {
      return null;
    }
    FrameMirror frame = stack.get(frameIndex);
    return frame.declaringClass();
  }
Пример #3
1
  protected void purgeEntries(Field properties)
      throws IllegalArgumentException, IllegalAccessException {
    if (properties == null) return;

    if (!properties.isAccessible()) properties.setAccessible(true);

    ConcurrentHashMap map = (ConcurrentHashMap) properties.get(null);
    if (map == null) return;

    Iterator<Class> itor = map.keySet().iterator();
    while (itor.hasNext()) {
      Class clazz = itor.next();
      LOG.info("Clazz: " + clazz + " loaded by " + clazz.getClassLoader());
      if (Thread.currentThread().getContextClassLoader().equals(clazz.getClassLoader())) {
        itor.remove();
        LOG.info("removed");
      } else
        LOG.info(
            "not removed: "
                + "contextclassloader="
                + Thread.currentThread().getContextClassLoader()
                + "clazz's classloader="
                + clazz.getClassLoader());
    }
  }
 /**
  * Instantiate an object given a class name. Check that the <code>className</code> is a subclass
  * of <code>superClass</code>. If that test fails or the object could not be instantiated, then
  * <code>defaultValue</code> is returned.
  *
  * @param className The fully qualified class name of the object to instantiate.
  * @param superClass The class to which the new object should belong.
  * @param defaultValue The object to return in case of non-fulfillment
  */
 public static Object instantiateByClassName(
     String className, Class superClass, Object defaultValue) {
   if (className != null) {
     try {
       Class classObj = Loader.loadClass(className);
       if (!superClass.isAssignableFrom(classObj)) {
         LogLog.error(
             "A \""
                 + className
                 + "\" object is not assignable to a \""
                 + superClass.getName()
                 + "\" variable.");
         LogLog.error("The class \"" + superClass.getName() + "\" was loaded by ");
         LogLog.error("[" + superClass.getClassLoader() + "] whereas object of type ");
         LogLog.error(
             "\"" + classObj.getName() + "\" was loaded by [" + classObj.getClassLoader() + "].");
         return defaultValue;
       }
       return classObj.newInstance();
     } catch (Exception e) {
       LogLog.error("Could not instantiate class [" + className + "].", e);
     }
   }
   return defaultValue;
 }
Пример #5
1
  public static void main(String[] args) throws Exception {
    Class clazz = Class.forName("java.lang.String");

    System.out.println(clazz.getClassLoader());

    Class clazz2 = Class.forName("com.shengsiyuan.classloader.C");

    System.out.println(clazz2.getClassLoader());
  }
Пример #6
1
 public ModuleManager createModuleManagerProxy(
     PluginVersionReference pluginVersionReference, InvocationHandler invocationHandler)
     throws CantCreateProxyException {
   ModuleManager moduleManager = null;
   if (!openModules.containsKey(pluginVersionReference)) {
     try {
       ModuleManager moduleManagerBase =
           FermatSystem.getInstance().getModuleManager2(pluginVersionReference);
       if (moduleManagerBase == null)
         throw new RuntimeException(
             "Module manager null in platform, please check if your plugin is connected, pluginVersionReference: "
                 + pluginVersionReference.toString3());
       Class clazz = moduleManagerBase.getClass();
       moduleManager =
           (ModuleManager)
               Proxy.newProxyInstance(
                   clazz.getClassLoader(), clazz.getInterfaces(), invocationHandler);
       openModules.put(clazz, moduleManager);
     } catch (CantGetModuleManagerException e) {
       try {
         Class clazz = FermatSystem.getInstance().getModuleManager3(pluginVersionReference);
         if (clazz == null)
           throw new RuntimeException(
               "Module manager null in platform, please check if your plugin is connected, pluginVersionReference: "
                   + pluginVersionReference.toString3());
         moduleManager =
             (ModuleManager)
                 Proxy.newProxyInstance(
                     clazz.getClassLoader(), clazz.getInterfaces(), invocationHandler);
         openModules.put(clazz, moduleManager);
       } catch (Exception e2) {
         Log.e(
             TAG,
             "Cant get module manager in platform, please check if your plugin is connected, pluginVersionReference: "
                 + pluginVersionReference.toString3());
         throw new CantCreateProxyException(
             "Cant get module manager from system", e, "factory", "");
       }
     } catch (ModuleManagerNotFoundException e) {
       Log.e(
           TAG,
           "Cant get module manager in platform, please check if your plugin is connected, pluginVersionReference: "
               + pluginVersionReference.toString3());
       throw new CantCreateProxyException(
           "Cant fount module manager from system", e, "factory", "");
     }
   } else {
     moduleManager = openModules.get(pluginVersionReference);
   }
   //        Log.i(TAG,"interfaces: ");
   //        for (Class<?> aClass : moduleManager.getClass().getInterfaces()) {
   //            Log.i(TAG,aClass.getName());
   //        }
   return moduleManager;
 }
  public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
    Class<?> clazz = findLoadedClass(name);
    if (clazz != null) {
      return clazz;
    }

    if (!overrideClass.equals(name)) {
      try {
        clazz = getSystemClassLoader().loadClass(name);
        if (clazz != null) {
          if (resolve) resolveClass(clazz);
          log(
              "Returning (System ClassLoader) "
                  + clazz
                  + " with class loader: "
                  + clazz.getClassLoader());
          return (clazz);
        }
      } catch (ClassNotFoundException e) {
      }

      ClassLoader loader = getParent();
      if (loader != null) {
        try {
          clazz = loader.loadClass(name);
          if (clazz != null) {
            if (resolve) resolveClass(clazz);
            log(
                "Returning (Parent ClassLoader) "
                    + clazz
                    + " with class loader: "
                    + clazz.getClassLoader());
            return (clazz);
          }
        } catch (ClassNotFoundException e) {
        }
      }
    }

    String file = convertToFile(name);
    if (memoryMappedFiles.containsKey(file)) {
      clazz = findClass(name);
      if (clazz != null) {
        if (resolve) resolveClass(clazz);
        log(
            "Returning (OverrideJarClassLoader) "
                + clazz
                + " with class loader: "
                + clazz.getClassLoader());
        return clazz;
      }
    }

    throw new ClassNotFoundException(name);
  }
Пример #8
0
  private static ClassLoader getClassLoader(Class<?> clazz) {
    if (clazz != null && clazz.getClassLoader() != null) {
      return clazz.getClassLoader();
    }

    if (Thread.currentThread().getContextClassLoader() != null) {
      return Thread.currentThread().getContextClassLoader();
    }

    return ClassLoader.getSystemClassLoader();
  }
Пример #9
0
 public ClassLoader[] findClassLoaders(String className) {
   List<ClassLoader> list = new ArrayList<ClassLoader>();
   try {
     ClassLoader cl = getClassLoader();
     while (cl != null) {
       Vector<?> loadedClasses = Util.getField(cl, ClassLoader.class, "classes", Vector.class);
       boolean founded = false;
       for (Object object : loadedClasses) {
         Class<?> clz = (Class<?>) object;
         if (clz.getName().equals(className)) {
           list.add(clz.getClassLoader());
           founded = true;
           break;
         }
       }
       if (!founded) {
         Class<?> clz;
         try {
           clz =
               Util.invokeMethod(
                   cl,
                   ClassLoader.class,
                   "findClass",
                   new Class[] {String.class},
                   new Object[] {className},
                   Class.class);
           list.add(clz.getClassLoader());
         } catch (InvocationTargetException e) {
           if (!(e.getCause() instanceof ClassNotFoundException)) {
             // ignore class not found
             if (e.getCause() instanceof SecurityException) {
               if (reportErrorNoPermission) {
                 throw (SecurityException) e.getCause();
               }
             }
           }
         }
       }
       cl = cl.getParent();
     }
     // check bootstrap classes
     Resource resource = Launcher.getBootstrapClassPath().getResource(Util.resolveName(className));
     if (resource != null) {
       // bootstrap classloader in first
       list.add(0, null);
     }
   } catch (RuntimeException e) {
     if (reportErrorNoPermission) {
       throw e;
     }
   }
   return list.toArray(new ClassLoader[list.size()]);
 }
 /**
  * Return whether or not the persistence unit bundle has a consistent JPA interface class space
  * with the provider bundle. This method must be called after both bundles have been resolved.
  */
 public boolean areCompatibleBundles(Bundle pUnitBundle, Bundle providerBundle) {
   try {
     debug("Extender - checking bundle compatibility of: ", pUnitBundle);
     Class<?> pUnitClass = pUnitBundle.loadClass("javax.persistence.Entity");
     Class<?> providerClass = providerBundle.loadClass("javax.persistence.Entity");
     return pUnitClass.getClassLoader() == providerClass.getClassLoader();
   } catch (ClassNotFoundException cnfEx) {
     // If one of the bundles does not have the class in its class space
     // then by definition the two are consistent w.r.t. that package
     return true;
   }
 }
Пример #11
0
 Class<?> getHandlerClass(Class<?> frameClass) throws ClassNotFoundException {
   JavaHandlerClass handlerClass = frameClass.getAnnotation(JavaHandlerClass.class);
   if (handlerClass != null) {
     return handlerClass.value();
   }
   if (frameClass.getClassLoader() == null) {
     throw new ClassNotFoundException(
         "FrameClass: "
             + frameClass.getCanonicalName()
             + " getClassLoader() returned null... no $Impl can be found in this case!");
   }
   return frameClass.getClassLoader().loadClass(frameClass.getName() + "$Impl");
 }
Пример #12
0
 /**
  * Returns the per class aspect instance for the aspect with the given name for the perTarget
  * model
  *
  * @param name the name of the aspect
  * @param targetClass the targetClass class
  * @return the per class aspect instance
  */
 public static Object aspectOf(final String name, final Class targetClass) {
   try {
     Class aspectClass = Class.forName(name, false, targetClass.getClassLoader());
     return aspectOf(aspectClass, targetClass);
   } catch (ClassNotFoundException e) {
     // try to guess it from the system definitions if we have a uuid prefix
     String className =
         lookupAspectClassName(Thread.currentThread().getContextClassLoader(), name);
     if (className != null) {
       return aspectOf(className, targetClass);
     } else {
       throw new Error("Could not load aspect " + name + " from " + targetClass.getClassLoader());
     }
   }
 }
 Class<?> getHandlerClass(Class<?> frameClass) throws ClassNotFoundException {
   JavaHandlerClass handlerClass = frameClass.getAnnotation(JavaHandlerClass.class);
   if (handlerClass != null) {
     return handlerClass.value();
   }
   return frameClass.getClassLoader().loadClass(frameClass.getName() + "$Impl");
 }
Пример #14
0
    public Class<? extends T> generate() {
      visitor.visitEnd();

      byte[] bytecode = visitor.toByteArray();
      return DEFINE_CLASS_METHOD.invoke(
          type.getClassLoader(), typeName, bytecode, 0, bytecode.length);
    }
Пример #15
0
  /**
   * Creates a Scriptella Driver using specified class.
   *
   * <p>If class is a {@link Driver} {@link GenericDriver JDBC Bridge} is used.
   *
   * <p>To be successfully instantiated the driver class must implement {@link ScriptellaDriver}
   * class and has no-arg public constructor.
   *
   * @param drvClass driver class.
   * @return Scriptella Driver
   */
  @SuppressWarnings("unchecked")
  public static ScriptellaDriver getDriver(Class drvClass) {
    if (Driver.class.isAssignableFrom(drvClass)) {
      // We must load JDBC driver using the same classloader as drvClass
      try {

        ClassLoader drvClassLoader = drvClass.getClassLoader();
        if (drvClassLoader == null) { // if boot classloader is used,
          // load scriptella driver using the class loader for this class.
          drvClassLoader = DriverFactory.class.getClassLoader();
        }
        Class<?> cl = Class.forName("scriptella.jdbc.GenericDriver", true, drvClassLoader);
        return (ScriptellaDriver) cl.newInstance();
      } catch (Exception e) {
        throw new IllegalStateException("Unable to instantiate JDBC driver for " + drvClass, e);
      }
    } else if (ScriptellaDriver.class.isAssignableFrom(drvClass)) {
      try {
        return (ScriptellaDriver) drvClass.newInstance();
      } catch (Exception e) {
        throw new IllegalStateException("Unable to instantiate driver for " + drvClass, e);
      }

    } else {
      throw new IllegalArgumentException(
          "Class " + drvClass + " is not a scriptella compatible driver.");
    }
  }
 private Callback createReverseEngineeredCallbackOfProperType(
     Callback callback, int index, Map callbackIndexMap) {
   Class iface = null;
   Class[] interfaces = callback.getClass().getInterfaces();
   for (int i = 0; i < interfaces.length; i++) {
     if (Callback.class.isAssignableFrom(interfaces[i])) {
       iface = interfaces[i];
       if (iface == Callback.class) {
         ConversionException exception = new ConversionException("Cannot handle CGLIB callback");
         exception.add("CGLIB callback type", callback.getClass().getName());
         throw exception;
       }
       interfaces = iface.getInterfaces();
       if (Arrays.asList(interfaces).contains(Callback.class)) {
         break;
       }
       i = -1;
     }
   }
   return (Callback)
       Proxy.newProxyInstance(
           iface.getClassLoader(),
           new Class[] {iface},
           new ReverseEngineeringInvocationHandler(index, callbackIndexMap));
 }
Пример #17
0
  void enableLionFS() {
    try {
      String version = System.getProperty("os.version");
      String[] tokens = version.split("\\.");
      int major = Integer.parseInt(tokens[0]), minor = 0;
      if (tokens.length > 1) minor = Integer.parseInt(tokens[1]);
      if (major < 10 || (major == 10 && minor < 7))
        throw new Exception("Operating system version is " + version);

      Class fsuClass = Class.forName("com.apple.eawt.FullScreenUtilities");
      Class argClasses[] = new Class[] {Window.class, Boolean.TYPE};
      Method setWindowCanFullScreen = fsuClass.getMethod("setWindowCanFullScreen", argClasses);
      setWindowCanFullScreen.invoke(fsuClass, this, true);

      Class fsListenerClass = Class.forName("com.apple.eawt.FullScreenListener");
      InvocationHandler fsHandler = new MyInvocationHandler(cc);
      Object proxy =
          Proxy.newProxyInstance(
              fsListenerClass.getClassLoader(), new Class[] {fsListenerClass}, fsHandler);
      argClasses = new Class[] {Window.class, fsListenerClass};
      Method addFullScreenListenerTo = fsuClass.getMethod("addFullScreenListenerTo", argClasses);
      addFullScreenListenerTo.invoke(fsuClass, this, proxy);

      canDoLionFS = true;
    } catch (Exception e) {
      vlog.debug("Could not enable OS X 10.7+ full-screen mode:");
      vlog.debug("  " + e.toString());
    }
  }
	@Override
	public DynamicQuery dynamicQuery() {
		Class<?> clazz = getClass();

		return DynamicQueryFactoryUtil.forClass(Message.class,
			clazz.getClassLoader());
	}
Пример #19
0
  /**
   * Gets the application base directory.
   *
   * @return the base directory
   */
  public static URL getBaseDir() {
    try {
      Class<?> c =
          (new Object() {
                public String toString() {
                  return super.toString();
                }
              })
              .getClass();

      /* We're using the classloader to determine the base URL. */
      ClassLoader cl = c.getClassLoader();
      URL url = cl.getResource(".");

      if (url == null) {
        return getBaseDir(c);
      }

      String protocol = url.getProtocol().toLowerCase();
      String host = url.getHost().toLowerCase();
      String basePathString = url.getFile();

      if (basePathString.endsWith("/bin")
          || basePathString.endsWith("/bin/")
          || basePathString.endsWith("/build")
          || basePathString.endsWith("/build/")) {
        basePathString = (new File(basePathString)).getParent();
      }
      return new URL(protocol, host, basePathString);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
Пример #20
0
 @SuppressWarnings("unchecked")
 public synchronized <T> T getService(Class<T> serviceInterface, String hostname, int port) {
   // if (socketProvider == null) {
   // if (log.isInfoEnabled()) {
   // log.info("The current socketProvider is null. Then using default provider:
   // \"SimpleSocketProvider\".");
   // }
   // socketProvider = new SimpleSocketProvider();
   // }
   if (socketChannelProvider == null) {
     socketChannelProvider = new SimpleSocketChannelProvider();
   }
   if (byteOrder == null) {
     if (log.isInfoEnabled()) {
       log.info("The current byteOrder is null. Then using defaul byteOrder: \"BIG_ENDIAN\".");
     }
     byteOrder = ByteOrder.BIG_ENDIAN;
   }
   if (dataBufferProvider == null) {
     if (log.isInfoEnabled()) {
       log.info(
           "The current dataBufferProvider is null. Then using the default: \"CachedDataBufferProvider\".");
     }
     dataBufferProvider = new CachedDataBufferProvider(byteOrder);
   }
   Object proxy =
       Proxy.newProxyInstance(
           serviceInterface.getClassLoader(),
           new Class[] {serviceInterface},
           icmInvocationHandler);
   endpoints.put(proxy, new EndPoint(hostname, port));
   return (T) proxy;
 }
Пример #21
0
  /**
   * Invokes main() method on class with provided parameters.
   *
   * @param sClass class name in form "MyClass" for default package or "com.abc.MyClass" for class
   *     in some package
   * @param args arguments for the main() method or null.
   * @throws Throwable wrapper for many exceptions thrown while
   *     <p>(1) main() method lookup: ClassNotFoundException, SecurityException,
   *     NoSuchMethodException
   *     <p>(2) main() method launch: IllegalArgumentException, IllegalAccessException (disabled)
   *     <p>(3) Actual cause of InvocationTargetException
   *     <p>See {@link
   *     http://java.sun.com/developer/Books/javaprogramming/JAR/api/jarclassloader.html} and {@link
   *     http://java.sun.com/developer/Books/javaprogramming/JAR/api/example-1dot2/JarClassLoader.java}
   */
  public void invokeMain(String sClass, String[] args) throws Throwable {
    Class<?> clazz = loadClass(sClass);
    logInfo(LogArea.CONFIG, "Launch: %s.main(); Loader: %s", sClass, clazz.getClassLoader());
    Method method = clazz.getMethod("main", new Class<?>[] {String[].class});

    boolean bValidModifiers = false;
    boolean bValidVoid = false;

    if (method != null) {
      method.setAccessible(true); // Disable IllegalAccessException
      int nModifiers = method.getModifiers(); // main() must be "public static"
      bValidModifiers = Modifier.isPublic(nModifiers) && Modifier.isStatic(nModifiers);
      Class<?> clazzRet = method.getReturnType(); // main() must be "void"
      bValidVoid = (clazzRet == void.class);
    }
    if (method == null || !bValidModifiers || !bValidVoid) {
      throw new NoSuchMethodException("The main() method in class \"" + sClass + "\" not found.");
    }

    // Invoke method.
    // Crazy cast "(Object)args" because param is: "Object... args"
    try {
      method.invoke(null, (Object) args);
    } catch (InvocationTargetException e) {
      throw e.getTargetException();
    }
  } // invokeMain()
Пример #22
0
  /**
   * Format a string buffer containing the Class, Interfaces, CodeSource, and ClassLoader
   * information for the given object clazz.
   *
   * @param clazz the Class
   * @param results, the buffer to write the info to
   */
  public static void displayClassInfo(Class clazz, StringBuffer results) {
    // Print out some codebase info for the ProbeHome
    ClassLoader cl = clazz.getClassLoader();
    results.append("\n" + clazz.getName() + ".ClassLoader=" + cl);
    ClassLoader parent = cl;
    while (parent != null) {
      results.append("\n.." + parent);
      URL[] urls = getClassLoaderURLs(parent);
      int length = urls != null ? urls.length : 0;
      for (int u = 0; u < length; u++) {
        results.append("\n...." + urls[u]);
      }
      if (parent != null) parent = parent.getParent();
    }
    CodeSource clazzCS = clazz.getProtectionDomain().getCodeSource();
    if (clazzCS != null) results.append("\n++++CodeSource: " + clazzCS);
    else results.append("\n++++Null CodeSource");

    results.append("\nImplemented Interfaces:");
    Class[] ifaces = clazz.getInterfaces();
    for (int i = 0; i < ifaces.length; i++) {
      results.append("\n++" + ifaces[i]);
      ClassLoader loader = ifaces[i].getClassLoader();
      results.append("\n++++ClassLoader: " + loader);
      ProtectionDomain pd = ifaces[i].getProtectionDomain();
      CodeSource cs = pd.getCodeSource();
      if (cs != null) results.append("\n++++CodeSource: " + cs);
      else results.append("\n++++Null CodeSource");
    }
  }
Пример #23
0
 public URL locateCodeSource(Class<?> clz) {
   if (clz == null) {
     throw new IllegalArgumentException("null class");
   }
   ProtectionDomain protectionDomain = null;
   try {
     protectionDomain = clz.getProtectionDomain();
   } catch (SecurityException e) {
     // got security error
     if (reportErrorNoPermission) {
       throw e;
     } else {
       return null;
     }
   }
   if (protectionDomain != null && protectionDomain.getCodeSource() != null) {
     return protectionDomain.getCodeSource().getLocation();
   }
   if (clz.getClassLoader() == null) {
     // bootstrap loader
     String name = Util.resolveName(clz.getName());
     URL resourceURL = Util.getDummyLoader().getResource(name);
     return Util.extractBaseURL(resourceURL, name);
   }
   return null;
 }
Пример #24
0
 /**
  * Force initialization of the static members. As of Java 5, referencing a class doesn't force it
  * to initialize. Since this class requires that the classes be initialized to declare their
  * comparators, we force that initialization to happen.
  *
  * @param cls the class to initialize
  */
 private static void forceInit(Class<?> cls) {
   try {
     Class.forName(cls.getName(), true, cls.getClassLoader());
   } catch (ClassNotFoundException e) {
     throw new IllegalArgumentException("Can't initialize class " + cls, e);
   }
 }
Пример #25
0
 /**
  * 生成代理方法
  *
  * @param <T> 泛型
  * @param mapperInterface mapper接口
  * @param sqlSession sqlSession
  * @return T
  */
 @SuppressWarnings("unchecked")
 public static <T> T newMapperProxy(Class<T> mapperInterface, SqlSession sqlSession) {
   ClassLoader classLoader = mapperInterface.getClassLoader();
   Class<?>[] interfaces = {mapperInterface};
   MyBatisMapperProxy proxy = new MyBatisMapperProxy(sqlSession);
   return (T) Proxy.newProxyInstance(classLoader, interfaces, proxy);
 }
  protected InputStream getResource(String name) {
    Class<?> clazz = getClass();

    ClassLoader classLoader = clazz.getClassLoader();

    return classLoader.getResourceAsStream(name);
  }
  @Override
  public DynamicQuery dynamicQuery() {
    Class<?> clazz = getClass();

    return DynamicQueryFactoryUtil.forClass(
        ExportImportConfiguration.class, clazz.getClassLoader());
  }
 private InputStream getClassAsStream(Class<?> clazz) {
   ClassLoader classLoader = clazz.getClassLoader();
   if (classLoader == null) {
     classLoader = ClassLoader.getSystemClassLoader();
   }
   return getClassAsStream(classLoader, clazz.getName());
 }
Пример #29
0
 public static <T> T getOsgiServiceProxy(BundleContext bundleContext, Class<T> clazz) {
   return (T)
       Proxy.newProxyInstance(
           clazz.getClassLoader(),
           new Class[] {clazz},
           new DelegatingInvocationHandler<T>(bundleContext, clazz));
 }
  /**
   * There is a possible case that methods of particular object should be executed with classpath
   * different from the one implied by the current class' class loader. External system offers
   * {@link ParametersEnhancer#enhanceLocalProcessing(List)} method for defining that custom
   * classpath.
   *
   * <p>It's also possible that particular implementation of {@link ParametersEnhancer} is compiled
   * using dependency to classes which are provided by the {@link
   * ParametersEnhancer#enhanceLocalProcessing(List) expanded classpath}. E.g. a class <code>'A'
   * </code> might use method of class <code>'B'</code> and 'A' is located at the current
   * (system/plugin) classpath but <code>'B'</code> is not. We need to reload <code>'A'</code> using
   * its expanded classpath then, i.e. create new class loaded with that expanded classpath and load
   * <code>'A'</code> by it.
   *
   * <p>This method allows to do that.
   *
   * @param clazz custom classpath-aware class which instance should be created (is assumed to have
   *     a no-args constructor)
   * @param <T> target type
   * @return newly created instance of the given class loaded by custom classpath-aware loader
   * @throws IllegalAccessException as defined by reflection processing
   * @throws InstantiationException as defined by reflection processing
   * @throws NoSuchMethodException as defined by reflection processing
   * @throws InvocationTargetException as defined by reflection processing
   * @throws ClassNotFoundException as defined by reflection processing
   */
  @NotNull
  public static <T extends ParametersEnhancer> T reloadIfNecessary(@NotNull final Class<T> clazz)
      throws IllegalAccessException, InstantiationException, NoSuchMethodException,
          InvocationTargetException, ClassNotFoundException {
    T instance = clazz.newInstance();
    List<URL> urls = ContainerUtilRt.newArrayList();
    instance.enhanceLocalProcessing(urls);
    if (urls.isEmpty()) {
      return instance;
    }

    final ClassLoader baseLoader = clazz.getClassLoader();
    Method method = baseLoader.getClass().getMethod("getUrls");
    if (method != null) {
      //noinspection unchecked
      urls.addAll((Collection<? extends URL>) method.invoke(baseLoader));
    }
    UrlClassLoader loader =
        new UrlClassLoader(UrlClassLoader.build().urls(urls).parent(baseLoader.getParent())) {
          @Override
          protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
            if (name.equals(clazz.getName())) {
              return super.loadClass(name, resolve);
            } else {
              try {
                return baseLoader.loadClass(name);
              } catch (ClassNotFoundException e) {
                return super.loadClass(name, resolve);
              }
            }
          }
        };
    //noinspection unchecked
    return (T) loader.loadClass(clazz.getName()).newInstance();
  }