KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mullassery > act > TaskMaster


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2002 The Apache Software Foundation. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met: 1.
8  * Redistributions of source code must retain the above copyright notice, this
9  * list of conditions and the following disclaimer. 2. Redistributions in
10  * binary form must reproduce the above copyright notice, this list of
11  * conditions and the following disclaimer in the documentation and/or other
12  * materials provided with the distribution. 3. The end-user documentation
13  * included with the redistribution, if any, must include the following
14  * acknowlegement: "This product includes software developed by the Apache
15  * Software Foundation (http://www.apache.org/)." Alternately, this
16  * acknowlegement may appear in the software itself, if and wherever such
17  * third-party acknowlegements normally appear. 4. The names "The Jakarta
18  * Project", "Ant", and "Apache Software Foundation" must not be used to
19  * endorse or promote products derived from this software without prior written
20  * permission. For written permission, please contact apache@apache.org. 5.
21  * Products derived from this software may not be called "Apache" nor may
22  * "Apache" appear in their names without prior written permission of the
23  * Apache Group.
24  *
25  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
26  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
27  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28  * APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
29  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
30  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
32  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35  * ====================================================================
36  *
37  * This software consists of voluntary contributions made by many individuals
38  * on behalf of the Apache Software Foundation. For more information on the
39  * Apache Software Foundation, please see <http://www.apache.org/> .
40  */

41
42 package com.mullassery.act;
43
44 import java.awt.Toolkit JavaDoc;
45 import java.io.File JavaDoc;
46 import java.util.Enumeration JavaDoc;
47 import java.util.HashMap JavaDoc;
48 import java.util.Hashtable JavaDoc;
49 import java.util.Iterator JavaDoc;
50
51 import org.apache.tools.ant.BuildEvent;
52 import org.apache.tools.ant.BuildException;
53 import org.apache.tools.ant.BuildListener;
54 import org.apache.tools.ant.DefaultLogger;
55 import org.apache.tools.ant.IntrospectionHelper;
56 import org.apache.tools.ant.Project;
57 import org.apache.tools.ant.Target;
58 import org.apache.tools.ant.Task;
59 import org.w3c.dom.Document JavaDoc;
60 import org.w3c.dom.Element JavaDoc;
61 import org.w3c.dom.NamedNodeMap JavaDoc;
62 import org.w3c.dom.Node JavaDoc;
63 import org.w3c.dom.NodeList JavaDoc;
64
65 import com.mullassery.act.util.DebugUtil;
66 import com.mullassery.act.util.ResourceUtil;
67 import com.mullassery.act.util.XMLUtil;
68
69 /**
70  * @author Abey Mullassery
71  *
72  */

73 public class TaskMaster {
74     public final static String JavaDoc CHILDREN = "children";
75     public final Project proj = new Project();
76     //public Properties types;
77

78     /** Private : Preventing the creation of an instance of TaskUtil */
79     public TaskMaster() throws ACTException {
80         this.projectInitialize();
81     }
82
83     /**
84      * Gets an elements Attribute names and types
85      */

86     public static HashMap JavaDoc getElementInfo(Class JavaDoc element) throws ACTException {
87         HashMap JavaDoc info = new HashMap JavaDoc();
88         try {
89             IntrospectionHelper ih = IntrospectionHelper.getHelper(element);
90             Enumeration JavaDoc en = ih.getAttributes();
91             String JavaDoc attr = null;
92             while (en.hasMoreElements()) {
93                 attr = en.nextElement().toString();
94                 info.put(attr, ih.getAttributeType(attr));
95             }
96
97             en = ih.getNestedElements();
98             HashMap JavaDoc childElements = null;
99             String JavaDoc nestedElement = null;
100             while (en.hasMoreElements()) {
101                 nestedElement = en.nextElement().toString();
102                 if (childElements == null)
103                     childElements = new HashMap JavaDoc();
104                 childElements.put(
105                     nestedElement,
106                     ih.getElementType(nestedElement));
107             }
108             if (childElements != null)
109                 info.put(CHILDREN, childElements);
110         } catch (Throwable JavaDoc be) {
111             throw new ACTException(
112                 "Could not get all the details of the element : " + be);
113         }
114         return info;
115     }
116
117     public static void setAttributes(Project proj, Object JavaDoc t, Element JavaDoc vals) {
118         IntrospectionHelper ih = IntrospectionHelper.getHelper(t.getClass());
119
120         NodeList JavaDoc nl = vals.getChildNodes();
121         Node JavaDoc n = null;
122         for (int i = 0; i < nl.getLength(); i++) {
123             n = nl.item(i);
124             if (n.getNodeType() == Node.ELEMENT_NODE) {
125                 Object JavaDoc nested = ih.createElement(proj, t, n.getNodeName());
126                 setAttributes(proj, nested, (Element JavaDoc) n);
127                 ih.storeElement(proj, t, nested, n.getNodeName());
128             }
129         }
130
131         NamedNodeMap JavaDoc nm = vals.getAttributes();
132         for (int i = 0; i < nm.getLength(); i++) {
133             n = nm.item(i);
134             if (n.getNodeType() == Node.ATTRIBUTE_NODE) {
135                 ih.setAttribute(proj, t, n.getNodeName(), n.getNodeValue());
136             }
137         }
138     }
139
140     public void addDataType(String JavaDoc typeName, String JavaDoc typeClass)
141         throws ACTException {
142         try {
143             proj.addDataTypeDefinition(typeName, Class.forName(typeClass));
144         } catch (Exception JavaDoc e) {
145             throw new ACTException(e.getMessage());
146         }
147     }
148
149     public void addTask(String JavaDoc taskName, String JavaDoc taskClass)
150         throws ACTException {
151         try {
152             proj.addTaskDefinition(taskName, Class.forName(taskClass));
153         } catch (ClassNotFoundException JavaDoc e) {
154             throw new ACTException("Could not find " + taskClass);
155         } catch (Exception JavaDoc e) {
156             throw new ACTException(e.toString());
157         }
158     }
159     // TODO: make provision to reuse or remove target
160
public Task createMainTask(final String JavaDoc mainTask, final String JavaDoc dir)
161         throws ACTException {
162         Task t = null;
163         try {
164             t = (Task) (getTaskClass(mainTask).newInstance());
165         } catch (Exception JavaDoc e) {
166             throw new ACTException(
167                 "Could not create the Task Object ("
168                     + mainTask
169                     + ") : "
170                     + e.getLocalizedMessage());
171         }
172         this.proj.setBasedir(dir);
173         t.setProject(this.proj);
174         t.setTaskName(mainTask);
175         Target trg = new Target();
176         trg.setName("ACT-Execution");
177         trg.addTask(t);
178         t.setOwningTarget(trg);
179         proj.addOrReplaceTarget(trg);
180         return t;
181     }
182
183     public void execute(final Task tsk) throws ACTException {
184         try {
185             proj.executeTarget(tsk.getOwningTarget().getName());
186         } catch (BuildException be) {
187             throw new ACTException(
188                 "Task Execution Failed : " + be.getMessage());
189         }
190     }
191
192     public void executeTask(
193         final String JavaDoc mainTask,
194         final String JavaDoc dir,
195         final Element JavaDoc values)
196         throws ACTException {
197         DefaultLogger dl = new DefaultLogger();
198         dl.setOutputPrintStream(System.out);
199         dl.setErrorPrintStream(System.err);
200         dl.setMessageOutputLevel(Project.MSG_INFO);
201         executeTask(mainTask, dir, values, dl);
202     }
203
204     public void executeTask(
205         final String JavaDoc mainTask,
206         final String JavaDoc dir,
207         final Element JavaDoc values,
208         BuildListener bl)
209         throws ACTException {
210         synchronized (this.proj) {
211             Task tsk = createMainTask(mainTask, Project.translatePath(dir));
212             if (bl != null)
213                 tsk.getProject().addBuildListener(bl);
214             setAttributes(tsk.getProject(), tsk, values);
215             execute(tsk);
216         }
217     }
218
219     public Hashtable JavaDoc getAllTasks() throws ACTException {
220         return proj.getTaskDefinitions();
221     }
222
223     public Hashtable JavaDoc getAllTypes() throws ACTException {
224         return this.proj.getDataTypeDefinitions();
225     }
226
227     public Class JavaDoc getElementClass(String JavaDoc elem) throws ACTException {
228         Class JavaDoc clazz = getTypeClass(elem);
229         return clazz != null ? clazz : getTaskClass(elem);
230     }
231
232     public String JavaDoc getElementHelp(String JavaDoc elem) throws ACTException {
233         HashMap JavaDoc val = getElementInfo(getElementClass(elem));
234         StringBuffer JavaDoc sb =
235             new StringBuffer JavaDoc("\"" + elem + "\" properties listed below :");
236         String JavaDoc prop = null;
237         Object JavaDoc obj = null;
238         Iterator JavaDoc en = val.keySet().iterator();
239         while (en.hasNext()) {
240             obj = en.next();
241             prop = obj.toString();
242             obj = val.get(obj);
243             if (!prop.equals(CHILDREN)) {
244                 sb.append("\n\t-" + prop);
245             }
246         }
247         if (val.containsKey(CHILDREN)) {
248             sb.append("\n\t\"Also supports the following nested elements ");
249             sb.append("\n\t Usage -[element].[property] [value]");
250             HashMap JavaDoc nVal = (HashMap JavaDoc) val.get(CHILDREN);
251             en = nVal.keySet().iterator();
252             while (en.hasNext()) {
253                 obj = en.next();
254                 prop = obj.toString();
255                 sb.append("\n\t\t" + prop);
256             }
257         }
258         return sb.toString();
259     }
260
261     public Class JavaDoc getTaskClass(java.lang.String JavaDoc task) throws ACTException {
262         return (Class JavaDoc) getAllTasks().get(task);
263     }
264
265     public Class JavaDoc getTypeClass(java.lang.String JavaDoc type) throws ACTException {
266         return (Class JavaDoc) getAllTypes().get(type);
267     }
268
269     private void projectInitialize() throws ACTException {
270         try {
271             this.proj.init();
272         } catch (BuildException be) {
273             throw new ACTException(
274                 "Initialization Failed : " + be.getMessage());
275         }
276         File JavaDoc tf = ResourceUtil.getSettingsFile();
277         DebugUtil.debug("Using settings from " + tf.getAbsolutePath());
278         if (!tf.exists())
279             return;
280         addGroups(XMLUtil.getDocumentElement(tf));
281     }
282
283     private void addGroups(Element JavaDoc group) {
284         NodeList JavaDoc nGroups = group.getChildNodes();
285         DebugUtil.debug(
286             "\t"
287                 + group.getNodeName()
288                 + " has children : "
289                 + nGroups.getLength());
290         //sub groups
291
for (int i = 0; i < nGroups.getLength(); i++) {
292             try {
293                 if (nGroups.item(i).getNodeType() != Node.ELEMENT_NODE
294                     || !nGroups.item(i).getNodeName().equals("task-group")) {
295                     continue;
296                 }
297                 Element JavaDoc node = (Element JavaDoc) nGroups.item(i);
298                 String JavaDoc name = node.getAttribute("display-name");
299                 if (name != null && name.length() > 0) {
300                     DebugUtil.debug("Adding group " + name);
301                     addGroups(node);
302                 }
303             } catch (Throwable JavaDoc t) {
304                 continue;
305             }
306         }
307         addTasks(group);
308     }
309
310     private void addTasks(Element JavaDoc group) {
311         NodeList JavaDoc tasks = group.getElementsByTagName("task");
312         DebugUtil.debug("Found " + tasks.getLength() + " tasks");
313         for (int j = 0; j < tasks.getLength(); j++) {
314             Element JavaDoc task = (Element JavaDoc) tasks.item(j);
315             if (!task.hasAttribute("class") || !task.hasAttribute("name"))
316                 continue;
317             String JavaDoc id = task.getAttribute("name");
318             String JavaDoc tClass = task.getAttribute("class");
319             if (id.length() == 0 && tClass.length() == 0)
320                 continue;
321             try {
322                 this.addTask(id, tClass);
323                 DebugUtil.debug("Added " + id + " : " + tClass + " task");
324             } catch (ACTException e) { //remain silent
325
DebugUtil.debug(e.toString());
326             }
327         }
328     }
329
330     public void removeTask(String JavaDoc taskName) {
331         proj.getTaskDefinitions().remove(taskName);
332     }
333
334     //TODO: Must build a proper CLI manager
335
public void run(String JavaDoc[] args) throws ACTException {
336         String JavaDoc[] params = handleInput(args);
337         if (params == null)
338             return;
339         String JavaDoc taskName = params[0];
340         Document JavaDoc doc = XMLUtil.getDocumentBuilder().newDocument();
341         Element JavaDoc e = doc.createElement(taskName);
342         for (int i = 2; i < params.length; i += 2) {
343             String JavaDoc name = params[i - 1].substring(1);
344             String JavaDoc value = params[i];
345
346             HashMap JavaDoc cm = getElementInfo(getElementClass(e.getNodeName()));
347             XMLUtil.setProperty(cm, e, name, value);
348         }
349         this.executeTask(taskName, ".", e, new BuildListener() {
350             boolean logging = false;
351             private void addMessage(String JavaDoc evt) {
352                 if (logging)
353                     System.out.println(evt);
354             }
355             public void messageLogged(BuildEvent evt) {
356                 addMessage(evt.getMessage());
357             }
358             public void buildFinished(BuildEvent arg0) {
359             }
360             public void buildStarted(BuildEvent arg0) {
361             }
362             public void targetFinished(BuildEvent arg0) {
363             }
364             public void targetStarted(BuildEvent arg0) {
365             }
366             public void taskFinished(BuildEvent evt) {
367                 Toolkit.getDefaultToolkit().beep();
368                 logging = false;
369             }
370             public void taskStarted(BuildEvent evt) {
371                 logging = true;
372             }
373         });
374     }
375
376     private String JavaDoc[] handleInput(String JavaDoc[] args) throws ACTException {
377         if (args.length == 0 || (args[0].equals("-dir") && args.length < 3)) {
378             System.err.println(
379                 "Usage: ACT [-dir parent_dir_of_act-setting.xml] taskname attributes"
380                     + "Try task name -help for help.");
381             return null;
382         }
383         if (args[0].equals("-dir")) {
384             File JavaDoc dir = new File JavaDoc(args[1]);
385             if (dir.exists() && dir.isDirectory()) {
386                 ResourceUtil.actDir = args[1];
387             } else {
388                 System.err.println(args[1] + " is not a valid directory!");
389                 return null;
390             }
391             String JavaDoc[] temp = new String JavaDoc[args.length - 2];
392             System.arraycopy(args, 2, temp, 0, args.length-2);
393             args = temp;
394         }
395         if ((args.length > 1
396             && (args[1].equals("?") || args[1].equalsIgnoreCase("-help")))) {
397             System.err.println(getElementHelp(args[0]));
398             return null;
399         }
400         return args;
401     }
402 }
403
Popular Tags