ant-contrib-1.0~b3+svn177/0000755000175000017500000000000011257224430014242 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/0000755000175000017500000000000011257224415015224 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/src/0000755000175000017500000000000011257224415016013 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/src/net/0000755000175000017500000000000011257224415016601 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/src/net/sf/0000755000175000017500000000000011257224415017211 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/0000755000175000017500000000000011257224415021354 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/logic/0000755000175000017500000000000011257224415022451 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/logic/IfTaskTest.java0000644000175000017500000000665211257223237025347 0ustar mkochmkoch/* * 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.BuildFileTest; /** * Testcase for . */ public class IfTaskTest extends BuildFileTest { public IfTaskTest(String name) { super(name); } public void setUp() { configureProject("test/resources/logic/if.xml"); } public void testNoCondition() { expectSpecificBuildException("noCondition", "no condition", "You must nest a condition into "); } public void testTwoConditions() { expectSpecificBuildException("twoConditions", "two conditions", "You must not nest more than one " + "condition into "); } public void testNothingToDo() { expectLog("nothingToDo", ""); } public void testTwoThens() { expectSpecificBuildException("twoThens", "two s", "You must not nest more than one " + " into "); } public void testTwoElses() { expectSpecificBuildException("twoElses", "two s", "You must not nest more than one " + " into "); } public void testNormalOperation() { executeTarget("normalOperation"); assertTrue(getLog().indexOf("In then") > -1); assertTrue(getLog().indexOf("some value") > -1); assertEquals(-1, getLog().indexOf("${inner}")); assertEquals(-1, getLog().indexOf("In else")); } public void testNormalOperation2() { executeTarget("normalOperation2"); assertTrue(getLog().indexOf("In else") > -1); assertEquals(-1, getLog().indexOf("In then")); } public void testNoConditionInElseif() { expectSpecificBuildException("noConditionInElseif", "no condition", "You must nest a condition into "); } public void testTwoConditionInElseif() { expectSpecificBuildException("twoConditionsInElseif", "two conditions", "You must not nest more than one " + "condition into "); } public void testNormalOperationElseif() { executeTarget("normalOperationElseif"); assertTrue(getLog().indexOf("In elseif") > -1); assertEquals(-1, getLog().indexOf("In then")); assertEquals(-1, getLog().indexOf("In else-branch")); } public void testNormalOperationElseif2() { executeTarget("normalOperationElseif2"); assertTrue(getLog().indexOf("In else-branch") > -1); assertEquals(-1, getLog().indexOf("In then")); assertEquals(-1, getLog().indexOf("In elseif")); } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/logic/TryCatchTaskTest.java0000644000175000017500000000477611257223237026537 0ustar mkochmkoch/* * 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.logic; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.BuildFileTest; /** * Testcase for . */ public class TryCatchTaskTest extends BuildFileTest { public TryCatchTaskTest(String name) { super(name); } public void setUp() { configureProject("test/resources/logic/trycatch.xml"); } public void testFullTest() { executeTarget("fullTest"); assertEquals("Tada!", getProject().getProperty("foo")); Object e = getProject().getReference("bar"); assertNotNull(e); assertTrue(e instanceof BuildException); assertEquals("Tada!", ((BuildException) e).getMessage()); } public void testTwoCatches() { // two catch blocks were not supported prior to TryCatchTask.java v 1.4. executeTarget("twoCatches"); } public void testTwoFinallys() { expectSpecificBuildException("twoFinallys", "two finally children", "You must not specify more than one "); } public void testTwoTrys() { expectSpecificBuildException("twoTrys", "two try children", "You must not specify more than one "); } public void testNoTry() { expectSpecificBuildException("noTry", "no try child", "A nested element is required"); } public void testNoException() { executeTarget("noException"); int message = getLog().indexOf("Tada!"); int catchBlock = getLog().indexOf("In "); int finallyBlock = getLog().indexOf("In "); assertTrue(message > -1); assertEquals(-1, catchBlock); assertTrue(finallyBlock > message); assertNull(getProject().getProperty("foo")); assertNull(getProject().getReference("bar")); } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/logic/OutOfDateTest.java0000644000175000017500000000732211257223237026013 0ustar mkochmkoch/* * 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.BuildFileTest; import org.apache.tools.ant.types.Path; /** * Testcase for . * * @author Peter Reilly */ public class OutOfDateTest extends BuildFileTest { public OutOfDateTest(String name) { super(name); } public void setUp() { configureProject("test/resources/logic/outofdate.xml"); } public void tearDown() { executeTarget("cleanup"); } public void testSimple() { executeTarget("simple"); } public void testVerbose() { executeTarget("verbose"); assertTrue(getLog().indexOf("outofdate with regard to") > -1); } public void testDelete() { executeTarget("delete"); } public void testDeleteAll() { executeTarget("delete-all"); } public void testDeleteQuiet() { executeTarget("init"); executeTarget("delete-quiet"); assertTrue("No deleting message", getLog().indexOf("Deleting") == -1); } public void testFileset() { executeTarget("outofdate.init"); executeTarget("outofdate.test"); assertTrue(getLog().indexOf("outofdate triggered") > -1); String outofdateSources = getProject().getProperty("outofdate.sources"); // switch \ to / if present outofdateSources.replace('\\', '/'); assertTrue("newer.text empty", outofdateSources.indexOf( "newer.text") > -1); assertTrue("file.notdone", outofdateSources.indexOf( "outofdate/source/1/2/file.notdone") > -1); assertTrue("file.done", outofdateSources.indexOf( "outofdate/source/1/2/file.done") == -1); assertTrue("done.y", outofdateSources.indexOf( "outofdate/source/1/done.y") == -1); assertTrue("partial.y", outofdateSources.indexOf( "outofdate/source/1/partial.y") > -1); String outofdateTargets = getProject().getProperty("outofdate.targets"); assertTrue(outofdateTargets.indexOf( "outofdate.xml") > -1); assertTrue(outofdateTargets.indexOf( "outofdate/gen/1/2/file.notdone") > -1); assertTrue(outofdateTargets.indexOf( "outofdate/gen/1/partial.h") > -1); assertTrue(outofdateTargets.indexOf( "outofdate/gen/1/partial.c") == -1); assertTrue(outofdateTargets.indexOf( "outofdate/gen/1/done.h") == -1); Path sourcesPath = (Path) getProject().getReference( "outofdate.sources.path"); assertTrue(sourcesPath != null); String[] sources = sourcesPath.list(); assertTrue(sources.length == 3); Path targetsPath = (Path) getProject().getReference( "outofdate.targets.path"); String[] targets = targetsPath.list(); assertTrue(targetsPath != null); assertTrue(targets.length == 3); } public void testEmptySources() { executeTarget("empty-sources"); } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/logic/ThrowTaskTest.java0000644000175000017500000000242411257223237026105 0ustar mkochmkoch/* * 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.BuildFileTest; /** * Testcase for . */ public class ThrowTaskTest extends BuildFileTest { public ThrowTaskTest(String name) { super(name); } public void setUp() { configureProject("test/resources/logic/throw.xml"); } public void testRefid() { String message = "exception created by testcase"; getProject().addReference("testref", new BuildException(message)); expectSpecificBuildException("useRefid", "this is what we've put in", message); } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/logic/AssertTest.java0000644000175000017500000000375511257223237025430 0ustar mkochmkoch/* * 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 net.sf.antcontrib.BuildFileTestBase; /** * Since AntCallBack is basically a copy and paste of antcall, the only testing * done here is on the extra features provided by antcallback. It is assumed * that changes to antcall will be propagated to antcallback and that antcall * has it's own unit tests (which turns out to have been a bad assumption, * I can't find any unit tests for antcall). * * @author danson */ public class AssertTest extends BuildFileTestBase { /** * Constructor for the AntCallBackTest object * * @param name Description of the Parameter */ public AssertTest( String name ) { super( name ); } /** The JUnit setup method */ public void setUp() { configureProject( "test/resources/logic/asserttest.xml" ); } /** A unit test for JUnit */ public void test1() { executeTarget( "test1" ); } public void test3() { expectBuildException("test3"); } public void test4() { executeTarget("test4"); } public void test5() { executeTarget("test5"); } public void test6() { executeTarget("test6"); } public void test7(){ expectBuildException("test7"); } public void test8() { executeTarget("test8"); } public void test9() { expectBuildException("test9"); } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/logic/ForeachTaskTest.java0000644000175000017500000000566411257223237026362 0ustar mkochmkoch/* * 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.BuildFileTest; /** * Testcase for . */ public class ForeachTaskTest extends BuildFileTest { public ForeachTaskTest(String name) { super(name); } public void setUp() { configureProject("test/resources/logic/foreach.xml"); } public void tearDown() { executeTarget("teardown"); } public void testSimpleList() { simpleTest("simpleList"); } public void testDelimiter() { simpleTest("delimiter"); } public void testFileset() { simpleTest("fileset"); assertTrue(getLog().indexOf("The nested fileset element is deprectated," + " use a nested path instead") > -1); } public void testFilesetAndList() { simpleTest("filesetAndList"); assertTrue(getLog().indexOf("The nested fileset element is deprectated," + " use a nested path instead") > -1); } public void testNoList() { expectSpecificBuildException("noList", "neither list nor fileset", "You must have a list or path to iterate through"); } public void testNoTarget() { expectSpecificBuildException("noTarget", "no target", "You must supply a target to perform"); } public void testNoParam() { expectSpecificBuildException("noParam", "no param", "You must supply a property name to set on each iteration in param"); } public void testNestedParam() { executeTarget("nestedParam"); assertTrue(getLog().indexOf("Called with param: rincewind") > -1); } public void testNestedReference() { executeTarget("nestedReference"); assertTrue(getLog().indexOf("Called with param: twoflower") > -1); } public void testPath() { simpleTest("path"); } public void testPathAndList() { simpleTest("pathAndList"); } private void simpleTest(String target) { executeTarget(target); int last = -1; for (int i = 1; i < 4; i++) { int thisIdx = getLog().indexOf("Called with param: " + i); assertTrue(thisIdx > last); last = thisIdx; } } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/logic/TimestampSelectorTest.java0000644000175000017500000000304311257223237027621 0ustar mkochmkoch/* * 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.BuildFileTest; /** * Testcase for . */ public class TimestampSelectorTest extends BuildFileTest { public TimestampSelectorTest(String name) { super(name); } public void setUp() { configureProject("test/resources/logic/timestampselector.xml"); } public void tearDown() { executeTarget("teardown"); } public void testFileStampFL() { simpleTest("filestamp.fl", "file2.txt"); } public void testFileStampPR() { simpleTest("filestamp.pr", "file2.txt"); } public void testDirStampDL() { simpleTest("dirstamp.dl", "dir2"); } public void testDirStampPR() { simpleTest("dirstamp.pr", "dir2"); } private void simpleTest(String target, String expected) { executeTarget(target); assertTrue(getLog().indexOf(expected) > -1); } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/logic/ForTest.java0000644000175000017500000000243511257223237024707 0ustar mkochmkoch/* * Copyright (c) 2006 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.BuildFileTest; /** * Testcase for . */ public class ForTest extends BuildFileTest { public ForTest(String name) { super(name); } public void setUp() { configureProject("test/resources/logic/for.xml"); } public void testLoop() { executeTarget("loop"); assertTrue(getLog().indexOf( "i is 10") != -1); } public void testStep() { executeTarget("step"); assertTrue(getLog().indexOf( "i is 10") != -1); assertTrue(getLog().indexOf( "i is 3") == -1); } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/logic/SwitchTest.java0000644000175000017500000000553311257223237025424 0ustar mkochmkoch/* * 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.BuildFileTest; /** * Testcase for . */ public class SwitchTest extends BuildFileTest { public SwitchTest(String name) { super(name); } public void setUp() { configureProject("test/resources/logic/switch.xml"); } public void testNoValue() { expectSpecificBuildException("noValue", "no value", "Value is missing"); } public void testNoChildren() { expectSpecificBuildException("noChildren", "no children", "No cases supplied"); } public void testTwoDefaults() { expectSpecificBuildException("twoDefaults", "two defaults", "Cannot specify multiple default cases"); } public void testNoMatch() { expectSpecificBuildException("noMatch", "no match", "No case matched the value foo" + " and no default has been specified."); } public void testCaseNoValue() { expectSpecificBuildException("caseNoValue", " no value", "Value is required for case."); } public void testDefault() { executeTarget("testDefault"); assertTrue(getLog().indexOf("In default") > -1); assertTrue(getLog().indexOf("baz") > -1); assertEquals(-1, getLog().indexOf("${inner}")); assertEquals(-1, getLog().indexOf("In case")); } public void testCase() { executeTarget("testCase"); assertTrue(getLog().indexOf("In case") > -1); assertTrue(getLog().indexOf("baz") > -1); assertEquals(-1, getLog().indexOf("${inner}")); assertEquals(-1, getLog().indexOf("In default")); } public void testCaseSensitive() { executeTarget("testCaseSensitive"); assertTrue(getLog().indexOf("In default") > -1); assertEquals(-1, getLog().indexOf("In case")); } public void testCaseInSensitive() { executeTarget("testCaseInSensitive"); assertTrue(getLog().indexOf("In case") > -1); assertEquals(-1, getLog().indexOf("In default")); } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/logic/AntCallBackTest.java0000644000175000017500000000476511257223237026270 0ustar mkochmkoch/* * 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 net.sf.antcontrib.BuildFileTestBase; /** * Since AntCallBack is basically a copy and paste of antcall, the only testing * done here is on the extra features provided by antcallback. It is assumed * that changes to antcall will be propagated to antcallback and that antcall * has it's own unit tests (which turns out to have been a bad assumption, * I can't find any unit tests for antcall). * * @author danson */ public class AntCallBackTest extends BuildFileTestBase { /** * Constructor for the AntCallBackTest object * * @param name Description of the Parameter */ public AntCallBackTest( String name ) { super( name ); } /** The JUnit setup method */ public void setUp() { configureProject( "test/resources/logic/antcallbacktest.xml" ); } /** A unit test for JUnit */ public void test1() { expectPropertySet( "test1", "prop1", "prop1" ); } /** A unit test for JUnit */ public void test2() { expectPropertySet( "test2", "prop1", "prop1" ); expectPropertySet( "test2", "prop2", "prop2" ); expectPropertySet( "test2", "prop3", "prop3" ); } /** A unit test for JUnit */ public void test3() { expectPropertySet( "test3", "prop1", "prop1" ); expectPropertySet( "test3", "prop2", "prop2" ); expectPropertySet( "test3", "prop3", "prop3" ); } /** A unit test for JUnit */ public void test4() { expectPropertyUnset( "test4", "prop1" ); expectPropertySet( "test4", "prop2", "prop2" ); expectPropertySet( "test4", "prop3", "prop3" ); } /** A unit test for JUnit */ public void test5() { expectPropertySet( "test5", "prop1", "blah" ); expectPropertySet( "test5", "prop2", "prop2" ); expectPropertySet( "test5", "prop3", "prop3" ); } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/logic/RelentlessTaskTest.java0000644000175000017500000000343711257223237027127 0ustar mkochmkoch/* * Copyright (c) 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 org.apache.tools.ant.BuildFileTest; /** * Testcase for . * @author Christopher Heiny */ public class RelentlessTaskTest extends BuildFileTest { public RelentlessTaskTest(String name) { super(name); } public void setUp() { configureProject("test/resources/logic/relentless.xml"); } public void tearDown() { executeTarget("teardown"); } public void testSimpleTasks() { simpleTest("simpleTasks"); } public void testFailTask() { expectSpecificBuildException("failTask", "2 failed tasks", "Relentless execution: 2 of 4 tasks failed."); } public void testNoTasks() { expectSpecificBuildException("noTasks", "missing task list", "No tasks specified for ."); } private void simpleTest(String target) { executeTarget(target); int last = -1; for (int i = 1; i < 4; i++) { int thisIdx = getLog().indexOf("Called with param: " + i); assertTrue(thisIdx > last); last = thisIdx; } } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/antclipse/0000755000175000017500000000000011257224415023336 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/antclipse/AntclipseTest.java0000644000175000017500000000271411257223237026770 0ustar mkochmkoch/* * 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 org.apache.tools.ant.BuildFileTest; /** * Basic test for "antclipse" task. For the moment it just launches the test xml script. * @author Adrian Spinei aspinei@myrealbox.com * @version $Revision: 1.2 $ */ public class AntclipseTest extends BuildFileTest { /** * Simple overriden constructor * @param arg0 */ public AntclipseTest(String arg0) { super(arg0); } /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ public void setUp() { configureProject("test/resources/antclipse/antclipsetest.xml"); } /* (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ public void tearDown() { //nothing to do } /** * Launches the "everything" task. Should not throw errors. */ public void testExecuteDefaultBuild() { executeTarget("everything"); } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/design/0000755000175000017500000000000011257224415022625 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/design/VerifyDesignTest.java0000644000175000017500000003401011257223237026725 0ustar mkochmkoch/* * 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 junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.tools.ant.BuildFileTest; import org.apache.tools.ant.util.JavaEnvUtils; /** * BIG NOTE*************************************************** * Always expect specific exceptions. Most of these test cases when * first submitted were not and therefore were not testing what they said * they were testing. Exceptions were being caused by other things and the * tests were still passing. Now all tests expect a specific exception * so if any other is thrown we will fail the test case. * ************************************************************ * * Testcase for . */ public class VerifyDesignTest extends BuildFileTest { private final static String REASON = "Build should have failed with proper message and did not"; private String baseDir = "test"+File.separator +"resources"+File.separator +"design"+File.separator; private String c = File.separator; public VerifyDesignTest(String name) { super(name); } public void setUp() { configureProject("test/resources/design/verifydesign.xml"); // project.log("ASFDSADF", Project.MSG_INFO); } private static String s = ""; public static void log(String msg) { s += msg+"\n"; } public void tearDown() { executeTarget("cleanup"); //System.out.println("test log=\n"+s); } public void testArrayDepend() { String class1 = "mod.arraydepend.ClassDependsOnArray"; String class2 = "mod.dummy.DummyClass"; expectDesignCheckFailure("testArrayDepend", Design.getErrorMessage(class1, class2)); } public void testArrayDepend2() { executeTarget("testArrayDepend2"); } public void testArrayDepend3() { String class1 = "mod.arraydepend3.ClassDependsOnArray"; // // The trailing semi-colon makes the test pass, // but likely reflects a problem in the VerifyDesign task // String class2 = "mod.dummy.DummyClass;"; expectDesignCheckFailure("testArrayDepend3", Design.getErrorMessage(class1, class2)); } public void testBadXML() { File designFile = new File("test/resources/design/designfiles/badxml.xml"); String msg = "\nProblem parsing design file='" + designFile.getAbsolutePath() + "'. \nline=3 column=1 Reason:\nElement type \"design\" must be followed by either attribute specifications, \">\" or \"/>\".\n"; expectSpecificBuildException("testBadXML", REASON, msg); } public void testCastDepend() { String class1 = "mod.castdepend.ClassDependsOnCast"; String class2 = "mod.dummy.DummyInterface"; expectDesignCheckFailure("testCastDepend", Design.getErrorMessage(class1, class2)); } public void testCatchDepend() { String class1 = "mod.catchdepend.ClassDependsOnCatch"; String class2 = "mod.dummy.DummyRuntimeException"; expectDesignCheckFailure("testCatchDepend", Design.getErrorMessage(class1, class2)); } public void testClassFiles() { String class1 = "mod.castdepend.ClassDependsOnCast"; String class2 = "mod.dummy.DummyInterface"; expectDesignCheckFailure("testClassFiles", Design.getErrorMessage(class1, class2)); } public void testDeclareJavaUtil() { executeTarget("testDeclareJavaUtil"); } public void testDeclareJavaUtilFail() { String class1 = "mod.declarejavautil.ClassDependsOnJavaUtil"; String class2 = "java.util.List"; expectDesignCheckFailure("testDeclareJavaUtilFail", Design.getErrorMessage(class1, class2)); } public void testDeclareJavax() { String class1 = "mod.declarejavax.ClassDependsOnJavax"; String class2 = "javax.swing.JButton"; expectDesignCheckFailure("testDeclareJavax", Design.getErrorMessage(class1, class2)); } public void testDeclareJavaxPass() { executeTarget("testDeclareJavaxPass"); } //tests to write //depend on java.util should pass by default //depend on java.util should fail after defining needDeclareTrue //depend on javax.swing should pass after needDeclareFalse //depend on dummy should pass after needDeclareFalse public void testFieldDepend() { String class1 = "mod.fielddepend.ClassDependsOnField"; String class2 = "mod.dummy.DummyClass"; expectDesignCheckFailure("testFieldDepend", Design.getErrorMessage(class1, class2)); } public void testFieldRefDepend() { if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_1) || JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_2) || JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_3)) { return; } String class1 = "mod.fieldrefdepend.ClassDependsOnReferenceInFieldDeclaration"; String class2 = "mod.dummy.DummyClass"; expectDesignCheckFailure("testFieldRefDepend", Design.getErrorMessage(class1, class2)); } public void testInnerClassDepend() { String class1 = "mod.innerclassdepend.InnerClassDependsOnSuper$Inner"; String class2 = "mod.dummy.DummyClass"; expectDesignCheckFailure("testInnerClassDepend", Design.getErrorMessage(class1, class2)); } public void testInstanceOfDepend() { String class1 = "mod.instanceofdepend.ClassDependsOnInstanceOf"; String class2 = "mod.dummy.DummyInterface"; expectDesignCheckFailure("testInstanceOfDepend", Design.getErrorMessage(class1, class2)); } public void testInterfaceDepend() { String class1 = "mod.interfacedepend.ClassDependsOnInterfaceMod2"; String class2 = "mod.dummy.DummyInterface"; expectDesignCheckFailure("testInterfaceDepend", Design.getErrorMessage(class1, class2)); } public void testLocalVarDepend() { String class1 = "mod.localvardepend.ClassDependsOnLocalVar"; String class2 = "mod.dummy.DummyClass"; expectDesignCheckFailure("testLocalVarDepend", Design.getErrorMessage(class1, class2)); } public void testLocalVarRefDepend() { if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_1) || JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_2) || JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_3)) { return; } String class1 = "mod.localvarrefdepend.ClassDependsOnLocalVariableReference"; String class2 = "mod.dummy.DummyInterface"; expectDesignCheckFailure("testLocalVarRefDepend", Design.getErrorMessage(class1, class2)); } public void testMissingAttribute() { File designFile = new File("test/resources/design/designfiles/missingattribute.xml"); String msg = "\nProblem parsing design file='" + designFile.getAbsolutePath() + "'. \nline=3 column=31 Reason:\nError in file=" + designFile.getAbsolutePath() + ", package element must contain the 'name' attribute\n"; expectSpecificBuildException("testMissingAttribute", REASON, msg); } public void testMultipleErrors() { File jarFile = new File(baseDir+File.separator+"build"+File.separator+"jar" +File.separator+"test.jar"); String class1 = "mod.arraydepend.ClassDependsOnArray"; String class2 = "mod.dummy.DummyClass"; //executeTarget("testMultipleErrors"); String error1 = Design.getWrapperMsg(jarFile, Design.getErrorMessage(class1, class2)); class1 = "mod.castdepend.ClassDependsOnCast"; String error2 = Design.getWrapperMsg(jarFile, Design.getNoDefinitionError(class1)); class1 = "mod.catchdepend.ClassDependsOnCatch"; class2 = "mod.dummy.DummyRuntimeException"; String error3 = Design.getWrapperMsg(jarFile, Design.getErrorMessage(class1, class2)); String s = "\nEvaluating package=mod.arraydepend"+error1; s += "\nEvaluating package=mod.castdepend"+error2; s += "\nEvaluating package=mod.catchdepend"+error3; s += "\nEvaluating package=mod.dummy"; // executeTarget("testMultipleErrors"); expectDesignCheckFailure("testMultipleErrors", s); } public void testNewDepend() { String class1 = "mod.newdepend.ClassDependsOnNew"; String class2 = "mod.dummy.DummyClass"; expectDesignCheckFailure("testNewDepend", Design.getErrorMessage(class1, class2)); } public void testNewDepend2() { String class1 = "mod.newdepend2.ClassDependsOnNewInField"; String class2 = "mod.dummy.DummyClass"; expectDesignCheckFailure("testNewDepend2", Design.getErrorMessage(class1, class2)); } public void testNoDebugOption() { String class1 = "mod.nodebugoption.ClassDependsOnLocalVar"; expectDesignCheckFailure("testNoDebugOption", VisitorImpl.getNoDebugMsg(class1)); } public void testNoJar() { File jar = new File("test/resources/design/build/jar/test.jar"); expectSpecificBuildException("testNoJar", REASON, VisitorImpl.getNoFileMsg(jar)); } public void testParamDepend() { String class1 = "mod.paramdepend.ClassDependsOnParameter"; String class2 = "mod.dummy.DummyClass"; expectDesignCheckFailure("testParamDepend", Design.getErrorMessage(class1, class2)); } public void testPassLocalDepend() { executeTarget("testPassLocalDepend"); } public void testPathElementLocation() { executeTarget("testPathElementLocation"); } public void testPathElementPath() { executeTarget("testPathElementPath"); } public void testPutStatic() { executeTarget("testPutStatic"); } public void testRecursion() { executeTarget("testRecursion"); } public void testRecursion2() { executeTarget("testRecursion2"); } public void testRecursion3() { executeTarget("testRecursion3"); } public void testReturnValDepend() { String class1 = "mod.returnvaldepend.ClassDependsOnReturnValue"; String class2 = "mod.dummy.DummyInterface"; expectDesignCheckFailure("testReturnValDepend", Design.getErrorMessage(class1, class2)); } public void testSignatureExceptionDepend() { String class1 = "mod.signatureexceptiondepend.ClassDependsOnExceptionInMethodSignature"; String class2 = "mod.dummy.DummyException"; expectDesignCheckFailure("testSignatureExceptionDepend", Design.getErrorMessage(class1, class2)); } public void testStaticDepend() { String class1 = "mod.staticdepend.ClassDependsOnStatic"; String class2 = "mod.dummy.DummyClass"; expectDesignCheckFailure("testStaticDepend", Design.getErrorMessage(class1, class2)); } public void testStaticField2Depend() { String class1 = "mod.staticfield2depend.ClassDependsOnStaticField"; String class2 = "mod.dummy.DummyClass"; expectDesignCheckFailure("testStaticField2Depend", Design.getErrorMessage(class1, class2)); } public void testStaticFieldDepend() { String class1 = "mod.staticfielddepend.ClassDependsOnStaticField"; String class2 = "mod.dummy.DummyClass"; expectDesignCheckFailure("testStaticFieldDepend", Design.getErrorMessage(class1, class2)); } public void testStaticFinalDepend() { //This is an impossible test since javac compiles String and primitive constants into the code //losing any reference to the class that contains the constant...In this one instance, //verifydesign can't verify that constant imports don't violate the design!!!! //check out mod.staticfinaldepend.ClassDependsOnStaticField to see the code //that will pass the design even if it is violating it. // String class1 = "mod.staticfinaldepend.ClassDependsOnConstant"; // String class2 = "mod.dummy.DummyClass"; // expectDesignCheckFailure("testStaticFinalDepend", Design.getErrorMessage(class1, class2)); } public void testSuperDepend() { String s = File.separator; File f = new File("test"+s+"resources"+s+"design"+s+"build"+s+"jar"+s+"test.jar"); // executeTarget("testSuperDepend"); String class1 = "mod.superdepend.ClassDependsOnSuperMod2"; String class2 = "mod.dummy.DummyClass"; expectDesignCheckFailure("testSuperDepend", Design.getErrorMessage(class1, class2)); //jar file should have been deleted assertTrue("jar file should not exist yet still does", !f.exists()); } public void testWarSuccess() { executeTarget("testWarSuccess"); } public void testWarFailure() { String class1 = "mod.warfailure.ClassDependsOnSuperMod2"; String class2 = "mod.dummy.DummyClass"; expectDesignCheckFailure("testWarFailure", Design.getErrorMessage(class1, class2)); } public static void main(String[] args) { TestSuite suite = new TestSuite(); suite.addTest(new VerifyDesignTest("testArrayDepend2")); TestRunner.run(suite); } private void expectDesignCheckFailure(String target, String message) { expectSpecificBuildException(target, "Design is broken", "Design check failed due to previous " + "errors"); assertLogContaining(message); } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/math/0000755000175000017500000000000011257224415022305 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/math/MathTest.java0000644000175000017500000000227111257223237024704 0ustar mkochmkoch/* * 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 net.sf.antcontrib.BuildFileTestBase; /** * * @author danson */ public class MathTest extends BuildFileTestBase { /** * Constructor for the MathTest object * * @param name Description of the Parameter */ public MathTest( String name ) { super( name ); } /** The JUnit setup method */ public void setUp() { configureProject( "test/resources/math/mathtest.xml" ); } /** A unit test for JUnit */ public void test1() { expectPropertySet("test1", "result", "18"); } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/property/0000755000175000017500000000000011257224415023240 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/property/PropertySelectorTest.java0000644000175000017500000000336711257223237030302 0ustar mkochmkoch/* * 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.property; import org.apache.tools.ant.BuildFileTest; /** * Testcase for . */ public class PropertySelectorTest extends BuildFileTest { public PropertySelectorTest(String name) { super(name); } public void setUp() { configureProject("test/resources/property/propertyselector.xml"); } public void testDefaultGrouping() { simpleTest("select.test.grouping.0", "module.Module1.id", "module.Module2.id"); } public void testDefaultGrouping1() { simpleTest("select.test.grouping.1", "Module1", "Module2"); } private void simpleTest(String target, String expected1, String expected2) { executeTarget(target); String order1 = expected1 + "," + expected2; String order2 = expected2 + "," + expected1; int index1 = getLog().indexOf(order1); int index2 = getLog().indexOf(order2); assertTrue("Neither '" + order1 + "' nor '" + order2 + "' was found in '" + getLog() + "'", index1 > -1 || index2 > -1); } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/property/VariableTest.java0000644000175000017500000000366511257223237026503 0ustar mkochmkoch/* * 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 net.sf.antcontrib.BuildFileTestBase; public class VariableTest extends BuildFileTestBase { public VariableTest(String name) { super(name); } public void setUp() { configureProject("test/resources/property/variabletest.xml"); } public void test1() { expectPropertySet("test1", "x", "6"); } public void test2() { expectPropertySet("test2", "x", "12"); } public void test3() { expectPropertySet("test3", "x", "6 + 12"); } public void test4() { expectPropertySet("test4", "x", "6"); } public void test5() { expectPropertySet("test5", "str", "I am a string."); } public void test6() { expectPropertySet("test6", "x", "Today is blue."); } public void test7() { expectPropertySet("test7", "x", "6"); } /* TODO: depends on the Antelope , need to adjust to use the ant-contrib public void test8() { expectPropertySet("test8", "x", "12"); expectLogContaining("test8", "12"); } */ public void test9() { expectPropertyUnset("test9", "i"); } public void test10() { expectPropertySet("test10", "x", "xxx"); } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/property/PropertyCopyTest.java0000644000175000017500000000351511257223237027427 0ustar mkochmkoch/* * 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.BuildFileTest; /** * Testcase for . */ public class PropertyCopyTest extends BuildFileTest { public PropertyCopyTest(String name) { super(name); } public void setUp() { configureProject("test/resources/property/propertycopy.xml"); } /** * Runs a propertyCopy without a specified name attribute. */ public void testMissingName() { expectSpecificBuildException("missingName", "missing name", "You must specify a property to set."); } public void testMissingFrom() { expectSpecificBuildException("missingFrom", "missing from", "Missing the 'from' attribute."); } public void testNonSilent() { expectSpecificBuildException("nonSilent", "from doesn't exist", "Property 'bar' is not defined."); } public void testSilent() { executeTarget("silent"); assertPropertyEquals("foo", null); } public void testNormal() { executeTarget("normal"); assertPropertyEquals("displayName", "My Organiziation"); } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/property/PathToFileSetTest.java0000644000175000017500000000451111257223237027420 0ustar mkochmkoch/* * 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.BuildFileTest; /** * Testcase for . */ public class PathToFileSetTest extends BuildFileTest { public PathToFileSetTest(String name) { super(name); } public void setUp() { configureProject("test/resources/property/pathtofileset.xml"); } public void tearDown() { executeTarget("cleanup"); } public void testSimple() { executeTarget("simple"); assertPropertyContains("simple.0.property", "0.java"); assertPropertyContains("simple.0.property", "1.java"); assertPropertyNotContains("simple.0.property", "2.java"); assertPropertyNotContains("simple.0.property", "3.java"); assertPropertyNotContains("simple.1.property", "0.java"); assertPropertyNotContains("simple.1.property", "1.java"); assertPropertyContains("simple.1.property", "2.java"); assertPropertyContains("simple.1.property", "3.java"); } public void testSimpleException() { expectBuildExceptionContaining("simple-exception", "expect not relative to", "is not relative to"); } private void assertPropertyContains(String property, String expected) { String result = getProject().getProperty(property); assertTrue("property " + property + " contains " + expected, result.indexOf(expected) != -1); } private void assertPropertyNotContains(String property, String expected) { String result = getProject().getProperty(property); assertTrue("property " + property + " contains " + expected, result.indexOf(expected) == -1); } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/platform/0000755000175000017500000000000011257224415023200 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/platform/OsFamilyTest.java0000644000175000017500000000254611257223237026436 0ustar mkochmkoch/* * 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.BuildFileTest; /** * Testcase for . */ public class OsFamilyTest extends BuildFileTest { public OsFamilyTest(String name) { super(name); } public void setUp() { configureProject("test/resources/platform/osfamily.xml"); } public void testConsistency() { executeTarget("consistency"); assertPropertyEquals("consistent", "true"); } public void testMissingProperty() { expectSpecificBuildException("missingProperty", "no attribute", "The attribute 'property' is required " + "for the OsFamily task."); } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/platform/ShellScriptTest.java0000644000175000017500000001077211257223237027147 0ustar mkochmkoch/* * 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.BuildFileTest; /** * Testcase for * * @author Peter Reilly */ public class ShellScriptTest extends BuildFileTest { public ShellScriptTest(String name) { super(name); } public void setUp() { configureProject("test/resources/platform/shellscript.xml"); staticInitialize(); } public void testShHello() { if (! hasSh) return; executeTarget("sh.hello"); assertTrue(getLog().indexOf("hello world") > -1); } public void testBashHello() { if (! hasBash) return; executeTarget("bash.hello"); assertTrue(getLog().indexOf("hello world") > -1); } public void testShInputString() { if (! hasSh) return; executeTarget("sh.inputstring"); assertTrue(getLog().indexOf("hello world") > -1); } public void testShProperty() { if (! hasSh) return; executeTarget("sh.property"); assertTrue(getLog().indexOf("this is a property") > -1); } public void testPythonHello() { if (! hasPython) return; executeTarget("python.hello"); assertTrue(getLog().indexOf("hello world") > -1); } public void testPerlHello() { if (! hasPerl) return; executeTarget("perl.hello"); assertTrue(getLog().indexOf("hello world") > -1); } public void testNoShell() { expectBuildExceptionContaining( "noshell", "Execute failed", "a shell that should not exist"); } public void testSed() { if (! hasSed) return; executeTarget("sed.test"); assertTrue(getLog().indexOf("BAR bar bar bar BAR bar") > -1); } public void testSetProperty() { if (! hasSh) return; executeTarget("sh.set.property"); assertPropertyEquals("sh.set.property", "hello world"); } public void testTmpSuffix() { if (! hasSh) return; executeTarget("sh.tmp.suffix"); assertTrue(getLog().indexOf(".bat") > -1); } public void testCmd() { if (! hasCmd) return; executeTarget("cmd.test"); assertTrue(getLog().indexOf("hello world") > -1); } public void testDir() { if (! hasBash) return; executeTarget("dir.test"); assertTrue( getProject().getProperty("dir.test.property") .indexOf("subdir") > -1); } public void testCommand() { expectBuildExceptionContaining( "command.test", "Attribute failed", "Attribute command is not supported"); } private static boolean initialized = false; private static boolean hasSh = false; private static boolean hasBash = false; private static boolean hasPython = false; private static boolean hasPerl = false; private static boolean hasSed = false; private static boolean hasCmd = false; private static Object staticMonitor = new Object(); /** * check if the env contains the shells * sh, bash, python and perl * assume cmd.exe exists for windows */ private void staticInitialize() { synchronized (staticMonitor) { if (initialized) return; initialized = true; hasSh = hasShell("hassh"); hasBash = hasShell("hasbash"); hasPerl = hasShell("hasperl"); hasPython = hasShell("haspython"); hasSed = hasShell("hassed"); hasCmd = hasShell("hascmd"); } } private boolean hasShell(String target) { try { executeTarget(target); return true; } catch (Throwable t) { return false; } } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/BuildFileTestBase.java0000644000175000017500000001011411257223237025507 0ustar mkochmkoch/* * 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; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URL; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.BuildFileTest; /** * More methods for BuildFileTest. * * @author Dale Anson */ public abstract class BuildFileTestBase extends BuildFileTest { /** * Constructor for the BuildFileTestBase object * * @param name string to pass up to TestCase constructor */ public BuildFileTestBase( String name ) { super( name ); } /** * run a target, expect a build exception * * @param target target to run */ protected void expectBuildException( String target ) { expectSpecificBuildException( target, "no specific reason", null ); } /** * Assert that the given message has NOT been logged with a priority >= INFO * when running the given target. * * @param target Description of the Parameter * @param log Description of the Parameter */ protected void expectLogNotContaining( String target, String log ) { executeTarget( target ); String realLog = getLog(); assertTrue( "expecting log to NOT contain \"" + log + "\" log was \"" + realLog + "\"", realLog.indexOf( log ) < 0 ); } /** * set up to run the named project *

* Overrides BuildFileTest.configureProject to first * attempt to make a File out of the filename parameter, if the resulting * file does not exists, then attempt to locate the file in the classpath. * This way, test xml files can be placed alongside of their corresponding * class file and can be easily found. * * @param filename name of project file to run * @exception BuildException Description of the Exception */ protected void configureProject( String filename ) throws BuildException { // find the build file File f = new File( filename ); if ( !f.exists() ) { URL url = getClass().getClassLoader().getResource( filename ); if ( url == null ) throw new BuildException( "Can't find " + filename ); f = new File( url.getPath() ); if ( !f.exists() ) throw new BuildException( "Can't find " + filename ); } super.configureProject(f.getAbsolutePath()); } /** * run a target, expect an exception string containing the substring we look * for (case sensitive match) * * @param target target to run * @param cause information string to reader of report * @param contains substring of the build exception to look for */ protected void expectBuildExceptionStackTraceContaining( String target, String cause, String contains ) { try { executeTarget( target ); } catch ( org.apache.tools.ant.BuildException ex ) { //buildException = ex; // buildException has private access in super StringWriter stacktrace = new StringWriter(); PrintWriter writer = new PrintWriter( stacktrace, true ); ex.printStackTrace( writer ); String trace = stacktrace.toString(); if ( ( null != contains ) && ( trace.indexOf( contains ) == -1 ) ) { fail( "Should throw BuildException because '" + cause + "' with message containing '" + contains + "' (actual message '" + trace + "' instead)" ); } return; } fail( "Should throw BuildException because: " + cause ); } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/walls/0000755000175000017500000000000011257224415022476 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/walls/CompileWithWallsTest.java0000644000175000017500000003374611257223237027446 0ustar mkochmkoch/* * 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.BuildFileTest; import junit.framework.TestSuite; import junit.textui.TestRunner; /** * BIG NOTE*************************************************** * Always expect specific exceptions. Most of these test cases when * first submitted were not and therefore were not testing what they said * they were testing. Exceptions were being caused by other things and the * tests were still passing. Now all tests expect a specific exception * so if any other is thrown we will fail the test case. * ************************************************************ * * Testcase for . */ public class CompileWithWallsTest extends BuildFileTest { private String baseDir = "test"+File.separator +"resources"+File.separator +"walls"+File.separator; private String c = File.separator; public CompileWithWallsTest(String name) { super(name); } public void setUp() { configureProject("test/resources/walls/compilewithwalls.xml"); // project.addBuildListener(new LogListener()); } // protected class LogListener implements BuildListener { // // /* (non-Javadoc) // * @see org.apache.tools.ant.BuildListener#buildStarted(org.apache.tools.ant.BuildEvent) // */ // public void buildStarted(BuildEvent event) { // // TODO Auto-generated method stub // // } // // /* (non-Javadoc) // * @see org.apache.tools.ant.BuildListener#buildFinished(org.apache.tools.ant.BuildEvent) // */ // public void buildFinished(BuildEvent event) { // // TODO Auto-generated method stub // // } // // /* (non-Javadoc) // * @see org.apache.tools.ant.BuildListener#targetStarted(org.apache.tools.ant.BuildEvent) // */ // public void targetStarted(BuildEvent event) { // // TODO Auto-generated method stub // // } // // /* (non-Javadoc) // * @see org.apache.tools.ant.BuildListener#targetFinished(org.apache.tools.ant.BuildEvent) // */ // public void targetFinished(BuildEvent event) { // // TODO Auto-generated method stub // // } // // /* (non-Javadoc) // * @see org.apache.tools.ant.BuildListener#taskStarted(org.apache.tools.ant.BuildEvent) // */ // public void taskStarted(BuildEvent event) { // // TODO Auto-generated method stub // // } // // /* (non-Javadoc) // * @see org.apache.tools.ant.BuildListener#taskFinished(org.apache.tools.ant.BuildEvent) // */ // public void taskFinished(BuildEvent event) { // // TODO Auto-generated method stub // // } // // /* (non-Javadoc) // * @see org.apache.tools.ant.BuildListener#messageLogged(org.apache.tools.ant.BuildEvent) // */ // public void messageLogged(BuildEvent event) { // // System.out.println(event.getException()); // System.out.println("aaa"); // } // // } public void tearDown() { executeTarget("cleanup"); // System.out.println(getFullLog()); // System.out.println("std out. from ant build begin--------------"); // System.out.println(getOutput()); // System.out.println("std.out. from ant build end----------------"); // System.out.println("std err. from ant build begin--------------"); // System.out.println(getError()); // System.out.println("std.err. from ant build end----------------"); } public void testTooManyNestedWallElements() { expectSpecificBuildException("testTooManyNestedWallElements" , "TooManyNestedWallElements" , "compilewithwalls task only supports one nested walls element or one walls attribute"); } public void testFakeTest() { //this is being deprecated, tests no longer really needed. } // public void testTooManyNestedJavacElements() { // expectSpecificBuildException("testTooManyNestedJavacElements" // , "TooManyNestedJavacElements" // , "compilewithwalls task only supports one nested javac element"); // } // // public void testNoWallElement() { // expectSpecificBuildException("testNoWallElement" // , "NoWallElement" // , "There must be a nested walls element"); // } // // public void testNoJavacElement() { // expectSpecificBuildException("testNoJavacElement" // , "NoJavacElement" // , "There must be a nested javac element"); // } // // public void testMoreThanOneSrcDirInJavac() { // executeTarget("testMoreThanOneSrcDirInJavac"); // } // // public void testNoSrcDirInJavac() { // expectSpecificBuildException("testNoSrcDirInJavac" // , "NoSrcDirInJavac" // , "Javac inside compilewithwalls must have a srcdir specified"); // } // // public void testIntermediaryDirAndDestDirSame() { // expectSpecificBuildException("testIntermediaryDirAndDestDirSame" // , "IntermediaryDirAndDestDirSame" // , "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"); // } // // public void testIntermediaryDirInsideDestDir() { // expectSpecificBuildException("testIntermediaryDirInsideDestDir" // , "IntermediaryDirInsideDestDir" // , "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"); // } // // public void testPackageDoesntEndWithStar() { // expectSpecificBuildException("testPackageDoesntEndWithStar" // , "PackageDoesntEndWithStar" // , "The package='biz.xsoftware' must end with " // + ".* or .** such as biz.xsoftware.* or " // + "biz.xsoftware.**" ); // } // // public void testPackageDoesntHaveSlash() { // expectSpecificBuildException("testPackageDoesntHaveSlash" // , "PackageDoesntHaveSlash" // ,"A package name cannot contain '\\' or '/' like package=" // + "biz/xsoftware.*\nIt must look like biz.xsoftware.* for example"); // } // // public void testDependsOnNonExistPackage() { // expectSpecificBuildException("testDependsOnNonExistPackage" // , "DependsOnNonExistPackage" // , "package name=modA did not have modB" // + " listed before it and cannot compile without it"); // } // // public void testDependsOnPackageAfter() { // expectSpecificBuildException("testDependsOnPackageAfter" // , "DependsOnPackageAfter" // , "package name=modA did not have modB" // + " listed before it and cannot compile without it"); // } // // public void testPackageABreakingWhenAIsCompiledFirst() { // expectSpecificBuildException("testPackageABreakingWhenAIsCompiledFirst" // , "PackageABreakingWhenAIsCompiledFirst" // , "Compile failed; see the compiler error output for details."); // } // // // /** // * This test case tests when modB depends on modA but it was // * not specified in the walls so modA is not in modB's path. // * The build should then fail until they change the build.xml // * so modB depends on modA in the walls element. // */ // public void testPackageBBreakingWhenAIsCompiledFirst() { // // expectSpecificBuildException("testPackageBBreakingWhenAIsCompiledFirst" // , "PackageBBreakingWhenAIsCompiledFirst" // , "Compile failed; see the compiler error output for details."); // // //modA should have been compiled successfully, it is only modB that // //fails. It is very important we make sure A got compiled otherwise // //we are not testing the correct behavior and the test would be wrong. // ensureClassFileExists("testB"+c+"mod"+c+"modA"+c+"ModuleA.class", true); // ensureClassFileExists("testB"+c+"mod"+c+"modB"+c+"ModuleB.class", false); // } // // public void testCompileOfAllUsingDepends() { // ensureClassFileExists("testC"+c+"mod"+c+"Module.class", false); // //make sure we are testing the correct thing and Module.java exists! // ensureJavaFileExists("testC"+c+"mod"+c+"Module.java", true); // // executeTarget("testCompileOfAllUsingDepends"); // // //must test class files were actually created afterwards. // //The build might pass with no class files if the task is // //messed up. // ensureClassFileExists("testC"+c+"mod"+c+"Module.class", true); // // } ////--------------------------------------------------------- //// //// The following tests are all just repeats of some of the above tests //// except the below tests use External walls file and the above tests //// don't. //// ////--------------------------------------------------------- // // public void testDependsOnPackageAfterExternalWalls() { // expectSpecificBuildException("testDependsOnPackageAfterExternalWalls" // , "DependsOnPackageAfterExternalWalls" // , "package name=modA did not have modB" // + " listed before it and cannot compile without it"); // } // // /** // * This test case tests when modB depends on modA but it was // * not specified in the walls so modA is not in modB's path. // * The build should then fail until they change the build.xml // * so modB depends on modA in the walls element. // */ // public void testPackageBBreakingWhenAIsCompiledFirstExternalWalls() { // ensureClassFileExists("testB"+c+"mod"+c+"modA"+c+"ModuleA.class", false); // ensureJavaFileExists("testB"+c+"mod"+c+"modB"+c+"ModuleB.java", true); // // expectSpecificBuildException("testPackageBBreakingWhenAIsCompiledFirst" // , "PackageBBreakingWhenAIsCompiledFirst" // , "Compile failed; see the compiler error output for details."); // // //modA should have been compiled successfully, it is only modB that // //fails. It is very important we make sure A got compiled otherwise // //we are not testing the correct behavior and the test would be wrong. // ensureClassFileExists("testB"+c+"mod"+c+"modA"+c+"ModuleA.class", true); // ensureClassFileExists("testB"+c+"mod"+c+"modB"+c+"ModuleB.class", false); // } // // public void testCompileOfAllUsingDependsExternalWalls() { // ensureClassFileExists("testC"+c+"mod"+c+"Module.class", false); // ensureJavaFileExists("testC"+c+"mod"+c+"Module.java", true); // executeTarget("testCompileOfAllUsingDependsExternalWalls"); // //must test class files were actually created afterwards. // //The build might pass with no class files if the task is // //messed up. // ensureClassFileExists("testC"+c+"mod"+c+"Module.class", true); // } private void ensureJavaFileExists(String file, boolean shouldExist) { //must test that it is testing the correct directory. //It wasn't before. String javaFile = baseDir+file; File f1 = new File(javaFile); if(shouldExist) assertTrue("The java file="+f1.getAbsolutePath()+" didn't exist, we can't run this test. It will pass with false results", f1.exists()); else assertTrue("The java file="+f1.getAbsolutePath()+" exists and shouldn't, we can't run this test. It will pass with false results", !f1.exists()); } private void ensureClassFileExists(String file, boolean shouldExist) { String classFile = baseDir +"compilewithwalls"+File.separator +"classes"+File.separator +file; File f1 = new File(classFile); if(shouldExist) assertTrue("The class file="+f1.getAbsolutePath()+" didn't get created, No build exception\nwas thrown, but the build failed because a class\nfile should have been created", f1.exists()); else assertTrue("The class file="+f1.getAbsolutePath()+" exists and shouldn't\nTest may be inaccurate if this file already exists...correct the test", !f1.exists()); } public static void main(String[] args) { TestSuite suite = new TestSuite(CompileWithWallsTest.class); TestRunner.run(suite); } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/process/0000755000175000017500000000000011257224415023032 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/process/LimitTest.java0000644000175000017500000000214611257223237025617 0ustar mkochmkoch/* * 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 net.sf.antcontrib.BuildFileTestBase; public class LimitTest extends BuildFileTestBase { public LimitTest(String name) { super(name); } public void setUp() { configureProject("test/resources/logic/limittest.xml"); } public void test1() { expectLogNotContaining("test1", "_failed_"); } public void test2() { expectLogContaining("test2", "_passed_"); } } ant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/antserver/0000755000175000017500000000000011257224415023365 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/src/net/sf/antcontrib/antserver/AntServerTest.java0000644000175000017500000000574211257223237027012 0ustar mkochmkoch/* * 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 net.sf.antcontrib.BuildFileTestBase; /**************************************************************************** * Place class description here. * * @author inger * @author * * @since * ****************************************************************************/ public class AntServerTest extends BuildFileTestBase { public AntServerTest(String name) { super(name); } public void setUp() { configureProject("test/resources/antserver/antservertest.xml"); } public void tearDown() { executeTarget("cleanup"); } public void test1() { String expected[] = new String[] { "Test1 Successfully Called", "[test1_remote]" }; expectLogContaining("test1", expected); } public void test2() { String expected[] = new String[] { "Test2 Successfully Called", "[test2_remote]" }; expectLogContaining("test2", expected); } public void test3() { String expected[] = new String[] { "Test3 Successfully Called", "[test3_remote]" }; expectLogContaining("test3", expected); } public void test4() { String expected[] = new String[] { "Test4 Successfully Called", "[test4_remote]" }; expectLogContaining("test4", expected); } public void test5() { this.executeTarget("test5"); } /** * Assert that the given message has been logged with a priority * >= INFO when running the given target. */ protected void expectLogContaining(String target, String logs[]) { executeTarget(target); String realLog = getLog(); int cnt = 0; StringBuffer sb = new StringBuffer(); for (int i = 0; i < logs.length; i++) { if (realLog.indexOf(logs[i]) >= 0) cnt++; if (i != 0) sb.append(" and "); sb.append("\"").append(logs[i]).append("\""); } assertTrue("expecting log to contain " + sb.toString() + " log was \"" + realLog + "\"", cnt == logs.length); } } ant-contrib-1.0~b3+svn177/test/src/org/0000755000175000017500000000000011257224415016602 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/src/org/apache/0000755000175000017500000000000011257224415020023 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/src/org/apache/tools/0000755000175000017500000000000011257224415021163 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/src/org/apache/tools/ant/0000755000175000017500000000000011257224415021745 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/src/org/apache/tools/ant/BuildFileTest.java0000644000175000017500000003526211257223237025320 0ustar mkochmkoch/* * Copyright 2001-2004 The Apache Software Foundation * * 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 org.apache.tools.ant; import junit.framework.TestCase; import org.apache.tools.ant.Project; import java.io.File; import java.io.PrintStream; import java.net.URL; /** * A BuildFileTest is a TestCase which executes targets from an Ant buildfile * for testing. * * This class provides a number of utility methods for particular build file * tests which extend this class. * */ public abstract class BuildFileTest extends TestCase { protected Project project; private StringBuffer logBuffer; private StringBuffer fullLogBuffer; private StringBuffer outBuffer; private StringBuffer errBuffer; private BuildException buildException; /** * Constructor for the BuildFileTest object * *@param name string to pass up to TestCase constructor */ public BuildFileTest(String name) { super(name); } /** * run a target, expect for any build exception * *@param target target to run *@param cause information string to reader of report */ protected void expectBuildException(String target, String cause) { expectSpecificBuildException(target, cause, null); } /** * Assert that only the given message has been logged with a * priority >= INFO when running the given target. */ protected void expectLog(String target, String log) { executeTarget(target); String realLog = getLog(); assertEquals(log, realLog); } /** * Assert that the given substring is in the log messages */ protected void assertLogContaining(String substring) { String realLog = getLog(); assertTrue("expecting log to contain \"" + substring + "\" log was \"" + realLog + "\"", realLog.indexOf(substring) >= 0); } /** * Assert that the given message has been logged with a priority * >= INFO when running the given target. */ protected void expectLogContaining(String target, String log) { executeTarget(target); assertLogContaining(log); } /** * Gets the log the BuildFileTest object. * only valid if configureProject() has * been called. * @pre logBuffer!=null * @return The log value */ protected String getLog() { return logBuffer.toString(); } /** * Assert that the given message has been logged with a priority * >= DEBUG when running the given target. */ protected void expectDebuglog(String target, String log) { executeTarget(target); String realLog = getFullLog(); assertEquals(log, realLog); } /** * Gets the log the BuildFileTest object. * only valid if configureProject() has * been called. * @pre fullLogBuffer!=null * @return The log value */ protected String getFullLog() { return fullLogBuffer.toString(); } /** * execute the target, verify output matches expectations * *@param target target to execute *@param output output to look for */ protected void expectOutput(String target, String output) { executeTarget(target); String realOutput = getOutput(); assertEquals(output, realOutput.trim()); } /** * execute the target, verify output matches expectations * and that we got the named error at the end *@param target target to execute *@param output output to look for *@param error Description of Parameter */ protected void expectOutputAndError(String target, String output, String error) { executeTarget(target); String realOutput = getOutput(); assertEquals(output, realOutput); String realError = getError(); assertEquals(error, realError); } protected String getOutput() { return cleanBuffer(outBuffer); } protected String getError() { return cleanBuffer(errBuffer); } protected BuildException getBuildException() { return buildException; } private String cleanBuffer(StringBuffer buffer) { StringBuffer cleanedBuffer = new StringBuffer(); boolean cr = false; for (int i = 0; i < buffer.length(); i++) { char ch = buffer.charAt(i); if (ch == '\r') { cr = true; continue; } if (!cr) { cleanedBuffer.append(ch); } else { cleanedBuffer.append(ch); } } return cleanedBuffer.toString(); } /** * set up to run the named project * * @param filename name of project file to run */ protected void configureProject(String filename) throws BuildException { configureProject(filename, Project.MSG_DEBUG); } /** * set up to run the named project * * @param filename name of project file to run */ protected void configureProject(String filename, int logLevel) throws BuildException { logBuffer = new StringBuffer(); fullLogBuffer = new StringBuffer(); project = new Project(); project.init(); project.setUserProperty( "ant.file" , new File(filename).getAbsolutePath() ); project.addBuildListener(new AntTestListener(logLevel)); ProjectHelper.configureProject(project, new File(filename)); } /** * execute a target we have set up * @pre configureProject has been called * @param targetName target to run */ protected void executeTarget(String targetName) { PrintStream sysOut = System.out; PrintStream sysErr = System.err; try { sysOut.flush(); sysErr.flush(); outBuffer = new StringBuffer(); PrintStream out = new PrintStream(new AntOutputStream(outBuffer)); System.setOut(out); errBuffer = new StringBuffer(); PrintStream err = new PrintStream(new AntOutputStream(errBuffer)); System.setErr(err); logBuffer = new StringBuffer(); fullLogBuffer = new StringBuffer(); buildException = null; project.executeTarget(targetName); } finally { System.setOut(sysOut); System.setErr(sysErr); } } /** * Get the project which has been configured for a test. * * @return the Project instance for this test. */ protected Project getProject() { return project; } /** * get the directory of the project * @return the base dir of the project */ protected File getProjectDir() { return project.getBaseDir(); } /** * run a target, wait for a build exception * *@param target target to run *@param cause information string to reader of report *@param msg the message value of the build exception we are waiting for set to null for any build exception to be valid */ protected void expectSpecificBuildException(String target, String cause, String msg) { try { executeTarget(target); } catch (org.apache.tools.ant.BuildException ex) { buildException = ex; if ((null != msg) && (!ex.getMessage().equals(msg))) { fail("Should throw BuildException because '" + cause + "' with message '" + msg + "' (actual message '" + ex.getMessage() + "' instead)"); } return; } fail("Should throw BuildException because: " + cause); } /** * run a target, expect an exception string * containing the substring we look for (case sensitive match) * *@param target target to run *@param cause information string to reader of report *@param contains substring of the build exception to look for */ protected void expectBuildExceptionContaining(String target, String cause, String contains) { try { executeTarget(target); } catch (org.apache.tools.ant.BuildException ex) { buildException = ex; if ((null != contains) && (ex.getMessage().indexOf(contains) == -1)) { fail("Should throw BuildException because '" + cause + "' with message containing '" + contains + "' (actual message '" + ex.getMessage() + "' instead)"); } return; } fail("Should throw BuildException because: " + cause); } /** * call a target, verify property is as expected * * @param target build file target * @param property property name * @param value expected value */ protected void expectPropertySet(String target, String property, String value) { executeTarget(target); assertPropertyEquals(property, value); } /** * assert that a property equals a value; comparison is case sensitive. * @param property property name * @param value expected value */ protected void assertPropertyEquals(String property, String value) { String result = project.getProperty(property); assertEquals("property " + property,value,result); } /** * assert that a property equals "true" * @param property property name */ protected void assertPropertySet(String property) { assertPropertyEquals(property, "true"); } /** * assert that a property is null * @param property property name */ protected void assertPropertyUnset(String property) { assertPropertyEquals(property, null); } /** * call a target, verify named property is "true". * * @param target build file target * @param property property name */ protected void expectPropertySet(String target, String property) { expectPropertySet(target, property, "true"); } /** * call a target, verify property is null * @param target build file target * @param property property name */ protected void expectPropertyUnset(String target, String property) { expectPropertySet(target, property, null); } /** * Retrieve a resource from the caller classloader to avoid * assuming a vm working directory. The resource path must be * relative to the package name or absolute from the root path. * @param resource the resource to retrieve its url. * @throws AssertionFailureException if resource is not found. */ protected URL getResource(String resource){ URL url = getClass().getResource(resource); assertNotNull("Could not find resource :" + resource, url); return url; } /** * an output stream which saves stuff to our buffer. */ private static class AntOutputStream extends java.io.OutputStream { private StringBuffer buffer; public AntOutputStream( StringBuffer buffer ) { this.buffer = buffer; } public void write(int b) { buffer.append((char)b); } } /** * our own personal build listener */ private class AntTestListener implements BuildListener { private int logLevel; /** * Constructs a test listener which will ignore log events * above the given level */ public AntTestListener(int logLevel) { this.logLevel = logLevel; } /** * Fired before any targets are started. */ public void buildStarted(BuildEvent event) { } /** * Fired after the last target has finished. This event * will still be thrown if an error occured during the build. * * @see BuildEvent#getException() */ public void buildFinished(BuildEvent event) { } /** * Fired when a target is started. * * @see BuildEvent#getTarget() */ public void targetStarted(BuildEvent event) { //System.out.println("targetStarted " + event.getTarget().getName()); } /** * Fired when a target has finished. This event will * still be thrown if an error occured during the build. * * @see BuildEvent#getException() */ public void targetFinished(BuildEvent event) { //System.out.println("targetFinished " + event.getTarget().getName()); } /** * Fired when a task is started. * * @see BuildEvent#getTask() */ public void taskStarted(BuildEvent event) { //System.out.println("taskStarted " + event.getTask().getTaskName()); } /** * Fired when a task has finished. This event will still * be throw if an error occured during the build. * * @see BuildEvent#getException() */ public void taskFinished(BuildEvent event) { //System.out.println("taskFinished " + event.getTask().getTaskName()); } /** * Fired whenever a message is logged. * * @see BuildEvent#getMessage() * @see BuildEvent#getPriority() */ public void messageLogged(BuildEvent event) { if (event.getPriority() > logLevel) { // ignore event return; } if (event.getPriority() == Project.MSG_INFO || event.getPriority() == Project.MSG_WARN || event.getPriority() == Project.MSG_ERR) { logBuffer.append(event.getMessage()); } fullLogBuffer.append(event.getMessage()); } } } ant-contrib-1.0~b3+svn177/test/resources/0000755000175000017500000000000011257224415017236 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/logic/0000755000175000017500000000000011257224415020333 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/logic/relentless.xml0000644000175000017500000000270211257223240023231 0ustar mkochmkoch Don't call this file directly. Called with param: ${param} ant-contrib-1.0~b3+svn177/test/resources/logic/trycatch.xml0000644000175000017500000000410411257223240022670 0ustar mkochmkoch Don't call this file directly. Tada! In <catch>. In <finally>. Tada! In <catch>. In <catch2>. Tada! In <finally>. In <finally2>. Tada! Tada! In <catch>. In <finally>. In <catch>. In <finally>. Tada! In <catch>. In <finally>. ant-contrib-1.0~b3+svn177/test/resources/logic/timestampselector.xml0000644000175000017500000000426011257223240024616 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/logic/foreach.xml0000644000175000017500000000533011257223240022460 0ustar mkochmkoch Don't call this file directly. Called with param: ${param} Called with param: ${param2} ant-contrib-1.0~b3+svn177/test/resources/logic/asserttest.xml0000644000175000017500000000357511257223240023263 0ustar mkochmkoch test build file for the Assert task ant-contrib-1.0~b3+svn177/test/resources/logic/outofdate.xml0000644000175000017500000001027311257223240023045 0ustar mkochmkoch Don't call this file directly. Simple seq not triggered delete failed delete too much delete failed delete all failed Empty sources seq not triggered ant-contrib-1.0~b3+svn177/test/resources/logic/limittest.xml0000644000175000017500000000332311257223240023067 0ustar mkochmkoch test build file for the Limit task _failed_ _passed_ ant-contrib-1.0~b3+svn177/test/resources/logic/for.xml0000644000175000017500000000100411257223240021631 0ustar mkochmkoch i is @{i} i is @{i} ant-contrib-1.0~b3+svn177/test/resources/logic/switch.xml0000644000175000017500000000357411257223240022362 0ustar mkochmkoch Don't call this file directly. In case In default ${inner} In case ${inner} In default In case In default In case In default ant-contrib-1.0~b3+svn177/test/resources/logic/throw.xml0000644000175000017500000000056611257223240022222 0ustar mkochmkoch Don't call this file directly. ant-contrib-1.0~b3+svn177/test/resources/logic/if.xml0000644000175000017500000000555211257223240021455 0ustar mkochmkoch Don't call this file directly. Foo Foo In then ${inner} In else In then In else Foo Foo In then In elseif In else-branch In then In elseif In else-branch ant-contrib-1.0~b3+svn177/test/resources/logic/antcallbacktest.xml0000644000175000017500000000316011257223240024207 0ustar mkochmkoch test build file for the AntCallBack task ant-contrib-1.0~b3+svn177/test/resources/antclipse/0000755000175000017500000000000011257224415021220 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/antclipse/antclipsetest.xml0000644000175000017500000000370411257223237024631 0ustar mkochmkoch The newly created classpath is ${cpcontent} ant-contrib-1.0~b3+svn177/test/resources/antclipse/.classpath0000644000175000017500000000070411257223237023205 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/0000755000175000017500000000000011257224415020507 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/verifydesign.xml0000644000175000017500000004022111257223240023721 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/web.xml0000644000175000017500000000000011257223240021767 0ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/designfiles/0000755000175000017500000000000011257224415023003 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/designfiles/staticfinaldepend.xml0000644000175000017500000000017111257223240027200 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/recursion.xml0000644000175000017500000000024411257223240025531 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/paramdepend.xml0000644000175000017500000000016311257223240026000 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/newdepend.xml0000644000175000017500000000016111257223240025467 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/signatureexceptiondepend.xml0000644000175000017500000000020011257223240030610 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/arraydepend.xml0000644000175000017500000000016311257223240026016 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/castdepend.xml0000644000175000017500000000016211257223240025631 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/localvardepend.xml0000644000175000017500000000033311257223240026502 0ustar mkochmkoch factory ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/instanceofdepend.xml0000644000175000017500000000017011257223240027027 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/arraydepend2.xml0000644000175000017500000000016411257223240026101 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/recursion2.xml0000644000175000017500000000025211257223240025612 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/fieldrefdepend.xml0000644000175000017500000000016611257223240026463 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/fielddepend.xml0000644000175000017500000000016311257223240025763 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/innerclassdepend.xml0000644000175000017500000000017011257223240027037 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/superdepend.xml0000644000175000017500000000016311257223240026036 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/newdepend2.xml0000644000175000017500000000016211257223240025552 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/nojar.xml0000644000175000017500000000016311257223240024631 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/staticfield2depend.xml0000644000175000017500000000017211257223240027255 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/localvarrefdepend.xml0000644000175000017500000000017111257223240027177 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/declarejavautilfail.xml0000644000175000017500000000035711257223240027520 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/interfacedepend.xml0000644000175000017500000000016711257223240026644 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/pathelementpath.xml0000644000175000017500000000024711257223240026706 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/arraydepend3.xml0000644000175000017500000000016411257223240026102 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/staticdepend.xml0000644000175000017500000000016411257223240026170 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/staticfielddepend.xml0000644000175000017500000000017111257223240027172 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/missingattribute.xml0000644000175000017500000000014611257223240027116 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/badxml.xml0000644000175000017500000000016211257223240024766 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/recursion3.xml0000644000175000017500000000013711257223240025615 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/passlocaldepend.xml0000644000175000017500000000016711257223240026665 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/warsuccess.xml0000644000175000017500000000020211257223240025674 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/declarejavautil.xml0000644000175000017500000000016711257223240026663 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/nodebugoption.xml0000644000175000017500000000016511257223240026376 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/putstatic.xml0000644000175000017500000000016111257223240025536 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/returnvaldepend.xml0000644000175000017500000000016711257223240026726 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/catchdepend.xml0000644000175000017500000000016311257223240025762 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/warfailure.xml0000644000175000017500000000016211257223240025660 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/declarejavax.xml0000644000175000017500000000016411257223240026152 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/declarejavaxpass.xml0000644000175000017500000000027311257223240027042 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/designfiles/multipleerrors.xml0000644000175000017500000000024711257223240026613 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/design/src/0000755000175000017500000000000011257224415021276 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/0000755000175000017500000000000011257224415022055 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/putstatic/0000755000175000017500000000000011257224415024075 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/putstatic/ClassDependsOnNothing.java0000644000175000017500000000152111257223240031126 0ustar mkochmkoch/* * 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 13, 2005 */ package mod.putstatic; /** * * @author dhiller */ public class ClassDependsOnNothing { private static String s; public static void setJarLocator(String l) { s = l; } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/localvarrefdepend/0000755000175000017500000000000011257224415025535 5ustar mkochmkoch././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootant-contrib-1.0~b3+svn177/test/resources/design/src/mod/localvarrefdepend/ClassDependsOnLocalVariableReference.javaant-contrib-1.0~b3+svn177/test/resources/design/src/mod/localvarrefdepend/ClassDependsOnLocalVariabl0000644000175000017500000000156511257223240032603 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.localvarrefdepend; import mod.dummy.DummyInterface; /** * * @author dhiller */ public class ClassDependsOnLocalVariableReference { public void doNothing() { Class c = DummyInterface.class; } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/paramdepend/0000755000175000017500000000000011257224415024335 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/paramdepend/ClassDependsOnParameter.java0000644000175000017500000000153411257223237031712 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.paramdepend; import mod.dummy.DummyClass; /** * * @author dhiller */ public class ClassDependsOnParameter { public void setSomething(String dummy, DummyClass c) { } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/dummy/0000755000175000017500000000000011257224415023210 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/dummy/DummyException.java0000644000175000017500000000140311257223240027016 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.dummy; /** * * @author dhiller */ public class DummyException extends Exception { } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/dummy/DummyInterface.java0000644000175000017500000000136511257223240026767 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.dummy; /** * * @author dhiller */ public interface DummyInterface { } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/dummy/DummyRuntimeException.java0000644000175000017500000000142111257223240030362 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.dummy; /** * * @author dhiller */ public class DummyRuntimeException extends RuntimeException { } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/dummy/DummyClass.java0000644000175000017500000000160611257223240026132 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.dummy; /** * * @author dhiller */ public class DummyClass { public static final String CONSTANT = "asdf"; public static String staticField = "xxxx"; public static String returnSomething() { return "Xxx"; } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/innerclassdepend/0000755000175000017500000000000011257224415025376 5ustar mkochmkoch././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootant-contrib-1.0~b3+svn177/test/resources/design/src/mod/innerclassdepend/InnerClassDependsOnSuper.javaant-contrib-1.0~b3+svn177/test/resources/design/src/mod/innerclassdepend/InnerClassDependsOnSuper.ja0000644000175000017500000000152411257223240032567 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.innerclassdepend; import mod.dummy.DummyClass; /** * * @author dhiller */ public class InnerClassDependsOnSuper { private class Inner extends DummyClass { } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/nodebugoption/0000755000175000017500000000000011257224415024731 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/nodebugoption/ClassDependsOnLocalVar.java0000644000175000017500000000177111257223240032066 0ustar mkochmkoch/* * 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 13, 2005 */ package mod.nodebugoption; import mod.dummy.DummyClass; /** * * @author dhiller */ public class ClassDependsOnLocalVar { public void doSomething() { DummyClass c = null; //without debug option enabled, the type DummyClass is lost so we //must fail with the error saying class wasn't compiled with -g option //enabled in javac. } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/staticdepend/0000755000175000017500000000000011257224415024524 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/staticdepend/ClassDependsOnStatic.java0000644000175000017500000000154611257223240031405 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.staticdepend; import mod.dummy.DummyClass; /** * * @author dhiller */ public class ClassDependsOnStatic { public String getSomething() { return DummyClass.returnSomething(); } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/castdepend/0000755000175000017500000000000011257224415024167 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/castdepend/ClassDependsOnCast.java0000644000175000017500000000155111257223240030507 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.castdepend; import mod.dummy.DummyInterface; /** * * @author dhiller */ public class ClassDependsOnCast { public void getSomething(Object obj) { Object o = (DummyInterface)obj; } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/warsuccess/0000755000175000017500000000000011257224415024237 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/warsuccess/ClassDependsOnSuperMod2.java0000644000175000017500000000162111257223237031511 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.warsuccess; import mod.dummy.DummyClass; /** * This class depends on a superclass in another package creating a dependency * between packages. * @author dhiller */ public class ClassDependsOnSuperMod2 extends DummyClass { } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/temp/0000755000175000017500000000000011257224415023022 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/temp/Factory.java0000644000175000017500000000151211257223237025274 0ustar mkochmkoch/* * 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 13, 2005 */ package mod.temp; import mod.dummy.DummyClass; /** * * @author dhiller */ public class Factory { public static DummyClass create() { return new DummyClass(); } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/recursion2/0000755000175000017500000000000011257224415024150 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/recursion2/dependency/0000755000175000017500000000000011257224415026266 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/recursion2/dependency/Dependency.java0000644000175000017500000000137511257223237031216 0ustar mkochmkoch/* * 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 13, 2005 */ package mod.recursion2.dependency; /** * * @author dhiller */ public class Dependency { } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/recursion2/rec/0000755000175000017500000000000011257224415024721 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/recursion2/rec/client/0000755000175000017500000000000011257224415026177 5ustar mkochmkoch././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootant-contrib-1.0~b3+svn177/test/resources/design/src/mod/recursion2/rec/client/SubpackageClassDependsOnPackage.javaant-contrib-1.0~b3+svn177/test/resources/design/src/mod/recursion2/rec/client/SubpackageClassDepends0000644000175000017500000000156311257223237032466 0ustar mkochmkoch/* * 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 16, 2005 */ package mod.recursion2.rec.client; import mod.recursion2.dependency.Dependency; /** * * @author dhiller */ public class SubpackageClassDependsOnPackage { public Dependency doNothing() { return null; } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/superdepend/0000755000175000017500000000000011257224415024373 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/superdepend/ClassDependsOnSuperMod2.java0000644000175000017500000000162211257223240031640 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.superdepend; import mod.dummy.DummyClass; /** * This class depends on a superclass in another package creating a dependency * between packages. * @author dhiller */ public class ClassDependsOnSuperMod2 extends DummyClass { } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/declarejavax/0000755000175000017500000000000011257224415024506 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/declarejavax/ClassDependsOnJavax.java0000644000175000017500000000146511257223237031217 0ustar mkochmkoch/* * 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 19, 2005 */ package mod.declarejavax; import javax.swing.JButton; /** * * @author dhiller */ public class ClassDependsOnJavax { public JButton b = null; } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/arraydepend3/0000755000175000017500000000000011257224415024436 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/arraydepend3/ClassDependsOnArray.java0000644000175000017500000000155311257223237031152 0ustar mkochmkoch/* * 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 mod.arraydepend3; import mod.dummy.DummyClass; /** * * @author dhiller */ public class ClassDependsOnArray { public void testArray() throws Exception { Class c = DummyClass[].class; } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/passlocaldepend/0000755000175000017500000000000011257224415025216 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/passlocaldepend/FakeClass.java0000644000175000017500000000136611257223240027716 0ustar mkochmkoch/* * 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 13, 2005 */ package mod.passlocaldepend; /** * * @author dhiller */ public class FakeClass { } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootant-contrib-1.0~b3+svn177/test/resources/design/src/mod/passlocaldepend/ClassDependsOnClassInSamePackage.javaant-contrib-1.0~b3+svn177/test/resources/design/src/mod/passlocaldepend/ClassDependsOnClassInSamePac0000644000175000017500000000147311257223240032515 0ustar mkochmkoch/* * 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 13, 2005 */ package mod.passlocaldepend; /** * * @author dhiller */ public class ClassDependsOnClassInSamePackage { public void doSomething(FakeClass c) { } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/staticfinaldepend/0000755000175000017500000000000011257224415025536 5ustar mkochmkoch././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootant-contrib-1.0~b3+svn177/test/resources/design/src/mod/staticfinaldepend/ClassDependsOnConstant.javaant-contrib-1.0~b3+svn177/test/resources/design/src/mod/staticfinaldepend/ClassDependsOnConstant.jav0000644000175000017500000000154511257223240032617 0ustar mkochmkoch/* * 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 mod.staticfinaldepend; import mod.dummy.DummyClass; /** * * @author dhiller */ public class ClassDependsOnConstant { public void doNothing() { String s = ""+DummyClass.CONSTANT; } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/signatureexceptiondepend/0000755000175000017500000000000011257224415027155 5ustar mkochmkoch././@LongLink0000000000000000000000000000017700000000000011572 Lustar rootrootant-contrib-1.0~b3+svn177/test/resources/design/src/mod/signatureexceptiondepend/ClassDependsOnExceptionInMethodSignature.javaant-contrib-1.0~b3+svn177/test/resources/design/src/mod/signatureexceptiondepend/ClassDependsOnExcep0000644000175000017500000000160511257223240032727 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.signatureexceptiondepend; import mod.dummy.DummyException; /** * * @author dhiller */ public class ClassDependsOnExceptionInMethodSignature { public String doNothing() throws DummyException { return null; } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/warfailure/0000755000175000017500000000000011257224415024216 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/warfailure/ClassDependsOnSuperMod2.java0000644000175000017500000000162111257223240031462 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.warfailure; import mod.dummy.DummyClass; /** * This class depends on a superclass in another package creating a dependency * between packages. * @author dhiller */ public class ClassDependsOnSuperMod2 extends DummyClass { } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/arraydepend2/0000755000175000017500000000000011257224415024435 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/arraydepend2/ClassDependsOnArray.java0000644000175000017500000000151111257223237031143 0ustar mkochmkoch/* * 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 mod.arraydepend2; /** * * @author dhiller */ public class ClassDependsOnArray { public void testArray() throws Exception { Class c = String[].class; } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/fieldrefdepend/0000755000175000017500000000000011257224415025015 5ustar mkochmkoch././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootant-contrib-1.0~b3+svn177/test/resources/design/src/mod/fieldrefdepend/ClassDependsOnReferenceInFieldDeclaration.javaant-contrib-1.0~b3+svn177/test/resources/design/src/mod/fieldrefdepend/ClassDependsOnReferenceInFiel0000644000175000017500000000153211257223240032507 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.fieldrefdepend; import mod.dummy.DummyClass; /** * * @author dhiller */ public class ClassDependsOnReferenceInFieldDeclaration { private Class c = DummyClass.class; } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/newdepend/0000755000175000017500000000000011257224415024026 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/newdepend/ClassDependsOnNew.java0000644000175000017500000000151011257223240030200 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.newdepend; import mod.dummy.DummyClass; /** * * @author dhiller */ public class ClassDependsOnNew { public void doNothing() { new DummyClass(); } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/instanceofdepend/0000755000175000017500000000000011257224415025366 5ustar mkochmkoch././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootant-contrib-1.0~b3+svn177/test/resources/design/src/mod/instanceofdepend/ClassDependsOnInstanceOf.javaant-contrib-1.0~b3+svn177/test/resources/design/src/mod/instanceofdepend/ClassDependsOnInstanceOf.ja0000644000175000017500000000162011257223240032513 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.instanceofdepend; import mod.dummy.DummyInterface; /** * * @author dhiller */ public class ClassDependsOnInstanceOf { public void getSomething(Object o) { int x = 0; if(o instanceof DummyInterface) { x = 4; } } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/localvardepend/0000755000175000017500000000000011257224415025040 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/localvardepend/ClassDependsOnLocalVar.java0000644000175000017500000000155111257223237032177 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.localvardepend; import mod.dummy.DummyClass; /** * * @author dhiller */ public class ClassDependsOnLocalVar { public String doNothing() { DummyClass c = null; return ""+c; } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/recursion3/0000755000175000017500000000000011257224415024151 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/recursion3/client/0000755000175000017500000000000011257224415025427 5ustar mkochmkoch././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootant-contrib-1.0~b3+svn177/test/resources/design/src/mod/recursion3/client/SubpackageClassDependsOnSubpackage.javaant-contrib-1.0~b3+svn177/test/resources/design/src/mod/recursion3/client/SubpackageClassDependsOnSu0000644000175000017500000000156111257223237032521 0ustar mkochmkoch/* * 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 16, 2005 */ package mod.recursion3.client; import mod.recursion3.svc.DependencyClass; /** * * @author dhiller */ public class SubpackageClassDependsOnSubpackage { public void doSomething(DependencyClass c) { } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/recursion3/svc/0000755000175000017500000000000011257224415024744 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/recursion3/svc/DependencyClass.java0000644000175000017500000000137311257223237030660 0ustar mkochmkoch/* * 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 16, 2005 */ package mod.recursion3.svc; /** * * @author dhiller */ public class DependencyClass { } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/recursion/0000755000175000017500000000000011257224415024066 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/recursion/client/0000755000175000017500000000000011257224415025344 5ustar mkochmkoch././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootant-contrib-1.0~b3+svn177/test/resources/design/src/mod/recursion/client/ClassDependsOnSubPackage.javaant-contrib-1.0~b3+svn177/test/resources/design/src/mod/recursion/client/ClassDependsOnSubPackage.ja0000644000175000017500000000154211257223240032450 0ustar mkochmkoch/* * 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 13, 2005 */ package mod.recursion.client; import mod.recursion.rec.a.FakeClass; /** * * @author dhiller */ public class ClassDependsOnSubPackage { public FakeClass getSoemthing() { return null; } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/recursion/rec/0000755000175000017500000000000011257224415024637 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/recursion/rec/a/0000755000175000017500000000000011257224415025057 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/recursion/rec/a/FakeClass.java0000644000175000017500000000136611257223240027557 0ustar mkochmkoch/* * 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 13, 2005 */ package mod.recursion.rec.a; /** * * @author dhiller */ public class FakeClass { } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/returnvaldepend/0000755000175000017500000000000011257224415025257 5ustar mkochmkoch././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootant-contrib-1.0~b3+svn177/test/resources/design/src/mod/returnvaldepend/ClassDependsOnReturnValue.javaant-contrib-1.0~b3+svn177/test/resources/design/src/mod/returnvaldepend/ClassDependsOnReturnValue.ja0000644000175000017500000000154211257223240032632 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.returnvaldepend; import mod.dummy.DummyInterface; /** * * @author dhiller */ public class ClassDependsOnReturnValue { public DummyInterface getSomething() { return null; } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/staticfield2depend/0000755000175000017500000000000011257224415025612 5ustar mkochmkoch././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootant-contrib-1.0~b3+svn177/test/resources/design/src/mod/staticfield2depend/ClassDependsOnStaticField.javaant-contrib-1.0~b3+svn177/test/resources/design/src/mod/staticfield2depend/ClassDependsOnStaticField0000644000175000017500000000151611257223240032514 0ustar mkochmkoch/* * 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 mod.staticfield2depend; import mod.dummy.DummyClass; /** * * @author dhiller */ public class ClassDependsOnStaticField { public static DummyClass x = null; } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/arraydepend/0000755000175000017500000000000011257224415024353 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/arraydepend/ClassDependsOnArray.java0000644000175000017500000000153111257223240031055 0ustar mkochmkoch/* * 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 mod.arraydepend; import mod.dummy.DummyClass; /** * * @author dhiller */ public class ClassDependsOnArray { public void something() { Object[] o = new DummyClass[5]; } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/catchdepend/0000755000175000017500000000000011257224415024317 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/catchdepend/ClassDependsOnCatch.java0000644000175000017500000000162611257223240030772 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.catchdepend; import mod.dummy.DummyRuntimeException; /** * * @author dhiller */ public class ClassDependsOnCatch { public void doNothing() { try { int x = 0; int y = x+4; } catch(DummyRuntimeException e) { } } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/declarejavautil/0000755000175000017500000000000011257224415025214 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/declarejavautil/ClassDependsOnJavaUtil.java0000644000175000017500000000145611257223237032373 0ustar mkochmkoch/* * 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 19, 2005 */ package mod.declarejavautil; import java.util.List; /** * * @author dhiller */ public class ClassDependsOnJavaUtil { public List list; } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/staticfielddepend/0000755000175000017500000000000011257224415025530 5ustar mkochmkoch././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootant-contrib-1.0~b3+svn177/test/resources/design/src/mod/staticfielddepend/ClassDependsOnStaticField.javaant-contrib-1.0~b3+svn177/test/resources/design/src/mod/staticfielddepend/ClassDependsOnStaticField.0000644000175000017500000000155011257223240032506 0ustar mkochmkoch/* * 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 mod.staticfielddepend; import mod.dummy.DummyClass; /** * * @author dhiller */ public class ClassDependsOnStaticField { public void doNothing() { String s = DummyClass.staticField; } } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/fielddepend/0000755000175000017500000000000011257224415024320 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/fielddepend/ClassDependsOnField.java0000644000175000017500000000154711257223237031004 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.fielddepend; import mod.dummy.DummyClass; /** * This class depends on a field in another package. * * @author dhiller */ public class ClassDependsOnField { private DummyClass f; } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/newdepend2/0000755000175000017500000000000011257224415024110 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/design/src/mod/newdepend2/ClassDependsOnNewInField.java0000644000175000017500000000150311257223237031525 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.newdepend2; import mod.dummy.DummyClass; /** * * @author dhiller */ public class ClassDependsOnNewInField { public Object o = new DummyClass(); } ant-contrib-1.0~b3+svn177/test/resources/design/src/mod/interfacedepend/0000755000175000017500000000000011257224415025175 5ustar mkochmkoch././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootant-contrib-1.0~b3+svn177/test/resources/design/src/mod/interfacedepend/ClassDependsOnInterfaceMod2.javaant-contrib-1.0~b3+svn177/test/resources/design/src/mod/interfacedepend/ClassDependsOnInterfaceMod2.0000644000175000017500000000165111257223240032404 0ustar mkochmkoch/* * 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 29, 2004 */ package mod.interfacedepend; import mod.dummy.DummyInterface; /** * This class depends on an interface in another package creating a dependency * between packages. * * @author dhiller */ public class ClassDependsOnInterfaceMod2 implements DummyInterface { } ant-contrib-1.0~b3+svn177/test/resources/math/0000755000175000017500000000000011257224415020167 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/math/mathtest.xml0000644000175000017500000000122411257223240022534 0ustar mkochmkoch test build file for the Math task ${op1} ${op} ${op2} = ${result} ant-contrib-1.0~b3+svn177/test/resources/property/0000755000175000017500000000000011257224415021122 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/property/propertycopy.xml0000644000175000017500000000162311257223237024426 0ustar mkochmkoch Don't call this file directly. ant-contrib-1.0~b3+svn177/test/resources/property/variabletest.xml0000644000175000017500000000416011257223237024333 0ustar mkochmkoch test build file for the Variable task ant-contrib-1.0~b3+svn177/test/resources/property/propertyselector.xml0000644000175000017500000000200111257223237025263 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/property/pathtofileset.xml0000644000175000017500000000311311257223237024516 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/property/propertyselector.properties0000644000175000017500000000021511257223237026664 0ustar mkochmkoch#Module 1 Properties module.Module1.id=1 module.Module1.name=Module 1 #Module 2 Properties module.Module2.id=2 module.Module2.name=Module 2 ant-contrib-1.0~b3+svn177/test/resources/platform/0000755000175000017500000000000011257224415021062 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/platform/shellscript.xml0000644000175000017500000000533211257223237024144 0ustar mkochmkoch Don't call this file directly. echo a echo "hello world" echo "hello world" print "hello world" print STDOUT "hello world\n"; FOO bar bar bar FOO bar bar echo ${my.sh.property} echo hello world echo $0 echo hello world current=`pwd` echo "dir is $current" ant-contrib-1.0~b3+svn177/test/resources/platform/osfamily.xml0000644000175000017500000000072411257223237023433 0ustar mkochmkoch Don't call this file directly. ant-contrib-1.0~b3+svn177/test/resources/walls/0000755000175000017500000000000011257224415020360 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/walls/packageB-break.xml0000644000175000017500000000026011257223237023660 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/walls/compilewithwalls.xml0000644000175000017500000001740211257223237024476 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/walls/dependsafter.xml0000644000175000017500000000040111257223237023542 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/walls/testB/0000755000175000017500000000000011257224415021441 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/walls/testB/mod/0000755000175000017500000000000011257224415022220 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/walls/testB/mod/modA/0000755000175000017500000000000011257224415023100 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/walls/testB/mod/modA/TrialBModuleA.java0000644000175000017500000000006411257223237026370 0ustar mkochmkoch package mod.modA; public class TrialBModuleA { };ant-contrib-1.0~b3+svn177/test/resources/walls/testB/mod/modB/0000755000175000017500000000000011257224415023101 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/walls/testB/mod/modB/TrialBModuleB.java0000644000175000017500000000016311257223237026372 0ustar mkochmkoch package mod.modB; import mod.modA.TrialBModuleA; public class TrialBModuleB { private TrialBModuleA temp; };ant-contrib-1.0~b3+svn177/test/resources/walls/testC/0000755000175000017500000000000011257224415021442 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/walls/testC/mod/0000755000175000017500000000000011257224415022221 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/walls/testC/mod/TrialCModule.java0000644000175000017500000000025611257223237025414 0ustar mkochmkoch package mod; import mod.modA.TrialCModuleA; import mod.modB.TrialCModuleB; public class TrialCModule { private TrialCModuleA temp1; private TrialCModuleB temp2; };ant-contrib-1.0~b3+svn177/test/resources/walls/testC/mod/modA/0000755000175000017500000000000011257224415023101 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/walls/testC/mod/modA/TrialCModuleA.java0000644000175000017500000000006411257223237026372 0ustar mkochmkoch package mod.modA; public class TrialCModuleA { };ant-contrib-1.0~b3+svn177/test/resources/walls/testC/mod/modB/0000755000175000017500000000000011257224415023102 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/walls/testC/mod/modB/TrialCModuleB.java0000644000175000017500000000006411257223237026374 0ustar mkochmkoch package mod.modB; public class TrialCModuleB { };ant-contrib-1.0~b3+svn177/test/resources/walls/walls.xml0000644000175000017500000000032111257223237022221 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/walls/testA/0000755000175000017500000000000011257224415021440 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/walls/testA/mod/0000755000175000017500000000000011257224415022217 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/walls/testA/mod/modA/0000755000175000017500000000000011257224415023077 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/walls/testA/mod/modA/ModuleA.java0000644000175000017500000000014511257223237025271 0ustar mkochmkoch package mod.modA; import mod.modB.ModuleB; public class ModuleA { private ModuleB moduleB; };ant-contrib-1.0~b3+svn177/test/resources/walls/testA/mod/modB/0000755000175000017500000000000011257224415023100 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/walls/testA/mod/modB/ModuleB.java0000644000175000017500000000005511257223237025273 0ustar mkochmkoch package mod.modB; public class ModuleB { };ant-contrib-1.0~b3+svn177/test/resources/antserver/0000755000175000017500000000000011257224415021247 5ustar mkochmkochant-contrib-1.0~b3+svn177/test/resources/antserver/antservertest.xml0000644000175000017500000001063411257223237024707 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/test/resources/antserver/clientfile.txt0000644000175000017500000000004211257223237024123 0ustar mkochmkochThis is the file from the client. ant-contrib-1.0~b3+svn177/build.properties0000644000175000017500000000032111257223261017454 0ustar mkochmkochproject.name=ant-contrib project.version=dev jar.name=${project.name}.jar jar.name.versioned=${project.name}-${project.version}.jar ivy.deliver.revision=${project.version} jdk.source=1.4 jdk.target=1.4 ant-contrib-1.0~b3+svn177/ivysettings.xml0000644000175000017500000000104611257223261017356 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/docs/0000755000175000017500000000000011257224415015175 5ustar mkochmkochant-contrib-1.0~b3+svn177/docs/manual/0000755000175000017500000000000011257224415016452 5ustar mkochmkochant-contrib-1.0~b3+svn177/docs/manual/tasks/0000755000175000017500000000000011257224415017577 5ustar mkochmkochant-contrib-1.0~b3+svn177/docs/manual/tasks/antfetch_task.html0000644000175000017500000000773211257223261023312 0ustar mkochmkoch AntFetch

AntFetch

AntFetch is identical to the standard 'Ant' task, except that it allows properties from the new project to be set in the original project.

Some background may be in order: When the <ant> task is used, in actuality, a new Ant project is created, and depending on the inheritAll property, it is populated with properties from the original project. Then the target in this new project is executed. Any properties set in the new project remain with that project, they do not get "passed back" to the original project. So, for example, if the target in the new project sets a property named "image.directory", there is no reference to that property in the original. Here's an example of what I mean:

Suppose that the "fillImageDirectory" target sets a property named "image.directory" and I call the following:


    <ant dir="${image.project} target="fillImageDirectory"/>
    <echo>${image.directory}</echo>

The output of the echo task will be ${image.directory}, not whatever was set in the "fillImageDirectory" target.

The AntFetch task allows that image.directory property to be set in the original project. The attributes for AntFetch are identical to the 'Ant' task, with one additional, optional attibute. This attribute is named "return" and can be either a single property name or a comma separated list of property names.

Assuming that "fillImageDirectory" actually sets a property named "image.directory", the following example will print out the directory name:


    <antfetch dir="${image.project} target="fillImageDirectory" return="image.directory"/>
    <echo>${image.directory}</echo>

And this one will also print out the thumbnail directory:


    <antfetch dir="${image.project} target="fillImageDirectory" return="image.directory, thumbnail.directory"/>
    <echo>${image.directory}</echo>
    <echo>${thumbnail.directory}</echo>

The attributes for AntFetch are identical to the 'ant' task, with one additional, optional attibute. This attribute is named "return" and can be either a single property name or a comma separated list of property names.

Table 14.1. AntFetch Attributes

Attribute Description Default Required
return A comma separated list of property names. Whitespace is allowed, so either "a,b" or "a, b" are acceptable. None No

For other attribute and nested element information and more examples, see the documentation for the "ant" task in the Ant documentation.


Copyright © 2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/trycatch.html0000644000175000017500000000537411257223261022315 0ustar mkochmkoch Ant-contrib Tasks: Trycatch

Trycatch

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.

This mirrors Java's try/catch/finally.

The tasks inside of the required <try> element will be run. If one of them should throw a BuildException several things can happen:

  • If there is no <catch> block, the exception will be passed through to Ant.
  • If the property attribute has been set, a property of the given name will be set to the message of the exception.
  • If the reference attribute has been set, a reference of the given id will be created and point to the exception object.
  • If there is a <catch> block, the tasks nested into it will be run.

If a <finally> block is present, the task nested into it will be run, no matter whether the first tasks have thrown an exception or not.

Parameters

Attribute Description Required
property Name of a property that will receive the message of the exception that has been caught (if any) No.
reference Id of a reference that will point to the exception object that has been caught (if any) No

Example

<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>

results in

  [trycatch] Caught exception: Tada!
      [echo] In <catch>.
      [echo] In <finally>.
      [echo] As property: Tada!
      [echo] From reference: Tada!

Copyright © 2002-2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/switch.html0000644000175000017500000000433311257223261021767 0ustar mkochmkoch Ant-contrib Tasks: Switch

Switch

Task definition for the ANT task to switch on a particular value.

Parameters

Attribute Description Required
value The value to switch on. Yes.
caseinsensitive Should we do case insensitive comparisons? No, default is "false"

Parameters specified as nested elements

At least one <case> or <default> is required.

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.

Parameters

Attribute Description Required
value The value to match against the tasks value attribute. Yes.

default

The default case for when no match is found. Must not appear more than once per task.

Example

<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>

Copyright © 2002 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/forget.html0000644000175000017500000000334411257223261021755 0ustar mkochmkoch Ant-contrib Tasks: Forget

Forget

The Forget task will execute a set of tasks sequentially as a background thread. Once the thread is started, control is returned to the calling target. This is useful in being able to kick off a background server process, such as a webserver. This allows you to not have to use the parallel task to start server processes.

Parameters

Attribute Description Required
daemon Should the created thread be a daemon thread. That is, should the ANT program be allowed to exit if the thread is still running. No. Defaults to true.

Example

The following code
    
    <forget>
        <exec executeable="${env.CATALINA_HOME}/bin/catalina.bat}">
            <arg line="start -security" />
        </exec>
    </forget>

    <waitfor maxwait="1" maxwaitunit="minute"
                checkevery="100" checkeveryunit="millisecond">
        <http url="http://localhost:8080" />
    </waitfor>

    
    
Would start the Tomcat webserver as a background process, then waiting for the server to become available.

Copyright © 2002-2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/verifydesign.html0000644000175000017500000003457211257223261023174 0ustar mkochmkoch VerifyDesign Ant Task

VerifyDesign Ant Task

  • Creator: Dean Hiller (dean@xsoftware.biz)
  • Contributor: Matt Inger (thanks for some really awesome changes)
  • Contributor: Anthony Y Robins

Feedback on task and documentation are welcome!

Description

Describe your design dependencies in an xml file, and this task will enforce them so they are not violated

For example, if there are three packages in one source tree

  • biz.xsoftware.presentation
  • biz.xsoftware.business
  • biz.xsoftware.dataaccess
and naturally presentation should only depend on business package, and business should depend on dataaccess. If you define your design this way and it is violated the build will fail when the verifydesign ant task is called. For example, if I created a class in biz.xsoftware.presentation and that class depended on a class in biz.xsoftware.dataaccess, the build would fail. This ensures the design actually follows what is documented(to some degree at least). This is especially nice with automated builds

Getting Started

Download bcel jar from this link Bcel download as this ant task uses the jar built from the bcel project on jakarta. Choose a directory to put in place of the XXXXXX below and add the ant-contrib jar as well as the bcel jar to that directory. You should now be all set to use the verifydesign element in your build.xml file as well as any other ant-contrib tasks. If you want to use this with 5.0jdk, you must download the bcel from the head of cvs until something better than 5.1 is released. This version of ant-contrib will work with both 5.0jdk and 1.4 jdk. 1.3 and before is not tested.
    <taskdef resource="net/sf/antcontrib/antlib.xml">
        <classpath>
           <fileset dir="XXXXXX">
               <include name="**/*.jar"/>
           </fileset>
        </classpath>
    </taskdef>
Now, you can skip to the VerifyDesign Legacy Project Tutorial which guides you through how to use this task if you already have alot of existing code, or you can start with the VerifyDesign New Project Tutorial where you don't have much code or any at all.

Parameters

Attribute Description Required
design The file that specifies the design in xml format(Examples below) required
jar The jar file of who's design we want to validate required
circularDesign I strongly encourage you not to use this. This turns on allowing circular dependencies. There is always a way to get around circular dependencies, and I suggest you use it instead of introducing a circular dependency. If you think you have found one you can't work around, send me mail and maybe I can give you some ideas. optional(default=false)
deleteFiles Deletes jar/class files upon build failure to prevent usage. Use this option for new projects so the binaries are not used without the design being met. optional(default=false)
fillInBuildException Fills the BuildException with all the same errors reported in the logs. This is for products like cruisecontrol who only see standard ant task logs and would miss reporting these errors otherwise(ie. instead it just reports build failed with look at the design errors) optional(default=false)
needDeclarationsDefault false is saying that for this particular package, no other package needs to declare that they depend on this package. It is basically saying the needDeclarations attribute in the package element in the design file is whatever the value of this attribute is in the build.xml file if the design file does not override it. optional(default=true)
needDependsDefault false is saying that by default no package in the design file has to declare it's dependencies. It is basically saying the needDepends attribute in the package element in the design file is whatever the value of this attribute is in the build.xml file if the design file does not override it. optional(default=true)

Parameters specified as nested elements

No nested elements allowed

Design File

The design file is an xml based file specifying dependencies that are ok. Any dependencies not specified will not be allowed and will make sure the build fails. Examples of the contents of the design file can be found below.

design Root Element

The root element of the design file is 'design'. Here are design's allowed subelements.

Subelement Description Required
package subelement representing a package and it's dependencies One or more Required

package SubElement

Here are package elements allowed attributes and subelements

Attribute Description Required
name A smaller nickname for the package to reference in the depends subelement or attribute Required
package The package to compile such as biz.xsoftware.presentation Required
depends Contains one and only one 'name' of a package to depend on(taken from name attribute above). If you want to specify more, use the depends subelement Optional(Default=no dependencies)
subpackages Can be set to include or exclude. Basically allows classes in subpackages to be part of the package specified.(see examples below) Optional(default=exclude)
needdeclarations Can be set to true or false. True means if other packages depend on this package, a depends subelement or attribute must exist stating the dependency. False means other packages need not declare they depend on this package. This should be used sparingly for things like java.lang. By default "java" package and all subpackages are set to false. This can be overridden if you need however so you can make sure only certain packages depend on java.util or something if you really need that. (see examples below) Optional(default=true)
needdepends Can be set to true or false. True means if this package depends on other packages, those dependencies must be defined(unless those other packages have needdeclarations set to false). False means this package must list all the packages it depends on. This is typically for legacy code where you don't want to deal with what this package depends on right now. On a new project, I never use this. Optional(default=true)

Subelement Description Required
depends Contains one and only one 'name' of a package to depend on(taken from name attribute above) One or more Optional

depends SubElement

Contents contain the 'name' of a package found in the package element's name attribute

Examples

Ant's build.xml File

  <verifydesign jar="application.jar" design="design.xml"/>

That is simple enough. application.jar is the jar I am verifying the design of. design.xml contains the design I want the jar file to adhere to. There is no need to include third party jars(unless you want to verify their design which you shouldn't). The design file can still define what your stuff depends on in those third party libraries without requiring those libraries to be present. If it does not adhere to that design, the build fails. Examples of a design.xml can be found further below.

Another example equivalent to the above is below. verifydesign takes a path like structure(see ant documentation). I highly advise breaking the design on purpose and verifying that the build fails. This ensures you have the ant task set up correctly.

  <verifydesign design="design.xml">
     <path>
        <pathelement jar="application.jar"/>
     </path>
  </verifydesign>
One last example would be like so
  <verifydesign design="design.xml">
     <path>
        <fileset dir="${classesDir}">
            <include name="**/*.class"/>
        </fileset>
     </path>
  </verifydesign>
Now let's move on to define the contents of design.xml file.

design.xml File

These lines would be in dependencies.xml.....
  <design>
     <package name="alljavax" package="javax" subpackages="include" needdeclarations="false"/>
     <package name="util" package="biz.xsoftware.util" subpackages="include"/>
     <package name="dataaccess" package="biz.xsoftware.dataaccess"/>
     <package name="business" package="biz.xsoftware.business" depends="dataaccess"/>
     <package name="presentation" package="biz.xsoftware.presentation">
        <depends>business</depends>
        <depends>util</depends>
     </package>
  </design>

Notice in this example, if biz.xsoftware.dataaccess.XYZClass depended on biz.xsoftware.util.Util, the build would fail since that package dependency is not defined. Similarly, any class in biz.xsoftware.presentation cannot depend on any class in biz.xsoftware.dataaccess

Also, notice that biz.xsoftware.presentation.Gui is allowed to depend on biz.xsoftware.util.pres.ClassInSubpackage because subpackages is set to include. This allows subpackages of biz.xsoftware.util to also be included in the design without having to define every subpackage.

Lastly, notice the first line so javax and all javax subpackages can be depended on without declaring them. Use this sparingly though as sometimes you might want to isolate dependencies like depending on JMX to a certain package. For example, you may want only biz.xsoftware.management to depend on JMX and nothing else to depend on it. If you declare the same declaration I declared here for javax, you will not be able to guarantee that.

The wad design.xml file

If you really want to, you could design for a wad. This is not suggested and if you want to do this, don't use this ant task please.
  <design>
     <package name="wad" package="<default package>" subpackages="include"/>
  </design>

Including subpackages design.xml

  <design>
     <package name="service1" package="biz.xsoftware.service1" subpackages="include"/>
     <package name="client1"  package="biz.xsoftware.client1"  depends="service1"/>
     <package name="service2" package="biz.xsoftware.service2"/>
     <package name="client2"  package="biz.xsoftware.client2"  depends="service2" subpackages="include"/>
  </design>

Note that here for service 1, classes in package biz.xsoftware.client1 can depend on any classes in biz.xsoftware.service1 and can also depend on classes in subpackages of biz.xsoftware.service1.

Note that for service 2, classes in biz.xsoftware.client2 and client2's subpackages are all allowed to depend on classes in biz.xsoftware.service2.

One Design Note

One big note to consider, there is one design dependency that verifydesign cannot see from the class file. This is due to the String constants(This only happens with static final Strings and static final primitives being compiled into the class file. Here is example code demonstrating this task cannot catch these dependencies....
public class Client {
    public void fakeMethod() {
	     String s = Dependency.CONSTANT;  //verifydesign task can't tell this depends on
		                                  //DependencyClass as that info is lost after compiling
	}
}

public class DependencyClass {
    public static final String CONSTANT = "asdf"; 
}

Copyright © 2002-2004 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/verifylegacytutorial.html0000644000175000017500000001053611257223261024745 0ustar mkochmkoch VerifyDesign Legacy System Tutorial

VerifyDesign Legacy System Tutorial

If you have a legacy system, it can be overwhelming as a typical system is a mess when it comes to package dependencies. This tutorial shows a way to ease into the verifydesign task instead of fixing everything all at once.

First, in your build.xml file, use this line to verify your jar(or you can modify it to verify multiple jars)

    <verifydesign jar="yourjarname.jar"
                  design="design.xml" 
                  />
Now is the hardest part, go ahead and define every package and set the needDepends attribute to false for all of them so your design.xml should look like so
  <design>
      <package name="first" package="your.first.package" needDepends="false"/>
      <package name="second" package="your.second.package" needDepends="false"/>
      <package name="third" package="your.third.package" needDepends="false"/>
      <package name="fourth" package="your.fourth.package" needDepends="false"/>
      <package name="fifth" package="your.fifth.package" needDepends="false"/>
  </design>
Please give them better names then first, second, third, etc. You may have 100 packages on some projects and this may take a while to get started, but keep in mind once you are done with this, you are done with the majority of the work and the build will pass once you are done with this too! Now comes the fun part, learning about your design. Take a package that you want to start restricting dependencies on and erase the needDepends(by default it's value will be true). Let's take your.first.package and create the new design.xml file like so...
  <design>
      <package name="first" package="your.first.package"/>
      <package name="second" package="your.second.package" needDepends="false"/>
      <package name="third" package="your.third.package" needDepends="false"/>
      <package name="fourth" package="your.fourth.package" needDepends="false"/>
      <package name="fifth" package="your.fifth.package" needDepends="false"/>
  </design>
Now we run the build and we get errors that your.first.package depends on second, third, and fourth. Let's pretend we only wanted to depend on second and third. We then change our design file to so...
  <design>
      <package name="first" package="your.first.package"
         <depends>second</depends>
         <depends>third</depends>
      </package>
      <package name="second" package="your.second.package" needDepends="false"/>
      <package name="third" package="your.third.package" needDepends="false"/>
      <package name="fourth" package="your.fourth.package" needDepends="false"/>
      <package name="fifth" package="your.fifth.package" needDepends="false"/>
  </design>
Now we run the build and clean up all the code so that first doesn't depend on fourth anymore. This first step can typically take a full release if you are doing this in the margins. That is ok and now forever your.first.package will only depend on second and third until the design file is changed. You have made major progress. I would suggest a package a release. It can clean up dependencies and you will start finding it can be easier to add more and more features and not end up with a wad or mess on your hands. Good luck designing. Refactoring a legacy system can be very challenging and very long with or without this task. This ant task guarantees that you are actually heading in your defined direction. Whether the direction is correct or not is another story :).

Copyright © 2002-2004 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/limit_task.html0000644000175000017500000001065511257223261022632 0ustar mkochmkoch Chapter 10. Limit

Limit

The Limit task is a task container (that is, it holds other tasks) and sets a time limit on how long the nested tasks are allowed to run. This is useful for unit tests that go awry, hung socket connections, or other potentially long running tasks that need to be shut off without stopping the build.

Table 10.1. Limit Task Attributes

Attribute Description Default Required
maxwait How long to wait for nested tasks to finish. 180 seconds (3 minutes) No
maxwaitunit The unit for maxwait. Valid values are "millisecond", "second", "minute", "hour", "day", "week". seconds No
failonerror Should the build fail if the time limit has been exceeded? false No
property The name of a property to set if the max wait time is exceeded. none No
value The value to set for the property if the max wait time is exceeded. true No
milliseconds How long to wait in milliseconds. 3 minutes No
seconds How long to wait in seconds. 3 minutes No
minutes How long to wait in minutes. 3 minutes No
hours How long to wait in hours. 3 minutes No
days How long to wait in days. 3 minutes No
weeks How long to wait in weeks. 3 minutes No

Examples:

Neither the echo nor the fail will happen in this example. The build will continue once the time has expired.


<limit maxwait="3">
   <sleep seconds="10"/>
   <echo>This won't happen...</echo>
   <fail>This won't happen either...</fail>
</limit>

This is identical to the above example, but uses the convenience "seconds" attribute:


<limit seconds="3">
   <sleep seconds="10"/>
   <echo>This won't happen...</echo>
   <fail>This won't happen either...</fail>
</limit>

Neither the echo nor the fail will happen in this example. The build will not continue once the time has expired.


<limit maxwait="3" failonerror="true">
   <sleep seconds="10"/>
   <echo>This won't happen...</echo>
   <fail>This won't happen either...</fail>
</limit>

The limit will be reached and a property will be set indicating so.


<limit minutes="3" property="limit_reached">
   <sleep minutes="10"/>
   <echo>This won't happen...</echo>
   <fail>This won't happen either...</fail>
</limit>
<echo>limit_reached = ${limit_reached)</echo>


Copyright © 2003-2004 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/method_task_common.html0000644000175000017500000001641611257223261024345 0ustar mkochmkoch Ant-contrib Tasks: Http Tasks

*Method

The <method> tasks allows the caller to use the various HTTP methods (current GET, HEAD and POST are supported). These methods have some common attributes, and sub-elements which are are as shown below:

Parameters

Attribute Description Required
url The url that is being called. No, if the client host configuration is defined, and the path attribute is specified.
path The path which we are going to connect to. If this is used, you must declare an httpClient subelement, or set the clientRefId attribute for an HttpClient instance with configured host parameters. No.
queryString The queryString which we are posting to. If this is used, you must declare an httpClient subelement, or set the clientRefId attribute for an HttpClient instance with configured host parameters. No.
clientRefId The reference id of a previously declared <httpClient> data type instance. This is necessary if you want to retain state (cookies) across multiple requests, or you want specific client configuration and host configuration parameters. If not specified, we create a new <httpClient> with the default settings. No.
responseDataFile The path of the file where the response data will be placed. No.
responseDataProperty The property where the response data will be placed. No.
statusCodeProperty The name of the property to set with the HTTP response status code. No.
doAuthentication Should we perform authentication. No. If set, you must either declare an <httpClient> instance, or set the clientRefId attribute for an HttpClient which has credentials installed into it.
followRedirects Should we automatically follow redirects. No.

Parameters specified as Nested Elements



<httpClient>

Create (or reference an existing) HttpClient for use with this HTTP method call. This is necessary if you wish to configure the client beyond the default settings, enable authentication, or retain state across multiple method calls.

Please see the httpClient documentation for more details on this element


<header>

Create a request header to be sent.

Attribute Description Required
name The header name. Yes.
value The header value. Yes.


<responseHeader>

Specify a response header to be retrieved into a property.

Attribute Description Required
name The header name. Yes.
property The property to be set with the header value. Yes.


<params>

Create http method paramaters.

Attribute Description Required
contentCharSet The content character set No.
cookiePolicy The cookie policy (IGNORE_COOKIES, RFC_2109, NETSCAPE or DEFAULT) No.
credentialCharSet No.
httpElementCharSet No.
soTimeout No.
version The HTTP version. No.


Additional <params> subelements:
<double>,<int>,<long>,<boolean> ,<string>

Create a method parameter.

Attribute Description Required
name The parameter name Yes.
value The parameter value. Yes.

Examples


Copyright © 2002-2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/http-state_type.html0000644000175000017500000001147411257223261023630 0ustar mkochmkoch Ant-contrib Tasks: Http Tasks

HttpState

The <httpState> type allows the caller to create an HttpState instance, and add it as a reference, or be nested as a subelement of an <httpClient> element.

Parameters

Attribute Description Required
id The reference id to store this HttpState under. No.
refId The reference id of the HttpState which this element references. No.

Parameters specified as Nested Elements



<cookie>

Create a cookie.

Attribute Description Required
domain No.
path No.
name No.
value No.
secure No.
comment No.
expiryDate No.
version No.
domainAttributeSpecified No.
pathAttributeSpecified No.


<credentials>

Create authentication credentials.

Attribute Description Required
host The host. No.
port The port. No.
realm The realm. No.
scheme The scheme. No.
username The username. No.
password The password. No.


<proxyCredentials>

Create proxy authentication credentials.

Identitical to <credentials> element.

Examples


Copyright © 2002-2003 Ant-Contrib Project. All rights Reserved.

    
    <httpState id="myState">
       <cookie name="loginId" value="username" realm="sourceforge.net" />
    </httpState>
    
    <httpClient id="myClient" stateRefId="myState" />

    <httpClient id="myClient>
      <httpState >
        <cookie name="loginId" value="username" realm="sourceforge.net" />
      </httpState>
    </httpClient>
    
    
ant-contrib-1.0~b3+svn177/docs/manual/tasks/server_tasks.html0000644000175000017500000002077711257223261023213 0ustar mkochmkoch Ant-contrib Server Tasks

Ant-Contrib Server Tasks

The following tasks exist for running Ant server on one machine, and calling that server from another (or possibly the same) machine, to execute tasks.


AntServer

Starts an ANT server in current process. This server will wait for client connections, and when received, it will execute the commands that the client has sent. NOTE: This is a blocking call, and this task will not return until someone sends the server a shutdown command.

Parameters

Attribute Description Required
port The port on which the server will listen. No. Defaults to 17000

Example:

    
        <antserver port="12345" />
    
    

RemoteAnt

Sends command requests to a running instance of an AntServer which was started using the <antserver> task. These commands are executed in the space of the server, and therefore have no access to any variables or references in the currently executing project.

Parameters

Attribute Description Required
machine The machine name on which the server is running. No. Defaults to "localhost"
port The port on which the server is listening. No. Defaults to 17000
persistant Should we execute all commands, regardless of whether or not one of them fails. If false, as soon as a failure is encountered, we will stop execution. No. Defaults to false
failonerror If any of the sent commands encounters a build failure on the server, should we fail this task. No. Defaults to true.

Parameters Specified as Nested Elements

The commands to send are represented as nested elements as described below

runtarget

Runs a target which is contained in the same buildfile where the <antserver> task was called. This element may contain nested <property> elements for sending parameters to the target, and nested <reference> elements for sending references to the target.

Parameters

Attribute Description Required
target The name of the target to run. Yes.

runant

Runs a target in an arbitrary buildfile on the machine where the <antserver> task was called. If a relative pathname is given, then the path of the buildfile is relative to the base directory of the project where the <antserver> task was called. This element may contain nested <property> elements for sending text parameters to the target, and nested <reference> elements for sending references to the target.

Parameters

Attribute Description Required
antfile The path of the ant file to run (if relative, then the filename is computed relative to the buildfile of the server task's base directory No. Defaults to "build.xml" in the directory where the buildfile is to execute (specified by the dir attribute)
target The name of the target to run. No. Defaults to the default target of the specified antfile.
dir the directory to use as a basedir for the new Ant project. Defaults to the server 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. No.
inheritall Should the target task inherit all of the server's properties. This is equivalent to the flag of the same name on the <ant> task. No. Defaults to false
inheritrefs Should the target task inherit all of the server's references. This is equivalent to the flag of the same name on the <ant> task. No. Defaults to false

shutdown

Instructs the <antserver> task to shut itself down. Control will return to the ANT engine and will procede as necessary in the server's buildfile.

Example:

    
        <remoteant machine="localhost" port="12345">
            <runtarget target="execute.build">
               <property name="build.type" value="full" />
            </runtarget>
            <runant dir="tests" target="build.tests">
               <property name="build.type" value="full" />
               <reference refid="my.ref" torefid="inherited.ref" />
            </runtarget>
        </remoteant>
    
    

would be the equivalent of running the following directly on the server machine, from within the same buildfile where the <antserver> task was run

    
        <antcall target="execute.build">
           <param name="build.type" value="full" />
        </antcall>
        <ant dir="tests">
           <property name="build.type" value="full" />
           <reference refid="my.ref" torefid="inherited.ref" />
        </antcall>
    
    

sendfile

Sends a file from the client to the server

Parameters

Attribute Description Required
file The path of the file to send. Yes.
tofile The filename where the file is to be stored on the server, if a relative path, then it is stored relative to the server project's base directory. No. If todir is specified
tofile The directory where the file is to be stored on the server, if a relative path, then it is stored relative to the server project's base directory. The name of the file will be the same name as the source file No. If tofile is specified

Copyright © 2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/antclipse_task.html0000644000175000017500000003653211257223261023500 0ustar mkochmkoch Antclipse Task

Antclipse Task

Creator: Adrian Spinei (aspinei@myrealbox.com)

Description

UNSTABLE CODE, some parameters are supposed to change

This task creates classpaths or filesets based on your current .classpath file generated by Eclipse

Classpath creation is simple, it just produces a classpath that you can subsequently retrieve by its refid. The filesets are a little trickier, because the task is producing a fileset per directory in the case of sources and another separate fileset for the output file. Which is not necessarily bad, since the content of each directory usually serves a different purpose. Now, in order to avoit conflicting refids each fileset has a name composed by the idcontainer, followed by a dash and postfixed by the path. Supposing that your output path is bin/classes and the idcontainer is default, the task will create a fileset with refid "antclipse-bin/classes". The fileset will include all the files contained in your output directory, but without the trailing path bin/classes (as you usually strip it when creating the distribution jar).

If you have two source directories, called src and test, you'll be provided with two filesets, with refids like antclipse-src and antclipse-test. However, you don't have to code manually the path since some properties are created as a "byproduct" each time you execute the task. Their name is "idref" postfixed by "outpath" and "srcpath" (in the case of the source, you'll find the location of the first source directory).

Parameters

Attribute Description Required
produce This parameter tells the task wether to produce a "classpath" or a "fileset" (multiple filesets, as a matter of fact). Yes
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" No
includelibs Boolean, whether to include or not the project libraries. Default is true. No
includesource Boolean, whether to include or not the project source directories. Default is false. No
includeoutput Boolean, whether to include or not the project output directories. Default is false. No
verbose Boolean, telling the app to throw some info during each step. Default is false. No
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. No
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. No

Parameters specified as nested elements

None at the moment.

TODOS

  • make "includes" and "excludes" to work on the source and output filesets
  • maybe find an elegant solution to this multiple fileset/directories issues
  • work with files referenced in other projects

Example

This is a pretty self-explanatory Ant script, just follow the comments.

<?xml version="1.0"?>
<project default="compile" name="test" basedir=".">
<taskdef name="antclipse" classname="net.sf.antcontrib.antclipse.ClassPathTask"/>
<target name="make.fs.output">
	<!-- creates a fileset including all the files from the output directory, called ecl1-bin if your binary directory is bin/ -->
	<antclipse produce="fileset" idcontainer="ecl1" includeoutput="true" includesource="false"
	includelibs="false" verbose="true"/>
</target>
<target name="make.fs.sources">
	<!-- creates a fileset for each source directory, called ecl2-*source-dir-name*/ -->
	<antclipse produce="fileset" idcontainer="ecl2" includeoutput="false" includesource="true"
	includelibs="false" verbose="true"/>
</target>
<target name="make.fs.libs">
	<!-- creates a fileset sontaining all your project libs called ecl3/ -->
	<antclipse produce="fileset" idcontainer="ecl3" verbose="true"/>
</target>
<target name="make.cp">
	<!-- creates a fileset sontaining all your project libs called ecl3/ -->
	<antclipse produce="classpath" idcontainer="eclp" verbose="true" includeoutput="true"/>
</target>
<target name="compile" depends="make.fs.libs, make.fs.output, make.fs.sources, make.cp">
    <echo message="The output path is ${ecl1outpath}"/>
    <echo message="The source path is ${ecl2srcpath}"/>
    <!-- makes a jar file with the content of the output directory -->
	<zip destfile="out.jar"><fileset refid="ecl1-${ecl1outpath}"/></zip>
	<!-- makes a zip file with all your sources (supposing you have only source directory) -->
	 <zip destfile="src.zip"><fileset refid="ecl2-${ecl2srcpath}"/></zip>
	<!-- makes a big zip file with all your project libraries -->
	 <zip destfile="libs.zip"><fileset refid="ecl3"/></zip>
	 <!-- imports the classpath into a property then echoes the property -->
	 <property name="cpcontent" refid="eclp"/>
	<echo>The newly created classpath is ${cpcontent}</echo>
</target>
</project>

Copyright © 2002-2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/urlencode.html0000644000175000017500000000474511257223261022455 0ustar mkochmkoch Ant-contrib Tasks: URLEncode

Foreach

The URLEncode task will encode a given property for use within a a URL string. This value which is actually set will be encoded via the java.net.URLEncoder.encode() method. Typically, you must do this for all parameter values within a URL.

Parameters

Attribute Description Required
property The name of the property to set. Yes.
override If the property is already set, should we change it's value. Can be true or false No. Defaults to false
name Deprecated The name of the property to set. No. Use the property attribute instead
value The value of the property. No, if refid or location is specified
location The location of a file whose absolute path will be the value of the property. No, if value or refid is specified.
refid The id of a saved reference whose value will be the value of the property. No, defaults to ",".

Example

The following code
    
    <urlencode name="file.location" location="C:\\wwwhome\\my reports\\report.xml" />
    
    
would set the "file.location" property to the value: C%3A%5Cwwwhome%5Cmy+reports%5Creport.xml which could then be used in a URL.

Copyright © 2002-2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/throw.html0000644000175000017500000000215211257223261021626 0ustar mkochmkoch Ant-contrib Tasks: Throw

Throw

Extension of Ant's built-in <fail> task that can throw an exception that is given by a reference. This may be useful if you want to rethrow the exception that has been caught by a <trycatch> task in the <catch> block.

Parameters

Attribute Description Required
refid Id of the referenced exception. No.

In addition, all attributes of the <fail> task are supported.


Copyright © 2002 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/timestampselector.html0000644000175000017500000001056111257223261024232 0ustar mkochmkoch Ant-contrib Tasks: TimestampSelector

TimestampSelector

The TimestampSelector task takes either a nested <path> element, or a path reference, and sets either a named property, or a path instance to absolute pathnames of the files with either the N latest or earliest modification dates (based on the age attribute)

Parameters

Attribute Description Required
property The property to set with the most recently modified file. Mutually exclusive with the outputsetid attribute. Yes, if outputsetid is not specified.
outputsetid The id of a path instance which will contain the resulting list of files. This id should not already exist. Mutually exclusive with the property attribute Yes, if property is note specified.
count The number of files to find. If more than 1, than the files in the output appear in the order indicated by the age attribute. No. Defaults to 1
age The age of the files to retrieve, either eldest or youngest. Defaults to youngest. No. Defaults to 1
pathSep The path separator to separate paths with when using the property attribute in conjunction with the count attribute No. Defaults to ,
pathref Id of the path to find the most recently modified file in. No, if a path subelement is specified.

Parameters specified as nested elements

path

Path is used to select sets of files or directories in which to find the most recently modified file

Example

Using a path reference

    

    <path id="mypath">
       <fileset dir="${log.dir}">
         <include name="update*.log" />
       </fileset>
    <path>
    <timestampselector property="most.recent.logs"
                        pathref="mypath" count="3"
                        pathsep=";" />

    <echo message="${most.recent.logs}" />
    
    

Using a nested path element

    

    <timestampselector property="most.recent.logs"
                        count="3"
                        pathsep=";" >
      <path>
         <fileset dir="${log.dir}">
           <include name="update*.log" />
         </fileset>
      <path>
    </timestampselector>

    <echo message="${most.recent.logs}" />
    
    

Outputing to a path element

    

    <timestampselector outputsetref="most.recent.logs"
                        pathref="mypath" count="3">
      <path>
         <fileset dir="${log.dir}">
           <include name="update*.log" />
         </fileset>
      <path>
    </timestampselector>

    <copy todir="somedir">
      <path refid="most.recent.logs" />
    </copy>
    
    

Copyright © 2002-2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/propertyregex.html0000644000175000017500000001111411257223261023400 0ustar mkochmkoch Ant-contrib Tasks: PropertyRegex

PropertyRegex

Performs regular expression operations on an input string, and sets the results to a property. There are two different operations that can be performed:

  1. Replacement - The matched regular expression is replaced with a substitition pattern
  2. Selection - Groupings within the regular expression are selected via a selection expression.

Parameters

Attribute Description Required
property The name of the property to set. Yes.
override If the property is already set, should we change it's value. Can be true or false No. Defaults to false
input The input string to be processed Yes.
regexp The regular expression which is matched in the input string. Yes (can be specified in a <regexp> subelement).
select A pattern which indicates what selection pattern you want in the returned value. This uses the substitution pattern syntax to indicate where to insert groupings created as a result of the regular expression match. Yes, unless a replace is specified
replace A regular expression substitition pattern, which will be used to replace the given regular expression in the input string. Yes, unless a select is specified
casesensitive Should the match be case sensitive No. default is "true".
global Should a replacement operation be performed on the entire string, rather than just the first occurance No. default is false.
defaultValue The value to set the output property to, if the input string does not match the specific regular expression. No.

Select expressions

Expressions are selected in a the same syntax as a regular expression substitution pattern.
  • \0 indicates the entire property name (default).
  • \1 indicates the first grouping
  • \2 indicates the second grouping
  • etc...

Replacement

It is important to note that when doing a "replace" operation, if the input string does not match the regular expression, then the property is not set. You can change this behavior by supplying the "defaultValue" attribute. This attribute should contain the value to set the property to in this case.

Example

    
    <propertyregex property="pack.name"
              input="package.ABC.name"
              regexp="package\.([^\.]*)\.name"
              select="\1"
              casesensitive="false" />
    
    yields ABC
    
    
    <propertyregex property="pack.name"
              input="package.ABC.name"
              regexp="(package)\.[^\.]*\.(name)"
              replace="\1.DEF.\2"
              casesensitive="false" />
    
    yields package.DEF.name
    

Copyright © 2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/stopwatch_task.html0000644000175000017500000000453111257223261023524 0ustar mkochmkoch Stopwatch

Stopwatch

The Stopwatch task makes it easy to add performance timing to Ant targets. Stopwatches are named so that multiple watches can run simultaneously.

Table 9.1. Stopwatch Task Attributes

Attribute Description Default Required
name The name for the stopwatch. The elapsed time or total time will be stored as an Ant property with this name. None Yes
action Valid values are "start", "stop", "elapsed", and "total". "start" No

The stopwatch is started with the "start" action. When the action is "elapsed" or "total", the running time of the stopwatch is printed out. Both "stop" and "total" stop the stopwatch and reset it to zero. "elapsed" prints out the current running time of the stopwatch without stopping it.

Example:


<stopwatch name="timer1"/>
<!-- do some tasks here... -->
<stopwatch name="timer1" action="elapsed"/> <!-- print the elapsed time -->
<!-- do some more tasks here... -->
<stopwatch name="timer1" action="total"/> <!-- print out the total time -->


Copyright © 2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/osfamily.html0000644000175000017500000000211011257223261022300 0ustar mkochmkoch Ant-contrib Tasks: Osfamily

Osfamily

Task definition for the OsFamily 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", "os/2", "os/400", "z/os", "tandem" and "windows".

Parameters

Attribute Description Required
property The name of the property to set with the OS family name. Yes.

Copyright © 2002-2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/for.html0000644000175000017500000002121711257223261021254 0ustar mkochmkoch Ant-contrib Tasks: For

For

The for task iterates over a list, a list of paths, or any type that has a public iterator() method. The list will be evaluated first. Nested paths are evaluated in the order they appear in the task. Nested types will then be evalulated.

This task is the same as the <foreach> task, except that

  • it uses a nested sequential for each iteration; and
  • it implements an additional "keepgoing" attribute.
<for> makes use of ant's macrodef task, so the @{} notation is used for parameter substition.

This task only works for ant version greater than or equal to ant 1.6.0.

Parameters

Attribute Description Required
list The list of values to process, with the delimiter character, indicated by the "delimiter" attribute, separating each value. Yes, one of these need to be set, unless a nested path has been specified.
end Sets the ending index value. If this attribute is set, the <for> task will loop from "start" (default 1) to "end", using "step" (default 1) increments.
param Name of the parameter to pass the tokens or files in as to the sequential. Yes
delimiter The delimiter characters that separates the values in the "list" attribute. Each character in the supplied string can act as a delimiter. This follows the semantics of the StringTokenizer class. No, defaults to ",".
parallel If true, all iterations of the nested <sequential> will execute in parallel. Defaults to false, which forces sequential execution of the iterations. It is up to the caller to ensure that parallel execution is safe. No
keepgoing If true, all iterations of the called <sequential> will be executed, even if a task in one or more of them fails. Defaults to false, which forces execution to stop as soon as a task fails. At the end, if any iterator has failed, the <for> task will fail, otherwise <for> will succeed.

Note that execution does not proceed keepgoing from one task to the next within the <sequential>, but rather from one iteration to the next.

It is up to the caller to ensure that keepgoing execution is safe.

No
threadCount The maximum number of allowable threads when executing in parallel. No. Defaults to 5.
trim If true, any leading or trailing whitespace will be removed from the list item before it is passed to the sequential. No. Defaults to false.
begin Sets the starting index value. This in only used if the "end" attribute is set. No. Defaults to "1".
step Sets the index increment step. This in only used if the "end" attribute is set. No. Defaults to "1".

Parameters specified as nested elements

path

Paths are used to select sets of files or directories to iterate over.

Using a path allows you to determine the order by which files are considered by using filelists or explicit pathelements. You also can specify whether you want to iterate over files or directories by chosing either filesets or dirsets.

fileset

FileSets are used to select sets of files to iterate over.

dirset

DirSets are used to select sets of directories to iterate over.

sequential

This is the list of tasks to be run for each iteration of the list.

Example

To print out the first five letters of the latin alphabet:

<echo message="The first five letters of the alphabet are:"/>
<for list="a,b,c,d,e" param="letter">
  <sequential>
    <echo>Letter @{letter}</echo>
  </sequential>
</for>
        

A more complicated example to to iterate over a set of c++ source files and invoke the <cc> task on them:

<for param="file">
  <path>
    <fileset dir="${test.dir}/mains" includes="*.cpp"/>
  </path>
  <sequential>
    <propertyregex override="yes"
      property="program"  input="@{file}"
      regexp=".*/([^\.]*)\.cpp" replace="\1"/>
    <mkdir dir="${obj.dir}/${program}"/>
    <mkdir dir="${build.bin.dir}"/>
    <cc link="executable" objdir="${obj.dir}/${program}"
        outfile="${build.bin.dir}/${program}">
      <compiler refid="compiler.options"/>
      <fileset file="@{file}"/>
      <linker refid="linker-libs"/>
    </cc>
  </sequential>
</for>
        
The preceding example will stop as soon as one of the <cc> tasks fails. If you change the first line of the example to
    <for param="file" keepgoing="true">
All iterations will be executed, and then <for> will fail if any one or more of the <cc> tasks failed.

The following example embeds an outofdate type and iterates over the sources that are newer than their corresponding targets.

    <ac:for param="xmlfile" xmlns:ac="antlib:net.sf.antcontrib">
      <ac:outofdate>
        <ac:sourcefiles>
          <ac:fileset dir="${basedir}/xdocs" includes="**/*.xml"/>
        </ac:sourcefiles>
        <ac:mapper dir="${basedir}/xdocs"
                   type="glob" from="*.xml" to="${basedir}/docs/*.html"/>
      </ac:outofdate>
      <ac:sequential>
        <echo>Need to generate a target html file from source file @{xmlfile}</echo>
      </ac:sequential>
    </ac:for>
      

The following example loops from one to ten.

    <ac:for param="i" end="10">
      <sequential>
        <echo>i is @{i}</echo>
      </sequential>
    </ac:for>
    

The following example counts down from 10 to 0 in steps of -2.

    <ac:for param="i" begin="10" step="-2" end="0">
      <sequential>
        <echo>i is @{i}</echo>
      </sequential>
    </ac:for>
    

Copyright © 2003-2006 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/runtarget.html0000644000175000017500000000150211257223261022474 0ustar mkochmkoch Ant-contrib Tasks: RunTarget

RunTarget

Ant task that runs a target without creating a new project.

Parameters

Attribute Description Required
target The name of the target to run. Yes.

Example

      
      TO BE DONE
      
    

Copyright © 2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/compilewithwalls.html0000644000175000017500000001510011257223261024047 0ustar mkochmkoch Compile With Walls Task

Compile With Walls Task

Deprecated: Use verifydesign task instead

Creator: Dean Hiller (dean@xsoftware.biz)

Description

Puts up walls in a the same source tree to ensure that designs are not violated

This task helps someone separate out packages and prevent dependencies from occurring on accident. For example, if there are three packages in one source tree

  • biz.xsoftware.mod
  • biz.xsoftware.modA
  • biz.xsoftware.modB
and modB and modA should be able to compiled independently, you can put a wall up in between the two so that if anyone adds a dependency between modA and modB, the build will break. This is particularly good if the builds are automated.

This task is for low level design. For architectural walls like client and server, I would suggest using multiple source trees and compiling those source trees independently as two different ant compile targets.

One pattern I personally like to follow can be seen on the vmaster project on sourceforge. Instructions to check it out and look at are HERE. The interesting files in vmaster to look at our here....
  • vmaster/vmasterdiff/conf/build.xml(ant file using compilewithwalls)
  • vmaster/vmasterdiff/conf/dependencies.xml(The compilewithwalls task references this file as the walls)
Looking at some of the 2nd file(dependencies.xml), one can see apis separated out for many non-GUI and GUI components in these packages
  • api.biz.xsoftware.difflib.file.*
  • api.biz.xsoftware.difflib.dir.*
  • more api.* packages
  • org.vmasterdiff.gui.dirdiff.impl.*
Looking closely at the api.* packages, each one has a Factory. This factory uses reflection to create the implementation components. Basically, the api should not know of the implementation so there are walls around the api. Reflection to instantiate the implementation gets around these walls. My bigger components that use the smaller one's use these factories. In my design you are guaranteed these components are replaceable. Feel free to checkout vmaster and look at the factories also.

Parameters

Attribute Description Required
walls Specifies the external dependency file to use(see example below) Either this or a nested walls element is required
intermediaryBuildDir Specifies scratch area for the compilewithwalls task to do the building and ensure dependencies are not violated required

Parameters specified as nested elements

This task can contain one nested javac task and one nested walls task. See the javac task for it's attributes and nested elements.

Walls element

The nested walls element or the walls attribute must be specified. Only one may be used. The walls element contains nested package elements. These nested package elements have the following attributes. If any package depends on another, it must be listed after the package it depends on in the walls element.

Attribute Description Required
name A smaller nickname for the package to reference in depends Required
package The package to compile such as biz.xsoftware.* to include the immediate package only or biz.xsoftware.** to include biz.xsoftware and all subpackages. Required
depends If a package need one of the previously specified packages to compile, it's name would be added here in a comma separated list. For example depends="modA,modB" Optional

Examples

In the examples, I will show the javac as a null element, because it's use is documented in the javac task documentation.

Walls Nested Element....

  <compilewithwalls>
     <walls>
        <package name="modA" package="biz.xsoftware.mod.modA.**"/>
        <package name="modB" package="biz.xsoftware.mod.modB.*"/>
        <package name="mod" package="biz.xsoftware.mod.modA.*" depends="modA,modB"/>
     </walls>
     <javac></javac>
  </compilewithwalls>

Notice that the package named mod had to come after the packages it depended on. Now if anybody puts code in modA that uses classes in modB, the build will break telling them they are violating a design constraint. I personally have had many a devoloper accidentally put dependencies in that we agreed in the design should not be there. This includes myself. This prevents this from happening as long as someone doesn't change the ant build file....If someone does though, at least you can view the package dependencies and now what they are.

Walls attribute......

These next lines would be in build.xml.....
  <compilewithwalls walls="dependencies.xml">
     <javac></javac>
  </compilewithwalls>
These lines would be in dependencies.xml.....
  <walls>
     <package name="modA" package="biz.xsoftware.mod.modA.**"/>
     <package name="modB" package="biz.xsoftware.mod.modB.*"/>
     <package name="mod" package="biz.xsoftware.mod.modA.*" depends="modA,modB"/>
  </walls>

Copyright © 2002-2004 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/get-method_task.html0000644000175000017500000000101411257223261023536 0ustar mkochmkoch Ant-contrib Tasks: Http Tasks

GetMethod

The <getMethod> task allows the caller to use the HTTP GET method. This method inherits the Common Method attributes and subelements.

Examples


Copyright © 2002-2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/shellscript.html0000644000175000017500000001024011257223261023014 0ustar mkochmkoch Ant-contrib Tasks: ShellScript

ShellScript

Task definition for the shellscript task. This task allows the user to execute a script against a particular shell program on a machine. It is an extension of the "exec" task, and as such, supports the same attributes. One can however use "shell" instead of "executable". Also the "command" attribute is not allowed. See the ANT documentation for a description of the <exec> task parameters.

Parameters

Attribute

Description

Required

shell

The name of the shell executable which is to be executed. This shell must support taking a single parameter whose value is a script file which is to be executed.

Yes

executable

Same as “shell”


tmpsuffix

The contents of the script are placed in a temporary file. This attribute is the extension to use. note: The value must contain any dots required. This attribute is usefull for using script files with windows

No

inputstring

This is placed in the script file.

No

Nested Text

Any nested text is treated as the contents of the script that is to be executed within the shell. Embedded ant properties will be converted.

Examples

        <shellscript shell="bash" dir="${src.mib.dir}">
           mibgen -i ../include mib.mib -c ${build.gen.dir}/generated.cpp
           mibgen -i ../include mib.mib -h ${build.gen.dir}/generated.h
        </shellscript>

        <shellscript shell="sed" outputproperty="sed.output">
          <arg value="-e"/>
          <arg value="s/FOO/BAR/g"/>
          FOO bar bar bar FOO bar bar
        </shellscript>

        <shellscript shell="cmd.exe" tmpsuffix=".bat">
          <arg value="/c"/>
          <arg value="call"/>
          echo hello world
        </shellscript>

        <shellscript shell="bash"
          dir="${build.bin.dir}"
          inputstring="ls -rt | tail -n 1"
          outputproperty="last.bin.file"/>

        <shellscript executable="perl">
          print STDOUT "Hello World!\n";
        </shellscript>

        <shellscript shell="sh" dir="${thirdparty.dist.dir}/lib">
          rm *.so
          for file in *.0
          do
            x=`echo $file | sed -e's/.0.1.0//'`
            ln -s $file $x
          done
        </shellscript>



Warning:

One should be carefull in using shellscript, as overuse will make your build files difficult to understand, to maintain and to support multiplatform builds. Use of cygwin in a windows environment will help. However one should strive to use the java tasks whereever possible.

    

Copyright © 2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/variable_task.html0000644000175000017500000001402611257223261023275 0ustar mkochmkoch Variable Task

Chapter 8. Variable Task

The Variable task provides a mutable property to Ant and works much like variable assignment in Java. This task is similar to the standard Ant Property task, except that THESE PROPERTIES ARE MUTABLE. While this goes against the standard Ant use of properties, occasionally it is useful to be able to change a property value within the build. In general, use of this task is DISCOURAGED, and the standard Ant Property should be used if possible. Having said that, in real life I use this a lot.

Variables can be set individually or loaded from a standard properties file. A 'feature' of variables is that they can override properties, but properties cannot override variables. So if an already established property exists, its value can be reassigned by use of this task.

Table 8.1. Variable Task Attributes

Attribute Description Default Required
name The name of the property to set. None Yes, unless 'file' is used.
value The value of the property. "" No
unset Removes the property from the project as if it had never been set. false No
file The name of a standard properties file to load variables from. None No

In the following example, the property x is first set to "6", then evaluated by the if , and reassigned the value "12". The echo task will print out 12.



    <var name="x" value="6"/>
    <if>
        <equals arg1="${x}" arg2="6" />
        <then>
            <var name="x" value="12"/>
        </then>
    </if>
    <echo>${x}</echo>   <!-- will print 12 -->

The next example shows a property being set, echoed, unset, then reset:


    <property name="x" value="6"/>
    <echo>${x}</echo>   <!-- will print 6 -->
    <var name="x" unset="true"/>
    <property name="x" value="12"/>
    <echo>${x}</echo>   <!-- will print 12 -->


The following shows some more uses of the Variable task. It is especially handy for property appending. Notice a couple of things: the property task can't override a var value, in general, you should use var with the unset attribute to change the value of a property.



    <var name="x" value="6"/>
    <echo>x = ${x}</echo>   <!-- print: 6 -->

    <var name="x" value="12"/>
    <echo>x = ${x}</echo>   <!-- print: 12 -->

    <var name="x" value="6 + ${x}"/>
    <echo>x = ${x}</echo>   <!-- print: 6 + 12 -->

    <var name="str" value="I "/>
    <var name="str" value="${str} am "/>
    <var name="str" value="${str} a "/>
    <var name="str" value="${str} string."/>
    <echo>${str}</echo>     <!-- print: I am a string. -->

    <var name="x" value="6"/>
    <echo>x = ${x}</echo>   <!-- print: 6 -->

    <property name="x" value="12"/>
    <echo>x = ${x}</echo>   <!-- print: 6 (property can't override) -->

    <var name="x" value="blue"/>
    <tstamp>
        <format property="x" pattern="EEEE"/>
    </tstamp>
    <echo>Today is ${x}.</echo> <!-- print: Today is blue. -->

    <var name="x" value="" unset="true"/>
    <tstamp>
        <format property="x" pattern="EEEE"/>
    </tstamp>
    <echo>Today is ${x}.</echo> <!-- print: Today is Friday. -->



Copyright © 2003-2004 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/inifile.html0000644000175000017500000000625611257223261022113 0ustar mkochmkoch Ant-contrib Tasks: IniFile

IniFile

Build and Edit Windows .ini files. Only the simple edits, remove and set are allowed. Set has limited computation capability which is described later.

Parameters

Attribute Description Required
source The name source .ini file to read in. No.
dest The name destination .ini file to write. Yes.

Parameters specified as nested elements

remove
Attribute Description Required
section The name of the section Yes.
property The name property. No. If not supplied, the entire section will be removed
set
Attribute Description Required
section The name of the section Yes.
property The name property. Yes.
value The value to set the property to. No, if operation is specified.
operation The operation to perform on the existing value. Possible values are "+" and "-", which add and subtract 1, respectively from the existing value. If the value doesn't already exist, the set is not performed. No, if value is specified.

Example



<inifile source="myprog.ini" dest="myprog.new.ini">
   <set section="Section1" property="release-date" value="${todays.date}" />
   <set section="Section1" property="build-number" operation="+" />
   <remove section="Section2" property="useless" />
   <remove section="OutdatedSection" />
</inifile>

Copyright © 2002-2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/get-cookie_task.html0000644000175000017500000000523011257223261023533 0ustar mkochmkoch Ant-contrib Tasks: Http Tasks

GetCookie

The <getCookie> task allows the caller to retrieve one or more cookies from an <httpState> reference.

Parameters

Attribute Description Required
realm The realm of the cookie(s) to retrieve. Yes.
port The port of the cookie(s) to retrieve. No. defaults to 80
path The path of the cookie(s) to retrieve. Yes.
secure The secure flag of the cookie(s) to retrieve. No. Default to false.
name The name of the cookie to retrieve. No. If not specified, multiple cookies may be found.
cookiePolicy The cookiePolicy to use to match cookies. No. Default to 'rfc2109'.
property The property to retrieve the cookie into. This will only retrieve the first cookie found which matches the query. If no 'name' attribute is specified, there is no guarantee you will get the cookie you are expecting. No, unless 'prefix' is not specified.
prefix The prefix to use when settings properties for the cookies. One property will be set for each cookie, where the property name will be of the pattern: ${prefix}${cookie.name} where ${cookie.name} is the name of the cookie. No, unless 'property' is not specified.

Examples


Copyright © 2002-2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/http-client_type.html0000644000175000017500000001425011257223261023761 0ustar mkochmkoch Ant-contrib Tasks: Http Tasks

HttpClient

The <httpClient> type allows the caller to create an HttpClient instance, and add it as a reference, or be nested as a subelement of an HTTP method call.

Parameters

Attribute Description Required
id The reference id to store this HttpClient under. No.
refId The reference id of the HttpClient this element refers to. No.
stateRefId The HttpState object to use. No. Uses a default HttpState.

Parameters specified as Nested Elements



<clientParams>

Create http client params.

Attribute Description Required
strict Should we be strict on the protocol. No.
authenticationPreemptive Should we pre-emptively try to authenticate? No.
connectionManagerTimeout The timeout for the connection manager. No.
contentCharSet The content character set No.
cookiePolicy The cookie policy (IGNORE_COOKIES, RFC_2109, NETSCAPE or DEFAULT) No.
credentialCharSet No.
httpElementCharSet No.
soTimeout No.
version The HTTP version. No.
Additional <clientParams> subelements:
<double>,<int>,<long>,<boolean> ,<string>

Create a client parameter.

Attribute Description Required
name The parameter name Yes.
value The parameter value. Yes.


<hostConfig>

Create a host configuration.

Attribute Description Required
host The host to connect to. No.
port No.
protocol No.
address No.
proxyHost The proxyHost to connect to. No.
proxyPort No.


Additional <hostConfig> subelements:
<hostParams>

Specify HostParams.

<hostParams> subelements are identical to those of <clientParams>


<httpState>

Create (or reference an existing) HttpState for use with this HTTP client. This is necessary if you wish to enable authentication, or retain state across multiple method calls.

Please see the httpState documentation for more details on this element

Examples

    
    <httpClient id="client1">
        <clientParams cookiePolicy="RFC_2109" />
    </httpClient>
    
    

Copyright © 2002-2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/propertycopy.html0000644000175000017500000000444011257223261023244 0ustar mkochmkoch Ant-contrib Tasks: Propertycopy

Propertycopy

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.

Parameters

Attribute Description Required
property The name of the property to set. Yes.
override If the property is already set, should we change it's value. Can be true or false No. Defaults to false
name Deprecated The name of the property to set. No. Use the property attribute instead
from The name of the property you wish to copy the value from. Yes.
silent Do you want to suppress the error if the "from" property does not exist, and just not set the property "name". No, default is "false".

Example

<property name="org" value="MyOrg" />
<property name="org.MyOrg.DisplayName" value="My Organiziation" />
<propertycopy name="displayName" from="org.${org}.DisplayName" />

Sets displayName to "My Organiziation".


Copyright © 2002 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/sortlist.html0000644000175000017500000001143611257223261022353 0ustar mkochmkoch Ant-contrib Tasks: SortList

SortList

Sort a delimited list of items in their natural string order. Note that the value and refid attributes are mutually exclusive, and the value attribute takes precedence if both are specified.

Parameters

Attribute Description Required
property The name of the property to set. Yes.
override If the property is already set, should we change it's value. Can be true or false No. Defaults to false
value The list of values to process, with the delimiter character, indicated by the "delimiter" attribute, separating each value. Yes, unless "refid" is specified.
refid The id of where the list of values to sort is stored. Yes, unless "value" is specified.
delimiter The delimiter string that separates the values in the "list" attribute. No, defaults to ",".
casesensitive If true, does a case sensitive sorting of the strings. If false does case insensitive sorting. No. Defaults to true.
numeric If true, does a numeric sorting, treating all list entries as if they were numbers. No. Defaults to false.
orderPropertyFile If specified, the list will sorted as if they were property names, and will be sorted in the order those properties appear in the given property file. Any properties in the value attribute which do not appear in the properties file will be inserted at the end of the list. This property is most useful when used in conjunction with the <propertyselector> task (see Example 2). No.
orderPropertyFilePrefix If orderPropertyFile is specified, this value (with a trailing '.') will be prefixed to each property in the specified orderPropertyFile to determine sorting order No.

Example 1

    
    <property name="my.list" value="z,y,x,w,v,u,t" />
    <sortlist property="my.sorted.list" value="${my.list}"
                 delimiter="," />
    <echo message="${my.sorted.list}" />
    

    prints

    
     [echo] t,u,v,w,x,y,z
    

    

Example 2

    test.properties
    ---------------
    a.name=a
    c.name=c
    b.name=b

    
    <property file="test.properties" prefix="test" />
    <propertyselector property="my.list"
                         delimiter=","
                         match="test\..*\.name"
                         select="\0" />
    <sortlist property="my.sorted.list"
                 value="${my.list}"
                 delimiter=","
                 orderPropertyFile="test.properties"
                 orderPropertyFilePrefix="test" />

    <echo message="${my.sorted.list}" />

    prints

    
     [echo] test.a.name,test.c.name,test.b.name
    

    Notice that the test.properties file did not have "test."
    prefixing all the properties.  The orderPropertyFilePrefix was
    used to do that.
    

Copyright © 2002-2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/head-method_task.html0000644000175000017500000000101311257223261023657 0ustar mkochmkoch Ant-contrib Tasks: Http Tasks

Head-Method

The <headMethod> task allows the caller to use the HTTP HEAD method. This method inherits the Common Method attributes and subelements.

Examples


Copyright © 2002-2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/post-method_task.html0000644000175000017500000001020211257223261023743 0ustar mkochmkoch Ant-contrib Tasks: Http Tasks

Post-Method

The <post-method> task allows the caller to use the HTTP POST method to send data to an arbitrary url. This data can be one of the following:
  • Name/Value pairs
  • File content
  • Text content
  • Multi-part content
This method inherits the Common Method attributes and subelements. It also contains the following additional attributes and subelements:

Parameters

Attribute Description Required
multipart Should multipart content be forced, even if only a single file or text part is specified. No.
parameters A java .properties file which contains post parameters. No.

Parameters specified as Nested Elements



<parameter>

Create a text post parameter.

Attribute Description Required
name The parameter name. Yes.
value The parameter value. Yes.


<file>

Add a File part to the request.

Attribute Description Required
name The parameter name. Yes.
path The file path to send. Yes.
contentType The content type of the file. No.
charSet The character set. No.


<text>

Add a Text part to the request.

Attribute Description Required
name The parameter name. Yes.
value The string value to send. This may also be specified as nested text to this element. Yes.
contentType The content type of the file. No.
charSet The character set. No.

Examples


Copyright © 2002-2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/toc.html0000644000175000017500000000664311257223261021261 0ustar mkochmkoch Task List

Logic Tasks

Network Tasks

Http Tasks and Types

Performance Monitoring and Tasks

Platform Tasks

Property Tasks

Process Tasks

Other Tasks

ant-contrib-1.0~b3+svn177/docs/manual/tasks/if.html0000644000175000017500000000636111257223261021067 0ustar mkochmkoch Ant-contrib Tasks: If

If

Perform some tasks based on whether a given condition holds true or not.

This task is heavily based on the Condition framework that can be found in Ant 1.4 and later, therefore it cannot be used inconjunction with versions of Ant prior to 1.4. Due to numeruos bugs in Ant 1.4(.1) that affect this task, we recommend to use Ant 1.5 or later.

Parameters

This task doesn't have any attributes, the condition to test is specified by a nested element - see the documentation of your <condition> task (see the online documentation for example) for a complete list of nested elements.

Just like the <condition> task, only a single condition can be specified - you combine them using <and> or <or> conditions.

In addition to the condition, you can specify three different child elements, <elseif>, <then> and <else>. All three subelements are optional. Both <then> and <else> must not be used more than once inside the if task. Both are containers for Ant tasks, just like Ant's <parallel> and <sequential> tasks - in fact they are implemented using the same class as Ant's <sequential> task.

The <elseif> behaves exactly like an <if> except that it cannot contain the <else> 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 <if> is false, then the first <elseif> who's conditional evaluates to true will be executed. The <else> will be executed only if the <if> and all <elseif> conditions are false.

Example


<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>

<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>

Copyright © 2002-2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/performance_monitor.html0000644000175000017500000001056411257223261024541 0ustar mkochmkoch Performance Monitoring

Performance Monitoring

The "Performance Monitor" is a special Ant listener than can keep track of the amount of time that each target and task takes to execute. At the end of the build, these times will be sorted from fastest to slowest and displayed following the build output. This can be useful to pinpoint slow and/or inefficient spots in the build process and identify those areas that could benefit from optimization.

The performance listener can be used by passing a parameter to the command line for Ant:



    ant -listener net.sf.antcontrib.perf.AntPerformanceListener target

Following is an example of the results from using the listener. The result format is projectname.targetname for targets and projectname.targetname.taskname for tasks. All times are shown to the nearest millisecond.


[danson@blackdog antelope]$ ant -listener net.sf.antcontrib.perf.AntPerformanceListener dist
Buildfile: build.xml

init:

clean:
   [delete] Deleting 170 files from /home/danson/apps/antelope/build

compile:
    [javac] Compiling 61 source files to /home/danson/apps/antelope/build

all:

-build_number:

prep_files:
   [delete] Deleting 3 files from /home/danson/apps/antelope/config
     [copy] Copying 3 files to /home/danson/apps/antelope/config

combined:
     [echo] basedir = /home/danson/apps/antelope
      [jar] Building jar: /home/danson/apps/antelope/Antelope_1.208.jar

dist:
   [delete] Deleting 4 files from /home/danson/apps/antelope/dist
      [zip] Building zip: /home/danson/apps/antelope/dist/Antelope_1.208.zip
     [echo] Created zip file.

-zip_docs:
      [zip] Building zip: /home/danson/apps/antelope/dist/Antelope_docs_1.208.zip
     [echo] Zipped docs to Antelope_docs_1.208.zip.

-zip_tasks:
      [jar] Building jar: /tmp/Antelope_tasks_1.208.jar
      [zip] Building zip: /home/danson/apps/antelope/dist/Antelope_tasks_1.208.zip
   [delete] Deleting: /tmp/Antelope_tasks_1.208.jar
     [echo] Zipped tasks to Antelope_tasks_1.208.zip.
     [copy] Copying 1 file to /home/danson/apps/antelope/dist

BUILD SUCCESSFUL
Total time: 8 seconds

-------------- Target Results -----------------------
Antelope.all: 0.000 sec
Antelope.init: 0.011 sec
Antelope.-build_number: 0.014 sec
Antelope.clean: 0.233 sec
Antelope.-zip_tasks: 0.297 sec
Antelope.prep_files: 0.311 sec
Antelope.-zip_docs: 0.546 sec
Antelope.combined: 1.290 sec
Antelope.compile: 1.724 sec
Antelope.dist: 2.162 sec

-------------- Task Results -----------------------
Antelope.init.mkdir: 0.000 sec
Antelope.init.mkdir: 0.001 sec
Antelope.dist.echo: 0.002 sec
Antelope.prep_files.delete: 0.004 sec
Antelope.combined.echo: 0.005 sec
Antelope.dist.delete: 0.006 sec
Antelope.-zip_tasks.echo: 0.007 sec
Antelope.dist.copy: 0.011 sec
Antelope.-build_number.buildnumber: 0.014 sec
Antelope.compile.copy: 0.016 sec
Antelope.prep_files.copy: 0.020 sec
Antelope.prep_files.replace: 0.071 sec
Antelope.-zip_tasks.zip: 0.122 sec
Antelope.-zip_tasks.jar: 0.161 sec
Antelope.prep_files.replace: 0.216 sec
Antelope.clean.delete: 0.233 sec
Antelope.dist.antcall: 0.421 sec
Antelope.-zip_docs.zip: 0.540 sec
Antelope.dist.antcall: 0.685 sec
Antelope.dist.zip: 1.036 sec
Antelope.combined.jar: 1.284 sec
Antelope.compile.javac: 1.708 sec

-------------- Totals -----------------------
Start time: Thu, 5 Dec 2002 17:18:30
Stop time: Thu, 5 Dec 2002 17:18:39
Total time: 8.476 sec


Copyright © 2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/antcallback_task.html0000644000175000017500000001045311257223261023747 0ustar mkochmkoch AntCallBack

AntCallBack

AntCallBack is identical to the standard 'antcall' task, except that it allows properties set in the called target to be available in the calling target.

Some background may be in order: When the <antcall> task is used, in actuality, a new Ant project is created, and depending on the inheritAll property, it is populated with properties from the original project. Then the requested target in this new project is executed. Any properties set in the new project remain with that project, they do not get "passed back" to the original project. So, for example, if the target in the new project sets a property named "image.directory", there is no reference to that property in the original. Here's an example of what I mean:



    <target name="testCallback" description="Test CallBack">
        <antcallback target="-testcb" return="a, b"/>
        <echo>a = ${a}</echo>
        <echo>b = ${b}</echo>
    </target>

    <target name="-testcb">
        <property name="a" value="A"/>
        <property name="b" value="B"/>
    </target>

The output from executing "testCallback" looks like this:

a = A
b = B
Contrast with this output from "antcall":

a = ${a}
b = ${b}

This is an often requested feature for Ant, at least judging from the Ant mailing lists. I assume this is because it allows a more functional programming style than Ant natively supports. The proper Ant way of doing the above is like this:


    <target name="testCallback" description="Test CallBack" depends="-testcb">
        <echo>a = ${a}</echo>
        <echo>b = ${b}</echo>
    </target>

    <target name="-testcb">
        <property name="a" value="A"/>
        <property name="b" value="B"/>
    </target>

This is actually looks cleaner in this situation, and is faster, too. There is significant overhead in using both "antcall" and "antcallback" in that they both require a lot of object instantiation and property copying. That said, many people prefer to use "antcall" and "antcallback" as it better fits their logic and style.

The attributes for AntCallBack are identical to the 'antcall' task, with one additional, optional attibute. This attribute is named "return" and can be either a single property name or a comma separated list of property names.

Table 15.1. AntCallBack Attributes

Attribute Description Default Required
return A comma separated list of property names. Whitespace is allowed, so either "a,b" or "a, b" are acceptable. None No

For other attribute and nested element information and more examples, see the documentation for the "antcall" task in the Ant documentation.


Copyright © 2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/more_conditions.html0000644000175000017500000001504711257223261023665 0ustar mkochmkoch More Conditions

More Conditions

These conditions are suitable for use in the <bool> element. Unfortunately, they cannot be used in the <condition> task, although all conditions for the <condition> task can be used with the <bool> and the <bool> can be used anywhere that <condition> can be used.

IfPropertyTrue

Given a property name, tests whether the value for that property equals "true" (or "yes" or "on").

Table 5.2. IfPropertyTrue Attributes

Attribute Description Required
property The name of a property to test the value of. Yes



<ispropertytrue property="myprop"/>
<ispropertytrue property="${someprop}"/>

IfPropertyFalse

Given a property name, tests whether the value for that property equals "false" (or "no" or "off").

Table 5.3. IfPropertyFalse Attributes

Attribute Description Required
property The name of a property to test the value of. Yes



<ispropertyfalse property="myprop"/>
<ispropertyfalse property="${someprop}"/>

StartsWith

Given a property name, tests whether the value for that property starts with a specified string.

Table 5.4. StartsWith Attributes

Attribute Description Required
string The string to test. Yes
with Check if 'string' starts with this value. Yes



<startswith string="abcdefg" with="abc"/>
<startswith string="${myprop}" with="foo"/>

EndsWith

Given a property name, tests whether the value for that ends with with a specified string.

Table 5.5. EndsWith Attributes

Attribute Description Required
string The string to test. Yes
with Check if 'string' ends with this value. Yes



<endswith string="abcdefg" with="efg"/>
<endswith string="${myprop}" with="bar"/>

IsGreaterThan

Tests whether the first argument is greater than the second argument. Will automatically treat the arguments as numbers if both arguments consists of only the characters 0 through 9 and optionally a decimal point. Otherwise, a String comparison is used.

Table 5.6. IsGreaterThan Attributes

Attribute Description Required
arg1 The first argument. Yes
arg2 The second argument. Yes



<!-- evaluates to true -->
<isgreaterthan arg1="6.02" arg2="4"/>

<!-- evaluates to false -->
<isgreaterthan arg1="bar" arg2="foo"/>

IsLessThan

Tests whether the first argument is less than the second argument. Will automatically treat the arguments as numbers if both arguments consists of only the characters 0 through 9 and optionally a decimal point. Otherwise, a String comparison is used.

Table 5.7. IsLessThan Attributes

Attribute Description Required
arg1 The first argument. Yes
arg2 The second argument. Yes



<!-- evaluates to false -->
<islessthan arg1="6.02" arg2="4"/>

<!-- evaluates to true -->
<islessthan arg1="bar" arg2="foo"/>


Copyright © 2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/index.html0000644000175000017500000000055511257223261021577 0ustar mkochmkoch Ant-Contrib Tasks <h2>Ant-Contrib Tasks</h2> <a href="toc.html">Task List</a> ant-contrib-1.0~b3+svn177/docs/manual/tasks/pathtofileset.html0000644000175000017500000000473411257223261023346 0ustar mkochmkoch Ant-contrib Tasks: Pathtofileset

Pathtofileset

Coverts a path to a fileset. This is usefull if you have a path but need to use a fileset as input in a ant task.

Parameters

Attribute Description Required
dir The root of the directory tree of this FileSet Yes
pathrefid The reference to the path to convert from Yes
ignorenonrelative This boolean controls what will happen if any of the files in the path are not in the directory for the fileset. If this is "true" the files are ignored, if this is "false" a build exception is thrown. (Note: if files are not present no check is made). No, default is "false"
name This is the identifier of the fileset to create. This fileset will contain the files that are relative to the directory root. Any files that are not present will not be placed in the set. Yes

Example

    <outofdate outputsourcespath="modified.sources.path">
      <sourcefiles>
        <fileset dir="a/b/c" includes="**/*.java"/>
      </sourcefiles>
      <mapper dir="a/b/c" type="glob" from="*.java" to="output/*.xml"/>
      <sequential>
        <pathtofileset name="modified.sources.fileset"
                       pathrefid="modified.sources.path"
                       dir="a/b/c"/>
        <copy todir="output">
          <fileset refid="modified.sources.fileset"/>
          <mapper type="glob" from="*.java" to="*.xml"/>
        </copy>
      </sequential>
    </outofdate>
    

Copyright © 2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/post_task.html0000644000175000017500000001720211257223261022474 0ustar mkochmkoch HTTP Post

HTTP Post

The Post task is a companion to the standard Ant "Get" task. This task does a post and does not necessarily expect anything in return. Almost always, there will be some sort of returned data, this can be logged or written to a file if needed.

Basically, an HTTP POST sends name/value pairs to a web server. A very common usage is for html forms for submitting data. A typical use of this task is to send data to a servlet for updating a web page with the status of a build.

This task handles cookies correctly, which is useful for websites that set a session id to track logins or whatever. This means that if you do several posts in a row, cookies gathered from the first post will be returned with subsequent posts.

The Post task has three ways of specifying the data to be posted. Nested "prop" elements can be used. A "prop" element represents a single name/value pair. The second way is to specify a property file as an attribute to the Post. All properties from the file will be sent as part of the Post data. The third way is to just type in some defined Ant properties. Is it allowed to use all three ways at once, that is, read some properties from a file, specify others via "prop" elements, and just type in some Ant properties.

Table 12.1. Post Task Attributes

Attribute Description Default Required
to The URL of the remote server to send the post. None Yes
encoding Character encoding for the name/value pairs. UTF-8 No
logfile The name of a file to write any response to. Ignored if wantresponse is set to false. None No
property The name of a property to write any response to. Ignored if wantresponse is set to false. None No
append Should an existing log file be appended to or overwritten? True, append to an existing file. No
file A file to read POST data from. All Ant properties contained in this file will be resolved (that is, ${} syntax will be expanded to their values) prior to sending the file contents. None No
rawFile Should the file be trated as raw file instead of property-like file. True - send the content of the file directly to http-post, all properties set by 'property' are ignored!
Has only impact when the property 'file' is specified.
False, treat file as property-like No
rawFileNoEncoding Don't encode the raw file prior to sending http post request.
Has only impact when the property 'rawFile' is specified.
False, http-encode the content of the file No
maxwait The maximum amount of time in seconds to wait for the data to be sent or for a response from the remote server. Setting this to zero means wait forever. 180 (3 minutes) No
wantresponse Whether to wait for a response from the remote server or not. In many cases this can greatly improve the performance of the build script as the server response may be large and useless to the script. Use this with caution - while the response from the server may not be required for the client, the server may require that the client accept the response prior to processing the post data. true No
failonerror Whether the build should fail if the post fails. false No

Post supports nested "prop" elements. As an HTTP POST basically sends a list of names and values, the "prop" element represents one name/value pair. A Post may contain any number of "prop" elements.

Table 12.2. Prop Attributes

Attribute Description Default Required
name The name of a property to post. None Yes
value The value associated with the name. None No

The "value" attribute is not strictly required. This provides a short-cut method in cases where the property data is an already-defined Ant property. Suppose the build file has this property defined:



    <property name="src.dir" value="/home/user/project/src"/>

Then the following are equivalent:



    <prop name="src.dir"/>
    <prop name="src.dir" value="${src.dir}"/>
    <prop name="src.dir" value="/home/user/project/src"/>

Defined Ant properties can be entered directly into the post element. Again, suppose the build file has this property defined:



    <property name="src.dir" value="/home/user/project/src"/>

Then the following are equivalent:



    ${src.dir}
    <prop name="src.dir"/>
    <prop name="src.dir" value="${src.dir}"/>
    <prop name="src.dir" value="/home/user/project/src"/>

I googled for the URL in the following example.



    <property name="test.val" value="here's my test value"/>
    <property name="test.val2" value="second test value"/>
    <post to="http://wwwj.cs.unc.edu:8888/tang/servlet/tangGetPostServlet"
        verbose="true">
        <prop name="prop1" value="val1 ${test.val}"/>
        <prop name="prop2" value="val1 value 2"/>
        <prop name="prop3" value="val got some spaces %funky ^$* chars"/>
        <prop name="prop4" value="&amp; do an ampersand like this &amp;amp; or
        Ant will whine"/>
        <prop name="thanks" value="dude, thanks for the echo server!"/>
        <prop name="test.val"/>
        ${test.val2}
    </post>


Copyright © 2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/math_task.html0000644000175000017500000002365511257223261022451 0ustar mkochmkoch Math

Math

The Math task provides support for all the basic mathematical operations provided by the java.lang.Math and java.lang.StrictMath classed. It supports int, long, float and double data types. Nesting of operations is supported to allow computation of formulas like (6 + (7.25 * 3.9))/(2 * 3 * 3) or calculating the area of a circle given a radius (I'm sure this comes up often in builds controlled by Ant!).

In addition to the operations provided by the java.lang.Math and java.lang.StrictMath classes, the Math task provides several additional operations: "add", "subtract", "multiply", "divide", and "mod", which duplicate the basic Java mathematical operations "+", "-", "*", "/", and "%", respectively. In fact, either notation can be used, that is, the operation can be set to "add" or "+", depending only on which you feel is more convenient.

Table 11.1. Math Task Attributes

Attribute Description Default Required
result The name of the property to hold the result of the operation. None Yes
datatype Sets the datatype of the calculation. Allowed values are "int", "long", "float", or "double". Optional, if used, will be applied to all numbers in this math operation. double No
strict If true, use the methods in the java.lang.StrictMath class. false No
operation If used, any nested Ops will be ignored. This is for convenience for simple calculations. None No
operand1 A number to use with the operation specified in the 'operation' attribute. None Depends on the specific operation.
operand2 A number to use with the operation specified in the 'operation' attribute. None Depends on the specific operation.

The 'result' property is reusable.

The Math task supports nested "Op" elements. An Op element represents single mathematical operation, such as "min" or "add". As an alternate, if using Ant 1.5+, you can specify the operation in the tag name itself. However, you must use the text name (+,-,/,*,% are not permitted as tag names)
  <radians>
     <num value="90" />
  </radians>
instead of
  <op op="radians">
     <num value="90" />
  </op>

Table 11.2. Op Attributes

Attribute Description Default Required
op Set the name of this operation. Allowed values are one of the method names from java.lang.Math or java.lang.StrictMath, or one of "add", "subtract", "multiply", "divide", or "mod" (or "+", "-", "*", "/", or "%", respectively). "toRadians" and "toDegrees" can be represented by "radians" and "degrees", respectively, as a shorthand None Yes, if not specified in the tag name.
datatype Sets the datatype of this calculation. Allowed values are "int", "long", "float", or "double". Optional, default is "double". If the parent Math task has a datatype set, this value will be ignored and the datatype specifed in the task will be used. "int" No
arg1, arg2, arg3, arg4, arg5/td> The arguments for this operation. This is a shorthand to avoid having to use nested elements when performing a simple calculation. None No. However, these attributes are mutually exclusive with the and subelements.

The Op element supports nested "Op" elements and nested "Num" elements. A Num represents a number. When an Op is nested in another Op, the result of the Op is treated as a Num. The nested elements can be any combination of Op (short form included as mentioned above) or Num as appropriate for the formula being calculated. Most of the operations provided by java.lang.Math and java.lang.StrictMath operate on one or two numbers. The "+", "-", "*", "/", and "%" operations can task any number of nested numbers.

Table 11.3. Num Attributes

Attribute Description Default Required
value Set the value for this number. Must be able to parse to the datatype set by the parent element or the default datatype set by the task. Two special numbers, pi and e, can be represented by PI and E respectively. ("PI" is the ratio of the diameter of a circle to its radius, "E" is Euler's e, the base for natural logrithms.) None Yes
datatype Sets the datatype of this number. Allowed values are "int", "long", "float", or "double". Optional, default is "double". If the parent Math task has a datatype set, this value will be ignored and the datatype specifed in the task will be used. double No

Some examples:



    <var name="op1" value="12"/>
    <var name="op2" value="6"/>
    <var name="op" value="+"/>

    <!-- demo plus -->
    <math result="result" operand1="${op1}" operation="${op}" operand2="${op2}" datatype="int"/>
    <echo>${op1} ${op} ${op2} = ${result}</echo>
    <assert name="result" value="18"/>

    <!-- demo reusing result -->
    <math result="result" operand1="${result}" operation="${op}" operand2="${op2}" datatype="int"/>
    <echo>${op1} ${op} ${op2} = ${result}</echo>
    <assert name="result" value="24"/>

    <!-- demo minus -->
    <var name="op" value="-"/>
    <math result="result" operand1="${op1}" operation="${op}" operand2="${op2}" datatype="int"/>
    <echo>${op1} ${op} ${op2} = ${result}</echo>
    <assert name="result" value="6"/>

    <!-- demo multiply -->
    <var name="op" value="*"/>
    <math result="result" operand1="${op1}" operation="${op}" operand2="${op2}" datatype="int"/>
    <echo>${op1} ${op} ${op2} = ${result}</echo>
    <assert name="result" value="72"/>

    <!-- demo divide -->
    <var name="op" value="/"/>
    <math result="result" operand1="${op1}" operation="${op}" operand2="${op2}" datatype="int"/>
    <echo>${op1} ${op} ${op2} = ${result}</echo>
    <assert name="result" value="2"/>

    <!-- demo modulo -->
    <var name="op" value="%"/>
    <math result="result" operand1="${op1}" operation="${op}" operand2="${op2}" datatype="int"/>
    <echo>${op1} ${op} ${op2} = ${result}</echo>
    <assert name="result" value="0"/>

    <!-- demo calculating the area of a circle -->
    <!-- first, calculate the radius -->
    <math result="radius">  <!-- defaults to double datatype -->
        <op type="*">
            <num value="1"/>
            <num value="2"/>
            <num value="3"/>
            <num value="4"/>
            <num value="5"/>
        </op>
    </math>
    <echo> 1 * 2 * 3 * 4 * 5 = ${radius}</echo>

    <!-- now calculate the area -->
    <math result="area" precision="float">
        <op type="*">
            <num value="PI"/>
            <op type="pow">
                <num value="${radius}"/>
                <num value="2"/>
            </op>
        </op>
    </math>
    <echo>area = PI * radius ^ 2 = ${area}</echo>

    <!-- demo calculating a random number between 0 and 100 -->
    <math result="result">
        <op op="rint">
            <op op="*">
                <num value="100"/>
                <op op="random"/>
            </op>
        </op>
    </math>
    <echo>a random number between 0 and 100: ${result}</echo>

    <!-- demo another multiplication -->
    <math result="result" operation="multiply" operand1="17" operand2="13"/>
    <echo>${result}</echo>

    <!-- demo shorthand notation for calculating sin of an angle, which is degrees -->
    <math result="sin">
      <sin>
        <radians arg1="${angle_in_degrees}" />
      </sin>
    </math>
    <echo>${sin}</echo>


Copyright © 2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/propertyselector.html0000644000175000017500000001027311257223261024113 0ustar mkochmkoch Ant-contrib Tasks: PropertySelector

PropertySelector

Selects property names that match a given regular expression and returns them in a delimited list

Parameters

Attribute Description Required
property The name of the property you wish to set. Yes.
override If the property is already set, should we change it's value. Can be true or false No. Defaults to false
match The regular expression which is used to select property names for inclusion in the list. This follows the standard regular expression syntax accepted by ant's regular expression tasks. Yes.
select A pattern which indicates what selection pattern you want in the returned list. This used the substitution pattern syntax to indicate where to insert groupings created as a result of the regular expression match. No. default is "\0".
casesensitive Should the match be case sensitive No. default is "true".
delimiter The delimiter used to seperate entries in the resulting property No. default is ",".
distinct Should the returned entries be a distinct set (no duplicate entries) No. default is "false".

Select expressions

Expressions are selected in a the same syntax as a regular expression substitution pattern.
  • \0 indicates the entire property name (default).
  • \1 indicates the first grouping
  • \2 indicates the second grouping
  • etc...

Example

The following code
    
    <property name="package.ABC.name" value="abc pack name" />
    <property name="package.DEF.name" value="def pack name" />
    <property name="package.GHI.name" value="ghi pack name" />
    <property name="package.JKL.name" value="jkl pack name" />

    <propertyselector property="pack.list"
                         delimiter=","
                         match="package\.([^\.]*)\.name"
                         select="\1"
                         casesensitive="false" />

    
    
would yield the results
    
    ABC,DEF,GHI,JKL
    
    
You could then iterate through this list using the ForEach Task as follows:
    
    <foreach list="${pack.list}"
                delimiter=","
                target="print.name"
                param="pack.id" />

    <target name="print.name" >
      <propertycopy name="pack.name" value="package.${pack.id}.name" />
      <echo message="${pack.name}" />
    </target>
    
    
Would print
    
      [echo] abc pack name
      [echo] def pack name
      [echo] ghi pack name
      [echo] jkl pack name
    
    

Copyright © 2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/outofdate.html0000644000175000017500000002414711257223261022465 0ustar mkochmkoch Ant-contrib Tasks: OutOfDate

OutOfDate

Task definition for the outofdate task. This is an extension of uptodate which allows multible targets and contains an embedded <parallel> or <sequential> element. If any of the target file's dates are earlier than any of the source file's dates, then the specified <parallel> or <sequential> block is executed. The task may also contain mappers to map source files to corresponding target files.

Parameters

Attribute

Description

Required

property

The name of the property to set to the contents of the value parameter if any of the target files are out of date

No

value

The value to set the property specified by the parameter property to, if any of the target files are out of date

No, defaults to "true"

force Force outofdate ("true"/"false"). Default is "false". No
verbose Set vebose logging level for this task ("true"/"false"). Default is "false". No

outputsources

The name of a property to set containing the sources that are newer that their corresponding targets.

No

outputtargets

The name of a property to set containing the targets that are outofDate with respect to their corresponding sources.

No

alltargets

The name of a property to set containing all the targets. This is usefull for debugging mapper nested elements.

No

separator

The separator used to separate the files in the properties above. If a filename contains the separator, double quotes will be placed aroudnd the filename.

No, defaults to “ “

outputsourcespath

The id of a path to create containing the source files that are outofdate.

No

outputtargetspath

The id of a path to create containing the target files that need to be updated.

No

alltargetspath

The id of a path to create containing all the target files.

No

Attributes specified as nested elements

sourcefiles - The list of files which are source files. This element is required.

targetfiles - The list of files which are target files.

Both of these nested elements are Path elements which are are used to select sets or lists of files or directories

The sourcefiles may contain no files. In this case, outofdate will check the existance of the targetfiles.

mapper – This is used to map source files to target files.

As well as the regular attributes for mapper, there is a extra attribute to specify the relative directory of the sources.

Attribute Description Required
dir The directory to the sources are relative to for the mapper. Default is ${base.dir}. No

There may be a number of mapper nested elements.

deletetargets – This is used to delete targets if the corresponding sources are outofdate.

Attribute Description Required
all Whether to delete all the targets ("true"/"false"). Defaults to "false". No
quiet Do not display diagnostic messages when deleting targets ("true"/ "false"). Defaults to false. When set to "true", if a file or directory cannot be deleted, no error is reported. This setting emulates the -f option to the Unix rm command. Default is "false". Setting this to "true" implies setting failonerror to "false" No
failonerror Controls whether an error (such as a failure to delete a file) stops the build or is merely reported to the screen. Only relevant if quiet is "false". Default is "true". Controls whether a failure to delete a target stops the build or is merely reported to the screen. No

Examples

The following example creates the file ${jrun.file} if is older that build.xml, or any file in ${lib.dir}.

        <outofdate>
          <sourcefiles>
            <pathelement path="build.xml"/>
            <fileset dir="${lib.dir}"/>
          </sourcefiles>
          <targetfiles path="${jrun.file}"/>
          <sequential>
            <mkdir dir="${build.bin.dir}"/>
            <echo file="${jrun.file}" message="java -cp ${jrun.path} $*"/>
            <chmod file="${jrun.file}" perm="ugo+rx"/>
          </sequential>
        </outofdate> 

The following example check the generated files, MODULE.IDS, acme_agent_mib.h, acme_agent_mib.cpp are older that miblist.txt, or any file in ${mib.src}, and if so an embedded shellScript is invoked to update the files.

        <outofdate>
          <sourcefiles>
            <pathelement path="${agent.src}/miblist.txt"/>
            <fileset dir="${mib.src}"/>
          </sourcefiles>
          <targetfiles>
            <pathelement path="${rep}/MODULE.IDS"/>
            <pathelement path="${gen-agent}/acme_agent_mib.h"/>
            <pathelement path="${gen-agent}/acme_agent_mib.cpp"/>
          </targetfiles>
          <sequential>
            <shellscript shell="bash" dir="${agent.src}">
                    classname=com.agentpp.agentgen.AgentGenConsole
                    h1=${gen-agent}/acme_agent_mib.x
                    ag() {
                        java -cp ${lib.dir}/agentgen.jar $classname ${rep} $@
                    }
                    ag initialize
                    ag load miblist.txt
                    ag generate ACME-AGENT-MIB h > $h1
                    (head -16 $h1; echo "using namespace Agentpp;";
                    tail +16 $h1) > ${gen-agent}/acme_agent_mib.h
                    ag generate ACME-AGENT-MIB c >\
                        ${gen-agent}/acme_agent_mib.cpp
            </shellscript>
          </sequential>
        </outofdate>

The following example sets the project manual.outofdate if any of the xml files are newer than index.html, or if any of the xml files are newer than their corresponding .html file. A path identified by sources.path, is created which contains the sources that fullfilled these conditions.

    <outofdate property="manual.outofdate" outputsourcespath="sources.path">
      <sourcefiles>
        <fileset dir="${src.manual}" includes="**/*.xml"/>
      </sourcefiles>
      <targetfiles path="${doc.manual}/index.html"/>
      <mapper type="glob" dir="${src.manual}" from="*.xml" to="${doc.manual}/*.html"/>
    </outofdate>

The following assumes that there is a program called gengrammer that takes a grammer file as an input and generates a .h and a .c file in the current directory.

  <outofdate property="manual.outofdate"
             outputsources="grammer.sources">
    <sourcefiles>
      <fileset dir="${src.grammer}" includes="**/*.y"/>
    </sourcefiles>
    <mapper type="glob" dir="${src.grammer}" from="*.y" to="${gen.grammer}/*.c"/>
    <mapper type="glob" dir="${src.grammer}" from="*.y" to="${gen.grammer}/*.h"/>
    <sequential>
      <shellscript shell="bash">
        cd ${gen.grammer}
        for g in ${grammer.sources}
        do
            gengrammer $g
        done
      </shellscript>
    </sequential>
  </outofdate>

Copyright © 2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/importurl.html0000755000175000017500000001720711257223261022532 0ustar mkochmkoch Ant-contrib Tasks: Importurl

Importurl

The Importurl task will download a file, and import it's contents into the current project. The file can be in the form of a standard ant .xml project file, or a .jar/.zip file.

In the case of an .xml file, the file is downloaded, and imported as is. In this case, the file itself is the only thing downloaded (ie. no corresponding .properties files, or other build files are downloaded).

In the case of a .jar/.zip file, the file is downloaded and then decompressed. After decompression, the file 'build.xml' at the root level of the jar is imported (the name of the imported file can be overriden with the 'resource' attribute). By importing a .jar/.zip file, one can package additional resources along with the build.xml file. However, you must be careful how you refer to these resources. The build.xml file must follow the same rules as any other file imported with the <import> task, in that references relative to the build.xml file must be made with the property: ant.file.<projectname> where <projectname> is the name of the project being imported, as specified in the project tag. Example:

    
    
        <project name="common">
            <dirname property="ant.dir.common" file="${ant.file.common}" />
            <property file="${ant.dir.common}/build.properties" />
        </project>
    
    

This task should be compatible with older versions of ant, but has only been tested with Ant 1.6.x. The underlying implementation is done using the Ivy dependency resolver software, and thus, it needs available to the same classloader that loads this task.

Parameters

Attribute Description Required
org The organization that publishes the script. Yes.
module The name of the module which is to be fetched. Yes.
rev The revision of the module to be fetched. No. Defaults to "latest.integration". See the ivy details for more information on the possible wildcarding that can be used for this value.
type The type of file to be downloaded No. Defaults to 'jar'. Can be any file extension. However, unless the type is 'xml', the file is assumed to be a compressed file, expandable by ant's <expand> task (which is aliased to unjar, unzip).
ivyConfUrl The URL of an ivy configuration file to use. We will use the default resolver in this file to find the requested resource. No. Defaults to the IvyRepResolver.
ivyConfFile The path of an ivy configuration file to use. We will use the default resolver in this file to find the requested resource. No. Defaults to the IvyRepResolver.
repositoryUrl The URL base of the repository to use. This results in using Ivy's URLResolver to resolve the requested resource. No. Defaults to the IvyRepResolver.
repositoryDir The file base of the repository to use. This results in using Ivy's FileSystemResolver to resolve the requested resource. No. Defaults to the IvyRepResolver.
artifactPattern The pattern used to find artifacts in the repository. No. If repositoryUrl or repositoryDir are specified, this defaults to the standard repository pattern: "/[org]/[module]/[ext]s/[module]-[revision].[ext]". Please see the ivy documentation for more information on the contents of this pattern.
ivyPattern The pattern used to find ivy file for the artifact in the repository. No. If repositoryUrl or repositoryDir are specified, this defaults to the standard repository pattern: "/[org]/[module]/ivy-[revision].xml". Please see the ivy documentation for more information on the contents of this pattern.
resource The name of the resource within a compressed file to import. No. Defaults to "build.xml".

Example

    
    <project name="build" basedir="." default="build" xmlns:ac="antlib:net.sf.antcontrib">
        <ac:antcontrib:importurl org="antcontrib"
                                 module="common"
                                 rev="3.2" />
    </project>
    
    
would look for the file "antcontrib/common/jars/common-3.2.jar" in the IvyRep repository.
    
    <ac:antcontrib:importurl org="antcontrib"
                             module="common"
                             rev="3.2" 
                             type="xml" />
    
    
would look for the file "antcontrib/common/jars/common-3.2.xml" in the IvyRep repository.
    
    <ac:antcontrib:importurl repositoryUrl="http://www.antcontrib.org/ivyrep"
                             org="antcontrib"
                             module="common"
                             rev="3.2" />
    
    
would look for the located at "http://www.antcontrib.org/ivyrep/antcontrib/common/jars/common-3.2.jar"
    
    <ac:antcontrib:importurl ivyConfUrl="http://ivyrep.myorg.com/ivyconf.xml"
                                org="antcontrib"
                                module="common"
                                rev="3.2" />
    
    
would configure ivy using the ivy configuration file at the given ivyConfUrl.

The following build.xml may be packaged into a .jar with it's corresponding build.properties file:

    
    <project name="common">
    <basedir property="ant.dir.common" file="${ant.file.common}" />
    <property file="${ant.dir.common}/build.properties" />
    </project>
    
    

Copyright © 2002-2006 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/assert_task.html0000644000175000017500000001344011257223261023010 0ustar mkochmkoch Assert Task

Assert Task

The Assert task adds an assertion capability to Ant projects. This task works in a manner very similar to the Java assert keyword, and provides a limited "design by contract" facility to Ant. This is very useful for testing build scripts prior to putting them into production.

The Assert task verifies that a particular boolean condition is met, and throws a BuildException if it is not.

Also like Java's assert keyword, the Assert task must be 'turned on' using the property ant.enable.asserts . If not set, or is set to false , the Assert task works exactly like the Sequential task. If the Variable task is used to define this property, then it can be turned on and off as needed throughout a build.

This task can hold other tasks including Assert.

Thie assert task may contain a single conditional element known by ANT, or one of the following additional conditions: IsPropertyTrue , IsPropertyFalse , StartsWith , EndsWith , IsGreaterThan , IsLessThan and conditions. See the If task for examples of using these conditionals.

Table 4.1. Assert Task Attributes

Attribute Description Default Required
name The name of the property to test for. This is a shortcut for specifying an <equals> condition. none No. However, if specified, the 'value' attribute must also be present
value The value to test for, implies . If the value in the project is different than this value, a BuildException will be thrown and the build will stop. none No, unless the 'name' attribute is specified.
execute Should the tasks contained in this task be executed? It may be useful to set this to false when testing build files. True No
failonerror Should the build halt if the assertion fails? Setting this to false is contrary to the intented use of assertions, but may be useful in certain situations. True No

Examples

In the following example, the first assert task checks that the wait property exists and does not execute the echo and sleep tasks. The second assert task checks that the wait property exists, has a value of 2, and executes the echo task.



     <property name="wait" value="2"/>
     <assert execute="false">
        <isset property="wait" />
        <sequential>
        <echo>
            Waiting ${wait} seconds...
            Click the red button to stop waiting.
            </echo>
            <sleep seconds="${wait}"/>
        </sequential>
     </assert>
     <assert name="wait" value="2" execute="true">
        <sequential>
            <echo>done waiting!</echo>
        </sequential>
     </assert>

The next example shows Assert being used in a unit test for the "limit" task:


  <property name="ant.enable.asserts" value="true"/>
  <target name="test2">
    <!-- should not stop 'sleep' task, should print out '_passed_' -->
    <stopwatch name="timer"/>
    <limit maxwait="5">
        <sleep seconds="1"/>
        <echo>_passed_</echo>
    </limit>
    <stopwatch name="timer" action="total"/>
    <assert message="Too much time.">
        <islessthan arg1="${timer}" arg2="2"/>
    </assert>
  </target>

If the ant.enable.asserts property is set to false, then in the above example, the echo , sleep , and echo tasks will all execute.


Copyright © 2003 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/relentless.html0000644000175000017500000001114711257223261022647 0ustar mkochmkoch Ant-contrib Tasks: Relentless

Relentless

The <relentless> task will execute all of the nested tasks, regardless of whether one or more of the nested tasks fails. When <relentless> has completed executing the nested tasks, it will either

  • fail, if any one or more of the nested tasks failed; or
  • succeed, if all of the nested tasks succeeded.
An appropriate message will be written to the log.

Tasks are executed in the order that they appear within the <relentless> task. It is up to the user to ensure that relentless execution of the nested tasks is safe.

This task only works for ant version greater than or equal to ant 1.6.0.

Parameters

Attribute Description Required
description A string that will be included in the log output. This can be useful for helping to identify sections of large Ant builds. No
terse Setting this to true will eliminate some of the progress output generated by <relentless>. This can reduce clutter in some cases. The default value is false. No

Nested elements

task list

The only nested element supported by <relentless> is a list of tasks to be executed. At least one task must be specified.

It is important to note that <relentless> only proceeds relentlessly from one task to the next - it does not apply recursively to any tasks that might be invoked by these nested tasks. If a nested task invokes some other list of tasks (perhaps by <antcall> for example), and one of those other tasks fails, then the nested task will stop at that point.

Example

A relentless task to print out the first five canonical variable names:

<relentless description="The first five canonical variable names.">
    <echo>foo</echo>
    <echo>bar</echo>
    <echo>baz</echo>
    <echo>bat</echo>
    <echo>blah</echo>
</relentless>
which should produce output looking more or less like
[relentless] Relentlessly executing: The first five canonical variable names.
[relentless] Executing: task 1
     [echo] foo
[relentless] Executing: task 2
     [echo] bar
[relentless] Executing: task 3
     [echo] baz
[relentless] Executing: task 4
     [echo] bat
[relentless] Executing: task 5
     [echo] blah
[relentless] All tasks completed successfully.

If you change the first line to set the terse parameter,
    <relentless terse="true" description="The first five canonical variable names."/>
the output will look more like this:
[relentless] Relentlessly executing: The first five canonical variable names.
     [echo] foo
     [echo] bar
     [echo] baz
     [echo] bat
     [echo] blah
[relentless] All tasks completed successfully.

If we change the third task to deliberately fail

<relentless terse="true" description="The first five canonical variable names.">
    <echo>foo</echo>
    <echo>bar</echo>
    <fail>baz</fail>
    <echo>bat</echo>
    <echo>blah</echo>
</relentless>
then the output should look something like this.
[relentless] Relentlessly executing: The first five canonical variable names.
     [echo] foo
     [echo] bar
[relentless] Task task 3 failed: baz
     [echo] bat
     [echo] blah

BUILD FAILED
/home/richter/firmware/sensor/build.xml:1177: Relentless execution: 1 of 5 tasks failed.


Copyright © 2005 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/foreach.html0000644000175000017500000001235011257223261022073 0ustar mkochmkoch Ant-contrib Tasks: Foreach

Foreach

The foreach task iterates over a list, a list of paths, or both. If both, list and paths, are specified, the list will be evaluated first. Nested paths are evaluated in the order they appear in the task.

Parameters

Attribute Description Required
list The list of values to process, with the delimiter character, indicated by the "delimiter" attribute, separating each value. Yes, unless a nested Fileset has been specified.
target Name of the target to call for each token or matched file. Yes
param Name of the parameter to pass the tokens or files in as to the target. Yes
delimiter The delimiter characters that separates the values in the "list" attribute. Each character in the supplied string can act as a delimiter. This follows the semantics of the StringTokenizer class. No, defaults to ",".
inheritall If true, pass all properties to the called target. Defaults to false. No
inheritrefs If true, pass all references to the the called target. Defaults to false. No
parallel If true, all instances of the called target will execute in parallel. Defaults to false, which forces sequential execution of the targets. It is up to the caller to ensure that parallel execution is safe. This is accomplished through the means of the "parallel" task contained in the ANT core. No
maxThreads The maximum number of allowable threads when executing in parallel. No. Defaults to 5.
trim If true, any leading or trailing whitespace will be removed from the list item before it is passed to the requested target No. Defaults to false.

Parameters specified as nested elements

path

Paths are used to select sets of files or directories to iterate over.

Using a path allows you to determine the order by which files are considered by using filelists or explicit pathelements. You also can specify whether you want to iterate over files or directories by chosing either filesets or dirsets.

fileset

FileSets are used to select sets of files to iterate over. This element is deprecated, use nested path elements instead.

param

Specifies the properties to set before running the specified target. See property for usage guidelines.

reference

Used to chose references that shall be copied into the new project, optionally changing their id.

Attribute Description Required
refid The id of the reference in the calling project. Yes
torefid The id of the reference in the called project. No, defaults to the value of refid.

Copyright © 2002-2004 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/tasks/verifynewprojtutorial.html0000644000175000017500000000304411257223261025161 0ustar mkochmkoch VerifyDesign New Project Tutorial

VerifyDesign New Project Tutorial

This is by far the easiest tutorial. Before you have any code, add this to your build.xml file.
    <verifydesign jar="yourjarname.jar"
                  design="design.xml" 
                  />
Create your design.xml file from the design that is in your head or in documentation like so
  <design>
     <package name="service1" package="biz.xsoftware.service1" subpackages="include"/>
     <package name="client1"  package="biz.xsoftware.client1"  depends="service1"/>
     <package name="service2" package="biz.xsoftware.service2"/>
     <package name="client2"  package="biz.xsoftware.client2"  depends="service2" subpackages="include"/>
  </design>
From now on, when you run the build, if this is violated like service1 depending on client2 or something, the build will fail and you will catch the errors of violating the design before it is too late. You can then guarantee things like only this package will depend on the JMS technology. This way if you change JMS to something later, you know you only have to change that one package.

Copyright © 2002-2004 Ant-Contrib Project. All rights Reserved.

ant-contrib-1.0~b3+svn177/docs/manual/index.html0000644000175000017500000000567211257223261020457 0ustar mkochmkoch Ant-Contrib Tasks

Ant-Contrib Tasks

Contents

What's this?

The Ant-Contrib project is a collection of tasks (and at one point maybe types and other tools) for Apache Ant.

This Software is distributed under the Apache Software License.

Installation

First you must install Apache Ant itself, most of the Ant-Contrib tasks require Ant 1.5 or higher to work properly, however, there are some tasks, specifically <for> which require Ant 1.6. You can download Ant from Apache.

Then you need the Ant-Contrib tasks themselves. As there is no release of these tasks yet, you have to build them from sources. Fortunately this is easy, check out the sources (grab the ant-contrib module from CVS), change into the source directory of ant-contrib and type ant. After Ant has completed, you'll find ant-contrib-version.jar in the lib subdirectory.

You now have the choice:

  1. Copy ant-contrib-version.jar to the lib directory of your Ant installation, or on your CLASSPATH environment variable. If you want to use one of the tasks in your project, add the line
    <taskdef resource="net/sf/antcontrib/antlib.xml"/>
    
    to your build file.


  2. Keep ant-contrib-version.jar in a separate location. You now have to tell Ant explicitly where to find it (say in /usr/share/java/lib):
    <taskdef resource="net/sf/antcontrib/antlib.xml">
      <classpath>
        <pathelement location="/usr/share/java/lib/ant-contrib-version.jar"/>
      </classpath>
    </taskdef>
    
  3. If you would like to use run with Ant Version 1.5 you must use the the .properties file instead. Keep in mind that some tasks will not be available to you , such as the <for> task:
    <taskdef resource="net/sf/antcontrib/antcontrib.properties">
      <classpath>
        <pathelement location="/usr/share/java/lib/ant-contrib-version.jar"/>
      </classpath>
    </taskdef>
    

    Copyright © 2002-2004 Ant-Contrib Project. All rights Reserved.

    ant-contrib-1.0~b3+svn177/docs/LICENSE.txt0000644000175000017500000000444011257223261017020 0ustar mkochmkoch/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 Ant-Contrib project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Ant-Contrib project (http://sourceforge.net/projects/ant-contrib)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The name Ant-Contrib must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact * ant-contrib-developers@lists.sourceforge.net. * * 5. Products derived from this software may not be called "Ant-Contrib" * nor may "Ant-Contrib" appear in their names without prior written * permission of the Ant-Contrib project. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE ANT-CONTRIB PROJECT OR ITS * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== */ ant-contrib-1.0~b3+svn177/ivy.xml0000644000175000017500000000315611257223261015601 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/pom.xml0000644000175000017500000002561611257223261015572 0ustar mkochmkoch 4.0.0 ant-contrib ant-contrib jar cpptasks 1.0b5-SNAPSHOT Ant-contrib tasks for Apache Ant http://ant-contrib.sourceforge.net:80 SourceForge Tracker http://sourceforge.net/tracker/?group_id=36177/ Gump http://vmgump.apache.org/gump/public/ant-contrib/index.html 2001 ant-contrib-cvs https://lists.sourceforge.net/lists/listinfo/ant-contrib-cvs https://lists.sourceforge.net/lists/listinfo/ant-contrib-cvs http://sourceforge.net/mailarchive/forum.php?forum_name=ant-contrib-cvs ant-contrib-developers http://lists.sourceforge.net/mailman/listinfo/ant-contrib-developers http://lists.sourceforge.net/mailman/listinfo/ant-contrib-developers ant-contrib-developers@lists.sourceforge.net http://sourceforge.net/mailarchive/forum.php?forum_name=ant-contrib-developers Ant-Contrib Project http://ant-contrib.sourceforge.net The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo scm:svn:https://ant-contrib.svn.sourceforge.net/svnroot/ant-contrib/ant-contrib/trunk scm:svn:https://ant-contrib.svn.sourceforge.net/svnroot/ant-contrib/ant-contrib/trunk http://ant-contrib.svn.sourceforge.net/viewvc/ant-contrib/ant-contrib/trunk/ maven-surefire-plugin plain **/IfTaskTest.java **/OutOfDateTest.java **/PropertySelectorTest.java **/AntclipseTest.java **/AntServerTest.java **/VerifyDesignTest.java maven-compiler-plugin 1.2 1.1 maven-jar-plugin net.sf.antcontrib.cpptasks Ant-contrib Tasks for Apache Ant. ${project.version} Ant-Contrib Project maven-antrun-plugin pre-site pre-site run site untag-site run ant ant-nodeps 1.6.5 maven-assembly-plugin src/assembly/bin.xml false assembly maven-javadoc-plugin jar maven-source-plugin jar org.codehaus.mojo clirr-maven-plugin 1.0b3 test/src test/resources ant ant 1.6.5 ant ant-launcher 1.6.5 test bcel bcel 5.1 xerces xercesImpl 2.8.1 commons-httpclient commons-httpclient 3.0.1 jayasoft ivy 1.4.1 junit junit 3.8.1 test true maven-project-info-reports-plugin scm cim javadoc issue-tracking mailing-list license maven-release-plugin site-deploy maven-changes-plugin changes-report http://sourceforge.net/tracker/index.php?func=detail&aid=%ISSUE%&group_id=36177&atid=416920 org.apache.maven.plugins maven-javadoc-plugin ant-contrib.repo scp://shell.sourceforge.net/home/groups/a/an/ant-contrib/htdocs/m2-repo cpptasks.site scp://shell.sourceforge.net/home/groups/a/an/ant-contrib/htdocs ant-contrib-1.0~b3+svn177/build.xml0000644000175000017500000002756611257223261016104 0ustar mkochmkoch ant-contrib-1.0~b3+svn177/src/0000755000175000017500000000000011257224415015034 5ustar mkochmkochant-contrib-1.0~b3+svn177/src/site/0000755000175000017500000000000011257224415016000 5ustar mkochmkochant-contrib-1.0~b3+svn177/src/site/site.xml0000644000175000017500000001206211257223261017465 0ustar mkochmkoch ant-contrib http://ant-contrib.sourceforge.net/ SourceForge.net Logo http://sflogo.sourceforge.net/sflogo.php?group_id=36177&type=5 http://www.sourceforge.net/ ant-contrib-1.0~b3+svn177/src/site/fml/0000755000175000017500000000000011257224415016556 5ustar mkochmkochant-contrib-1.0~b3+svn177/src/site/fml/faq.fml0000644000175000017500000000174511257223261020032 0ustar mkochmkoch A Question? An Answer. ant-contrib-1.0~b3+svn177/src/site/xdoc/0000755000175000017500000000000011257224415016735 5ustar mkochmkochant-contrib-1.0~b3+svn177/src/main/0000755000175000017500000000000011257224415015760 5ustar mkochmkochant-contrib-1.0~b3+svn177/src/main/java/0000755000175000017500000000000011257224415016701 5ustar mkochmkochant-contrib-1.0~b3+svn177/src/main/java/net/0000755000175000017500000000000011257224415017467 5ustar mkochmkochant-contrib-1.0~b3+svn177/src/main/java/net/sf/0000755000175000017500000000000011257224415020077 5ustar mkochmkochant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/0000755000175000017500000000000011257224415022242 5ustar mkochmkochant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/logic/0000755000175000017500000000000011257224415023337 5ustar mkochmkochant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/logic/Switch.java0000644000175000017500000001273011257223261025444 0ustar mkochmkoch/* * 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. * *
     *
     * Usage:
     *
     *   Task declaration in the project:
     *   
     *     <taskdef name="switch" classname="net.sf.antcontrib.logic.Switch" />
     *   
     *
     *   Task calling syntax:
     *    
     *     <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>
     *    
     *
     *
     *   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:
     *
     *     
     *     <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>
     *     
     *
     * 
    * * @author Matthew Inger * @author Stefan Bodewig */ 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 *
  4. "sources" the sources that are newer than the corresponding targets.
  5. *
  6. "targets" the targets that are older or not present than the corresponding * sources.
  7. *
  8. "allsources" all the sources
  9. *
  10. "alltargets" all the targets
  11. * * @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 or " + " into "); } 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 or " + " into "); } 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 element."); } if (targetpaths == null && mappers.size() == 0) { throw new BuildException( "You must specify a or 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(); if (paths.length == 0) { ret = true; } else { 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 MyMapper 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; } } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/logic/IfTask.java0000644000175000017500000001615111257223261025365 0ustar mkochmkoch/* * 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. * *

    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.

    * *

    This task doesn't have any attributes, the condition to test is * specified by a nested element - see the documentation of your * <condition> task (see * the * online documentation for example) for a complete list of nested * elements.

    * *

    Just like the <condition> task, only a single * condition can be specified - you combine them using * <and> or <or> conditions.

    * *

    In addition to the condition, you can specify three different * child elements, <elseif>, <then> and * <else>. All three subelements are optional. * * Both <then> and <else> must not be * used more than once inside the if task. Both are * containers for Ant tasks, just like Ant's * <parallel> and <sequential> * tasks - in fact they are implemented using the same class as Ant's * <sequential> task.

    * * The <elseif> behaves exactly like an <if> * except that it cannot contain the <else> 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 <if> is false, then the first * <elseif> who's conditional evaluates to true * will be executed. The <else> will be executed * only if the <if> and all <elseif> * conditions are false. * *

    Use the following task to define the <if> * task before you use it the first time:

    * *
    
     *   <taskdef name="if" classname="net.sf.antcontrib.logic.IfTask" />
     * 
    * *

    Crude Example

    * *
    
     * <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>
     * 
     *
     * 
     * <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>
     * 
    * * @author Stefan Bodewig */ 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 into "); } thenTasks = t; } public boolean eval() throws BuildException { if (countConditions() > 1) { throw new BuildException("You must not nest more than one condition into "); } if (countConditions() < 1) { throw new BuildException("You must nest a condition into "); } 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. * *

    Not required.

    */ public void addThen(Sequential t) { if (thenTasks != null) { throw new BuildException("You must not nest more than one into "); } thenTasks = t; } /** * A nested <else> element - a container of tasks that will * be run if the condition doesn't hold true. * *

    Not required.

    */ public void addElse(Sequential e) { if (elseTasks != null) { throw new BuildException("You must not nest more than one into "); } elseTasks = e; } public void execute() throws BuildException { if (countConditions() > 1) { throw new BuildException("You must not nest more than one condition into "); } if (countConditions() < 1) { throw new BuildException("You must nest a condition into "); } 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." ); } log("Relentlessly executing: " + this.getDescription()); Iterator iter = taskList.iterator(); while ( iter.hasNext() ) { Task t = (Task) iter.next(); taskNo++; String desc = t.getDescription(); if ( desc == null ) { desc = "task " + taskNo; } if (!terse) log("Executing: " + desc); try { t.perform(); } catch (BuildException x) { log("Task " + desc + " failed: " + x.getMessage()); failCount++; } } if ( failCount > 0 ) { throw new BuildException( "Relentless execution: " + failCount + " of " + taskList.size() + " tasks failed." ); } else { log("All tasks completed successfully."); } } /** Ant will call this to inform us of nested tasks. */ public void addTask(org.apache.tools.ant.Task task) { taskList.add(task); } /** Set this to true to reduce the amount of output generated. */ public void setTerse(boolean terse) { this.terse = terse; } /** Retrieve the terse property, indicating how much output we will generate. */ public boolean isTerse() { return terse; } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/logic/ProjectDelegate.java0000644000175000017500000002166211257223261027250 0ustar mkochmkochpackage net.sf.antcontrib.logic; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Hashtable; import java.util.Vector; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.BuildListener; import org.apache.tools.ant.Executor; import org.apache.tools.ant.Project; import org.apache.tools.ant.Target; import org.apache.tools.ant.Task; import org.apache.tools.ant.input.InputHandler; import org.apache.tools.ant.types.FilterSet; import org.apache.tools.ant.types.Path; public class ProjectDelegate extends Project { private Project delegate; private Project subproject; public ProjectDelegate(Project delegate) { super(); this.delegate = delegate; } public Project getSubproject() { return subproject; } public void addBuildListener(BuildListener arg0) { delegate.addBuildListener(arg0); } public void addDataTypeDefinition(String arg0, Class arg1) { delegate.addDataTypeDefinition(arg0, arg1); } public void addFilter(String arg0, String arg1) { delegate.addFilter(arg0, arg1); } public void addOrReplaceTarget(String arg0, Target arg1) { delegate.addOrReplaceTarget(arg0, arg1); } public void addOrReplaceTarget(Target arg0) { delegate.addOrReplaceTarget(arg0); } public void addReference(String arg0, Object arg1) { delegate.addReference(arg0, arg1); } public void addTarget(String arg0, Target arg1) throws BuildException { delegate.addTarget(arg0, arg1); } public void addTarget(Target arg0) throws BuildException { delegate.addTarget(arg0); } public void addTaskDefinition(String arg0, Class arg1) throws BuildException { delegate.addTaskDefinition(arg0, arg1); } public void checkTaskClass(Class arg0) throws BuildException { delegate.checkTaskClass(arg0); } public void copyFile(File arg0, File arg1, boolean arg2, boolean arg3, boolean arg4) throws IOException { delegate.copyFile(arg0, arg1, arg2, arg3, arg4); } public void copyFile(File arg0, File arg1, boolean arg2, boolean arg3) throws IOException { delegate.copyFile(arg0, arg1, arg2, arg3); } public void copyFile(File arg0, File arg1, boolean arg2) throws IOException { delegate.copyFile(arg0, arg1, arg2); } public void copyFile(File arg0, File arg1) throws IOException { delegate.copyFile(arg0, arg1); } public void copyFile(String arg0, String arg1, boolean arg2, boolean arg3, boolean arg4) throws IOException { delegate.copyFile(arg0, arg1, arg2, arg3, arg4); } public void copyFile(String arg0, String arg1, boolean arg2, boolean arg3) throws IOException { delegate.copyFile(arg0, arg1, arg2, arg3); } public void copyFile(String arg0, String arg1, boolean arg2) throws IOException { delegate.copyFile(arg0, arg1, arg2); } public void copyFile(String arg0, String arg1) throws IOException { delegate.copyFile(arg0, arg1); } public void copyInheritedProperties(Project arg0) { delegate.copyInheritedProperties(arg0); } public void copyUserProperties(Project arg0) { delegate.copyUserProperties(arg0); } public AntClassLoader createClassLoader(Path arg0) { return delegate.createClassLoader(arg0); } public Object createDataType(String arg0) throws BuildException { return delegate.createDataType(arg0); } public Task createTask(String arg0) throws BuildException { return delegate.createTask(arg0); } public int defaultInput(byte[] arg0, int arg1, int arg2) throws IOException { return delegate.defaultInput(arg0, arg1, arg2); } public void demuxFlush(String arg0, boolean arg1) { delegate.demuxFlush(arg0, arg1); } public int demuxInput(byte[] arg0, int arg1, int arg2) throws IOException { return delegate.demuxInput(arg0, arg1, arg2); } public void demuxOutput(String arg0, boolean arg1) { delegate.demuxOutput(arg0, arg1); } public boolean equals(Object arg0) { return delegate.equals(arg0); } public void executeSortedTargets(Vector arg0) throws BuildException { delegate.executeSortedTargets(arg0); } public void executeTarget(String arg0) throws BuildException { delegate.executeTarget(arg0); } public void executeTargets(Vector arg0) throws BuildException { delegate.executeTargets(arg0); } public void fireBuildFinished(Throwable arg0) { delegate.fireBuildFinished(arg0); } public void fireBuildStarted() { delegate.fireBuildStarted(); } public void fireSubBuildFinished(Throwable arg0) { delegate.fireSubBuildFinished(arg0); } public void fireSubBuildStarted() { delegate.fireSubBuildStarted(); } public File getBaseDir() { return delegate.getBaseDir(); } public Vector getBuildListeners() { return delegate.getBuildListeners(); } public ClassLoader getCoreLoader() { return delegate.getCoreLoader(); } public Hashtable getDataTypeDefinitions() { return delegate.getDataTypeDefinitions(); } public InputStream getDefaultInputStream() { return delegate.getDefaultInputStream(); } public String getDefaultTarget() { return delegate.getDefaultTarget(); } public String getDescription() { return delegate.getDescription(); } public String getElementName(Object arg0) { return delegate.getElementName(arg0); } public Executor getExecutor() { return delegate.getExecutor(); } public Hashtable getFilters() { return delegate.getFilters(); } public FilterSet getGlobalFilterSet() { return delegate.getGlobalFilterSet(); } public InputHandler getInputHandler() { return delegate.getInputHandler(); } public String getName() { return delegate.getName(); } public Hashtable getProperties() { return delegate.getProperties(); } public String getProperty(String arg0) { return delegate.getProperty(arg0); } public Object getReference(String arg0) { return delegate.getReference(arg0); } public Hashtable getReferences() { return delegate.getReferences(); } public Hashtable getTargets() { return delegate.getTargets(); } public Hashtable getTaskDefinitions() { return delegate.getTaskDefinitions(); } public Task getThreadTask(Thread arg0) { return delegate.getThreadTask(arg0); } public Hashtable getUserProperties() { return delegate.getUserProperties(); } public String getUserProperty(String arg0) { return delegate.getUserProperty(arg0); } public int hashCode() { return delegate.hashCode(); } public void init() throws BuildException { delegate.init(); } public void initSubProject(Project arg0) { delegate.initSubProject(arg0); this.subproject = arg0; } public boolean isKeepGoingMode() { return delegate.isKeepGoingMode(); } public void log(String arg0, int arg1) { delegate.log(arg0, arg1); } public void log(String arg0) { delegate.log(arg0); } public void log(Target arg0, String arg1, int arg2) { delegate.log(arg0, arg1, arg2); } public void log(Task arg0, String arg1, int arg2) { delegate.log(arg0, arg1, arg2); } public void registerThreadTask(Thread arg0, Task arg1) { delegate.registerThreadTask(arg0, arg1); } public void removeBuildListener(BuildListener arg0) { delegate.removeBuildListener(arg0); } public String replaceProperties(String arg0) throws BuildException { return delegate.replaceProperties(arg0); } public File resolveFile(String arg0, File arg1) { return delegate.resolveFile(arg0, arg1); } public File resolveFile(String arg0) { return delegate.resolveFile(arg0); } public void setBaseDir(File arg0) throws BuildException { delegate.setBaseDir(arg0); } public void setBasedir(String arg0) throws BuildException { delegate.setBasedir(arg0); } public void setCoreLoader(ClassLoader arg0) { delegate.setCoreLoader(arg0); } public void setDefault(String arg0) { delegate.setDefault(arg0); } public void setDefaultInputStream(InputStream arg0) { delegate.setDefaultInputStream(arg0); } public void setDefaultTarget(String arg0) { delegate.setDefaultTarget(arg0); } public void setDescription(String arg0) { delegate.setDescription(arg0); } public void setExecutor(Executor arg0) { delegate.setExecutor(arg0); } public void setFileLastModified(File arg0, long arg1) throws BuildException { delegate.setFileLastModified(arg0, arg1); } public void setInheritedProperty(String arg0, String arg1) { delegate.setInheritedProperty(arg0, arg1); } public void setInputHandler(InputHandler arg0) { delegate.setInputHandler(arg0); } public void setJavaVersionProperty() throws BuildException { delegate.setJavaVersionProperty(); } public void setKeepGoingMode(boolean arg0) { delegate.setKeepGoingMode(arg0); } public void setName(String arg0) { delegate.setName(arg0); } public void setNewProperty(String arg0, String arg1) { delegate.setNewProperty(arg0, arg1); } public void setProperty(String arg0, String arg1) { delegate.setProperty(arg0, arg1); } public void setSystemProperties() { delegate.setSystemProperties(); } public void setUserProperty(String arg0, String arg1) { delegate.setUserProperty(arg0, arg1); } public String toString() { return delegate.toString(); } }ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/logic/AntCallBack.java0000644000175000017500000004723511257223261026312 0ustar mkochmkoch/* * 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.
     *  <target name="foo" depends="init">
     *    <ant antfile="build.xml" target="bar" >
     *      <property name="property1" value="aaaaa" />
     *      <property name="foo" value="baz" />
     *    </ant> </target> <target name="bar"
     * depends="init"> <echo message="prop is ${property1}
     * ${foo}" /> </target> 
    *

    Developed for use with Antelope, migrated to ant-contrib Oct 2003. *

    Credit to Costin for the original <ant> task, on which this is based. * * @author costin@dnt.ro * @author Dale Anson, danson@germane-software.com * @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)project.getTaskDefinitions() .get( "property" ) ); } /** * Called in execute or createProperty if newProject is null.

    * * 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).

    * * Sets all properties that have been defined as nested property elements. *

    */ 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 = project.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 = project.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 = project.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 = project.getBaseDir(); } initializeProject(); if ( dir != null ) { newProject.setBaseDir( dir ); if ( savedDir != null ) { // has been set explicitly newProject.setInheritedProperty( "basedir", dir.getAbsolutePath() ); } } else { dir = project.getBaseDir(); } overrideProperties(); if ( antFile == null ) { throw new BuildException( "Attribute target is required.", location ); //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( project.getBaseDir() ) && newProject.getProperty( "ant.file" ).equals( project.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 ) { project.setUserProperty( name, value ); } else { value = newProject.getProperty( name ); if ( value != null ) { project.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)project.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.

    * * If we cannot clone it, copy the referenced object itself and keep our * fingers crossed.

    * * @param oldKey Description of the Parameter * @param newKey Description of the Parameter */ private void copyReference( String oldKey, String newKey ) { Object orig = project.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, location ); } } 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; } } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/logic/ForTask.java0000644000175000017500000003224511257223261025557 0ustar mkochmkoch/* * 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; private int begin = 0; private Integer end = null; private int step = 1; private int taskCount = 0; private int errorCount = 0; /** * Creates a new For instance. */ 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 true 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(); } /** * Set begin attribute. * @param begin the value to use. */ public void setBegin(int begin) { this.begin = begin; } /** * Set end attribute. * @param end the value to use. */ public void setEnd(Integer end) { this.end = end; } /** * Set step attribute. * */ public void setStep(int step) { this.step = step; } /** * 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 && end == null) { throw new BuildException( "You must have a list or path or sequence 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"); } if (end != null) { int iEnd = end.intValue(); if (step == 0) { throw new BuildException("step cannot be 0"); } else if (iEnd > begin && step < 0) { throw new BuildException("end > begin, step needs to be > 0"); } else if (iEnd <= begin && step > 0) { throw new BuildException("end <= begin, step needs to be < 0"); } } 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 doToken(String tok) { try { taskCount++; doSequentialIteration(tok); } catch (BuildException bx) { if (keepgoing) { log(tok + ": " + bx.getMessage(), Project.MSG_ERR); errorCount++; } else { throw bx; } } } private void doTheTasks() { errorCount = 0; taskCount = 0; // Create a macro attribute if (macroDef.getAttributes().isEmpty()) { 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(); } doToken(tok); } } // Take care of the begin/end/step attributes if (end != null) { int iEnd = end.intValue(); if (step > 0) { for (int i = begin; i < (iEnd + 1); i = i + step) { doToken("" + i); } } else { for (int i = begin; i > (iEnd - 1); i = i + step) { doToken("" + i); } } } // 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]); doToken(nextFile.getAbsolutePath()); } // Take care of iterators for (Iterator i = hasIterators.iterator(); i.hasNext();) { Iterator it = ((HasIterator) i.next()).iterator(); while (it.hasNext()) { doToken(it.next().toString()); } } 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 FileSet value */ public void add(FileSet fileset) { getOrCreatePath().addFileset(fileset); } /** * Add a fileset to be iterated over. * * @param fileset a FileSet value */ public void addFileSet(FileSet fileset) { add(fileset); } /** * Add a dirset to be iterated over. * * @param dirset a DirSet value */ public void add(DirSet dirset) { getOrCreatePath().addDirset(dirset); } /** * Add a dirset to be iterated over. * * @param dirset a DirSet value */ public void addDirSet(DirSet dirset) { add(dirset); } /** * Add a collection that can be iterated over. * * @param collection a Collection value. */ public void add(Collection collection) { hasIterators.add(new ReflectIterator(collection)); } /** * Add an iterator to be iterated over. * * @param iterator an Iterator 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); } } } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/logic/Assert.java0000644000175000017500000000627511257223261025453 0ustar mkochmkoch/* * 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 net.sf.antcontrib.logic.condition.BooleanConditionBase; 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; 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.Equals; /** * */ public class Assert extends BooleanConditionBase { private List tasks = new ArrayList(); private String message; private boolean failOnError = true; private boolean execute = true; private Sequential sequential; private String name; private String value; public Sequential createSequential() { this.sequential = (Sequential) getProject().createTask("sequential"); return this.sequential; } public void setName(String name) { this.name = name; } public void setValue(String value) { this.value = value; } public void setMessage(String message) { this.message = message; } public BooleanConditionBase createBool() { return this; } public void setExecute(boolean execute) { this.execute = execute; } public void setFailOnError(boolean failOnError) { this.failOnError = failOnError; } public void execute() { String use_asserts = getProject().getProperty("ant.enable.asserts"); boolean assertsEnabled = Project.toBoolean(use_asserts); if (assertsEnabled) { if (name != null) { if (value == null) { throw new BuildException("The 'value' attribute must accompany the 'name' attribute."); } String propVal = getProject().replaceProperties("${" + name + "}"); Equals e = new Equals(); e.setArg1(propVal); e.setArg2(value); addEquals(e); } 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."); } Condition c = (Condition) getConditions().nextElement(); if (! c.eval()) { if (failOnError) { Exit fail = (Exit) getProject().createTask("fail"); fail.setMessage(message); fail.execute(); } } else { if (execute && sequential != null) { this.sequential.execute(); } } } else { if (execute && sequential != null) { this.sequential.execute(); } } } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/logic/condition/0000755000175000017500000000000011257224415025325 5ustar mkochmkochant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/logic/condition/BooleanConditionBase.java0000644000175000017500000000341411257223261032211 0ustar mkochmkoch/* * 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.condition; import org.apache.tools.ant.taskdefs.condition.ConditionBase; /** * Extends ConditionBase so I can get access to the condition count and the * first condition. This is the class that the BooleanConditionTask is proxy * for. *

    Developed for use with Antelope, migrated to ant-contrib Oct 2003. * * @author Dale Anson, danson@germane-software.com */ public class BooleanConditionBase extends ConditionBase { /** * Adds a feature to the IsPropertyTrue attribute of the BooleanConditionBase * object * * @param i The feature to be added to the IsPropertyTrue attribute */ public void addIsPropertyTrue( IsPropertyTrue i ) { super.add( i ); } /** * Adds a feature to the IsPropertyFalse attribute of the * BooleanConditionBase object * * @param i The feature to be added to the IsPropertyFalse attribute */ public void addIsPropertyFalse( IsPropertyFalse i ) { super.add( i ); } public void addIsGreaterThan( IsGreaterThan i) { super.add(i); } public void addIsLessThan( IsLessThan i) { super.add(i); } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/logic/condition/IsPropertyFalse.java0000644000175000017500000000277311257223261031272 0ustar mkochmkoch/* * Copyright (c) 2001-2004, 2007 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.condition; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.ProjectComponent; import org.apache.tools.ant.taskdefs.condition.Condition; /** * Checks the value of a specified property. *

    Developed for use with Antelope, migrated to ant-contrib Oct 2003. * * @author Dale Anson, danson@germane-software.com * @version $Revision: 1.3 $ */ public final class IsPropertyFalse extends ProjectComponent implements Condition { private String name = null; public void setProperty(String name) { this.name = name; } public boolean eval() throws BuildException { if (name == null) throw new BuildException("Property name must be set."); String value = getProject().getProperty(name); return value == null || !getProject().toBoolean(value); } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/logic/condition/IsLessThan.java0000644000175000017500000000477511257223261030220 0ustar mkochmkoch/* * Copyright (c) 2001-2004, 2007 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.condition; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.taskdefs.condition.Condition; /** * Condition to test if the first argument is less than the * second argument. Will deal with base 10 integer and decimal numbers, otherwise, * treats arguments as Strings. *

    Developed for use with Antelope, migrated to ant-contrib Oct 2003. * * @author Dale Anson, danson@germane-software.com * @version $Revision: 1.4 $ */ public final class IsLessThan implements Condition { private String arg1, arg2; private boolean trim = false; private boolean caseSensitive = true; public void setArg1(String a1) { arg1 = a1; } public void setArg2(String a2) { arg2 = a2; } /** * Should we want to trim the arguments before comparing them? * * @since Revision: 1.3, Ant 1.5 */ public void setTrim(boolean b) { trim = b; } /** * Should the comparison be case sensitive? * * @since Revision: 1.3, Ant 1.5 */ public void setCasesensitive(boolean b) { caseSensitive = b; } public boolean eval() throws BuildException { if (arg1 == null || arg2 == null) { throw new BuildException("both arg1 and arg2 are required in " + "less than"); } if (trim) { arg1 = arg1.trim(); arg2 = arg2.trim(); } // check if args are numbers try { double num1 = Double.parseDouble(arg1); double num2 = Double.parseDouble(arg2); return num1 < num2; } catch(NumberFormatException nfe) { // ignored, fall thru to string comparision } return caseSensitive ? arg1.compareTo(arg2) < 0 : arg1.compareToIgnoreCase(arg2) < 0; } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/logic/condition/IsGreaterThan.java0000644000175000017500000000500611257223261030667 0ustar mkochmkoch/* * Copyright (c) 2001-2004, 2007 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.condition; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.taskdefs.condition.Condition; /** * Condition to test if the first argument is greater than the * second argument. Will deal with base 10 integer and decimal numbers, otherwise, * treats arguments as Strings. *

    Developed for use with Antelope, migrated to ant-contrib Oct 2003. * * @author Dale Anson, danson@germane-software.com * @version $Revision: 1.4 $ */ public final class IsGreaterThan implements Condition { private String arg1, arg2; private boolean trim = false; private boolean caseSensitive = true; public void setArg1(String a1) { arg1 = a1; } public void setArg2(String a2) { arg2 = a2; } /** * Should we want to trim the arguments before comparing them? * * @since Revision: 1.3, Ant 1.5 */ public void setTrim(boolean b) { trim = b; } /** * Should the comparison be case sensitive? * * @since Revision: 1.3, Ant 1.5 */ public void setCasesensitive(boolean b) { caseSensitive = b; } public boolean eval() throws BuildException { if (arg1 == null || arg2 == null) { throw new BuildException("both arg1 and arg2 are required in " + "greater than"); } if (trim) { arg1 = arg1.trim(); arg2 = arg2.trim(); } // check if args are numbers try { double num1 = Double.parseDouble(arg1); double num2 = Double.parseDouble(arg2); return num1 > num2; } catch(NumberFormatException nfe) { // ignored, fall thru to string comparision } return caseSensitive ? arg1.compareTo(arg2) > 0 : arg1.compareToIgnoreCase(arg2) > 0; } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/logic/condition/IsPropertyTrue.java0000644000175000017500000000276411257223261031157 0ustar mkochmkoch/* * Copyright (c) 2001-2004, 2007 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.condition; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.ProjectComponent; import org.apache.tools.ant.taskdefs.condition.Condition; /** * Checks the value of a specified property. *

    Developed for use with Antelope, migrated to ant-contrib Oct 2003. * * @author Dale Anson, danson@germane-software.com * @version $Revision: 1.3 $ */ public final class IsPropertyTrue extends ProjectComponent implements Condition { private String name = null; public void setProperty( String name ) { this.name = name; } public boolean eval() throws BuildException { if ( name == null ) throw new BuildException( "Property name must be set." ); String value = getProject().getProperty( name ); return value != null && getProject().toBoolean( value ); } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/logic/ForEach.java0000644000175000017500000002706011257223261025514 0ustar mkochmkoch/* * 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. * *

     *
     * Usage:
     *
     *   Task declaration in the project:
     *   
     *     <taskdef name="foreach" classname="net.sf.antcontrib.logic.ForEach" />
     *   
     *
     *   Call Syntax:
     *   
     *     <foreach list="values" target="targ" param="name"
     *                 [parallel="true|false"]
     *                 [delimiter="delim"] />
     *   
     *
     *   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?
     *
     * 
    * @author Matthew Inger */ 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 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 <antcall>'s inheritall * attribute. */ public void setInheritall(boolean b) { this.inheritAll = b; } /** * Corresponds to <antcall>'s inheritrefs * 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 <antcall>'s nested * <param> element. */ public void addParam(Property p) { params.addElement(p); } /** * Corresponds to <antcall>'s nested * <reference> 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); } } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/logic/AntFetch.java0000644000175000017500000000520211257223261025673 0ustar mkochmkoch/* * 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.StringTokenizer; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Ant; /** * Subclass of CallTarget which allows us to fetch * properties which are set in the scope of the called * target, and set them in the scope of the calling target. * Normally, these properties are thrown away as soon as the * called target completes execution. * * @author inger * @author Dale Anson, danson@germane-software.com */ public class AntFetch extends Ant { /** the name of the property to fetch from the new project */ private String returnName = null; private ProjectDelegate fakeProject = null; public void setProject(Project realProject) { fakeProject = new ProjectDelegate(realProject); super.setProject(fakeProject); } /** * Do the execution. * * @exception BuildException Description of the Exception */ public void execute() throws BuildException { super.execute(); // copy back the props if possible if ( returnName != null ) { StringTokenizer st = new StringTokenizer( returnName, "," ); while ( st.hasMoreTokens() ) { String name = st.nextToken().trim(); String value = fakeProject.getSubproject().getUserProperty( name ); if ( value != null ) { getProject().setUserProperty( name, value ); } else { value = fakeProject.getSubproject().getProperty( name ); if ( value != null ) { getProject().setProperty( name, value ); } } } } } /** * 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; } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/logic/Throw.java0000644000175000017500000000311011257223261025276 0ustar mkochmkoch/* * 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 <fail> that can throw an exception * that is a reference in the project. * *

    This may be useful inside the <catch> block * of a <trycatch> task if you want to rethrow the * exception just caught.

    */ 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(); } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/logic/TimestampSelector.java0000644000175000017500000001731311257223261027651 0ustar mkochmkoch/* * 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. * *
     *
     * Usage:
     *
     *   Task declaration in the project:
     *   
     *     <taskdef name="latesttimestamp" classname="net.sf.antcontrib.logic.TimestampSelector" />
     *   
     *
     *   Call Syntax:
     *   
     *     <timestampselector
     *                 [property="prop" | outputsetref="id"]
     *                 [count="num"]
     *                 [age="eldest|youngest"]
     *                 [pathSep=","]
     *                 [pathref="ref"] >
     *       <path>
     *          ...
     *       </path>
     *     </latesttimestamp>
     *   
     *
     *   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.
     *
     * 
    * @author Matthew Inger */ 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;iThis mirrors Java's try/catch/finally.

    * *

    The tasks inside of the required <try> * element will be run. If one of them should throw a {@link * org.apache.tools.ant.BuildException BuildException} several things * can happen:

    * *
      *
    • If there is no <catch> block, the * exception will be passed through to Ant.
    • * *
    • If the property attribute has been set, a property of the * given name will be set to the message of the exception.
    • * *
    • If the reference attribute has been set, a reference of the * given id will be created and point to the exception object.
    • * *
    • If there is a <catch> block, the tasks * nested into it will be run.
    • *
    * *

    If a <finally> block is present, the task * nested into it will be run, no matter whether the first tasks have * thrown an exception or not.

    * *

    Attributes:

    * * * * * * * * * * * * * * * * * *
    NameDescriptionRequired
    propertyName of a property that will receive the message of the * exception that has been caught (if any)No
    referenceId of a reference that will point to the exception object * that has been caught (if any)No
    * *

    Use the following task to define the <trycatch> * task before you use it the first time:

    * *
    
     *   <taskdef name="trycatch" 
     *            classname="net.sf.antcontrib.logic.TryCatchTask" />
     * 
    * *

    Crude Example

    * *
    
     * <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>
     * 
    * *

    results in

    * *
    
     *   [trycatch] Caught exception: Tada!
     *       [echo] In <catch>.
     *       [echo] In <finally>.
     *       [echo] As property: Tada!
     *       [echo] From reference: Tada!
     * 
    * * @author Stefan Bodewig * @author Dan Ritchey */ 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 "); } 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 "); } 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 { Throwable thrown = null; if (tryTasks == null) { throw new BuildException("A nested 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); } if (! executed) { thrown = e; } } finally { if (finallyTasks != null) { finallyTasks.perform(); } } if (thrown != null) { throw new BuildException(thrown); } } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/logic/RunTargetTask.java0000644000175000017500000000266211257223261026744 0ustar mkochmkoch/* * 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 nicolaken@apache.org */ 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); } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/antclipse/0000755000175000017500000000000011257224415024224 5ustar mkochmkochant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/antclipse/ClassPathTask.java0000644000175000017500000003136411257223260027600 0ustar mkochmkoch/* * 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 aspinei@myrealbox.com * @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)); } } } } } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/antclipse/ClassPathParser.java0000644000175000017500000000635111257223260030130 0ustar mkochmkoch/* * 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 aspinei@myrealbox.com * @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 } } } } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/design/0000755000175000017500000000000011257224415023513 5ustar mkochmkochant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/design/VerifyDesign.java0000644000175000017500000000361211257223261026754 0ustar mkochmkoch/* * 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(); } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/design/Design.java0000644000175000017500000003160011257223261025565 0ustar mkochmkoch/* * 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.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Vector; import net.sf.antcontrib.logic.ProjectDelegate; 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(dean@xsoftware.biz) */ 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.setUsed(true); 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"); String currentPackage = thePackage; Package result = (Package)packageNameToPackage.get(currentPackage); while(!Package.DEFAULT.equals(currentPackage)) { log.log("p="+currentPackage+"result="+result, Project.MSG_DEBUG); if(result != null) { if(currentPackage.equals(thePackage)) return result; else if(result.isIncludeSubpackages()) return result; return null; } currentPackage = VerifyDesignDelegate.getPackageName(currentPackage); result = (Package)packageNameToPackage.get(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); } /** * @param className Class name of a class our currentAliasPackage depends on. */ public void verifyDependencyOk(String className) { log.log(" className="+className, Project.MSG_DEBUG); if(className.startsWith("L")) className = className.substring(1, className.length()); //get the classPackage our currentAliasPackage depends on.... 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) { throw new BuildException(getErrorMessage(currentClass, className), location); } p.setUsed(true); //set package to used since we have classes in it 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)) { temp.setUsed(true); //set package to used since we are depending on it(could be external package like junit) currentAliasPackage.addUsedDependency(d); 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); } currentAliasPackage.setUsed(true); } log.log(" class="+className, Project.MSG_VERBOSE); if(packageName.equals(Package.DEFAULT)) { if(className.indexOf('.') != -1) { throw new RuntimeException("Internal Error"); } } else 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; } /** * @param designErrors */ public void fillInUnusedPackages(Vector designErrors) { Collection values = nameToPackage.values(); Iterator iterator = values.iterator(); while(iterator.hasNext()) { Package pack = (Package)iterator.next(); if(!pack.isUsed()) { String msg = "Package name="+pack.getName()+" is unused. Full package="+pack.getPackage(); log.log(msg, Project.MSG_ERR); designErrors.add(new BuildException(msg)); } else { fillInUnusedDepends(designErrors, pack); } } } /** * @param designErrors * @param pack */ private void fillInUnusedDepends(Vector designErrors, Package pack) { Iterator iterator = pack.getUnusedDepends().iterator(); while(iterator.hasNext()) { Depends depends = (Depends)iterator.next(); String msg = "Package name="+pack.getName()+" has a dependency declared that is not true anymore. Please erase the dependency "+depends.getName()+" from package="+pack.getName(); log.log(msg, Project.MSG_ERR); designErrors.add(new BuildException(msg)); } } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/design/Depends.java0000644000175000017500000000206011257223261025734 0ustar mkochmkoch/* * 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; } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/design/Package.java0000644000175000017500000000617011257223261025713 0ustar mkochmkoch/* * 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.HashSet; import java.util.List; import java.util.Set; /* * 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(dean@xsoftware.biz) */ 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 Set unusedDepends = new HashSet(); private boolean isIncludeSubpackages; private boolean needDeclarations; private boolean needDepends; private boolean isUsed = false; 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); unusedDepends.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; } /** * @param b */ public void setUsed(boolean b) { isUsed = b; } public boolean isUsed() { return isUsed; } /** * @param d */ public void addUsedDependency(Depends d) { unusedDepends.remove(d); } public Set getUnusedDepends() { return unusedDepends; } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/design/VisitorImpl.java0000644000175000017500000001446311257223261026645 0ustar mkochmkoch/* * 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; } }ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/design/DesignFileHandler.java0000644000175000017500000003151611257223261027671 0ustar mkochmkoch/* * 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 null * if none is available. Ignored in this * implementation. * @param systemId The system identifier provided in the XML * document. Will not be null. */ 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 null. */ 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 { } }ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/design/InstructionVisitor.java0000644000175000017500000000750311257223261030262 0ustar mkochmkoch/* * 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); } }ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/design/VerifyDesignDelegate.java0000644000175000017500000003752711257223261030423 0ustar mkochmkoch/* * 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); } //only put unused errors if there are no other errors //this is because you end up with false unused errors if you don't do this. if(designErrors.isEmpty()) design.fillInUnusedPackages(designErrors); 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 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); } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/design/Log.java0000644000175000017500000000144011257223261025074 0ustar mkochmkoch/* * 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); } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/net/0000755000175000017500000000000011257224415023030 5ustar mkochmkochant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/net/PostTask.java0000644000175000017500000006547711257223260025463 0ustar mkochmkoch/* * 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, danson@germane-software.com * @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).

    * * 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(); } } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/net/Ivy20Adapter.java0000644000175000017500000000740211257223260026105 0ustar mkochmkochpackage net.sf.antcontrib.net; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.apache.ivy.ant.IvyConfigure; import org.apache.ivy.ant.IvyCacheFileset; import org.apache.tools.ant.BuildException; public class Ivy20Adapter implements IvyAdapter { public void configure(URLImportTask task) { IvyConfigure configure = new IvyConfigure(); configure.setProject(task.getProject()); configure.setLocation(task.getLocation()); configure.setOwningTarget(task.getOwningTarget()); configure.setTaskName(task.getTaskName()); configure.setOverride("true"); configure.setSettingsId("urlimporttask"); configure.init(); URL ivyConfUrl = task.getIvyConfUrl(); File ivyConfFile = task.getIvyConfFile(); String repositoryUrl = task.getRepositoryUrl(); File repositoryDir = task.getRepositoryDir(); String ivyPattern = task.getIvyPattern(); String artifactPattern = task.getArtifactPattern(); if (ivyConfUrl != null) { if (ivyConfUrl.getProtocol().equalsIgnoreCase("file")) { String path = ivyConfUrl.getPath(); File f = new File(path); if (! f.isAbsolute()) { f = new File(task.getProject().getBaseDir(), path); } configure.setFile(f); } else { try { configure.setUrl(ivyConfUrl.toExternalForm()); } catch (MalformedURLException e) { throw new BuildException(e); } } } else if (ivyConfFile != null) { configure.setFile(ivyConfFile); } else if (repositoryDir != null || repositoryUrl != null) { File temp = null; FileWriter fw = null; try { temp = File.createTempFile("ivyconf", ".xml"); temp.deleteOnExit(); fw = new FileWriter(temp); fw.write(""); fw.write(""); fw.write(""); if (repositoryDir != null) { fw.write(""); fw.write(""); fw.write(""); fw.write(""); } else { fw.write(""); fw.write(""); fw.write(""); fw.write(""); } fw.write(""); fw.write(""); fw.write(""); fw.write(""); fw.write(""); fw.close(); fw = null; configure.setFile(temp); } catch (IOException e) { throw new BuildException(e); } finally { try { if (fw != null) { fw.close(); fw = null; } } catch (IOException e) { ; } } } //task.getProject().addReference("urlimporttask", configure); configure.execute(); } public void fileset(URLImportTask task, String setId) { String org = task.getOrg(); String module = task.getModule(); String rev = task.getRev(); String conf = task.getConf(); IvyCacheFileset cacheFileSet = new IvyCacheFileset(); cacheFileSet.setProject(task.getProject()); cacheFileSet.setLocation(task.getLocation()); cacheFileSet.setOwningTarget(task.getOwningTarget()); cacheFileSet.setTaskName(task.getTaskName()); cacheFileSet.setInline(true); cacheFileSet.setOrganisation(org); cacheFileSet.setModule(module); cacheFileSet.setRevision(rev); cacheFileSet.setConf(conf); cacheFileSet.init(); cacheFileSet.setSetid(setId); cacheFileSet.setSettingsRef( new org.apache.tools.ant.types.Reference(task.getProject(), "urlimporttask")); cacheFileSet.execute(); } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/net/Ivy14Adapter.java0000644000175000017500000000671711257223260026120 0ustar mkochmkochpackage net.sf.antcontrib.net; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.apache.tools.ant.BuildException; import fr.jayasoft.ivy.ant.IvyCacheFileset; import fr.jayasoft.ivy.ant.IvyConfigure; public class Ivy14Adapter implements IvyAdapter { public void configure(URLImportTask task) { IvyConfigure configure = new IvyConfigure(); configure.setProject(task.getProject()); configure.setLocation(task.getLocation()); configure.setOwningTarget(task.getOwningTarget()); configure.setTaskName(task.getTaskName()); configure.init(); URL ivyConfUrl = task.getIvyConfUrl(); File ivyConfFile = task.getIvyConfFile(); String repositoryUrl = task.getRepositoryUrl(); File repositoryDir = task.getRepositoryDir(); String ivyPattern = task.getIvyPattern(); String artifactPattern = task.getArtifactPattern(); if (ivyConfUrl != null) { if (ivyConfUrl.getProtocol().equalsIgnoreCase("file")) { String path = ivyConfUrl.getPath(); File f = new File(path); if (! f.isAbsolute()) { f = new File(task.getProject().getBaseDir(), path); } configure.setFile(f); } else { try { configure.setUrl(ivyConfUrl.toExternalForm()); } catch (MalformedURLException e) { throw new BuildException(e); } } } else if (ivyConfFile != null) { configure.setFile(ivyConfFile); } else if (repositoryDir != null || repositoryUrl != null) { File temp = null; FileWriter fw = null; try { temp = File.createTempFile("ivyconf", ".xml"); temp.deleteOnExit(); fw = new FileWriter(temp); fw.write(""); fw.write(""); fw.write(""); if (repositoryDir != null) { fw.write(""); fw.write(""); fw.write(""); fw.write(""); } else { fw.write(""); fw.write(""); fw.write(""); fw.write(""); } fw.write(""); fw.write(""); fw.write(""); fw.write(""); fw.write(""); fw.close(); fw = null; configure.setFile(temp); } catch (IOException e) { throw new BuildException(e); } finally { try { if (fw != null) { fw.close(); fw = null; } } catch (IOException e) { ; } } } configure.execute(); } public void fileset(URLImportTask task, String setId) { String org = task.getOrg(); String module = task.getModule(); String rev = task.getRev(); String conf = task.getConf(); IvyCacheFileset cacheFileSet = new IvyCacheFileset(); cacheFileSet.setProject(task.getProject()); cacheFileSet.setLocation(task.getLocation()); cacheFileSet.setOwningTarget(task.getOwningTarget()); cacheFileSet.setTaskName(task.getTaskName()); cacheFileSet.setInline(true); cacheFileSet.setOrganisation(org); cacheFileSet.setModule(module); cacheFileSet.setRevision(rev); cacheFileSet.setConf(conf); cacheFileSet.init(); cacheFileSet.setSetid(setId); cacheFileSet.execute(); } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/net/IvyAdapter.java0000644000175000017500000000022611257223260025740 0ustar mkochmkochpackage net.sf.antcontrib.net; public interface IvyAdapter { void configure(URLImportTask task); void fileset(URLImportTask task, String setId); } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/net/httpclient/0000755000175000017500000000000011257224415025206 5ustar mkochmkochant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/net/httpclient/MethodParams.java0000644000175000017500000000362711257223260030442 0ustar mkochmkoch/* * Copyright (c) 2001-2006 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.httpclient; import org.apache.commons.httpclient.HttpVersion; import org.apache.commons.httpclient.ProtocolException; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.tools.ant.BuildException; public class MethodParams extends HttpMethodParams { private static final long serialVersionUID = -1; public void setStrict(boolean strict) { if (strict) { makeStrict(); } else { makeLenient(); } } public void setVersion(String version) { try { setVersion(HttpVersion.parse(version)); } catch (ProtocolException e) { throw new BuildException(e); } } public void addConfiguredDouble(Params.DoubleParam param) { setDoubleParameter(param.getName(), param.getValue()); } public void addConfiguredInt(Params.IntParam param) { setIntParameter(param.getName(), param.getValue()); } public void addConfiguredLong(Params.LongParam param) { setLongParameter(param.getName(), param.getValue()); } public void addConfiguredString(Params.StringParam param) { setParameter(param.getName(), param.getValue()); } public void addConfiguredBoolean(Params.BooleanParam param) { setBooleanParameter(param.getName(), param.getValue()); } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/net/httpclient/ClearCookiesTask.java0000644000175000017500000000165311257223260031241 0ustar mkochmkoch/* * Copyright (c) 2001-2006 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.httpclient; import org.apache.tools.ant.BuildException; public class ClearCookiesTask extends AbstractHttpStateTypeTask { protected void execute(HttpStateType stateType) throws BuildException { stateType.getState().clearCookies(); } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/net/httpclient/PostMethodTask.java0000644000175000017500000001435111257223260030763 0ustar mkochmkoch/* * Copyright (c) 2001-2006 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.httpclient; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.InputStreamRequestEntity; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.StringPart; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.util.FileUtils; public class PostMethodTask extends AbstractMethodTask { private List parts = new ArrayList(); private boolean multipart; private transient FileInputStream stream; public static class FilePartType { private File path; private String contentType = FilePart.DEFAULT_CONTENT_TYPE; private String charSet = FilePart.DEFAULT_CHARSET; public File getPath() { return path; } public void setPath(File path) { this.path = path; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public String getCharSet() { return charSet; } public void setCharSet(String charSet) { this.charSet = charSet; } } public static class TextPartType { private String name = ""; private String value = ""; private String charSet = StringPart.DEFAULT_CHARSET; private String contentType = StringPart.DEFAULT_CONTENT_TYPE; public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCharSet() { return charSet; } public void setCharSet(String charSet) { this.charSet = charSet; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public void setText(String text) { this.value = text; } } public void addConfiguredFile(FilePartType file) { this.parts.add(file); } public void setMultipart(boolean multipart) { this.multipart = multipart; } public void addConfiguredText(TextPartType text) { this.parts.add(text); } public void setParameters(File parameters) { PostMethod post = getPostMethod(); Properties p = new Properties(); Iterator it = p.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); post.addParameter(entry.getKey().toString(), entry.getValue().toString()); } } protected HttpMethodBase createNewMethod() { return new PostMethod(); } private PostMethod getPostMethod() { return ((PostMethod)createMethodIfNecessary()); } public void addConfiguredParameter(NameValuePair pair) { getPostMethod().setParameter(pair.getName(), pair.getValue()); } public void setContentChunked(boolean contentChunked) { getPostMethod().setContentChunked(contentChunked); } protected void configureMethod(HttpMethodBase method) { PostMethod post = (PostMethod) method; if (parts.size() == 1 && ! multipart) { Object part = parts.get(0); if (part instanceof FilePartType) { FilePartType filePart = (FilePartType)part; try { stream = new FileInputStream( filePart.getPath().getAbsolutePath()); post.setRequestEntity( new InputStreamRequestEntity(stream, filePart.getPath().length(), filePart.getContentType())); } catch (IOException e) { throw new BuildException(e); } } else if (part instanceof TextPartType) { TextPartType textPart = (TextPartType)part; try { post.setRequestEntity( new StringRequestEntity(textPart.getValue(), textPart.getContentType(), textPart.getCharSet())); } catch (UnsupportedEncodingException e) { throw new BuildException(e); } } } else if (! parts.isEmpty()){ Part partArray[] = new Part[parts.size()]; for (int i=0;i 0) { Property p = (Property)getProject().createTask("property"); p.setName(property); p.setValue(matches[0].getValue()); p.perform(); } } else if (prefix != null) { if (matches != null && matches.length > 0) { for (int i=0;iDeveloped for use with Antelope, migrated to ant-contrib Oct 2003. * * @author Dale Anson, danson@germane-software.com * @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; } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/math/0000755000175000017500000000000011257224415023173 5ustar mkochmkochant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/math/Operation.java0000644000175000017500000001143011257223261025773 0ustar mkochmkoch/* * 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 + "]"; } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/math/Math.java0000644000175000017500000004712011257223261024731 0ustar mkochmkoch/* * 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); } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/math/Numeric.java0000644000175000017500000000511311257223261025436 0ustar mkochmkoch/* * 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 + "]"; } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/math/MathTask.java0000644000175000017500000000643211257223261025555 0ustar mkochmkoch/* * 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) { getLocalOperation().setArg1(operand1); } public void setOperand2(String operand2) { getLocalOperation().setArg2(operand2); } public Operation createOperation() { if (locOperation != null || operation != null) throw new BuildException("Only 1 operation can be specified"); this.operation = new Operation(); this.operation.setStrict(strict); this.operation.setDatatype(datatype); return this.operation; } // conform to old task public Operation createOp() { return createOperation(); } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/math/Evaluateable.java0000644000175000017500000000145011257223261026426 0ustar mkochmkoch/* * 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(); } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/util/0000755000175000017500000000000011257224415023217 5ustar mkochmkochant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/util/Reflector.java0000644000175000017500000001513311257223261026010 0ustar mkochmkoch/* * 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); } } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/util/ThreadPoolThread.java0000644000175000017500000000306611257223261027256 0ustar mkochmkoch/* * 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 Matthew Inger * ****************************************************************************/ 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; } } } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/util/ThreadPool.java0000644000175000017500000000312011257223261026115 0ustar mkochmkoch/* * 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 Matthew Inger * ****************************************************************************/ 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); } } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/property/0000755000175000017500000000000011257224415024126 5ustar mkochmkochant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/property/PathToFileSet.java0000644000175000017500000000721011257223260027441 0ustar mkochmkoch/* * 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()); } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/property/RegexUtil.java0000644000175000017500000001074511257223260026705 0ustar mkochmkoch/* * 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 Matthew Inger * ****************************************************************************/ 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 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(); } } ant-contrib-1.0~b3+svn177/src/main/java/net/sf/antcontrib/property/PathFilterTask.java0000644000175000017500000000516111257223260027656 0ustar mkochmkoch/* * 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