KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hammurapi > QuickHammurapiTask


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.FileInputStream JavaDoc;
27 import java.io.FileNotFoundException JavaDoc;
28 import java.io.FileReader JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.InputStream JavaDoc;
31 import java.io.InputStreamReader JavaDoc;
32 import java.io.Reader JavaDoc;
33 import java.sql.SQLException JavaDoc;
34 import java.text.MessageFormat JavaDoc;
35 import java.util.ArrayList JavaDoc;
36 import java.util.Collection JavaDoc;
37 import java.util.Date JavaDoc;
38 import java.util.Iterator JavaDoc;
39 import java.util.LinkedList JavaDoc;
40 import java.util.List JavaDoc;
41
42 import org.apache.commons.cli.CommandLine;
43 import org.apache.commons.cli.CommandLineParser;
44 import org.apache.commons.cli.Options;
45 import org.apache.commons.cli.PosixParser;
46 import org.apache.tools.ant.AntClassLoader;
47 import org.apache.tools.ant.BuildException;
48 import org.apache.tools.ant.DirectoryScanner;
49 import org.apache.tools.ant.Project;
50 import org.hammurapi.results.CompositeResults;
51 import org.hammurapi.results.ResultsFactory;
52 import org.hammurapi.results.quick.PackageTotal;
53 import org.hammurapi.results.simple.QuickResultsFactory;
54
55 import com.pavelvlasov.config.Component;
56 import com.pavelvlasov.config.ConfigurationException;
57 import com.pavelvlasov.jsel.JselException;
58 import com.pavelvlasov.jsel.impl.CompilationUnitImpl;
59 import com.pavelvlasov.logging.AntLogger;
60 import com.pavelvlasov.logging.Logger;
61 import com.pavelvlasov.sql.DataAccessObject;
62 import com.pavelvlasov.util.ClassResourceLoader;
63 import com.pavelvlasov.util.VisitorStack;
64 import com.pavelvlasov.util.VisitorStackSource;
65
66 /**
67  * Performs automatic code reviews. Quick mode - doesn't store anything to the database,
68  * package and repository level inspectors are not invoked.
69  * <section name="Example" suppress-description="yes">
70 If you copy content of Hammurapi lib directory to ant lib directory then you can
71 invoke Hammurapi in the following way:
72  <pre>
73 &lt;taskdef name="quickurappi" classname="org.hammurapi.QuickHammurapiTask" /&gt;<br/>
74 <br/>
75 &lt;quickurappi&gt;<br/>
76     <tab/>&lt;src dir="src"/&gt;<br/>
77     <tab/>&lt;output dir="review"/&gt;<br/>
78 &lt;/quickurappi&gt;</pre>
79 or, if you didn't copy jar files to Ant lib directory, use this syntax:
80 <pre>
81 &lt;taskdef name="quickurappi" classname="org.hammurapi.QuickHammurapiTask"&gt;<br/>
82     <tab/>&lt;classpath&gt;<br/>
83         <tab/><tab/>&lt;fileset dir="${hammurapi.home}/lib" includes="*.jar"/&gt;<br/>
84     <tab/>&lt;/classpath&gt;<br/>
85 &lt;/taskdef&gt;<br/>
86 <br/>
87 &lt;quickurappi&gt;<br/>
88     <tab/>&lt;src dir="src"/&gt;<br/>
89     <tab/>&lt;output dir="review"/&gt;<br/>
90 &lt;/quickurappi&gt;
91 </pre>
92
93 </section>
94  * @ant.element name="hammurapi" display-name="Automatic code review task"
95  * @author Pavel Vlasov
96  * @version $Revision: 1.10 $
97  */

98 public class QuickHammurapiTask extends TaskBase {
99     public void execute() throws BuildException {
100         if (!suppressLogo) {
101             log("Quick Hammurapi 3 Copyright (C) 2004 Hammurapi Group");
102         }
103         
104         File JavaDoc archiveTmpDir=processArchive();
105         
106         try {
107             long start=System.currentTimeMillis();
108             
109             Logger logger=new AntLogger(this);
110             
111             final VisitorStack[] visitorStack={null};
112             final VisitorStackSource visitorStackSource=new VisitorStackSource() {
113                 public VisitorStack getVisitorStack() {
114                     return visitorStack[0];
115                 }
116             };
117             
118             final SessionImpl session=new SessionImpl();
119             
120             InspectorSet inspectorSet=new InspectorSet(
121                     new InspectorContextFactory() {
122                         public InspectorContext newContext(InspectorDescriptor descriptor, Logger logger) {
123                             return new InspectorContextImpl(
124                                     descriptor,
125                                     logger,
126                                     visitorStackSource,
127                                     session,
128                                     violationFilters);
129                         }
130                     },
131                     logger);
132             
133             if (embeddedInspectors) {
134                 log("Loading embedded inspectors", Project.MSG_VERBOSE);
135                 loadEmbeddedInspectors(inspectorSet);
136             }
137             
138             log("Loading inspectors", Project.MSG_VERBOSE);
139             Iterator JavaDoc it=inspectors.iterator();
140             while (it.hasNext()) {
141                 Object JavaDoc o=it.next();
142                 if (o instanceof InspectorSource) {
143                     ((InspectorSource) o).loadInspectors(inspectorSet);
144                 } else {
145                     InspectorEntry inspectorEntry = (InspectorEntry) o;
146                     inspectorSet.addDescriptor(inspectorEntry);
147                     inspectorSet.addInspectorSourceInfo(
148                             new InspectorSourceInfo(
149                                     "Inline inspector "+inspectorEntry.getName(),
150                                     "Build file: "+inspectorEntry.getLocation().toString(),
151                                     ""));
152                 }
153             }
154             
155             log("Inspectors loaded: "+inspectorSet.size(), Project.MSG_VERBOSE);
156             
157             log("Loading waivers", Project.MSG_VERBOSE);
158             Date JavaDoc now=new Date JavaDoc();
159             WaiverSet waiverSet=new WaiverSet();
160             it=waivers.iterator();
161             while (it.hasNext()) {
162                 ((WaiverSource) it.next()).loadWaivers(waiverSet,now);
163             }
164             
165             log("Waivers loaded: "+waiverSet.size(), Project.MSG_VERBOSE);
166             
167             log("Loading listeners", Project.MSG_VERBOSE);
168             List JavaDoc listeners=new LinkedList JavaDoc();
169             it=listenerEntries.iterator();
170             while (it.hasNext()) {
171                 listeners.add(((ListenerEntry) it.next()).getObject(null));
172             }
173             
174             //Outputs
175
listeners.addAll(outputs);
176             listeners.add(new ReviewToLogListener(project));
177             
178             Collection JavaDoc inspectors=new LinkedList JavaDoc(inspectorSet.getInspectors());
179             session.setInspectors(inspectorSet);
180             Iterator JavaDoc inspectorsIt=inspectors.iterator();
181             log("Inspectors mapping", Project.MSG_VERBOSE);
182             while (inspectorsIt.hasNext()) {
183                 Inspector inspector=(Inspector) inspectorsIt.next();
184                 log("\t"+inspector.getContext().getDescriptor().getName()+" -> "+inspector.getClass().getName(), Project.MSG_VERBOSE);
185             }
186             
187             ClassLoader JavaDoc classLoader;
188             if (classPath==null) {
189                 classLoader=this.getClass().getClassLoader();
190             } else {
191                 classLoader=new AntClassLoader(project, classPath, false);
192                 session.setClassPath(classPath.list());
193             }
194             
195             new QuickResultsFactory(waiverSet, classLoader, tabSize, logger).install();
196                         
197             Iterator JavaDoc lit=listeners.iterator();
198             while (lit.hasNext()) {
199                 ((Listener) lit.next()).onBegin(inspectorSet);
200             }
201             
202             try {
203                 QuickResultsCollector collector = new QuickResultsCollector(this, title, listeners);
204                 
205                 // Initializing violation filters
206
Iterator JavaDoc vfit=violationFilters.iterator();
207                 while (vfit.hasNext()) {
208                     Object JavaDoc vf=vfit.next();
209                     if (vf instanceof DataAccessObject) {
210                         ((DataAccessObject) vf).setSQLProcessor(collector.getProcessor());
211                     }
212                     
213                     if (vf instanceof Component) {
214                         ((Component) vf).start();
215                     }
216                 }
217                             
218                 try {
219                     inspectors.add(collector);
220                     
221                     QuickReviewEngine engine=new QuickReviewEngine(inspectors, this, collector);
222                     visitorStack[0]=engine.getVisitorStack();
223                     session.setVisitor(engine.getVisitor());
224                                             
225                     it=srcFileSets.iterator();
226                     while (it.hasNext()) {
227                         HammurapiFileSet fs=(HammurapiFileSet) it.next();
228                         fs.setDefaultIncludes();
229                         DirectoryScanner scanner=fs.getDirectoryScanner(project);
230                         String JavaDoc[] includedFiles=scanner.getIncludedFiles();
231                         for (int i=0; i<includedFiles.length; i++) {
232                             review(new File JavaDoc(scanner.getBasedir(), includedFiles[i]), engine, classLoader, logger);
233                         }
234                     }
235                     
236                     it=srcFiles.iterator();
237                     while (it.hasNext()) {
238                         review((File JavaDoc) it.next(), engine, classLoader, logger);
239                     }
240                     
241                     collector.getEngine().deleteOld();
242                     
243                     Collection JavaDoc packageResults=new ArrayList JavaDoc();
244                     Iterator JavaDoc pit=collector.getEngine().getPackageTotal().iterator();
245                     while (pit.hasNext()) {
246                         CompositeResults packageResult = new QuickPackageResults((PackageTotal) pit.next(), collector, inspectorSet);
247                         packageResult.commit();
248                         Iterator JavaDoc llit=listeners.iterator();
249                         while (llit.hasNext()) {
250                             ((Listener) llit.next()).onPackage(packageResult);
251                         }
252                         
253                         packageResults.add(packageResult);
254                     }
255                                                     
256                     log("Building summary");
257                     
258                     CompositeResults summary = new QuickSummary(title, collector, inspectorSet, packageResults);
259                     ResultsFactory.pushThreadResults(summary);
260                     
261                     // Stopping violation filters
262
vfit=violationFilters.iterator();
263                     while (vfit.hasNext()) {
264                         Object JavaDoc vf=vfit.next();
265                         if (vf instanceof Component) {
266                             ((Component) vf).stop();
267                         }
268                     }
269                     
270                     Iterator JavaDoc slit=listeners.iterator();
271                     while (slit.hasNext()) {
272                         ((Listener) slit.next()).onSummary(summary, inspectorSet);
273                     }
274                     
275                     Iterator JavaDoc rit=getReviewAcceptorEntries().iterator();
276                     while (rit.hasNext()) {
277                         ((ReviewAcceptor) ((ReviewAcceptorEntry) rit.next()).getObject(null)).accept(summary);
278                     }
279                     
280                     long finish=System.currentTimeMillis();
281                     
282                     long elapsedSec = (finish-start)/1000;
283                     long min=elapsedSec/60;
284                     long sec=elapsedSec % 60;
285                     
286                     log("Time: "+min+" min. "+sec+" sec.");
287                     log(
288                             MessageFormat.format(
289                                     "Performance {0, number,###.000000}",
290                                     new Object JavaDoc[] {
291                                             new Double JavaDoc(
292                                                     (double) summary.getCodeBase() * 1000
293                                                     / (finish - start))}));
294                     
295                     
296                     Integer JavaDoc severityThreshold = getSeverityThreshold();
297                     if (severityThreshold!=null) {
298                         final int sth=getSeverityThreshold().intValue();
299                         new ReviewAcceptor() {
300                             public void accept(CompositeResults summary) throws HammurapiException {
301                                 Number JavaDoc severity=summary.getMaxSeverity();
302                                 if (severity!=null && severity.intValue()<=sth) {
303                                     throw new HammurapiException("Severity threshold ("+sth+") infringed");
304                                 }
305                             }
306                         }.accept(summary);
307                     }
308                     
309                     Double JavaDoc sigmaThreshold = getSigmaThreshold();
310                     if (sigmaThreshold!=null) {
311                         final double cth=sigmaThreshold.doubleValue();
312                         new ReviewAcceptor() {
313                             public void accept(CompositeResults summary) throws HammurapiException {
314                                 try {
315                                     if (Double.parseDouble(summary.getSigma())<cth) {
316                                         throw new HammurapiException("Sigma is below threshold ("+cth+")");
317                                     }
318                                 } catch (NumberFormatException JavaDoc e) {
319                                     throw new HammurapiException("Sigma is not valid");
320                                 }
321                             }
322                         }.accept(summary);
323                     }
324                     
325                     Integer JavaDoc dpmoThreshold = getDpmoThreshold();
326                     if (dpmoThreshold!=null) {
327                         final int cth=dpmoThreshold.intValue();
328                         new ReviewAcceptor() {
329                             public void accept(CompositeResults summary) throws HammurapiException {
330                                 try {
331                                     if (Integer.parseInt(summary.getDPMO())>cth) {
332                                         throw new HammurapiException("DPMO is above threshold ("+cth+")");
333                                     }
334                                 } catch (NumberFormatException JavaDoc e) {
335                                     throw new HammurapiException("DPMO is not valid");
336                                 }
337                             }
338                         }.accept(summary);
339                     }
340                     
341                     if (isFailOnWarnings() && !summary.getWarnings().isEmpty()) {
342                         throw new HammurapiNonConsumableException("There have been warnings during execution.");
343                     }
344                             
345                     summary.commit();
346                 } finally {
347                     session.shutdown();
348                     collector.shutdown();
349                 }
350             } finally {
351                 if (archiveTmpDir!=null) {
352                     deleteFile(archiveTmpDir);
353                 }
354             }
355                         
356             if (hadExceptions) {
357                 throw new BuildException("There have been exceptions during execution. Check log output.");
358             }
359         } catch (ClassNotFoundException JavaDoc e) {
360             throw new BuildException(e);
361         } catch (SQLException JavaDoc e) {
362             throw new BuildException(e);
363         } catch (JselException e) {
364             throw new BuildException(e);
365         } catch (HammurapiException e) {
366             throw new BuildException(e);
367         } catch (ConfigurationException e) {
368             throw new BuildException(e);
369         } catch (FileNotFoundException JavaDoc e) {
370             throw new BuildException(e);
371         } catch (IOException JavaDoc e) {
372             throw new BuildException(e);
373         }
374     }
375     
376     /**
377      * @param file
378      * @param engine
379      * @param classLoader
380      * @param logger
381      * @throws JselException
382      * @throws FileNotFoundException
383      * @throws SQLException
384      */

385     private void review(File JavaDoc file, QuickReviewEngine engine, ClassLoader JavaDoc classLoader, Logger logger) throws JselException, FileNotFoundException JavaDoc, SQLException JavaDoc, IOException JavaDoc {
386         if (file.isFile()) {
387             _review(file, engine, classLoader, logger);
388         } else if (file.isDirectory()) {
389             File JavaDoc[] files=file.listFiles();
390             for (int i=0; i<files.length; i++) {
391                 review(files[i], engine, classLoader, logger);
392             }
393         }
394     }
395
396     /**
397      * @param file
398      * @param engine
399      * @param classLoader
400      * @param logger
401      * @throws JselException
402      * @throws FileNotFoundException
403      * @throws SQLException
404      */

405     private void _review(File JavaDoc file, QuickReviewEngine engine, ClassLoader JavaDoc classLoader, Logger logger) throws JselException, FileNotFoundException JavaDoc, SQLException JavaDoc, IOException JavaDoc {
406         InputStream JavaDoc is=new FileInputStream JavaDoc(file);
407         Reader JavaDoc reader= getEncoding()==null ? new InputStreamReader JavaDoc(is) : new InputStreamReader JavaDoc(is, getEncoding());
408         try {
409             engine.review(new CompilationUnitImpl(reader, getEncoding(), null, file.getAbsolutePath(), tabSize, classLoader, logger));
410         } finally {
411             reader.close();
412             is.close();
413         }
414     }
415     
416     /**
417      * Use it for inspector debugging
418      * @param args
419      */

420     public static void main(String JavaDoc[] args) {
421         System.out.println("Hammurapi 3 Copyright (C) 2004 Hammurapi Group");
422         
423         Options options=new Options();
424         
425         populateOptions(options);
426         
427         CommandLineParser parser=new PosixParser();
428         CommandLine line=null;
429         try {
430             line=parser.parse(options, args);
431         } catch (org.apache.commons.cli.ParseException e) {
432             System.err.println(e.getMessage());
433             System.err.flush();
434             printHelpAndExit(options);
435         }
436         
437         if (line.hasOption("h")) {
438             printHelpAndExit(options);
439         }
440     
441         QuickHammurapiTask task=new QuickHammurapiTask();
442         Project project = new Project();
443         task.setProject(project);
444         project.setCoreLoader(task.getClass().getClassLoader());
445         
446         task.configure(options, line);
447                 
448         task.suppressLogo=true;
449         
450         task.setTaskName("quickurapi");
451         
452         try {
453             task.execute();
454             System.exit(0);
455         } catch (Exception JavaDoc e) {
456             e.printStackTrace();
457             System.exit(2);
458         }
459     }
460     
461     protected static void loadEmbeddedInspectors(InspectorSet inspectorSet) throws BuildException, HammurapiException {
462         TaskBase.loadEmbeddedInspectors(inspectorSet);
463         
464         ClassResourceLoader crl=new ClassResourceLoader(QuickHammurapiTask.class);
465         InputStream JavaDoc inspectorStream=crl.getResourceAsStream(null, null, "xml");
466         if (inspectorStream==null) {
467             throw new BuildException("Cannot load quick embedded inspectors");
468         }
469         
470         DomInspectorSource source=new DomInspectorSource(inspectorStream, "Hammurapi.jar");
471         source.loadInspectors(inspectorSet);
472     }
473 }
474
Popular Tags