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

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

log4j added

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