Example usage for java.net URLClassLoader URLClassLoader

List of usage examples for java.net URLClassLoader URLClassLoader

Introduction

In this page you can find the example usage for java.net URLClassLoader URLClassLoader.

Prototype

public URLClassLoader(URL[] urls) 

Source Link

Document

Constructs a new URLClassLoader for the specified URLs using the default delegation parent ClassLoader .

Usage

From source file:org.microtitan.diffusive.utils.ClassLoaderUtils.java

public static void main(String[] args) throws IOException {
    // set the logging level
    DOMConfigurator.configure("log4j.xml");
    Logger.getRootLogger().setLevel(Level.DEBUG);

    final String classname = "org.microtitan.tests.threaded.MultiThreadedCalc";
    final byte[] systemBytes = loadClassToByteArray(classname);
    if (systemBytes == null) {
        System.out.println("null");
    } else {/*from   w  w w.  j a  v a  2 s  . co m*/
        System.out.println(systemBytes.length);
    }

    final URL url = new URL("file", null,
            "///C:/Users/desktop/workspace/diffusive/Diffusive_v0.2.0/examples/example_0.2.0.jar");
    //      final URL url = new URL( "file", null, "/Users/rob/Documents/workspace/diffusive/Diffusive_v0.2.0/examples/example_0.2.0.jar" );
    System.out.println(url.toString());
    final URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { url });
    final byte[] urlBytes = loadClassToByteArray(classname, urlClassLoader);
    if (urlBytes == null) {
        System.out.println("null");
    } else {
        System.out.println(urlBytes.length);
    }

    final InputStream input = urlClassLoader.getResourceAsStream(classname.replace('.', '/') + ".class");
    if (input == null) {
        System.out.println("null");
    } else {
        System.out.println(IOUtils.toByteArray(input).length);
    }
    urlClassLoader.close();

    //      final String className = BeanTest.class.getName();
    //      byte[] bytes = convertClassToByteArray( className );
    //      
    //      Class< ? > clazz = new RestfulClassLoader( null, ClassLoaderUtils.class.getClassLoader() ).getClazz( className, bytes );
    //      try
    //      {
    //         final Method method = clazz.getMethod( "print" );
    //         method.invoke( clazz.newInstance() );
    //      }
    //      catch( IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException | InstantiationException e )
    //      {
    //         e.printStackTrace();
    //      }
    //      
    //      System.out.println( clazz.getName() );
}

From source file:org.apache.hadoop.hbase.util.RunTrigger.java

/**
 * @param args/*w w  w  .  j ava2s .c o m*/
 * @throws Throwable 
 */
public static void main(String[] args) throws Throwable {
    String usage = "RunTrigger jarFile [mainClass] args...";

    if (args.length < 1) {
        System.err.println(usage);
        System.exit(-1);
    }
    int firstArg = 0;
    String fileName = args[firstArg++];
    File file = new File(fileName);
    File tmpJarFile = new File("/tmp/hbase/triggerJar/trigger.jar");
    if (tmpJarFile.exists()) {
        tmpJarFile.delete();
    }
    FileUtils.copyFile(file, tmpJarFile);

    String mainClassName = null;
    JarFile jarFile;
    try {
        jarFile = new JarFile(fileName);
    } catch (IOException e) {
        throw new IOException("Error opening trigger jar: " + fileName).initCause(e);
    }

    Manifest manifest = jarFile.getManifest();
    if (manifest != null) {
        mainClassName = manifest.getMainAttributes().getValue("Main-Class");
    }
    jarFile.close();
    System.out.println("Manifest From Jar: " + mainClassName);

    if (mainClassName == null) {
        if (args.length < 2) {
            System.err.println(usage);
            System.exit(-1);
        }
        mainClassName = args[firstArg++];
    }
    System.out.println("Manifest class from argument: " + mainClassName);

    mainClassName = mainClassName.replace("/", ".");

    //'hbase.tmp.dir'
    File tmpDir = new File("/tmp/hbase/trigger/");

    tmpDir.mkdirs();
    if (!tmpDir.isDirectory()) {
        System.err.println("Mkdirs failed to create " + tmpDir);
        System.exit(-1);
    }
    final File workDir = File.createTempFile("trigger-unjar", "", tmpDir);
    workDir.delete();
    workDir.mkdirs();
    if (!workDir.isDirectory()) {
        System.err.println("Mkdirs failed to create " + workDir);
        System.exit(-1);
    }

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                FileUtil.fullyDelete(workDir);
            } catch (IOException e) {
            }
        }
    });

    unJar(file, workDir);

    ArrayList<URL> classPath = new ArrayList<URL>();
    classPath.add(new File(workDir + "/").toURL());
    classPath.add(file.toURL());
    classPath.add(new File(workDir, "classes/").toURL());
    File[] libs = new File(workDir, "lib").listFiles();
    if (libs != null) {
        for (int i = 0; i < libs.length; i++) {
            classPath.add(libs[i].toURL());
        }
    }

    ClassLoader loader = new URLClassLoader(classPath.toArray(new URL[0]));
    Thread.currentThread().setContextClassLoader(loader);
    Class<?> mainClass = Class.forName(mainClassName, true, loader);
    Method main = mainClass.getMethod("main", new Class[] { Array.newInstance(String.class, 0).getClass() });
    String[] newArgs = Arrays.asList(args).subList(firstArg, args.length).toArray(new String[0]);
    try {
        main.invoke(null, new Object[] { newArgs });
    } catch (InvocationTargetException e) {
        throw e.getTargetException();
    }
}

From source file:org.apache.stratos.cartridge.agent.statistics.publisher.PluginLoader.java

public static List<Class> loadPluginClassesFromJar(File jarPath, Class pluginInterface) {
    List<Class> listeners = new LinkedList<Class>();

    try {/*from w ww . j  a  v a  2s .c  o  m*/
        URLClassLoader loader = new URLClassLoader(new URL[] { jarPath.toURI().toURL() });
        JarFile jar = new JarFile(jarPath);
        Enumeration<? extends JarEntry> jarEnum = jar.entries();

        log.trace("Scanning jar file " + jarPath);

        while (jarEnum.hasMoreElements()) {
            ZipEntry zipEntry = jarEnum.nextElement();
            String fileName = zipEntry.getName();

            if (fileName.endsWith(".class")) {
                log.trace("Considering jar entry " + fileName);
                try {
                    String className = fileName.replace(".class", "").replace("/", ".");
                    Class cls = loader.loadClass(className);
                    log.trace("Loaded class " + className);

                    if (hasInterface(cls, pluginInterface)) {
                        log.trace("Class has " + pluginInterface.getName() + " interface; adding ");
                        listeners.add(cls);
                    }
                } catch (ClassNotFoundException e) {
                    log.error("Unable to load class from " + fileName + " in " + jarPath);
                }
            }
        }

    } catch (IOException e) {
        log.error("Unable to open JAR file " + jarPath, e);
    }

    return listeners;
}

From source file:com.ut.healthelink.service.CCDtoTxt.java

public String TranslateCCDtoTxt(String fileLocation, String ccdFileName, int orgId) throws Exception {

    Organization orgDetails = organizationmanager.getOrganizationById(orgId);
    fileSystem dir = new fileSystem();

    dir.setDir(orgDetails.getcleanURL(), "templates");

    String templatefileName = orgDetails.getparsingTemplate();

    URLClassLoader loader = new URLClassLoader(
            new URL[] { new URL("file://" + dir.getDir() + templatefileName) });

    // Remove the .class extension
    Class cls = loader.loadClass(templatefileName.substring(0, templatefileName.lastIndexOf('.')));
    Constructor constructor = cls.getConstructor();

    Object CCDObj = constructor.newInstance();

    Method myMethod = cls.getMethod("CCDtoTxt", new Class[] { File.class });

    /* Get the uploaded CCD File */
    fileLocation = fileLocation.replace("/Applications/bowlink/", "").replace("/home/bowlink/", "")
            .replace("/bowlink/", "");
    dir.setDirByName(fileLocation);/*from  www .ja  va  2 s.  co  m*/

    File ccdFile = new File(dir.getDir() + ccdFileName + ".xml");

    /* Create the txt file that will hold the CCD fields */
    String newfileName = new StringBuilder()
            .append(ccdFile.getName().substring(0, ccdFile.getName().lastIndexOf("."))).append(".")
            .append("txt").toString();

    File newFile = new File(dir.getDir() + newfileName);

    if (newFile.exists()) {
        try {

            if (newFile.exists()) {
                int i = 1;
                while (newFile.exists()) {
                    int iDot = newfileName.lastIndexOf(".");
                    newFile = new File(dir.getDir() + newfileName.substring(0, iDot) + "_(" + ++i + ")"
                            + newfileName.substring(iDot));
                }
                newfileName = newFile.getName();
                newFile.createNewFile();
            } else {
                newFile.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {
        newFile.createNewFile();
        newfileName = newFile.getName();

    }

    FileWriter fw = new FileWriter(newFile, true);

    /* END */
    String fileRecords = (String) myMethod.invoke(CCDObj, new Object[] { ccdFile });

    fw.write(fileRecords);

    fw.close();

    return newfileName;

}

From source file:com.ut.healthelink.service.hl7toTxt.java

public String TranslateHl7toTxt(String fileLocation, String fileName, int orgId) throws Exception {

    Organization orgDetails = organizationmanager.getOrganizationById(orgId);
    fileSystem dir = new fileSystem();

    dir.setDir(orgDetails.getcleanURL(), "templates");

    String templatefileName = orgDetails.getparsingTemplate();

    URLClassLoader loader = new URLClassLoader(
            new URL[] { new URL("file://" + dir.getDir() + templatefileName) });

    // Remove the .class extension
    Class cls = loader.loadClass(templatefileName.substring(0, templatefileName.lastIndexOf('.')));

    Constructor constructor = cls.getConstructor();

    Object HL7Obj = constructor.newInstance();

    Method myMethod = cls.getMethod("HL7toTxt", new Class[] { File.class });

    /* Get the uploaded HL7 File */
    fileLocation = fileLocation.replace("/Applications/bowlink/", "").replace("/home/bowlink/", "")
            .replace("/bowlink/", "");
    dir.setDirByName(fileLocation);/*w w  w  . j  av a 2 s .  c om*/

    File hl7File = new File(dir.getDir() + fileName + ".hr");

    /* Create the output file */
    String newfileName = new StringBuilder()
            .append(hl7File.getName().substring(0, hl7File.getName().lastIndexOf("."))).append(".")
            .append("txt").toString();

    File newFile = new File(dir.getDir() + newfileName);

    if (newFile.exists()) {
        try {

            if (newFile.exists()) {
                int i = 1;
                while (newFile.exists()) {
                    int iDot = newfileName.lastIndexOf(".");
                    newFile = new File(dir.getDir() + newfileName.substring(0, iDot) + "_(" + ++i + ")"
                            + newfileName.substring(iDot));
                }
                newfileName = newFile.getName();
                newFile.createNewFile();
            } else {
                newFile.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    } else {
        newFile.createNewFile();
        newfileName = newFile.getName();

    }

    FileWriter fw = new FileWriter(newFile, true);

    /* END */
    String fileRecords = (String) myMethod.invoke(HL7Obj, new Object[] { hl7File });

    fw.write(fileRecords);

    fw.close();

    return newfileName;

}

From source file:com.legstar.jaxb.plugin.EnumCases.java

/**
 * Check Get Set methods on enumerations.
 * @throws Exception if test fails//  ww  w.j  a v  a 2s . c o m
 */
public void testGetSetEnum() throws Exception {
    /* Load the generated class */
    URI loc = GEN_SRC_DIR.toURI();
    URL[] ua = { loc.toURL() };
    URLClassLoader cl = new URLClassLoader(ua);
    Class<?> clazzSearchRequestType = cl.loadClass("com.legstar.test.coxb.enumvar.SearchRequestType");
    Object searchRequest = clazzSearchRequestType.newInstance();

    /* Create an Enum type with a value */
    Class<?> clazzSafeSearchOptionsType = cl.loadClass("com.legstar.test.coxb.enumvar.SafeSearchOptionsType");
    Field[] fields = clazzSafeSearchOptionsType.getDeclaredFields();
    for (Field field : fields) {
        _log.debug(field.getName());
    }

    /* Create a new enum type with a value */
    Method getValueMethod = clazzSafeSearchOptionsType.getMethod("value", (Class[]) null);
    Method fromValueMethod = clazzSafeSearchOptionsType.getMethod("fromValue",
            new Class[] { getValueMethod.getReturnType() });
    Object safeSearchOption = fromValueMethod.invoke(null, new Object[] { "Strict" });

    /* Get the value of an Enum */
    getValueMethod.invoke(safeSearchOption, (Object[]) null);

    /* Set the Enum value*/
    Class<?>[] param = { clazzSafeSearchOptionsType };
    String setterName = "setSafeSearch";
    Method setter = searchRequest.getClass().getMethod(setterName, param);
    setter.invoke(searchRequest, safeSearchOption);

    String getterName = "getSafeSearch";
    Method getter = searchRequest.getClass().getMethod(getterName);
    Object result = getter.invoke(searchRequest);
    assertEquals("Strict", getValueMethod.invoke(result, (Object[]) null));
}

From source file:org.apache.openjpa.eclipse.util.PCEnhancerHelperTest.java

public void todotestEnhanceFile() throws Exception {
    String className = "TestEntity";

    URL[] urls = new URL[] { targetDir.toURI().toURL() };
    ClassLoader classLoader = new URLClassLoader(urls);
    PCEnhancerHelper eh = new PCEnhancerHelperImpl(classLoader);
    boolean r = checkEnhance(eh, className);
    Assert.assertTrue(r); // was enhanced..

    // Reset/re-initialize classLoader, to freshly load and check the enhanced class
    classLoader = new URLClassLoader(urls);
    Class<?> testClass = classLoader.loadClass(classPackage + className);
    Assert.assertNotNull(testClass);/*  w w w .  j  a v a 2 s  . c  o m*/
    Assert.assertEquals(1, testClass.getInterfaces().length);
    Assert.assertTrue(testClass.getInterfaces()[0].equals(PersistenceCapable.class));
}

From source file:org.jiemamy.utils.sql.DriverUtil.java

/**
 * JAR???Driver???// ww w .j  a  va  2  s . c om
 * 
 * @param paths JAR?URL??
 * @return Driver?
 * @throws IOException ????
 * @throws IllegalArgumentException ?{@code null}????????{@code null}??
 * @throws IllegalArgumentException URI??????URL????????
 * @throws FileNotFoundException paths???JAR????????
 */
public static Collection<Class<? extends Driver>> getDriverClasses(URL[] paths) throws IOException {
    Validate.noNullElements(paths);

    URLClassLoader classLoader = new URLClassLoader(paths);

    Collection<Class<? extends Driver>> driverList = Lists.newArrayList();

    for (URL path : paths) {
        try {
            File file = new File(path.toURI());
            if (file.exists() == false) {
                throw new FileNotFoundException(file.getAbsolutePath());
            }
            JarFile jarFile = new JarFile(file);
            ClassTraversal.forEach(jarFile, new GetDriverClassesFromJarHandler(driverList, classLoader));
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(path.toString(), e);
        } catch (TraversalHandlerException e) {
            logger.error(LogMarker.DETAIL, "fail to handle jar entry.", e);
        }
    }
    return driverList;
}

From source file:com.ts.db.connector.ConnectorDriverManager.java

static Driver getDriver(String url, String driverClassName, String classpath) throws SQLException {
    assert !StringUtils.isBlank(url);
    final boolean hasClasspath = !StringUtils.isBlank(classpath);
    if (!hasClasspath) {
        for (Driver driver : new ArrayList<Driver>(drivers)) {
            if (driver.acceptsURL(url)) {
                return driver;
            }//  w  w  w  . j a  va2  s.  com
        }
    }
    List<File> jars = new ArrayList<File>();
    ClassLoader cl;
    if (hasClasspath) {
        List<URL> urls = new ArrayList<URL>();
        for (String path : classpath.split(pathSeparator)) {
            final File file = new File(path);
            if (isJarFile(file)) {
                jars.add(file);
            }
            try {
                urls.add(file.toURI().toURL());
            } catch (MalformedURLException ex) {
                log.warn(ex.toString());
            }
        }
        cl = new URLClassLoader(urls.toArray(new URL[urls.size()]));
    } else {
        jars.addAll(getJarFiles("."));
        jars.addAll(driverFiles);
        List<URL> urls = new ArrayList<URL>();
        for (File file : jars) {
            try {
                urls.add(file.toURI().toURL());
            } catch (MalformedURLException ex) {
                log.warn(ex.toString());
            }
        }
        cl = new URLClassLoader(urls.toArray(new URL[urls.size()]), ClassLoader.getSystemClassLoader());
    }
    driverFiles.addAll(jars);
    final boolean hasDriverClassName = !StringUtils.isBlank(driverClassName);
    if (hasDriverClassName) {
        try {
            Driver driver = DynamicLoader.newInstance(driverClassName, cl);
            assert driver != null;
            return driver;
        } catch (DynamicLoadingException ex) {
            Throwable cause = (ex.getCause() != ex) ? ex.getCause() : ex;
            SQLException exception = new SQLException(cause.toString());
            exception.initCause(cause);
            throw exception;
        }
    }
    final String jdbcDrivers = System.getProperty("jdbc.drivers");
    if (!StringUtils.isBlank(jdbcDrivers)) {
        for (String jdbcDriver : jdbcDrivers.split(":")) {
            try {
                Driver driver = DynamicLoader.newInstance(jdbcDriver, cl);
                if (driver != null) {
                    if (!hasClasspath) {
                        drivers.add(driver);
                    }
                    return driver;
                }
            } catch (DynamicLoadingException ex) {
                log.warn(ex.toString());
            }
        }
    }
    for (File jar : jars) {
        try {
            Driver driver = getDriver(jar, url, cl);
            if (driver != null) {
                if (!hasClasspath) {
                    drivers.add(driver);
                }
                return driver;
            }
        } catch (IOException ex) {
            log.warn(ex.toString());
        }
    }
    for (String path : System.getProperty("java.class.path", "").split(pathSeparator)) {
        if (isJarFile(path)) {
            Driver driver;
            try {
                driver = getDriver(new File(path), url, cl);
                if (driver != null) {
                    drivers.add(driver);
                    return driver;
                }
            } catch (IOException ex) {
                log.warn(ex.toString());
            }
        }
    }
    throw new SQLException("driver not found");
}

From source file:org.eclipse.wb.internal.swing.laf.LafUtils.java

/**
 * Opens given <code>jarFile</code>, loads every class inside own {@link ClassLoader} and checks
 * loaded class for to be instance of {@link LookAndFeel}. Returns the array of {@link LafInfo}
 * containing all found {@link LookAndFeel} classes.
 * /*from  www . j a  v  a2 s.  c om*/
 * @param jarFileName
 *          the absolute OS path pointing to source JAR file.
 * @param monitor
 *          the progress monitor which checked for interrupt request.
 * @return the array of {@link UserDefinedLafInfo} containing all found {@link LookAndFeel}
 *         classes.
 */
public static UserDefinedLafInfo[] scanJarForLookAndFeels(String jarFileName, IProgressMonitor monitor)
        throws Exception {
    List<UserDefinedLafInfo> lafList = Lists.newArrayList();
    File jarFile = new File(jarFileName);
    URLClassLoader ucl = new URLClassLoader(new URL[] { jarFile.toURI().toURL() });
    JarFile jar = new JarFile(jarFile);
    Enumeration<?> entries = jar.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = (JarEntry) entries.nextElement();
        String entryName = entry.getName();
        if (entry.isDirectory() || !entryName.endsWith(".class") || entryName.indexOf('$') >= 0) {
            continue;
        }
        String className = entryName.replace('/', '.').replace('\\', '.');
        className = className.substring(0, className.lastIndexOf('.'));
        Class<?> clazz = null;
        try {
            clazz = ucl.loadClass(className);
        } catch (Throwable e) {
            continue;
        }
        // check loaded class to be a non-abstract subclass of javax.swing.LookAndFeel class
        if (LookAndFeel.class.isAssignableFrom(clazz) && !Modifier.isAbstract(clazz.getModifiers())) {
            // use the class name as name of LAF
            String shortClassName = CodeUtils.getShortClass(className);
            // strip trailing "LookAndFeel"
            String lafName = StringUtils.chomp(shortClassName, "LookAndFeel");
            lafList.add(new UserDefinedLafInfo(StringUtils.isEmpty(lafName) ? shortClassName : lafName,
                    className, jarFileName));
        }
        // check for Cancel button pressed
        if (monitor.isCanceled()) {
            return lafList.toArray(new UserDefinedLafInfo[lafList.size()]);
        }
        // update ui
        while (DesignerPlugin.getStandardDisplay().readAndDispatch()) {
        }
    }
    return lafList.toArray(new UserDefinedLafInfo[lafList.size()]);
}