/** Executes the task. */ public void execute() throws BuildException { checkParameters(); reportFilesMap = new HashMap<String, String>(); AntClassLoader classLoader = null; if (classpath != null) { jasperReportsContext.setProperty( JRCompiler.COMPILER_CLASSPATH, String.valueOf(classpath)); // FIXMECONTEXT is this needed? what about class loader below/ ClassLoader parentClassLoader = getClass().getClassLoader(); classLoader = new AntClassLoader(parentClassLoader, getProject(), classpath, true); classLoader.setThreadContextLoader(); } try { /* */ scanSrc(); /* */ decompile(); } finally { if (classLoader != null) { classLoader.resetThreadContextLoader(); } } }
/** * Initializes default class loader. It inherits from classloader, which was used to load this * task, therefore build-in classes and resources are loaded automatically. * * <p>Notice: task's classpath has priority over default classpath, therefore we are able to * easily override resources (templates) */ protected void initClassloader() { // NOTICE: we should use the same classloader, which was used to load this task // otherwise we won't be able to cast instances // (that were loaded via different class loaders) // we are introducting workaround, // that tries to add classpath for current task to original class loader // and stores original classpath // after the task is executed, classpath is restored ClassLoader classLoader = getClass().getClassLoader(); if (classLoader instanceof AntClassLoader) { // add defined classpath AntClassLoader antClassLoader = (AntClassLoader) classLoader; antClassLoader.setParentFirst(false); antClassLoader.setProject(getProject()); savedClasspath = antClassLoader.getClasspath(); Path cp = getClasspath(); // add defined classpath to original path cp.add(new Path(getProject(), savedClasspath)); antClassLoader.setClassPath(cp); } else { // create new class loader classLoader = new AntClassLoader(getClass().getClassLoader(), getProject(), getClasspath(), false); } // set this class loader as new class loader for whole thread // ContextClassLoader is used in StringTemplate's PathGroupLoader and other classes Thread.currentThread().setContextClassLoader(classLoader); }
/** Restores default class loader. */ protected void restoreClassloader() { ClassLoader classLoader = getClass().getClassLoader(); if (classLoader instanceof AntClassLoader && savedClasspath != null) { AntClassLoader antClassLoader = (AntClassLoader) classLoader; antClassLoader.setClassPath(new Path(getProject(), savedClasspath)); savedClasspath = null; } }
protected GroovyClassLoader buildClassLoaderFor() { // GROOVY-5044 if (!fork && !getIncludeantruntime()) { throw new IllegalArgumentException( "The includeAntRuntime=false option is not compatible with fork=false"); } ClassLoader parent = getIncludeantruntime() ? getClass().getClassLoader() : new AntClassLoader( new RootLoader(EMPTY_URL_ARRAY, null), getProject(), getClasspath()); if (parent instanceof AntClassLoader) { AntClassLoader antLoader = (AntClassLoader) parent; String[] pathElm = antLoader.getClasspath().split(File.pathSeparator); List<String> classpath = configuration.getClasspath(); /* * Iterate over the classpath provided to groovyc, and add any missing path * entries to the AntClassLoader. This is a workaround, since for some reason * 'directory' classpath entries were not added to the AntClassLoader' classpath. */ for (String cpEntry : classpath) { boolean found = false; for (String path : pathElm) { if (cpEntry.equals(path)) { found = true; break; } } /* * fix for GROOVY-2284 * seems like AntClassLoader doesn't check if the file * may not exist in the classpath yet */ if (!found && new File(cpEntry).exists()) { try { antLoader.addPathElement(cpEntry); } catch (BuildException e) { log.warn("The classpath entry " + cpEntry + " is not a valid Java resource"); } } } } GroovyClassLoader loader = new GroovyClassLoader(parent, configuration); if (!forceLookupUnnamedFiles) { // in normal case we don't need to do script lookups loader.setResourceLoader( new GroovyResourceLoader() { public URL loadGroovySource(String filename) throws MalformedURLException { return null; } }); } return loader; }
/** * 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() { AntClassLoader l = null; try { l = getProject().createClassLoader(commandline.getClasspath()); l.loadClass("antlr.Version"); return true; } catch (ClassNotFoundException e) { return false; } finally { if (l != null) { l.cleanup(); } } }
@Override public URL[] getURLs() { Set<URL> urls = new HashSet<URL>(); // convert urls from antLoader String[] paths = antLoader.getClasspath().split(new String(new char[] {File.pathSeparatorChar})); if (paths != null) { for (String p : paths) { File f = new File(p); try { urls.add(f.toURI().toURL()); } catch (Exception e) { LOG.ignore(e); } } } // add in any that may have been added to us as a URL directly URL[] ourURLS = super.getURLs(); if (ourURLS != null) { for (URL u : ourURLS) urls.add(u); } return urls.toArray(new URL[urls.size()]); }
private void prepare() { String jdkPath = RegistryHandler.getJDKPath(); if (!isToolsJarInWebSDK()) { copyJdkTools(jdkPath); } File tools_jar = new File(jdkPath + "\\lib\\tools.jar"); current.addPathComponent(tools_jar); try { fileHandler.deleteFolder(new File(tempAndroidProjectPath)); copyAssets(); copyProject(); changeIcon(); changePackage(); changeName(); createBuildProperties(); targetId = RegistryHandler.getAndroidTarget() + 1; // Update R.java and some properties. cmdHelper.updateAndroidProject(targetId, tempAndroidProjectPath, getNameForFile()); } catch (IOException ex) { java.util.logging.Logger.getLogger(AndroidApplicationModel.class.getName()) .log(Level.SEVERE, null, ex); } }
/** * Load named class and test whether it can be rmic'ed * * @param classname the name of the class to be tested * @return true if the class can be rmic'ed */ public boolean isValidRmiRemote(String classname) { try { Class testClass = loader.loadClass(classname); // One cannot RMIC an interface for "classic" RMI (JRMP) if (testClass.isInterface() && !iiop && !idl) { return false; } return isValidRmiRemote(testClass); } catch (ClassNotFoundException e) { log(ERROR_UNABLE_TO_VERIFY_CLASS + classname + ERROR_NOT_FOUND, Project.MSG_WARN); } catch (NoClassDefFoundError e) { log(ERROR_UNABLE_TO_VERIFY_CLASS + classname + ERROR_NOT_DEFINED, Project.MSG_WARN); } catch (Throwable t) { log( ERROR_UNABLE_TO_VERIFY_CLASS + classname + ERROR_LOADING_CAUSED_EXCEPTION + t.getMessage(), Project.MSG_WARN); } // we only get here if an exception has been thrown return false; }
protected IDemoCase createDemo() throws BuildException { try { Class demoClass = null; if (classLoader == null) { demoClass = Class.forName(demoId.getClassName()); } else { demoClass = classLoader.loadClass(demoId.getClassName()); AntClassLoader.initializeClass(demoClass); } // Method suiteMethod = null; // try { // // check if there is a suite method // suiteMethod = demoClass.getMethod("suite", new Class[0]); // } catch (Exception e) { // // no appropriate suite method found. We don't report any // // error here since it might be perfectly normal. We don't // // know exactly what is the cause, but we're doing exactly // // the same as JUnit TestRunner do. We swallow the exceptions. // } // if (suiteMethod != null){ // // if there is a suite method available, then try // // to extract the suite from it. If there is an error // // here it will be caught below and reported. // suite = (Test) suiteMethod.invoke(null, new Class[0]); // } else { // // try to extract a test suite automatically // // this will generate warnings if the class is no suitable Test // suite = new TestSuite(demoClass); // } // return DemoUtilities.createDemoCase(demoId.getMethodName(), demoClass); } catch (Exception exception) { throw new BuildException("unable to create demo (" + exception.getMessage() + ")", exception); } }
public Runnable createTargetInstance(Target target, Properties localProperties, Logger logger) { // System.out.println("DefaultProjectModel.createTargetInstance"); AntClassLoader loader = null; DefaultResources resources; try { org.apache.tools.ant.types.Path classPath = toAntPath(resolvePathGroup(target, "classpath")); // Allow additional classes to added to the plugin classpath. This is primarily designed to // allow the additional of instrumented testing classes and libraries for code coverage of // integration // tests with Cobertura String key = "quokka.classpath." + target.getPlugin().getArtifact().getId().getGroup(); if (log.isDebugEnabled()) { log.debug("Searching for additional classpath with key: " + key); } String additionalPath = System.getProperty(key); if ((additionalPath != null) && !additionalPath.trim().equals("")) { org.apache.tools.ant.types.Path existing = classPath; classPath = new org.apache.tools.ant.types.Path(antProject, additionalPath); log.verbose("Prefixing classpath with: " + classPath); classPath.append(existing); // Make sure additions override existing } if ("true".equals(antProject.getProperty("quokka.project.debugclassloaders"))) { loader = new QuokkaLoader(target, antProject.getClass().getClassLoader(), antProject, classPath); } else { loader = antProject.createClassLoader(classPath); } loader.setParent(antProject.getCoreLoader()); loader.setParentFirst(true); loader.setIsolated(false); loader.setThreadContextLoader(); // Initialise this plugin Plugin plugin = target.getPlugin(); loader.forceLoadClass(plugin.getClassName()); Class pluginClass = Class.forName(plugin.getClassName(), true, loader); ws.quokka.core.plugin_spi.Plugin actualPlugin = (ws.quokka.core.plugin_spi.Plugin) pluginClass.newInstance(); if (actualPlugin instanceof MetadataAware) { ((MetadataAware) actualPlugin).setMetadata(getMetadata()); } if (actualPlugin instanceof ResourcesAware) { resources = new DefaultResources(this, target, antProject, logger); ((ResourcesAware) actualPlugin).setResources(resources); } if (actualPlugin instanceof RepositoryAware) { ((RepositoryAware) actualPlugin).setRepository(getRepository()); } if (actualPlugin instanceof RepositoryFactoryAware) { ((RepositoryFactoryAware) actualPlugin) .setRepositoryFactory( (RepositoryFactory) antProject.getReference(ProjectHelper.REPOSITORY_FACTORY)); } if (actualPlugin instanceof ResolverAware) { ((ResolverAware) actualPlugin).setResolver(pathResolver); } if (actualPlugin instanceof ModelFactoryAware) { ((ModelFactoryAware) actualPlugin).setModelFactory(getModelFactory()); } actualPlugin.initialise(); return actualPlugin.getTarget( (target.getTemplateName() != null) ? target.getTemplateName() : target.getName()); } catch (Exception e) { throw new BuildException(e); } finally { if (loader != null) { loader.resetThreadContextLoader(); loader.cleanup(); } } }
public void execute() { AntClassLoader loader; MergeFileSystemAndClassPathXMLApplicationContext mergeContext; try { ConfigurationOnlyState state = new ConfigurationOnlyState(); state.setConfigurationOnly(true); ConfigurationOnlyState.setState(state); loader = getProject().createClassLoader(classPath); ClassLoader classLoader = this.getClass().getClassLoader(); loader.setParent( classLoader); // if this is not set, classes from the taskdef cannot be found - which is // crucial for e.g. annotations. loader.setThreadContextLoader(); // launch the service merge application context to get the entity configuration for the entire // framework String[] contexts = StandardConfigLocations.retrieveAll(StandardConfigLocations.TESTCONTEXTTYPE); String[] otherContexts = new String[classPathApplicationContexts.size()]; for (int j = 0; j < otherContexts.length; j++) { otherContexts[j] = classPathApplicationContexts.get(j).getPath(); } contexts = (String[]) ArrayUtils.addAll(contexts, otherContexts); String[] fileSystemItems = new String[fileSystemApplicationContexts.size()]; for (int j = 0; j < fileSystemItems.length; j++) { fileSystemItems[j] = fileSystemApplicationContexts.get(j).getPath(); } mergeContext = new MergeFileSystemAndClassPathXMLApplicationContext(contexts, fileSystemItems); } catch (Exception e) { throw new BuildException(e, getLocation()); } finally { ConfigurationOnlyState.setState(null); } int count = 1; ExporterTask generatorTask = null; try { for (Object configuration : configurationTasks) { JPAConfigurationTask configurationTask = (JPAConfigurationTask) configuration; log("Executing Hibernate Tool with a " + configurationTask.getDescription()); @SuppressWarnings("rawtypes") Iterator iterator = generators.iterator(); while (iterator.hasNext()) { generatorTask = (ExporterTask) iterator.next(); log(count++ + ". task: " + generatorTask.getName()); generatorTask.setOutputFileName( configurationTask.getDialect() + "_" + configurationTask.getPersistenceUnit() + ".sql"); generatorTask.setDestdir(destDir); generatorTask.setConfiguration(configurationTask.createConfiguration(mergeContext)); generatorTask.execute(); } } } catch (RuntimeException re) { reportException(re, count, generatorTask); } finally { if (loader != null) { loader.resetThreadContextLoader(); loader.cleanup(); } } try { if (combinePersistenceUnits) { ArrayList<File> combine = new ArrayList<File>(); for (Object configuration : configurationTasks) { JPAConfigurationTask configurationTask = (JPAConfigurationTask) configuration; File[] sqlFiles = destDir.listFiles(new SqlFileFilter()); for (File file : sqlFiles) { if (file.getName().startsWith(configurationTask.getDialect())) { combine.add(file); } } combineFiles(combine); combine.clear(); } } if (refineFileNames) { File[] sqlFiles = destDir.listFiles(new SqlFileFilter()); for (File file : sqlFiles) { String filename = file.getName(); String[] starters = {"org.hibernate.dialect.", "org.broadleafcommerce.profile.util.sql."}; for (String starter : starters) { if (filename.startsWith(starter)) { String newFileName = filename.substring(starter.length(), filename.length()); file.renameTo(new File(destDir, newFileName)); } } } } } catch (Exception e) { throw new BuildException(e, getLocation()); } }
/** * Determine the dependencies between classes. Class dependencies are determined by examining the * class references in a class file to other classes. * * <p>This method sets up the following fields * * <ul> * <li>affectedClassMap - the list of classes each class affects * <li>classFileInfoMap - information about each class * <li>classpathDependencies - the list of jars and classes from the classpath that each class * depends upon. * </ul> * * If required, the dependencies are written to the cache. * * @exception IOException if either the dependencies cache or the class files cannot be read or * written */ private void determineDependencies() throws IOException { affectedClassMap = new Hashtable(); classFileInfoMap = new Hashtable(); boolean cacheDirty = false; Hashtable dependencyMap = new Hashtable(); File cacheFile = null; boolean cacheFileExists = true; long cacheLastModified = Long.MAX_VALUE; // read the dependency cache from the disk if (cache != null) { cacheFile = new File(cache, CACHE_FILE_NAME); cacheFileExists = cacheFile.exists(); cacheLastModified = cacheFile.lastModified(); if (cacheFileExists) { dependencyMap = readCachedDependencies(cacheFile); } } Enumeration classfileEnum = getClassFiles(destPath).elements(); while (classfileEnum.hasMoreElements()) { ClassFileInfo info = (ClassFileInfo) classfileEnum.nextElement(); log("Adding class info for " + info.className, Project.MSG_DEBUG); classFileInfoMap.put(info.className, info); Vector dependencyList = null; if (cache != null) { // try to read the dependency info from the map if it is // not out of date if (cacheFileExists && cacheLastModified > info.absoluteFile.lastModified()) { // depFile exists and is newer than the class file // need to get dependency list from the map. dependencyList = (Vector) dependencyMap.get(info.className); } } if (dependencyList == null) { // not cached - so need to read directly from the class file DependencyAnalyzer analyzer = new AntAnalyzer(); analyzer.addRootClass(info.className); analyzer.addClassPath(destPath); analyzer.setClosure(false); dependencyList = new Vector(); Enumeration depEnum = analyzer.getClassDependencies(); while (depEnum.hasMoreElements()) { dependencyList.addElement(depEnum.nextElement()); } if (dependencyList != null) { cacheDirty = true; dependencyMap.put(info.className, dependencyList); } } // This class depends on each class in the dependency list. For each // one of those, add this class into their affected classes list Enumeration depEnum = dependencyList.elements(); while (depEnum.hasMoreElements()) { String dependentClass = (String) depEnum.nextElement(); Hashtable affectedClasses = (Hashtable) affectedClassMap.get(dependentClass); if (affectedClasses == null) { affectedClasses = new Hashtable(); affectedClassMap.put(dependentClass, affectedClasses); } affectedClasses.put(info.className, info); } } classpathDependencies = null; Path checkPath = getCheckClassPath(); if (checkPath != null) { // now determine which jars each class depends upon classpathDependencies = new Hashtable(); AntClassLoader loader = new AntClassLoader(getProject(), checkPath); Hashtable classpathFileCache = new Hashtable(); Object nullFileMarker = new Object(); for (Enumeration e = dependencyMap.keys(); e.hasMoreElements(); ) { String className = (String) e.nextElement(); Vector dependencyList = (Vector) dependencyMap.get(className); Hashtable dependencies = new Hashtable(); classpathDependencies.put(className, dependencies); Enumeration e2 = dependencyList.elements(); while (e2.hasMoreElements()) { String dependency = (String) e2.nextElement(); Object classpathFileObject = classpathFileCache.get(dependency); if (classpathFileObject == null) { classpathFileObject = nullFileMarker; if (!dependency.startsWith("java.") && !dependency.startsWith("javax.")) { URL classURL = loader.getResource(dependency.replace('.', '/') + ".class"); if (classURL != null) { if (classURL.getProtocol().equals("jar")) { String jarFilePath = classURL.getFile(); if (jarFilePath.startsWith("file:")) { int classMarker = jarFilePath.indexOf('!'); jarFilePath = jarFilePath.substring(5, classMarker); } classpathFileObject = new File(jarFilePath); } else if (classURL.getProtocol().equals("file")) { String classFilePath = classURL.getFile(); classpathFileObject = new File(classFilePath); } log( "Class " + className + " depends on " + classpathFileObject + " due to " + dependency, Project.MSG_DEBUG); } } classpathFileCache.put(dependency, classpathFileObject); } if (classpathFileObject != null && classpathFileObject != nullFileMarker) { // we need to add this jar to the list for this class. File jarFile = (File) classpathFileObject; dependencies.put(jarFile, jarFile); } } } } // write the dependency cache to the disk if (cache != null && cacheDirty) { writeCachedDependencies(dependencyMap); } }
/** * Cleans up resources. * * @since Ant 1.8.0 */ protected void cleanup() { if (loader != null) { loader.cleanup(); loader = null; } }