KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > bull > eclipse > jonas > AddLog


1 /*
2  * Created on 6 mars 2004
3  *
4  * To change the template for this generated file go to
5  * Window>Preferences>Java>Code Generation>Code and Comments
6  */

7 package com.bull.eclipse.jonas;
8
9 import java.util.ArrayList JavaDoc;
10 import java.util.Collection JavaDoc;
11 import java.util.Iterator JavaDoc;
12
13 import org.eclipse.jdt.core.Flags;
14 import org.eclipse.jdt.core.ICompilationUnit;
15 import org.eclipse.jdt.core.IType;
16 import org.eclipse.jdt.core.JavaCore;
17 import org.eclipse.jdt.core.JavaModelException;
18 import org.eclipse.jdt.core.ToolFactory;
19 import org.eclipse.jdt.core.compiler.IScanner;
20 import org.eclipse.jdt.core.compiler.ITerminalSymbols;
21 import org.eclipse.jdt.core.compiler.InvalidInputException;
22 import org.eclipse.jdt.core.formatter.CodeFormatter;
23 import org.eclipse.jdt.core.jdom.DOMFactory;
24 import org.eclipse.jdt.core.jdom.IDOMCompilationUnit;
25 import org.eclipse.jdt.core.jdom.IDOMField;
26 import org.eclipse.jdt.core.jdom.IDOMImport;
27 import org.eclipse.jdt.core.jdom.IDOMMethod;
28 import org.eclipse.jdt.core.jdom.IDOMNode;
29 import org.eclipse.jdt.core.jdom.IDOMType;
30
31 /**
32  * @author cnedi
33  *
34  * To change the template for this generated type comment go to
35  * Window>Preferences>Java>Code Generation>Code and Comments
36  */

37
38 public class AddLog {
39
40     private ICompilationUnit cu;
41     private static String JavaDoc sLog =
42         "\n\tif (logger_ == null)\n\t\tlogger_ = Log.getLogger(NCC_);\n\n\tlogger_.log(BasicLevel.DEBUG, \" Ctor \");\n";
43
44     DOMFactory jdom = new DOMFactory();
45     IDOMCompilationUnit theCompUnit = null;
46     IDOMType theType = null;
47
48     public void run(ICompilationUnit cu) throws Exception JavaDoc {
49
50         this.cu = cu;
51
52         IType[] itcu = cu.getAllTypes();
53         if (itcu.length == 0) {
54             throw new Exception JavaDoc("This java file contains no Class !\n");
55         }
56
57         jdom = new DOMFactory();
58         theCompUnit =
59             jdom.createCompilationUnit(cu.getSource(), cu.getElementName());
60
61         // présence de Log ??
62
if (isLogPresent())
63             return;
64
65         theType = jdom.createType(itcu[0].getSource());
66         if (theType == null)
67             return;
68
69         // ne pas traiter les interfaces ...
70
if (Flags.isInterface(theType.getFlags()))
71             return;
72
73         addImports();
74         // System.out.println(theCompUnit.getContents());
75

76         addCtor();
77         // System.out.println(theType.getContents());
78

79         addClassDeclaration();
80         // System.out.println(theType.getContents());
81

82         //
83
addLog();
84         // System.out.println(theType.getContents());
85

86         addLogException();
87         // System.out.println(theType.getContents());
88

89         addLogReturn();
90         // System.out.println(theType.getContents());
91

92         // Vrai toujours ?
93
IDOMNode node = theCompUnit.getFirstChild();
94         while (node != null && node.getNodeType() != IDOMNode.TYPE)
95             node = node.getNextNode();
96
97         if (node != null)
98             node.remove();
99
100         theCompUnit.addChild(theType);
101
102         cu.getBuffer().setContents(theCompUnit.getContents());
103         CodeFormat(cu);
104
105         // cu.save(null, false);
106

107     }
108
109     private void addLogException() throws Exception JavaDoc {
110
111         ArrayList JavaDoc mark = new ArrayList JavaDoc();
112
113         String JavaDoc code = theCompUnit.getContents();
114         int token = 0;
115         IScanner scanner =
116             ToolFactory.createScanner(false, false, false, false);
117         scanner.setSource(code.toCharArray());
118         int start = 0;
119         int end = code.length() - 1;
120         scanner.resetTo(start, end);
121         int visu = 0;
122         try {
123             while ((token = scanner.getNextToken())
124                 != ITerminalSymbols.TokenNameEOF) {
125                 switch (token) {
126                     case ITerminalSymbols.TokenNamecatch :
127                         int offset = scanner.getCurrentTokenStartPosition();
128                             while ((token = scanner.getNextToken()) // (
129
!= ITerminalSymbols.TokenNameLPAREN);
130                         while (true) {
131                                 while ((token =
132                                     scanner.getNextToken())
133                                 // ignorer tout jusqu'au 1er ' '
134
!= ITerminalSymbols.TokenNameIdentifier) {
135                                 visu = scanner.getCurrentTokenStartPosition();
136                             }
137                             token = scanner.getNextToken();
138                             if (token == ITerminalSymbols.TokenNameIdentifier)
139                                 break;
140                         }
141
142                         int k = scanner.getCurrentTokenStartPosition();
143
144                             while ((token =
145                                 scanner.getNextToken()) // Exception Name
146
!= ITerminalSymbols.TokenNameRPAREN);
147
148                         int l = scanner.getCurrentTokenEndPosition();
149
150                         // récupérer le handle de l'exception ...
151
String JavaDoc name =
152                             code.substring(
153                                 k,
154                                 scanner.getCurrentTokenEndPosition());
155                         myCatch my = new myCatch(name, offset);
156                         mark.add(my);
157                 }
158             }
159         } catch (InvalidInputException e) {
160         }
161         char[] c = code.toCharArray();
162         ArrayList JavaDoc su = new ArrayList JavaDoc();
163         int max = c.length - 1;
164         myCatch my = null;
165         for (int i = mark.size() - 1; i >= 0; i--) {
166             my = (myCatch) mark.get(i);
167             int u = my.getOffst();
168             while (c[u] != '{')
169                 u++;
170             String JavaDoc s = new String JavaDoc(c, u + 1, max - u);
171             String JavaDoc exc =
172                 "\n\tlogger_.log(BasicLevel.DEBUG,\"Exception :\" + "
173                     + my.getName()
174                     + ".getMessage());";
175             su.add(exc + "\n" + s);
176             max = u;
177         }
178
179         String JavaDoc s = new String JavaDoc(c, 0, max + 1);
180         su.add(s);
181
182         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(code.length());
183         for (int i = su.size() - 1; i >= 0; i--) {
184             sb.append(su.get(i));
185         }
186
187         cu.getBuffer().setContents(sb.toString());
188
189     }
190
191     private void addLogReturn() throws Exception JavaDoc {
192
193         ArrayList JavaDoc mark = new ArrayList JavaDoc();
194
195         String JavaDoc code = theCompUnit.getContents();
196         int token = 0;
197         int token0 = 0;
198         int token1 = 0;
199         int token2 = 0;
200
201         IScanner scanner =
202             ToolFactory.createScanner(false, false, false, false);
203         scanner.setSource(code.toCharArray());
204         int start = 0;
205         int end = code.length() - 1;
206         scanner.resetTo(start, end);
207         int visu = 0;
208         try {
209             while ((token = scanner.getNextToken())
210                 != ITerminalSymbols.TokenNameEOF) {
211                 switch (token) {
212                     case ITerminalSymbols.TokenNamereturn :
213
214                         int offset = scanner.getCurrentTokenStartPosition();
215
216                         token = scanner.getNextToken();
217
218                             while ((token = scanner.getNextToken()) // (
219
!= ITerminalSymbols.TokenNameSEMICOLON);
220                         int k = scanner.getCurrentTokenStartPosition();
221
222                         int l = scanner.getCurrentTokenEndPosition();
223
224                         // récupérer le handle de l'exception ...
225
String JavaDoc name =
226                             code.substring(
227                                 offset,
228                                 scanner.getCurrentTokenEndPosition());
229                         myCatch my = new myCatch(name, offset);
230                         mark.add(my);
231                 }
232             }
233         } catch (InvalidInputException e) {
234         }
235
236         for (int i = 0; i < mark.size(); i++) {
237             // scan du texte ...
238
myCatch my = (myCatch) mark.get(i);
239             String JavaDoc sParse = my.getName();
240
241             scanner.setSource(sParse.toCharArray());
242             start = 0;
243             end = sParse.length() - 1;
244             scanner.resetTo(start, end);
245
246             token0 = scanner.getNextToken(); // return
247
token1 = scanner.getNextToken(); // ??
248
token2 = scanner.getNextToken(); // ;
249

250         }
251
252     }
253
254     private void addLog() throws Exception JavaDoc {
255
256         IDOMNode root = theType;
257         IDOMNode node = theType.getFirstChild();
258         IDOMMethod meth = null;
259         String JavaDoc sBody = null;
260         String JavaDoc sTrace = null;
261
262         while (node != null) {
263             // Methode
264
System.out.println(" node content " + node.getContents());
265             if (node.getNodeType() == IDOMNode.METHOD
266                 && ((IDOMMethod) node).isConstructor() == false) {
267
268                 // trt méthode
269
meth = (IDOMMethod) node;
270                 if (!Flags.isAbstract(meth.getFlags())) {
271                     System.out.println(" body" + meth.getBody());
272                     // IJavaElement ij = node.getJavaElement(null);
273
char[] c = meth.getBody().toCharArray();
274                     int i = 0;
275                     while (c[i] != '{')
276                         i++;
277                     c[i] = ' ';
278                     sBody = new String JavaDoc(c);
279                     sTrace = buildTrace(meth);
280                     sBody =
281                         "{\n\n\tlogger_.log(BasicLevel.DEBUG,"
282                             + sTrace
283                             + ");\n\n"
284                             + sBody
285                             + "\n\n";
286                     meth.setBody(sBody);
287                     //System.out.println(" body" + meth.getBody());
288
//System.out.println(" body" + root.getContents());
289
}
290             }
291             node = node.getNextNode();
292         }
293
294     }
295
296     private String JavaDoc buildTrace(IDOMMethod m_) {
297         IDOMMethod meth = null;
298         String JavaDoc[] snames = m_.getParameterNames();
299
300         if (snames == null)
301             return "\"\"";
302
303         String JavaDoc[] stypes = m_.getParameterTypes();
304         String JavaDoc strace = new String JavaDoc("");
305
306         for (int i = 0; i < snames.length; i++) {
307             if (strace.length() > 0)
308                 strace += " + ";
309
310             strace += " \" " + snames[i] + " = \" + " + snames[i];
311         }
312         return strace;
313     }
314
315     private String JavaDoc TraceReturn(String JavaDoc code) {
316         int[] i = null;
317         int token = 0;
318         IScanner scanner =
319             ToolFactory.createScanner(false, false, false, false);
320         scanner.setSource(code.toCharArray());
321         int start = 0;
322         int end = code.length() - 1;
323         scanner.resetTo(start, end);
324         i =
325             new int[] {
326                 scanner.getCurrentTokenStartPosition(),
327                 scanner.getCurrentTokenEndPosition()};
328
329         try {
330             while ((token = scanner.getNextToken())
331                 != ITerminalSymbols.TokenNameEOF) {
332                 switch (token) {
333                     case ITerminalSymbols.TokenNamereturn :
334                         i =
335                             new int[] {
336                                 scanner.getCurrentTokenStartPosition(),
337                                 scanner.getCurrentTokenEndPosition()};
338                 }
339             }
340         } catch (InvalidInputException e) {
341         }
342         int ii = token;
343         int k = scanner.getCurrentTokenStartPosition();
344         int u = scanner.getCurrentTokenEndPosition();
345
346         return "";
347     }
348
349     private void addImports() throws JavaModelException {
350
351         // pointer sur 1er noeud après package ...
352
IDOMNode node = theCompUnit.getFirstChild();
353
354         // pas de noeud enfant !
355
if (node == null)
356             return;
357
358         // ignorer package
359
while (node != null && node.getNodeType() == IDOMNode.PACKAGE)
360             node = node.getNextNode();
361
362         //ignorer imports
363
while (node != null && node.getNodeType() == IDOMNode.IMPORT)
364             node = node.getNextNode();
365
366         if (node == null)
367             node = theCompUnit.getFirstChild();
368
369         IDOMImport id = jdom.createImport();
370         id.setName("org.objectweb.jonas.common.Log");
371         node.insertSibling(id);
372         // theCompUnit.addChild(id);
373

374         id = jdom.createImport();
375         id.setName("org.objectweb.util.monolog.api.Logger");
376         node.insertSibling(id);
377         // theCompUnit.addChild(id);
378

379         id = jdom.createImport();
380         id.setName("org.objectweb.util.monolog.api.BasicLevel");
381         node.insertSibling(id);
382         // theCompUnit.addChild(id);
383

384     }
385
386     private void addClassDeclaration() throws JavaModelException {
387
388         IDOMType it = theType;
389         IDOMNode node = theType.getFirstChild(); //
390

391         IDOMField ifd =
392             jdom.createField("\n\tpublic static Logger logger_ = null;\n");
393         if (node == null) {
394             theType.addChild(ifd);
395         } else
396             node.insertSibling(ifd);
397         //
398
ifd =
399             jdom.createField(
400                 "\n\tpublic final static transient String NCC_ = "
401                     + theType.getName()
402                     + ".class.getName();\n\n");
403
404         if (node == null) {
405             theType.addChild(ifd);
406         } else
407             node.insertSibling(ifd);
408
409     }
410
411     private void addCtor() throws JavaModelException {
412
413         IDOMMethod theMethod = null;
414         Collection JavaDoc ctor = null;
415
416         if (!isCtorPresent()) {
417             ctor = addConstructor();
418         } else
419             ctor = getConstructors();
420
421         // ajout séquence de log dans CTOR
422

423         Iterator JavaDoc it = ctor.iterator();
424         while (it.hasNext()) {
425             theMethod = (IDOMMethod) it.next();
426             String JavaDoc sBody = theMethod.getBody();
427             theMethod.setBody(insertLog(sBody));
428         }
429
430
431     }
432
433     private void CodeFormat(ICompilationUnit unit) throws Exception JavaDoc {
434         // reformat code
435
CodeFormatter ic = ToolFactory.createCodeFormatter(JavaCore.getOptions());
436         String JavaDoc srcCode = theCompUnit.getContents();
437         System.out.println("in : " + srcCode);
438         srcCode = ic.format(CodeFormatter.K_COMPILATION_UNIT, srcCode,4 ,4 ,0 , null).toString();
439         System.out.println("out : " + srcCode);
440         unit.getBuffer().setContents(srcCode);
441         unit.getBuffer().save(null, false);
442     }
443
444     class myCatch {
445
446         private String JavaDoc szName = null;
447         private int iOffset = 0;
448
449         myCatch(String JavaDoc szName, int iOffset) {
450             this.szName = szName;
451             this.iOffset = iOffset;
452         }
453         public int getOffst() {
454             return this.iOffset;
455         }
456         public String JavaDoc getName() {
457             return this.szName;
458         }
459     }
460
461     // vérifie si un import LOG est présent
462
private boolean isLogPresent() {
463
464         IDOMNode node = theCompUnit.getFirstChild();
465
466         while (node != null) {
467             if (node.getNodeType() == IDOMNode.IMPORT) {
468
469                 IDOMImport imp = (IDOMImport) node;
470
471                 if (imp.getName().startsWith("org.objectweb.jonas.common.Log"))
472                     return true;
473
474                 if (imp.getName().startsWith("org.apache.log4j"))
475                     return true;
476
477             }
478             node = node.getNextNode();
479         }
480         return false;
481     }
482
483     // vérifie si un CTOR est présent
484
private boolean isCtorPresent() {
485
486         IDOMNode node = theType.getFirstChild();
487         while (node != null) {
488             if (node.getNodeType() == IDOMNode.METHOD) {
489                 IDOMMethod imp = (IDOMMethod) node;
490                 if (imp.isConstructor())
491                     return true;
492             }
493             node = node.getNextNode();
494         }
495
496         return false;
497     }
498
499     // Obtenir Liste de CTORs
500
private Collection JavaDoc getConstructors() {
501
502         ArrayList JavaDoc ctor = new ArrayList JavaDoc();
503         IDOMNode node = theType.getFirstChild();
504         while (node != null) {
505             if (node.getNodeType() == IDOMNode.METHOD) {
506                 IDOMMethod imp = (IDOMMethod) node;
507                 if (imp.isConstructor())
508                     ctor.add(imp);
509             }
510             node = node.getNextNode();
511         }
512
513         return ctor;
514     }
515
516     // ajouter un CTOR
517
private Collection JavaDoc addConstructor() {
518
519         ArrayList JavaDoc ctor = new ArrayList JavaDoc();
520         IDOMMethod theMethod = null;
521
522         // méthode bidon ...
523
theMethod = jdom.createMethod("private void _nop_()");
524         theMethod.setBody("{}\n");
525         System.out.println(theMethod.getContents());
526         theType.addChild(theMethod);
527         System.out.println(theType.getContents());
528
529         // add a ctor
530
theMethod = jdom.createMethod();
531         System.out.println(theMethod.getContents());
532         theMethod.setConstructor(true);
533         theMethod.setName(theType.getName());
534         theMethod.setBody("{\n}\n");
535         theMethod.setFlags(Flags.AccPublic);
536         System.out.println(theMethod.getContents());
537
538         theType.addChild(theMethod);
539
540         ctor.add(theMethod);
541
542         return ctor;
543     }
544
545     private String JavaDoc insertLog(String JavaDoc sStr) {
546
547         char[] s = sStr.toCharArray();
548         char[] t = sLog.toCharArray();
549         char[] n = new char[s.length + sLog.length()];
550
551         int i = 0;
552         while (s[i] != '{') {
553             n[i] = s[i];
554             i++;
555         }
556
557         n[i] = s[i++]; // recopier '{'
558
int j = i;
559         for (int k = 0; k < t.length; k++, j++)
560             n[j] = t[k];
561         // finir de recopier
562
while (i < s.length) {
563             n[j++] = s[i++];
564         }
565
566         return new String JavaDoc(n);
567     }
568 }
569
Popular Tags