1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.nuiton.util.rmi;
23
24 import org.apache.commons.logging.Log;
25 import org.apache.commons.logging.LogFactory;
26
27 import java.lang.reflect.InvocationHandler;
28 import java.lang.reflect.Method;
29 import java.lang.reflect.Proxy;
30 import java.rmi.ConnectException;
31 import java.rmi.NotBoundException;
32 import java.rmi.RemoteException;
33 import java.rmi.ServerException;
34 import java.rmi.registry.LocateRegistry;
35 import java.rmi.registry.Registry;
36
37
38
39
40
41
42 public class RemoteProxyFactory {
43
44 private static final Log log = LogFactory.getLog(RemoteProxyFactory.class);
45
46
47 protected final static int PORT = 12345;
48
49 protected final static String REGISTRY_IP = "127.0.0.1";
50
51
52
53
54
55
56
57
58
59
60
61
62 public static <T> T createProxy(final Class<T> serviceInterface)
63 throws RemoteException, NotBoundException {
64
65
66 String rmiName = serviceInterface.getName();
67 T result = createProxy(rmiName, serviceInterface);
68
69 return result;
70 }
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85 public static <T> T createProxy(String rmiName, Class<T> serviceInterface)
86 throws RemoteException, NotBoundException {
87
88
89 Registry registry = LocateRegistry.getRegistry(REGISTRY_IP, PORT);
90 try {
91 registry.list();
92 } catch (ConnectException ce) {
93
94 registry = LocateRegistry.getRegistry();
95 }
96 final RemoteMethodExecutor stub =
97 (RemoteMethodExecutor) registry.lookup(rmiName);
98
99 InvocationHandler handler = new InvocationHandler() {
100 @Override
101 public Object invoke(Object proxy, Method method, Object[] args)
102 throws Throwable {
103
104
105 String methodName = method.getName();
106 Class<?>[] parametersType = method.getParameterTypes();
107
108
109 Object result;
110 try {
111 result = stub.execute(methodName, parametersType, args);
112 } catch (ServerException se) {
113 if (log.isInfoEnabled()) {
114 log.info("Server exception: " + se.getMessage());
115 }
116 Throwable cause = se.getCause();
117 if (cause instanceof RemoteException) {
118 RemoteException re = (RemoteException) cause;
119 cause = re.getCause();
120 }
121 throw cause;
122 }
123
124 return result;
125 }
126 };
127
128
129 T proxy = (T) Proxy.newProxyInstance(
130 ServiceExporter.class.getClassLoader(),
131 new Class<?>[]{serviceInterface},
132 handler);
133
134 return proxy;
135 }
136
137 }