List of usage examples for javax.jms Session createConsumer
MessageConsumer createConsumer(Destination destination) throws JMSException;
From source file:org.apache.synapse.message.store.impl.jms.JmsStore.java
/** * Returns a new JMS Message Consumer.//from www . j av a2 s. co m * @param session A JMS Session * @return A JMS Message Consumer * @throws JMSException */ public javax.jms.MessageConsumer newConsumer(Session session) throws JMSException { if (session == null) { logger.error(nameString() + " cannot create JMS Consumer. Invalid session."); return null; } if (!createDestIfAbsent(session)) { logger.error(nameString() + " cannot create JMS Consumer. " + "Destination queue is invalid."); return null; } javax.jms.MessageConsumer consumer; if (isVersion11) { consumer = session.createConsumer(queue); } else { consumer = ((QueueSession) session).createReceiver((Queue) queue); } if (logger.isDebugEnabled()) { logger.debug(nameString() + " created JMS Message Consumer to destination [" + queue.toString() + "]."); } return consumer; }
From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java
/** * Purge destinations for clean test setup. Especially applicable to WMQ tests, as messages from * other tests may still exist from other tests' runs. * <p/>//www. j ava2 s.com * Well-behaving tests should drain both inbound and outbound destinations, as well as any intermediary ones. * @param destination destination name without any protocol specifics */ protected void purge(final String destination) throws JMSException { Connection c = null; Session s = null; try { logger.debug("purging queue : " + destination); c = getConnection(false, false); assertNotNull(c); c.start(); s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination d = s.createQueue(destination); MessageConsumer consumer = s.createConsumer(d); while (consumer.receiveNoWait() != null) { logger.debug("Destination " + destination + " isn't empty, draining it"); } } catch (Exception e) { logger.error("unable to purge : " + destination); } 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()); } } } }
From source file:com.microsoft.azure.servicebus.samples.jmsqueuequickstart.JmsQueueQuickstart.java
public void run(String connectionString) throws Exception { // The connection string builder is the only part of the azure-servicebus SDK library // we use in this JMS sample and for the purpose of robustly parsing the Service Bus // connection string. ConnectionStringBuilder csb = new ConnectionStringBuilder(connectionString); // set up JNDI context Hashtable<String, String> hashtable = new Hashtable<>(); hashtable.put("connectionfactory.SBCF", "amqps://" + csb.getEndpoint().getHost() + "?amqp.idleTimeout=120000&amqp.traceFrames=true"); hashtable.put("queue.QUEUE", "BasicQueue"); hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory"); Context context = new InitialContext(hashtable); ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF"); // Look up queue Destination queue = (Destination) context.lookup("QUEUE"); // we create a scope here so we can use the same set of local variables cleanly // again to show the receive side separately with minimal clutter {/*from w w w .j ava 2s .c o m*/ // Create Connection Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey()); // Create Session, no transaction, client ack Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); // Create producer MessageProducer producer = session.createProducer(queue); // Send messages for (int i = 0; i < totalSend; i++) { BytesMessage message = session.createBytesMessage(); message.writeBytes(String.valueOf(i).getBytes()); producer.send(message); System.out.printf("Sent message %d.\n", i + 1); } producer.close(); session.close(); connection.stop(); connection.close(); } { // Create Connection Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey()); connection.start(); // Create Session, no transaction, client ack Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); // Create consumer MessageConsumer consumer = session.createConsumer(queue); // create a listener callback to receive the messages consumer.setMessageListener(message -> { try { // receives message is passed to callback System.out.printf("Received message %d with sq#: %s\n", totalReceived.incrementAndGet(), // increments the tracking counter message.getJMSMessageID()); message.acknowledge(); } catch (Exception e) { logger.error(e); } }); // wait on the main thread until all sent messages have been received while (totalReceived.get() < totalSend) { Thread.sleep(1000); } consumer.close(); session.close(); connection.stop(); connection.close(); } System.out.printf("Received all messages, exiting the sample.\n"); System.out.printf("Closing queue client.\n"); }
From source file:org.dawnsci.commandserver.ui.view.StatusQueueView.java
/** * Listens to a topic//from www .j av a2 s . c o m */ 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); StatusQueueView.this.topicConnection = connectionFactory.createConnection(); topicConnection.start(); Session session = topicConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic(getTopicName()); MessageConsumer consumer = session.createConsumer(topic); final Class clazz = getBeanClass(); 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 bean = mapper.readValue(t.getText(), clazz); mergeBean(bean); } } catch (Exception e) { logger.error("Updating changed bean from topic", e); } } }; consumer.setMessageListener(listener); // Create a listener for administrator broadcast messages. topic = session.createTopic(Constants.ADMIN_MESSAGE_TOPIC); consumer = session.createConsumer(topic); listener = new MessageListener() { public void onMessage(Message message) { try { if (message instanceof TextMessage) { // AdministratorMessage shows a message to the user. final Class msgClass = AdministratorMessage.class; TextMessage t = (TextMessage) message; final AdministratorMessage bean = mapper.readValue(t.getText(), msgClass); getSite().getShell().getDisplay().syncExec(new Runnable() { public void run() { MessageDialog.openError(getViewSite().getShell(), bean.getTitle(), bean.getMessage()); viewer.refresh(); } }); } } catch (Exception e) { // Not a big deal if they do not get admin messages. } } }; 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.apache.activemq.apollo.JmsQueueBrowserTest.java
public void testBrowseClose() throws Exception { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQQueue destination = new ActiveMQQueue("TEST"); connection.start();//from www . j a va 2 s . c o m TextMessage[] outbound = new TextMessage[] { session.createTextMessage("First Message"), session.createTextMessage("Second Message"), session.createTextMessage("Third Message") }; MessageProducer producer = session.createProducer(destination); producer.send(outbound[0]); producer.send(outbound[1]); producer.send(outbound[2]); // create browser first QueueBrowser browser = session.createBrowser((Queue) destination); Enumeration enumeration = browser.getEnumeration(); // browse some messages assertEquals(outbound[0], (Message) enumeration.nextElement()); assertEquals(outbound[1], (Message) enumeration.nextElement()); //assertEquals(outbound[2], (Message) enumeration.nextElement()); browser.close(); // create consumer MessageConsumer consumer = session.createConsumer(destination); // Receive the first message. TextMessage msg = (TextMessage) consumer.receive(1000); assertEquals("Expected " + outbound[0].getText() + " but received " + msg.getText(), outbound[0], msg); msg = (TextMessage) consumer.receive(1000); assertEquals("Expected " + outbound[1].getText() + " but received " + msg.getText(), outbound[1], msg); msg = (TextMessage) consumer.receive(1000); assertEquals("Expected " + outbound[2].getText() + " but received " + msg.getText(), outbound[2], msg); consumer.close(); producer.close(); }
From source file:org.apache.activemq.usecases.RequestReplyToTopicViaThreeNetworkHopsTest.java
public void testMessages(Session sess, MessageProducer req_prod, Destination resp_dest, int num_msg) throws Exception { MessageConsumer resp_cons;/* w w w . j a v a 2 s . c om*/ TextMessage msg; MessageClient cons_client; int cur; int tot_expected; resp_cons = sess.createConsumer(resp_dest); cons_client = new MessageClient(resp_cons, num_msg); cons_client.start(); cur = 0; while ((cur < num_msg) && (!fatalTestError)) { msg = sess.createTextMessage("MSG AAAA " + cur); msg.setIntProperty("SEQ", 100 + cur); msg.setStringProperty("TEST", "TOPO"); msg.setJMSReplyTo(resp_dest); if (cur == (num_msg - 1)) msg.setBooleanProperty("end-of-response", true); sendWithRetryOnDeletedDest(req_prod, msg); LOG.debug("Sent:" + msg); cur++; } // // Give the consumer some time to receive the response. // cons_client.waitShutdown(5000); // // Now shutdown the consumer if it's still running. // if (cons_client.shutdown()) LOG.debug("Consumer client shutdown complete"); else LOG.debug("Consumer client shutdown incomplete!!!"); // // Check that the correct number of messages was received. // tot_expected = num_msg * (echoResponseFill + 1); if (cons_client.getNumMsgReceived() == tot_expected) { LOG.debug("Have " + tot_expected + " messages, as-expected"); } else { testError = true; if (cons_client.getNumMsgReceived() == 0) fatalTestError = true; LOG.error("Have " + cons_client.getNumMsgReceived() + " messages; expected " + tot_expected + " on destination " + resp_dest); } resp_cons.close(); }
From source file:com.seajas.search.profiler.service.profiler.ProfilerService.java
/** * Default constructor./* w ww.ja v a 2 s.c o m*/ * * @param jobNames * @param jobDescriptions * @param availableApplicationLanguages * @param availableSearchLanguages * @param jmsRequestQueue * @param jmsConnectionFactory * @throws Exception */ @Autowired public ProfilerService(@Value("${profiler.project.search.enricher.jobs}") final String jobNames, @Value("${profiler.project.search.enricher.jobs.descriptions}") final String jobDescriptions, @Value("${profiler.project.languages.available}") final String availableApplicationLanguages, @Value("${profiler.project.search.languages}") final String availableSearchLanguages, @Qualifier("jmsPrimaryRequestQueue") final ActiveMQQueue jmsRequestQueue, @Qualifier("connectionFactory") final ConnectionFactory jmsConnectionFactory) throws Exception { /* InputStream caCertificate = getClass().getClassLoader().getResourceAsStream("ca.crt"); LicenseValidator.validateLicenseFile(caCertificate, licenseFile); * * try { caCertificate.close(); } catch (IOException e) { logger.error("Could not close the CA certificate stream."); } */ String[] names = jobNames.split(","); String[] descriptions = jobDescriptions.split(","); this.jobNames = new LinkedHashMap<String, String>(); for (int i = 0; i < names.length; i++) this.jobNames.put(names[i].trim(), descriptions[i].trim()); this.availableApplicationLanguages = Arrays .asList(StringUtils.tokenizeToStringArray(availableApplicationLanguages, ",", true, true)); this.availableSearchLanguages = Arrays .asList(StringUtils.tokenizeToStringArray(availableSearchLanguages, ",", true, true)); // Keep track of the active consumers on the request channel Connection connection = jmsConnectionFactory.createConnection(); Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); connection.start(); Destination destinationAdvisory = AdvisorySupport.getConsumerAdvisoryTopic(jmsRequestQueue); MessageConsumer consumerAdvisory = session.createConsumer(destinationAdvisory); consumerAdvisory.setMessageListener(new MessageListener() { @Override public void onMessage(final Message message) { try { Object consumerCount = ((ActiveMQMessage) message).getProperty("consumerCount"); if (consumerCount != null) { String clientId = ((ActiveMQMessage) message).getConnection().getConnectionInfo() .getClientId(); if (activeContenderClients.contains(clientId) && ((Integer) consumerCount == 0)) { if (staticLogger.isInfoEnabled()) staticLogger.info("Client with ID " + clientId + " was dropped from the current consumer-clients"); activeContenderClients.remove(clientId); } else if (!activeContenderClients.contains(clientId) && ((Integer) consumerCount > 0)) { if (staticLogger.isInfoEnabled()) staticLogger.info("Client with ID " + clientId + " was added to the current consumer-clients"); activeContenderClients.add(clientId); } } } catch (IOException e) { staticLogger.error("Could not retrieve consumer count from connection message", e); } } }); }
From source file:org.sakaiproject.kernel.messaging.activemq.ActiveMQEmailDeliveryT.java
public void testCommonsEmailOneWaySeparateSessions() { Queue emailQueue = null;// w w w. java 2 s . com MessageConsumer consumer = null; MessageProducer producer = null; Session clientSession = null; Session listenerSession = null; // it is not necessary to use the Email interface here // Email is used here just to allow for multiple types of emails to // occupy // the same varaible. SimpleEmail etc can each be used directly. List<Email> emails = new ArrayList<Email>(); EmailMessagingService messagingService = new EmailMessagingService(vmURL, emailQueueName, emailType, null, null, null, null); emails.add(new SimpleEmail(messagingService)); emails.add(new MultiPartEmail(messagingService)); emails.add(new HtmlEmail(messagingService)); try { listenerSession = listenerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); emailQueue = listenerSession.createQueue(emailQueueName); consumer = listenerSession.createConsumer(emailQueue); consumer.setMessageListener(new EmailListener()); listenerConn.start(); listenerSession.run(); } catch (JMSException e2) { e2.printStackTrace(); Assert.assertTrue(false); } Wiser smtpServer = new Wiser(); smtpServer.setPort(smtpTestPort); smtpServer.start(); try { clientSession = clientConn.createSession(false, Session.AUTO_ACKNOWLEDGE); emailQueue = clientSession.createQueue(emailQueueName); producer = clientSession.createProducer(emailQueue); clientConn.start(); clientSession.run(); } catch (JMSException e) { e.printStackTrace(); Assert.assertTrue(false); } for (Email em : emails) { try { em.addTo(TEST_EMAIL_TO); em.setFrom(TEST_EMAIL_FROM_ADDRESS, TEST_EMAIL_FROM_LABEL); // host and port will be ignored since the email session is // established // by // the listener em.setHostName("localhost"); em.setSmtpPort(smtpTestPort); em.setSubject(TEST_EMAIL_SUBJECT); if (em instanceof HtmlEmail) { em.setMsg(TEST_EMAIL_BODY_HTMLEMAIL); } else if (em instanceof MultiPartEmail) { em.setMsg(TEST_EMAIL_BODY_MULTIPARTEMAIL); } else if (em instanceof SimpleEmail) { em.setMsg(TEST_EMAIL_BODY_SIMPLEEMAIL); } } catch (EmailException e1) { Assert.assertTrue(false); e1.printStackTrace(); } try { em.buildMimeMessage(); } catch (EmailException e1) { e1.printStackTrace(); Assert.assertTrue(false); } ByteArrayOutputStream os = new ByteArrayOutputStream(); try { em.getMimeMessage().writeTo(os); } catch (javax.mail.MessagingException e) { e.printStackTrace(); Assert.assertTrue(false); } catch (IOException e) { e.printStackTrace(); Assert.assertTrue(false); } String content = os.toString(); ObjectMessage om; try { om = clientSession.createObjectMessage(content); om.setJMSType(emailType); LOG.info("Client: Sending test message...."); producer.send(om); } catch (JMSException e) { e.printStackTrace(); Assert.assertTrue(false); } } long start = System.currentTimeMillis(); while (listenerMessagesProcessed < 3 && System.currentTimeMillis() - start < 10000L) { // wait for transport } Assert.assertTrue(listenerMessagesProcessed == 3); List<WiserMessage> messages = smtpServer.getMessages(); Assert.assertTrue(messages.size() + " != expected value of 3", messages.size() == 3); for (WiserMessage wisermsg : messages) { String body = null; String subject = null; MimeMessage testmail = null; try { testmail = wisermsg.getMimeMessage(); } catch (MessagingException e) { Assert.assertTrue(false); e.printStackTrace(); } if (testmail != null) { LOG.info("SMTP server: test email received: "); try { LOG.info("To: " + testmail.getHeader("To", ",")); LOG.info("Subject: " + testmail.getHeader("Subject", ",")); body = getBodyAsString(testmail.getContent()); subject = testmail.getHeader("Subject", ","); } catch (MessagingException e) { Assert.assertTrue(false); e.printStackTrace(); } catch (IOException e) { Assert.assertTrue(false); e.printStackTrace(); } LOG.info("Body: " + body); Assert.assertTrue(subject.contains(TEST_EMAIL_SUBJECT)); Assert.assertTrue(body.contains("This is a Commons")); } else { Assert.assertTrue(false); } } if (clientSession != null) { try { clientSession.close(); } catch (JMSException e) { e.printStackTrace(); Assert.assertTrue(false); } clientSession = null; } if (listenerSession != null) { try { listenerSession.close(); } catch (JMSException e) { e.printStackTrace(); Assert.assertTrue(false); } listenerSession = null; } smtpServer.stop(); }
From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java
@Test @Ignore//from w w w . j a va 2 s.c o m public void testReplicationQuorumLoss() throws Throwable { System.out.println("======================================"); System.out.println(" Start 2 ActiveMQ nodes."); System.out.println("======================================"); startBrokerAsync(createBrokerNode("node-1", port)); startBrokerAsync(createBrokerNode("node-2", port)); BrokerService master = waitForNextMaster(); System.out.println("======================================"); System.out.println(" Start the producer and consumer"); System.out.println("======================================"); final AtomicBoolean stopClients = new AtomicBoolean(false); final ArrayBlockingQueue<String> errors = new ArrayBlockingQueue<String>(100); final AtomicLong receivedCounter = new AtomicLong(); final AtomicLong sentCounter = new AtomicLong(); Thread producer = startFailoverClient("producer", new Client() { @Override public void execute(Connection connection) throws Exception { Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageProducer producer = session.createProducer(session.createQueue("test")); long actual = 0; while (!stopClients.get()) { TextMessage msg = session.createTextMessage("Hello World"); msg.setLongProperty("id", actual++); producer.send(msg); sentCounter.incrementAndGet(); } } }); Thread consumer = startFailoverClient("consumer", new Client() { @Override public void execute(Connection connection) throws Exception { connection.start(); Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(session.createQueue("test")); long expected = 0; while (!stopClients.get()) { Message msg = consumer.receive(200); if (msg != null) { long actual = msg.getLongProperty("id"); if (actual != expected) { errors.offer("Received got unexpected msg id: " + actual + ", expected: " + expected); } msg.acknowledge(); expected = actual + 1; receivedCounter.incrementAndGet(); } } } }); try { assertCounterMakesProgress(sentCounter, 10, TimeUnit.SECONDS); assertCounterMakesProgress(receivedCounter, 5, TimeUnit.SECONDS); assertNull(errors.poll()); System.out.println("======================================"); System.out.println(" Master should stop once the quorum is lost."); System.out.println("======================================"); ArrayList<BrokerService> stopped = stopSlaves();// stopping the slaves should kill the quorum. assertStopsWithin(master, 10, TimeUnit.SECONDS); assertNull(errors.poll()); // clients should not see an error since they are failover clients. stopped.add(master); System.out.println("======================================"); System.out.println(" Restart the slave. Clients should make progress again.."); System.out.println("======================================"); startBrokersAsync(createBrokerNodes(stopped)); assertCounterMakesProgress(sentCounter, 10, TimeUnit.SECONDS); assertCounterMakesProgress(receivedCounter, 5, TimeUnit.SECONDS); assertNull(errors.poll()); } catch (Throwable e) { e.printStackTrace(); throw e; } finally { // Wait for the clients to stop.. stopClients.set(true); producer.join(); consumer.join(); } }
From source file:org.apache.qpid.test.utils.QpidBrokerTestCase.java
/** * Consume all the messages in the specified queue. Helper to ensure * persistent tests don't leave data behind. * * @param queue the queue to purge//from w ww .j av a 2 s . c o m * * @return the count of messages drained * * @throws Exception if a problem occurs */ protected int drainQueue(Queue queue) throws Exception { Connection connection = getConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(queue); connection.start(); int count = 0; while (consumer.receive(1000) != null) { count++; } connection.close(); return count; }