KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hammurapi > Reviewer


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.FileReader JavaDoc;
27 import java.io.InputStream JavaDoc;
28 import java.io.Reader JavaDoc;
29 import java.lang.reflect.Method JavaDoc;
30 import java.net.URL JavaDoc;
31 import java.net.URLClassLoader JavaDoc;
32 import java.sql.SQLException JavaDoc;
33 import java.util.Collection JavaDoc;
34 import java.util.Date JavaDoc;
35 import java.util.HashSet JavaDoc;
36 import java.util.Iterator JavaDoc;
37 import java.util.Set JavaDoc;
38
39 import org.hammurapi.results.Annotation;
40
41 import com.pavelvlasov.config.ConfigurationException;
42 import com.pavelvlasov.jsel.CompilationUnit;
43 import com.pavelvlasov.jsel.JselException;
44 import com.pavelvlasov.jsel.impl.CompilationUnitImpl;
45 import com.pavelvlasov.logging.Logger;
46 import com.pavelvlasov.persistence.CompositeStorage;
47 import com.pavelvlasov.persistence.FileStorage;
48 import com.pavelvlasov.persistence.MemoryStorage;
49 import com.pavelvlasov.review.Signed;
50 import com.pavelvlasov.review.SourceMarker;
51 import com.pavelvlasov.util.ClassResourceLoader;
52 import com.pavelvlasov.util.DispatchingVisitor;
53 import com.pavelvlasov.util.VisitorExceptionSink;
54 import com.pavelvlasov.util.VisitorStack;
55 import com.pavelvlasov.util.VisitorStackSource;
56
57 /**
58  * This class is to be used by IDE plugins
59  * @author Pavel Vlasov
60  * @version $Revision: 1.8 $
61  */

62 public class Reviewer {
63
64     private Logger logger;
65     private InspectorSet inspectorSet;
66     private WaiverSet waiverSet=new WaiverSet();
67     private CompositeStorage storage=new CompositeStorage();
68     private DispatchingVisitor visitor;
69     private SessionImpl session=new SessionImpl();
70     private int tabSize=8;
71     
72     private class ReviewerInspectorContext extends InspectorContextBase {
73
74         public ReviewerInspectorContext(InspectorDescriptor descriptor, Logger logger, VisitorStackSource visitorStackSource) {
75             super(descriptor, logger, visitorStackSource, session);
76         }
77
78         /**
79          *
80          * @param source
81          * @param message
82          */

83         public void reportViolation(SourceMarker source, String JavaDoc message) {
84             Violation violation=new SimpleViolation(detach(source), message, descriptor);
85             addViolation(violation);
86         }
87
88         public void annotate(Annotation annotation) {
89             addAnnotation(annotation);
90         }
91
92         public void addMetric(SourceMarker source, String JavaDoc name, double value) {
93             // Ignore
94
}
95
96         /**
97          * Report warning
98          * @param source
99          * @param message
100          */

101         public void warn(SourceMarker source, String JavaDoc message) {
102             Violation violation=new SimpleViolation(detach(source), message, descriptor);
103             addWarning(violation);
104             if (source==null) {
105                 System.err.println("WARNING: "+message);
106             } else {
107                 System.err.println("WARNING at "+source.getSourceURL()+" "+source.getLine()+":"+source.getColumn()+" : "+message);
108             }
109         }
110
111         /**
112          * Report warning
113          * @param source
114          */

115         public void warn(SourceMarker source, Throwable JavaDoc th) {
116             Violation violation=new SimpleViolation(detach(source), th.toString(), descriptor);
117             addWarning(violation);
118             // TODO better warning handling here
119
if (source==null) {
120                 System.err.println("WARNING: "+th);
121             } else {
122                 System.err.println("WARNING at "+source.getSourceURL()+" "+source.getLine()+":"+source.getColumn()+" : "+th);
123             }
124             th.printStackTrace();
125         }
126
127         /**
128          * Creates a waiver for inspector with a given key
129          * @param inspectorKey
130          */

131         public void waive(Signed signed, final String JavaDoc inspectorKey) {
132             final String JavaDoc iName=descriptor.getWaivedInspectorName(inspectorKey);
133             if (iName==null) {
134                 warn(signed instanceof SourceMarker ? (SourceMarker) signed : null, descriptor.getName()+": Inspector with key '"+inspectorKey+"' not found.");
135             } else {
136                 final String JavaDoc signature=signed==null ? null : signed.getSignature();
137                 final Set JavaDoc signatures=new HashSet JavaDoc();
138                 if (signature!=null) {
139                     signatures.add(signature);
140                 }
141                 
142                 if (Reviewer.this.logger!=null) {
143                     Reviewer.this.logger.debug(this, "Inspector "+getDescriptor().getName()+" autowaives "+iName+" at "+signature);
144                 }
145                 
146                 Waiver waiver=new Waiver() {
147                     boolean active=true;
148         
149                     public String JavaDoc getInspectorName() {
150                         return iName;
151                     }
152         
153                     public boolean waive(Violation violation, boolean peek) {
154                         if (iName.equals(violation.getDescriptor().getName())) {
155                             if (signature==null) {
156                                 return true;
157                             } else if (violation.getSource() instanceof Signed && signature.equals(((Signed) violation.getSource()).getSignature())) {
158                                 if (!peek) {
159                                     active=false;
160                                 }
161                                 return true;
162                             }
163                         }
164                         return false;
165                     }
166                     
167                     public Date JavaDoc getExpirationDate() {
168                         return null;
169                     }
170         
171                     public String JavaDoc getReason() {
172                         return descriptor.getWaiveReason(inspectorKey);
173                     }
174         
175                     public boolean isActive() {
176                         return active;
177                     }
178         
179                     public Collection JavaDoc getSignatures() {
180                         return signatures;
181                     }
182                 };
183                 waiverSet.addWaiver(waiver, date);
184             }
185         }
186     }
187
188     public Reviewer(
189                 final Logger logger,
190                 boolean embeddedInspectors,
191                 Collection JavaDoc inspectors,
192                 Collection JavaDoc waivers) throws HammurapiException {
193         this.logger=logger;
194         final VisitorStack[] visitorStack={null};
195         
196         final VisitorStackSource delegatingVisitorStackSource = new VisitorStackSource() {
197
198             public VisitorStack getVisitorStack() {
199                 return visitorStack[0];
200             }
201         };
202         
203         inspectorSet=new InspectorSet(
204             new InspectorContextFactory() {
205                 public InspectorContext newContext(final InspectorDescriptor descriptor, final Logger logger) {
206                     return new ReviewerInspectorContext(descriptor, logger, delegatingVisitorStackSource);
207                 }
208             },
209             logger);
210         
211         if (embeddedInspectors) {
212             InputStream JavaDoc inspectorStream=HammurapiTask.class.getResourceAsStream("inspectors.xml");
213             if (inspectorStream==null) {
214                 throw new HammurapiException("Cannot load embedded inspectors");
215             }
216             
217             DomInspectorSource source=new DomInspectorSource(inspectorStream, "Hammurapi.jar");
218             source.loadInspectors(inspectorSet);
219         }
220         
221         if (inspectors!=null) {
222             Iterator JavaDoc it=inspectors.iterator();
223             while (it.hasNext()) {
224                 try {
225                     inspectorSet.addDescriptor((InspectorDescriptor) it.next());
226                 } catch (ConfigurationException e) {
227                     throw new HammurapiException(e);
228                 }
229             }
230         }
231
232         if (waivers!=null) {
233             Date JavaDoc now=new Date JavaDoc();
234             Iterator JavaDoc it=waivers.iterator();
235             while (it.hasNext()) {
236                 waiverSet.addWaiver((Waiver) it.next(), now);
237             }
238         }
239         
240         storage.addStorage("file", new FileStorage(new File JavaDoc(System.getProperties().getProperty("java.io.tmpdir"))));
241         storage.addStorage("memory", new MemoryStorage());
242         session.setStorage(storage);
243         
244         try {
245             Collection JavaDoc ic = inspectorSet.getInspectors();
246             
247             visitor = new DispatchingVisitor(
248                     ic,
249                     new VisitorExceptionSink() {
250                         public void consume(DispatchingVisitor dispatcher, Object JavaDoc visitor, Method JavaDoc method, Object JavaDoc visitee, Exception JavaDoc e) {
251                             if (logger!=null) {
252                                 logger.warn(visitee, "Exception: "+e);
253                             }
254                             
255                             e.printStackTrace();
256             
257                             getRequest().onWarning(new SimpleViolation(visitee instanceof SourceMarker ? (SourceMarker) visitee : null, "Exception: "+e, null));
258                         }
259                     },
260                     null);
261             session.setInspectors(inspectorSet);
262             visitorStack[0]=visitor.getVisitorStack();
263         } catch (ConfigurationException e) {
264             throw new HammurapiException(e);
265         }
266         
267         session.setVisitor(visitor);
268     }
269     
270     public Reviewer(
271             final Logger logger,
272             boolean embeddedInspectors,
273             InspectorSource inspectorSource,
274             WaiverSource waiverSource) throws HammurapiException {
275         this.logger=logger;
276         final VisitorStack[] visitorStack={null};
277         
278         final VisitorStackSource delegatingVisitorStackSource = new VisitorStackSource() {
279     
280             public VisitorStack getVisitorStack() {
281                 return visitorStack[0];
282             }
283         };
284         
285         inspectorSet=new InspectorSet(
286             new InspectorContextFactory() {
287                 public InspectorContext newContext(final InspectorDescriptor descriptor, final Logger logger) {
288                     return new ReviewerInspectorContext(descriptor, logger, delegatingVisitorStackSource);
289                 }
290             },
291             logger);
292         
293         if (embeddedInspectors) {
294             ClassResourceLoader crl=new ClassResourceLoader(TaskBase.class);
295             InputStream JavaDoc inspectorStream=crl.getResourceAsStream(null,null,"xml");
296             if (inspectorStream==null) {
297                 throw new HammurapiException("Cannot load embedded inspectors");
298             }
299             
300             DomInspectorSource source=new DomInspectorSource(inspectorStream, "Hammurapi.jar");
301             source.loadInspectors(inspectorSet);
302         }
303         
304         if (inspectorSource!=null) {
305             inspectorSource.loadInspectors(inspectorSet);
306         }
307     
308         if (waiverSource!=null) {
309             Date JavaDoc now=new Date JavaDoc();
310             waiverSource.loadWaivers(waiverSet, now);
311         }
312         
313         storage.addStorage("file", new FileStorage(new File JavaDoc(System.getProperties().getProperty("java.io.tmpdir"))));
314         storage.addStorage("memory", new MemoryStorage());
315         session.setStorage(storage);
316         
317         try {
318             Collection JavaDoc ic = inspectorSet.getInspectors();
319             
320             visitor = new DispatchingVisitor(
321                     ic,
322                     new VisitorExceptionSink() {
323                         public void consume(DispatchingVisitor dispatcher, Object JavaDoc visitor, Method JavaDoc method, Object JavaDoc visitee, Exception JavaDoc e) {
324                             if (logger!=null) {
325                                 logger.warn(visitee, "Exception: "+e);
326                             }
327                             
328                             e.printStackTrace();
329             
330                             getRequest().onWarning(new SimpleViolation(visitee instanceof SourceMarker ? (SourceMarker) visitee : null, "Exception: "+e, null));
331                         }
332                     },
333                     null);
334             session.setInspectors(inspectorSet);
335             visitorStack[0]=visitor.getVisitorStack();
336         } catch (ConfigurationException e) {
337             throw new HammurapiException(e);
338         }
339         
340         session.setVisitor(visitor);
341     }
342     
343     private ThreadLocal JavaDoc requestTL=new ThreadLocal JavaDoc();
344     
345     private ReviewRequest getRequest() {
346         return (ReviewRequest) requestTL.get();
347     }
348     
349     public void process(final ReviewRequest request) throws HammurapiException {
350         requestTL.set(request);
351         try {
352             CompilationUnit cu=new CompilationUnitImpl(request.getSource(), null, request.getRootDir(), request.getName(), tabSize, request.getClassLoader(), logger);
353             cu.accept(visitor);
354         } catch (JselException e) {
355             throw new HammurapiException(e);
356         } finally {
357             requestTL.set(null);
358         }
359     }
360
361     private void addViolation(Violation violation) {
362         getRequest().onViolation(violation);
363     }
364
365     /**
366      * @param annotation
367      */

368     private void addAnnotation(Annotation annotation) {
369         // Annotations are ignored
370
}
371
372     /**
373      * @param violation
374      */

375     private void addWarning(Violation violation) {
376         getRequest().onWarning(violation);
377     }
378         
379     public void shutdown() throws HammurapiException {
380         try {
381             session.shutdown();
382         } catch (SQLException JavaDoc e) {
383             throw new HammurapiException("Cannot shutdown session", e);
384         }
385     }
386     
387     public static void main(String JavaDoc[] arg) throws Exception JavaDoc {
388         final File JavaDoc source=new File JavaDoc("..\\UmlApi\\src\\com\\pavelvlasov\\uml\\Operation.java");
389         System.out.println(source.getAbsolutePath());
390         ClassLoader JavaDoc classLoader=new URLClassLoader JavaDoc(new URL JavaDoc[] { new File JavaDoc("..\\UmlApi\\bin").toURL()}, Reviewer.class.getClassLoader());
391         
392         final Reader JavaDoc sr=new FileReader JavaDoc(source);
393         Reviewer reviewer=new Reviewer(null, true, (InspectorSource) null, null);
394         reviewer.process(new ReviewRequestBase(classLoader) {
395
396             public Reader JavaDoc getSource() {
397                 return sr;
398             }
399
400             public String JavaDoc getName() {
401                 return "com/pavelvlasov/uml/Operation.java";
402             }
403
404             public void onViolation(Violation violation) {
405                 System.out.println("VIOLATION: "+violation.getDescriptor().getName()+": "+violation.getMessage());
406             }
407
408             public void onWarning(Violation warning) {
409                 System.out.println("WARNING: "+warning.getMessage());
410             }
411
412             public File JavaDoc getRootDir() {
413                 return new File JavaDoc("..\\UmlApi\\src");
414             }
415         });
416     }
417     
418     /**
419      * @return Returns the tabSize.
420      */

421     public int getTabSize() {
422         return tabSize;
423     }
424     
425     /**
426      * @param tabSize The tabSize to set.
427      */

428     public void setTabSize(int tabSize) {
429         this.tabSize = tabSize;
430     }
431 }
432
Popular Tags