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

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

startEventTrigger added

File size: 7.5 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        public void startTriggerEvent(String reference, Broker broker) throws Exception {
93                this.broker = broker;
94                UID = reference;
95                if (channel == null || !channel.isOpen()) {
96                        channel = broker.getChannel();
97                }
98        }
99
100        @Override
101        public void run() {
102                while (!killed) {
103                        try {
104                                Delivery delivery = consumer.nextDelivery();
105
106                                logger.debug(UID + " has received a message");
107
108                                remoteWrapper.notifyDelivery(delivery);
109                        } catch (InterruptedException i) {
110                                logger.error(i);
111                        } catch (ShutdownSignalException e) {
112                                logger.error(e);
113                                try {
114                                        if (channel.isOpen()) {
115                                                channel.close();
116                                        }
117                                        startQueues();
118                                } catch (Exception e1) {
119                                        try {
120                                                long milis = Long.parseLong(env.getProperty(ParameterQueue.RETRY_TIME_CONNECTION, "2000"));
121                                                Thread.sleep(milis);
122                                        } catch (InterruptedException e2) {
123                                                logger.error(e2);
124                                        }
125                                        logger.error(e1);
126                                }
127                        } catch (ConsumerCancelledException e) {
128                                logger.error(e);
129                        } catch (SerializerException e) {
130                                logger.error(e);
131                        } catch (Exception e) {
132                                logger.error(e);
133                        }
134                }
135        }
136
137        @Override
138        public String getRef() {
139                return UID;
140        }
141
142        @Override
143        public void notifyEvent(Event event) throws IOException, SerializerException {
144                event.setTopic(UID);
145                EventWrapper wrapper = new EventWrapper(event);
146                channel.exchangeDeclare(UID, "fanout");
147                channel.basicPublish(UID, "", null, serializer.serialize(wrapper));
148        }
149
150        public void kill() throws IOException {
151                logger.warn("Killing objectmq: " + this.getRef());
152                killed = true;
153                interrupt();
154                channel.close();
155                remoteWrapper.stopRemoteWrapper();
156        }
157
158        public Object invokeMethod(String methodName, Object[] arguments) throws Exception {
159
160                // Get the specific method identified by methodName and its arguments
161                Method method = loadMethod(methodName, arguments);
162
163                return method.invoke(this, arguments);
164        }
165
166        private Method loadMethod(String methodName, Object[] args) throws NoSuchMethodException {
167                Method m = null;
168
169                // Obtain the class reference
170                Class<?> clazz = this.getClass();
171                Class<?>[] argArray = null;
172
173                if (args != null) {
174                        argArray = new Class<?>[args.length];
175                        for (int i = 0; i < args.length; i++) {
176                                argArray[i] = args[i].getClass();
177                        }
178                }
179
180                try {
181                        m = clazz.getMethod(methodName, argArray);
182                } catch (NoSuchMethodException nsm) {
183                        m = loadMethodWithPrimitives(methodName, argArray);
184                }
185                return m;
186        }
187
188        private Method loadMethodWithPrimitives(String methodName, Class<?>[] argArray) throws NoSuchMethodException {
189                if (argArray != null) {
190                        Method[] methods = this.getClass().getMethods();
191                        int length = argArray.length;
192
193                        for (Method method : methods) {
194                                String name = method.getName();
195                                int argsLength = method.getParameterTypes().length;
196
197                                if (name.equals(methodName) && length == argsLength) {
198                                        // This array can have primitive types inside
199                                        Class<?>[] params = method.getParameterTypes();
200
201                                        boolean found = true;
202
203                                        for (int i = 0; i < length; i++) {
204                                                if (params[i].isPrimitive()) {
205                                                        Class<?> paramWrapper = primitiveClasses.get(params[i].getName());
206
207                                                        if (!paramWrapper.equals(argArray[i])) {
208                                                                found = false;
209                                                                break;
210                                                        }
211                                                }
212                                        }
213                                        if (found) {
214                                                return method;
215                                        }
216                                }
217                        }
218                }
219                throw new NoSuchMethodException(methodName);
220        }
221
222        public List<Class<?>> getParams(String methodName) {
223                return params.get(methodName);
224        }
225
226        public Channel getChannel() {
227                return channel;
228        }
229
230        private void startQueues() throws Exception {
231                // Get info about which exchange and queue will use
232                String exchange = env.getProperty(ParameterQueue.RPC_EXCHANGE);
233                String queue = UID;
234                String routingKey = UID;
235                // Multi info
236                String multiExchange = multi + exchange;
237
238                boolean durable = Boolean.parseBoolean(env.getProperty(ParameterQueue.DURABLE_QUEUES, "false"));
239
240                // Start channel
241                channel = broker.getNewChannel();
242
243                // Declares and bindings
244                logger.info("RemoteObject: " + UID + " declaring direct exchange: " + exchange + ", Queue: " + queue);
245                channel.exchangeDeclare(exchange, "direct");
246                channel.queueDeclare(queue, durable, false, false, null);
247                channel.queueBind(queue, exchange, routingKey);
248
249                channel.exchangeDeclare(multiExchange, "fanout");
250                channel.queueDeclare(multiQueue, durable, false, false, null);
251                channel.queueBind(multiQueue, multiExchange, "");
252
253                // Declare the event topic fanout
254                logger.info("RemoteObject: " + UID + " declaring fanout exchange: " + UID);
255                channel.exchangeDeclare(UID, "fanout");
256
257                // Declare a new consumer
258                consumer = new QueueingConsumer(channel);
259                channel.basicConsume(queue, true, consumer);
260                channel.basicConsume(multiQueue, true, consumer);
261        }
262
263        @Override
264        public void addListener(EventListener<?> eventListener) throws Exception {
265        }
266
267        @Override
268        public void removeListener(EventListener<?> eventListener) throws Exception {
269        }
270
271        @Override
272        public Collection<EventListener<?>> getListeners() throws Exception {
273                return null;
274        }
275
276}
Note: See TracBrowser for help on using the repository browser.