static public void copyFile(File src, File obj) { final class AntCopy extends Copy { @SuppressWarnings("deprecation") public AntCopy() { project = new Project(); project.init(); taskType = "copy"; taskName = "copy"; target = new Target(); } } AntCopy ant = new AntCopy(); ant.setFile(src); ant.setTofile(obj); ant.execute(); }
private static void configureTask(Target target, AntTarget task, File baseDir, Transformer<? extends String, ? super String> taskNamer) { task.setTarget(target); task.setBaseDir(baseDir); final List<String> taskDependencyNames = getTaskDependencyNames(target, taskNamer); task.dependsOn(new AntTargetsTaskDependency(taskDependencyNames)); addDependencyOrdering(taskDependencyNames, task.getProject().getTasks()); }
public BasicAntBuilder() { // These are used to discard references to tasks so they can be garbage collected Field collectorField; try { nodeField = AntBuilder.class.getDeclaredField("lastCompletedNode"); nodeField.setAccessible(true); collectorField = AntBuilder.class.getDeclaredField("collectorTarget"); collectorField.setAccessible(true); Target target = (Target) collectorField.get(this); Field childrenField = Target.class.getDeclaredField("children"); childrenField.setAccessible(true); children = (List) childrenField.get(target); } catch (Exception e) { throw new RuntimeException(e); } getAntProject().addDataTypeDefinition("gradleFileResource", AntFileResource.class); getAntProject().addDataTypeDefinition("gradleBaseDirSelector", BaseDirSelector.class); }
public void testInstallAllTargetWithClusters() { InsertModuleAllTargets insert = new InsertModuleAllTargets(); insert.setProject(p); insert.execute(); Object obj = p.getTargets().get("all-java.source.queries"); assertNotNull("Target found", obj); Target t = (Target)obj; Set<String> s = depsToNames(t.getDependencies()); assertEquals("One dep: " + s, 1, s.size()); assertEquals("Just dep on init", "init", s.iterator().next()); int callTargets = 0; for (Task task : t.getTasks()) { if (task instanceof CallTarget) { callTargets++; } } assertEquals("One call target to build super cluster", 1, callTargets); }
public void testInstallAllTargetWithoutClusters() { InsertModuleAllTargets insert = new InsertModuleAllTargets(); insert.setProject(p); insert.setUseClusters(false); insert.execute(); Object obj = p.getTargets().get("all-java.source.queries"); assertNotNull("Target found", obj); Target t = (Target)obj; Set<String> s = depsToNames(t.getDependencies()); assertEquals("Three dependencies: " + s, 5, s.size()); assertTrue("on init", s.contains("init")); assertTrue("on all-openide.util", s.contains("all-openide.util")); assertTrue("on all-openide.util.lookup", s.contains("all-openide.util.lookup")); assertTrue("on all-api.annotations.common", s.contains("all-api.annotations.common")); assertTrue("on all-openide.dialogs", s.contains("all-openide.dialogs")); int callTargets = 0; for (Task task : t.getTasks()) { if (task instanceof CallTarget) { callTargets++; } } assertEquals("No call targes", 0, callTargets); }
/** * Execute all tasks. * * @exception BuildException Description of Exception */ public void execute() throws BuildException { for ( int i = initValue; i < maxValue; i += inc ) { if ( initName != null ) { getProject().setUserProperty( initName, String.valueOf( i ) ); } Target target = new Target(); target.setName( "for.subtarget" ); getProject().addOrReplaceTarget( target ); for ( Enumeration e = tasks.elements(); e.hasMoreElements(); ) { Task task = (Task)e.nextElement(); addTaskToTarget( target, task ); } target.execute(); } }
private void addTaskToTarget( Target target, Task task ) { UnknownElement replacement = new UnknownElement( taskType ); // shouldn't do taskType, for Ant 1.6 and later there is a getTaskType method replacement.setProject( getProject() ); invokeMethod( replacement, "setTaskType", taskType ); replacement.setTaskName( task.getTaskName() ); replacement.setLocation( task.getLocation() ); replacement.setOwningTarget( target ); replacement.setRuntimeConfigurableWrapper( task.getRuntimeConfigurableWrapper() ); invokeMethod( task.getRuntimeConfigurableWrapper(), "setProxy", replacement ); replacement.maybeConfigure(); log("replacement is a " + replacement.getTaskName() + ", " + replacement.getClass().getName()); if (replacement instanceof TaskContainer) { log("replacement is a TaskContainer"); invokeMethod(replacement, "handleChildren", new Object[]{this, this.getRuntimeConfigurableWrapper()}); } target.addTask(replacement); }
private Target extracted(Project p) { Target target = new Target() { // @Override // public Project getProject() { // return p; // } }; target.setProject(p); target.setName("Hello build"); target.setDescription("Runtime Adding Target"); Echo echo = new Echo(); echo.setMessage("Hello ant build"); echo.setProject(p); target.addTask(echo); return target; }
/** * Removes files from a given zip file. * * @param zipFile name of the zip file to be modified * @param removePattern pattern of the files to be removed * * @throws IOException */ public static void removeFiles(File zipFile, String removePattern) throws IOException { String zipFileName = zipFile.getName(); File tmpFile = new File(zipFile.getCanonicalPath() + ".tmp"); Project antProject = new Project(); Target antTarget = new Target(); antProject.addTarget("zip", antTarget); Zip zipTask = new Zip(); zipTask.setProject(antProject); zipTask.setDestFile(tmpFile); ZipFileSet set = new ZipFileSet(); set.setSrc(zipFile); set.setExcludes(removePattern); zipTask.addZipfileset(set); antTarget.addTask(zipTask); antTarget.execute(); zipFile.delete(); tmpFile.renameTo(new File(tmpFile.getParentFile(), zipFileName)); }
public AntBuilder(final Project project, final Target owningTarget) { this.project = project; /* * GROOVY-4524: The following is not needed anymore as an ant Project already by default has inputhandler * set to DefaultInputHandler. And if it is again set here, it mistakenly overrides the custom input handler * if set using -inputhandler switch. */ //this.project.setInputHandler(new DefaultInputHandler()); collectorTarget = owningTarget; antXmlContext = new AntXMLContext(project); collectorTarget.setProject(project); antXmlContext.setCurrentTarget(collectorTarget); antXmlContext.setLocator(new AntBuilderLocator()); antXmlContext.setCurrentTargets(new HashMap<String, Target>()); implicitTarget = new Target(); implicitTarget.setProject(project); implicitTarget.setName(""); antXmlContext.setImplicitTarget(implicitTarget); // FileScanner is a Groovy utility project.addDataTypeDefinition("fileScanner", FileScanner.class); }
private Target onDefineTarget(final Attributes attrs, String tagName, String ns) { final Target target = new Target(); target.setProject(project); target.setLocation(new Location(antXmlContext.getLocator())); try { antTargetHandler.onStartElement(ns, tagName, tagName, attrs, antXmlContext); final Target newTarget = getProject().getTargets().get(attrs.getValue("name")); antXmlContext.setCurrentTarget(newTarget); definingTarget = newTarget; return newTarget; } catch (final SAXParseException e) { log.log(Level.SEVERE, "Caught: " + e, e); } return null; }
private Target onStartTarget(final Attributes attrs, String tagName, String ns) { final Target target = new Target(); target.setProject(project); target.setLocation(new Location(antXmlContext.getLocator())); try { antTargetHandler.onStartElement(ns, tagName, tagName, attrs, antXmlContext); final Target newTarget = getProject().getTargets().get(attrs.getValue("name")); // execute dependencies (if any) final Vector<Target> targets = new Vector<Target>(); for (final Enumeration<String> deps = newTarget.getDependencies(); deps.hasMoreElements();) { final String targetName = deps.nextElement(); targets.add(project.getTargets().get(targetName)); } getProject().executeSortedTargets(targets); antXmlContext.setCurrentTarget(newTarget); return newTarget; } catch (final SAXParseException e) { log.log(Level.SEVERE, "Caught: " + e, e); } return null; }
static public void zipDir(File destFile, File zipFile) { final class AntZIP extends Zip { @SuppressWarnings("deprecation") public AntZIP() { project = new Project(); project.init(); taskType = "zip"; taskName = "zip"; target = new Target(); } } AntZIP zip = new AntZIP(); zip.setBasedir(zipFile); zip.setDestFile(destFile); zip.execute(); }
static public void unzipFile(File destFile, File zipFile) { final class Expander extends Expand { @SuppressWarnings("deprecation") public Expander() { project = new Project(); project.init(); taskType = "unzip"; taskName = "unzip"; target = new Target(); } } Expander expander = new Expander(); expander.setSrc(zipFile); expander.setDest(destFile); expander.execute(); }
static public void delDir(File dir) { final class AntDelete extends Delete { @SuppressWarnings("deprecation") public AntDelete() { project = new Project(); project.init(); taskType = "delete"; taskName = "delete"; target = new Target(); } } AntDelete ant = new AntDelete(); ant.setDir(dir); ant.execute(); }
/** * Execute the target compile * @return true if execution of the task was successful * @throws TargetNotFoundException * @throws BuildException */ public boolean compile() throws TargetNotFoundException, BuildException { Target t = targets.get("compile"); if (t == null) throw new TargetNotFoundException( "The target compile was not found in the build file"); antProject.executeTarget(t.getName()); return true; }
/** * Parse an unknown element from a url * * @param project the current project * @param source the url containing the task * @return a configured task * @exception BuildException if an error occurs */ public UnknownElement parseUnknownElement(Project project, URL source) throws BuildException { Target dummyTarget = new Target(); dummyTarget.setProject(project); AntXMLContext context = new AntXMLContext(project); context.addTarget(dummyTarget); context.setImplicitTarget(dummyTarget); parse(context.getProject(), source, new RootHandler(context, elementHandler)); Task[] tasks = dummyTarget.getTasks(); if (tasks.length != 1) { throw new BuildException("No tasks defined"); } return (UnknownElement) tasks[0]; }
/** {@inheritDoc}. */ public void executeTargets(Project project, String[] targetNames) throws BuildException { Hashtable<String, Target> targets = project.getTargets(); BuildException thrownException = null; for (int i = 0; i < targetNames.length; i++) { try { Target t = targets.get(targetNames[i]); if (t == null) { throw new BuildException("Unknown target " + targetNames[i]); } t.performTasks(); } catch (BuildException ex) { if (project.isKeepGoingMode()) { thrownException = ex; } else { throw ex; } } } if (thrownException != null) { throw thrownException; } }
private static void concatDescriptions(Project project, Target t, StringBuilder description) { if (t == null) { return; } for (Task task : findElementInTarget(t, "description")) { if (!(task instanceof UnknownElement)) { continue; } UnknownElement ue = ((UnknownElement) task); String descComp = ue.getWrapper().getText().toString(); if (descComp != null) { description.append(project.replaceProperties(descComp)); } } }
public static List searchTask(Class expectedTaskClass, Project project) { List result = new ArrayList(); for (Iterator iterator = project.getTargets().values().iterator(); iterator .hasNext();) { Target t = (Target) iterator.next(); for (int i = 0; i < t.getTasks().length; i++) { Task task = t.getTasks()[i]; Class taskClass = ComponentHelper.getComponentHelper(project) .getComponentClass(task.getTaskType()); // will need to see in what cases it could return a null type // perhaps failing when the task is using a custom antlib // defined task if (taskClass != null && taskClass.equals(expectedTaskClass)) { result.add(task); } } } return result; }
private void learn() { Project p = new TestAnt().readAnt(new File("/home/jesus/usr/qool/workspace/org.eclectic.idc/build-instrument.xml"), TestAnt.class.getClassLoader()); System.out.println( p.getTaskDefinitions() ); System.out.println( p.getTargets() ); System.out.println( "@@@" ); Set set = p.getTargets().keySet(); for (Object key : set) { Target t = (Target) p.getTargets().get(key); System.out.println("Target: " + t); Enumeration deps = t.getDependencies(); while ( deps.hasMoreElements() ) { Object obj = deps.nextElement(); System.out.println("--"); System.out.println(obj); System.out.println(obj.getClass()); } } }
/** * Update the current Ant target in the build database the the current progress. * * @param conn Database connection * @param id Primary key for the progress table entry * @param indicator Information about the matching progress indicator * @param target Ant target information * @return Autogenerated primary key for the inserted database row */ public synchronized void updateTarget(Connection conn, int id, ProgressTarget indicator, Target target) throws SQLException { String endDate = DATETIME.format(new Date()); StringBuffer sql = new StringBuffer(); sql.append("UPDATE " + progressTable + " "); sql.append("SET " + END_DATE + " = \"" + endDate + "\" "); sql.append("WHERE " + PROGRESS_ID + " = \"" + id + "\" "); Statement st = conn.createStatement(); try { st.execute(sql.toString()); } catch (SQLException ex) { System.err.println("Failed to add criteria: " + sql.toString()); ex.printStackTrace(); } }
/** * Determine if the parse target matches the specified ant Target. * * @param target Ant target * @return TRUE if the target matches */ public boolean matches(Target target) { boolean match = true; if (!targetName.equals(target.getName())) { match = false; } Location location = target.getLocation(); String targetFileName = targetFile.getAbsolutePath(); if (!targetFileName.equals(location.getFileName())) { match = false; } return match; }
/** * Signals that a target has finished. This event will * still be fired if an error occurred during the build. * * @param event An event with any relevant extra information. * Must not be <code>null</code>. * * @see BuildEvent#getException() */ public void targetFinished(BuildEvent event) { Target currentTarget = event.getTarget(); Integer currentKey = null; try { ProgressTarget match = getProgressIndicator(currentTarget); if (match != null) { if (!keys.empty()) { currentKey = (Integer) keys.pop(); dbTable.updateTarget(dbConnection, currentKey.intValue(), match, currentTarget); } else { throw new BuildException("Attempt to update a non-existent progress entry in the database."); } } } catch (SQLException sqe) { System.err.println("Unable to update target progress in the database."); sqe.printStackTrace(); } }
/** * Signals that a target has finished. This event will * still be fired if an error occurred during the build. * * @param event An event with any relevant extra information. * Must not be <code>null</code>. * * @see BuildEvent#getException() */ public void targetFinished(BuildEvent event) { pop(); Target target = event.getTarget(); String targetName = target.getName(); // Cycle through the list of targets ReportParseTarget currentTarget = null; for (int idx = 0; idx < targets.size(); idx++) { currentTarget = (ReportParseTarget) targets.get(idx); if (targetName.equalsIgnoreCase(currentTarget.getTargetName())) { currentTarget.stop(); } } showMatches(event); }
/** * Determine whether the log entry was a child of the specified target * by examining the execution stack to find out if it contains a match. * * @param targetName Target to be matched * @return TRUE if the target was found in the stack, FALSE otherwise */ public boolean loggedBy(String targetName) { // Cycle through the execution stack to examine all targets Object current = null; for (int idx = 0; idx < executionStack.size(); idx++) { current = executionStack.get(idx); if (current instanceof Target) { // Compare the names and return if they match String currentName = ((Target)current).getName(); if (targetName.equalsIgnoreCase(currentName)) { return true; } } } return false; }
public Echo getEchoTask() { Project project = new Project(); project.setName("testProject"); Target target = new Target(); target.setName("testTarget"); target.setProject(project); Echo.EchoLevel level = new Echo.EchoLevel(); level.setValue("error"); Echo echoTask = new Echo(); echoTask.setOwningTarget(target); echoTask.setLevel(level); echoTask.setTaskName("echo"); echoTask.setTaskType("echo"); echoTask.setMessage("This is a sample message."); return echoTask; }
/** * Searches the specified task (the first occurence) within the specified * target. * * @param target * the target to search for the task for * @param clazz * the type of the task to be returned (if several are found the * first one is returned) * * @return the found task */ @SuppressWarnings("unchecked") protected <T extends Task> T findTask(final Target target, final Class<T> clazz) { for (final Task task : target.getTasks()) { if (UnknownElement.class.equals(task.getClass())) { final UnknownElement unknownTask = (UnknownElement) task; // make sure we have the real thing unknownTask.maybeConfigure(); // check it if (clazz.equals(unknownTask.getRealThing().getClass())) { return (T) unknownTask.getRealThing(); } } else if (clazz.equals(task.getClass())) { return (T) task; } } return null; }
public void importBuild(Object antBuildFile, Transformer<? extends String, ? super String> taskNamer) { File file = gradleProject.file(antBuildFile); final File baseDir = file.getParentFile(); Set<String> existingAntTargets = new HashSet<String>(getAntProject().getTargets().keySet()); File oldBaseDir = getAntProject().getBaseDir(); getAntProject().setBaseDir(baseDir); try { getAntProject().setUserProperty(MagicNames.ANT_FILE, file.getAbsolutePath()); ProjectHelper.configureProject(getAntProject(), file); } catch (Exception e) { throw new GradleException("Could not import Ant build file '" + String.valueOf(file) + "'.", e); } finally { getAntProject().setBaseDir(oldBaseDir); } // Chuck away the implicit target. It has already been executed getAntProject().getTargets().remove(""); // Add an adapter for each newly added target Set<String> newAntTargets = new HashSet<String>(getAntProject().getTargets().keySet()); newAntTargets.removeAll(existingAntTargets); for (String name : newAntTargets) { final Target target = getAntProject().getTargets().get(name); String taskName = taskNamer.transform(target.getName()); final AntTarget task = gradleProject.getTasks().create(taskName, AntTarget.class); configureTask(target, task, baseDir, taskNamer); } }
private static List<String> getTaskDependencyNames(Target target, Transformer<? extends String, ? super String> taskNamer) { Enumeration<String> dependencies = target.getDependencies(); List<String> taskDependencyNames = Lists.newLinkedList(); while (dependencies.hasMoreElements()) { String targetName = dependencies.nextElement(); String taskName = taskNamer.transform(targetName); taskDependencyNames.add(taskName); } return taskDependencyNames; }
/** * Try to find the location of an Ant target. * @param project if not null, the main project from which this target might have been imported */ private Location getLocationOfTarget(Target target, Project project) { if (targetGetLocation != null) { try { return (Location) targetGetLocation.invoke(target); } catch (Exception e) { LOG.log(Level.WARNING, null, e); } } // For Ant 1.6.2 and earlier, hope we got the right info from the hacks above. LOG.log(Level.FINEST, "knownImportedTargets: {0}", knownImportedTargets); if (project != null) { String file = project.getProperty("ant.file"); // NOI18N if (file != null) { Map<String,String> targetLocations = knownImportedTargets.get(file); if (targetLocations != null) { String importedFile = targetLocations.get(target.getName()); if (importedFile != null) { // Have no line number, note. return new Location(importedFile); } } } } // Dunno. return null; }
public Expander() { setProject(new Project()); getProject().init(); setTaskType("unzip"); setTaskName("unzip"); setOwningTarget(new Target()); }
/** * Execute a target's dependencies followed by the target itself. * @param target the target to execute */ private void executeDependencies( Target target ) { if ( target == null ) return ; Enumeration en = target.getDependencies(); if ( en == null ) return ; while ( en.hasMoreElements() ) { String name = ( String ) en.nextElement(); Target t = ( Target ) getProject().getTargets().get( name ); executeDependencies( t ); t.performTasks(); } }
private AntTaskRunner getAntTaskRunnerInstanceFromProject() { Target target = (Target) this.getProject().getTargets().get( "run" ); Task[] tasks = target.getTasks(); for (Task t : tasks) { if ("greenpepper".equals( t.getTaskName() )) { UnknownElement gpTask = (UnknownElement) t; return (AntTaskRunner) gpTask.getRealThing(); } } throw new IllegalArgumentException( "GreenPepper task not found!" ); }
/** * Execute the target all * @return true if execution of the task was successful * @throws TargetNotFoundException * @throws BuildException */ public boolean all() throws TargetNotFoundException, BuildException { Target t = targets.get("all"); if (t == null) throw new TargetNotFoundException( "The target all was not found in the build file"); antProject.executeTarget(t.getName()); return true; }