List of usage examples for javax.jms Connection createSession
Session createSession(boolean transacted, int acknowledgeMode) throws JMSException;
From source file:org.codehaus.stomp.jms.ProtocolConverter.java
protected void onStompConnect(StompFrame command) throws IOException, JMSException { if (noneXaSession != null) { throw new ProtocolException("Already connected."); }//from ww w .j ava 2 s .c om Map<String, Object> headers = command.getHeaders(); login = (String) headers.get(Stomp.Headers.Connect.LOGIN); passcode = (String) headers.get(Stomp.Headers.Connect.PASSCODE); clientId = (String) headers.get(Stomp.Headers.Connect.CLIENT_ID); Connection noneXaConnection; if (login != null) { noneXaConnection = noneXAConnectionFactory.createConnection(login, passcode); } else { noneXaConnection = noneXAConnectionFactory.createConnection(); } if (clientId != null) { noneXaConnection.setClientID(clientId); } noneXaConnection.start(); Session session = noneXaConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); if (log.isDebugEnabled()) { log.debug("Created session with ack mode: " + session.getAcknowledgeMode()); } this.noneXaSession = new StompSession(initialContext, this, session, noneXaConnection); Map<String, Object> responseHeaders = new HashMap<String, Object>(); responseHeaders.put(Stomp.Headers.Connected.SESSION, clientId); String requestId = (String) headers.get(Stomp.Headers.Connect.REQUEST_ID); if (requestId == null) { // TODO legacy requestId = (String) headers.get(Stomp.Headers.RECEIPT_REQUESTED); } if (requestId != null) { // TODO legacy responseHeaders.put(Stomp.Headers.Connected.RESPONSE_ID, requestId); responseHeaders.put(Stomp.Headers.Response.RECEIPT_ID, requestId); } StompFrame sc = new StompFrame(); sc.setAction(Stomp.Responses.CONNECTED); sc.setHeaders(responseHeaders); sendToStomp(sc); }
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 av a 2s . 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.springframework.integration.jms.JmsOutboundGatewayTests.java
@Test public void testReplyContainerRecovery() throws Exception { JmsOutboundGateway gateway = new JmsOutboundGateway(); ConnectionFactory connectionFactory = mock(ConnectionFactory.class); gateway.setConnectionFactory(connectionFactory); gateway.setRequestDestinationName("foo"); gateway.setUseReplyContainer(true);//w w w .j a v a 2 s. c o m ReplyContainerProperties replyContainerProperties = new ReplyContainerProperties(); final List<Throwable> errors = new ArrayList<Throwable>(); ErrorHandlingTaskExecutor errorHandlingTaskExecutor = new ErrorHandlingTaskExecutor( Executors.newFixedThreadPool(10), new ErrorHandler() { @Override public void handleError(Throwable t) { logger.info("Error:", t); errors.add(t); throw new RuntimeException(t); } }); replyContainerProperties.setTaskExecutor(errorHandlingTaskExecutor); replyContainerProperties.setRecoveryInterval(100L); gateway.setReplyContainerProperties(replyContainerProperties); final Connection connection = mock(Connection.class); final AtomicInteger connectionAttempts = new AtomicInteger(); doAnswer(new Answer<Connection>() { @SuppressWarnings("serial") @Override public Connection answer(InvocationOnMock invocation) throws Throwable { int theCount = connectionAttempts.incrementAndGet(); if (theCount > 1 && theCount < 4) { throw new JmsException("bar") { }; } return connection; } }).when(connectionFactory).createConnection(); Session session = mock(Session.class); when(connection.createSession(false, 1)).thenReturn(session); MessageConsumer consumer = mock(MessageConsumer.class); when(session.createConsumer(any(Destination.class), anyString())).thenReturn(consumer); when(session.createTemporaryQueue()).thenReturn(mock(TemporaryQueue.class)); final Message message = mock(Message.class); final AtomicInteger count = new AtomicInteger(); doAnswer(new Answer<Message>() { @SuppressWarnings("serial") @Override public Message answer(InvocationOnMock invocation) throws Throwable { int theCount = count.incrementAndGet(); if (theCount > 1 && theCount < 4) { throw new JmsException("foo") { }; } if (theCount > 4) { Thread.sleep(100); return null; } return message; } }).when(consumer).receive(anyLong()); when(message.getJMSCorrelationID()).thenReturn("foo"); DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.initialize(); beanFactory.registerSingleton("taskScheduler", taskScheduler); gateway.setBeanFactory(beanFactory); gateway.afterPropertiesSet(); gateway.start(); Thread.sleep(1000); assertTrue(count.get() > 4); assertEquals(0, errors.size()); }
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); }// w ww . j a v a2 s. com 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)); } } }
From source file:org.seedstack.jms.internal.JmsPlugin.java
private void configureMessageListeners(Collection<Class<?>> listenerCandidates) { for (Class<?> candidate : listenerCandidates) { if (MessageListener.class.isAssignableFrom(candidate)) { //noinspection unchecked 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); }/*from w ww . ja v a 2 s.c o m*/ 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; DestinationType destinationType; if (!annotation.destinationTypeStr().isEmpty()) { try { destinationType = DestinationType .valueOf(application.substituteWithConfiguration(annotation.destinationTypeStr())); } catch (IllegalArgumentException e) { throw SeedException.wrap(e, JmsErrorCodes.UNKNOWN_DESTINATION_TYPE) .put(ERROR_DESTINATION_TYPE, annotation.destinationTypeStr()) .put(ERROR_CONNECTION_NAME, annotation.connection()) .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName); } } else { destinationType = annotation.destinationType(); } try { switch (destinationType) { case QUEUE: destination = session .createQueue(application.substituteWithConfiguration(annotation.destinationName())); break; case TOPIC: destination = session .createTopic(application.substituteWithConfiguration(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_DESTINATION_TYPE, destinationType.name()) .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, application.substituteWithConfiguration(annotation.connection()), session, destination, application.substituteWithConfiguration(annotation.selector()), messageListenerClass, messagePollerClass)); } } }
From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java
public void createSession(final CreateSessionCommand command) { try {/*from w w w . jav a 2s . c om*/ final Connection connection = _testConnections.get(command.getConnectionName()); if (connection == null) { throw new DistributedTestException( "No test connection found called: " + command.getConnectionName(), command); } final boolean transacted = command.getAcknowledgeMode() == Session.SESSION_TRANSACTED; final Session newSession = connection.createSession(transacted, command.getAcknowledgeMode()); LOGGER.debug("Created session " + command.getSessionName() + " with transacted = " + newSession.getTransacted() + " and acknowledgeMode = " + newSession.getAcknowledgeMode()); addSession(command.getSessionName(), newSession); } catch (final JMSException jmse) { throw new DistributedTestException("Unable to create new session: " + command, jmse); } }
From source file:org.apache.qpid.systest.management.jmx.QueueManagementTest.java
private void startAsyncConsumerOn(Destination queue, Connection asyncConnection, final CountDownLatch requiredNumberOfMessagesRead, final AtomicInteger totalConsumed) throws Exception { Session session = asyncConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(queue); consumer.setMessageListener(new MessageListener() { @Override//w w w . ja va 2 s .co m public void onMessage(Message arg0) { totalConsumed.incrementAndGet(); requiredNumberOfMessagesRead.countDown(); } }); }
From source file:nl.nn.adapterframework.extensions.esb.EsbUtils.java
public static String receiveMessageAndMoveToErrorStorage(EsbJmsListener esbJmsListener, JdbcTransactionalStorage errorStorage) { String result = null;//from w w w . ja va 2 s.c om PoolingConnectionFactory jmsConnectionFactory = null; PoolingDataSource jdbcDataSource = null; BitronixTransactionManager btm = null; javax.jms.Connection jmsConnection = null; try { jmsConnectionFactory = getPoolingConnectionFactory(esbJmsListener); if (jmsConnectionFactory != null) { jdbcDataSource = getPoolingDataSource(errorStorage); if (jdbcDataSource != null) { String instanceNameLc = AppConstants.getInstance().getString("instance.name.lc", null); String logDir = AppConstants.getInstance().getString("log.dir", null); TransactionManagerServices.getConfiguration().setServerId(instanceNameLc + ".tm"); TransactionManagerServices.getConfiguration() .setLogPart1Filename(logDir + File.separator + instanceNameLc + "-btm1.tlog"); TransactionManagerServices.getConfiguration() .setLogPart2Filename(logDir + File.separator + instanceNameLc + "-btm2.tlog"); btm = TransactionManagerServices.getTransactionManager(); jmsConnection = jmsConnectionFactory.createConnection(); Session jmsSession = null; MessageConsumer jmsConsumer = null; java.sql.Connection jdbcConnection = null; btm.begin(); log.debug("started transaction [" + btm.getCurrentTransaction().getGtrid() + "]"); try { jmsSession = jmsConnection.createSession(true, Session.AUTO_ACKNOWLEDGE); String queueName = esbJmsListener.getPhysicalDestinationShortName(); Queue queue = jmsSession.createQueue(queueName); jmsConsumer = jmsSession.createConsumer(queue); jmsConnection.start(); long timeout = 30000; log.debug("looking for message on queue [" + queueName + "] with timeout of [" + timeout + "] msec"); Message rawMessage = jmsConsumer.receive(timeout); if (rawMessage == null) { log.debug("no message found on queue [" + queueName + "]"); } else { String id = rawMessage.getJMSMessageID(); log.debug("found message on queue [" + queueName + "] with messageID [" + id + "]"); Serializable sobj = null; if (rawMessage != null) { if (rawMessage instanceof Serializable) { sobj = (Serializable) rawMessage; } else { try { sobj = new MessageWrapper(rawMessage, esbJmsListener); } catch (ListenerException e) { log.error("could not wrap non serializable message for messageId [" + id + "]", e); if (rawMessage instanceof TextMessage) { TextMessage textMessage = (TextMessage) rawMessage; sobj = textMessage.getText(); } else { sobj = rawMessage.toString(); } } } } jdbcConnection = jdbcDataSource.getConnection(); result = errorStorage.storeMessage(jdbcConnection, id, id, new Date(System.currentTimeMillis()), "moved message", null, sobj); } log.debug("committing transaction [" + btm.getCurrentTransaction().getGtrid() + "]"); btm.commit(); } catch (Exception e) { if (btm.getCurrentTransaction() != null) { log.debug("rolling back transaction [" + btm.getCurrentTransaction().getGtrid() + "]"); btm.rollback(); } log.error("exception on receiving message and moving to errorStorage", e); } finally { if (jdbcConnection != null) { jdbcConnection.close(); } if (jmsConnection != null) { jmsConnection.stop(); } if (jmsConsumer != null) { jmsConsumer.close(); } if (jmsSession != null) { jmsSession.close(); } } } } } catch (Exception e) { log.error("exception on receiving message and moving to errorStorage", e); } finally { if (jmsConnection != null) { try { jmsConnection.close(); } catch (JMSException e) { log.warn("exception on closing connection", e); } } if (jmsConnectionFactory != null) { jmsConnectionFactory.close(); } if (jdbcDataSource != null) { jdbcDataSource.close(); } if (btm != null) { btm.shutdown(); } } return result; }
From source file:org.apache.activemq.network.BrokerNetworkWithStuckMessagesTest.java
@SuppressWarnings({ "unchecked", "unused" }) private Object[] browseQueueWithJms(BrokerService broker) throws Exception { Object[] messages = null;//from w w w . j a va2 s . c o m Connection connection = null; Session session = null; try { URI brokerUri = connector.getUri(); ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUri.toString()); connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue destination = session.createQueue(queueName); QueueBrowser browser = session.createBrowser(destination); List<Message> list = new ArrayList<Message>(); for (Enumeration<Message> enumn = browser.getEnumeration(); enumn.hasMoreElements();) { list.add(enumn.nextElement()); } messages = list.toArray(); } finally { if (session != null) { session.close(); } if (connection != null) { connection.close(); } } LOG.info("+Browsed with JMS: " + messages.length); return messages; }
From source file:org.rhq.enterprise.server.drift.DriftManagerBean.java
@Override @TransactionAttribute(REQUIRES_NEW)/* ww 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(); }