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:com.mothsoft.alexis.engine.retrieval.DocumentRetrievalTaskImpl.java

private String requestParse(final Long documentId, final String content) {
    Connection connection = null;
    Session session = null;/*from   w  w w.ja  v a 2  s. com*/
    MessageProducer producer = null;

    // set up JMS connection, session, consumer, producer
    try {
        connection = this.connectionFactory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producer = session.createProducer(this.requestQueue);

        logger.info("Sending parse request, document ID: " + documentId);
        final TextMessage textMessage = session.createTextMessage(content);
        textMessage.setJMSReplyTo(this.responseQueue);
        textMessage.setLongProperty(DOCUMENT_ID, documentId);

        producer.send(textMessage);
    } catch (JMSException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (producer != null) {
                producer.close();
            }
            if (session != null) {
                session.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }

    return content;
}

From source file:com.fusesource.forge.jmstest.tests.AsyncConsumer.java

public void onMessage(Message msg) {
    if (receiveCount != null) {
        receiveCount.incrementAndGet();/* ww w .j  a  va2 s  .  co  m*/
    }
    MessageProducer producer = null;
    try {
        Destination replyDest = msg.getJMSReplyTo();
        if (replyDest != null) {
            Message response = getSession().createTextMessage("Response");
            response.setStringProperty("ServedBy", getName());
            response.setJMSCorrelationID(msg.getJMSCorrelationID());
            for (Enumeration<?> en = msg.getPropertyNames(); en.hasMoreElements();) {
                String key = (String) en.nextElement();
                Object value = msg.getObjectProperty(key);
                if (key.equals("BrokerStamp")) {
                    value = value.toString() + " --";
                }
                response.setObjectProperty(key, value);
            }
            producer = getSession().createProducer(replyDest);
            producer.send(response);
        }
    } catch (Exception e) {
        LOG.error(e);
    } finally {
        if (producer != null) {
            try {
                producer.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:eu.eubrazilcc.lvl.storage.activemq.ActiveMQConnector.java

public void sendMessage(final String topicName, final String message) {
    checkArgument(isNotBlank(topicName), "Uninitialized or invalid topic");
    checkArgument(isNotBlank(message), "Uninitialized or invalid message");
    TopicConnection conn = null;//from w ww  .  j  a  va  2s  .  c  o  m
    TopicSession session = null;
    MessageProducer producer = null;
    try {
        conn = (TopicConnection) broker().getProducersConnFactory().createConnection();
        /* conn = broker().getConnFactory().createTopicConnection();
        conn.start(); */
        session = conn.createTopicSession(false, AUTO_ACKNOWLEDGE);
        final Topic topic = session.createTopic(topicName);
        producer = session.createProducer(topic);
        producer.setDeliveryMode(NON_PERSISTENT);
        final TextMessage textMessage = session.createTextMessage(message);
        producer.send(textMessage);
    } catch (JMSException e) {
        LOGGER.error("Failed to send message to topic: " + topicName, e);
    } finally {
        if (producer != null) {
            try {
                producer.close();
            } catch (JMSException ignore) {
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch (JMSException ignore) {
            }
        }
        /* if (conn != null) {
           try {
              conn.close();
           } catch (JMSException ignore) { }
        } */
    }
}

From source file:com.legstar.mq.client.AbstractCicsMQ.java

/**
 * Creates and send a JMS message to the mainframe.
 * <p/>/*  ww  w. ja  v a  2 s. c  om*/
 * Reply to queue name is where we expect the reply. We expect it to be
 * managed by the same mq manager as the request queue.
 * <p/>
 * Save the unique message ID that was generated by JMS. It will be needed
 * to retrieve the correlated reply.
 * 
 * @param request the request to be sent
 * @throws RequestException if send fails
 */
public void sendRequest(final LegStarRequest request) throws RequestException {

    MessageProducer producer = null;
    try {
        if (_log.isDebugEnabled()) {
            _log.debug("Sending Request:" + request.getID() + " on Connection:" + _connectionID + " "
                    + request.getRequestMessage().getHeaderPart().getJsonString() + '.');
        }

        Message jmsMessage = createRequestMessage(request);
        jmsMessage.setJMSReplyTo(getJmsReplyQueue());
        producer = getJmsQueueSession().createProducer(getJmsRequestQueue());
        producer.send(jmsMessage);

        request.setAttachment(jmsMessage.getJMSMessageID().getBytes());

        _lastUsedTime = System.currentTimeMillis();
        if (_log.isDebugEnabled()) {
            _log.debug("Sent Request:" + request.getID() + " on Connection:" + _connectionID + ". Message ID:"
                    + jmsMessage.getJMSMessageID());
        }
    } catch (HeaderPartException e) {
        throw new RequestException(e);
    } catch (JMSException e) {
        throw new RequestException(e);
    } finally {
        if (producer != null) {
            try {
                producer.close();
            } catch (JMSException e) {
                _log.error(e);
            }
        }
    }
}

From source file:org.dawnsci.commandserver.core.consumer.RemoteSubmission.java

/**
 * Submits the bean onto the server. From there events about this
 * bean are tacked by monitoring the status queue.
 * // w  w w.  j  av a 2  s  .c  om
 * @param uri
 * @param bean
 */
public synchronized TextMessage submit(StatusBean bean, boolean prepareBean) throws Exception {

    if (getQueueName() == null || "".equals(getQueueName()))
        throw new Exception("Please specify a queue name!");

    Connection send = null;
    Session session = null;
    MessageProducer producer = null;

    try {
        QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
        send = connectionFactory.createConnection();

        session = send.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(queueName);

        producer = session.createProducer(queue);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);

        ObjectMapper mapper = new ObjectMapper();

        if (getTimestamp() < 1)
            setTimestamp(System.currentTimeMillis());
        if (getPriority() < 1)
            setPriority(1);
        if (getLifeTime() < 1)
            setLifeTime(7 * 24 * 60 * 60 * 1000); // 7 days in ms

        if (prepareBean) {
            if (bean.getUserName() == null)
                bean.setUserName(System.getProperty("user.name"));
            bean.setUniqueId(uniqueId);
            bean.setSubmissionTime(getTimestamp());
        }
        String jsonString = mapper.writeValueAsString(bean);

        TextMessage message = session.createTextMessage(jsonString);

        message.setJMSMessageID(uniqueId);
        message.setJMSExpiration(getLifeTime());
        message.setJMSTimestamp(getTimestamp());
        message.setJMSPriority(getPriority());

        producer.send(message);

        return message;

    } finally {
        if (send != null)
            send.close();
        if (session != null)
            session.close();
        if (producer != null)
            producer.close();
    }

}

From source file:com.bitsofproof.supernode.core.ImplementBCSAPI.java

private void addBloomScanListener() throws JMSException {
    addMessageListener("scanRequest", new MessageListener() {
        @Override// w w w.ja v  a 2  s . c o  m
        public void onMessage(Message msg) {
            BytesMessage o = (BytesMessage) msg;
            byte[] body;
            try {
                body = new byte[(int) o.getBodyLength()];
                o.readBytes(body);
                BCSAPIMessage.FilterRequest request = BCSAPIMessage.FilterRequest.parseFrom(body);
                byte[] data = request.getFilter().toByteArray();
                long hashFunctions = request.getHashFunctions();
                long tweak = request.getTweak();
                UpdateMode updateMode = UpdateMode.values()[request.getMode()];
                final BloomFilter filter = new BloomFilter(data, hashFunctions, tweak, updateMode);
                final MessageProducer producer = session.createProducer(msg.getJMSReplyTo());
                requestProcessor.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            store.scan(filter, new TransactionProcessor() {
                                @Override
                                public void process(Tx tx) {
                                    if (tx != null) {
                                        Transaction transaction = toBCSAPITransaction(tx);
                                        BytesMessage m;
                                        try {
                                            m = session.createBytesMessage();
                                            m.writeBytes(transaction.toProtobuf().toByteArray());
                                            producer.send(m);
                                        } catch (JMSException e) {
                                        }
                                    } else {
                                        try {
                                            BytesMessage m = session.createBytesMessage();
                                            producer.send(m); // indicate EOF
                                            producer.close();
                                        } catch (JMSException e) {
                                        }
                                    }
                                }
                            });
                        } catch (ValidationException e) {
                            log.error("Error while scanning", e);
                        }
                    }
                });
            } catch (JMSException e) {
                log.error("invalid filter request", e);
            } catch (InvalidProtocolBufferException e) {
                log.error("invalid filter request", e);
            }
        }
    });
}

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()}
 *//*from   www  .j  a  v  a  2  s . com*/
@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.bitsofproof.supernode.core.ImplementBCSAPI.java

private void addMatchScanListener() throws JMSException {
    addMessageListener("matchRequest", new MessageListener() {
        @Override/* w  ww  . j  a v  a  2 s. c o  m*/
        public void onMessage(Message msg) {
            BytesMessage o = (BytesMessage) msg;
            byte[] body;
            try {
                body = new byte[(int) o.getBodyLength()];
                o.readBytes(body);
                BCSAPIMessage.ExactMatchRequest request = BCSAPIMessage.ExactMatchRequest.parseFrom(body);
                final List<byte[]> match = new ArrayList<byte[]>();
                for (ByteString bs : request.getMatchList()) {
                    match.add(bs.toByteArray());
                }
                final UpdateMode mode = UpdateMode.values()[request.getMode()];
                final MessageProducer producer = session.createProducer(msg.getJMSReplyTo());
                final long after = request.hasAfter() ? request.getAfter() : 0;
                requestProcessor.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            store.filterTransactions(match, mode, after, new TransactionProcessor() {
                                @Override
                                public void process(Tx tx) {
                                    if (tx != null) {
                                        Transaction transaction = toBCSAPITransaction(tx);
                                        BytesMessage m;
                                        try {
                                            m = session.createBytesMessage();
                                            m.writeBytes(transaction.toProtobuf().toByteArray());
                                            producer.send(m);
                                        } catch (JMSException e) {
                                        }
                                    } else {
                                        try {
                                            BytesMessage m = session.createBytesMessage();
                                            producer.send(m); // indicate EOF
                                            producer.close();
                                        } catch (JMSException e) {
                                        }
                                    }
                                }
                            });
                        } catch (ValidationException e) {
                            log.error("Error while scanning", e);
                        }
                    }
                });
            } catch (JMSException e) {
                log.error("invalid filter request", e);
            } catch (InvalidProtocolBufferException e) {
                log.error("invalid filter request", e);
            }
        }
    });
}

From source file:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java

@Override
public boolean sendMessage(Run<?, ?> build, TaskListener listener, MessageUtils.MESSAGE_TYPE type, String props,
        String content) {//from   w w w .  jav a  2  s.  com
    Connection connection = null;
    Session session = null;
    MessageProducer publisher = null;

    try {
        String ltopic = getTopic();
        if (provider.getAuthenticationMethod() != null && ltopic != null && provider.getBroker() != null) {
            ActiveMQConnectionFactory connectionFactory = provider.getConnectionFactory();
            connection = connectionFactory.createConnection();
            connection.start();

            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createTopic(ltopic);
            publisher = session.createProducer(destination);

            TextMessage message;
            message = session.createTextMessage("");
            message.setJMSType(JSON_TYPE);

            message.setStringProperty("CI_NAME", build.getParent().getName());
            message.setStringProperty("CI_TYPE", type.getMessage());
            if (!build.isBuilding()) {
                message.setStringProperty("CI_STATUS",
                        (build.getResult() == Result.SUCCESS ? "passed" : "failed"));
            }

            StrSubstitutor sub = new StrSubstitutor(build.getEnvironment(listener));

            if (props != null && !props.trim().equals("")) {
                Properties p = new Properties();
                p.load(new StringReader(props));
                @SuppressWarnings("unchecked")
                Enumeration<String> e = (Enumeration<String>) p.propertyNames();
                while (e.hasMoreElements()) {
                    String key = e.nextElement();
                    message.setStringProperty(key, sub.replace(p.getProperty(key)));
                }
            }

            message.setText(sub.replace(content));

            publisher.send(message);
            log.info("Sent " + type.toString() + " message for job '" + build.getParent().getName()
                    + "' to topic '" + ltopic + "':\n" + formatMessage(message));
        } else {
            log.severe("One or more of the following is invalid (null): user, password, topic, broker.");
            return false;
        }

    } catch (Exception e) {
        log.log(Level.SEVERE, "Unhandled exception in perform.", e);
    } finally {
        if (publisher != null) {
            try {
                publisher.close();
            } catch (JMSException e) {
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
            }
        }
    }
    return true;
}

From source file:org.apache.james.queue.activemq.ActiveMQMailQueue.java

/**
 * Produce the mail to the JMS Queue/*from   w w  w  . j  a va 2  s  .c o m*/
 */
protected void produceMail(Session session, Map<String, Object> props, int msgPrio, Mail mail)
        throws JMSException, MessagingException, IOException {
    MessageProducer producer = null;
    BlobMessage blobMessage = null;
    boolean reuse = false;

    try {

        // check if we should use a blob message here
        if (useBlob) {
            MimeMessage mm = mail.getMessage();
            MimeMessage wrapper = mm;

            ActiveMQSession amqSession = getAMQSession(session);

            /*
             * Remove this optimization as it could lead to problems when the same blob content
             * is shared across different messages. 
             * 
             * I still think it would be a good idea to somehow do this but at the moment it's just 
             * safer to disable it.
             * 
             * TODO: Re-Enable it again once it works!
             * 
             * See JAMES-1240
            if (wrapper instanceof MimeMessageCopyOnWriteProxy) {
            wrapper = ((MimeMessageCopyOnWriteProxy) mm).getWrappedMessage();
            }
                    
            if (wrapper instanceof MimeMessageWrapper) {
            URL blobUrl = (URL) mail.getAttribute(JAMES_BLOB_URL);
            String fromQueue = (String) mail.getAttribute(JAMES_QUEUE_NAME);
            MimeMessageWrapper mwrapper = (MimeMessageWrapper) wrapper;
                    
            if (blobUrl != null && fromQueue != null && mwrapper.isModified() == false) {
                // the message content was not changed so don't need to
                // upload it again and can just point to the url
                blobMessage = amqSession.createBlobMessage(blobUrl);
                reuse = true;
            }
                    
            }*/
            if (blobMessage == null) {
                // just use the MimeMessageInputStream which can read every
                // MimeMessage implementation
                blobMessage = amqSession.createBlobMessage(new MimeMessageInputStream(wrapper));
            }

            // store the queue name in the props
            props.put(JAMES_QUEUE_NAME, queuename);

            Queue queue = session.createQueue(queuename);

            producer = session.createProducer(queue);
            for (Map.Entry<String, Object> entry : props.entrySet()) {
                blobMessage.setObjectProperty(entry.getKey(), entry.getValue());
            }
            producer.send(blobMessage, Message.DEFAULT_DELIVERY_MODE, msgPrio, Message.DEFAULT_TIME_TO_LIVE);

        } else {
            super.produceMail(session, props, msgPrio, mail);
        }
    } catch (JMSException e) {
        if (!reuse && blobMessage != null && blobMessage instanceof ActiveMQBlobMessage) {
            ((ActiveMQBlobMessage) blobMessage).deleteFile();
        }
        throw e;
    } finally {

        try {
            if (producer != null)
                producer.close();
        } catch (JMSException e) {
            // ignore here
        }
    }

}