KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > CocoonTask


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.cocoon;
17
18 import java.io.File JavaDoc;
19 import java.lang.reflect.InvocationTargetException JavaDoc;
20 import java.lang.reflect.Method JavaDoc;
21
22 import javax.xml.parsers.DocumentBuilder JavaDoc;
23 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
24 import javax.xml.parsers.ParserConfigurationException JavaDoc;
25
26 import org.apache.tools.ant.AntClassLoader;
27 import org.apache.tools.ant.BuildException;
28 import org.apache.tools.ant.DynamicConfigurator;
29 import org.apache.tools.ant.ExitException;
30 import org.apache.tools.ant.Project;
31 import org.apache.tools.ant.Task;
32 import org.apache.tools.ant.types.CommandlineJava;
33 import org.apache.tools.ant.types.Path;
34 import org.apache.tools.ant.types.Reference;
35
36 import org.w3c.dom.Document JavaDoc;
37 import org.w3c.dom.Element JavaDoc;
38 import org.w3c.dom.NamedNodeMap JavaDoc;
39 import org.w3c.dom.Node JavaDoc;
40
41 /**
42  * Ant task for running Cocoon. Allows for the embedding of Cocoon into
43  *
44  * @author <a HREF="mailto:uv@upaya.co.uk">Upayavira</a>
45  * @version CVS $Id: CocoonTask.java 30932 2004-07-29 17:35:38Z vgritsenko $
46  */

47 public class CocoonTask extends Task implements DynamicConfigurator {
48
49     private CommandlineJava cmdl = new CommandlineJava();
50     private boolean failOnError = false;
51     private Throwable JavaDoc caught = null;
52
53     private String JavaDoc uriGroup = null;
54     private Document JavaDoc xconf;
55     private Element JavaDoc root;
56     private ElementWrapper _wrapper;
57     
58     private static final String JavaDoc CLASS_DELEGATE = "org.apache.cocoon.bean.helpers.AntDelegate";
59             
60     public CocoonTask() {
61         try {
62             DocumentBuilder JavaDoc builder =
63                 DocumentBuilderFactory.newInstance().newDocumentBuilder();
64             xconf = builder.newDocument();
65             root = xconf.createElement("cocoon");
66             xconf.appendChild(root);
67             _wrapper = new ElementWrapper(root);
68             cmdl.setClassname(CLASS_DELEGATE);
69         }
70         catch (ParserConfigurationException JavaDoc e) {
71             throw new BuildException(e);
72         }
73     }
74     
75     /**
76      * Adds a path to the classpath.
77      *
78      * @return created classpath
79      */

80     public Path createClasspath() {
81         return cmdl.createClasspath(getProject()).createPath();
82     }
83
84     /**
85      * Classpath to use, by reference.
86      *
87      * @param r a reference to an existing classpath
88      */

89     public void setClasspathRef(Reference r) {
90         createClasspath().setRefid(r);
91     }
92
93     /**
94      * Set the classpath to be used when running the Java class
95      *
96      * @param s an Ant Path object containing the classpath.
97      */

98     public void setClasspath(Path s) {
99         createClasspath().append(s);
100     }
101
102     public void setUrigroup(String JavaDoc group) {
103         this.uriGroup = group;
104     }
105  
106     /**
107      * A dynamic configurator for each element.
108      */

109     private static class ElementWrapper
110                          implements DynamicConfigurator {
111
112         private Node JavaDoc node;
113
114         /** Instantiate a root wrapper */
115         private ElementWrapper(Node JavaDoc node) {
116             this.node = node;
117         }
118
119         /** Instantiate a child wrapper */
120         private ElementWrapper(Node JavaDoc parent, String JavaDoc childName) {
121             Document JavaDoc document = parent.getOwnerDocument();
122             if (document == null) {
123               document = (Document JavaDoc)parent; // Node is the document!
124
}
125             node = document.createElement(childName);
126             parent.appendChild(node);
127         }
128
129         //
130
// interface DynamicConfigurator
131
public void setDynamicAttribute(String JavaDoc name, String JavaDoc value)
132                     throws BuildException {
133             // Never called for anything by Element wrappers
134
Element JavaDoc element = (Element JavaDoc)node;
135             element.setAttribute(name, value);
136         }
137
138         public Object JavaDoc createDynamicElement(String JavaDoc name)
139                       throws BuildException {
140             return new ElementWrapper(node, name);
141         }
142     }
143
144     public File JavaDoc getLibDir() throws BuildException {
145         Element JavaDoc root = xconf.getDocumentElement();
146         String JavaDoc contextDir = null;
147         if (root!=null) {
148             if (hasAttribute(root, "context-dir")){
149                 contextDir = getAttributeValue(root, "context-dir");
150             }
151         }
152         if (contextDir != null) {
153             return new File JavaDoc(contextDir + "/WEB-INF/lib");
154         } else {
155             throw new BuildException("No context directory specified. Cannot find Cocoon");
156         }
157     }
158
159     private static String JavaDoc getAttributeValue(Node JavaDoc node, String JavaDoc attr) throws IllegalArgumentException JavaDoc {
160         NamedNodeMap JavaDoc nodes = node.getAttributes();
161         if (nodes != null) {
162             Node JavaDoc attribute = nodes.getNamedItem(attr);
163             if (attribute != null && attribute.getNodeValue() != null) {
164                 return attribute.getNodeValue();
165             }
166         }
167         throw new IllegalArgumentException JavaDoc("Missing " + attr + " attribute on <" + node.getNodeName() + "> node");
168     }
169
170     private static boolean hasAttribute(Node JavaDoc node, String JavaDoc attr) {
171         NamedNodeMap JavaDoc nodes = node.getAttributes();
172         if (nodes != null) {
173             Node JavaDoc attribute = nodes.getNamedItem(attr);
174             return (attribute != null);
175         }
176         return false;
177     }
178
179     //
180
// interface DynamicConfigurator
181
public void setDynamicAttribute(String JavaDoc name, String JavaDoc value)
182                 throws BuildException {
183         root.setAttribute(name, value);
184     }
185
186     public Object JavaDoc createDynamicElement(String JavaDoc name)
187                   throws BuildException {
188         return _wrapper.createDynamicElement(name);
189     }
190
191     /**
192      * Do the execution and return a return code.
193      *
194      * @return the return code from the execute java class if it was
195      * executed in a separate VM (fork = "yes").
196      *
197      * @throws BuildException if required parameters are missing
198      */

199     public void execute() throws BuildException {
200         // FIXME - This is never read
201
int err= -1;
202
203         if (cmdl.getClasspath() == null) {
204             throw new BuildException("Could not find a classpath that points to the Cocoon classes");
205         }
206         try {
207             try {
208                 execute(cmdl);
209                 err = 0;
210             } catch (ExitException ex) {
211                 err = ex.getStatus();
212             }
213         } catch (BuildException e) {
214             if (failOnError) {
215                 throw e;
216             } else {
217                 log(e.getMessage(), Project.MSG_ERR);
218                 err = 0;
219             }
220         } catch (Throwable JavaDoc t) {
221             if (failOnError) {
222                 throw new BuildException(t);
223             } else {
224                 log(t.getMessage(), Project.MSG_ERR);
225                 err = 0;
226             }
227         }
228     }
229     
230     public void execute(CommandlineJava command) throws BuildException {
231         final String JavaDoc classname = command.getJavaCommand().getExecutable();
232
233         AntClassLoader loader = null;
234         try {
235             if (command.getSystemProperties() != null) {
236                 command.getSystemProperties().setSystem();
237             }
238
239             final Class JavaDoc[] param = {Class.forName("org.w3c.dom.Document"), Class.forName("java.lang.String")};
240             Class JavaDoc target = null;
241             if (command.getClasspath() == null) {
242                 target = Class.forName(classname);
243             } else {
244                 loader = new AntClassLoader(getProject().getCoreLoader(), getProject(),
245                                             command.getClasspath(), false);
246                 loader.setIsolated(true);
247                 loader.setThreadContextLoader();
248                 target = loader.forceLoadClass(classname);
249                 Class.forName(classname, true, loader);
250             }
251             Method JavaDoc method = target.getMethod("process", param);
252             if (method == null) {
253                 throw new BuildException("Could not find process() method in "
254                                          + classname);
255             }
256
257             run(method);
258
259             if (caught != null) {
260                 throw caught;
261             }
262
263         } catch (ClassNotFoundException JavaDoc e) {
264             throw new BuildException("Could not find " + classname + "."
265                                      + " Make sure you have it in your"
266                                      + " classpath");
267         } catch (SecurityException JavaDoc e) {
268             throw e;
269         } catch (Throwable JavaDoc e) {
270             throw new BuildException(e);
271         } finally {
272             if (loader != null) {
273                 loader.resetThreadContextLoader();
274                 loader.cleanup();
275             }
276             if (command.getSystemProperties() != null) {
277                 command.getSystemProperties().restoreSystem();
278             }
279         }
280     }
281
282     public void run(Method JavaDoc method) {
283         final Object JavaDoc[] argument = {xconf, uriGroup};
284         try {
285             method.invoke(null, argument);
286         } catch (InvocationTargetException JavaDoc e) {
287             Throwable JavaDoc t = e.getTargetException();
288             if (!(t instanceof InterruptedException JavaDoc)) {
289                 caught = t;
290             } /* else { swallow, probably due to timeout } */
291         } catch (Throwable JavaDoc t) {
292             caught = t;
293         } finally {
294             synchronized (this) {
295                 notifyAll();
296             }
297         }
298     }
299 }
300
Popular Tags