1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package net.sf.jour.instrumentor;
22
23 import java.util.ArrayList;
24 import java.util.Iterator;
25
26 import javassist.CannotCompileException;
27 import javassist.ClassPool;
28 import javassist.CtClass;
29 import javassist.CtConstructor;
30 import javassist.CtMethod;
31 import javassist.NotFoundException;
32 import net.sf.jour.InterceptorException;
33
34
35
36
37
38
39
40
41
42
43
44 public class ExceptionCatcherInstrumentor extends AbstractInstrumentor {
45
46 private ArrayList exceptions = new ArrayList();
47
48 private String code;
49
50
51
52
53 public ExceptionCatcherInstrumentor() {
54 }
55
56 public void exceptionType(String exception) {
57 exceptions.add(exception);
58 }
59
60 public void code(String code) {
61 this.code = code;
62 }
63
64 public boolean instrumentClass(CtClass clazz) throws InterceptorException {
65 return false;
66 }
67
68 public boolean instrumentMethod(CtClass clazz, CtMethod method)
69 throws InterceptorException {
70 if (method.isEmpty()) {
71 return false;
72 }
73
74 try {
75 boolean modified = false;
76 for (Iterator iter = exceptions.iterator(); iter.hasNext();) {
77 String exception = (String) iter.next();
78 addCatch(clazz, method, exception);
79 modified = true;
80 }
81 return modified;
82 } catch (Exception e) {
83 e.printStackTrace();
84 throw new InterceptorException("Failed to add catch to method " +
85 method + " of class " + clazz);
86 }
87 }
88
89 private void addCatch(CtClass clazz, CtMethod method, String exception)
90 throws NotFoundException, CannotCompileException {
91 String mname = method.getName();
92 CtClass etype = ClassPool.getDefault().get(exception);
93 StringBuffer codeBuffer = new StringBuffer();
94 if (this.code == null) {
95 codeBuffer.append("{ System.out.println(\"Exception ").append(exception).append(" at ");
96 codeBuffer.append(clazz.getName()).append(".").append(mname).append("\");");
97 codeBuffer.append(" throw $e; }");
98 } else {
99 codeBuffer.append(this.code);
100 }
101 method.addCatch(codeBuffer.toString(), etype);
102 }
103
104 public boolean instrumentConstructor(CtClass clazz, CtConstructor constructor)
105 throws InterceptorException {
106 return false;
107 }
108
109 }