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) throws JMSException;

Source Link

Document

Sends a message using the MessageProducer 's default delivery mode, priority, and time to live.

Usage

From source file:org.artificer.events.jms.JMSEventProducer.java

private void publishEvent(Object payload, String type) {
    for (Destination destination : destinations) {
        MessageProducer producer = null;
        try {//  www . j av a2 s. c  om
            producer = session.createProducer(destination);
            TextMessage textMessage = session.createTextMessage();
            textMessage.setJMSType(type);

            ObjectMapper mapper = new ObjectMapper();
            String text = mapper.writeValueAsString(payload);
            textMessage.setText(text);

            producer.send(textMessage);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        } finally {
            if (producer != null) {
                try {
                    producer.close();
                } catch (Exception e) {
                }
            }
        }
    }
}

From source file:org.apache.activemq.store.kahadb.SubscriptionRecoveryTest.java

private void sendMessages(Destination destination, int count) throws Exception {
    Connection connection = cf.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    for (int i = 0; i < count; ++i) {
        TextMessage message = session.createTextMessage("Message #" + i + " for destination: " + destination);
        producer.send(message);
    }// ww w .  ja va2 s  .com
    connection.close();
}

From source file:org.dawnsci.commandserver.core.producer.ProcessConsumer.java

/**
 * Parse the queue for stale jobs and things that should be rerun.
 * @param bean/*from  w w  w  .  j  av  a2  s  .c om*/
 * @throws Exception 
 */
private void processStatusQueue(URI uri, String statusQName) throws Exception {

    QueueConnection qCon = null;

    try {
        QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
        qCon = connectionFactory.createQueueConnection();
        QueueSession qSes = qCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = qSes.createQueue(statusQName);
        qCon.start();

        QueueBrowser qb = qSes.createBrowser(queue);

        @SuppressWarnings("rawtypes")
        Enumeration e = qb.getEnumeration();

        ObjectMapper mapper = new ObjectMapper();

        Map<String, StatusBean> failIds = new LinkedHashMap<String, StatusBean>(7);
        List<String> removeIds = new ArrayList<String>(7);
        while (e.hasMoreElements()) {
            Message m = (Message) e.nextElement();
            if (m == null)
                continue;
            if (m instanceof TextMessage) {
                TextMessage t = (TextMessage) m;

                try {
                    @SuppressWarnings("unchecked")
                    final StatusBean qbean = mapper.readValue(t.getText(), getBeanClass());
                    if (qbean == null)
                        continue;
                    if (qbean.getStatus() == null)
                        continue;
                    if (!qbean.getStatus().isStarted()) {
                        failIds.put(t.getJMSMessageID(), qbean);
                        continue;
                    }

                    // If it has failed, we clear it up
                    if (qbean.getStatus() == Status.FAILED) {
                        removeIds.add(t.getJMSMessageID());
                        continue;
                    }
                    if (qbean.getStatus() == Status.NONE) {
                        removeIds.add(t.getJMSMessageID());
                        continue;
                    }

                    // If it is running and older than a certain time, we clear it up
                    if (qbean.getStatus() == Status.RUNNING) {
                        final long submitted = qbean.getSubmissionTime();
                        final long current = System.currentTimeMillis();
                        if (current - submitted > getMaximumRunningAge()) {
                            removeIds.add(t.getJMSMessageID());
                            continue;
                        }
                    }

                    if (qbean.getStatus().isFinal()) {
                        final long submitted = qbean.getSubmissionTime();
                        final long current = System.currentTimeMillis();
                        if (current - submitted > getMaximumCompleteAge()) {
                            removeIds.add(t.getJMSMessageID());
                        }
                    }

                } catch (Exception ne) {
                    System.out.println("Message " + t.getText() + " is not legal and will be removed.");
                    removeIds.add(t.getJMSMessageID());
                }
            }
        }

        // We fail the non-started jobs now - otherwise we could
        // actually start them late. TODO check this
        final List<String> ids = new ArrayList<String>();
        ids.addAll(failIds.keySet());
        ids.addAll(removeIds);

        if (ids.size() > 0) {

            for (String jMSMessageID : ids) {
                MessageConsumer consumer = qSes.createConsumer(queue, "JMSMessageID = '" + jMSMessageID + "'");
                Message m = consumer.receive(1000);
                if (removeIds.contains(jMSMessageID))
                    continue; // We are done

                if (m != null && m instanceof TextMessage) {
                    MessageProducer producer = qSes.createProducer(queue);
                    final StatusBean bean = failIds.get(jMSMessageID);
                    bean.setStatus(Status.FAILED);
                    producer.send(qSes.createTextMessage(mapper.writeValueAsString(bean)));

                    System.out.println("Failed job " + bean.getName() + " messageid(" + jMSMessageID + ")");

                }
            }
        }
    } finally {
        if (qCon != null)
            qCon.close();
    }

}

From source file:org.apache.activemq.usecases.DurableSubscriberWithNetworkRestartTest.java

public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception {
    bridge(SPOKE, HUB);/*from   w w  w.  j a v a 2 s.  co  m*/
    startAllBrokers();

    verifyDuplexBridgeMbean();

    // Setup connection
    URI hubURI = brokers.get(HUB).broker.getTransportConnectors().get(0).getPublishableConnectURI();
    URI spokeURI = brokers.get(SPOKE).broker.getTransportConnectors().get(0).getPublishableConnectURI();
    ActiveMQConnectionFactory facHub = new ActiveMQConnectionFactory(hubURI);
    ActiveMQConnectionFactory facSpoke = new ActiveMQConnectionFactory(spokeURI);
    Connection conHub = facHub.createConnection();
    Connection conSpoke = facSpoke.createConnection();
    conHub.setClientID("clientHUB");
    conSpoke.setClientID("clientSPOKE");
    conHub.start();
    conSpoke.start();
    Session sesHub = conHub.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Session sesSpoke = conSpoke.createSession(false, Session.AUTO_ACKNOWLEDGE);

    ActiveMQTopic topic = new ActiveMQTopic("TEST.FOO");
    String consumerName = "consumerName";

    // Setup consumers
    MessageConsumer remoteConsumer = sesHub.createDurableSubscriber(topic, consumerName);
    sleep(1000);
    remoteConsumer.close();

    // Setup producer
    MessageProducer localProducer = sesSpoke.createProducer(topic);
    localProducer.setDeliveryMode(DeliveryMode.PERSISTENT);

    final String payloadString = new String(new byte[10 * 1024]);
    // Send messages
    for (int i = 0; i < MESSAGE_COUNT; i++) {
        Message test = sesSpoke.createTextMessage("test-" + i);
        test.setStringProperty("payload", payloadString);
        localProducer.send(test);
    }
    localProducer.close();

    final String options = "?persistent=true&useJmx=true&deleteAllMessagesOnStartup=false";
    for (int i = 0; i < 2; i++) {
        brokers.get(SPOKE).broker.stop();
        sleep(1000);
        createBroker(new URI("broker:(tcp://localhost:61616)/" + SPOKE + options));
        bridge(SPOKE, HUB);
        brokers.get(SPOKE).broker.start();
        LOG.info("restarted spoke..:" + i);

        assertTrue("got mbeans on restart", Wait.waitFor(new Wait.Condition() {
            @Override
            public boolean isSatisified() throws Exception {
                return countMbeans(brokers.get(HUB).broker, "networkBridge", 20000) == (dynamicOnly ? 1 : 2);
            }
        }));
    }
}

From source file:org.sofun.core.messaging.SofunMessagingServiceImpl.java

@Override
public void sendMessage(Serializable message, String destination) {

    Connection connection = null;
    Session session = null;/*from   ww  w . j a  va  2s .c  om*/
    MessageProducer sender = null;
    Queue q = getQueueFor(destination);
    if (q == null) {
        log.error("Cannot find associated queue for destination=" + destination);
    }
    try {
        connection = connFactory.createConnection(SofunMessagingCredentials.USERNAME,
                SofunMessagingCredentials.PASSWORD);
        session = connection.createSession(true, 0);
        sender = session.createProducer(q);
        ObjectMessage msg = session.createObjectMessage(message);
        sender.send(msg);
    } catch (Exception e) {
        log.error(e.getMessage());
    } finally {
        try {
            if (sender != null) {
                sender.close();
            }
            if (session != null) {
                session.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (JMSException e) {
            log.error(e.getMessage());
        }

    }

}

From source file:eu.domibus.submission.jms.BackendJMSImpl.java

private Boolean submitToBackend(final String messageId) {
    Connection connection;//from  w ww  .j  a va  2s .c o m
    MessageProducer producer;

    try {
        connection = this.cf.createConnection();
        final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producer = session.createProducer(this.receivingQueue);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        final MapMessage resMessage = session.createMapMessage();
        this.downloadMessage(messageId, resMessage);
        producer.send(resMessage);
        producer.close();
        session.close();

        connection.close();
    } catch (JMSException | ValidationException e) {
        BackendJMSImpl.LOG.error("", e);
        return false;
    }
    return true;
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.jms.JMSReplySender.java

/**
 * Send the reply back to the response queue/topic
 * *///from   ww  w  .j a  v a  2s  .co  m
public void sendBack(MessageContext synCtx) {
    log.debug("Begin sending reply to the destination queue.");
    MessageProducer producer = null;
    Session session = null;
    try {
        Connection connection = cachedJMSConnectionFactory.getConnection(strUserName, strPassword);
        session = cachedJMSConnectionFactory.getSession(connection);
        producer = cachedJMSConnectionFactory.createProducer(session, replyTo, true);
        Message message = createJMSMessage(synCtx, session, null);
        producer.send(message);
    } catch (JMSException e) {
        log.error("Error sending JMS response", e);
    } catch (Exception e) {
        log.error("Error sending JMS response", e);
    } finally {
        try {
            producer.close();
        } catch (Exception e) {
            log.debug("ERROR: Unable to close the producer");
        }
        try {
            session.close();
        } catch (Exception e) {
            log.debug("ERROR: Unable to close the session");
        }
    }
}

From source file:org.apache.activemq.apollo.JmsQueueBrowserTest.java

/**
 * Tests the queue browser. Browses the messages then the consumer tries to receive them. The messages should still
 * be in the queue even when it was browsed.
 *
 * Re-enable once https://issues.apache.org/jira/browse/APLO-226 is fixed.
 *
 * @throws Exception//from  ww w.  ja  v  a  2s .  c  o  m
 */
public void testReceiveBrowseReceive() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    connection.start();

    Message[] outbound = new Message[] { session.createTextMessage("First Message"),
            session.createTextMessage("Second Message"), session.createTextMessage("Third Message") };

    // lets consume any outstanding messages from previous test runs
    while (consumer.receive(1000) != null) {
    }

    producer.send(outbound[0]);
    producer.send(outbound[1]);
    producer.send(outbound[2]);

    // Get the first.
    assertEquals(outbound[0], consumer.receive(1000));
    consumer.close();
    //Thread.sleep(200);

    QueueBrowser browser = session.createBrowser((Queue) destination);
    Enumeration enumeration = browser.getEnumeration();

    // browse the second
    assertTrue("should have received the second message", enumeration.hasMoreElements());
    assertEquals(outbound[1], (Message) enumeration.nextElement());

    // browse the third.
    assertTrue("Should have received the third message", enumeration.hasMoreElements());
    assertEquals(outbound[2], (Message) enumeration.nextElement());

    // There should be no more.
    boolean tooMany = false;
    while (enumeration.hasMoreElements()) {
        LOG.info("Got extra message: " + ((TextMessage) enumeration.nextElement()).getText());
        tooMany = true;
    }
    assertFalse(tooMany);
    browser.close();

    // Re-open the consumer.
    consumer = session.createConsumer(destination);
    // Receive the second.
    assertEquals(outbound[1], consumer.receive(1000));
    // Receive the third.
    assertEquals(outbound[2], consumer.receive(1000));
    consumer.close();

}

From source file:org.apache.activemq.web.AjaxTest.java

@Test(timeout = 15 * 1000)
public void testMultipleAjaxClientsMayExistInTheSameSession() throws Exception {
    LOG.debug("*** testMultipleAjaxClientsMayExistInTheSameSession ***");
    int port = getPort();

    // send messages to queues testA and testB.
    MessageProducer producerA = session.createProducer(session.createQueue("testA"));
    MessageProducer producerB = session.createProducer(session.createQueue("testB"));
    producerA.send(session.createTextMessage("A1"));
    producerA.send(session.createTextMessage("A2"));
    producerB.send(session.createTextMessage("B1"));
    producerB.send(session.createTextMessage("B2"));

    HttpClient httpClient = new HttpClient();
    httpClient.start();//from   w  ww .  j av a  2s. c om

    // clientA subscribes to /queue/testA
    LOG.debug("SENDING LISTEN");
    String sessionId = subscribe(httpClient, port,
            "destination=queue://testA&type=listen&message=handlerA&clientId=clientA");

    // clientB subscribes to /queue/testB using the same JSESSIONID.
    subscribe(httpClient, port, "destination=queue://testB&type=listen&message=handlerB&clientId=clientB", null,
            sessionId);

    // clientA polls for messages
    final StringBuffer buf = new StringBuffer();
    final CountDownLatch latch = asyncRequest(httpClient,
            "http://localhost:" + port + "/amq?timeout=5000&clientId=clientA", buf, sessionId);
    latch.await();

    LOG.debug("clientA response : " + buf.toString());
    String expected1 = "<response id='handlerA' destination='queue://testA' >A1</response>";
    String expected2 = "<response id='handlerA' destination='queue://testA' >A2</response>";

    assertContains(expected1, buf.toString());
    assertContains(expected2, buf.toString());

    // clientB polls for messages
    final StringBuffer buf2 = new StringBuffer();
    final CountDownLatch latch2 = asyncRequest(httpClient,
            "http://localhost:" + port + "/amq?timeout=5000&clientId=clientB", buf2, sessionId);
    latch2.await();

    LOG.debug("clientB response : " + buf2.toString());
    expected1 = "<response id='handlerB' destination='queue://testB' >B1</response>";
    expected2 = "<response id='handlerB' destination='queue://testB' >B2</response>";
    assertContains(expected1, buf2.toString());
    assertContains(expected2, buf2.toString());

    httpClient.stop();
}

From source file:org.aludratest.service.jms.impl.JmsActionImpl.java

@Override
public void sendMessage(Message message, String destinationName) {
    MessageProducer producer = null;
    try {//from  w w  w  . j  ava2s  .co  m
        LOGGER.debug("Sending message to destination " + destinationName);
        Destination dest = (Destination) context.lookup(destinationName);
        producer = getSession().createProducer(dest);
        this.startConnection();
        producer.send(message);
        this.stopConnection();
    } catch (NamingException e) {
        throw new AutomationException("Could not lookup destination " + destinationName, e);
    } catch (ClassCastException e) {
        throw new AutomationException("JNDI object with name " + destinationName + " is no destination", e);
    } catch (JMSException e) {
        throw new AccessFailure("Could not send JMS message", e);
    } finally {
        if (producer != null) {
            try {
                producer.close();
            } catch (JMSException e) {
            }
        }
    }
}