List of usage examples for javax.jms Session AUTO_ACKNOWLEDGE
int AUTO_ACKNOWLEDGE
To view the source code for javax.jms Session AUTO_ACKNOWLEDGE.
Click Source Link
From source file:org.apache.activemq.bugs.AMQ6131Test.java
@Test(timeout = 300000) public void testDurableWithNoMessageAfterRestartAndIndexRecovery() throws Exception { final File persistentDir = getPersistentDir(); broker.getBroker().addDestination(broker.getAdminConnectionContext(), new ActiveMQTopic("durable.sub"), false);/*from w ww. j a v a 2 s . c om*/ ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(this.brokerConnectURI); ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); connection.setClientID("myId"); connection.start(); final Session jmsSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); TopicSubscriber durable = jmsSession.createDurableSubscriber(new ActiveMQTopic("durable.sub"), "sub"); final MessageProducer producer = jmsSession.createProducer(new ActiveMQTopic("durable.sub")); final int original = new ArrayList<File>( FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"), TrueFileFilter.INSTANCE)) .size(); // 100k messages final byte[] data = new byte[100000]; final Random random = new Random(); random.nextBytes(data); // run test with enough messages to create a second journal file final AtomicInteger messageCount = new AtomicInteger(); assertTrue("Should have added a journal file", Wait.waitFor(new Condition() { @Override public boolean isSatisified() throws Exception { final ActiveMQBytesMessage message = new ActiveMQBytesMessage(); message.setContent(new ByteSequence(data)); for (int i = 0; i < 100; i++) { producer.send(message); messageCount.getAndIncrement(); } return new ArrayList<File>(FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"), TrueFileFilter.INSTANCE)).size() > original; } })); // Consume all messages for (int i = 0; i < messageCount.get(); i++) { durable.receive(); } durable.close(); assertTrue("Subscription should go inactive", Wait.waitFor(new Condition() { @Override public boolean isSatisified() throws Exception { return broker.getAdminView().getInactiveDurableTopicSubscribers().length == 1; } })); // force a GC of unneeded journal files getBroker().getPersistenceAdapter().checkpoint(true); // wait until a journal file has been GC'd after receiving messages assertTrue("Should have garbage collected", Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { return new ArrayList<File>(FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"), TrueFileFilter.INSTANCE)).size() == original; } })); // stop the broker so we can blow away the index getBroker().stop(); getBroker().waitUntilStopped(); // delete the index so that the durables are gone from the index // The test passes if you take out this delete section for (File index : FileUtils.listFiles(persistentDir, new WildcardFileFilter("db.*"), TrueFileFilter.INSTANCE)) { FileUtils.deleteQuietly(index); } stopBroker(); setUpBroker(false); assertEquals(1, broker.getAdminView().getInactiveDurableTopicSubscribers().length); assertEquals(0, broker.getAdminView().getDurableTopicSubscribers().length); ActiveMQConnectionFactory connectionFactory2 = new ActiveMQConnectionFactory(this.brokerConnectURI); ActiveMQConnection connection2 = (ActiveMQConnection) connectionFactory2.createConnection(); connection2.setClientID("myId"); connection2.start(); final Session jmsSession2 = connection2.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); TopicSubscriber durable2 = jmsSession2.createDurableSubscriber(new ActiveMQTopic("durable.sub"), "sub"); assertEquals(0, broker.getAdminView().getInactiveDurableTopicSubscribers().length); assertEquals(1, broker.getAdminView().getDurableTopicSubscribers().length); assertNull(durable2.receive(500)); }
From source file:de.klemp.middleware.controller.Controller.java
public static void sendMessageFast(String message, String topic) { String url = ActiveMQConnection.DEFAULT_BROKER_URL; ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); // Create a Connection Connection connection;//from w w w . jav a 2 s . c o m try { connectionFactory.setOptimizeAcknowledge(true); connectionFactory.setUseAsyncSend(true); connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Create the destination (Topic or Queue) Destination destination = session.createTopic(topic); // 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 message1 = session.createTextMessage(message); // Tell the producer to send the message producer.send(message1); session.close(); connection.close(); } catch (JMSException e) { logger.error("Message could not be sended to activemq", e); } }
From source file:nl.nn.adapterframework.extensions.tibco.GetTibcoQueues.java
public String doPipeWithTimeoutGuarded(Object input, IPipeLineSession session) throws PipeRunException { String result;/*from w w w.j a v a2s .com*/ String url_work; String authAlias_work; String userName_work; String password_work; String queueName_work = null; ParameterValueList pvl = null; if (getParameterList() != null) { ParameterResolutionContext prc = new ParameterResolutionContext((String) input, session); try { pvl = prc.getValues(getParameterList()); } catch (ParameterException e) { throw new PipeRunException(this, getLogPrefix(session) + "exception on extracting parameters", e); } } url_work = getParameterValue(pvl, "url"); if (url_work == null) { url_work = getUrl(); } authAlias_work = getParameterValue(pvl, "authAlias"); if (authAlias_work == null) { authAlias_work = getAuthAlias(); } userName_work = getParameterValue(pvl, "userName"); if (userName_work == null) { userName_work = getUserName(); } password_work = getParameterValue(pvl, "password"); if (password_work == null) { password_work = getPassword(); } CredentialFactory cf = new CredentialFactory(authAlias_work, userName_work, password_work); Connection connection = null; Session jSession = null; TibjmsAdmin admin = null; try { admin = TibcoUtils.getActiveServerAdmin(url_work, cf); if (admin == null) { throw new PipeRunException(this, "could not find an active server"); } String ldapUrl = getParameterValue(pvl, "ldapUrl"); LdapSender ldapSender = null; if (StringUtils.isNotEmpty(ldapUrl)) { ldapSender = retrieveLdapSender(ldapUrl, cf); } queueName_work = getParameterValue(pvl, "queueName"); if (StringUtils.isNotEmpty(queueName_work)) { String countOnly_work = getParameterValue(pvl, "countOnly"); boolean countOnly = ("true".equalsIgnoreCase(countOnly_work) ? true : false); if (countOnly) { return getQueueMessageCountOnly(admin, queueName_work); } } ConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(url_work); connection = factory.createConnection(cf.getUsername(), cf.getPassword()); jSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); if (StringUtils.isNotEmpty(queueName_work)) { String queueItem_work = getParameterValue(pvl, "queueItem"); int qi; if (StringUtils.isNumeric(queueItem_work)) { qi = Integer.parseInt(queueItem_work); } else { qi = 1; } result = getQueueMessage(jSession, admin, queueName_work, qi, ldapSender); } else { String showAge_work = getParameterValue(pvl, "showAge"); boolean showAge = ("true".equalsIgnoreCase(showAge_work) ? true : false); result = getQueuesInfo(jSession, admin, showAge, ldapSender); } } catch (Exception e) { String msg = getLogPrefix(session) + "exception on showing Tibco queues, url [" + url_work + "]" + (StringUtils.isNotEmpty(queueName_work) ? " queue [" + queueName_work + "]" : ""); throw new PipeRunException(this, msg, e); } finally { if (admin != null) { try { admin.close(); } catch (TibjmsAdminException e) { log.warn(getLogPrefix(session) + "exception on closing Tibjms Admin", e); } } if (connection != null) { try { connection.close(); } catch (JMSException e) { log.warn(getLogPrefix(session) + "exception on closing connection", e); } } } return result; }
From source file:com.chinamobile.bcbsp.comm.ProducerTool.java
/** Run method of Thread. */ public final void run() { while (true) { while (this.idle) { if (this.completed) { return; }//from w w w. j a v a 2 s .c o m if (this.noMoreMessagesFlag) { this.superStepCounter++; this.noMoreMessagesFlag = false; // LOG.info("Test Progress: from " + (this.superStepCounter - 1) + // " to " + this.superStepCounter); } try { Thread.sleep(this.sleepTime); } catch (InterruptedException e) { LOG.error("[ProducerTool] to " + this.hostNameAndPort + " has been interrupted for ", e); return; } } if (this.hostNameAndPort == null) { LOG.error("Destination hostname is null."); return; } if (this.messageQueue == null) { LOG.error("Message queue for ProducerTool is null."); return; } this.messageCount = 0; this.connectTime = 0; this.sendTime = 0; while (true) { if (this.reconnectCount == ProducerTool.RECONNECTTHRESHOLD) { break; } try { if (this.newHostNameAndPort) { // Should create new connection. if (connection != null) { try { connection.close(); } catch (Throwable ignore) { LOG.warn("[ConsumerTool] run connection " + ignore); } } long start = System.currentTimeMillis(); /** Clock */ // Make the destination broker's url. this.url = "tcp://" + this.hostNameAndPort; // Create the connection. // ActiveMQConnectionFactory connectionFactory = new // ActiveMQConnectionFactory( // user, password, url); BSPActiveMQConnFactory connectionFactory = new BSPActiveMQConnFactoryImpl(); connectionFactory.activeMQConnFactoryMethod(url); connectionFactory.setCopyMessageOnSend(false); connection = connectionFactory.createConnection(); connection.start(); // Create the session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE); this.connectTime += (System.currentTimeMillis() - start); /* Clock */ this.newHostNameAndPort = false; start = System.currentTimeMillis(); /* Clock */ destination = session.createQueue(subject); // Create the producer. producer = session.createProducer(destination); if (persistent) { producer.setDeliveryMode(DeliveryMode.PERSISTENT); } else { producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); } if (timeToLive != 0) { producer.setTimeToLive(timeToLive); } this.connectTime += (System.currentTimeMillis() - start); } // Start sending messages sendLoopOptimistic(session, producer); this.idle = true; break; } catch (Exception e) { this.reconnectCount++; if (this.reconnectCount == 1) { LOG.error("[ProducerTool] to " + this.hostNameAndPort + " caught: ", e); } LOG.info("[ProducerTool] to " + this.hostNameAndPort + " is reconnecting for " + this.reconnectCount + "th time."); LOG.info("---------------- Memory Info ------------------"); MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage(); long used = memoryUsage.getUsed(); long committed = memoryUsage.getCommitted(); LOG.info("[JVM Memory used] = " + used / MB_SIZE + "MB"); LOG.info("[JVM Memory committed] = " + committed / MB_SIZE + "MB"); LOG.info("-----------------------------------------------"); try { Thread.sleep(this.sleepTime); } catch (InterruptedException e1) { LOG.error("[ProducerTool] caught: ", e1); } } } LOG.info("[ProducerTool] to " + this.hostNameAndPort + " has sent " + this.messageCount + " messages totally! (with " + this.messageQueue.size() + " messages lost!)"); this.sender.addConnectTime(this.connectTime); /* Clock */ this.sender.addSendTime(this.sendTime); /* Clock */ if (this.reconnectCount == ProducerTool.RECONNECTTHRESHOLD) { LOG.info("[ProducerTool] to " + this.hostNameAndPort + " has reconnected for " + this.reconnectCount + " times but failed!"); this.isFailed = true; break; } } }
From source file:com.mothsoft.alexis.engine.retrieval.DocumentRetrievalTaskImpl.java
private String requestParse(final Long documentId, final String content) { Connection connection = null; Session session = null;/* ww w . j av a 2 s.co m*/ MessageProducer producer = null; // set up JMS connection, session, consumer, producer try { connection = this.connectionFactory.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = session.createProducer(this.requestQueue); logger.info("Sending parse request, document ID: " + documentId); final TextMessage textMessage = session.createTextMessage(content); textMessage.setJMSReplyTo(this.responseQueue); textMessage.setLongProperty(DOCUMENT_ID, documentId); producer.send(textMessage); } catch (JMSException e) { throw new RuntimeException(e); } finally { try { if (producer != null) { producer.close(); } if (session != null) { session.close(); } if (connection != null) { connection.close(); } } catch (JMSException e) { throw new RuntimeException(e); } } return content; }
From source file:org.apache.activemq.usecases.RequestReplyToTopicViaThreeNetworkHopsTest.java
/** * TEST TEMPORARY QUEUES// w w w .ja va 2 s. c o m */ public void testTempQueue(String prod_broker_url, String cons_broker_url) throws Exception { int num_msg; Connection conn; Session sess; Destination cons_dest; num_msg = 5; LOG.info("TESTING TEMP QUEUES " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); // // Connect to the bus. // conn = createConnection(cons_broker_url); conn.start(); sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); // // Create the destination on which messages are being tested. // LOG.trace("Creating destination"); cons_dest = sess.createTemporaryQueue(); testOneDest(conn, sess, cons_dest, num_msg); // // Cleanup // sess.close(); conn.close(); }
From source file:org.apache.servicemix.wsn.jms.JmsSubscription.java
@Override protected void resume() throws ResumeFailedFault { if (session != null) { ResumeFailedFaultType fault = new ResumeFailedFaultType(); throw new ResumeFailedFault("Subscription is already running", fault); } else {// w w w . j a v a 2 s .com try { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(jmsTopic); consumer.setMessageListener(this); } catch (JMSException e) { ResumeFailedFaultType fault = new ResumeFailedFaultType(); throw new ResumeFailedFault("Error resuming subscription", fault, e); } } }
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 . jav a 2s.co m*/ 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 testScheduledStats() throws Exception { AtomicLong publishedMessageSize = new AtomicLong(); Connection connection = cf.createConnection(); connection.start();// ww w . j a v a 2 s .co m Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(session.createQueue(defaultQueueName)); producer.setDeliveryDelay(2000); producer.send(session.createTextMessage("test")); verifyPendingStats(defaultQueueName, 1, publishedMessageSize.get()); verifyPendingDurableStats(defaultQueueName, 1, publishedMessageSize.get()); verifyScheduledStats(defaultQueueName, 1, publishedMessageSize.get()); consumeTestQueueMessages(1); verifyPendingStats(defaultQueueName, 0, 0); verifyPendingDurableStats(defaultQueueName, 0, 0); verifyScheduledStats(defaultQueueName, 0, 0); connection.close(); }
From source file:org.seedstack.seed.jms.internal.JmsPlugin.java
@SuppressWarnings("unchecked") private void configureMessageListeners(Collection<Class<?>> listenerCandidates) { for (Class<?> candidate : listenerCandidates) { if (MessageListener.class.isAssignableFrom(candidate)) { Class<? extends MessageListener> messageListenerClass = (Class<? extends MessageListener>) candidate; String messageListenerName = messageListenerClass.getCanonicalName(); JmsMessageListener annotation = messageListenerClass.getAnnotation(JmsMessageListener.class); boolean isTransactional; try { isTransactional = transactionPlugin .isTransactional(messageListenerClass.getMethod("onMessage", Message.class)); } catch (NoSuchMethodException e) { throw SeedException.wrap(e, JmsErrorCodes.UNEXPECTED_EXCEPTION); }// ww w. ja v a 2 s . c om Connection listenerConnection = connections.get(annotation.connection()); if (listenerConnection == null) { throw SeedException.createNew(JmsErrorCodes.MISSING_CONNECTION_FACTORY) .put(ERROR_CONNECTION_NAME, annotation.connection()) .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName); } Session session; try { session = listenerConnection.createSession(isTransactional, Session.AUTO_ACKNOWLEDGE); } catch (JMSException e) { throw SeedException.wrap(e, JmsErrorCodes.UNABLE_TO_CREATE_SESSION) .put(ERROR_CONNECTION_NAME, annotation.connection()) .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName); } Destination destination; try { switch (annotation.destinationType()) { case QUEUE: destination = session.createQueue(annotation.destinationName()); break; case TOPIC: destination = session.createTopic(annotation.destinationName()); break; default: throw SeedException.createNew(JmsErrorCodes.UNKNOWN_DESTINATION_TYPE) .put(ERROR_CONNECTION_NAME, annotation.connection()) .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName); } } catch (JMSException e) { throw SeedException.wrap(e, JmsErrorCodes.UNABLE_TO_CREATE_DESTINATION) .put(ERROR_CONNECTION_NAME, annotation.connection()) .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName); } Class<? extends MessagePoller> messagePollerClass = null; if (annotation.poller().length > 0) { messagePollerClass = annotation.poller()[0]; } registerMessageListener(new MessageListenerDefinition(messageListenerName, annotation.connection(), session, destination, annotation.selector(), messageListenerClass, messagePollerClass)); } } }