KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hammurapi > inspectors > metrics > CallerTrace


1 /*
2  * Hammurapi
3  * Automated Java code review system.
4  * Copyright (C) 2004 Johannes Bellert
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.com
21  * e-Mail: Johannes.Bellert@ercgroup.com
22  *
23  * * Created on Apr 11, 2004
24  *
25  */

26 package org.hammurapi.inspectors.metrics;
27
28 import java.io.FileInputStream JavaDoc;
29 import java.io.FileOutputStream JavaDoc;
30 import java.util.Collection JavaDoc;
31 import java.util.Enumeration JavaDoc;
32 import java.util.Iterator JavaDoc;
33 import java.util.Properties JavaDoc;
34
35 import org.hammurapi.HammurapiException;
36 import org.hammurapi.InspectorBase;
37 import org.hammurapi.inspectors.metrics.callertrace.CallerTraceService;
38 import org.hammurapi.inspectors.metrics.callertrace.MethodMap;
39 import org.hammurapi.inspectors.metrics.callertrace.MethodWrapper;
40 import org.hammurapi.inspectors.metrics.callertrace.MethodWrapperDeclaration;
41 import org.hammurapi.inspectors.metrics.callertrace.MethodWrapperInvoked;
42 import org.hammurapi.results.AnnotationContext;
43 import org.hammurapi.results.LinkedAnnotation;
44 import org.w3c.dom.Document JavaDoc;
45 import org.w3c.dom.Element JavaDoc;
46
47 import com.pavelvlasov.config.ConfigurationException;
48 import com.pavelvlasov.config.Parameterizable;
49 import com.pavelvlasov.jsel.Code;
50 import com.pavelvlasov.jsel.Constructor;
51 import com.pavelvlasov.jsel.JselException;
52 import com.pavelvlasov.jsel.LanguageElement;
53 import com.pavelvlasov.jsel.Method;
54 import com.pavelvlasov.jsel.Operation;
55 import com.pavelvlasov.jsel.OperationInfo;
56 import com.pavelvlasov.jsel.Repository;
57 import com.pavelvlasov.jsel.TypeBody;
58 import com.pavelvlasov.jsel.TypeDefinition;
59 import com.pavelvlasov.jsel.expressions.MethodCall;
60 import com.pavelvlasov.jsel.impl.AbstractRepositoryImpl;
61 import com.pavelvlasov.jsel.impl.ClassImpl;
62 import com.pavelvlasov.render.RenderRequest;
63 import com.pavelvlasov.render.dom.AbstractRenderer;
64 import com.pavelvlasov.review.SourceMarker;
65 import com.pavelvlasov.util.Acceptor;
66
67 /**
68  * @author Johannes Bellert
69  *
70  */

71
72 //!! move class up to caller trace package
73
public class CallerTrace extends InspectorBase implements Parameterizable {
74
75     private CallerTraceService callerTraceService = new CallerTraceService();
76     //private Repository repository = null;
77

78     public void visit(Operation methodCall) {
79         // System.out.println("*if> " + methodCall.toString());
80
}
81     
82 public void visit(MethodCall methodCall) {
83     
84         //System.out.println("*> " + methodCall.toString());
85

86         try {
87             AbstractRepositoryImpl repository = null;
88             OperationInfo opi = methodCall.getProvider();
89             MethodWrapperInvoked mwi = new MethodWrapperInvoked( opi, (SourceMarker)methodCall );
90         /*
91             if( "java.lang.StringBuffer".equals( mwi.getDeclaringType() )
92                     || "java.lang.String".equals( mwi.getDeclaringType() )
93                     || ( !mwi.getDeclaringType().startsWith("java.sql.")
94                             && mwi.getDeclaringType().startsWith("java.") ) ){
95             */

96             Code code = ((LanguageElement) methodCall).getEnclosingCode();
97 // *> childNodes.item(i).getNodeName().equalsIgnoreCase(ApplicationConstants.LOGFILENAME
98
if( code != null && code instanceof Operation ){
99                 Operation op = (Operation) code;
100             // OperationInfo provider = new OperationInfo(code);
101
TypeBody tb = code.getEnclosingType();
102             // String key = provider.getDeclaringType()+ ">>" +op.getOperationSignature();
103
String JavaDoc key = tb.getFcn() + ">>" +op.getOperationSignature();
104             
105             //System.out.println("methodCall " + key );
106

107             MethodMap mp = callerTraceService.getAllMethodsImplemented();
108             MethodWrapperDeclaration caller = (MethodWrapperDeclaration)mp.selectMethodsWithoutHashkey( key ) ;
109             
110             // System.out.println("methodDecl of Caller " + caller.getMethodKey() );
111

112             if ( caller != null ){
113                 caller.getInvokedMethods().add(mwi);
114                 
115             } else {
116                 // System.out.println("!!!!! methodCall without MethodWrapperDeclaration " + key );
117
}
118             
119             mwi.setCallerMethod( caller );
120             MethodWrapper invokeeDeclarationResolution = mwi;
121             MethodWrapperDeclaration invokeeDecla = (MethodWrapperDeclaration)mp.selectMethodsWithoutHashkey( mwi.getMethodKey() ) ;
122             
123             if ( invokeeDecla != null ){
124                 // System.out.println("methodDecl of invokee " + caller.getMethodKey() );
125
invokeeDecla.setCalled();
126                 invokeeDecla.afferentMethodCoupling++;
127                 //System.out.println("Ma " + invokeeDecla.afferentMethodCoupling );
128
invokeeDeclarationResolution = invokeeDecla;
129                 
130             } else {
131                 // System.out.println("!!!!! invokeeDecla without MethodWrapperDeclaration " + mwi.getMethodKey() );
132
}
133             //!! search for implementor of methodCall and use this for reference
134
// put only methodcalls as an node, if there is no declaration
135
// issue: depending on scan relationship, the method impl may not accessable
136
callerTraceService.getAdjacencyMatrix().put( invokeeDeclarationResolution.getMethodKey(), caller.getMethodKey() );
137             callerTraceService.getAllMethods().put(mwi.getMethodKey(), mwi);
138             callerTraceService.getAllInvokedMethodTable().put( mwi.getMethodKey(), mwi);
139             }
140     // if }
141
} catch (Exception JavaDoc e) {
142             // TODO Auto-generated catch block
143
// System.out.println( methodCall.toString() );
144
e.printStackTrace();
145         }
146     }
147
148 public void visit(Constructor aConstructor) {
149     try {
150          Repository repository = aConstructor.getCompilationUnit().getPackage().getRepository();
151     MethodWrapperDeclaration mwd = new MethodWrapperDeclaration( aConstructor.getInfo(), (SourceMarker)aConstructor);
152     
153     if( this.callerTraceService.getAllInterfacesAndImplementors().containsKey( mwd.getDeclaringType() )){
154         callerTraceService.getAllInterfaceOperations().add( mwd );
155         // System.out.println("added 2 allInterfaceOperations " + mwd.getMethodKey());
156
}
157     
158     callerTraceService.getAllMethods().put(mwd.getMethodKey(),mwd);
159     callerTraceService.getAllMethodsImplemented().put(mwd.getMethodKey(),mwd);
160     } catch (JselException e) {
161         // TODO Auto-generated catch block
162
e.printStackTrace();
163     }
164 }
165
166
167     public void visit(Method methodDecl) {
168         try {
169              Repository repository = methodDecl.getCompilationUnit().getPackage().getRepository();
170         MethodWrapperDeclaration mwd = new MethodWrapperDeclaration(methodDecl.getInfo(), (SourceMarker)methodDecl);
171         
172         if( this.callerTraceService.getAllInterfacesAndImplementors().containsKey( mwd.getDeclaringType() )){
173             callerTraceService.getAllInterfaceOperations().add( mwd );
174             // System.out.println("added 2 allInterfaceOperations " + mwd.getMethodKey());
175
}
176         
177         callerTraceService.getAllMethods().put(mwd.getMethodKey(),mwd);
178         callerTraceService.getAllMethodsImplemented().put(mwd.getMethodKey(),mwd);
179         } catch (JselException e) {
180             // TODO Auto-generated catch block
181
e.printStackTrace();
182         }
183     }
184
185     public void visit(com.pavelvlasov.jsel.Interface ifc) {
186         // System.out.println("ifc: " + ifc.toString());
187

188         final String JavaDoc searchTerm = ifc.getFcn();
189         
190           Repository repository = ifc.getCompilationUnit().getPackage().getRepository();
191         Collection JavaDoc classesOfInterest=repository.findAll(new Acceptor() {
192             public boolean accept(Object JavaDoc element) {
193                 try {
194                     return (element instanceof TypeDefinition && ((TypeDefinition) element).isKindOf( searchTerm));
195                 } catch (JselException e) {
196                     // TODO You can put more proper handling here, e.g. throw JselRuntimeException.
197
e.printStackTrace();
198                     return false;
199                 }
200             }
201   });
202           if (classesOfInterest != null && classesOfInterest.size()>0 ){
203             // System.out.println("<~ " + ifc.getName() );
204
this.callerTraceService.getAllInterfacesAndImplementors().put( ifc.getName(), classesOfInterest );
205           }
206           
207     }
208     
209     
210     //!! should be move to adj matrox
211
/*
212      * side effect: changed left-hand side node (invokees) of adjacence edges
213      */

214     
215     private void resolveInvokeesImplementors(){
216         callerTraceService.resolveInvokeesImplementors();
217     }
218
219         /*
220          * Construct a adjacenz matrix edge between each
221          * interface operation and all the implementor operations (and only them)
222          */

223
224     private void handleInterfaces() {
225
226          for( int i=0; i<this.callerTraceService.getAllInterfaceOperations().size(); i++){
227             MethodWrapperDeclaration interFaceOp = (MethodWrapperDeclaration)this.callerTraceService.getAllInterfaceOperations().elementAt(i);
228             String JavaDoc keyIf = interFaceOp.getDeclaringType()+ ">>" +interFaceOp.getSignature();
229              // System.out.println( "keyIf " + keyIf );
230
Enumeration JavaDoc enumIF = this.callerTraceService.getAllInterfacesAndImplementors().keys();
231             while ( enumIF.hasMoreElements() ){
232                 
233                 String JavaDoc key = (String JavaDoc)enumIF.nextElement();
234                  // System.out.println( "*** " + key);
235

236                 Collection JavaDoc classes = (Collection JavaDoc)this.callerTraceService.getAllInterfacesAndImplementors().get(key);
237                 Iterator JavaDoc itcls = classes.iterator();
238                     while ( itcls.hasNext() ){
239                         // String str = (String)itcls.next();
240
Object JavaDoc obj = itcls.next();
241                         if( obj instanceof ClassImpl){
242                              // System.out.println("+++ " + ((ClassImpl) obj).getFcn() );
243
String JavaDoc keyImpl = ((ClassImpl) obj).getFcn()+ ">>" + interFaceOp.getSignature();
244                              // System.out.println("+++ keyImpl" + keyImpl );
245
// String keyImpl = ((ClassImpl) obj).getFcn()+ ">>" +interFaceOp.getName();
246
// callerTraceService.getAdjacencyMatrix().put(keyIf, keyImpl );
247
// System.out.println(this.callerTraceService.getAllMethodsImplemented());
248
MethodWrapperDeclaration mwif = (MethodWrapperDeclaration)this.callerTraceService.getAllMethodsImplemented().selectMethodsWithoutHashkey( keyIf ) ;
249                              MethodWrapperDeclaration mwd = (MethodWrapperDeclaration)this.callerTraceService.getAllMethodsImplemented().selectMethodsWithoutHashkey( keyImpl ) ;
250                              // System.out.println( "mwd.getMethodKey() " + mwif.getMethodKey() );
251
callerTraceService.getAdjacencyMatrix().put(mwd.getMethodKey(), mwif.getMethodKey() );
252                         }
253                     }
254             }
255             
256          }
257     }
258
259     private void aggregate(){
260         // System.out.println("aggregate");
261
resolveInvokeesImplementors();
262         handleInterfaces();
263         
264         callerTraceService.init();
265         callerTraceService.traceCaller();
266     }
267
268     public void leave(Repository repository) {
269         aggregate();
270
271         context.annotate( new LinkedAnnotation() {
272             private String JavaDoc path;
273
274             public String JavaDoc getName() {
275                 return getContext().getDescriptor().getName();
276             }
277
278             public String JavaDoc getPath() {
279                 return path;
280             }
281
282             public void render(AnnotationContext context) throws HammurapiException {
283                 String JavaDoc errorCausingFile = "";
284
285                 // Output images here. See AnnotationTest for details.
286

287                 class CallerTraceRenderer extends AbstractRenderer {
288                     CallerTraceRenderer() {
289                         super(new RenderRequest(CallerTrace.this));
290                     }
291
292                     public Element JavaDoc render(Document JavaDoc document) {
293                         CallerTrace ctInspector=(CallerTrace) request.getRenderee();
294
295                         Element JavaDoc ctInspectorElement=document.createElement("CallerTrace");
296                          callerTraceService.toDom( document , ctInspectorElement) ;
297
298                         
299                         return ctInspectorElement;
300                     }
301                 } //-- end class NcssInspectorRenderer
302

303
304                 AnnotationContext.FileEntry fileEntry=context.getNextFile(context.getExtension());
305                 path=fileEntry.getPath();
306             // System.out.println( ".> " +this.getPath().toString() );
307

308                 AnnotationContext.FileEntry fileEntryXml=context.getNextFile(".xml");
309                 try {
310                     CallerTraceRenderer renderer=new CallerTraceRenderer();
311                     FileOutputStream JavaDoc out=new FileOutputStream JavaDoc(fileEntry.getFile());
312
313                     renderer.setEmbeddedStyle(context.isEmbeddedStyle());
314                     try {
315                         errorCausingFile = fileEntry.getFile().getAbsolutePath();
316                         renderer.render(context.getParameter("style")==null ? null : new FileInputStream JavaDoc(context.getParameter("style").toString()), out);
317                     } finally {
318                         out.close();
319                     }
320                         //-- write a XML file for other XSL usage
321
FileOutputStream JavaDoc outXml=new FileOutputStream JavaDoc(fileEntryXml.getFile());
322
323                     try {
324                         errorCausingFile = fileEntryXml.getFile().getAbsolutePath();
325                         //-- write a XML file for other XSL usage
326
renderer.setEmbeddedStyle(false);
327                         renderer.render(outXml);
328 // renderer.setPrettyPrint( true );
329
// InputStream inStream=getClass().getClassLoader().getResourceAsStream(xmlResourceName);
330
// renderer.render(inStream, outXml);
331

332                     } finally {
333                         outXml.close();
334                     }
335                 } catch (Exception JavaDoc e) {
336                     throw new HammurapiException("Can't save "+ errorCausingFile +". " +e.getMessage() );
337                 }
338             }
339             public Properties JavaDoc getProperties() {
340                 Properties JavaDoc ret=new Properties JavaDoc();
341                 ret.setProperty("left-panel", "yes");
342                 ret.setProperty("target", "Caller Trace");
343                 return ret;
344             }
345         });
346     }
347
348
349     /**
350      * Configures the rule. Reads in the values of the parameters XXX and
351      * class-max-complexity.
352      *
353      * @param name the name of the parameter being loaded from Hammurapi configuration
354      * @param value the value of the parameter being loaded from Hammurapi configuration
355      * @exception ConfigurationException in case of a not supported parameter
356      */

357     public boolean setParameter(String JavaDoc name, Object JavaDoc value) throws ConfigurationException {
358         if (true) {
359             return true;
360         } else {
361             throw new ConfigurationException("Parameter '"+name+"' is not supported");
362         }
363     }
364 }
365
366
Popular Tags