KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hammurapi > TaskBase


1 /*
2   * Hammurapi
3  * Automated Java code review system.
4  * Copyright (C) 2004 Hammurapi Group
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * URL: http://www.hammurapi.org
21  * e-Mail: support@hammurapi.biz
22   */

23 package org.hammurapi;
24
25 import java.io.File JavaDoc;
26 import java.io.FileNotFoundException JavaDoc;
27 import java.io.FileOutputStream JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.io.InputStream JavaDoc;
30 import java.io.PrintStream JavaDoc;
31 import java.text.ParseException JavaDoc;
32 import java.text.SimpleDateFormat JavaDoc;
33 import java.util.ArrayList JavaDoc;
34 import java.util.Collection JavaDoc;
35 import java.util.Date JavaDoc;
36 import java.util.Enumeration JavaDoc;
37 import java.util.HashSet JavaDoc;
38 import java.util.Iterator JavaDoc;
39 import java.util.LinkedList JavaDoc;
40 import java.util.List JavaDoc;
41 import java.util.zip.ZipEntry JavaDoc;
42 import java.util.zip.ZipException JavaDoc;
43 import java.util.zip.ZipFile JavaDoc;
44
45 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
46 import javax.xml.parsers.FactoryConfigurationError JavaDoc;
47 import javax.xml.parsers.ParserConfigurationException JavaDoc;
48 import javax.xml.transform.TransformerException JavaDoc;
49
50 import org.apache.commons.cli.CommandLine;
51 import org.apache.commons.cli.HelpFormatter;
52 import org.apache.commons.cli.Option;
53 import org.apache.commons.cli.OptionBuilder;
54 import org.apache.commons.cli.Options;
55 import org.apache.tools.ant.BuildException;
56 import org.apache.tools.ant.BuildLogger;
57 import org.apache.tools.ant.DefaultLogger;
58 import org.apache.tools.ant.DemuxOutputStream;
59 import org.apache.tools.ant.Project;
60 import org.apache.tools.ant.Task;
61 import org.apache.tools.ant.types.FileSet;
62 import org.apache.tools.ant.types.Path;
63 import org.apache.xpath.CachedXPathAPI;
64 import org.hammurapi.render.dom.DetailedResultsRenderer;
65 import org.hammurapi.results.persistent.jdbc.BaselineSetupViolationFilter;
66 import org.hammurapi.results.persistent.jdbc.BaselineViolationFilter;
67 import org.w3c.dom.Document JavaDoc;
68 import org.w3c.dom.Element JavaDoc;
69 import org.w3c.dom.traversal.NodeIterator;
70 import org.xml.sax.SAXException JavaDoc;
71
72 import com.pavelvlasov.ant.ObjectEntry;
73 import com.pavelvlasov.ant.XmlSourceEntry;
74 import com.pavelvlasov.jsel.RevisionMapper;
75 import com.pavelvlasov.render.RenderRequest;
76 import com.pavelvlasov.render.RenderingException;
77 import com.pavelvlasov.render.dom.AbstractRenderer;
78 import com.pavelvlasov.review.Signed;
79 import com.pavelvlasov.util.ClassResourceLoader;
80 import com.pavelvlasov.xml.dom.AbstractDomObject;
81
82 /**
83  * @author Pavel Vlasov
84  *
85  * @version $Revision: 1.9 $
86  */

87 public class TaskBase extends Task {
88
89     protected void deleteFile(File JavaDoc file) {
90         if (file!=null) {
91             if (file.isDirectory()) {
92                 File JavaDoc[] children=file.listFiles();
93                 if (children!=null) {
94                     for (int i=0; i<children.length; i++) {
95                         deleteFile(children[i]);
96                     }
97                 }
98             }
99             
100             if (file.isFile() || file.isDirectory()) {
101                 file.delete();
102             }
103         }
104     }
105
106     /**
107      * @return Returns the reviewAcceptorEntries.
108      */

109     protected List JavaDoc getReviewAcceptorEntries() {
110         return reviewAcceptorEntries;
111     }
112
113     /**
114      * @return Returns the severityThreshold.
115      */

116     protected Integer JavaDoc getSeverityThreshold() {
117         return severityThreshold;
118     }
119
120     /**
121      * @return Returns the dpmoThreshold.
122      */

123     protected Double JavaDoc getSigmaThreshold() {
124         return sigmaThreshold;
125     }
126
127     /**
128      * @return Returns the dpmoThreshold.
129      */

130     protected Integer JavaDoc getDpmoThreshold() {
131         return dpmoThreshold;
132     }
133
134     /**
135      * @return Returns the failOnWarnings.
136      */

137     protected boolean isFailOnWarnings() {
138         return failOnWarnings;
139     }
140     
141     private File JavaDoc unpackDir;
142     
143     /**
144      * If this attribute is set then HAR archive will be unpacked
145      * in the given directory instead of a temporary one.
146      * @ant.non-required
147      * @param unpackDir
148      */

149     public void setUnpackDir(File JavaDoc unpackDir) {
150         this.unpackDir=unpackDir;
151     }
152
153     /**
154      * @return Returns the debugType.
155      * @ant.ignore
156      */

157     public String JavaDoc getDebugType() {
158         return debugType;
159     }
160
161     protected Collection JavaDoc srcFiles = new LinkedList JavaDoc();
162
163     protected static void loadEmbeddedInspectors(InspectorSet inspectorSet) throws BuildException, HammurapiException {
164         ClassResourceLoader crl=new ClassResourceLoader(TaskBase.class);
165         InputStream JavaDoc inspectorStream=crl.getResourceAsStream(null, null, "xml");
166         if (inspectorStream==null) {
167             throw new BuildException("Cannot load embedded inspectors");
168         }
169         
170         DomInspectorSource source=new DomInspectorSource(inspectorStream, "Hammurapi.jar");
171         source.loadInspectors(inspectorSet);
172     }
173
174     /**
175      * @param options
176      */

177     protected static void populateOptions(Options options) {
178         Option waiverStubsOption=OptionBuilder
179         .withArgName("waiverStubs")
180         .hasArg()
181         .withDescription("Where to output waiver stubs")
182         .isRequired(false)
183         .create("w");
184         
185         options.addOption(waiverStubsOption);
186         
187         Option databaseOption=OptionBuilder
188         .withDescription("Database name")
189         .withArgName("local database")
190         .hasArg()
191         .isRequired(false)
192         .create("D");
193         
194         options.addOption(databaseOption);
195         
196         Option includeInspectorOption=OptionBuilder
197         .withDescription("Enable inspector")
198         .withArgName("inspector name")
199         .hasArg()
200         .isRequired(false)
201         .create("I");
202         
203         options.addOption(includeInspectorOption);
204         
205         Option configFileOption=OptionBuilder
206         .withDescription("Config file")
207         .withArgName("file")
208         .hasArg()
209         .isRequired(false)
210         .create("m");
211         
212         options.addOption(configFileOption);
213         
214         Option configUrlOption=OptionBuilder
215         .withDescription("Config url")
216         .withArgName("url")
217         .hasArg()
218         .isRequired(false)
219         .create("q");
220         
221         options.addOption(configUrlOption);
222         
223         Option unpackDirOption=OptionBuilder
224         .withDescription("Unpack directory")
225         .withArgName("directory")
226         .hasArg()
227         .isRequired(false)
228         .create("r");
229         
230         options.addOption(unpackDirOption);
231         
232         Option excludeInspectorOption=OptionBuilder
233         .withDescription("Disable inspector")
234         .withArgName("inspector name")
235         .hasArg()
236         .isRequired(false)
237         .create("X");
238         
239         options.addOption(excludeInspectorOption);
240         
241         Option archiveFileOption=OptionBuilder
242         .withArgName("archive")
243         .hasArg()
244         .withDescription("Hammurapi archive")
245         .isRequired(false)
246         .create("A");
247         
248         options.addOption(archiveFileOption);
249         Option waiversFileOption=OptionBuilder
250         .withArgName("waivers file")
251         .hasArg()
252         .withDescription("Waivers File")
253         .isRequired(false)
254         .create("W");
255         
256         options.addOption(waiversFileOption);
257         
258         Option forceOption=OptionBuilder
259         .withDescription("Force reviews of unchanged files")
260         .isRequired(false)
261         .create("f");
262         
263         //Anu 20050701 : Baselining.Moved from HammurapiTask.java
264
Option baseliningOption=OptionBuilder
265         .withArgName("off|on|set")
266         .hasArg()
267         .withDescription("Baselining mode")
268         .isRequired(false)
269         .create("B");
270         
271         options.addOption(forceOption);
272         
273         Option forceOnWarningsOption=OptionBuilder
274         .withDescription("Do not force reviews of files with warnings")
275         .isRequired(false)
276         .create("k");
277         
278         options.addOption(forceOnWarningsOption);
279         
280         Option doNotEvictOption=OptionBuilder
281         .withDescription("Evict bad inspectors")
282         .isRequired(false)
283         .create("E");
284         
285         options.addOption(doNotEvictOption);
286         
287         Option waiversUrlOption=OptionBuilder
288         .withArgName("waivers url")
289         .hasArg()
290         .withDescription("Waivers URL")
291         .isRequired(false)
292         .create("U");
293         
294         options.addOption(waiversUrlOption);
295         
296         Option classPathOption=OptionBuilder
297         .withArgName("classpath")
298         .hasArg()
299         .withDescription("ClassPath")
300         .isRequired(false)
301         .create("c");
302         
303         options.addOption(classPathOption);
304         
305         Option sigmaThresholdOption=OptionBuilder
306         .withArgName("sigmaThreshold")
307         .hasArg()
308         .withDescription("Sigma threshold")
309         .isRequired(false)
310         .create("s");
311         
312         options.addOption(sigmaThresholdOption);
313         
314         Option dpmoThresholdOption=OptionBuilder
315         .withArgName("dpmoThreshold")
316         .hasArg()
317         .withDescription("DPMO Threshold")
318         .isRequired(false)
319         .create("d");
320         
321         options.addOption(dpmoThresholdOption);
322         
323         Option severityThresholdOption=OptionBuilder
324         .withArgName("severityThreshold")
325         .hasArg()
326         .withDescription("Severity threshold")
327         .isRequired(false)
328         .create("S");
329         
330         options.addOption(severityThresholdOption);
331         
332         Option noEmbeddedInspectorsOption=OptionBuilder
333         .withDescription("Do not load embedded inspectors")
334         .isRequired(false)
335         .create("e");
336         
337         options.addOption(noEmbeddedInspectorsOption);
338         
339         Option inspectorsFileOption=OptionBuilder
340         .withArgName("inspectorsFile")
341         .hasArg()
342         .withDescription("Inspectors file")
343         .isRequired(false)
344         .create("i");
345         
346         options.addOption(inspectorsFileOption);
347         
348         Option inspectorsURLOption=OptionBuilder
349         .withArgName("inspectorsURL")
350         .hasArg()
351         .withDescription("Inspectors URL")
352         .isRequired(false)
353         .create("u");
354         
355         options.addOption(inspectorsURLOption);
356         
357         Option titleOption=OptionBuilder
358         .withArgName("title")
359         .hasArg()
360         .withDescription("Report title")
361         .isRequired(false)
362         .create("T");
363         
364         options.addOption(titleOption);
365         
366         Option debugTypeOption=OptionBuilder
367         .withArgName("debug type")
368         .hasArg()
369         .withDescription("Jsel type to debug")
370         .isRequired(false)
371         .create("t");
372         
373         options.addOption(debugTypeOption);
374         
375         Option listenerOption=OptionBuilder
376         .withArgName("class name")
377         .hasArg()
378         .withDescription("Review listener")
379         .isRequired(false)
380         .create("l");
381         
382         options.addOption(listenerOption);
383                 
384         Option debugOption=OptionBuilder
385         .withDescription("Debug")
386         .isRequired(false)
387         .create("g");
388         
389         options.addOption(debugOption);
390         
391         Option verboseOption=OptionBuilder
392         .withDescription("Verbose")
393         .isRequired(false)
394         .create("v");
395         
396         options.addOption(verboseOption);
397         
398         Option xmlOption=OptionBuilder
399         .withDescription("Output XML")
400         .isRequired(false)
401         .create("x");
402                         
403         options.addOption(xmlOption);
404         
405         Option suppressOutputOption=OptionBuilder
406         .withDescription("Suppress output")
407         .isRequired(false)
408         .create("o");
409                                                 
410         options.addOption(suppressOutputOption);
411         
412         Option descriptionOption=OptionBuilder
413         .withDescription("Review description")
414         .withArgName("description")
415         .hasArg()
416         .isRequired(false)
417         .create("y");
418         
419         options.addOption(descriptionOption);
420         
421         Option helpOption=OptionBuilder.withDescription("Print this message").isRequired(false).create("h");
422         options.addOption(helpOption);
423     }
424
425     protected static void printHelpAndExit(Options options) {
426         HelpFormatter formatter=new HelpFormatter();
427         formatter.printHelp("Usage: hammurapi [options] <output dir> <source files/dirs>", options, false);
428         System.exit(1);
429     }
430
431     /**
432      * Class name to debug
433      * @ant.non-required
434      */

435     public void setDebugType(String JavaDoc debugType) {
436         this.debugType=debugType;
437     }
438
439     /**
440      * Load embedded inspectors. Defaults to true.
441      * @ant.non-required
442      */

443     public void setEmbeddedInspectors(boolean embeddedInspectors) {
444         this.embeddedInspectors=embeddedInspectors;
445     }
446
447     private String JavaDoc debugType;
448     protected boolean embeddedInspectors = true;
449     protected List JavaDoc srcFileSets = new LinkedList JavaDoc();
450
451     /**
452      * Source files fileset.
453      * @ant.non-required
454      */

455     public FileSet createSrc() {
456         FileSet ret=new HammurapiFileSet("**/*.java");
457         srcFileSets.add(ret);
458         return ret;
459     }
460
461     protected void setHadExceptions() {
462         hadExceptions=true;
463     }
464
465     /**
466      * @param collection
467      * @throws FileNotFoundException
468      * @throws RenderingException
469      */

470     protected void writeWaiverStubs(final Collection JavaDoc rejectedViolations) throws RenderingException, FileNotFoundException JavaDoc {
471         if (waiverStubs!=null) {
472             class WaiverStubsRenderer extends AbstractRenderer {
473                 WaiverStubsRenderer() {
474                     super(new RenderRequest(rejectedViolations));
475                 }
476     
477                 public Element JavaDoc render(Document JavaDoc document) {
478                     Element JavaDoc ret=document.createElement("waivers");
479                     Iterator JavaDoc it=rejectedViolations.iterator();
480                     final Date JavaDoc now=new Date JavaDoc();
481                     while (it.hasNext()) {
482                         final Violation violation=(Violation) it.next();
483                         
484                         StringBuffer JavaDoc comment=new StringBuffer JavaDoc();
485                         comment.append("Source: ");
486                         comment.append(violation.getSource().getSourceURL());
487                         
488                         comment.append("\nLine: ");
489                         comment.append(violation.getSource().getLine());
490                         
491                         comment.append("\nCol: ");
492                         comment.append(violation.getSource().getColumn());
493                         
494                         comment.append("\nDescription: ");
495                         comment.append(violation.getDescriptor().getDescription());
496                         
497                         comment.append("\nMesssage: ");
498                         comment.append(violation.getMessage());
499                         
500                         ret.appendChild(document.createComment(comment.toString()));
501                         
502                         Waiver waiver=new Waiver() {
503     
504                             public String JavaDoc getInspectorName() {
505                                 return violation.getDescriptor().getName();
506                             }
507     
508                             public Date JavaDoc getExpirationDate() {
509                                 return now;
510                             }
511     
512                             public String JavaDoc getReason() {
513                                 return "*** Put reason here ***";
514                             }
515     
516                             public boolean waive(Violation violation, boolean peek) {
517                                 // This 'waiver' will never waive anything, it is used only for rendering
518
return false;
519                             }
520     
521                             public boolean isActive() {
522                                 // This 'waiver' will never waive anything, it is used only for rendering
523
return false;
524                             }
525                             
526                             Collection JavaDoc signatures=new HashSet JavaDoc();
527                             
528                             {
529                                 if (violation.getSource() instanceof Signed) {
530                                     signatures.add(((Signed) violation.getSource()).getSignature());
531                                 }
532                             }
533     
534                             public Collection JavaDoc getSignatures() {
535                                 return signatures;
536                             }
537                         };
538                         ret.appendChild(DetailedResultsRenderer.renderWaiver(waiver, document));
539                     }
540                     return ret;
541                 }
542             }
543             WaiverStubsRenderer renderer=new WaiverStubsRenderer();
544             renderer.setEmbeddedStyle(false);
545             renderer.render(new FileOutputStream JavaDoc(waiverStubs));
546         }
547     }
548
549     protected File JavaDoc processArchive() {
550         if (archive==null) {
551             return null;
552         }
553         
554         String JavaDoc tmpDirProperty=System.getProperty("java.io.tmpdir");
555         File JavaDoc tmpDir=tmpDirProperty==null ? new File JavaDoc(".") : new File JavaDoc(tmpDirProperty);
556         SimpleDateFormat JavaDoc sdf=new SimpleDateFormat JavaDoc("yyyyMMddHHmmss");
557         String JavaDoc prefix = "har_"+sdf.format(new Date JavaDoc());
558         File JavaDoc workDir = unpackDir==null ? new File JavaDoc(tmpDir, prefix) : unpackDir;
559         
560         for (int i=0; unpackDir==null && workDir.exists(); i++) {
561             workDir=new File JavaDoc(tmpDir, prefix+"_"+Integer.toString(i, Character.MAX_RADIX));
562         }
563         
564         if (workDir.exists() || workDir.mkdir()) {
565             try {
566                 ZipFile JavaDoc zipFile=new ZipFile JavaDoc(archive);
567                 Enumeration JavaDoc entries = zipFile.entries();
568                 while (entries.hasMoreElements()) {
569                     ZipEntry JavaDoc entry=(ZipEntry JavaDoc) entries.nextElement();
570                     if (!entry.getName().endsWith("/")) {
571                         File JavaDoc outFile=new File JavaDoc(workDir, entry.getName().replace('/', File.separatorChar));
572                         if (!outFile.getParentFile().exists() && !outFile.getParentFile().mkdirs()) {
573                             throw new BuildException("Directory does not exist and cannot be created: "+outFile.getParentFile().getAbsolutePath());
574                         }
575                         
576                         log("Archive entry "+entry.getName()+" unpacked to "+outFile.getAbsolutePath(), Project.MSG_DEBUG);
577                         
578                         byte[] buf=new byte[4096];
579                         int l;
580                         InputStream JavaDoc in=zipFile.getInputStream(entry);
581                         FileOutputStream JavaDoc fos=new FileOutputStream JavaDoc(outFile);
582                         while ((l=in.read(buf))!=-1) {
583                             fos.write(buf, 0, l);
584                         }
585                         in.close();
586                         fos.close();
587                     }
588                 }
589                 zipFile.close();
590                 
591                 File JavaDoc configFile=new File JavaDoc(workDir, "config.xml");
592                 if (configFile.exists() && configFile.isFile()) {
593                     Document JavaDoc configDoc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(configFile);
594                     processConfig(workDir, configDoc.getDocumentElement());
595                 } else {
596                     throw new BuildException("Archive configuration file does not exist or is not a file");
597                 }
598             } catch (ZipException JavaDoc e) {
599                 throw new BuildException(e.toString(), e);
600             } catch (IOException JavaDoc e) {
601                 throw new BuildException(e.toString(), e);
602             } catch (SAXException JavaDoc e) {
603                 throw new BuildException(e.toString(), e);
604             } catch (ParserConfigurationException JavaDoc e) {
605                 throw new BuildException(e.toString(), e);
606             } catch (FactoryConfigurationError JavaDoc e) {
607                 throw new BuildException(e.toString(), e);
608             }
609         } else {
610             throw new BuildException("Could not create directory "+workDir.getAbsolutePath());
611         }
612         return unpackDir==null ? workDir : null;
613     }
614
615     /**
616      * @param workDir
617      * @param configDoc
618      * @throws ParseException
619      * @throws TransformerException
620      */

621     private void processConfig(File JavaDoc workDir, Element JavaDoc config) {
622         if (config!=null) {
623             try {
624                 setAttributes(config);
625                 
626                 CachedXPathAPI cxpa=new CachedXPathAPI();
627                 NodeIterator nit=cxpa.selectNodeIterator(config, "sources/source");
628                 Element JavaDoc element;
629                 while ((element=(Element JavaDoc) nit.nextNode())!=null) {
630                     srcFiles.add(new File JavaDoc(workDir, AbstractDomObject.getElementText(element)));
631                 }
632                 
633                 nit=cxpa.selectNodeIterator(config, "classpath/path");
634                 while ((element=(Element JavaDoc) nit.nextNode())!=null) {
635                     File JavaDoc cpe = new File JavaDoc(workDir, AbstractDomObject.getElementText(element));
636                     if (cpe.exists()) {
637                         createClasspath().setLocation(cpe);
638                         log("File "+cpe.getAbsolutePath()+" added to classpath", Project.MSG_DEBUG);
639                     } else {
640                         throw new BuildException("Classpath element "+cpe.getAbsolutePath()+" does not exist");
641                     }
642                 }
643             } catch (TransformerException JavaDoc e) {
644                 throw new BuildException("Cannot load config", e);
645             }
646         }
647     }
648
649     /**
650      * @param config
651      * @throws ParseException
652      */

653     protected void setAttributes(Element JavaDoc config) {
654         if (config.hasAttribute("title")) {
655             setTitle(config.getAttribute("title"));
656         }
657         
658         if (config.hasAttribute("dpmo-threshold")) {
659             setDpmoThreshold(Integer.parseInt(config.getAttribute("dpmo-threshold")));
660         }
661         
662         if (config.hasAttribute("sigma-threshold")) {
663             setSigmaThreshold(Double.parseDouble(config.getAttribute("sigma-threshold")));
664         }
665         
666         if (config.hasAttribute("severity-threshold")) {
667             setSeverityThreshold(Integer.parseInt(config.getAttribute("severity-threshold")));
668         }
669         
670         if (config.hasAttribute("force")) {
671             setForce("yes".equals(config.getAttribute("force")));
672         }
673         
674         if (config.hasAttribute("force-on-warnings")) {
675             setForceOnWarnings("yes".equals(config.getAttribute("force-on-warnings")));
676         }
677         
678         if (config.hasAttribute("review-description")) {
679             setReviewDescription(config.getAttribute("review-description"));
680         }
681         
682         //Anu : 20050701 for baselining
683
if (config.hasAttribute("baselining")) {
684             setBaselining(config.getAttribute("baselining"));
685         }
686     }
687
688     protected boolean suppressLogo;
689
690     /**
691      * Defines output
692      * @ant.non-required
693      */

694     public Output createOutput() {
695         Output output=new Output(this);
696         outputs.add(output);
697         return output;
698     }
699
700     /**
701      * Defines history output, which stores review summary
702      * into database.
703      * @ant.non-required
704      */

705     public HistoryOutput createHistoryOutput() {
706         HistoryOutput historyOutput=new HistoryOutput();
707         outputs.add(historyOutput);
708         return historyOutput;
709     }
710     
711     protected List JavaDoc outputs = new LinkedList JavaDoc();
712     protected boolean hadExceptions;
713
714     /**
715      * Maybe creates a nested classpath element.
716      * @ant :non-required
717      */

718     public Path createClasspath() {
719         if (classPath == null) {
720             classPath = new Path(project);
721         }
722         return classPath.createPath();
723     }
724
725     public void setClassPath(Path classPath) {
726         if (this.classPath == null) {
727             this.classPath = classPath;
728         } else {
729             this.classPath.append(classPath);
730         }
731     }
732
733     /**
734      * Classpath for loading classes.
735      * @ant :non-required
736      */

737     protected Path classPath;
738
739     /**
740      * Defines inspector
741      * @ant.non-required
742      */

743     public InspectorEntry createInspector() {
744         InspectorEntry inspectorEntry=new InspectorEntry();
745         inspectors.add(inspectorEntry);
746         return inspectorEntry;
747     }
748
749     protected List JavaDoc inspectors = new LinkedList JavaDoc();
750
751     /**
752      * Defines waivers source
753      * @ant.non-required
754      */

755     public WaiverSourceEntry createWaivers() {
756         WaiverSourceEntry ret=new WaiverSourceEntry();
757         ret.setProject(getProject());
758         waivers.add(ret);
759         return ret;
760     }
761     
762     private Collection JavaDoc configs=new ArrayList JavaDoc();
763     
764     protected void processConfigs(File JavaDoc baseDir) {
765         Iterator JavaDoc it=configs.iterator();
766         while (it.hasNext()) {
767             XmlSourceEntry xse=(XmlSourceEntry) it.next();
768             processConfig(xse.getFile()==null ? baseDir : xse.getFile(), xse.getDocumentElement());
769         }
770     }
771
772     /**
773      * Configuration source.
774      * Task can be configured from multiple sources.
775      * @ant.non-required
776      */

777     public XmlSourceEntry createConfig() {
778         XmlSourceEntry ret=new XmlSourceEntry();
779         configs.add(ret);
780         ret.setProject(getProject());
781         return ret;
782     }
783     
784     /**
785      * Defines inspector source
786      * @ant.non-required
787      */

788     public InspectorSourceEntry createInspectors() {
789         InspectorSourceEntry ret=new InspectorSourceEntry();
790         inspectors.add(ret);
791         ret.setProject(getProject());
792         return ret;
793     }
794
795     /**
796      * Hammurapi archive to process.
797      * @ant.non-required
798      * @param archive
799      */

800     public void setArchive(File JavaDoc archive) {
801         this.archive=archive;
802     }
803
804     private File JavaDoc archive;
805
806     /**
807      * Fail build if project DPMO is above the threshold.
808      * @ant.non-required
809      */

810     public void setDpmoThreshold(int dpmoThreshold) throws BuildException {
811         this.dpmoThreshold=new Integer JavaDoc(dpmoThreshold);
812     }
813
814     /**
815      * Fail build if project Sigma is below the threshold.
816      * @ant.non-required
817      */

818     public void setSigmaThreshold(double sigmaThreshold) throws BuildException {
819         this.sigmaThreshold=new Double JavaDoc(sigmaThreshold);
820     }
821
822     protected Collection JavaDoc waivers = new LinkedList JavaDoc();
823     private Integer JavaDoc dpmoThreshold;
824     private Double JavaDoc sigmaThreshold;
825
826     /**
827      * Review listener
828      * @ant.non-required
829      */

830     public void addConfiguredListener(ListenerEntry listener) {
831         listenerEntries.add(listener);
832     }
833
834     /**
835      * Review acceptor.
836      * @ant.non-required
837      */

838     public void addConfiguredReviewAcceptor(ReviewAcceptorEntry reviewAcceptor) throws BuildException {
839         reviewAcceptorEntries.add(reviewAcceptor);
840     }
841
842     private List JavaDoc reviewAcceptorEntries = new LinkedList JavaDoc();
843
844     /**
845      * Fail build as soon as there is an exception. Default is false.
846      * @ant.non-required
847      */

848     public void setFailOnFirstException(boolean failOnFirstException) {
849         this.failOnFirstException=failOnFirstException;
850     }
851
852     protected boolean failOnFirstException = false;
853
854     /**
855      * Fail build if there have been warnings. Default is true.
856      * @ant.non-required
857      */

858     public void setFailOnWarnings(boolean failOnWarnings) {
859         this.failOnWarnings=failOnWarnings;
860     }
861
862     private boolean failOnWarnings = true;
863
864     /**
865      * Fail build on violations with severity levels lower or equal to the threshold.
866      * @ant.non-required
867      */

868     public void setSeverityThreshold(int severityThreshold) {
869         this.severityThreshold=new Integer JavaDoc(severityThreshold);
870     }
871
872     /**
873      * @ant.non-required
874      * @param title
875      */

876     public void setTitle(String JavaDoc title) {
877         this.title=title;
878     }
879
880     protected String JavaDoc title = "Summary "+new Date JavaDoc();
881
882     /**
883      * @param options
884      * @param line
885      * @param task
886      * @param project
887      */

888     protected void configure(Options options, CommandLine line) {
889         String JavaDoc[] largs=line.getArgs();
890         if (largs.length==0) {
891             System.out.println("Output dir has to be provided");
892             printHelpAndExit(options);
893         }
894         
895         if (!line.hasOption('o')) {
896             new File JavaDoc(largs[0]).mkdirs();
897             Output output=createOutput();
898             output.setDir(largs[0]);
899             
900             if (line.hasOption('x')) {
901                 output.setEmbeddedStyle(false);
902                 output.setExtension(".xml");
903             }
904         }
905         
906         if (largs.length==1 && !line.hasOption('A')) {
907             System.out.println("At least one source directory or archive must be provided");
908             printHelpAndExit(options);
909         }
910                 
911         if (line.hasOption('y')) {
912             setReviewDescription(line.getOptionValue('y'));
913         }
914         
915         for (int i=1; i<largs.length; i++) {
916             File JavaDoc file = new File JavaDoc(largs[i]);
917             if (file.isFile()) {
918                 srcFiles.add(file);
919             } else if (file.isDirectory()) {
920                 createSrc().setDir(file);
921             }
922         }
923     
924         String JavaDoc[] values=line.getOptionValues('c');
925         for (int i=0; values!=null && i<values.length; i++) {
926             createClasspath().append(new Path(project, values[i]));
927         }
928         
929         values=line.getOptionValues('m');
930         for (int i=0; values!=null && i<values.length; i++) {
931             createConfig().setFile(new File JavaDoc(values[i]));
932         }
933         
934         values=line.getOptionValues('q');
935         for (int i=0; values!=null && i<values.length; i++) {
936             createConfig().setURL(values[i]);
937         }
938         
939         values=line.getOptionValues('I');
940         for (int i=0; values!=null && i<values.length; i++) {
941             InspectorEntry ie = createInspector();
942             ie.setName(values[i]);
943             ie.setEnabled(true);
944         }
945         
946         values=line.getOptionValues('X');
947         for (int i=0; values!=null && i<values.length; i++) {
948             InspectorEntry ie = createInspector();
949             ie.setName(values[i]);
950             ie.setEnabled(false);
951         }
952         
953         setEvictBadInspectors(line.hasOption('E'));
954         
955         setEmbeddedInspectors(!line.hasOption('e'));
956     
957         if (line.hasOption('t')) {
958             setDebugType(line.getOptionValue('t'));
959         }
960                 
961         if (line.hasOption('r')) {
962             setUnpackDir(new File JavaDoc(line.getOptionValue('r')));
963         }
964                 
965         if (line.hasOption('T')) {
966             setTitle(line.getOptionValue('T'));
967         }
968     
969         BuildLogger logger = new DefaultLogger();
970         logger.setMessageOutputLevel(Project.MSG_INFO);
971         logger.setOutputPrintStream(System.out);
972         logger.setErrorPrintStream(System.err);
973         logger.setEmacsMode(false);
974         
975         if (line.hasOption('v')) {
976             logger.setMessageOutputLevel(Project.MSG_VERBOSE);
977         }
978         
979         if (line.hasOption('g')) {
980             logger.setMessageOutputLevel(Project.MSG_DEBUG);
981         }
982         
983         project.addBuildListener(logger);
984         
985         System.setOut(new PrintStream JavaDoc(new DemuxOutputStream(project, false)));
986         System.setErr(new PrintStream JavaDoc(new DemuxOutputStream(project, true)));
987         
988         if (line.hasOption('w')) {
989             setWaiverStubs(new File JavaDoc(line.getOptionValue('w')));
990         }
991         
992         if (line.hasOption('s')) {
993             setSigmaThreshold(Double.parseDouble(line.getOptionValue('s')));
994         }
995         
996         if (line.hasOption('d')) {
997             setDpmoThreshold(Integer.parseInt(line.getOptionValue('d')));
998         }
999         
1000        if (line.hasOption('S')) {
1001            setSeverityThreshold(Integer.parseInt(line.getOptionValue('S')));
1002        }
1003                
1004        if (line.hasOption('f')) {
1005            setForce(true);
1006        }
1007        
1008        if (line.hasOption('k')) {
1009            setForceOnWarnings(false);
1010        }
1011        
1012        if (line.hasOption('D')) {
1013            setDatabase(new File JavaDoc(line.getOptionValue('D')));
1014        }
1015        
1016        values=line.getOptionValues('i');
1017        for (int i=0; values!=null && i<values.length; i++) {
1018            createInspectors().setFile(new File JavaDoc(values[i]));
1019        }
1020                
1021        values=line.getOptionValues('u');
1022        for (int i=0; values!=null && i<values.length; i++) {
1023            createInspectors().setURL(values[i]);
1024        }
1025        
1026        values=line.getOptionValues('l');
1027        for (int i=0; values!=null && i<values.length; i++) {
1028            ListenerEntry listenerEntry = new ListenerEntry();
1029            listenerEntry.setClassName(values[i]);
1030            addConfiguredListener(listenerEntry);
1031        }
1032        
1033        values=line.getOptionValues('W');
1034        for (int i=0; values!=null && i<values.length; i++) {
1035            createWaivers().setFile(new File JavaDoc(values[i]));
1036        }
1037                
1038        values=line.getOptionValues('U');
1039        for (int i=0; values!=null && i<values.length; i++) {
1040            createWaivers().setURL(values[i]);
1041        }
1042        
1043        if (line.hasOption('A')) {
1044            setArchive(new File JavaDoc(line.getOptionValue('A')));
1045        }
1046        
1047        //Anu 20050701 : baselining
1048
if (line.hasOption('B')) {
1049            setBaselining(line.getOptionValue('B'));
1050        }
1051    }
1052
1053    /**
1054     * File to output waiver stubs for rejected waiver requests to. Selected waiver stubs can then be copied to waiver source. Simplifies waiver creation
1055     * @ant.non-required
1056     * @param waiverStubs
1057     */

1058    public void setWaiverStubs(File JavaDoc waiverStubs) {
1059        this.waiverStubs=waiverStubs;
1060    }
1061
1062    /**
1063     * Revision mapper. Must implement com.pavelvlasov.jsel.RevisionMapper interface.
1064     * @ant.non-required
1065     * @return
1066     */

1067    public ObjectEntry createRevisionMapper() {
1068        if (revisionMapper==null) {
1069            revisionMapper = new ObjectEntry() {
1070                protected void validateClass(Class JavaDoc clazz) throws BuildException {
1071                    super.validateClass(clazz);
1072                    if (!RevisionMapper.class.isAssignableFrom(clazz)) {
1073                        throw new BuildException(clazz.getName()+" doesn't implement "+RevisionMapper.class.getName());
1074                    }
1075                }
1076            };
1077            return revisionMapper;
1078        } else {
1079            throw new BuildException("Revision mapper already defined");
1080        }
1081    }
1082
1083    private File JavaDoc waiverStubs;
1084    private Integer JavaDoc severityThreshold;
1085    protected List JavaDoc listenerEntries = new LinkedList JavaDoc();
1086    ObjectEntry revisionMapper;
1087    protected boolean force = false;
1088    protected boolean evictBadInspectors = false;
1089
1090    /**
1091     * Remove inspector from inspector set if it throws an exception
1092     * during review
1093     * @param evictBadInspectors
1094     * @ant.non-required
1095     */

1096    public void setEvictBadInspectors(boolean evictBadInspectors) {
1097        this.evictBadInspectors=evictBadInspectors;
1098    }
1099
1100    /**
1101     * Force review even if the file is not changed
1102     * @param force
1103     * @ant.non-required
1104     */

1105    public void setForce(boolean force) {
1106        this.force=force;
1107    }
1108
1109    //Anu 20050701 : setBaselining method moved from HammurapiTask to TaskBase
1110
/**
1111     * Sets baselining mode. Possible values:
1112     * off (default) - no baselining, on - do not report
1113     * violations stored in the baseline table, set - all violations
1114     * from current scan are saved to the baseline table.
1115     * The idea is to filter out all violations in
1116     * preexisting code and report only new violations.
1117     * Not all violations can be filtered out, only thouse
1118     * with signatures. Significant code modifications can surface some
1119     * baselined violation.
1120     * @ant.non-required
1121     * @param baselineMode
1122     */

1123    public void setBaselining(String JavaDoc baselineMode) {
1124        if ("off".equals(baselineMode)) {
1125            // Nothing.
1126
} else if ("on".equals(baselineMode)) {
1127            violationFilters.add(new BaselineViolationFilter());
1128        } else if ("set".equalsIgnoreCase(baselineMode)) {
1129            violationFilters.add(new BaselineSetupViolationFilter());
1130        } else {
1131            throw new BuildException("Invalid baselining mode: "+baselineMode);
1132        }
1133        
1134    }
1135
1136    
1137    protected boolean forceOnWarnings = true;
1138
1139    /**
1140     * Force review of files with warnings, even if the file is not changed.
1141     * Default is true
1142     * @param
1143     * @ant.non-required
1144     */

1145    public void setForceOnWarnings(boolean forceOnWarnings) {
1146        this.forceOnWarnings=forceOnWarnings;
1147    }
1148
1149    protected File JavaDoc database;
1150    protected String JavaDoc reviewDescription;
1151
1152    /**
1153     * Description of review, e.g. release number. Appears in history annotation.
1154     * @ant.non-required
1155     * @param baseLine
1156     */

1157    public void setReviewDescription(String JavaDoc reviewDescription) {
1158        this.reviewDescription=reviewDescription;
1159    }
1160
1161    /**
1162     * If this parameter is set then Hypersonic standalone database
1163     * will be used instead of temporary database. You must set
1164     * database name if you want to run incremental reviews.
1165     * @ant.non-required
1166     * @param database
1167     */

1168    public void setDatabase(File JavaDoc database) {
1169        this.database=database;
1170    }
1171
1172    protected boolean isForceOnWarnings() {
1173        return forceOnWarnings;
1174    }
1175
1176    protected boolean isForce() {
1177        return force;
1178    }
1179    
1180    protected int tabSize=8;
1181
1182    /**
1183     * Tab size in source files. Defaults to 8.
1184     * @param tabSize The tabSize to set.
1185     * @ant.non-required
1186     */

1187    public void setTabSize(int tabSize) {
1188        this.tabSize = tabSize;
1189    }
1190
1191    protected Collection JavaDoc violationFilters = new ArrayList JavaDoc();
1192    
1193    private String JavaDoc encoding;
1194    
1195    /**
1196     * Files encoding
1197     * @param encoding
1198     * @ant.non-required
1199     */

1200    public void setEncoding(String JavaDoc encoding) {
1201        this.encoding = encoding;
1202    }
1203    
1204    protected String JavaDoc getEncoding() {
1205        return encoding;
1206    }
1207}
1208
Popular Tags