List of usage examples for javax.jms Connection createSession
Session createSession(boolean transacted, int acknowledgeMode) throws JMSException;
From source file:org.rhq.enterprise.server.drift.DriftManagerBean.java
@Override @TransactionAttribute(REQUIRES_NEW)/* w w w. j a v a 2 s . co m*/ public void addFiles(Subject subject, int resourceId, String driftDefName, String token, long zipSize, InputStream zipStream) throws Exception { Connection connection = factory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(fileQueue); ObjectMessage msg = session .createObjectMessage(new DriftUploadRequest(resourceId, driftDefName, token, zipSize, zipStream)); producer.send(msg); connection.close(); }
From source file:org.apache.servicemix.jms.jca.JcaConsumerProcessor.java
public void process(MessageExchange exchange) throws Exception { Context context = (Context) pendingMessages.remove(exchange.getExchangeId()); Message message = (Message) context.getProperty(Message.class.getName()); Message response = null;//from www. j av a 2 s. co m Connection connection = null; try { if (exchange.getStatus() == ExchangeStatus.DONE) { return; } else if (exchange.getStatus() == ExchangeStatus.ERROR) { if (endpoint.isRollbackOnError()) { TransactionManager tm = (TransactionManager) endpoint.getServiceUnit().getComponent() .getComponentContext().getTransactionManager(); tm.setRollbackOnly(); return; } else if (exchange instanceof InOnly) { LOG.info("Exchange in error: " + exchange, exchange.getError()); return; } else { connection = connectionFactory.createConnection(); Session session = connection.createSession(true, Session.SESSION_TRANSACTED); Exception error = exchange.getError(); if (error == null) { error = new Exception("Exchange in error"); } response = session.createObjectMessage(error); MessageProducer producer = session.createProducer(message.getJMSReplyTo()); if (endpoint.isUseMsgIdInResponse()) { response.setJMSCorrelationID(message.getJMSMessageID()); } else { response.setJMSCorrelationID(message.getJMSCorrelationID()); } producer.send(response); } } else { connection = connectionFactory.createConnection(); Session session = connection.createSession(true, Session.SESSION_TRANSACTED); response = fromNMSResponse(exchange, context, session); if (response != null) { MessageProducer producer = session.createProducer(message.getJMSReplyTo()); if (endpoint.isUseMsgIdInResponse()) { response.setJMSCorrelationID(message.getJMSMessageID()); } else { response.setJMSCorrelationID(message.getJMSCorrelationID()); } producer.send(response); } } } finally { if (connection != null) { connection.close(); } if (exchange.getStatus() == ExchangeStatus.ACTIVE) { exchange.setStatus(ExchangeStatus.DONE); channel.send(exchange); } } }
From source file:org.gss_project.gss.server.ejb.AdminAPIBean.java
public void indexFile(Long fileId, boolean delete) { Connection qConn = null; Session session = null;//from w ww.ja va 2 s . c o m MessageProducer sender = null; try { Context jndiCtx = new InitialContext(); ConnectionFactory factory = (QueueConnectionFactory) jndiCtx.lookup("java:/JmsXA"); Queue queue = (Queue) jndiCtx.lookup("queue/gss-indexingQueue"); qConn = factory.createConnection(); session = qConn.createSession(false, Session.AUTO_ACKNOWLEDGE); sender = session.createProducer(queue); MapMessage map = session.createMapMessage(); map.setObject("id", fileId); map.setBoolean("delete", delete); sender.send(map); } catch (NamingException e) { logger.error("Index was not updated: ", e); } catch (JMSException e) { logger.error("Index was not updated: ", e); } finally { try { if (sender != null) sender.close(); if (session != null) session.close(); if (qConn != null) qConn.close(); } catch (JMSException e) { logger.warn(e); } } }
From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java
public void send(Scenario scenario) throws Exception { Connection connection = null; try {// ww w .j a va 2 s . c o m connection = getConnection(false, false); connection.start(); Session session = null; try { session = connection.createSession(scenario.isTransacted(), scenario.getAcknowledge()); Destination destination = createInputDestination(session, scenario); MessageProducer producer = null; try { producer = session.createProducer(destination); if (scenario.isPersistent()) { producer.setDeliveryMode(DeliveryMode.PERSISTENT); } scenario.send(session, producer); } finally { if (producer != null) { producer.close(); } } } finally { if (session != null) { session.close(); } } } finally { if (connection != null) { connection.close(); } } }
From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java
public Message receive(Scenario scenario) throws Exception { assertNotNull("scenario is null!", scenario); Connection connection = null; try {/*from w w w .ja va2 s. c o m*/ connection = getConnection(false, false); connection.start(); Session session = null; try { session = connection.createSession(scenario.isTransacted(), scenario.getAcknowledge()); Destination destination = createOutputDestination(session, scenario); MessageConsumer consumer = null; try { consumer = session.createConsumer(destination); return scenario.receive(session, consumer); } finally { if (consumer != null) { consumer.close(); } } } finally { if (session != null) { session.close(); } } } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { logger.warn("Failed to close jms connection: " + e.getMessage()); } } } }
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 *///from w w w . j a va 2 s.c o 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.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java
/** * Purge destinations for clean test setup. Especially applicable to WMQ tests, as messages from * other tests may still exist from other tests' runs. * <p/>/* ww w . java 2 s . c om*/ * Well-behaving tests should drain both inbound and outbound destinations, as well as any intermediary ones. * @param destination destination name without any protocol specifics */ protected void purge(final String destination) throws JMSException { Connection c = null; Session s = null; try { logger.debug("purging queue : " + destination); c = getConnection(false, false); assertNotNull(c); c.start(); s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination d = s.createQueue(destination); MessageConsumer consumer = s.createConsumer(d); while (consumer.receiveNoWait() != null) { logger.debug("Destination " + destination + " isn't empty, draining it"); } } catch (Exception e) { logger.error("unable to purge : " + destination); } finally { if (c != null) { c.stop(); if (s != null) { s.close(); } try { c.close(); } catch (JMSException e) { logger.warn("Failed to close jms connection: " + e.getMessage()); } } } }
From source file:org.apache.synapse.message.store.impl.jms.JmsStore.java
/** * Creates a new JMS Session.//w w w . j a v a 2 s .c o m * * @param connection The JMS Connection that must be used when creating the session. * @param mode Acknowledgement mode that must be used for this session. * @param isProducerSession Type of the session going to create * @return A JMS Session. * @throws JMSException */ public Session newSession(Connection connection, int mode, boolean isProducerSession) throws JMSException { if (connection == null) { logger.error(nameString() + " cannot create JMS Session. Invalid connection."); return null; } Session session; if (isVersion11) { if (isGuaranteedDeliveryEnable && isProducerSession) { session = connection.createSession(true, Session.SESSION_TRANSACTED); } else { session = connection.createSession(false, mode); } } else { if (isGuaranteedDeliveryEnable && isProducerSession) { session = ((QueueConnection) connection).createQueueSession(true, Session.SESSION_TRANSACTED); } else { session = ((QueueConnection) connection).createQueueSession(false, mode); } } if (logger.isDebugEnabled()) { logger.debug(nameString() + ". Created JMS Session."); } return session; }
From source file:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java
@Override public String waitForMessage(Run<?, ?> build, String selector, String variable, Integer timeout) { String ip = null;/* w w w . j a v a 2 s. c o m*/ try { ip = Inet4Address.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { log.severe("Unable to get localhost IP address."); } String ltopic = getTopic(); if (ip != null && provider.getAuthenticationMethod() != null && ltopic != null && provider.getBroker() != null) { log.info("Waiting for message with selector: " + selector); Connection connection = null; MessageConsumer consumer = null; try { ActiveMQConnectionFactory connectionFactory = provider.getConnectionFactory(); connection = connectionFactory.createConnection(); connection.setClientID(ip + "_" + UUID.randomUUID().toString()); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic destination = session.createTopic(ltopic); consumer = session.createConsumer(destination, selector); Message message = consumer.receive(timeout * 60 * 1000); if (message != null) { String value = getMessageBody(message); if (build != null) { if (StringUtils.isNotEmpty(variable)) { EnvVars vars = new EnvVars(); vars.put(variable, value); build.addAction(new CIEnvironmentContributingAction(vars)); } } log.info("Received message with selector: " + selector + "\n" + formatMessage(message)); return value; } log.info("Timed out waiting for message!"); } catch (Exception e) { log.log(Level.SEVERE, "Unhandled exception waiting for message.", e); } finally { if (consumer != null) { try { consumer.close(); } catch (Exception e) { } } if (connection != null) { try { connection.close(); } catch (Exception e) { } } } } else { log.severe("One or more of the following is invalid (null): ip, user, password, topic, broker."); } return null; }
From source file:com.seajas.search.profiler.service.profiler.ProfilerService.java
/** * Default constructor.//from w w w .j a va 2 s.c o m * * @param jobNames * @param jobDescriptions * @param availableApplicationLanguages * @param availableSearchLanguages * @param jmsRequestQueue * @param jmsConnectionFactory * @throws Exception */ @Autowired public ProfilerService(@Value("${profiler.project.search.enricher.jobs}") final String jobNames, @Value("${profiler.project.search.enricher.jobs.descriptions}") final String jobDescriptions, @Value("${profiler.project.languages.available}") final String availableApplicationLanguages, @Value("${profiler.project.search.languages}") final String availableSearchLanguages, @Qualifier("jmsPrimaryRequestQueue") final ActiveMQQueue jmsRequestQueue, @Qualifier("connectionFactory") final ConnectionFactory jmsConnectionFactory) throws Exception { /* InputStream caCertificate = getClass().getClassLoader().getResourceAsStream("ca.crt"); LicenseValidator.validateLicenseFile(caCertificate, licenseFile); * * try { caCertificate.close(); } catch (IOException e) { logger.error("Could not close the CA certificate stream."); } */ String[] names = jobNames.split(","); String[] descriptions = jobDescriptions.split(","); this.jobNames = new LinkedHashMap<String, String>(); for (int i = 0; i < names.length; i++) this.jobNames.put(names[i].trim(), descriptions[i].trim()); this.availableApplicationLanguages = Arrays .asList(StringUtils.tokenizeToStringArray(availableApplicationLanguages, ",", true, true)); this.availableSearchLanguages = Arrays .asList(StringUtils.tokenizeToStringArray(availableSearchLanguages, ",", true, true)); // Keep track of the active consumers on the request channel Connection connection = jmsConnectionFactory.createConnection(); Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); connection.start(); Destination destinationAdvisory = AdvisorySupport.getConsumerAdvisoryTopic(jmsRequestQueue); MessageConsumer consumerAdvisory = session.createConsumer(destinationAdvisory); consumerAdvisory.setMessageListener(new MessageListener() { @Override public void onMessage(final Message message) { try { Object consumerCount = ((ActiveMQMessage) message).getProperty("consumerCount"); if (consumerCount != null) { String clientId = ((ActiveMQMessage) message).getConnection().getConnectionInfo() .getClientId(); if (activeContenderClients.contains(clientId) && ((Integer) consumerCount == 0)) { if (staticLogger.isInfoEnabled()) staticLogger.info("Client with ID " + clientId + " was dropped from the current consumer-clients"); activeContenderClients.remove(clientId); } else if (!activeContenderClients.contains(clientId) && ((Integer) consumerCount > 0)) { if (staticLogger.isInfoEnabled()) staticLogger.info("Client with ID " + clientId + " was added to the current consumer-clients"); activeContenderClients.add(clientId); } } } catch (IOException e) { staticLogger.error("Could not retrieve consumer count from connection message", e); } } }); }