KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > antmod > util > AntUtil


1 package org.antmod.util;
2
3 import java.io.File JavaDoc;
4 import java.lang.reflect.Method JavaDoc;
5 import java.util.ArrayList JavaDoc;
6 import java.util.Enumeration JavaDoc;
7 import java.util.Hashtable JavaDoc;
8 import java.util.Vector JavaDoc;
9
10 import org.apache.tools.ant.*;
11 import org.apache.tools.ant.taskdefs.Input;
12 import org.apache.tools.ant.util.FileUtils;
13
14 /**
15  * Utilities related to Ant.
16  *
17  * @author Klaas Waslander
18  */

19 public final class AntUtil {
20     /** counter for generating unique property names for ask results */
21     private static int askCounter;
22
23     /** synchronization object for the "ask" method */
24     private final static Object JavaDoc SYNC_ASK = new Object JavaDoc();
25
26
27     /** not to be instantiated */
28     private AntUtil() {
29     }
30
31     /**
32      * Helper method for asking a question. Under the hood, this utility
33      * method uses Ant's "Input" task.
34      * @param question The question to be shown to the user
35      * @param validArgs Command separated list with valid responses.
36      * @return The response to the question, matching one of the validArgs.
37      */

38     public static String JavaDoc ask(Project antProject, String JavaDoc question, String JavaDoc validArgs) throws BuildException {
39         synchronized (SYNC_ASK) {
40             String JavaDoc askProperty = "input.antmod.ask.internal." + (askCounter++);
41
42             Input in = new Input();
43             in.setProject(antProject);
44             in.setTaskName("input");
45             in.setMessage(question);
46             in.setValidargs(validArgs);
47             in.setAddproperty(askProperty);
48             in.execute();
49
50             return antProject.getProperty(askProperty);
51         }
52     }
53
54     /**
55      * Get all ant targets available in the given Ant project.
56      */

57     public static ArrayList JavaDoc getAntTargets(Project antProject) {
58         ArrayList JavaDoc result = new ArrayList JavaDoc();
59         if (antProject != null) {
60             Enumeration JavaDoc targetNames = antProject.getTargets().keys();
61             while (targetNames.hasMoreElements()) {
62                 result.add(targetNames.nextElement());
63             }
64         }
65         return result;
66     }
67
68     /**
69      * Returns a Project representing the given Ant XML buildfile.
70      */

71     public static Project getAntProject(Project parentAntProject, File JavaDoc antXmlFile, boolean inheritAll) {
72         if (!antXmlFile.exists()) {
73             return null;
74         }
75
76         Project newProject = createEmptyProject(parentAntProject, inheritAll);
77         try {
78             ProjectHelper.getProjectHelper().parse(newProject, antXmlFile);
79             
80             // set basedir to that of the parent Ant project
81
newProject.setBaseDir(parentAntProject.getBaseDir());
82             
83             // let the new project refer to the ant file using relative path to basedir
84
newProject.setUserProperty("ant.file" , FileUtils.newFileUtils().resolveFile(parentAntProject.getBaseDir(), antXmlFile.getAbsolutePath()).getAbsolutePath());
85
86             // return newly created project
87
return newProject;
88         } catch (BuildException e) {
89             BuildException throwing = new BuildException("Failed to parse \"" + antXmlFile + "\": " + e.getMessage());
90             throwing.setStackTrace(e.getStackTrace());
91             throw throwing;
92         }
93     }
94
95     private static Project createEmptyProject(Project parentAntProject, boolean inheritAll) {
96         Project newProject = new Project();
97         newProject.setJavaVersionProperty();
98
99         // input and output
100
newProject.setDefaultInputStream(parentAntProject.getDefaultInputStream());
101         newProject.setInputHandler(parentAntProject.getInputHandler());
102         Vector JavaDoc listeners = parentAntProject.getBuildListeners();
103         final int count = listeners.size();
104         for (int i = 0; i < count; i++) {
105             newProject.addBuildListener((BuildListener) listeners.elementAt(i));
106         }
107         
108         // other initialization
109
parentAntProject.initSubProject(newProject);
110
111         // task definitions
112
newProject.addTaskDefinition("property", (Class JavaDoc) parentAntProject.getTaskDefinitions().get("property"));
113         Hashtable JavaDoc taskdefs = parentAntProject.getTaskDefinitions();
114         Enumeration JavaDoc et = taskdefs.keys();
115         while (et.hasMoreElements()) {
116             String JavaDoc taskName = (String JavaDoc) et.nextElement();
117             if (taskName.equals("property")) {
118                 // we have already added this taskdef in #init
119
continue;
120             }
121             Class JavaDoc taskClass = (Class JavaDoc) taskdefs.get(taskName);
122             newProject.addTaskDefinition(taskName, taskClass);
123         }
124         
125         Hashtable JavaDoc typedefs = parentAntProject.getDataTypeDefinitions();
126         Enumeration JavaDoc e = typedefs.keys();
127         while (e.hasMoreElements()) {
128             String JavaDoc typeName = (String JavaDoc) e.nextElement();
129             Class JavaDoc typeClass = (Class JavaDoc) typedefs.get(typeName);
130             newProject.addDataTypeDefinition(typeName, typeClass);
131         }
132         
133         // property inheritance
134
if (!inheritAll) {
135             // set java built-in props separately, b/c they are not inherited
136
newProject.setSystemProperties();
137         } else {
138             // pass (almost) all properties to new project
139
addAlmostAll(newProject, parentAntProject.getProperties());
140         }
141
142         return newProject;
143     }
144
145
146
147     /**
148      * !!!!COPY-PASTE FROM org.apache.tools.ant.taskdefs.Ant CLASS!!!!
149      *
150      * Copies all properties from the given table to the new project -
151      * omitting those that have already been set in the new project as
152      * well as properties named basedir or ant.file.
153      * @param props properties to copy to the new project
154      */

155     private static void addAlmostAll(Project newProject, Hashtable JavaDoc props) {
156         Enumeration JavaDoc e = props.keys();
157         while (e.hasMoreElements()) {
158             String JavaDoc key = e.nextElement().toString();
159             if ("basedir".equals(key) || "ant.file".equals(key)) {
160                 // basedir and ant.file get special treatment in execute()
161
continue;
162             }
163
164             String JavaDoc value = props.get(key).toString();
165             // don't re-set user properties, avoid the warning message
166
if (newProject.getProperty(key) == null) {
167                 // no user property
168
newProject.setNewProperty(key, value);
169             }
170         }
171     }
172     
173     public static void inheritRefs(Project parentProject, Project newProject) {
174         Hashtable JavaDoc thisReferences = (Hashtable JavaDoc) parentProject.getReferences().clone();
175         Hashtable JavaDoc newReferences = newProject.getReferences();
176
177         // Now add all references that are not defined in the
178
// subproject, if inheritRefs is true
179
for (Enumeration JavaDoc e = thisReferences.keys(); e.hasMoreElements();) {
180             String JavaDoc key = (String JavaDoc) e.nextElement();
181             if (newReferences.containsKey(key)) {
182                 continue;
183             }
184             copyReference(parentProject, newProject, key, key);
185         }
186     }
187
188     /**
189      * !!!!COPY-PASTE FROM org.apache.tools.ant.taskdefs.Ant CLASS!!!!
190      *
191      * Try to clone and reconfigure the object referenced by oldkey in
192      * the parent project and add it to the new project with the key newkey.
193      *
194      * <p>If we cannot clone it, copy the referenced object itself and
195      * keep our fingers crossed.</p>
196      * @param oldKey the reference id in the current project.
197      * @param newKey the reference id in the new project.
198      */

199     private static void copyReference(Project parentProject, Project newProject, String JavaDoc oldKey, String JavaDoc newKey) {
200         Object JavaDoc orig = parentProject.getReference(oldKey);
201         if (orig == null) {
202             parentProject.log("No object referenced by " + oldKey + ". Can't copy to "
203                 + newKey,
204                 Project.MSG_WARN);
205             return;
206         }
207
208         Class JavaDoc c = orig.getClass();
209         Object JavaDoc copy = orig;
210         try {
211             Method JavaDoc cloneM = c.getMethod("clone", new Class JavaDoc[0]);
212             if (cloneM != null) {
213                 copy = cloneM.invoke(orig, new Object JavaDoc[0]);
214                 parentProject.log("Adding clone of reference " + oldKey, Project.MSG_DEBUG);
215             }
216         } catch (Exception JavaDoc e) {
217             // not Clonable
218
}
219
220
221         if (copy instanceof ProjectComponent) {
222             ((ProjectComponent) copy).setProject(newProject);
223         } else {
224             try {
225                 Method JavaDoc setProjectM =
226                     c.getMethod("setProject", new Class JavaDoc[] {Project.class});
227                 if (setProjectM != null) {
228                     setProjectM.invoke(copy, new Object JavaDoc[] {newProject});
229                 }
230             } catch (NoSuchMethodException JavaDoc e) {
231                 // ignore this if the class being referenced does not have
232
// a set project method.
233
} catch (Exception JavaDoc e2) {
234                 String JavaDoc msg = "Error setting new project instance for "
235                     + "reference with id " + oldKey;
236                 throw new BuildException(msg, e2); //getLocation());
237
}
238         }
239         newProject.addReference(newKey, copy);
240     }
241 }
242
Popular Tags