Example usage for java.net URLClassLoader newInstance

List of usage examples for java.net URLClassLoader newInstance

Introduction

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

Prototype

public static URLClassLoader newInstance(final URL[] urls) 

Source Link

Document

Creates a new instance of URLClassLoader for the specified URLs and default parent class loader.

Usage

From source file:info.novatec.testit.livingdoc.util.ClassUtils.java

public static ClassLoader toClassLoaderWithDefaultParent(Collection<String> classPaths)
        throws MalformedURLException {
    Set<URL> dependencies = new HashSet<URL>();
    for (String classPath : classPaths) {
        File dependency = new File(classPath);
        dependencies.add(dependency.toURI().toURL());
    }/*from w  w  w .j  a va 2  s  .c  o  m*/
    ClassLoader classLoader = URLClassLoader.newInstance(dependencies.toArray(new URL[dependencies.size()]));
    return classLoader;
}

From source file:it.jnrpe.plugins.factory.CPluginFactory.java

/**
 * @deprecated/*from   ww  w  .  j av a  2 s  .c om*/
 */
private void configurePlugins(File fDir) {
    m_Logger.trace("READING PLUGIN CONFIGURATION FROM DIRECTORY " + fDir.getName());
    CStreamManager streamMgr = new CStreamManager();
    File[] vfJars = fDir.listFiles(new FileFilter() {

        public boolean accept(File f) {
            return f.getName().endsWith(".jar");
        }

    });

    // Initializing classloader
    URL[] urls = new URL[vfJars.length];
    URLClassLoader ul = null;

    for (int j = 0; j < vfJars.length; j++) {
        try {
            urls[j] = vfJars[j].toURI().toURL();
        } catch (MalformedURLException e) {
            // should never happen
        }
    }

    ul = URLClassLoader.newInstance(urls);

    for (int i = 0; i < vfJars.length; i++) {
        File file = vfJars[i];

        try {
            m_Logger.info("READING PLUGINS DATA IN FILE '" + file.getName() + "'");

            ZipInputStream jin = (ZipInputStream) streamMgr
                    .handle(new ZipInputStream(new FileInputStream(file)));
            ZipEntry ze = null;

            while ((ze = jin.getNextEntry()) != null) {
                if (ze.getName().equals("plugin.xml")) {
                    parsePluginXmlFile(jin);
                    break;
                }
            }
        } catch (Exception e) {
            m_Logger.error("UNABLE TO READ DATA FROM FILE '" + file.getName() + "'. THE FILE WILL BE IGNORED.",
                    e);
        } finally {
            streamMgr.closeAll();
        }

    }
}

From source file:de.xirp.ate.ATEManager.java

/**
 * Executes the a the <code>algorithm( )</code> method from a
 * given class, which is indicated by is name.
 * //w  w  w  .j a va 2  s . c  o m
 * @param className
 *            The class to execute the method from.
 */
public static void execute(String className) {
    File clazz = new File(Constants.MAZE_CODE_DIR);
    try {
        URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { clazz.toURI().toURL() });
        Class<?> forName = Class.forName(className, true, classLoader);
        Method declaredMethod = forName.getDeclaredMethod("algorithm", new Class[0]); //$NON-NLS-1$
        declaredMethod.invoke(forName.newInstance(), new Object[0]);
    } catch (Exception e) {
        logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
    }
}

From source file:gdt.data.entity.facet.ExtensionHandler.java

private static FacetHandler[] listExtensionHandlers(Entigrator entigrator, String extension$) {
    try {//from www . j a v a  2  s.  c o  m
        System.out.println("ExtesionHandler:listExtensionHandlers:extension=" + extension$);
        Sack extension = entigrator.getEntityAtKey(extension$);
        String lib$ = extension.getElementItemAt("field", "lib");
        String[] sa = extension.elementList("content.fhandler");
        if (sa == null)
            return null;

        ArrayList<FacetHandler> fl = new ArrayList<FacetHandler>();
        FacetHandler fh;
        Class<?> cls;
        String jar$ = "jar:file:" + entigrator.getEntihome() + "/" + extension$ + "/" + lib$ + "!/";
        URL[] urls = { new URL(jar$) };
        URLClassLoader cl = URLClassLoader.newInstance(urls);
        for (String aSa : sa) {
            try {
                //         System.out.println("ExtesionHandler:listExtensionHandlers:jar="+jar$);
                cls = cl.loadClass(aSa);
                fh = (FacetHandler) cls.newInstance();
                fl.add(fh);
            } catch (Exception ee) {
                Logger.getLogger(ExtensionHandler.class.getName()).severe("load class: " + ee.toString());
            }
        }
        return fl.toArray(new FacetHandler[0]);
    } catch (Exception e) {
        Logger.getLogger(ExtensionHandler.class.getName()).severe(e.toString());
        return null;
    }
}

From source file:org.callimachusproject.behaviours.SqlDatasourceSupport.java

private ClassLoader createClassLoader() {
    List<URL> urls = new ArrayList<URL>();
    for (RDFObject jar : this.getCalliDriverJar()) {
        try {//from  w w w.j av  a2  s  .c om
            urls.add(new URL(jar.getResource().stringValue()));
        } catch (MalformedURLException e) {
            logger.warn(e.toString(), e);
        }
    }
    return URLClassLoader.newInstance(urls.toArray(new URL[urls.size()]));
}

From source file:com.datatorrent.stram.StramLocalClusterTest.java

@Test
public void testDynamicLoading() throws Exception {
    String generatedJar = generatejar("POJO");
    URLClassLoader uCl = URLClassLoader.newInstance(new URL[] { new File(generatedJar).toURI().toURL() });
    Class<?> pojo = uCl.loadClass("POJO");

    DynamicLoaderApp app = new DynamicLoaderApp();
    app.generatedJar = generatedJar;//from ww  w. j  ava2  s . c  o m
    app.pojo = pojo;

    LocalMode lma = LocalMode.newInstance();
    lma.prepareDAG(app, new Configuration());
    LocalMode.Controller lc = lma.getController();
    lc.runAsync();
    DynamicLoaderApp.latch.await();
    Assert.assertTrue(DynamicLoaderApp.passed);
    lc.shutdown();
}

From source file:org.pentaho.ui.xul.impl.AbstractXulLoader.java

private URLClassLoader getLocalDirClassLoader() throws MalformedURLException {
    if (localDirClassLoader == null) {
        final URL url = new File(".").toURI().toURL();
        localDirClassLoader = URLClassLoader.newInstance(new URL[] { url });
    }/* w  w  w . j a  va  2 s  .c  om*/
    return localDirClassLoader;
}

From source file:com.datatorrent.stram.client.StramAppLauncher.java

/**
 * Scan the application jar file entries for configuration classes.
 * This needs to occur in a class loader with access to the application dependencies.
 *///from  w w w  . jav a  2s.  c om
private void findAppConfigClasses(List<String> classFileNames) {
    URLClassLoader cl = URLClassLoader
            .newInstance(launchDependencies.toArray(new URL[launchDependencies.size()]));
    for (final String classFileName : classFileNames) {
        final String className = classFileName.replace('/', '.').substring(0, classFileName.length() - 6);
        try {
            final Class<?> clazz = cl.loadClass(className);
            if (!Modifier.isAbstract(clazz.getModifiers())
                    && StreamingApplication.class.isAssignableFrom(clazz)) {
                final AppFactory appConfig = new AppFactory() {
                    @Override
                    public String getName() {
                        return classFileName;
                    }

                    @Override
                    public String getDisplayName() {
                        ApplicationAnnotation an = clazz.getAnnotation(ApplicationAnnotation.class);
                        if (an != null) {
                            return an.name();
                        } else {
                            return classFileName;
                        }
                    }

                    @Override
                    public LogicalPlan createApp(LogicalPlanConfiguration conf) {
                        // load class from current context class loader
                        Class<? extends StreamingApplication> c = StramUtils.classForName(className,
                                StreamingApplication.class);
                        StreamingApplication app = StramUtils.newInstance(c);
                        LogicalPlan dag = new LogicalPlan();
                        conf.prepareDAG(dag, app, getName());
                        return dag;
                    }

                };
                appResourceList.add(appConfig);
            }
        } catch (Throwable e) { // java.lang.NoClassDefFoundError
            LOG.error("Unable to load class: " + className + " " + e);
        }
    }
}

From source file:com.datatorrent.stram.client.StramAppLauncher.java

public URLClassLoader loadDependencies() {
    URLClassLoader cl = URLClassLoader
            .newInstance(launchDependencies.toArray(new URL[launchDependencies.size()]));
    Thread.currentThread().setContextClassLoader(cl);
    StringCodecs.check();/*from  w  w w  .  java2  s  .  co m*/
    return cl;
}

From source file:com.consol.citrus.admin.service.TestCaseService.java

private ClassLoader getTestClassLoader(Project project) throws IOException {
    List<URL> classpathUrls = new ArrayList<>();

    classpathUrls.add(new FileSystemResource(
            project.getProjectHome() + File.separator + "target" + File.separator + "classes").getURL());
    classpathUrls.add(new FileSystemResource(
            project.getProjectHome() + File.separator + "target" + File.separator + "test-classes").getURL());

    File[] mavenDependencies = Maven.configureResolver().workOffline()
            .loadPomFromFile(project.getMavenPomFile()).importRuntimeAndTestDependencies().resolve()
            .withTransitivity().asFile();

    for (File mavenDependency : mavenDependencies) {
        classpathUrls.add(new FileSystemResource(mavenDependency).getURL());
    }//from   w  w w.j  av a  2 s. c o  m

    return URLClassLoader.newInstance(classpathUrls.toArray(new URL[classpathUrls.size()]));
}