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:cz.muni.fi.mir.services.MathCanonicalizerLoaderImpl.java

@Override
public void execute(List<Formula> formulas, ApplicationRun applicationRun) throws IllegalStateException {
    if (!fileService.canonicalizerExists(applicationRun.getRevision().getRevisionHash())) {
        throw new IllegalStateException("Given canonicalizer with revision ["
                + applicationRun.getRevision().getRevisionHash() + "] does not exists.");
    } else {/*from  w ww  .ja va  2  s .c o  m*/
        Path path = FileSystems.getDefault().getPath(this.jarFolder,
                applicationRun.getRevision().getRevisionHash() + ".jar");
        Class mainClass = null;
        URL jarFile = null;
        try {
            jarFile = path.toUri().toURL();
        } catch (MalformedURLException me) {
            logger.fatal(me);
        }
        URLClassLoader cl = URLClassLoader.newInstance(new URL[] { jarFile });

        try {
            mainClass = cl.loadClass("cz.muni.fi.mir.mathmlcanonicalization." + this.mainClassName);
        } catch (ClassNotFoundException cnfe) {
            logger.fatal(cnfe);
        }

        CanonicalizationTask ct = taskFactory.createTask();

        ct.setDependencies(formulas, applicationRun, mainClass);

        taskService.submitTask(ct);
    }
}

From source file:org.jamocha.classloading.Loader.java

/**
 * Recursively loads all class files in the specified jar file within the specified package.
 *
 * @param pathToJar//from  w w  w  .  j  ava 2  s  .  co  m
 *         the path to the jar file containing the package hierarchy (separator '/')
 * @param packageString
 *         the path within the package hierarchy (separator '/')
 */
public static void loadClassesInJar(final String pathToJar, final String packageString) {
    log.debug("Loading classes in jar:file:{}!/{}", pathToJar, packageString);
    try (final JarFile jarFile = new JarFile(pathToJar)) {
        final URL[] urls = { new URL("jar:file:" + pathToJar + "!/" + packageString) };
        try (final URLClassLoader loader = URLClassLoader.newInstance(urls)) {
            jarFile.stream().filter(entry -> !entry.isDirectory() && entry.getName().endsWith(".class")
                    && entry.getName().startsWith(packageString)).forEach(entry -> {
                        final String className = filePathToClassName(entry.getName());
                        log.debug("Loading class {}", className);
                        try {
                            Class.forName(className, true, loader);
                        } catch (final ClassNotFoundException ex) {
                            log.catching(ex);
                        } catch (final ExceptionInInitializerError ex) {
                            log.catching(ex);
                        }
                    });
        }
    } catch (final IOException ex) {
        log.catching(ex);
    }
}

From source file:request.processing.ServletLoader.java

public static void loadServlet(String servletDir) {
    try {//from   w  w  w  .  j a v  a2s  .c  o m
        JarFile jarFile = new JarFile(servletDir);
        Enumeration<JarEntry> e = jarFile.entries();

        URL[] urls = { new URL("jar:file:" + servletDir + "!/") };
        URLClassLoader cl = URLClassLoader.newInstance(urls);
        while (e.hasMoreElements()) {
            try {
                JarEntry je = (JarEntry) e.nextElement();
                if (je.isDirectory() || !je.getName().endsWith(".class")) {
                    continue;
                }
                String className = je.getName().substring(0, je.getName().length() - 6);
                className = className.replace('/', '.');
                Class c = cl.loadClass(className);
                if (Servlet.class.isAssignableFrom(c)) {
                    Constructor<Servlet> constructor = c.getConstructor();
                    Servlet i = constructor.newInstance();
                    namesToServlets.put(c.getSimpleName(), i);
                } else {
                    continue;
                }

            } catch (ClassNotFoundException cnfe) {
                System.err.println("Class not found");
                cnfe.printStackTrace();
            } catch (NoSuchMethodException e1) {
                System.err.println("No such method");
                e1.printStackTrace();
            } catch (SecurityException e1) {
                System.err.println("Security Exception");
                e1.printStackTrace();
            } catch (InstantiationException e1) {
                System.err.println("Instantiation Exception");
                e1.printStackTrace();
            } catch (IllegalAccessException e1) {
                System.err.println("IllegalAccessException");
                e1.printStackTrace();
            } catch (IllegalArgumentException e1) {
                System.err.println("IllegalArgumentException");
                e1.printStackTrace();
            } catch (InvocationTargetException e1) {
                System.err.println("InvocationTargetException");
                e1.printStackTrace();
            }

        }
        jarFile.close();
    } catch (IOException e) {
        System.err.println("Not a jarFile, no biggie. Moving on.");
    }
}

From source file:org.kitodo.serviceloader.KitodoServiceLoader.java

/**
 * Loads bean classes and registers them to the FacesContext. Afterwards
 * they can be used in all frontend files
 *//*from   www  . ja va 2  s .  co m*/
private void loadBeans() {
    Path moduleFolder = FileSystems.getDefault().getPath(modulePath);
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(moduleFolder, JAR)) {

        for (Path f : stream) {
            try (JarFile jarFile = new JarFile(f.toString())) {

                if (hasFrontendFiles(jarFile)) {

                    Enumeration<JarEntry> e = jarFile.entries();

                    URL[] urls = { new URL("jar:file:" + f.toString() + "!/") };
                    try (URLClassLoader cl = URLClassLoader.newInstance(urls)) {
                        while (e.hasMoreElements()) {
                            JarEntry je = e.nextElement();

                            /*
                             * IMPORTANT: Naming convention: the name of the
                             * java class has to be in upper camel case or
                             * "pascal case" and must be equal to the file
                             * name of the corresponding facelet file
                             * concatenated with the word "Form".
                             *
                             * Example: template filename "sample.xhtml" =>
                             * "SampleForm.java"
                             *
                             * That is the reason for the following check
                             * (e.g. whether the JarEntry name ends with
                             * "Form.class")
                             */
                            if (je.isDirectory() || !je.getName().endsWith("Form.class")) {
                                continue;
                            }

                            String className = je.getName().substring(0, je.getName().length() - 6);
                            className = className.replace('/', '.');
                            Class c = cl.loadClass(className);

                            String beanName = className.substring(className.lastIndexOf('.') + 1).trim();

                            FacesContext facesContext = FacesContext.getCurrentInstance();
                            HttpSession session = (HttpSession) facesContext.getExternalContext()
                                    .getSession(false);

                            session.getServletContext().setAttribute(beanName, c.newInstance());
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.error(ERROR, e.getMessage());
    }
}

From source file:hydrograph.ui.expression.editor.buttons.ValidateExpressionToolButton.java

/**
 * Complies the given expression using engine's jar from ELT-Project's build path. 
 * //from w  w  w.j  a  va2  s . co m
 * @param expressionStyledText
 * @param fieldMap
 * @param componentName
 * @return DiagnosticCollector 
 *          complete diagnosis of given expression
 * @throws JavaModelException
 * @throws InvocationTargetException
 * @throws ClassNotFoundException
 * @throws MalformedURLException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 */
@SuppressWarnings({ "unchecked" })
public static DiagnosticCollector<JavaFileObject> compileExpresion(String expressionStyledText,
        Map<String, Class<?>> fieldMap, String componentName)
        throws JavaModelException, InvocationTargetException, ClassNotFoundException, MalformedURLException,
        IllegalAccessException, IllegalArgumentException {
    LOGGER.debug("Compiling expression using Java-Compiler");
    String expressiontext = getExpressionText(expressionStyledText);
    DiagnosticCollector<JavaFileObject> diagnostics = null;
    Object[] returObj = getBuildPathForMethodInvocation();
    List<URL> urlList = (List<URL>) returObj[0];
    String transfromJarPath = (String) returObj[1];
    String propertyFilePath = (String) returObj[2];
    URLClassLoader child = URLClassLoader.newInstance(urlList.toArray(new URL[urlList.size()]));

    Class<?> class1 = Class.forName(HYDROGRAPH_ENGINE_EXPRESSION_VALIDATION_API_CLASS, true, child);
    Thread.currentThread().setContextClassLoader(child);
    Method[] methods = class1.getDeclaredMethods();
    for (Method method : methods) {
        if (method.getParameterTypes().length == 4
                && StringUtils.equals(method.getName(),
                        COMPILE_METHOD_OF_EXPRESSION_JAR_FOR_TRANSFORM_COMPONENTS)
                && !StringUtils.equalsIgnoreCase(componentName, hydrograph.ui.common.util.Constants.FILTER)) {
            method.getDeclaringClass().getClassLoader();
            diagnostics = (DiagnosticCollector<JavaFileObject>) method.invoke(null, expressiontext,
                    propertyFilePath, fieldMap, transfromJarPath);

            break;
        } else if (method.getParameterTypes().length == 4
                && StringUtils.equals(method.getName(), COMPILE_METHOD_OF_EXPRESSION_JAR_FOR_FILTER_COMPONENT)
                && StringUtils.equalsIgnoreCase(componentName, hydrograph.ui.common.util.Constants.FILTER)) {
            method.getDeclaringClass().getClassLoader();
            diagnostics = (DiagnosticCollector<JavaFileObject>) method.invoke(null, expressiontext,
                    propertyFilePath, fieldMap, transfromJarPath);
            break;
        }

    }

    try {
        child.close();
    } catch (IOException ioException) {
        LOGGER.error("Error occurred while closing classloader", ioException);
    }
    return diagnostics;
}

From source file:hydrograph.ui.expression.editor.evaluate.EvaluateExpression.java

@SuppressWarnings({ "unchecked" })
String invokeEvaluateFunctionFromJar(String expression, String[] fieldNames, Object[] values) {
    LOGGER.debug("Evaluating expression from jar");
    String output = null;/*  w w w  .j a  va2s  . c o  m*/
    Object[] returnObj;
    expression = ValidateExpressionToolButton.getExpressionText(expression);
    URLClassLoader child = null;
    try {
        returnObj = ValidateExpressionToolButton.getBuildPathForMethodInvocation();
        List<URL> urlList = (List<URL>) returnObj[0];
        String userFunctionsPropertyFileName = (String) returnObj[2];
        child = URLClassLoader.newInstance(urlList.toArray(new URL[urlList.size()]));
        Thread.currentThread().setContextClassLoader(child);
        Class<?> class1 = Class.forName(
                ValidateExpressionToolButton.HYDROGRAPH_ENGINE_EXPRESSION_VALIDATION_API_CLASS, true, child);
        Method[] methods = class1.getDeclaredMethods();
        for (Method method : methods) {
            if (method.getParameterTypes().length == 4
                    && StringUtils.equals(method.getName(), EVALUATE_METHOD_OF_EXPRESSION_JAR)) {
                method.getDeclaringClass().getClassLoader();
                output = String.valueOf(
                        method.invoke(null, expression, userFunctionsPropertyFileName, fieldNames, values));
                break;
            }
        }
    } catch (JavaModelException | MalformedURLException | ClassNotFoundException | IllegalAccessException
            | IllegalArgumentException exception) {
        evaluateDialog.showError(Messages.ERROR_OCCURRED_WHILE_EVALUATING_EXPRESSION);
        LOGGER.error(Messages.ERROR_OCCURRED_WHILE_EVALUATING_EXPRESSION, exception);
    } catch (InvocationTargetException | RuntimeException exception) {
        if (exception.getCause().getCause() != null) {
            if (StringUtils.equals(exception.getCause().getCause().getClass().getSimpleName(),
                    TARGET_ERROR_EXCEPTION_CLASS)) {
                evaluateDialog.showError(getTargetException(exception.getCause().getCause().toString()));
            } else
                evaluateDialog.showError(exception.getCause().getCause().getMessage());
        } else
            evaluateDialog.showError(exception.getCause().getMessage());
        LOGGER.debug("Invalid Expression....", exception);
    } finally {
        if (child != null) {
            try {
                child.close();
            } catch (IOException ioException) {
                LOGGER.error("Error occurred while closing classloader", ioException);
            }
        }
    }
    return output;
}

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

/**
 * Get the handler instance.  /* ww w .  j  a  v  a 2 s .  c  om*/
 *  @param entigrator entigrator instance
 *  @param extension$ extension key
 *  @param handlerClass$ class name
 * @return handler instance.
 */

public static Object loadHandlerInstance(Entigrator entigrator, String extension$, String handlerClass$) {
    try {
        System.out.println(
                "ExtensionHandler:loadHandlerInstance:extension=" + extension$ + " handler=" + handlerClass$);

        Object obj = null;
        Class<?> cls = entigrator.getClass(handlerClass$);
        if (cls == null) {
            System.out.println("ExtensionHandler:loadHandlerInstance:1");
            Sack extension = entigrator.getEntityAtKey(extension$);
            String lib$ = extension.getElementItemAt("field", "lib");
            String jar$ = "jar:file:" + entigrator.getEntihome() + "/" + extension$ + "/" + lib$ + "!/";
            ArrayList<URL> urll = new ArrayList<URL>();
            urll.add(new URL(jar$));

            String[] sa = extension.elementListNoSorted("external");
            if (sa != null) {
                File file;
                for (String s : sa) {
                    file = new File(entigrator.getEntihome() + "/" + extension$ + "/" + s);
                    if (file.exists())
                        urll.add(new URL("jar:file:" + file.getPath() + "!/"));
                }
            }
            URL[] urls = urll.toArray(new URL[0]);
            URLClassLoader cl = URLClassLoader.newInstance(urls);

            //   Class<?>cls=entigrator.getClass(handlerClass$);

            cls = cl.loadClass(handlerClass$);

            if (cls == null) {
                System.out.println("ExtensionHandler:loadHandlerInstance:cannot load class =" + handlerClass$);
                return null;
            } else {
                //   System.out.println("ExtensionHandler:loadHandlerInstance:found class ="+handlerClass$);
                entigrator.putClass(handlerClass$, cls);
            }

        }

        try {

            Constructor[] ctors = cls.getDeclaredConstructors();
            System.out.println("ExtensionHandler:loadHandlerInstance:ctors=" + ctors.length);
            Constructor ctor = null;
            for (int i = 0; i < ctors.length; i++) {
                ctor = ctors[i];
                if (ctor.getGenericParameterTypes().length == 0)
                    break;
            }
            ctor.setAccessible(true);
            obj = ctor.newInstance();

        } catch (java.lang.NoClassDefFoundError ee) {
            System.out.println("ExtensionHandler:loadHandlerInstance:" + ee.toString());
            return null;
        }
        //if(obj!=null)
        System.out.println("ExtensionHandler:loadHandlerInstance:obj=" + obj.getClass().getName());
        return obj;
    } catch (Exception e) {
        Logger.getLogger(ExtensionHandler.class.getName()).severe(e.toString());
        return null;
    }

}

From source file:cf.janga.hook.core.SimplePluginLoader.java

<T extends CoreAPI> Plugin<T> loadPluginIntoClasspath(PluginFile<T> pluginFile) throws PluginException {
    pluginFile.getFilePath();/*from w w  w.  ja  v a  2  s  .c  o  m*/
    String pluginClassName = pluginFile.getPluginClass();
    if (StringUtils.isBlank(pluginClassName)) {
        throw new PluginException("The plugin class has not been provided on the manifest of the plugin file.");
    }
    try {
        URLClassLoader classLoader = URLClassLoader
                .newInstance(new URL[] { new File(pluginFile.getFilePath()).toURI().toURL() });
        Class<Plugin<T>> pluginClass = (Class<Plugin<T>>) classLoader.loadClass(pluginClassName);
        return pluginClass.newInstance();
    } catch (MalformedURLException e) {
        throw new PluginException("Error loading plugin file. The plugin folder may be missing or malformed.",
                e);
    } catch (ClassNotFoundException e) {
        throw new PluginException(
                "Error loading plugin file. The plugin class cannot be found on the file provided.", e);
    } catch (InstantiationException e) {
        throw new PluginException("Error instantiating the plugin class.", e);
    } catch (IllegalAccessException e) {
        throw new PluginException("Error instantiating the plugin. Illegal access to plugin class.", e);
    }
}

From source file:org.cloudfoundry.practical.demo.web.controller.CompilerController.java

private void runWithRedirectedOutput(final Folders folders) throws MalformedURLException,
        ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    List<URL> urls = new ArrayList<URL>();
    urls.add(ResourceURL.get(folders.getOutput()));
    urls.addAll(ResourceURL.getForResources(folders.getLibJars()));
    URLClassLoader classLoader = URLClassLoader.newInstance(urls.toArray(new URL[urls.size()]));
    invokeMain(classLoader);/*from  w  w  w. j  a  v  a 2s .c o  m*/
}

From source file:org.dbflute.intro.app.logic.dfprop.TestConnectionLogic.java

private Driver prepareJdbcDriver(String dbfluteVersion, OptionalThing<String> jdbcDriverJarPath,
        DatabaseInfoMap databaseInfoMap)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException, MalformedURLException {
    final List<URL> urls = new ArrayList<URL>();
    if (jdbcDriverJarPath.isPresent()) {
        final String jarPath = jdbcDriverJarPath.get();
        final URL fileUrl = new File(jarPath).toURI().toURL();
        urls.add(fileUrl);//from   www . jav a2 s  . co m
    } else {
        final File libDir = enginePhysicalLogic.findLibDir(dbfluteVersion);
        if (libDir.isDirectory()) {
            for (File existingJarFile : FileUtils.listFiles(libDir, FileFilterUtils.suffixFileFilter(".jar"),
                    null)) {
                try {
                    urls.add(existingJarFile.toURI().toURL());
                } catch (MalformedURLException e) { // no way
                    throw new IllegalStateException(
                            "Failed to create the URL for the jar file: " + existingJarFile.getPath());
                }
            }
        }
    }
    final URLClassLoader loader = URLClassLoader.newInstance(urls.toArray(new URL[urls.size()]));
    final String jdbcDriver = databaseInfoMap.getDriver();

    @SuppressWarnings("unchecked")
    final Class<Driver> driverClass = (Class<Driver>) loader.loadClass(jdbcDriver);
    return driverClass.newInstance();
}