List of usage examples for javax.jms MessageProducer setTimeToLive
void setTimeToLive(long timeToLive) throws JMSException;
From source file:com.fusesource.examples.activemq.SimplePublisher.java
public static void main(String args[]) { Connection connection = null; try {//www.j ava2 s . c om // JNDI lookup of JMS Connection Factory and JMS Destination Context context = new InitialContext(); ConnectionFactory factory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY_NAME); connection = factory.createConnection(); connection.start(); Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic(DESTINATION_NAME); MessageProducer producer = session.createProducer(topic); producer.setTimeToLive(MESSAGE_TIME_TO_LIVE_MILLISECONDS); for (int i = 1; i <= NUM_MESSAGES_TO_BE_SENT; i++) { TextMessage message = session.createTextMessage(i + ". message sent"); LOG.info("Sending to destination: " + DESTINATION_NAME + " this text: '" + message.getText()); producer.send(message); Thread.sleep(MESSAGE_DELAY_MILLISECONDS); } // Cleanup producer.close(); session.close(); } catch (Throwable t) { LOG.error(t); } finally { // Cleanup code // In general, you should always close producers, consumers, // sessions, and connections in reverse order of creation. // For this simple example, a JMS connection.close will // clean up all other resources. if (connection != null) { try { connection.close(); } catch (JMSException e) { LOG.error(e); } } } }
From source file:com.fusesource.examples.activemq.SimpleProducer.java
public static void main(String args[]) { Connection connection = null; try {// w w w . j a v a2 s . co m // JNDI lookup of JMS Connection Factory and JMS Destination Context context = new InitialContext(); ConnectionFactory factory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY_NAME); Destination destination = (Destination) context.lookup(DESTINATION_NAME); connection = factory.createConnection(); connection.start(); Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(destination); producer.setTimeToLive(MESSAGE_TIME_TO_LIVE_MILLISECONDS); for (int i = 1; i <= NUM_MESSAGES_TO_BE_SENT; i++) { TextMessage message = session.createTextMessage(i + ". message sent"); LOG.info("Sending to destination: " + destination.toString() + " this text: '" + message.getText()); producer.send(message); Thread.sleep(MESSAGE_DELAY_MILLISECONDS); } // Cleanup producer.close(); session.close(); } catch (Throwable t) { LOG.error(t); } finally { // Cleanup code // In general, you should always close producers, consumers, // sessions, and connections in reverse order of creation. // For this simple example, a JMS connection.close will // clean up all other resources. if (connection != null) { try { connection.close(); } catch (JMSException e) { LOG.error(e); } } } }
From source file:org.apache.activemq.usecases.DurableSubscriptionHangTestCase.java
private void produceExpiredAndOneNonExpiredMessages() throws JMSException { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName); TopicConnection connection = connectionFactory.createTopicConnection(); TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic(topicName); MessageProducer producer = session.createProducer(topic); producer.setTimeToLive(TimeUnit.SECONDS.toMillis(1)); for (int i = 0; i < 40000; i++) { sendRandomMessage(session, producer); }//w ww. java2 s.c om producer.setTimeToLive(TimeUnit.DAYS.toMillis(1)); sendRandomMessage(session, producer); connection.close(); LOG.info("produceExpiredAndOneNonExpiredMessages done"); }
From source file:org.mot.common.mq.ActiveMQFactory.java
/** * Create a new message producer onto a particular destination * /*from w w w.j a v a 2s . c om*/ * @param destination - destination queue/topic object * @return the message producer object */ public MessageProducer createMessageProducer(String channel, long ttl, boolean persistent) { Destination destination = createDestination(channel); MessageProducer msg = null; try { msg = session.createProducer(destination); msg.setTimeToLive(ttl); if (persistent) { msg.setDeliveryMode(DeliveryMode.PERSISTENT); } else { msg.setDeliveryMode(DeliveryMode.NON_PERSISTENT); } } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } return msg; }
From source file:ProducerTool.java
public void run() { Connection connection = null; try {/*from ww w. j a v a 2 s.c om*/ // Create the connection. ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url); connection = connectionFactory.createConnection(); connection.start(); // Create the session Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE); if (topic) { destination = session.createTopic(subject); } else { destination = session.createQueue(subject); } // Create the producer. MessageProducer producer = session.createProducer(destination); if (persistent) { producer.setDeliveryMode(DeliveryMode.PERSISTENT); } else { producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); } if (timeToLive != 0) { producer.setTimeToLive(timeToLive); } // Start sending messages sendLoop(session, producer); System.out.println("[" + this.getName() + "] Done."); synchronized (lockResults) { ActiveMQConnection c = (ActiveMQConnection) connection; System.out.println("[" + this.getName() + "] Results:\n"); c.getConnectionStats().dump(new IndentPrinter()); } } catch (Exception e) { System.out.println("[" + this.getName() + "] Caught: " + e); e.printStackTrace(); } finally { try { connection.close(); } catch (Throwable ignore) { } } }
From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java
public void createProducer(final CreateProducerCommand command) { try {// w w w . ja v a 2 s. c o m final Session session = _testSessions.get(command.getSessionName()); if (session == null) { throw new DistributedTestException("No test session found called: " + command.getSessionName(), command); } synchronized (session) { final Destination destination; if (command.isTopic()) { destination = session.createTopic(command.getDestinationName()); } else { destination = session.createQueue(command.getDestinationName()); } final MessageProducer jmsProducer = session.createProducer(destination); if (command.getPriority() != -1) { jmsProducer.setPriority(command.getPriority()); } if (command.getTimeToLive() > 0) { jmsProducer.setTimeToLive(command.getTimeToLive()); } if (command.getDeliveryMode() == DeliveryMode.NON_PERSISTENT || command.getDeliveryMode() == DeliveryMode.PERSISTENT) { jmsProducer.setDeliveryMode(command.getDeliveryMode()); } addProducer(command.getParticipantName(), jmsProducer); } } catch (final JMSException jmse) { throw new DistributedTestException("Unable to create new producer: " + command, jmse); } }
From source file:org.jbpm.bpel.integration.server.SoapHandler.java
protected ObjectMessage sendRequest(SOAPMessage soapMessage, Session jmsSession, JbpmContext jbpmContext) throws SOAPException, JMSException { // create a jms message to deliver the incoming content ObjectMessage jmsRequest = jmsSession.createObjectMessage(); // put the partner link identified by handle in a jms property PartnerLinkEntry partnerLinkEntry = integrationControl.getPartnerLinkEntry(portTypeName, serviceName, portName);/* ww w.j a v a 2 s . com*/ long partnerLinkId = partnerLinkEntry.getId(); jmsRequest.setLongProperty(IntegrationConstants.PARTNER_LINK_ID_PROP, partnerLinkId); Operation operation = determineOperation(soapMessage); if (operation == null) throw new SOAPException("could not determine operation to perform"); // put the operation name in a jms property String operationName = operation.getName(); jmsRequest.setStringProperty(IntegrationConstants.OPERATION_NAME_PROP, operationName); log.debug("received request: partnerLink=" + partnerLinkId + ", operation=" + operationName); // extract message content HashMap requestParts = new HashMap(); formatter.readMessage(operationName, soapMessage, requestParts, MessageDirection.INPUT); jmsRequest.setObject(requestParts); // fill message properties BpelProcessDefinition process = integrationControl.getDeploymentDescriptor() .findProcessDefinition(jbpmContext); MessageType requestType = process.getImportDefinition() .getMessageType(operation.getInput().getMessage().getQName()); fillCorrelationProperties(requestParts, jmsRequest, requestType.getPropertyAliases()); // set up producer MessageProducer producer = jmsSession.createProducer(partnerLinkEntry.getDestination()); try { // is the exchange pattern request/response? if (operation.getOutput() != null) { Destination replyTo = integrationControl.getIntegrationServiceFactory().getResponseDestination(); jmsRequest.setJMSReplyTo(replyTo); // have jms discard request message if response timeout expires Number responseTimeout = getResponseTimeout(jbpmContext); if (responseTimeout != null) producer.setTimeToLive(responseTimeout.longValue()); } else { // have jms discard message if one-way timeout expires Number oneWayTimeout = getOneWayTimeout(jbpmContext); if (oneWayTimeout != null) producer.setTimeToLive(oneWayTimeout.longValue()); } // send request message producer.send(jmsRequest); log.debug("sent request: " + RequestListener.messageToString(jmsRequest)); return jmsRequest; } finally { // release producer resources producer.close(); } }
From source file:org.wso2.carbon.identity.agent.outbound.server.UserStoreServerEndpoint.java
/** * Process response message and send to response queue. * @param message Message//from w ww. j a v a 2s .c o m */ private void processResponse(String message) { JMSConnectionFactory connectionFactory = new JMSConnectionFactory(); Connection connection = null; MessageProducer producer; try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Start processing response message: " + message); } MessageBrokerConfig conf = ServerConfigurationBuilder.build().getMessagebroker(); connectionFactory.createActiveMQConnectionFactory(conf.getUrl()); connection = connectionFactory.createConnection(); connectionFactory.start(connection); javax.jms.Session session = connectionFactory.createSession(connection); Destination responseQueue = connectionFactory.createQueueDestination(session, UserStoreConstants.QUEUE_NAME_RESPONSE); producer = connectionFactory.createMessageProducer(session, responseQueue, DeliveryMode.NON_PERSISTENT); producer.setTimeToLive(UserStoreConstants.QUEUE_SERVER_MESSAGE_LIFETIME); JSONObject resultObj = new JSONObject(message); String responseData = resultObj.get(UserStoreConstants.UM_JSON_ELEMENT_RESPONSE_DATA).toString(); String correlationId = (String) resultObj .get(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA_CORRELATION_ID); UserOperation responseOperation = new UserOperation(); responseOperation.setCorrelationId(correlationId); responseOperation.setResponseData(responseData.toString()); ObjectMessage responseMessage = session.createObjectMessage(); responseMessage.setObject(responseOperation); responseMessage.setJMSCorrelationID(correlationId); producer.send(responseMessage); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Finished processing response message: " + message); } } catch (JMSException e) { LOGGER.error("Error occurred while sending message: " + message, e); } catch (JSONException e) { LOGGER.error("Error occurred while reading json payload of message: " + message, e); } catch (JMSConnectionException e) { LOGGER.error("Error occurred while creating JMS connection to send message: " + message, e); } finally { try { connectionFactory.closeConnection(connection); } catch (JMSConnectionException e) { LOGGER.error("Error occurred while closing JMS connection", e); } } }
From source file:nl.nn.adapterframework.jms.JMSFacade.java
public MessageProducer getMessageProducer(Session session, Destination destination) throws NamingException, JMSException { MessageProducer mp; if (useJms102()) { if (useTopicFunctions) { mp = getTopicPublisher((TopicSession) session, (Topic) destination); } else {/*from w ww. ja v a 2 s . co m*/ mp = getQueueSender((QueueSession) session, (Queue) destination); } } else { mp = session.createProducer(destination); } if (getMessageTimeToLive() > 0) mp.setTimeToLive(getMessageTimeToLive()); return mp; }
From source file:org.wso2.carbon.event.output.adapter.jms.internal.util.JMSMessageSender.java
/** * Perform actual send of JMS message to the Destination selected *///ww w. j a v a 2s . co m public void send(Object message, JMSEventAdapter.PublisherDetails publisherDetails, String jmsHeaders) { Map<String, String> messageProperties = publisherDetails.getMessageConfig(); Boolean jtaCommit = getBooleanProperty(messageProperties, BaseConstants.JTA_COMMIT_AFTER_SEND); Boolean rollbackOnly = getBooleanProperty(messageProperties, BaseConstants.SET_ROLLBACK_ONLY); Boolean persistent = getBooleanProperty(messageProperties, JMSConstants.JMS_DELIVERY_MODE); Integer priority = getIntegerProperty(messageProperties, JMSConstants.JMS_PRIORITY); Integer timeToLive = getIntegerProperty(messageProperties, JMSConstants.JMS_TIME_TO_LIVE); MessageProducer producer = null; Destination destination = null; Session session = null; boolean sendingSuccessful = false; JMSConnectionFactory.JMSPooledConnectionHolder pooledConnection = null; try { pooledConnection = jmsConnectionFactory.getConnectionFromPool(); producer = pooledConnection.getProducer(); session = pooledConnection.getSession(); Message jmsMessage = convertToJMSMessage(message, publisherDetails.getMessageConfig(), session); setJMSTransportHeaders(jmsMessage, jmsHeaders); // Do not commit, if message is marked for rollback if (rollbackOnly != null && rollbackOnly) { jtaCommit = Boolean.FALSE; } if (persistent != null) { try { producer.setDeliveryMode(DeliveryMode.PERSISTENT); } catch (JMSException e) { handleConnectionException("Error setting JMS Producer for PERSISTENT delivery", e); } } if (priority != null) { try { producer.setPriority(priority); } catch (JMSException e) { handleConnectionException("Error setting JMS Producer priority to : " + priority, e); } } if (timeToLive != null) { try { producer.setTimeToLive(timeToLive); } catch (JMSException e) { handleConnectionException("Error setting JMS Producer TTL to : " + timeToLive, e); } } // perform actual message sending // try { if (jmsSpec11 || isQueue == null) { producer.send(jmsMessage); } else { if (isQueue) { ((QueueSender) producer).send(jmsMessage); } else { ((TopicPublisher) producer).publish(jmsMessage); } } sendingSuccessful = true; if (log.isDebugEnabled()) { // // set the actual MessageID to the message context for use by any others down the line String msgId = null; try { msgId = jmsMessage.getJMSMessageID(); } catch (JMSException jmse) { log.error(jmse.getMessage(), jmse); } log.debug(" with JMS Message ID : " + msgId + " to destination : " + producer.getDestination()); } } catch (JMSException e) { handleConnectionException("Error sending message to destination : " + destination, e); } catch (Exception e) { log.error(e.getMessage(), e); } finally { if (jtaCommit != null) { try { if (session.getTransacted()) { if (sendingSuccessful && (rollbackOnly == null || !rollbackOnly)) { session.commit(); } else { session.rollback(); } } if (log.isDebugEnabled()) { log.debug((sendingSuccessful ? "Committed" : "Rolled back") + " local (JMS Session) Transaction"); } } catch (Exception e) { handleConnectionException("Error committing/rolling back local (i.e. session) " + "transaction after sending of message "//with MessageContext ID : " + + " to destination : " + destination, e); } } if (pooledConnection != null) { jmsConnectionFactory.returnPooledConnection(pooledConnection); } } }