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:pl.psnc.synat.wrdz.zu.certificate.CertificateChecker.java

/**
 * Notifies the system monitor that the given user has a certificate that's beyond the expiration threshold.
 * //from www .  j  a  v  a2s  .  c o m
 * @param username
 *            name of the user with the (nearly) expired certificate
 */
private void notifyExpirationCheckFail(String username) {
    QueueConnection connection = null;
    try {
        connection = queueConnectionFactory.createQueueConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        TextMessage message = session.createTextMessage();
        message.setText(username);
        session.createProducer(certificateQueue).send(message);
    } catch (JMSException e) {
        logger.error("Sending message to the JMS queue failed", e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                logger.error("Error while closing a connection.", e);
            }
        }
    }
}

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

/**
 * This method checks for pending messages received by another gateway and processes them to a JMS destination
 *
 * @param ctx//  w  w  w  .  ja  v  a 2  s  . c o  m
 */
public void executeInternal(final JobExecutionContext ctx) {
    try {

        final Collection<String> ids = this.messageRetriever.listPendingMessages();

        if (!ids.isEmpty() || ids.size() > 0) {
            final String[] messageIds = ids.toArray(new String[ids.size()]);

            Connection connection;
            MessageProducer producer;

            connection = this.cf.createConnection();
            for (final String messageId : messageIds) {
                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();
        } else {
            BackendJMSImpl.LOG.debug("No pending messages to send");
        }

    } catch (final JMSException | ValidationException ex) {
        BackendJMSImpl.LOG.error(ex);
    }
}

From source file:Retailer.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    try {/*w  w w .  j a  v a  2s .c o m*/
        Connection connection = connectionFactory.createConnection();

        // The Retailer's session is non-trasacted.
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination vendorOrderQueue = session.createQueue("VendorOrderQueue");
        TemporaryQueue retailerConfirmQueue = session.createTemporaryQueue();

        MessageProducer producer = session.createProducer(vendorOrderQueue);
        MessageConsumer replyConsumer = session.createConsumer(retailerConfirmQueue);

        connection.start();

        for (int i = 0; i < 5; i++) {
            MapMessage message = session.createMapMessage();
            message.setString("Item", "Computer(s)");
            int quantity = (int) (Math.random() * 4) + 1;
            message.setInt("Quantity", quantity);
            message.setJMSReplyTo(retailerConfirmQueue);
            producer.send(message);
            System.out.println("Retailer: Ordered " + quantity + " computers.");

            MapMessage reply = (MapMessage) replyConsumer.receive();
            if (reply.getBoolean("OrderAccepted")) {
                System.out.println("Retailer: Order Filled");
            } else {
                System.out.println("Retailer: Order Not Filled");
            }
        }

        // Send a non-MapMessage to signal the end
        producer.send(session.createMessage());

        replyConsumer.close();
        connection.close();

    } catch (JMSException e) {
        e.printStackTrace();
    }
}

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  w ww  . j a v  a 2 s . c om
 */
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.ct.amq.jdbc.security.JdbcAuthenticationPluginTest.java

public void testSecurityContextClearedOnPurge() throws Exception {

    connection.close();/* w w  w .j  a v a 2s.co  m*/
    ActiveMQConnectionFactory tcpFactory = new ActiveMQConnectionFactory(
            broker.getTransportConnectors().get(0).getPublishableConnectString());
    ActiveMQConnection conn = (ActiveMQConnection) tcpFactory.createConnection("user", "password");
    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    conn.start();

    final int numDests = broker.getRegionBroker().getDestinations().length;
    for (int i = 0; i < 10; i++) {
        MessageProducer p = sess.createProducer(new ActiveMQQueue("USERS.PURGE." + i));
        p.close();
    }

    assertTrue("dests are purged", Wait.waitFor(new Wait.Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            LOG.info(
                    "dests, orig: " + numDests + ", now: " + broker.getRegionBroker().getDestinations().length);
            return (numDests + 1) == broker.getRegionBroker().getDestinations().length;
        }
    }));

    // verify removed from connection security context
    TransportConnection brokerConnection = broker.getTransportConnectors().get(0).getConnections().get(0);
    TransportConnectionState transportConnectionState = brokerConnection
            .lookupConnectionState(conn.getConnectionInfo().getConnectionId());
    assertEquals("no destinations", 0,
            transportConnectionState.getContext().getSecurityContext().getAuthorizedWriteDests().size());
}

From source file:org.sakaiproject.kernel.messaging.email.EmailMessagingService.java

public String send(Email email) throws MessagingException, JMSException {
    try {/*from  w  w  w  .j av  a2s  . co m*/
        email.buildMimeMessage();
    } catch (Exception e) {
        // this is a lossy cast. This would be a commons EmailException
        // this up cast is to keep commons-email out of our direct bindings
        throw new MessagingException(e);
    }

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        email.getMimeMessage().writeTo(os);
    } catch (javax.mail.MessagingException e) {
        throw new MessagingException(e);

    } catch (IOException e) {
        throw new MessagingException(e);
    }

    String content = os.toString();
    Connection conn = connectionFactory.createTopicConnection();
    conn.setClientID(getNextId());
    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);
    // TODO finish this
    return null;

}

From source file:org.apache.flume.source.jms.TestIntegrationActiveMQ.java

private void putQueue(List<String> events) throws Exception {
    ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER_BIND_URL);
    Connection connection = factory.createConnection();
    connection.start();/* ww  w .j a  va2  s. c  o  m*/

    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createQueue(DESTINATION_NAME);
    MessageProducer producer = session.createProducer(destination);

    for (String event : events) {
        TextMessage message = session.createTextMessage();
        message.setText(event);
        producer.send(message);
    }
    session.commit();
    session.close();
    connection.close();
}

From source file:org.apache.flume.source.jms.TestIntegrationActiveMQ.java

private void putTopic(List<String> events) throws Exception {
    ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER_BIND_URL);
    Connection connection = factory.createConnection();
    connection.start();/*from w w w . j  a v  a2 s  .c o  m*/

    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createTopic(DESTINATION_NAME);
    MessageProducer producer = session.createProducer(destination);

    for (String event : events) {
        TextMessage message = session.createTextMessage();
        message.setText(event);
        producer.send(message);
    }
    session.commit();
    session.close();
    connection.close();
}

From source file:org.wso2.carbon.registry.caching.invalidator.connection.JMSNotification.java

@Override
public void publish(Object message) {
    Session pubSession = null;
    try {/*from   w  ww.j  a va2s . c  o  m*/
        if (connection != null) {
            pubSession = connection.createSession(false, TopicSession.AUTO_ACKNOWLEDGE);
            MessageProducer publisher = pubSession.createProducer(destination);
            BytesMessage bytesMessage = pubSession.createBytesMessage();
            bytesMessage.writeBytes((byte[]) message);
            publisher.send(bytesMessage);
        }
    } catch (JMSException e) {
        log.error("Global cache invalidation: Error in publishing the message", e);
    } finally {
        if (pubSession != null) {
            try {
                pubSession.close();
            } catch (JMSException e) {
                log.error("Global cache invalidation: Error in publishing the message", e);
            }
        }
    }
}

From source file:org.apache.servicemix.wsn.jms.JmsPublisher.java

@Override
public void notify(NotificationMessageHolderType messageHolder, String mes) {
    Session session = null;
    try {//from  w  ww .  ja v  a 2s. co m
        Topic topic = topicConverter.toActiveMQTopic(messageHolder.getTopic());
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(topic);
        Message message = session.createTextMessage(mes);
        producer.send(message);
    } catch (JMSException e) {
        log.warn("Error dispatching message", e);
    } catch (InvalidTopicException e) {
        log.warn("Error dispatching message", e);
    } finally {
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                log.debug("Error closing session", e);
            }
        }
    }
}