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 javassist.CannotCompileException;
24 import javassist.CtClass;
25 import javassist.CtConstructor;
26 import javassist.CtMethod;
27 import javassist.CtNewMethod;
28 import javassist.NotFoundException;
29 import net.sf.jour.InterceptorException;
30
31
32
33
34
35
36
37
38
39
40
41 public class InstanceCounterInstrumentor extends AbstractInstrumentor
42 implements InstrumentorConsts {
43
44 public boolean instrumentClass(CtClass clazz) throws InterceptorException {
45 try {
46 addCounterDecrementer(clazz);
47 return true;
48 } catch (Exception e) {
49 e.printStackTrace();
50 throw new InterceptorException(
51 "Failed to add instance counter member to class " + clazz);
52 }
53 }
54
55 public boolean instrumentMethod(CtClass clazz, CtMethod method)
56 throws InterceptorException {
57 return false;
58 }
59
60 public boolean instrumentConstructor(CtClass clazz, CtConstructor constructor)
61 throws InterceptorException {
62 if (constructor.isClassInitializer()) {
63 return false;
64 }
65
66 try {
67 addCounterIncrementer(clazz, constructor);
68 return true;
69 } catch (Exception e) {
70 e.printStackTrace();
71 throw new InterceptorException(
72 "Failed to add instance counter incrementor to constructor of class " +
73 clazz);
74 }
75 }
76
77 private void addCounterIncrementer(CtClass clazz, CtConstructor constructor)
78 throws NotFoundException, CannotCompileException {
79
80 String code = "net.sf.jour.rt.agent.Elog.logEvent(new net.sf.jour.rt.agent.InstanceCounterEvent(this.getClass(), true));";
81 constructor.insertAfter(code);
82 }
83
84 private void addCounterDecrementer(CtClass clazz)
85 throws CannotCompileException {
86 CtMethod finalize;
87 try {
88 finalize = clazz.getDeclaredMethod("finalize",
89 new CtClass[] {});
90 if (finalize != null) {
91 String code = "net.sf.jour.rt.agent.Elog.logEvent(new net.sf.jour.rt.agent.InstanceCounterEvent(this.getClass(), false));";
92 finalize.insertAfter(code, true);
93 }
94 } catch (NotFoundException nfe) {
95 StringBuffer code = new StringBuffer(
96 "protected void finalize() throws Throwable { super.finalize(); ");
97 code.append(
98 "net.sf.jour.rt.agent.Elog.logEvent(new net.sf.jour.rt.agent.InstanceCounterEvent(this.getClass(), false));}");
99 finalize = CtNewMethod.make(code.toString(), clazz);
100 clazz.addMethod(finalize);
101 }
102 }
103
104 }