diff --git a/proposal/sandbox/antlib/.cvsignore b/proposal/sandbox/antlib/.cvsignore deleted file mode 100644 index 9d0b71a3c..000000000 --- a/proposal/sandbox/antlib/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -build -dist diff --git a/proposal/sandbox/antlib/README b/proposal/sandbox/antlib/README deleted file mode 100644 index 23823cf0a..000000000 --- a/proposal/sandbox/antlib/README +++ /dev/null @@ -1,18 +0,0 @@ -There are the following features in the antlib proposal: - - 1) antlib & antjar - 2) type definitions that allow to define new implementations of mappers, selectors, paths, conditions, etc. That you can define in your antlib and a way to link this with the introspectors (I am not sure how complete this is). - 3) A scoping framework for the symbol tables needed to manage the antlib definitions (I think ANT has something on this regard) - 4) A framework for managing classloaders where you can specify which classloader to use when loading an antlib. - -(2) would be really nice, because it will eliminate all the need for mentioning classnames all around, antlibs will be used just like core. -Also useful for tasks like which has vendor specific components that should be part of the antlib of the vendor. - -(3) Probably should die and be replaced by whatever scoping thing comes from proposal. - -(4) This was probably what killed the last time around. Probably needs to be treated separately. In any case, if you load -multiple antlibs with dependencies, there has t be a way to make them share the same classloader otherwise you cannot use it. - -So there we go, take a look at the code and let us know what you think, - -Jose Alberto & Antoine diff --git a/proposal/sandbox/antlib/build.xml b/proposal/sandbox/antlib/build.xml deleted file mode 100644 index b6db7a3ec..000000000 --- a/proposal/sandbox/antlib/build.xml +++ /dev/null @@ -1,106 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/proposal/sandbox/antlib/docs/manual/CoreTasks/antjar.html b/proposal/sandbox/antlib/docs/manual/CoreTasks/antjar.html deleted file mode 100644 index ee6a4a130..000000000 --- a/proposal/sandbox/antlib/docs/manual/CoreTasks/antjar.html +++ /dev/null @@ -1,102 +0,0 @@ - - - - -Ant User Manual - - - - -

AntJar

-

Description

-

An extension of the Jar task with special -treatment for the library descriptor file that should end up in the -META-INF directory of the Ant Archive.

-

-Descriptors must follow the following rules, although there is no fix DTD -for them: -

-
-<!-- Root element for the Antlib descriptor.                 -->
-<!ELEMENT antlib (role | rolename)* >
-
-<!-- Declaration of roles contained in the library.          -->
-<!ELEMENT role EMPTY>
-<!ATTLIST role 
-          name     CDATA #REQUIRED
-          class    CDATA #REQUIRED
-          proxy    CDATA #IMPLIED
->
-
-<!-- Declaration of datatypes contained in the library       -->
-<!ELEMENT rolename EMPTY>
-<!ATTLIST rolename 
-          name     CDATA #REQUIRED
-          class    CDATA #REQUIRED
->
-
-
-There are two predefined roles: task and datatype. -

-

Role definition

-The name of the role. This name is used when specifying -elements for this role. -

-The class defining a role must be an interface containing a -unique void method with only one argument whose type is the that of -elements declared on the role. -

-The proxy defined in a role specifies a class that can be used -to bridge between the type expected by the role and the type of -elements declared for that role. -

Element definition

-Any element whose name is that of a role declares an element for that role. -

-The name defined the name of the element to use in the buildfile -to specify the element being declared. -

-The class the class defining the element. -

Parameters

- - - - - - - - - - - - - - - - -
AttributeDescriptionRequired
antxmlThe library descriptor to use (META-INF/antlib.xml).Yes
Others...All attributes inherited form the - Jar task.
-

Nested elements

-See the nested elements of the Jar task. -

Examples

-
  <antjar file="${dist}/lib/app.jar" 
-       antxml="${src}/applib.xml" basedir="${build}/classes"/>
-

jars all files in the ${build}/classes directory into a file -called app.jar in the ${dist}/lib directory and -sets the content of ${src}/applib.xml as the library descriptor -in META-INF/antlib.xml.

-

Here is a sample META-INF/antlib.xml:

-
-<?xml version="1.0" encoding="UTF8" ?>
-
-<antlib version="1.0" >
-  <task name="case" class="org.apache.ant.contrib.Case" />
-</antlib>
-
-
-
-

Copyright © 2000,2001 Apache Software Foundation. All rights -Reserved.

- - - - diff --git a/proposal/sandbox/antlib/docs/manual/CoreTasks/antlib.html b/proposal/sandbox/antlib/docs/manual/CoreTasks/antlib.html deleted file mode 100644 index 34003f7a2..000000000 --- a/proposal/sandbox/antlib/docs/manual/CoreTasks/antlib.html +++ /dev/null @@ -1,148 +0,0 @@ - - - - -Ant User Manual - - - - -

AntLib

-

Description

-

Defines and loads elements contained in an ANT library.

-

It also allows the aliasing of the names being defined in order to avoid -collisions and provides means to override definitions with the ones defined -in the library.

-Ant libraries are associated with ClassLoaders identified by the -loaderid attribute. If no loader is specified a default loader -will be used. Ant libraries specifying the same loader are loaded by the -same ClassLoader as long as the libraries are defined on the same project. -Classloaders with the same ID in a subproject have the corresponding -classloader in the parent project as their parent classloader. -

-Ant libraries can be loaded in the current classloader, -which is more efficient, -but requires the tasks to be in the path already (such as in the ant lib -directory) - set useCurrentClassloader to true to enable this. -It is also possible to add more libraries to the path, such as any -libraries the task is dependent on. -

-Ant libraries define objects of several types: -

    -
  1. Roles: Define an interface to be implemented by elements -(usually tasks) that accept subelements of the specified role. -Roles may also define a proxy class which may be applied to an element -in order to make it compatible with the role. -
  2. -
  3. Tasks: define elements that belong to the predefined -role "task". -
  4. Data types: define elements that belong to the predefined role -"datatype". -
  5. Other role elements: declare elements for other roles that -have been previously defined. -
-

Parameters

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
AttributeDescriptionRequired
fileThe jar-file of the library.at least one of the two
libraryThe name of a library relative to ${ant.home}/antlib.
overrideReplace any existing definition with the same name. - ("true"/"false"). - When "false" already defined tasks - and datatytes take precedence over those in the library. - Default is "false" when omitted.No
useCurrentClassloaderSet to "true" to avoid using a separate - ClassLoader for the tasks in the library. Using this option requires - that the library jar is already accessible by the ClassLoader of - the project. Default is "false". - No
classpathA - classpath - for extra libraries to pull in. - No
loaderidThe ID of the ClassLoader to use to load the classes - defined in this library. If omitted a default per project ClassLoader - will be used. - No
-

Parameters specified as nested elements

- -

alias

-

Specifies the usage of a different name from that defined in the library -descriptor. Applies only to element definitions (not role declarations).

- - - - - - - - - - - - - - - - -
AttributeDescriptionRequired
nameThe name used in the library descriptor.Yes
asThe alias to use in the project.Yes
-

Specifies the usage of a different name from that defined in the library -descriptor. This is used to deal with name clashes

- -

classpath

- -A classpath of extra libraries to import to support this library. - -

classpathref

-A reference to an existing classpath. - -

Examples

-
  <antlib file="${build}/lib/mylib.jar"/>
-

loads the definitions from the library located at -${build}/lib/ant.jar.

-
  <antlib library="optional.jar"/>
-

loads the definitions from the library optional.jar -located at ${ant.home}/lib.

-
  <antlib file="${build}/lib/mylib.jar">
-    <alias name="echo" as="myecho"/>
-  </antlib>
-
-

loads the definitions from the library located at -${build}/lib/ant.jar but uses the name -"myecho" for the "echo" task -declared in the library.

- -

Copyright © 2000,2001 Apache Software Foundation. All rights -Reserved.

- - - - diff --git a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/ComponentHelper.java b/proposal/sandbox/antlib/src/main/org/apache/tools/ant/ComponentHelper.java deleted file mode 100644 index 13fe89eea..000000000 --- a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/ComponentHelper.java +++ /dev/null @@ -1,649 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * Copyright (c) 2003 The Apache Software Foundation. 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 - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowlegement may appear in the software itself, - * if and wherever such third-party acknowlegements normally appear. - * - * 4. The names "Ant" and "Apache Software - * Foundation" must not be used to endorse or promote products derived - * from this software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache" - * nor may "Apache" appear in their names without prior written - * permission of the Apache Group. - * - * 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 APACHE SOFTWARE FOUNDATION 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - */ - -package org.apache.tools.ant; - -import org.apache.tools.ant.util.LazyHashtable; -import org.apache.tools.ant.util.WeakishReference; - -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Properties; -import java.util.Vector; -import java.io.InputStream; -import java.io.IOException; -import java.lang.reflect.Modifier; - -/** - * Component creation and configuration. - * - * This is cut&paste from Project.java of everything related to - * task/type management. Project will just delegate. - * - * A very simple hook mechnism is provided that allows users to plug - * in custom code. It is also possible to replace the default behavior - * ( for example in an app embeding ant ) - * - * @author Costin Manolache - * @since Ant1.6 - */ -public class ComponentHelper { - /** Map from data type names to implementing classes (String to Class). */ - private Hashtable dataClassDefinitions; - /** Map from task names to implementing classes (String to Class). */ - private Hashtable taskClassDefinitions; - /** - * Map from task names to vectors of created tasks - * (String to Vector of Task). This is used to invalidate tasks if - * the task definition changes. - */ - private Hashtable createdTasks = new Hashtable(); - - - protected ComponentHelper next; - protected Project project; - - /** - */ - public static ComponentHelper getComponentHelper(Project project) { - // Singleton for now, it may change ( per/classloader ) - ComponentHelper ph=(ComponentHelper)project.getReference( "ant.ComponentHelper" ); - if( ph!=null ) return ph; - ph=new ComponentHelper(); - ph.setProject( project ); - - project.addReference( "ant.ComponentHelper",ph ); - return ph; - } - - protected ComponentHelper() { - } - - public void setNext( ComponentHelper next ) { - this.next=next; - } - - public ComponentHelper getNext() { - return next; - } - - public void setProject(Project project) { - this.project = project; - dataClassDefinitions= new AntTaskTable(project, false); - taskClassDefinitions= new AntTaskTable(project, true); - } - - /** Factory method to create the components. - * - * This should be called by UnknownElement. - * - * @param ue The component helper has access via ue to the entire XML tree. - * @param ns Namespace. Also available as ue.getNamespace() - * @param taskName The element name. Also available as ue.getTag() - * @return - * @throws BuildException - */ - public Object createComponent( UnknownElement ue, - String ns, - String taskName ) - throws BuildException - { - Object component=null; - - // System.out.println("Fallback to project default " + taskName ); - // Can't create component. Default is to use the old methods in project. - - // This policy is taken from 1.5 ProjectHelper. In future the difference between - // task and type should disapear. - if( project.getDataTypeDefinitions().get(taskName) != null ) { - // This is the original policy in ProjectHelper. The 1.5 version of UnkwnonwElement - // used to try first to create a task, and if it failed tried a type. In 1.6 the diff - // should disapear. - component = this.createDataType(taskName); - if( component!=null ) return component; - } - - // from UnkwnonwElement.createTask. The 'top level' case is removed, we're - // allways lazy - component = this.createTask(taskName); - - return component; - } - - /** Initialization code - implementing the original ant component - * loading from /org/apache/tools/ant/taskdefs/default.properties - * and .../types/default.properties - * - * @throws BuildException - */ - public void initDefaultDefinitions() throws BuildException { - project.loadDefinitions(); - } - - /** - * Adds a new task definition to the project. - * Attempting to override an existing definition with an - * equivalent one (i.e. with the same classname) results in - * a verbose log message. Attempting to override an existing definition - * with a different one results in a warning log message and - * invalidates any tasks which have already been created with the - * old definition. - * - * @param taskName The name of the task to add. - * Must not be null. - * @param taskClass The full name of the class implementing the task. - * Must not be null. - * - * @exception BuildException if the class is unsuitable for being an Ant - * task. An error level message is logged before - * this exception is thrown. - * - * @see #checkTaskClass(Class) - */ - public void addTaskDefinition(String taskName, Class taskClass) - throws BuildException { - Class old = (Class) taskClassDefinitions.get(taskName); - if (null != old) { - if (old.equals(taskClass)) { -// project.log("Ignoring override for task " + taskName -// + ", it is already defined by the same class.", -// Project.MSG_VERBOSE); - return; - } else { - int logLevel = Project.MSG_WARN; - if (old.getName().equals(taskClass.getName())) { - ClassLoader oldLoader = old.getClassLoader(); - ClassLoader newLoader = taskClass.getClassLoader(); - // system classloader on older JDKs can be null - if (oldLoader != null - && newLoader != null - && oldLoader instanceof AntClassLoader - && newLoader instanceof AntClassLoader - && ((AntClassLoader) oldLoader).getClasspath() - .equals(((AntClassLoader) newLoader).getClasspath()) - ) { - // same classname loaded from the same - // classpath components - logLevel = Project.MSG_VERBOSE; - } - } - - project.log("Trying to override old definition of task " + taskName, - logLevel); - invalidateCreatedTasks(taskName); - } - } - - String msg = " +User task: " + taskName + " " + taskClass.getName(); - project.log(msg, Project.MSG_DEBUG); - checkTaskClass(taskClass); - taskClassDefinitions.put(taskName, taskClass); - } - - /** - * Checks whether or not a class is suitable for serving as Ant task. - * Ant task implementation classes must be public, concrete, and have - * a no-arg constructor. - * - * @param taskClass The class to be checked. - * Must not be null. - * - * @exception BuildException if the class is unsuitable for being an Ant - * task. An error level message is logged before - * this exception is thrown. - */ - public void checkTaskClass(final Class taskClass) throws BuildException { - if (!Modifier.isPublic(taskClass.getModifiers())) { - final String message = taskClass + " is not public"; - project.log(message, Project.MSG_ERR); - throw new BuildException(message); - } - if (Modifier.isAbstract(taskClass.getModifiers())) { - final String message = taskClass + " is abstract"; - project.log(message, Project.MSG_ERR); - throw new BuildException(message); - } - try { - taskClass.getConstructor(null); - // don't have to check for public, since - // getConstructor finds public constructors only. - } catch (NoSuchMethodException e) { - final String message = "No public no-arg constructor in " - + taskClass; - project.log(message, Project.MSG_ERR); - throw new BuildException(message); - } - if (!Task.class.isAssignableFrom(taskClass)) { - TaskAdapter.checkTaskClass(taskClass, project); - } - } - - /** - * Returns the current task definition hashtable. The returned hashtable is - * "live" and so should not be modified. - * - * @return a map of from task name to implementing class - * (String to Class). - */ - public Hashtable getTaskDefinitions() { - return taskClassDefinitions; - } - - /** - * Adds a new datatype definition. - * Attempting to override an existing definition with an - * equivalent one (i.e. with the same classname) results in - * a verbose log message. Attempting to override an existing definition - * with a different one results in a warning log message, but the - * definition is changed. - * - * @param typeName The name of the datatype. - * Must not be null. - * @param typeClass The full name of the class implementing the datatype. - * Must not be null. - */ - public void addDataTypeDefinition(String typeName, Class typeClass) { - synchronized(dataClassDefinitions) { - Class old = (Class) dataClassDefinitions.get(typeName); - if (null != old) { - if (old.equals(typeClass)) { -// project.log("Ignoring override for datatype " + typeName -// + ", it is already defined by the same class.", -// Project.MSG_VERBOSE); - return; - } else { - project.log("Trying to override old definition of datatype " - + typeName, Project.MSG_WARN); - } - } - dataClassDefinitions.put(typeName, typeClass); - } - String msg = " +User datatype: " + typeName + " " - + typeClass.getName(); - project.log(msg, Project.MSG_DEBUG); - } - - /** - * Returns the current datatype definition hashtable. The returned - * hashtable is "live" and so should not be modified. - * - * @return a map of from datatype name to implementing class - * (String to Class). - */ - public Hashtable getDataTypeDefinitions() { - return dataClassDefinitions; - } - - /** - * Creates a new instance of a task, adding it to a list of - * created tasks for later invalidation. This causes all tasks - * to be remembered until the containing project is removed - * - * Called from Project.createTask(), which can be called by tasks. - * The method should be deprecated, as it doesn't support ns and libs. - * - * @param taskType The name of the task to create an instance of. - * Must not be null. - * - * @return an instance of the specified task, or null if - * the task name is not recognised. - * - * @exception BuildException if the task name is recognised but task - * creation fails. - */ - public Task createTask(String taskType) throws BuildException { - Task task=createNewTask(taskType); - if(task!=null) { - addCreatedTask(taskType, task); - } - return task; - } - - /** - * Creates a new instance of a task. This task is not - * cached in the createdTasks list. - * @since ant1.6 - * @param taskType The name of the task to create an instance of. - * Must not be null. - * - * @return an instance of the specified task, or null if - * the task name is not recognised. - * - * @exception BuildException if the task name is recognised but task - * creation fails. - */ - private Task createNewTask(String taskType) throws BuildException { - Class c = (Class) taskClassDefinitions.get(taskType); - - if (c == null) { - return null; - } - - try { - Object o = c.newInstance(); - if ( project != null ) { - project.setProjectReference( o ); - } - Task task = null; - if (o instanceof Task) { - task = (Task) o; - } else { - // "Generic" Bean - use the setter pattern - // and an Adapter - TaskAdapter taskA = new TaskAdapter(); - taskA.setProxy(o); - if ( project != null ) { - project.setProjectReference( taskA ); - } - task = taskA; - } - task.setProject( project ); - task.setTaskType(taskType); - - // set default value, can be changed by the user - task.setTaskName(taskType); - - String msg = " +Task: " + taskType; - project.log (msg, Project.MSG_DEBUG); - return task; - } catch (Throwable t) { - System.out.println("task CL=" + c.getClassLoader()); - String msg = "Could not create task of type: " - + taskType + " due to " + t; - throw new BuildException(msg, t); - } - } - - /** - * Keeps a record of all tasks that have been created so that they - * can be invalidated if a new task definition overrides the current one. - * - * @param type The name of the type of task which has been created. - * Must not be null. - * - * @param task The freshly created task instance. - * Must not be null. - */ - private void addCreatedTask(String type, Task task) { - synchronized (createdTasks) { - Vector v = (Vector) createdTasks.get(type); - if (v == null) { - v = new Vector(); - createdTasks.put(type, v); - } - v.addElement(WeakishReference.createReference(task)); - } - } - - /** - * Mark tasks as invalid which no longer are of the correct type - * for a given taskname. - * - * @param type The name of the type of task to invalidate. - * Must not be null. - */ - private void invalidateCreatedTasks(String type) { - synchronized (createdTasks) { - Vector v = (Vector) createdTasks.get(type); - if (v != null) { - Enumeration enum = v.elements(); - while (enum.hasMoreElements()) { - WeakishReference ref= - (WeakishReference) enum.nextElement(); - Task t = (Task) ref.get(); - //being a weak ref, it may be null by this point - if(t!=null) { - t.markInvalid(); - } - } - v.removeAllElements(); - createdTasks.remove(type); - } - } - } - - /** - * Creates a new instance of a data type. - * - * @param typeName The name of the data type to create an instance of. - * Must not be null. - * - * @return an instance of the specified data type, or null if - * the data type name is not recognised. - * - * @exception BuildException if the data type name is recognised but - * instance creation fails. - */ - public Object createDataType(String typeName) throws BuildException { - Class c = (Class) dataClassDefinitions.get(typeName); - - if (c == null) { - return null; - } - - try { - java.lang.reflect.Constructor ctor = null; - boolean noArg = false; - // DataType can have a "no arg" constructor or take a single - // Project argument. - try { - ctor = c.getConstructor(new Class[0]); - noArg = true; - } catch (NoSuchMethodException nse) { - ctor = c.getConstructor(new Class[] {Project.class}); - noArg = false; - } - - Object o = null; - if (noArg) { - o = ctor.newInstance(new Object[0]); - } else { - o = ctor.newInstance(new Object[] {project}); - } - if ( project != null ) { - project.setProjectReference( o ); - } - String msg = " +DataType: " + typeName; - project.log(msg, Project.MSG_DEBUG); - return o; - } catch (java.lang.reflect.InvocationTargetException ite) { - Throwable t = ite.getTargetException(); - String msg = "Could not create datatype of type: " - + typeName + " due to " + t; - throw new BuildException(msg, t); - } catch (Throwable t) { - String msg = "Could not create datatype of type: " - + typeName + " due to " + t; - throw new BuildException(msg, t); - } - } - - /** - * Returns a description of the type of the given element, with - * special handling for instances of tasks and data types. - *

- * This is useful for logging purposes. - * - * @param element The element to describe. - * Must not be null. - * - * @return a description of the element type - * - * @since Ant 1.6 - */ - public String getElementName(Object element) { - Hashtable elements = taskClassDefinitions; - Class elementClass = element.getClass(); - String typeName = "task"; - if (!elements.contains(elementClass)) { - elements = dataClassDefinitions; - typeName = "data type"; - if (!elements.contains(elementClass)) { - elements = null; - } - } - - if (elements != null) { - Enumeration e = elements.keys(); - while (e.hasMoreElements()) { - String name = (String) e.nextElement(); - Class clazz = (Class) elements.get(name); - if (elementClass.equals(clazz)) { - return "The <" + name + "> " + typeName; - } - } - } - - return "Class " + elementClass.getName(); - } - - - private static class AntTaskTable extends LazyHashtable { - Project project; - Properties props; - boolean tasks=false; - - public AntTaskTable( Project p, boolean tasks ) { - this.project=p; - this.tasks=tasks; - } - - public void addDefinitions( Properties props ) { - this.props=props; - } - - protected void initAll( ) { - if( initAllDone ) { - return; - } - project.log("InitAll", Project.MSG_DEBUG); - if( props==null ) { - return; - } - Enumeration enum = props.propertyNames(); - while (enum.hasMoreElements()) { - String key = (String) enum.nextElement(); - Class taskClass=getTask( key ); - if( taskClass!=null ) { - // This will call a get() and a put() - if( tasks ) { - project.addTaskDefinition(key, taskClass); - } else { - project.addDataTypeDefinition(key, taskClass ); - } - } - } - initAllDone=true; - } - - protected Class getTask(String key) { - if( props==null ) { - return null; // for tasks loaded before init() - } - String value=props.getProperty(key); - if( value==null) { - //project.log( "No class name for " + key, Project.MSG_VERBOSE ); - return null; - } - try { - Class taskClass=null; - if( project.getCoreLoader() != null && - !("only".equals(project.getProperty("build.sysclasspath")))) { - try { - project.log("Loading with the core loader " + value, - Project.MSG_DEBUG); - taskClass=project.getCoreLoader().loadClass(value); - if( taskClass != null ) { - return taskClass; - } - } catch( Exception ex ) { - //ignore - } - } - taskClass = Class.forName(value); - return taskClass; - } catch (NoClassDefFoundError ncdfe) { - project.log("Could not load a dependent class (" - + ncdfe.getMessage() + ") for task " - + key, Project.MSG_DEBUG); - } catch (ClassNotFoundException cnfe) { - project.log("Could not load class (" + value - + ") for task " + key, Project.MSG_DEBUG); - } - return null; - } - - // Hashtable implementation - public Object get( Object key ) { - Object orig=super.get( key ); - if( orig!= null ) { - return orig; - } - if( ! (key instanceof String) ) { - return null; - } - project.log("Get task " + key, Project.MSG_DEBUG ); - Object taskClass=getTask( (String) key); - if( taskClass != null) { - super.put( key, taskClass ); - } - return taskClass; - } - - public boolean containsKey( Object key ) { - return get( key ) != null; - } - - } -} diff --git a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/Project.java b/proposal/sandbox/antlib/src/main/org/apache/tools/ant/Project.java deleted file mode 100644 index 11020baa6..000000000 --- a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/Project.java +++ /dev/null @@ -1,2320 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * Copyright (c) 2000-2003 The Apache Software Foundation. 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 - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowlegement may appear in the software itself, - * if and wherever such third-party acknowlegements normally appear. - * - * 4. The names "Ant" and "Apache Software - * Foundation" must not be used to endorse or promote products derived - * from this software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache" - * nor may "Apache" appear in their names without prior written - * permission of the Apache Group. - * - * 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 APACHE SOFTWARE FOUNDATION 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - */ - -package org.apache.tools.ant; - -import java.io.File; -import java.io.IOException; -import java.io.EOFException; -import java.io.InputStream; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Properties; -import java.util.Stack; -import java.util.Vector; -import org.apache.tools.ant.input.DefaultInputHandler; -import org.apache.tools.ant.input.InputHandler; -import org.apache.tools.ant.taskdefs.Antlib; -import org.apache.tools.ant.types.FileSet; -import org.apache.tools.ant.types.FilterSet; -import org.apache.tools.ant.types.FilterSetCollection; -import org.apache.tools.ant.types.Description; -import org.apache.tools.ant.types.Path; -import org.apache.tools.ant.types.DataTypeAdapterTask; -import org.apache.tools.ant.util.FileUtils; -import org.apache.tools.ant.util.JavaEnvUtils; - -/** - * Central representation of an Ant project. This class defines an - * Ant project with all of its targets, tasks and various other - * properties. It also provides the mechanism to kick off a build using - * a particular target name. - *

- * This class also encapsulates methods which allow files to be referred - * to using abstract path names which are translated to native system - * file paths at runtime. - * - * @author duncan@x180.com - * - * @version $Revision$ - */ - -public class Project { - /** Message priority of "error". */ - public static final int MSG_ERR = 0; - /** Message priority of "warning". */ - public static final int MSG_WARN = 1; - /** Message priority of "information". */ - public static final int MSG_INFO = 2; - /** Message priority of "verbose". */ - public static final int MSG_VERBOSE = 3; - /** Message priority of "debug". */ - public static final int MSG_DEBUG = 4; - - /** - * LoaderId for the CoreLoader. - */ - public final static String CORELOADER_ID = null; - - - /** - * Description of the Field - */ - public final static String TASK_ROLE = "task"; - /** - * Description of the Field - */ - public final static String DATATYPE_ROLE = "data-type"; - /** - * Constant for the "visiting" state, used when - * traversing a DFS of target dependencies. - */ - private static final String VISITING = "VISITING"; - /** - * Constant for the "visited" state, used when - * traversing a DFS of target dependencies. - */ - private static final String VISITED = "VISITED"; - - /** - * The class name of the Ant class loader to use for - * JDK 1.2 and above - */ - private static final String ANTCLASSLOADER_JDK12 - = "org.apache.tools.ant.loader.AntClassLoader2"; - - /** - * Version constant for Java 1.0 - * - * @deprecated use org.apache.tools.ant.util.JavaEnvUtils instead - */ - public static final String JAVA_1_0 = JavaEnvUtils.JAVA_1_0; - /** - * Version constant for Java 1.1 - * - * @deprecated use org.apache.tools.ant.util.JavaEnvUtils instead - */ - public static final String JAVA_1_1 = JavaEnvUtils.JAVA_1_1; - /** - * Version constant for Java 1.2 - * - * @deprecated use org.apache.tools.ant.util.JavaEnvUtils instead - */ - public static final String JAVA_1_2 = JavaEnvUtils.JAVA_1_2; - /** - * Version constant for Java 1.3 - * - * @deprecated use org.apache.tools.ant.util.JavaEnvUtils instead - */ - public static final String JAVA_1_3 = JavaEnvUtils.JAVA_1_3; - /** - * Version constant for Java 1.4 - * - * @deprecated use org.apache.tools.ant.util.JavaEnvUtils instead - */ - public static final String JAVA_1_4 = JavaEnvUtils.JAVA_1_4; - - /** Default filter start token. */ - public static final String TOKEN_START = FilterSet.DEFAULT_TOKEN_START; - /** Default filter end token. */ - public static final String TOKEN_END = FilterSet.DEFAULT_TOKEN_END; - - private final static String CORE_DEFINITIONS = "org/apache/tools/ant/antlib.xml"; - /** Name of this project. */ - private String name; - /** Description for this project (if any). */ - private String description; - - - /** Map of references within the project (paths etc) (String to Object). */ - private Hashtable references = new AntRefTable(this); - - /** Name of the project's default target. */ - private String defaultTarget; - - private Hashtable createdTasks = new Hashtable(); - /** Map from target names to targets (String to Target). */ - private Hashtable targets = new Hashtable(); - /** Set of global filters. */ - private FilterSet globalFilterSet = new FilterSet(); - /** - * Wrapper around globalFilterSet. This collection only ever - * contains one FilterSet, but the wrapper is needed in order to - * make it easier to use the FileUtils interface. - */ - private FilterSetCollection globalFilters - = new FilterSetCollection(globalFilterSet); - - /** Project base directory. */ - private File baseDir; - - /** List of listeners to notify of build events. */ - private Vector listeners = new Vector(); - - /** - * The Ant core classloader - may be null if using - * parent classloader. - */ - private ClassLoader coreLoader = null; - - /** Records the latest task to be executed on a thread (Thread to Task). */ - private Hashtable threadTasks = new Hashtable(); - - /** Records the latest task to be executed on a thread Group. */ - private Hashtable threadGroupTasks = new Hashtable(); - - /** - * Called to handle any input requests. - */ - private InputHandler inputHandler = null; - - /** - * The default input stream used to read any input - */ - private InputStream defaultInputStream = null; - - /** - * Strore symbol tables - */ - private SymbolTable symbols; - - /** - * Sets the input handler - * - * @param handler the InputHandler instance to use for gathering input. - */ - public void setInputHandler(InputHandler handler) { - inputHandler = handler; - } - - /** - * Set the default System input stream. Normally this stream is set to - * System.in. This inputStream is used when no task inptu redirection is - * being performed. - * - * @param defaultInputStream the default input stream to use when input - * is reuested. - * @since Ant 1.6 - */ - public void setDefaultInputStream(InputStream defaultInputStream) { - this.defaultInputStream = defaultInputStream; - } - - /** - * Get this project's input stream - * - * @return the InputStream instance in use by this Porject instance to - * read input - */ - public InputStream getDefaultInputStream() { - return defaultInputStream; - } - - /** - * Retrieves the current input handler. - * - * @return the InputHandler instance currently in place for the project - * instance. - */ - public InputHandler getInputHandler() { - return inputHandler; - } - - /** Instance of a utility class to use for file operations. */ - private FileUtils fileUtils; - - /** - * Flag which catches Listeners which try to use System.out or System.err - */ - private boolean loggingMessage = false; - - /** - *

- * - * Description: The only reason for this class is to make the - * LoadDefinition method visible in this package.

- * - *@author jfernandez - *@created February 27, 2002 - */ - private class Corelib extends Antlib { - /** - * Constructor for the Corelib object - */ - Corelib() { - super(Project.this); - setLoaderid(CORELOADER_ID); - getOnerror().setValue("ignore"); - } - - - /** - * Description of the Method - */ - public void loadCoreDefinitions() { - getOnerror().setValue("report"); - super.loadDefinitions(CORE_DEFINITIONS); - } - } - - /** - * Creates a new Ant project. - */ - public Project() { - fileUtils = FileUtils.newFileUtils(); - inputHandler = new DefaultInputHandler(); - symbols = new SymbolTable(); - symbols.setProject(this); - } - - /** - * create a new ant project that inherits from caller project - * - *@param p the calling project - */ - private Project(Project p) { - fileUtils = FileUtils.newFileUtils(); - inputHandler = new DefaultInputHandler(); - symbols = new SymbolTable(p.getSymbols()); - symbols.setProject(this); - setCoreLoader(p.getCoreLoader()); - } - /** - * Loads the core definitions into the Root project. - */ - /** - * TODO should be private temporarily called from ComponentHelper - */ - protected void loadDefinitions() { - // Initialize symbol table just in case - symbols.addRole(TASK_ROLE, TaskContainer.class, TaskAdapter.class); - symbols.addRole(DATATYPE_ROLE, TaskContainer.class, - DataTypeAdapterTask.class); - - Corelib load = new Corelib(); - load.loadDefinitions(); - - // If the most basic of tasks, "property", is not defined - // then there was no antlib jars from where to load the descriptors - // we should be doing bootstrapping, or ant.jar is not an antlib. - /* - if (!isDefinedOnRole(TASK_ROLE, "property")) { - load.loadCoreDefinitions(); - - if (!isDefinedOnRole(TASK_ROLE, "property")) { - throw new BuildException("Can't load core definitions"); - } - } - */ - autoLoadDefinitions(); - } - - private void autoLoadDefinitions() { - DirectoryScanner ds = new DirectoryScanner(); - try { - File autolib=new File(getProperty("ant.home"),"autolib"); - log("scanning the autolib directory "+autolib.toString(),MSG_DEBUG); - ds.setBasedir(autolib); - ds.scan(); - String dirs[] = ds.getIncludedDirectories(); - for (int i = 0; i < dirs.length; i++) { - autoLoad(ds.getBasedir(), dirs[i]); - } - } catch (Exception e) {} - - } - - private void autoLoad(File base, String dir) { - FileSet fs = new FileSet(); - fs.setProject(this); - fs.setDir(new File(base, dir)); - fs.setIncludes("*.jar"); - - Path cp = new Path(this); - cp.addFileset(fs); - if (cp.size() == 0) { - return; - } - - Antlib.FailureAction fa = new Antlib.FailureAction(); - fa.setValue("ignore"); - - Antlib lib = new Antlib(this); - lib.setClasspath(cp); - lib.setLoaderid(dir); - lib.setOnerror(fa); - lib.loadDefinitions(); - } - - /** - * Creates a subproject of the current project. - * - *@return Description of the Return Value - */ - public Project createSubProject() { - return new Project(this); - } - - - /** - * Initialises the project. - * - * This involves setting the default task definitions and loading the - * system properties. - * - * @exception BuildException if the default task list cannot be loaded - */ - public void init() throws BuildException { - setJavaVersionProperty(); - setSystemProperties(); - - if (!isRoleDefined(TASK_ROLE)) { - // Top project, need to load the core definitions - loadDefinitions(); - } - setSystemProperties(); - - ComponentHelper.getComponentHelper(this).initDefaultDefinitions(); - - setSystemProperties(); - } - - /** - * Factory method to create a class loader for loading classes - * - * @return an appropriate classloader - */ - private AntClassLoader createClassLoader() { - AntClassLoader loader = null; - if (!JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_1)) { - try { - // 1.2+ - create advanced helper dynamically - Class loaderClass - = Class.forName(ANTCLASSLOADER_JDK12); - loader = (AntClassLoader) loaderClass.newInstance(); - } catch (Exception e) { - log("Unable to create Class Loader: " - + e.getMessage(), Project.MSG_DEBUG); - } - } - - if (loader == null) { - loader = new AntClassLoader(); - } - - loader.setProject(this); - return loader; - } - - /** - * Sets the CoreLoader to the default of the Project object - */ - private void setDefaultCoreLoader() { - coreLoader = this.getClass().getClassLoader(); - if (coreLoader == null) { - // This should only happen if ANT is being - // loader by the Bootstrap classloader - // This may be the case in JDK 1.1 - coreLoader = ClassLoader.getSystemClassLoader(); - } - } - - - /** - * Factory method to create a class loader for loading classes from - * a given path - * - * @param path the path from whcih clases are to be loaded. - * - * @return an appropriate classloader - */ - public AntClassLoader createClassLoader(Path path) { - AntClassLoader loader = createClassLoader(); - loader.setClassPath(path); - return loader; - } - - /** - * Sets the core classloader for the project. If a null - * classloader is specified, the parent classloader should be used. - * - * @param coreLoader The classloader to use for the project. - * May be null. - */ - public void setCoreLoader(ClassLoader coreLoader) { - if (coreLoader == null) { - setDefaultCoreLoader(); - } - this.coreLoader = coreLoader; - } - - /** - * Returns the core classloader to use for this project. - * This may be null, indicating that - * the parent classloader should be used. - * - * @return the core classloader to use for this project. - * - */ - public ClassLoader getCoreLoader() { - if (coreLoader == null) { - setDefaultCoreLoader(); - } - return coreLoader; - } - - /** - * Adds a build listener to the list. This listener will - * be notified of build events for this project. - * - * @param listener The listener to add to the list. - * Must not be null. - */ - public void addBuildListener(BuildListener listener) { - listeners.addElement(listener); - } - - /** - * Removes a build listener from the list. This listener - * will no longer be notified of build events for this project. - * - * @param listener The listener to remove from the list. - * Should not be null. - */ - public void removeBuildListener(BuildListener listener) { - listeners.removeElement(listener); - } - - /** - * Returns a list of build listeners for the project. - * - * @return a list of build listeners for the project - */ - public Vector getBuildListeners() { - return (Vector) listeners.clone(); - } - - /** - * Get the symbols associated with this project. - * - *@return The symbols value - */ - private SymbolTable getSymbols() { - // Package protected on purpose - return symbols; - } - - /** - * Writes a message to the log with the default log level - * of MSG_INFO - * @param message The text to log. Should not be null. - */ - - public void log(String message) { - log(message, MSG_INFO); - } - - /** - * Writes a project level message to the log with the given log level. - * @param message The text to log. Should not be null. - * @param msgLevel The priority level to log at. - */ - public void log(String message, int msgLevel) { - fireMessageLogged(this, message, msgLevel); - } - - /** - * Writes a task level message to the log with the given log level. - * @param task The task to use in the log. Must not be null. - * @param message The text to log. Should not be null. - * @param msgLevel The priority level to log at. - */ - public void log(Task task, String message, int msgLevel) { - fireMessageLogged(task, message, msgLevel); - } - - /** - * Writes a target level message to the log with the given log level. - * @param target The target to use in the log. - * Must not be null. - * @param message The text to log. Should not be null. - * @param msgLevel The priority level to log at. - */ - public void log(Target target, String message, int msgLevel) { - fireMessageLogged(target, message, msgLevel); - } - - /** - * Returns the set of global filters. - * - * @return the set of global filters - */ - public FilterSet getGlobalFilterSet() { - return globalFilterSet; - } - - /** - * Sets a property. Any existing property of the same name - * is overwritten, unless it is a user property. - * @param name The name of property to set. - * Must not be null. - * @param value The new value of the property. - * Must not be null. - */ - public synchronized void setProperty(String name, String value) { - PropertyHelper.getPropertyHelper(this). - setProperty(null, name, value, true); - } - - /** - * Sets a property if no value currently exists. If the property - * exists already, a message is logged and the method returns with - * no other effect. - * - * @param name The name of property to set. - * Must not be null. - * @param value The new value of the property. - * Must not be null. - * @since 1.5 - */ - public synchronized void setNewProperty(String name, String value) { - PropertyHelper.getPropertyHelper(this).setNewProperty(null, name, - value); - } - - /** - * Sets a user property, which cannot be overwritten by - * set/unset property calls. Any previous value is overwritten. - * @param name The name of property to set. - * Must not be null. - * @param value The new value of the property. - * Must not be null. - * @see #setProperty(String,String) - */ - public synchronized void setUserProperty(String name, String value) { - PropertyHelper.getPropertyHelper(this).setUserProperty(null, name, - value); - } - - /** - * Sets a user property, which cannot be overwritten by set/unset - * property calls. Any previous value is overwritten. Also marks - * these properties as properties that have not come from the - * command line. - * - * @param name The name of property to set. - * Must not be null. - * @param value The new value of the property. - * Must not be null. - * @see #setProperty(String,String) - */ - public synchronized void setInheritedProperty(String name, String value) { - PropertyHelper ph = PropertyHelper.getPropertyHelper(this); - ph.setInheritedProperty(null, name, value); - } - - /** - * Sets a property unless it is already defined as a user property - * (in which case the method returns silently). - * - * @param name The name of the property. - * Must not be null. - * @param value The property value. Must not be null. - */ - private void setPropertyInternal(String name, String value) { - PropertyHelper ph = PropertyHelper.getPropertyHelper(this); - ph.setProperty(null, name, value, false); - } - - /** - * Returns the value of a property, if it is set. - * - * @param name The name of the property. - * May be null, in which case - * the return value is also null. - * @return the property value, or null for no match - * or if a null name is provided. - */ - public String getProperty(String name) { - PropertyHelper ph = PropertyHelper.getPropertyHelper(this); - return (String) ph.getProperty(null, name); - } - - /** - * Replaces ${} style constructions in the given value with the - * string value of the corresponding data types. - * - * @param value The string to be scanned for property references. - * May be null. - * - * @return the given string with embedded property names replaced - * by values, or null if the given string is - * null. - * - * @exception BuildException if the given value has an unclosed - * property name, e.g. ${xxx - */ - public String replaceProperties(String value) - throws BuildException { - PropertyHelper ph = PropertyHelper.getPropertyHelper(this); - return ph.replaceProperties(null, value, null); - } - - /** - * Returns the value of a user property, if it is set. - * - * @param name The name of the property. - * May be null, in which case - * the return value is also null. - * @return the property value, or null for no match - * or if a null name is provided. - */ - public String getUserProperty(String name) { - PropertyHelper ph = PropertyHelper.getPropertyHelper(this); - return (String) ph.getUserProperty(null, name); - } - - /** - * Returns a copy of the properties table. - * @return a hashtable containing all properties - * (including user properties). - */ - public Hashtable getProperties() { - PropertyHelper ph = PropertyHelper.getPropertyHelper(this); - return ph.getProperties(); - } - - /** - * Returns a copy of the user property hashtable - * @return a hashtable containing just the user properties - */ - public Hashtable getUserProperties() { - PropertyHelper ph = PropertyHelper.getPropertyHelper(this); - return ph.getUserProperties(); - } - - /** - * Copies all user properties that have been set on the command - * line or a GUI tool from this instance to the Project instance - * given as the argument. - * - *

To copy all "user" properties, you will also have to call - * {@link #copyInheritedProperties copyInheritedProperties}.

- * - * @param other the project to copy the properties to. Must not be null. - * - * @since Ant 1.5 - */ - public void copyUserProperties(Project other) { - PropertyHelper ph = PropertyHelper.getPropertyHelper(this); - ph.copyUserProperties(other); - } - - /** - * Copies all user properties that have not been set on the - * command line or a GUI tool from this instance to the Project - * instance given as the argument. - * - *

To copy all "user" properties, you will also have to call - * {@link #copyUserProperties copyUserProperties}.

- * - * @param other the project to copy the properties to. Must not be null. - * - * @since Ant 1.5 - */ - public void copyInheritedProperties(Project other) { - PropertyHelper ph = PropertyHelper.getPropertyHelper(this); - ph.copyInheritedProperties(other); - } - - /** - * Sets the default target of the project. - * - * @param defaultTarget The name of the default target for this project. - * May be null, indicating that there is - * no default target. - * - * @deprecated use setDefault - * @see #setDefault(String) - */ - public void setDefaultTarget(String defaultTarget) { - this.defaultTarget = defaultTarget; - } - - /** - * Returns the name of the default target of the project. - * @return name of the default target or - * null if no default has been set. - */ - public String getDefaultTarget() { - return defaultTarget; - } - - /** - * Sets the default target of the project. - * - * @param defaultTarget The name of the default target for this project. - * May be null, indicating that there is - * no default target. - */ - public void setDefault(String defaultTarget) { - this.defaultTarget = defaultTarget; - } - - /** - * Sets the name of the project, also setting the user - * property ant.project.name. - * - * @param name The name of the project. - * Must not be null. - */ - public void setName(String name) { - setUserProperty("ant.project.name", name); - this.name = name; - } - - /** - * Returns the project name, if one has been set. - * - * @return the project name, or null if it hasn't been set. - */ - public String getName() { - return name; - } - - /** - * Sets the project description. - * - * @param description The description of the project. - * May be null. - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Returns the project description, if one has been set. - * - * @return the project description, or null if it hasn't - * been set. - */ - public String getDescription() { - if (description == null) { - description = Description.getDescription(this); - } - - return description; - } - - /** - * Adds a filter to the set of global filters. - * - * @param token The token to filter. - * Must not be null. - * @param value The replacement value. - * Must not be null. - * @deprecated Use getGlobalFilterSet().addFilter(token,value) - * - * @see #getGlobalFilterSet() - * @see FilterSet#addFilter(String,String) - */ - public void addFilter(String token, String value) { - if (token == null) { - return; - } - - globalFilterSet.addFilter(new FilterSet.Filter(token, value)); - } - - /** - * Returns a hashtable of global filters, mapping tokens to values. - * - * @return a hashtable of global filters, mapping tokens to values - * (String to String). - * - * @deprecated Use getGlobalFilterSet().getFilterHash() - * - * @see #getGlobalFilterSet() - * @see FilterSet#getFilterHash() - */ - public Hashtable getFilters() { - // we need to build the hashtable dynamically - return globalFilterSet.getFilterHash(); - } - - /** - * Sets the base directory for the project, checking that - * the given filename exists and is a directory. - * - * @param baseD The project base directory. - * Must not be null. - * - * @exception BuildException if the directory if invalid - */ - public void setBasedir(String baseD) throws BuildException { - setBaseDir(new File(baseD)); - } - - /** - * Sets the base directory for the project, checking that - * the given file exists and is a directory. - * - * @param baseDir The project base directory. - * Must not be null. - * @exception BuildException if the specified file doesn't exist or - * isn't a directory - */ - public void setBaseDir(File baseDir) throws BuildException { - baseDir = fileUtils.normalize(baseDir.getAbsolutePath()); - if (!baseDir.exists()) { - throw new BuildException("Basedir " + baseDir.getAbsolutePath() - + " does not exist"); - } - if (!baseDir.isDirectory()) { - throw new BuildException("Basedir " + baseDir.getAbsolutePath() - + " is not a directory"); - } - this.baseDir = baseDir; - setPropertyInternal("basedir", this.baseDir.getPath()); - String msg = "Project base dir set to: " + this.baseDir; - log(msg, MSG_VERBOSE); - } - - /** - * Returns the base directory of the project as a file object. - * - * @return the project base directory, or null if the - * base directory has not been successfully set to a valid value. - */ - public File getBaseDir() { - if (baseDir == null) { - try { - setBasedir("."); - } catch (BuildException ex) { - ex.printStackTrace(); - } - } - return baseDir; - } - - /** - * Returns the version of Java this class is running under. - * @return the version of Java as a String, e.g. "1.1" - * @see org.apache.tools.ant.util.JavaEnvUtils#getJavaVersion - * @deprecated use org.apache.tools.ant.util.JavaEnvUtils instead - */ - public static String getJavaVersion() { - return JavaEnvUtils.getJavaVersion(); - } - - /** - * Sets the ant.java.version property and tests for - * unsupported JVM versions. If the version is supported, - * verbose log messages are generated to record the Java version - * and operating system name. - * - * @exception BuildException if this Java version is not supported - * - * @see org.apache.tools.ant.util.JavaEnvUtils#getJavaVersion - */ - public void setJavaVersionProperty() throws BuildException { - String javaVersion = JavaEnvUtils.getJavaVersion(); - setPropertyInternal("ant.java.version", javaVersion); - - // sanity check - if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_0)) { - throw new BuildException("Ant cannot work on Java 1.0"); - } - - log("Detected Java version: " + javaVersion + " in: " - + System.getProperty("java.home"), MSG_VERBOSE); - - log("Detected OS: " + System.getProperty("os.name"), MSG_VERBOSE); - } - - /** - * Adds all system properties which aren't already defined as - * user properties to the project properties. - */ - public void setSystemProperties() { - Properties systemP = System.getProperties(); - Enumeration e = systemP.keys(); - while (e.hasMoreElements()) { - Object name = e.nextElement(); - String value = systemP.get(name).toString(); - this.setPropertyInternal(name.toString(), value); - } - } - - /** - * Adds a feature to the ToLoader attribute of the Project object - * - *@param loader The feature to be added to the ToLoader attribute - *@param path The feature to be added to the ToLoader attribute - *@return Description of the Return Value - */ - public ClassLoader addToLoader(String loader, Path path) { - if (loader == CORELOADER_ID) { - // It is not possible to add more libraries to the CoreLoader - // Just return it as is. - return getCoreLoader(); - } - return symbols.addToLoader(loader, path); - } - - - /** - * Adds a feature to the RoleDefinition attribute of the Project object - * - *@param role The feature to be added to the RoleDefinition attribute - *@param roleClass The feature to be added to the RoleDefinition attribute - *@param adapter The feature to be added to the RoleDefinition attribute - *@return Description of the Return Value - */ - public boolean addRoleDefinition(String role, - Class roleClass, Class adapter) { - return symbols.addRole(role, roleClass, adapter); - } - - - /** - * test for a role name being in use already - * - *@param name the name to test - *@return true if it is a task or a datatype - */ - public boolean isRoleDefined(String name) { - return (symbols.getRole(name) != null); - } - - - /** - * Adds a feature to the DefinitionOnRole attribute of the Project object - * - *@param role The feature to be added to the DefinitionOnRole attribute - *@param type The feature to be added to the DefinitionOnRole attribute - *@param clz The feature to be added to the DefinitionOnRole attribute - */ - public void addDefinitionOnRole(String role, - String type, Class clz) { - Class old = symbols.add(role, type, clz); - // Special management for Tasks - if (TASK_ROLE.equals(role) && null != old && !old.equals(clz)) { - invalidateCreatedTasks(type); - } - } - - - /** - * test for a name being in use already on this role - * - *@param name the name to test - *@param role Description of the Parameter - *@return true if it is a task or a datatype - */ - public boolean isDefinedOnRole(String role, String name) { - return (symbols.get(role, name) != null); - } - - - /** - * Adds a new task definition to the project. - * Attempting to override an existing definition with an - * equivalent one (i.e. with the same classname) results in - * a verbose log message. Attempting to override an existing definition - * with a different one results in a warning log message and - * invalidates any tasks which have already been created with the - * old definition. - * - * @param taskName The name of the task to add. - * Must not be null. - * @param taskClass The full name of the class implementing the task. - * Must not be null. - * - * @exception BuildException if the class is unsuitable for being an Ant - * task. An error level message is logged before - * this exception is thrown. - * - * @see #checkTaskClass(Class) - */ - public void addTaskDefinition(String taskName, Class taskClass) - throws BuildException { - ComponentHelper.getComponentHelper(this).addTaskDefinition(taskName, - taskClass); - } - - /** - * Checks whether or not a class is suitable for serving as Ant task. - * Ant task implementation classes must be public, concrete, and have - * a no-arg constructor. - * - * @param taskClass The class to be checked. - * Must not be null. - * - * @exception BuildException if the class is unsuitable for being an Ant - * task. An error level message is logged before - * this exception is thrown. - */ - public void checkTaskClass(final Class taskClass) throws BuildException { - ComponentHelper.getComponentHelper(this).checkTaskClass(taskClass); - - if (!Modifier.isPublic(taskClass.getModifiers())) { - final String message = taskClass + " is not public"; - log(message, Project.MSG_ERR); - throw new BuildException(message); - } - if (Modifier.isAbstract(taskClass.getModifiers())) { - final String message = taskClass + " is abstract"; - log(message, Project.MSG_ERR); - throw new BuildException(message); - } - try { - taskClass.getConstructor(null); - // don't have to check for public, since - // getConstructor finds public constructors only. - } catch (NoSuchMethodException e) { - final String message = "No public no-arg constructor in " - + taskClass; - log(message, Project.MSG_ERR); - throw new BuildException(message); - } - if (!Task.class.isAssignableFrom(taskClass)) { - TaskAdapter.checkTaskClass(taskClass, this); - } - } - - /** - * Returns the current task definition hashtable. The returned hashtable is - * "live" and so should not be modified. - * - * @return a map of from task name to implementing class - * (String to Class). - */ - public Hashtable getTaskDefinitions() { - return ComponentHelper.getComponentHelper(this).getTaskDefinitions(); - } - - /** - * Adds a new datatype definition. - * Attempting to override an existing definition with an - * equivalent one (i.e. with the same classname) results in - * a verbose log message. Attempting to override an existing definition - * with a different one results in a warning log message, but the - * definition is changed. - * - * @param typeName The name of the datatype. - * Must not be null. - * @param typeClass The full name of the class implementing the datatype. - * Must not be null. - */ - public void addDataTypeDefinition(String typeName, Class typeClass) { - ComponentHelper.getComponentHelper(this).addDataTypeDefinition(typeName, - typeClass); - } - - /** - * Returns the current datatype definition hashtable. The returned - * hashtable is "live" and so should not be modified. - * - * @return a map of from datatype name to implementing class - * (String to Class). - */ - public Hashtable getDataTypeDefinitions() { - return ComponentHelper.getComponentHelper(this).getDataTypeDefinitions(); - } - - /** - * Adds a new target to the project. - * - * @param target The target to be added to the project. - * Must not be null. - * - * @exception BuildException if the target already exists in the project - * - * @see Project#addOrReplaceTarget - */ - public void addTarget(Target target) throws BuildException { - String name = target.getName(); - if (targets.get(name) != null) { - throw new BuildException("Duplicate target: `" + name + "'"); - } - addOrReplaceTarget(name, target); - } - - /** - * Adds a new target to the project. - * - * @param targetName The name to use for the target. - * Must not be null. - * @param target The target to be added to the project. - * Must not be null. - * - * @exception BuildException if the target already exists in the project - * - * @see Project#addOrReplaceTarget - */ - public void addTarget(String targetName, Target target) - throws BuildException { - if (targets.get(targetName) != null) { - throw new BuildException("Duplicate target: `" + targetName + "'"); - } - addOrReplaceTarget(targetName, target); - } - - /** - * Adds a target to the project, or replaces one with the same - * name. - * - * @param target The target to be added or replaced in the project. - * Must not be null. - */ - public void addOrReplaceTarget(Target target) { - addOrReplaceTarget(target.getName(), target); - } - - /** - * Adds a target to the project, or replaces one with the same - * name. - * - * @param targetName The name to use for the target. - * Must not be null. - * @param target The target to be added or replaced in the project. - * Must not be null. - */ - public void addOrReplaceTarget(String targetName, Target target) { - String msg = " +Target: " + targetName; - log(msg, MSG_DEBUG); - target.setProject(this); - targets.put(targetName, target); - } - - /** - * Returns the hashtable of targets. The returned hashtable - * is "live" and so should not be modified. - * @return a map from name to target (String to Target). - */ - public Hashtable getTargets() { - return targets; - } - - /** - * Create a new element instance on a Role - * - *@param role name of the role to use - *@param type name of the element to create - *@return null if element unknown on this role - */ - public Object createForRole(String role, String type) { - SymbolTable.Factory f = symbols.get(role, type); - if (f == null) { - return null; - } - - try { - Object o = f.create(this); - setProjectReference(o); - if (o instanceof ProjectComponent) { - ((ProjectComponent) o).setProject(this); - if (o instanceof Task) { - Task task = (Task) o; - task.setTaskType(type); - - // set default value, can be changed by the user - task.setTaskName(type); - addCreatedTask(type, task); - } - } - String msg = " +" + role + ": " + type; - log(msg, MSG_DEBUG); - return o; - } catch (Throwable t) { - String msg = "Could not create " + role + " of type: " - + type + " due to " + t; - throw new BuildException(msg, t); - } - } - - /** - * Keep a record of all tasks that have been created so that they can be - * invalidated if a taskdef overrides the definition. - * - *@param type The feature to be added to the CreatedTask attribute - *@param task The feature to be added to the CreatedTask attribute - */ - private void addCreatedTask(String type, Task task) { - synchronized (createdTasks) { - Vector v = (Vector) createdTasks.get(type); - if (v == null) { - v = new Vector(); - createdTasks.put(type, v); - } - v.addElement(task); - } - } - - - /** - * Mark tasks as invalid which no longer are of the correct type for a - * given taskname. - * - *@param type Description of the Parameter - */ - private void invalidateCreatedTasks(String type) { - synchronized (createdTasks) { - Vector v = (Vector) createdTasks.get(type); - if (v != null) { - Enumeration enum = v.elements(); - while (enum.hasMoreElements()) { - Task t = (Task) enum.nextElement(); - t.markInvalid(); - } - v.removeAllElements(); - createdTasks.remove(type); - } - } - } - - - /** - * Creates a new instance of a task, adding it to a list of - * created tasks for later invalidation. This causes all tasks - * to be remembered until the containing project is removed - * @param taskType The name of the task to create an instance of. - * Must not be null. - * - * @return an instance of the specified task, or null if - * the task name is not recognised. - * - * @exception BuildException if the task name is recognised but task - * creation fails. - */ - public Task createTask(String taskType) throws BuildException { - return ComponentHelper.getComponentHelper(this).createTask( taskType ); - } - - /** - * Creates a new instance of a data type. - * - * @param typeName The name of the data type to create an instance of. - * Must not be null. - * - * @return an instance of the specified data type, or null if - * the data type name is not recognised. - * - * @exception BuildException if the data type name is recognised but - * instance creation fails. - */ - public Object createDataType(String typeName) throws BuildException { - return ComponentHelper.getComponentHelper(this).createDataType(typeName); - } - - /** - * Execute the specified sequence of targets, and the targets - * they depend on. - * - * @param targetNames A vector of target name strings to execute. - * Must not be null. - * - * @exception BuildException if the build failed - */ - public void executeTargets(Vector targetNames) throws BuildException { - - for (int i = 0; i < targetNames.size(); i++) { - executeTarget((String) targetNames.elementAt(i)); - } - } - - /** - * Demultiplexes output so that each task receives the appropriate - * messages. If the current thread is not currently executing a task, - * the message is logged directly. - * - * @param line Message to handle. Should not be null. - * @param isError Whether the text represents an error (true) - * or information (false). - */ - public void demuxOutput(String line, boolean isError) { - Task task = getThreadTask(Thread.currentThread()); - if (task == null) { - fireMessageLogged(this, line, isError ? MSG_ERR : MSG_INFO); - } else { - if (isError) { - task.handleErrorOutput(line); - } else { - task.handleOutput(line); - } - } - } - - /** - * Read data from the default input stream. If no default has been - * specified, System.in is used. - * - * @param buffer the buffer into which data is to be read. - * @param offset the offset into the buffer at which data is stored. - * @param length the amount of data to read - * - * @return the number of bytes read - * - * @exception IOException if the data cannot be read - * @since Ant 1.6 - */ - public int defaultInput(byte[] buffer, int offset, int length) - throws IOException { - if (defaultInputStream != null) { - return defaultInputStream.read(buffer, offset, length); - } else { - throw new EOFException("No input provided for project"); - } - } - - /** - * Demux an input request to the correct task. - * - * @param buffer the buffer into which data is to be read. - * @param offset the offset into the buffer at which data is stored. - * @param length the amount of data to read - * - * @return the number of bytes read - * - * @exception IOException if the data cannot be read - * @since Ant 1.6 - */ - public int demuxInput(byte[] buffer, int offset, int length) - throws IOException { - Task task = getThreadTask(Thread.currentThread()); - if (task == null) { - return defaultInput(buffer, offset, length); - } else { - return task.handleInput(buffer, offset, length); - } - } - - /** - * Demultiplexes flush operation so that each task receives the appropriate - * messages. If the current thread is not currently executing a task, - * the message is logged directly. - * - * @since Ant 1.5.2 - * - * @param line Message to handle. Should not be null. - * @param isError Whether the text represents an error (true) - * or information (false). - */ - public void demuxFlush(String line, boolean isError) { - Task task = getThreadTask(Thread.currentThread()); - if (task == null) { - fireMessageLogged(this, line, isError ? MSG_ERR : MSG_INFO); - } else { - if (isError) { - task.handleErrorFlush(line); - } else { - task.handleFlush(line); - } - } - } - - - - /** - * Executes the specified target and any targets it depends on. - * - * @param targetName The name of the target to execute. - * Must not be null. - * - * @exception BuildException if the build failed - */ - public void executeTarget(String targetName) throws BuildException { - - // sanity check ourselves, if we've been asked to build nothing - // then we should complain - - if (targetName == null) { - String msg = "No target specified"; - throw new BuildException(msg); - } - - // Sort the dependency tree, and run everything from the - // beginning until we hit our targetName. - // Sorting checks if all the targets (and dependencies) - // exist, and if there is any cycle in the dependency - // graph. - Vector sortedTargets = topoSort(targetName, targets); - - int curidx = 0; - Target curtarget; - - do { - curtarget = (Target) sortedTargets.elementAt(curidx++); - curtarget.performTasks(); - } while (!curtarget.getName().equals(targetName)); - } - - /** - * Returns the canonical form of a filename. - *

- * If the specified file name is relative it is resolved - * with respect to the given root directory. - * - * @param fileName The name of the file to resolve. - * Must not be null. - * - * @param rootDir The directory to resolve relative file names with - * respect to. May be null, in which case - * the current directory is used. - * - * @return the resolved File. - * - * @deprecated - */ - public File resolveFile(String fileName, File rootDir) { - return fileUtils.resolveFile(rootDir, fileName); - } - - /** - * Returns the canonical form of a filename. - *

- * If the specified file name is relative it is resolved - * with respect to the project's base directory. - * - * @param fileName The name of the file to resolve. - * Must not be null. - * - * @return the resolved File. - * - */ - public File resolveFile(String fileName) { - return fileUtils.resolveFile(baseDir, fileName); - } - - /** - * Translates a path into its native (platform specific) format. - *

- * This method uses PathTokenizer to separate the input path - * into its components. This handles DOS style paths in a relatively - * sensible way. The file separators are then converted to their platform - * specific versions. - * - * @param toProcess The path to be translated. - * May be null. - * - * @return the native version of the specified path or - * an empty string if the path is null or empty. - * - * @see PathTokenizer - */ - public static String translatePath(String toProcess) { - if (toProcess == null || toProcess.length() == 0) { - return ""; - } - - StringBuffer path = new StringBuffer(toProcess.length() + 50); - PathTokenizer tokenizer = new PathTokenizer(toProcess); - while (tokenizer.hasMoreTokens()) { - String pathComponent = tokenizer.nextToken(); - pathComponent = pathComponent.replace('/', File.separatorChar); - pathComponent = pathComponent.replace('\\', File.separatorChar); - if (path.length() != 0) { - path.append(File.pathSeparatorChar); - } - path.append(pathComponent); - } - - return path.toString(); - } - - /** - * Convenience method to copy a file from a source to a destination. - * No filtering is performed. - * - * @param sourceFile Name of file to copy from. - * Must not be null. - * @param destFile Name of file to copy to. - * Must not be null. - * - * @exception IOException if the copying fails - * - * @deprecated - */ - public void copyFile(String sourceFile, String destFile) - throws IOException { - fileUtils.copyFile(sourceFile, destFile); - } - - /** - * Convenience method to copy a file from a source to a destination - * specifying if token filtering should be used. - * - * @param sourceFile Name of file to copy from. - * Must not be null. - * @param destFile Name of file to copy to. - * Must not be null. - * @param filtering Whether or not token filtering should be used during - * the copy. - * - * @exception IOException if the copying fails - * - * @deprecated - */ - public void copyFile(String sourceFile, String destFile, boolean filtering) - throws IOException { - fileUtils.copyFile(sourceFile, destFile, - filtering ? globalFilters : null); - } - - /** - * Convenience method to copy a file from a source to a - * destination specifying if token filtering should be used and if - * source files may overwrite newer destination files. - * - * @param sourceFile Name of file to copy from. - * Must not be null. - * @param destFile Name of file to copy to. - * Must not be null. - * @param filtering Whether or not token filtering should be used during - * the copy. - * @param overwrite Whether or not the destination file should be - * overwritten if it already exists. - * - * @exception IOException if the copying fails - * - * @deprecated - */ - public void copyFile(String sourceFile, String destFile, boolean filtering, - boolean overwrite) throws IOException { - fileUtils.copyFile(sourceFile, destFile, - filtering ? globalFilters : null, overwrite); - } - - /** - * Convenience method to copy a file from a source to a - * destination specifying if token filtering should be used, if - * source files may overwrite newer destination files, and if the - * last modified time of the resulting file should be set to - * that of the source file. - * - * @param sourceFile Name of file to copy from. - * Must not be null. - * @param destFile Name of file to copy to. - * Must not be null. - * @param filtering Whether or not token filtering should be used during - * the copy. - * @param overwrite Whether or not the destination file should be - * overwritten if it already exists. - * @param preserveLastModified Whether or not the last modified time of - * the resulting file should be set to that - * of the source file. - * - * @exception IOException if the copying fails - * - * @deprecated - */ - public void copyFile(String sourceFile, String destFile, boolean filtering, - boolean overwrite, boolean preserveLastModified) - throws IOException { - fileUtils.copyFile(sourceFile, destFile, - filtering ? globalFilters : null, overwrite, preserveLastModified); - } - - /** - * Convenience method to copy a file from a source to a destination. - * No filtering is performed. - * - * @param sourceFile File to copy from. - * Must not be null. - * @param destFile File to copy to. - * Must not be null. - * - * @exception IOException if the copying fails - * - * @deprecated - */ - public void copyFile(File sourceFile, File destFile) throws IOException { - fileUtils.copyFile(sourceFile, destFile); - } - - /** - * Convenience method to copy a file from a source to a destination - * specifying if token filtering should be used. - * - * @param sourceFile File to copy from. - * Must not be null. - * @param destFile File to copy to. - * Must not be null. - * @param filtering Whether or not token filtering should be used during - * the copy. - * - * @exception IOException if the copying fails - * - * @deprecated - */ - public void copyFile(File sourceFile, File destFile, boolean filtering) - throws IOException { - fileUtils.copyFile(sourceFile, destFile, - filtering ? globalFilters : null); - } - - /** - * Convenience method to copy a file from a source to a - * destination specifying if token filtering should be used and if - * source files may overwrite newer destination files. - * - * @param sourceFile File to copy from. - * Must not be null. - * @param destFile File to copy to. - * Must not be null. - * @param filtering Whether or not token filtering should be used during - * the copy. - * @param overwrite Whether or not the destination file should be - * overwritten if it already exists. - * - * @exception IOException if the file cannot be copied. - * - * @deprecated - */ - public void copyFile(File sourceFile, File destFile, boolean filtering, - boolean overwrite) throws IOException { - fileUtils.copyFile(sourceFile, destFile, - filtering ? globalFilters : null, overwrite); - } - - /** - * Convenience method to copy a file from a source to a - * destination specifying if token filtering should be used, if - * source files may overwrite newer destination files, and if the - * last modified time of the resulting file should be set to - * that of the source file. - * - * @param sourceFile File to copy from. - * Must not be null. - * @param destFile File to copy to. - * Must not be null. - * @param filtering Whether or not token filtering should be used during - * the copy. - * @param overwrite Whether or not the destination file should be - * overwritten if it already exists. - * @param preserveLastModified Whether or not the last modified time of - * the resulting file should be set to that - * of the source file. - * - * @exception IOException if the file cannot be copied. - * - * @deprecated - */ - public void copyFile(File sourceFile, File destFile, boolean filtering, - boolean overwrite, boolean preserveLastModified) - throws IOException { - fileUtils.copyFile(sourceFile, destFile, - filtering ? globalFilters : null, overwrite, preserveLastModified); - } - - /** - * Calls File.setLastModified(long time) on Java above 1.1, and logs - * a warning on Java 1.1. - * - * @param file The file to set the last modified time on. - * Must not be null. - * - * @param time the required modification time. - * - * @deprecated - * - * @exception BuildException if the last modified time cannot be set - * despite running on a platform with a version - * above 1.1. - */ - public void setFileLastModified(File file, long time) - throws BuildException { - if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_1)) { - log("Cannot change the modification time of " + file - + " in JDK 1.1", Project.MSG_WARN); - return; - } - fileUtils.setFileLastModified(file, time); - log("Setting modification time for " + file, MSG_VERBOSE); - } - - /** - * Returns the boolean equivalent of a string, which is considered - * true if either "on", "true", - * or "yes" is found, ignoring case. - * - * @param s The string to convert to a boolean value. - * Must not be null. - * - * @return true if the given string is "on", - * "true" or "yes", or - * false otherwise. - */ - public static boolean toBoolean(String s) { - return (s.equalsIgnoreCase("on") || - s.equalsIgnoreCase("true") || - s.equalsIgnoreCase("yes")); - } - - /** - * Topologically sorts a set of targets. - * - * @param root The name of the root target. The sort is created in such - * a way that the sequence of Targets up to the root - * target is the minimum possible such sequence. - * Must not be null. - * @param targets A map of names to targets (String to Target). - * Must not be null. - * @return a vector of strings with the names of the targets in - * sorted order. - * @exception BuildException if there is a cyclic dependency among the - * targets, or if a named target does not exist. - */ - public final Vector topoSort(String root, Hashtable targets) - throws BuildException { - Vector ret = new Vector(); - Hashtable state = new Hashtable(); - Stack visiting = new Stack(); - - // We first run a DFS based sort using the root as the starting node. - // This creates the minimum sequence of Targets to the root node. - // We then do a sort on any remaining unVISITED targets. - // This is unnecessary for doing our build, but it catches - // circular dependencies or missing Targets on the entire - // dependency tree, not just on the Targets that depend on the - // build Target. - - tsort(root, targets, state, visiting, ret); - log("Build sequence for target `" + root + "' is " + ret, MSG_VERBOSE); - for (Enumeration en = targets.keys(); en.hasMoreElements();) { - String curTarget = (String) en.nextElement(); - String st = (String) state.get(curTarget); - if (st == null) { - tsort(curTarget, targets, state, visiting, ret); - } else if (st == VISITING) { - throw new RuntimeException("Unexpected node in visiting state: " - + curTarget); - } - } - log("Complete build sequence is " + ret, MSG_VERBOSE); - return ret; - } - - /** - * Performs a single step in a recursive depth-first-search traversal of - * the target dependency tree. - *

- * The current target is first set to the "visiting" state, and pushed - * onto the "visiting" stack. - *

- * An exception is then thrown if any child of the current node is in the - * visiting state, as that implies a circular dependency. The exception - * contains details of the cycle, using elements of the "visiting" stack. - *

- * If any child has not already been "visited", this method is called - * recursively on it. - *

- * The current target is then added to the ordered list of targets. Note - * that this is performed after the children have been visited in order - * to get the correct order. The current target is set to the "visited" - * state. - *

- * By the time this method returns, the ordered list contains the sequence - * of targets up to and including the current target. - * - * @param root The current target to inspect. - * Must not be null. - * @param targets A mapping from names to targets (String to Target). - * Must not be null. - * @param state A mapping from target names to states - * (String to String). - * The states in question are "VISITING" and "VISITED". - * Must not be null. - * @param visiting A stack of targets which are currently being visited. - * Must not be null. - * @param ret The list to add target names to. This will end up - * containing the complete list of depenencies in - * dependency order. - * Must not be null. - * - * @exception BuildException if a non-existent target is specified or if - * a circular dependency is detected. - */ - private final void tsort(String root, Hashtable targets, - Hashtable state, Stack visiting, - Vector ret) - throws BuildException { - state.put(root, VISITING); - visiting.push(root); - - Target target = (Target) targets.get(root); - - // Make sure we exist - if (target == null) { - StringBuffer sb = new StringBuffer("Target `"); - sb.append(root); - sb.append("' does not exist in this project. "); - visiting.pop(); - if (!visiting.empty()) { - String parent = (String) visiting.peek(); - sb.append("It is used from target `"); - sb.append(parent); - sb.append("'."); - } - - throw new BuildException(new String(sb)); - } - - for (Enumeration en = target.getDependencies(); en.hasMoreElements();) { - String cur = (String) en.nextElement(); - String m = (String) state.get(cur); - if (m == null) { - // Not been visited - tsort(cur, targets, state, visiting, ret); - } else if (m == VISITING) { - // Currently visiting this node, so have a cycle - throw makeCircularException(cur, visiting); - } - } - - String p = (String) visiting.pop(); - if (root != p) { - throw new RuntimeException("Unexpected internal error: expected to " - + "pop " + root + " but got " + p); - } - state.put(root, VISITED); - ret.addElement(target); - } - - /** - * Builds an appropriate exception detailing a specified circular - * dependency. - * - * @param end The dependency to stop at. Must not be null. - * @param stk A stack of dependencies. Must not be null. - * - * @return a BuildException detailing the specified circular dependency. - */ - private static BuildException makeCircularException(String end, Stack stk) { - StringBuffer sb = new StringBuffer("Circular dependency: "); - sb.append(end); - String c; - do { - c = (String) stk.pop(); - sb.append(" <- "); - sb.append(c); - } while (!c.equals(end)); - return new BuildException(new String(sb)); - } - - /** - * Adds a reference to the project. - * - * @param name The name of the reference. Must not be null. - * @param value The value of the reference. Must not be null. - */ - public void addReference(String name, Object value) { - synchronized (references) { - Object old = ((AntRefTable) references).getReal(name); - if (old == value) { - // no warning, this is not changing anything - return; - } - if (old != null && !(old instanceof UnknownElement)) { - log("Overriding previous definition of reference to " + name, - MSG_WARN); - } - - String valueAsString = ""; - try { - valueAsString = value.toString(); - } catch (Throwable t) { - log("Caught exception (" + t.getClass().getName() + ")" - + " while expanding " + name + ": " + t.getMessage(), - MSG_WARN); - } - log("Adding reference: " + name + " -> " + valueAsString, - MSG_DEBUG); - references.put(name, value); - } - } - - /** - * Returns a map of the references in the project (String to Object). - * The returned hashtable is "live" and so must not be modified. - * - * @return a map of the references in the project (String to Object). - */ - public Hashtable getReferences() { - return references; - } - - /** - * Looks up a reference by its key (ID). - * - * @param key The key for the desired reference. - * Must not be null. - * - * @return the reference with the specified ID, or null if - * there is no such reference in the project. - */ - public Object getReference(String key) { - return references.get(key); - } - - /** - * Returns a description of the type of the given element, with - * special handling for instances of tasks and data types. - *

- * This is useful for logging purposes. - * - * @param element The element to describe. - * Must not be null. - * - * @return a description of the element type - * - * @since 1.95, Ant 1.5 - */ - public String getElementName(Object element) { - return ComponentHelper.getComponentHelper(this).getElementName(element); - } - - /** - * Sends a "build started" event to the build listeners for this project. - */ - public void fireBuildStarted() { - BuildEvent event = new BuildEvent(this); - Vector listeners = getBuildListeners(); - int size = listeners.size(); - for (int i = 0; i < size; i++) { - BuildListener listener = (BuildListener) listeners.elementAt(i); - listener.buildStarted(event); - } - } - - /** - * Sends a "build finished" event to the build listeners for this project. - * @param exception an exception indicating a reason for a build - * failure. May be null, indicating - * a successful build. - */ - public void fireBuildFinished(Throwable exception) { - BuildEvent event = new BuildEvent(this); - event.setException(exception); - Vector listeners = getBuildListeners(); - int size = listeners.size(); - for (int i = 0; i < size; i++) { - BuildListener listener = (BuildListener) listeners.elementAt(i); - listener.buildFinished(event); - } - } - - - /** - * Sends a "target started" event to the build listeners for this project. - * - * @param target The target which is starting to build. - * Must not be null. - */ - protected void fireTargetStarted(Target target) { - BuildEvent event = new BuildEvent(target); - Vector listeners = getBuildListeners(); - int size = listeners.size(); - for (int i = 0; i < size; i++) { - BuildListener listener = (BuildListener) listeners.elementAt(i); - listener.targetStarted(event); - } - } - - /** - * Sends a "target finished" event to the build listeners for this - * project. - * - * @param target The target which has finished building. - * Must not be null. - * @param exception an exception indicating a reason for a build - * failure. May be null, indicating - * a successful build. - */ - protected void fireTargetFinished(Target target, Throwable exception) { - BuildEvent event = new BuildEvent(target); - event.setException(exception); - Vector listeners = getBuildListeners(); - int size = listeners.size(); - for (int i = 0; i < size; i++) { - BuildListener listener = (BuildListener) listeners.elementAt(i); - listener.targetFinished(event); - } - } - - /** - * Sends a "task started" event to the build listeners for this project. - * - * @param task The target which is starting to execute. - * Must not be null. - */ - protected void fireTaskStarted(Task task) { - // register this as the current task on the current thread. - registerThreadTask(Thread.currentThread(), task); - BuildEvent event = new BuildEvent(task); - Vector listeners = getBuildListeners(); - int size = listeners.size(); - for (int i = 0; i < size; i++) { - BuildListener listener = (BuildListener) listeners.elementAt(i); - listener.taskStarted(event); - } - } - - /** - * Sends a "task finished" event to the build listeners for this - * project. - * - * @param task The task which has finished executing. - * Must not be null. - * @param exception an exception indicating a reason for a build - * failure. May be null, indicating - * a successful build. - */ - protected void fireTaskFinished(Task task, Throwable exception) { - registerThreadTask(Thread.currentThread(), null); - System.out.flush(); - System.err.flush(); - BuildEvent event = new BuildEvent(task); - event.setException(exception); - Vector listeners = getBuildListeners(); - int size = listeners.size(); - for (int i = 0; i < size; i++) { - BuildListener listener = (BuildListener) listeners.elementAt(i); - listener.taskFinished(event); - } - } - - /** - * Sends a "message logged" event to the build listeners for this project. - * - * @param event The event to send. This should be built up with the - * appropriate task/target/project by the caller, so that - * this method can set the message and priority, then send - * the event. Must not be null. - * @param message The message to send. Should not be null. - * @param priority The priority of the message. - */ - private void fireMessageLoggedEvent(BuildEvent event, String message, - int priority) { - event.setMessage(message, priority); - Vector listeners = getBuildListeners(); - synchronized (this) { - if (loggingMessage) { - throw new BuildException("Listener attempted to access " - + (priority == MSG_ERR ? "System.err" : "System.out") - + " - infinite loop terminated"); - } - loggingMessage = true; - int size = listeners.size(); - for (int i = 0; i < size; i++) { - BuildListener listener = (BuildListener) listeners.elementAt(i); - listener.messageLogged(event); - } - loggingMessage = false; - } - } - - /** - * Sends a "message logged" project level event to the build listeners for - * this project. - * - * @param project The project generating the event. - * Should not be null. - * @param message The message to send. Should not be null. - * @param priority The priority of the message. - */ - protected void fireMessageLogged(Project project, String message, - int priority) { - BuildEvent event = new BuildEvent(project); - fireMessageLoggedEvent(event, message, priority); - } - - /** - * Sends a "message logged" target level event to the build listeners for - * this project. - * - * @param target The target generating the event. - * Must not be null. - * @param message The message to send. Should not be null. - * @param priority The priority of the message. - */ - protected void fireMessageLogged(Target target, String message, - int priority) { - BuildEvent event = new BuildEvent(target); - fireMessageLoggedEvent(event, message, priority); - } - - /** - * Sends a "message logged" task level event to the build listeners for - * this project. - * - * @param task The task generating the event. - * Must not be null. - * @param message The message to send. Should not be null. - * @param priority The priority of the message. - */ - protected void fireMessageLogged(Task task, String message, int priority) { - BuildEvent event = new BuildEvent(task); - fireMessageLoggedEvent(event, message, priority); - } - - /** - * Register a task as the current task for a thread. - * If the task is null, the thread's entry is removed. - * - * @param thread the thread on which the task is registered. - * @param task the task to be registered. - * @since Ant 1.5 - */ - public synchronized void registerThreadTask(Thread thread, Task task) { - if (task != null) { - threadTasks.put(thread, task); - threadGroupTasks.put(thread.getThreadGroup(), task); - } else { - threadTasks.remove(thread); - threadGroupTasks.remove(thread.getThreadGroup()); - } - } - - /** - * Get the current task assopciated with a thread, if any - * - * @param thread the thread for which the task is required. - * @return the task which is currently registered for the given thread or - * null if no task is registered. - */ - public Task getThreadTask(Thread thread) { - Task task = (Task) threadTasks.get(thread); - if (task == null) { - ThreadGroup group = thread.getThreadGroup(); - while (task == null && group != null) { - task = (Task) threadGroupTasks.get(group); - group = group.getParent(); - } - } - return task; - } - - - // Should move to a separate public class - and have API to add - // listeners, etc. - private static class AntRefTable extends Hashtable { - Project project; - public AntRefTable(Project project) { - super(); - this.project = project; - } - - /** Returns the unmodified original object. - * This method should be called internally to - * get the 'real' object. - * The normal get method will do the replacement - * of UnknownElement ( this is similar with the JDNI - * refs behavior ) - */ - public Object getReal(Object key) { - return super.get(key); - } - - /** Get method for the reference table. - * It can be used to hook dynamic references and to modify - * some references on the fly - for example for delayed - * evaluation. - * - * It is important to make sure that the processing that is - * done inside is not calling get indirectly. - * - * @param key - * @return - */ - public Object get(Object key) { - //System.out.println("AntRefTable.get " + key); - Object o = super.get(key); - if (o instanceof UnknownElement) { - // Make sure that - ((UnknownElement) o).maybeConfigure(); - o = ((UnknownElement) o).getTask(); - } - return o; - } - } - - /** - * Set a reference to this Project on the parameterized object. - * Need to set the project before other set/add elements - * are called - * @param obj the object to invoke setProject(this) on - */ - public final void setProjectReference( final Object obj ) { - if ( obj instanceof ProjectComponent ) { - ( (ProjectComponent) obj ).setProject( this ); - return; - } - try { - Method method = - obj.getClass().getMethod( - "setProject", new Class[] {Project.class} ); - if ( method != null ) { - method.invoke( obj, new Object[] { this } ); - } - } catch (Throwable e) { - // ignore this if the object does not have - // a set project method or the method - // is private/protected. - } - } -} diff --git a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/RoleAdapter.java b/proposal/sandbox/antlib/src/main/org/apache/tools/ant/RoleAdapter.java deleted file mode 100644 index 57c1f62d9..000000000 --- a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/RoleAdapter.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * Copyright (c) 1999 The Apache Software Foundation. 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 - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowlegement may appear in the software itself, - * if and wherever such third-party acknowlegements normally appear. - * - * 4. The names "The Jakarta Project", "Ant", and "Apache Software - * Foundation" must not be used to endorse or promote products derived - * from this software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache" - * nor may "Apache" appear in their names without prior written - * permission of the Apache Group. - * - * 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 APACHE SOFTWARE FOUNDATION 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - */ -package org.apache.tools.ant; - -public interface RoleAdapter { - - /** - * Obtain the id in case it is needed. - */ - public void setId(String id); - - /** - * Set the object being adapted. - * @param o the object being adapted - */ - public void setProxy(Object o); - - /** - * Get the object adapted by this class. - * @return the object being adapted, if any. - */ - public Object getProxy(); -} diff --git a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/SymbolTable.java b/proposal/sandbox/antlib/src/main/org/apache/tools/ant/SymbolTable.java deleted file mode 100644 index aa6fd78bd..000000000 --- a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/SymbolTable.java +++ /dev/null @@ -1,561 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * Copyright (c) 1999 The Apache Software Foundation. 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 - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowlegement may appear in the software itself, - * if and wherever such third-party acknowlegements normally appear. - * - * 4. The names "The Jakarta Project", "Ant", and "Apache Software - * Foundation" must not be used to endorse or promote products derived - * from this software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache" - * nor may "Apache" appear in their names without prior written - * permission of the Apache Group. - * - * 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 APACHE SOFTWARE FOUNDATION 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - */ -package org.apache.tools.ant; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.*; - -import org.apache.tools.ant.types.Path; - -public class SymbolTable { - - /** Parent symbol table */ - private SymbolTable parentTable; - - /** Project associated with this symbol table */ - private Project project; - - /** The table of roles available to this Project */ - private Hashtable roles = new Hashtable(); - - /** The table of loaders active on this Project */ - private Hashtable loaders = new Hashtable(); - - /** - * Table of per role definitions. - */ - private Hashtable defs = new Hashtable(); - - /** - * Parameters for checking adapters. - */ - private static final Class[] CHECK_ADAPTER_PARAMS = - new Class[]{Class.class, Project.class}; - - /** - * Create a top level Symbol table. - */ - public SymbolTable() { - } - - /** - * Create a symbol table inheriting the definitions - * from that defined in the calling Project. - * @param st the calling project - */ - public SymbolTable(SymbolTable st) { - parentTable = st; - } - - /** - * Set the project associated with this symbol table. - * @param p the project for this symbol table - */ - public void setProject(Project p) { - this.project = p; - } - - /** - * Get the specified loader for the project. - * @param name the name of the loader - * @return the corresponding ANT classloader - */ - private AntClassLoader getLoader(String name) { - AntClassLoader cl = (AntClassLoader) loaders.get(name); - if (cl == null && parentTable != null) { - return parentTable.getLoader(name); - } - return cl; - } - - /** - * Add the specified class-path to a loader. - * If the loader is defined in an ancestor project then a new - * classloader inheritin from the one already existing - * will be created, otherwise the path willbe added to the existing - * ClassLoader. - * @param name the name of the loader to use. - * @param clspath the path to be added to the classloader - */ - public ClassLoader addToLoader(String name, Path clspath) { - // Find if the loader is already defined in the current project - AntClassLoader cl = (AntClassLoader) loaders.get(name); - if (cl == null) { - // Is it inherited from the calling project - if (parentTable != null) { - cl = parentTable.getLoader(name); - } - cl = new AntClassLoader(cl, project, clspath, true); - loaders.put(name, cl); - } - else { - // Add additional path to the existing definition - String[] pathElements = clspath.list(); - for (int i = 0; i < pathElements.length; ++i) { - try { - cl.addPathElement(pathElements[i]); - } - catch (BuildException e) { - // ignore path elements invalid relative to the project - } - } - } - return cl; - } - - /** - * Find all the roles supported by a Class - * on this symbol table. - * @param clz the class to analyze - * @return an array of roles supported by the class - */ - public String[] findRoles(final Class clz) { - Vector list = new Vector(); - findRoles(clz, list); - return (String[])list.toArray(new String[list.size()]); - } - - /** - * Collect the roles for the class - * @param clz the class being inspected - * @param list the roles collected up to this point - */ - private void findRoles(final Class clz, Vector list) { - for (Enumeration e = roles.keys(); e.hasMoreElements();) { - String role = (String) e.nextElement(); - - if (((Role) roles.get(role)).isImplementedBy(clz)) { - list.addElement(role); - } - } - if (parentTable != null) parentTable.findRoles(clz, list); - } - - /** - * Get the Role definition - * @param role the name of the role - * @return the Role description - */ - public Role getRole(String role) { - Role r = (Role) roles.get(role); - if (r == null && parentTable != null) { - return parentTable.getRole(role); - } - return r; - } - - /** - * Add a new role definition to this project. - * @param role the name of the role - * @param rclz the interface used to specify support for the role. - * @param aclz the optional adapter class - * @return whether the role replaced a different definition - */ - public boolean addRole(String role, Class rclz, Class aclz) { - // Check if role already declared - Role old = getRole(role); - if (old != null && old.isSameAsFor(rclz, aclz)) { - project.log("Ignoring override for role " + role - + ", it is already defined by the same definition.", - project.MSG_VERBOSE); - return false; - } - // Role interfaces should only contain one method - roles.put(role, new Role(rclz, aclz)); - return (old != null); - } - - /** - * Add a new type of element to a role. - * @param role the role for this Class. - * @param name the name of the element for this Class - * @param clz the Class being declared - * @return the old definition - */ - public Class add(String role, String name, Class clz) { - // Find the role definition - Role r = getRole(role); - if (r == null) { - throw new BuildException("Unknown role: " + role); - } - // Check if it is already defined - Factory old = get(role, name); - if (old != null) { - if (old.getOriginalClass().equals(clz)) { - project.log("Ignoring override for "+ role + " " + name - + ", it is already defined by the same class.", - project.MSG_VERBOSE); - return old.getOriginalClass(); - } - else { - project.log("Trying to override old definition of " + - role + " " + name, - project.MSG_WARN); - } - } - Factory f = checkClass(clz); - // Check that the Class is compatible with the role definition - f = r.verifyAdaptability(role, f); - // Record the new type - Hashtable defTable = (Hashtable)defs.get(role); - if (defTable == null) { - defTable = new Hashtable(); - defs.put(role, defTable); - } - defTable.put(name, f); - - String msg = - " +User " + role + ": " + name + " " + clz.getName(); - project.log(msg, project.MSG_DEBUG); - return (old != null ? old.getOriginalClass() : null); - } - - /** - * Checks a class, whether it is suitable for serving in ANT. - * @return the factory to use when instantiating the class - * @throws BuildException and logs as Project.MSG_ERR for - * conditions, that will cause execution to fail. - */ - Factory checkClass(final Class clz) // Package on purpose - throws BuildException { - if (clz == null) return null; - - if(!Modifier.isPublic(clz.getModifiers())) { - final String message = clz + " is not public"; - project.log(message, Project.MSG_ERR); - throw new BuildException(message); - } - if(Modifier.isAbstract(clz.getModifiers())) { - final String message = clz + " is abstract"; - project.log(message, Project.MSG_ERR); - throw new BuildException(message); - } - try { - // Class can have a "no arg" constructor or take a single - // Project argument. - // don't have to check for public, since - // getConstructor finds public constructors only. - try { - clz.getConstructor(new Class[0]); - return new Factory(){ - public Object create(Project p) { - try { - return clz.newInstance(); - } - catch(Exception e) { - throw new BuildException(e); - } - } - - public Class getOriginalClass() { - return clz; - } - }; - } catch (NoSuchMethodException nse) { - final Constructor c = - clz.getConstructor(new Class[] {Project.class}); - return new Factory(){ - public Object create(Project p) { - try { - return c.newInstance(new Object[]{p}); - } - catch(Exception e) { - throw new BuildException(e); - } - } - - public Class getOriginalClass() { - return clz; - } - }; - } - } catch(NoSuchMethodException e) { - final String message = "No valid public constructor in " + clz; - project.log(message, Project.MSG_ERR); - throw new BuildException(message); - } - catch (NoClassDefFoundError ncdfe) { - final String msg = "Class cannot be loaded: " + ncdfe.getMessage(); - throw new BuildException(msg, ncdfe); - } - } - - /** - * Get the class in the role identified with the element name. - * @param role the role to look into. - * @param name the name of the element to sea - * @return the Class implementation - */ - public Factory get(String role, String name) { - Hashtable defTable = (Hashtable)defs.get(role); - if (defTable != null) { - Factory f = (Factory)defTable.get(name); - if (f != null) return f; - } - if (parentTable != null) { - return parentTable.get(role, name); - } - return null; - } - - /** - * Get a Hashtable that is usable for manipulating elements on Role. - * @param role the role of the elements in the table - * @return a Hashtable that delegates to the Symbol table. - */ - Hashtable getDefinitions(String role) { // package scope on purpose - return new SymbolHashtable(role); - } - - /** - * Hashtable implementation that delegates - * the search operations to the Symbol table - */ - private class SymbolHashtable extends Hashtable { - final String role; - SymbolHashtable(String role) { - this.role = role; - } - - public synchronized Object put(Object key, Object value) { - return SymbolTable.this.add(role, (String) key, (Class) value); - } - - public synchronized Object get(Object key) { - Factory f = SymbolTable.this.get(role, (String)key); - return (f == null? null : f.getOriginalClass()); - } - } - - /** - * Factory for creating ANT objects. - * Class objects are not instanciated directly but through a Factory - * which is able to resolve issues such as proxys and such. - */ - public static interface Factory { - /** - * Creates an object for the Role - * @param p the project in which it is created - * @return the instantiated object with a proxy if necessary - */ - public Object create(Project p); - - /** - * Creates an object for the Role, adapted if necessary - * for a particular interface. - */ -// public Object adaptFor(Class clz, Project p, Object o); - - /** - * The original class of the object without proxy. - */ - public Class getOriginalClass(); - } - - /** - * The definition of a role - */ - public class Role { - private Method interfaceMethod; - private Method adapterVerifier; - private Factory adapterFactory; - - /** - * Creates a new Role object - * @param roleClz the class that defines the role - * @param adapterClz the class for the adapter, or null if none - */ - Role(Class roleClz, Class adapterClz) { - interfaceMethod = validInterface(roleClz); - adapterFactory = checkClass(adapterClz); - adapterVerifier = validAdapter(adapterClz, interfaceMethod); - } - - /** - * Get the method used to set on interface - */ - public Method getInterfaceMethod() { - return interfaceMethod; - } - - /** - * Instantiate a new adapter for this role. - */ - public RoleAdapter createAdapter(Project p) { - if (adapterFactory == null) return null; - - try { - return (RoleAdapter) adapterFactory.create(p); - } - catch(BuildException be) { - throw be; - } - catch(Exception e) { - throw new BuildException(e); - } - } - - /** - * Verify if the class can be adapted to use by the role - * @param role the name of the role to verify - * @param f the factory for the class to verify - */ - public Factory verifyAdaptability(String role, final Factory f) { - final Class clz = f.getOriginalClass(); - if (interfaceMethod.getParameterTypes()[0].isAssignableFrom(clz)) { - return f; - } - if (adapterVerifier == null) { - String msg = "Class " + clz.getName() + - " incompatible with role: " + role; - throw new BuildException(msg); - } - try { - try { - adapterVerifier.invoke(null, new Object[]{clz, project}); - return new Factory(){ - public Object create(Project p) { - RoleAdapter ra = createAdapter(p); - ra.setProxy(f.create(p)); - return ra; - } - - public Class getOriginalClass() { - return clz; - } - }; - } - catch (InvocationTargetException ite) { - throw ite.getTargetException(); - } - } - catch(BuildException be) { throw be; } - catch(Error err) {throw err; } - catch(Throwable t) { - throw new BuildException(t); - } - } - - public boolean isSameAsFor(Class clz, Class pclz) { - return interfaceMethod.getDeclaringClass().equals(clz) && - ((adapterVerifier == null && pclz == null) || - adapterVerifier.getDeclaringClass().equals(pclz)); - } - - public boolean isImplementedBy(Class clz) { - return interfaceMethod.getDeclaringClass().isAssignableFrom(clz); - } - - /** - * Verify if the interface is valid. - * @param clz the interface to validate - * @return the method defined by the interface - */ - private Method validInterface(Class clz) { - Method m[] = clz.getDeclaredMethods(); - if (m.length == 1 - && java.lang.Void.TYPE.equals(m[0].getReturnType())) { - Class args[] = m[0].getParameterTypes(); - if (args.length == 1 - && !java.lang.String.class.equals(args[0]) - && !args[0].isArray() - && !args[0].isPrimitive()) { - return m[0]; - } - else { - throw new BuildException("Invalid role interface method in: " - + clz.getName()); - } - } - else { - throw new BuildException("More than one method on role interface"); - } - } - - /** - * Verify if the adapter is valid with respect to the interface. - * @param clz the class adapter to validate - * @param mtd the method whose only argument must match - * @return the static method to use for validating adaptees - */ - private Method validAdapter(Class clz, Method mtd) { - if (clz == null) return null; - - if (!mtd.getParameterTypes()[0].isAssignableFrom(clz)) { - String msg = "Adapter " + clz.getName() + - " is incompatible with role interface " + - mtd.getDeclaringClass().getName(); - throw new BuildException(msg); - } - String msg = "Class " + clz.getName() + " is not an adapter: "; - if (!RoleAdapter.class.isAssignableFrom(clz)) { - throw new BuildException(msg + "does not implement RoleAdapter"); - } - try { - Method chk = clz.getMethod("checkClass", CHECK_ADAPTER_PARAMS); - if (!Modifier.isStatic(chk.getModifiers())) { - throw new BuildException(msg + "checkClass() is not static"); - } - return chk; - } - catch(NoSuchMethodException nme){ - throw new BuildException(msg + "checkClass() not found", nme); - } - } - - } -} diff --git a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/TaskAdapter.java b/proposal/sandbox/antlib/src/main/org/apache/tools/ant/TaskAdapter.java deleted file mode 100644 index 077131c1b..000000000 --- a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/TaskAdapter.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * Copyright (c) 2000-2001 The Apache Software Foundation. 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 - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowlegement may appear in the software itself, - * if and wherever such third-party acknowlegements normally appear. - * - * 4. The names "The Jakarta Project", "Ant", and "Apache Software - * Foundation" must not be used to endorse or promote products derived - * from this software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache" - * nor may "Apache" appear in their names without prior written - * permission of the Apache Group. - * - * 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 APACHE SOFTWARE FOUNDATION 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - */ - -package org.apache.tools.ant; - -import java.lang.reflect.Method; -import java.lang.reflect.InvocationTargetException; - - - -/** - * Use introspection to "adapt" an arbitrary Bean ( not extending Task, but with similar - * patterns). - * - * @author costin@dnt.ro - * @author j_a_fernandez@yahoo.com - */ -public class TaskAdapter extends Task implements RoleAdapter { - - Object proxy; - - /** - * Checks a class, whether it is suitable to be adapted by TaskAdapter. - * - * Checks conditions only, which are additionally required for a tasks - * adapted by TaskAdapter. Thus, this method should be called by - * {@link Project#checkTaskClass}. - * - * Throws a BuildException and logs as Project.MSG_ERR for - * conditions, that will cause the task execution to fail. - * Logs other suspicious conditions with Project.MSG_WARN. - */ - public static void checkTaskClass(final Class taskClass, final Project project) { - // This code is for backward compatibility - checkClass(taskClass, project); - } - - /** - * Checks a class, whether it is suitable to be adapted. - * - * Checks conditions only, which are additionally required for a tasks - * adapted by TaskAdapter. - * - * Throws a BuildException and logs as Project.MSG_ERR for - * conditions, that will cause the task execution to fail. - * Logs other suspicious conditions with Project.MSG_WARN. - */ - public static void checkClass(final Class taskClass, final Project project) { - // don't have to check for interface, since then - // taskClass would be abstract too. - try { - final Method executeM = taskClass.getMethod( "execute", null ); - // don't have to check for public, since - // getMethod finds public method only. - // don't have to check for abstract, since then - // taskClass would be abstract too. - if(!Void.TYPE.equals(executeM.getReturnType())) { - final String message = "return type of execute() should be void but was \""+executeM.getReturnType()+"\" in " + taskClass; - project.log(message, Project.MSG_WARN); - } - } catch(NoSuchMethodException e) { - final String message = "No public execute() in " + taskClass; - project.log(message, Project.MSG_ERR); - throw new BuildException(message); - } - } - - /** - * Do the execution. - */ - public void execute() throws BuildException { - Method setProjectM = null; - try { - Class c = proxy.getClass(); - setProjectM = - c.getMethod( "setProject", new Class[] {Project.class}); - if(setProjectM != null) { - setProjectM.invoke(proxy, new Object[] {project}); - } - } catch (NoSuchMethodException e) { - // ignore this if the class being used as a task does not have - // a set project method. - } catch( Exception ex ) { - log("Error setting project in " + proxy.getClass(), - Project.MSG_ERR); - throw new BuildException( ex ); - } - - - Method executeM=null; - try { - Class c=proxy.getClass(); - executeM=c.getMethod( "execute", new Class[0] ); - if( executeM == null ) { - log("No public execute() in " + proxy.getClass(), Project.MSG_ERR); - throw new BuildException("No public execute() in " + proxy.getClass()); - } - executeM.invoke(proxy, null); - return; - } catch( InvocationTargetException ite ) { - Throwable t = ite.getTargetException(); - if (t instanceof BuildException) { - throw (BuildException) t; - } - throw new BuildException(t); - } catch( Exception ex ) { - log("Error in " + proxy.getClass(), Project.MSG_ERR); - throw new BuildException( ex ); - } - - } - - /** - * Set the target object class - */ - public void setProxy(Object o) { - this.proxy = o; - } - - public Object getProxy() { - return this.proxy ; - } - - public void setId(String id) {} -} diff --git a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/antlib.xml b/proposal/sandbox/antlib/src/main/org/apache/tools/ant/antlib.xml deleted file mode 100644 index 11481a323..000000000 --- a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/antlib.xml +++ /dev/null @@ -1,161 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/opt-antlib.xml b/proposal/sandbox/antlib/src/main/org/apache/tools/ant/opt-antlib.xml deleted file mode 100644 index f70e98771..000000000 --- a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/opt-antlib.xml +++ /dev/null @@ -1,179 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/taskdefs/Ant.java b/proposal/sandbox/antlib/src/main/org/apache/tools/ant/taskdefs/Ant.java deleted file mode 100644 index 7181f8d19..000000000 --- a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/taskdefs/Ant.java +++ /dev/null @@ -1,651 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * Copyright (c) 2000-2003 The Apache Software Foundation. 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 - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowlegement may appear in the software itself, - * if and wherever such third-party acknowlegements normally appear. - * - * 4. The names "Ant" and "Apache Software - * Foundation" must not be used to endorse or promote products derived - * from this software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache" - * nor may "Apache" appear in their names without prior written - * permission of the Apache Group. - * - * 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 APACHE SOFTWARE FOUNDATION 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - */ - -package org.apache.tools.ant.taskdefs; - -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.Vector; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.BuildListener; -import org.apache.tools.ant.DefaultLogger; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.ProjectComponent; -import org.apache.tools.ant.ProjectHelper; -import org.apache.tools.ant.Task; -import org.apache.tools.ant.util.FileUtils; - -/** - * 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>
- * 
- * - * - * @author Costin Manolache - * - * @since Ant 1.1 - * - * @ant.task category="control" - */ -public class Ant 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; - - /** - * If true, pass all properties to the new Ant project. - * Defaults to true. - */ - public void setInheritAll(boolean value) { - inheritAll = value; - } - - /** - * If true, pass all references to the new Ant project. - * Defaults to false. - */ - public void setInheritRefs(boolean value) { - inheritRefs = value; - } - - /** - * Creates a Project instance for the project to call. - */ - public void init() { - newProject = getProject().createSubProject(); - newProject.setDefaultInputStream(getProject().getDefaultInputStream()); - newProject.setJavaVersionProperty(); - /* newProject.addTaskDefinition("property", - (Class) getProject().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.getTaskDefinitions().get("property"); - newP.setName(p.getName()); - if (p.getValue() != null) { - newP.setValue(p.getValue()); - } - if (p.getFile() != null) { - newP.setFile(p.getFile()); - } - if (p.getResource() != null) { - newP.setResource(p.getResource()); - } - if (p.getPrefix() != null) { - newP.setPrefix(p.getPrefix()); - } - if (p.getRefid() != null) { - newP.setRefid(p.getRefid()); - } - if (p.getEnvironment() != null) { - newP.setEnvironment(p.getEnvironment()); - } - if (p.getClasspath() != null) { - newP.setClasspath(p.getClasspath()); - } - properties.setElementAt(newP, i); - } - } - - /** - * Attaches the build listeners of the current project to the new - * project, configures a possible logfile, transfers task and - * data-type definitions, transfers properties (either all or just - * the ones specified as user properties to the current project, - * depending on inheritall), transfers the input handler. - */ - private void initializeProject() { - newProject.setInputHandler(getProject().getInputHandler()); - - Vector listeners = getProject().getBuildListeners(); - final int count = listeners.size(); - for (int i = 0; i < count; i++) { - newProject.addBuildListener((BuildListener) listeners.elementAt(i)); - } - - if (output != null) { - File outfile = null; - if (dir != null) { - outfile = FileUtils.newFileUtils().resolveFile(dir, output); - } else { - outfile = getProject().resolveFile(output); - } - try { - out = new PrintStream(new FileOutputStream(outfile)); - DefaultLogger logger = new DefaultLogger(); - logger.setMessageOutputLevel(Project.MSG_INFO); - logger.setOutputPrintStream(out); - logger.setErrorPrintStream(out); - newProject.addBuildListener(logger); - } catch (IOException ex) { - log("Ant: Can't set output to " + output); - } - } - - Hashtable taskdefs = getProject().getTaskDefinitions(); - Enumeration et = taskdefs.keys(); - while (et.hasMoreElements()) { - String taskName = (String) et.nextElement(); - Class taskClass = (Class) taskdefs.get(taskName); - newProject.addTaskDefinition(taskName, taskClass); - } - - Hashtable typedefs = getProject().getDataTypeDefinitions(); - Enumeration e = typedefs.keys(); - while (e.hasMoreElements()) { - String typeName = (String) e.nextElement(); - Class typeClass = (Class) typedefs.get(typeName); - newProject.addDataTypeDefinition(typeName, typeClass); - } - - // set user-defined properties - getProject().copyUserProperties(newProject); - - if (!inheritAll) { - // set Java built-in properties separately, - // b/c we won't inherit them. - newProject.setSystemProperties(); - - } else { - // set all properties from calling project - - Hashtable props = getProject().getProperties(); - e = props.keys(); - while (e.hasMoreElements()) { - String arg = e.nextElement().toString(); - if ("basedir".equals(arg) || "ant.file".equals(arg)) { - // basedir and ant.file get special treatment in execute() - continue; - } - - String value = props.get(arg).toString(); - // don't re-set user properties, avoid the warning message - if (newProject.getProperty(arg) == null){ - // no user property - newProject.setNewProperty(arg, value); - } - } - } - } - - /** - * Pass output sent to System.out to the new project. - * - * @since Ant 1.5 - */ - public void handleOutput(String line) { - if (newProject != null) { - newProject.demuxOutput(line, false); - } else { - super.handleOutput(line); - } - } - - /** - * @see Task#handleInput(byte[], int, int) - * - * @since Ant 1.6 - */ - public int handleInput(byte[] buffer, int offset, int length) - throws IOException { - if (newProject != null) { - return newProject.demuxInput(buffer, offset, length); - } else { - return super.handleInput(buffer, offset, length); - } - } - - /** - * Pass output sent to System.out to the new project. - * - * @since Ant 1.5.2 - */ - public void handleFlush(String line) { - if (newProject != null) { - newProject.demuxFlush(line, false); - } else { - super.handleFlush(line); - } - } - - /** - * Pass output sent to System.err to the new project. - * - * @since Ant 1.5 - */ - public void handleErrorOutput(String line) { - if (newProject != null) { - newProject.demuxOutput(line, true); - } else { - super.handleErrorOutput(line); - } - } - - /** - * Pass output sent to System.err to the new project. - * - * @since Ant 1.5.2 - */ - public void handleErrorFlush(String line) { - if (newProject != null) { - newProject.demuxFlush(line, true); - } else { - super.handleErrorFlush(line); - } - } - - /** - * Do the execution. - */ - public void execute() throws BuildException { - File savedDir = dir; - String savedAntFile = antFile; - String savedTarget = target; - try { - if (newProject == null) { - reinit(); - } - - if ((dir == null) && (inheritAll)) { - dir = getProject().getBaseDir(); - } - - initializeProject(); - - if (dir != null) { - newProject.setBaseDir(dir); - if (savedDir != null) { // has been set explicitly - newProject.setInheritedProperty("basedir" , - dir.getAbsolutePath()); - } - } else { - dir = getProject().getBaseDir(); - } - - overrideProperties(); - - if (antFile == null) { - antFile = "build.xml"; - } - - File file = FileUtils.newFileUtils().resolveFile(dir, antFile); - antFile = file.getAbsolutePath(); - - log("calling target " + (target != null ? target : "[default]") - + " in build file " + antFile.toString(), - Project.MSG_VERBOSE); - newProject.setUserProperty("ant.file" , antFile); - ProjectHelper.configureProject(newProject, new File(antFile)); - - if (target == null) { - target = newProject.getDefaultTarget(); - } - - // Are we trying to call the target in which we are defined (or - // the build file if this is a top level task)? - if (newProject.getBaseDir().equals(getProject().getBaseDir()) && - newProject.getProperty("ant.file").equals(getProject().getProperty("ant.file")) - && getOwningTarget() != null - && (getOwningTarget().getName().equals("") || - getOwningTarget().getName().equals(target))) { - throw new BuildException("ant task calling its own parent " - + "target"); - } - - addReferences(); - - if (target != null) { - newProject.executeTarget(target); - } else { - newProject.executeTarget(""); - } - } finally { - // help the gc - newProject = null; - Enumeration enum = properties.elements(); - while (enum.hasMoreElements()) { - Property p = (Property) enum.nextElement(); - p.setProject(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. - */ - 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. - */ - private void addReferences() throws BuildException { - Hashtable thisReferences - = (Hashtable) getProject().getReferences().clone(); - Hashtable newReferences = newProject.getReferences(); - Enumeration e; - if (references.size() > 0) { - for (e = references.elements(); e.hasMoreElements();) { - Reference ref = (Reference) e.nextElement(); - String refid = ref.getRefId(); - if (refid == null) { - throw new BuildException("the refid attribute is required" - + " for reference elements"); - } - if (!thisReferences.containsKey(refid)) { - log("Parent project doesn't contain any reference '" - + refid + "'", - Project.MSG_WARN); - continue; - } - - thisReferences.remove(refid); - String toRefid = ref.getToRefid(); - if (toRefid == null) { - toRefid = refid; - } - copyReference(refid, toRefid); - } - } - - // Now add all references that are not defined in the - // subproject, if inheritRefs is true - if (inheritRefs) { - for (e = thisReferences.keys(); e.hasMoreElements();) { - String key = (String) e.nextElement(); - if (newReferences.containsKey(key)) { - continue; - } - copyReference(key, key); - } - } - } - - /** - * Try to clone and reconfigure the object referenced by oldkey in - * the parent project and add it to the new project with the key - * newkey. - * - *

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

- */ - private void copyReference(String oldKey, String newKey) { - Object orig = getProject().getReference(oldKey); - if (orig == null) { - log("No object referenced by " + oldKey + ". Can't copy to " - + newKey, - Project.MSG_WARN); - return; - } - - 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]); - log("Adding clone of reference " + oldKey, Project.MSG_DEBUG); - } - } catch (Exception e) { - // not Clonable - } - - - if (copy instanceof ProjectComponent) { - ((ProjectComponent) copy).setProject(newProject); - } else { - try { - Method setProjectM = - c.getMethod("setProject", new Class[] {Project.class}); - if (setProjectM != null) { - setProjectM.invoke(copy, new Object[] {newProject}); - } - } catch (NoSuchMethodException e) { - // ignore this if the class being referenced does not have - // a set project method. - } catch (Exception e2) { - String msg = "Error setting new project instance for " - + "reference with id " + oldKey; - throw new BuildException(msg, e2, getLocation()); - } - } - newProject.addReference(newKey, copy); - } - - /** - * The directory to use as a base directory for the new Ant project. - * Defaults to the current project's basedir, unless inheritall - * has been set to false, in which case it doesn't have a default - * value. This will override the basedir setting of the called project. - */ - 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. - */ - 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. - */ - public void setTarget(String s) { - if (s.equals("")) { - throw new BuildException("target attribute must not be empty"); - } - - 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. - */ - public void setOutput(String s) { - this.output = s; - } - - /** - * Property to pass to the new project. - * The property is passed as a 'user property' - */ - public Property createProperty() { - if (newProject == null) { - reinit(); - } - Property p = new Property(true, getProject()); - p.setProject(newProject); - p.setTaskName("property"); - properties.addElement(p); - return p; - } - - /** - * Reference element identifying a data type to carry - * over to the new project. - */ - public void addReference(Reference r) { - references.addElement(r); - } - - /** - * Helper class that implements the nested <reference> - * element of <ant> and <antcall>. - */ - public static class Reference - extends org.apache.tools.ant.types.Reference { - - /** Creates a reference to be configured by Ant */ - public Reference() { - super(); - } - - private String targetid = null; - - /** - * Set the id that this reference to be stored under in the - * new project. - * - * @param targetid the id under which this reference will be passed to - * the new project */ - public void setToRefid(String targetid) { - this.targetid = targetid; - } - - /** - * Get the id under which this reference will be stored in the new - * project - * - * @return the id of the reference in the new project. - */ - public String getToRefid() { - return targetid; - } - } -} diff --git a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/taskdefs/Antjar.java b/proposal/sandbox/antlib/src/main/org/apache/tools/ant/taskdefs/Antjar.java deleted file mode 100644 index 96db8fffe..000000000 --- a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/taskdefs/Antjar.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * Copyright (c) 2000,2003 The Apache Software Foundation. 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 - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowlegement may appear in the software itself, - * if and wherever such third-party acknowlegements normally appear. - * - * 4. The names "The Jakarta Project", "Ant", and "Apache Software - * Foundation" must not be used to endorse or promote products derived - * from this software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache" - * nor may "Apache" appear in their names without prior written - * permission of the Apache Group. - * - * 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 APACHE SOFTWARE FOUNDATION 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - */ -package org.apache.tools.ant.taskdefs; - - -import org.apache.tools.ant.*; -import org.apache.tools.ant.types.ZipFileSet; -import org.apache.tools.zip.*; - -import java.io.*; - -/** - * Creates a ANTLIB archive. Code is similar to the War class, but with - * bonus dtd validation. - * - * @author doc and layout changes by steve loughran, steve_l@iseran.com - * @author Jose Alberto Fernandez - * @author Stefan Bodewig - * - * @since ant1.5 - */ -public class Antjar extends Jar { - - /** - * location of the xml descriptor (antxml attribute) - */ - private File libraryDescriptor; - - /** - * status flag - */ - private boolean descriptorAdded; - - - /** - * Constructor for the Antjar object - */ - public Antjar() { - super(); - archiveType = "jar"; - emptyBehavior = "create"; - } - - - /** - * Sets the Antxml attribute of the Antjar object - * - * @param descriptor The new Antxml value - */ - public void setAntxml(File descriptor) { - libraryDescriptor = descriptor; - if (!libraryDescriptor.exists()) { - throw new BuildException("Deployment descriptor: " + - libraryDescriptor + " does not exist."); - } - - // Create a ZipFileSet for this file, and pass it up. - ZipFileSet fs = new ZipFileSet(); - fs.setDir(new File(libraryDescriptor.getParent())); - fs.setIncludes(libraryDescriptor.getName()); - fs.setFullpath(Antlib.ANT_DESCRIPTOR); - super.addFileset(fs); - } - - - /** - * override of superclass method; add check for - * valid descriptor - * @param zOut stream to init - * @exception IOException io trouble - * @exception BuildException other trouble - */ - protected void initZipOutputStream(ZipOutputStream zOut) - throws IOException, BuildException { - // If no antxml file is specified, it's an error. - if (libraryDescriptor == null) { - throw new BuildException("antxml attribute is required", - getLocation()); - } - - super.initZipOutputStream(zOut); - } - - - /** - * override of parent method; warn if a second descriptor is added - * - * @param file file to add - * @param zOut stream to add to - * @param vPath the path to add it to in the zipfile - * @param mode the Unix permissions to set. - * @exception IOException io trouble - */ - protected void zipFile(File file, ZipOutputStream zOut, String vPath, int mode) - throws IOException { - // If the file being added is META-INF/antlib.xml, we warn if it's not the - // one specified in the "antxml" attribute - or if it's being added twice, - // meaning the same file is specified by the "antxml" attribute and in - // a element. - if (vPath.equalsIgnoreCase(Antlib.ANT_DESCRIPTOR)) { - if (libraryDescriptor == null || - !libraryDescriptor.equals(file) || descriptorAdded) { - log("Warning: selected " + archiveType + " files include a " + - Antlib.ANT_DESCRIPTOR + " which will be ignored " + - "(please use antxml attribute to " + archiveType + - " task)", Project.MSG_WARN); - } - else { - super.zipFile(file, zOut, vPath, mode); - descriptorAdded = true; - } - } - else { - super.zipFile(file, zOut, vPath, mode); - } - } - - - /** - * Make sure we don't think we already have a descriptor next time this - * task gets executed. - */ - protected void cleanUp() { - descriptorAdded = false; - super.cleanUp(); - } - -} diff --git a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/taskdefs/Antlib-V1_0.dtd b/proposal/sandbox/antlib/src/main/org/apache/tools/ant/taskdefs/Antlib-V1_0.dtd deleted file mode 100644 index 66da10858..000000000 --- a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/taskdefs/Antlib-V1_0.dtd +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/taskdefs/Antlib.java b/proposal/sandbox/antlib/src/main/org/apache/tools/ant/taskdefs/Antlib.java deleted file mode 100644 index 29f7c1fa3..000000000 --- a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/taskdefs/Antlib.java +++ /dev/null @@ -1,883 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * Copyright (c) 1999,2003 The Apache Software Foundation. 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 - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowlegement may appear in the software itself, - * if and wherever such third-party acknowlegements normally appear. - * - * 4. The names "The Jakarta Project", "Ant", and "Apache Software - * Foundation" must not be used to endorse or promote products derived - * from this software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache" - * nor may "Apache" appear in their names without prior written - * permission of the Apache Group. - * - * 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 APACHE SOFTWARE FOUNDATION 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - */ -package org.apache.tools.ant.taskdefs; - -import org.apache.tools.ant.*; -import org.apache.tools.ant.types.*; -import org.xml.sax.*; -import javax.xml.parsers.*; - -import java.util.*; -import java.util.zip.*; -import java.io.*; -import java.net.*; - -/** - * Make available the tasks and types from an Ant library.
- * <antlib library="libname.jar" >
- *   <alias name="nameOnLib" as="newName" />
- * </antlib>
- *
- * <antlib file="libname.jar" override="true" />
- * 
- * - * @author minor changes by steve loughran, steve_l@iseran.com - * @author Jose Alberto Fernandez - * @since ant1.5 - */ -public class Antlib extends Task { - - /** - * Location of descriptor in library - */ - public static final String ANT_DESCRIPTOR = "META-INF/antlib.xml"; - - /** - * The named classloader to use. - * Defaults to the default classLoader. - */ - private String loaderId = ""; - - /** - * file attribute - */ - private File file = null; - /** - * override attribute - */ - private boolean override = false; - /** - * attribute to control failure when loading - */ - private FailureAction onerror = new FailureAction(); - - /** - * classpath to build up - */ - private Path classpath = null; - - - /** - * our little xml parse - */ - private SAXParserFactory saxFactory; - - /** - * table of aliases - */ - private Vector aliases = new Vector(); - - /** - * Some internal constants. - */ - private static final int FAIL = 0, REPORT = 1, IGNORE = 2; - - /** - * Posible actions when classes are not found - */ - public static class FailureAction extends EnumeratedAttribute { - public String[] getValues() { - return new String[]{"fail", "report", "ignore"}; - } - } - - private static class DescriptorEnumeration implements Enumeration { - - /** - * The name of the resource being searched for. - */ - private String resourceName; - - /** - * The index of the next file to search. - */ - private int index; - - /** - * The list of files to search - */ - private File files[]; - - /** - * The URL of the next resource to return in the enumeration. If this - * field is null then the enumeration has been completed, - * i.e., there are no more elements to return. - */ - private URL nextDescriptor; - - /** - * Construct a new enumeration of resources of the given name found - * within this class loader's classpath. - * - * @param name the name of the resource to search for. - */ - DescriptorEnumeration(String fileNames[], String name) { - this.resourceName = name; - this.index = 0; - this.files = new File[fileNames.length]; - for (int i = 0; i < files.length; i++) { - files[i] = new File(fileNames[i]); - } - findNextDescriptor(); - } - - /** - * Indicates whether there are more elements in the enumeration to - * return. - * - * @return true if there are more elements in the - * enumeration; false otherwise. - */ - public boolean hasMoreElements() { - return (this.nextDescriptor != null); - } - - /** - * Returns the next resource in the enumeration. - * - * @return the next resource in the enumeration. - */ - public Object nextElement() { - URL ret = this.nextDescriptor; - findNextDescriptor(); - return ret; - } - - /** - * Locates the next descriptor of the correct name in the files and - * sets nextDescriptor to the URL of that resource. If no - * more resources can be found, nextDescriptor is set to - * null. - */ - private void findNextDescriptor() { - URL url = null; - while (index < files.length && url == null) { - try { - url = getDescriptorURL(files[index], this.resourceName); - index++; - } - catch (BuildException e) { - // ignore path elements which are not valid relative to the - // project - } - } - this.nextDescriptor = url; - } - - /** - * Get an URL to a given resource in the given file which may - * either be a directory or a zip file. - * - * @param file the file (directory or jar) in which to search for - * the resource. Must not be null. - * @param resourceName the name of the resource for which a URL - * is required. Must not be null. - * - * @return a URL to the required resource or null if the - * resource cannot be found in the given file object - * @todo This code is extracted from AntClassLoader.getResourceURL - * I hate when that happens but the code there is too tied to - * the ClassLoader internals. Maybe we can find a nice place - * to put it where both can use it. - */ - private URL getDescriptorURL(File file, String resourceName) { - try { - if (!file.exists()) { - return null; - } - - if (file.isDirectory()) { - File resource = new File(file, resourceName); - - if (resource.exists()) { - try { - return new URL("file:"+resource.toString()); - } catch (MalformedURLException ex) { - return null; - } - } - } - else { - ZipFile zipFile = new ZipFile(file); - try { - ZipEntry entry = zipFile.getEntry(resourceName); - if (entry != null) { - try { - return new URL("jar:file:"+file.toString()+"!/"+entry); - } catch (MalformedURLException ex) { - return null; - } - } - } - finally { - zipFile.close(); - } - } - } - catch (Exception e) { - e.printStackTrace(); - } - - return null; - } - - } - - /** - * constructor creates a validating sax parser - */ - public Antlib() { - super(); - // Default error action - onerror.setValue("report"); - saxFactory = SAXParserFactory.newInstance(); - saxFactory.setValidating(false); - } - - - /** - * constructor binds to a project and sets ignore mode on errors - * - * @param p Description of Parameter - */ - public Antlib(Project p) { - this(); - setProject(p); - } - - - /** - * Set name of library to load. The library is located in $ANT_HOME/antlib. - * - * @param lib the name of library relative to $ANT_HOME/antlib. - */ - public void setLibrary(String lib) { - setFile(libraryFile("antlib", lib)); - } - - - /** - * Set file location of library to load. - * - * @param file the jar file for the library. - */ - public void setFile(File file) { - this.file = file; - } - - /** - * Set the ID of the ClassLoader to use for this library. - * - * @param id the id for the ClassLoader to use, - * null means use ANT's core classloader. - */ - public void setLoaderid(String id) { - this.loaderId = id; - } - - /** - * Set whether to override any existing definitions. - * - * @param override if true new definitions will replace existing ones. - */ - public void setOverride(boolean override) { - this.override = override; - } - - - /** - * Get what to do if a definition cannot be loaded - * This method is mostly used by the core when loading core tasks. - * - * @return what to do if a definition cannot be loaded - */ - final protected FailureAction getOnerror() { - return this.onerror; - } - - - /** - * Set whether to fail if a definition cannot be loaded - * Default is true. - * This property is mostly used by the core when loading core tasks. - * - * @param onerror if true loading will stop if classes - * cannot be instantiated - */ - public void setOnerror(FailureAction onerror) { - this.onerror = onerror; - } - - - /** - * Create new Alias element. - * - * @return Description of the Returned Value - */ - public Alias createAlias() { - Alias als = new Alias(); - aliases.add(als); - return als; - } - - - /** - * Set the classpath to be used for this compilation - * - * @param cp The new Classpath value - */ - public void setClasspath(Path cp) { - if (classpath == null) { - classpath = cp; - } - else { - classpath.append(cp); - } - } - - - /** - * create a nested classpath element. - * - * @return classpath to use - */ - public Path createClasspath() { - if (classpath == null) { - classpath = new Path(getProject()); - } - return classpath.createPath(); - } - - - /** - * Adds a reference to a CLASSPATH defined elsewhere - * - * @param r The new ClasspathRef value - */ - public void setClasspathRef(Reference r) { - createClasspath().setRefid(r); - } - - - /** - * Obtain library file from ANT_HOME directory. - * - * @param lib the library name. - * @return the File instance of the library - */ - private File libraryFile(String homeSubDir, String lib) { - // For the time being libraries live in $ANT_HOME/antlib. - // The idea being that not to load all the jars there anymore - String home = getProject().getProperty("ant.home"); - - if (home == null) { - throw new BuildException("ANT_HOME not set as required."); - } - - return new File(new File(home, homeSubDir), lib); - } - - /** - * actually do the work of loading the library - * - * @exception BuildException Description of Exception - */ - public void execute() - throws BuildException { - if (file == null && classpath == null) { - String msg = - "Must specify either library or file attribute or classpath."; - throw new BuildException(msg, getLocation()); - } - if (file != null && !file.exists()) { - String msg = "Cannot find library: " + file; - throw new BuildException(msg, getLocation()); - } - - loadDefinitions(); - } - - - /** - * Load definitions in library and classpath - * - * @exception BuildException failure to access the resource - */ - public boolean loadDefinitions() throws BuildException { - return loadDefinitions(ANT_DESCRIPTOR); - } - - /** - * Load definitions from resource name in library and classpath - * - * @param res the name of the resources to load - * @exception BuildException failure to access the resource - */ - final protected boolean loadDefinitions(String res) - throws BuildException { - Path path = makeLoaderClasspath(); - ClassLoader cl = makeClassLoader(path); - boolean found = false; - try { - for (Enumeration e = getDescriptors(path, res); e.hasMoreElements(); ) { - URL resURL = (URL)e.nextElement(); - InputStream is = resURL.openStream(); - loadDefinitions(cl, is); - found = true; - } - if (!found && onerror.getIndex() != IGNORE) { - String sPath = path.toString(); - if ("".equals(sPath.trim())) { - sPath = System.getProperty("java.classpath"); - } - String msg = "Cannot find any " + res + - " antlib descriptors in: " + sPath; - switch (onerror.getIndex()) { - case FAIL: - throw new BuildException(msg); - case REPORT: - log(msg, Project.MSG_WARN); - } - } - } - catch (IOException io) { - String msg = "Cannot load definitions from: " + res; - switch (onerror.getIndex()) { - case FAIL: - throw new BuildException(msg, io); - case REPORT: - log(io.getMessage(), Project.MSG_WARN); - } - } - return found; - } - - - /** - * Load definitions directly from InputStream. - * - * @param is InputStream for the Antlib descriptor. - * @exception BuildException trouble - */ - private void loadDefinitions(ClassLoader cl, InputStream is) - throws BuildException { - evaluateDescriptor(cl, processAliases(), is); - } - - - /** - * get an Enumeration of URLs for all resouces corresponding to the - * descriptor name. - * - * @param res the name of the resource to collect - * @return input stream to the Descriptor or null if none existent - * @exception BuildException io trouble, or it isnt a zipfile - */ - private Enumeration getDescriptors(Path path, final String res) - throws BuildException, IOException { - if (loaderId == null) { - // Path cannot be added to the CoreLoader so simply - // ask for all instances of the resource descriptors - return getProject().getCoreLoader().getResources(res); - } - - return new DescriptorEnumeration(path.list(), res); - } - - - /** - * turn the alias list to a property hashtable - * - * @return generated property hashtable - */ - private Properties processAliases() { - Properties p = new Properties(); - - for (Enumeration e = aliases.elements(); e.hasMoreElements(); ) { - Alias a = (Alias) e.nextElement(); - p.put(a.name, a.as); - } - return p; - } - - - /** - * create the classpath for this library from the file passed in and - * any classpath parameters - * - * @param clspath library file to use - * @return classloader using te - * @exception BuildException trouble creating the classloader - */ - protected ClassLoader makeClassLoader(Path clspath) - throws BuildException { - if (loaderId == null) { - log("Loading definitions from CORE, ignored", - Project.MSG_VERBOSE); - return getProject().getCoreLoader(); - } - - log("Using ClassLoader '" + loaderId + "' to load path: " + clspath, - Project.MSG_VERBOSE); - return getProject().addToLoader(loaderId, clspath); - } - - - /** - * Constructs the Path to add to the ClassLoader - */ - private Path makeLoaderClasspath() - { - Path clspath = new Path(getProject()); - if (file != null) clspath.setLocation(file); - //append any build supplied classpath - if (classpath != null) { - clspath.append(classpath); - } - return clspath; - } - - /** - * parse the antlib descriptor - * - * @param cl optional classloader - * @param als alias list as property hashtable - * @param is input stream to descriptor - * @exception BuildException trouble - */ - protected void evaluateDescriptor(ClassLoader cl, - Properties als, InputStream is) - throws BuildException { - try { - SAXParser saxParser = saxFactory.newSAXParser(); - - InputSource inputSource = new InputSource(is); - //inputSource.setSystemId(uri); //URI is nasty for jar entries - getProject().log("parsing descriptor for library: " + file, - Project.MSG_VERBOSE); - saxParser.parse(inputSource, new AntLibraryHandler(cl, als)); - } - catch (ParserConfigurationException exc) { - throw new BuildException("Parser has not been configured correctly", exc); - } - catch (SAXParseException exc) { - Location location = - new Location(ANT_DESCRIPTOR, - exc.getLineNumber(), exc.getColumnNumber()); - - Throwable t = exc.getException(); - if (t instanceof BuildException) { - BuildException be = (BuildException) t; - if (be.getLocation() == Location.UNKNOWN_LOCATION) { - be.setLocation(location); - } - throw be; - } - throw new BuildException(exc.getMessage(), t, location); - } - catch (SAXException exc) { - Throwable t = exc.getException(); - if (t instanceof BuildException) { - throw (BuildException) t; - } - throw new BuildException(exc.getMessage(), t); - } - catch (IOException exc) { - throw new BuildException("Error reading library descriptor", exc); - } - finally { - if (is != null) { - try { - is.close(); - } - catch (IOException ioe) { - // ignore this - } - } - } - } - - - /** - * Parses the document describing the content of the - * library. An inner class for access to Project.log - */ - private class AntLibraryHandler extends HandlerBase { - - /** - * our classloader - */ - private final ClassLoader classloader; - /** - * the aliases - */ - private final Properties aliasMap; - /** - * doc locator - */ - private Locator locator = null; - - private int level = 0; - - private String name = null; - private String className = null; - private String adapter = null; - - /** - * Constructor for the AntLibraryHandler object - * - * @param classloader optional classloader - * @param als alias list - */ - AntLibraryHandler(ClassLoader classloader, Properties als) { - this.classloader = classloader; - this.aliasMap = als; - } - - /** - * Sets the DocumentLocator attribute of the AntLibraryHandler - * object - * - * @param locator The new DocumentLocator value - */ - public void setDocumentLocator(Locator locator) { - this.locator = locator; - } - - private void parseAttributes(String tag, AttributeList attrs) - throws SAXParseException { - name = null; - className = null; - adapter = null; - - for (int i = 0, last = attrs.getLength(); i < last; i++) { - String key = attrs.getName(i); - String value = attrs.getValue(i); - - if (key.equals("name")) { - name = value; - } - else if (key.equals("class")) { - className = value; - } - else if ("role".equals(tag) && key.equals("adapter")) { - adapter = value; - } - else { - throw new SAXParseException("Unexpected attribute \"" - + key + "\"", locator); - } - } - if (name == null || className == null) { - String msg = "Underspecified " + tag + " declaration."; - throw new SAXParseException(msg, locator); - } - } - - /** - * SAX callback handler - * - * @param tag XML tag - * @param attrs attributes - * @exception SAXParseException parse trouble - */ - public void startElement(String tag, AttributeList attrs) - throws SAXParseException { - level ++; - if ("antlib".equals(tag)) { - if (level > 1) { - throw new SAXParseException("Unexpected element: " + tag, - locator); - } - // No attributes to worry about - return; - } - if (level == 1) { - throw new SAXParseException("Missing antlib root element", - locator); - } - - // Must have the two attributes declared - parseAttributes(tag, attrs); - - try { - if ("role".equals(tag)) { - if (getProject().isRoleDefined(name)) { - String msg = "Cannot override role: " + name; - log(msg, Project.MSG_WARN); - return; - } - // Defining a new role - Class clz = loadClass(className); - if (clz != null) { - getProject().addRoleDefinition(name, clz, - (adapter == null? null : - loadClass(adapter))); - } - return; - } - - // Defining a new element kind - //check for name alias - String alias = aliasMap.getProperty(name); - if (alias != null) { - name = alias; - } - //catch an attempted override of an existing name - if (!override && getProject().isDefinedOnRole(tag, name)) { - String msg = "Cannot override " + tag + ": " + name; - log(msg, Project.MSG_WARN); - return; - } - Class clz = loadClass(className); - if (clz != null) - getProject().addDefinitionOnRole(tag, name, clz); - } - catch(BuildException be) { - switch (onerror.getIndex()) { - case FAIL: - throw new SAXParseException(be.getMessage(), locator, be); - case REPORT: - getProject().log(be.getMessage(), Project.MSG_WARN); - break; - default: - getProject().log(be.getMessage(), Project.MSG_DEBUG); - } - } - } - - public void endElement(String tag) { - level--; - } - - private Class loadClass(String className) - throws SAXParseException { - String msg = null; - try { - //load the named class - Class cls; - if(classloader==null) { - cls=Class.forName(className); - } - else { - cls=classloader.loadClass(className); - } - return cls; - } - catch (ClassNotFoundException cnfe) { - msg = "Class " + className + " cannot be found"; - if (onerror.getIndex() == FAIL) - throw new SAXParseException(msg, locator, cnfe); - } - catch (NoClassDefFoundError ncdfe) { - msg = "Class " + className + " cannot be loaded"; - if (onerror.getIndex() == FAIL) - throw new SAXParseException(msg, locator); - } - - if (onerror.getIndex() == REPORT) { - getProject().log(msg, Project.MSG_WARN); - } - else { - getProject().log(msg, Project.MSG_DEBUG); - } - return null; - } - - //end inner class AntLibraryHandler - } - - - /** - * this class is used for alias elements - * - * @author slo - * @created 11 November 2001 - */ - public static class Alias { - /** - * Description of the Field - */ - private String name; - /** - * Description of the Field - */ - private String as; - - - /** - * Sets the Name attribute of the Alias object - * - * @param name The new Name value - */ - public void setName(String name) { - this.name = name; - } - - - /** - * Sets the As attribute of the Alias object - * - * @param as The new As value - */ - public void setAs(String as) { - this.as = as; - } - //end inner class alias - } - -//end class Antlib -} - - diff --git a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/types/DataTypeAdapterTask.java b/proposal/sandbox/antlib/src/main/org/apache/tools/ant/types/DataTypeAdapterTask.java deleted file mode 100644 index 4669a0789..000000000 --- a/proposal/sandbox/antlib/src/main/org/apache/tools/ant/types/DataTypeAdapterTask.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * Copyright (c) 2000-2001 The Apache Software Foundation. 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 - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowlegement may appear in the software itself, - * if and wherever such third-party acknowlegements normally appear. - * - * 4. The names "The Jakarta Project", "Ant", and "Apache Software - * Foundation" must not be used to endorse or promote products derived - * from this software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache" - * nor may "Apache" appear in their names without prior written - * permission of the Apache Group. - * - * 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 APACHE SOFTWARE FOUNDATION 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - */ - -package org.apache.tools.ant.types; - -import java.lang.reflect.Method; -import org.apache.tools.ant.*; - - -/** - * Use introspection to "adapt" a DataType to be accepted in a Task position - * - * @author j_a_fernandez@yahoo.com - */ -public class DataTypeAdapterTask extends Task implements RoleAdapter { - - Object proxy; - String id = null; - - /** - * Checks a class, whether it is suitable to be adapted. - * - * Throws a BuildException and logs as Project.MSG_ERR for - * conditions, that will cause the task execution to fail. - * Logs other suspicious conditions with Project.MSG_WARN. - */ - public static void checkClass(final Class typeClass, - final Project project) { - // Any class can be used as a data type - } - - /** - * Do the execution. - */ - public void execute() throws BuildException { - if (id != null) { - // Need to re-register this reference - // The container has register the Adapter instead - project.addReference(id, proxy); - } - } - - /** - * Propagate configuration of Project - */ - public void setProject(Project p) { - super.setProject(p); - - // Check to see if the DataType has a setProject method to set - if (proxy instanceof ProjectComponent) { - ((ProjectComponent)proxy).setProject(p); - return; - } - - // This may not be needed - // We are trying to set project even if is was not declared - // just like TaskAdapter does for beans, this is not done - // by the original code - Method setProjectM = null; - try { - Class c = proxy.getClass(); - setProjectM = - c.getMethod( "setProject", new Class[] {Project.class}); - if(setProjectM != null) { - setProjectM.invoke(proxy, new Object[] {p}); - } - } catch (NoSuchMethodException e) { - // ignore this if the class being used as a task does not have - // a set project method. - } catch( Exception ex ) { - log("Error setting project in " + proxy.getClass(), - Project.MSG_ERR); - throw new BuildException( ex ); - } - } - - /** - * Set the target object class - */ - public void setProxy(Object o) { - this.proxy = o; - } - - public Object getProxy() { - return this.proxy ; - } - - public void setId(String id) { - log("Setting adapter id to: " + id, Project.MSG_DEBUG); - this.id = id; - } -} diff --git a/proposal/sandbox/antlib/src/testcases/build.xml b/proposal/sandbox/antlib/src/testcases/build.xml deleted file mode 100644 index e0f34f241..000000000 --- a/proposal/sandbox/antlib/src/testcases/build.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/proposal/sandbox/antlib/src/testcases/case-antlib.xml b/proposal/sandbox/antlib/src/testcases/case-antlib.xml deleted file mode 100644 index e5ae1e847..000000000 --- a/proposal/sandbox/antlib/src/testcases/case-antlib.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/proposal/sandbox/antlib/src/testcases/case.xml b/proposal/sandbox/antlib/src/testcases/case.xml deleted file mode 100644 index b289106d5..000000000 --- a/proposal/sandbox/antlib/src/testcases/case.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/proposal/sandbox/antlib/src/testcases/org/apache/ant/contrib/Case.java b/proposal/sandbox/antlib/src/testcases/org/apache/ant/contrib/Case.java deleted file mode 100644 index e2363eb71..000000000 --- a/proposal/sandbox/antlib/src/testcases/org/apache/ant/contrib/Case.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * Copyright (c) 1999 The Apache Software Foundation. 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 - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowlegement may appear in the software itself, - * if and wherever such third-party acknowlegements normally appear. - * - * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software - * Foundation" must not be used to endorse or promote products derived - * from this software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache" - * nor may "Apache" appear in their names without prior written - * permission of the Apache Group. - * - * 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 APACHE SOFTWARE FOUNDATION 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - */ - -package org.apache.ant.contrib; - -import java.io.*; -import java.util.*; -import org.apache.tools.ant.*; -import org.apache.tools.ant.types.*; - -/** - * Will set one of the given properties depending on the result of testing - * the value of another property. - * - * - * The name of the property to test - * - * The value to compare and set prop. - * The name of the property to set - * - * The name of the property to set otherwise - * The value to set; default "true". - * - * @author Jose Alberto Fernandez jfernandez@viquity.com - */ - -public class Case extends Task { - - public class When { - private String property; - private String value; - - public void setProperty(String name) { - property = name; - } - - public String getProperty() { - return property; - } - - public void setValue(String val) { - value = val; - } - - public String getValue() { - return value; - } - - public boolean tryCase(String caseValue) throws BuildException { - if (property == null) - throw new BuildException("Property attribute is mandatory"); - - if (value == null) - throw new BuildException("Value attribute is mandatory"); - - if (!value.equals(caseValue)) return false; - - if (getProject().getProperty(property) == null) { - getProject().setProperty(property, value); - } else { - log("Override ignored for " + property, Project.MSG_VERBOSE); - } - return true; - } - - public void doElse() throws BuildException { - if (property == null) - throw new BuildException("Property attribute is mandatory"); - - String elseValue = (value == null) ? "true" : value; - - if (getProject().getProperty(property) == null) { - getProject().setProperty(property, elseValue); - } else { - log("Override ignored for " + property, Project.MSG_VERBOSE); - } - } - } - - private String caseProperty; - private Vector whenList = new Vector(); - private When elseCase = null; - - public When createWhen() throws BuildException { - When w = new When(); - whenList.addElement(w); - return w; - } - - public When createElse() throws BuildException { - if (elseCase != null) - throw new BuildException("Only one else element allowed per case"); - - return (elseCase = new When()); - } - - public void setProperty(String property) { - this.caseProperty = property; - } - - public void execute() throws BuildException { - if (caseProperty == null) { - throw new BuildException("property attribute is required", - location); - } - - String caseValue = getProject().getProperty(caseProperty); - - for (Enumeration e = whenList.elements(); e.hasMoreElements(); ) { - When w = (When)e.nextElement(); - if (w.tryCase(caseValue)) return; - } - - if (elseCase != null) - elseCase.doElse(); - } - -}