List of usage examples for javax.jms MessageConsumer close
void close() throws JMSException;
From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java
public void closeTestConsumer(String consumerName) { MessageConsumer consumer = _testConsumers.get(consumerName); if (consumer != null) { try {/*from w w w . j ava 2s .co m*/ consumer.close(); LOGGER.debug("Closed test consumer " + consumerName); } catch (JMSException e) { throw new DistributedTestException("Failed to close consumer: " + consumerName, e); } } }
From source file:org.codehaus.stomp.jms.StompSession.java
public Message receiveFromJms(String destinationName, Map headers) throws JMSException, ProtocolException, NamingException { long ttl = getTimeToLive(headers); log.trace("Consuming message - ttl=" + ttl); Destination destination = convertDestination(destinationName, true); MessageConsumer consumer = session.createConsumer(destination); Message message;//from www.j a v a2 s . c o m if (ttl > 0) { message = consumer.receive(ttl); } else { message = consumer.receive(); } if (message != null) { // As this is a dequeue, automatically acknowledge the message message.acknowledge(); } consumer.close(); log.trace("Received message: " + message); return message; }
From source file:org.dhatim.routing.jms.activemq.ActiveMQProvider.java
public final void stop() throws Exception { assertStarted();/*ww w . java 2 s .co m*/ if (brokerService != null) { for (MessageConsumer consumer : consumers) { try { consumer.close(); } catch (Exception e) { logger.debug("Failed to close consumer.", e); } } close(queueConnection, queueSession); close(topicConnection, topicSession); brokerService.stop(); brokerService = null; } }
From source file:org.jboss.activemq.clients.JMSConsumer.java
public static void main(String args[]) { Connection connection = null; try {// ww w . jav a 2s . c o m Options options = new Options(); options.addOption("h", "help", false, "help:"); options.addOption("url", true, "url for the broker to connect to"); options.addOption("u", "username", true, "User name for connection"); options.addOption("p", "password", true, "password for connection"); options.addOption("d", "destination", true, "destination to send to"); options.addOption("n", "number", true, "number of messages to send"); options.addOption("delay", true, "delay between each send"); CommandLineParser parser = new BasicParser(); CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption("h")) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("OptionsTip", options); System.exit(0); } String url = commandLine.hasOption("host") ? commandLine.getOptionValue("host") : URL; String userName = commandLine.hasOption("u") ? commandLine.getOptionValue("u") : "admin"; String password = commandLine.hasOption("p") ? commandLine.getOptionValue("p") : "admin"; String destinationName = commandLine.hasOption("d") ? commandLine.getOptionValue("d") : DESTINATION_NAME; int numberOfMessages = commandLine.hasOption("n") ? Integer.parseInt(commandLine.getOptionValue("n")) : NUM_MESSAGES_TO_RECEIVE; ; ConnectionFactory factory = new ActiveMQConnectionFactory(userName, password, url); connection = factory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic(destinationName); MessageConsumer consumer = session.createConsumer(topic); LOG.info("Start consuming " + numberOfMessages + " messages from " + topic.toString()); for (int i = 0; i < numberOfMessages; i++) { Message message = consumer.receive(); if (message != null) { if (message instanceof BytesMessage) { BytesMessage bytesMessage = (BytesMessage) message; int len = (int) bytesMessage.getBodyLength(); byte[] data = new byte[len]; bytesMessage.readBytes(data); String value = new String(data); LOG.info("Got " + value); } else { LOG.info("Got a message " + message); } } } consumer.close(); session.close(); } catch (Throwable t) { LOG.error("Error receiving message", t); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { LOG.error("Error closing connection", e); } } } }
From source file:org.jbpm.bpel.integration.server.SoapHandler.java
protected ObjectMessage receiveResponse(Session jmsSession, Destination replyTo, String requestId, JbpmContext jbpmContext) throws JMSException, SOAPFaultException { // set up consumer String selector = "JMSCorrelationID='" + requestId + '\''; MessageConsumer consumer = jmsSession.createConsumer(replyTo, selector); try {// ww w . ja v a 2 s . co m // receive response message log.debug("listening for response: destination=" + replyTo + ", requestId=" + requestId); Number responseTimeout = getResponseTimeout(jbpmContext); ObjectMessage jmsResponse = (ObjectMessage) (responseTimeout != null ? consumer.receive(responseTimeout.longValue()) : consumer.receive()); // did a message arrive in time? if (jmsResponse == null) { log.debug("response timeout expired: destination=" + replyTo + ", requestId" + requestId); throw new SOAPFaultException(SoapBindConstants.SERVER_FAULTCODE, SoapBindConstants.TIMEOUT_FAULTSTRING, null, null); } jmsResponse.acknowledge(); log.debug("received response: " + RequestListener.messageToString(jmsResponse)); return jmsResponse; } finally { // release consumer resources consumer.close(); } }
From source file:org.mule.modules.jmsbatchmessaging.JmsBatchMessagingConnector.java
/** * Complete the batch operation and release all resources (including closing any open transactions.) * <p/>/*from w ww . j ava2 s .c o m*/ * {@sample.xml ../../../doc/jms-batch-messaging-connector.xml.sample * jms-batch-messaging:complete} * * @param muleMessage the current MuleMessage * @throws Exception */ @Processor @Inject public void complete(MuleMessage muleMessage) throws Exception { Session session = muleMessage.getInboundProperty("session"); MessageConsumer consumer = muleMessage.getInboundProperty("consumer"); Boolean isTransactional = muleMessage.getInboundProperty("transactional"); if (isTransactional) { session.commit(); } session.close(); consumer.close(); }
From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java
public Message receive(Scenario scenario) throws Exception { assertNotNull("scenario is null!", scenario); Connection connection = null; try {/*from www.j a va 2 s . c o m*/ connection = getConnection(false, false); connection.start(); Session session = null; try { session = connection.createSession(scenario.isTransacted(), scenario.getAcknowledge()); Destination destination = createOutputDestination(session, scenario); MessageConsumer consumer = null; try { consumer = session.createConsumer(destination); return scenario.receive(session, consumer); } finally { if (consumer != null) { consumer.close(); } } } finally { if (session != null) { session.close(); } } } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { logger.warn("Failed to close jms connection: " + e.getMessage()); } } } }
From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java
/** * Clear the specified topic/* www . j ava 2 s. c o m*/ */ protected void purgeTopic(String destination, String topic) throws Exception { Connection c = null; Session s = null; try { logger.debug("purging topic : " + topic); c = getConnection(true, false); if (c == null) { logger.debug("could not create a connection to topic : " + destination); } c.start(); s = ((TopicConnection) c).createTopicSession(true, Session.SESSION_TRANSACTED); logger.debug("created topic session"); Topic dest = s.createTopic(destination); logger.debug("created topic destination"); if (client != null) { client.dispose(); } MessageConsumer consumer = null; try { consumer = s.createDurableSubscriber(dest, topic); logger.debug("created consumer"); while (consumer.receiveNoWait() != null) { logger.debug("Topic " + topic + " isn't empty, draining it"); } logger.debug("topic should be empty"); consumer.close(); s.unsubscribe(topic); } catch (JMSException e) { logger.debug("could not unsubscribe : " + topic); } } finally { if (c != null) { c.stop(); if (s != null) { s.close(); } try { c.close(); } catch (JMSException e) { logger.warn("Failed to close jms connection: " + e.getMessage()); } } } logger.debug("completed draining topic :" + topic); }
From source file:org.openanzo.combus.bayeux.BridgeConnectionManager.java
/** * Sets up state for connecting a single Bayeux client to the BayeuxJMSBridge. * //from w ww.ja v a2 s . c om * @param clientId * the Bayeux client id. * @return true if client was connected. false if there was already a connection for the client. */ protected boolean connectClient(String clientId, MessageListener listener, AnzoPrincipal principal) throws JMSException { // checks if connection already exists, create topic and client state, add to maps. boolean ret = false; boolean clientAlreadyConnected = false; mapLock.lock(); try { clientAlreadyConnected = clientIdToClientState.containsKey(clientId); } finally { mapLock.unlock(); } if (!clientAlreadyConnected) { // We don't have a temporary topic for this client yet so we'll create one. // We make sure to do this while NOT holding the mapLock to avoid deadlocks // (like http://www.openanzo.org/projects/openanzo/ticket/286). This // means that it's possible, in rare cases, that we could create a temp topic which we'll // have to just throw out immediately but there's not much harm in that. TemporaryTopic topic = session.createTemporaryTopic(); String tempDestinationId = topic.getTopicName(); MessageConsumer consumer = session.createConsumer(topic); consumer.setMessageListener(listener); boolean destroyNewJMSState = false; mapLock.lock(); try { if (clientIdToClientState.containsKey(clientId)) { // Some other thread seems to have connected this client while we were busy creating // JMS topics, etc. That's okay, we'll just close the topics we created since they aren't needed anymore. // But we don't want to destroy them while holding the mapLock, so we'll just mark a boolean so that they // are deleted after releasing the lock. destroyNewJMSState = true; } else { ClientState state = new ClientState(principal, topic, clientId, consumer); tempDestinationToClientState.put(tempDestinationId, state); clientIdToClientState.put(clientId, state); ret = true; } } finally { mapLock.unlock(); if (destroyNewJMSState) { consumer.close(); topic.delete(); } } } return ret; }
From source file:org.openanzo.combus.bayeux.BridgeConnectionManager.java
/** * Sets up a subscription of the given Bayeux client to the JMS topic. * //ww w . ja v a 2 s . c o m * @param topic * @param clientId * @return true if a subscription was added. false if there was already a subscription. * @throws AnzoException * if the user does not have access to the topic * @throws JMSException */ protected boolean topicSubscribe(String topic, String clientId, AnzoPrincipal principal, MessageListener listener, IOperationContext opContext) throws JMSException, AnzoException { // check if subscription already exists, update maps and client state boolean ret = false; boolean subscriptionAlreadyExists = false; boolean consumerAlreadyExists = false; mapLock.lock(); try { TopicSubscription topicSubscription = topicSubscriptions.get(topic); consumerAlreadyExists = topicSubscription != null; subscriptionAlreadyExists = topicSubscription != null && topicSubscription.subscribedClients.containsKey(clientId); if (!subscriptionAlreadyExists) { // If we're going to be adding a subscription, check the access control first. if (!userHasTopicAccess(topic, principal, opContext)) { throw new AnzoException(ExceptionConstants.DATASOURCE.NO_READ_ERROR, topic, opContext.getOperationPrincipal().getUserURI().toString()); } if (consumerAlreadyExists) { // If there is already a JMS consumer for the topic, then we can finish things here with some // simple manipulation of the relevant maps. addTopicSubscription(topic, clientId, topicSubscription); ret = true; subscriptionAlreadyExists = true; } } } finally { mapLock.unlock(); } if (!subscriptionAlreadyExists) { // Handle adding the subscription when the JMS topic consumer doesn't exist. // We make sure to create the consumer while NOT holding mapLock to avoid deadlocks // (like http://www.openanzo.org/projects/openanzo/ticket/286). This // means that it's possible, in rare cases, that we could create a duplicate consumer // which we'll have to just throw out immediately but there's not much harm in that. assert !consumerAlreadyExists; Destination destination = session.createTopic(topic); MessageConsumer consumer = session.createConsumer(destination); consumer.setMessageListener(listener); boolean destroyNewJMSState = false; mapLock.lock(); try { TopicSubscription topicSubscription = topicSubscriptions.get(topic); if (topicSubscription == null) { topicSubscription = new TopicSubscription(consumer); topicSubscriptions.put(topic, topicSubscription); } else { // Some other thread seems to have created a consumer for this graph topic while we were busy creating // JMS topics, etc. That's okay, we'll just close the consumer we created since they aren't needed now. // But we don't want to destroy them while holding the mapLock, so we'll just mark a boolean so that they // are deleted after releasing the lock. destroyNewJMSState = true; } if (!topicSubscription.subscribedClients.containsKey(clientId)) { // NOTE: Access control was already verified earlier in the method. addTopicSubscription(topic, clientId, topicSubscription); ret = true; } } finally { mapLock.unlock(); if (destroyNewJMSState) { consumer.close(); } } } return ret; }