Skip to main content
summaryrefslogtreecommitdiffstats
blob: 89414e8124c96c400d394202b54207e4f46b439f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/*******************************************************************************
 * Copyright (c) 2010 Boeing.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Boeing - initial API and implementation
 *******************************************************************************/
package org.eclipse.osee.framework.messaging.internal.activemq;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.logging.Level;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TemporaryTopic;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.eclipse.osee.framework.core.exception.OseeCoreException;
import org.eclipse.osee.framework.core.exception.OseeWrappedException;
import org.eclipse.osee.framework.jdk.core.type.CompositeKeyHashMap;
import org.eclipse.osee.framework.jdk.core.type.Pair;
import org.eclipse.osee.framework.logging.OseeLog;
import org.eclipse.osee.framework.messaging.ConnectionListener;
import org.eclipse.osee.framework.messaging.ConnectionNodeFailoverSupport;
import org.eclipse.osee.framework.messaging.MessageID;
import org.eclipse.osee.framework.messaging.NodeInfo;
import org.eclipse.osee.framework.messaging.OseeMessagingListener;
import org.eclipse.osee.framework.messaging.OseeMessagingStatusCallback;
import org.eclipse.osee.framework.messaging.internal.Activator;
import org.eclipse.osee.framework.messaging.services.internal.OseeMessagingStatusImpl;

/**
 * @author Andrew M. Finkbeiner
 */
class ConnectionNodeActiveMq implements ConnectionNodeFailoverSupport, MessageListener {

   //   private String version;
   //   private String sourceId;
   private NodeInfo nodeInfo;
   //   private ExecutorService executor;
   private Connection connection;
   private Session session;
   private TemporaryTopic temporaryTopic;
   private MessageConsumer replyToConsumer;
   private Map<String, OseeMessagingListener> replyListeners;
   private CompositeKeyHashMap<String, MessageConsumer, OseeMessagingListener> regularListeners;
   private boolean started = false;

   private ConcurrentHashMap<String, Topic> topicCache;
   private ConcurrentHashMap<Topic, MessageProducer> messageProducerCache;
   private final ExceptionListener exceptionListener;

   private MessageProducer replyProducer;
   private ActiveMqUtil activeMqUtil;

   public ConnectionNodeActiveMq(String version, String sourceId, NodeInfo nodeInfo, ExecutorService executor, ExceptionListener exceptionListener) {
      this.nodeInfo = nodeInfo;
      this.exceptionListener = exceptionListener;
      activeMqUtil = new ActiveMqUtil();
      topicCache = new ConcurrentHashMap<String, Topic>();
      messageProducerCache = new ConcurrentHashMap<Topic, MessageProducer>();
      regularListeners = new CompositeKeyHashMap<String, MessageConsumer, OseeMessagingListener>(64, true);
      replyListeners = new ConcurrentHashMap<String, OseeMessagingListener>();
   }

   public synchronized void start() throws OseeCoreException {
      if (started) {
         return;
      }
      try {
         String uri = nodeInfo.getUri().toASCIIString();
         ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER, ActiveMQConnectionFactory.DEFAULT_PASSWORD, uri);
         connection = factory.createConnection();
         connection.setExceptionListener(exceptionListener);
         session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
         temporaryTopic = session.createTemporaryTopic();
         replyToConsumer = session.createConsumer(temporaryTopic);
         replyToConsumer.setMessageListener(this);
         replyProducer = session.createProducer(null);
         connection.start();
         started = true;
      } catch (Throwable ex) {
         throw new OseeWrappedException(ex);
      }
   }

   @Override
   public void send(MessageID topic, Object body) throws OseeCoreException {
      String errorMessage = String.format("Error sending message(%s)", topic.getId());
      OseeMessagingStatusImpl defaultErrorHandler = new OseeMessagingStatusImpl(errorMessage, getClass());
      this.send(topic, body, defaultErrorHandler);
   }
   
   @Override
   public synchronized void send(MessageID messageId, Object message, OseeMessagingStatusCallback statusCallback) throws OseeCoreException {
      send(messageId, message, null, statusCallback);
   }
   
   @Override
   public synchronized void send(MessageID messageId, Object message, Properties properties, OseeMessagingStatusCallback statusCallback) throws OseeCoreException {
      try {
         if (messageId.isTopic()) {
            try{
               sendInternal(messageId, message, properties, statusCallback);
            } catch (JMSException ex){
               removeProducerFromCache(messageId);
               sendInternal(messageId, message, properties, statusCallback);
            }
         //   OseeLog.log(Activator.class, Level.FINE, String.format("Sending message %s - %s", topic.getName(), topic.getGuid()));
            statusCallback.success();
         }
      } catch (JMSException ex) {
         statusCallback.fail(ex);
         throw new OseeWrappedException(ex);
      } catch (NullPointerException ex) {
         statusCallback.fail(ex);
         throw new OseeWrappedException(ex);
      }
   }
   
	private synchronized void sendInternal(MessageID messageId, Object message, Properties properties, OseeMessagingStatusCallback statusCallback) throws JMSException, OseeCoreException {
		Topic destination = getOrCreateTopic(messageId);
		MessageProducer producer = getOrCreateProducer(destination);
		Message msg = activeMqUtil.createMessage(session, messageId.getSerializationClass(), message);
		if (messageId.isReplyRequired()) {
			msg.setJMSReplyTo(temporaryTopic);
		}
		if(properties != null){
		   for(Entry<Object, Object> entry:properties.entrySet()){
		      if(entry.getValue() instanceof Integer){
		         msg.setIntProperty(entry.getKey().toString(), (Integer)entry.getValue());
		      } if(entry.getValue() instanceof Boolean){
		         msg.setBooleanProperty(entry.getKey().toString(), (Boolean)entry.getValue());
            } if(entry.getValue() instanceof Byte){
               msg.setByteProperty(entry.getKey().toString(), (Byte)entry.getValue());
            } if(entry.getValue() instanceof Double){
               msg.setDoubleProperty(entry.getKey().toString(), (Double)entry.getValue());
            } if(entry.getValue() instanceof Float){
               msg.setFloatProperty(entry.getKey().toString(), (Float)entry.getValue());
            } if(entry.getValue() instanceof Long){
               msg.setLongProperty(entry.getKey().toString(), (Long)entry.getValue());
            } if(entry.getValue() instanceof String){
               msg.setStringProperty(entry.getKey().toString(), (String)entry.getValue());
            } if(entry.getValue() instanceof Short){
               msg.setShortProperty(entry.getKey().toString(), (Short)entry.getValue());
            } else {
		         msg.setObjectProperty(entry.getKey().toString(), entry.getValue());
		      }
		   }
		}
		producer.send(msg);
//		OseeLog.log(Activator.class, Level.FINE, String.format("Sending message %s - %s", topic.getName(), topic.getGuid()));
		statusCallback.success();
	}

   @Override
   public synchronized void subscribe(MessageID messageId, OseeMessagingListener listener, OseeMessagingStatusCallback statusCallback) {
      Topic destination;
      try {
         if (isConnectedThrow()) {
            destination = getOrCreateTopic(messageId);
            MessageConsumer consumer = session.createConsumer(destination);
            consumer.setMessageListener(new ActiveMqMessageListenerWrapper(activeMqUtil, replyProducer, session, listener));
            regularListeners.put(messageId.getId(), consumer, listener);
            statusCallback.success();
         } else {
            statusCallback.fail(new OseeCoreException("This connection is not started."));
         }
      } catch (JMSException ex) {
         statusCallback.fail(ex);
      } catch (NullPointerException ex) {
         statusCallback.fail(ex);
      }
   }
   
   @Override
   public void subscribe(MessageID messageId, OseeMessagingListener listener, String selector, OseeMessagingStatusCallback statusCallback) {
      Topic destination;
      try {
         if (isConnectedThrow()) {
            destination = getOrCreateTopic(messageId);
            MessageConsumer consumer = session.createConsumer(destination, selector);
            consumer.setMessageListener(new ActiveMqMessageListenerWrapper(activeMqUtil, replyProducer, session, listener));
            regularListeners.put(messageId.getId(), consumer, listener);
            statusCallback.success();
         } else {
            statusCallback.fail(new OseeCoreException("This connection is not started."));
         }
      } catch (JMSException ex) {
         statusCallback.fail(ex);
      } catch (NullPointerException ex) {
         statusCallback.fail(ex);
      }
   }
   
   @Override
   public void subscribe(MessageID messageId, OseeMessagingListener listener) {
      String errorMessage = String.format("Error subscribing message(%s)", messageId.getId());
      OseeMessagingStatusImpl defaultErrorHandler = new OseeMessagingStatusImpl(errorMessage, getClass());
      this.subscribe(messageId, listener, defaultErrorHandler);
   }

   private Topic getOrCreateTopic(MessageID messageId) throws JMSException {
      Topic topic = topicCache.get(messageId.getId());
      if (topic == null) {
         topic = session.createTopic(messageId.getId());
         topicCache.put(messageId.getId(), topic);
      }
      return topic;
   }

   private MessageProducer getOrCreateProducer(Topic destination) throws JMSException {
      MessageProducer producer = messageProducerCache.get(destination);
      if (producer == null) {
         producer = session.createProducer(destination);
         producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
         messageProducerCache.put(destination, producer);
      }
      return producer;
   }
   
   private void removeProducerFromCache(MessageID topic) throws JMSException{
	   Topic destination = getOrCreateTopic(topic);
	   messageProducerCache.remove(destination);
   }

   @Override
   public boolean subscribeToReply(MessageID messageId, OseeMessagingListener listener) {
      replyListeners.put(messageId.getId(), listener);
      return true;
   }
   
   @Override
   public void unsubscribe(MessageID messageId, OseeMessagingListener listener) {
      String errorMessage = String.format("Error unsubscribing message(%s)", messageId.getId());
      OseeMessagingStatusImpl defaultErrorHandler = new OseeMessagingStatusImpl(errorMessage, getClass());
      this.unsubscribe(messageId, listener, defaultErrorHandler);
   }

   @Override
   public void unsubscribe(MessageID messageId, OseeMessagingListener listener, OseeMessagingStatusCallback statusCallback) {
      Map<MessageConsumer, OseeMessagingListener> listeners = regularListeners.getKeyedValues(messageId.getId());
      List<MessageConsumer> consumersToRemove = new ArrayList<MessageConsumer>();
      if (listeners != null) {
         try{ 
            for(Entry<MessageConsumer, OseeMessagingListener> entry:listeners.entrySet()){
               if(entry.getValue().equals(listener)){
                  entry.getKey().setMessageListener(null);
                  consumersToRemove.add(entry.getKey());
               }
            }
            for(MessageConsumer messageConsumer: consumersToRemove){
            	messageConsumer.setMessageListener(null);
               	messageConsumer.close();
            }
         }catch (JMSException ex) {
            statusCallback.fail(ex);
         }
      }
      statusCallback.success();
   }

   @Override
   public boolean unsubscribteToReply(MessageID messageId, OseeMessagingListener listener) {
      replyListeners.remove(messageId.getId());
      return true;
   }

   @Override
   public void onMessage(Message jmsMessage) {
      try {
         String correlationId = jmsMessage.getJMSCorrelationID();
         if (correlationId != null) {
            OseeMessagingListener listener = replyListeners.get(correlationId);
            if (listener != null) {
               listener.process(activeMqUtil.translateMessage(jmsMessage, listener.getClazz()), new HashMap<String, Object>(), new ReplyConnectionActiveMqImpl());
            }
         }
      } catch (JMSException ex) {
         OseeLog.log(ConnectionNodeActiveMq.class, Level.SEVERE, ex);
      } catch (OseeCoreException ex) {
         OseeLog.log(ConnectionNodeActiveMq.class, Level.SEVERE, ex);
      }
      OseeLog.log(Activator.class, Level.FINE, String.format("recieved reply message %s", jmsMessage.toString()));
   }

   @Override
   public synchronized void stop() {
	  topicCache.clear();
	  messageProducerCache.clear();
	  regularListeners.clear();
      try {
         if (session != null) {
            session.close();
            session = null;
         }
      } catch (JMSException ex) {
         OseeLog.log(ConnectionNodeActiveMq.class, Level.SEVERE, ex);
      }
      try {
         if (connection != null) {
            connection.close();
            connection = null;
         }
      } catch (JMSException ex) {
         OseeLog.log(ConnectionNodeActiveMq.class, Level.SEVERE, ex);
      }
   }

   @Override
   public synchronized boolean isConnected() {
      try {
         return isConnectedThrow();
      } catch (JMSException ex) {
         started = false;
         return false;
      }
   }

   private synchronized boolean isConnectedThrow() throws JMSException {
      if (connection == null || started == false) {
         return false;
      }
      connection.getMetaData();
      session.createProducer(session.createTopic("mytest"));
      return true;
   }

   @Override
   public void addConnectionListener(ConnectionListener connectionListener) {
   }

   @Override
   public void removeConnectionListener(ConnectionListener connectionListener) {
   }
   
   
   @Override
   public String getSenders() {
      StringBuilder sb = new StringBuilder();
      for(Entry<Topic, MessageProducer> entry:this.messageProducerCache.entrySet()){
         try {
            sb.append(String.format("Topic [%s] \n", entry.getKey().getTopicName()));
            sb.append(String.format("\tProducer Destination [%s]\n", entry.getValue().getDestination().toString()));
         } catch (JMSException ex) {
            OseeLog.log(Activator.class, Level.SEVERE, ex);
         }
      }
      return sb.toString();
   }

   @Override
   public String getSubscribers() {
      StringBuilder sb = new StringBuilder();
      for(Pair<String, MessageConsumer> entry:this.regularListeners.keySet()){
         try {
            sb.append(String.format("Topic [%s] \n", entry.getFirst()));
            sb.append(String.format("\tConsumer Selector [%s]\n", entry.getSecond().getMessageSelector()));
            MessageListener listener = entry.getSecond().getMessageListener();
            if(listener instanceof ActiveMqMessageListenerWrapper){
               sb.append("\tConsumer Listeners:\n");   
               sb.append(String.format("\t\t%s\n", ((ActiveMqMessageListenerWrapper)listener).getListener().toString()));   
            }
         } catch (JMSException ex) {
            OseeLog.log(Activator.class, Level.SEVERE, ex);
         }
      }
      return sb.toString();
   }

   @Override
   public String getSummary() {
      StringBuilder sb = new StringBuilder();
      sb.append(nodeInfo.toString());
      sb.append("\n");
      sb.append(String.format("\tisStarted[%b]\n", started));
      sb.append(getSenders());
      sb.append(getSubscribers());
      return sb.toString();
   }

}

Back to the top