Example usage for javax.jms MessageProducer send

List of usage examples for javax.jms MessageProducer send

Introduction

In this page you can find the example usage for javax.jms MessageProducer send.

Prototype

void send(Message message, CompletionListener completionListener) throws JMSException;

Source Link

Document

Sends a message using the MessageProducer 's default delivery mode, priority, and time to live, performing part of the work involved in sending the message in a separate thread and notifying the specified CompletionListener when the operation has completed.

Usage

From source file:test.SecureSampleApp.java

private static String sendMessage(final String encryptedMessage) {
    return template.execute(new SessionCallback<String>() {
        @Override/*from  w  w  w .jav a  2 s. co m*/
        public String doInJms(Session session) throws JMSException {
            TextMessage message = session.createTextMessage(encryptedMessage);
            Queue outQueue = session.createQueue("receive");
            Destination inDest = session.createTemporaryQueue();
            String correlationID = UUID.randomUUID().toString();
            message.setJMSReplyTo(inDest);
            message.setJMSCorrelationID(correlationID);
            MessageProducer producer = session.createProducer(outQueue);
            producer.send(outQueue, message);
            return ((TextMessage) session.createConsumer(inDest).receive(10000)).getText();
        }
    }, true);
}

From source file:samples.jms.producercallback.ProducerCallbackExampleTests.java

@Test
public void testProducer() throws Exception {

    jmsTemplate.execute(new ProducerCallback<Object>() {
        public Object doInJms(Session session, MessageProducer producer) throws JMSException {
            for (int i = 1; i <= 10; i++) {
                Message message = session.createTextMessage("Hello #" + i);
                producer.send(destination, message);
            }/*  w  w  w.ja va  2s.  c  om*/
            return null;
        }
    });
}

From source file:org.geoserver.wfs.notification.JMSEventHelper.java

private boolean fireNotification(String byteString, JMSInfo info) {
    Session session = null;//from   ww w  .j a va  2 s .  c  o m
    for (int i = 0; i < 5 && !info.closed; ++i) {
        session = info.getSession();

        if (session == null) {
            continue;
        }

        try {
            MessageProducer producer = session.createProducer(null);
            Message message = session.createTextMessage(byteString);
            for (Destination d : info.destinations) {
                producer.send(d, message);
            }
            return true;
        } catch (Exception e) {
            recordFailure(e);
            info.invalidateSession(session);
            session = null; // Don't try to return the session
            continue;
        } finally {
            try {
                if (session != null) {
                    info.returnSession(session);
                }
            } catch (Exception e) {
                // ignore
            }
        }
    }

    // Ran out of retries

    return false;
}

From source file:org.apache.activemq.bugs.AMQ6133PersistJMSRedeliveryTest.java

private void sendMessages() throws Exception {
    Connection connection = createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination queue = session.createQueue(QUEUE_NAME);
    Destination retainQueue = session.createQueue(QUEUE_NAME + "-retain");
    MessageProducer producer = session.createProducer(null);

    final byte[] payload = new byte[1000];
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    BytesMessage message = session.createBytesMessage();
    message.writeBytes(payload);//from ww w  .j  a  v  a  2  s.c  o m

    // Build up a set of messages that will be redelivered and updated later.
    while (getLogFileCount() < 3) {
        producer.send(queue, message);
    }

    // Now create some space for files that are retained during the test.
    while (getLogFileCount() < 6) {
        producer.send(retainQueue, message);
    }

    connection.close();
}

From source file:fr.xebia.springframework.jms.ManagedCachingConnectionFactoryTest.java

@Test
public void testMessageProducer() throws Exception {
    ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(
            "vm://localhost?broker.persistent=false&broker.useJmx=true");
    ManagedConnectionFactory connectionFactory = new ManagedConnectionFactory(activeMQConnectionFactory);
    Connection connection = null;
    Session session = null;// w w w  . java  2  s.  c  om
    MessageProducer messageProducer = null;
    try {
        connection = connectionFactory.createConnection();
        assertEquals(1, connectionFactory.getActiveConnectionCount());
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        assertEquals(1, connectionFactory.getActiveSessionCount());
        Destination myQueue = session.createQueue("test-queue");
        messageProducer = session.createProducer(myQueue);

        assertEquals(1, connectionFactory.getActiveMessageProducerCount());

        messageProducer.send(myQueue, session.createTextMessage("test"));

        assertEquals(0, connectionFactory.getActiveMessageConsumerCount());
    } finally {
        JmsUtils.closeMessageProducer(messageProducer);
        assertEquals(0, connectionFactory.getActiveMessageProducerCount());
        JmsUtils.closeSession(session);
        assertEquals(0, connectionFactory.getActiveSessionCount());
        JmsUtils.closeConnection(connection);
        assertEquals(0, connectionFactory.getActiveConnectionCount());
    }
}

From source file:biz.fstechnology.micro.common.jms.SyncSessionCallbackImpl.java

/**
 * @see org.springframework.jms.core.SessionCallback#doInJms(javax.jms.Session)
 *//*  www  .ja v  a  2s.  c  o m*/
@Override
public T doInJms(Session session) throws JMSException {
    Topic destTopic = session.createTopic(topicName);
    TemporaryQueue responseQueue = session.createTemporaryQueue();

    // oh my god...
    // why MessageProducer & MessageConsumer not have AutoCloseable!!!
    try (AutoCloseableWrapper<MessageProducer> producerCont = new AutoCloseableWrapper<>(
            () -> createProducer(session, destTopic), JmsUtils::closeMessageProducer);
            AutoCloseableWrapper<MessageConsumer> consumerCont = new AutoCloseableWrapper<>(
                    () -> createConsumer(session, responseQueue), JmsUtils::closeMessageConsumer)) {

        MessageProducer producer = producerCont.unwrap();
        MessageConsumer consumer = consumerCont.unwrap();
        consumer.setMessageListener(this);

        if (getMessageCreator() == null) {
            RequestMessageCreator messageCreator = new RequestMessageCreator();
            messageCreator.setContents(getMessageObj());
            setMessageCreator(messageCreator);
        }
        if (getMessageCreator() instanceof RequestMessageCreator) {
            ((RequestMessageCreator) getMessageCreator()).setReplyTo(responseQueue);
        }
        Message requestMessage = getMessageCreator().createMessage(session);
        producer.send(destTopic, requestMessage);

        if (getMessageCreator() instanceof RequestMessageCreator) {
            return waitResponse(consumer, requestMessage);
        } else {
            return null;
        }
    }
}

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  v  a2s  . co m*/
@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.cws.esolutions.agent.mq.MQMessageHandler.java

public void onMessage(final Message message) {
    final String methodName = MQMessageHandler.CNAME + "#onMessage(final Message message)";

    if (DEBUG) {/*from   w ww.ja  va 2s .co  m*/
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Message: {}", message);
    }

    final Session session = agentBean.getSession();
    final MessageProducer producer = agentBean.getProducer();
    final Destination destination = MQMessageHandler.agentBean.getResponseQueue();

    if (DEBUG) {
        DEBUGGER.debug("Session: {}", session);
        DEBUGGER.debug("MessageProducer: {}", producer);
        DEBUGGER.debug("Destination: {}", destination);
    }

    try {
        ObjectMessage mqMessage = (ObjectMessage) message;

        if (DEBUG) {
            DEBUGGER.debug("mqMessage: {}", mqMessage);
        }

        if ((StringUtils.equals(MQMessageHandler.serverConfig.getRequestQueue(),
                MQMessageHandler.serverConfig.getResponseQueue()))
                && (mqMessage.getObject() instanceof AgentResponse)) {
            return;
        }

        AgentRequest agentRequest = (AgentRequest) mqMessage.getObject();

        if (DEBUG) {
            DEBUGGER.debug("agentRequest: {}", agentRequest);
        }

        mqMessage.acknowledge();

        AgentResponse agentResponse = MQMessageHandler.processor.processRequest(agentRequest);

        if (DEBUG) {
            DEBUGGER.debug("AgentResponse: {}", agentResponse);
        }

        ObjectMessage oMessage = session.createObjectMessage(true);
        oMessage.setObject(agentResponse);
        oMessage.setJMSCorrelationID(message.getJMSCorrelationID());

        if (DEBUG) {
            DEBUGGER.debug("ObjectMessage: {}", oMessage);
        }

        producer.send(destination, oMessage);
    } catch (JMSException jx) {
        ERROR_RECORDER.error(jx.getMessage(), jx);
    } catch (AgentException ax) {
        ERROR_RECORDER.error(ax.getMessage(), ax);
    }
}