source: trunk/src/main/java/omq/server/RemoteObject.java @ 63

Last change on this file since 63 was 58, checked in by stoda, 11 years ago

@MultiMethod? + @SyncMethod? implemented and tested

File size: 7.3 KB
Line 
1package omq.server;
2
3import java.io.IOException;
4import java.lang.reflect.Method;
5import java.util.ArrayList;
6import java.util.Collection;
7import java.util.HashMap;
8import java.util.List;
9import java.util.Map;
10import java.util.Properties;
11
12import org.apache.log4j.Logger;
13
14import omq.Remote;
15import omq.common.broker.Broker;
16import omq.common.event.Event;
17import omq.common.event.EventListener;
18import omq.common.event.EventWrapper;
19import omq.common.util.ParameterQueue;
20import omq.common.util.Serializer;
21import omq.exception.SerializerException;
22
23import com.rabbitmq.client.Channel;
24import com.rabbitmq.client.ConsumerCancelledException;
25import com.rabbitmq.client.QueueingConsumer;
26import com.rabbitmq.client.QueueingConsumer.Delivery;
27import com.rabbitmq.client.ShutdownSignalException;
28
29/**
30 *
31 * @author Sergi Toda <sergi.toda@estudiants.urv.cat>
32 *
33 */
34public abstract class RemoteObject extends Thread implements Remote {
35
36        private static final long serialVersionUID = -1778953938739846450L;
37        private static final String multi = "multi#";
38        private static final Logger logger = Logger.getLogger(RemoteObject.class.getName());
39
40        private String UID;
41        private String multiQueue;
42        private Properties env;
43        private transient Broker broker;
44        private transient Serializer serializer;
45        private transient RemoteWrapper remoteWrapper;
46        private transient Map<String, List<Class<?>>> params;
47        private transient Channel channel;
48        private transient QueueingConsumer consumer;
49        private transient boolean killed = false;
50
51        private static final Map<String, Class<?>> primitiveClasses = new HashMap<String, Class<?>>();
52
53        static {
54                primitiveClasses.put("byte", Byte.class);
55                primitiveClasses.put("short", Short.class);
56                primitiveClasses.put("char", Character.class);
57                primitiveClasses.put("int", Integer.class);
58                primitiveClasses.put("long", Long.class);
59                primitiveClasses.put("float", Float.class);
60                primitiveClasses.put("double", Double.class);
61        }
62
63        public RemoteObject() {
64        }
65
66        public void startRemoteObject(String reference, Broker broker) throws Exception {
67                this.broker = broker;
68                UID = reference;
69                multiQueue = UID + System.currentTimeMillis();
70                env = broker.getEnvironment();
71                serializer = broker.getSerializer();
72
73                params = new HashMap<String, List<Class<?>>>();
74                for (Method m : this.getClass().getMethods()) {
75                        List<Class<?>> list = new ArrayList<Class<?>>();
76                        for (Class<?> clazz : m.getParameterTypes()) {
77                                list.add(clazz);
78                        }
79                        params.put(m.getName(), list);
80                }
81
82                // Get num threads to use
83                int numThreads = Integer.parseInt(env.getProperty(ParameterQueue.NUM_THREADS, "1"));
84                remoteWrapper = new RemoteWrapper(this, numThreads, broker.getSerializer());
85
86                startQueues();
87
88                // Start this listener
89                this.start();
90        }
91
92        @Override
93        public void run() {
94                while (!killed) {
95                        try {
96                                Delivery delivery = consumer.nextDelivery();
97
98                                logger.debug(UID + " has received a message");
99
100                                remoteWrapper.notifyDelivery(delivery);
101                        } catch (InterruptedException i) {
102                                logger.error(i);
103                        } catch (ShutdownSignalException e) {
104                                logger.error(e);
105                                try {
106                                        if (channel.isOpen()) {
107                                                channel.close();
108                                        }
109                                        startQueues();
110                                } catch (Exception e1) {
111                                        try {
112                                                long milis = Long.parseLong(env.getProperty(ParameterQueue.RETRY_TIME_CONNECTION, "2000"));
113                                                Thread.sleep(milis);
114                                        } catch (InterruptedException e2) {
115                                                logger.error(e2);
116                                        }
117                                        logger.error(e1);
118                                }
119                        } catch (ConsumerCancelledException e) {
120                                logger.error(e);
121                        } catch (SerializerException e) {
122                                logger.error(e);
123                        } catch (Exception e) {
124                                logger.error(e);
125                        }
126                }
127        }
128
129        @Override
130        public String getRef() {
131                return UID;
132        }
133
134        @Override
135        public void notifyEvent(Event event) throws IOException, SerializerException {
136                event.setTopic(UID);
137                EventWrapper wrapper = new EventWrapper(event);
138                channel.exchangeDeclare(UID, "fanout");
139                channel.basicPublish(UID, "", null, serializer.serialize(wrapper));
140        }
141
142        public void kill() throws IOException {
143                logger.warn("Killing objectmq: " + this.getRef());
144                killed = true;
145                interrupt();
146                channel.close();
147                remoteWrapper.stopRemoteWrapper();
148        }
149
150        public Object invokeMethod(String methodName, Object[] arguments) throws Exception {
151
152                // Get the specific method identified by methodName and its arguments
153                Method method = loadMethod(methodName, arguments);
154
155                return method.invoke(this, arguments);
156        }
157
158        private Method loadMethod(String methodName, Object[] args) throws NoSuchMethodException {
159                Method m = null;
160
161                // Obtain the class reference
162                Class<?> clazz = this.getClass();
163                Class<?>[] argArray = null;
164
165                if (args != null) {
166                        argArray = new Class<?>[args.length];
167                        for (int i = 0; i < args.length; i++) {
168                                argArray[i] = args[i].getClass();
169                        }
170                }
171
172                try {
173                        m = clazz.getMethod(methodName, argArray);
174                } catch (NoSuchMethodException nsm) {
175                        m = loadMethodWithPrimitives(methodName, argArray);
176                }
177                return m;
178        }
179
180        private Method loadMethodWithPrimitives(String methodName, Class<?>[] argArray) throws NoSuchMethodException {
181                if (argArray != null) {
182                        Method[] methods = this.getClass().getMethods();
183                        int length = argArray.length;
184
185                        for (Method method : methods) {
186                                String name = method.getName();
187                                int argsLength = method.getParameterTypes().length;
188
189                                if (name.equals(methodName) && length == argsLength) {
190                                        // This array can have primitive types inside
191                                        Class<?>[] params = method.getParameterTypes();
192
193                                        boolean found = true;
194
195                                        for (int i = 0; i < length; i++) {
196                                                if (params[i].isPrimitive()) {
197                                                        Class<?> paramWrapper = primitiveClasses.get(params[i].getName());
198
199                                                        if (!paramWrapper.equals(argArray[i])) {
200                                                                found = false;
201                                                                break;
202                                                        }
203                                                }
204                                        }
205                                        if (found) {
206                                                return method;
207                                        }
208                                }
209                        }
210                }
211                throw new NoSuchMethodException(methodName);
212        }
213
214        public List<Class<?>> getParams(String methodName) {
215                return params.get(methodName);
216        }
217
218        public Channel getChannel() {
219                return channel;
220        }
221
222        private void startQueues() throws Exception {
223                // Get info about which exchange and queue will use
224                String exchange = env.getProperty(ParameterQueue.RPC_EXCHANGE);
225                String queue = UID;
226                String routingKey = UID;
227                // Multi info
228                String multiExchange = multi + exchange;
229
230                boolean durable = Boolean.parseBoolean(env.getProperty(ParameterQueue.DURABLE_QUEUES, "false"));
231
232                // Start channel
233                channel = broker.getNewChannel();
234
235                // Declares and bindings
236                logger.info("RemoteObject: " + UID + " declaring direct exchange: " + exchange + ", Queue: " + queue);
237                channel.exchangeDeclare(exchange, "direct");
238                channel.queueDeclare(queue, durable, false, false, null);
239                channel.queueBind(queue, exchange, routingKey);
240
241                channel.exchangeDeclare(multiExchange, "fanout");
242                channel.queueDeclare(multiQueue, durable, false, false, null);
243                channel.queueBind(multiQueue, multiExchange, "");
244
245                // Declare the event topic fanout
246                logger.info("RemoteObject: " + UID + " declaring fanout exchange: " + UID);
247                channel.exchangeDeclare(UID, "fanout");
248
249                // Declare a new consumer
250                consumer = new QueueingConsumer(channel);
251                channel.basicConsume(queue, true, consumer);
252                channel.basicConsume(multiQueue, true, consumer);
253        }
254
255        @Override
256        public void addListener(EventListener<?> eventListener) throws Exception {
257        }
258
259        @Override
260        public void removeListener(EventListener<?> eventListener) throws Exception {
261        }
262
263        @Override
264        public Collection<EventListener<?>> getListeners() throws Exception {
265                return null;
266        }
267
268}
Note: See TracBrowser for help on using the repository browser.