List of usage examples for javax.jms Session createConsumer
MessageConsumer createConsumer(Destination destination) throws JMSException;
From source file:org.dawnsci.commandserver.core.process.ProgressableProcess.java
/** * Starts a connection which listens to the topic and if * a cancel is found published, tries to terminate the subprocess. * /*from w w w .ja v a 2 s . c om*/ * @param p */ protected void createTerminateListener() throws Exception { ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri); ProgressableProcess.this.topicConnection = connectionFactory.createConnection(); topicConnection.start(); Session session = topicConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); final Topic topic = session.createTopic(statusTName); final MessageConsumer consumer = session.createConsumer(topic); final Class clazz = bean.getClass(); final ObjectMapper mapper = new ObjectMapper(); MessageListener listener = new MessageListener() { public void onMessage(Message message) { try { if (message instanceof TextMessage) { TextMessage t = (TextMessage) message; final StatusBean tbean = mapper.readValue(t.getText(), clazz); if (bean.getStatus().isFinal()) { // Something else already happened topicConnection.close(); return; } if (bean.getUniqueId().equals(tbean.getUniqueId())) { if (tbean.getStatus() == Status.REQUEST_TERMINATE) { bean.merge(tbean); out.println("Terminating job '" + tbean.getName() + "'"); terminate(); topicConnection.close(); bean.setStatus(Status.TERMINATED); bean.setMessage("Foricibly terminated before finishing."); broadcast(bean); return; } } } } catch (Exception e) { e.printStackTrace(); } } }; consumer.setMessageListener(listener); }
From source file:com.fusesource.forge.jmstest.tests.AsyncProducer.java
public void run() { try {/* w w w .j a v a2 s. c om*/ Connection conn = getConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); if (isExpectReply()) { Destination replyTo = getDestinationProvider().getDestination(session, getReplyDestination()); MessageConsumer consumer = session.createConsumer(replyTo); consumer.setMessageListener(this); } Destination dest = getDestinationProvider().getDestination(session, getDestinationName()); MessageProducer producer = session.createProducer(dest); producer.setDeliveryMode(getDeliveryMode().getCode()); getConnection().start(); LOG.info(">>Starting Message send loop"); while (!done.get()) { try { locallySent++; Destination replyDest = null; Message msg = getMessageFactory().createMessage(session); if (getMsgGroup() != null) { LOG.debug("Setting message group to : " + getMsgGroup()); msg.setStringProperty("JMSXGroupID", getMsgGroup()); if (getMessagesToSend() > 0) { if (locallySent == getMessagesToSend()) { LOG.debug("Closing message group: " + getMsgGroup()); msg.setIntProperty("JMSXGroupSeq", 0); } } } msg.setLongProperty("MsgNr", locallySent); if (isExpectReply()) { corrId = getReplyDestination() + "Seq-" + locallySent; msg.setStringProperty("JMSCorrelationID", corrId); replyDest = getDestinationProvider().getDestination(session, getReplyDestination()); msg.setJMSReplyTo(replyDest); receivedResponse = false; } long sendTime = System.currentTimeMillis(); producer.send(msg, deliveryMode.getCode(), 4, ttl); if (sent != null) { sent.incrementAndGet(); } done.set((getMessagesToSend() > 0) && ((locallySent) == getMessagesToSend())); if (isExpectReply()) { try { LOG.debug("Waiting for response ..."); synchronized (corrId) { try { if (getReplyTimeOut() > 0) { corrId.wait(getReplyTimeOut()); } else { corrId.wait(); } } catch (InterruptedException ie) { } if (receivedResponse) { long duration = System.currentTimeMillis() - sendTime; LOG.debug("Got response from peer in " + duration + " ms"); } else { LOG.error("Response not received within time frame..."); if (timeOuts != null) { timeOuts.incrementAndGet(); } } } } catch (Exception e) { if (exceptions != null) { exceptions.incrementAndGet(); } } } if (sleep > 0L) { try { Thread.sleep(sleep); } catch (InterruptedException ie) { } } } catch (JMSException e) { if (exceptions != null) { exceptions.incrementAndGet(); } } } } catch (Exception e) { } finally { try { closeConnection(); } catch (Throwable e) { } } LOG.info(">>MessageSender done...(" + sent + ")"); }
From source file:org.dawnsci.commandserver.ui.view.ConsumerView.java
/** * Listens to a topic// w w w . j av a 2 s. c om */ private void createTopicListener(final URI uri) throws Exception { // Use job because connection might timeout. final Job topicJob = new Job("Create topic listener") { @Override protected IStatus run(IProgressMonitor monitor) { try { ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri); topicConnection = connectionFactory.createConnection(); topicConnection.start(); Session session = topicConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); final Topic topic = session.createTopic(Constants.ALIVE_TOPIC); final MessageConsumer consumer = session.createConsumer(topic); final ObjectMapper mapper = new ObjectMapper(); MessageListener listener = new MessageListener() { public void onMessage(Message message) { try { if (message instanceof TextMessage) { TextMessage t = (TextMessage) message; final ConsumerBean bean = mapper.readValue(t.getText(), ConsumerBean.class); bean.setLastAlive(System.currentTimeMillis()); consumers.put(bean.getConsumerId(), bean); } } catch (Exception e) { logger.error("Updating changed bean from topic", e); } } }; consumer.setMessageListener(listener); return Status.OK_STATUS; } catch (Exception ne) { logger.error("Cannot listen to topic changes because command server is not there", ne); return Status.CANCEL_STATUS; } } }; topicJob.setPriority(Job.INTERACTIVE); topicJob.setSystem(true); topicJob.setUser(false); topicJob.schedule(); }
From source file:org.openengsb.ports.jms.JMSPortTest.java
private String sendWithTempQueue(final String msg) { String resultString = jmsTemplate.execute(new SessionCallback<String>() { @Override/*from ww w . j a v a 2 s .co m*/ public String doInJms(Session session) throws JMSException { Queue queue = session.createQueue("receive"); MessageProducer producer = session.createProducer(queue); TemporaryQueue tempQueue = session.createTemporaryQueue(); MessageConsumer consumer = session.createConsumer(tempQueue); TextMessage message = session.createTextMessage(msg); message.setJMSReplyTo(tempQueue); producer.send(message); TextMessage response = (TextMessage) consumer.receive(10000); assertThat( "server should set the value of the correltion ID to the value of the received message id", response.getJMSCorrelationID(), is(message.getJMSMessageID())); JmsUtils.closeMessageProducer(producer); JmsUtils.closeMessageConsumer(consumer); return response != null ? response.getText() : null; } }, true); return resultString; }
From source file:org.sakaiproject.kernel.email.outgoing.OutgoingEmailMessageListener.java
protected void activate(ComponentContext ctx) { @SuppressWarnings("unchecked") Dictionary props = ctx.getProperties(); Integer _maxRetries = (Integer) props.get(MAX_RETRIES); if (_maxRetries != null) { if (diff(maxRetries, _maxRetries)) { maxRetries = _maxRetries;/* w w w . j av a 2 s .c om*/ } } else { LOGGER.error("Maximum times to retry messages not set."); } Integer _retryInterval = (Integer) props.get(RETRY_INTERVAL); if (_retryInterval != null) { if (diff(_retryInterval, retryInterval)) { retryInterval = _retryInterval; } } else { LOGGER.error("SMTP retry interval not set."); } if (maxRetries * retryInterval < 4320 /* minutes in 3 days */) { LOGGER.warn("SMTP retry window is very short."); } Integer _smtpPort = (Integer) props.get(SMTP_PORT); boolean validPort = _smtpPort != null && _smtpPort >= 0 && _smtpPort <= 65535; if (validPort) { if (diff(smtpPort, _smtpPort)) { smtpPort = _smtpPort; } } else { LOGGER.error("Invalid port set for SMTP"); } String _smtpServer = (String) props.get(SMTP_SERVER); boolean smtpServerEmpty = _smtpServer == null || _smtpServer.trim().length() == 0; if (!smtpServerEmpty) { if (diff(smtpServer, _smtpServer)) { smtpServer = _smtpServer; } } else { LOGGER.error("No SMTP server set"); } String _brokerUrl = (String) props.get(BROKER_URL); try { boolean urlEmpty = _brokerUrl == null || _brokerUrl.trim().length() == 0; if (!urlEmpty) { if (diff(brokerUrl, _brokerUrl)) { LOGGER.info("Creating a new ActiveMQ Connection Factory"); connectionFactory = connFactoryService.createFactory(_brokerUrl); } if (connectionFactory != null) { connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic dest = session.createTopic(TOPIC_NAME); MessageConsumer consumer = session.createConsumer(dest); consumer.setMessageListener(this); connection.start(); } } else { LOGGER.error("Cannot create JMS connection factory with an empty URL."); } brokerUrl = _brokerUrl; } catch (JMSException e) { LOGGER.error(e.getMessage(), e); if (connection != null) { try { connection.close(); } catch (JMSException e1) { } } } }
From source file:org.sakaiproject.nakamura.email.outgoing.OutgoingEmailMessageListener.java
protected void activate(ComponentContext ctx) { @SuppressWarnings("rawtypes") Dictionary props = ctx.getProperties(); Integer _maxRetries = (Integer) props.get(MAX_RETRIES); if (_maxRetries != null) { if (diff(maxRetries, _maxRetries)) { maxRetries = _maxRetries;//from ww w . java 2 s . c om } } else { LOGGER.error("Maximum times to retry messages not set."); } Integer _retryInterval = (Integer) props.get(RETRY_INTERVAL); if (_retryInterval != null) { if (diff(_retryInterval, retryInterval)) { retryInterval = _retryInterval; } } else { LOGGER.error("SMTP retry interval not set."); } if (maxRetries * retryInterval < 4320 /* minutes in 3 days */) { LOGGER.warn("SMTP retry window is very short."); } Integer _smtpPort = (Integer) props.get(SMTP_PORT); boolean validPort = _smtpPort != null && _smtpPort >= 0 && _smtpPort <= 65535; if (validPort) { if (diff(smtpPort, _smtpPort)) { smtpPort = _smtpPort; } } else { LOGGER.error("Invalid port set for SMTP"); } String _smtpServer = (String) props.get(SMTP_SERVER); boolean smtpServerEmpty = _smtpServer == null || _smtpServer.trim().length() == 0; if (!smtpServerEmpty) { if (diff(smtpServer, _smtpServer)) { smtpServer = _smtpServer; } } else { LOGGER.error("No SMTP server set"); } try { connection = connFactoryService.getDefaultConnectionFactory().createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue dest = session.createQueue(QUEUE_NAME); MessageConsumer consumer = session.createConsumer(dest); consumer.setMessageListener(this); connection.start(); } catch (JMSException e) { LOGGER.error(e.getMessage(), e); if (connection != null) { try { connection.close(); } catch (JMSException e1) { } } } }
From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java
@Test public void testTopicNonPersistentMessageSize() throws Exception { AtomicLong publishedMessageSize = new AtomicLong(); Connection connection = cf.createConnection(); connection.setClientID("clientId"); connection.start();/*from w ww. ja va 2 s. c om*/ Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(session.createTopic(defaultTopicName)); publishTestTopicMessages(200, DeliveryMode.NON_PERSISTENT, publishedMessageSize); verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get()); // consume all messages consumeTestMessages(consumer, 200); // All messages should now be gone verifyPendingStats(defaultTopicName, 0, 0); connection.close(); }
From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java
@Test public void testTopicMessageSize() throws Exception { AtomicLong publishedMessageSize = new AtomicLong(); Connection connection = cf.createConnection(); connection.setClientID("clientId"); connection.start();/* w w w. ja va 2s . c om*/ Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(session.createTopic(defaultTopicName)); publishTestTopicMessages(200, publishedMessageSize); verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get()); verifyPendingDurableStats(defaultQueueName, 0, 0); // consume all messages consumeTestMessages(consumer, 200); // All messages should now be gone verifyPendingStats(defaultTopicName, 0, 0); verifyPendingDurableStats(defaultQueueName, 0, 0); connection.close(); }
From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java
@Test public void testTopicPersistentAndNonPersistentMessageSize() throws Exception { AtomicLong publishedMessageSize = new AtomicLong(); AtomicLong publishedNonPersistentMessageSize = new AtomicLong(); Connection connection = cf.createConnection(); connection.setClientID("clientId"); connection.start();/* w w w . j a v a2 s .c om*/ Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(session.createTopic(defaultTopicName)); publishTestTopicMessages(100, DeliveryMode.NON_PERSISTENT, publishedNonPersistentMessageSize); publishTestTopicMessages(100, DeliveryMode.PERSISTENT, publishedMessageSize); verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get() + publishedNonPersistentMessageSize.get()); // consume all messages consumeTestMessages(consumer, 200); // All messages should now be gone verifyPendingStats(defaultTopicName, 0, 0); connection.close(); }
From source file:org.springframework.jms.core.JmsTemplate.java
/** * Create a JMS MessageConsumer for the given Session and Destination. * <p>This implementation uses JMS 1.1 API. * @param session the JMS Session to create a MessageConsumer for * @param destination the JMS Destination to create a MessageConsumer for * @return the new JMS MessageConsumer//from w w w . j av a2 s .c om * @throws JMSException if thrown by JMS API methods */ protected MessageConsumer createConsumer(Session session, Destination destination) throws JMSException { return session.createConsumer(destination); }