KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > hivemind > test > services > impl > CountFactory


1 // Copyright 2004, 2005 The Apache Software Foundation
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
// http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14

15 package hivemind.test.services.impl;
16
17 import java.lang.reflect.InvocationHandler;
18 import java.lang.reflect.InvocationTargetException;
19 import java.lang.reflect.Method;
20 import java.lang.reflect.Proxy;
21 import java.util.List;
22
23 import org.apache.hivemind.InterceptorStack;
24 import org.apache.hivemind.ServiceInterceptorFactory;
25 import org.apache.hivemind.internal.Module;
26
27 /**
28  * Simple factory that uses dynamic proxies to count the number of times
29  * methods in interfaces it has enhanced have been executed.
30  *
31  * @author Howard Lewis Ship
32  */

33 public class CountFactory implements ServiceInterceptorFactory
34 {
35     private static int _count = 0;
36
37     public static int getCount()
38     {
39         return _count;
40     }
41
42     public static void reset()
43     {
44         _count = 0;
45     }
46
47     public static void incrementCount()
48     {
49         _count++;
50     }
51
52     private static class CountHandler implements InvocationHandler
53     {
54         private Object _inner;
55
56         CountHandler(Object inner)
57         {
58             _inner = inner;
59         }
60
61         public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
62         {
63             try
64             {
65                 incrementCount();
66
67                 return method.invoke(_inner, args);
68             }
69             catch (InvocationTargetException ex)
70             {
71                 throw ex.getTargetException();
72             }
73         }
74
75     }
76
77     public void createInterceptor(InterceptorStack stack, Module invokingModule, List parameters)
78     {
79         InvocationHandler countHandler = new CountHandler(stack.peek());
80
81         Object proxy =
82             Proxy.newProxyInstance(
83                 invokingModule.getClassResolver().getClassLoader(),
84                 new Class[] { stack.getServiceInterface()},
85                 countHandler);
86
87         stack.push(proxy);
88     }
89 }
90
Popular Tags