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, final ClassLoader parent) 

Source Link

Document

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

Usage

From source file:me.jaimegarza.syntax.test.java.TestLalr.java

@Test
public void test01WithExecute() throws ParsingException, AnalysisException, OutputException,
        MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException,
        NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
    generateLanguageFile(expandedArgs);//from w  w  w .  j a  v a2  s.c om

    File source = new File(tmpLanguageFile);
    File sourceDir = source.getParentFile();
    CompilationResult result = compileJavaFile(source, sourceDir);
    if (result.getErrors().length > 0) {
        for (CompilationProblem cr : result.getErrors()) {
            System.err.println(cr);
        }
    }
    Assert.assertEquals(result.getErrors().length, 0, "Syntax errors found trying to execute");

    URL urls[] = new URL[1];
    urls[0] = sourceDir.toURI().toURL();
    URLClassLoader classLoader = URLClassLoader.newInstance(urls, this.getClass().getClassLoader());
    String className = FilenameUtils.getBaseName(tmpLanguageFile);
    Class<?> clazz = classLoader.loadClass(className);
    Object parser = clazz.newInstance();
    Method setVerbose = parser.getClass().getMethod("setVerbose", boolean.class);
    Method parse = parser.getClass().getMethod("parse");
    Method getExpr = parser.getClass().getMethod("getExpr");
    setVerbose.invoke(parser, true);
    Object o = parse.invoke(parser);
    Assert.assertTrue(o instanceof Integer);
    int rc = (Integer) o;
    Assert.assertEquals(rc, 1, "Parse did not succeed");
    o = getExpr.invoke(parser);
    Assert.assertTrue(o instanceof String);
    String s = (String) o;
    Assert.assertEquals(s, "(abc)d", "string does not match");
}

From source file:me.jaimegarza.syntax.test.java.TestJavaLexerModes.java

@Test
public void testJavaLexerModes() throws ParsingException, AnalysisException, OutputException,
        MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException,
        NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
    generateLanguageFile(args);//w  w  w.ja va  2 s .  co  m
    File source = new File(tmpLanguageFile);
    File sourceDir = source.getParentFile();
    CompilationResult result = compileJavaFile(source, sourceDir);

    if (result.getErrors().length > 0) {
        for (CompilationProblem problemo : result.getErrors()) {
            if (problemo.isError()) {
                System.err.println(problemo.toString());
            }
        }
        Assert.fail("Errors during the compilation of the output java file");
    }

    URL urls[] = new URL[1];
    urls[0] = sourceDir.toURI().toURL();
    URLClassLoader classLoader = URLClassLoader.newInstance(urls, this.getClass().getClassLoader());
    String className = FilenameUtils.getBaseName(tmpLanguageFile);
    Class<?> clazz = classLoader.loadClass(className);
    Object parser = clazz.newInstance();
    //Method setVerbose = parser.getClass().getMethod("setVerbose", boolean.class);
    Method parse = parser.getClass().getMethod("parse");
    Method getOutput = parser.getClass().getMethod("getOutput");
    //setVerbose.invoke(parser, true);
    Object o = parse.invoke(parser);
    Assert.assertTrue(o instanceof Integer);
    int rc = (Integer) o;
    Assert.assertEquals(rc, 1, "Parse did not succeed");
    o = getOutput.invoke(parser);
    Assert.assertTrue(o instanceof String);
    String s = (String) o;
    Assert.assertEquals(s, "bacaab", "string does not match");
}

From source file:me.jaimegarza.syntax.test.java.TestJavaRegexTokenizer.java

@Test
public void test01WithExecute() throws ParsingException, AnalysisException, OutputException,
        MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException,
        NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
    generateLanguageFile(expandedArgs);/* w  w  w  . j  a va 2s .c o  m*/

    File source = new File(tmpLanguageFile);
    File sourceDir = source.getParentFile();
    CompilationResult result = compileJavaFile(source, sourceDir);
    if (result.getErrors().length > 0) {
        for (CompilationProblem cr : result.getErrors()) {
            System.err.println(cr);
        }
    }
    Assert.assertEquals(result.getErrors().length, 0, "Syntax errors found trying to execute");

    URL urls[] = new URL[1];
    urls[0] = sourceDir.toURI().toURL();
    URLClassLoader classLoader = URLClassLoader.newInstance(urls, this.getClass().getClassLoader());
    String className = FilenameUtils.getBaseName(tmpLanguageFile);
    Class<?> clazz = classLoader.loadClass(className);
    Object parser = clazz.newInstance();
    //Method setVerbose = parser.getClass().getMethod("setVerbose", boolean.class);
    Method parse = parser.getClass().getMethod("parse");
    Method getExpr = parser.getClass().getMethod("getExpr");
    //setVerbose.invoke(parser, true);
    Object o = parse.invoke(parser);
    Assert.assertTrue(o instanceof Integer);
    int rc = (Integer) o;
    Assert.assertEquals(rc, 1, "Parse did not succeed");
    o = getExpr.invoke(parser);
    Assert.assertTrue(o instanceof String);
    String s = (String) o;
    Assert.assertEquals(s, "EABCDFGIA", "string does not match");
}

From source file:org.kalaider.desktop.scheduler.runner.Runner.java

private static void runScheduler(Path configFilePath, String profile, int nThreads) throws Exception {
    Path libs = Paths.get("./lib");
    Path plugins = Paths.get("./plugin");

    LOG.log(Level.INFO, "Libraries found: {}.", Arrays.asList(getUrlsInDirectory(libs)));
    LOG.log(Level.INFO, "Plugins found: {}.", Arrays.asList(getUrlsInDirectory(plugins)));

    ClassLoader libsLoader = URLClassLoader.newInstance(getUrlsInDirectory(libs),
            Thread.currentThread().getContextClassLoader());
    ClassLoader pluginsLoader = URLClassLoader.newInstance(getUrlsInDirectory(plugins), libsLoader);

    Thread newDaemon = new Thread(() -> {
        synchronized (lock) {
            Class<?> schedulerInstanceClass;

            try {
                schedulerInstanceClass = pluginsLoader
                        .loadClass("org.kalaider.desktop.scheduler.SchedulerInstance");
            } catch (ClassNotFoundException ex) {
                LOG.fatal("Class not found.", ex);
                return;
            }/*from w w w .  j ava2s .c o  m*/

            Method getDefaultInstanceMethod;

            try {
                getDefaultInstanceMethod = schedulerInstanceClass.getMethod("getDefaultInstance", Path.class,
                        String.class, int.class);
            } catch (NoSuchMethodException | SecurityException ex) {
                LOG.fatal("Method not found.", ex);
                return;
            }

            try {
                schedulerInstance = getDefaultInstanceMethod.invoke(null, configFilePath, profile, nThreads);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                LOG.fatal("Illegal method call.", ex);
                return;
            }

            Method startupMethod;

            try {
                startupMethod = schedulerInstanceClass.getMethod("startup");
            } catch (NoSuchMethodException | SecurityException ex) {
                LOG.fatal("Method not found.", ex);
                return;
            }
            try {
                startupMethod.invoke(schedulerInstance);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                LOG.fatal("Illegal method call.", ex);
                return;
            }
        }
    });
    newDaemon.setName("SchedulerRunnerThread");
    newDaemon.setContextClassLoader(pluginsLoader);
    newDaemon.setDaemon(true);
    newDaemon.start();
}

From source file:com.stratio.explorer.interpreter.InterpreterFactory.java

public Interpreter createRepl(String dirName, String className, Properties property) {
    logger.info("Create repl {} from {}", className, dirName);

    ClassLoader oldcl = Thread.currentThread().getContextClassLoader();
    try {//  ww w.j  a  v a2s. com

        URLClassLoader ccl = cleanCl.get(dirName);
        if (ccl == null) {
            // classloader fallback
            ccl = URLClassLoader.newInstance(new URL[] {}, oldcl);
        }

        boolean separateCL = true;
        try { // check if server's classloader has driver already.
            Class cls = this.getClass().forName(className);
            if (cls != null) {
                separateCL = false;
            }
        } catch (Exception e) {
            // nothing to do.
        }

        URLClassLoader cl;

        if (separateCL == true) {
            cl = URLClassLoader.newInstance(new URL[] {}, ccl);
        } else {
            cl = (URLClassLoader) ccl;
        }
        Thread.currentThread().setContextClassLoader(cl);

        Class<Interpreter> replClass = (Class<Interpreter>) cl.loadClass(className);
        Constructor<Interpreter> constructor = replClass.getConstructor(new Class[] { Properties.class });
        Interpreter repl = constructor.newInstance(property);
        if (conf.containsKey("args")) {
            property.put("args", conf.getProperty("args"));
        }
        property.put("share", share);
        property.put("classloaderUrls", ccl.getURLs());
        return new ClassloaderInterpreter(repl, cl, property);
    } catch (SecurityException e) {
        throw new InterpreterException(e);
    } catch (NoSuchMethodException e) {
        throw new InterpreterException(e);
    } catch (IllegalArgumentException e) {
        throw new InterpreterException(e);
    } catch (InstantiationException e) {
        throw new InterpreterException(e);
    } catch (IllegalAccessException e) {
        throw new InterpreterException(e);
    } catch (InvocationTargetException e) {
        throw new InterpreterException(e);
    } catch (ClassNotFoundException e) {
        throw new InterpreterException(e);
    } finally {
        Thread.currentThread().setContextClassLoader(oldcl);
    }
}

From source file:me.jaimegarza.syntax.test.java.TestJavaPackedParser.java

@Test
public void test03Runtime() throws ParsingException, AnalysisException, OutputException, MalformedURLException,
        ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException,
        NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
    generateLanguageFile(packedArgs);/*ww w  .  j a  v  a  2  s.c o  m*/

    File source = new File(tmpLanguageFile);
    File sourceDir = source.getParentFile();
    CompilationResult result = compileJavaFile(source, sourceDir);
    Assert.assertEquals(result.getErrors().length, 0, "Syntax errors found trying to execute");

    URL urls[] = new URL[1];
    urls[0] = sourceDir.toURI().toURL();
    URLClassLoader classLoader = URLClassLoader.newInstance(urls, this.getClass().getClassLoader());
    String className = FilenameUtils.getBaseName(tmpLanguageFile);
    Class<?> clazz = classLoader.loadClass(className);
    Object parser = clazz.newInstance();
    Method setVerbose = parser.getClass().getMethod("setVerbose", boolean.class);
    Method parse = parser.getClass().getMethod("parse");
    Method getTotal = parser.getClass().getMethod("getTotal");
    setVerbose.invoke(parser, true);
    parse.invoke(parser);
    Object o = getTotal.invoke(parser);
    Assert.assertTrue(o instanceof Integer);
    Integer i = (Integer) o;
    Assert.assertEquals((int) i, -17, "total does not match");
}

From source file:org.batfish.common.plugin.PluginConsumer.java

private void loadPluginJar(Path path) {
    /*// w  w w.j a  v a2  s . co m
     * Adapted from
     * http://stackoverflow.com/questions/11016092/how-to-load-classes-at-
     * runtime-from-a-folder-or-jar Retrieved: 2016-08-31 Original Authors:
     * Kevin Crain http://stackoverflow.com/users/2688755/kevin-crain
     * Apfelsaft http://stackoverflow.com/users/1447641/apfelsaft License:
     * https://creativecommons.org/licenses/by-sa/3.0/
     */
    String pathString = path.toString();
    if (pathString.endsWith(".jar")) {
        try {
            URL[] urls = { new URL("jar:file:" + pathString + "!/") };
            URLClassLoader cl = URLClassLoader.newInstance(urls, _currentClassLoader);
            _currentClassLoader = cl;
            Thread.currentThread().setContextClassLoader(cl);
            JarFile jar = new JarFile(path.toFile());
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry element = entries.nextElement();
                String name = element.getName();
                if (element.isDirectory() || !name.endsWith(CLASS_EXTENSION)) {
                    continue;
                }
                String className = name.substring(0, name.length() - CLASS_EXTENSION.length()).replace("/",
                        ".");
                try {
                    cl.loadClass(className);
                    Class<?> pluginClass = Class.forName(className, true, cl);
                    if (!Plugin.class.isAssignableFrom(pluginClass)
                            || Modifier.isAbstract(pluginClass.getModifiers())) {
                        continue;
                    }
                    Constructor<?> pluginConstructor;
                    try {
                        pluginConstructor = pluginClass.getConstructor();
                    } catch (NoSuchMethodException | SecurityException e) {
                        throw new BatfishException(
                                "Could not find default constructor in plugin: '" + className + "'", e);
                    }
                    Object pluginObj;
                    try {
                        pluginObj = pluginConstructor.newInstance();
                    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                            | InvocationTargetException e) {
                        throw new BatfishException(
                                "Could not instantiate plugin '" + className + "' from constructor", e);
                    }
                    Plugin plugin = (Plugin) pluginObj;
                    plugin.initialize(this);

                } catch (ClassNotFoundException e) {
                    jar.close();
                    throw new BatfishException("Unexpected error loading classes from jar", e);
                }
            }
            jar.close();
        } catch (IOException e) {
            throw new BatfishException("Error loading plugin jar: '" + path.toString() + "'", e);
        }
    }
}

From source file:me.jaimegarza.syntax.test.java.TestJavaExpandedParser.java

@Test
public void test03Runtime() throws ParsingException, AnalysisException, OutputException, MalformedURLException,
        ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException,
        NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
    generateLanguageFile(expandedArgs);/*from w w  w .j av  a 2 s . com*/

    File source = new File(tmpLanguageFile);
    File sourceDir = source.getParentFile();
    CompilationResult result = compileJavaFile(source, sourceDir);
    Assert.assertEquals(result.getErrors().length, 0, "Syntax errors found trying to execute");

    URL urls[] = new URL[1];
    urls[0] = sourceDir.toURI().toURL();
    URLClassLoader classLoader = URLClassLoader.newInstance(urls, this.getClass().getClassLoader());
    String className = FilenameUtils.getBaseName(tmpLanguageFile);
    Class<?> clazz = classLoader.loadClass(className);
    Object parser = clazz.newInstance();
    Method setVerbose = parser.getClass().getMethod("setVerbose", boolean.class);
    Method parse = parser.getClass().getMethod("parse");
    Method getTotal = parser.getClass().getMethod("getTotal");
    setVerbose.invoke(parser, true);
    parse.invoke(parser);
    Object o = getTotal.invoke(parser);
    Assert.assertTrue(o instanceof Integer);
    Integer i = (Integer) o;
    Assert.assertEquals((int) i, -17, "total does not match");
}

From source file:me.jaimegarza.syntax.test.java.TestJavaExpandedScanner.java

@Test
public void test03Runtime() throws ParsingException, AnalysisException, OutputException, MalformedURLException,
        ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException,
        NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
    generateLanguageFile(packedArgs);//w w w . j  a v a  2s .  c o m

    File source = new File(tmpLanguageFile);
    File sourceDir = source.getParentFile();
    CompilationResult result = compileJavaFile(source, sourceDir);
    Assert.assertEquals(result.getErrors().length, 0, "Syntax errors found trying to execute");

    URL urls[] = new URL[1];
    urls[0] = sourceDir.toURI().toURL();
    URLClassLoader classLoader = URLClassLoader.newInstance(urls, this.getClass().getClassLoader());
    String className = FilenameUtils.getBaseName(tmpLanguageFile);
    Class<?> clazz = classLoader.loadClass(className);
    String lexicalClassName = className + "$StackElement";
    Class<?> lexicalClazz = classLoader.loadClass(lexicalClassName);
    Object parser = clazz.newInstance();
    Method setVerbose = parser.getClass().getMethod("setVerbose", boolean.class);
    Method init = parser.getClass().getMethod("init");
    Method parse = parser.getClass().getMethod("parse", Integer.TYPE, lexicalClazz);
    Method getValidTokens = parser.getClass().getMethod("getValidTokens");
    Method getTotal = parser.getClass().getMethod("getTotal");
    setVerbose.invoke(parser, true);
    init.invoke(parser);
    for (Parameter p : parameters) {
        int[] tokens = (int[]) getValidTokens.invoke(parser);
        Assert.assertTrue(arrayContains(tokens, p.token), "Token " + p.token + " ain't there");
        Object lexicalValue = lexicalClazz.newInstance();
        Method setNumber = lexicalClazz.getMethod("setNumber", Integer.TYPE);
        setNumber.invoke(lexicalValue, p.value);
        parse.invoke(parser, p.token, lexicalValue);
        Object t = getTotal.invoke(parser);
        Assert.assertEquals(((Integer) t).intValue(), p.result, "Result is not " + p.result);
    }
    Object o = getTotal.invoke(parser);
    Assert.assertTrue(o instanceof Integer);
    Integer i = (Integer) o;
    Assert.assertEquals((int) i, -17, "total does not match");
}

From source file:org.asoem.greyfish.cli.GreyfishCLIApplication.java

private static Module createCommandLineModule(final OptionSet optionSet) {

    return new AbstractModule() {
        @SuppressWarnings("unchecked")
        @Override/*from   www  . j  av  a  2s .co  m*/
        protected void configure() {

            if (optionSet.nonOptionArguments().size() != 1) {
                exitWithErrorMessage("Missing CLASS argument");
            }

            final String modelClassName = optionSet.nonOptionArguments().get(0);

            ClassLoader classLoader = GreyfishCLIApplication.class.getClassLoader();
            if (optionSet.has(classpathOptionSpec)) {
                for (String classPath : optionSet.valuesOf(classpathOptionSpec)) {
                    try {
                        final File file = new File(classPath);
                        if (!file.canRead()) {
                            exitWithErrorMessage("Specified classpath is not readable: " + classPath);
                        }

                        classLoader = URLClassLoader.newInstance(new URL[] { file.toURI().toURL() },
                                classLoader);
                    } catch (MalformedURLException e) {
                        throw new AssertionError(e);
                    }
                }
            }

            try {
                final Class<?> experimentClass = Class.forName(modelClassName, true, classLoader);
                if (!Experiment.class.isAssignableFrom(experimentClass)) {
                    exitWithErrorMessage("Specified Class does not implement " + Experiment.class);
                }
                bind(Experiment.class).to((Class<Experiment>) experimentClass);
            } catch (ClassNotFoundException e) {
                logger.error("Unable to load class {}", modelClassName, e);
                exitWithErrorMessage("Could not find class " + modelClassName);
            }

            if (optionSet.has(modelParameterOptionSpec)) {
                final Map<String, String> properties = Maps.newHashMap();
                final List<ModelParameterOptionValue> modelParameterOptionValues = optionSet
                        .valuesOf(modelParameterOptionSpec);
                for (final ModelParameterOptionValue modelParameterOption : modelParameterOptionValues) {
                    if (properties.containsKey(modelParameterOption.key)) {
                        logger.warn("Model parameter {} was defined twice. Overwriting value {} with {}",
                                modelParameterOption.key, properties.get(modelParameterOption.key),
                                modelParameterOption.value);
                    }
                    properties.put(modelParameterOption.key, modelParameterOption.value);
                }
                bindListener(Matchers.any(), new ModelParameterTypeListener(properties));
                ModelParameters.bind(binder(), properties);
            }

            bind(Boolean.class).annotatedWith(Names.named("quiet"))
                    .toProvider(Providers.of(optionSet.has(quietOptionSpec)));
            bind(Integer.class).annotatedWith(Names.named("parallelizationThreshold"))
                    .toInstance(optionSet.valueOf(parallelizationThresholdOptionSpec));

            // TODO: Move logger definition to experiment
            final String pathname = optionSet.valueOf(workingDirectoryOptionSpec) + "/"
                    + optionSet.valueOf(simulationNameOptionSpec);
            final String path = Files.simplifyPath(pathname);

            final Provider<SimulationLogger> loggerProvider = new Provider<SimulationLogger>() {
                @Override
                public SimulationLogger get() {
                    final GreyfishH2ConnectionManager connectionSupplier = GreyfishH2ConnectionManager.create(
                            path, GreyfishH2ConnectionManager.defaultInitSql(),
                            GreyfishH2ConnectionManager.defaultFinalizeSql());
                    final SimulationLogger jdbcLogger = SimulationLoggers.createJDBCLogger(connectionSupplier,
                            optionSet.valueOf(commitThresholdSpec));

                    closer.register(connectionSupplier);
                    // Logger must be closed before the connection (put on stack after the connection)
                    closer.register(jdbcLogger);

                    return jdbcLogger;
                }
            };

            bind(SimulationLogger.class).toProvider(loggerProvider).in(Scopes.SINGLETON);
        }

    };
}