diff options
author | mattinger <[email protected]> | 2006-07-06 21:53:00 +0000 |
---|---|---|
committer | mattinger <[email protected]> | 2006-07-06 21:53:00 +0000 |
commit | 1159111b7a71b72eb04326df33211e1733f7e742 (patch) | |
tree | f0a80c384f633e521649654ab78e6239cf5e0d6f /src |
Initial addition into subversion with build script changes
git-svn-id: file:///home/sven/projects/JOGL/temp/ant-contrib/svn/ant-contrib-code/trunk/ant-contrib@5 32d7a393-a5a9-423c-abd3-5d954feb1f2f
Diffstat (limited to 'src')
84 files changed, 15542 insertions, 0 deletions
diff --git a/src/java/net/sf/antcontrib/AntContribVersion.java b/src/java/net/sf/antcontrib/AntContribVersion.java new file mode 100644 index 0000000..8633459 --- /dev/null +++ b/src/java/net/sf/antcontrib/AntContribVersion.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib; + +/** + * @author Dean Hiller + * + * To change the template for this generated type comment go to + * Window - Preferences - Java - Code Generation - Code and Comments + */ +public class AntContribVersion { + + private Package thePackage; + + /** + * The main program for MockVersion that prints the version info from + * the manifest file. + * + * @param args Ignores all arguments. + */ + public static void main(String[] args) { + AntContribVersion version = new AntContribVersion(AntContribVersion.class); + System.out.println(""+version); + } + + /** + * Constructor that takes a class to get the version information + * from out of the manifest. Uses the class's package to retrieve + * the manifest version info. + * @param c The Class on whose package to use to get version info. + */ + public AntContribVersion(Class c) { + String name = c.getName(); + int index = name.lastIndexOf("."); + + if(index < 0) + throw new RuntimeException("This class is the default package and can't be to use this feature"); + + String packageName = name.substring(0, index); + thePackage = Package.getPackage(packageName); + } + + + /** + * Prints the version info the MockVersion represents. + * + * @see java.lang.Object#toString() + */ + public String toString() { + String version = "\nVersion of Ant Contrib..."; + version += "\ntitle="+thePackage.getImplementationTitle(); + version += "\nwebsite="+thePackage.getImplementationVendor(); + version += "\nversion="+thePackage.getImplementationVersion()+"\n"; + + return version; + } +} diff --git a/src/java/net/sf/antcontrib/antclipse/ClassPathParser.java b/src/java/net/sf/antcontrib/antclipse/ClassPathParser.java new file mode 100644 index 0000000..389c89e --- /dev/null +++ b/src/java/net/sf/antcontrib/antclipse/ClassPathParser.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.antclipse; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Location; +import org.xml.sax.HandlerBase; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +/** + * Classic tool firing a SAX parser. Must feed the source file and a handler. + * Nothing really special about it, only probably some special file handling in nasty cases + * (Windows files containing strange chars, internationalized filenames, + * but you shouldn't be doing this, anyway :)). + * @author Adrian Spinei [email protected] + * @version $Revision: 1.2 $ + * @since Ant 1.5 + */ +public class ClassPathParser +{ + void parse(File file, HandlerBase handler) throws BuildException + { + String fName = file.getName(); + FileInputStream fileInputStream = null; + InputSource inputSource = null; + try + { + SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); + //go to UFS if we're on win + String uri = "file:" + fName.replace('\\', '/'); + fileInputStream = new FileInputStream(file); + inputSource = new InputSource(fileInputStream); + inputSource.setSystemId(uri); + saxParser.parse(inputSource, handler); + } + catch (ParserConfigurationException pceException) + { + throw new BuildException("Parser configuration failed", pceException); + } + catch (SAXParseException exc) + { + Location location = new Location(fName.toString(), exc.getLineNumber(), exc.getColumnNumber()); + Throwable throwable = exc.getException(); + if ((Object) throwable instanceof BuildException) + { + BuildException be = (BuildException) (Object) throwable; + if (be.getLocation() == Location.UNKNOWN_LOCATION) + be.setLocation(location); + throw be; + } + throw new BuildException(exc.getMessage(), throwable, location); + } + catch (SAXException exc) + { + Throwable throwable = exc.getException(); + if ((Object) throwable instanceof BuildException) + throw (BuildException) (Object) throwable; + throw new BuildException(exc.getMessage(), throwable); + } + catch (FileNotFoundException exc) + { + throw new BuildException(exc); + } + catch (IOException exc) + { + throw new BuildException("Error reading file", exc); + } + finally + { + if (fileInputStream != null) + { + try + { + fileInputStream.close(); + } + catch (IOException ioexception) + { + //do nothing, should not appear + } + } + } + } +} diff --git a/src/java/net/sf/antcontrib/antclipse/ClassPathTask.java b/src/java/net/sf/antcontrib/antclipse/ClassPathTask.java new file mode 100644 index 0000000..6c32181 --- /dev/null +++ b/src/java/net/sf/antcontrib/antclipse/ClassPathTask.java @@ -0,0 +1,419 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.antclipse; +import java.io.File; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.taskdefs.Property; +import org.apache.tools.ant.types.FileSet; +import org.apache.tools.ant.types.Path; +import org.apache.tools.ant.types.Path.PathElement; +import org.apache.tools.ant.util.RegexpPatternMapper; +import org.xml.sax.AttributeList; +import org.xml.sax.HandlerBase; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +/** + * Support class for the Antclipse task. Basically, it takes the .classpath Eclipse file + * and feeds a SAX parser. The handler is slightly different according to what we want to + * obtain (a classpath or a fileset) + * @author Adrian Spinei [email protected] + * @version $Revision: 1.2 $ + * @since Ant 1.5 + */ +public class ClassPathTask extends Task +{ + private String project; + private String idContainer = "antclipse"; + private boolean includeSource = false; //default, do not include source + private boolean includeOutput = false; //default, do not include output directory + private boolean includeLibs = true; //default, include all libraries + private boolean verbose = false; //default quiet + RegexpPatternMapper irpm = null; + RegexpPatternMapper erpm = null; + public static final String TARGET_CLASSPATH = "classpath"; + public static final String TARGET_FILESET = "fileset"; + private String produce = null; //classpath by default + + /** + * Setter for task parameter + * @param includeLibs Boolean, whether to include or not the project libraries. Default is true. + */ + public void setIncludeLibs(boolean includeLibs) + { + this.includeLibs = includeLibs; + } + + /** + * Setter for task parameter + * @param produce This parameter tells the task wether to produce a "classpath" or a "fileset" (multiple filesets, as a matter of fact). + */ + public void setproduce(String produce) + { + this.produce = produce; + } + + /** + * Setter for task parameter + * @param verbose Boolean, telling the app to throw some info during each step. Default is false. + */ + public void setVerbose(boolean verbose) + { + this.verbose = verbose; + } + + /** + * Setter for task parameter + * @param excludes A regexp for files to exclude. It is taken into account only when producing a classpath, doesn't work on source or output files. It is a real regexp, not a "*" expression. + */ + public void setExcludes(String excludes) + { + if (excludes != null) + { + erpm = new RegexpPatternMapper(); + erpm.setFrom(excludes); + erpm.setTo("."); //mandatory + } + else + erpm = null; + } + + /** + * Setter for task parameter + * @param includes A regexp for files to include. It is taken into account only when producing a classpath, doesn't work on source or output files. It is a real regexp, not a "*" expression. + */ + public void setIncludes(String includes) + { + if (includes != null) + { + irpm = new RegexpPatternMapper(); + irpm.setFrom(includes); + irpm.setTo("."); //mandatory + } + else + irpm = null; + } + + /** + * Setter for task parameter + * @param idContainer The refid which will serve to identify the deliverables. When multiple filesets are produces, their refid is a concatenation between this value and something else (usually obtained from a path). Default "antclipse" + */ + public void setIdContainer(String idContainer) + { + this.idContainer = idContainer; + } + + /** + * Setter for task parameter + * @param includeOutput Boolean, whether to include or not the project output directories. Default is false. + */ + public void setIncludeOutput(boolean includeOutput) + { + this.includeOutput = includeOutput; + } + + /** + * Setter for task parameter + * @param includeSource Boolean, whether to include or not the project source directories. Default is false. + */ + public void setIncludeSource(boolean includeSource) + { + this.includeSource = includeSource; + } + + /** + * Setter for task parameter + * @param project project name + */ + public void setProject(String project) + { + this.project = project; + } + + /** + * @see org.apache.tools.ant.Task#execute() + */ + public void execute() throws BuildException + { + if (!TARGET_CLASSPATH.equalsIgnoreCase(this.produce) && !TARGET_FILESET.equals(this.produce)) + throw new BuildException( + "Mandatory target must be either '" + TARGET_CLASSPATH + "' or '" + TARGET_FILESET + "'"); + ClassPathParser parser = new ClassPathParser(); + AbstractCustomHandler handler; + if (TARGET_CLASSPATH.equalsIgnoreCase(this.produce)) + { + Path path = new Path(this.getProject()); + this.getProject().addReference(this.idContainer, path); + handler = new PathCustomHandler(path); + } + else + { + FileSet fileSet = new FileSet(); + this.getProject().addReference(this.idContainer, fileSet); + fileSet.setDir(new File(this.getProject().getBaseDir().getAbsolutePath().toString())); + handler = new FileSetCustomHandler(fileSet); + } + parser.parse(new File(this.getProject().getBaseDir().getAbsolutePath(), ".classpath"), handler); + } + + abstract class AbstractCustomHandler extends HandlerBase + { + protected String projDir; + protected static final String ATTRNAME_PATH = "path"; + protected static final String ATTRNAME_KIND = "kind"; + protected static final String ATTR_LIB = "lib"; + protected static final String ATTR_SRC = "src"; + protected static final String ATTR_OUTPUT = "output"; + protected static final String EMPTY = ""; + } + + class FileSetCustomHandler extends AbstractCustomHandler + { + private FileSet fileSet = null; + + /** + * nazi style, forbid default constructor + */ + private FileSetCustomHandler() + { + } + + /** + * @param fileSet + */ + public FileSetCustomHandler(FileSet fileSet) + { + super(); + this.fileSet = fileSet; + projDir = getProject().getBaseDir().getAbsolutePath().toString(); + } + + /** + * @see org.xml.sax.DocumentHandler#endDocument() + */ + public void endDocument() throws SAXException + { + super.endDocument(); + if (fileSet != null && !fileSet.hasPatterns()) + fileSet.setExcludes("**/*"); + //exclude everything or we'll take all the project dirs + } + + public void startElement(String tag, AttributeList attrs) throws SAXParseException + { + if (tag.equalsIgnoreCase("classpathentry")) + { + //start by checking if the classpath is coherent at all + String kind = attrs.getValue(ATTRNAME_KIND); + if (kind == null) + throw new BuildException("classpathentry 'kind' attribute is mandatory"); + String path = attrs.getValue(ATTRNAME_PATH); + if (path == null) + throw new BuildException("classpathentry 'path' attribute is mandatory"); + + //put the outputdirectory in a property + if (kind.equalsIgnoreCase(ATTR_OUTPUT)) + { + String propName = idContainer + "outpath"; + Property property = new Property(); + property.setName(propName); + property.setValue(path); + property.setProject(getProject()); + property.execute(); + if (verbose) + System.out.println("Setting property " + propName + " to value " + path); + } + + //let's put the last source directory in a property + if (kind.equalsIgnoreCase(ATTR_SRC)) + { + String propName = idContainer + "srcpath"; + Property property = new Property(); + property.setName(propName); + property.setValue(path); + property.setProject(getProject()); + property.execute(); + if (verbose) + System.out.println("Setting property " + propName + " to value " + path); + } + + if ((kind.equalsIgnoreCase(ATTR_SRC) && includeSource) + || (kind.equalsIgnoreCase(ATTR_OUTPUT) && includeOutput) + || (kind.equalsIgnoreCase(ATTR_LIB) && includeLibs)) + { + //all seem fine + // check the includes + String[] inclResult = new String[] { "all included" }; + if (irpm != null) + { + inclResult = irpm.mapFileName(path); + } + String[] exclResult = null; + if (erpm != null) + { + exclResult = erpm.mapFileName(path); + } + if (inclResult != null && exclResult == null) + { + //THIS is the specific code + if (kind.equalsIgnoreCase(ATTR_OUTPUT)) + { + //we have included output so let's build a new fileset + FileSet outFileSet = new FileSet(); + String newReference = idContainer + "-" + path.replace(File.separatorChar, '-'); + getProject().addReference(newReference, outFileSet); + if (verbose) + System.out.println( + "Created new fileset " + + newReference + + " containing all the files from the output dir " + + projDir + + File.separator + + path); + outFileSet.setDefaultexcludes(false); + outFileSet.setDir(new File(projDir + File.separator + path)); + outFileSet.setIncludes("**/*"); //get everything + } + else + if (kind.equalsIgnoreCase(ATTR_SRC)) + { + //we have included source so let's build a new fileset + FileSet srcFileSet = new FileSet(); + String newReference = idContainer + "-" + path.replace(File.separatorChar, '-'); + getProject().addReference(newReference, srcFileSet); + if (verbose) + System.out.println( + "Created new fileset " + + newReference + + " containing all the files from the source dir " + + projDir + + File.separator + + path); + srcFileSet.setDefaultexcludes(false); + srcFileSet.setDir(new File(projDir + File.separator + path)); + srcFileSet.setIncludes("**/*"); //get everything + } + else + { + //not otuptut, just add file after file to the fileset + File file = new File(fileSet.getDir(getProject()) + "/" + path); + if (file.isDirectory()) + path += "/**/*"; + if (verbose) + System.out.println( + "Adding " + + path + + " to fileset " + + idContainer + + " at " + + fileSet.getDir(getProject())); + fileSet.setIncludes(path); + } + } + } + } + } + } + + class PathCustomHandler extends AbstractCustomHandler + { + private Path path = null; + + /** + * @param path the path to add files + */ + public PathCustomHandler(Path path) + { + super(); + this.path = path; + } + + /** + * nazi style, forbid default constructor + */ + private PathCustomHandler() + { + } + + public void startElement(String tag, AttributeList attrs) throws SAXParseException + { + if (tag.equalsIgnoreCase("classpathentry")) + { + //start by checking if the classpath is coherent at all + String kind = attrs.getValue(ATTRNAME_KIND); + if (kind == null) + throw new BuildException("classpathentry 'kind' attribute is mandatory"); + String path = attrs.getValue(ATTRNAME_PATH); + if (path == null) + throw new BuildException("classpathentry 'path' attribute is mandatory"); + + //put the outputdirectory in a property + if (kind.equalsIgnoreCase(ATTR_OUTPUT)) + { + String propName = idContainer + "outpath"; + Property property = new Property(); + property.setName(propName); + property.setValue(path); + property.setProject(getProject()); + property.execute(); + if (verbose) + System.out.println("Setting property " + propName + " to value " + path); + } + + //let's put the last source directory in a property + if (kind.equalsIgnoreCase(ATTR_SRC)) + { + String propName = idContainer + "srcpath"; + Property property = new Property(); + property.setName(propName); + property.setValue(path); + property.setProject(getProject()); + property.execute(); + if (verbose) + System.out.println("Setting property " + propName + " to value " + path); + } + + if ((kind.equalsIgnoreCase(ATTR_SRC) && includeSource) + || (kind.equalsIgnoreCase(ATTR_OUTPUT) && includeOutput) + || (kind.equalsIgnoreCase(ATTR_LIB) && includeLibs)) + { + //all seem fine + // check the includes + String[] inclResult = new String[] { "all included" }; + if (irpm != null) + { + inclResult = irpm.mapFileName(path); + } + String[] exclResult = null; + if (erpm != null) + { + exclResult = erpm.mapFileName(path); + } + if (inclResult != null && exclResult == null) + { + //THIS is the only specific code + if (verbose) + System.out.println("Adding " + path + " to classpath " + idContainer); + PathElement element = this.path.createPathElement(); + element.setLocation(new File(path)); + } + } + } + } + } +} diff --git a/src/java/net/sf/antcontrib/antcontrib.properties b/src/java/net/sf/antcontrib/antcontrib.properties new file mode 100644 index 0000000..3ddba23 --- /dev/null +++ b/src/java/net/sf/antcontrib/antcontrib.properties @@ -0,0 +1,55 @@ +
+# Antclipse tasks
+antclipse=net.sf.antcontrib.antclipse.ClassPathTask
+
+# AntServer tasks
+antserver=net.sf.antcontrib.antserver.server.ServerTask
+remoteant=net.sf.antcontrib.antserver.client.ClientTask
+
+# Design Tasks
+verifydesign=net.sf.antcontrib.design.VerifyDesign
+
+# IniFile
+inifile=net.sf.antcontrib.inifile.IniFileTask
+
+# Logic tasks
+if=net.sf.antcontrib.logic.IfTask
+foreach=net.sf.antcontrib.logic.ForEach
+throw=net.sf.antcontrib.logic.Throw
+trycatch=net.sf.antcontrib.logic.TryCatchTask
+switch=net.sf.antcontrib.logic.Switch
+outofdate=net.sf.antcontrib.logic.OutOfDate
+runtarget=net.sf.antcontrib.logic.RunTargetTask
+timestampselector=net.sf.antcontrib.logic.TimestampSelector
+antcallback=net.sf.antcontrib.logic.AntCallBack
+antfetch=net.sf.antcontrib.logic.AntFetch
+assert=net.sf.antcontrib.logic.Assert
+
+# Math Tasks
+math=net.sf.antcontrib.math.MathTask
+
+# Net tasks
+post=net.sf.antcontrib.net.PostTask
+
+# Peformance Tasks
+stopwatch=net.sf.antcontrib.perf.StopWatchTask
+
+# Platform Tasks
+osfamily=net.sf.antcontrib.platform.OsFamily
+shellscript=net.sf.antcontrib.platform.ShellScriptTask
+
+# Process Tasks
+forget=net.sf.antcontrib.process.ForgetTask
+limit=net.sf.antcontrib.process.Limit
+
+# Property Tasks
+propertycopy=net.sf.antcontrib.property.PropertyCopy
+pathtofileset=net.sf.antcontrib.property.PathToFileSet
+propertyselector=net.sf.antcontrib.property.PropertySelector
+propertyregex=net.sf.antcontrib.property.RegexTask
+sortlist=net.sf.antcontrib.property.SortList
+urlencode=net.sf.antcontrib.property.URLEncodeTask
+var=net.sf.antcontrib.property.Variable
+
+# Walls Tasks
+compilewithwalls=net.sf.antcontrib.walls.CompileWithWalls
diff --git a/src/java/net/sf/antcontrib/antlib.xml b/src/java/net/sf/antcontrib/antlib.xml new file mode 100644 index 0000000..69cfa43 --- /dev/null +++ b/src/java/net/sf/antcontrib/antlib.xml @@ -0,0 +1,9 @@ +<antlib> + <!-- typedef the tasks that work for ant less than 1.6 --> + <taskdef resource="net/sf/antcontrib/antcontrib.properties"/> + + <taskdef + name="for" + classname="net.sf.antcontrib.logic.ForTask" + onerror="report"/> +</antlib> diff --git a/src/java/net/sf/antcontrib/antserver/Command.java b/src/java/net/sf/antcontrib/antserver/Command.java new file mode 100644 index 0000000..e9d84a0 --- /dev/null +++ b/src/java/net/sf/antcontrib/antserver/Command.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.sf.antcontrib.antserver; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Serializable; + +import org.apache.tools.ant.Project; + + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public interface Command + extends Serializable +{ + /*** + * This should throw a build exception if the parameters + * are invalid. + */ + public void validate(Project project); + + /*** + * Is there additional content being sent from the local + * machine to the remote server + */ + public long getContentLength(); + + /*** + * Gets the content's input stream. Should be called only on the + * client side for sending the content over the connection + * @return the content's input stream. + */ + public InputStream getContentStream() throws IOException; + + + public long getResponseContentLength(); + + public InputStream getReponseContentStream() throws IOException; + + /*** + * Execute the command. + * @param project The project which is being executed + * @return If true, the connection will be closed + * @throws Throwable + */ + public boolean execute(Project project, + long contentLength, + InputStream contentStream) + throws Throwable; + + /*** + * Process any additional data from a response. + */ + public boolean respond(Project project, + long contentLength, + InputStream contentStream) + throws IOException; + +} diff --git a/src/java/net/sf/antcontrib/antserver/Response.java b/src/java/net/sf/antcontrib/antserver/Response.java new file mode 100644 index 0000000..b1958d9 --- /dev/null +++ b/src/java/net/sf/antcontrib/antserver/Response.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.sf.antcontrib.antserver; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.io.Serializable; + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * + ****************************************************************************/ + + +public class Response + implements Serializable +{ + private boolean succeeded; + private String errorStackTrace; + private String errorMessage; + private String resultsXml; + + private long contentLength; + + public Response() + { + super(); + this.succeeded = true; + } + + + public boolean isSucceeded() + { + return succeeded; + } + + + public void setSucceeded(boolean succeeded) + { + this.succeeded = succeeded; + } + + public void setThrowable(Throwable t) + { + errorMessage = t.getMessage(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + PrintStream ps = new PrintStream(baos); + t.printStackTrace(ps); + ps.flush(); + setErrorStackTrace(baos.toString()); + } + + public String getErrorStackTrace() + { + return errorStackTrace; + } + + + public void setErrorStackTrace(String errorStackTrace) + { + this.errorStackTrace = errorStackTrace; + } + + + public String getErrorMessage() + { + return errorMessage; + } + + + public void setErrorMessage(String errorMessage) + { + this.errorMessage = errorMessage; + } + + + public String getResultsXml() + { + return resultsXml; + } + + + public void setResultsXml(String resultsXml) + { + this.resultsXml = resultsXml; + } + + public long getContentLength() + { + return contentLength; + } + + public void setContentLength(long contentLength) + { + this.contentLength = contentLength; + } +} diff --git a/src/java/net/sf/antcontrib/antserver/Util.java b/src/java/net/sf/antcontrib/antserver/Util.java new file mode 100644 index 0000000..124e315 --- /dev/null +++ b/src/java/net/sf/antcontrib/antserver/Util.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.antserver; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class Util +{ + public static final int CHUNK = 10*1024; + + public static final void transferBytes(InputStream input, + long length, + OutputStream output, + boolean closeInput) + throws IOException + { + + byte b[] = new byte[CHUNK]; + int read = 0; + int totalread = 0; + + while (totalread < length) + { + int toRead = (int)Math.min(CHUNK, length - totalread); + read = input.read(b, 0, toRead); + output.write(b, 0, read); + totalread += read; + } + + try + { + if (closeInput) + input.close(); + } + catch (IOException e) + { + // ; gulp + } + } +} diff --git a/src/java/net/sf/antcontrib/antserver/client/Client.java b/src/java/net/sf/antcontrib/antserver/client/Client.java new file mode 100644 index 0000000..061815f --- /dev/null +++ b/src/java/net/sf/antcontrib/antserver/client/Client.java @@ -0,0 +1,251 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.antserver.client; + +import java.io.*; +import java.net.Socket; +import java.net.SocketException; + +import org.apache.tools.ant.Project; + +import net.sf.antcontrib.antserver.Command; +import net.sf.antcontrib.antserver.Response; +import net.sf.antcontrib.antserver.Util; +import net.sf.antcontrib.antserver.commands.DisconnectCommand; + + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class Client +{ + private String machine; + private int port; + private Project project; + + + public Client(Project project, String machine, int port) + { + super(); + this.machine = machine; + this.port = port; + this.project = project; + } + + + private Socket socket; + private OutputStream os; + private InputStream is; + private ObjectOutputStream oos; + private ObjectInputStream ois; + private boolean connected; + + + public void connect() + throws IOException + { + project.log("Opening connection to " + machine + ":" + port, + Project.MSG_DEBUG); + + try + { + socket = new Socket(machine, port); + socket.setKeepAlive(true); + project.log("Got connection to " + machine + ":" + port, + Project.MSG_DEBUG); + + os = socket.getOutputStream(); + is = socket.getInputStream(); + + oos = new ObjectOutputStream(os); + ois = new ObjectInputStream(is); + + connected = true; + try + { + // Read the initial response object so that the + // object stream is initialized + ois.readObject(); + } + catch (ClassNotFoundException e) + { + ; // gulp + } + } + finally + { + // If we were unable to connect, close everything + if (!connected) + { + + try + { + if (os != null) + os.close(); + os = null; + oos = null; + } + catch (IOException e) + { + + } + + try + { + if (is != null) + is.close(); + is = null; + ois = null; + } + catch (IOException e) + { + + } + + try + { + if (socket != null) + socket.close(); + socket = null; + } + catch (IOException e) + { + + } + } + } + + + } + + public void shutdown() + { + try + { + if (os != null) + os.close(); + } + catch (IOException e) + { + ; // gulp + + } + os = null; + oos = null; + + try + { + if (is != null) + is.close(); + } + catch (IOException e) + { + ; // gulp + + } + is = null; + ois = null; + + try + { + socket.close(); + } + catch (IOException e) + { + ; // gulp + } + socket = null; + + connected = false; + } + + + public void disconnect() + throws IOException + { + if (!connected) + return; + + try { + oos.writeObject(DisconnectCommand.DISCONNECT_COMMAND); + try + { + // Read disconnect response + ois.readObject(); + } + catch (ClassNotFoundException e) + { + ; // gulp + } + + shutdown(); + } + catch (SocketException e) { + ; // connection was closed + } + catch (EOFException e) { + ; // connection was closed + } + } + + + public Response sendCommand(Command command) + throws IOException + { + project.log("Sending command: " + command, + Project.MSG_DEBUG); + oos.writeObject(command); + + if (command.getContentLength() > 0) + { + Util.transferBytes(command.getContentStream(), + command.getContentLength(), + os, + true); + } + + Response response = null; + + try + { + // Read the response object + response = (Response) ois.readObject(); + project.log("Received Response: " + response, + Project.MSG_DEBUG); + if (response.getContentLength() != 0) + { + command.respond(project, + response.getContentLength(), + is); + } + } + catch (ClassNotFoundException e) + { + ; // gulp + } + + return response; + } + +} diff --git a/src/java/net/sf/antcontrib/antserver/client/ClientTask.java b/src/java/net/sf/antcontrib/antserver/client/ClientTask.java new file mode 100644 index 0000000..34236f0 --- /dev/null +++ b/src/java/net/sf/antcontrib/antserver/client/ClientTask.java @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.sf.antcontrib.antserver.client; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.Enumeration; +import java.util.Vector; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.Task; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import net.sf.antcontrib.antserver.Command; +import net.sf.antcontrib.antserver.Response; +import net.sf.antcontrib.antserver.commands.RunAntCommand; +import net.sf.antcontrib.antserver.commands.RunTargetCommand; +import net.sf.antcontrib.antserver.commands.SendFileCommand; +import net.sf.antcontrib.antserver.commands.ShutdownCommand; + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class ClientTask + extends Task +{ + private String machine = "localhost"; + private int port = 17000; + private Vector commands; + private boolean persistant = false; + private boolean failOnError = true; + + public ClientTask() + { + super(); + this.commands = new Vector(); + } + + + public void setMachine(String machine) + { + this.machine = machine; + } + + + public void setPort(int port) + { + this.port = port; + } + + + public void setPersistant(boolean persistant) + { + this.persistant = persistant; + } + + + public void setFailOnError(boolean failOnError) + { + this.failOnError = failOnError; + } + + + public void addConfiguredShutdown(ShutdownCommand cmd) + { + commands.add(cmd); + } + + public void addConfiguredRunTarget(RunTargetCommand cmd) + { + commands.add(cmd); + } + + public void addConfiguredRunAnt(RunAntCommand cmd) + { + commands.add(cmd); + } + + public void addConfiguredSendFile(SendFileCommand cmd) + { + commands.add(cmd); + } + + + public void execute() + { + Enumeration e = commands.elements(); + Command c = null; + while (e.hasMoreElements()) + { + c = (Command)e.nextElement(); + c.validate(getProject()); + } + + Client client = new Client(getProject(), machine, port); + + try + { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + + try + { + int failCount = 0; + + client.connect(); + + e = commands.elements(); + c = null; + Response r = null; + Document d = null; + boolean keepGoing = true; + while (e.hasMoreElements() && keepGoing) + { + c = (Command)e.nextElement(); + r = client.sendCommand(c); + if (! r.isSucceeded()) + { + failCount++; + log("Command caused a build failure:" + c, + Project.MSG_ERR); + log(r.getErrorMessage(), + Project.MSG_ERR); + log(r.getErrorStackTrace(), + Project.MSG_DEBUG); + if (! persistant) + keepGoing = false; + } + + try + { + ByteArrayInputStream bais = + new ByteArrayInputStream(r.getResultsXml().getBytes()); + d = db.parse(bais); + NodeList nl = d.getElementsByTagName("target"); + int len = nl.getLength(); + Element element = null; + for (int i=0;i<len;i++) + { + element = (Element)nl.item(i); + getProject().log("[" + element.getAttribute("name") + "]", + Project.MSG_INFO); + } + } + catch (SAXException se) + { + + } + + if (c instanceof ShutdownCommand) + { + keepGoing = false; + client.shutdown(); + } + } + + if (failCount > 0 && failOnError) + throw new BuildException("One or more commands failed."); + } + finally + { + if (client != null) + client.disconnect(); + } + } + catch (ParserConfigurationException ex) + { + throw new BuildException(ex); + } + catch (IOException ex) + { + throw new BuildException(ex); + } + } +} diff --git a/src/java/net/sf/antcontrib/antserver/commands/AbstractCommand.java b/src/java/net/sf/antcontrib/antserver/commands/AbstractCommand.java new file mode 100644 index 0000000..9734631 --- /dev/null +++ b/src/java/net/sf/antcontrib/antserver/commands/AbstractCommand.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.antserver.commands; + +import java.io.IOException; +import java.io.InputStream; + +import org.apache.tools.ant.Project; + +import net.sf.antcontrib.antserver.Command; + + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * + ****************************************************************************/ + + +public abstract class AbstractCommand + implements Command +{ + public long getContentLength() + { + return 0; + } + + + public InputStream getContentStream() + throws IOException + { + return null; + } + + + public long getResponseContentLength() + { + return 0; + } + + + public InputStream getReponseContentStream() throws IOException + { + return null; + } + + + public boolean respond(Project project, + long contentLength, + InputStream contentStream) + throws IOException + { + return false; + } +} diff --git a/src/java/net/sf/antcontrib/antserver/commands/DisconnectCommand.java b/src/java/net/sf/antcontrib/antserver/commands/DisconnectCommand.java new file mode 100644 index 0000000..a89177b --- /dev/null +++ b/src/java/net/sf/antcontrib/antserver/commands/DisconnectCommand.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.sf.antcontrib.antserver.commands; + +import java.io.InputStream; + +import org.apache.tools.ant.Project; + +import net.sf.antcontrib.antserver.Command; + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class DisconnectCommand + extends AbstractCommand + implements Command +{ + public static Command DISCONNECT_COMMAND = + new DisconnectCommand(); + + private DisconnectCommand() + { + } + + public void validate(Project project) + { + } + + public boolean execute(Project project, + long contentLength, + InputStream content) + throws Throwable + { + return true; + } +} diff --git a/src/java/net/sf/antcontrib/antserver/commands/HelloWorldCommand.java b/src/java/net/sf/antcontrib/antserver/commands/HelloWorldCommand.java new file mode 100644 index 0000000..68f884f --- /dev/null +++ b/src/java/net/sf/antcontrib/antserver/commands/HelloWorldCommand.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.sf.antcontrib.antserver.commands; + +import java.io.InputStream; + +import org.apache.tools.ant.Project; + +import net.sf.antcontrib.antserver.Command; + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class HelloWorldCommand + extends AbstractCommand + implements Command +{ + public void validate(Project project) + { + } + + public boolean execute(Project project, + long contentLength, + InputStream content) + throws Throwable + { + project.log("Hello World", Project.MSG_ERR); + return false; + } +} diff --git a/src/java/net/sf/antcontrib/antserver/commands/PropertyContainer.java b/src/java/net/sf/antcontrib/antserver/commands/PropertyContainer.java new file mode 100644 index 0000000..9c7aaf4 --- /dev/null +++ b/src/java/net/sf/antcontrib/antserver/commands/PropertyContainer.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.sf.antcontrib.antserver.commands; + +import java.io.Serializable; + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class PropertyContainer + implements Serializable +{ + private String name; + private String value; + + public PropertyContainer() + { + super(); + } + + + public String getName() + { + return name; + } + + + public void setName(String name) + { + this.name = name; + } + + + public String getValue() + { + return value; + } + + + public void setValue(String value) + { + this.value = value; + } +} diff --git a/src/java/net/sf/antcontrib/antserver/commands/ReferenceContainer.java b/src/java/net/sf/antcontrib/antserver/commands/ReferenceContainer.java new file mode 100644 index 0000000..e755343 --- /dev/null +++ b/src/java/net/sf/antcontrib/antserver/commands/ReferenceContainer.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.sf.antcontrib.antserver.commands; + +import java.io.Serializable; + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class ReferenceContainer + implements Serializable +{ + private String refId; + private String toRefId; + + public ReferenceContainer() + { + super(); + } + + + public String getRefId() + { + return refId; + } + + + public void setRefid(String refId) + { + this.refId = refId; + } + + + public String getToRefId() + { + return toRefId; + } + + + public void setToRefId(String toRefId) + { + this.toRefId = toRefId; + } +} diff --git a/src/java/net/sf/antcontrib/antserver/commands/RunAntCommand.java b/src/java/net/sf/antcontrib/antserver/commands/RunAntCommand.java new file mode 100644 index 0000000..51b114c --- /dev/null +++ b/src/java/net/sf/antcontrib/antserver/commands/RunAntCommand.java @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.sf.antcontrib.antserver.commands; + +import java.io.File; +import java.io.InputStream; +import java.util.Enumeration; +import java.util.Vector; + +import org.apache.tools.ant.Project; +import org.apache.tools.ant.taskdefs.Ant; +import org.apache.tools.ant.taskdefs.Property; + +import net.sf.antcontrib.antserver.Command; + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class RunAntCommand + extends AbstractCommand + implements Command +{ + + private String antFile; + private String dir; + private String target; + private Vector properties; + private Vector references; + private boolean inheritall = false; + private boolean interitrefs = false; + + public RunAntCommand() + { + super(); + this.properties = new Vector(); + this.references = new Vector(); + } + + + public String getTarget() + { + return target; + } + + + public void setTarget(String target) + { + this.target = target; + } + + + public Vector getProperties() + { + return properties; + } + + + public void setProperties(Vector properties) + { + this.properties = properties; + } + + public Vector getReferences() + { + return references; + } + + + public void setReferences(Vector references) + { + this.references = references; + } + + public boolean isInheritall() + { + return inheritall; + } + + + public void setInheritall(boolean inheritall) + { + this.inheritall = inheritall; + } + + + public boolean isInteritrefs() + { + return interitrefs; + } + + + public void setInteritrefs(boolean interitrefs) + { + this.interitrefs = interitrefs; + } + + + public String getAntFile() + { + return antFile; + } + + + public void setAntFile(String antFile) + { + this.antFile = antFile; + } + + + public String getDir() + { + return dir; + } + + + public void setDir(String dir) + { + this.dir = dir; + } + + + public void addConfiguredProperty(PropertyContainer property) + { + properties.addElement(property); + } + + public void addConfiguredReference(ReferenceContainer reference) + { + references.addElement(reference); + } + + public void validate(Project project) + { + } + + public boolean execute(Project project, + long contentLength, + InputStream content) + throws Throwable + { + Ant ant = (Ant)project.createTask("ant"); + File baseDir = project.getBaseDir(); + if (dir != null) + baseDir = new File(dir); + ant.setDir(baseDir); + ant.setInheritAll(inheritall); + ant.setInheritRefs(interitrefs); + + if (target != null) + ant.setTarget(target); + + if (antFile != null) + ant.setAntfile(antFile); + + Enumeration e = properties.elements(); + PropertyContainer pc = null; + Property p = null; + while (e.hasMoreElements()) + { + pc = (PropertyContainer)e.nextElement(); + p = ant.createProperty(); + p.setName(pc.getName()); + p.setValue(pc.getValue()); + } + + e = references.elements(); + ReferenceContainer rc = null; + Ant.Reference ref = null; + while (e.hasMoreElements()) + { + rc = (ReferenceContainer)e.nextElement(); + ref = new Ant.Reference(); + ref.setRefId(rc.getRefId()); + ref.setToRefid(rc.getToRefId()); + ant.addReference(ref); + } + + ant.execute(); + + return false; + } +} diff --git a/src/java/net/sf/antcontrib/antserver/commands/RunTargetCommand.java b/src/java/net/sf/antcontrib/antserver/commands/RunTargetCommand.java new file mode 100644 index 0000000..a22e5db --- /dev/null +++ b/src/java/net/sf/antcontrib/antserver/commands/RunTargetCommand.java @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.sf.antcontrib.antserver.commands; + +import java.io.InputStream; +import java.util.Enumeration; +import java.util.Vector; + +import org.apache.tools.ant.Project; +import org.apache.tools.ant.taskdefs.Ant; +import org.apache.tools.ant.taskdefs.CallTarget; +import org.apache.tools.ant.taskdefs.Property; + +import net.sf.antcontrib.antserver.Command; + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class RunTargetCommand + extends AbstractCommand + implements Command +{ + private String target; + private Vector properties; + private Vector references; + private boolean inheritall = false; + private boolean interitrefs = false; + + public RunTargetCommand() + { + super(); + this.properties = new Vector(); + this.references = new Vector(); + } + + + public String getTarget() + { + return target; + } + + + public void setTarget(String target) + { + this.target = target; + } + + + public Vector getProperties() + { + return properties; + } + + + public void setProperties(Vector properties) + { + this.properties = properties; + } + + + + public Vector getReferences() + { + return references; + } + + + public void setReferences(Vector references) + { + this.references = references; + } + + + public boolean isInheritall() + { + return inheritall; + } + + + public void setInheritall(boolean inheritall) + { + this.inheritall = inheritall; + } + + + public boolean isInteritrefs() + { + return interitrefs; + } + + + public void setInteritrefs(boolean interitrefs) + { + this.interitrefs = interitrefs; + } + + + public void addConfiguredProperty(PropertyContainer property) + { + properties.addElement(property); + } + + + public void addConfiguredReference(ReferenceContainer reference) + { + references.addElement(reference); + } + + public void validate(Project project) + { + } + + public boolean execute(Project project, + long contentLength, + InputStream content) + throws Throwable + { + CallTarget callTarget = (CallTarget)project.createTask("antcall"); + callTarget.setInheritAll(inheritall); + callTarget.setInheritRefs(interitrefs); + + String toExecute = target; + if (toExecute == null) + toExecute = project.getDefaultTarget(); + callTarget.setTarget(toExecute); + + Enumeration e = properties.elements(); + PropertyContainer pc = null; + Property p = null; + while (e.hasMoreElements()) + { + pc = (PropertyContainer)e.nextElement(); + p = callTarget.createParam(); + p.setName(pc.getName()); + p.setValue(pc.getValue()); + } + + + e = references.elements(); + ReferenceContainer rc = null; + Ant.Reference ref = null; + while (e.hasMoreElements()) + { + rc = (ReferenceContainer)e.nextElement(); + ref = new Ant.Reference(); + ref.setRefId(rc.getRefId()); + ref.setToRefid(rc.getToRefId()); + callTarget.addReference(ref); + } + + callTarget.execute(); + + return false; + } +} diff --git a/src/java/net/sf/antcontrib/antserver/commands/SendFileCommand.java b/src/java/net/sf/antcontrib/antserver/commands/SendFileCommand.java new file mode 100644 index 0000000..3aada4d --- /dev/null +++ b/src/java/net/sf/antcontrib/antserver/commands/SendFileCommand.java @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.antserver.commands; + +import java.io.*; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; + +import net.sf.antcontrib.antserver.Command; +import net.sf.antcontrib.antserver.Util; + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class SendFileCommand + extends AbstractCommand + implements Command +{ + private long contentLength; + private String todir; + private String tofile; + private String fileBaseName; + private transient File file; + + public File getFile() + { + return file; + } + + public long getContentLength() + { + return contentLength; + } + + public InputStream getContentStream() + throws IOException + { + return new FileInputStream(file); + } + + public void setFile(File file) + { + this.file = file; + this.fileBaseName = file.getName(); + this.contentLength = file.length(); + } + + + public String getTofile() + { + return tofile; + } + + + public void setTofile(String tofile) + { + this.tofile = tofile; + } + + + public String getTodir() + { + return todir; + } + + + public void setTodir(String todir) + { + this.todir = todir; + } + + public void validate(Project project) + { + if (file == null) + throw new BuildException("Missing required attribute 'file'"); + + if (tofile == null && todir == null) + throw new BuildException("Missing both attributes 'tofile' and 'todir'" + + " at least one must be supplied"); + + /* + try + { + String realBasePath = project.getBaseDir().getCanonicalPath(); + String realGetBasePath = file.getCanonicalPath(); + if (! realGetBasePath.startsWith(realBasePath)) + throw new SecurityException("Cannot access a file that is not rooted in the project execution directory"); + } + catch (IOException e) + { + throw new BuildException(e); + } + */ + + + } + + public boolean execute(Project project, + long contentLength, + InputStream content) + throws Throwable + { + File dest = null; + + if (tofile != null) + { + dest = new File(project.getBaseDir(), tofile); + if (! new File(tofile).getCanonicalPath().startsWith(project.getBaseDir().getCanonicalPath())) { + System.out.println("throwing an exception"); + throw new SecurityException("The requested filename must be a relative path."); + } + } + else + { + dest = new File(project.getBaseDir(), todir); + dest = new File(dest, fileBaseName); + + if (! new File(todir, tofile).getCanonicalPath().startsWith(project.getBaseDir().getCanonicalPath())) { + throw new SecurityException("The requested filename must be a relative path."); + } + + } + + FileOutputStream fos = null; + + try + { + fos = new FileOutputStream(dest); + + Util.transferBytes(content, + contentLength, + fos, + false); + } + finally + { + try + { + if (fos != null) + fos.close(); + } + catch (IOException e) + { + ; // gulp; + } + } + return false; + } +} diff --git a/src/java/net/sf/antcontrib/antserver/commands/ShutdownCommand.java b/src/java/net/sf/antcontrib/antserver/commands/ShutdownCommand.java new file mode 100644 index 0000000..6dcf226 --- /dev/null +++ b/src/java/net/sf/antcontrib/antserver/commands/ShutdownCommand.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.sf.antcontrib.antserver.commands; + +import java.io.InputStream; + +import org.apache.tools.ant.Project; + +import net.sf.antcontrib.antserver.Command; + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class ShutdownCommand + extends AbstractCommand + implements Command +{ + public void validate(Project project) + { + } + + public boolean execute(Project project, + long contentLength, + InputStream content) + throws Throwable + { + return false; + } + +} diff --git a/src/java/net/sf/antcontrib/antserver/server/ConnectionBuildListener.java b/src/java/net/sf/antcontrib/antserver/server/ConnectionBuildListener.java new file mode 100644 index 0000000..39cf1e5 --- /dev/null +++ b/src/java/net/sf/antcontrib/antserver/server/ConnectionBuildListener.java @@ -0,0 +1,198 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.sf.antcontrib.antserver.server; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.Stack; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.tools.ant.BuildEvent; +import org.apache.tools.ant.BuildListener; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class ConnectionBuildListener + implements BuildListener +{ + private Document results; + private Stack elementStack; + private ThreadGroup group; + + public ConnectionBuildListener() + throws ParserConfigurationException + { + group = Thread.currentThread().getThreadGroup(); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + results = builder.newDocument(); + elementStack = new Stack(); + + Element rootElement = results.createElement("results"); + elementStack.push(rootElement); + results.appendChild(rootElement); + } + + public Document getDocument() + { + return results; + } + + public void buildStarted(BuildEvent event) + { + } + + + public void buildFinished(BuildEvent event) + { + } + + + public void targetStarted(BuildEvent event) + { + if (Thread.currentThread().getThreadGroup() != group) + return; + + Element parent = (Element)elementStack.peek(); + + Element myElement = results.createElement("target"); + myElement.setAttribute("name", event.getTarget().getName()); + parent.appendChild(myElement); + + elementStack.push(myElement); + } + + + public void targetFinished(BuildEvent event) + { + if (Thread.currentThread().getThreadGroup() != group) + return; + + Element myElement = (Element)elementStack.peek(); + + String message = event.getMessage(); + if (message != null) + myElement.setAttribute("message", message); + + Throwable t = event.getException(); + if (t != null) + { + myElement.setAttribute("status", "failure"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + PrintStream ps = new PrintStream(baos); + t.printStackTrace(ps); + ps.flush(); + String errorMessage = t.getMessage(); + String stackTrace = baos.toString(); + + Element error = results.createElement("error"); + Element errorMsgElement = results.createElement("message"); + errorMsgElement.appendChild(results.createTextNode(errorMessage)); + Element stackElement = results.createElement("stack"); + stackElement.appendChild(results.createCDATASection(stackTrace)); + error.appendChild(errorMsgElement); + error.appendChild(stackElement); + myElement.appendChild(error); + } + else + { + myElement.setAttribute("status", "success"); + } + + elementStack.pop(); + } + + + public void taskStarted(BuildEvent event) + { + + if (Thread.currentThread().getThreadGroup() != group) + return; + + Element parent = (Element)elementStack.peek(); + + Element myElement = results.createElement("task"); + myElement.setAttribute("name", event.getTask().getTaskName()); + parent.appendChild(myElement); + + elementStack.push(myElement); + } + + + public void taskFinished(BuildEvent event) + { + if (Thread.currentThread().getThreadGroup() != group) + return; + + Element myElement = (Element)elementStack.peek(); + + Throwable t = event.getException(); + if (t != null) + { + myElement.setAttribute("status", "failure"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + PrintStream ps = new PrintStream(baos); + t.printStackTrace(ps); + ps.flush(); + String errorMessage = t.getMessage(); + String stackTrace = baos.toString(); + + Element error = results.createElement("error"); + Element errorMsgElement = results.createElement("message"); + errorMsgElement.appendChild(results.createTextNode(errorMessage)); + Element stackElement = results.createElement("stack"); + stackElement.appendChild(results.createCDATASection(stackTrace)); + error.appendChild(errorMsgElement); + error.appendChild(stackElement); + myElement.appendChild(error); + } + else + { + myElement.setAttribute("status", "success"); + } + + elementStack.pop(); + } + + + public void messageLogged(BuildEvent event) + { + /* + if (Thread.currentThread().getThreadGroup() != group) + return; + + Element parentElement = (Element)elementStack.peek(); + + Element messageElement = results.createElement("message"); + messageElement.setAttribute("level", String.valueOf(event.getPriority())); + messageElement.appendChild(results.createCDATASection(event.getMessage())); + parentElement.appendChild(messageElement); + */ + } +} diff --git a/src/java/net/sf/antcontrib/antserver/server/ConnectionHandler.java b/src/java/net/sf/antcontrib/antserver/server/ConnectionHandler.java new file mode 100644 index 0000000..23169e0 --- /dev/null +++ b/src/java/net/sf/antcontrib/antserver/server/ConnectionHandler.java @@ -0,0 +1,231 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.sf.antcontrib.antserver.server; + +import java.io.*; +import java.net.Socket; + +import org.apache.tools.ant.Project; +import org.apache.xml.serialize.OutputFormat; +import org.apache.xml.serialize.XMLSerializer; + +import net.sf.antcontrib.antserver.Command; +import net.sf.antcontrib.antserver.Response; +import net.sf.antcontrib.antserver.Util; +import net.sf.antcontrib.antserver.commands.DisconnectCommand; +import net.sf.antcontrib.antserver.commands.ShutdownCommand; + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class ConnectionHandler + implements Runnable +{ + private static long nextGroupId = 0; + private ServerTask task; + private Socket socket; + private Thread thread; + private Throwable thrown; + + public ConnectionHandler(ServerTask task, Socket socket) + { + super(); + this.socket = socket; + this.task = task; + } + + public void start() + { + long gid = nextGroupId; + if (nextGroupId == Long.MAX_VALUE) + nextGroupId = 0; + else + nextGroupId++; + + ThreadGroup group = new ThreadGroup("server-tg-" + gid); + thread = new Thread(group, this); + thread.start(); + } + + public Throwable getThrown() + { + return thrown; + } + + public void run() + { + InputStream is = null; + OutputStream os = null; + + + try + { + ConnectionBuildListener cbl = null; + + is = socket.getInputStream(); + os = socket.getOutputStream(); + + ObjectInputStream ois = new ObjectInputStream(is); + ObjectOutputStream oos = new ObjectOutputStream(os); + + // Write the initial response object so that the + // object stream is initialized + oos.writeObject(new Response()); + + boolean disconnect = false; + Command inputCommand = null; + Response response = null; + + while (! disconnect) + { + task.getProject().log("Reading command object.", + Project.MSG_DEBUG); + + inputCommand = (Command) ois.readObject(); + + task.getProject().log("Executing command object: " + inputCommand, + Project.MSG_DEBUG); + + response = new Response(); + + try + { + cbl = new ConnectionBuildListener(); + task.getProject().addBuildListener(cbl); + + inputCommand.execute(task.getProject(), + inputCommand.getContentLength(), + is); + + response.setSucceeded(true); + } + catch (Throwable t) + { + response.setSucceeded(false); + response.setThrowable(t); + } + finally + { + if (cbl != null) + task.getProject().removeBuildListener(cbl); + } + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + XMLSerializer serial = new XMLSerializer(); + OutputFormat fmt = new OutputFormat(); + fmt.setOmitDocumentType(true); + fmt.setOmitXMLDeclaration(false); + serial.setOutputFormat(fmt); + serial.setOutputByteStream(baos); + serial.serialize(cbl.getDocument()); + response.setResultsXml(baos.toString()); + + task.getProject().log("Executed command object: " + inputCommand, + Project.MSG_DEBUG); + + task.getProject().log("Sending response: " + response, + Project.MSG_DEBUG); + + response.setContentLength(inputCommand.getContentLength()); + + oos.writeObject(response); + + if (inputCommand.getResponseContentLength() != 0) + { + Util.transferBytes(inputCommand.getReponseContentStream(), + inputCommand.getResponseContentLength(), + os, + true); + } + + if (inputCommand instanceof DisconnectCommand) + { + disconnect = true; + task.getProject().log("Got disconnect command", + Project.MSG_DEBUG); + } + else if (inputCommand instanceof ShutdownCommand) + { + disconnect = true; + task.getProject().log("Got shutdown command", + Project.MSG_DEBUG); + task.shutdown(); + } + + } + + } + catch (ClassNotFoundException e) + { + thrown = e; + } + catch (IOException e) + { + thrown = e; + } + catch (Throwable t) + { + thrown = t; + } + finally + { + if (is != null) + { + try + { + is.close(); + } + catch (IOException e) + { + + } + } + + if (os != null) + { + try + { + os.close(); + } + catch (IOException e) + { + + } + } + + if (socket != null) + { + try + { + socket.close(); + } + catch (IOException e) + { + + } + } + + } + } +} diff --git a/src/java/net/sf/antcontrib/antserver/server/Server.java b/src/java/net/sf/antcontrib/antserver/server/Server.java new file mode 100644 index 0000000..b0e8c56 --- /dev/null +++ b/src/java/net/sf/antcontrib/antserver/server/Server.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.sf.antcontrib.antserver.server; + +import java.io.IOException; +import java.io.InterruptedIOException; +import java.net.ServerSocket; +import java.net.Socket; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class Server + implements Runnable +{ + private ServerTask task; + private int port = 17000; + private boolean running = false; + private Thread thread = null; + + public Server(ServerTask task, int port) + { + super(); + this.task = task; + this.port = port; + } + + public void start() + throws InterruptedException + { + thread = new Thread(this); + thread.start(); + thread.join(); + } + + public void stop() + { + running = false; + } + + public void run() + { + ServerSocket server = null; + running = true; + try + { + task.getProject().log("Starting server on port: " + port, + Project.MSG_DEBUG); + try + { + server = new ServerSocket(port); + server.setSoTimeout(500); + } + catch (IOException e) + { + throw new BuildException(e); + } + + + while (running) + { + try + { + Socket clientSocket = server.accept(); + task.getProject().log("Got a client connection. Starting Handler.", + Project.MSG_DEBUG); + ConnectionHandler handler = new ConnectionHandler(task, + clientSocket); + handler.start(); + } + catch (InterruptedIOException e) + { + ; // gulp, no socket connection + } + catch (IOException e) + { + task.getProject().log(e.getMessage(), + Project.MSG_ERR); + } + } + } + finally + { + if (server != null) + { + try + { + server.close(); + server = null; + } + catch (IOException e) + { + ; // gulp + } + } + } + running = false; + + + } + +} diff --git a/src/java/net/sf/antcontrib/antserver/server/ServerTask.java b/src/java/net/sf/antcontrib/antserver/server/ServerTask.java new file mode 100644 index 0000000..74006af --- /dev/null +++ b/src/java/net/sf/antcontrib/antserver/server/ServerTask.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.sf.antcontrib.antserver.server; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; + + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class ServerTask + extends Task +{ + private Server server; + private int port = 17000; + + public ServerTask() + { + super(); + } + + + public void setPort(int port) + { + this.port = port; + } + + + public void shutdown() + { + server.stop(); + } + + public void execute() + { + try + { + server = new Server(this, port); + server.start(); + } + catch (InterruptedException e) + { + throw new BuildException(e); + } + } +} diff --git a/src/java/net/sf/antcontrib/design/Depends.java b/src/java/net/sf/antcontrib/design/Depends.java new file mode 100644 index 0000000..570efc0 --- /dev/null +++ b/src/java/net/sf/antcontrib/design/Depends.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * Created on Dec 24, 2004 + */ +package net.sf.antcontrib.design; + +/** + * + * @author dhiller + */ +public class Depends { + + private String name; + + public Depends() {} + /** + * @param name + */ + public Depends(String name) { + super(); + this.name = name; + } + /** + * @param string + */ + public void setName(String s) { + this.name = s; + } + + public String getName() { + return name; + } + + public String toString() { + return name; + } +} diff --git a/src/java/net/sf/antcontrib/design/Design.java b/src/java/net/sf/antcontrib/design/Design.java new file mode 100644 index 0000000..6da018d --- /dev/null +++ b/src/java/net/sf/antcontrib/design/Design.java @@ -0,0 +1,271 @@ +/* + * Copyright (c) 2001-2005 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.design; + +import java.io.File; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Location; +import org.apache.tools.ant.Project; + + +/* + * Created on Aug 24, 2003 + * + * To change the template for this generated file go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +/** + * FILL IN JAVADOC HERE + * + * @author Dean Hiller([email protected]) + */ +public class Design { + + private Map nameToPackage = new HashMap(); + private Map packageNameToPackage = new HashMap(); + private boolean isCircularDesign; + private Log log; + private Location location; + + private String currentClass = null; + private String currentPackageName = null; + private Package currentAliasPackage = null; + + private HashSet primitives = new HashSet(); + + public Design(boolean isCircularDesign, Log log, Location loc) { + //by default, add java as a configured package with the name java + Package p = new Package(); + p.setIncludeSubpackages(true); + p.setName("java"); + p.setNeedDeclarations(false); + p.setPackage("java"); + addConfiguredPackage(p); + + this.isCircularDesign = isCircularDesign; + this.log = log; + this.location = loc; + + primitives.add("boolean"); + + //integral types + primitives.add("byte"); + primitives.add("short"); + primitives.add("int"); + primitives.add("long"); + primitives.add("char"); + + //floating point types + primitives.add("double"); + primitives.add("float"); + } + + public Package getPackage(String nameAttribute) { + return (Package)nameToPackage.get(nameAttribute); + } + + private Package retreivePack(String thePackage) { + if(thePackage == null) + throw new IllegalArgumentException("Cannot retrieve null packages"); + + Package result = null; + String currentPackage = thePackage; + while(!Package.DEFAULT.equals(currentPackage)) { + result = (Package)packageNameToPackage.get(currentPackage); + if(result != null) { + if(currentPackage.equals(thePackage)) + return result; + else if(result.isIncludeSubpackages()) + return result; + return null; + } + currentPackage = VerifyDesignDelegate.getPackageName(currentPackage); + } + + //result must now be default package + if(result != null && result.isIncludeSubpackages()) + return result; + + return null; + } + + public void addConfiguredPackage(Package p) { + + String pack = p.getPackage(); + + Depends[] depends = p.getDepends(); + + if(depends != null && !isCircularDesign) { + //make sure all depends are in Map first + //circular references then are not a problem because they must + //put the stuff in order + for(int i = 0; i < depends.length; i++) { + Package dependsPackage = (Package)nameToPackage.get(depends[i].getName()); + + if(dependsPackage == null) { + throw new RuntimeException("package name="+p.getName()+" did not\n" + + "have "+depends[i]+" listed before it. circularDesign is off\n"+ + "so package="+p.getName()+" must be moved up in the xml file"); + } + } + } + + nameToPackage.put(p.getName(), p); + packageNameToPackage.put(p.getPackage(), p); + } + + public void verifyDependencyOk(String className) { + log.log(" className="+className, Project.MSG_DEBUG); + if(className.startsWith("L")) + className = className.substring(1, className.length()); + + String classPackage = VerifyDesignDelegate.getPackageName(className); + + //check if this is an needdeclarations="false" package, if so, the dependency is ok if it + //is not declared + log.log(" classPackage="+classPackage, Project.MSG_DEBUG); + Package p = retreivePack(classPackage); + if(p != null && !p.isNeedDeclarations()) + return; + + String pack = currentAliasPackage.getPackage(); + + log.log(" AllowedDepends="+pack, Project.MSG_DEBUG); + log.log(" CurrentDepends="+className, Project.MSG_DEBUG); + if(isClassInPackage(className, currentAliasPackage)) + return; + + Depends[] depends = currentAliasPackage.getDepends(); + + //probably want to create a regular expression out of all the depends and just match on that + //each time. for now though, just get it working and do the basic(optimize later if needed) + for(int i = 0; i < depends.length; i++) { + Depends d = depends[i]; + String name = d.getName(); + + Package temp = getPackage(name); + log.log(" AllowedDepends="+temp.getPackage(), Project.MSG_DEBUG); + log.log(" CurrentDepends="+className, Project.MSG_DEBUG); + if(isClassInPackage(className, temp)) + return; + } + + log.log("***************************************", Project.MSG_DEBUG); + log.log("***************************************", Project.MSG_DEBUG); + + throw new BuildException(Design.getErrorMessage(currentClass, className), location); + } + + public boolean isClassInPackage(String className, Package p) { + String classPackage = VerifyDesignDelegate.getPackageName(className); + if(p.isIncludeSubpackages()) { + if(className.startsWith(p.getPackage())) + return true; + } else { //if not including subpackages, the it must be the exact package. + if(classPackage.equals(p.getPackage())) + return true; + } + return false; + } + /** + * @param className + * @return whether or not this class needs to be checked. (ie. if the + * attribute needdepends=false, we don't care about this package. + */ + public boolean needEvalCurrentClass(String className) { + currentClass = className; + String packageName = VerifyDesignDelegate.getPackageName(className); +// log("class="+className, Project.MSG_DEBUG); + if(!packageName.equals(currentPackageName) || currentAliasPackage == null) { + currentPackageName = packageName; + log.log("\nEvaluating package="+currentPackageName, Project.MSG_INFO); + currentAliasPackage = retreivePack(packageName); + //DEANDO: test this scenario + if(currentAliasPackage == null) { + log.log(" class="+className, Project.MSG_VERBOSE); + throw new BuildException(getNoDefinitionError(className), location); + } + } + log.log(" class="+className, Project.MSG_VERBOSE); + + if(!className.startsWith(currentPackageName)) + throw new RuntimeException("Internal Error"); + + if(!currentAliasPackage.getNeedDepends()) + return false; + return true; + } + + public String getCurrentClass() { + return currentClass; + } + + void checkClass(String dependsOn) { + log.log(" dependsOn1="+dependsOn, Project.MSG_DEBUG); + if(dependsOn.endsWith("[]")) { + int index = dependsOn.indexOf("["); + dependsOn = dependsOn.substring(0, index); + log.log(" dependsOn2="+dependsOn, Project.MSG_DEBUG); + } + + if(primitives.contains(dependsOn)) + return; + + //Anything in java.lang package seems to be passed in as just the + //className with no package like Object, String or Class, so here we try to + //see if the name is a java.lang class.... + String tempTry = "java.lang."+dependsOn; + try { + Class c = VerifyDesign.class.getClassLoader().loadClass(tempTry); + return; + } catch(ClassNotFoundException e) { + //not found, continue on... + } + //sometimes instead of passing java.lang.String or java.lang.Object, the bcel + //passes just String or Object +// if("String".equals(dependsOn) || "Object".equals(dependsOn)) +// return; + + verifyDependencyOk(dependsOn); + + } + + public static String getErrorMessage(String className, String dependsOnClass) { + String s = "\nYou are violating your own design...." + + "\nClass = "+className+" depends on\nClass = "+dependsOnClass+ + "\nThe dependency to allow this is not defined in your design" + + "\nPackage="+VerifyDesignDelegate.getPackageName(className)+" is not defined to depend on"+ + "\nPackage="+VerifyDesignDelegate.getPackageName(dependsOnClass)+ + "\nChange the code or the design"; + return s; + } + + public static String getNoDefinitionError(String className) { + String s = "\nPackage="+VerifyDesignDelegate.getPackageName(className)+" is not defined in the design.\n"+ + "All packages with classes must be declared in the design file\n"+ + "Class found in the offending package="+className; + return s; + } + + public static String getWrapperMsg(File originalFile, String message) { + String s = "\nThe file '" + originalFile.getAbsolutePath() + "' failed due to: " + message; + return s; + } +}
\ No newline at end of file diff --git a/src/java/net/sf/antcontrib/design/DesignFileHandler.java b/src/java/net/sf/antcontrib/design/DesignFileHandler.java new file mode 100644 index 0000000..52e1bf2 --- /dev/null +++ b/src/java/net/sf/antcontrib/design/DesignFileHandler.java @@ -0,0 +1,336 @@ +/* + * Copyright (c) 2004-2005 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.design; + +import java.io.File; +import java.util.Stack; + +import org.apache.tools.ant.Location; +import org.apache.tools.ant.Project; +import org.xml.sax.Attributes; +import org.xml.sax.ContentHandler; +import org.xml.sax.InputSource; +import org.xml.sax.Locator; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + + +/** + * Handler for the root element. Its only child must be the "project" element. + */ +class DesignFileHandler implements ContentHandler { + + private final static String DESIGN = "design"; + private final static String PACKAGE = "package"; + private final static String DEPENDS = "depends"; + + private Log log = null; + private File file = null; + private boolean isCircularDesign; + private boolean needDeclarationsDefault = true; + private boolean needDependsDefault = true; + + private Design design = null; + private Package currentPackage = null; + private Stack stack = new Stack(); + private Locator locator = null; + private Location loc; + + /** + * @param CompileWithWalls + */ + DesignFileHandler(Log log, File file, boolean isCircularDesign, Location loc) { + this.log = log; + this.file = file; + this.isCircularDesign = isCircularDesign; + this.loc = loc; + } + + /** + * @param needDeclarationsDefault + */ + public void setNeedDeclarationsDefault(boolean b) { + needDeclarationsDefault = b; + } + + /** + * @param needDependsDefault + */ + public void setNeedDependsDefault(boolean b) { + needDependsDefault = b; + } + + public Design getDesign() { + return design; + } + + /** + * Resolves file: URIs relative to the build file. + * + * @param publicId The public identifer, or <code>null</code> + * if none is available. Ignored in this + * implementation. + * @param systemId The system identifier provided in the XML + * document. Will not be <code>null</code>. + */ + public InputSource resolveEntity(String publicId, + String systemId) { + log.log("publicId="+publicId+" systemId="+systemId, + Project.MSG_VERBOSE); + return null; + } + + /** + * Sets the locator in the project helper for future reference. + * + * @param locator The locator used by the parser. + * Will not be <code>null</code>. + */ + public void setDocumentLocator(Locator locator) { + this.locator = locator; + } + + /** + * @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, java.lang.String) + */ + public void startPrefixMapping(String prefix, String uri) throws SAXException { + } + + /** + * @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String) + */ + public void endPrefixMapping(String prefix) throws SAXException { + } + + /** + * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) + */ + public void startElement(String uri, String name, String qName, Attributes attrs) throws SAXException { + log.log("Parsing startElement="+name, Project.MSG_DEBUG); + if (name == null || "".equals(name)) { + // XMLReader is not-namespace aware + name = qName; + } + + try { + Object o = null; + if(name.equals(DESIGN)) { + o = handleDesign(attrs); + } else if(name.equals(PACKAGE)) { + currentPackage = handlePackage(attrs); + o = currentPackage; + } else if(name.equals(DEPENDS)) { + o = handleDepends(attrs); + } else { + throw new SAXParseException("Error in file="+file.getAbsolutePath() + +", Unexpected element \"" + name + "\"", locator); + } + stack.push(o); + } catch(RuntimeException e) { + log.log("exception111111111111111111", Project.MSG_INFO); + throw new SAXParseException("PRoblem parsing", locator, e); + } + } + + private Design handleDesign(Attributes attrs) throws SAXParseException { + if(attrs.getLength() > 0) + throw new SAXParseException("Error in file="+file.getAbsolutePath() + +", no attributes allowed for "+DESIGN+" element", locator); + else if(stack.size() > 0) + throw new SAXParseException("Error in file="+file.getAbsolutePath() + +", "+DESIGN+" cannot be a subelement of "+stack.pop(), locator); + else if(attrs.getLength() > 0) + throw new SAXParseException("Error in file="+file.getAbsolutePath() + +", "+DESIGN+" element can't have any attributes", locator); + design = new Design(isCircularDesign, log, loc); + return design; + } + + private Package handlePackage(Attributes attrs) throws SAXParseException { + if(stack.size() <= 0 || !(stack.peek() instanceof Design)) + throw new SAXParseException("Error in file="+file.getAbsolutePath() + +", "+PACKAGE+" element must be nested in a "+DESIGN+" element", locator); + + int len = attrs.getLength(); + String name = null; + String thePackage = null; + String depends = null; + String subpackages = null; + String needDeclarations = null; + String needDepends = null; + for(int i = 0; i < len; i++) { + String attrName = attrs.getLocalName(i); + + if ("".equals(attrName)) { + // XMLReader is not-namespace aware + attrName = attrs.getQName(i); + } + String value = attrs.getValue(i); + log.log("attr="+attrName+" value="+value, Project.MSG_DEBUG); + if("name".equals(attrName)) + name = value; + else if("package".equals(attrName)) + thePackage = value; + else if("depends".equals(attrName)) + depends = value; + else if("subpackages".equals(attrName)) + subpackages = value; + else if("needdeclarations".equals(attrName)) + needDeclarations = value; + else if("needdepends".equals(attrName)) + needDepends = value; + else + throw new SAXParseException("Error in file="+file.getAbsolutePath() + +"\n'"+attrName+"' attribute is an invalid attribute for the package element", locator); + } + + //set the defaults + if(subpackages == null) + subpackages = "exclude"; + if(needDeclarations == null) + needDeclarations = Boolean.toString(needDeclarationsDefault); + if(needDepends == null) + needDepends = Boolean.toString(needDependsDefault); + + //make sure every attribute had a valid value... + if(name == null) + throw new SAXParseException("Error in file="+file.getAbsolutePath() + +", package element must contain the 'name' attribute", locator); + else if(thePackage == null) + throw new SAXParseException("Error in file="+file.getAbsolutePath() + +", package element must contain the 'package' attribute", locator); + else if(!("include".equals(subpackages) || "exclude".equals(subpackages))) + throw new SAXParseException("Error in file="+file.getAbsolutePath() + +"\nThe subpackages attribute in the package element can only have a" + +"\nvalue of \"include\" or \"exclude\". value='"+subpackages+"'", locator); + else if(!("true".equals(needDeclarations) || "false".equals(needDeclarations))) + throw new SAXParseException("Error in file="+file.getAbsolutePath() + +"\nThe needdeclarations attribute in the package element can only have a" + +"\nvalue of \"true\" or \"false\". value='"+needDeclarations+"'", locator); + else if(!("true".equals(needDepends) || "false".equals(needDepends))) + throw new SAXParseException("Error in file="+file.getAbsolutePath() + +"\nThe needdepends attribute in the package element can only have a" + +"\nvalue of \"true\" or \"false\". value='"+needDepends+"'", locator); + + Package p = new Package(); + p.setName(name); + p.setPackage(thePackage); + if("exclude".equals(subpackages)) + p.setIncludeSubpackages(false); + else + p.setIncludeSubpackages(true); + if("true".equals(needDeclarations)) + p.setNeedDeclarations(true); + else + p.setNeedDeclarations(false); + if("true".equals(needDepends)) + p.setNeedDepends(true); + else + p.setNeedDepends(false); + + if(depends != null) + p.addDepends(new Depends(depends)); + return p; + } + + private Depends handleDepends(Attributes attrs) throws SAXParseException { + if(stack.size() <= 0 || !(stack.peek() instanceof Package)) + throw new SAXParseException("Error in file="+file.getAbsolutePath() + +", "+DEPENDS+" element must be nested in a "+PACKAGE+" element", locator); + else if(attrs.getLength() > 0) + throw new SAXParseException("Error in file="+file.getAbsolutePath() + +", "+DEPENDS+" element can't have any attributes", locator); + + return new Depends(); + } + + /** + * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) + */ + public void endElement(String uri, String localName, String qName) throws SAXException { + try { + Object o = stack.pop(); + if(o instanceof Package) { + Package p = (Package)o; + + Package tmp = design.getPackage(p.getName()); + if(tmp != null) + throw new SAXParseException("Error in file="+file.getAbsolutePath() + +"\nname attribute on "+PACKAGE+" element has the same\n" + +"name as another package. name=\""+p.getName()+"\" is used twice or more", locator); + + + design.addConfiguredPackage(p); + currentPackage = null; + } else if(o instanceof Depends) { + Depends d = (Depends)o; + currentPackage.addDepends(d); + } + } catch(RuntimeException e) { + throw new SAXParseException("exception", locator, e); + } + } + + /** + * @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String) + */ + public void skippedEntity(String name) throws SAXException { + } + + /** + * @see org.xml.sax.ContentHandler#startDocument() + */ + public void startDocument() throws SAXException { + } + + /** + * @see org.xml.sax.ContentHandler#endDocument() + */ + public void endDocument() throws SAXException { + } + + /** + * @see org.xml.sax.ContentHandler#characters(char[], int, int) + */ + public void characters(char[] ch, int start, int length) throws SAXException { + try { + Object o = stack.peek(); + if(o instanceof Depends) { + String s = new String(ch, start, length); + Depends d = (Depends)o; + if (d.getName() != null) + d.setName(d.getName() + s.trim()); + else + d.setName(s.trim()); + } + } catch(RuntimeException e) { + log.log("exception3333333333333333333", Project.MSG_INFO); + throw new SAXParseException("exception", locator, e); + } + } + + /** + * @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int) + */ + public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { + } + + /** + * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, java.lang.String) + */ + public void processingInstruction(String target, String data) throws SAXException { + } +}
\ No newline at end of file diff --git a/src/java/net/sf/antcontrib/design/InstructionVisitor.java b/src/java/net/sf/antcontrib/design/InstructionVisitor.java new file mode 100644 index 0000000..eb4c920 --- /dev/null +++ b/src/java/net/sf/antcontrib/design/InstructionVisitor.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.design; + +import org.apache.bcel.generic.ANEWARRAY; +import org.apache.bcel.generic.CHECKCAST; +import org.apache.bcel.generic.ConstantPoolGen; +import org.apache.bcel.generic.EmptyVisitor; +import org.apache.bcel.generic.INSTANCEOF; +import org.apache.bcel.generic.INVOKESTATIC; +import org.apache.bcel.generic.LoadInstruction; +import org.apache.bcel.generic.NEW; +import org.apache.bcel.generic.PUTSTATIC; +import org.apache.bcel.generic.Type; +import org.apache.tools.ant.Project; + + + +public class InstructionVisitor extends EmptyVisitor { + + + private ConstantPoolGen poolGen; + private Log log; + private Design design; + + /** + * @param poolGen + * @param v + */ + public InstructionVisitor(ConstantPoolGen poolGen, Log log, Design d) { + this.poolGen = poolGen; + this.log = log; + this.design = d; + } + + public void visitCHECKCAST(CHECKCAST c) { + Type t = c.getType(poolGen); + log.log(" instr(checkcast)="+t, Project.MSG_DEBUG); + String type = t.toString(); + + design.checkClass(type); + } + + public void visitLoadInstruction(LoadInstruction l) { + //log.log(" visit load", Project.MSG_DEBUG); + Type t = l.getType(poolGen); + log.log(" instr(loadinstr)="+t, Project.MSG_DEBUG); + String type = t.toString(); + + design.checkClass(type); + } + + public void visitNEW(NEW n) { + Type t= n.getType(poolGen); + log.log(" instr(new)="+t, Project.MSG_DEBUG); + String type = t.toString(); + + design.checkClass(type); + } + + public void visitANEWARRAY(ANEWARRAY n) { + Type t = n.getType(poolGen); + log.log(" instr(anewarray)="+t, Project.MSG_DEBUG); + String type = t.toString(); + + design.checkClass(type); + } + + public void visitINSTANCEOF(INSTANCEOF i) { + Type t = i.getType(poolGen); + log.log(" instr(instanceof)="+t, Project.MSG_DEBUG); + String type = t.toString(); + + design.checkClass(type); + } + public void visitINVOKESTATIC(INVOKESTATIC s) { + String t = s.getClassName(poolGen); + log.log(" instr(invokestatic)="+t, Project.MSG_DEBUG); + + design.checkClass(t); + } + + public void visitPUTSTATIC(PUTSTATIC s) { + String one = s.getClassName(poolGen); + String two = s.getFieldName(poolGen); + String three = s.getName(poolGen); + String four = s.getSignature(poolGen); + String five = s.getClassType(poolGen)+""; + String six = s.getFieldType(poolGen)+""; + log.log(" instr(putstatic)a="+one, Project.MSG_DEBUG); + log.log(" instr(putstatic)b="+two, Project.MSG_DEBUG); + log.log(" instr(putstatic)c="+three, Project.MSG_DEBUG); + log.log(" instr(putstatic)d="+four, Project.MSG_DEBUG); + log.log(" instr(putstatic)e="+five, Project.MSG_DEBUG); + log.log(" instr(putstatic)f="+six, Project.MSG_DEBUG); + + String className = s.getFieldName(poolGen); + if("staticField".equals(className)) + return; + + if(className.startsWith("class$") || className.startsWith("array$")) + ; + else return; + + log.log(" instr(putstatic)1="+className, Project.MSG_DEBUG); + className = className.substring(6, className.length()); + log.log(" instr(putstatic)2="+className, Project.MSG_DEBUG); + className = className.replace('$', '.'); + log.log(" instr(putstatic)3="+className, Project.MSG_DEBUG); + + design.checkClass(className); + } +}
\ No newline at end of file diff --git a/src/java/net/sf/antcontrib/design/Log.java b/src/java/net/sf/antcontrib/design/Log.java new file mode 100644 index 0000000..466dcdc --- /dev/null +++ b/src/java/net/sf/antcontrib/design/Log.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * Created on Dec 24, 2004 + */ +package net.sf.antcontrib.design; + +/** + * + * @author dhiller + */ +public interface Log { + + public void log(String s, int level); +} diff --git a/src/java/net/sf/antcontrib/design/Package.java b/src/java/net/sf/antcontrib/design/Package.java new file mode 100644 index 0000000..a470f8c --- /dev/null +++ b/src/java/net/sf/antcontrib/design/Package.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.design; + +import java.util.ArrayList; +import java.util.List; + + +/* + * Created on Aug 24, 2003 + * + * To change the template for this generated file go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +/** + * FILL IN JAVADOC HERE + * + * @author Dean Hiller([email protected]) + */ +public class Package { + + public final static String DEFAULT = "<default package>"; + private String name; + private String pack; + + //holds the name attribute of the package element of each + //package this package depends on. + private List depends; + private boolean isIncludeSubpackages; + private boolean needDeclarations; + private boolean needDepends; + + public void setName(String name) { + if("".equals(name)) + name = DEFAULT; + this.name = name; + } + public String getName() { + return name; + } + + public void setPackage(String pack) { + this.pack = pack; + } + + public String getPackage() { + return pack; + } + + public void addDepends(Depends d) { + if(depends == null) + depends = new ArrayList(); + depends.add(d); + } + + public Depends[] getDepends() { + Depends[] d = new Depends[0]; + if(depends == null) + return d; + return (Depends[])depends.toArray(d); + } + + /** + * @param b + */ + public void setIncludeSubpackages(boolean b) { + isIncludeSubpackages = b; + } + /** + * @return + */ + public boolean isIncludeSubpackages() { + return isIncludeSubpackages; + } + /** + * @param b + */ + public void setNeedDeclarations(boolean b) { + needDeclarations = b; + } + /** + * @return + */ + public boolean isNeedDeclarations() { + return needDeclarations; + } + /** + * @param b + */ + public void setNeedDepends(boolean b) { + needDepends = b; + } + + public boolean getNeedDepends() { + return needDepends; + } +} diff --git a/src/java/net/sf/antcontrib/design/VerifyDesign.java b/src/java/net/sf/antcontrib/design/VerifyDesign.java new file mode 100644 index 0000000..dfffd47 --- /dev/null +++ b/src/java/net/sf/antcontrib/design/VerifyDesign.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2004-2005 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.design; + +import java.io.File; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.types.Path; + +/** + * @author dhiller + */ +public class VerifyDesign + extends Task + implements Log { + + private VerifyDesignDelegate delegate; + + public VerifyDesign() { + delegate = new VerifyDesignDelegate(this); + } + + public void setJar(File f) { + delegate.setJar(f); + } + + public void setDesign(File f) { + delegate.setDesign(f); + } + + public void setCircularDesign(boolean isCircularDesign) { + delegate.setCircularDesign(isCircularDesign); + } + + public void setDeleteFiles(boolean deleteFiles) { + delegate.setDeleteFiles(deleteFiles); + } + + public void setFillInBuildException(boolean b) { + delegate.setFillInBuildException(b); + } + + public void setNeedDeclarationsDefault(boolean b) { + delegate.setNeedDeclarationsDefault(b); + } + + public void setNeedDependsDefault(boolean b) { + delegate.setNeedDependsDefault(b); + } + + public void addConfiguredPath(Path path) { + delegate.addConfiguredPath(path); + } + public void execute() + throws BuildException { + delegate.execute(); + } +} diff --git a/src/java/net/sf/antcontrib/design/VerifyDesignDelegate.java b/src/java/net/sf/antcontrib/design/VerifyDesignDelegate.java new file mode 100644 index 0000000..1c2fb01 --- /dev/null +++ b/src/java/net/sf/antcontrib/design/VerifyDesignDelegate.java @@ -0,0 +1,424 @@ +/* + * Copyright (c) 2004-2005 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.antcontrib.design; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.Vector; +import java.util.jar.JarFile; +import java.util.zip.ZipEntry; + +import org.apache.bcel.Constants; +import org.apache.bcel.classfile.ClassFormatException; +import org.apache.bcel.classfile.ClassParser; +import org.apache.bcel.classfile.Constant; +import org.apache.bcel.classfile.ConstantClass; +import org.apache.bcel.classfile.ConstantPool; +import org.apache.bcel.classfile.ConstantUtf8; +import org.apache.bcel.classfile.DescendingVisitor; +import org.apache.bcel.classfile.JavaClass; +import org.apache.bcel.classfile.Utility; +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.DirectoryScanner; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.types.FileSet; +import org.apache.tools.ant.types.Path; +import org.apache.tools.ant.types.PatternSet; +import org.apache.tools.ant.util.JAXPUtils; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; +import org.xml.sax.XMLReader; + +/** + * + * + * + * @author dhiller + * + */ + +public class VerifyDesignDelegate implements Log { + + private File designFile; + private Vector paths = new Vector(); + private boolean isCircularDesign = false; + private boolean deleteFiles = false; + private boolean fillInBuildException = false; + private boolean needDeclarationsDefault = true; + private boolean needDependsDefault = true; + + private Task task; + private Design design; + private HashSet primitives = new HashSet(); + private Vector designErrors = new Vector(); + private boolean verifiedAtLeastOne = false; + + public VerifyDesignDelegate(Task task) { + this.task = task; + primitives.add("B"); + primitives.add("C"); + primitives.add("D"); + primitives.add("F"); + primitives.add("I"); + primitives.add("J"); + primitives.add("S"); + primitives.add("Z"); + } + + public void addConfiguredPath(Path path) { +// Path newPath = new Path(task.getProject()); +// path. + + + paths.add(path); + } + + public void setJar(File f) { + Path p = (Path)task.getProject().createDataType("path"); + p.createPathElement().setLocation(f.getAbsoluteFile()); + addConfiguredPath(p); + } + + public void setDesign(File f) { + this.designFile = f; + } + + public void setCircularDesign(boolean isCircularDesign) { + this.isCircularDesign = isCircularDesign; + } + + public void setDeleteFiles(boolean deleteFiles) { + this.deleteFiles = deleteFiles; + } + + public void setFillInBuildException(boolean b) { + fillInBuildException = b; + } + + public void setNeedDeclarationsDefault(boolean b) { + needDeclarationsDefault = b; + } + + public void setNeedDependsDefault(boolean b) { + needDependsDefault = b; + } + + public void execute() { + if(!designFile.exists() || designFile.isDirectory()) + throw new BuildException("design attribute in verifydesign element specified an invalid file="+designFile); + + verifyJarFilesExist(); + + try { + XMLReader reader = JAXPUtils.getXMLReader(); + DesignFileHandler ch = new DesignFileHandler(this, designFile, isCircularDesign, task.getLocation()); + ch.setNeedDeclarationsDefault(needDeclarationsDefault); + ch.setNeedDependsDefault(needDependsDefault); + reader.setContentHandler(ch); + //reader.setEntityResolver(ch); + //reader.setErrorHandler(ch); + //reader.setDTDHandler(ch); + + log("about to start parsing file='"+designFile+"'", Project.MSG_INFO); + FileInputStream fileInput = new FileInputStream(designFile); + InputSource src = new InputSource(fileInput); + reader.parse(src); + design = ch.getDesign(); + + Enumeration pathsEnum = paths.elements(); + Path p = null; + while (pathsEnum.hasMoreElements()) { + p = (Path)pathsEnum.nextElement(); + verifyPathAdheresToDesign(design, p); + } + + if (! designErrors.isEmpty()) { + log(designErrors.size()+"Errors.", Project.MSG_WARN); + if(!fillInBuildException) + throw new BuildException("Design check failed due to previous errors"); + throwAllErrors(); + } + + } catch (SAXException e) { + maybeDeleteFiles(); + if (e.getException() != null + && e.getException() instanceof RuntimeException) + throw (RuntimeException) e.getException(); + else if (e instanceof SAXParseException) { + SAXParseException pe = (SAXParseException) e; + throw new BuildException("\nProblem parsing design file='" + + designFile + "'. \nline=" + pe.getLineNumber() + + " column=" + pe.getColumnNumber() + " Reason:\n" + + e.getMessage() + "\n", e); + } + throw new BuildException("\nProblem parsing design file='" + + designFile + "'. Reason:\n" + e, e); + } catch (IOException e) { + maybeDeleteFiles(); + throw new RuntimeException("See attached exception", e); + // throw new BuildException("IOException on design file='" + // + designFile + "'. attached:", e); + } catch(RuntimeException e) { + maybeDeleteFiles(); + throw e; + } finally { + + } + + if(!verifiedAtLeastOne) + throw new BuildException("Did not find any class or jar files to verify"); + } + //some auto builds like cruisecontrol can only report all the + //standard ant task errors and the build exceptions so here + //we need to fill in the buildexception so the errors are reported + //correctly through those tools....though, you think ant has a hook + //in that cruisecontrol is not using like LogListeners or something + private void throwAllErrors() { + String result = "Design check failed due to following errors"; + Enumeration exceptions = designErrors.elements(); + while(exceptions.hasMoreElements()) { + BuildException be = (BuildException)exceptions.nextElement(); + String message = be.getMessage(); + result += "\n" + message; + } + throw new BuildException(result); + } + + private void verifyJarFilesExist() { + Enumeration pathsEnum = paths.elements(); + Path p = null; + while (pathsEnum.hasMoreElements()) { + p = (Path)pathsEnum.nextElement(); + String files[] = p.list(); + for (int i=0;i<files.length;i++) { + File file = new File(files[i]); + + if (!file.exists()) + throw new BuildException(VisitorImpl.getNoFileMsg(file)); + } + } + } + + private void maybeDeleteFiles() { + if (deleteFiles) { + log("Deleting all class and jar files so you do not get tempted to\n" + + "use a jar that doesn't abide by the design(This option can\n" + + "be turned off if you really want)", Project.MSG_INFO); + + Enumeration pathsEnum = paths.elements(); + Path p = null; + while (pathsEnum.hasMoreElements()) { + p = (Path)pathsEnum.nextElement(); + deleteFilesInPath(p); + } + } + } + + private void deleteFilesInPath(Path p) { + String files[] = p.list(); + for (int i=0;i<files.length;i++) { + File file = new File(files[i]); + + boolean deleted = file.delete(); + if (! deleted) { + file.deleteOnExit(); + } + } + } + + private void verifyPathAdheresToDesign(Design d, Path p) throws ClassFormatException, IOException { + String files[] = p.list(); + for (int i=0;i<files.length;i++) { + File file = new File(files[i]); + if(file.isDirectory()) { + FileSet set = new FileSet(); + set.setDir(file); + set.setProject(task.getProject()); + PatternSet.NameEntry entry1 = set.createInclude(); + PatternSet.NameEntry entry2 = set.createInclude(); + PatternSet.NameEntry entry3 = set.createInclude(); + entry1.setName("**/*.class"); + entry2.setName("**/*.jar"); + entry3.setName("**/*.war"); + DirectoryScanner scanner = set.getDirectoryScanner(task.getProject()); + scanner.setBasedir(file); + String[] scannerFiles = scanner.getIncludedFiles(); + for(int j = 0; j < scannerFiles.length; j++) { + verifyPartOfPath(scannerFiles[j], new File(file, scannerFiles[j]), d); + } + } else + verifyPartOfPath(files[i], file, d); + } + } + + private void verifyPartOfPath(String fileName, File file, Design d) throws IOException { + if (fileName.endsWith(".jar") || fileName.endsWith(".war")) { + JarFile jarFile = new JarFile(file); + verifyJarAdheresToDesign(d, jarFile, file); + } else if (fileName.endsWith(".class")) { + verifyClassAdheresToDesign(d, file); + } else + throw new BuildException("Only directories, jars, wars, and class files can be supplied to verify design, not file="+file.getAbsolutePath()); + } + + private void verifyClassAdheresToDesign(Design d, File classFile) + throws ClassFormatException, IOException { + FileInputStream fis = null; + try { + fis = new FileInputStream(classFile); + verifyClassAdheresToDesign(d, fis, classFile.getAbsolutePath(), classFile); + } + finally { + try { + if (fis != null) { + fis.close(); + } + } + catch (IOException e) { + ; //doh!! + } + } + + } + + private void verifyJarAdheresToDesign(Design d, JarFile jarFile, File original) + throws ClassFormatException, IOException { + + try { + Enumeration en = jarFile.entries(); + while(en.hasMoreElements()) { + ZipEntry entry = (ZipEntry)en.nextElement(); + InputStream in = null; + if(entry.getName().endsWith(".class")) { + in = jarFile.getInputStream(entry); + try { + in = jarFile.getInputStream(entry); + verifyClassAdheresToDesign(d, in, entry.getName(), original); + } + finally { + try { + if (in != null) { + in.close(); + } + } + catch (IOException e) { + ; // doh!!! + } + } + } + } + } + finally { + try { + jarFile.close(); + } + catch (IOException e) { + ; //doh!!! + } + } + } + + private String className = ""; + + private void verifyClassAdheresToDesign(Design d, InputStream in, String name, File originalClassOrJarFile) throws ClassFormatException, IOException { + try { + verifiedAtLeastOne = true; + ClassParser parser = new ClassParser(in, name); + JavaClass javaClass = parser.parse(); + className = javaClass.getClassName(); + + if(!d.needEvalCurrentClass(className)) + return; + + ConstantPool pool = javaClass.getConstantPool(); + processConstantPool(pool); + VisitorImpl visitor = new VisitorImpl(pool, this, d, task.getLocation()); + DescendingVisitor desc = new DescendingVisitor(javaClass, visitor); + desc.visit(); + } catch(BuildException e) { + log(Design.getWrapperMsg(originalClassOrJarFile, e.getMessage()), Project.MSG_ERR); + designErrors.addElement(e); + } + } + + private void processConstantPool(ConstantPool pool) { + Constant[] constants = pool.getConstantPool(); + if(constants == null) { + log(" constants=null", Project.MSG_VERBOSE); + return; + } + + log(" constants len="+constants.length, Project.MSG_VERBOSE); + for(int i = 0; i < constants.length; i++) { + processConstant(pool, constants[i], i); + } + } + + private void processConstant(ConstantPool pool, Constant c, int i) { + if(c == null) //don't know why, but constant[0] seems to be always null. + return; + + log(" const["+i+"]="+pool.constantToString(c)+" inst="+c.getClass().getName(), Project.MSG_DEBUG); + byte tag = c.getTag(); + switch(tag) { + //reverse engineered from ConstantPool.constantToString.. + case Constants.CONSTANT_Class: + int ind = ((ConstantClass)c).getNameIndex(); + c = pool.getConstant(ind, Constants.CONSTANT_Utf8); + String className = Utility.compactClassName(((ConstantUtf8)c).getBytes(), false); + log(" classNamePre="+className, Project.MSG_DEBUG); + className = getRidOfArray(className); + String firstLetter = className.charAt(0)+""; + if(primitives.contains(firstLetter)) + return; + log(" className="+className, Project.MSG_VERBOSE); + design.checkClass(className); + break; + default: + + } + } + + private static String getRidOfArray(String className) { + while(className.startsWith("[")) + className = className.substring(1, className.length()); + return className; + } + + public static String getPackageName(String className) { + String packageName = Package.DEFAULT; + int index = className.lastIndexOf("."); + if(index > 0) + packageName = className.substring(0, index); + //DEANDO: test the else scenario here(it is a corner case)... + + return packageName; + } + + public void log(String msg, int level) { + //if(level == Project.MSG_WARN || level == Project.MSG_INFO + // || level == Project.MSG_ERR || level == Project.MSG_VERBOSE) + //VerifyDesignTest.log(msg); + task.log(msg, level); + } +} diff --git a/src/java/net/sf/antcontrib/design/VisitorImpl.java b/src/java/net/sf/antcontrib/design/VisitorImpl.java new file mode 100644 index 0000000..84aefee --- /dev/null +++ b/src/java/net/sf/antcontrib/design/VisitorImpl.java @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * Created on Jan 9, 2005 + */ +package net.sf.antcontrib.design; + +import java.io.File; + +import org.apache.bcel.Constants; +import org.apache.bcel.classfile.Code; +import org.apache.bcel.classfile.CodeException; +import org.apache.bcel.classfile.ConstantPool; +import org.apache.bcel.classfile.EmptyVisitor; +import org.apache.bcel.classfile.ExceptionTable; +import org.apache.bcel.classfile.Field; +import org.apache.bcel.classfile.JavaClass; +import org.apache.bcel.classfile.LineNumberTable; +import org.apache.bcel.classfile.LocalVariable; +import org.apache.bcel.classfile.Method; +import org.apache.bcel.classfile.Utility; +import org.apache.bcel.generic.ConstantPoolGen; +import org.apache.bcel.generic.Instruction; +import org.apache.bcel.generic.InstructionHandle; +import org.apache.bcel.generic.MethodGen; +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Location; +import org.apache.tools.ant.Project; + +class VisitorImpl extends EmptyVisitor { + + private ConstantPool pool; + private Log log; + private Design design; + private ConstantPoolGen poolGen; + private InstructionVisitor visitor; + private Location location; + + public VisitorImpl(ConstantPool pool, Log log, Design d, Location loc) { + this.pool = pool; + this.log = log; + this.design = d; + this.location = loc; + this.poolGen = new ConstantPoolGen(pool); + visitor = new InstructionVisitor(poolGen, log, d); + } + + private void log(String s, int level) { + log.log(s, level); + } + + public void visitJavaClass(JavaClass c) { + log(" super=" + c.getSuperclassName(), Project.MSG_VERBOSE); + String[] names = c.getInterfaceNames(); + + String superClass = c.getSuperclassName(); + + design.checkClass(superClass); + + for (int i = 0; i < names.length; i++) { + log(" interfaces=" + names[i], Project.MSG_VERBOSE); + design.checkClass(names[i]); + } + } + + /** + * @see org.apache.bcel.classfile.Visitor#visitField(org.apache.bcel.classfile.Field) + */ + public void visitField(Field f) { + String type = Utility.methodSignatureReturnType(f.getSignature()); + log(" field type=" + type, Project.MSG_VERBOSE); + design.checkClass(type); + + } + + /** + * @see org.apache.bcel.classfile.Visitor#visitLocalVariable(org.apache.bcel.classfile.LocalVariable) + */ + public void visitLocalVariable(LocalVariable v) { + String type = Utility.methodSignatureReturnType(v.getSignature()); + log(" localVar type=" + type, Project.MSG_VERBOSE); + design.checkClass(type); + } + + /** + * @see org.apache.bcel.classfile.Visitor#visitMethod(org.apache.bcel.classfile.Method) + */ + public void visitMethod(Method m) { + log(" method=" + m.getName(), Project.MSG_VERBOSE); + String retType = Utility.methodSignatureReturnType(m.getSignature()); + log(" method ret type=" + retType, Project.MSG_VERBOSE); + if (!"void".equals(retType)) + design.checkClass(retType); + + String[] types = Utility.methodSignatureArgumentTypes(m.getSignature()); + for (int i = 0; i < types.length; i++) { + log(" method param[" + i + "]=" + types[i], + Project.MSG_VERBOSE); + design.checkClass(types[i]); + } + + ExceptionTable excs = m.getExceptionTable(); + if (excs != null) { + types = excs.getExceptionNames(); + for (int i = 0; i < types.length; i++) { + log(" exc=" + types[i], Project.MSG_VERBOSE); + design.checkClass(types[i]); + } + } + + processInstructions(m); + } + + private void processInstructions(Method m) { + MethodGen mg = new MethodGen(m, design.getCurrentClass(), poolGen); + + if (!mg.isAbstract() && !mg.isNative()) { + InstructionHandle ih = mg.getInstructionList().getStart(); + for (; ih != null; ih = ih.getNext()) { + Instruction i = ih.getInstruction(); + log(" instr=" + i, Project.MSG_DEBUG); + // if (i instanceof BranchInstruction) { + // branch_map.put(i, ih); // memorize container + // } + + // if (ih.hasTargeters()) { + // if (i instanceof BranchInstruction) { + // _out.println(" InstructionHandle ih_" + // + ih.getPosition() + ";"); + // } else { + // _out.print(" InstructionHandle ih_" + // + ih.getPosition() + " = "); + // } + // } else { + // _out.print(" "); + // } + + // if (!visitInstruction(i)) + i.accept(visitor); + } + + // CodeExceptionGen[] handlers = mg.getExceptionHandlers(); + // + // log("handlers len="+handlers.length, Project.MSG_DEBUG); + // for (int i = 0; i < handlers.length; i++) { + // CodeExceptionGen h = handlers[i]; + // ObjectType t = h.getCatchType(); + // log("type="+t, Project.MSG_DEBUG); + // if(t != null) { + // log("type="+t.getClassName(), Project.MSG_DEBUG); + // } + // } + // updateExceptionHandlers(); + } + } + + public void visitCodeException(CodeException c) { + String s = c.toString(pool, false); + + int catch_type = c.getCatchType(); + + if (catch_type == 0) + return; + + String temp = pool.getConstantString(catch_type, + Constants.CONSTANT_Class); + String str = Utility.compactClassName(temp, false); + + log(" catch=" + str, Project.MSG_DEBUG); + design.checkClass(str); + } + + // + public void visitCode(Code c) { + LineNumberTable table = c.getLineNumberTable(); + // LocalVariableTable table = c.getLocalVariableTable(); + if (table == null) + throw new BuildException(getNoDebugMsg(design.getCurrentClass()), location); + } + + public static String getNoDebugMsg(String className) { + String s = "Class="+className+" was not compiled with the debug option(-g) and\n" + + "therefore verifydesign cannot be used on this jar. Please compile your code\n"+ + "with -g option in javac or debug=\"true\" in the ant build.xml file"; + return s; + } + + /** + * @param jarName + * @return + */ + public static String getNoFileMsg(File jarName) { + String s = "File you specified in your path(or jar attribute)='"+jarName.getAbsolutePath()+"' does not exist"; + return s; + } + + +}
\ No newline at end of file diff --git a/src/java/net/sf/antcontrib/inifile/IniFile.java b/src/java/net/sf/antcontrib/inifile/IniFile.java new file mode 100644 index 0000000..b65044a --- /dev/null +++ b/src/java/net/sf/antcontrib/inifile/IniFile.java @@ -0,0 +1,232 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.sf.antcontrib.inifile; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; +import java.util.*; + + +/**************************************************************************** + * Class representing a windows style .ini file. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * + ****************************************************************************/ + +public class IniFile +{ + private List sections; + private Map sectionMap; + + /*** + * Create a new IniFile object + */ + public IniFile() + { + super(); + this.sections = new ArrayList(); + this.sectionMap = new HashMap(); + } + + /*** + * Gets the List of IniSection objects contained in this IniFile + * @return a List of IniSection objects + */ + public List getSections() + { + return sections; + } + + + /*** + * Gets the IniSection with the given name + * @param name the name of the section + */ + public IniSection getSection(String name) + { + return (IniSection)sectionMap.get(name); + } + + /*** + * Sets an IniSection object. If a section with the given + * name already exists, it is replaced with the passed in section. + * @param section The section to set. + */ + public void setSection(IniSection section) + { + IniSection sec = (IniSection)sectionMap.get(section.getName()); + if (sec != null) + { + int idx = sections.indexOf(sec); + sections.set(idx, section); + } + else + { + sections.add(section); + } + + sectionMap.put(section.getName(), section); + } + + /*** + * Removes an entire section from the IniFile + * @param name The name of the section to remove + */ + public void removeSection(String name) + { + IniSection sec = (IniSection)sectionMap.get(name); + if (sec != null) + { + int idx = sections.indexOf(sec); + sections.remove(idx); + sectionMap.remove(name); + } + } + + /*** + * Gets a named property from a specific section + * @param section The name of the section + * @param property The name of the property + * @return The property value, or null, if either the section or property + * does not exist. + */ + public String getProperty(String section, String property) + { + String value = null; + IniSection sec = getSection(section); + if (sec != null) + { + IniProperty prop = sec.getProperty(property); + if (prop != null) + { + value = prop.getValue(); + } + } + return value; + } + + /*** + * Sets the value of a property in a given section. If the section does + * not exist, it is automatically created. + * @param section The name of the section + * @param property The name of the property + * @param value The value of the property + */ + public void setProperty(String section, String property, String value) + { + IniSection sec = getSection(section); + if (sec == null) + { + sec = new IniSection(section); + setSection(sec); + } + + sec.setProperty(new IniProperty(property, value)); + } + + /*** + * Removes a property from a section. + * @param section The name of the section + * @param property The name of the property + */ + public void removeProperty(String section, String property) + { + IniSection sec = getSection(section); + if (sec != null) + { + sec.removeProperty(property); + } + } + + /*** + * Writes the current iniFile instance to a Writer object for + * serialization. + * @param writer The writer to write to + * @throws IOException + */ + public void write(Writer writer) + throws IOException + { + Iterator it = sections.iterator(); + IniSection section = null; + while (it.hasNext()) + { + section = (IniSection)it.next(); + section.write(writer); + writer.write(System.getProperty("line.separator")); + } + } + + /*** + * Reads from a Reader into the current IniFile instance. Reading + * appends to the current instance, so if the current instance has + * properties, those properties will still exist. + * @param reader The reader to read from. + * @throws IOException + */ + public void read(Reader reader) + throws IOException + { + BufferedReader br = new BufferedReader(reader); + String line = null; + + IniSection currentSection = new IniSection("NONE"); + + while ((line = br.readLine()) != null) + { + int pos = line.indexOf('#'); + if (pos != -1) + line = line.substring(0,pos); + + pos = line.indexOf(';'); + if (pos != -1) + line = line.substring(0,pos); + + line = line.trim(); + if (line.length() > 0) + { + if(line.startsWith("[") && line.endsWith("]")) + { + String secName = line.substring(1, line.length()-1); + currentSection = getSection(secName); + if (currentSection == null) + { + currentSection = new IniSection(secName); + setSection(currentSection); + } + } + else + { + String name = line; + String value = ""; + pos = line.indexOf("="); + if (pos != -1) + { + name = line.substring(0,pos); + value = line.substring(pos+1); + } + + currentSection.setProperty(new IniProperty(name,value)); + } + } + + + } + } +} diff --git a/src/java/net/sf/antcontrib/inifile/IniFileTask.java b/src/java/net/sf/antcontrib/inifile/IniFileTask.java new file mode 100644 index 0000000..d7e44aa --- /dev/null +++ b/src/java/net/sf/antcontrib/inifile/IniFileTask.java @@ -0,0 +1,326 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.sf.antcontrib.inifile; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Iterator; +import java.util.Vector; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.Task; + + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class IniFileTask + extends Task +{ + public static abstract class IniOperation + { + private String section; + private String property; + private String ifCond; + private String unlessCond; + + public IniOperation() + { + super(); + } + + public String getSection() + { + return section; + } + + + public void setSection(String section) + { + this.section = section; + } + + + public String getProperty() + { + return property; + } + + + public void setProperty(String property) + { + this.property = property; + } + + + public void setIf(String ifCond) + { + this.ifCond = ifCond; + } + + public void setUnless(String unlessCond) + { + this.unlessCond = unlessCond; + } + + /** + * Returns true if the define's if and unless conditions + * (if any) are satisfied. + */ + public boolean isActive(org.apache.tools.ant.Project p) + { + if (ifCond != null && p.getProperty(ifCond) == null) + { + return false; + } + else if (unlessCond != null && p.getProperty(unlessCond) != null) + { + return false; + } + + return true; + } + + public void execute(Project project, IniFile iniFile) + { + if (isActive(project)) + operate(iniFile); + } + + protected abstract void operate(IniFile file); + } + + public static final class Remove + extends IniOperation + { + public Remove() + { + super(); + } + + protected void operate(IniFile file) + { + String secName = getSection(); + String propName = getProperty(); + + if (propName == null) + { + file.removeSection(secName); + } + else + { + IniSection section = file.getSection(secName); + if (section != null) + section.removeProperty(propName); + } + } + } + + + public final class Set + extends IniOperation + { + private String value; + private String operation; + + public Set() + { + super(); + } + + + public void setValue(String value) + { + this.value = value; + } + + + public void setOperation(String operation) + { + this.operation = operation; + } + + + protected void operate(IniFile file) + { + String secName = getSection(); + String propName = getProperty(); + + IniSection section = file.getSection(secName); + if (section == null) + { + section = new IniSection(secName); + file.setSection(section); + } + + if (propName != null) + { + if (operation != null) + { + if ("+".equals(operation)) + { + IniProperty prop = section.getProperty(propName); + value = prop.getValue(); + int intVal = Integer.parseInt(value) + 1; + value = String.valueOf(intVal); + } + else if ("-".equals(operation)) + { + IniProperty prop = section.getProperty(propName); + value = prop.getValue(); + int intVal = Integer.parseInt(value) - 1; + value = String.valueOf(intVal); + } + } + section.setProperty(new IniProperty(propName, value)); + } + } + + } + + private File source; + private File dest; + private Vector operations; + + public IniFileTask() + { + super(); + this.operations = new Vector(); + } + + public Set createSet() + { + Set set = new Set(); + operations.add(set); + return set; + } + + public Remove createRemove() + { + Remove remove = new Remove(); + operations.add(remove); + return remove; + } + + + public void setSource(File source) + { + this.source = source; + } + + + public void setDest(File dest) + { + this.dest = dest; + } + + + public void execute() + throws BuildException + { + if (dest == null) + throw new BuildException("You must supply a dest file to write to."); + + IniFile iniFile = null; + + try + { + iniFile = readIniFile(source); + } + catch (IOException e) + { + throw new BuildException(e); + } + + Iterator it = operations.iterator(); + IniOperation operation = null; + while (it.hasNext()) + { + operation = (IniOperation)it.next(); + operation.execute(getProject(), iniFile); + } + + FileWriter writer = null; + + try + { + try + { + writer = new FileWriter(dest); + iniFile.write(writer); + } + finally + { + try + { + if (writer != null) + writer.close(); + } + catch (IOException e) + { + ; // gulp + } + } + } + catch (IOException e) + { + throw new BuildException(e); + } + + } + + + private IniFile readIniFile(File source) + throws IOException + { + FileReader reader = null; + IniFile iniFile = new IniFile(); + + if (source == null) + return iniFile; + + try + { + reader = new FileReader(source); + iniFile.read(reader); + } + finally + { + try + { + if (reader != null) + reader.close(); + } + catch (IOException e) + { + ; // gulp + } + } + + return iniFile; + } +} diff --git a/src/java/net/sf/antcontrib/inifile/IniPart.java b/src/java/net/sf/antcontrib/inifile/IniPart.java new file mode 100644 index 0000000..b7e07f1 --- /dev/null +++ b/src/java/net/sf/antcontrib/inifile/IniPart.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.sf.antcontrib.inifile; + +import java.io.IOException; +import java.io.Writer; + + +/**************************************************************************** + * A part of an IniFile that might be written to disk. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + ****************************************************************************/ + + +public interface IniPart +{ + /*** + * Write this part of the IniFile to a writer + * @param writer The writer to write to + */ + public void write(Writer writer) + throws IOException; +} diff --git a/src/java/net/sf/antcontrib/inifile/IniProperty.java b/src/java/net/sf/antcontrib/inifile/IniProperty.java new file mode 100644 index 0000000..49a61af --- /dev/null +++ b/src/java/net/sf/antcontrib/inifile/IniProperty.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.sf.antcontrib.inifile; + +import java.io.IOException; +import java.io.Writer; + + +/**************************************************************************** + * A single property in an IniSection. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * + ****************************************************************************/ + + +public class IniProperty + implements IniPart +{ + private String name; + private String value; + + /*** + * Default constructor + */ + public IniProperty() + { + super(); + } + + /*** + * Construct an IniProperty with a certain name and value + * @param name The name of the property + * @param value The property value + */ + public IniProperty(String name, String value) + { + this(); + this.name = name; + this.value = value; + } + + /*** + * Gets the name of the property + */ + public String getName() + { + return name; + } + + /*** + * Sets the name of the property + * @param name The name of the property + */ + public void setName(String name) + { + this.name = name; + } + + + /*** + * Gets the value of the property + */ + public String getValue() + { + return value; + } + + + /*** + * Sets the value of the property + * @param value the value of the property + */ + public void setValue(String value) + { + this.value = value; + } + + + /*** + * Write this property to a writer object. + * @param writer + * @throws IOException + */ + public void write(Writer writer) + throws IOException + { + writer.write(name); + if (! name.trim().startsWith(";")) + writer.write("=" + value); + } + +} diff --git a/src/java/net/sf/antcontrib/inifile/IniSection.java b/src/java/net/sf/antcontrib/inifile/IniSection.java new file mode 100644 index 0000000..da98859 --- /dev/null +++ b/src/java/net/sf/antcontrib/inifile/IniSection.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.sf.antcontrib.inifile; + +import java.io.IOException; +import java.io.Writer; +import java.util.*; + + +/**************************************************************************** + * A section within an IniFile. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * + ****************************************************************************/ + + +public class IniSection + implements IniPart +{ + private String name; + private List properties; + private Map propertyMap; + + /*** + * Default contructor, constructs an IniSectino with no name + */ + public IniSection() + { + super(); + this.propertyMap = new HashMap(); + this.properties = new ArrayList(); + } + + + /*** + * Constructs an IniSection with the given name + * @param name The name of the section + */ + public IniSection(String name) + { + this(); + this.name = name; + } + + + /*** + * Gets a list of all properties in this section + * @return A List of IniProperty objects + */ + public List getProperties() + { + return properties; + } + + + /*** + * Gets the name of the section + */ + public String getName() + { + return name; + } + + + /*** + * Sets the name of the section + * @param name The name of the section + */ + public void setName(String name) + { + this.name = name; + } + + /*** + * Gets the property with the given name + * @param name The name of the property + */ + public IniProperty getProperty(String name) + { + return (IniProperty)propertyMap.get(name); + } + + /*** + * Sets a property, replacing the old value, if necessary. + * @param property The property to set + */ + public void setProperty(IniProperty property) + { + IniProperty prop = (IniProperty)propertyMap.get(property.getName()); + if (prop != null) + { + int idx = properties.indexOf(prop); + properties.set(idx, property); + } + else + { + properties.add(property); + } + + propertyMap.put(property.getName(), property); + } + + /*** + * Removes a property from this ection + * @param name The name of the property to remove + */ + public void removeProperty(String name) + { + IniProperty prop = (IniProperty)propertyMap.get(name); + if (prop != null) + { + int idx = properties.indexOf(prop); + properties.remove(idx); + propertyMap.remove(name); + } + } + + + public void write(Writer writer) + throws IOException + { + writer.write("[" + name + "]"); + writer.write(System.getProperty("line.separator")); + Iterator it = properties.iterator(); + IniProperty prop = null; + while (it.hasNext()) + { + prop = (IniProperty)it.next(); + prop.write(writer); + writer.write(System.getProperty("line.separator")); + } + } +} diff --git a/src/java/net/sf/antcontrib/input/GUIInputHandler.java b/src/java/net/sf/antcontrib/input/GUIInputHandler.java new file mode 100644 index 0000000..82f7abe --- /dev/null +++ b/src/java/net/sf/antcontrib/input/GUIInputHandler.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.input; + +import java.awt.*; +import javax.swing.*; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.input.InputHandler; +import org.apache.tools.ant.input.InputRequest; +import org.apache.tools.ant.input.MultipleChoiceInputRequest; + +/** + * Prompts for user input using a JOptionPane. Developed for use with + * Antelope, migrated to ant-contrib Oct 2003. + * + * @author <a href="mailto:[email protected]">Dale Anson</a> + * @version $Revision: 1.3 $ + * @since Ant 1.5 + */ +public class GUIInputHandler implements InputHandler { + + private Component parent = null; + + public GUIInputHandler() {} + + /** + * @param parent the parent component to display the input dialog. + */ + public GUIInputHandler( Component parent ) { + this.parent = parent; + } + + /** + * Prompts and requests input. May loop until a valid input has + * been entered. + */ + public void handleInput( InputRequest request ) throws BuildException { + + if ( request instanceof MultipleChoiceInputRequest ) { + String prompt = request.getPrompt(); + String title = "Select Input"; + int optionType = JOptionPane.YES_NO_OPTION; + int messageType = JOptionPane.QUESTION_MESSAGE; + Icon icon = null; + Object[] choices = ( ( MultipleChoiceInputRequest ) request ).getChoices().toArray(); + Object initialChoice = null; + do { + Object input = JOptionPane.showInputDialog(parent, prompt, + title, optionType, icon, choices, initialChoice); + if (input == null) + throw new BuildException("User cancelled."); + request.setInput(input.toString()); + } while (!request.isInputValid()); + + } + else { + do { + String input = JOptionPane.showInputDialog( parent, request.getPrompt() ); + request.setInput( input ); + } while ( !request.isInputValid() ); + } + } + +} diff --git a/src/java/net/sf/antcontrib/logic/AntCallBack.java b/src/java/net/sf/antcontrib/logic/AntCallBack.java new file mode 100644 index 0000000..cbd09dc --- /dev/null +++ b/src/java/net/sf/antcontrib/logic/AntCallBack.java @@ -0,0 +1,644 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.logic; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.lang.reflect.Method; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.StringTokenizer; +import java.util.Vector; + +import org.apache.tools.ant.*; +import org.apache.tools.ant.taskdefs.Property; +import org.apache.tools.ant.util.FileUtils; + +/** + * Identical (copy and paste, even) to the 'Ant' task, with the exception that + * properties from the new project can be copied back into the original project. + * Further modified to emulate "antcall". Build a sub-project. <pre> + * <target name="foo" depends="init"> + * <ant antfile="build.xml" target="bar" > + * <property name="property1" value="aaaaa" /> + * <property name="foo" value="baz" /> + * </ant></SPAN> </target></SPAN> <target name="bar" + * depends="init"> <echo message="prop is ${property1} + * ${foo}" /> </target> </pre> + * <p>Developed for use with Antelope, migrated to ant-contrib Oct 2003. + * <p>Credit to Costin for the original <ant> task, on which this is based. + * + * @author [email protected] + * @author Dale Anson, [email protected] + * @since Ant 1.1 + * @ant.task category="control" + */ +public class AntCallBack extends Task { + + /** the basedir where is executed the build file */ + private File dir = null; + + /** + * the build.xml file (can be absolute) in this case dir will be ignored + */ + private String antFile = null; + + /** the target to call if any */ + private String target = null; + + /** the output */ + private String output = null; + + /** should we inherit properties from the parent ? */ + private boolean inheritAll = true; + + /** should we inherit references from the parent ? */ + private boolean inheritRefs = false; + + /** the properties to pass to the new project */ + private Vector properties = new Vector(); + + /** the references to pass to the new project */ + private Vector references = new Vector(); + + /** the temporary project created to run the build file */ + private Project newProject; + + /** The stream to which output is to be written. */ + private PrintStream out = null; + + /** the name of the property to fetch from the new project */ + private String returnName = null; + + + /** + * If true, pass all properties to the new Ant project. Defaults to true. + * + * @param value The new inheritAll value + */ + public void setInheritAll( boolean value ) { + inheritAll = value; + } + + + /** + * If true, pass all references to the new Ant project. Defaults to false. + * + * @param value The new inheritRefs value + */ + public void setInheritRefs( boolean value ) { + inheritRefs = value; + } + + + /** Creates a Project instance for the project to call. */ + public void init() { + newProject = new Project(); + newProject.setJavaVersionProperty(); + newProject.addTaskDefinition( "property", + (Class)getProject().getTaskDefinitions() + .get( "property" ) ); + } + + + /** + * Called in execute or createProperty if newProject is null. <p> + * + * This can happen if the same instance of this task is run twice as + * newProject is set to null at the end of execute (to save memory and help + * the GC).</p> <p> + * + * Sets all properties that have been defined as nested property elements. + * </p> + */ + private void reinit() { + init(); + final int count = properties.size(); + for ( int i = 0; i < count; i++ ) { + Property p = (Property)properties.elementAt( i ); + Property newP = (Property)newProject.createTask( "property" ); + newP.setName( p.getName() ); + if ( p.getValue() != null ) { + newP.setValue( p.getValue() ); + } + if ( p.getFile() != null ) { + newP.setFile( p.getFile() ); + } + if ( p.getResource() != null ) { + newP.setResource( p.getResource() ); + } + if ( p.getPrefix() != null ) { + newP.setPrefix( p.getPrefix() ); + } + if ( p.getRefid() != null ) { + newP.setRefid( p.getRefid() ); + } + if ( p.getEnvironment() != null ) { + newP.setEnvironment( p.getEnvironment() ); + } + if ( p.getClasspath() != null ) { + newP.setClasspath( p.getClasspath() ); + } + properties.setElementAt( newP, i ); + } + } + + + /** + * Attaches the build listeners of the current project to the new project, + * configures a possible logfile, transfers task and data-type definitions, + * transfers properties (either all or just the ones specified as user + * properties to the current project, depending on inheritall), transfers the + * input handler. + */ + private void initializeProject() { + newProject.setInputHandler( getProject().getInputHandler() ); + + Vector listeners = getProject().getBuildListeners(); + final int count = listeners.size(); + for ( int i = 0; i < count; i++ ) { + newProject.addBuildListener( (BuildListener)listeners.elementAt( i ) ); + } + + if ( output != null ) { + File outfile = null; + if ( dir != null ) { + outfile = FileUtils.newFileUtils().resolveFile( dir, output ); + } + else { + outfile = getProject().resolveFile( output ); + } + try { + out = new PrintStream( new FileOutputStream( outfile ) ); + DefaultLogger logger = new DefaultLogger(); + logger.setMessageOutputLevel( Project.MSG_INFO ); + logger.setOutputPrintStream( out ); + logger.setErrorPrintStream( out ); + newProject.addBuildListener( logger ); + } + catch ( IOException ex ) { + log( "Ant: Can't set output to " + output ); + } + } + + Hashtable taskdefs = getProject().getTaskDefinitions(); + Enumeration et = taskdefs.keys(); + while ( et.hasMoreElements() ) { + String taskName = (String)et.nextElement(); + if ( taskName.equals( "property" ) ) { + // we have already added this taskdef in #init + continue; + } + Class taskClass = (Class)taskdefs.get( taskName ); + newProject.addTaskDefinition( taskName, taskClass ); + } + + Hashtable typedefs = getProject().getDataTypeDefinitions(); + Enumeration e = typedefs.keys(); + while ( e.hasMoreElements() ) { + String typeName = (String)e.nextElement(); + Class typeClass = (Class)typedefs.get( typeName ); + newProject.addDataTypeDefinition( typeName, typeClass ); + } + + // set user-defined properties + getProject().copyUserProperties( newProject ); + + if ( !inheritAll ) { + // set Java built-in properties separately, + // b/c we won't inherit them. + newProject.setSystemProperties(); + + } + else { + // set all properties from calling project + + Hashtable props = getProject().getProperties(); + e = props.keys(); + while ( e.hasMoreElements() ) { + String arg = e.nextElement().toString(); + if ( "basedir".equals( arg ) || "ant.file".equals( arg ) ) { + // basedir and ant.file get special treatment in execute() + continue; + } + + String value = props.get( arg ).toString(); + // don't re-set user properties, avoid the warning message + if ( newProject.getProperty( arg ) == null ) { + // no user property + newProject.setNewProperty( arg, value ); + } + } + } + } + + + /** + * Pass output sent to System.out to the new project. + * + * @param line Description of the Parameter + * @since Ant 1.5 + */ + protected void handleOutput( String line ) { + if ( newProject != null ) { + newProject.demuxOutput( line, false ); + } + else { + super.handleOutput( line ); + } + } + + + /** + * Pass output sent to System.err to the new project. + * + * @param line Description of the Parameter + * @since Ant 1.5 + */ + protected void handleErrorOutput( String line ) { + if ( newProject != null ) { + newProject.demuxOutput( line, true ); + } + else { + super.handleErrorOutput( line ); + } + } + + + /** + * Do the execution. + * + * @exception BuildException Description of the Exception + */ + public void execute() throws BuildException { + setAntfile( getProject().getProperty( "ant.file" ) ); + + File savedDir = dir; + String savedAntFile = antFile; + String savedTarget = target; + try { + if ( newProject == null ) { + reinit(); + } + + if ( ( dir == null ) && ( inheritAll ) ) { + dir = getProject().getBaseDir(); + } + + initializeProject(); + + if ( dir != null ) { + newProject.setBaseDir( dir ); + if ( savedDir != null ) { // has been set explicitly + newProject.setInheritedProperty( "basedir", + dir.getAbsolutePath() ); + } + } + else { + dir = getProject().getBaseDir(); + } + + overrideProperties(); + + if ( antFile == null ) { + throw new BuildException( "Attribute target is required.", + getLocation() ); + //antFile = "build.xml"; + } + + File file = FileUtils.newFileUtils().resolveFile( dir, antFile ); + antFile = file.getAbsolutePath(); + + log( "calling target " + ( target != null ? target : "[default]" ) + + " in build file " + antFile.toString(), + Project.MSG_VERBOSE ); + newProject.setUserProperty( "ant.file", antFile ); + ProjectHelper.configureProject( newProject, new File( antFile ) ); + + if ( target == null ) { + target = newProject.getDefaultTarget(); + } + + addReferences(); + + // Are we trying to call the target in which we are defined? + if ( newProject.getBaseDir().equals( getProject().getBaseDir() ) && + newProject.getProperty( "ant.file" ).equals( getProject().getProperty( "ant.file" ) ) && + getOwningTarget() != null && + target.equals( this.getOwningTarget().getName() ) ) { + + throw new BuildException( "antcallback task calling its own parent " + + "target" ); + } + + newProject.executeTarget( target ); + + // copy back the props if possible + if ( returnName != null ) { + StringTokenizer st = new StringTokenizer( returnName, "," ); + while ( st.hasMoreTokens() ) { + String name = st.nextToken().trim(); + String value = newProject.getUserProperty( name ); + if ( value != null ) { + getProject().setUserProperty( name, value ); + } + else { + value = newProject.getProperty( name ); + if ( value != null ) { + getProject().setProperty( name, value ); + } + } + } + } + } + finally { + // help the gc + newProject = null; + if ( output != null && out != null ) { + try { + out.close(); + } + catch ( final Exception e ) { + //ignore + } + } + dir = savedDir; + antFile = savedAntFile; + target = savedTarget; + } + } + + + /** + * Override the properties in the new project with the one explicitly defined + * as nested elements here. + * + * @exception BuildException Description of the Exception + */ + private void overrideProperties() throws BuildException { + Enumeration e = properties.elements(); + while ( e.hasMoreElements() ) { + Property p = (Property)e.nextElement(); + p.setProject( newProject ); + p.execute(); + } + getProject().copyInheritedProperties( newProject ); + } + + + /** + * Add the references explicitly defined as nested elements to the new + * project. Also copy over all references that don't override existing + * references in the new project if inheritrefs has been requested. + * + * @exception BuildException Description of the Exception + */ + private void addReferences() throws BuildException { + Hashtable thisReferences = (Hashtable)getProject().getReferences().clone(); + Hashtable newReferences = newProject.getReferences(); + Enumeration e; + if ( references.size() > 0 ) { + for ( e = references.elements(); e.hasMoreElements(); ) { + Reference ref = (Reference)e.nextElement(); + String refid = ref.getRefId(); + if ( refid == null ) { + throw new BuildException( "the refid attribute is required" + + " for reference elements" ); + } + if ( !thisReferences.containsKey( refid ) ) { + log( "Parent project doesn't contain any reference '" + + refid + "'", + Project.MSG_WARN ); + continue; + } + + thisReferences.remove( refid ); + String toRefid = ref.getToRefid(); + if ( toRefid == null ) { + toRefid = refid; + } + copyReference( refid, toRefid ); + } + } + + // Now add all references that are not defined in the + // subproject, if inheritRefs is true + if ( inheritRefs ) { + for ( e = thisReferences.keys(); e.hasMoreElements(); ) { + String key = (String)e.nextElement(); + if ( newReferences.containsKey( key ) ) { + continue; + } + copyReference( key, key ); + } + } + } + + + /** + * Try to clone and reconfigure the object referenced by oldkey in the parent + * project and add it to the new project with the key newkey. <p> + * + * If we cannot clone it, copy the referenced object itself and keep our + * fingers crossed.</p> + * + * @param oldKey Description of the Parameter + * @param newKey Description of the Parameter + */ + private void copyReference( String oldKey, String newKey ) { + Object orig = getProject().getReference( oldKey ); + Class c = orig.getClass(); + Object copy = orig; + try { + Method cloneM = c.getMethod( "clone", new Class[0] ); + if ( cloneM != null ) { + copy = cloneM.invoke( orig, new Object[0] ); + } + } + catch ( Exception e ) { + // not Clonable + } + + if ( copy instanceof ProjectComponent ) { + ( (ProjectComponent)copy ).setProject( newProject ); + } + else { + try { + Method setProjectM = + c.getMethod( "setProject", new Class[]{Project.class} ); + if ( setProjectM != null ) { + setProjectM.invoke( copy, new Object[]{newProject} ); + } + } + catch ( NoSuchMethodException e ) { + // ignore this if the class being referenced does not have + // a set project method. + } + catch ( Exception e2 ) { + String msg = "Error setting new project instance for " + + "reference with id " + oldKey; + throw new BuildException( msg, e2, getLocation() ); + } + } + newProject.addReference( newKey, copy ); + } + + + /** + * The directory to use as a base directory for the new Ant project. Defaults + * to the current project's basedir, unless inheritall has been set to false, + * in which case it doesn't have a default value. This will override the + * basedir setting of the called project. + * + * @param d The new dir value + */ + public void setDir( File d ) { + this.dir = d; + } + + + /** + * The build file to use. Defaults to "build.xml". This file is expected to + * be a filename relative to the dir attribute given. + * + * @param s The new antfile value + */ + public void setAntfile( String s ) { + // @note: it is a string and not a file to handle relative/absolute + // otherwise a relative file will be resolved based on the current + // basedir. + this.antFile = s; + } + + + /** + * The target of the new Ant project to execute. Defaults to the new + * project's default target. + * + * @param s The new target value + */ + public void setTarget( String s ) { + this.target = s; + } + + + /** + * Filename to write the output to. This is relative to the value of the dir + * attribute if it has been set or to the base directory of the current + * project otherwise. + * + * @param s The new output value + */ + public void setOutput( String s ) { + this.output = s; + } + + + /** + * Property to pass to the new project. The property is passed as a 'user + * property' + * + * @return Description of the Return Value + */ + public Property createProperty() { + if ( newProject == null ) { + reinit(); + } + /* + * Property p = new Property( true, getProject() ); + */ + Property p = new Property(); + p.setProject( newProject ); + p.setTaskName( "property" ); + properties.addElement( p ); + return p; + } + + + /** + * Property to pass to the invoked target. + */ + public Property createParam() { + return createProperty(); + } + + /** + * Set the property or properties that are set in the new project to be + * transfered back to the original project. As with all properties, if the + * property already exists in the original project, it will not be overridden + * by a different value from the new project. + * + * @param r the name of a property in the new project to set in the original + * project. This may be a comma separate list of properties. + */ + public void setReturn( String r ) { + returnName = r; + } + + + /** + * Reference element identifying a data type to carry over to the new + * project. + * + * @param r The feature to be added to the Reference attribute + */ + public void addReference( Reference r ) { + references.addElement( r ); + } + + + /** + * Helper class that implements the nested <reference> element of + * <ant> and <antcall>. + * + * @author danson + */ + public static class Reference + extends org.apache.tools.ant.types.Reference { + + /** Creates a reference to be configured by Ant */ + public Reference() { + super(); + } + + + private String targetid = null; + + + /** + * Set the id that this reference to be stored under in the new project. + * + * @param targetid the id under which this reference will be passed to + * the new project + */ + public void setToRefid( String targetid ) { + this.targetid = targetid; + } + + + /** + * Get the id under which this reference will be stored in the new project + * + * @return the id of the reference in the new project. + */ + public String getToRefid() { + return targetid; + } + } +} + diff --git a/src/java/net/sf/antcontrib/logic/AntFetch.java b/src/java/net/sf/antcontrib/logic/AntFetch.java new file mode 100644 index 0000000..fa2b13f --- /dev/null +++ b/src/java/net/sf/antcontrib/logic/AntFetch.java @@ -0,0 +1,638 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.logic; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.lang.reflect.Method; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.StringTokenizer; +import java.util.Vector; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.BuildListener; +import org.apache.tools.ant.DefaultLogger; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.ProjectComponent; +import org.apache.tools.ant.ProjectHelper; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.taskdefs.Property; +import org.apache.tools.ant.util.FileUtils; + +/** + * Identical (copy and paste, even) to the 'Ant' task, with the exception that + * properties from the new project can be copied back into the original project. + * Build a sub-project. <pre> + * <target name="foo" depends="init"> + * <ant antfile="build.xml" target="bar" > + * <property name="property1" value="aaaaa" /> + * <property name="foo" value="baz" /> + * </ant></SPAN> </target></SPAN> <target name="bar" + * depends="init"> <echo message="prop is ${property1} + * ${foo}" /> </target> </pre> + * <p>Developed for use with Antelope, migrated to ant-contrib Oct 2003. + * <p>Credit to Costin for the original <ant> task, on which this is based. + * + * @author [email protected] + * @author Dale Anson, [email protected] + * @since Ant 1.1 + * @ant.task category="control" + */ +public class AntFetch extends Task { + + /** the basedir where is executed the build file */ + private File dir = null; + + /** + * the build.xml file (can be absolute) in this case dir will be ignored + */ + private String antFile = null; + + /** the target to call if any */ + private String target = null; + + /** the output */ + private String output = null; + + /** should we inherit properties from the parent ? */ + private boolean inheritAll = true; + + /** should we inherit references from the parent ? */ + private boolean inheritRefs = false; + + /** the properties to pass to the new project */ + private Vector properties = new Vector(); + + /** the references to pass to the new project */ + private Vector references = new Vector(); + + /** the temporary project created to run the build file */ + private Project newProject; + + /** The stream to which output is to be written. */ + private PrintStream out = null; + + /** the name of the property to fetch from the new project */ + private String returnName = null; + + + /** + * If true, pass all properties to the new Ant project. Defaults to true. + * + * @param value The new inheritAll value + */ + public void setInheritAll( boolean value ) { + inheritAll = value; + } + + + /** + * If true, pass all references to the new Ant project. Defaults to false. + * + * @param value The new inheritRefs value + */ + public void setInheritRefs( boolean value ) { + inheritRefs = value; + } + + + /** Creates a Project instance for the project to call. */ + public void init() { + newProject = new Project(); + newProject.setJavaVersionProperty(); + newProject.addTaskDefinition( "property", + (Class)getProject().getTaskDefinitions() + .get( "property" ) ); + } + + + /** + * Called in execute or createProperty if newProject is null. <p> + * + * This can happen if the same instance of this task is run twice as + * newProject is set to null at the end of execute (to save memory and help + * the GC).</p> <p> + * + * Sets all properties that have been defined as nested property elements. + * </p> + */ + private void reinit() { + init(); + final int count = properties.size(); + for ( int i = 0; i < count; i++ ) { + Property p = (Property)properties.elementAt( i ); + Property newP = (Property)newProject.createTask( "property" ); + newP.setName( p.getName() ); + if ( p.getValue() != null ) { + newP.setValue( p.getValue() ); + } + if ( p.getFile() != null ) { + newP.setFile( p.getFile() ); + } + if ( p.getResource() != null ) { + newP.setResource( p.getResource() ); + } + if ( p.getPrefix() != null ) { + newP.setPrefix( p.getPrefix() ); + } + if ( p.getRefid() != null ) { + newP.setRefid( p.getRefid() ); + } + if ( p.getEnvironment() != null ) { + newP.setEnvironment( p.getEnvironment() ); + } + if ( p.getClasspath() != null ) { + newP.setClasspath( p.getClasspath() ); + } + properties.setElementAt( newP, i ); + } + } + + + /** + * Attaches the build listeners of the current project to the new project, + * configures a possible logfile, transfers task and data-type definitions, + * transfers properties (either all or just the ones specified as user + * properties to the current project, depending on inheritall), transfers the + * input handler. + */ + private void initializeProject() { + newProject.setInputHandler( getProject().getInputHandler() ); + + Vector listeners = getProject().getBuildListeners(); + final int count = listeners.size(); + for ( int i = 0; i < count; i++ ) { + newProject.addBuildListener( (BuildListener)listeners.elementAt( i ) ); + } + + if ( output != null ) { + File outfile = null; + if ( dir != null ) { + outfile = FileUtils.newFileUtils().resolveFile( dir, output ); + } + else { + outfile = getProject().resolveFile( output ); + } + try { + out = new PrintStream( new FileOutputStream( outfile ) ); + DefaultLogger logger = new DefaultLogger(); + logger.setMessageOutputLevel( Project.MSG_INFO ); + logger.setOutputPrintStream( out ); + logger.setErrorPrintStream( out ); + newProject.addBuildListener( logger ); + } + catch ( IOException ex ) { + log( "Ant: Can't set output to " + output ); + } + } + + Hashtable taskdefs = getProject().getTaskDefinitions(); + Enumeration et = taskdefs.keys(); + while ( et.hasMoreElements() ) { + String taskName = (String)et.nextElement(); + if ( taskName.equals( "property" ) ) { + // we have already added this taskdef in #init + continue; + } + Class taskClass = (Class)taskdefs.get( taskName ); + newProject.addTaskDefinition( taskName, taskClass ); + } + + Hashtable typedefs = getProject().getDataTypeDefinitions(); + Enumeration e = typedefs.keys(); + while ( e.hasMoreElements() ) { + String typeName = (String)e.nextElement(); + Class typeClass = (Class)typedefs.get( typeName ); + newProject.addDataTypeDefinition( typeName, typeClass ); + } + + // set user-defined properties + getProject().copyUserProperties( newProject ); + + if ( !inheritAll ) { + // set Java built-in properties separately, + // b/c we won't inherit them. + newProject.setSystemProperties(); + + } + else { + // set all properties from calling project + + Hashtable props = getProject().getProperties(); + e = props.keys(); + while ( e.hasMoreElements() ) { + String arg = e.nextElement().toString(); + if ( "basedir".equals( arg ) || "ant.file".equals( arg ) ) { + // basedir and ant.file get special treatment in execute() + continue; + } + + String value = props.get( arg ).toString(); + // don't re-set user properties, avoid the warning message + if ( newProject.getProperty( arg ) == null ) { + // no user property + newProject.setNewProperty( arg, value ); + } + } + } + } + + + /** + * Pass output sent to System.out to the new project. + * + * @param line Description of the Parameter + * @since Ant 1.5 + */ + protected void handleOutput( String line ) { + if ( newProject != null ) { + newProject.demuxOutput( line, false ); + } + else { + super.handleOutput( line ); + } + } + + + /** + * Pass output sent to System.err to the new project. + * + * @param line Description of the Parameter + * @since Ant 1.5 + */ + protected void handleErrorOutput( String line ) { + if ( newProject != null ) { + newProject.demuxOutput( line, true ); + } + else { + super.handleErrorOutput( line ); + } + } + + + /** + * Do the execution. + * + * @exception BuildException Description of the Exception + */ + public void execute() throws BuildException { + File savedDir = dir; + String savedAntFile = antFile; + String savedTarget = target; + try { + if ( newProject == null ) { + reinit(); + } + + if ( ( dir == null ) && ( inheritAll ) ) { + dir = getProject().getBaseDir(); + } + + initializeProject(); + + if ( dir != null ) { + newProject.setBaseDir( dir ); + if ( savedDir != null ) { // has been set explicitly + newProject.setInheritedProperty( "basedir", + dir.getAbsolutePath() ); + } + } + else { + dir = getProject().getBaseDir(); + } + + overrideProperties(); + + if ( antFile == null ) { + antFile = "build.xml"; + } + + File file = FileUtils.newFileUtils().resolveFile( dir, antFile ); + antFile = file.getAbsolutePath(); + + log( "calling target " + ( target != null ? target : "[default]" ) + + " in build file " + antFile.toString(), + Project.MSG_VERBOSE ); + newProject.setUserProperty( "ant.file", antFile ); + ProjectHelper.configureProject( newProject, new File( antFile ) ); + + if ( target == null ) { + target = newProject.getDefaultTarget(); + } + + addReferences(); + + // Are we trying to call the target in which we are defined? + if ( newProject.getBaseDir().equals( getProject().getBaseDir() ) && + newProject.getProperty( "ant.file" ).equals( getProject().getProperty( "ant.file" ) ) && + getOwningTarget() != null && + target.equals( this.getOwningTarget().getName() ) ) { + + throw new BuildException( "ant task calling its own parent " + + "target" ); + } + + newProject.executeTarget( target ); + + // copy back the props if possible + if ( returnName != null ) { + StringTokenizer st = new StringTokenizer( returnName, "," ); + while ( st.hasMoreTokens() ) { + String name = st.nextToken().trim(); + String value = newProject.getUserProperty( name ); + if ( value != null ) { + getProject().setUserProperty( name, value ); + } + else { + value = newProject.getProperty( name ); + if ( value != null ) { + getProject().setProperty( name, value ); + } + } + } + } + } + finally { + // help the gc + newProject = null; + if ( output != null && out != null ) { + try { + out.close(); + } + catch ( final Exception e ) { + //ignore + } + } + dir = savedDir; + antFile = savedAntFile; + target = savedTarget; + } + } + + + /** + * Override the properties in the new project with the one explicitly defined + * as nested elements here. + * + * @exception BuildException Description of the Exception + */ + private void overrideProperties() throws BuildException { + Enumeration e = properties.elements(); + while ( e.hasMoreElements() ) { + Property p = (Property)e.nextElement(); + p.setProject( newProject ); + p.execute(); + } + getProject().copyInheritedProperties( newProject ); + } + + + /** + * Add the references explicitly defined as nested elements to the new + * project. Also copy over all references that don't override existing + * references in the new project if inheritrefs has been requested. + * + * @exception BuildException Description of the Exception + */ + private void addReferences() throws BuildException { + Hashtable thisReferences = (Hashtable)getProject().getReferences().clone(); + Hashtable newReferences = newProject.getReferences(); + Enumeration e; + if ( references.size() > 0 ) { + for ( e = references.elements(); e.hasMoreElements(); ) { + Reference ref = (Reference)e.nextElement(); + String refid = ref.getRefId(); + if ( refid == null ) { + throw new BuildException( "the refid attribute is required" + + " for reference elements" ); + } + if ( !thisReferences.containsKey( refid ) ) { + log( "Parent project doesn't contain any reference '" + + refid + "'", + Project.MSG_WARN ); + continue; + } + + thisReferences.remove( refid ); + String toRefid = ref.getToRefid(); + if ( toRefid == null ) { + toRefid = refid; + } + copyReference( refid, toRefid ); + } + } + + // Now add all references that are not defined in the + // subproject, if inheritRefs is true + if ( inheritRefs ) { + for ( e = thisReferences.keys(); e.hasMoreElements(); ) { + String key = (String)e.nextElement(); + if ( newReferences.containsKey( key ) ) { + continue; + } + copyReference( key, key ); + } + } + } + + + /** + * Try to clone and reconfigure the object referenced by oldkey in the parent + * project and add it to the new project with the key newkey. <p> + * + * If we cannot clone it, copy the referenced object itself and keep our + * fingers crossed.</p> + * + * @param oldKey Description of the Parameter + * @param newKey Description of the Parameter + */ + private void copyReference( String oldKey, String newKey ) { + Object orig = getProject().getReference( oldKey ); + Class c = orig.getClass(); + Object copy = orig; + try { + Method cloneM = c.getMethod( "clone", new Class[0] ); + if ( cloneM != null ) { + copy = cloneM.invoke( orig, new Object[0] ); + } + } + catch ( Exception e ) { + // not Clonable + } + + if ( copy instanceof ProjectComponent ) { + ( (ProjectComponent)copy ).setProject( newProject ); + } + else { + try { + Method setProjectM = + c.getMethod( "setProject", new Class[]{Project.class} ); + if ( setProjectM != null ) { + setProjectM.invoke( copy, new Object[]{newProject} ); + } + } + catch ( NoSuchMethodException e ) { + // ignore this if the class being referenced does not have + // a set project method. + } + catch ( Exception e2 ) { + String msg = "Error setting new project instance for " + + "reference with id " + oldKey; + throw new BuildException( msg, e2, getLocation() ); + } + } + newProject.addReference( newKey, copy ); + } + + + /** + * The directory to use as a base directory for the new Ant project. Defaults + * to the current project's basedir, unless inheritall has been set to false, + * in which case it doesn't have a default value. This will override the + * basedir setting of the called project. + * + * @param d The new dir value + */ + public void setDir( File d ) { + this.dir = d; + } + + + /** + * The build file to use. Defaults to "build.xml". This file is expected to + * be a filename relative to the dir attribute given. + * + * @param s The new antfile value + */ + public void setAntfile( String s ) { + // @note: it is a string and not a file to handle relative/absolute + // otherwise a relative file will be resolved based on the current + // basedir. + this.antFile = s; + } + + + /** + * The target of the new Ant project to execute. Defaults to the new + * project's default target. + * + * @param s The new target value + */ + public void setTarget( String s ) { + this.target = s; + } + + + /** + * Filename to write the output to. This is relative to the value of the dir + * attribute if it has been set or to the base directory of the current + * project otherwise. + * + * @param s The new output value + */ + public void setOutput( String s ) { + this.output = s; + } + + + /** + * Property to pass to the new project. The property is passed as a 'user + * property' + * + * @return Description of the Return Value + */ + public Property createProperty() { + if ( newProject == null ) { + reinit(); + } + /* + * Property p = new Property( true, getProject() ); + */ + Property p = new Property(); + p.setProject( newProject ); + p.setTaskName( "property" ); + properties.addElement( p ); + return p; + } + + + /** + * Set the property or properties that are set in the new project to be + * transfered back to the original project. As with all properties, if the + * property already exists in the original project, it will not be overridden + * by a different value from the new project. + * + * @param r the name of a property in the new project to set in the original + * project. This may be a comma separate list of properties. + */ + public void setReturn( String r ) { + returnName = r; + } + + + /** + * Reference element identifying a data type to carry over to the new + * project. + * + * @param r The feature to be added to the Reference attribute + */ + public void addReference( Reference r ) { + references.addElement( r ); + } + + + /** + * Helper class that implements the nested <reference> element of + * <ant> and <antcall>. + * + * @author danson + */ + public static class Reference + extends org.apache.tools.ant.types.Reference { + + /** Creates a reference to be configured by Ant */ + public Reference() { + super(); + } + + + private String targetid = null; + + + /** + * Set the id that this reference to be stored under in the new project. + * + * @param targetid the id under which this reference will be passed to + * the new project + */ + public void setToRefid( String targetid ) { + this.targetid = targetid; + } + + + /** + * Get the id under which this reference will be stored in the new project + * + * @return the id of the reference in the new project. + */ + public String getToRefid() { + return targetid; + } + } +} diff --git a/src/java/net/sf/antcontrib/logic/Assert.java b/src/java/net/sf/antcontrib/logic/Assert.java new file mode 100644 index 0000000..38ac6e8 --- /dev/null +++ b/src/java/net/sf/antcontrib/logic/Assert.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.logic; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.TaskContainer; +import org.apache.tools.ant.taskdefs.Exit; +import org.apache.tools.ant.taskdefs.Sequential; +import org.apache.tools.ant.taskdefs.condition.Condition; +import org.apache.tools.ant.taskdefs.condition.ConditionBase; + + +/** + * + */ +public class Assert + extends ConditionBase + implements TaskContainer { + + private List tasks = new ArrayList(); + private String message; + private boolean failOnError; + + + public void setFailOnError(boolean failOnError) { + this.failOnError = failOnError; + } + + public void setMessage(String message) { + this.message = message; + } + + public void addTask(Task task) { + tasks.add(task); + } + + public void execute() { + if (countConditions() == 0) { + throw new BuildException("There is no condition specified."); + } + else if (countConditions() > 1) { + throw new BuildException("There must be exactly one condition specified."); + } + + Sequential sequential = (Sequential) getProject().createTask("sequential"); + Condition c = (Condition) getConditions().nextElement(); + if (! c.eval()) { + if (failOnError) { + Exit fail = (Exit) getProject().createTask("fail"); + fail.setMessage(message); + sequential.addTask(fail); + } + } + else { + Iterator it = tasks.iterator(); + while (it.hasNext()) { + sequential.addTask((Task)it.next()); + } + } + } + + +} diff --git a/src/java/net/sf/antcontrib/logic/ForEach.java b/src/java/net/sf/antcontrib/logic/ForEach.java new file mode 100644 index 0000000..ad822f0 --- /dev/null +++ b/src/java/net/sf/antcontrib/logic/ForEach.java @@ -0,0 +1,423 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.logic; + +import java.io.File; +import java.util.Enumeration; +import java.util.StringTokenizer; +import java.util.Vector; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.TaskContainer; +import org.apache.tools.ant.taskdefs.Ant; +import org.apache.tools.ant.taskdefs.CallTarget; +import org.apache.tools.ant.taskdefs.Property; +import org.apache.tools.ant.types.FileSet; +import org.apache.tools.ant.types.Mapper; +import org.apache.tools.ant.types.Path; +import org.apache.tools.ant.util.FileNameMapper; + +import net.sf.antcontrib.util.ThreadPool; +import net.sf.antcontrib.util.ThreadPoolThread; + +/*** + * Task definition for the foreach task. The foreach task iterates + * over a list, a list of filesets, or both. + * + * <pre> + * + * Usage: + * + * Task declaration in the project: + * <code> + * <taskdef name="foreach" classname="net.sf.antcontrib.logic.ForEach" /> + * </code> + * + * Call Syntax: + * <code> + * <foreach list="values" target="targ" param="name" + * [parallel="true|false"] + * [delimiter="delim"] /> + * </code> + * + * Attributes: + * list --> The list of values to process, with the delimiter character, + * indicated by the "delim" attribute, separating each value + * target --> The target to call for each token, passing the token as the + * parameter with the name indicated by the "param" attribute + * param --> The name of the parameter to pass the tokens in as to the + * target + * delimiter --> The delimiter string that separates the values in the "list" + * parameter. The default is "," + * parallel --> Should all targets execute in parallel. The default is false. + * trim --> Should we trim the list item before calling the target? + * + * </pre> + * @author <a href="mailto:[email protected]">Matthew Inger</a> + */ +public class ForEach extends Task +{ + private String list; + private String param; + private String delimiter; + private String target; + private boolean inheritAll; + private boolean inheritRefs; + private Vector params; + private Vector references; + private Path currPath; + private boolean parallel; + private boolean trim; + private int maxThreads; + private Mapper mapper; + + /*** + * Default Constructor + */ + public ForEach() + { + super(); + this.list = null; + this.param = null; + this.delimiter = ","; + this.target = null; + this.inheritAll = false; + this.inheritRefs = false; + this.params = new Vector(); + this.references = new Vector(); + this.parallel = false; + this.maxThreads = 5; + } + + private void executeParallel(Vector tasks) + { + ThreadPool pool = new ThreadPool(maxThreads); + Enumeration e = tasks.elements(); + Runnable r = null; + Vector threads = new Vector(); + + // start each task in it's own thread, using the + // pool to ensure that we don't exceed the maximum + // amount of threads + while (e.hasMoreElements()) + { + // Create the Runnable object + final Task task = (Task)e.nextElement(); + r = new Runnable() + { + public void run() + { + task.execute(); + } + }; + + // Get a thread, and start the task. + // If there is no thread available, this will + // block until one becomes available + try + { + ThreadPoolThread tpt = pool.borrowThread(); + tpt.setRunnable(r); + tpt.start(); + threads.addElement(tpt); + } + catch (Exception ex) + { + throw new BuildException(ex); + } + + } + + // Wait for all threads to finish before we + // are allowed to return. + Enumeration te = threads.elements(); + Thread t= null; + while (te.hasMoreElements()) + { + t = (Thread)te.nextElement(); + if (t.isAlive()) + { + try + { + t.join(); + } + catch (InterruptedException ex) + { + throw new BuildException(ex); + } + } + } + } + + private void executeSequential(Vector tasks) + { + TaskContainer tc = (TaskContainer) getProject().createTask("sequential"); + Enumeration e = tasks.elements(); + Task t = null; + while (e.hasMoreElements()) + { + t = (Task)e.nextElement(); + tc.addTask(t); + } + + ((Task)tc).execute(); + } + + public void execute() + throws BuildException + { + if (list == null && currPath == null) { + throw new BuildException("You must have a list or path to iterate through"); + } + if (param == null) + throw new BuildException("You must supply a property name to set on each iteration in param"); + if (target == null) + throw new BuildException("You must supply a target to perform"); + + Vector values = new Vector(); + + // Take Care of the list attribute + if (list != null) + { + StringTokenizer st = new StringTokenizer(list, delimiter); + + while (st.hasMoreTokens()) + { + String tok = st.nextToken(); + if (trim) tok = tok.trim(); + values.addElement(tok); + } + } + + String[] pathElements = new String[0]; + if (currPath != null) { + pathElements = currPath.list(); + } + + for (int i=0;i<pathElements.length;i++) + { + if (mapper != null) + { + FileNameMapper m = mapper.getImplementation(); + String mapped[] = m.mapFileName(pathElements[i]); + for (int j=0;j<mapped.length;j++) + values.addElement(mapped[j]); + } + else + { + values.addElement(new File(pathElements[i])); + } + } + + Vector tasks = new Vector(); + + int sz = values.size(); + CallTarget ct = null; + Object val = null; + Property p = null; + + for (int i = 0; i < sz; i++) { + val = values.elementAt(i); + ct = createCallTarget(); + p = ct.createParam(); + p.setName(param); + + if (val instanceof File) + p.setLocation((File)val); + else + p.setValue((String)val); + + tasks.addElement(ct); + } + + if (parallel && maxThreads > 1) + { + executeParallel(tasks); + } + else + { + executeSequential(tasks); + } + } + + public void setTrim(boolean trim) + { + this.trim = trim; + } + + public void setList(String list) + { + this.list = list; + } + + public void setDelimiter(String delimiter) + { + this.delimiter = delimiter; + } + + public void setParam(String param) + { + this.param = param; + } + + public void setTarget(String target) + { + this.target = target; + } + + public void setParallel(boolean parallel) + { + this.parallel = parallel; + } + + /** + * Corresponds to <code><antcall></code>'s <code>inheritall</code> + * attribute. + */ + public void setInheritall(boolean b) { + this.inheritAll = b; + } + + /** + * Corresponds to <code><antcall></code>'s <code>inheritrefs</code> + * attribute. + */ + public void setInheritrefs(boolean b) { + this.inheritRefs = b; + } + + + /*** + * Set the maximum amount of threads we're going to allow + * at once to execute + * @param maxThreads + */ + public void setMaxThreads(int maxThreads) + { + this.maxThreads = maxThreads; + } + + + /** + * Corresponds to <code><antcall></code>'s nested + * <code><param></code> element. + */ + public void addParam(Property p) { + params.addElement(p); + } + + /** + * Corresponds to <code><antcall></code>'s nested + * <code><reference></code> element. + */ + public void addReference(Ant.Reference r) { + references.addElement(r); + } + + /** + * @deprecated Use createPath instead. + */ + public void addFileset(FileSet set) + { + log("The nested fileset element is deprectated, use a nested path " + + "instead", + Project.MSG_WARN); + createPath().addFileset(set); + } + + public Path createPath() { + if (currPath == null) { + currPath = new Path(getProject()); + } + return currPath; + } + + public Mapper createMapper() + { + mapper = new Mapper(getProject()); + return mapper; + } + + private CallTarget createCallTarget() { + CallTarget ct = (CallTarget) getProject().createTask("antcall"); + ct.setOwningTarget(getOwningTarget()); + ct.init(); + ct.setTarget(target); + ct.setInheritAll(inheritAll); + ct.setInheritRefs(inheritRefs); + Enumeration e = params.elements(); + while (e.hasMoreElements()) { + Property param = (Property) e.nextElement(); + Property toSet = ct.createParam(); + toSet.setName(param.getName()); + if (param.getValue() != null) { + toSet.setValue(param.getValue()); + } + if (param.getFile() != null) { + toSet.setFile(param.getFile()); + } + if (param.getResource() != null) { + toSet.setResource(param.getResource()); + } + if (param.getPrefix() != null) { + toSet.setPrefix(param.getPrefix()); + } + if (param.getRefid() != null) { + toSet.setRefid(param.getRefid()); + } + if (param.getEnvironment() != null) { + toSet.setEnvironment(param.getEnvironment()); + } + if (param.getClasspath() != null) { + toSet.setClasspath(param.getClasspath()); + } + } + + e = references.elements(); + while (e.hasMoreElements()) { + ct.addReference((Ant.Reference) e.nextElement()); + } + + return ct; + } + + protected void handleOutput(String line) + { + try { + super.handleOutput(line); + } + // This is needed so we can run with 1.5 and 1.5.1 + catch (IllegalAccessError e) { + super.handleOutput(line); + } + } + + protected void handleErrorOutput(String line) + { + try { + super.handleErrorOutput(line); + } + // This is needed so we can run with 1.5 and 1.5.1 + catch (IllegalAccessError e) { + super.handleErrorOutput(line); + } + } + +} + + diff --git a/src/java/net/sf/antcontrib/logic/ForTask.java b/src/java/net/sf/antcontrib/logic/ForTask.java new file mode 100644 index 0000000..516773b --- /dev/null +++ b/src/java/net/sf/antcontrib/logic/ForTask.java @@ -0,0 +1,433 @@ +/* + * Copyright (c) 2003-2005 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.logic; + +import java.io.File; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.taskdefs.MacroDef; +import org.apache.tools.ant.taskdefs.MacroInstance; +import org.apache.tools.ant.taskdefs.Parallel; +import org.apache.tools.ant.types.DirSet; +import org.apache.tools.ant.types.FileSet; +import org.apache.tools.ant.types.Path; + +/*** + * Task definition for the for task. This is based on + * the foreach task but takes a sequential element + * instead of a target and only works for ant >= 1.6Beta3 + * @author Peter Reilly + */ +public class ForTask extends Task { + + private String list; + private String param; + private String delimiter = ","; + private Path currPath; + private boolean trim; + private boolean keepgoing = false; + private MacroDef macroDef; + private List hasIterators = new ArrayList(); + private boolean parallel = false; + private Integer threadCount; + private Parallel parallelTasks; + + /** + * Creates a new <code>For</code> instance. + * This checks if the ant version is correct to run this task. + */ + public ForTask() { + } + + /** + * Attribute whether to execute the loop in parallel or in sequence. + * @param parallel if true execute the tasks in parallel. Default is false. + */ + public void setParallel(boolean parallel) { + this.parallel = parallel; + } + + /*** + * Set the maximum amount of threads we're going to allow + * to execute in parallel + * @param threadCount the number of threads to use + */ + public void setThreadCount(int threadCount) { + if (threadCount < 1) { + throw new BuildException("Illegal value for threadCount " + threadCount + + " it should be > 0"); + } + this.threadCount = new Integer(threadCount); + } + + /** + * Set the trim attribute. + * + * @param trim if true, trim the value for each iterator. + */ + public void setTrim(boolean trim) { + this.trim = trim; + } + + /** + * Set the keepgoing attribute, indicating whether we + * should stop on errors or continue heedlessly onward. + * + * @param keepgoing a boolean, if <code>true</code> then we act in + * the keepgoing manner described. + */ + public void setKeepgoing(boolean keepgoing) { + this.keepgoing = keepgoing; + } + + /** + * Set the list attribute. + * + * @param list a list of delimiter separated tokens. + */ + public void setList(String list) { + this.list = list; + } + + /** + * Set the delimiter attribute. + * + * @param delimiter the delimiter used to separate the tokens in + * the list attribute. The default is ",". + */ + public void setDelimiter(String delimiter) { + this.delimiter = delimiter; + } + + /** + * Set the param attribute. + * This is the name of the macrodef attribute that + * gets set for each iterator of the sequential element. + * + * @param param the name of the macrodef attribute. + */ + public void setParam(String param) { + this.param = param; + } + + private Path getOrCreatePath() { + if (currPath == null) { + currPath = new Path(getProject()); + } + return currPath; + } + + /** + * This is a path that can be used instread of the list + * attribute to interate over. If this is set, each + * path element in the path is used for an interator of the + * sequential element. + * + * @param path the path to be set by the ant script. + */ + public void addConfigured(Path path) { + getOrCreatePath().append(path); + } + + /** + * This is a path that can be used instread of the list + * attribute to interate over. If this is set, each + * path element in the path is used for an interator of the + * sequential element. + * + * @param path the path to be set by the ant script. + */ + public void addConfiguredPath(Path path) { + addConfigured(path); + } + + /** + * @return a MacroDef#NestedSequential object to be configured + */ + public Object createSequential() { + macroDef = new MacroDef(); + macroDef.setProject(getProject()); + return macroDef.createSequential(); + } + + /** + * Run the for task. + * This checks the attributes and nested elements, and + * if there are ok, it calls doTheTasks() + * which constructes a macrodef task and a + * for each interation a macrodef instance. + */ + public void execute() { + if (parallel) { + parallelTasks = (Parallel) getProject().createTask("parallel"); + if (threadCount != null) { + parallelTasks.setThreadCount(threadCount.intValue()); + } + } + if (list == null && currPath == null && hasIterators.size() == 0) { + throw new BuildException( + "You must have a list or path to iterate through"); + } + if (param == null) { + throw new BuildException( + "You must supply a property name to set on" + + " each iteration in param"); + } + if (macroDef == null) { + throw new BuildException( + "You must supply an embedded sequential " + + "to perform"); + } + doTheTasks(); + if (parallel) { + parallelTasks.perform(); + } + } + + + private void doSequentialIteration(String val) { + MacroInstance instance = new MacroInstance(); + instance.setProject(getProject()); + instance.setOwningTarget(getOwningTarget()); + instance.setMacroDef(macroDef); + instance.setDynamicAttribute(param.toLowerCase(), + val); + if (!parallel) { + instance.execute(); + } else { + parallelTasks.addTask(instance); + } + } + + private void doTheTasks() { + int errorCount = 0; + int taskCount = 0; + + // Create a macro attribute + MacroDef.Attribute attribute = new MacroDef.Attribute(); + attribute.setName(param); + macroDef.addConfiguredAttribute(attribute); + // Take Care of the list attribute + if (list != null) { + StringTokenizer st = new StringTokenizer(list, delimiter); + + while (st.hasMoreTokens()) { + String tok = st.nextToken(); + if (trim) { + tok = tok.trim(); + } + try { + taskCount++; + doSequentialIteration(tok); + } catch (BuildException bx) { + if (keepgoing) { + log(tok + ": " + bx.getMessage(), Project.MSG_ERR); + errorCount++; + } else { + throw bx; + } + } + } + } + if (keepgoing && (errorCount != 0)) { + throw new BuildException( + "Keepgoing execution: " + errorCount + + " of " + taskCount + " iterations failed."); + } + + // Take Care of the path element + String[] pathElements = new String[0]; + if (currPath != null) { + pathElements = currPath.list(); + } + for (int i = 0; i < pathElements.length; i++) { + File nextFile = new File(pathElements[i]); + try { + taskCount++; + doSequentialIteration(nextFile.getAbsolutePath()); + } catch (BuildException bx) { + if (keepgoing) { + log(nextFile + ": " + bx.getMessage(), Project.MSG_ERR); + errorCount++; + } else { + throw bx; + } + } + } + if (keepgoing && (errorCount != 0)) { + throw new BuildException( + "Keepgoing execution: " + errorCount + + " of " + taskCount + " iterations failed."); + } + + // Take care of iterators + for (Iterator i = hasIterators.iterator(); i.hasNext();) { + Iterator it = ((HasIterator) i.next()).iterator(); + while (it.hasNext()) { + String s = it.next().toString(); + try { + taskCount++; + doSequentialIteration(s); + } catch (BuildException bx) { + if (keepgoing) { + log(s + ": " + bx.getMessage(), Project.MSG_ERR); + errorCount++; + } else { + throw bx; + } + } + } + } + if (keepgoing && (errorCount != 0)) { + throw new BuildException( + "Keepgoing execution: " + errorCount + + " of " + taskCount + " iterations failed."); + } + } + + /** + * Add a Map, iterate over the values + * + * @param map a Map object - iterate over the values. + */ + public void add(Map map) { + hasIterators.add(new MapIterator(map)); + } + + /** + * Add a fileset to be iterated over. + * + * @param fileset a <code>FileSet</code> value + */ + public void add(FileSet fileset) { + getOrCreatePath().addFileset(fileset); + } + + /** + * Add a fileset to be iterated over. + * + * @param fileset a <code>FileSet</code> value + */ + public void addFileSet(FileSet fileset) { + add(fileset); + } + + /** + * Add a dirset to be iterated over. + * + * @param dirset a <code>DirSet</code> value + */ + public void add(DirSet dirset) { + getOrCreatePath().addDirset(dirset); + } + + /** + * Add a dirset to be iterated over. + * + * @param dirset a <code>DirSet</code> value + */ + public void addDirSet(DirSet dirset) { + add(dirset); + } + + /** + * Add a collection that can be iterated over. + * + * @param collection a <code>Collection</code> value. + */ + public void add(Collection collection) { + hasIterators.add(new ReflectIterator(collection)); + } + + /** + * Add an iterator to be iterated over. + * + * @param iterator an <code>Iterator</code> value + */ + public void add(Iterator iterator) { + hasIterators.add(new IteratorIterator(iterator)); + } + + /** + * Add an object that has an Iterator iterator() method + * that can be iterated over. + * + * @param obj An object that can be iterated over. + */ + public void add(Object obj) { + hasIterators.add(new ReflectIterator(obj)); + } + + /** + * Interface for the objects in the iterator collection. + */ + private interface HasIterator { + Iterator iterator(); + } + + private static class IteratorIterator implements HasIterator { + private Iterator iterator; + public IteratorIterator(Iterator iterator) { + this.iterator = iterator; + } + public Iterator iterator() { + return this.iterator; + } + } + + private static class MapIterator implements HasIterator { + private Map map; + public MapIterator(Map map) { + this.map = map; + } + public Iterator iterator() { + return map.values().iterator(); + } + } + + private static class ReflectIterator implements HasIterator { + private Object obj; + private Method method; + public ReflectIterator(Object obj) { + this.obj = obj; + try { + method = obj.getClass().getMethod( + "iterator", new Class[] {}); + } catch (Throwable t) { + throw new BuildException( + "Invalid type " + obj.getClass() + " used in For task, it does" + + " not have a public iterator method"); + } + } + + public Iterator iterator() { + try { + return (Iterator) method.invoke(obj, new Object[] {}); + } catch (Throwable t) { + throw new BuildException(t); + } + } + } +} diff --git a/src/java/net/sf/antcontrib/logic/IfTask.java b/src/java/net/sf/antcontrib/logic/IfTask.java new file mode 100644 index 0000000..4d538df --- /dev/null +++ b/src/java/net/sf/antcontrib/logic/IfTask.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.antcontrib.logic; + +import java.util.Vector; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.taskdefs.Sequential; +import org.apache.tools.ant.taskdefs.condition.Condition; +import org.apache.tools.ant.taskdefs.condition.ConditionBase; + +/** + * Perform some tasks based on whether a given condition holds true or + * not. + * + * <p>This task is heavily based on the Condition framework that can + * be found in Ant 1.4 and later, therefore it cannot be used in + * conjunction with versions of Ant prior to 1.4.</p> + * + * <p>This task doesn't have any attributes, the condition to test is + * specified by a nested element - see the documentation of your + * <code><condition></code> task (see + * <a href="http://jakarta.apache.org/ant/manual/CoreTasks/condition.html">the + * online documentation</a> for example) for a complete list of nested + * elements.</p> + * + * <p>Just like the <code><condition></code> task, only a single + * condition can be specified - you combine them using + * <code><and></code> or <code><or></code> conditions.</p> + * + * <p>In addition to the condition, you can specify three different + * child elements, <code><elseif></code>, <code><then></code> and + * <code><else></code>. All three subelements are optional. + * + * Both <code><then></code> and <code><else></code> must not be + * used more than once inside the if task. Both are + * containers for Ant tasks, just like Ant's + * <code><parallel></code> and <code><sequential></code> + * tasks - in fact they are implemented using the same class as Ant's + * <code><sequential></code> task.</p> + * + * The <code><elseif></code> behaves exactly like an <code><if></code> + * except that it cannot contain the <code><else></code> element + * inside of it. You may specify as may of these as you like, and the + * order they are specified is the order they are evaluated in. If the + * condition on the <code><if></code> is false, then the first + * <code><elseif></code> who's conditional evaluates to true + * will be executed. The <code><else></code> will be executed + * only if the <code><if></code> and all <code><elseif></code> + * conditions are false. + * + * <p>Use the following task to define the <code><if></code> + * task before you use it the first time:</p> + * + * <pre><code> + * <taskdef name="if" classname="net.sf.antcontrib.logic.IfTask" /> + * </code></pre> + * + * <h3>Crude Example</h3> + * + * <pre><code> + * <if> + * <equals arg1="${foo}" arg2="bar" /> + * <then> + * <echo message="The value of property foo is bar" /> + * </then> + * <else> + * <echo message="The value of property foo is not bar" /> + * </else> + * </if> + * </code> + * + * <code> + * <if> + * <equals arg1="${foo}" arg2="bar" /> + * <then> + * <echo message="The value of property foo is 'bar'" /> + * </then> + * + * <elseif> + * <equals arg1="${foo}" arg2="foo" /> + * <then> + * <echo message="The value of property foo is 'foo'" /> + * </then> + * </elseif> + * + * <else> + * <echo message="The value of property foo is not 'foo' or 'bar'" /> + * </else> + * </if> + * </code></pre> + * + * @author <a href="mailto:[email protected]">Stefan Bodewig</a> + */ +public class IfTask extends ConditionBase { + + public static final class ElseIf + extends ConditionBase + { + private Sequential thenTasks = null; + + public void addThen(Sequential t) + { + if (thenTasks != null) + { + throw new BuildException("You must not nest more than one <then> into <elseif>"); + } + thenTasks = t; + } + + public boolean eval() + throws BuildException + { + if (countConditions() > 1) { + throw new BuildException("You must not nest more than one condition into <elseif>"); + } + if (countConditions() < 1) { + throw new BuildException("You must nest a condition into <elseif>"); + } + Condition c = (Condition) getConditions().nextElement(); + + return c.eval(); + } + + public void execute() + throws BuildException + { + if (thenTasks != null) + { + thenTasks.execute(); + } + } + } + + private Sequential thenTasks = null; + private Vector elseIfTasks = new Vector(); + private Sequential elseTasks = null; + + /*** + * A nested Else if task + */ + public void addElseIf(ElseIf ei) + { + elseIfTasks.addElement(ei); + } + + /** + * A nested <then> element - a container of tasks that will + * be run if the condition holds true. + * + * <p>Not required.</p> + */ + public void addThen(Sequential t) { + if (thenTasks != null) { + throw new BuildException("You must not nest more than one <then> into <if>"); + } + thenTasks = t; + } + + /** + * A nested <else> element - a container of tasks that will + * be run if the condition doesn't hold true. + * + * <p>Not required.</p> + */ + public void addElse(Sequential e) { + if (elseTasks != null) { + throw new BuildException("You must not nest more than one <else> into <if>"); + } + elseTasks = e; + } + + public void execute() throws BuildException { + if (countConditions() > 1) { + throw new BuildException("You must not nest more than one condition into <if>"); + } + if (countConditions() < 1) { + throw new BuildException("You must nest a condition into <if>"); + } + Condition c = (Condition) getConditions().nextElement(); + if (c.eval()) { + if (thenTasks != null) { + thenTasks.execute(); + } + } + else + { + boolean done = false; + int sz = elseIfTasks.size(); + for (int i=0;i<sz && ! done;i++) + { + + ElseIf ei = (ElseIf)(elseIfTasks.elementAt(i)); + if (ei.eval()) + { + done = true; + ei.execute(); + } + } + + if (!done && elseTasks != null) + { + elseTasks.execute(); + } + } + } +} diff --git a/src/java/net/sf/antcontrib/logic/OutOfDate.java b/src/java/net/sf/antcontrib/logic/OutOfDate.java new file mode 100644 index 0000000..014a15e --- /dev/null +++ b/src/java/net/sf/antcontrib/logic/OutOfDate.java @@ -0,0 +1,675 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.logic; + +import java.io.File; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.Hashtable; +import java.util.Vector; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.taskdefs.Parallel; +import org.apache.tools.ant.taskdefs.Sequential; +import org.apache.tools.ant.taskdefs.condition.Condition; +import org.apache.tools.ant.types.Mapper; +import org.apache.tools.ant.types.Path; +import org.apache.tools.ant.util.FileNameMapper; +import org.apache.tools.ant.util.FileUtils; + +import org.apache.tools.ant.types.EnumeratedAttribute; + +/** +* Task to help in calling tasks if generated files are older +* than source files. +* Sets a given property or runs an internal task. +* +* Based on +* org.apache.org.apache.tools.ant.taskdefs.UpToDate +* +* @author peter reilly +*/ + +public class OutOfDate extends Task implements Condition { + + /** + * Enumerated type for collection attribute + * + * @see EnumeratedAttribute + */ + public static class CollectionEnum extends EnumeratedAttribute { + /** Constants for the enumerations */ + public static final int + SOURCES = 0, TARGETS = 1, ALLSOURCES = 2, ALLTARGETS = 3; + + /** + * get the values + * @return an array of the allowed values for this attribute. + */ + public String[] getValues() { + return new String[] {"sources", "targets", "allsources", "alltargets"}; + } + } + + // attributes and nested elements + private Task doTask = null; + private String property; + private String value = "true"; + private boolean force = false; + private int verbosity = Project.MSG_VERBOSE; + private Vector mappers = new Vector(); + private Path targetpaths = null; + private Path sourcepaths = null; + private String outputSources = null; + private String outputSourcesPath = null; + private String outputTargets = null; + private String outputTargetsPath = null; + private String allTargets = null; + private String allTargetsPath = null; + private String separator = " "; + private DeleteTargets deleteTargets = null; + private int collection = CollectionEnum.SOURCES; + + // variables + private Hashtable targetSet = new Hashtable(); + private Hashtable sourceSet = new Hashtable(); + private Hashtable allTargetSet = new Hashtable(); + private Hashtable allSourceSet = new Hashtable(); + + /** + * Set the collection attribute, controls what is + * returned by the iterator method. + * <dl> + * <li>"sources" the sources that are newer than the corresponding targets.</li> + * <li>"targets" the targets that are older or not present than the corresponding + * sources.</li> + * <li>"allsources" all the sources</li> + * <li>"alltargets" all the targets</li> + * </dl> + * @param collection "sources" the changes + */ + public void setCollection(CollectionEnum collection) { + this.collection = collection.getIndex(); + } + + /** + * Defines the FileNameMapper to use (nested mapper element). + * @return Mappper to be configured + */ + public Mapper createMapper() { + MyMapper mapper = new MyMapper(getProject()); + mappers.addElement(mapper); + return mapper; + } + + /** + * The property to set if any of the target files are outofdate with + * regard to any of the source files. + * + * @param property the name of the property to set if Target is outofdate. + */ + public void setProperty(String property) { + this.property = property; + } + + /** + * The separator to use to separate the files + * @param separator separator used in outout properties + */ + + public void setSeparator(String separator) { + this.separator = separator; + } + + /** + * The value to set the named property to the target files + * are outofdate + * + * @param value the value to set the property + */ + public void setValue(String value) { + this.value = value; + } + + /** + * whether to allways be outofdate + * @param force true means that outofdate is always set, default + * false + */ + public void setForce(boolean force) { + this.force = force; + } + + /** + * whether to have verbose output + * @param verbose true means that outofdate outputs debug info + */ + public void setVerbose(boolean verbose) { + if (verbose) { + this.verbosity = Project.MSG_INFO; + } else { + this.verbosity = Project.MSG_VERBOSE; + } + } + + /** + * Add to the target files + * + * @return a path to be configured + */ + public Path createTargetfiles() { + if (targetpaths == null) { + targetpaths = new Path(getProject()); + } + return targetpaths; + } + + /** + * Add to the source files + * + * @return a path to be configured + */ + public Path createSourcefiles() { + if (sourcepaths == null) { + sourcepaths = new Path(getProject()); + } + return sourcepaths; + } + + /** + * A property to contain the output source files + * + * @param outputSources the name of the property + */ + public void setOutputSources(String outputSources) { + this.outputSources = outputSources; + } + + /** + * A property to contain the output target files + * + * @param outputTargets the name of the property + */ + public void setOutputTargets(String outputTargets) { + this.outputTargets = outputTargets; + } + + /** + * A reference to contain the path of target files that + * are outofdate + * + * @param outputTargetsPath the name of the reference + */ + public void setOutputTargetsPath(String outputTargetsPath) { + this.outputTargetsPath = outputTargetsPath; + } + + /** + * A refernce to contain the path of all the targets + * + * @param allTargetsPath the name of the reference + */ + public void setAllTargetsPath(String allTargetsPath) { + this.allTargetsPath = allTargetsPath; + } + + /** + * A property to contain all the target filenames + * + * @param allTargets the name of the property + */ + public void setAllTargets(String allTargets) { + this.allTargets = allTargets; + } + + /** + * A reference to the path containing all the sources files. + * + * @param outputSourcesPath the name of the reference + */ + public void setOutputSourcesPath(String outputSourcesPath) { + this.outputSourcesPath = outputSourcesPath; + } + + /** + * optional nested delete element + * @return an element to be configured + */ + public DeleteTargets createDeleteTargets() { + deleteTargets = new DeleteTargets(); + return deleteTargets; + } + + /** + * Embedded do parallel + * @param doTask the parallel to embed + */ + public void addParallel(Parallel doTask) { + if (this.doTask != null) { + throw new BuildException( + "You must not nest more that one <parallel> or <sequential>" + + " into <outofdate>"); + } + this.doTask = doTask; + } + + /** + * Embedded do sequential. + * @param doTask the sequential to embed + */ + public void addSequential(Sequential doTask) { + if (this.doTask != null) { + throw new BuildException( + "You must not nest more that one <parallel> or <sequential>" + + " into <outofdate>"); + } + this.doTask = doTask; + } + + /** + * Evaluate (all) target and source file(s) to + * see if the target(s) is/are outoutdate. + * @return true if any of the targets are outofdate + */ + public boolean eval() { + boolean ret = false; + FileUtils fileUtils = FileUtils.newFileUtils(); + if (sourcepaths == null) { + throw new BuildException( + "You must specify a <sourcefiles> element."); + } + + if (targetpaths == null && mappers.size() == 0) { + throw new BuildException( + "You must specify a <targetfiles> or <mapper> element."); + } + + // Source Paths + String[] spaths = sourcepaths.list(); + + for (int i = 0; i < spaths.length; i++) { + File sourceFile = new File(spaths[i]); + if (!sourceFile.exists()) { + throw new BuildException(sourceFile.getAbsolutePath() + + " not found."); + } + } + + // Target Paths + + if (targetpaths != null) { + String[] paths = targetpaths.list(); + for (int i = 0; i < paths.length; ++i) { + if (targetNeedsGen(paths[i], spaths)) { + ret = true; + } + } + } + + // Mapper Paths + for (Enumeration e = mappers.elements(); e.hasMoreElements();) { + MyMapper mapper = (MyMapper) e.nextElement(); + + File relativeDir = mapper.getDir(); + File baseDir = new File(getProject().getProperty("basedir")); + if (relativeDir == null) { + relativeDir = baseDir; + } + String[] rpaths = new String[spaths.length]; + for (int i = 0; i < spaths.length; ++i) { + rpaths[i] = fileUtils.removeLeadingPath(relativeDir, new File(spaths[i])); + } + + FileNameMapper fileNameMapper = mapper.getImplementation(); + for (int i = 0; i < spaths.length; ++i) { + String[] mapped = fileNameMapper.mapFileName(rpaths[i]); + if (mapped != null) { + for (int j = 0; j < mapped.length; ++j) { + if (outOfDate(new File(spaths[i]), + fileUtils.resolveFile( + baseDir, mapped[j]))) { + ret = true; + } + } + } + } + } + + if (allTargets != null) { + this.getProject().setNewProperty( + allTargets, setToString(allTargetSet)); + } + + if (allTargetsPath != null) { + this.getProject().addReference( + allTargetsPath, setToPath(allTargetSet)); + } + + if (outputSources != null) { + this.getProject().setNewProperty( + outputSources, setToString(sourceSet)); + } + + if (outputTargets != null) { + this.getProject().setNewProperty( + outputTargets, setToString(targetSet)); + } + + if (outputSourcesPath != null) { + this.getProject().addReference( + outputSourcesPath, setToPath(sourceSet)); + } + + if (outputTargetsPath != null) { + this.getProject().addReference( + outputTargetsPath, setToPath(targetSet)); + } + + if (force) { + ret = true; + } + + if (ret && deleteTargets != null) { + deleteTargets.execute(); + } + + if (ret) { + if (property != null) { + this.getProject().setNewProperty(property, value); + } + } + + return ret; + } + + private boolean targetNeedsGen(String target, String[] spaths) { + boolean ret = false; + File targetFile = new File(target); + for (int i = 0; i < spaths.length; i++) { + if (outOfDate(new File(spaths[i]), targetFile)) { + ret = true; + } + } + // Special case : there are no source files, make sure the + // targets exist + if (spaths.length == 0) { + if (outOfDate(null, targetFile)) { + ret = true; + } + } + return ret; + } + + /** + * Call evalute and return an iterator over the result + * @return an iterator over the result + */ + public Iterator iterator() { + // Perhaps should check the result and return + // an empty set if it returns false + eval(); + + switch (collection) { + case CollectionEnum.SOURCES: + return sourceSet.values().iterator(); + case CollectionEnum.TARGETS: + return targetSet.values().iterator(); + case CollectionEnum.ALLSOURCES: + return allSourceSet.values().iterator(); + case CollectionEnum.ALLTARGETS: + return allTargetSet.values().iterator(); + default: + return sourceSet.values().iterator(); + } + } + + /** + * Sets property to true and/or executes embedded do + * if any of the target file(s) do not have a more recent timestamp + * than (each of) the source file(s). + */ + public void execute() { + if (!eval()) { + return; + } + + if (doTask != null) { + doTask.perform(); + } + + } + + + private boolean outOfDate(File sourceFile, File targetFile) { + boolean ret = false; + if (sourceFile != null) { + allSourceSet.put(sourceFile, sourceFile); + } + allTargetSet.put(targetFile, targetFile); + if (!targetFile.exists()) { + ret = true; + } + if ((!ret) && (sourceFile != null)) { + ret = sourceFile.lastModified() > targetFile.lastModified(); + } + if (ret) { + if ((sourceFile != null && sourceSet.get(sourceFile) == null) + || targetSet.get(targetFile) == null) { + log("SourceFile " + sourceFile + " outofdate " + + "with regard to " + targetFile, verbosity); + } + if (sourceFile != null) { + sourceSet.put(sourceFile, sourceFile); + } + targetSet.put(targetFile, targetFile); + } + return ret; + } + + private String setToString(Hashtable set) { + StringBuffer b = new StringBuffer(); + for (Enumeration e = set.keys(); e.hasMoreElements();) { + File v = (File) e.nextElement(); + if (b.length() != 0) { + b.append(separator); + } + String s = v.getAbsolutePath(); + // DOTO: The following needs more work! + // Handle paths contains sep + if (s.indexOf(separator) != -1) { + if (s.indexOf("\"") != -1) { + s = "'" + s + "'"; + } else { + s = "\"" + s + "\""; + } + } + b.append(s); + } + return b.toString(); + } + + private Path setToPath(Hashtable set) { + Path ret = new Path(getProject()); + for (Enumeration e = set.keys(); e.hasMoreElements();) { + File v = (File) e.nextElement(); + Path.PathElement el = ret.createPathElement(); + el.setLocation(v); + } + return ret; + } + + /** + * nested delete targets + */ + public class DeleteTargets { + private boolean all = false; + private boolean quiet = false; + private boolean failOnError = false; + + private int myLogging = Project.MSG_INFO; + + /** + * whether to delete all the targets + * or just those that are newer than the + * corresponding sources. + * @param all true to delete all, default false + */ + public void setAll(boolean all) { + this.all = all; + } + + /** + * @param quiet if true suppress messages on deleting files + */ + public void setQuiet(boolean quiet) { + this.quiet = quiet; + myLogging = quiet ? Project.MSG_VERBOSE : Project.MSG_INFO; + } + + /** + * @param failOnError if true halt if there is a failure to delete + */ + public void setFailOnError(boolean failOnError) { + this.failOnError = failOnError; + } + + private void execute() { + if (myLogging != Project.MSG_INFO) { + myLogging = verbosity; + } + + // Quiet overrides failOnError + if (quiet) { + failOnError = false; + } + + Path toBeDeleted = null; + if (all) { + toBeDeleted = setToPath(allTargetSet); + } else { + toBeDeleted = setToPath(targetSet); + } + + String[] names = toBeDeleted.list(); + for (int i = 0; i < names.length; ++i) { + File file = new File(names[i]); + if (!file.exists()) { + continue; + } + if (file.isDirectory()) { + removeDir(file); + continue; + } + log("Deleting " + file.getAbsolutePath(), myLogging); + if (!file.delete()) { + String message = + "Unable to delete file " + file.getAbsolutePath(); + if (failOnError) { + throw new BuildException(message); + } else { + log(message, myLogging); + } + } + } + } + + private static final int DELETE_RETRY_SLEEP_MILLIS = 10; + /** + * Attempt to fix possible race condition when deleting + * files on WinXP. If the delete does not work, + * wait a little and try again. + */ + private boolean delete(File f) { + if (!f.delete()) { + try { + Thread.sleep(DELETE_RETRY_SLEEP_MILLIS); + return f.delete(); + } catch (InterruptedException ex) { + return f.delete(); + } + } + return true; + } + + private void removeDir(File d) { + String[] list = d.list(); + if (list == null) { + list = new String[0]; + } + for (int i = 0; i < list.length; i++) { + String s = list[i]; + File f = new File(d, s); + if (f.isDirectory()) { + removeDir(f); + } else { + log("Deleting " + f.getAbsolutePath(), myLogging); + if (!f.delete()) { + String message = "Unable to delete file " + + f.getAbsolutePath(); + if (failOnError) { + throw new BuildException(message); + } else { + log(message, myLogging); + } + } + } + } + log("Deleting directory " + d.getAbsolutePath(), myLogging); + if (!delete(d)) { + String message = "Unable to delete directory " + + d.getAbsolutePath(); + if (failOnError) { + throw new BuildException(message); + } else { + log(message, myLogging); + } + } + } + } + + /** + * Wrapper for mapper - includes dir + */ + public static class MyMapper extends Mapper { + private File dir = null; + /** + * Creates a new <code>MyMapper</code> instance. + * + * @param project the current project + */ + public MyMapper(Project project) { + super(project); + } + + /** + * @param dir the directory that the from files are relative to + */ + public void setDir(File dir) { + this.dir = dir; + } + + /** + * @return the directory that the from files are relative to + */ + public File getDir() { + return dir; + } + } +} + + diff --git a/src/java/net/sf/antcontrib/logic/RunTargetTask.java b/src/java/net/sf/antcontrib/logic/RunTargetTask.java new file mode 100644 index 0000000..16b87ca --- /dev/null +++ b/src/java/net/sf/antcontrib/logic/RunTargetTask.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.logic; +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; + +/** + * Ant task that runs a target without creating a new project. + * + * @author Nicola Ken Barozzi [email protected] + */ +public class RunTargetTask extends Task { + + private String target = null; + + /** + * The target attribute + * + * @param target the name of a target to execute + */ + public void setTarget(String target) { + this.target = target; + } + + /** + * execute the target + * + * @exception BuildException if a target is not specified + */ + public void execute() throws BuildException { + if (target == null) { + throw new BuildException("target property required"); + } + + getProject().executeTarget(target); + } +} diff --git a/src/java/net/sf/antcontrib/logic/Switch.java b/src/java/net/sf/antcontrib/logic/Switch.java new file mode 100644 index 0000000..14f31ec --- /dev/null +++ b/src/java/net/sf/antcontrib/logic/Switch.java @@ -0,0 +1,207 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.logic; + +import java.util.Vector; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.taskdefs.Sequential; + +/*** + * Task definition for the ANT task to switch on a particular value. + * + * <pre> + * + * Usage: + * + * Task declaration in the project: + * <code> + * <taskdef name="switch" classname="net.sf.antcontrib.logic.Switch" /> + * </code> + * + * Task calling syntax: + * <code> + * <switch value="value" [caseinsensitive="true|false"] > + * <case value="val"> + * <property name="propname" value="propvalue" /> | + * <antcall target="targetname" /> | + * any other tasks + * </case> + * [ + * <default> + * <property name="propname" value="propvalue" /> | + * <antcall target="targetname" /> | + * any other tasks + * </default> + * ] + * </switch> + * </code> + * + * + * Attributes: + * value -> The value to switch on + * caseinsensitive -> Should we do case insensitive comparisons? + * (default is false) + * + * Subitems: + * case --> An individual case to consider, if the value that + * is being switched on matches to value attribute of + * the case, then the nested tasks will be executed. + * default --> The default case for when no match is found. + * + * + * Crude Example: + * + * <code> + * <switch value="${foo}"> + * <case value="bar"> + * <echo message="The value of property foo is bar" /> + * </case> + * <case value="baz"> + * <echo message="The value of property foo is baz" /> + * </case> + * <default> + * <echo message="The value of property foo is not sensible" /> + * </default> + * </switch> + * </code> + * + * </pre> + * + * @author <a href="mailto:[email protected]">Matthew Inger</a> + * @author <a href="mailto:[email protected]">Stefan Bodewig</a> + */ +public class Switch extends Task +{ + private String value; + private Vector cases; + private Sequential defaultCase; + private boolean caseInsensitive; + + /*** + * Default Constructor + */ + public Switch() + { + cases = new Vector(); + } + + public void execute() + throws BuildException + { + if (value == null) + throw new BuildException("Value is missing"); + if (cases.size() == 0 && defaultCase == null) + throw new BuildException("No cases supplied"); + + Sequential selectedCase = defaultCase; + + int sz = cases.size(); + for (int i=0;i<sz;i++) + { + Case c = (Case)(cases.elementAt(i)); + + String cvalue = c.value; + if (cvalue == null) { + throw new BuildException("Value is required for case."); + } + String mvalue = value; + + if (caseInsensitive) + { + cvalue = cvalue.toUpperCase(); + mvalue = mvalue.toUpperCase(); + } + + if (cvalue.equals(mvalue) && c != defaultCase) + selectedCase = c; + } + + if (selectedCase == null) { + throw new BuildException("No case matched the value " + value + + " and no default has been specified."); + } + selectedCase.perform(); + } + + /*** + * Sets the value being switched on + */ + public void setValue(String value) + { + this.value = value; + } + + public void setCaseInsensitive(boolean c) + { + caseInsensitive = c; + } + + public final class Case extends Sequential + { + private String value; + + public Case() + { + super(); + } + + public void setValue(String value) + { + this.value = value; + } + + public void execute() + throws BuildException + { + super.execute(); + } + + public boolean equals(Object o) + { + boolean res = false; + Case c = (Case)o; + if (c.value.equals(value)) + res = true; + return res; + } + } + + /*** + * Creates the <case> tag + */ + public Switch.Case createCase() + throws BuildException + { + Switch.Case res = new Switch.Case(); + cases.addElement(res); + return res; + } + + /*** + * Creates the <default> tag + */ + public void addDefault(Sequential res) + throws BuildException + { + if (defaultCase != null) + throw new BuildException("Cannot specify multiple default cases"); + + defaultCase = res; + } + +} diff --git a/src/java/net/sf/antcontrib/logic/Throw.java b/src/java/net/sf/antcontrib/logic/Throw.java new file mode 100644 index 0000000..552de46 --- /dev/null +++ b/src/java/net/sf/antcontrib/logic/Throw.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.logic; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.taskdefs.Exit; +import org.apache.tools.ant.types.Reference; + +/** + * Extension of <code><fail></code> that can throw an exception + * that is a reference in the project. + * + * <p>This may be useful inside the <code><catch></code> block + * of a <code><trycatch></code> task if you want to rethrow the + * exception just caught.</p> + */ +public class Throw extends Exit { + + private Reference ref; + + /** + * The reference that points to a BuildException. + */ + public void setRefid(Reference ref) { + this.ref = ref; + } + + public void execute() throws BuildException { + Object reffed = ref != null + ? ref.getReferencedObject(getProject()) + : null; + if (reffed != null && reffed instanceof BuildException) { + throw (BuildException) reffed; + } + super.execute(); + } +} diff --git a/src/java/net/sf/antcontrib/logic/TimestampSelector.java b/src/java/net/sf/antcontrib/logic/TimestampSelector.java new file mode 100644 index 0000000..da4ccd8 --- /dev/null +++ b/src/java/net/sf/antcontrib/logic/TimestampSelector.java @@ -0,0 +1,285 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.logic; + +import java.io.File; +import java.util.Vector; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.types.Path; +import org.apache.tools.ant.types.Reference; + + +/*** + * Task definition for the foreach task. The foreach task iterates + * over a list, a list of filesets, or both. + * + * <pre> + * + * Usage: + * + * Task declaration in the project: + * <code> + * <taskdef name="latesttimestamp" classname="net.sf.antcontrib.logic.TimestampSelector" /> + * </code> + * + * Call Syntax: + * <code> + * <timestampselector + * [property="prop" | outputsetref="id"] + * [count="num"] + * [age="eldest|youngest"] + * [pathSep=","] + * [pathref="ref"] > + * <path> + * ... + * </path> + * </latesttimestamp> + * </code> + * + * Attributes: + * outputsetref --> The reference of the output Path set which will contain the + * files with the latest timestamps. + * property --> The name of the property to set with file having the latest + * timestamp. If you specify the "count" attribute, you will get + * the lastest N files. These will be the absolute pathnames + * count --> How many of the latest files do you wish to find + * pathSep --> What to use as the path separator when using the "property" + * attribute, in conjunction with the "count" attribute + * pathref --> The reference of the path which is the input set of files. + * + * </pre> + * @author <a href="mailto:[email protected]">Matthew Inger</a> + */ +public class TimestampSelector extends Task +{ + private static final String AGE_ELDEST = "eldest"; + private static final String AGE_YOUNGEST = "youngest"; + + private String property; + private Path path; + private String outputSetId; + private int count = 1; + private char pathSep = ','; + private String age = AGE_YOUNGEST; + + + /*** + * Default Constructor + */ + public TimestampSelector() + { + super(); + } + + + public void doFileSetExecute(String paths[]) + throws BuildException + { + + } + + // Sorts entire array + public void sort(Vector array) + { + sort(array, 0, array.size() - 1); + } + + // Sorts partial array + protected void sort(Vector array, int start, int end) + { + int p; + if (end > start) + { + p = partition(array, start, end); + sort(array, start, p-1); + sort(array, p+1, end); + } + } + + protected int compare(File a, File b) + { + if (age.equalsIgnoreCase(AGE_ELDEST)) + return new Long(a.lastModified()).compareTo(new Long(b.lastModified())); + else + return new Long(b.lastModified()).compareTo(new Long(a.lastModified())); + } + + protected int partition(Vector array, int start, int end) + { + int left, right; + File partitionElement; + + partitionElement = (File)array.elementAt(end); + + left = start - 1; + right = end; + for (;;) + { + while (compare(partitionElement, (File)array.elementAt(++left)) == 1) + { + if (left == end) break; + } + while (compare(partitionElement, (File)array.elementAt(--right)) == -1) + { + if (right == start) break; + } + if (left >= right) break; + swap(array, left, right); + } + swap(array, left, end); + + return left; + } + + protected void swap(Vector array, int i, int j) + { + Object temp; + + temp = array.elementAt(i); + array.setElementAt(array.elementAt(j), i); + array.setElementAt(temp, j); + } + + public void execute() + throws BuildException + { + if (property == null && outputSetId == null) + throw new BuildException("Property or OutputSetId must be specified."); + if (path == null) + throw new BuildException("A path element or pathref attribute must be specified."); + + // Figure out the list of existing file elements + // from the designated path + String s[] = path.list(); + Vector v = new Vector(); + for (int i=0;i<s.length;i++) + { + File f = new File(s[i]); + if (f.exists()) + v.addElement(f); + } + + // Sort the vector, need to make java 1.1 compliant + sort(v); + + // Pull off the first N items + Vector v2 = new Vector(); + int sz = v.size(); + for (int i=0;i<sz && i<count;i++) + v2.add(v.elementAt(i)); + + + + + // Build the resulting Path object + Path path = new Path(getProject()); + sz = v2.size(); + for (int i=0;i<sz;i++) + { + File f = (File)(v.elementAt(i)); + Path p = new Path(getProject(), f.getAbsolutePath()); + path.addExisting(p); + } + + + if (outputSetId != null) + { + // Add the reference to the project + getProject().addReference(outputSetId, path); + } + else + { + // Concat the paths, and put them in a property + // which is separated list of the files, using the + // "pathSep" attribute as the separator + String paths[] = path.list(); + StringBuffer sb = new StringBuffer(); + for (int i=0;i<paths.length;i++) + { + if (i != 0) sb.append(pathSep); + sb.append(paths[i]); + } + + if (paths.length != 0) + getProject().setProperty(property, sb.toString()); + } + } + + + public void setProperty(String property) + { + if (outputSetId != null) + throw new BuildException("Cannot set both Property and OutputSetId."); + + this.property = property; + } + + public void setCount(int count) + { + this.count = count; + } + + public void setAge(String age) + { + if (age.equalsIgnoreCase(AGE_ELDEST) || + age.equalsIgnoreCase(AGE_YOUNGEST)) + this.age = age; + else + throw new BuildException("Invalid age: " + age); + } + + public void setPathSep(char pathSep) + { + this.pathSep = pathSep; + } + + public void setOutputSetId(String outputSetId) + { + if (property != null) + throw new BuildException("Cannot set both Property and OutputSetId."); + this.outputSetId = outputSetId; + } + + public void setPathRef(Reference ref) + throws BuildException + { + if (path == null) + { + path = new Path(getProject()); + path.setRefid(ref); + } + else + { + throw new BuildException("Path element already specified."); + } + } + + + public Path createPath() + throws BuildException + { + if (path == null) + path = new Path(getProject()); + else + throw new BuildException("Path element already specified."); + return path; + } + +} + + diff --git a/src/java/net/sf/antcontrib/logic/TryCatchTask.java b/src/java/net/sf/antcontrib/logic/TryCatchTask.java new file mode 100644 index 0000000..4933e7d --- /dev/null +++ b/src/java/net/sf/antcontrib/logic/TryCatchTask.java @@ -0,0 +1,232 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.logic; + +import java.util.Enumeration; +import java.util.Vector; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.taskdefs.Sequential; + +/** + * A wrapper that lets you run a set of tasks and optionally run a + * different set of tasks if the first set fails and yet another set + * after the first one has finished. + * + * <p>This mirrors Java's try/catch/finally.</p> + * + * <p>The tasks inside of the required <code><try></code> + * element will be run. If one of them should throw a {@link + * org.apache.tools.ant.BuildException BuildException} several things + * can happen:</p> + * + * <ul> + * <li>If there is no <code><catch></code> block, the + * exception will be passed through to Ant.</li> + * + * <li>If the property attribute has been set, a property of the + * given name will be set to the message of the exception.</li> + * + * <li>If the reference attribute has been set, a reference of the + * given id will be created and point to the exception object.</li> + * + * <li>If there is a <code><catch></code> block, the tasks + * nested into it will be run.</li> + * </ul> + * + * <p>If a <code><finally></code> block is present, the task + * nested into it will be run, no matter whether the first tasks have + * thrown an exception or not.</p> + * + * <p><strong>Attributes:</strong></p> + * + * <table> + * <tr> + * <td>Name</td> + * <td>Description</td> + * <td>Required</td> + * </tr> + * <tr> + * <td>property</td> + * <td>Name of a property that will receive the message of the + * exception that has been caught (if any)</td> + * <td>No</td> + * </tr> + * <tr> + * <td>reference</td> + * <td>Id of a reference that will point to the exception object + * that has been caught (if any)</td> + * <td>No</td> + * </tr> + * </table> + * + * <p>Use the following task to define the <code><trycatch></code> + * task before you use it the first time:</p> + * + * <pre><code> + * <taskdef name="trycatch" + * classname="net.sf.antcontrib.logic.TryCatchTask" /> + * </code></pre> + * + * <h3>Crude Example</h3> + * + * <pre><code> + * <trycatch property="foo" reference="bar"> + * <try> + * <fail>Tada!</fail> + * </try> + * + * <catch> + * <echo>In &lt;catch&gt;.</echo> + * </catch> + * + * <finally> + * <echo>In &lt;finally&gt;.</echo> + * </finally> + * </trycatch> + * + * <echo>As property: ${foo}</echo> + * <property name="baz" refid="bar" /> + * <echo>From reference: ${baz}</echo> + * </code></pre> + * + * <p>results in</p> + * + * <pre><code> + * [trycatch] Caught exception: Tada! + * [echo] In <catch>. + * [echo] In <finally>. + * [echo] As property: Tada! + * [echo] From reference: Tada! + * </code></pre> + * + * @author <a href="mailto:[email protected]">Stefan Bodewig</a> + * @author <a href="mailto:[email protected]">Dan Ritchey</a> + */ +public class TryCatchTask extends Task { + + public static final class CatchBlock extends Sequential { + private String throwable = BuildException.class.getName(); + + public CatchBlock() { + super(); + } + + public void setThrowable(String throwable) { + this.throwable = throwable; + } + + public boolean execute(Throwable t) throws BuildException { + try { + Class c = Thread.currentThread().getContextClassLoader().loadClass(throwable); + if (c.isAssignableFrom(t.getClass())) { + execute(); + return true; + } + return false; + } + catch (ClassNotFoundException e) { + throw new BuildException(e); + } + } + } + + + private Sequential tryTasks = null; + private Vector catchBlocks = new Vector(); + private Sequential finallyTasks = null; + private String property = null; + private String reference = null; + + /** + * Adds a nested <try> block - one is required, more is + * forbidden. + */ + public void addTry(Sequential seq) throws BuildException { + if (tryTasks != null) { + throw new BuildException("You must not specify more than one <try>"); + } + + tryTasks = seq; + } + + public void addCatch(CatchBlock cb) { + catchBlocks.add(cb); + } + + /** + * Adds a nested <finally> block - at most one is allowed. + */ + public void addFinally(Sequential seq) throws BuildException { + if (finallyTasks != null) { + throw new BuildException("You must not specify more than one <finally>"); + } + + finallyTasks = seq; + } + + /** + * Sets the property attribute. + */ + public void setProperty(String p) { + property = p; + } + + /** + * Sets the reference attribute. + */ + public void setReference(String r) { + reference = r; + } + + /** + * The heart of the task. + */ + public void execute() throws BuildException { + if (tryTasks == null) { + throw new BuildException("A nested <try> element is required"); + } + + try { + tryTasks.perform(); + } catch (Throwable e) { + if (property != null) { + /* + * Using setProperty instead of setNewProperty to + * be able to compile with Ant < 1.5. + */ + getProject().setProperty(property, e.getMessage()); + } + + if (reference != null) { + getProject().addReference(reference, e); + } + + boolean executed = false; + Enumeration blocks = catchBlocks.elements(); + while (blocks.hasMoreElements() && ! executed) { + CatchBlock cb = (CatchBlock)blocks.nextElement(); + executed = cb.execute(e); + } + } finally { + if (finallyTasks != null) { + finallyTasks.perform(); + } + } + } + +} diff --git a/src/java/net/sf/antcontrib/math/Evaluateable.java b/src/java/net/sf/antcontrib/math/Evaluateable.java new file mode 100644 index 0000000..2e56967 --- /dev/null +++ b/src/java/net/sf/antcontrib/math/Evaluateable.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.math; + +/** + * An object which can evaluate to a numeric value. + * + * @author inger + */ + + +public interface Evaluateable +{ + Number evaluate(); +} diff --git a/src/java/net/sf/antcontrib/math/Math.java b/src/java/net/sf/antcontrib/math/Math.java new file mode 100644 index 0000000..984a2ce --- /dev/null +++ b/src/java/net/sf/antcontrib/math/Math.java @@ -0,0 +1,584 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.math; + +import org.apache.tools.ant.BuildException; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + + +/** + * Utility class for executing calculations. + * + * @author inger + */ + + +public class Math +{ + public static final Number evaluate(String operation, + String datatype, + boolean strict, + Evaluateable operands[]) + { + if (datatype == null) + datatype = "double"; + + try + { + operation = operation.toLowerCase(); + + Method m = Math.class.getDeclaredMethod(operation, + new Class[]{ + String.class, + Boolean.TYPE, + operands.getClass() + }); + Number n = (Number) m.invoke(null, + new Object[]{ + datatype, + strict ? Boolean.TRUE : Boolean.FALSE, + operands + }); + + return n; + } + catch (NoSuchMethodException e) + { + e.printStackTrace(); + } + catch (IllegalAccessException e) + { + e.printStackTrace(); + } + catch (InvocationTargetException e) + { + e.getTargetException().printStackTrace(); + } + return null; + } + + public static final Number add(String datatype, + boolean strict, + Evaluateable operands[]) + { + Number result = null; + + Number numbers[] = new Number[operands.length]; + for (int i = 0; i < operands.length; i++) + numbers[i] = operands[i].evaluate(); + + if (datatype.equalsIgnoreCase("int")) + { + int sum = 0; + for (int i = 0; i < numbers.length; i++) + sum += numbers[i].intValue(); + result = new Integer(sum); + } + else if (datatype.equalsIgnoreCase("long")) + { + long sum = 0; + for (int i = 0; i < numbers.length; i++) + sum += numbers[i].longValue(); + result = new Long(sum); + } + else if (datatype.equalsIgnoreCase("float")) + { + float sum = 0; + for (int i = 0; i < numbers.length; i++) + sum += numbers[i].floatValue(); + result = new Float(sum); + } + else if (datatype.equalsIgnoreCase("double")) + { + double sum = 0; + for (int i = 0; i < numbers.length; i++) + sum += numbers[i].doubleValue(); + result = new Double(sum); + } + return result; + } + + public static final Number subtract(String datatype, + boolean strict, + Evaluateable operands[]) + { + Number result = null; + + Number numbers[] = new Number[operands.length]; + for (int i = 0; i < operands.length; i++) + numbers[i] = operands[i].evaluate(); + + if (datatype.equalsIgnoreCase("int")) + { + int sum = numbers[0].intValue(); + for (int i = 1; i < numbers.length; i++) + sum -= numbers[i].intValue(); + result = new Integer(sum); + } + else if (datatype.equalsIgnoreCase("long")) + { + long sum = numbers[0].longValue(); + for (int i = 1; i < numbers.length; i++) + sum -= numbers[i].longValue(); + result = new Long(sum); + } + else if (datatype.equalsIgnoreCase("float")) + { + float sum = numbers[0].floatValue(); + for (int i = 1; i < numbers.length; i++) + sum -= numbers[i].floatValue(); + result = new Float(sum); + } + else if (datatype.equalsIgnoreCase("double")) + { + double sum = numbers[0].doubleValue(); + for (int i = 1; i < numbers.length; i++) + sum -= numbers[i].doubleValue(); + result = new Double(sum); + } + return result; + } + + public static final Number multiply(String datatype, + boolean strict, + Evaluateable operands[]) + { + Number result = null; + + Number numbers[] = new Number[operands.length]; + for (int i = 0; i < operands.length; i++) + numbers[i] = operands[i].evaluate(); + + if (datatype.equalsIgnoreCase("int")) + { + int sum = 1; + for (int i = 0; i < numbers.length; i++) + sum *= numbers[i].intValue(); + result = new Integer(sum); + } + else if (datatype.equalsIgnoreCase("long")) + { + long sum = 1; + for (int i = 0; i < numbers.length; i++) + sum *= numbers[i].longValue(); + result = new Long(sum); + } + else if (datatype.equalsIgnoreCase("float")) + { + float sum = 1; + for (int i = 0; i < numbers.length; i++) + sum *= numbers[i].floatValue(); + result = new Float(sum); + } + else if (datatype.equalsIgnoreCase("double")) + { + double sum = 1; + for (int i = 0; i < numbers.length; i++) + sum *= numbers[i].doubleValue(); + result = new Double(sum); + } + return result; + } + + public static final Number divide(String datatype, + boolean strict, + Evaluateable operands[]) + { + Number result = null; + + Number numbers[] = new Number[operands.length]; + for (int i = 0; i < operands.length; i++) + numbers[i] = operands[i].evaluate(); + + if (datatype.equalsIgnoreCase("int")) + { + int sum = numbers[0].intValue(); + for (int i = 1; i < numbers.length; i++) + sum /= numbers[i].intValue(); + result = new Integer(sum); + } + else if (datatype.equalsIgnoreCase("long")) + { + long sum = numbers[0].longValue(); + for (int i = 1; i < numbers.length; i++) + sum /= numbers[i].longValue(); + result = new Long(sum); + } + else if (datatype.equalsIgnoreCase("float")) + { + float sum = numbers[0].floatValue(); + for (int i = 1; i < numbers.length; i++) + sum /= numbers[i].floatValue(); + result = new Float(sum); + } + else if (datatype.equalsIgnoreCase("double")) + { + double sum = numbers[0].doubleValue(); + for (int i = 1; i < numbers.length; i++) + sum /= numbers[i].doubleValue(); + result = new Double(sum); + } + return result; + } + + public static final Number mod(String datatype, + boolean strict, + Evaluateable operands[]) + { + Number result = null; + + Number numbers[] = new Number[operands.length]; + for (int i = 0; i < operands.length; i++) + numbers[i] = operands[i].evaluate(); + + if (datatype.equalsIgnoreCase("int")) + { + int sum = numbers[0].intValue(); + for (int i = 1; i < numbers.length; i++) + sum %= numbers[i].intValue(); + result = new Integer(sum); + } + else if (datatype.equalsIgnoreCase("long")) + { + long sum = numbers[0].longValue(); + for (int i = 1; i < numbers.length; i++) + sum %= numbers[i].longValue(); + result = new Long(sum); + } + else if (datatype.equalsIgnoreCase("float")) + { + float sum = numbers[0].floatValue(); + for (int i = 1; i < numbers.length; i++) + sum %= numbers[i].floatValue(); + result = new Float(sum); + } + else if (datatype.equalsIgnoreCase("double")) + { + double sum = numbers[0].doubleValue(); + for (int i = 1; i < numbers.length; i++) + sum %= numbers[i].doubleValue(); + result = new Double(sum); + } + return result; + } + + public static final Number convert(Number n, String datatype) + { + if (datatype == null) + datatype = "double"; + if (datatype.equals("int")) + return new Integer(n.intValue()); + if (datatype.equals("long")) + return new Long(n.longValue()); + if (datatype.equals("float")) + return new Float(n.floatValue()); + if (datatype.equals("double")) + return new Double(n.doubleValue()); + throw new BuildException("Invalid datatype."); + } + + public static final Number execute(String method, + String datatype, + boolean strict, + Class paramTypes[], + Object params[]) + { + try + { + Class c = null; + if (strict) + { + c = Thread.currentThread().getContextClassLoader().loadClass("java.lang.StrictMath"); + } + else + { + c = Thread.currentThread().getContextClassLoader().loadClass("java.lang.Math"); + } + + Method m = c.getDeclaredMethod(method, paramTypes); + Number n = (Number) m.invoke(null, params); + return convert(n, datatype); + } + catch (ClassNotFoundException e) + { + throw new BuildException(e); + } + catch (NoSuchMethodException e) + { + throw new BuildException(e); + } + catch (IllegalAccessException e) + { + throw new BuildException(e); + } + catch (InvocationTargetException e) + { + throw new BuildException(e); + } + } + + public static final Number random(String datatype, + boolean strict, + Evaluateable operands[]) + { + return execute("random", + datatype, + strict, + new Class[0], + new Object[0]); + } + + public static Class getPrimitiveClass(String datatype) + { + if (datatype == null) + return Double.TYPE; + if (datatype.equals("int")) + return Integer.TYPE; + if (datatype.equals("long")) + return Long.TYPE; + if (datatype.equals("float")) + return Float.TYPE; + if (datatype.equals("double")) + return Double.TYPE; + throw new BuildException("Invalid datatype."); + + } + + public static final Number abs(String datatype, + boolean strict, + Evaluateable operands[]) + { + Object ops[] = new Object[]{convert(operands[0].evaluate(), datatype)}; + Class params[] = new Class[]{getPrimitiveClass(datatype)}; + + return execute("abs", + datatype, + strict, + params, + ops); + } + + private static final Number doOneDoubleArg(String operation, + String datatype, + boolean strict, + Evaluateable operands[]) + { + Object ops[] = new Object[]{convert(operands[0].evaluate(), + "double")}; + Class params[] = new Class[]{Double.TYPE}; + + return execute(operation, + datatype, + strict, + params, + ops); + } + + public static final Number acos(String datatype, + boolean strict, + Evaluateable operands[]) + { + return doOneDoubleArg("acos", datatype, strict, operands); + } + + public static final Number asin(String datatype, + boolean strict, + Evaluateable operands[]) + { + return doOneDoubleArg("asin", datatype, strict, operands); + } + + public static final Number atan(String datatype, + boolean strict, + Evaluateable operands[]) + { + return doOneDoubleArg("atan", datatype, strict, operands); + } + + public static final Number atan2(String datatype, + boolean strict, + Evaluateable operands[]) + { + Object ops[] = new Object[]{convert(operands[0].evaluate(), + "double"), + convert(operands[1].evaluate(), + "double")}; + Class params[] = new Class[]{Double.TYPE, + Double.TYPE}; + + return execute("atan2", + datatype, + strict, + params, + ops); + } + + public static final Number sin(String datatype, + boolean strict, + Evaluateable operands[]) + { + return doOneDoubleArg("sin", datatype, strict, operands); + } + + public static final Number tan(String datatype, + boolean strict, + Evaluateable operands[]) + { + return doOneDoubleArg("sin", datatype, strict, operands); + } + + public static final Number cos(String datatype, + boolean strict, + Evaluateable operands[]) + { + return doOneDoubleArg("cos", datatype, strict, operands); + } + + public static final Number ceil(String datatype, + boolean strict, + Evaluateable operands[]) + { + return doOneDoubleArg("ceil", datatype, strict, operands); + } + + public static final Number floor(String datatype, + boolean strict, + Evaluateable operands[]) + { + return doOneDoubleArg("floor", datatype, strict, operands); + } + + public static final Number exp(String datatype, + boolean strict, + Evaluateable operands[]) + { + return doOneDoubleArg("exp", datatype, strict, operands); + } + + public static final Number rint(String datatype, + boolean strict, + Evaluateable operands[]) + { + return doOneDoubleArg("rint", datatype, strict, operands); + } + + public static final Number round(String datatype, + boolean strict, + Evaluateable operands[]) + { + Object ops[] = new Object[]{convert(operands[0].evaluate(), + datatype)}; + Class params[] = new Class[]{getPrimitiveClass(datatype)}; + + return execute("round", + datatype, + strict, + params, + ops); + } + + public static final Number sqrt(String datatype, + boolean strict, + Evaluateable operands[]) + { + return doOneDoubleArg("sqrt", datatype, strict, operands); + } + + public static final Number degrees(String datatype, + boolean strict, + Evaluateable operands[]) + { + return todegrees(datatype, strict, operands); + } + + public static final Number todegrees(String datatype, + boolean strict, + Evaluateable operands[]) + { + return doOneDoubleArg("toDegrees", datatype, strict, operands); + } + + public static final Number radians(String datatype, + boolean strict, + Evaluateable operands[]) + { + return toradians(datatype, strict, operands); + } + + public static final Number toradians(String datatype, + boolean strict, + Evaluateable operands[]) + { + return doOneDoubleArg("toRadians", datatype, strict, operands); + } + + public static final Number ieeeremainder(String datatype, + boolean strict, + Evaluateable operands[]) + { + Object ops[] = new Object[]{convert(operands[0].evaluate(), + "double"), + convert(operands[1].evaluate(), + "double")}; + Class params[] = new Class[]{Double.TYPE, + Double.TYPE}; + + return execute("IEEERemainder", + datatype, + strict, + params, + ops); + } + + public static final Number min(String datatype, + boolean strict, + Evaluateable operands[]) + { + Object ops[] = new Object[]{convert(operands[0].evaluate(), + datatype), + convert(operands[1].evaluate(), + datatype)}; + Class params[] = new Class[]{getPrimitiveClass(datatype), + getPrimitiveClass(datatype)}; + + return execute("min", + datatype, + strict, + params, + ops); + } + + public static final Number max(String datatype, + boolean strict, + Evaluateable operands[]) + { + Object ops[] = new Object[]{convert(operands[0].evaluate(), + datatype), + convert(operands[1].evaluate(), + datatype)}; + Class params[] = new Class[]{getPrimitiveClass(datatype), + getPrimitiveClass(datatype)}; + + return execute("max", + datatype, + strict, + params, + ops); + } + +} diff --git a/src/java/net/sf/antcontrib/math/MathTask.java b/src/java/net/sf/antcontrib/math/MathTask.java new file mode 100644 index 0000000..bdcc12d --- /dev/null +++ b/src/java/net/sf/antcontrib/math/MathTask.java @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.math; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.DynamicConfigurator; + +/** + * Task for mathematical operations. + * + * @author inger + */ + + +public class MathTask + extends Task + implements DynamicConfigurator +{ + // storage for result + private String result = null; + private Operation operation = null; + private Operation locOperation = null; + private String datatype = null; + private boolean strict = false; + + public MathTask() + { + super(); + } + + public void execute() + throws BuildException + { + Operation op = locOperation; + if (op == null) + op = operation; + + Number res = op.evaluate(); + + if (datatype != null) + res = Math.convert(res, datatype); + getProject().setUserProperty(result, res.toString()); + } + + public void setDynamicAttribute(String s, String s1) + throws BuildException { + throw new BuildException("No dynamic attributes for this task"); + } + + public Object createDynamicElement(String name) + throws BuildException { + Operation op = new Operation(); + op.setOperation(name); + operation = op; + return op; + } + + public void setResult(String result) + { + this.result = result; + } + + public void setDatatype(String datatype) + { + this.datatype = datatype; + } + + public void setStrict(boolean strict) + { + this.strict = strict; + } + + private Operation getLocalOperation() + { + if (locOperation == null) + { + locOperation = new Operation(); + locOperation.setDatatype(datatype); + locOperation.setStrict(strict); + } + return locOperation; + } + + public void setOperation(String operation) + { + getLocalOperation().setOperation(operation); + } + + public void setDataType(String dataType) + { + getLocalOperation().setDatatype(dataType); + } + + public void setOperand1(String operand1) + { + Numeric n = new Numeric(); + n.setValue(operand1); + getLocalOperation().addConfiguredNumeric(n); + } + + public void setOperand2(String operand2) + { + Numeric n = new Numeric(); + n.setValue(operand2); + getLocalOperation().addConfiguredNumeric(n); + } + + public Operation createOperation() + { + if (locOperation != null || operation != null) + throw new BuildException("Doh!!!"); + this.operation = new Operation(); + this.operation.setStrict(strict); + this.operation.setDatatype(datatype); + return this.operation; + } + + // conform to old task + public Operation createOp() + { + return createOperation(); + } +} diff --git a/src/java/net/sf/antcontrib/math/Numeric.java b/src/java/net/sf/antcontrib/math/Numeric.java new file mode 100644 index 0000000..1164e14 --- /dev/null +++ b/src/java/net/sf/antcontrib/math/Numeric.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.math; + +import org.apache.tools.ant.BuildException; + + +/** + * A numeric value that implements Evaluateable. + * + * @author inger + */ + + +public class Numeric + implements Evaluateable +{ + private String datatype; + private String value; + + /** + * Set the value for this number. This string must parse to the set + * datatype, for example, setting value to "7.992" and datatype to INT + * will cause a number format exception to be thrown. Supports two special + * numbers, "E" and "PI". + * + * @param value the value for this number + */ + public void setValue(String value) + { + if (value.equals("E")) + value = String.valueOf(java.lang.Math.E); + else if (value.equals("PI")) + value = String.valueOf(java.lang.Math.PI); + this.value = value; + } + + /** + * @return the value for this number as a Number. Cast as appropriate to + * Integer, Long, Float, or Double. + */ + public Number evaluate() + { + if (datatype == null) + datatype = "double"; + if (datatype.equals("int")) + return new Integer(value); + if (datatype.equals("long")) + return new Long(value); + if (datatype.equals("float")) + return new Float(value); + if (datatype.equals("double")) + return new Double(value); + throw new BuildException("Invalid datatype."); + } + + /** + * Sets the datatype of this number. Allowed values are + * "int", "long", "float", or "double". + */ + public void setDatatype(String p) + { + datatype = p; + } + + /** + * @return the datatype as one of the defined types. + */ + public String getDatatype() + { + if (datatype == null) + datatype = "double"; + return datatype; + } + + public String toString() + { + return "Numeric[value=" + value + + ";datatype=" + datatype + + "]"; + } +} diff --git a/src/java/net/sf/antcontrib/math/Operation.java b/src/java/net/sf/antcontrib/math/Operation.java new file mode 100644 index 0000000..8727a10 --- /dev/null +++ b/src/java/net/sf/antcontrib/math/Operation.java @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.math; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.DynamicConfigurator; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Vector; + +/** + * Class to represent a mathematical operation. + * + * @author inger + */ + + +public class Operation + implements Evaluateable, DynamicConfigurator { + private String operation = "add"; + private Vector operands = new Vector(); + private String datatype = "double"; + private boolean strict = false; + + private boolean hasLocalOperands = false; + private Numeric localOperands[] = new Numeric[5]; + + public void setDynamicAttribute(String s, String s1) + throws BuildException { + throw new BuildException("no dynamic attributes for this element"); + } + + public Object createDynamicElement(String name) + throws BuildException { + Operation op = new Operation(); + op.setOperation(name); + operands.add(op); + return op; + } + + private void setLocalOperand(String value, int index) { + hasLocalOperands = true; + localOperands[index - 1] = new Numeric(); + localOperands[index - 1].setValue(value); + } + + public void setArg1(String value) { + setLocalOperand(value, 1); + } + + public void setArg2(String value) { + setLocalOperand(value, 2); + } + + public void setArg3(String value) { + setLocalOperand(value, 3); + } + + public void setArg4(String value) { + setLocalOperand(value, 4); + } + + public void setArg5(String value) { + setLocalOperand(value, 5); + } + + public void addConfiguredNumeric(Numeric numeric) { + if (hasLocalOperands) + throw new BuildException("Cannot combine operand attributes with subelements"); + + operands.add(numeric); + } + + public void addConfiguredOperation(Operation operation) { + if (hasLocalOperands) + throw new BuildException("Cannot combine operand attributes with subelements"); + + operands.add(operation); + } + + public void addConfiguredNum(Numeric numeric) { + if (hasLocalOperands) + throw new BuildException("Cannot combine operand attributes with subelements"); + + operands.add(numeric); + } + + public void addConfiguredOp(Operation operation) { + if (hasLocalOperands) + throw new BuildException("Cannot combine operand attributes with subelements"); + + operands.add(operation); + } + + public void setOp(String operation) { + setOperation(operation); + } + + public void setOperation(String operation) { + if (operation.equals("+")) + this.operation = "add"; + else if (operation.equals("-")) + this.operation = "subtract"; + else if (operation.equals("*")) + this.operation = "multiply"; + else if (operation.equals("/")) + this.operation = "divide"; + else if (operation.equals("%")) + this.operation = "mod"; + else + this.operation = operation; + } + + public void setDatatype(String datatype) { + this.datatype = datatype; + } + + public void setStrict(boolean strict) { + this.strict = strict; + } + + public Number evaluate() { + Evaluateable ops[] = null; + + if (hasLocalOperands) { + List localOps = new ArrayList(); + for (int i = 0; i < localOperands.length; i++) { + if (localOperands[i] != null) + localOps.add(localOperands[i]); + } + + ops = (Evaluateable[]) localOps.toArray(new Evaluateable[localOps.size()]); + } + else { + ops = (Evaluateable[]) operands.toArray(new Evaluateable[operands.size()]); + } + + return Math.evaluate(operation, + datatype, + strict, + ops); + } + + public String toString() { + return "Operation[operation=" + operation + + ";datatype=" + datatype + + ";strict=" + strict + + ";localoperands=" + Arrays.asList(localOperands) + + ";operands=" + operands + + "]"; + } +} diff --git a/src/java/net/sf/antcontrib/net/PostTask.java b/src/java/net/sf/antcontrib/net/PostTask.java new file mode 100644 index 0000000..4f1d5b0 --- /dev/null +++ b/src/java/net/sf/antcontrib/net/PostTask.java @@ -0,0 +1,751 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.net; + +import java.io.BufferedReader; +import java.io.DataOutputStream; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.HttpURLConnection; + +import java.net.URL; +import java.net.URLConnection; +import java.net.URLDecoder; +import java.net.URLEncoder; + +import java.rmi.server.UID; + +import java.util.*; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.ProjectHelper; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.TaskContainer; + +/** + * This task does an http post. Name/value pairs for the post can be set in + * either or both of two ways, by nested Prop elements and/or by a file + * containing properties. Nested Prop elements are automatically configured by + * Ant. Properties from a file are configured by code borrowed from Property so + * all Ant property constructs (like ${somename}) are resolved prior to the + * post. This means that a file can be set up in advance of running the build + * and the appropriate property values will be filled in at run time. + * + * @author Dale Anson, [email protected] + * @version $Revision: 1.11 $ + */ +public class PostTask extends Task { + + /** Storage for name/value pairs to send. */ + private Hashtable props = new Hashtable(); + /** URL to send the name/value pairs to. */ + private URL to = null; + /** File to read name/value pairs from. */ + private File propsFile = null; + /** storage for Ant properties */ + private String textProps = null; + /** encoding to use for the name/value pairs */ + private String encoding = "UTF-8"; + /** where to store the server response */ + private File log = null; + /** append to the log? */ + private boolean append = true; + /** verbose? */ + private boolean verbose = true; + /** want to keep the server response? */ + private boolean wantResponse = true; + /** store output in a property */ + private String property = null; + + /** how long to wait for a response from the server */ + private long maxwait = 180000; // units for maxwait is milliseconds + /** fail on error? */ + private boolean failOnError = false; + + // storage for cookies + private static Hashtable cookieStorage = new Hashtable(); + + /** connection to the server */ + private URLConnection connection = null; + /** for thread handling */ + private Thread currentRunner = null; + + + + /** + * Set the url to post to. Required. + * + * @param name the url to post to. + */ + public void setTo( URL name ) { + to = name; + } + + + /** + * Set the name of a file to read a set of properties from. + * + * @param f the file + */ + public void setFile( File f ) { + propsFile = f; + } + + + /** + * Set the name of a file to save the response to. Optional. Ignored if + * "want response" is false. + * + * @param f the file + */ + public void setLogfile( File f ) { + log = f; + } + + + /** + * Should the log file be appended to or overwritten? Default is true, + * append to the file. + * + * @param b append or not + */ + public void setAppend( boolean b ) { + append = b; + } + + + /** + * If true, progress messages and returned data from the post will be + * displayed. Default is true. + * + * @param b true = verbose + */ + public void setVerbose( boolean b ) { + verbose = b; + } + + + /** + * Default is true, get the response from the post. Can be set to false for + * "fire and forget" messages. + * + * @param b print/log server response + */ + public void setWantresponse( boolean b ) { + wantResponse = b; + } + + /** + * Set the name of a property to save the response to. Optional. Ignored if + * "wantResponse" is false. + * @param name the name to use for the property + */ + public void setProperty( String name ) { + property = name; + } + + /** + * Sets the encoding of the outgoing properties, default is UTF-8. + * + * @param encoding The new encoding value + */ + public void setEncoding( String encoding ) { + this.encoding = encoding; + } + + + /** + * How long to wait on the remote server. As a post is generally a two part + * process (sending and receiving), maxwait is applied separately to each + * part, that is, if 180 is passed as the wait parameter, this task will + * spend at most 3 minutes to connect to the remote server and at most + * another 3 minutes waiting on a response after the post has been sent. + * This means that the wait period could total as much as 6 minutes (or 360 + * seconds). <p> + * + * The default wait period is 3 minutes (180 seconds). + * + * @param wait time to wait in seconds, set to 0 to wait forever. + */ + public void setMaxwait( int wait ) { + maxwait = wait * 1000; + } + + + /** + * Should the build fail if the post fails? + * + * @param fail true = fail the build, default is false + */ + public void setFailonerror( boolean fail ) { + failOnError = fail; + } + + /** + * Adds a name/value pair to post. Optional. + * + * @param p A property pair to send as part of the post. + * @exception BuildException When name and/or value are missing. + */ + public void addConfiguredProp( Prop p ) throws BuildException { + String name = p.getName(); + if ( name == null ) { + throw new BuildException( "name is null", getLocation() ); + } + String value = p.getValue(); + if ( value == null ) { + value = getProject().getProperty( name ); + } + if ( value == null ) { + throw new BuildException( "value is null", getLocation() ); + } + props.put( name, value ); + } + + + /** + * Adds a feature to the Text attribute of the PostTask object + * + * @param text The feature to be added to the Text attribute + */ + public void addText( String text ) { + textProps = text; + } + + + /** + * Do the post. + * + * @exception BuildException On any error. + */ + public void execute() throws BuildException { + if ( to == null ) { + throw new BuildException( "'to' attribute is required", getLocation() ); + } + final String content = getContent(); + try { + if ( verbose ) + log( "Opening connection for post to " + to.toString() + "..." ); + + // do the POST + Thread runner = + new Thread() { + public void run() { + DataOutputStream out = null; + try { + // set the url connection properties + connection = to.openConnection(); + connection.setDoInput( true ); + connection.setDoOutput( true ); + connection.setUseCaches( false ); + connection.setRequestProperty( + "Content-Type", + "application/x-www-form-urlencoded" ); + + // check if there are cookies to be included + for ( Iterator it = cookieStorage.keySet().iterator(); it.hasNext(); ) { + StringBuffer sb = new StringBuffer(); + Object name = it.next(); + if ( name != null ) { + String key = name.toString(); + Cookie cookie = ( Cookie ) cookieStorage.get( name ); + if ( to.getPath().startsWith( cookie.getPath() ) ) { + connection.addRequestProperty( "Cookie", cookie.toString() ); + } + } + } + + // do the post + if ( verbose ) { + log( "Connected, sending data..." ); + } + out = new DataOutputStream( connection.getOutputStream() ); + if ( verbose ) { + log( content ); + } + out.writeBytes( content ); + out.flush(); + if ( verbose ) { + log( "Data sent." ); + } + } + catch ( Exception e ) { + if ( failOnError ) { + throw new BuildException( e, getLocation() ); + } + } + finally { + try { + out.close(); + } + catch ( Exception e ) { + // ignored + } + } + } + } + ; + runner.start(); + runner.join( maxwait ); + if ( runner.isAlive() ) { + runner.interrupt(); + if ( failOnError ) { + throw new BuildException( "maxwait exceeded, unable to send data", getLocation() ); + } + return ; + } + + // read the response, if any, optionally writing it to a file + if ( wantResponse ) { + if ( verbose ) { + log( "Waiting for response..." ); + } + runner = + new Thread() { + public void run() { + PrintWriter fw = null; + StringWriter sw = null; + PrintWriter pw = null; + BufferedReader in = null; + try { + if ( connection instanceof HttpURLConnection ) { + // read and store cookies + Map map = ( ( HttpURLConnection ) connection ).getHeaderFields(); + for ( Iterator it = map.keySet().iterator(); it.hasNext(); ) { + String name = ( String ) it.next(); + if ( name != null && name.equals( "Set-Cookie" ) ) { + List cookies = ( List ) map.get( name ); + for ( Iterator c = cookies.iterator(); c.hasNext(); ) { + String raw = ( String ) c.next(); + Cookie cookie = new Cookie( raw ); + cookieStorage.put( cookie.getId(), cookie ); + } + } + } + + // maybe log response headers + if ( verbose ) { + log( String.valueOf( ( ( HttpURLConnection ) connection ).getResponseCode() ) ); + log( ( ( HttpURLConnection ) connection ).getResponseMessage() ); + StringBuffer sb = new StringBuffer(); + map = ( ( HttpURLConnection ) connection ).getHeaderFields(); + for ( Iterator it = map.keySet().iterator(); it.hasNext(); ) { + String name = ( String ) it.next(); + sb.append( name ).append( "=" ); + List values = ( List ) map.get( name ); + if ( values != null ) { + if ( values.size() == 1 ) + sb.append( values.get( 0 ) ); + else if ( values.size() > 1 ) { + sb.append( "[" ); + for ( Iterator v = values.iterator(); v.hasNext(); ) { + sb.append( v.next() ).append( "," ); + } + sb.append( "]" ); + } + } + sb.append( "\n" ); + log( sb.toString() ); + } + } + } + in = new BufferedReader( + new InputStreamReader( connection.getInputStream() ) ); + if ( log != null ) { + // user wants output stored to a file + fw = new PrintWriter( new FileWriter( log, append ) ); + } + if ( property != null ) { + // user wants output stored in a property + sw = new StringWriter(); + pw = new PrintWriter( sw ); + } + String line; + while ( null != ( ( line = in.readLine() ) ) ) { + if ( currentRunner != this ) { + break; + } + if ( verbose ) { + log( line ); + } + if ( fw != null ) { + // write response to a file + fw.println( line ); + } + if ( pw != null ) { + // write response to a property + pw.println( line ); + } + } + } + catch ( Exception e ) { + //e.printStackTrace(); + if ( failOnError ) { + throw new BuildException( e, getLocation() ); + } + } + finally { + try { + in.close(); + } + catch ( Exception e ) { + // ignored + } + try { + if ( fw != null ) { + fw.flush(); + fw.close(); + } + } + catch ( Exception e ) { + // ignored + } + } + if ( property != null && sw != null ) { + // save property + getProject().setProperty( property, sw.toString() ); + } + } + }; + currentRunner = runner; + runner.start(); + runner.join( maxwait ); + if ( runner.isAlive() ) { + currentRunner = null; + runner.interrupt(); + if ( failOnError ) { + throw new BuildException( "maxwait exceeded, unable to receive data", getLocation() ); + } + } + } + if ( verbose ) + log( "Post complete." ); + } + catch ( Exception e ) { + if ( failOnError ) { + throw new BuildException( e ); + } + } + } + + + /** + * Borrowed from Property -- load variables from a file + * + * @param file file to load + * @exception BuildException Description of the Exception + */ + private void loadFile( File file ) throws BuildException { + Properties fileprops = new Properties(); + try { + if ( file.exists() ) { + FileInputStream fis = new FileInputStream( file ); + try { + fileprops.load( fis ); + } + finally { + if ( fis != null ) { + fis.close(); + } + } + addProperties( fileprops ); + } + else { + log( "Unable to find property file: " + file.getAbsolutePath(), + Project.MSG_VERBOSE ); + } + log( "Post complete." ); + } + catch ( Exception e ) { + if ( failOnError ) { + throw new BuildException( e ); + } + } + } + + + /** + * Builds and formats the message to send to the server. Message is UTF-8 + * encoded unless encoding has been explicitly set. + * + * @return the message to send to the server. + */ + private String getContent() { + if ( propsFile != null ) { + loadFile( propsFile ); + } + + if ( textProps != null ) { + loadTextProps( textProps ); + } + + StringBuffer content = new StringBuffer(); + try { + Enumeration en = props.keys(); + while ( en.hasMoreElements() ) { + String name = ( String ) en.nextElement(); + String value = ( String ) props.get( name ); + content.append( URLEncoder.encode( name, encoding ) ); + content.append( "=" ); + content.append( URLEncoder.encode( value, encoding ) ); + if ( en.hasMoreElements() ) { + content.append( "&" ); + } + } + } + catch ( IOException ex ) { + if ( failOnError ) { + throw new BuildException( ex, getLocation() ); + } + } + return content.toString(); + } + + + /** + * Description of the Method + * + * @param tp + */ + private void loadTextProps( String tp ) { + Properties p = new Properties(); + Project project = getProject(); + StringTokenizer st = new StringTokenizer( tp, "$" ); + while ( st.hasMoreTokens() ) { + String token = st.nextToken(); + int start = token.indexOf( "{" ); + int end = token.indexOf( "}" ); + if ( start > -1 && end > -1 && end > start ) { + String name = token.substring( start + 1, end - start ); + String value = project.getProperty( name ); + if ( value != null ) + p.setProperty( name, value ); + } + } + addProperties( p ); + } + + + /** + * Borrowed from Property -- iterate through a set of properties, resolve + * them, then assign them + * + * @param fileprops The feature to be added to the Properties attribute + */ + private void addProperties( Properties fileprops ) { + resolveAllProperties( fileprops ); + Enumeration e = fileprops.keys(); + while ( e.hasMoreElements() ) { + String name = ( String ) e.nextElement(); + String value = fileprops.getProperty( name ); + props.put( name, value ); + } + } + + + /** + * Borrowed from Property -- resolve properties inside a properties + * hashtable + * + * @param fileprops Description of the Parameter + * @exception BuildException Description of the Exception + */ + private void resolveAllProperties( Properties fileprops ) throws BuildException { + for ( Enumeration e = fileprops.keys(); e.hasMoreElements(); ) { + String name = ( String ) e.nextElement(); + String value = fileprops.getProperty( name ); + + boolean resolved = false; + while ( !resolved ) { + Vector fragments = new Vector(); + Vector propertyRefs = new Vector(); + /// this is the Ant 1.5 way of doing it. The Ant 1.6 PropertyHelper + /// should be used -- eventually. + ProjectHelper.parsePropertyString( value, fragments, + propertyRefs ); + + resolved = true; + if ( propertyRefs.size() != 0 ) { + StringBuffer sb = new StringBuffer(); + Enumeration i = fragments.elements(); + Enumeration j = propertyRefs.elements(); + while ( i.hasMoreElements() ) { + String fragment = ( String ) i.nextElement(); + if ( fragment == null ) { + String propertyName = ( String ) j.nextElement(); + if ( propertyName.equals( name ) ) { + throw new BuildException( "Property " + name + + " was circularly " + + "defined." ); + } + fragment = getProject().getProperty( propertyName ); + if ( fragment == null ) { + if ( fileprops.containsKey( propertyName ) ) { + fragment = fileprops.getProperty( propertyName ); + resolved = false; + } + else { + fragment = "${" + propertyName + "}"; + } + } + } + sb.append( fragment ); + } + value = sb.toString(); + fileprops.put( name, value ); + } + } + } + } + + /** + * Represents a cookie. See RFC 2109 and 2965. + */ + public class Cookie { + private String name; + private String value; + private String domain; + private String path = "/"; + private String id; + + /** + * @param raw the raw string abstracted from the header of an http response + * for a single cookie. + */ + public Cookie( String raw ) { + String[] args = raw.split( "[;]" ); + for ( int i = 0; i < args.length; i++ ) { + String part = args[ i ]; + int eq_index = part.indexOf("="); + if (eq_index == -1) + continue; + String first_part = part.substring(0, eq_index).trim(); + String second_part = part.substring(eq_index + 1); + if ( i == 0 ) { + name = first_part; + value = second_part; + } + else if ( first_part.equalsIgnoreCase( "Path" ) ) + path = second_part; + else if ( first_part.equalsIgnoreCase( "Domain" ) ) + domain = second_part; + } + if (name == null) + throw new IllegalArgumentException("Raw cookie does not contain a cookie name."); + if (path == null) + path = "/"; + setId(path, name); + } + + /** + * @param name name of the cookie + * @param value the value of the cookie + */ + public Cookie( String name, String value ) { + if (name == null) + throw new IllegalArgumentException("Cookie name may not be null."); + + this.name = name; + this.value = value; + setId(name); + } + + /** + * @return the id of the cookie, used internally by Post to store the cookie + * in a hashtable. + */ + public String getId() { + if (id == null) + setId(path, name); + return id.toString(); + } + + private void setId(String name) { + setId(path, name); + } + + private void setId(String path, String name) { + if (name == null) + name = ""; + id = path + name; + } + + /** + * @return the name of the cookie + */ + public String getName() { + return name; + } + + /** + * @return the value of the cookie + */ + public String getValue() { + return value; + } + + /** + * @param domain the domain of the cookie + */ + public void setDomain( String domain ) { + this.domain = domain; + } + + /** + * @return the domain of the cookie + */ + public String getDomain() { + return domain; + } + + /** + * @param path the path of the cookie + */ + public void setPath( String path ) { + this.path = path; + } + + /** + * @return the path of the cookie + */ + public String getPath() { + return path; + } + + /** + * @return a Cookie formatted as a Cookie Version 1 string. The returned + * string is suitable for including with an http request. + */ + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append( name ).append( "=" ).append( value ).append( ";" ); + if ( domain != null ) + sb.append( "Domain=" ).append( domain ).append( ";" ); + if ( path != null ) + sb.append( "Path=" ).append( path ).append( ";" ); + sb.append( "Version=\"1\";" ); + return sb.toString(); + } + } +} + diff --git a/src/java/net/sf/antcontrib/net/Prop.java b/src/java/net/sf/antcontrib/net/Prop.java new file mode 100644 index 0000000..8e4fdcb --- /dev/null +++ b/src/java/net/sf/antcontrib/net/Prop.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.net; + +/** + * Simple bean to represent a name/value pair. + * <p>Developed for use with Antelope, migrated to ant-contrib Oct 2003. + * + * @author Dale Anson, [email protected] + * @version $Revision: 1.3 $ + */ +public class Prop { + private String name = null; + private String value = null; + public void setName( String name ) { + this.name = name; + } + public String getName() { + return name; + } + public void setValue( String value ) { + this.value = value; + } + public String getValue() { + return value; + } +} + diff --git a/src/java/net/sf/antcontrib/perf/AntPerformanceListener.java b/src/java/net/sf/antcontrib/perf/AntPerformanceListener.java new file mode 100644 index 0000000..ba8ea5b --- /dev/null +++ b/src/java/net/sf/antcontrib/perf/AntPerformanceListener.java @@ -0,0 +1,320 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.perf; + +import java.io.File; +import java.io.FileWriter; +import java.text.SimpleDateFormat; +import java.util.*; + +import org.apache.tools.ant.*; + +/** + * This BuildListener keeps track of the total time it takes for each target and + * task to execute, then prints out the totals when the build is finished. This + * can help pinpoint the areas where a build is taking a lot of time so + * optimization efforts can focus where they'll do the most good. Execution times + * are grouped by targets and tasks, and are sorted from fastest running to + * slowest running. + * + * Output can be saved to a file by setting a property in Ant. Set + * "performance.log" to the name of a file. This can be set either on the + * command line with the -D option (-Dperformance.log=/tmp/performance.log) + * or in the build file itself (<property name="performance.log" + * location="/tmp/performance.log"/>). + * <p>Developed for use with Antelope, migrated to ant-contrib Oct 2003. + * + * @author Dale Anson, [email protected] + * @version $Revision: 1.5 $ + */ +public class AntPerformanceListener implements BuildListener { + + private HashMap targetStats = new HashMap(); // key is Target, value is StopWatch + private HashMap taskStats = new HashMap(); // key is Task, value is StopWatch + private StopWatch master = null; + private long start_time = 0; + + /** + * Starts a 'running total' stopwatch. + */ + public void buildStarted( BuildEvent be ) { + master = new StopWatch(); + start_time = master.start(); + } + + /** + * Sorts and prints the results. + */ + public void buildFinished( BuildEvent be ) { + long stop_time = master.stop(); + + // sort targets, key is StopWatch, value is Target + TreeMap sortedTargets = new TreeMap( new StopWatchComparator() ); + Iterator it = targetStats.keySet().iterator(); + while ( it.hasNext() ) { + Object key = it.next(); + Object value = targetStats.get( key ); + sortedTargets.put( value, key ); + } + + // sort tasks, key is StopWatch, value is Task + TreeMap sortedTasks = new TreeMap( new StopWatchComparator() ); + it = taskStats.keySet().iterator(); + while ( it.hasNext() ) { + Object key = it.next(); + Object value = taskStats.get( key ); + sortedTasks.put( value, key ); + } + + // print the sorted results + StringBuffer msg = new StringBuffer(); + String lSep = System.getProperty( "line.separator" ); + msg.append( lSep ).append("Statistics:").append( lSep ); + msg.append( "-------------- Target Results ---------------------" ).append( lSep ); + it = sortedTargets.keySet().iterator(); + while ( it.hasNext() ) { + StopWatch key = ( StopWatch ) it.next(); + StringBuffer sb = new StringBuffer(); + Target target = ( Target ) sortedTargets.get( key ); + if (target != null) { + Project p = target.getProject(); + if (p != null && p.getName() != null) + sb.append( p.getName() ).append( "." ); + String total = format( key.total() ); + String target_name = target.getName(); + if (target_name == null || target_name.length() == 0) + target_name = "<implicit>"; + sb.append( target_name ).append( ": " ).append( total ); + } + msg.append( sb.toString() ).append( lSep ); + } + msg.append( lSep ); + msg.append( "-------------- Task Results -----------------------" ).append( lSep ); + it = sortedTasks.keySet().iterator(); + while ( it.hasNext() ) { + StopWatch key = ( StopWatch ) it.next(); + Task task = ( Task ) sortedTasks.get( key ); + StringBuffer sb = new StringBuffer(); + Target target = task.getOwningTarget(); + if (target != null) { + Project p = target.getProject(); + if (p != null && p.getName() != null) + sb.append( p.getName() ).append( "." ); + String target_name = target.getName(); + if (target_name == null || target_name.length() == 0) + target_name = "<implicit>"; + sb.append( target_name ).append( "." ); + } + sb.append( task.getTaskName() ).append( ": " ).append( format( key.total() ) ); + msg.append( sb.toString() ).append( lSep ); + } + + msg.append( lSep ); + msg.append( "-------------- Totals -----------------------------" ).append( lSep ); + SimpleDateFormat format = new SimpleDateFormat( "EEE, d MMM yyyy HH:mm:ss.SSS" ); + msg.append( "Start time: " + format.format( new Date( start_time ) ) ).append( lSep ); + msg.append( "Stop time: " + format.format( new Date( stop_time ) ) ).append( lSep ); + msg.append( "Total time: " + format( master.total() ) ).append( lSep ); + System.out.println( msg.toString() ); + + // write stats to file? + Project p = be.getProject(); + File outfile = null; + if ( p != null ) { + String f = p.getProperty( "performance.log" ); + if ( f != null ) + outfile = new File( f ); + } + if ( outfile != null ) { + try { + FileWriter fw = new FileWriter( outfile ); + fw.write( msg.toString() ); + fw.flush(); + fw.close(); + System.out.println( "Wrote stats to: " + outfile.getAbsolutePath() + lSep); + } + catch ( Exception e ) { + // ignored + } + } + + // reset the stats registers + + targetStats = new HashMap(); + taskStats = new HashMap(); + } + + /** + * Formats the milliseconds from a StopWatch into decimal seconds. + */ + private String format( long ms ) { + String total = String.valueOf( ms ); + String frontpad = "000"; + int pad_length = 3 - total.length(); + if ( pad_length >= 0 ) + total = "0." + frontpad.substring( 0, pad_length ) + total; + else { + total = total.substring( 0, total.length() - 3 ) + "." + total.substring( total.length() - 3 ); + } + return total + " sec"; + } + + /** + * Start timing the given target. + */ + public void targetStarted( BuildEvent be ) { + StopWatch sw = new StopWatch(); + sw.start(); + targetStats.put( be.getTarget(), sw ); + } + + /** + * Stop timing the given target. + */ + public void targetFinished( BuildEvent be ) { + StopWatch sw = ( StopWatch ) targetStats.get( be.getTarget() ); + sw.stop(); + } + + /** + * Start timing the given task. + */ + public void taskStarted( BuildEvent be ) { + StopWatch sw = new StopWatch(); + sw.start(); + taskStats.put( be.getTask(), sw ); + } + + /** + * Stop timing the given task. + */ + public void taskFinished( BuildEvent be ) { + StopWatch sw = ( StopWatch ) taskStats.get( be.getTask() ); + if (sw != null) + sw.stop(); + } + + /** + * no-op + */ + public void messageLogged( BuildEvent be ) { + // does nothing + } + + /** + * Compares the total times for two StopWatches. + */ + public class StopWatchComparator implements Comparator { + /** + * Compares the total times for two StopWatches. + */ + public int compare( Object o1, Object o2 ) { + StopWatch a = ( StopWatch ) o1; + StopWatch b = ( StopWatch ) o2; + if ( a.total() < b.total() ) + return -1; + else if ( a.total() == b.total() ) + return 0; + else + return 1; + } + } + + /** + * A stopwatch, useful for 'quick and dirty' performance testing. + * @author Dale Anson + * @version $Revision: 1.5 $ + */ + public class StopWatch { + + /** + * storage for start time + */ + private long _start_time = 0; + /** + * storage for stop time + */ + private long _stop_time = 0; + + /** + * cumulative elapsed time + */ + private long _total_time = 0; + + /** + * Starts the stopwatch. + */ + public StopWatch() { + start(); + } + + /** + * Starts/restarts the stopwatch. + * + * @return the start time, the long returned System.currentTimeMillis(). + */ + public long start() { + _start_time = System.currentTimeMillis(); + return _start_time; + } + + /** + * Stops the stopwatch. + * + * @return the stop time, the long returned System.currentTimeMillis(). + */ + public long stop() { + long stop_time = System.currentTimeMillis(); + _total_time += stop_time - _start_time; + _start_time = 0; + _stop_time = 0; + return stop_time; + } + + /** + * Total cumulative elapsed time. + * + * @return the total time + */ + public long total() { + return _total_time; + } + + /** + * Elapsed time, difference between the last start time and now. + * + * @return the elapsed time + */ + public long elapsed() { + return System.currentTimeMillis() - _start_time; + } + } + + // quick test for the formatter + public static void main ( String[] args ) { + AntPerformanceListener apl = new AntPerformanceListener(); + + System.out.println( apl.format( 1 ) ); + System.out.println( apl.format( 10 ) ); + System.out.println( apl.format( 100 ) ); + System.out.println( apl.format( 1000 ) ); + System.out.println( apl.format( 100000 ) ); + System.out.println( apl.format( 1000000 ) ); + System.out.println( apl.format( 10000000 ) ); + System.out.println( apl.format( 100000000 ) ); + System.out.println( apl.format( 1000000000 ) ); + } +} diff --git a/src/java/net/sf/antcontrib/perf/StopWatch.java b/src/java/net/sf/antcontrib/perf/StopWatch.java new file mode 100644 index 0000000..ddb3324 --- /dev/null +++ b/src/java/net/sf/antcontrib/perf/StopWatch.java @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.perf; + +/** + * A stopwatch, useful for 'quick and dirty' performance testing. Typical usage: + * <pre> + * StopWatch sw = new StopWatch(); // automatically starts + * // do something here... + * sw.stop(); + * System.out.println(sw.toString()); // print the total + * sw.start(); // restart the stopwatch + * // do some more things... + * sw.stop(); + * System.out.println(sw.format(sw.elapsed()); // print the time since the last start + * System.out.println(sw.toString()); // print the cumulative total + * </pre> + * <p>Developed for use with Antelope, migrated to ant-contrib Oct 2003. + * + * @author Dale Anson + * @version $Revision: 1.4 $ + */ +public class StopWatch { + + /** an identifying name for this stopwatch */ + private String name = ""; + + /** storage for start time */ + private long startTime = 0; + + /** storage for stop time */ + private long stopTime = 0; + + /** cumulative elapsed time */ + private long totalTime = 0; + + /** is the stopwatch running? */ + private boolean running = false; + + /** + * Starts the stopwatch. + */ + public StopWatch() { + this( "" ); + } + + /** + * Starts the stopwatch. + * @param name an identifying name for this StopWatch + */ + public StopWatch( String name ) { + this.name = name; + start(); + } + + /** + * Starts/restarts the stopwatch. <code>stop</code> must be called prior + * to restart. + * + * @return the start time, the long returned System.currentTimeMillis(). + */ + public long start() { + if ( !running ) + startTime = System.currentTimeMillis(); + running = true; + return startTime; + } + + /** + * Stops the stopwatch. + * + * @return the stop time, the long returned System.currentTimeMillis(). + */ + public long stop() { + stopTime = System.currentTimeMillis(); + if ( running ) { + totalTime += stopTime - startTime; + } + startTime = stopTime; + running = false; + return stopTime; + } + + /** + * Total cumulative elapsed time. + * + * @return the total time + */ + public long total() { + stop(); + long rtn = totalTime; + totalTime = 0; + return rtn; + } + + /** + * Elapsed time, difference between the last start time and now. + * + * @return the elapsed time + */ + public long elapsed() { + return System.currentTimeMillis() - startTime; + } + + /** + * @return the name of this StopWatch + */ + public String getName() { + return name; + } + + /** + * Formats the given time into decimal seconds. + * @return the time formatted as mm:ss.ddd + */ + public String format( long ms ) { + String total = String.valueOf( ms ); + String frontpad = "000"; + int pad_length = 3 - total.length(); + if ( pad_length >= 0 ) + total = "0." + frontpad.substring( 0, pad_length ) + total; + else { + String dec = total.substring( total.length() - 3 ); + total = ""; + int min = 0, sec = 0; + min = ( int ) ( ms / 60000 ); + sec = min > 0 ? ( int ) ( ( ms - ( min * 60000 ) ) / 1000 ) : ( int ) ( ms / 1000 ); + if ( min > 0 ) { + total = String.valueOf( min ) + ":" + ( sec < 10 ? "0" : "" ) + String.valueOf( sec ) + "." + dec; + } + else { + total = String.valueOf( sec ) + "." + dec; + } + } + return total + " sec"; + } + + /** + * Returns the total elapsed time of the stopwatch formatted in decimal seconds. + * @return [name: mm:ss.ddd] + */ + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append( "[" ); + if ( name != null ) + sb.append( name ).append( ": " ); + sb.append( format( totalTime ) ); + sb.append( "]" ); + return sb.toString(); + } + + public static void main ( String[] args ) { + StopWatch sw = new StopWatch( "test" ); + + // test the formatter + System.out.println( sw.format( 1 ) ); + System.out.println( sw.format( 10 ) ); + System.out.println( sw.format( 100 ) ); + System.out.println( sw.format( 1000 ) ); + System.out.println( sw.format( 100000 ) ); + System.out.println( sw.format( 1000000 ) ); + + // test the stopwatch + try { + System.out.println( "StopWatch: " + sw.getName() ); + Thread.currentThread().sleep( 2000 ); + sw.stop(); + System.out.println( sw.toString() ); + sw.start(); + Thread.currentThread().sleep( 2000 ); + sw.stop(); + System.out.println( "elapsed: " + sw.format( sw.elapsed() ) ); + System.out.println( "total: " + sw.format( sw.total() ) ); + } + catch ( Exception e ) { + e.printStackTrace(); + } + } +} + diff --git a/src/java/net/sf/antcontrib/perf/StopWatchTask.java b/src/java/net/sf/antcontrib/perf/StopWatchTask.java new file mode 100644 index 0000000..5de4163 --- /dev/null +++ b/src/java/net/sf/antcontrib/perf/StopWatchTask.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.perf; + +import java.util.Hashtable; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; + +/** + * Assists in timing tasks and/or targets. + * <p>Developed for use with Antelope, migrated to ant-contrib Oct 2003. + * @author Dale Anson, [email protected] + * @version $Revision: 1.5 $ + */ +public class StopWatchTask extends Task { + + // storage for stopwatch name + private String name = null; + + // storage for action + private String action = null; + + // storage for watches + private static Hashtable watches = null; + + // action definitions + private static final String STOP = "stop"; + private static final String START = "start"; + private static final String ELAPSED = "elapsed"; + private static final String TOTAL = "total"; + + + public void setName( String name ) { + this.name = name; + } + + public void setAction( String action ) { + action = action.toLowerCase(); + if ( action.equals( STOP ) || + action.equals( START ) || + action.equals( ELAPSED ) || + action.equals( TOTAL ) ) { + this.action = action; + } + else { + throw new BuildException( "invalid action: " + action ); + } + } + + public void execute() { + if ( name == null ) + throw new BuildException( "name is null" ); + if ( action == null ) + action = START; + if ( watches == null ) + watches = new Hashtable(); + StopWatch sw = ( StopWatch ) watches.get( name ); + if ( sw == null && action.equals( START ) ) { + sw = new StopWatch( name ); + watches.put( name, sw ); + return ; + } + if ( sw == null ) + return ; + if ( action.equals( START) ) { + sw.start(); + return; + } + if ( action.equals( STOP ) ) { + sw.stop(); + return ; + } + if ( action.equals( TOTAL ) ) { + String time = sw.format( sw.total() ); + log( "[" + name + ": " + time + "]" ); + getProject().setProperty(name, time); + return ; + } + if ( action.equals( ELAPSED ) ) { + String time = sw.format( sw.elapsed() ); + log( "[" + name + ": " + time + "]" ); + getProject().setProperty(name, time); + return ; + } + } +} diff --git a/src/java/net/sf/antcontrib/platform/OsFamily.java b/src/java/net/sf/antcontrib/platform/OsFamily.java new file mode 100644 index 0000000..851969b --- /dev/null +++ b/src/java/net/sf/antcontrib/platform/OsFamily.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.platform; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; + +/*** + * Task definition for the <code>OsFamily</code> task. + * This task sets the property indicated in the "property" + * attribute with the string representing the operating + * system family. Possible values include "unix", "dos", "mac" + * and "windows". + * + * <pre> + * + * Task Declaration: + * + * <code> + * <taskdef name="osfamily" classname="net.sf.antcontrib.platform.OsFamily" /> + * </code> + * + * Usage: + * <code> + * <osfamily property="propname" /> + * </code> + * + * Attributes: + * property --> The name of the property to set with the OS family name + * + * </pre> + * @author <a href="mailto:[email protected]">Matthew Inger</a> + */ +public class OsFamily extends Task +{ + private String property; + + public OsFamily() + { + } + + public void setProperty(String property) + { + this.property = property; + } + + public void execute() + throws BuildException + { + if (property == null) + throw new BuildException("The attribute 'property' is required " + + "for the OsFamily task."); + + String familyStr = Platform.getOsFamilyName(); + if (familyStr != null) + getProject().setProperty(property, familyStr); + } + +} diff --git a/src/java/net/sf/antcontrib/platform/Platform.java b/src/java/net/sf/antcontrib/platform/Platform.java new file mode 100644 index 0000000..23e32f6 --- /dev/null +++ b/src/java/net/sf/antcontrib/platform/Platform.java @@ -0,0 +1,217 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.platform; + +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Properties; +import java.util.Vector; + +import org.apache.tools.ant.taskdefs.Execute; + +/*** + * + * </pre> + * @author <a href="mailto:[email protected]">Matthew Inger</a> + */ +public class Platform +{ + public static final int FAMILY_NONE = 0; + public static final int FAMILY_UNIX = 1; + public static final int FAMILY_WINDOWS = 2; + public static final int FAMILY_OS2 = 3; + public static final int FAMILY_ZOS = 4; + public static final int FAMILY_OS400 = 5; + public static final int FAMILY_DOS = 6; + public static final int FAMILY_MAC = 7; + public static final int FAMILY_MACOSX = 8; + public static final int FAMILY_TANDEM = 9; + public static final int FAMILY_OPENVMS = 10; + + public static final String FAMILY_NAME_UNIX = "unix"; + public static final String FAMILY_NAME_WINDOWS = "windows"; + public static final String FAMILY_NAME_OS2 = "os/2"; + public static final String FAMILY_NAME_ZOS = "z/os"; + public static final String FAMILY_NAME_OS400 = "os/400"; + public static final String FAMILY_NAME_DOS = "dos"; + public static final String FAMILY_NAME_MAC = "mac"; + public static final String FAMILY_NAME_TANDEM = "tandem"; + public static final String FAMILY_NAME_OPENVMS = "openvms"; + + private static final Hashtable familyNames; + + static + { + familyNames = new Hashtable(); + familyNames.put(new Integer(FAMILY_WINDOWS), FAMILY_NAME_WINDOWS); + familyNames.put(new Integer(FAMILY_OS2), FAMILY_NAME_OS2); + familyNames.put(new Integer(FAMILY_ZOS), FAMILY_NAME_ZOS); + familyNames.put(new Integer(FAMILY_OS400), FAMILY_NAME_OS400); + familyNames.put(new Integer(FAMILY_DOS), FAMILY_NAME_DOS); + familyNames.put(new Integer(FAMILY_MAC), FAMILY_NAME_MAC); + familyNames.put(new Integer(FAMILY_MACOSX), FAMILY_NAME_UNIX); + familyNames.put(new Integer(FAMILY_TANDEM), FAMILY_NAME_TANDEM); + familyNames.put(new Integer(FAMILY_UNIX), FAMILY_NAME_UNIX); + familyNames.put(new Integer(FAMILY_OPENVMS), FAMILY_NAME_OPENVMS); + } + + public static final int getOsFamily() + { + String osName = System.getProperty("os.name").toLowerCase(); + String pathSep = System.getProperty("path.separator"); + int family = FAMILY_NONE; + + if (osName.indexOf("windows") != -1) + { + family = FAMILY_WINDOWS; + } + else if (osName.indexOf("os/2") != -1) + { + family = FAMILY_OS2; + } + else if (osName.indexOf("z/os") != -1 + || osName.indexOf("os/390") != -1) + { + family = FAMILY_ZOS; + } + else if (osName.indexOf("os/400") != -1) + { + family = FAMILY_OS400; + } + else if (pathSep.equals(";")) + { + family = FAMILY_DOS; + } + else if (osName.indexOf("mac") != -1) + { + if (osName.endsWith("x")) + family = FAMILY_UNIX; // MACOSX + else + family = FAMILY_MAC; + } + else if (osName.indexOf("nonstop_kernel") != -1) + { + family = FAMILY_TANDEM; + } + else if (osName.indexOf("openvms") != -1) + { + family = FAMILY_OPENVMS; + } + else if (pathSep.equals(":")) + { + family = FAMILY_UNIX; + } + + return family; + } + + public static final String getOsFamilyName() + { + int family = getOsFamily(); + return (String)(familyNames.get(new Integer(family))); + } + + public static final Properties getEnv() + { + Properties env = new Properties(); + Vector osEnv = Execute.getProcEnvironment(); + for (Enumeration e = osEnv.elements(); e.hasMoreElements();) { + String entry = (String) e.nextElement(); + int pos = entry.indexOf('='); + if (pos != -1) { + env.setProperty(entry.substring(0, pos), + entry.substring(pos + 1)); + } + } + return env; + } + + public static final String getDefaultShell() + { + String shell = getEnv().getProperty("SHELL"); + + if (shell == null) + { + int family = getOsFamily(); + switch (family) + { + case FAMILY_DOS: + case FAMILY_WINDOWS: + { + shell = "CMD.EXE"; + break; + } + + default: + { + shell = "bash"; + break; + } + } + } + return shell; + } + + public static final String getDefaultScriptSuffix() + { + int family = getOsFamily(); + String suffix = null; + + switch (family) + { + case FAMILY_DOS: + case FAMILY_WINDOWS: + { + suffix = ".bat"; + break; + } + + default: + { + suffix = null; + break; + } + } + + return suffix; + } + + + public static final String[] getDefaultShellArguments() + { + int family = getOsFamily(); + String args[] = null; + + switch (family) + { + case FAMILY_DOS: + case FAMILY_WINDOWS: + { + args = new String[] { "/c" , "call" }; + break; + } + + default: + { + args = new String[0]; + break; + } + } + + return args; + } + +} diff --git a/src/java/net/sf/antcontrib/platform/ShellScriptTask.java b/src/java/net/sf/antcontrib/platform/ShellScriptTask.java new file mode 100644 index 0000000..3b34d8f --- /dev/null +++ b/src/java/net/sf/antcontrib/platform/ShellScriptTask.java @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.platform; + + +import java.io.File; +import java.io.FileOutputStream; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.taskdefs.ExecTask; +import org.apache.tools.ant.types.Commandline; +import org.apache.tools.ant.util.FileUtils; + +/** + * A generic front-end for passing "shell lines" to any application which can + * accept a filename containing script input (bash, perl, csh, tcsh, etc.). + * see antcontrib doc for useage + * + * @author stephan beal + *@author peter reilly + */ + +public class ShellScriptTask extends ExecTask { + + private StringBuffer script = new StringBuffer(); + private String shell = null; + private File tmpFile; + private String tmpSuffix = null; + + /** + * Adds s to the lines of script code. + */ + public void addText(String s) { + script.append(getProject().replaceProperties(s)); + } + + /** + * Sets script code to s. + */ + public void setInputString(String s) { + script.append(s); + } + + /** + * Sets the shell used to run the script. + * @param shell the shell to use (bash is default) + */ + public void setShell(String shell) { + this.shell = shell; + } + + /** + * Sets the shell used to run the script. + * @param shell the shell to use (bash is default) + */ + public void setExecutable(String shell) { + this.shell = shell; + } + + /** + * Disallow the command attribute of parent class ExecTask. + * ant.attribute ignore="true" + * @param notUsed not used + * @throws BuildException if called + */ + public void setCommand(Commandline notUsed) { + throw new BuildException("Attribute command is not supported"); + } + + + /** + * Sets the suffix for the tmp file used to + * contain the script. + * This is useful for cmd.exe as one can + * use cmd /c call x.bat + * @param tmpSuffix the suffix to use + */ + + public void setTmpSuffix(String tmpSuffix) { + this.tmpSuffix = tmpSuffix; + } + + /** + * execute the task + */ + public void execute() throws BuildException { + // Remove per peter's comments. Makes sense. + /* + if (shell == null) + { + // Get the default shell + shell = Platform.getDefaultShell(); + + // Get the default shell arguments + String args[] = Platform.getDefaultShellArguments(); + for (int i=args.length-1;i>=0;i--) + this.cmdl.createArgument(true).setValue(args[i]); + + // Get the default script suffix + if (tmpSuffix == null) + tmpSuffix = Platform.getDefaultScriptSuffix(); + + } + */ + if (shell == null) + throw new BuildException("You must specify a shell to run."); + + try { + /* // The following may be used when ant 1.6 is used. + if (tmpSuffix == null) + super.setInputString(script.toString()); + else + */ + { + writeScript(); + super.createArg().setValue(tmpFile.getAbsolutePath()); + } + super.setExecutable(shell); + super.execute(); + } + finally { + if (tmpFile != null) { + if (! tmpFile.delete()) { + log("Non-fatal error: could not delete temporary file " + + tmpFile.getAbsolutePath()); + } + } + } + } + + /** + * Writes the script lines to a temp file. + */ + protected void writeScript() throws BuildException { + FileOutputStream os = null; + try { + FileUtils fileUtils = FileUtils.newFileUtils(); + // NB: use File.io.createTempFile whenever jdk 1.2 is allowed + tmpFile = fileUtils.createTempFile("script", tmpSuffix, null); + os = new java.io.FileOutputStream(tmpFile); + String string = script.toString(); + os.write(string.getBytes(), 0, string.length()); + os.close(); + } + catch (Exception e) { + throw new BuildException(e); + } + finally { + try {os.close();} catch (Throwable t) {} + } + } + +} + diff --git a/src/java/net/sf/antcontrib/process/ForgetTask.java b/src/java/net/sf/antcontrib/process/ForgetTask.java new file mode 100644 index 0000000..69990bd --- /dev/null +++ b/src/java/net/sf/antcontrib/process/ForgetTask.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.process; + +import org.apache.tools.ant.taskdefs.Sequential; + + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class ForgetTask + extends Sequential + implements Runnable +{ + private boolean daemon = true; + + public ForgetTask() + { + super(); + } + + + public void setDaemon(boolean daemon) + { + this.daemon = daemon; + } + + + public void execute() + { + Thread t = new Thread(this); + t.setDaemon(daemon); + t.start(); + } + + public void run() + { + super.execute(); + } + +} diff --git a/src/java/net/sf/antcontrib/process/Limit.java b/src/java/net/sf/antcontrib/process/Limit.java new file mode 100644 index 0000000..b9cd7df --- /dev/null +++ b/src/java/net/sf/antcontrib/process/Limit.java @@ -0,0 +1,402 @@ + +/* +* Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package net.sf.antcontrib.process; + + +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Vector; + + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.TaskContainer; +import org.apache.tools.ant.types.EnumeratedAttribute; + + +/** + * Limits the amount of time that a task or set of tasks can run. This is useful + * for tasks that may "hang" or otherwise not complete in a timely fashion. This + * task is done when either the maxwait time has expired or all nested tasks are + * complete, whichever is first. + * + * <p>Developed for use with Antelope, migrated to ant-contrib Oct 2003. + * + * @author Dale Anson + * @author Robert D. Rice + * @version $Revision: 1.6 $ + * @since Ant 1.5 + */ +public class Limit extends Task implements TaskContainer { + + + // storage for nested tasks + private Vector tasks = new Vector(); + + + // time units, default value is 3 minutes. + private long maxwait = 180; + protected TimeUnit unit = TimeUnit.SECOND_UNIT; + + // property to set if time limit is reached + private String timeoutProperty = null; + private String timeoutValue = "true"; + + + // storage for task currently executing + private Task currentTask = null; + + + // used to control thread stoppage + private Thread taskRunner = null; + + + // should the build fail if the time limit has expired? Default is no. + private boolean failOnError = false; + + + private Exception exception = null; + + + + + /** + * Add a task to wait on. + * + * @param task A task to execute + * @exception BuildException won't happen + */ + public void addTask( Task task ) throws BuildException { + tasks.addElement( task ); + } + + + + + /** + * How long to wait for all nested tasks to complete, in units. + * Default is to wait 3 minutes. + * + * @param wait time to wait, set to 0 to wait forever. + */ + public void setMaxwait( int wait ) { + maxwait = wait; + } + + /** + * Sets the unit for the max wait. Default is minutes. + + * @param unit valid values are "millisecond", "second", "minute", "hour", "day", and "week". + + */ + public void setUnit( String unit ) { + if ( unit == null ) + return ; + if ( unit.equals( TimeUnit.SECOND ) ) { + setMaxWaitUnit( TimeUnit.SECOND_UNIT ); + return ; + } + if ( unit.equals( TimeUnit.MILLISECOND ) ) { + setMaxWaitUnit( TimeUnit.MILLISECOND_UNIT ); + return ; + } + if ( unit.equals( TimeUnit.MINUTE ) ) { + setMaxWaitUnit( TimeUnit.MINUTE_UNIT ); + return ; + } + if ( unit.equals( TimeUnit.HOUR ) ) { + setMaxWaitUnit( TimeUnit.HOUR_UNIT ); + return ; + } + if ( unit.equals( TimeUnit.DAY ) ) { + setMaxWaitUnit( TimeUnit.DAY_UNIT ); + return ; + } + if ( unit.equals( TimeUnit.WEEK ) ) { + setMaxWaitUnit( TimeUnit.WEEK_UNIT ); + return ; + } + + } + + /** + * Set a millisecond wait value. + * @param value the number of milliseconds to wait. + */ + public void setMilliseconds( int value ) { + setMaxwait( value ); + setMaxWaitUnit( TimeUnit.MILLISECOND_UNIT ); + } + + /** + * Set a second wait value. + * @param value the number of seconds to wait. + */ + public void setSeconds( int value ) { + setMaxwait( value ); + setMaxWaitUnit( TimeUnit.SECOND_UNIT ); + } + + /** + * Set a minute wait value. + * @param value the number of milliseconds to wait. + */ + public void setMinutes( int value ) { + setMaxwait( value ); + setMaxWaitUnit( TimeUnit.MINUTE_UNIT ); + } + + /** + * Set an hours wait value. + * @param value the number of hours to wait. + */ + public void setHours( int value ) { + setMaxwait( value ); + setMaxWaitUnit( TimeUnit.HOUR_UNIT ); + } + + /** + * Set a day wait value. + * @param value the number of days to wait. + */ + public void setDays( int value ) { + setMaxwait( value ); + setMaxWaitUnit( TimeUnit.DAY_UNIT ); + } + + /** + * Set a week wait value. + * @param value the number of weeks to wait. + */ + public void setWeeks( int value ) { + setMaxwait( value ); + setMaxWaitUnit( TimeUnit.WEEK_UNIT ); + } + + /** + * Set the max wait time unit, default is minutes. + */ + public void setMaxWaitUnit( TimeUnit unit ) { + this.unit = unit; + } + + + /** + * Determines whether the build should fail if the time limit has + * expired on this task. + * Default is no. + * + * @param fail if true, fail the build if the time limit has been reached. + */ + public void setFailonerror( boolean fail ) { + failOnError = fail; + } + + + /** + * Name the property to set after a timeout. + * + * @param p of property to set if the time limit has been reached. + */ + public void setProperty( String p ) { + timeoutProperty = p; + } + + + /** + * The value for the property to set after a timeout, defaults to true. + * + * @param v for the property to set if the time limit has been reached. + */ + public void setValue( String v ) { + timeoutValue = v; + } + + + /** + * Execute all nested tasks, but stopping execution of nested tasks after + * maxwait or when all tasks are done, whichever is first. + * + * @exception BuildException Description of the Exception + */ + public void execute() throws BuildException { + try { + // start executing nested tasks + final Thread runner = + new Thread() { + public void run() { + Enumeration e = tasks.elements(); + while ( e.hasMoreElements() ) { + if ( taskRunner != this ) { + break; + } + currentTask = ( Task ) e.nextElement(); + try { + currentTask.perform(); + } + catch ( Exception ex ) { + if ( failOnError ) { + exception = ex; + return ; + } + else { + exception = ex; + } + } + } + } + }; + taskRunner = runner; + runner.start(); + runner.join( unit.toMillis( maxwait ) ); + + + // stop executing the nested tasks + if ( runner.isAlive() ) { + taskRunner = null; + runner.interrupt(); + int index = tasks.indexOf( currentTask ); + StringBuffer not_ran = new StringBuffer(); + for ( int i = index + 1; i < tasks.size(); i++ ) { + not_ran.append( '<' ).append( ( ( Task ) tasks.get( i ) ).getTaskName() ).append( '>' ); + if ( i < tasks.size() - 1 ) { + not_ran.append( ", " ); + } + } + + + // maybe set timeout property + if ( timeoutProperty != null ) { + getProject().setNewProperty( timeoutProperty, timeoutValue ); + } + + + // create output message + StringBuffer msg = new StringBuffer(); + msg.append( "Interrupted task <" ) + .append( currentTask.getTaskName() ) + .append( ">. Waited " ) + .append( ( maxwait ) ).append( " " ).append( unit.getValue() ) + .append( ", but this task did not complete." ) + .append( ( not_ran.length() > 0 ? + " The following tasks did not execute: " + not_ran.toString() + "." : + "" ) ); + + + // deal with it + if ( failOnError ) { + throw new BuildException( msg.toString() ); + } + else { + log( msg.toString() ); + } + } + else if ( failOnError && exception != null ) { + throw new BuildException( exception ); + } + } + catch ( Exception e ) { + throw new BuildException( e ); + } + } + + + /** + * The enumeration of units: + * millisecond, second, minute, hour, day, week + * Todo: we use timestamps in many places, why not factor this out + */ + public static class TimeUnit extends EnumeratedAttribute { + + public static final String MILLISECOND = "millisecond"; + public static final String SECOND = "second"; + public static final String MINUTE = "minute"; + public static final String HOUR = "hour"; + public static final String DAY = "day"; + public static final String WEEK = "week"; + + /** static unit objects, for use as sensible defaults */ + public static final TimeUnit MILLISECOND_UNIT = + new TimeUnit( MILLISECOND ); + public static final TimeUnit SECOND_UNIT = + new TimeUnit( SECOND ); + public static final TimeUnit MINUTE_UNIT = + new TimeUnit( MINUTE ); + public static final TimeUnit HOUR_UNIT = + new TimeUnit( HOUR ); + public static final TimeUnit DAY_UNIT = + new TimeUnit( DAY ); + public static final TimeUnit WEEK_UNIT = + new TimeUnit( WEEK ); + + + private static final String[] units = { + MILLISECOND, SECOND, MINUTE, HOUR, DAY, WEEK + }; + + private Hashtable timeTable = new Hashtable(); + + public TimeUnit() { + timeTable.put( MILLISECOND, new Long( 1L ) ); + timeTable.put( SECOND, new Long( 1000L ) ); + timeTable.put( MINUTE, new Long( 1000L * 60L ) ); + timeTable.put( HOUR, new Long( 1000L * 60L * 60L ) ); + timeTable.put( DAY, new Long( 1000L * 60L * 60L * 24L ) ); + timeTable.put( WEEK, new Long( 1000L * 60L * 60L * 24L * 7L ) ); + } + + /** + * private constructor + * used for static construction of TimeUnit objects. + * @param value String representing the value. + */ + private TimeUnit( String value ) { + this( ); + setValueProgrammatically( value ); + } + + /** + * set the inner value programmatically. + * @param value to set + */ + protected void setValueProgrammatically( String value ) { + this.value = value; + } + + public long getMultiplier() { + String key = getValue().toLowerCase(); + Long l = ( Long ) timeTable.get( key ); + return l.longValue(); + } + + public String[] getValues() { + return units; + } + + /** + * convert the time in the current unit, to millis + * @param numberOfUnits long expressed in the current objects units + * @return long representing the value in millis + */ + public long toMillis( long numberOfUnits ) { + return numberOfUnits * getMultiplier( ); + } + } +} + + + diff --git a/src/java/net/sf/antcontrib/property/AbstractPropertySetterTask.java b/src/java/net/sf/antcontrib/property/AbstractPropertySetterTask.java new file mode 100644 index 0000000..87b594f --- /dev/null +++ b/src/java/net/sf/antcontrib/property/AbstractPropertySetterTask.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.property; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.taskdefs.Property; + + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public abstract class AbstractPropertySetterTask + extends Task +{ + private boolean override; + private String property; + + public AbstractPropertySetterTask() + { + super(); + } + + + public void setOverride(boolean override) + { + this.override = override; + } + + + public void setProperty(String property) + { + this.property = property; + } + + protected void validate() + { + if (property == null) + throw new BuildException("You must specify a property to set."); + } + + + protected final void setPropertyValue(String value) + { + if (value != null) + { + if (override) + { + if (getProject().getUserProperty(property) == null) + getProject().setProperty(property, value); + else + getProject().setUserProperty(property, value); + } + else + { + Property p = (Property)project.createTask("property"); + p.setName(property); + p.setValue(value); + p.execute(); + } + } + } +} diff --git a/src/java/net/sf/antcontrib/property/PathFilterTask.java b/src/java/net/sf/antcontrib/property/PathFilterTask.java new file mode 100644 index 0000000..9547923 --- /dev/null +++ b/src/java/net/sf/antcontrib/property/PathFilterTask.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.property; + +import java.io.File; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.types.DirSet; +import org.apache.tools.ant.types.FileList; +import org.apache.tools.ant.types.FileSet; +import org.apache.tools.ant.types.Path; +import org.apache.tools.ant.types.selectors.OrSelector; + +public class PathFilterTask + extends Task { + + private OrSelector select; + private Path path; + private String pathid; + + + public void setPathId(String pathid) { + this.pathid = pathid; + } + + public OrSelector createSelect() { + select = new OrSelector(); + return select; + } + + public void addConfiguredFileSet(FileSet fileset) { + if (this.path == null) { + this.path = (Path)getProject().createDataType("path"); + } + this.path.addFileset(fileset); + } + + public void addConfiguredDirSet(DirSet dirset) { + if (this.path == null) { + this.path = (Path)getProject().createDataType("path"); + } + this.path.addDirset(dirset); + } + + public void addConfiguredFileList(FileList filelist) { + if (this.path == null) { + this.path = (Path)getProject().createDataType("path"); + } + this.path.addFilelist(filelist); + } + + public void addConfiguredPath(Path path) { + if (this.path == null) { + this.path = (Path)getProject().createDataType("path"); + } + this.path.add(path); + } + + + public void execute() throws BuildException { + if (select == null) { + throw new BuildException("A <select> element must be specified."); + } + + if (pathid == null) { + throw new BuildException("A 'pathid' attribute must be specified."); + } + + Path selectedFiles = (Path)getProject().createDataType("path"); + + if (this.path != null) { + String files[] = this.path.list(); + for (int i=0;i<files.length;i++) { + File file = new File(files[i]); + if (select.isSelected(file.getParentFile(), + file.getName(), + file)) { + selectedFiles.createPathElement().setLocation(file); + } + } + + getProject().addReference(pathid, selectedFiles); + } + } + + + +} diff --git a/src/java/net/sf/antcontrib/property/PathToFileSet.java b/src/java/net/sf/antcontrib/property/PathToFileSet.java new file mode 100644 index 0000000..d1231af --- /dev/null +++ b/src/java/net/sf/antcontrib/property/PathToFileSet.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.property; + +import java.io.File; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.types.FileSet; +import org.apache.tools.ant.types.Path; +import org.apache.tools.ant.util.FileUtils; + +public class PathToFileSet + extends Task +{ + private File dir; + private String name; + private String pathRefId; + private boolean ignoreNonRelative = false; + + private static FileUtils fileUtils = FileUtils.newFileUtils(); + + public void setDir(File dir) { + this.dir = dir; + } + + public void setName(String name) { + this.name = name; + } + + public void setPathRefId(String pathRefId) { + this.pathRefId = pathRefId; + } + + public void setIgnoreNonRelative(boolean ignoreNonRelative) { + this.ignoreNonRelative = ignoreNonRelative; + } + + public void execute() { + if (dir == null) + throw new BuildException("missing dir"); + if (name == null) + throw new BuildException("missing name"); + if (pathRefId == null) + throw new BuildException("missing pathrefid"); + + if (! dir.isDirectory()) + throw new BuildException( + dir.toString() + " is not a directory"); + + Object path = getProject().getReference(pathRefId); + if (path == null) + throw new BuildException("Unknown reference " + pathRefId); + if (! (path instanceof Path)) + throw new BuildException(pathRefId + " is not a path"); + + + String[] sources = ((Path) path).list(); + + FileSet fileSet = new FileSet(); + fileSet.setProject(getProject()); + fileSet.setDir(dir); + String dirNormal = + fileUtils.normalize(dir.getAbsolutePath()).getAbsolutePath(); + if (! dirNormal.endsWith(File.separator)) { + dirNormal += File.separator; + } + + + boolean atLeastOne = false; + for (int i = 0; i < sources.length; ++i) { + File sourceFile = new File(sources[i]); + if (! sourceFile.exists()) + continue; + String relativeName = getRelativeName(dirNormal, sourceFile); + if (relativeName == null && !ignoreNonRelative) { + throw new BuildException( + sources[i] + " is not relative to " + dir.getAbsolutePath()); + } + if (relativeName == null) + continue; + fileSet.createInclude().setName(relativeName); + atLeastOne = true; + } + + if (! atLeastOne) { + // need to make an empty fileset + fileSet.createInclude().setName("a:b:c:d//THis si &&& not a file !!! "); + } + getProject().addReference(name, fileSet); + } + + private String getRelativeName(String dirNormal, File file) { + String fileNormal = + fileUtils.normalize(file.getAbsolutePath()).getAbsolutePath(); + if (! fileNormal.startsWith(dirNormal)) + return null; + return fileNormal.substring(dirNormal.length()); + } +} + diff --git a/src/java/net/sf/antcontrib/property/PropertyCopy.java b/src/java/net/sf/antcontrib/property/PropertyCopy.java new file mode 100644 index 0000000..558c4ac --- /dev/null +++ b/src/java/net/sf/antcontrib/property/PropertyCopy.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.property; + +import org.apache.tools.ant.BuildException; + +/*** + * Task definition for the propertycopy task, which copies the value of a + * named property to another property. This is useful when you need to + * plug in the value of another property in order to get a property name + * and then want to get the value of that property name. + * + * <pre> + * Usage: + * + * Task declaration in the project: + * <code> + * <taskdef name="propertycopy" classname="net.sf.antcontrib.property.PropertyCopy" /> + * </code> + * + * Call Syntax: + * <code> + * <propertycopy name="propname" from="copyfrom" (silent="true|false")? /> + * </code> + * + * Attributes: + * name --> The name of the property you wish to set with the value + * from --> The name of the property you wish to copy the value from + * silent --> Do you want to suppress the error if the "from" property + * does not exist, and just not set the property "name". Default + * is false. + * + * Example: + * <property name="org" value="MyOrg" /> + * <property name="org.MyOrg.DisplayName" value="My Organiziation" /> + * <propertycopy name="displayName" from="org.${org}.DisplayName" /> + * <echo message="${displayName}" /> + * </pre> + * + * @author <a href="mailto:[email protected]">Matthew Inger</a> + */ +public class PropertyCopy + extends AbstractPropertySetterTask +{ + private String from; + private boolean silent; + + /*** + * Default Constructor + */ + public PropertyCopy() + { + super(); + this.from = null; + this.silent = false; + } + + public void setName(String name) + { + setProperty(name); + } + + public void setFrom(String from) + { + this.from = from; + } + + public void setSilent(boolean silent) + { + this.silent = silent; + } + + protected void validate() + { + super.validate(); + if (from == null) + throw new BuildException("Missing the 'from' attribute."); + } + + public void execute() + throws BuildException + { + validate(); + + String value = getProject().getProperty(from); + + if (value == null && ! silent) + throw new BuildException("Property '" + from + "' is not defined."); + + if (value != null) + setPropertyValue(value); + } + +} + + diff --git a/src/java/net/sf/antcontrib/property/PropertySelector.java b/src/java/net/sf/antcontrib/property/PropertySelector.java new file mode 100644 index 0000000..23328c4 --- /dev/null +++ b/src/java/net/sf/antcontrib/property/PropertySelector.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.property; + +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Vector; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.types.RegularExpression; +import org.apache.tools.ant.util.regexp.Regexp; + + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class PropertySelector + extends AbstractPropertySetterTask +{ + private RegularExpression match; + private String select = "\\0"; + private char delim = ','; + private boolean caseSensitive = true; + private boolean distinct = false; + + + public PropertySelector() + { + super(); + } + + + public void setMatch(String match) + { + this.match = new RegularExpression(); + this.match.setPattern(match); + } + + + public void setSelect(String select) + { + this.select = select; + } + + + public void setCaseSensitive(boolean caseSensitive) + { + this.caseSensitive = caseSensitive; + } + + + public void setDelimiter(char delim) + { + this.delim = delim; + } + + + public void setDistinct(boolean distinct) + { + this.distinct = distinct; + } + + + protected void validate() + { + super.validate(); + if (match == null) + throw new BuildException("No match expression specified."); + } + + + public void execute() + throws BuildException + { + validate(); + + int options = 0; + if (!caseSensitive) + options |= Regexp.MATCH_CASE_INSENSITIVE; + + Regexp regex = match.getRegexp(project); + Hashtable props = project.getProperties(); + Enumeration e = props.keys(); + StringBuffer buf = new StringBuffer(); + int cnt = 0; + + Vector used = new Vector(); + + while (e.hasMoreElements()) + { + String key = (String) (e.nextElement()); + if (regex.matches(key, options)) + { + String output = select; + Vector groups = regex.getGroups(key, options); + int sz = groups.size(); + for (int i = 0; i < sz; i++) + { + String s = (String) (groups.elementAt(i)); + + RegularExpression result = null; + result = new RegularExpression(); + result.setPattern("\\\\" + i); + Regexp sregex = result.getRegexp(project); + output = sregex.substitute(output, s, Regexp.MATCH_DEFAULT); + } + + if (!(distinct && used.contains(output))) + { + used.addElement(output); + if (cnt != 0) buf.append(delim); + buf.append(output); + cnt++; + } + } + } + + if (buf.length() > 0) + setPropertyValue(buf.toString()); + } +} diff --git a/src/java/net/sf/antcontrib/property/RegexTask.java b/src/java/net/sf/antcontrib/property/RegexTask.java new file mode 100644 index 0000000..433835f --- /dev/null +++ b/src/java/net/sf/antcontrib/property/RegexTask.java @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.property; + +import java.util.Vector; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.types.RegularExpression; +import org.apache.tools.ant.types.Substitution; +import org.apache.tools.ant.util.regexp.Regexp; + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class RegexTask + extends AbstractPropertySetterTask +{ + private String input; + + private RegularExpression regexp; + private String select; + private Substitution replace; + private String defaultValue; + + private boolean caseSensitive = true; + private boolean global = true; + + public RegexTask() + { + super(); + } + + public void setInput(String input) + { + this.input = input; + } + + public void setDefaultValue(String defaultValue) + { + this.defaultValue = defaultValue; + } + + public void setRegexp(String regex) + { + if (this.regexp != null) + throw new BuildException("Cannot specify more than one regular expression"); + + this.regexp = new RegularExpression(); + this.regexp.setPattern(regex); + } + + + public RegularExpression createRegexp() + { + if (this.regexp != null) + throw new BuildException("Cannot specify more than one regular expression"); + regexp = new RegularExpression(); + return regexp; + } + + public void setReplace(String replace) + { + if (this.replace != null) + throw new BuildException("Cannot specify more than one replace expression"); + if (select != null) + throw new BuildException("You cannot specify both a select and replace expression"); + this.replace = new Substitution(); + this.replace.setExpression(replace); + } + + public Substitution createReplace() + { + if (replace != null) + throw new BuildException("Cannot specify more than one replace expression"); + if (select != null) + throw new BuildException("You cannot specify both a select and replace expression"); + replace = new Substitution(); + return replace; + } + + public void setSelect(String select) + { + if (replace != null) + throw new BuildException("You cannot specify both a select and replace expression"); + this.select = select; + } + + public void setCaseSensitive(boolean caseSensitive) + { + this.caseSensitive = caseSensitive; + } + + public void setGlobal(boolean global) + { + this.global = global; + } + + protected String doReplace() + throws BuildException + { + if (replace == null) + throw new BuildException("No replace expression specified."); + + int options = 0; + if (! caseSensitive) + options |= Regexp.MATCH_CASE_INSENSITIVE; + if (global) + options |= Regexp.REPLACE_ALL; + + Regexp sregex = regexp.getRegexp(project); + + String output = null; + + if (sregex.matches(input, options)) { + String expression = replace.getExpression(project); + output = sregex.substitute(input, + expression, + options); + } + + if (output == null) + output = defaultValue; + + return output; + } + + protected String doSelect() + throws BuildException + { + int options = 0; + if (! caseSensitive) + options |= Regexp.MATCH_CASE_INSENSITIVE; + + Regexp sregex = regexp.getRegexp(project); + + String output = select; + Vector groups = sregex.getGroups(input, options); + + if (groups != null && groups.size() > 0) + { + output = RegexUtil.select(select, groups); + } + else + { + output = null; + } + + if (output == null) + output = defaultValue; + + return output; + } + + + protected void validate() + { + super.validate(); + if (regexp == null) + throw new BuildException("No match expression specified."); + if (replace == null && select == null) + throw new BuildException("You must specify either a replace or select expression"); + } + + public void execute() + throws BuildException + { + validate(); + + String output = input; + if (replace != null) + output = doReplace(); + else + output = doSelect(); + + if (output != null) + setPropertyValue(output); + } +} diff --git a/src/java/net/sf/antcontrib/property/RegexUtil.java b/src/java/net/sf/antcontrib/property/RegexUtil.java new file mode 100644 index 0000000..0a8b350 --- /dev/null +++ b/src/java/net/sf/antcontrib/property/RegexUtil.java @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.property; + +import java.util.Enumeration; +import java.util.Vector; + +/**************************************************************************** + * Regular Expression utilities + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * + ****************************************************************************/ + + +public class RegexUtil +{ + + /*** + * An abritrary node in a select expression + */ + private static interface SelectNode + { + /*** + * Select the value based on the groups + * @param groups The groups found in the match + */ + public String select(Vector groups); + } + + /*** + * A group node in a select expression + */ + private static class GroupSelectNode + implements SelectNode + { + private int groupNumber; + + public GroupSelectNode(int groupNumber) + { + this.groupNumber = groupNumber; + } + + public String select(Vector groups) + { + if ( groupNumber < groups.size()) + return (String)groups.elementAt(groupNumber); + else + return "\\" + groupNumber; + } + + public String toString() + { + return "group: " + groupNumber; + } + } + + /*** + * An abritrary node in a select expression + */ + private static class StringSelectNode + implements SelectNode + { + private String text; + + public StringSelectNode(String text) + { + this.text = text; + } + + public String select(Vector groups) + { + return text; + } + + public String toString() + { + return "string: " + text; + } + } + + /*** + * Parses a select string into a List of SelectNode objects. + * These objects can then be merged with a group list to produce + * an output string (using the "select" method) + * @param input The select string + * @return a List of SelectNode objects + */ + private static Vector parseSelectString(String input) + { + Vector nodes = new Vector(); + StringBuffer buf = new StringBuffer(); + char c[] = input.toCharArray(); + for (int i=0;i<c.length;i++) + { + if (c[i] == '\\') + { + if (buf.length() > 0) + { + nodes.addElement(new StringSelectNode(buf.toString())); + buf.setLength(0); + } + + while (i+1 < c.length && Character.isDigit(c[i+1])) + { + buf.append(c[i+1]); + i++; + } + + int groupNum = Integer.parseInt(buf.toString()); + buf.setLength(0); + nodes.addElement(new GroupSelectNode(groupNum)); + } + else + { + buf.append(c[i]); + } + } + + + if (buf.length() > 0) + { + nodes.addElement(new StringSelectNode(buf.toString())); + buf.setLength(0); + } + + return nodes; + } + + /*** + * Parse a select string, and merge it with a match groups + * vector to produce an output string. Each group placehold + * in the select string is replaced with the group at the + * corresponding index in the match groups vector + * @param select The select string + * @param groups The match groups + * @return The output string with the merged selection + */ + public static String select(String select, Vector groups) + { + Vector nodes = parseSelectString(select); + + StringBuffer buf = new StringBuffer(); + Enumeration e = nodes.elements(); + SelectNode node = null; + while (e.hasMoreElements()) + { + node = (SelectNode)e.nextElement(); + buf.append(node.select(groups)); + } + return buf.toString(); + } +} diff --git a/src/java/net/sf/antcontrib/property/SortList.java b/src/java/net/sf/antcontrib/property/SortList.java new file mode 100644 index 0000000..f6e9440 --- /dev/null +++ b/src/java/net/sf/antcontrib/property/SortList.java @@ -0,0 +1,293 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package net.sf.antcontrib.property; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.Enumeration; +import java.util.StringTokenizer; +import java.util.Vector; +import java.util.Locale; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.types.Reference; + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class SortList + extends AbstractPropertySetterTask +{ + private String value; + private Reference ref; + private boolean casesensitive = true; + private boolean numeric = false; + private String delimiter = ","; + private File orderPropertyFile; + private String orderPropertyFilePrefix; + + public SortList() + { + super(); + } + + public void setNumeric(boolean numeric) + { + this.numeric = numeric; + } + + public void setValue(String value) + { + this.value = value; + } + + + public void setRefid(Reference ref) + { + this.ref = ref; + } + + + public void setCasesensitive(boolean casesenstive) + { + this.casesensitive = casesenstive; + } + + public void setDelimiter(String delimiter) + { + this.delimiter = delimiter; + } + + + public void setOrderPropertyFile(File orderPropertyFile) + { + this.orderPropertyFile = orderPropertyFile; + } + + + public void setOrderPropertyFilePrefix(String orderPropertyFilePrefix) + { + this.orderPropertyFilePrefix = orderPropertyFilePrefix; + } + + + private static void mergeSort(String src[], + String dest[], + int low, + int high, + boolean caseSensitive, + boolean numeric) { + int length = high - low; + + // Insertion sort on smallest arrays + if (length < 7) { + for (int i=low; i<high; i++) + for (int j=i; j>low && + compare(dest[j-1],dest[j], caseSensitive, numeric)>0; j--) + swap(dest, j, j-1); + return; + } + + // Recursively sort halves of dest into src + int mid = (low + high)/2; + mergeSort(dest, src, low, mid, caseSensitive, numeric); + mergeSort(dest, src, mid, high, caseSensitive, numeric); + + // If list is already sorted, just copy from src to dest. This is an + // optimization that results in faster sorts for nearly ordered lists. + if (compare(src[mid-1], src[mid], caseSensitive, numeric) <= 0) { + System.arraycopy(src, low, dest, low, length); + return; + } + + // Merge sorted halves (now in src) into dest + for(int i = low, p = low, q = mid; i < high; i++) { + if (q>=high || p<mid && compare(src[p], src[q], caseSensitive, numeric)<=0) + dest[i] = src[p++]; + else + dest[i] = src[q++]; + } + } + + private static int compare(String s1, + String s2, + boolean casesensitive, + boolean numeric) + { + int res = 0; + + if (numeric) + { + double d1 = new Double(s1).doubleValue(); + double d2 = new Double(s2).doubleValue(); + if (d1 < d2) + res = -1; + else if (d1 == d2) + res = 0; + else + res = 1; + } + else if (casesensitive) + { + res = s1.compareTo(s2); + } + else + { + Locale l = Locale.getDefault(); + res = s1.toLowerCase(l).compareTo(s2.toLowerCase(l)); + } + + return res; + } + + /** + * Swaps x[a] with x[b]. + */ + private static void swap(Object x[], int a, int b) { + Object t = x[a]; + x[a] = x[b]; + x[b] = t; + } + + + private Vector sortByOrderPropertyFile(Vector props) + throws IOException + { + FileReader fr = null; + Vector orderedProps = new Vector(); + + try + { + fr = new FileReader(orderPropertyFile); + BufferedReader br = new BufferedReader(fr); + String line = ""; + String pname = ""; + int pos = 0; + while ((line = br.readLine()) != null) + { + pos = line.indexOf('#'); + if (pos != -1) + line = line.substring(0, pos).trim(); + + if (line.length() > 0) + { + pos = line.indexOf('='); + if (pos != -1) + pname = line.substring(0,pos).trim(); + else + pname = line.trim(); + + String prefPname = pname; + if (orderPropertyFilePrefix != null) + prefPname = orderPropertyFilePrefix + "." + prefPname; + + if (props.contains(prefPname) && + ! orderedProps.contains(prefPname)) + { + orderedProps.addElement(prefPname); + } + } + } + + Enumeration e = props.elements(); + while (e.hasMoreElements()) + { + String prop = (String)(e.nextElement()); + if (! orderedProps.contains(prop)) + orderedProps.addElement(prop); + } + + return orderedProps; + } + finally + { + try + { + if (fr != null) + fr.close(); + } + catch (IOException e) + { + ; // gulp + } + } + } + + protected void validate() + { + super.validate(); + } + + public void execute() + { + validate(); + + String val = value; + if (val == null && ref != null) + val = ref.getReferencedObject(project).toString(); + + if (val == null) + throw new BuildException("Either the 'Value' or 'Refid' attribute must be set."); + + StringTokenizer st = new StringTokenizer(val, delimiter); + Vector vec = new Vector(st.countTokens()); + while (st.hasMoreTokens()) + vec.addElement(st.nextToken()); + + + String propList[] = null; + + if (orderPropertyFile != null) + { + try + { + Vector sorted = sortByOrderPropertyFile(vec); + propList = new String[sorted.size()]; + sorted.copyInto(propList); + } + catch (IOException e) + { + throw new BuildException(e); + } + } + else + { + String s[] = (String[])(vec.toArray(new String[vec.size()])); + propList = new String[s.length]; + System.arraycopy(s, 0, propList, 0, s.length); + mergeSort(s, propList, 0, s.length, casesensitive, numeric); + } + + StringBuffer sb = new StringBuffer(); + for (int i=0;i<propList.length;i++) + { + if (i != 0) sb.append(delimiter); + sb.append(propList[i]); + } + + setPropertyValue(sb.toString()); + } +} diff --git a/src/java/net/sf/antcontrib/property/URLEncodeTask.java b/src/java/net/sf/antcontrib/property/URLEncodeTask.java new file mode 100644 index 0000000..cb11365 --- /dev/null +++ b/src/java/net/sf/antcontrib/property/URLEncodeTask.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.property; + +import java.io.File; +import java.net.URLEncoder; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.types.Reference; + + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * @author <additional author> + * + * @since + * + ****************************************************************************/ + + +public class URLEncodeTask + extends AbstractPropertySetterTask +{ + private String value; + private Reference ref; + + public void setName(String name) + { + setProperty(name); + } + + + public void setValue(String value) + { + this.value = URLEncoder.encode(value); + } + + public String getValue(Project p) + { + String val = value; + + if (ref != null) + val = ref.getReferencedObject(p).toString(); + + return val; + } + + public void setLocation(File location) { + setValue(location.getAbsolutePath()); + } + + public void setRefid(Reference ref) { + this.ref = ref; + } + + public String toString() { + return value == null ? "" : value; + } + + protected void validate() + { + super.validate(); + if (value == null && ref == null) + { + throw new BuildException("You must specify value, location or " + + "refid with the name attribute", + getLocation()); + } + } + + public void execute() + { + validate(); + String val = getValue(getProject()); + setPropertyValue(val); + } + +} diff --git a/src/java/net/sf/antcontrib/property/Variable.java b/src/java/net/sf/antcontrib/property/Variable.java new file mode 100644 index 0000000..013014c --- /dev/null +++ b/src/java/net/sf/antcontrib/property/Variable.java @@ -0,0 +1,352 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.property; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Properties; +import java.util.Vector; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.ProjectHelper; +import org.apache.tools.ant.Task; + +/** + * Similar to Property, but this property is mutable. In fact, much of the code + * in this class is copy and paste from Property. In general, the standard Ant + * property should be used, but occasionally it is useful to use a mutable + * property. + * <p> + * This used to be a nice little task that took advantage of what is probably + * a flaw in the Ant Project API -- setting a "user" property programatically + * causes the project to overwrite a previously set property. Now this task + * has become more violent and employs a technique known as "object rape" to + * directly access the Project's private property hashtable. + * <p>Developed for use with Antelope, migrated to ant-contrib Oct 2003. + * + * @author Dale Anson, [email protected] + * @since Ant 1.5 + * @version $Revision: 1.6 $ + */ +public class Variable extends Task { + + // attribute storage + private String value = ""; + private String name = null; + private File file = null; + private boolean remove = false; + + + /** + * Set the name of the property. Required unless 'file' is used. + * + * @param name the name of the property. + */ + public void setName( String name ) { + this.name = name; + } + + + /** + * Set the value of the property. Optional, defaults to "". + * + * @param value the value of the property. + */ + public void setValue( String value ) { + this.value = value; + } + + + /** + * Set the name of a file to read properties from. Optional. + * + * @param file the file to read properties from. + */ + public void setFile( File file ) { + this.file = file; + } + + /** + * Determines whether the property should be removed from the project. + * Default is false. Once removed, conditions that check for property + * existence will find this property does not exist. + * + * @param b set to true to remove the property from the project. + */ + public void setUnset( boolean b ) { + remove = b; + } + + + /** + * Execute this task. + * + * @exception BuildException Description of the Exception + */ + public void execute() throws BuildException { + if ( remove ) { + if ( name == null || name.equals( "" ) ) { + throw new BuildException( "The 'name' attribute is required with 'unset'." ); + } + removeProperty( name ); + return ; + } + if ( file == null ) { + // check for the required name attribute + if ( name == null || name.equals( "" ) ) { + throw new BuildException( "The 'name' attribute is required." ); + } + + // check for the required value attribute + if ( value == null ) { + value = ""; + } + + // adjust the property value if necessary -- is this necessary? + // Doesn't Ant do this automatically? + value = getProject().replaceProperties( value ); + + // set the property + forceProperty( name, value ); + } + else { + if ( !file.exists() ) { + throw new BuildException( file.getAbsolutePath() + " does not exists." ); + } + loadFile( file ); + } + } + + /** + * Remove a property from the project's property table and the userProperty table. + * Note that Ant 1.6 uses a helper for this. + */ + private void removeProperty( String name ) { + Hashtable properties = null; + // Ant 1.5 stores properties in Project + try { + properties = ( Hashtable ) getValue( getProject(), "properties" ); + if ( properties != null ) { + properties.remove( name ); + } + } + catch ( Exception e ) { + // ignore, could be Ant 1.6 + } + try { + properties = ( Hashtable ) getValue( getProject(), "userProperties" ); + if ( properties != null ) { + properties.remove( name ); + } + } + catch ( Exception e ) { + // ignore, could be Ant 1.6 + } + + // Ant 1.6 uses a PropertyHelper, can check for it by checking for a + // reference to "ant.PropertyHelper" + try { + Object property_helper = getProject().getReference( "ant.PropertyHelper" ); + if ( property_helper != null ) { + try { + properties = ( Hashtable ) getValue( property_helper, "properties" ); + if ( properties != null ) { + properties.remove( name ); + } + } + catch ( Exception e ) { + // ignore + } + try { + properties = ( Hashtable ) getValue( property_helper, "userProperties" ); + if ( properties != null ) { + properties.remove( name ); + } + } + catch ( Exception e ) { + // ignore + } + } + } + catch ( Exception e ) { + // ignore, could be Ant 1.5 + } + } + + private void forceProperty( String name, String value ) { + try { + Hashtable properties = ( Hashtable ) getValue( getProject(), "properties" ); + if ( properties == null ) { + getProject().setUserProperty( name, value ); + } + else { + properties.put( name, value ); + } + } + catch ( Exception e ) { + getProject().setUserProperty( name, value ); + } + } + + + /** + * Object rape: fondle the private parts of an object without it's + * permission. + * + * @param thisClass The class to rape. + * @param fieldName The field to fondle + * @return The field value + * @exception NoSuchFieldException Darn, nothing to fondle. + */ + private Field getField( Class thisClass, String fieldName ) throws NoSuchFieldException { + if ( thisClass == null ) { + throw new NoSuchFieldException( "Invalid field : " + fieldName ); + } + try { + return thisClass.getDeclaredField( fieldName ); + } + catch ( NoSuchFieldException e ) { + return getField( thisClass.getSuperclass(), fieldName ); + } + } + + + /** + * Object rape: fondle the private parts of an object without it's + * permission. + * + * @param instance the object instance + * @param fieldName the name of the field + * @return an object representing the value of the + * field + * @exception IllegalAccessException foiled by the security manager + * @exception NoSuchFieldException Darn, nothing to fondle + */ + private Object getValue( Object instance, String fieldName ) + throws IllegalAccessException, NoSuchFieldException { + Field field = getField( instance.getClass(), fieldName ); + field.setAccessible( true ); + return field.get( instance ); + } + + + /** + * load variables from a file + * + * @param file file to load + * @exception BuildException Description of the Exception + */ + private void loadFile( File file ) throws BuildException { + Properties props = new Properties(); + try { + if ( file.exists() ) { + FileInputStream fis = new FileInputStream( file ); + try { + props.load( fis ); + } + finally { + if ( fis != null ) { + fis.close(); + } + } + addProperties( props ); + } + else { + log( "Unable to find property file: " + file.getAbsolutePath(), + Project.MSG_VERBOSE ); + } + } + catch ( IOException ex ) { + throw new BuildException( ex, location ); + } + } + + + /** + * iterate through a set of properties, resolve them, then assign them + * + * @param props The feature to be added to the Properties attribute + */ + protected void addProperties( Properties props ) { + resolveAllProperties( props ); + Enumeration e = props.keys(); + while ( e.hasMoreElements() ) { + String name = ( String ) e.nextElement(); + String value = props.getProperty( name ); + forceProperty( name, value ); + } + } + + + /** + * resolve properties inside a properties hashtable + * + * @param props properties object to resolve + * @exception BuildException Description of the Exception + */ + private void resolveAllProperties( Properties props ) throws BuildException { + for ( Enumeration e = props.keys(); e.hasMoreElements(); ) { + String name = ( String ) e.nextElement(); + String value = props.getProperty( name ); + + boolean resolved = false; + while ( !resolved ) { + Vector fragments = new Vector(); + Vector propertyRefs = new Vector(); + ProjectHelper.parsePropertyString( value, fragments, + propertyRefs ); + + resolved = true; + if ( propertyRefs.size() != 0 ) { + StringBuffer sb = new StringBuffer(); + Enumeration i = fragments.elements(); + Enumeration j = propertyRefs.elements(); + while ( i.hasMoreElements() ) { + String fragment = ( String ) i.nextElement(); + if ( fragment == null ) { + String propertyName = ( String ) j.nextElement(); + if ( propertyName.equals( name ) ) { + throw new BuildException( "Property " + name + + " was circularly " + + "defined." ); + } + fragment = getProject().getProperty( propertyName ); + if ( fragment == null ) { + if ( props.containsKey( propertyName ) ) { + fragment = props.getProperty( propertyName ); + resolved = false; + } + else { + fragment = "${" + propertyName + "}"; + } + } + } + sb.append( fragment ); + } + value = sb.toString(); + props.put( name, value ); + } + } + } + } + +} + diff --git a/src/java/net/sf/antcontrib/util/Reflector.java b/src/java/net/sf/antcontrib/util/Reflector.java new file mode 100644 index 0000000..ab6decc --- /dev/null +++ b/src/java/net/sf/antcontrib/util/Reflector.java @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.antcontrib.util; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import org.apache.tools.ant.BuildException; + +/** + * Utility class to handle reflection on java objects. + * Its main purpose is to allow ant-contrib classes + * to compile under ant1.5 but allow the classes to + * use ant1.6 classes and code if present. + * The class is a holder class for an object and + * uses java reflection to call methods on the objects. + * If things go wrong, BuildExceptions are thrown. + * @author Peter Reilly + */ + +public class Reflector { + private Object obj; + /** + * Constructor for the wrapper using a classname + * @param name the classname of the object to construct. + */ + public Reflector(String name) { + try { + Class clazz; + clazz = Class.forName(name); + Constructor constructor; + constructor = clazz.getConstructor(new Class[]{}); + obj = constructor.newInstance(new Object[]{}); + } catch (Throwable t) { + throw new BuildException(t); + } + } + + /** + * Constructor using a passed in object. + * @param obj the object to wrap. + */ + + public Reflector(Object obj) { + this.obj = obj; + } + + /** + * @return the wrapped object. + */ + public Object getObject() { + return obj; + } + + /** + * Call a method on the object with no parameters. + * @param methodName the name of the method to call + * @return the object returned by the method + */ + public Object call(String methodName) { + try { + Method method; + method = obj.getClass().getMethod( + methodName, new Class[] {}); + return method.invoke(obj, new Object[] {}); + } catch (InvocationTargetException t) { + Throwable t2 = t.getTargetException(); + if (t2 instanceof BuildException) { + throw (BuildException) t2; + } + throw new BuildException(t2); + } catch (Throwable t) { + throw new BuildException(t); + } + } + + /** + * Call a method with an object using a specific + * type as for the method parameter. + * @param methodName the name of the method + * @param className the name of the class of the parameter of the method + * @param o the object to use as the argument of the method + * @return the object returned by the method + */ + public Object callExplicit( + String methodName, String className, Object o) { + try { + Method method; + Class clazz = Class.forName(className); + method = obj.getClass().getMethod( + methodName, new Class[] {clazz}); + return method.invoke(obj, new Object[] {o}); + } catch (InvocationTargetException t) { + Throwable t2 = t.getTargetException(); + if (t2 instanceof BuildException) { + throw (BuildException) t2; + } + throw new BuildException(t2); + } catch (Throwable t) { + throw new BuildException(t); + } + } + + /** + * Call a method with an object using a specific + * type as for the method parameter. + * @param methodName the name of the method + * @param classType the class of the parameter of the method + * @param o the object to use as the argument of the method + * @return the object returned by the method + */ + public Object callExplicit( + String methodName, Class classType, Object o) { + try { + Method method; + method = obj.getClass().getMethod( + methodName, new Class[] {classType}); + return method.invoke(obj, new Object[] {o}); + } catch (InvocationTargetException t) { + Throwable t2 = t.getTargetException(); + if (t2 instanceof BuildException) { + throw (BuildException) t2; + } + throw new BuildException(t2); + } catch (Throwable t) { + throw new BuildException(t); + } + } + + /** + * Call a method with one parameter. + * @param methodName the name of the method to call + * @param o the object to use as the parameter, this must + * be of the same type as the method parameter (not a subclass). + * @return the object returned by the method + */ + public Object call(String methodName, Object o) { + try { + Method method; + method = obj.getClass().getMethod( + methodName, new Class[] {o.getClass()}); + return method.invoke(obj, new Object[] {o}); + } catch (InvocationTargetException t) { + Throwable t2 = t.getTargetException(); + if (t2 instanceof BuildException) { + throw (BuildException) t2; + } + throw new BuildException(t2); + } catch (Throwable t) { + throw new BuildException(t); + } + } + + /** + * Call a method with two parameters. + * @param methodName the name of the method to call + * @param o1 the object to use as the first parameter, this must + * be of the same type as the method parameter (not a subclass). + * @param o2 the object to use as the second parameter, this must + * be of the same type as the method parameter (not a subclass). + * @return the object returned by the method + */ + public Object call(String methodName, Object o1, Object o2) { + try { + Method method; + method = obj.getClass().getMethod( + methodName, new Class[] {o1.getClass(), o2.getClass()}); + return method.invoke(obj, new Object[] {o1, o2}); + } catch (InvocationTargetException t) { + Throwable t2 = t.getTargetException(); + if (t2 instanceof BuildException) { + throw (BuildException) t2; + } + throw new BuildException(t2); + } catch (Throwable t) { + throw new BuildException(t); + } + } +} diff --git a/src/java/net/sf/antcontrib/util/ThreadPool.java b/src/java/net/sf/antcontrib/util/ThreadPool.java new file mode 100644 index 0000000..f8b25b3 --- /dev/null +++ b/src/java/net/sf/antcontrib/util/ThreadPool.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.util; + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * + ****************************************************************************/ + + +public class ThreadPool +{ + private int maxActive; + private int active; + + + public ThreadPool(int maxActive) + { + super(); + this.maxActive = maxActive; + this.active = 0; + } + + public void returnThread(ThreadPoolThread thread) + { + synchronized (this) + { + active--; + notify(); + } + } + + + public ThreadPoolThread borrowThread() + throws InterruptedException + { + synchronized (this) + { + if (maxActive > 0 && active >= maxActive) + { + wait(); + } + + active++; + return new ThreadPoolThread(this); + } + } +} diff --git a/src/java/net/sf/antcontrib/util/ThreadPoolThread.java b/src/java/net/sf/antcontrib/util/ThreadPoolThread.java new file mode 100644 index 0000000..6170ee4 --- /dev/null +++ b/src/java/net/sf/antcontrib/util/ThreadPoolThread.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.util; + + + + +/**************************************************************************** + * Place class description here. + * + * @author <a href='mailto:[email protected]'>Matthew Inger</a> + * + ****************************************************************************/ + + +public class ThreadPoolThread + extends Thread +{ + + private ThreadPool pool; + private Runnable runnable; + + public ThreadPoolThread(ThreadPool pool) + { + super(); + this.pool = pool; + } + + public void setRunnable(Runnable runnable) + { + this.runnable = runnable; + } + + + public void run() + { + try + { + if (runnable != null) + runnable.run(); + } + finally + { + try + { + pool.returnThread(this); + } + catch (Exception e) + { + ; // gulp; + } + } + } +} diff --git a/src/java/net/sf/antcontrib/walls/CompileWithWalls.java b/src/java/net/sf/antcontrib/walls/CompileWithWalls.java new file mode 100644 index 0000000..4b6548f --- /dev/null +++ b/src/java/net/sf/antcontrib/walls/CompileWithWalls.java @@ -0,0 +1,369 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.walls; +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.taskdefs.Copy; +import org.apache.tools.ant.taskdefs.Javac; +import org.apache.tools.ant.types.FileSet; +import org.apache.tools.ant.types.Path; +import org.apache.tools.ant.util.JAXPUtils; +import org.xml.sax.HandlerBase; +import org.xml.sax.Parser; +import org.xml.sax.SAXException; +/* + * Created on Aug 24, 2003 + * + * To change the template for this generated file go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +/** + * FILL IN JAVADOC HERE + * + * @author Dean Hiller([email protected]) + */ +public class CompileWithWalls extends Task { + private boolean setWallsTwice = false; + private boolean setJavacTwice = false; + private Walls walls; + private Javac javac; + private File wallsFile; + private File tempBuildDir; + + private Map packagesNeedingCompiling = new HashMap(); + + private SAXException cachedSAXException = null; + private IOException cachedIOException = null; + + public void setIntermediaryBuildDir(File f) { + tempBuildDir = f; + } + + public File getIntermediaryBuildDir() { + return tempBuildDir; + } + + public void setWalls(File f) { + this.wallsFile = f; + + Parser parser = JAXPUtils.getParser(); + HandlerBase hb = new WallsFileHandler(this, wallsFile); + parser.setDocumentHandler(hb); + parser.setEntityResolver(hb); + parser.setErrorHandler(hb); + parser.setDTDHandler(hb); + try { + log("about to start parsing walls file", Project.MSG_INFO); + parser.parse(wallsFile.toURL().toExternalForm()); + } catch (SAXException e) { + cachedSAXException = e; + throw new ParsingWallsException("Problem parsing walls file attached:", e); + } catch (IOException e) { + cachedIOException = e; + throw new ParsingWallsException("IOException on walls file attached:", e); + } + } + + public File getWalls() { + return wallsFile; + } + + + public Walls createWalls() { + if (walls != null) + setWallsTwice = true; + walls = new Walls(); + return walls; + } + public Javac createJavac() { + if (javac != null) + setJavacTwice = true; + javac = new Javac(); + return javac; + } + public void execute() throws BuildException { + if(cachedIOException != null) + throw new BuildException(cachedIOException, getLocation()); + else if(cachedSAXException != null) + throw new BuildException(cachedSAXException, getLocation()); + else if(tempBuildDir == null) + throw new BuildException( + "intermediaryBuildDir attribute must be specified on the compilewithwalls element" + , getLocation()); + else if (javac == null) + throw new BuildException( + "There must be a nested javac element", + getLocation()); + else if (walls == null) + throw new BuildException( + "There must be a nested walls element", + getLocation()); + else if (setWallsTwice) + throw new BuildException( + "compilewithwalls task only supports one nested walls element or one walls attribute", + getLocation()); + else if (setJavacTwice) + throw new BuildException( + "compilewithwalls task only supports one nested javac element", + getLocation()); + + getProject().addTaskDefinition("SilentMove", SilentMove.class); + getProject().addTaskDefinition("SilentCopy", SilentCopy.class); + + File destDir = javac.getDestdir(); + Path src = javac.getSrcdir(); + + if(src == null) + throw new BuildException("Javac inside compilewithwalls must have a srcdir specified"); + + String[] list = src.list(); + File[] tempSrcDirs1 = new File[list.length]; + for(int i = 0; i < list.length; i++) { + tempSrcDirs1[i] = getProject().resolveFile(list[i]); + } + + String[] classpaths = new String[0]; + if(javac.getClasspath() != null) + classpaths = javac.getClasspath().list(); + + File temp = null; + for(int i = 0; i < classpaths.length; i++) { + temp = new File(classpaths[i]); + if(temp.isDirectory()) { + + for(int n = 0; n < tempSrcDirs1.length; n++) { + if(tempSrcDirs1[n].compareTo(temp) == 0) + throw new BuildException("The classpath cannot contain any of the\n" + +"src directories, but it does.\n" + +"srcdir="+tempSrcDirs1[n]); + } + } + } + + //get rid of non-existent srcDirs + List srcDirs2 = new ArrayList(); + for(int i = 0; i < tempSrcDirs1.length; i++) { + if(tempSrcDirs1[i].exists()) + srcDirs2.add(tempSrcDirs1[i]); + } + + if (destDir == null) + throw new BuildException( + "destdir was not specified in nested javac task", + getLocation()); + + //make sure tempBuildDir is not inside destDir or we are in trouble!! + if(file1IsChildOfFile2(tempBuildDir, destDir)) + throw new BuildException("intermediaryBuildDir attribute cannot be specified\n" + +"to be the same as destdir or inside desdir of the javac task.\n" + +"This is an intermediary build directory only used by the\n" + +"compilewithwalls task, not the class file output directory.\n" + +"The class file output directory is specified in javac's destdir attribute", getLocation()); + + //create the tempBuildDir if it doesn't exist. + if(!tempBuildDir.exists()) { + tempBuildDir.mkdirs(); + log("created direction="+tempBuildDir, Project.MSG_VERBOSE); + } + + Iterator iter = walls.getPackagesToCompile(); + while (iter.hasNext()) { + Package toCompile = (Package)iter.next(); + + File buildSpace = toCompile.getBuildSpace(tempBuildDir); + if(!buildSpace.exists()) { + buildSpace.mkdir(); + log("created directory="+buildSpace, Project.MSG_VERBOSE); + } + + FileSet javaIncludes2 = + toCompile.getJavaCopyFileSet(getProject(), getLocation()); + + for(int i = 0; i < srcDirs2.size(); i++) { + File srcDir = (File)srcDirs2.get(i); + javaIncludes2.setDir(srcDir); + log(toCompile.getPackage()+": sourceDir["+i+"]="+srcDir+" destDir="+buildSpace, Project.MSG_VERBOSE); + copyFiles(srcDir, buildSpace, javaIncludes2); + } + + Path srcDir2 = toCompile.getSrcPath(tempBuildDir, getProject()); + Path classPath = toCompile.getClasspath(tempBuildDir, getProject()); + if(javac.getClasspath() != null) + classPath.addExisting(javac.getClasspath()); + + //unfortunately, we cannot clear the SrcDir in Javac, so we have to clone + //instead of just reusing the other Javac....this means added params in + //future releases will be missed unless this task is kept up to date. + //need to convert to reflection later so we don't need to keep this up to + //date. + Javac buildSpaceJavac = new Javac(); + buildSpaceJavac.setProject(getProject()); + buildSpaceJavac.setOwningTarget(getOwningTarget()); + buildSpaceJavac.setTaskName(getTaskName()); + log(toCompile.getPackage()+": Compiling"); + log(toCompile.getPackage()+": sourceDir="+srcDir2, Project.MSG_VERBOSE); + log(toCompile.getPackage()+": classPath="+classPath, Project.MSG_VERBOSE); + log(toCompile.getPackage()+": destDir="+buildSpace, Project.MSG_VERBOSE); + buildSpaceJavac.setSrcdir(srcDir2); + buildSpaceJavac.setDestdir(buildSpace); + //includes not used...ie. ignored + //includesfile not used + //excludes not used + //excludesfile not used + buildSpaceJavac.setClasspath(classPath); + //sourcepath not used + buildSpaceJavac.setBootclasspath(javac.getBootclasspath()); + //classpath not used..redefined by us + //sourcepathref not used...redefined by us. + //bootclasspathref was already copied above(see javac and you will understand) + buildSpaceJavac.setExtdirs(javac.getExtdirs()); + buildSpaceJavac.setEncoding(javac.getEncoding()); + buildSpaceJavac.setNowarn(javac.getNowarn()); + buildSpaceJavac.setDebug(javac.getDebug()); + buildSpaceJavac.setDebugLevel(javac.getDebugLevel()); + buildSpaceJavac.setOptimize(javac.getOptimize()); + buildSpaceJavac.setDeprecation(javac.getDeprecation()); + buildSpaceJavac.setTarget(javac.getTarget()); + buildSpaceJavac.setVerbose(javac.getVerbose()); + buildSpaceJavac.setDepend(javac.getDepend()); + buildSpaceJavac.setIncludeantruntime(javac.getIncludeantruntime()); + buildSpaceJavac.setIncludejavaruntime(javac.getIncludejavaruntime()); + buildSpaceJavac.setFork(javac.isForkedJavac()); + buildSpaceJavac.setExecutable(javac.getJavacExecutable()); + buildSpaceJavac.setMemoryInitialSize(javac.getMemoryInitialSize()); + buildSpaceJavac.setMemoryMaximumSize(javac.getMemoryMaximumSize()); + buildSpaceJavac.setFailonerror(javac.getFailonerror()); + buildSpaceJavac.setSource(javac.getSource()); + buildSpaceJavac.setCompiler(javac.getCompiler()); + + Javac.ImplementationSpecificArgument arg; + String[] args = javac.getCurrentCompilerArgs(); + if(args != null) { + for(int i = 0; i < args.length;i++) { + arg = buildSpaceJavac.createCompilerArg(); + arg.setValue(args[i]); + } + } + + buildSpaceJavac.setProject(getProject()); + buildSpaceJavac.perform(); + + //copy class files to javac's destDir where the user wants the class files + copyFiles(buildSpace, destDir, toCompile.getClassCopyFileSet(getProject(), getLocation())); + } + } + /** + * @param tempBuildDir + * @param destDir + * @return + */ + private boolean file1IsChildOfFile2(File tempBuildDir, File destDir) { + File parent = tempBuildDir; + for(int i = 0; i < 1000; i++) { + if(parent.compareTo(destDir) == 0) + return true; + parent = parent.getParentFile(); + if(parent == null) + return false; + } + + throw new RuntimeException("You either have more than 1000 directories in" + +"\nyour heirarchy or this is a bug, please report. parent="+parent+" destDir="+destDir); + } + + /** + * Move java or class files to temp files or moves the temp files + * back to java or class files. This must be done because javac + * is too nice and sticks already compiled classes and ones depended + * on in the classpath destroying the compile time wall. This way, + * we can keep the wall up. + * + * @param srcDir Directory to copy files from/to(Usually the java files dir or the class files dir) + * @param fileset The fileset of files to include in the move. + * @param moveToTempFile true if moving src files to temp files, false if moving temp files + * back to src files. + * @param isJavaFiles true if we are moving .java files, false if we are moving .class files. + */ + private void copyFiles( + File srcDir, + File destDir, + FileSet fileset) { + + fileset.setDir(srcDir); + if (!srcDir.exists()) + throw new BuildException( + "Directory=" + srcDir + " does not exist", + getLocation()); + + + //before we do this, we have to move all files not + //in the above fileset to xxx.java.ant-tempfile + //so that they don't get dragged into the compile + //This way we don't miss anything and all the dependencies + //are listed or the compile will break. + Copy move = (Copy)getProject().createTask("SilentCopy"); + move.setProject(getProject()); + move.setOwningTarget(getOwningTarget()); + move.setTaskName(getTaskName()); + move.setLocation(getLocation()); + move.setTodir(destDir); +// move.setOverwrite(true); + move.addFileset(fileset); + move.perform(); + } + + public void log(String msg, int level) { + super.log(msg, level); + } + + //until 1.3 is deprecated, this is a cheat to chain exceptions. + private class ParsingWallsException extends RuntimeException { + + private String message; + + public ParsingWallsException(String message, Throwable cause) { + super(message); + + this.message = message+"\n"; + + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + cause.printStackTrace(pw); + + this.message += sw; + } + + public String getMessage() { + return message; + } + + public String toString() { + return getMessage(); + } + } +}
\ No newline at end of file diff --git a/src/java/net/sf/antcontrib/walls/Package.java b/src/java/net/sf/antcontrib/walls/Package.java new file mode 100644 index 0000000..502b196 --- /dev/null +++ b/src/java/net/sf/antcontrib/walls/Package.java @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.walls; + +import java.io.File; +import java.util.StringTokenizer; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Location; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.types.FileSet; +import org.apache.tools.ant.types.Path; + + +/* + * Created on Aug 24, 2003 + * + * To change the template for this generated file go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +/** + * FILL IN JAVADOC HERE + * + * @author Dean Hiller([email protected]) + */ +public class Package { + + private String name; + private String pack; + + //signifies the package did not end with .* or .** + private boolean badPackage = false; + private String failureReason = null; + + //holds the name attribute of the package element of each + //package this package depends on. + private String[] depends; + + public void setName(String name) { + this.name = name; + } + public String getName() { + return name; + } + + public void setPackage(String pack) { + this.pack = pack; + } + public String getPackage() { + return pack; + } + + public void setDepends(String d) { + if(d == null) { + throw new RuntimeException("depends cannot be set to null"); + } + + //parse this first. + StringTokenizer tok = new StringTokenizer(d, ", \t"); + depends = new String[tok.countTokens()]; + int i = 0; + while(tok.hasMoreTokens()) { + depends[i] = tok.nextToken(); + i++; + } + } + + public String[] getDepends() { + return depends; + } + + /** + * FILL IN JAVADOC HERE + * + */ + public FileSet getJavaCopyFileSet(Project p, Location l) throws BuildException { + + if(failureReason != null) + throw new BuildException(failureReason, l); + else if(pack.indexOf("/") != -1 || pack.indexOf("\\") != -1) + throw new BuildException("A package name cannot contain '\\' or '/' like package="+pack + +"\nIt must look like biz.xsoftware.* for example", l); + FileSet set = new FileSet(); + + String match = getMatch(p, pack, ".java"); + //log("match="+match+" pack="+pack); + //first exclude the compilation module, then exclude all it's + //dependencies too. + set.setIncludes(match); + + return set; + } + + /** + * FILL IN JAVADOC HERE + * + */ + public FileSet getClassCopyFileSet(Project p, Location l) throws BuildException { + FileSet set = new FileSet(); + set.setIncludes("**/*.class"); + return set; + } + + public File getBuildSpace(File baseDir) { + return new File(baseDir, name); + } + + /** + * @return the source path + */ + public Path getSrcPath(File baseDir, Project p) { + Path path = new Path(p); + + path.setLocation(getBuildSpace(baseDir)); + return path; + } + + /** + * @return the classpath + */ + public Path getClasspath(File baseDir, Project p) { + Path path = new Path(p); + + if(depends != null) { + for(int i = 0; i < depends.length; i++) { + String buildSpace = (String)depends[i]; + + File dependsDir = new File(baseDir, buildSpace); + path.setLocation(dependsDir); + } + } + return path; + } + + private String getMatch(Project p, String pack, String postFix) { + pack = p.replaceProperties(pack); + + + pack = pack.replace('.', File.separatorChar); + + String match; + String classMatch; + if(pack.endsWith("**")) { + match = pack + File.separatorChar+"*"+postFix; + } + else if(pack.endsWith("*")) { + match = pack + postFix; + } + else + throw new RuntimeException("Please report this bug"); + + return match; + } + + /** + * FILL IN JAVADOC HERE + * @param r a fault reason string + */ + public void setFaultReason(String r) { + failureReason = r; + } +} diff --git a/src/java/net/sf/antcontrib/walls/SilentCopy.java b/src/java/net/sf/antcontrib/walls/SilentCopy.java new file mode 100644 index 0000000..d188952 --- /dev/null +++ b/src/java/net/sf/antcontrib/walls/SilentCopy.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.walls; + +import org.apache.tools.ant.Project; +import org.apache.tools.ant.taskdefs.Copy; + +/* + * Created on Aug 25, 2003 + * + * To change the template for this generated file go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +/** + * FILL IN JAVADOC HERE + * + * @author Dean Hiller([email protected]) + */ +public class SilentCopy extends Copy { + + public void log(String msg) { + log(msg, Project.MSG_INFO); + } + + public void log(String msg, int level) { + if(level == Project.MSG_INFO) + super.log(msg, Project.MSG_VERBOSE); + else if(level == Project.MSG_VERBOSE) + super.log(msg, Project.MSG_DEBUG); + + } +}
\ No newline at end of file diff --git a/src/java/net/sf/antcontrib/walls/SilentMove.java b/src/java/net/sf/antcontrib/walls/SilentMove.java new file mode 100644 index 0000000..721472a --- /dev/null +++ b/src/java/net/sf/antcontrib/walls/SilentMove.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.walls; + +import org.apache.tools.ant.Project; +import org.apache.tools.ant.taskdefs.Move; + +/* + * Created on Aug 25, 2003 + * + * To change the template for this generated file go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +/** + * FILL IN JAVADOC HERE + * + * @author Dean Hiller([email protected]) + */ +public class SilentMove extends Move { + + public void log(String msg) { + log(msg, Project.MSG_INFO); + } + + public void log(String msg, int level) { + if(level == Project.MSG_INFO) + super.log(msg, Project.MSG_VERBOSE); + else if(level == Project.MSG_VERBOSE) + super.log(msg, Project.MSG_DEBUG); + + } +}
\ No newline at end of file diff --git a/src/java/net/sf/antcontrib/walls/Walls.java b/src/java/net/sf/antcontrib/walls/Walls.java new file mode 100644 index 0000000..dda11cf --- /dev/null +++ b/src/java/net/sf/antcontrib/walls/Walls.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.walls; + +import java.util.*; + + +/* + * Created on Aug 24, 2003 + * + * To change the template for this generated file go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +/** + * FILL IN JAVADOC HERE + * + * @author Dean Hiller([email protected]) + */ +public class Walls { + + private List packages = new LinkedList(); + private Map nameToPackage = new HashMap(); + + public Package getPackage(String name) { + return (Package)nameToPackage.get(name); + } + + public void addConfiguredPackage(Package p) { + + String pack = p.getPackage(); + if(!pack.endsWith(".*") && !pack.endsWith(".**")) + p.setFaultReason("The package='"+pack+"' must end with " + +".* or .** such as biz.xsoftware.* or " + +"biz.xsoftware.**"); + + String[] depends = p.getDepends(); + if(depends == null) { + nameToPackage.put(p.getName(), p); + packages.add(p); + return; + } + + //make sure all depends are in Map first + //circular references then are not a problem because they must + //put the stuff in order + for(int i = 0; i < depends.length; i++) { + Package dependsPackage = (Package)nameToPackage.get(depends[i]); + + if(dependsPackage == null) { + p.setFaultReason("package name="+p.getName()+" did not have " + +depends[i]+" listed before it and cannot compile without it"); + } + } + + nameToPackage.put(p.getName(), p); + packages.add(p); + } + + public Iterator getPackagesToCompile() { + //must return the list, as we need to process in order, so unfortunately + //we cannot pass back an iterator from the hashtable because that would + //be unordered and would break. + return packages.iterator(); + } +}
\ No newline at end of file diff --git a/src/java/net/sf/antcontrib/walls/WallsFileHandler.java b/src/java/net/sf/antcontrib/walls/WallsFileHandler.java new file mode 100644 index 0000000..f9e8f65 --- /dev/null +++ b/src/java/net/sf/antcontrib/walls/WallsFileHandler.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.antcontrib.walls; + +import java.io.File; + +import org.apache.tools.ant.Project; +import org.xml.sax.*; + + +/** + * Handler for the root element. Its only child must be the "project" element. + */ +class WallsFileHandler extends HandlerBase { + + private final CompileWithWalls compilewithwalls; + private File file = null; + private Walls walls = null; + private Locator locator = null; + + /** + * @param CompileWithWalls + */ + WallsFileHandler(CompileWithWalls walls, File file) { + this.compilewithwalls = walls; + this.file = file; + } + + /** + * Resolves file: URIs relative to the build file. + * + * @param publicId The public identifer, or <code>null</code> + * if none is available. Ignored in this + * implementation. + * @param systemId The system identifier provided in the XML + * document. Will not be <code>null</code>. + */ + public InputSource resolveEntity(String publicId, + String systemId) { + compilewithwalls.log("publicId="+publicId+" systemId="+systemId, + Project.MSG_VERBOSE); + return null; + } + + /** + * Handles the start of a project element. A project handler is created + * and initialised with the element name and attributes. + * + * @param tag The name of the element being started. + * Will not be <code>null</code>. + * @param attrs Attributes of the element being started. + * Will not be <code>null</code>. + * + * @exception SAXParseException if the tag given is not + * <code>"project"</code> + */ + public void startElement(String name, AttributeList attrs) throws SAXParseException { + if (name.equals("walls")) { + if(attrs.getLength() > 0) + throw new SAXParseException("Error in file="+file.getAbsolutePath() + +", no attributes allowed for walls element", locator); + walls = this.compilewithwalls.createWalls(); + } else if (name.equals("package")) { + handlePackage(attrs); + } else { + throw new SAXParseException("Error in file="+file.getAbsolutePath() + +", Unexpected element \"" + name + "\"", locator); + } + } + + private void handlePackage(AttributeList attrs) throws SAXParseException { + if(walls == null) + throw new SAXParseException("Error in file="+file.getAbsolutePath() + +", package element must be nested in a walls element", locator); + + String name = attrs.getValue("name"); + String thePackage = attrs.getValue("package"); + String depends = attrs.getValue("depends"); + if(name == null) + throw new SAXParseException("Error in file="+file.getAbsolutePath() + +", package element must contain the 'name' attribute", locator); + else if(thePackage == null) + throw new SAXParseException("Error in file="+file.getAbsolutePath() + +", package element must contain the 'package' attribute", locator); + + Package p = new Package(); + p.setName(name); + p.setPackage(thePackage); + if(depends != null) + p.setDepends(depends); + + walls.addConfiguredPackage(p); + } + /** + * Sets the locator in the project helper for future reference. + * + * @param locator The locator used by the parser. + * Will not be <code>null</code>. + */ + public void setDocumentLocator(Locator locator) { + this.locator = locator; + } +}
\ No newline at end of file |