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:org.drools.semantics.lang.dl.DL_9_CompilationTest.java

@Test
public void testIncrementalCompilation() {
    try {/*from ww w.ja va 2s  .c o  m*/

        OntoModel diamond = factory.buildModel("diamondX",
                ResourceFactory.newClassPathResource("ontologies/diamondProp.manchester.owl"),
                DLFactoryConfiguration.newConfiguration(OntoModel.Mode.OPTIMIZED));

        compiler = new OntoModelCompiler(diamond, folder.getRoot());

        List<Diagnostic<? extends JavaFileObject>> diag1 = compiler
                .compileOnTheFly(OntoModelCompiler.minimalOptions, OntoModelCompiler.MOJO_VARIANTS.JPA2);

        for (Diagnostic<?> dx : diag1) {
            System.out.println(dx);
            assertFalse(dx.getKind() == Diagnostic.Kind.ERROR);
        }

        showDirContent(folder);

        ClassLoader urlKL = new URLClassLoader(new URL[] { compiler.getBinDir().toURI().toURL() },
                Thread.currentThread().getContextClassLoader());

        OntoModel results = factory.buildModel("diamondInc",
                ResourceFactory.newClassPathResource("ontologies/dependency.test.owl"),
                DLFactoryConfiguration.newConfiguration(OntoModel.Mode.OPTIMIZED), urlKL);

        System.out.println(results);

        Class bot = Class.forName("org.jboss.drools.semantics.diamond.BottomImpl", true, urlKL);
        Class botIF = Class.forName("org.jboss.drools.semantics.diamond.Bottom", true, urlKL);
        Assert.assertNotNull(bot);
        Assert.assertNotNull(botIF);
        Object botInst = bot.newInstance();
        Assert.assertNotNull(botInst);

        OntoModelCompiler compiler2 = new OntoModelCompiler(results, folder.getRoot());

        compiler2.fixResolvedClasses();

        compiler2.streamJavaInterfaces(false);
        compiler2.streamXSDsWithBindings(true);

        compiler2.mojo(OntoModelCompiler.defaultOptions, OntoModelCompiler.MOJO_VARIANTS.JPA2);

        showDirContent(folder);

        File unImplBoundLeft = new File(compiler2.getXjcDir() + File.separator
                + "org.jboss.drools.semantics.diamond".replace(".", File.separator) + File.separator
                + "Left.java");
        assertFalse(unImplBoundLeft.exists());
        File implBoundLeft = new File(compiler2.getXjcDir() + File.separator
                + "org.jboss.drools.semantics.diamond".replace(".", File.separator) + File.separator
                + "LeftImpl.java");
        assertTrue(implBoundLeft.exists());

        File leftInterface = new File(compiler2.getJavaDir() + File.separator
                + "org.jboss.drools.semantics.diamond".replace(".", File.separator) + File.separator
                + "Left.java");

        assertTrue(leftInterface.exists());

        List<Diagnostic<? extends JavaFileObject>> diagnostics = compiler2.doCompile();

        for (Diagnostic<?> dx : diagnostics) {
            System.out.println(dx);
            assertFalse(dx.getKind() == Diagnostic.Kind.ERROR);
        }

        showDirContent(folder);

        Document dox = parseXML(new File(compiler2.getBinDir().getPath() + "/META-INF/persistence.xml"), false);
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression expr = xpath.compile("//persistence-unit/@name");
        assertEquals("diamondX", (String) expr.evaluate(dox, XPathConstants.STRING));

        File YInterface = new File(compiler2.getJavaDir() + File.separator
                + "org.jboss.drools.semantics.diamond".replace(".", File.separator) + File.separator
                + "X.java");
        assertTrue(YInterface.exists());

        Class colf = Class.forName("some.dependency.test.ChildOfLeftImpl", true, urlKL);
        Assert.assertNotNull(colf);
        Object colfInst = colf.newInstance();

        List<String> hierarchy = getHierarchy(colf);
        assertTrue(hierarchy.contains("some.dependency.test.ChildOfLeftImpl"));
        assertTrue(hierarchy.contains("some.dependency.test.org.jboss.drools.semantics.diamond.LeftImpl"));
        assertTrue(hierarchy.contains("org.jboss.drools.semantics.diamond.LeftImpl"));
        assertTrue(hierarchy.contains("org.jboss.drools.semantics.diamond.C0Impl"));
        assertTrue(hierarchy.contains("org.jboss.drools.semantics.diamond.TopImpl"));
        assertTrue(hierarchy.contains("org.w3._2002._07.owl.ThingImpl"));

        Set<String> itfHierarchy = getIFHierarchy(colf);

        System.err.println(itfHierarchy.containsAll(
                Arrays.asList("org.jboss.drools.semantics.diamond.C1", "org.jboss.drools.semantics.diamond.C0",
                        "some.dependency.test.org.jboss.drools.semantics.diamond.Left",
                        "some.dependency.test.ChildOfLeft", "org.jboss.drools.semantics.diamond.Left",
                        "org.jboss.drools.semantics.diamond.Top", "com.clarkparsia.empire.EmpireGenerated",
                        "org.w3._2002._07.owl.Thing", "java.io.Serializable", "org.drools.semantics.Thing",
                        "com.clarkparsia.empire.SupportsRdfId")));

        Method getter1 = colf.getMethod("getAnotherLeftProp");
        assertNotNull(getter1);
        Method getter2 = colf.getMethod("getImportantProp");
        assertNotNull(getter2);

        for (Method m : colf.getMethods()) {
            if (m.getName().equals("addImportantProp")) {
                m.getName();
            }
        }

        Method adder = colf.getMethod("addImportantProp", botIF);
        assertNotNull(adder);
        adder.invoke(colfInst, botInst);
        List l = (List) getter2.invoke(colfInst);
        assertEquals(1, l.size());

        File off = new File(compiler2.getXjcDir() + File.separator
                + "org.jboss.drools.semantics.diamond".replace(".", File.separator) + File.separator
                + "Left_Off.java");
        assertFalse(off.exists());

        testPersistenceWithInstance(urlKL, "org.jboss.drools.semantics.diamond.Bottom", diamond.getName());
        System.out.println(" Done");

    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }

}

From source file:org.apache.taverna.activities.dependencyactivity.AbstractAsynchronousDependencyActivity.java

/**
 * Constructs a classloader capable of finding both local jar and artifact dependencies.
 * Called when classloader sharing policy is set to 'workflow'.
 *
 * @return A {@link ClassLoader} capable of accessing all the dependencies (both local jar and artifact)
 *//* w ww .  j  ava 2s.com*/
private ClassLoader makeClassLoader(JsonNode json, String workflowID) {
    // Find all artifact dependencies
    //      HashSet<URL> urls = findDependencies(ARTIFACTS, configurationBean, workflowID);

    // Add all local jar dependencies
    HashSet<URL> urls = findDependencies(LOCAL_JARS, json, workflowID);

    // Create the classloader capable of loading both local jar and artifact dependencies
    ClassLoader parent = this.getClass().getClassLoader(); // this will be a LocalArtifactClassLoader

    return new URLClassLoader(urls.toArray(new URL[0]), parent) {

        // For finding native libraries that have to be stored in TAVERNA_HOME/lib
        @Override
        protected String findLibrary(String libname) {
            String filename = System.mapLibraryName(libname);
            File libraryFile = new File(libDir, filename);
            if (libraryFile.isFile()) {
                logger.info("Found library " + libname + ": " + libraryFile.getAbsolutePath());
                return libraryFile.getAbsolutePath();
            }
            return super.findLibrary(libname);
        }
    };
}

From source file:com.moss.nomad.core.runner.Runner.java

public void run(String migrationPathName, MigrationHistory history, byte[] env) throws Exception {

    MigrationPath path = findPath(migrationPathName);
    if (path == null) {
        throw new RuntimeException("Cannot find a migration path by the name of '" + migrationPathName + "'");
    }//from  ww w. ja  v a  2s . c om

    Set<MigrationDef> executed = new HashSet<MigrationDef>();
    for (Migration migration : history.migrations()) {
        executed.add(migration.def());
    }

    /*
     * NOTE: How we determine what migrations to perform could be a lot more
     * sophisticated. We aren't checking the history to make sure that
     * migrations are only executed in sequence. This is how schematrax
     * works, but we might want to improve on it.
     */

    List<MigrationPackage> unexecuted = new ArrayList<MigrationPackage>();
    for (MigrationPackage pkg : path.packages()) {

        if (!executed.contains(pkg.def())) {
            unexecuted.add(pkg);
        }
    }

    if (unexecuted.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("No migrations remain to be executed, doing nothing.");
        }
        return;
    }

    final byte[] buffer = new byte[1024 * 10]; //10k buffer

    for (MigrationPackage pkg : unexecuted) {

        if (pkg.resources() == null) {
            throw new RuntimeException(
                    "Cannot perform migration, migration resource not available in migration jar: "
                            + pkg.def());
        }

        if (log.isDebugEnabled()) {
            log.debug("Executing migration: " + pkg.def());
        }

        Migration migration = new Migration(new Instant(), pkg.def());
        MigrationResources res = pkg.resources();

        List<URL> urls = new ArrayList<URL>();
        for (String req : res.classpath()) {

            String[] pathSegments = req.split("\\/");

            File copyTarget = workDir;
            for (String s : pathSegments) {
                copyTarget = new File(copyTarget, s);
            }

            if (!copyTarget.getParentFile().exists() && !copyTarget.getParentFile().mkdirs()) {
                throw new RuntimeException("Cannot create directory: " + copyTarget.getParentFile());
            }

            if (!copyTarget.exists()) {

                if (log.isDebugEnabled()) {
                    log.debug("Copying classpath resource " + req + " -> " + copyTarget);
                }

                JarEntry entry = packageJar.getJarEntry(req);

                if (entry == null) {
                    throw new RuntimeException("Expected package jar entry not found: " + req);
                }

                InputStream in = packageJar.getInputStream(entry);
                OutputStream out = new FileOutputStream(copyTarget);
                for (int numRead = in.read(buffer); numRead != -1; numRead = in.read(buffer)) {
                    out.write(buffer, 0, numRead);
                }
                in.close();
                out.close();
            }

            urls.add(copyTarget.toURL());
        }

        ClassLoader cl;
        {
            URL[] cp = urls.toArray(new URL[0]);
            cl = new URLClassLoader(cp, null);
        }

        Class clazz = cl.loadClass("com.moss.nomad.api.v1.ClassLoaderBridge");

        Method method = clazz.getMethod("execute", String.class, byte[].class);

        ClassLoader currentCl = Thread.currentThread().getContextClassLoader();
        try {
            firePreMigration(migration);

            /*
             * NOTE, the reason we're setting the context class loader here
             * is for java 5 compatibility. JAXBContext seems to load its
             * classes from the current thread context class loader. In
             * java 5 this causes problems, in java 6 it doesn't because
             * the JAXB stuff is in the boot classpath. Ah well.
             */

            Thread.currentThread().setContextClassLoader(cl);

            String stacktrace = (String) method.invoke(null, res.className(), env);

            Thread.currentThread().setContextClassLoader(currentCl);

            if (stacktrace != null) {
                throw new MigrationFailureException(stacktrace);
            }

            firePostMigration(migration);
        } catch (Exception ex) {
            Thread.currentThread().setContextClassLoader(currentCl);

            log.error("Failed to complete migration for migration-def " + pkg.def(), ex);
            fireMigrationFailure(migration, ex);
            throw ex;
        }
    }
}

From source file:org.apache.maven.plugin.checkstyle.exec.DefaultCheckstyleExecutor.java

public CheckstyleResults executeCheckstyle(CheckstyleExecutorRequest request)
        throws CheckstyleExecutorException, CheckstyleException {
    // Checkstyle will always use the context classloader in order
    // to load resources (dtds),
    // so we have to fix it
    // olamy this hack is not anymore needed in Maven 3.x
    ClassLoader checkstyleClassLoader = PackageNamesLoader.class.getClassLoader();
    Thread.currentThread().setContextClassLoader(checkstyleClassLoader);

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("executeCheckstyle start headerLocation : " + request.getHeaderLocation());
    }/*from www  . j a  v a 2  s.  co  m*/

    MavenProject project = request.getProject();

    configureResourceLocator(locator, request, null);

    configureResourceLocator(licenseLocator, request, request.getLicenseArtifacts());

    // Config is less critical than License, locator can still be used.
    // configureResourceLocator( configurationLocator, request, request.getConfigurationArtifacts() );

    List<File> files;
    try {
        files = getFilesToProcess(request);
    } catch (IOException e) {
        throw new CheckstyleExecutorException("Error getting files to process", e);
    }

    final String suppressionsFilePath = getSuppressionsFilePath(request);
    FilterSet filterSet = getSuppressionsFilterSet(suppressionsFilePath);

    Checker checker = new Checker();

    // setup classloader, needed to avoid "Unable to get class information for ..." errors
    List<String> classPathStrings = new ArrayList<String>();
    List<String> outputDirectories = new ArrayList<String>();

    // stand-alone
    Collection<File> sourceDirectories = null;
    Collection<File> testSourceDirectories = request.getTestSourceDirectories();

    // aggregator
    Map<MavenProject, Collection<File>> sourceDirectoriesByProject = new HashMap<MavenProject, Collection<File>>();
    Map<MavenProject, Collection<File>> testSourceDirectoriesByProject = new HashMap<MavenProject, Collection<File>>();

    if (request.isAggregate()) {
        for (MavenProject childProject : request.getReactorProjects()) {
            sourceDirectories = new ArrayList<File>(childProject.getCompileSourceRoots().size());
            List<String> compileSourceRoots = childProject.getCompileSourceRoots();
            for (String compileSourceRoot : compileSourceRoots) {
                sourceDirectories.add(new File(compileSourceRoot));
            }
            sourceDirectoriesByProject.put(childProject, sourceDirectories);

            testSourceDirectories = new ArrayList<File>(childProject.getTestCompileSourceRoots().size());
            List<String> testCompileSourceRoots = childProject.getTestCompileSourceRoots();
            for (String testCompileSourceRoot : testCompileSourceRoots) {
                testSourceDirectories.add(new File(testCompileSourceRoot));
            }
            testSourceDirectoriesByProject.put(childProject, testSourceDirectories);

            prepareCheckstylePaths(request, childProject, classPathStrings, outputDirectories,
                    sourceDirectories, testSourceDirectories);
        }
    } else {
        sourceDirectories = request.getSourceDirectories();
        prepareCheckstylePaths(request, project, classPathStrings, outputDirectories, sourceDirectories,
                testSourceDirectories);
    }

    final List<URL> urls = new ArrayList<URL>(classPathStrings.size());

    for (String path : classPathStrings) {
        try {
            urls.add(new File(path).toURL());
        } catch (MalformedURLException e) {
            throw new CheckstyleExecutorException(e.getMessage(), e);
        }
    }

    for (String outputDirectoryString : outputDirectories) {
        try {
            if (outputDirectoryString != null) {
                File outputDirectoryFile = new File(outputDirectoryString);
                if (outputDirectoryFile.exists()) {
                    URL outputDirectoryUrl = outputDirectoryFile.toURL();
                    getLogger().debug("Adding the outputDirectory " + outputDirectoryUrl.toString()
                            + " to the Checkstyle class path");
                    urls.add(outputDirectoryUrl);
                }
            }
        } catch (MalformedURLException e) {
            throw new CheckstyleExecutorException(e.getMessage(), e);
        }
    }

    URLClassLoader projectClassLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
        public URLClassLoader run() {
            return new URLClassLoader(urls.toArray(new URL[urls.size()]), null);
        }
    });

    checker.setClassloader(projectClassLoader);

    checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());

    if (filterSet != null) {
        checker.addFilter(filterSet);
    }
    Configuration configuration = getConfiguration(request);
    checker.configure(configuration);

    AuditListener listener = request.getListener();

    if (listener != null) {
        checker.addListener(listener);
    }

    if (request.isConsoleOutput()) {
        checker.addListener(request.getConsoleListener());
    }

    CheckstyleCheckerListener checkerListener = new CheckstyleCheckerListener(configuration);
    if (request.isAggregate()) {
        for (MavenProject childProject : request.getReactorProjects()) {
            sourceDirectories = sourceDirectoriesByProject.get(childProject);
            testSourceDirectories = testSourceDirectoriesByProject.get(childProject);
            addSourceDirectory(checkerListener, sourceDirectories, testSourceDirectories,
                    childProject.getResources(), request);
        }
    } else {
        addSourceDirectory(checkerListener, sourceDirectories, testSourceDirectories, request.getResources(),
                request);
    }

    checker.addListener(checkerListener);

    int nbErrors = checker.process(files);

    checker.destroy();

    if (projectClassLoader instanceof Closeable) {
        try {
            ((Closeable) projectClassLoader).close();
        } catch (IOException ex) {
            // Nothing we can do - and not detrimental to the build (save running out of file handles).
            getLogger().info("Failed to close custom Classloader - this indicated a bug in the code.", ex);
        }
    }

    if (request.getStringOutputStream() != null) {
        String message = request.getStringOutputStream().toString().trim();

        if (message.length() > 0) {
            getLogger().info(message);
        }
    }

    if (nbErrors > 0) {
        String message = "There are " + nbErrors + " checkstyle errors.";

        if (request.isFailsOnError()) {
            // TODO: should be a failure, not an error. Report is not meant to
            // throw an exception here (so site would
            // work regardless of config), but should record this information
            throw new CheckstyleExecutorException(message);
        } else {
            getLogger().info(message);
        }
    }

    return checkerListener.getResults();
}

From source file:com.photon.phresco.util.PhrescoDynamicLoader.java

private URLClassLoader getURLClassLoader() throws PhrescoException, URISyntaxException {
    List<Artifact> artifacts = new ArrayList<Artifact>();
    for (ArtifactGroup plugin : plugins) {
        List<ArtifactInfo> versions = plugin.getVersions();
        for (ArtifactInfo artifactInfo : versions) {
            Artifact artifact = createArtifact(plugin.getGroupId(), plugin.getArtifactId(), "jar",
                    artifactInfo.getVersion());
            artifacts.add(artifact);/*from   w  w  w  . ja v  a 2s .co  m*/
        }
    }

    URL artifactURL;
    try {
        artifactURL = MavenArtifactResolver.resolveSingleArtifact(repoInfo.getGroupRepoURL(),
                repoInfo.getRepoUserName(), repoInfo.getRepoPassword(), artifacts);
    } catch (Exception e) {
        e.printStackTrace();
        throw new PhrescoException(e);
    }
    ClassLoader clsLoader = Thread.currentThread().getContextClassLoader();
    if (clsLoader == null) {
        clsLoader = this.getClass().getClassLoader();
    }
    URLClassLoader classLoader = new URLClassLoader(new URL[] { artifactURL }, clsLoader);
    return classLoader;
}

From source file:org.mitre.ccv.mapred.CalculateCompositionVectors.java

@Override
public int run(String[] args) throws Exception {
    JobConf conf = new JobConf(getConf());
    int start = CalculateKmerCounts.DEFAULT_START;
    int end = CalculateKmerCounts.DEFAULT_END;
    boolean cleanLogs = false;

    // @TODO: use commons getopts
    List<String> other_args = new ArrayList<String>();
    for (int i = 0; i < args.length; ++i) {
        try {/*ww w  .j  av a2 s. c  o  m*/
            if ("-m".equals(args[i])) {
                conf.setNumMapTasks(Integer.parseInt(args[++i]));
            } else if ("-r".equals(args[i])) {
                conf.setNumReduceTasks(Integer.parseInt(args[++i]));
            } else if ("-s".equals(args[i])) {
                start = Integer.parseInt(args[++i]);
            } else if ("-e".equals(args[i])) {
                end = Integer.parseInt(args[++i]);
            } else if ("-c".equals(args[i])) {
                cleanLogs = true;
            } else if ("-libjars".equals(args[i])) {
                conf.set("tmpjars", FileUtils.validateFiles(args[++i], conf));

                URL[] libjars = FileUtils.getLibJars(conf);
                if (libjars != null && libjars.length > 0) {
                    // Add libjars to client/tasks classpath
                    conf.setClassLoader(new URLClassLoader(libjars, conf.getClassLoader()));
                    // Adds libjars to our classpath
                    Thread.currentThread().setContextClassLoader(
                            new URLClassLoader(libjars, Thread.currentThread().getContextClassLoader()));
                }
            } else {
                other_args.add(args[i]);
            }
        } catch (NumberFormatException except) {
            System.out.println("ERROR: Integer expected instead of " + args[i]);
            return printUsage();
        } catch (ArrayIndexOutOfBoundsException except) {
            System.out.println("ERROR: Required parameter missing from " + args[i - 1]);
            return printUsage();
        }
    }
    // Make sure there are exactly 2 parameters left.
    if (other_args.size() != 2) {
        System.out.println("ERROR: Wrong number of parameters: " + other_args.size() + " instead of 2.");

        return printUsage();
    }
    return initJob(conf, start, end, other_args.get(0), other_args.get(1), cleanLogs);
}

From source file:org.broadleafcommerce.common.extensibility.InstrumentationRuntimeFactory.java

private static Class<?> loadVMClass(File toolsJar) {
    try {//from w w w.  jav  a2s  .c o m
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        String cls = SUN_VM_CLASS;
        if (isIBM) {
            cls = IBM_VM_CLASS;
        } else {
            loader = new URLClassLoader(new URL[] { toolsJar.toURI().toURL() }, loader);
        }
        return loader.loadClass(cls);
    } catch (Exception e) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Failed to load the virtual machine class", e);
        }
    }
    return null;
}

From source file:org.b3log.latke.plugin.PluginManager.java

/**
 * Loads a plugin by the specified plugin directory and put it into the 
 * specified holder./*  ww w .  j  a v  a2  s.  c om*/
 * 
 * @param pluginDir the specified plugin directory
 * @param holder the specified holder
 * @return loaded plugin
 * @throws Exception exception
 */
private AbstractPlugin load(final File pluginDir, final HashMap<String, HashSet<AbstractPlugin>> holder)
        throws Exception {
    final Properties props = new Properties();

    props.load(new FileInputStream(pluginDir.getPath() + File.separator + "plugin.properties"));

    final File defaultClassesFileDir = new File(pluginDir.getPath() + File.separator + "classes");
    final URL defaultClassesFileDirURL = defaultClassesFileDir.toURI().toURL();

    final String webRoot = StringUtils.substringBeforeLast(AbstractServletListener.getWebRoot(),
            File.separator);
    final String classesFileDirPath = webRoot + props.getProperty("classesDirPath");
    final File classesFileDir = new File(classesFileDirPath);
    final URL classesFileDirURL = classesFileDir.toURI().toURL();

    final URLClassLoader classLoader = new URLClassLoader(
            new URL[] { defaultClassesFileDirURL, classesFileDirURL }, PluginManager.class.getClassLoader());

    classLoaders.add(classLoader);

    String pluginClassName = props.getProperty(Plugin.PLUGIN_CLASS);

    if (StringUtils.isBlank(pluginClassName)) {
        pluginClassName = NotInteractivePlugin.class.getName();
    }

    final String rendererId = props.getProperty(Plugin.PLUGIN_RENDERER_ID);

    if (StringUtils.isBlank(rendererId)) {
        LOGGER.log(Level.WARNING, "no renderer defined by this plugin[" + pluginDir.getName()
                + "]this plugin will be ignore!");
        return null;
    }

    final Class<?> pluginClass = classLoader.loadClass(pluginClassName);

    LOGGER.log(Level.FINEST, "Loading plugin class[name={0}]", pluginClassName);
    final AbstractPlugin ret = (AbstractPlugin) pluginClass.newInstance();

    ret.setRendererId(rendererId);

    setPluginProps(pluginDir, ret, props);

    registerEventListeners(props, classLoader, ret);

    register(ret, holder);

    ret.changeStatus();

    return ret;
}

From source file:org.ng200.openolympus.services.TestingService.java

private void checkVerdict(final Verdict verdict, final SolutionJudge judge, final List<Path> testFiles,
        final BigDecimal maximumScore, final Properties properties) throws ExecutionException {
    if (this.dataProvider == null) {
        throw new IllegalStateException("Shared data provider is null!");
    }/*  w ww  .  j a v a 2  s  . c  o m*/

    final Lock lock = verdict.getSolution().getTask().readLock();
    lock.lock();

    try {
        TestingService.logger.info("Scheduling verdict {} for testing.", verdict.getId());

        final JPPFJob job = new JPPFJob();
        job.setDataProvider(this.dataProvider);

        job.setName("Check verdict " + verdict.getId());

        final int priority = (int) ((verdict.isViewableWhenContestRunning() ? (Integer.MAX_VALUE / 2) : 0)
                - verdict.getId());
        job.getSLA().setMaxNodes(1);
        job.getSLA().setPriority(priority);
        job.getSLA().setDispatchExpirationSchedule(new JPPFSchedule(60000L));
        job.getSLA().setMaxDispatchExpirations(3);

        TaskContainer taskContainer = taskContainerCache
                .getTaskContainerForTask(verdict.getSolution().getTask());

        Thread.currentThread().setContextClassLoader(
                new URLClassLoader(taskContainer.getClassLoaderURLs().toArray(new URL[0]),
                        Thread.currentThread().getContextClassLoader()));

        job.add(new JacksonSerializationDelegatingTask<>(
                new VerdictCheckingTask(judge, testFiles, maximumScore, properties),
                taskContainer.getClassLoaderURLs()));

        job.setBlocking(true);

        jppfClient.registerClassLoader(taskContainer.getClassLoader(), job.getUuid());
        this.jppfClient.submitJob(job);
        @SuppressWarnings("unchecked")
        final org.jppf.node.protocol.Task<String> task = (org.jppf.node.protocol.Task<String>) job
                .awaitResults().get(0);

        if (task.getThrowable() != null) {
            throw task.getThrowable();
        }

        ObjectMapper objectMapper = JacksonSerializationFactory.createObjectMapper();

        final JsonTaskExecutionResult<Pair<SolutionJudge, SolutionResult>> checkingResult = ((JacksonSerializationDelegatingTask<Pair<SolutionJudge, SolutionResult>, VerdictCheckingTask>) job
                .awaitResults().get(0)).getResultOrThrowable();

        if (checkingResult.getError() != null) {
            throw checkingResult.getError();
        }

        final SolutionResult result = checkingResult.getResult().getSecond();

        verdict.setScore(result.getScore());
        verdict.setMemoryPeak(result.getMemoryPeak());
        verdict.setCpuTime(Duration.ofMillis(result.getCpuTime()));
        verdict.setRealTime(Duration.ofMillis(result.getRealTime()));

        verdict.setStatus(result.getResult());
        switch (result.getResult()) {
        case OK:
        case TIME_LIMIT:
        case MEMORY_LIMIT:
        case OUTPUT_LIMIT:
        case PRESENTATION_ERROR:
        case WRONG_ANSWER:
        case RUNTIME_ERROR:
            break;
        case INTERNAL_ERROR:
            result.getErrorMessages()
                    .forEach((stage, message) -> this.internalErrors.put(this.internalErrorCounter++,
                            new Pair<String, String>(verdict.getSolution().getTask().getName(), message)));
            break;
        case SECURITY_VIOLATION:
            verdict.setUnauthorisedSyscall(result.getUnauthorisedSyscall());
            break;
        case COMPILE_ERROR:
            final String message = result.getErrorMessages().values().stream()
                    .collect(Collectors.joining("\n"));
            verdict.setAdditionalInformation(
                    HtmlUtils.htmlEscape(message.substring(0, Math.min(128, message.length()))));
            break;
        case WAITING:
            throw new IllegalStateException("Judge returned result \"waiting\".");
        }

    } catch (final Throwable throwable) {
        verdict.setStatus(SolutionResult.Result.INTERNAL_ERROR);
        throw new RuntimeException("Couldn't run solution: ", throwable);
    } finally {
        lock.unlock();

        verdict.setTested(true);
        if (verdict.getStatus() == SolutionResult.Result.WAITING) {
            verdict.setStatus(SolutionResult.Result.INTERNAL_ERROR);
            TestingService.logger.error(
                    "Judge for task {} did not set the result status to an acceptable value: got WAITING instead.",
                    verdict.getSolution().getTask().getId());
        }
        this.solutionService.saveVerdict(verdict);
    }
}

From source file:org.overlord.sramp.shell.ShellCommandFactory.java

/**
 * Discover any contributed commands, both on the classpath and registered
 * in the .sramp/commands.ini file in the user's home directory.
 *//*from ww  w.j  a  v a  2s . c o m*/
private void discoverContributedCommands() {
    List<ClassLoader> commandClassloaders = new ArrayList<ClassLoader>();
    commandClassloaders.add(Thread.currentThread().getContextClassLoader());

    // Register commands listed in the user's commands.ini config file
    String userHome = System.getProperty("user.home", "/"); //$NON-NLS-1$ //$NON-NLS-2$
    String commandsDirName = System.getProperty("s-ramp.shell.commandsDir", //$NON-NLS-1$
            userHome + "/.s-ramp/commands"); //$NON-NLS-1$
    File commandsDir = new File(commandsDirName);
    if (!commandsDir.exists()) {
        commandsDir.mkdirs();
    }
    if (commandsDir.isDirectory()) {
        try {
            Collection<File> jarFiles = FileUtils.listFiles(commandsDir, new String[] { "jar" }, false); //$NON-NLS-1$
            List<URL> jarURLs = new ArrayList<URL>(jarFiles.size());
            for (File jarFile : jarFiles) {
                jarURLs.add(jarFile.toURI().toURL());
            }
            URL[] urls = jarURLs.toArray(new URL[jarURLs.size()]);
            ClassLoader extraCommandsCL = new URLClassLoader(urls,
                    Thread.currentThread().getContextClassLoader());
            commandClassloaders.add(extraCommandsCL);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Now that we have identified all ClassLoaders to check for commands, iterate
    // through them all and use the Java ServiceLoader mechanism to actually
    // load the commands.
    for (ClassLoader classLoader : commandClassloaders) {
        for (ShellCommandProvider provider : ServiceLoader.load(ShellCommandProvider.class, classLoader)) {
            Map<String, Class<? extends ShellCommand>> commands = provider.provideCommands();
            for (Map.Entry<String, Class<? extends ShellCommand>> entry : commands.entrySet()) {
                QName qualifiedCmdName = new QName(provider.getNamespace(), entry.getKey());
                registry.put(qualifiedCmdName, entry.getValue());
            }
        }
    }
}