List of usage examples for javax.jms Session createProducer
MessageProducer createProducer(Destination destination) throws JMSException;
From source file:org.apache.activemq.bugs.AMQ7067Test.java
@Test public void testCommit() throws Exception { final Connection connection = ACTIVE_MQ_NON_XA_CONNECTION_FACTORY.createConnection(); connection.start();/*w w w .j a va2 s .c o m*/ Session session = connection.createSession(true, Session.SESSION_TRANSACTED); Queue holdKahaDb = session.createQueue("holdKahaDb"); MessageProducer holdKahaDbProducer = session.createProducer(holdKahaDb); TextMessage helloMessage = session.createTextMessage(StringUtils.repeat("a", 10)); holdKahaDbProducer.send(helloMessage); Queue queue = session.createQueue("test"); produce(connection, queue, 100, 512 * 1024); session.commit(); produce(connection, queue, 100, 512 * 1024); System.out.println(String.format("QueueSize %s: %d", holdKahaDb.getQueueName(), getQueueSize(holdKahaDb.getQueueName()))); purgeQueue(queue.getQueueName()); Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { return 0 == getQueueSize(queue.getQueueName()); } }); // force gc broker.getPersistenceAdapter().checkpoint(true); connection.close(); curruptIndexFile(getDataDirectory()); broker.stop(); broker.waitUntilStopped(); createBroker(); broker.waitUntilStarted(); while (true) { try { TimeUnit.SECONDS.sleep(1); System.out.println(String.format("QueueSize %s: %d", holdKahaDb.getQueueName(), getQueueSize(holdKahaDb.getQueueName()))); break; } catch (Exception ex) { System.out.println(ex.getMessage()); break; } } // THIS SHOULD NOT FAIL AS THERE SHOULD BE ONLY 1 TRANSACTION! assertEquals(1, getQueueSize(holdKahaDb.getQueueName())); }
From source file:com.fusesource.forge.jmstest.tests.AsyncProducer.java
public void run() { try {/*from w w w . ja va2s .com*/ 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.apache.activemq.cli.test.ArtemisTest.java
public void testSimpleRun(String folderName) throws Exception { File instanceFolder = temporaryFolder.newFolder(folderName); setupAuth(instanceFolder);/*from ww w . j a va 2s. co m*/ String queues = "q1,q2"; String addresses = "a1,a2"; // This is usually set when run from the command line via artemis.profile Run.setEmbedded(true); Artemis.main("create", instanceFolder.getAbsolutePath(), "--force", "--silent", "--no-web", "--queues", queues, "--addresses", addresses, "--no-autotune", "--require-login"); System.setProperty("artemis.instance", instanceFolder.getAbsolutePath()); // Some exceptions may happen on the initialization, but they should be ok on start the basic core protocol Artemis.internalExecute("run"); try { try (ServerLocator locator = ServerLocatorImpl.newLocator("tcp://localhost:61616"); ClientSessionFactory factory = locator.createSessionFactory(); ClientSession coreSession = factory.createSession("admin", "admin", false, true, true, false, 0)) { for (String str : queues.split(",")) { ClientSession.QueueQuery queryResult = coreSession.queueQuery(SimpleString.toSimpleString(str)); assertTrue("Couldn't find queue " + str, queryResult.isExists()); } for (String str : addresses.split(",")) { ClientSession.AddressQuery queryResult = coreSession .addressQuery(SimpleString.toSimpleString(str)); assertTrue("Couldn't find address " + str, queryResult.isExists()); } } try { Artemis.internalExecute("data", "print"); Assert.fail("Exception expected"); } catch (CLIException expected) { } Artemis.internalExecute("data", "print", "--f"); assertEquals(Integer.valueOf(100), Artemis.internalExecute("producer", "--message-count", "100", "--verbose", "--user", "admin", "--password", "admin")); assertEquals(Integer.valueOf(100), Artemis.internalExecute("consumer", "--verbose", "--break-on-null", "--receive-timeout", "100", "--user", "admin", "--password", "admin")); ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616"); Connection connection = cf.createConnection("admin", "admin"); Session session = connection.createSession(true, Session.SESSION_TRANSACTED); MessageProducer producer = session.createProducer( ActiveMQDestination.createDestination("queue://TEST", ActiveMQDestination.QUEUE_TYPE)); TextMessage message = session.createTextMessage("Banana"); message.setStringProperty("fruit", "banana"); producer.send(message); for (int i = 0; i < 100; i++) { message = session.createTextMessage("orange"); message.setStringProperty("fruit", "orange"); producer.send(message); } session.commit(); connection.close(); cf.close(); assertEquals(Integer.valueOf(1), Artemis.internalExecute("browser", "--txt-size", "50", "--verbose", "--filter", "fruit='banana'", "--user", "admin", "--password", "admin")); assertEquals(Integer.valueOf(100), Artemis.internalExecute("browser", "--txt-size", "50", "--verbose", "--filter", "fruit='orange'", "--user", "admin", "--password", "admin")); assertEquals(Integer.valueOf(101), Artemis.internalExecute("browser", "--txt-size", "50", "--verbose", "--user", "admin", "--password", "admin")); // should only receive 10 messages on browse as I'm setting messageCount=10 assertEquals(Integer.valueOf(10), Artemis.internalExecute("browser", "--txt-size", "50", "--verbose", "--message-count", "10", "--user", "admin", "--password", "admin")); // Nothing was consumed until here as it was only browsing, check it's receiving again assertEquals(Integer.valueOf(1), Artemis.internalExecute("consumer", "--txt-size", "50", "--verbose", "--break-on-null", "--receive-timeout", "100", "--filter", "fruit='banana'", "--user", "admin", "--password", "admin")); // Checking it was acked before assertEquals(Integer.valueOf(100), Artemis.internalExecute("consumer", "--txt-size", "50", "--verbose", "--break-on-null", "--receive-timeout", "100", "--user", "admin", "--password", "admin")); } finally { stopServer(); } }
From source file:org.wso2.carbon.esb.scenario.test.common.jms.ActiveMQJMSClient.java
/** * Function to produce message to ActiveMQ Queue * * @param queueName name of the target queue * @param messageStr message to place// ww w. j a va2 s. com * @throws JMSException */ public void produceMessageToQueue(String queueName, String messageStr) throws JMSException { Connection connection = null; Session session = null; try { // Create a ConnectionFactory ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl); // Create a Connection connection = connectionFactory.createConnection(); connection.start(); connection.setExceptionListener(this); // Create a Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Create the destination (Topic or Queue) Destination destination = session.createQueue(queueName); // Create a MessageProducer from the Session to the Topic or Queue MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); // Create a messages TextMessage message = session.createTextMessage(messageStr); // Tell the producer to send the message producer.send(message); } finally { // Clean up if (session != null) { session.close(); } if (connection != null) { connection.close(); } } }
From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java
@Test public void testQueueLargeMessageSize() throws Exception { ActiveMQConnectionFactory acf = (ActiveMQConnectionFactory) cf; acf.setMinLargeMessageSize(1000);/*from ww w. ja v a 2 s . com*/ Connection connection = cf.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); String testText = StringUtils.repeat("t", 5000); ActiveMQTextMessage message = (ActiveMQTextMessage) session.createTextMessage(testText); session.createProducer(session.createQueue(defaultQueueName)).send(message); verifyPendingStats(defaultQueueName, 1, message.getCoreMessage().getPersistentSize()); verifyPendingDurableStats(defaultQueueName, 1, message.getCoreMessage().getPersistentSize()); connection.close(); this.killServer(); this.restartServer(); verifyPendingStats(defaultQueueName, 1, message.getCoreMessage().getPersistentSize()); verifyPendingDurableStats(defaultQueueName, 1, message.getCoreMessage().getPersistentSize()); }
From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java
protected void publishTestTopicMessages(int publishSize, int deliveryMode, AtomicLong publishedMessageSize) throws Exception { // create a new queue Connection connection = cf.createConnection(); connection.setClientID("clientId2"); connection.start();//w ww . jav a2 s . co m // Start the connection Session session = connection.createSession(false, TopicSession.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic(defaultTopicName); try { // publish a bunch of non-persistent messages to fill up the temp // store MessageProducer prod = session.createProducer(topic); prod.setDeliveryMode(deliveryMode); for (int i = 0; i < publishSize; i++) { prod.send( createMessage(i, session, JournalPendingMessageTest.maxMessageSize, publishedMessageSize)); } } finally { connection.close(); } }
From source file:org.jbpm.executor.impl.ExecutorImpl.java
protected void sendMessage(String messageBody, int priority) { if (connectionFactory == null && queue == null) { throw new IllegalStateException("ConnectionFactory and Queue cannot be null"); }//from w w w. ja va2 s . c o m Connection queueConnection = null; Session queueSession = null; MessageProducer producer = null; try { queueConnection = connectionFactory.createConnection(); queueSession = queueConnection.createSession(transacted, Session.AUTO_ACKNOWLEDGE); TextMessage message = queueSession.createTextMessage(messageBody); producer = queueSession.createProducer(queue); producer.setPriority(priority); queueConnection.start(); producer.send(message); } catch (Exception e) { throw new RuntimeException("Error when sending JMS message with executor job request", e); } finally { if (producer != null) { try { producer.close(); } catch (JMSException e) { logger.warn("Error when closing producer", e); } } if (queueSession != null) { try { queueSession.close(); } catch (JMSException e) { logger.warn("Error when closing queue session", e); } } if (queueConnection != null) { try { queueConnection.close(); } catch (JMSException e) { logger.warn("Error when closing queue connection", e); } } } }
From source file:org.apache.james.queue.activemq.ActiveMQMailQueue.java
/** * Try to use ActiveMQ StatisticsPlugin to get size and if that fails * fallback to {@link JMSMailQueue#getSize()} */// ww w . jav a 2 s. c o m @Override public long getSize() throws MailQueueException { Connection connection = null; Session session = null; MessageConsumer consumer = null; MessageProducer producer = null; TemporaryQueue replyTo = null; long size = -1; try { connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); replyTo = session.createTemporaryQueue(); consumer = session.createConsumer(replyTo); Queue myQueue = session.createQueue(queuename); producer = session.createProducer(null); String queueName = "ActiveMQ.Statistics.Destination." + myQueue.getQueueName(); Queue query = session.createQueue(queueName); Message msg = session.createMessage(); msg.setJMSReplyTo(replyTo); producer.send(query, msg); MapMessage reply = (MapMessage) consumer.receive(2000); if (reply != null && reply.itemExists("size")) { try { size = reply.getLong("size"); return size; } catch (NumberFormatException e) { // if we hit this we can't calculate the size so just catch // it } } } catch (Exception e) { throw new MailQueueException("Unable to remove mails", e); } finally { if (consumer != null) { try { consumer.close(); } catch (JMSException e1) { e1.printStackTrace(); // ignore on rollback } } if (producer != null) { try { producer.close(); } catch (JMSException e1) { // ignore on rollback } } if (replyTo != null) { try { // we need to delete the temporary queue to be sure we will // free up memory if thats not done and a pool is used // its possible that we will register a new mbean in jmx for // every TemporaryQueue which will never get unregistered replyTo.delete(); } catch (JMSException e) { } } try { if (session != null) session.close(); } catch (JMSException e1) { // ignore here } try { if (connection != null) connection.close(); } catch (JMSException e1) { // ignore here } } // if we came to this point we should just fallback to super method return super.getSize(); }
From source file:com.ccc.ccm.client.JMSTemplateAutowired.java
/** * Create a raw JMS MessageProducer for the given Session and Destination. * <p>This implementation uses JMS 1.1 API. * @param session the JMS Session to create a MessageProducer for * @param destination the JMS Destination to create a MessageProducer for * @return the new JMS MessageProducer//from w ww.ja va 2s .c om * @throws JMSException if thrown by JMS API methods */ protected MessageProducer doCreateProducer(Session session, Destination destination) throws JMSException { return session.createProducer(destination); }
From source file:org.rhq.enterprise.server.drift.DriftManagerBean.java
@Override @TransactionAttribute(REQUIRES_NEW)/*from w w w .j av a 2 s . c o m*/ public void addChangeSet(Subject subject, int resourceId, long zipSize, InputStream zipStream) throws Exception { Connection connection = factory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(changesetQueue); ObjectMessage msg = session.createObjectMessage(new DriftUploadRequest(resourceId, zipSize, zipStream)); producer.send(msg); connection.close(); }