List of usage examples for javax.jms MessageListener MessageListener
MessageListener
From source file:org.apache.axis2.transport.jms.MockEchoEndpoint.java
@Setup @SuppressWarnings("unused") private void setUp(JMSTestEnvironment env, JMSRequestResponseChannel channel) throws Exception { Destination destination = channel.getDestination(); Destination replyDestination = channel.getReplyDestination(); connection = env.getConnectionFactory().createConnection(); connection.setExceptionListener(this); connection.start();/*w ww.j a v a2s .c o m*/ replyConnection = env.getConnectionFactory().createConnection(); replyConnection.setExceptionListener(this); final Session replySession = replyConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageProducer producer = replySession.createProducer(replyDestination); MessageConsumer consumer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE) .createConsumer(destination); consumer.setMessageListener(new MessageListener() { public void onMessage(Message message) { try { log.info("Message received: ID = " + message.getJMSMessageID()); Message reply; if (message instanceof BytesMessage) { reply = replySession.createBytesMessage(); IOUtils.copy(new BytesMessageInputStream((BytesMessage) message), new BytesMessageOutputStream((BytesMessage) reply)); } else if (message instanceof TextMessage) { reply = replySession.createTextMessage(); ((TextMessage) reply).setText(((TextMessage) message).getText()); } else { // TODO throw new UnsupportedOperationException("Unsupported message type"); } reply.setJMSCorrelationID(message.getJMSMessageID()); reply.setStringProperty(BaseConstants.CONTENT_TYPE, message.getStringProperty(BaseConstants.CONTENT_TYPE)); producer.send(reply); log.info("Message sent: ID = " + reply.getJMSMessageID()); } catch (Throwable ex) { fireEndpointError(ex); } } }); }
From source file:org.apache.servicemix.audit.async.AbstractJmsExchangeListener.java
public void afterPropertiesSet() throws Exception { if (factory == null) { throw new IllegalStateException( "Unable to initialize JMS ExchangeListener -- no ConnectionFactory set"); }/*from w ww.jav a 2s . c o m*/ container = new DefaultMessageListenerContainer(); container.setConnectionFactory(factory); container.setDestinationName(getDestinationName()); container.setMessageListener(new MessageListener() { @SuppressWarnings("unchecked") public void onMessage(Message message) { ObjectMessage om = (ObjectMessage) message; try { T object = (T) om.getObject(); switch (Event.valueOf(om.getStringProperty(EVENT))) { case Sent: onSent(object); case Accepted: onAccepted(object); } } catch (JMSException e) { e.printStackTrace(); } } }); container.afterPropertiesSet(); container.setConcurrentConsumers(10); container.start(); jmsTemplate = new JmsTemplate(factory); jmsTemplate.setDefaultDestinationName(getDestinationName()); }
From source file:drepcap.frontend.jms.JmsAdapter.java
/** * /*from w w w . j a v a2 s. c o m*/ * Components are typically pcap-sensors or packet-mergers. The component * name is the name without any additional suffix, e.g., * "pcap.single.raw.2". * * @param connection * @param componentName * @throws JMSException */ public JmsAdapter(Connection connection, String componentName) throws JMSException { this.componentName = componentName; this.connection = connection; session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); commandTopic = session.createTopic(componentName + ".command"); commandConsumer = session.createConsumer(commandTopic); commandConsumer.setMessageListener(new MessageListener() { @Override public void onMessage(Message msg) { if (msg instanceof TextMessage) { TextMessage textMsg = (TextMessage) msg; try { final String txt = textMsg.getText(); for (StringReceiver cmdReplyReceiver : commandReplyReceivers) { if (cmdReplyReceiver != null && txt.startsWith("reply")) { cmdReplyReceiver.process(txt.replaceFirst("reply ", "")); } } } catch (JMSException e) { e.printStackTrace(); } } } }); commandProducer = session.createProducer(commandTopic); monitorTopic = session.createTopic(componentName + ".monitor"); monitorConsumer = session.createConsumer(monitorTopic); monitorConsumer.setMessageListener(new MessageListener() { @Override public void onMessage(Message msg) { if (msg instanceof TextMessage) { TextMessage textMsg = (TextMessage) msg; try { final String txt = textMsg.getText(); for (StringReceiver monReceiver : monitorReceivers) { if (monReceiver != null) { monReceiver.process(txt); } } if (statsDataReceivers.size() > 0) { processStatsFromString(txt); } } catch (JMSException e) { e.printStackTrace(); } } } }); }
From source file:eu.eubrazilcc.lvl.storage.security.shiro.BaseAuthorizingRealm.java
public BaseAuthorizingRealm(final CredentialsMatcher credentialsMatcher, final String identityProvider) { super(CACHE_MANAGER, credentialsMatcher); // enable authentication caching setAuthenticationCachingEnabled(true); // subscribe to changes in users' permissions ACTIVEMQ_CONN.subscribe(permissionChangedTopic(identityProvider), new MessageListener() { @Override/* w ww .j a v a 2s . com*/ public void onMessage(final Message message) { if (message instanceof TextMessage) { final TextMessage textMessage = (TextMessage) message; try { final String ownerId = textMessage.getText(); clearCache(new SimplePrincipalCollection(ownerId, getName())); LOGGER.trace( getName() + " - Cached authorization info was evicted for account: " + ownerId); } catch (JMSException e) { LOGGER.error(getName() + " - Failed to read message", e); } } } }); }
From source file:org.apache.activemq.usecases.DurableSubscriberWithNetworkDisconnectTest.java
public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception { bridgeBrokers(SPOKE, HUB);/*from w w w .ja v a 2s . co m*/ startAllBrokers(); // Setup connection URI hubURI = brokers.get(HUB).broker.getVmConnectorURI(); URI spokeURI = brokers.get(SPOKE).broker.getVmConnectorURI(); ActiveMQConnectionFactory facHub = new ActiveMQConnectionFactory(hubURI); ActiveMQConnectionFactory facSpoke = new ActiveMQConnectionFactory(spokeURI); Connection conHub = facHub.createConnection(); Connection conSpoke = facSpoke.createConnection(); conHub.setClientID("clientHUB"); conSpoke.setClientID("clientSPOKE"); conHub.start(); conSpoke.start(); Session sesHub = conHub.createSession(false, Session.AUTO_ACKNOWLEDGE); Session sesSpoke = conSpoke.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQTopic topic = new ActiveMQTopic("TEST.FOO"); String consumerName = "consumerName"; // Setup consumers MessageConsumer remoteConsumer = sesSpoke.createDurableSubscriber(topic, consumerName); remoteConsumer.setMessageListener(new MessageListener() { public void onMessage(Message msg) { try { TextMessage textMsg = (TextMessage) msg; receivedMsgs++; LOG.info("Received messages (" + receivedMsgs + "): " + textMsg.getText()); } catch (JMSException e) { e.printStackTrace(); } } }); // allow subscription information to flow back to Spoke sleep(1000); // Setup producer MessageProducer localProducer = sesHub.createProducer(topic); localProducer.setDeliveryMode(DeliveryMode.PERSISTENT); // Send messages for (int i = 0; i < MESSAGE_COUNT; i++) { sleep(50); if (i == 50 || i == 150) { if (simulateStalledNetwork) { socketProxy.pause(); } else { socketProxy.close(); } networkDownTimeStart = System.currentTimeMillis(); } else if (networkDownTimeStart > 0) { // restart after NETWORK_DOWN_TIME seconds sleep(NETWORK_DOWN_TIME); networkDownTimeStart = 0; if (simulateStalledNetwork) { socketProxy.goOn(); } else { socketProxy.reopen(); } } else { // slow message production to allow bridge to recover and limit message duplication sleep(500); } Message test = sesHub.createTextMessage("test-" + i); localProducer.send(test); } LOG.info("waiting for messages to flow"); Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { return receivedMsgs >= MESSAGE_COUNT; } }); assertTrue("At least message " + MESSAGE_COUNT + " must be received, count=" + receivedMsgs, MESSAGE_COUNT <= receivedMsgs); brokers.get(HUB).broker.deleteAllMessages(); brokers.get(SPOKE).broker.deleteAllMessages(); conHub.close(); conSpoke.close(); }
From source file:net.blogracy.controller.DistributedHashTable.java
public void lookup(final String id) { try {/*from ww w . j av a2 s . c o m*/ Destination tempDest = session.createTemporaryQueue(); MessageConsumer responseConsumer = session.createConsumer(tempDest); responseConsumer.setMessageListener(new MessageListener() { @Override public void onMessage(Message response) { try { String msgText = ((TextMessage) response).getText(); JSONObject keyValue = new JSONObject(msgText); String value = keyValue.getString("value"); PublicKey signerKey = JsonWebSignature.getSignerKey(value); JSONObject record = new JSONObject(JsonWebSignature.verify(value, signerKey)); JSONObject currentRecord = getRecord(id); if (currentRecord == null || currentRecord.getString("version").compareTo(record.getString("version")) < 0) { putRecord(record); String uri = record.getString("uri"); FileSharing.getSingleton().download(uri); } } catch (Exception e) { e.printStackTrace(); } } }); JSONObject record = new JSONObject(); record.put("id", id); TextMessage message = session.createTextMessage(); message.setText(record.toString()); message.setJMSReplyTo(tempDest); producer.send(lookupQueue, message); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.apache.servicemix.jms.endpoints.JmsJcaConsumerEndpoint.java
public synchronized void start() throws Exception { if (bootstrapContext == null) { Executor executor = getServiceUnit().getComponent().getExecutor(); WorkManager wm = new WorkManagerWrapper(executor); bootstrapContext = new SimpleBootstrapContext(wm); }// w w w . j a v a 2 s .c o m resourceAdapter.start(bootstrapContext); activationSpec.setResourceAdapter(resourceAdapter); if (endpointFactory == null) { TransactionManager tm = (TransactionManager) getContext().getTransactionManager(); endpointFactory = new SingletonEndpointFactory(new MessageListener() { public void onMessage(Message message) { try { JmsJcaConsumerEndpoint.this.onMessage(message, null); } catch (JMSException e) { throw new ListenerExecutionFailedException("Unable to handle message", e); } } }, tm); } resourceAdapter.endpointActivation(endpointFactory, activationSpec); super.start(); }
From source file:org.eclipse.scanning.event.SubscriberImpl.java
private MessageConsumer createConsumer(final String topicName, final Class<?> beanClass) throws JMSException { Topic topic = super.createTopic(topicName); final MessageConsumer consumer = session.createConsumer(topic); MessageListener listener = new MessageListener() { public void onMessage(Message message) { TextMessage txt = (TextMessage) message; try { String json = txt.getText(); json = JsonUtil.removeProperties(json, properties); try { Object bean = service.unmarshal(json, beanClass); schedule(new DiseminateEvent(bean)); } catch (Exception ne) { logger.error("Error processing message {} on topic {} with beanClass {}", message, topicName, beanClass, ne); ne.printStackTrace(); // Unit tests without log4j config show this one. }// w w w . ja va 2 s . c o m } catch (JMSException ne) { logger.error("Cannot get text from message " + txt, ne); } } }; consumer.setMessageListener(listener); return consumer; }
From source file:org.wso2.mb.integration.tests.amqp.functional.JMSRoutingKeyPropertyTestCase.java
/** * Publishes few messages to a queue with setting "AndesSetRoutingKey" system property set to non-null value and * check the correct routing key comes as a JMS property for each message. * * @throws AndesClientConfigurationException * @throws XPathExpressionException/*from w w w. j a v a 2 s . c o m*/ * @throws IOException * @throws JMSException * @throws AndesClientException * @throws NamingException */ @Test(groups = { "wso2.mb", "queue" }) public void queueRoutingKeyPropertyTestCase() throws AndesClientConfigurationException, XPathExpressionException, IOException, JMSException, AndesClientException, NamingException { System.setProperty(AndesClientConstants.ANDES_SET_ROUTING_KEY, "1"); long sendCount = 10; final List<Message> messages = new ArrayList<>(); // Creating a consumer client configuration AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(), ExchangeType.QUEUE, "RoutingKeyPropertyQueue"); consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.AUTO_ACKNOWLEDGE); consumerConfig.setAsync(false); // Creating a publisher client configuration AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration( getAMQPPort(), ExchangeType.QUEUE, "RoutingKeyPropertyQueue"); publisherConfig.setNumberOfMessagesToSend(sendCount); // Creating clients AndesClient consumerClient = new AndesClient(consumerConfig, true); final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0); MessageConsumer receiver = andesJMSConsumer.getReceiver(); receiver.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { messages.add(message); } }); AndesClient publisherClient = new AndesClient(publisherConfig, true); AndesJMSPublisher andesJMSPublisher = publisherClient.getPublishers().get(0); MessageProducer sender = andesJMSPublisher.getSender(); for (int i = 0; i < sendCount; i++) { TextMessage textMessage = andesJMSPublisher.getSession().createTextMessage("#" + Integer.toString(i)); sender.send(textMessage); } AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME); for (Message message : messages) { Assert.assertEquals( message.getStringProperty(AndesClientConstants.JMS_ANDES_ROUTING_KEY_MESSAGE_PROPERTY), "RoutingKeyPropertyQueue", "Invalid value received for " + "routing key property."); } }
From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java
public void setInstructionListener(final Client client) { try {//from ww w . ja v a2 s . c om _instructionQueue = _controllerSession.createTemporaryQueue(); final MessageConsumer instructionConsumer = _controllerSession.createConsumer(_instructionQueue); instructionConsumer.setMessageListener(new MessageListener() { @Override public void onMessage(final Message message) { client.processInstruction(JmsMessageAdaptor.messageToCommand(message)); } }); } catch (final JMSException jmse) { throw new DistributedTestException("Unable to setup instruction listener", jmse); } }