Example usage for javax.jms Session createProducer

List of usage examples for javax.jms Session createProducer

Introduction

In this page you can find the example usage for javax.jms Session createProducer.

Prototype


MessageProducer createProducer(Destination destination) throws JMSException;

Source Link

Document

Creates a MessageProducer to send messages to the specified destination.

Usage

From source file:fr.xebia.sample.springframework.jms.requestreply.RequestReplyClientInvoker.java

/**
 * Request/Reply SpringFramework sample.
 * //from w w w  . j ava2 s.  co m
 * @param request
 *            sent to the remote service
 * @return reply returned by the remote service
 * @throws JMSException
 */
public String requestReply(String request) throws JMSException {

    Connection connection = connectionFactory.createConnection();
    try {
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        try {
            MessageProducer messageProducer = session.createProducer(this.requestDestination);
            try {
                Message requestMessage = session.createTextMessage(request);
                requestMessage.setJMSReplyTo(this.replyToDestination);
                // requestMessage.setJMSCorrelationID(String.valueOf(random.nextLong()));

                messageProducer.send(requestMessage);
                String messageSelector = "JMSCorrelationID  LIKE '" + requestMessage.getJMSMessageID() + "'";

                MessageConsumer messageConsumer = session.createConsumer(this.replyToDestination,
                        messageSelector);
                TextMessage replyMessage = (TextMessage) messageConsumer.receive(timeoutInMillis);
                Assert.notNull(replyMessage, "Timeout waiting for jms response");
                logger.debug(
                        "requestReply " + "\r\nrequest : " + requestMessage + "\r\nreply : " + replyMessage);
                String result = replyMessage.getText();
                logger.debug("requestReply('" + request + "'): '" + result + "'");
                return result;
            } finally {
                JmsUtils.closeMessageProducer(messageProducer);
            }
        } finally {
            JmsUtils.closeSession(session);
        }
    } finally {
        JmsUtils.closeConnection(connection);
    }
}

From source file:org.jbpm.bpel.integration.jms.OutstandingRequest.java

public void sendReply(Map parts, QName faultName, Session jmsSession) throws JMSException {
    MessageProducer producer = null;/*from  w  w w  .j a  v  a 2s .co m*/
    try {
        producer = jmsSession.createProducer(replyDestination);
        /*
         * the given parts likely are an instance of PersistentMap which does not serialize nicely;
         * copy the parts to a transient Map implementation
         */
        switch (parts.size()) {
        case 0:
            parts = Collections.EMPTY_MAP;
            break;
        case 1: {
            Map.Entry single = (Entry) parts.entrySet().iterator().next();
            parts = Collections.singletonMap(single.getKey(), single.getValue());
            break;
        }
        default:
            parts = new HashMap(parts);
            break;
        }
        Message responseMsg = jmsSession.createObjectMessage((Serializable) parts);
        responseMsg.setJMSCorrelationID(correlationID);
        // set the fault name, if any
        if (faultName != null) {
            responseMsg.setStringProperty(IntegrationConstants.FAULT_NAME_PROP, faultName.getLocalPart());
        }
        // send the response
        producer.send(responseMsg);
        log.debug("sent response: " + RequestListener.messageToString(responseMsg));
    } finally {
        if (producer != null) {
            try {
                producer.close();
            } catch (JMSException e) {
                log.warn("could not close jms producer", e);
            }
        }
    }
}

From source file:org.jbpm.ejb.impl.CommandListenerBean.java

private void discard(Message message) throws JMSException {
    if (deadLetterQueue == null) {
        // lookup dead letter queue
        try {//from   w  w w  .  j a v  a 2 s .c o m
            Context initial = new InitialContext();
            deadLetterQueue = (Destination) initial.lookup("java:comp/env/jms/DeadLetterQueue");
        } catch (NamingException e) {
            log.debug("failed to retrieve dead letter queue, rejecting message: " + message);
            messageDrivenContext.setRollbackOnly();
            return;
        }
    }
    // send message to dead letter queue
    Session jmsSession = createSession();
    try {
        jmsSession.createProducer(deadLetterQueue).send(message);
    } finally {
        jmsSession.close();
    }
}

From source file:org.mule.transport.jms.Jms11Support.java

public MessageProducer createProducer(Session session, Destination destination, boolean topic)
        throws JMSException {
    return session.createProducer(destination);
}

From source file:com.microsoft.azure.servicebus.samples.jmstopicquickstart.JmsTopicQuickstart.java

public void run(String connectionString) throws Exception {

    // The connection string builder is the only part of the azure-servicebus SDK library 
    // we use in this JMS sample and for the purpose of robustly parsing the Service Bus 
    // connection string. 
    ConnectionStringBuilder csb = new ConnectionStringBuilder(connectionString);

    // set up the JNDI context 
    Hashtable<String, String> hashtable = new Hashtable<>();
    hashtable.put("connectionfactory.SBCF",
            "amqps://" + csb.getEndpoint().getHost() + "?amqp.idleTimeout=120000&amqp.traceFrames=true");
    hashtable.put("topic.TOPIC", "BasicTopic");
    hashtable.put("queue.SUBSCRIPTION1", "BasicTopic/Subscriptions/Subscription1");
    hashtable.put("queue.SUBSCRIPTION2", "BasicTopic/Subscriptions/Subscription2");
    hashtable.put("queue.SUBSCRIPTION3", "BasicTopic/Subscriptions/Subscription3");
    hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
    Context context = new InitialContext(hashtable);

    ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF");

    // Look up the topic
    Destination topic = (Destination) context.lookup("TOPIC");

    // we create a scope here so we can use the same set of local variables cleanly 
    // again to show the receive side seperately with minimal clutter
    {//from w  w  w  .j  a v  a 2  s  .co  m
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        connection.start();
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

        // Create producer
        MessageProducer producer = session.createProducer(topic);

        // Send messaGES
        for (int i = 0; i < totalSend; i++) {
            BytesMessage message = session.createBytesMessage();
            message.writeBytes(String.valueOf(i).getBytes());
            producer.send(message);
            System.out.printf("Sent message %d.\n", i + 1);
        }

        producer.close();
        session.close();
        connection.stop();
        connection.close();
    }

    // Look up the subscription (pretending it's a queue)
    receiveFromSubscription(csb, context, cf, "SUBSCRIPTION1");
    receiveFromSubscription(csb, context, cf, "SUBSCRIPTION2");
    receiveFromSubscription(csb, context, cf, "SUBSCRIPTION3");

    System.out.printf("Received all messages, exiting the sample.\n");
    System.out.printf("Closing queue client.\n");
}

From source file:org.apache.falcon.messaging.MessageProducer.java

/**
 * @param entityInstanceMessage - Accepts a Message to be send to JMS topic, creates a new
 *                  Topic based on topic name if it does not exist or else
 *                  existing topic with the same name is used to send the message.
 * @throws JMSException/*from  ww w . j  a v  a 2  s  . c om*/
 */
protected void sendMessage(EntityInstanceMessage entityInstanceMessage) throws JMSException {

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic entityTopic = session.createTopic(entityInstanceMessage.getTopicName());
    javax.jms.MessageProducer producer = session.createProducer(entityTopic);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    long messageTTL = DEFAULT_TTL;
    try {
        long messageTTLinMins = Long.parseLong(entityInstanceMessage.getBrokerTTL());
        messageTTL = messageTTLinMins * 60 * 1000;
    } catch (NumberFormatException e) {
        LOG.error("Error in parsing broker.ttl, setting TTL to: {} milli-seconds", DEFAULT_TTL);
    }
    producer.setTimeToLive(messageTTL);
    producer.send(new EntityInstanceMessageCreator(entityInstanceMessage).createMessage(session));
}

From source file:com.microsoft.azure.servicebus.samples.jmsqueuequickstart.JmsQueueQuickstart.java

public void run(String connectionString) throws Exception {

    // The connection string builder is the only part of the azure-servicebus SDK library
    // we use in this JMS sample and for the purpose of robustly parsing the Service Bus 
    // connection string. 
    ConnectionStringBuilder csb = new ConnectionStringBuilder(connectionString);

    // set up JNDI context
    Hashtable<String, String> hashtable = new Hashtable<>();
    hashtable.put("connectionfactory.SBCF",
            "amqps://" + csb.getEndpoint().getHost() + "?amqp.idleTimeout=120000&amqp.traceFrames=true");
    hashtable.put("queue.QUEUE", "BasicQueue");
    hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
    Context context = new InitialContext(hashtable);
    ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF");

    // Look up queue
    Destination queue = (Destination) context.lookup("QUEUE");

    // we create a scope here so we can use the same set of local variables cleanly 
    // again to show the receive side separately with minimal clutter
    {/*from w  w  w  .  j  a v  a  2s. co m*/
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

        // Create producer
        MessageProducer producer = session.createProducer(queue);

        // Send messages
        for (int i = 0; i < totalSend; i++) {
            BytesMessage message = session.createBytesMessage();
            message.writeBytes(String.valueOf(i).getBytes());
            producer.send(message);
            System.out.printf("Sent message %d.\n", i + 1);
        }

        producer.close();
        session.close();
        connection.stop();
        connection.close();
    }

    {
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        connection.start();
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        // Create consumer
        MessageConsumer consumer = session.createConsumer(queue);
        // create a listener callback to receive the messages
        consumer.setMessageListener(message -> {
            try {
                // receives message is passed to callback
                System.out.printf("Received message %d with sq#: %s\n", totalReceived.incrementAndGet(), // increments the tracking counter
                        message.getJMSMessageID());
                message.acknowledge();
            } catch (Exception e) {
                logger.error(e);
            }
        });

        // wait on the main thread until all sent messages have been received
        while (totalReceived.get() < totalSend) {
            Thread.sleep(1000);
        }
        consumer.close();
        session.close();
        connection.stop();
        connection.close();
    }

    System.out.printf("Received all messages, exiting the sample.\n");
    System.out.printf("Closing queue client.\n");
}

From source file:org.apache.ivory.messaging.MessageProducer.java

/**
 * /*  w  w  w  .j  a  v a 2s .c  om*/
 * @param arguments
 *            - Accepts a Message to be send to JMS topic, creates a new
 *            Topic based on topic name if it does not exist or else
 *            existing topic with the same name is used to send the message.
 * @throws JMSException
 */
protected void sendMessage(EntityInstanceMessage entityInstanceMessage) throws JMSException {

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic entityTopic = session.createTopic(entityInstanceMessage.getTopicName());
    javax.jms.MessageProducer producer = session.createProducer(entityTopic);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    long messageTTL = DEFAULT_TTL;
    try {
        long messageTTLinMins = Long.parseLong(entityInstanceMessage.getBrokerTTL());
        messageTTL = messageTTLinMins * 60 * 1000;
    } catch (NumberFormatException e) {
        LOG.error("Error in parsing broker.ttl, setting TTL to:" + DEFAULT_TTL + " milli-seconds");
    }
    producer.setTimeToLive(messageTTL);
    producer.send(new EntityInstanceMessageCreator(entityInstanceMessage).createMessage(session));

}

From source file:org.sakaiproject.kernel.messaging.JmsEmailMessageHandler.java

/**
 * {@inheritDoc}//from   w ww. j  av  a 2 s  .  co m
 *
 * @see org.sakaiproject.kernel.api.messaging.MessageHandler#handle(java.lang.String,
 *      java.lang.String, java.lang.String, javax.jcr.Node)
 */
public void handle(String userID, String filePath, String fileName, Node node) {
    try {
        InputStream inputStream = nodeFactory.getInputStream(filePath);
        String content = IOUtils.readFully(inputStream, "UTF-8");
        Connection conn = connFactory.createConnection();
        conn.setClientID("sakai.emailmessagehandler");
        Session clientSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination emailTopic = clientSession.createTopic(emailQueueName);
        MessageProducer client = clientSession.createProducer(emailTopic);
        ObjectMessage mesg = clientSession.createObjectMessage(content);
        mesg.setJMSType(emailJmsType);
        client.send(mesg);
    } catch (JMSException e) {
        log.error(e.getMessage(), e);
    } catch (RepositoryException e) {
        log.error(e.getMessage(), e);
    } catch (JCRNodeFactoryServiceException e) {
        log.error(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
}

From source file:io.fabric8.msg.gateway.TestGateway.java

/**
 * TODO - lets figure out a way of mocking kubernetes, running a ZK ensemble, an Artemis broker and testing it!
 * @throws Exception/*from  w  w w . ja  v  a2s.c  om*/
 */
@Ignore
public void simpleTest() throws Exception {
    int numberOfMessages = 10;
    String destinationName = "jms.queue.test.foo";
    String brokerURL = "tcp://0.0.0.0:61616";
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL);

    Connection consumerConnection = factory.createConnection();
    consumerConnection.start();
    Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination consumerDestination = consumerSession.createQueue(destinationName);
    MessageConsumer messageConsumer = consumerSession.createConsumer(consumerDestination);

    Connection producerConnection = factory.createConnection();
    producerConnection.start();
    Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = producerSession.createQueue(destinationName);
    MessageProducer producer = producerSession.createProducer(destination);

    for (int i = 0; i < numberOfMessages; i++) {
        Message message = producerSession.createTextMessage("test message: " + i);
        producer.send(message);
        //System.err.println("Sent message " + message);

    }

    Message message;

    for (int i = 0; i < numberOfMessages; i++) {
        message = messageConsumer.receive(5000);
        Assert.assertNotNull(message);
        //System.err.println("Got Message " + message);

    }
    messageConsumer.close();

}