root/trunk/src/java/org/jcoderz/phoenix/report/JcoderzReportAntTask.java

Revision 1011, 12.5 kB (checked in by amandel, 4 years ago)

Aligned svn keyword settings.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
Line 
1/*
2 * $Id$
3 *
4 * Copyright 2006, The jCoderZ.org Project. 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
8 * met:
9 *
10 *    * Redistributions of source code must retain the above copyright
11 *      notice, this list of conditions and the following disclaimer.
12 *    * Redistributions in binary form must reproduce the above
13 *      copyright notice, this list of conditions and the following
14 *      disclaimer in the documentation and/or other materials
15 *      provided with the distribution.
16 *    * Neither the name of the jCoderZ.org Project nor the names of
17 *      its contributors may be used to endorse or promote products
18 *      derived from this software without specific prior written
19 *      permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
28 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
29 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
30 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
31 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33package org.jcoderz.phoenix.report;
34
35import java.io.File;
36import java.io.IOException;
37import java.util.ArrayList;
38import java.util.Iterator;
39import java.util.List;
40
41import org.apache.tools.ant.BuildException;
42import org.apache.tools.ant.Project;
43import org.apache.tools.ant.taskdefs.Execute;
44import org.apache.tools.ant.taskdefs.LogStreamHandler;
45import org.apache.tools.ant.taskdefs.MatchingTask;
46import org.apache.tools.ant.types.Commandline;
47import org.apache.tools.ant.types.CommandlineJava;
48import org.apache.tools.ant.types.Environment;
49import org.apache.tools.ant.types.Path;
50
51/**
52 * jCoderZ Report Ant Task.
53 *
54 * This Task takes none, one or more input reports such as Checkstyle or PMD
55 * and generates a normalized report file (XML) for any Java source under
56 * <code>srcdir</code>.
57 *
58 * @author Michael Griffel (Michael.Griffel@jcoderz.com)
59 */
60public final class JcoderzReportAntTask
61      extends MatchingTask
62{
63   /** the current working directory when forking JVM. */
64   private File mWorkingDir = null;
65
66   /** Output directory for XML/HTML report. */
67   private File mOut = new File(".");
68   /** The Filter Filename. */
69   private File mFilter = null;
70   /** The project's name. */
71   private String mName = "Not defined";
72   /** The output format. */
73   private OutputFormat mOutputFormat = OutputFormat.XML;
74   /** Flag: exit build process if an error occurred. */
75   private boolean mFailOnError = false;
76   /** List of input report of type JcoderzReportAntTask.Report. */
77   private final List mReportFiles = new ArrayList();
78   /** The Java Commandline. */
79   private final CommandlineJava mCommandline = new CommandlineJava();
80   /**
81    * List of source directories of type JcoderzReportAntTask.SourceDirectory.
82    */
83   private final List mSourceDirectories = new ArrayList();
84
85   /** Debug output flag. */
86   private boolean mDebug = false;
87
88
89   /**
90    * Sets the output directory.
91    * This directory is used to store the report file(s).
92    *
93    * @param dir the output directory
94    */
95   public final void setOut (File dir)
96   {
97      mOut = dir;
98   }
99
100   /**
101    * Sets the filter file.
102    *
103    * @param f the filter file
104    */
105   public final void setFilter (File f)
106   {
107      mFilter = f;
108   }
109
110   /**
111    * Sets the projectName to given <code>projectName</code>.
112    *
113    * @param projectName the project name
114    */
115   public final void setName (String projectName)
116   {
117      mName = projectName;
118   }
119
120   /**
121    * The directory to invoke the VM in. Ignored if no JVM is forked.
122    *
123    * @param dir the directory to invoke the JVM from
124    */
125   public void setDir (File dir)
126   {
127      mWorkingDir = dir;
128   }
129
130   /**
131    * Set whether we should fail on an error.
132    *
133    * @param b whether we should fail on an error
134    */
135   public void setFailonerror (boolean b)
136   {
137      mFailOnError = b;
138   }
139
140   /**
141    * Sets the output format.
142    *
143    * @param s the output format
144    * @throws BuildException throws a BuildException when the format
145    *       name is not valid
146    */
147   public void setFormat (String s)
148         throws BuildException
149   {
150      try
151      {
152         mOutputFormat = OutputFormat.fromString(s);
153      }
154      catch (IllegalArgumentException e)
155      {
156         throw new BuildException("Unsupported output format '"
157               + s + "'", e, getLocation());
158      }
159   }
160
161   /**
162    * Sets the debug flag.
163    *
164    * @param b the debug mode
165    */
166   public void setDebug (boolean b)
167   {
168      mDebug = b;
169   }
170
171   /**
172    * Adds a classpath to the command line.
173    *
174    * @return the created classpath
175    */
176   public Path createClasspath ()
177   {
178      return mCommandline.createClasspath(getProject()).createPath();
179   }
180
181   /**
182    * Adds a bootclasspath to the command line.
183    *
184    * @return the created bootclasspath
185    */
186   public Path createBootclasspath ()
187   {
188      return mCommandline.createBootclasspath(getProject()).createPath();
189   }
190
191   /**
192    * Adds a system property.
193    *
194    * @param sysp system property
195    */
196   public void addSysproperty (Environment.Variable sysp)
197   {
198      mCommandline.addSysproperty(sysp);
199   }
200
201   /**
202    * Adds a JVM argument.
203    *
204    * @return the created command line argument
205    */
206   public Commandline.Argument createJvmarg ()
207   {
208      return mCommandline.createVmArgument();
209   }
210
211   /**
212    * Adds a report to the list of reports.
213    *
214    * @return the created report
215    */
216   public Report createReport ()
217   {
218      final Report ret = new Report();
219      mReportFiles.add(ret);
220      return ret;
221   }
222
223   /**
224    * Adds a source directory to the list of directories.
225    *
226    * @return the created source directory
227    */
228   public SourceDirectory createSrcDir ()
229   {
230      final SourceDirectory ret = new SourceDirectory();
231      mSourceDirectories.add(ret);
232      return ret;
233   }
234
235   /**
236    * Executes this task.
237    *
238    * @throws BuildException An building exception occurred.
239    */
240   public void execute ()
241         throws BuildException
242   {
243      checkParameters();
244
245      try
246      {
247         int exitValue;
248
249         exitValue = executeAsForked();
250
251         if (exitValue != 0)
252         {
253            final String msg = "ReportNormalizer returned with exit code '"
254               + exitValue + "'";
255            log(msg, Project.MSG_WARN);
256            throw new BuildException(msg, getLocation());
257         }
258      }
259      catch (BuildException e)
260      {
261         if (mFailOnError)
262         {
263            throw e;
264         }
265         log(e.getMessage(), e, Project.MSG_ERR);
266      }
267   }
268
269   /**
270    * Create a Java command line for executing the ReportNormalizer.
271    *
272    * @return the Java command line
273    */
274   private CommandlineJava createCommandline ()
275   {
276       final CommandlineJava cmd;
277       try
278       {
279           cmd = (CommandlineJava) mCommandline.clone();
280       }
281       catch (CloneNotSupportedException unexpected)
282       {
283           throw new RuntimeException(
284                   "Ups, CommandLineJava doesn't support the method clone()",
285                   unexpected);
286       }
287
288      cmd.setClassname(ReportNormalizer.class.getName());
289
290      cmd.createArgument().setValue("-out");
291      cmd.createArgument().setFile(mOut);
292
293      cmd.createArgument().setValue("-projectName");
294      cmd.createArgument().setValue(mName);
295
296      cmd.createArgument().setValue("-format");
297      cmd.createArgument().setValue(mOutputFormat.toString());
298
299      cmd.createArgument().setValue("-loglevel");
300      if (mDebug)
301      {
302         cmd.createArgument().setValue("ALL");
303      }
304      else
305      {
306         cmd.createArgument().setValue("INFO");
307      }
308
309      if (mFilter != null)
310      {
311         cmd.createArgument().setValue("-filter");
312         cmd.createArgument().setFile(mFilter);
313      }
314
315      for (final Iterator iterator = mSourceDirectories.iterator();
316            iterator.hasNext();)
317      {
318         final SourceDirectory sourceDir = (SourceDirectory) iterator.next();
319         cmd.createArgument().setValue("-srcDir");
320         cmd.createArgument().setPath(
321                  new Path(getProject(), sourceDir.getDir()));
322      }
323
324      for (final Iterator iterator = mReportFiles.iterator();
325            iterator.hasNext();)
326      {
327         final Report reportFile = (Report) iterator.next();
328         if (reportFile.testIfCondition())
329         {
330            cmd.createArgument().setValue("-" + reportFile.getFormat());
331            cmd.createArgument().setFile(reportFile.getFile());
332         }
333      }
334
335      return cmd;
336   }
337
338   private int executeAsForked ()
339         throws BuildException
340   {
341      final Execute execute
342         = new Execute(new LogStreamHandler(
343                  this, Project.MSG_INFO, Project.MSG_WARN));
344
345      final CommandlineJava cmd = createCommandline();
346      execute.setCommandline(cmd.getCommandline());
347
348      if (mWorkingDir != null)
349      {
350         log("Setting working directory to : "
351               + mWorkingDir, Project.MSG_VERBOSE);
352         execute.setWorkingDirectory(mWorkingDir);
353         execute.setAntRun(getProject());
354      }
355
356      final Path classpath = mCommandline.getClasspath();
357      if (classpath != null)
358      {
359         log("Using CLASSPATH " + classpath, Project.MSG_VERBOSE);
360      }
361
362      log("Executing: [fork] " + cmd.toString(), Project.MSG_VERBOSE);
363
364      try
365      {
366         return execute.execute();
367      }
368      catch (IOException e)
369      {
370         throw new BuildException("Process fork failed.", e, getLocation());
371      }
372   }
373
374   private void checkParameters ()
375   {
376      if (mSourceDirectories.size() == 0)
377      {
378         throw new BuildException(
379               "at least one srcdir element must be specified!", getLocation());
380      }
381   }
382
383   /** This class represents input report with a format and filename. */
384   public final class Report
385   {
386      private ReportFormat mReportFormat;
387      private File mReportFilename;
388      private String mIfCondition = "";
389
390      /**
391       * Returns the report filename.
392       *
393       * @return the report filename
394       */
395      public File getFile ()
396      {
397         return mReportFilename;
398      }
399
400      /**
401       * Sets the report filename.
402       *
403       * @param reportFilename the report filename
404       */
405      public void setFile (File reportFilename)
406      {
407         mReportFilename = reportFilename;
408      }
409
410      /**
411       * Returns the report format.
412       *
413       * @return the report format
414       */
415      public ReportFormat getFormat ()
416      {
417         return mReportFormat;
418      }
419
420      /**
421       * Sets the report format.
422       *
423       * @param reportFormat the report format
424       */
425      public void setFormat (String reportFormat)
426      {
427         mReportFormat = ReportFormat.fromString(reportFormat);
428      }
429
430      /**
431       * Only use report file if the property is set to <code>true</code>.
432       *
433       * @param property the property name to check
434       */
435      public void setif (String property)
436      {
437         mIfCondition = (property == null) ? "" : property;
438      }
439
440      /**
441       * Tests whether or not the "if" condition is satisfied.
442       *
443       * @return whether or not the "if" condition is satisfied. If no
444       *         condition (or an empty condition) has been set,
445       *         <code>true</code> is returned
446       */
447      private boolean testIfCondition ()
448      {
449         final boolean result;
450         if ("".equals(mIfCondition))
451         {
452             result = true;
453         }
454         else
455         {
456             final String test = getProject().replaceProperties(mIfCondition);
457             result = getProject().getProperty(test) != null;
458         }
459         return result;
460      }
461   }
462
463   public static final class SourceDirectory
464   {
465      private String mSourceDir;
466
467      /**
468       * Returns the sourceDir.
469       *
470       * @return the source directory
471       */
472      public final String getDir ()
473      {
474         return mSourceDir;
475      }
476
477      /**
478       * Sets the source directory.
479       *
480       * @param sourceDir the source directory
481       */
482      public final void setDir (String sourceDir)
483      {
484         mSourceDir = sourceDir;
485      }
486   }
487}
Note: See TracBrowser for help on using the browser.