HammurapiTask.java


Package: org.hammurapi

Results
Date2007/07/27
Codebase8165
Reviews15526
DPMO617
Sigma4.731

Metrics
NameNumberMinAvgMaxTotal
Class complexity26.0040.5075.0081.00
Code length261.0021.30268.00554.00
File length1820.00820.00820.00820.00
Operation complexity261.003.5337.0092.00
Work order12.212.212.212.21

Violations
#LineColumnNameSeverityDescription
1231ER-0233Packages should begin with []
212482ER-0363Line is too long
313582ER-0363Line is too long
4147126ER-0363Line is too long
521794ER-0363Line is too long
6227131ER-0363Line is too long
722888ER-0363Line is too long
822983ER-0363Line is too long
923191ER-0363Line is too long
1023286ER-0363Line is too long
1123390ER-0363Line is too long
1223988ER-0363Line is too long
1324891ER-0363Line is too long
1425091ER-0363Line is too long
1525183ER-0363Line is too long
1625380ER-0363Line is too long
17254117ER-0363Line is too long
18255127ER-0363Line is too long
1926092ER-0363Line is too long
2026786ER-0363Line is too long
2127086ER-0363Line is too long
2227691ER-0363Line is too long
2328792ER-0363Line is too long
24288101ER-0363Line is too long
2529981ER-0363Line is too long
2630189ER-0363Line is too long
2730297ER-0363Line is too long
28316106ER-0363Line is too long
2931999ER-0363Line is too long
3032596ER-0363Line is too long
3133192ER-0363Line is too long
32335104ER-0363Line is too long
3333781ER-0363Line is too long
3434182ER-0363Line is too long
3534287ER-0363Line is too long
3634392ER-0363Line is too long
37344130ER-0363Line is too long
38345121ER-0363Line is too long
3934889ER-0363Line is too long
4035591ER-0363Line is too long
4135887ER-0363Line is too long
42359111ER-0363Line is too long
4336381ER-0363Line is too long
4437495ER-0363Line is too long
4538082ER-0363Line is too long
46381132ER-0363Line is too long
4738783ER-0363Line is too long
48390127ER-0363Line is too long
4939195ER-0363Line is too long
5039288ER-0363Line is too long
5139496ER-0363Line is too long
5239984ER-0363Line is too long
53400150ER-0363Line is too long
5441394ER-0363Line is too long
55417125ER-0363Line is too long
56422106ER-0363Line is too long
5742999ER-0363Line is too long
5843796ER-0363Line is too long
5944925ER-0363Line is too long
60452123ER-0363Line is too long
61487154ER-0363Line is too long
62490106ER-0363Line is too long
6349185ER-0363Line is too long
64493162ER-0363Line is too long
6549680ER-0363Line is too long
66503116ER-0363Line is too long
6750495ER-0363Line is too long
68506201ER-0363Line is too long
69507199ER-0363Line is too long
7050881ER-0363Line is too long
71509122ER-0363Line is too long
7251287ER-0363Line is too long
7351680ER-0363Line is too long
74517130ER-0363Line is too long
7551880ER-0363Line is too long
76521147ER-0363Line is too long
77625129ER-0363Line is too long
78813128ER-0363Line is too long
791161ER-0492Unify logging strategy - define individual logger for class
801239ER-0492Unify logging strategy - define individual logger for class
811239ER-0761Make inner classes "private"
8213517ER-1053Document all Interfaces and public methods. Use a Class header. Provide Javadoc
831479ER-0053Classes, interfaces, methods, and variables should be named according to Sun's naming conventions.
8416232ER-0823Avoid using method parameter names that conflict with class member names
8517443ER-0823Avoid using method parameter names that conflict with class member names
8618339ER-0823Avoid using method parameter names that conflict with class member names
8719833ER-0823Avoid using method parameter names that conflict with class member names
882049ER-0111Cyclomatic complexity (37) exceeds 12
892049ER-0412Method is too long
9020438ER-0472Operation (method or constructor) declares subclasses of RuntimeException in throws clause
912049ER-1053Document all Interfaces and public methods. Use a Class header. Provide Javadoc
9220829ER-0303Avoid hardwired string literals
9321625ER-1042Use a Collection instead of arrays Object[]
9421833ER-1053Document all Interfaces and public methods. Use a Class header. Provide Javadoc
95227116ER-0823Avoid using method parameter names that conflict with class member names
9622749ER-1053Document all Interfaces and public methods. Use a Class header. Provide Javadoc
9723937ER-0303Avoid hardwired string literals
9824329ER-0303Avoid hardwired string literals
9925473ER-0303Avoid hardwired string literals
10025573ER-0303Avoid hardwired string literals
10125673ER-0303Avoid hardwired string literals
10226029ER-0303Avoid hardwired string literals
10326229ER-0303Avoid hardwired string literals
10427029ER-0303Avoid hardwired string literals
10527229ER-0303Avoid hardwired string literals
10628041ER-2141java.util.List is different from java.lang.Object
10728138ER-2141org.hammurapi.ReviewToLogListener is different from java.lang.Object
10828329ER-0303Avoid hardwired string literals
10928737ER-0303Avoid hardwired string literals
11032533ER-1053Document all Interfaces and public methods. Use a Class header. Provide Javadoc
11132749ER-1053Document all Interfaces and public methods. Use a Class header. Provide Javadoc
11233149ER-1053Document all Interfaces and public methods. Use a Class header. Provide Javadoc
11333749ER-1053Document all Interfaces and public methods. Use a Class header. Provide Javadoc
11434149ER-1053Document all Interfaces and public methods. Use a Class header. Provide Javadoc
11537527ER-1032Catch-blocks should log the exeption with Log4J.error("Context String" , exception )
11637637ER-0303Avoid hardwired string literals
11738044ER-0303Avoid hardwired string literals
11838144ER-0303Avoid hardwired string literals
119381112ER-0303Avoid hardwired string literals
12038244ER-0303Avoid hardwired string literals
12139729ER-0303Avoid hardwired string literals
12240097ER-1163Use StringBuffer for excessive String concatenation
12340090ER-1163Use StringBuffer for excessive String concatenation
12440037ER-0303Avoid hardwired string literals
12540091ER-0303Avoid hardwired string literals
12642529ER-0303Avoid hardwired string literals
12742744ER-2141org.hammurapi.HammurapiTask$ViolationFilterVisitor is different from org.hammurapi.ResultsCollector
12845258ER-0303Avoid hardwired string literals
12945419ER-1032Catch-blocks should log the exeption with Log4J.error("Context String" , exception )
13045619ER-1032Catch-blocks should log the exeption with Log4J.error("Context String" , exception )
13145819ER-1032Catch-blocks should log the exeption with Log4J.error("Context String" , exception )
13246019ER-1032Catch-blocks should log the exeption with Log4J.error("Context String" , exception )
13346219ER-1032Catch-blocks should log the exeption with Log4J.error("Context String" , exception )
13446419ER-1032Catch-blocks should log the exeption with Log4J.error("Context String" , exception )
13546619ER-1032Catch-blocks should log the exeption with Log4J.error("Context String" , exception )
13646819ER-1032Catch-blocks should log the exeption with Log4J.error("Context String" , exception )
13749753ER-0303Avoid hardwired string literals
13849761ER-0303Avoid hardwired string literals
13950349ER-1053Document all Interfaces and public methods. Use a Class header. Provide Javadoc
14050859ER-1032Catch-blocks should log the exeption with Log4J.error("Context String" , exception )
14150990ER-0303Avoid hardwired string literals
14252150ER-0303Avoid hardwired string literals
14353031ER-0823Avoid using method parameter names that conflict with class member names
14454627ER-1111LOG4J is mandatory for all logging in ERC. System.out.println will be lost in a system console of our web/app server.
14554628ER-0303Avoid hardwired string literals
14655611ER-1032Catch-blocks should log the exeption with Log4J.error("Context String" , exception )
14756228ER-0303Avoid hardwired string literals
14857534ER-0303Avoid hardwired string literals
14958019ER-1032Catch-blocks should log the exeption with Log4J.error("Context String" , exception )
15058237ER-0293Avoid hardwired numeric literals
15159528ER-0283Avoid hardwired character literals
15259928ER-0283Avoid hardwired character literals
15360328ER-0283Avoid hardwired character literals
15460458ER-0283Avoid hardwired character literals
15561136ER-0283Avoid hardwired character literals
15661255ER-0283Avoid hardwired character literals
15761536ER-0283Avoid hardwired character literals
15861763ER-0283Avoid hardwired character literals
15961855ER-0283Avoid hardwired character literals
16061956ER-0283Avoid hardwired character literals
16162060ER-0283Avoid hardwired character literals
16262436ER-0283Avoid hardwired character literals
16362571ER-0283Avoid hardwired character literals
16462597ER-0283Avoid hardwired character literals
165625123ER-0283Avoid hardwired character literals
16662828ER-0283Avoid hardwired character literals
16766922ER-0303Avoid hardwired string literals
16867126ER-0303Avoid hardwired string literals
16967317ER-0303Avoid hardwired string literals
17068826ER-0303Avoid hardwired string literals
17168930ER-0303Avoid hardwired string literals
17269217ER-0303Avoid hardwired string literals
17369726ER-0303Avoid hardwired string literals
17469830ER-0303Avoid hardwired string literals
17570117ER-0303Avoid hardwired string literals
17670626ER-0303Avoid hardwired string literals
17770730ER-0303Avoid hardwired string literals
17871017ER-0303Avoid hardwired string literals
17971526ER-0303Avoid hardwired string literals
18071630ER-0303Avoid hardwired string literals
18171917ER-0303Avoid hardwired string literals
18272426ER-0303Avoid hardwired string literals
18372530ER-0303Avoid hardwired string literals
18472817ER-0303Avoid hardwired string literals
18573326ER-0303Avoid hardwired string literals
18673430ER-0303Avoid hardwired string literals
18773717ER-0303Avoid hardwired string literals
18874226ER-0303Avoid hardwired string literals
18974417ER-0303Avoid hardwired string literals
19074926ER-0303Avoid hardwired string literals
19175117ER-0303Avoid hardwired string literals
19275626ER-0303Avoid hardwired string literals
19375817ER-0303Avoid hardwired string literals
19477046ER-0823Avoid using method parameter names that conflict with class member names
19577936ER-0823Avoid using method parameter names that conflict with class member names
19678831ER-0823Avoid using method parameter names that conflict with class member names
19779835ER-0823Avoid using method parameter names that conflict with class member names
19880841ER-0303Avoid hardwired string literals
19980955ER-0303Avoid hardwired string literals
20081141ER-0303Avoid hardwired string literals
201813115ER-0303Avoid hardwired string literals
20281419ER-1032Catch-blocks should log the exeption with Log4J.error("Context String" , exception )
20381546ER-0303Avoid hardwired string literals

JavaDoc
HammurapiTask
HammurapiTask.ViolationFilterVisitor

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 */

23package org.hammurapi;
24
25import java.io.File;
26import java.io.FileNotFoundException;
27import java.io.IOException;
28import java.io.InputStreamReader;
29import java.net.InetAddress;
30import java.sql.SQLException;
31import java.text.SimpleDateFormat;
32import java.util.Collection;
33import java.util.Date;
34import java.util.Iterator;
35import java.util.LinkedList;
36import java.util.List;
37
38import org.apache.commons.cli.CommandLine;
39import org.apache.commons.cli.CommandLineParser;
40import org.apache.commons.cli.Option;
41import org.apache.commons.cli.OptionBuilder;
42import org.apache.commons.cli.Options;
43import org.apache.commons.cli.ParseException;
44import org.apache.commons.cli.PosixParser;
45import org.apache.tools.ant.AntClassLoader;
46import org.apache.tools.ant.BuildException;
47import org.apache.tools.ant.DirectoryScanner;
48import org.apache.tools.ant.Project;
49import org.hammurapi.results.CompositeResults;
50import org.hammurapi.results.persistent.jdbc.ResultsFactory;
51import org.hammurapi.results.persistent.jdbc.ResultsFactoryConfig;
52import org.w3c.dom.Element;
53
54import com.pavelvlasov.ant.ConnectionEntry;
55import com.pavelvlasov.config.Component;
56import com.pavelvlasov.config.ConfigurationException;
57import com.pavelvlasov.jsel.JselException;
58import com.pavelvlasov.jsel.Repository;
59import com.pavelvlasov.jsel.RevisionMapper;
60import com.pavelvlasov.jsel.impl.DbRepositoryImpl;
61import com.pavelvlasov.jsel.impl.RepositoryConfig;
62import com.pavelvlasov.jsel.impl.WarningSink;
63import com.pavelvlasov.logging.AntLogger;
64import com.pavelvlasov.logging.Logger;
65import com.pavelvlasov.metrics.MeasurementCategoryFactory;
66import com.pavelvlasov.metrics.TimeIntervalCategory;
67import com.pavelvlasov.persistence.CompositeStorage;
68import com.pavelvlasov.persistence.FileStorage;
69import com.pavelvlasov.persistence.MemoryStorage;
70import com.pavelvlasov.render.RenderingException;
71import com.pavelvlasov.review.SimpleSourceMarker;
72import com.pavelvlasov.review.SourceMarker;
73import com.pavelvlasov.review.SourceMarkerComparator;
74import com.pavelvlasov.sql.ConnectionPerThreadDataSource;
75import com.pavelvlasov.sql.DataAccessObject;
76import com.pavelvlasov.sql.JdbcStorage;
77import com.pavelvlasov.sql.SQLProcessor;
78import com.pavelvlasov.sql.Transaction;
79import com.pavelvlasov.sql.hypersonic.HypersonicServerDataSource;
80import com.pavelvlasov.sql.hypersonic.HypersonicStandaloneDataSource;
81import com.pavelvlasov.sql.hypersonic.HypersonicTmpDataSource;
82import com.pavelvlasov.util.VisitorStack;
83import com.pavelvlasov.util.VisitorStackSource;
84
85/**
86 * Performs automatic code reviews.
87 * <section name="Example" suppress-description="yes">
88If you copy content of Hammurapi lib directory to ant lib directory then you can
89invoke Hammurapi in the following way:
90 <pre>
91&lt;taskdef name="hammurapi" classname="org.hammurapi.HammurapiTask" /&gt;<br/>
92<br/>
93&lt;hammurapi&gt;<br/>
94 <tab/>&lt;src dir="src"/&gt;<br/>
95 <tab/>&lt;output dir="review"/&gt;<br/>
96&lt;/hammurapi&gt;</pre>
97or, if you didn't copy jar files to Ant lib directory, use this syntax:
98<pre>
99&lt;taskdef name="hammurapi" classname="org.hammurapi.HammurapiTask"&gt;<br/>
100 <tab/>&lt;classpath&gt;<br/>
101 <tab/><tab/>&lt;fileset dir="${hammurapi.home}/lib" includes="*.jar"/&gt;<br/>
102 <tab/>&lt;/classpath&gt;<br/>
103&lt;/taskdef&gt;<br/>
104<br/>
105&lt;hammurapi&gt;<br/>
106 <tab/>&lt;src dir="src"/&gt;<br/>
107 <tab/>&lt;output dir="review"/&gt;<br/>
108&lt;/hammurapi&gt;
109</pre>
110
111</section>
112 * @ant.element name="hammurapi" display-name="Automatic code review task"
113 * @author Pavel Vlasov
114 * @version $Revision: 1.25 $
115 */

116public class HammurapiTask extends TaskBase {
117
118 /**
119 * Helper class to start/stop violation filters
120 * @author Pavel Vlasov
121 * @revision $Revision: 1.25 $
122 */

123 public class ViolationFilterVisitor {
124 public void visit(Repository repo) throws ConfigurationException {
125 // Initializing violation filters
126
Iterator vfit=violationFilters.iterator();
127 while (vfit.hasNext()) {
128 Object vf=vfit.next();
129 if (vf instanceof Component) {
130 ((Component) vf).start();
131 }
132 }
133 }
134
135 public void leave(Repository repo) throws ConfigurationException {
136 // Stopping violation filters
137
Iterator vfit=violationFilters.iterator();
138 while (vfit.hasNext()) {
139 Object vf=vfit.next();
140 if (vf instanceof Component) {
141 ((Component) vf).stop();
142 }
143 }
144 }
145 }
146
147 private static final TimeIntervalCategory tic=MeasurementCategoryFactory.getTimeIntervalCategory(HammurapiTask.class);
148
149 private boolean wrap=false;
150
151 private boolean cleanup=true;
152 boolean skipIntactPackages=false;
153
154 private boolean forceOnWaivers;
155
156 /**
157 * Cleanup old reviews info after review.
158 * Defaults to 'true'.
159 * @ant.non-required
160 * @param cleanup
161 */

162 public void setCleanup(boolean cleanup) {
163 this.cleanup = cleanup;
164 }
165
166 /**
167 * Do not generate summary pages for packages and summary
168 * if no files were changed in package/summary.
169 * Set it to 'true' to improve performance if you don not use
170 * 'New' marker on modified files.
171 * @ant.non-required
172 * @param skipIntactPackages
173 */

174 public void setSkipIntactPackages(boolean skipIntactPackages) {
175 this.skipIntactPackages = skipIntactPackages;
176 }
177
178 /**
179 * Force review of compilation units for which waivers are available.
180 * Default is true.
181 * @ant.non-required.
182 */

183 public void setForceOnWaivers(boolean forceOnWaivers) {
184 this.forceOnWaivers=forceOnWaivers;
185 }
186
187 boolean isForceOnWaivers() {
188 return forceOnWaivers;
189 }
190
191 private Date baseLine;
192
193 /**
194 * Date of baseline report
195 * @ant.non-required
196 * @param baseLine
197 */

198 public void setBaseLine(Date baseLine) {
199 this.baseLine=baseLine;
200 }
201
202 private String hostId;
203
204 public void execute() throws BuildException {
205 long started=System.currentTimeMillis();
206
207 if (!suppressLogo) {
208 log("Hammurapi 3 Copyright (C) 2004 Hammurapi Group");
209 }
210
211 File archiveTmpDir=processArchive();
212
213 try {
214 Logger logger=new AntLogger(this);
215
216 final VisitorStack[] visitorStack={null};
217 final VisitorStackSource visitorStackSource=new VisitorStackSource() {
218 public VisitorStack getVisitorStack() {
219 return visitorStack[0];
220 }
221 };
222
223 final SessionImpl reviewSession=new SessionImpl();
224
225 InspectorSet inspectorSet=new InspectorSet(
226 new InspectorContextFactory() {
227 public InspectorContext newContext(InspectorDescriptor descriptor, Logger logger) {
228 return new InspectorContextImpl(
229 descriptor,
230 logger,
231 visitorStackSource,
232 reviewSession,
233 violationFilters);
234 }
235 },
236 logger);
237
238 if (embeddedInspectors) {
239 log("Loading embedded inspectors", Project.MSG_VERBOSE);
240 loadEmbeddedInspectors(inspectorSet);
241 }
242
243 log("Loading inspectors", Project.MSG_VERBOSE);
244 Iterator it=inspectors.iterator();
245 while (it.hasNext()) {
246 Object o=it.next();
247 if (o instanceof InspectorSource) {
248 ((InspectorSource) o).loadInspectors(inspectorSet);
249 } else {
250 InspectorEntry inspectorEntry = (InspectorEntry) o;
251 inspectorSet.addDescriptor(inspectorEntry);
252 inspectorSet.addInspectorSourceInfo(
253 new InspectorSourceInfo(
254 "Inline inspector "+inspectorEntry.getName(),
255 "Build file: "+inspectorEntry.getLocation().toString(),
256 ""));
257 }
258 }
259
260 log("Inspectors loaded: "+inspectorSet.size(), Project.MSG_VERBOSE);
261
262 log("Loading waivers", Project.MSG_VERBOSE);
263 Date now=new Date();
264 WaiverSet waiverSet=new WaiverSet();
265 it=waivers.iterator();
266 while (it.hasNext()) {
267 ((WaiverSource) it.next()).loadWaivers(waiverSet,now);
268 }
269
270 log("Waivers loaded: "+waiverSet.size(), Project.MSG_VERBOSE);
271
272 log("Loading listeners", Project.MSG_VERBOSE);
273 List listeners=new LinkedList();
274 it=listenerEntries.iterator();
275 while (it.hasNext()) {
276 listeners.add(((ListenerEntry) it.next()).getObject(null));
277 }
278
279 //Outputs
280
listeners.addAll(outputs);
281 listeners.add(new ReviewToLogListener(project));
282
283 log("Loading source files", Project.MSG_VERBOSE);
284
285 RepositoryConfig config=new RepositoryConfig();
286 if (classPath!=null) {
287 log("Loading class files to repository", Project.MSG_DEBUG);
288 config.setClassLoader(new AntClassLoader(project, classPath, false));
289 reviewSession.setClassPath(classPath.list());
290 }
291
292 config.setLogger(logger);
293 config.setCalculateDependencies(calculateDependencies);
294 config.setStoreSource(storeSource);
295 config.setEncoding(getEncoding());
296
297 it=srcFileSets.iterator();
298 while (it.hasNext()) {
299 HammurapiFileSet fs=(HammurapiFileSet) it.next();
300 fs.setDefaultIncludes();
301 DirectoryScanner scanner=fs.getDirectoryScanner(project);
302 config.addFile(scanner.getBasedir(), scanner.getIncludedFiles());
303 }
304
305 /**
306 * For command-line interface
307 */

308 it=srcFiles.iterator();
309 while (it.hasNext()) {
310 config.addFile((File) it.next());
311 }
312
313 config.setName(title);
314
315 if (revisionMapper!=null) {
316 config.setRevisionMapper((RevisionMapper) revisionMapper.getObject(null));
317 }
318
319 ConnectionPerThreadDataSource dataSource = createDataSource(reviewSession);
320
321 reviewSession.setDatasource(dataSource);
322
323 final LinkedList repoWarnings=new LinkedList();
324 config.setWarningSink(new WarningSink() {
325 public void consume(final String source, final String message) {
326 repoWarnings.add(new Violation() {
327 public String getMessage() {
328 return message;
329 }
330
331 public InspectorDescriptor getDescriptor() {
332 return null;
333 }
334
335 SourceMarker sm=new SimpleSourceMarker(0,0,source,null);
336
337 public SourceMarker getSource() {
338 return sm;
339 }
340
341 public int compareTo(Object obj) {
342 if (obj instanceof Violation) {
343 Violation v=(Violation) obj;
344 int c=SourceMarkerComparator._compare(getSource(), v.getSource());
345 return c==0 ? getMessage().compareTo(v.getMessage()) : c;
346 }
347
348 return hashCode()-obj.hashCode();
349 }
350 });
351 }
352 });
353
354 config.setDataSource(dataSource);
355 final SQLProcessor sqlProcessor=new SQLProcessor(dataSource, null);
356 sqlProcessor.setTimeIntervalCategory(tic);
357
358 DbRepositoryImpl repositoryImpl = new DbRepositoryImpl(config);
359 Repository repository = wrap ? (Repository) repositoryImpl.getProxy() : repositoryImpl;
360
361 //new SimpleResultsFactory(waiverSet).install();
362

363 ResultsFactoryConfig rfConfig=new ResultsFactoryConfig();
364 rfConfig.setInspectorSet(inspectorSet);
365 rfConfig.setName(title);
366 rfConfig.setReportNumber(repository.getScanNumber());
367 rfConfig.setRepository(repository);
368 rfConfig.setSqlProcessor(sqlProcessor);
369 rfConfig.setHostId(hostId);
370 rfConfig.setBaseLine(baseLine);
371 rfConfig.setDescription(reviewDescription);
372
373 try {
374 rfConfig.setHostName(InetAddress.getLocalHost().getHostName());
375 } catch (Exception e) {
376 log("Cannot resolve host name: "+e);
377 }
378
379 CompositeStorage storage=new CompositeStorage();
380 storage.addStorage("jdbc", new JdbcStorage(sqlProcessor));
381 storage.addStorage("file", new FileStorage(new File(System.getProperties().getProperty("java.io.tmpdir"))));
382 storage.addStorage("memory", new MemoryStorage());
383
384 rfConfig.setStorage(storage);
385 rfConfig.setWaiverSet(waiverSet);
386
387 ResultsFactory resultsFactory=new ResultsFactory(rfConfig);
388 resultsFactory.install();
389
390 CompositeResults summary=org.hammurapi.results.ResultsFactory.getInstance().newCompositeResults(title);
391 org.hammurapi.results.ResultsFactory.getInstance().setSummary(summary);
392 org.hammurapi.results.ResultsFactory.pushThreadResults(summary);
393
394 Collection inspectorsPerSe=new LinkedList(inspectorSet.getInspectors());
395 reviewSession.setInspectors(inspectorSet);
396 Iterator inspectorsIt=inspectorsPerSe.iterator();
397 log("Inspectors mapping", Project.MSG_VERBOSE);
398 while (inspectorsIt.hasNext()) {
399 Inspector inspector=(Inspector) inspectorsIt.next();
400 log("\t"+inspector.getContext().getDescriptor().getName()+" -> "+inspector.getClass().getName(), Project.MSG_VERBOSE);
401 }
402
403 // Initializes listeners
404
it=listeners.iterator();
405 while (it.hasNext()) {
406 ((Listener) it.next()).onBegin(inspectorSet);
407 }
408
409 Iterator vfit=violationFilters.iterator();
410 while (vfit.hasNext()) {
411 Object vf=vfit.next();
412 if (vf instanceof DataAccessObject) {
413 ((DataAccessObject) vf).setSQLProcessor(sqlProcessor);
414 }
415 }
416
417 ResultsCollector collector = new ResultsCollector(this, inspectorSet, waiverSet, summary, listeners);
418 inspectorsPerSe.add(collector);
419
420 // Storing repo warnings
421
while (!repoWarnings.isEmpty()) {
422 collector.getSummary().addWarning((Violation) repoWarnings.removeFirst());
423 }
424
425 log("Reviewing", Project.MSG_VERBOSE);
426
427 inspectorsPerSe.add(new ViolationFilterVisitor());
428
429 SimpleReviewEngine rengine = new SimpleReviewEngine(inspectorsPerSe, this);
430 reviewSession.setVisitor(rengine.getVisitor());
431 visitorStack[0]=rengine.getVisitorStack();
432
433 rengine.review(repository);
434
435 writeWaiverStubs(waiverSet.getRejectedRequests());
436
437 ResultsFactory.getInstance().commit(System.currentTimeMillis()-started);
438
439 if (cleanup) {
440 repositoryImpl.cleanupOldScans();
441 resultsFactory.cleanupOldReports();
442 }
443
444 repositoryImpl.stop();
445 reviewSession.shutdown();
446 resultsFactory.shutdown();
447 dataSource.shutdown();
448
449 //log("SQL metrics:\n"+resultsFactory.getSQLMetrics(),Project.MSG_VERBOSE);
450

451 if (hadExceptions) {
452 throw new BuildException("There have been exceptions during execution. Check log output.");
453 }
454 } catch (JselException e) {
455 throw new BuildException(e);
456 } catch (HammurapiException e) {
457 throw new BuildException(e);
458 } catch (ConfigurationException e) {
459 throw new BuildException(e);
460 } catch (FileNotFoundException e) {
461 throw new BuildException(e);
462 } catch (ClassNotFoundException e) {
463 throw new BuildException(e);
464 } catch (IOException e) {
465 throw new BuildException(e);
466 } catch (SQLException e) {
467 throw new BuildException(e);
468 } catch (RenderingException e) {
469 throw new BuildException(e);
470 } finally {
471 if (archiveTmpDir!=null) {
472 deleteFile(archiveTmpDir);
473 }
474 }
475 }
476
477 /**
478 * @param reviewSession
479 * @param hammurapiNameMap
480 * @param dataSource
481 * @param hammurapiNameMap
482 * @return
483 * @throws ClassNotFoundException
484 * @throws IOException
485 * @throws SQLException
486 */

487 private ConnectionPerThreadDataSource createDataSource(final SessionImpl reviewSession) throws ClassNotFoundException, IOException, SQLException {
488 ConnectionPerThreadDataSource dataSource;
489 if (database==null && server==null && connection==null) {
490 dataSource = new HypersonicTmpDataSource(DbRepositoryImpl.HYPERSONIC_INIT_SCRIPT);
491 SQLProcessor sqlProcessor=new SQLProcessor(dataSource, null);
492 sqlProcessor.setTimeIntervalCategory(tic);
493 sqlProcessor.executeScript(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(ResultsFactory.HYPERSONIC_INIT_SCRIPT)));
494
495 reviewSession.scheduleInitDb();
496 } else if (database!=null && server==null && connection==null) {
497 reviewSession.setDbProperty("type", "Hypersonic");
498
499 dataSource = new HypersonicStandaloneDataSource(
500 database.getAbsolutePath(),
501 new Transaction() {
502
503 public boolean execute(SQLProcessor processor) throws SQLException {
504 processor.setTimeIntervalCategory(tic);
505 try {
506 processor.executeScript(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(DbRepositoryImpl.HYPERSONIC_INIT_SCRIPT)));
507 processor.executeScript(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(ResultsFactory.HYPERSONIC_INIT_SCRIPT)));
508 } catch (IOException e) {
509 throw new BuildException("Cannot initialize database", e);
510 }
511
512 reviewSession.scheduleInitDb();
513 return true;
514 }
515 });
516 } else if (database==null && server!=null && connection==null) {
517 dataSource=new HypersonicServerDataSource(server.getHost(), server.getUser(), server.getPassword(), null);
518 } else if (database==null && server==null && connection!=null) {
519 dataSource=connection.getDataSource();
520 } else {
521 throw new BuildException("server nested element, connection nested element and database attribute are mutually exclusive");
522 }
523 return dataSource;
524 }
525
526 /**
527 * Host id to differentiate reports created on different machines.
528 * @ant.non-required
529 */

530 public void setHostId(String hostId) {
531 this.hostId=hostId;
532 }
533
534 private ServerEntry server;
535
536 private ConnectionEntry connection;
537
538 private boolean calculateDependencies;
539 private boolean storeSource;
540
541 /**
542 * Use it for inspector debugging
543 * @param args
544 */

545 public static void main(String[] args) {
546 System.out.println("Hammurapi 3 Copyright (C) 2004 Hammurapi Group");
547
548 Options options=new Options();
549
550 populateOptions(options);
551
552 CommandLineParser parser=new PosixParser();
553 CommandLine line=null;
554 try {
555 line=parser.parse(options, args);
556 } catch (ParseException e) {
557 System.err.println(e.getMessage());
558 System.err.flush();
559 printHelpAndExit(options);
560 }
561
562 if (line.hasOption("h")) {
563 printHelpAndExit(options);
564 }
565
566 HammurapiTask task=new HammurapiTask();
567 Project project = new Project();
568 task.setProject(project);
569 project.setCoreLoader(task.getClass().getClassLoader());
570
571 task.configure(options, line);
572
573 task.suppressLogo=true;
574
575 task.setTaskName("hammurapi");
576
577 try {
578 task.execute();
579 System.exit(0);
580 } catch (Exception e) {
581 e.printStackTrace();
582 System.exit(2);
583 }
584 }
585
586 /**
587 * @param options
588 * @param line
589 * @param task
590 * @param project
591 */

592 protected void configure(Options options, CommandLine line) {
593 super.configure(options, line);
594
595 if (line.hasOption('z')) {
596 setCalculateDependencies(true);
597 }
598
599 if (line.hasOption('b')) {
600 setStoreSource(true);
601 }
602
603 if (line.hasOption('n')) {
604 setBaseLine(new Date(line.getOptionValue('n')));
605 }
606
607 //if (line.hasOption('B')) {
608
// setBaselining(line.getOptionValue('B'));
609
//}
610

611 if (line.hasOption('H')) {
612 setHostId(line.getOptionValue('H'));
613 }
614
615 if (line.hasOption('L')) {
616 ConnectionEntry ce=new ConnectionEntry();
617 ce.setDriverClass(line.getOptionValue('L'));
618 ce.setUrl(line.getOptionValue('N'));
619 ce.setUser(line.getOptionValue('j'));
620 ce.setPassword(line.getOptionValue('p'));
621 addConnection(ce);
622 }
623
624 if (line.hasOption('R')) {
625 addServer(new ServerEntry(line.getOptionValue('R'), line.getOptionValue('j'), line.getOptionValue('p')));
626 }
627
628 if (line.hasOption('F')) {
629 setForceOnWaivers(false);
630 }
631
632 //setWrap(line.hasOption('r'));
633
}
634
635 //Anu 20050701 : Method moved to TaskBase.java
636
// /**
637
// * Sets baselining mode. Possible values:
638
// * off (default) - no baselining, on - do not report
639
// * violations stored in the baseline table, set - all violations
640
// * from current scan are saved to the baseline table.
641
// * The idea is to filter out all violations in
642
// * preexisting code and report only new violations.
643
// * Not all violations can be filtered out, only thouse
644
// * with signatures. Significant code modifications can surface some
645
// * baselined violation.
646
// * @ant.non-required
647
// * @param baselineMode
648
// */
649
// public void setBaselining(String baselineMode) {
650
// if ("off".equals(baselineMode)) {
651
// // Nothing.
652
// } else if ("on".equals(baselineMode)) {
653
// violationFilters.add(new BaselineViolationFilter());
654
// } else if ("set".equalsIgnoreCase(baselineMode)) {
655
// violationFilters.add(new BaselineSetupViolationFilter());
656
// } else {
657
// throw new BuildException("Invalid baselining mode: "+baselineMode);
658
// }
659
//
660
// }
661

662 /**
663 * @param options
664 */

665 protected static void populateOptions(Options options) {
666 TaskBase.populateOptions(options);
667
668 Option hostIdOption=OptionBuilder
669 .withArgName("hostId")
670 .hasArg()
671 .withDescription("Host id")
672 .isRequired(false)
673 .create("H");
674
675 options.addOption(hostIdOption);
676
677//Anu 20050701 : Moved to TaskBase.java
678
// Option baseliningOption=OptionBuilder
679
// .withArgName("off|on|set")
680
// .hasArg()
681
// .withDescription("Baselining mode")
682
// .isRequired(false)
683
// .create("B");
684

685// options.addOption(baseliningOption);
686

687 Option serverOption=OptionBuilder
688 .withDescription("Database server name")
689 .withArgName("database server")
690 .hasArg()
691 .isRequired(false)
692 .create("R");
693
694 options.addOption(serverOption);
695
696 Option driverClassOption=OptionBuilder
697 .withDescription("Database driver class")
698 .withArgName("class name")
699 .hasArg()
700 .isRequired(false)
701 .create("L");
702
703 options.addOption(driverClassOption);
704
705 Option connectionUrlOption=OptionBuilder
706 .withDescription("Database connection URL")
707 .withArgName("url")
708 .hasArg()
709 .isRequired(false)
710 .create("N");
711
712 options.addOption(connectionUrlOption);
713
714 Option userOption=OptionBuilder
715 .withDescription("Database user")
716 .withArgName("user name")
717 .hasArg()
718 .isRequired(false)
719 .create("j");
720
721 options.addOption(userOption);
722
723 Option passwordOption=OptionBuilder
724 .withDescription("Database password")
725 .withArgName("password")
726 .hasArg()
727 .isRequired(false)
728 .create("p");
729
730 options.addOption(passwordOption);
731
732 Option baseLineOption=OptionBuilder
733 .withDescription("Baseline date")
734 .withArgName("date")
735 .hasArg()
736 .isRequired(false)
737 .create("n");
738
739 options.addOption(baseLineOption);
740
741 Option calculateDependenciesOption=OptionBuilder
742 .withDescription("Calculate dependencies")
743 .isRequired(false)
744 .create("z");
745
746 options.addOption(calculateDependenciesOption);
747
748 Option storeSourceOption=OptionBuilder
749 .withDescription("Store source")
750 .isRequired(false)
751 .create("b");
752
753 options.addOption(storeSourceOption);
754
755 Option forceOnWaiversOption=OptionBuilder
756 .withDescription("Do not force reviews on waivers")
757 .isRequired(false)
758 .create("F");
759
760 options.addOption(forceOnWaiversOption);
761
762 }
763
764 /**
765 * If set to 'true' Hammurapi stores dependency information to the
766 * database.
767 * @ant.non-required
768 * @param b
769 */

770 public void setCalculateDependencies(boolean calculateDependencies) {
771 this.calculateDependencies=calculateDependencies;
772 }
773
774 /**
775 * If set to 'true' Hammurapi stores source code to the database.
776 * @ant.non-required
777 * @param b
778 */

779 public void setStoreSource(boolean storeSource) {
780 this.storeSource=storeSource;
781 }
782
783 /**
784 * Database (Hypersonic) server to use as repository.
785 * @param entry
786 * @ant.non-required
787 */

788 public void addServer(ServerEntry server) {
789 this.server=server;
790 }
791
792 /**
793 * Defines database server to be used as repository.
794 * Mutually exclusive with server nested element and database attribute.
795 * @ant.non-required.
796 * @param connection
797 */

798 public void addConnection(ConnectionEntry connection) {
799 this.connection=connection;
800 }
801
802 /**
803 * @param config
804 * @throws ParseException
805 */

806 protected void setAttributes(Element config) {
807 super.setAttributes(config);
808 if (config.hasAttribute("host-id")) {
809 setHostId(config.getAttribute("host-id"));
810 }
811 if (config.hasAttribute("baseline")) {
812 try {
813 setBaseLine(new SimpleDateFormat(HammurapiArchiver.DATE_FORMAT).parse(config.getAttribute("baseline")));
814 } catch (java.text.ParseException e) {
815 throw new BuildException("Cannot parse baseline date", e);
816 }
817 }
818 }
819}
820
821

Hammurapi 3 Copyright © 2004 Hammurapi Group. All Rights Reserved.