List of usage examples for javax.jms Session close
void close() throws JMSException;
From source file:jenkins.plugins.logstash.persistence.ActiveMqDao.java
@Override public void push(String data) throws IOException { TopicConnection connection = null;//from www. j a va 2 s . co m Session session = null; try { // Create a Connection connection = connectionFactory.createTopicConnection(); connection.start(); // Create a Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Create the destination Queue Destination destination = session.createTopic(key); // Create the MessageProducer from the Session to the Queue MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.PERSISTENT); // Create the message TextMessage message = session.createTextMessage(data); message.setJMSType("application/json"); // Tell the producer to send the message producer.send(message); //logger.log( Level.FINER, String.format("JMS message sent with ID [%s]", message.getJMSMessageID())); } catch (JMSException e) { logger.log(Level.SEVERE, null != e.getMessage() ? e.getMessage() : e.getClass().getName()); throw new IOException(e); } finally { // Clean up try { if (null != session) session.close(); } catch (JMSException e) { logger.log(Level.WARNING, null != e.getMessage() ? e.getMessage() : e.getClass().getName()); } try { if (null != connection) connection.close(); } catch (JMSException e) { logger.log(Level.WARNING, null != e.getMessage() ? e.getMessage() : e.getClass().getName()); } } }
From source file:org.dawnsci.commandserver.core.consumer.RemoteSubmission.java
/** * Submits the bean onto the server. From there events about this * bean are tacked by monitoring the status queue. * /* w w w. ja va 2 s.co m*/ * @param uri * @param bean */ public synchronized TextMessage submit(StatusBean bean, boolean prepareBean) throws Exception { if (getQueueName() == null || "".equals(getQueueName())) throw new Exception("Please specify a queue name!"); Connection send = null; Session session = null; MessageProducer producer = null; try { QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri); send = connectionFactory.createConnection(); session = send.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue(queueName); producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.PERSISTENT); ObjectMapper mapper = new ObjectMapper(); if (getTimestamp() < 1) setTimestamp(System.currentTimeMillis()); if (getPriority() < 1) setPriority(1); if (getLifeTime() < 1) setLifeTime(7 * 24 * 60 * 60 * 1000); // 7 days in ms if (prepareBean) { if (bean.getUserName() == null) bean.setUserName(System.getProperty("user.name")); bean.setUniqueId(uniqueId); bean.setSubmissionTime(getTimestamp()); } String jsonString = mapper.writeValueAsString(bean); TextMessage message = session.createTextMessage(jsonString); message.setJMSMessageID(uniqueId); message.setJMSExpiration(getLifeTime()); message.setJMSTimestamp(getTimestamp()); message.setJMSPriority(getPriority()); producer.send(message); return message; } finally { if (send != null) send.close(); if (session != null) session.close(); if (producer != null) producer.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 w w . ja v a 2 s . c o 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:com.cws.esolutions.core.utils.MQUtils.java
/** * Puts an MQ message on a specified queue and returns the associated * correlation ID for retrieval upon request. * * @param connName - The connection name to utilize * @param authData - The authentication data to utilize, if required * @param requestQueue - The request queue name to put the message on * @param targetHost - The target host for the message * @param value - The data to place on the request. MUST be <code>Serialiable</code> * @return <code>String</code> - the JMS correlation ID associated with the message * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing *///w ww. ja v a2s . co m public static final synchronized String sendMqMessage(final String connName, final List<String> authData, final String requestQueue, final String targetHost, final Serializable value) throws UtilityException { final String methodName = MQUtils.CNAME + "sendMqMessage(final String connName, final List<String> authData, final String requestQueue, final String targetHost, final Serializable value) throws UtilityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", connName); DEBUGGER.debug("Value: {}", requestQueue); DEBUGGER.debug("Value: {}", targetHost); DEBUGGER.debug("Value: {}", value); } Connection conn = null; Session session = null; Context envContext = null; InitialContext initCtx = null; MessageProducer producer = null; ConnectionFactory connFactory = null; final String correlationId = RandomStringUtils.randomAlphanumeric(64); if (DEBUG) { DEBUGGER.debug("correlationId: {}", correlationId); } try { try { 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); } // Create a MessageProducer from the Session to the Topic or Queue if (envContext != null) { try { producer = session.createProducer((Destination) envContext.lookup(requestQueue)); } catch (NamingException nx) { throw new UtilityException(nx.getMessage(), nx); } } else { Destination destination = session.createTopic(requestQueue); if (DEBUG) { DEBUGGER.debug("Destination: {}", destination); } producer = session.createProducer(destination); } if (producer == null) { throw new JMSException("Failed to create a producer object"); } producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); if (DEBUG) { DEBUGGER.debug("MessageProducer: {}", producer); } ObjectMessage message = session.createObjectMessage(true); message.setJMSCorrelationID(correlationId); message.setStringProperty("targetHost", targetHost); if (DEBUG) { DEBUGGER.debug("correlationId: {}", correlationId); } message.setObject(value); if (DEBUG) { DEBUGGER.debug("ObjectMessage: {}", message); } producer.send(message); } 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 correlationId; }
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()} *//* w w w.ja va 2 s. c om*/ @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.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java
@Override public boolean sendMessage(Run<?, ?> build, TaskListener listener, MessageUtils.MESSAGE_TYPE type, String props, String content) {/*from ww w. ja va 2s.co m*/ Connection connection = null; Session session = null; MessageProducer publisher = null; try { String ltopic = getTopic(); if (provider.getAuthenticationMethod() != null && ltopic != null && provider.getBroker() != null) { ActiveMQConnectionFactory connectionFactory = provider.getConnectionFactory(); connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createTopic(ltopic); publisher = session.createProducer(destination); TextMessage message; message = session.createTextMessage(""); message.setJMSType(JSON_TYPE); message.setStringProperty("CI_NAME", build.getParent().getName()); message.setStringProperty("CI_TYPE", type.getMessage()); if (!build.isBuilding()) { message.setStringProperty("CI_STATUS", (build.getResult() == Result.SUCCESS ? "passed" : "failed")); } StrSubstitutor sub = new StrSubstitutor(build.getEnvironment(listener)); if (props != null && !props.trim().equals("")) { Properties p = new Properties(); p.load(new StringReader(props)); @SuppressWarnings("unchecked") Enumeration<String> e = (Enumeration<String>) p.propertyNames(); while (e.hasMoreElements()) { String key = e.nextElement(); message.setStringProperty(key, sub.replace(p.getProperty(key))); } } message.setText(sub.replace(content)); publisher.send(message); log.info("Sent " + type.toString() + " message for job '" + build.getParent().getName() + "' to topic '" + ltopic + "':\n" + formatMessage(message)); } else { log.severe("One or more of the following is invalid (null): user, password, topic, broker."); return false; } } catch (Exception e) { log.log(Level.SEVERE, "Unhandled exception in perform.", e); } finally { if (publisher != null) { try { publisher.close(); } catch (JMSException e) { } } if (session != null) { try { session.close(); } catch (JMSException e) { } } if (connection != null) { try { connection.close(); } catch (JMSException e) { } } } return true; }
From source file:net.timewalker.ffmq4.common.connection.AbstractConnection.java
/** * Close remaining sessions/* w ww .ja va 2 s.com*/ */ private void closeRemainingSessions() { if (sessions == null) return; List<AbstractSession> sessionsToClose = new ArrayList<>(sessions.size()); synchronized (sessions) { sessionsToClose.addAll(sessions.values()); } for (int n = 0; n < sessionsToClose.size(); n++) { Session session = sessionsToClose.get(n); log.debug("Auto-closing unclosed session : " + session); try { session.close(); } catch (JMSException e) { ErrorTools.log(e, log); } } }
From source file:net.timewalker.ffmq4.listeners.ClientProcessor.java
private CloseSessionResponse processCloseSession(CloseSessionQuery query) throws JMSException { Session localSession = lookupSession(query); localSession.close(); return new CloseSessionResponse(); }
From source file:nl.nn.adapterframework.extensions.esb.EsbUtils.java
public static String receiveMessageAndMoveToErrorStorage(EsbJmsListener esbJmsListener, JdbcTransactionalStorage errorStorage) { String result = null;/*ww w .j a va 2 s .c o m*/ 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:nl.nn.adapterframework.jms.MessagingSource.java
public void releaseSession(Session session) { if (session != null) { if (connectionsArePooled()) { Connection connection = (Connection) connectionTable.remove(session); try { // do not log, as this may happen very often // if (log.isDebugEnabled()) log.debug(getLogPrefix()+"closing Session, openSessionCount will become ["+(openSessionCount.getValue()-1)+"]"); session.close(); openSessionCount.decrease(); } catch (JMSException e) { log.error(getLogPrefix() + "Exception closing Session", e); } finally { releaseConnection(connection); }/* w w w.j a v a2 s . co m*/ } else { try { if (log.isDebugEnabled()) log.debug(getLogPrefix() + "closing Session"); session.close(); } catch (JMSException e) { log.error(getLogPrefix() + "Exception closing Session", e); } } } }