List of usage examples for javax.jms Session createProducer
MessageProducer createProducer(Destination destination) throws JMSException;
From source file:org.apache.activemq.usecases.RequestReplyToTopicViaThreeNetworkHopsTest.java
/** * Test one destination between the given "producer broker" and "consumer broker" specified. *//*from ww w .ja va2 s.co m*/ public void testOneDest(Connection conn, Session sess, Destination cons_dest, int num_msg) throws Exception { Destination prod_dest; MessageProducer msg_prod; // // Create the Producer to the echo request Queue // LOG.trace("Creating echo queue and producer"); prod_dest = sess.createQueue("echo"); msg_prod = sess.createProducer(prod_dest); // // Pass messages around. // testMessages(sess, msg_prod, cons_dest, num_msg); msg_prod.close(); }
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 ww w . j av a2s .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:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java
@Override public boolean sendMessage(Run<?, ?> build, TaskListener listener, MessageUtils.MESSAGE_TYPE type, String props, String content) {//www .j av a 2 s.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:nl.nn.adapterframework.jms.JMSFacade.java
public MessageProducer getMessageProducer(Session session, Destination destination) throws NamingException, JMSException { MessageProducer mp;/*from w w w .ja v a2s.c o m*/ if (useJms102()) { if (useTopicFunctions) { mp = getTopicPublisher((TopicSession) session, (Topic) destination); } else { mp = getQueueSender((QueueSession) session, (Queue) destination); } } else { mp = session.createProducer(destination); } if (getMessageTimeToLive() > 0) mp.setTimeToLive(getMessageTimeToLive()); return mp; }
From source file:tools.ProducerTool.java
@Override public void run() { Connection connection = null; Session session = null; try {/* w ww. j av a 2s. co m*/ connection = connectionFactory.createConnection(); if (clientId != null) { connection.setClientID(clientId); } 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); } } } MessageProducer producer = session.createProducer(destination); if (durable) { producer.setDeliveryMode(DeliveryMode.PERSISTENT); } else { producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); } int numMessagesToSend = useFinalControlMessage ? numMessages - 1 : numMessages; for (int i = 0; i < numMessagesToSend; i++) { String messageText = "Message " + i + " at " + new Date(); if (bytesLength > -1) { byte[] messageTextBytes = messageText.getBytes(StandardCharsets.UTF_8); BytesMessage bytesMessage = session.createBytesMessage(); bytesMessage.writeBytes(messageTextBytes); if (messageTextBytes.length < bytesLength) { byte[] paddingBytes = new byte[bytesLength - messageTextBytes.length]; bytesMessage.writeBytes(paddingBytes); } if (messageGroupId != null) { bytesMessage.setStringProperty("JMSXGroupID", messageGroupId); } LOGGER.info("Sending bytes message"); producer.send(bytesMessage); } else { TextMessage textMessage = session.createTextMessage(messageText); if (messageGroupId != null) { textMessage.setStringProperty("JMSXGroupID", messageGroupId); } LOGGER.info("Sending text message: " + messageText); producer.send(textMessage); } if (perMessageSleepMS > 0) { Thread.sleep(perMessageSleepMS); } if (transacted) { if ((i + 1) % batchSize == 0) { session.commit(); } } } if (useFinalControlMessage) { Message message = session.createMessage(); if (messageGroupId != null) { message.setStringProperty("JMSXGroupID", messageGroupId); } LOGGER.info("Sending message"); producer.send(message); if (transacted) { session.commit(); } } producer.close(); } catch (Exception ex) { LOGGER.error("ProducerTool 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 session", e); } } } }
From source file:nl.nn.adapterframework.jms.JMSFacade.java
public String send(Session session, Destination dest, Message message, boolean ignoreInvalidDestinationException) throws NamingException, JMSException { try {/*w w w . j a v a 2 s. c om*/ if (useJms102()) { if (dest instanceof Topic) { return sendByTopic((TopicSession) session, (Topic) dest, message); } else { return sendByQueue((QueueSession) session, (Queue) dest, message); } } else { MessageProducer mp = session.createProducer(dest); mp.send(message); mp.close(); return message.getJMSMessageID(); } } catch (InvalidDestinationException e) { if (ignoreInvalidDestinationException) { log.warn("queue [" + dest + "] doesn't exist"); return null; } else { throw e; } } }
From source file:org.apache.qpid.test.utils.QpidBrokerTestCase.java
/** * Send messages to the given destination. * * If session is transacted then messages will be committed before returning * * @param session the session to use for sending * @param destination where to send them to * @param count no. of messages to send/* ww w . j ava 2 s .co m*/ * * @param offset offset allows the INDEX value of the message to be adjusted. * @param batchSize the batchSize in which to commit, 0 means no batching, * but a single commit at the end * @return the sent message * * @throws Exception */ public List<Message> sendMessage(Session session, Destination destination, int count, int offset, int batchSize) throws Exception { List<Message> messages = new ArrayList<Message>(count); MessageProducer producer = session.createProducer(destination); int i = offset; for (; i < (count + offset); i++) { Message next = createNextMessage(session, i); producer.send(next); if (session.getTransacted() && batchSize > 0) { if (i % batchSize == 0) { session.commit(); } } messages.add(next); } // Ensure we commit the last messages // Commit the session if we are transacted and // we have no batchSize or // our count is not divible by batchSize. if (session.getTransacted() && ( batchSize == 0 || (i-1) % batchSize != 0)) { session.commit(); } return messages; }
From source file:org.springframework.integration.jms.JmsOutboundGateway.java
/** * Creates the MessageConsumer before sending the request Message since we are generating * our own correlationId value for the MessageSelector. *//*from www . j a v a 2 s. co m*/ private javax.jms.Message doSendAndReceiveWithGeneratedCorrelationId(Destination requestDestination, javax.jms.Message jmsRequest, Destination replyTo, Session session, int priority) throws JMSException { MessageProducer messageProducer = null; try { messageProducer = session.createProducer(requestDestination); Assert.state(this.correlationKey != null, "correlationKey must not be null"); String messageSelector = null; if (!this.correlationKey.equals("JMSCorrelationID*") || jmsRequest.getJMSCorrelationID() == null) { String correlationId = UUID.randomUUID().toString().replaceAll("'", "''"); if (this.correlationKey.equals("JMSCorrelationID")) { jmsRequest.setJMSCorrelationID(correlationId); messageSelector = "JMSCorrelationID = '" + correlationId + "'"; } else { jmsRequest.setStringProperty(this.correlationKey, correlationId); jmsRequest.setJMSCorrelationID(null); messageSelector = this.correlationKey + " = '" + correlationId + "'"; } } else { messageSelector = "JMSCorrelationID = '" + jmsRequest.getJMSCorrelationID() + "'"; } this.sendRequestMessage(jmsRequest, messageProducer, priority); return retryableReceiveReply(session, replyTo, messageSelector); } finally { JmsUtils.closeMessageProducer(messageProducer); } }
From source file:org.springframework.integration.jms.JmsOutboundGateway.java
/** * Creates the MessageConsumer before sending the request Message since we do not need any correlation. */// w ww. j av a 2 s. c om private javax.jms.Message doSendAndReceiveWithTemporaryReplyToDestination(Destination requestDestination, javax.jms.Message jmsRequest, Destination replyTo, Session session, int priority) throws JMSException { MessageProducer messageProducer = null; MessageConsumer messageConsumer = null; try { messageProducer = session.createProducer(requestDestination); messageConsumer = session.createConsumer(replyTo); this.sendRequestMessage(jmsRequest, messageProducer, priority); return this.receiveReplyMessage(messageConsumer); } finally { JmsUtils.closeMessageProducer(messageProducer); JmsUtils.closeMessageConsumer(messageConsumer); } }
From source file:org.springframework.integration.jms.JmsOutboundGateway.java
private javax.jms.Message doSendAndReceiveAsyncDefaultCorrelation(Destination requestDestination, javax.jms.Message jmsRequest, Session session, int priority) throws JMSException { String correlationId = null;/* w w w. j av a2s . co m*/ MessageProducer messageProducer = null; try { messageProducer = session.createProducer(requestDestination); LinkedBlockingQueue<javax.jms.Message> replyQueue = new LinkedBlockingQueue<javax.jms.Message>(1); this.sendRequestMessage(jmsRequest, messageProducer, priority); correlationId = jmsRequest.getJMSMessageID(); if (logger.isDebugEnabled()) { logger.debug(this.getComponentName() + " Sent message with correlationId " + correlationId); } this.replies.put(correlationId, replyQueue); /* * Check to see if the reply arrived before we obtained the correlationId */ synchronized (this.earlyOrLateReplies) { TimedReply timedReply = this.earlyOrLateReplies.remove(correlationId); if (timedReply != null) { if (logger.isDebugEnabled()) { logger.debug("Found early reply with correlationId " + correlationId); } replyQueue.add(timedReply.getReply()); } } return obtainReplyFromContainer(correlationId, replyQueue); } finally { JmsUtils.closeMessageProducer(messageProducer); if (correlationId != null) { this.replies.remove(correlationId); } } }