List of usage examples for javax.jms Connection start
void start() throws JMSException;
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 w w w. ja v a 2 s. c o m*/ 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
@Test public void testDeliveringStats() throws Exception { AtomicLong publishedMessageSize = new AtomicLong(); Connection connection = cf.createConnection(); connection.start(); Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageProducer producer = session.createProducer(session.createQueue(defaultQueueName)); producer.send(session.createTextMessage("test")); verifyPendingStats(defaultQueueName, 1, publishedMessageSize.get()); verifyPendingDurableStats(defaultQueueName, 1, publishedMessageSize.get()); verifyDeliveringStats(defaultQueueName, 0, 0); MessageConsumer consumer = session.createConsumer(session.createQueue(defaultQueueName)); Message msg = consumer.receive();/*from ww w. j a va2 s .c o m*/ verifyDeliveringStats(defaultQueueName, 1, publishedMessageSize.get()); msg.acknowledge(); verifyPendingStats(defaultQueueName, 0, 0); verifyPendingDurableStats(defaultQueueName, 0, 0); verifyDeliveringStats(defaultQueueName, 0, 0); connection.close(); }
From source file:com.cws.esolutions.core.utils.MQUtils.java
/** * Gets an MQ message off a specified queue and returns it as an * <code>Object</code> to the requestor for further processing. * * @param connName - The connection name to utilize * @param authData - The authentication data to utilize, if required * @param responseQueue - The request queue name to put the message on * @param timeout - How long to wait for a connection or response * @param messageId - The JMS correlation ID of the message the response is associated with * @return <code>Object</code> - The serializable data returned by the MQ request * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing *//*from w ww. j ava 2 s . c om*/ public static final synchronized Object getMqMessage(final String connName, final List<String> authData, final String responseQueue, final long timeout, final String messageId) throws UtilityException { final String methodName = MQUtils.CNAME + "getMqMessage(final String connName, final List<String> authData, final String responseQueue, final long timeout, final String messageId) throws UtilityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", connName); DEBUGGER.debug("Value: {}", responseQueue); DEBUGGER.debug("Value: {}", timeout); DEBUGGER.debug("Value: {}", messageId); } Connection conn = null; Session session = null; Object response = null; Context envContext = null; MessageConsumer consumer = null; ConnectionFactory connFactory = null; try { try { InitialContext initCtx = new InitialContext(); envContext = (Context) initCtx.lookup(MQUtils.INIT_CONTEXT); connFactory = (ConnectionFactory) envContext.lookup(connName); } catch (NamingException nx) { // we're probably not in a container connFactory = new ActiveMQConnectionFactory(connName); } if (DEBUG) { DEBUGGER.debug("ConnectionFactory: {}", connFactory); } if (connFactory == null) { throw new UtilityException("Unable to create connection factory for provided name"); } // Create a Connection conn = connFactory.createConnection(authData.get(0), PasswordUtils.decryptText(authData.get(1), authData.get(2), authData.get(3), Integer.parseInt(authData.get(4)), Integer.parseInt(authData.get(5)), authData.get(6), authData.get(7), authData.get(8))); conn.start(); if (DEBUG) { DEBUGGER.debug("Connection: {}", conn); } // Create a Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); if (DEBUG) { DEBUGGER.debug("Session: {}", session); } if (envContext != null) { try { consumer = session.createConsumer((Destination) envContext.lookup(responseQueue), "JMSCorrelationID='" + messageId + "'"); } catch (NamingException nx) { throw new UtilityException(nx.getMessage(), nx); } } else { Destination destination = session.createQueue(responseQueue); if (DEBUG) { DEBUGGER.debug("Destination: {}", destination); } consumer = session.createConsumer(destination, "JMSCorrelationID='" + messageId + "'"); } if (DEBUG) { DEBUGGER.debug("MessageConsumer: {}", consumer); } ObjectMessage message = (ObjectMessage) consumer.receive(timeout); if (DEBUG) { DEBUGGER.debug("ObjectMessage: {}", message); } if (message == null) { throw new UtilityException("Failed to retrieve message within the timeout specified."); } response = message.getObject(); message.acknowledge(); if (DEBUG) { DEBUGGER.debug("Object: {}", response); } } catch (JMSException jx) { throw new UtilityException(jx.getMessage(), jx); } finally { try { // Clean up if (!(session == null)) { session.close(); } if (!(conn == null)) { conn.close(); conn.stop(); } } catch (JMSException jx) { ERROR_RECORDER.error(jx.getMessage(), jx); } } return response; }
From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java
@Test public void testQueueLargeMessageSizeTX() throws Exception { ActiveMQConnectionFactory acf = (ActiveMQConnectionFactory) cf; acf.setMinLargeMessageSize(1000);/*from ww w . j ava2s .com*/ Connection connection = cf.createConnection(); connection.start(); Session session = connection.createSession(true, Session.SESSION_TRANSACTED); String testText = StringUtils.repeat("t", 2000); MessageProducer producer = session.createProducer(session.createQueue(defaultQueueName)); ActiveMQTextMessage message = (ActiveMQTextMessage) session.createTextMessage(testText); for (int i = 0; i < 10; i++) { producer.send(message); } //not commited so should be 0 verifyPendingStats(defaultQueueName, 0, message.getCoreMessage().getPersistentSize() * 10); verifyPendingDurableStats(defaultQueueName, 0, message.getCoreMessage().getPersistentSize() * 10); session.commit(); verifyPendingStats(defaultQueueName, 10, message.getCoreMessage().getPersistentSize() * 10); verifyPendingDurableStats(defaultQueueName, 10, message.getCoreMessage().getPersistentSize() * 10); connection.close(); this.killServer(); this.restartServer(); verifyPendingStats(defaultQueueName, 10, message.getCoreMessage().getPersistentSize()); verifyPendingDurableStats(defaultQueueName, 10, message.getCoreMessage().getPersistentSize()); }
From source file:Vendor.java
public void run() { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url); Session session = null;//from w ww. j a va 2s . com Destination orderQueue; Destination monitorOrderQueue; Destination storageOrderQueue; TemporaryQueue vendorConfirmQueue; MessageConsumer orderConsumer = null; MessageProducer monitorProducer = null; MessageProducer storageProducer = null; try { Connection connection = connectionFactory.createConnection(); session = connection.createSession(true, Session.SESSION_TRANSACTED); orderQueue = session.createQueue("VendorOrderQueue"); monitorOrderQueue = session.createQueue("MonitorOrderQueue"); storageOrderQueue = session.createQueue("StorageOrderQueue"); orderConsumer = session.createConsumer(orderQueue); monitorProducer = session.createProducer(monitorOrderQueue); storageProducer = session.createProducer(storageOrderQueue); Connection asyncconnection = connectionFactory.createConnection(); asyncSession = asyncconnection.createSession(true, Session.SESSION_TRANSACTED); vendorConfirmQueue = asyncSession.createTemporaryQueue(); MessageConsumer confirmConsumer = asyncSession.createConsumer(vendorConfirmQueue); confirmConsumer.setMessageListener(this); asyncconnection.start(); connection.start(); while (true) { Order order = null; try { Message inMessage = orderConsumer.receive(); MapMessage message; if (inMessage instanceof MapMessage) { message = (MapMessage) inMessage; } else { // end of stream Message outMessage = session.createMessage(); outMessage.setJMSReplyTo(vendorConfirmQueue); monitorProducer.send(outMessage); storageProducer.send(outMessage); session.commit(); break; } // Randomly throw an exception in here to simulate a Database error // and trigger a rollback of the transaction if (new Random().nextInt(3) == 0) { throw new JMSException("Simulated Database Error."); } order = new Order(message); MapMessage orderMessage = session.createMapMessage(); orderMessage.setJMSReplyTo(vendorConfirmQueue); orderMessage.setInt("VendorOrderNumber", order.getOrderNumber()); int quantity = message.getInt("Quantity"); System.out.println("Vendor: Retailer ordered " + quantity + " " + message.getString("Item")); orderMessage.setInt("Quantity", quantity); orderMessage.setString("Item", "Monitor"); monitorProducer.send(orderMessage); System.out.println("Vendor: ordered " + quantity + " Monitor(s)"); orderMessage.setString("Item", "HardDrive"); storageProducer.send(orderMessage); System.out.println("Vendor: ordered " + quantity + " Hard Drive(s)"); session.commit(); System.out.println("Vendor: Comitted Transaction 1"); } catch (JMSException e) { System.out.println("Vendor: JMSException Occured: " + e.getMessage()); e.printStackTrace(); session.rollback(); System.out.println("Vendor: Rolled Back Transaction."); } } synchronized (supplierLock) { while (numSuppliers > 0) { try { supplierLock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } connection.close(); asyncconnection.close(); } catch (JMSException e) { e.printStackTrace(); } }
From source file:org.wso2.andes.systest.TestingBaseCase.java
/** * Perform the Main test of a topic Consumer with the given AckMode. * * Test creates a new connection and sets up the connection to prevent * failover//from w w w .j a va 2s . c o m * * A new consumer is connected and started so that it will prefetch msgs. * * An asynchrounous publisher is started to fill the broker with messages. * * We then wait to be notified of the disconnection via the ExceptionListener * * 0-10 does not have the same notification paths but sync() apparently should * give us the exception, currently it doesn't, so the test is excluded from 0-10 * * We should ensure that this test has the same path for all protocol versions. * * Clients should not have to modify their code based on the protocol in use. * * @param ackMode @see javax.jms.Session * * @throws Exception */ protected void topicConsumer(int ackMode, boolean durable) throws Exception { Connection connection = getConnection(); connection.setExceptionListener(this); Session session = connection.createSession(ackMode == Session.SESSION_TRANSACTED, ackMode); _destination = session.createTopic(getName()); MessageConsumer consumer; if (durable) { consumer = session.createDurableSubscriber(_destination, getTestQueueName()); } else { consumer = session.createConsumer(_destination); } connection.start(); // Start the consumer pre-fetching // Don't care about response as we will fill the broker up with messages // after this point and ensure that the client is disconnected at the // right point. consumer.receiveNoWait(); startPublisher(_destination); boolean disconnected = _disconnectionLatch.await(DISCONNECTION_WAIT, TimeUnit.SECONDS); assertTrue("Client was not disconnected", disconnected); assertTrue("Client was not disconnected.", _connectionException != null); Exception linked = _connectionException.getLinkedException(); _publisher.join(JOIN_WAIT); assertFalse("Publisher still running", _publisher.isAlive()); //Validate publishing occurred ok if (_publisherError != null) { throw _publisherError; } // NOTE these exceptions will need to be modeled so that they are not // 0-8 specific. e.g. JMSSessionClosedException assertNotNull("No error received onException listener.", _connectionException); assertNotNull("No linked exception set on:" + _connectionException.getMessage(), linked); assertTrue("Incorrect linked exception received.", linked instanceof AMQException); AMQException amqException = (AMQException) linked; assertEquals("Channel was not closed with correct code.", AMQConstant.RESOURCE_ERROR, amqException.getErrorCode()); }
From source file:com.chinamobile.bcbsp.comm.ConsumerTool.java
/** Run of Thread. */ public void run() { try {// w w w. j a v a 2 s. c o m running = true; this.url = "failover://vm://" + this.brokerName; BSPActiveMQConnFactory connectionFactory = new BSPActiveMQConnFactoryImpl(); connectionFactory.activeMQConnFactoryMethod(url); connectionFactory.setOptimizeAcknowledge(true); Connection connection = connectionFactory.createConnection(); if (durable && clientId != null && clientId.length() > 0 && !"null".equals(clientId)) { connection.setClientID(clientId); } connection.setExceptionListener(this); connection.start(); session = connection.createSession(transacted, ackMode); if (topic) { destination = session.createTopic(subject); } else { destination = session.createQueue(subject); } replyProducer = session.createProducer(null); replyProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); if (durable && topic) { consumer = session.createDurableSubscriber((Topic) destination, consumerName); } else { consumer = session.createConsumer(destination); } consumeMessages(connection, session, consumer, receiveTimeOut); LOG.info("[ConsumerTool] has received " + this.messagesReceived + " object messages from <" + this.subject + ">."); LOG.info("[ConsumerTool] has received " + this.messageCount + " BSP messages from <" + this.subject + ">."); this.receiver.addMessageCount(this.messageCount); this.receiver.addMessageBytesCount(messageBytesCount); } catch (Exception e) { throw new RuntimeException("[ConsumerTool] caught: ", e); } }
From source file:tools.ConsumerTool.java
@Override public void run() { Connection connection = null; Session session = null;/*from ww w . j a v a 2s.c om*/ try { connection = connectionFactory.createConnection(); if (clientId != null) { connection.setClientID(clientId); } connection.start(); session = connection.createSession(transacted, acknowledgeMode); Destination destination = null; if (jndiLookupDestinations) { destination = (Destination) context.lookup(destinationName); } else { if (useQueueDestinations) { if (useTemporaryDestinations) { destination = session.createTemporaryQueue(); } else { destination = session.createQueue(destinationName); } } else { if (useTemporaryDestinations) { destination = session.createTemporaryTopic(); } else { destination = session.createTopic(destinationName); } } } if (useQueueBrowser) { runQueueBrowser(session, (Queue) destination); } else { MessageConsumer consumer = null; if (useQueueDestinations) { //Queues if (selector != null) { consumer = session.createConsumer(destination, selector); } else { consumer = session.createConsumer(destination); } } else { //Queues if (durable) { //Durable Subscribers if (selector != null) { consumer = session.createDurableSubscriber((Topic) destination, subscriptionName, selector, false); } else { consumer = session.createDurableSubscriber((Topic) destination, subscriptionName); } } else { //Non-Durable Subscribers if (selector != null) { consumer = session.createConsumer(destination, selector); } else { consumer = session.createConsumer(destination); } } } if (useAsyncListener) { final Session consumerSession = session; final AtomicInteger perConsumerReceivedMessages = new AtomicInteger(0); consumer.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { perConsumerReceivedMessages.incrementAndGet(); handleMessage(consumerSession, message, perConsumerReceivedMessages.get()); } }); while (perConsumerReceivedMessages.get() < numMessages) { Thread.sleep(100); } } else { int perConsumerReceivedMessages = 0; while (perConsumerReceivedMessages < numMessages) { Message message = null; if (receiveTimeoutMS > -1) { message = consumer.receive(receiveTimeoutMS); } else { message = consumer.receive(); } if (message != null) { perConsumerReceivedMessages++; handleMessage(session, message, perConsumerReceivedMessages); } } } consumer.close(); } } catch (Exception ex) { LOGGER.error("ConsumerTool hit exception: " + ex.getMessage(), ex); } finally { if (session != null) { try { session.close(); } catch (JMSException e) { LOGGER.error("JMSException closing session", e); } } if (connection != null) { try { connection.close(); } catch (JMSException e) { LOGGER.error("JMSException closing 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()} *///from www . j av 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: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(); 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);/*from w w w. j a va 2 s. c o m*/ // All messages should now be gone verifyPendingStats(defaultTopicName, 0, 0); connection.close(); }