static void validateAgainstAUDTDs(InputSource input, final Path updaterJar, final Task task) throws IOException, SAXException { XMLUtil.parse(input, true, false, XMLUtil.rethrowHandler(), new EntityResolver() { ClassLoader loader = new AntClassLoader(task.getProject(), updaterJar); public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { String remote = "http://www.netbeans.org/dtds/"; if (systemId.startsWith(remote)) { String rsrc = "org/netbeans/updater/resources/" + systemId.substring(remote.length()); URL u = loader.getResource(rsrc); if (u != null) { return new InputSource(u.toString()); } else { task.log(rsrc + " not found in " + updaterJar, Project.MSG_WARN); } } return null; } }); }
@Test public void testClassloaderInRootModule() throws IOException { TestRootModuleChecker.reset(); CheckerStub.reset(); final CheckstyleAntTask antTask = getCheckstyleAntTask( "InputCheckstyleAntTaskConfigCustomCheckerRootModule.xml"); antTask.setFile(new File(getPath(VIOLATED_INPUT))); antTask.execute(); final ClassLoader classLoader = CheckerStub.getClassLoader(); assertTrue("Classloader is not set or has invalid type", classLoader instanceof AntClassLoader); }
/** * Tries to resolve the given classname into a compiler adapter. * Throws a fit if it can't. * * @param className The fully qualified classname to be created. * @param classloader Classloader with which to load the class * @throws BuildException This is the fit that is thrown if className * isn't an instance of JspCompilerAdapter. */ private static JspCompilerAdapter resolveClassName(String className, AntClassLoader classloader) throws BuildException { try { Class<? extends JspCompilerAdapter> c = classloader.findClass(className).asSubclass(JspCompilerAdapter.class); return c.newInstance(); } catch (ClassNotFoundException cnfe) { throw new BuildException(className + " can\'t be found.", cnfe); } catch (ClassCastException cce) { throw new BuildException(className + " isn\'t the classname of " + "a compiler adapter.", cce); } catch (Throwable t) { // for all other possibilities throw new BuildException(className + " caused an interesting " + "exception.", t); } }
Class loadClass(String className) throws ClassNotFoundException { if (_classpath != null) { log("Loading " + className + " using AntClassLoader with classpath " + _classpath, Project.MSG_VERBOSE); AntClassLoader loader = new AntClassLoader(getProject(), _classpath); return loader.loadClass(className); } else { log("Loading " + className + " using system loader.", Project.MSG_VERBOSE); return Class.forName(className); } }
public void execute() throws BuildException { try { /* * This needs the ClassLoader we use to load the task * have all the dependancies set, hope that * is ok for now */ AntClassLoader cl = new AntClassLoader( getClass().getClassLoader(), getProject(), classpath == null ? createClasspath() : classpath, false); Thread.currentThread().setContextClassLoader(cl); Map commandLineOptions = this.fillOptionMap(); CommandLineOptionParser parser = new CommandLineOptionParser(commandLineOptions); new CodeGenerationEngine(parser).generate(); } catch (Throwable e) { throw new BuildException(e); } }
public void execute() throws BuildException { try { Map commandLineOptions = this.fillOptionMap(); ClassLoader conextClassLoader = Thread.currentThread().getContextClassLoader(); AntClassLoader cl = new AntClassLoader(getClass().getClassLoader(), getProject(), classpath == null ? createClasspath() : classpath, false); commandLineOptions.put(Java2WSDLConstants.CLASSPATH_OPTION, new Java2WSDLCommandLineOption(Java2WSDLConstants.CLASSPATH_OPTION, classpath.list())); Thread.currentThread().setContextClassLoader(cl); if (outputLocation != null) cl.addPathElement(outputLocation); new Java2WSDLCodegenEngine(commandLineOptions).generate(); Thread.currentThread().setContextClassLoader(conextClassLoader); } catch (Throwable e) { throw new BuildException(e); } }
private void doXJC() throws BuildException { ClassLoader old = Thread.currentThread().getContextClassLoader(); try { if (classpath != null) { for (String pathElement : classpath.list()) { try { options.classpaths.add(new File(pathElement).toURI().toURL()); } catch (MalformedURLException ex) { log("Classpath for XJC task not setup properly: " + pathElement); } } } // set the user-specified class loader so that XJC will use it. Thread.currentThread().setContextClassLoader(new AntClassLoader(getProject(),classpath)); _doXJC(); } finally { // restore the context class loader Thread.currentThread().setContextClassLoader(old); } }
/** * Sets the path for the parent-last ClassLoader, intended to be used for * {@link org.apache.hadoop.conf.Configuration Configuration}. * @param confpath The path to search for resources, classes, etc. before * parent ClassLoaders. */ public void setConf(String confpath) { confloader = AccessController.doPrivileged( new PrivilegedAction<AntClassLoader>() { @Override public AntClassLoader run() { return new AntClassLoader(getClass().getClassLoader(), false); } }); confloader.setProject(getProject()); if (null != confpath) confloader.addPathElement(confpath); }
/** * Sets the path for the parent-last ClassLoader, intended to be used for * {@link org.apache.hadoop.conf.Configuration Configuration}. * @param confpath The path to search for resources, classes, etc. before * parent ClassLoaders. */ public void setConf(String confpath) { confloader = new AntClassLoader(getClass().getClassLoader(), false); confloader.setProject(getProject()); if (null != confpath) confloader.addPathElement(confpath); }
private void doRun(List<String> args) throws Exception { AntClassLoader classLoader = new AntClassLoader( null, createRuntimeClasspath(), false ); try { classLoader.setThreadContextLoader(); log(classLoader.toString(), Project.MSG_DEBUG); AntTaskRunnerMonitor recorderMonitor = new AntTaskRunnerMonitor(); Object runnerInstance = createRunner( classLoader , new AntTaskRunnerLogger(this), recorderMonitor ); CommandLineRunnerMirror runner = DuckType.implement( CommandLineRunnerMirror.class, runnerInstance ); String[] arguments = new String[args.size()]; args.toArray(arguments); runner.run(arguments); log(String.format("Results: %s for %s specification(s)", recorderMonitor.getStatistics().toString(), recorderMonitor.getLocationCount()), Project.MSG_INFO); checkResults(recorderMonitor.hasException(), "Some greenpepper tests did not run"); checkResults(recorderMonitor.hasTestFailures(), "There were greenpepper tests failures"); } finally { classLoader.resetThreadContextLoader(); } }
protected String getCookCCPath () { ClassLoader cl = Task.class.getClassLoader (); if (cl instanceof AntClassLoader) { return ((AntClassLoader)cl).getClasspath (); } throw new RuntimeException ("Unable to determine the runtime path of CookCC."); }
public void execute() throws BuildException { if (taskClasspath==null || taskClasspath.size()==0) { throw new BuildException("no classpath given"); } Project project = getProject(); AntClassLoader loader = new AntClassLoader(makeRoot(),true); project.addReference(name,loader); }
/** * combines the various ways that could specify a ClassLoader and * potentially creates one that needs to be cleaned up when it is * no longer needed so that classes can get garbage collected. * * @return ClassLoaderWithFlag */ protected ClassLoaderWithFlag getClassLoader() { ClassLoader cl = null; if (loader != null) { cl = (ClassLoader) loader.getReferencedObject(); } boolean clNeedsCleanup = false; if (cl == null) { if (getClasspath() != null) { Path p = getClasspath().concatSystemClasspath("ignore"); if (parentFirst) { cl = getProject().createClassLoader(p); } else { cl = AntClassLoader.newAntClassLoader(getProject() .getCoreLoader(), getProject(), p, false); } clNeedsCleanup = loader == null; } else { cl = JavaResource.class.getClassLoader(); } if (loader != null && cl != null) { getProject().addReference(loader.getRefId(), cl); } } return new ClassLoaderWithFlag(cl, clNeedsCleanup); }
/** * Instantiates the identified custom selector class. */ public void selectorCreate() { if (classname != null && classname.length() > 0) { try { Class<?> c; if (classpath == null) { c = Class.forName(classname); } else { // Memory-Leak in line below AntClassLoader al = getProject().createClassLoader(classpath); c = Class.forName(classname, true, al); } dynselector = c.asSubclass(FileSelector.class).newInstance(); final Project p = getProject(); if (p != null) { p.setProjectReference(dynselector); } } catch (ClassNotFoundException cnfexcept) { setError("Selector " + classname + " not initialized, no such class"); } catch (InstantiationException iexcept) { setError("Selector " + classname + " not initialized, could not create class"); } catch (IllegalAccessException iaexcept) { setError("Selector " + classname + " not initialized, class not accessible"); } } else { setError("There is no classname specified"); } }
/** * Utility method to lookup a ResourceLocation in the classpath. * * @return An InputSource for reading the resource, or <code>null</code> * if the resource does not exist in the classpath or is not readable. */ private InputSource classpathLookup(ResourceLocation matchingEntry) { InputSource source = null; Path cp = classpath; if (cp != null) { cp = classpath.concatSystemClasspath("ignore"); } else { cp = (new Path(getProject())).concatSystemClasspath("last"); } AntClassLoader loader = getProject().createClassLoader(cp); // // for classpath lookup we ignore the base directory // InputStream is = loader.getResourceAsStream(matchingEntry.getLocation()); if (is != null) { source = new InputSource(is); URL entryURL = loader.getResource(matchingEntry.getLocation()); String sysid = entryURL.toExternalForm(); source.setSystemId(sysid); log("catalog entry matched a resource in the classpath: '" + sysid + "'", Project.MSG_DEBUG); } return source; }
/** * @since Ant 1.6.2 */ private boolean isTomcat5x() { try (AntClassLoader l = getProject().createClassLoader(getClasspath())) { l.loadClass("org.apache.jasper.tagplugins.jstl.If"); return true; } catch (ClassNotFoundException e) { return false; } }
/** * Check the path for multiple different versions of * ant. * @param cmd command to execute */ private void checkForkedPath(final CommandlineJava cmd) { if (forkedPathChecked) { return; } forkedPathChecked = true; if (!cmd.haveClasspath()) { return; } try (AntClassLoader loader = AntClassLoader.newAntClassLoader(null, getProject(), cmd.createClasspath(getProject()), true)) { final String projectResourceName = LoaderUtils.classNameToResource(Project.class.getName()); URL previous = null; try { for (final Enumeration<URL> e = loader.getResources(projectResourceName); e.hasMoreElements();) { final URL current = e.nextElement(); if (previous != null && !urlEquals(current, previous)) { log("WARNING: multiple versions of ant detected " + "in path for junit " + LINE_SEP + " " + previous + LINE_SEP + " and " + current, Project.MSG_WARN); return; } previous = current; } } catch (final Exception ex) { // Ignore exception } } }
/** * Checks is a junit is on given path. * @param path the {@link Path} to check * @return true when given {@link Path} contains junit * @since 1.9.8 */ private boolean hasJunit(final Path path) { try (AntClassLoader loader = AntClassLoader.newAntClassLoader( null, getProject(), path, true)) { try { loader.loadClass("junit.framework.Test"); return true; } catch (final Exception ex) { return false; } } }
/** {@inheritDoc}. */ @Override public JUnitTaskMirror.JUnitTestRunnerMirror newJUnitTestRunner(JUnitTest test, String[] methods, boolean haltOnError, boolean filterTrace, boolean haltOnFailure, boolean showOutput, boolean logTestListenerEvents, AntClassLoader classLoader) { return new JUnitTestRunner(test, methods, haltOnError, filterTrace, haltOnFailure, showOutput, logTestListenerEvents, classLoader); }
/** * Whether the antlr version is 2.7.2 (or higher). * * @return true if the version of Antlr present is 2.7.2 or later. * @since Ant 1.6 */ protected boolean is272() { try (AntClassLoader l = getProject().createClassLoader(commandline.getClasspath())) { l.loadClass("antlr.Version"); return true; } catch (ClassNotFoundException e) { return false; } }
/** * load properties from a resource in the current classpath * @param name name of resource to load */ protected void loadResource(String name) { Properties props = new Properties(); log("Resource Loading " + name, Project.MSG_VERBOSE); ClassLoader cL = null; boolean cleanup = false; if (classpath != null) { cleanup = true; cL = getProject().createClassLoader(classpath); } else { cL = this.getClass().getClassLoader(); } InputStream is = null; try { if (cL == null) { is = ClassLoader.getSystemResourceAsStream(name); } else { is = cL.getResourceAsStream(name); } if (is != null) { loadProperties(props, is, name.endsWith(".xml")); addProperties(props); } else { log("Unable to find resource " + name, Project.MSG_WARN); } } catch (IOException ex) { throw new BuildException(ex, getLocation()); } finally { FileUtils.close(is); if (cleanup && cL != null) { ((AntClassLoader) cL).cleanup(); } } }
/** * create a classloader for this definition * @return the classloader from the cpDelegate */ protected ClassLoader createLoader() { if (getAntlibClassLoader() != null && cpDelegate == null) { return getAntlibClassLoader(); } if (createdLoader == null) { createdLoader = getDelegate().getClassLoader(); // need to load Task via system classloader or the new // task we want to define will never be a Task but always // be wrapped into a TaskAdapter. ((AntClassLoader) createdLoader) .addSystemPackageRoot("org.apache.tools.ant"); } return createdLoader; }
/** * Assemble the reader * @return the assembled reader * @exception BuildException if an error occurs */ public ChainReader getAssembledReader() throws BuildException { if (primaryReader == null) { throw new BuildException("primaryReader must not be null."); } Reader instream = primaryReader; final List<AntClassLoader> classLoadersToCleanUp = new ArrayList<>(); final List<Object> finalFilters = filterChains.stream().map(FilterChain::getFilterReaders) .flatMap(Collection::stream).collect(Collectors.toList()); if (!finalFilters.isEmpty()) { boolean success = false; try { for (Object o : finalFilters) { if (o instanceof AntFilterReader) { instream = expandReader((AntFilterReader) o, instream, classLoadersToCleanUp); } else if (o instanceof ChainableReader) { setProjectOnObject(o); instream = ((ChainableReader) o).chain(instream); setProjectOnObject(instream); } } success = true; } finally { if (!(success || classLoadersToCleanUp.isEmpty())) { cleanUpClassLoaders(classLoadersToCleanUp); } } } return new ChainReader(instream, classLoadersToCleanUp); }
/** * {@inheritDoc} */ public void execute() throws BuildException { if (_commands.isEmpty()) { log("No sub tasks specified, so there is nothing to do.", Project.MSG_INFO); return; } ClassLoader sysClassLoader = Thread.currentThread().getContextClassLoader(); AntClassLoader newClassLoader = new AntClassLoader(getClass().getClassLoader(), true); // we're changing the thread classloader so that we can access resources // from the classpath used to load this task's class Thread.currentThread().setContextClassLoader(newClassLoader); try { MetadataManager manager = initOJB(); Database dbModel = readModel(); DescriptorRepository objModel = manager.getGlobalRepository(); if (dbModel == null) { throw new BuildException("No database model specified"); } for (Iterator it = _commands.iterator(); it.hasNext();) { Command cmd = (Command)it.next(); cmd.setPlatform(getPlatform()); cmd.execute(this, dbModel, objModel); } } finally { // rollback of our classloader change Thread.currentThread().setContextClassLoader(sysClassLoader); } }
@Override public void execute() throws BuildException { super.execute(); AntClassLoader loader = getProject().createClassLoader(classpath); loader.setParent(this.getClass().getClassLoader()); loader.setThreadContextLoader(); }
public AntResourceAccessor(final Project project, final Path classpath) { super(new ClassLoaderResourceAccessor( AccessController.doPrivileged(new PrivilegedAction<AntClassLoader>() { public AntClassLoader run() { return new AntClassLoader(project, classpath); } })), new ClassLoaderResourceAccessor( AccessController.doPrivileged(new PrivilegedAction<AntClassLoader>() { public AntClassLoader run() { return new AntClassLoader(project, new Path(project, ".")); } })) ); }
/** * {@inheritDoc} */ @Override @NotNull public AntClassLoader createClassLoader(@NotNull final Path path) { return createClassLoader(path, getProject()); }