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

URLClassLoader(URL[] urls, AccessControlContext acc) 

Source Link

Usage

From source file:com.github.ukase.toolkit.jar.JarSource.java

@Autowired
public JarSource(CompoundTemplateLoader templateLoader, UkaseSettings settings) {
    this.templateLoader = templateLoader;

    if (settings.getJar() == null) {
        classLoader = null;//from w w w  .  ja v a 2s .  co m
        fonts = Collections.emptyList();

        return;
    }

    try {
        URL jar = settings.getJar().toURI().toURL();

        Collection<String> props = templateLoader.getResources(IS_HELPERS_CONFIGURATION);

        Properties properties = new Properties();
        props.stream().map(templateLoader::getResource).filter(entry -> entry != null).map(this::mapZipEntry)
                .filter(stream -> stream != null).forEach(stream -> loadStreamToProperties(stream, properties));
        properties.forEach(this::registerHelper);

        fonts = templateLoader.getResources(IS_FONT).parallelStream().map(font -> "jar:" + jar + "!/" + font)
                .collect(Collectors.toList());

        if (hasHelpers()) {
            URL[] jars = new URL[] { jar };
            classLoader = new URLClassLoader(jars, getClass().getClassLoader());
            helpers.forEach((name, className) -> helpersInstances.put(name, getHelper(className)));
        } else {
            classLoader = null;
        }

    } catch (IOException e) {
        throw new IllegalStateException("Wrong configuration", e);
    }
}

From source file:com.aliyun.fs.oss.utils.ResourceLoader.java

@SuppressWarnings("unchecked")
public synchronized URLClassLoader getUrlClassLoader(Configuration conf) {
    if (urlClassLoader == null) {
        try {//from  ww w  .ja  v a2  s.  co m
            List<URL> urls = geClassLoaderURLs(conf);
            urlClassLoader = new URLClassLoader(urls.toArray(new URL[0]), null);
        } catch (Exception e) {
            throw new RuntimeException("Can not initialize OSS URLClassLoader, " + e.getMessage());
        }
    }
    return urlClassLoader;
}

From source file:org.apache.hama.monitor.Configurator.java

/**
 * Load jar from specified path.// w  w w . jav  a 2  s.  com
 * 
 * @param path to the jar file.
 * @param loader of the current thread.
 * @return task to be run.
 */
private static Task load(File path, ClassLoader loader) throws IOException {
    JarFile jar = new JarFile(path);
    Manifest manifest = jar.getManifest();
    String pkg = manifest.getMainAttributes().getValue("Package");
    String main = manifest.getMainAttributes().getValue("Main-Class");
    if (null == pkg || null == main)
        throw new NullPointerException("Package or main class not found " + "in menifest file.");
    String namespace = pkg + File.separator + main;
    namespace = namespace.replaceAll(File.separator, ".");
    LOG.debug("Task class to be loaded: " + namespace);
    URLClassLoader child = new URLClassLoader(new URL[] { path.toURI().toURL() }, loader);
    Thread.currentThread().setContextClassLoader(child);
    Class<?> taskClass = null;
    try {
        taskClass = Class.forName(namespace, true, child); // task class
    } catch (ClassNotFoundException cnfe) {
        LOG.warn("Task class is not found.", cnfe);
    }
    if (null == taskClass)
        return null;

    try {
        return (Task) taskClass.newInstance();
    } catch (InstantiationException ie) {
        LOG.warn("Unable to instantiate task class." + namespace, ie);
    } catch (IllegalAccessException iae) {
        LOG.warn(iae);
    }
    return null;
}

From source file:net.sourceforge.mavenhippo.AbstractHippoMojo.java

protected ClassLoader getProjectClassloader() throws MojoExecutionException {
    try {/*from  w w  w  . ja  v a  2s. co  m*/
        if (projectClassloader == null) {
            Set<Artifact> artifacts = project.getArtifacts();
            List<URL> urls = new ArrayList<URL>();
            for (Artifact artifact : artifacts) {
                urls.add(artifact.getFile().toURI().toURL());
            }
            if (getLog().isDebugEnabled()) {
                for (URL url : urls) {
                    getLog().debug("Project dependency URL: " + url.toString());
                }
            }
            projectClassloader = new URLClassLoader(urls.toArray(new URL[0]), this.getClass().getClassLoader());
        }
        return projectClassloader;
    } catch (MalformedURLException e) {
        throw new MojoExecutionException(e.getLocalizedMessage(), e);
    }

}

From source file:org.onecmdb.core.utils.transform.jdbc.JDBCDataSourceWrapper.java

public void setupDataSource(Properties p) throws IOException {
    // Load this under the provieded DriverLib class path.
    URLClassLoader loader = new URLClassLoader(getDriverLibURL(), this.getClass().getClassLoader());
    Thread.currentThread().setContextClassLoader(loader);

    try {/*from  w w w  .java 2  s.  c  o m*/
        Class driver = loader.loadClass(p.getProperty("jdbc.driverClass"));
        try {
            Object instance = driver.newInstance();
            System.out.println("Instance...." + instance);
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (ClassNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    /*
    Class cl = null;
    String clazz = "org.apache.commons.dbcp.BasicDataSource";
            
    try {
       cl = loader.loadClass(clazz);
    } catch (ClassNotFoundException e) {
       throw new IOException("Can't load class '" + clazz + "', using driver lib '" + driverLib + "'");
    }
    BasicDataSource jdbcSrc;
    try {
       jdbcSrc = (BasicDataSource) cl.newInstance();
    } catch (Exception e) {
       throw new IOException("Can't instanciate class '" + clazz + "', using driver lib '" + driverLib + "'");
    }
    */

    ClassLoaderBasicDataSource jdbcSrc = new ClassLoaderBasicDataSource();
    jdbcSrc.setDriverClassLoader(loader);
    jdbcSrc.setUrl(p.getProperty("db.url"));
    jdbcSrc.setUrl(p.getProperty("jdbc.url"));
    jdbcSrc.setDriverClassName(p.getProperty("db.driverClass"));
    jdbcSrc.setDriverClassName(p.getProperty("jdbc.driverClass"));

    jdbcSrc.setUsername(p.getProperty("db.user"));
    jdbcSrc.setUsername(p.getProperty("jdbc.user"));

    jdbcSrc.setPassword(p.getProperty("db.password"));
    jdbcSrc.setPassword(p.getProperty("jdbc.password"));
    /*
    String clazz2 = "org.onecmdb.core.utils.transform.jdbc.ClassLoaderBasicDataSource";
    try {
       cl = loader.loadClass(clazz2);
    } catch (ClassNotFoundException e) {
       throw new IOException("Can't load class '" + clazz + "', using driver lib '" + driverLib + "'");
    }
            
    ClassLoaderBasicDataSource jdbcSrc1;
    try {
       jdbcSrc1 = (ClassLoaderBasicDataSource) cl.newInstance();
       jdbcSrc1.setDs(jdbcSrc);
    } catch (Exception e) {
       throw new IOException("Can't instanciate class '" + clazz + "', using driver lib '" + driverLib + "'");
    }
    */
    setDataSource(jdbcSrc);
}

From source file:org.cytoscape.app.internal.manager.SimpleApp.java

@Override
public Object createAppInstance(CySwingAppAdapter appAdapter) throws AppInstanceException {
    File installFile = this.getAppTemporaryInstallFile();
    if (installFile == null) {
        throw new AppInstanceException("No copy of app jar for instancing was found");
    }/*from   ww  w.ja v a2 s  .c o m*/

    URL appURL = null;
    try {
        appURL = installFile.toURI().toURL();
    } catch (MalformedURLException e) {
        throw new AppInstanceException(
                "Unable to obtain URL for file: " + installFile + ". Reason: " + e.getMessage());
    }

    // TODO: Currently uses the CyAppAdapter's loader to load apps' classes. Is there reason to use a different one?
    ClassLoader appClassLoader = new URLClassLoader(new URL[] { appURL },
            appAdapter.getClass().getClassLoader());

    // Attempt to load the class
    Class<?> appEntryClass = null;
    try {
        appEntryClass = appClassLoader.loadClass(this.getEntryClassName());
    } catch (ClassNotFoundException e) {

        throw new AppInstanceException("Class " + this.getEntryClassName() + " not found in URL: " + appURL);
    }

    // Attempt to obtain the constructor
    Constructor<?> constructor = null;
    try {
        try {
            constructor = appEntryClass.getConstructor(CyAppAdapter.class);
        } catch (SecurityException e) {
            throw new AppInstanceException("Access to the constructor for " + appEntryClass + " denied.");
        } catch (NoSuchMethodException e) {
            throw new AppInstanceException("Unable to find a constructor for " + appEntryClass
                    + " that takes a CyAppAdapter as its argument.");
        }
    } catch (AppInstanceException e) {
        try {
            constructor = appEntryClass.getConstructor(CySwingAppAdapter.class);
        } catch (SecurityException e2) {
            throw new AppInstanceException("Access to the constructor for " + appEntryClass
                    + " taking a CySwingAppAdapter as its argument denied.");
        } catch (NoSuchMethodException e2) {
            throw new AppInstanceException("Unable to find an accessible constructor that takes either"
                    + " a CyAppAdapter or a CySwingAppAdapter as its argument.");
        }
    }

    // Attempt to instantiate the app's class that extends AbstractCyApp or AbstractCySwingApp.
    Object appInstance = null;
    try {
        appInstance = constructor.newInstance(appAdapter);
    } catch (IllegalArgumentException e) {
        throw new AppInstanceException(
                "Illegal arguments passed to the constructor for the app's entry class: " + e.getMessage());
    } catch (InstantiationException e) {
        throw new AppInstanceException(
                "Error instantiating the class " + appEntryClass + ": " + e.getMessage());
    } catch (IllegalAccessException e) {
        throw new AppInstanceException("Access to constructor denied: " + e.getMessage());
    } catch (InvocationTargetException e) {
        e.printStackTrace();
        throw new AppInstanceException("App constructor threw exception: " + e.toString());
    }

    return appInstance;
}

From source file:io.ingenieux.lambada.maven.AbstractLambadaMetadataMojo.java

public void setClasspathUrls(ConfigurationBuilder configurationBuilder) {
    List<String> classpathElements = null;
    try {//from   w ww  .  j  av  a2  s .  c o  m
        classpathElements = project.getCompileClasspathElements();
        List<URL> projectClasspathList = new ArrayList<URL>();

        for (String element : classpathElements) {
            projectClasspathList.add(new File(element).toURI().toURL());
        }

        configurationBuilder.addUrls(projectClasspathList);

        configurationBuilder.addClassLoader(new URLClassLoader(projectClasspathList.toArray(new URL[0]),
                Thread.currentThread().getContextClassLoader()));
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage());
    }
}

From source file:io.cloudslang.runtime.impl.java.JavaExecutor.java

JavaExecutor(Set<String> filePaths) {
    logger.info("Creating java classloader with [" + filePaths.size() + "] dependencies [" + filePaths + "]");
    if (!filePaths.isEmpty()) {
        Set<URL> result = Sets.newHashSet();
        for (String filePath : filePaths) {
            try {
                result.add(new File(filePath).toURI().toURL());
            } catch (MalformedURLException e) {
                logger.error("Failed to add to the classloader path [" + filePath + "]", e);
            }/* w ww .jav a2s . c o  m*/
        }
        classLoader = new URLClassLoader(result.toArray(new URL[result.size()]), PARENT_CLASS_LOADER);
    } else {
        // no dependencies - use application classloader
        classLoader = getClass().getClassLoader();
    }
}

From source file:org.apache.axis.components.compiler.Javac.java

private ClassLoader getClassLoader() {
    // Use reflection to be able to build on all JDKs
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    URL toolsURL = null;/*ww  w . j  av a 2  s.c om*/
    String tools = System.getProperty("java.home");
    if (tools != null) {
        File f = new File(tools + "/../lib/tools.jar");
        if (f.exists()) {
            try {
                toolsURL = f.toURL();
                cl = new URLClassLoader(new URL[] { toolsURL }, cl);
            } catch (MalformedURLException e) {
            }
        }
    }

    return cl;
}

From source file:com.mg.jet.birt.report.data.oda.ejbql.HibernateUtil.java

private static synchronized void initSessionFactory(String hibfile, String mapdir, String jndiName)
        throws HibernateException {
    //ClassLoader cl1;

    if (sessionFactory == null) {

        if (jndiName == null || jndiName.trim().length() == 0)
            jndiName = CommonConstant.DEFAULT_JNDI_URL;
        Context initCtx = null;/*from   w  w  w . j  a va  2s  .c  om*/
        try {
            initCtx = new InitialContext();
            sessionFactory = (SessionFactory) initCtx.lookup(jndiName);
            return;
        } catch (Exception e) {
            logger.log(Level.INFO, "Unable to get JNDI data source connection", e);
        } finally {
            if (initCtx != null)
                try {
                    initCtx.close();
                } catch (NamingException e) {
                    //ignore
                }
        }

        Thread thread = Thread.currentThread();
        try {
            //Class.forName("org.hibernate.Configuration");
            //Configuration ffff = new Configuration();
            //Class.forName("org.apache.commons.logging.LogFactory");

            oldloader = thread.getContextClassLoader();
            //Class thwy = oldloader.loadClass("org.hibernate.cfg.Configuration");
            //Class thwy2 = oldloader.loadClass("org.apache.commons.logging.LogFactory");
            //refreshURLs();
            //ClassLoader changeLoader = new URLClassLoader( (URL [])URLList.toArray(new URL[0]),HibernateUtil.class.getClassLoader());
            ClassLoader testLoader = new URLClassLoader((URL[]) URLList.toArray(new URL[0]), pluginLoader);
            //changeLoader = new URLClassLoader( (URL [])URLList.toArray(new URL[0]));

            thread.setContextClassLoader(testLoader);
            //Class thwy2 = changeLoader.loadClass("org.hibernate.cfg.Configuration");
            //Class.forName("org.apache.commons.logging.LogFactory", true, changeLoader);
            //Class cls = Class.forName("org.hibernate.cfg.Configuration", true, changeLoader);
            //Configuration cfg=null;
            //cfg = new Configuration();
            //Object oo = cls.newInstance();
            //Configuration cfg = (Configuration)oo;
            Configuration cfg = new Configuration();
            buildConfig(hibfile, mapdir, cfg);

            Class<? extends Driver> driverClass = testLoader
                    .loadClass(cfg.getProperty("connection.driver_class")).asSubclass(Driver.class);
            Driver driver = driverClass.newInstance();
            WrappedDriver wd = new WrappedDriver(driver, cfg.getProperty("connection.driver_class"));

            boolean foundDriver = false;
            Enumeration<Driver> drivers = DriverManager.getDrivers();
            while (drivers.hasMoreElements()) {
                Driver nextDriver = (Driver) drivers.nextElement();
                if (nextDriver.getClass() == wd.getClass()) {
                    if (nextDriver.toString().equals(wd.toString())) {
                        foundDriver = true;
                        break;
                    }
                }
            }
            if (!foundDriver) {

                DriverManager.registerDriver(wd);
            }

            sessionFactory = cfg.buildSessionFactory();
            //configuration = cfg;
            HibernateMapDirectory = mapdir;
            HibernateConfigFile = hibfile;
        } catch (Throwable e) {
            e.printStackTrace();
            throw new HibernateException("No Session Factory Created " + e.getLocalizedMessage(), e);
        } finally {
            thread.setContextClassLoader(oldloader);
        }
    }
}