Example usage for javax.jms MessageProducer close

List of usage examples for javax.jms MessageProducer close

Introduction

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

Prototype


void close() throws JMSException;

Source Link

Document

Closes the message producer.

Usage

From source file:org.springframework.jms.support.JmsUtils.java

/**
 * Close the given JMS MessageProducer and ignore any thrown exception.
 * This is useful for typical {@code finally} blocks in manual JMS code.
 * @param producer the JMS MessageProducer to close (may be {@code null})
 *//*from  w w w .ja v a2  s .c  o  m*/
public static void closeMessageProducer(@Nullable MessageProducer producer) {
    if (producer != null) {
        try {
            producer.close();
        } catch (JMSException ex) {
            logger.trace("Could not close JMS MessageProducer", ex);
        } catch (Throwable ex) {
            // We don't trust the JMS provider: It might throw RuntimeException or Error.
            logger.trace("Unexpected exception on closing JMS MessageProducer", ex);
        }
    }
}

From source file:org.symplify.runtime.jms.JMSContextImpl.java

public void send(Channel channel, Message message) throws Exception {
    javax.jms.Queue queue = getQueue(channel);

    if (queue != null) {
        //queue.put(message);
        javax.jms.MessageProducer producer = m_session.createProducer(queue);

        javax.jms.Message m = m_session.createObjectMessage(message);

        producer.send(m); //, 0, 0, message.getTimeToLive());

        producer.close();

    } else {//from  w w w.  j  a  v a 2  s  . c  o  m
        throw new Exception("Unable to find queue for channel");
    }
}

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  ava2s.  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.wso2.carbon.integration.test.client.JMSPublisherClient.java

/**
 * This method will publish the data in the test data file to the given topic via ActiveMQ message broker
 *
 * @param topicName             the topic which the messages should be published under
 * @param format                format of the test data file (csv or text)
 * @param testCaseFolderName    Testcase folder name which is in the test artifacts folder
 * @param dataFileName          data file name with the extension to be read
 *
 *//*from   www . jav a2s.c o  m*/
public static void publish(String topicName, String format, String testCaseFolderName, String dataFileName) {

    if (format == null || "map".equals(format)) {
        format = "csv";
    }

    try {
        Properties properties = new Properties();

        String filePath = getTestDataFileLocation(testCaseFolderName, dataFileName);
        properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
        Context context = new InitialContext(properties);
        TopicConnectionFactory connFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
        TopicConnection topicConnection = connFactory.createTopicConnection();
        topicConnection.start();
        Session session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

        Topic topic = session.createTopic(topicName);
        MessageProducer producer = session.createProducer(topic);

        List<String> messagesList = readFile(filePath);
        try {

            if (format.equalsIgnoreCase("csv")) {
                log.info("Sending Map messages on '" + topicName + "' topic");
                publishMapMessages(producer, session, messagesList);

            } else {
                log.info("Sending  " + format + " messages on '" + topicName + "' topic");
                publishTextMessage(producer, session, messagesList);
            }
        } catch (JMSException e) {
            log.error("Can not subscribe." + e.getMessage(), e);
        } finally {
            producer.close();
            session.close();
            topicConnection.stop();
            topicConnection.close();
        }
    } catch (Exception e) {
        log.error("Error when publishing messages" + e.getMessage(), e);
    }

    log.info("All Order Messages sent");
}

From source file:org.wso2.carbon.integration.test.client.JMSPublisherClient.java

/**
 * This method will publish the data in the test data file to the given queue via ActiveMQ message broker
 *
 * @param queueName             the queue which the messages should be published under
 * @param messageFormat         messageFormat of the test data file
 * @param testCaseFolderName    Testcase folder name which is in the test artifacts folder
 * @param dataFileName          data file name with the extension to be read
 *
 *//* ww w .j  a v a2 s.c o m*/
public static void publishToQueue(String queueName, String messageFormat, String testCaseFolderName,
        String dataFileName) throws JMSException, IOException, NamingException {

    //create connection
    Properties properties = new Properties();
    properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
    Context context = new InitialContext(properties);
    QueueConnectionFactory connFactory = (QueueConnectionFactory) context.lookup("ConnectionFactory");
    QueueConnection queueConnection = connFactory.createQueueConnection();
    queueConnection.start();
    Session session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue(queueName);
    MessageProducer producer = session.createProducer(queue);

    //publish data
    String filePath = getTestDataFileLocation(testCaseFolderName, dataFileName);
    List<String> messagesList = readFile(filePath);
    if (messageFormat.equalsIgnoreCase("map")) {
        publishMapMessages(producer, session, messagesList);
    } else {
        publishTextMessage(producer, session, messagesList);
    }

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

From source file:org.wso2.carbon.sample.jmsclient.JMSClient.java

public static void publishMessages(String topicName, String broker) {
    try {//from   w ww.  j a v  a 2  s. c o m

        //            filePath = JMSClientUtil.getEventFilePath(sampleNumber, format, topicName, filePath);

        TopicConnection topicConnection = null;
        Session session = null;

        Properties properties = new Properties();
        if (broker.equalsIgnoreCase("activemq")) {
            properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
            Context context = new InitialContext(properties);
            TopicConnectionFactory connFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
            topicConnection = connFactory.createTopicConnection();
            topicConnection.start();
            session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        } else if (broker.equalsIgnoreCase("mb")) {
            properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties"));
            Context context = new InitialContext(properties);
            TopicConnectionFactory connFactory = (TopicConnectionFactory) context
                    .lookup("qpidConnectionFactory");
            topicConnection = connFactory.createTopicConnection();
            topicConnection.start();
            session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        } else if (broker.equalsIgnoreCase("qpid")) {
            properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties"));
            Context context = new InitialContext(properties);
            TopicConnectionFactory connFactory = (TopicConnectionFactory) context
                    .lookup("qpidConnectionFactory");
            topicConnection = connFactory.createTopicConnection();
            topicConnection.start();
            session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        } else {
            log.info("Please enter a valid JMS message broker. (ex: activemq, mb, qpid");
        }

        if (session != null) {
            Topic topic = session.createTopic(topicName);
            MessageProducer producer = session.createProducer(topic);

            try {

                List<Map<String, Object>> messageList = new ArrayList<Map<String, Object>>();

                Random random = new Random();
                for (int j = 0; j < sessionsPerThread; j++) {
                    for (int i = 0; i < msgsPerSession; i++) {
                        HashMap<String, Object> map = new HashMap<String, Object>();

                        map.put("id", random.nextInt() + "");
                        map.put("value", random.nextInt());
                        map.put("content", "sample content");
                        map.put("client", "jmsQueueClient");
                        // setting the timestamp later
                        messageList.add(map);
                    }

                    publishMapMessage(producer, session, messageList);

                }
            } catch (JMSException e) {
                log.error("Can not subscribe." + e.getMessage(), e);
            } catch (IOException e) {
                log.error("Error when reading the data file." + e.getMessage(), e);
            } finally {
                producer.close();
                session.close();
                topicConnection.stop();
            }
        }
    } catch (Exception e) {
        log.error("Error when publishing message" + e.getMessage(), e);
    }
}

From source file:org.wso2.extension.siddhi.io.jms.source.client.JMSClient.java

public void sendJMSEvents(String filePath, String topicName, String queueName, String format, String broker,
        String providerURL) {//  w  w w  . j  a v a2s  . co  m
    if (format == null || "map".equals(format)) {
        format = "csv";
    }
    if ("".equalsIgnoreCase(broker)) {
        broker = "activemq";
    }
    Session session = null;
    Properties properties = new Properties();
    if (!"activemq".equalsIgnoreCase(broker) && !"mb".equalsIgnoreCase(broker)
            && !"qpid".equalsIgnoreCase(broker)) {
        log.error("Please enter a valid JMS message broker. (ex: activemq, mb, qpid");
        return;
    }
    try {
        if (topicName != null && !"".equalsIgnoreCase(topicName)) {
            TopicConnection topicConnection;
            TopicConnectionFactory connFactory = null;
            if ("activemq".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
                // to provide custom provider urls
                if (providerURL != null) {
                    properties.put(Context.PROVIDER_URL, providerURL);
                }
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
            } else if ("mb".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties"));
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("qpidConnectionFactory");
            } else if ("qpid".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties"));
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("qpidConnectionFactory");
            }
            if (connFactory != null) {
                topicConnection = connFactory.createTopicConnection();
                topicConnection.start();
                session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
                if (session != null) {
                    Topic topic = session.createTopic(topicName);
                    MessageProducer producer = session.createProducer(topic);
                    List<String> messagesList = JMSClientUtil.readFile(filePath);
                    try {
                        if ("csv".equalsIgnoreCase(format)) {
                            log.info("Sending Map messages on '" + topicName + "' topic");
                            JMSClientUtil.publishMapMessage(producer, session, messagesList);

                        } else {
                            log.info("Sending  " + format + " messages on '" + topicName + "' topic");
                            JMSClientUtil.publishTextMessage(producer, session, messagesList);
                        }
                        log.info("All Order Messages sent");
                    } catch (JMSException e) {
                        log.error("Cannot subscribe." + e.getMessage(), e);
                    } catch (IOException e) {
                        log.error("Error when reading the data file." + e.getMessage(), e);
                    } finally {
                        producer.close();
                        session.close();
                        topicConnection.stop();
                    }
                }
            } else {
                log.error("Error when creating connection factory. Please check necessary jar files");
            }
        } else if (queueName != null && !queueName.equalsIgnoreCase("")) {
            QueueConnection queueConnection;
            QueueConnectionFactory connFactory = null;
            if ("activemq".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("ConnectionFactory");
            } else if ("mb".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("qpidConnectionFactory");
            } else if ("qpid".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("qpidConnectionFactory");
            }
            if (connFactory != null) {
                queueConnection = connFactory.createQueueConnection();
                queueConnection.start();
                session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                if (session != null) {
                    Queue queue = session.createQueue(queueName);
                    MessageProducer producer = session.createProducer(queue);
                    List<String> messagesList = JMSClientUtil.readFile(filePath);
                    try {
                        if ("csv".equalsIgnoreCase(format)) {
                            log.info("Sending Map messages on '" + queueName + "' queue");
                            JMSClientUtil.publishMapMessage(producer, session, messagesList);

                        } else {
                            log.info("Sending  " + format + " messages on '" + queueName + "' queue");
                            JMSClientUtil.publishTextMessage(producer, session, messagesList);
                        }
                    } catch (JMSException e) {
                        log.error("Cannot subscribe." + e.getMessage(), e);
                    } catch (IOException e) {
                        log.error("Error when reading the data file." + e.getMessage(), e);
                    } finally {
                        producer.close();
                        session.close();
                        queueConnection.stop();
                    }
                }
            } else {
                log.error("Error when creating connection factory. Please check necessary jar files");
            }
        } else {
            log.error("Enter queue name or topic name to be published!");
        }
    } catch (Exception e) {
        log.error("Error when publishing" + e.getMessage(), e);
    }
}

From source file:org.wso2.extension.siddhi.io.jms.source.client.JMSClient.java

public void sendJMSEvents(List<String> messageList, String topicName, String queueName, String format,
        String broker, String providerURL) {
    if (format == null || "map".equals(format)) {
        format = "csv";
    }/* w  ww .  j a v a2s  . c o m*/
    if ("".equalsIgnoreCase(broker)) {
        broker = "activemq";
    }
    Session session = null;
    Properties properties = new Properties();
    if (!"activemq".equalsIgnoreCase(broker) && !"mb".equalsIgnoreCase(broker)
            && !"qpid".equalsIgnoreCase(broker)) {
        log.error("Please enter a valid JMS message broker. (ex: activemq, mb, qpid");
        return;
    }
    try {
        if (topicName != null && !"".equalsIgnoreCase(topicName)) {
            TopicConnection topicConnection;
            TopicConnectionFactory connFactory = null;
            if ("activemq".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
                // to provide custom provider urls
                if (providerURL != null) {
                    properties.put(Context.PROVIDER_URL, providerURL);
                }
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
            } else if ("mb".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties"));
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("qpidConnectionFactory");
            } else if ("qpid".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties"));
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("qpidConnectionFactory");
            }
            if (connFactory != null) {
                topicConnection = connFactory.createTopicConnection();
                topicConnection.start();
                session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
                if (session != null) {
                    Topic topic = session.createTopic(topicName);
                    MessageProducer producer = session.createProducer(topic);
                    //List<String> messagesList = JMSClientUtil.readFile(filePath);
                    try {
                        if ("csv".equalsIgnoreCase(format)) {
                            log.info("Sending Map messages on '" + topicName + "' topic");
                            JMSClientUtil.publishMapMessage(producer, session, messageList);

                        } else {
                            log.info("Sending  " + format + " messages on '" + topicName + "' topic");
                            JMSClientUtil.publishTextMessage(producer, session, messageList);
                        }
                        log.info("All Order Messages sent");
                    } catch (JMSException e) {
                        log.error("Cannot subscribe." + e.getMessage(), e);
                    } catch (IOException e) {
                        log.error("Error when reading the data file." + e.getMessage(), e);
                    } finally {
                        producer.close();
                        session.close();
                        topicConnection.stop();
                    }
                }
            } else {
                log.error("Error when creating connection factory. Please check necessary jar files");
            }
        } else if (queueName != null && !queueName.equalsIgnoreCase("")) {
            QueueConnection queueConnection;
            QueueConnectionFactory connFactory = null;
            if ("activemq".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
                // to provide custom provider urls
                if (providerURL != null) {
                    properties.put(Context.PROVIDER_URL, providerURL);
                }
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("ConnectionFactory");
            } else if ("mb".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("qpidConnectionFactory");
            } else if ("qpid".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("qpidConnectionFactory");
            }
            if (connFactory != null) {
                queueConnection = connFactory.createQueueConnection();
                queueConnection.start();
                session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                if (session != null) {
                    Queue queue = session.createQueue(queueName);
                    MessageProducer producer = session.createProducer(queue);
                    //List<String> messagesList = JMSClientUtil.readFile(filePath);
                    try {
                        if ("csv".equalsIgnoreCase(format)) {
                            log.info("Sending Map messages on '" + queueName + "' queue");
                            JMSClientUtil.publishMapMessage(producer, session, messageList);

                        } else {
                            log.info("Sending  " + format + " messages on '" + queueName + "' queue");
                            JMSClientUtil.publishTextMessage(producer, session, messageList);
                        }
                    } catch (JMSException e) {
                        log.error("Cannot subscribe." + e.getMessage(), e);
                    } catch (IOException e) {
                        log.error("Error when reading the data file." + e.getMessage(), e);
                    } finally {
                        producer.close();
                        session.close();
                        queueConnection.stop();
                    }
                }
            } else {
                log.error("Error when creating connection factory. Please check necessary jar files");
            }
        } else {
            log.error("Enter queue name or topic name to be published!");
        }
    } catch (Exception e) {
        log.error("Error when publishing" + e.getMessage(), e);
    }
}

From source file:tools.ProducerTool.java

@Override
public void run() {
    Connection connection = null;
    Session session = null;/*from w ww . j  ava2s . c o  m*/
    try {
        connection = connectionFactory.createConnection();
        if (clientId != null) {
            connection.setClientID(clientId);
        }
        session = connection.createSession(transacted, acknowledgeMode);
        Destination destination = null;
        if (jndiLookupDestinations) {
            destination = (Destination) context.lookup(destinationName);
        } else {
            if (useQueueDestinations) {
                if (useTemporaryDestinations) {
                    destination = session.createTemporaryQueue();
                } else {
                    destination = session.createQueue(destinationName);
                }
            } else {
                if (useTemporaryDestinations) {
                    destination = session.createTemporaryTopic();
                } else {
                    destination = session.createTopic(destinationName);
                }
            }
        }

        MessageProducer producer = session.createProducer(destination);
        if (durable) {
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        } else {
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        }

        int numMessagesToSend = useFinalControlMessage ? numMessages - 1 : numMessages;

        for (int i = 0; i < numMessagesToSend; i++) {
            String messageText = "Message " + i + " at " + new Date();
            if (bytesLength > -1) {
                byte[] messageTextBytes = messageText.getBytes(StandardCharsets.UTF_8);
                BytesMessage bytesMessage = session.createBytesMessage();
                bytesMessage.writeBytes(messageTextBytes);
                if (messageTextBytes.length < bytesLength) {
                    byte[] paddingBytes = new byte[bytesLength - messageTextBytes.length];
                    bytesMessage.writeBytes(paddingBytes);
                }
                if (messageGroupId != null) {
                    bytesMessage.setStringProperty("JMSXGroupID", messageGroupId);
                }
                LOGGER.info("Sending bytes message");
                producer.send(bytesMessage);
            } else {
                TextMessage textMessage = session.createTextMessage(messageText);
                if (messageGroupId != null) {
                    textMessage.setStringProperty("JMSXGroupID", messageGroupId);
                }
                LOGGER.info("Sending text message: " + messageText);
                producer.send(textMessage);
            }

            if (perMessageSleepMS > 0) {
                Thread.sleep(perMessageSleepMS);
            }
            if (transacted) {
                if ((i + 1) % batchSize == 0) {
                    session.commit();
                }
            }
        }
        if (useFinalControlMessage) {
            Message message = session.createMessage();
            if (messageGroupId != null) {
                message.setStringProperty("JMSXGroupID", messageGroupId);
            }
            LOGGER.info("Sending message");
            producer.send(message);
            if (transacted) {
                session.commit();
            }
        }
        producer.close();
    } catch (Exception ex) {
        LOGGER.error("ProducerTool hit exception: " + ex.getMessage(), ex);
    } finally {
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                LOGGER.error("JMSException closing session", e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                LOGGER.error("JMSException closing session", e);
            }
        }
    }
}