KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > taskdefs > optional > junit > AggregateTransformer


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

18 package org.apache.tools.ant.taskdefs.optional.junit;
19
20 import java.io.File JavaDoc;
21 import java.io.FileInputStream JavaDoc;
22 import java.io.FileNotFoundException JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.InputStream JavaDoc;
25
26 import java.net.URL JavaDoc;
27
28 import java.util.Iterator JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.Vector JavaDoc;
31
32 import javax.xml.parsers.DocumentBuilder JavaDoc;
33 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
34
35 import org.apache.tools.ant.BuildException;
36 import org.apache.tools.ant.Project;
37 import org.apache.tools.ant.Task;
38 import org.apache.tools.ant.taskdefs.XSLTProcess;
39 import org.apache.tools.ant.taskdefs.Delete;
40 import org.apache.tools.ant.taskdefs.TempFile;
41 import org.apache.tools.ant.util.JAXPUtils;
42 import org.apache.tools.ant.util.FileUtils;
43 import org.apache.tools.ant.types.EnumeratedAttribute;
44 import org.apache.tools.ant.types.Resource;
45 import org.apache.tools.ant.types.resources.URLResource;
46 import org.apache.tools.ant.types.resources.FileResource;
47
48 import org.w3c.dom.Document JavaDoc;
49
50 /**
51  * Transform a JUnit xml report.
52  * The default transformation generates an html report in either framed or non-framed
53  * style. The non-framed style is convenient to have a concise report via mail, the
54  * framed report is much more convenient if you want to browse into different
55  * packages or testcases since it is a Javadoc like report.
56  *
57  */

58 public class AggregateTransformer {
59     /**
60      * name of the frames format.
61      */

62     public static final String JavaDoc FRAMES = "frames";
63
64     /**
65      * name of the no frames format.
66      */

67     public static final String JavaDoc NOFRAMES = "noframes";
68
69     /**
70      * defines acceptable formats.
71      */

72     public static class Format extends EnumeratedAttribute {
73         /**
74          * list authorized values.
75          * @return authorized values.
76          */

77         public String JavaDoc[] getValues() {
78             return new String JavaDoc[]{FRAMES, NOFRAMES};
79         }
80     }
81
82     // CheckStyle:VisibilityModifier OFF - bc
83
/** Task */
84     protected Task task;
85
86     /** the xml document to process */
87     protected Document JavaDoc document;
88
89     /** the style directory. XSLs should be read from here if necessary */
90     protected File JavaDoc styleDir;
91
92     /** the destination directory, this is the root from where html should be generated */
93     protected File JavaDoc toDir;
94
95     /**
96      * The params that will be sent to the XSL transformation
97      *
98      * @since Ant 1.7
99      */

100     private List JavaDoc params;
101
102     /**
103      * Instance of a utility class to use for file operations.
104      *
105      * @since Ant 1.7
106      */

107     private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
108
109     /**
110      * Used to ensure the uniqueness of a property
111      */

112     private static int counter = 0;
113
114     /** the format to use for the report. Must be <tt>FRAMES</tt> or <tt>NOFRAMES</tt> */
115     protected String JavaDoc format = FRAMES;
116
117     /** XML Parser factory */
118     private static DocumentBuilderFactory JavaDoc privateDBFactory;
119
120     /** XML Parser factory accessible to subclasses */
121     protected static DocumentBuilderFactory JavaDoc dbfactory;
122
123     static {
124        privateDBFactory = DocumentBuilderFactory.newInstance();
125        dbfactory = privateDBFactory;
126     }
127     // CheckStyle:VisibilityModifier ON
128

129     /**
130      * constructor creating the transformer from the junitreport task.
131      * @param task task delegating to this class
132      */

133     public AggregateTransformer(Task task) {
134         this.task = task;
135         params = new Vector JavaDoc();
136     }
137
138     /**
139      * Get the Document Builder Factory
140      *
141      * @return the DocumentBuilderFactory instance in use
142      */

143     protected static DocumentBuilderFactory JavaDoc getDocumentBuilderFactory() {
144         return privateDBFactory;
145     }
146
147     /**
148      * sets the format.
149      * @param format Must be <tt>FRAMES</tt> or <tt>NOFRAMES</tt>
150      */

151     public void setFormat(Format format) {
152         this.format = format.getValue();
153     }
154
155     /**
156      * sets the input document.
157      * @param doc input dom tree
158      */

159     public void setXmlDocument(Document JavaDoc doc) {
160         this.document = doc;
161     }
162
163     /**
164      * Set the xml file to be processed. This is a helper if you want
165      * to set the file directly. Much more for testing purposes.
166      * @param xmlfile xml file to be processed
167      * @throws BuildException if the document cannot be parsed.
168      */

169     protected void setXmlfile(File JavaDoc xmlfile) throws BuildException {
170         try {
171             DocumentBuilder JavaDoc builder = privateDBFactory.newDocumentBuilder();
172             InputStream JavaDoc in = new FileInputStream JavaDoc(xmlfile);
173             try {
174                 Document JavaDoc doc = builder.parse(in);
175                 setXmlDocument(doc);
176             } finally {
177                 in.close();
178             }
179         } catch (Exception JavaDoc e) {
180             throw new BuildException("Error while parsing document: " + xmlfile, e);
181         }
182     }
183
184     /**
185      * set the style directory. It is optional and will override the
186      * default xsl used.
187      * @param styledir the directory containing the xsl files if the user
188      * would like to override with its own style.
189      */

190     public void setStyledir(File JavaDoc styledir) {
191         this.styleDir = styledir;
192     }
193
194     /** set the destination directory.
195      * @param todir the destination directory
196      */

197     public void setTodir(File JavaDoc todir) {
198         this.toDir = todir;
199     }
200
201     /** set the extension of the output files
202      * @param ext extension.
203      */

204     public void setExtension(String JavaDoc ext) {
205         task.log("extension is not used anymore", Project.MSG_WARN);
206     }
207
208     /**
209      * Create an instance of an XSL parameter for configuration by Ant.
210      *
211      * @return an instance of the Param class to be configured.
212      * @since Ant 1.7
213      */

214     public XSLTProcess.Param createParam() {
215         XSLTProcess.Param p = new XSLTProcess.Param();
216         params.add(p);
217         return p;
218     }
219
220     /**
221      * transformation
222      * @throws BuildException exception if something goes wrong with the transformation.
223      */

224     public void transform() throws BuildException {
225         checkOptions();
226         Project project = task.getProject();
227
228         TempFile tempFileTask = new TempFile();
229         tempFileTask.bindToOwner(task);
230
231         XSLTProcess xsltTask = new XSLTProcess();
232         xsltTask.bindToOwner(task);
233
234         xsltTask.setXslResource(getStylesheet());
235
236         // acrobatic cast.
237
xsltTask.setIn(((XMLResultAggregator) task).getDestinationFile());
238         File JavaDoc outputFile = null;
239         if (format.equals(FRAMES)) {
240             String JavaDoc tempFileProperty = getClass().getName() + String.valueOf(counter++);
241             File JavaDoc tmp = FILE_UTILS.resolveFile(project.getBaseDir(),
242                     project.getProperty("java.io.tmpdir"));
243             tempFileTask.setDestDir(tmp);
244             tempFileTask.setProperty(tempFileProperty);
245             tempFileTask.execute();
246             outputFile = new File JavaDoc(project.getProperty(tempFileProperty));
247         } else {
248             outputFile = new File JavaDoc(toDir, "junit-noframes.html");
249         }
250         xsltTask.setOut(outputFile);
251         for (Iterator JavaDoc i = params.iterator(); i.hasNext();) {
252             XSLTProcess.Param param = (XSLTProcess.Param) i.next();
253             XSLTProcess.Param newParam = xsltTask.createParam();
254             newParam.setProject(task.getProject());
255             newParam.setName(param.getName());
256             newParam.setExpression(param.getExpression());
257         }
258         XSLTProcess.Param paramx = xsltTask.createParam();
259         paramx.setProject(task.getProject());
260         paramx.setName("output.dir");
261         paramx.setExpression(toDir.getAbsolutePath());
262         final long t0 = System.currentTimeMillis();
263         try {
264             xsltTask.execute();
265         } catch (Exception JavaDoc e) {
266             throw new BuildException("Errors while applying transformations: "
267                     + e.getMessage(), e);
268         }
269         final long dt = System.currentTimeMillis() - t0;
270         task.log("Transform time: " + dt + "ms");
271         if (format.equals(FRAMES)) {
272             Delete delete = new Delete();
273             delete.bindToOwner(task);
274             delete.setFile(outputFile);
275             delete.execute();
276         }
277     }
278
279     /**
280      * access the stylesheet to be used as a resource.
281      * @return stylesheet as a resource
282      */

283     protected Resource getStylesheet() {
284         String JavaDoc xslname = "junit-frames.xsl";
285         if (NOFRAMES.equals(format)) {
286             xslname = "junit-noframes.xsl";
287         }
288         if (styleDir == null) {
289             // If style dir is not specified we have to retrieve
290
// the stylesheet from the classloader
291
URLResource stylesheet = new URLResource();
292             URL JavaDoc stylesheetURL = getClass().getClassLoader().getResource(
293                     "org/apache/tools/ant/taskdefs/optional/junit/xsl/" + xslname);
294             stylesheet.setURL(stylesheetURL);
295             return stylesheet;
296         }
297         // If we are here, then the style dir is here and we
298
// should read the stylesheet from the filesystem
299
FileResource stylesheet = new FileResource();
300         File JavaDoc stylesheetFile = new File JavaDoc(styleDir, xslname);
301         stylesheet.setFile(stylesheetFile);
302         return stylesheet;
303     }
304
305
306     /** check for invalid options
307      * @throws BuildException if something goes wrong.
308      */

309     protected void checkOptions() throws BuildException {
310         // set the destination directory relative from the project if needed.
311
if (toDir == null) {
312             toDir = task.getProject().resolveFile(".");
313         } else if (!toDir.isAbsolute()) {
314             toDir = task.getProject().resolveFile(toDir.getPath());
315         }
316     }
317
318     /**
319      * Get the systemid of the appropriate stylesheet based on its
320      * name and styledir. If no styledir is defined it will load
321      * it as a java resource in the xsl child package, otherwise it
322      * will get it from the given directory.
323      * @return system ID of the stylesheet.
324      * @throws IOException thrown if the requested stylesheet does
325      * not exist.
326      */

327     protected String JavaDoc getStylesheetSystemId() throws IOException JavaDoc {
328         String JavaDoc xslname = "junit-frames.xsl";
329         if (NOFRAMES.equals(format)) {
330             xslname = "junit-noframes.xsl";
331         }
332         if (styleDir == null) {
333             URL JavaDoc url = getClass().getResource("xsl/" + xslname);
334             if (url == null) {
335                 throw new FileNotFoundException JavaDoc("Could not find jar resource " + xslname);
336             }
337             return url.toExternalForm();
338         }
339         File JavaDoc file = new File JavaDoc(styleDir, xslname);
340         if (!file.exists()) {
341             throw new FileNotFoundException JavaDoc("Could not find file '" + file + "'");
342         }
343         return JAXPUtils.getSystemId(file);
344     }
345
346 }
347
Popular Tags