Example usage for javax.jms MessageProducer setDeliveryMode

List of usage examples for javax.jms MessageProducer setDeliveryMode

Introduction

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

Prototype


void setDeliveryMode(int deliveryMode) throws JMSException;

Source Link

Document

Sets the producer's default delivery mode.

Usage

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

/**
 * This method is called when a message was received at the incoming queue
 *
 * @param message The incoming JMS Message
 */// w w w. ja  v a2s  . c  o m
@Override
public void onMessage(final Message message) {
    final MapMessage map = (MapMessage) message;
    try {
        final Connection con = this.cf.createConnection();
        final Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
        final MapMessage res = session.createMapMessage();
        try {
            final String messageID = this.submit(map);
            res.setStringProperty("messageId", messageID);
        } catch (final TransformationException | ValidationException e) {
            BackendJMSImpl.LOG.error("Exception occurred: ", e);
            res.setString("ErrorMessage", e.getMessage());
        }

        res.setJMSCorrelationID(map.getJMSCorrelationID());
        final MessageProducer sender = session.createProducer(this.outQueue);
        sender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        sender.send(res);
        sender.close();
        session.close();
        con.close();

    } catch (final JMSException ex) {
        BackendJMSImpl.LOG.error("Error while sending response to queue", ex);

    }
}

From source file:ProducerTool.java

public void run() {
    Connection connection = null;
    try {//  www. j  a  v  a2 s.c om
        // Create the connection.
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
        connection = connectionFactory.createConnection();
        connection.start();

        // Create the session
        Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
        if (topic) {
            destination = session.createTopic(subject);
        } else {
            destination = session.createQueue(subject);
        }

        // Create the producer.
        MessageProducer producer = session.createProducer(destination);
        if (persistent) {
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        } else {
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        }
        if (timeToLive != 0) {
            producer.setTimeToLive(timeToLive);
        }

        // Start sending messages
        sendLoop(session, producer);

        System.out.println("[" + this.getName() + "] Done.");

        synchronized (lockResults) {
            ActiveMQConnection c = (ActiveMQConnection) connection;
            System.out.println("[" + this.getName() + "] Results:\n");
            c.getConnectionStats().dump(new IndentPrinter());
        }

    } catch (Exception e) {
        System.out.println("[" + this.getName() + "] Caught: " + e);
        e.printStackTrace();
    } finally {
        try {
            connection.close();
        } catch (Throwable ignore) {
        }
    }
}

From source file:com.mirth.connect.connectors.jms.JmsReceiverTests.java

private void putMessagesInDestination(Destination destination, int numMessages) throws Exception {
    if (numMessages > 0) {
        MessageProducer producer = session.createProducer(destination);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        logger.debug("Putting " + numMessages + " messages into destination");

        for (int i = 0; i < numMessages; i++) {
            TextMessage message = session.createTextMessage(TEST_HL7_MESSAGE);
            message.setIntProperty("messageNumber", i);
            producer.send(message);//  ww w . j a  va  2  s . c  om
        }
    }
}

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

public void run() {

    try {/*w  w  w .ja v a 2 s.c o  m*/
        Connection conn = getConnection();
        Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

        if (isExpectReply()) {
            Destination replyTo = getDestinationProvider().getDestination(session, getReplyDestination());
            MessageConsumer consumer = session.createConsumer(replyTo);
            consumer.setMessageListener(this);
        }

        Destination dest = getDestinationProvider().getDestination(session, getDestinationName());
        MessageProducer producer = session.createProducer(dest);
        producer.setDeliveryMode(getDeliveryMode().getCode());
        getConnection().start();

        LOG.info(">>Starting Message send loop");
        while (!done.get()) {
            try {
                locallySent++;
                Destination replyDest = null;
                Message msg = getMessageFactory().createMessage(session);
                if (getMsgGroup() != null) {
                    LOG.debug("Setting message group to : " + getMsgGroup());
                    msg.setStringProperty("JMSXGroupID", getMsgGroup());
                    if (getMessagesToSend() > 0) {
                        if (locallySent == getMessagesToSend()) {
                            LOG.debug("Closing message group: " + getMsgGroup());
                            msg.setIntProperty("JMSXGroupSeq", 0);
                        }
                    }
                }
                msg.setLongProperty("MsgNr", locallySent);
                if (isExpectReply()) {
                    corrId = getReplyDestination() + "Seq-" + locallySent;
                    msg.setStringProperty("JMSCorrelationID", corrId);
                    replyDest = getDestinationProvider().getDestination(session, getReplyDestination());
                    msg.setJMSReplyTo(replyDest);
                    receivedResponse = false;
                }
                long sendTime = System.currentTimeMillis();
                producer.send(msg, deliveryMode.getCode(), 4, ttl);
                if (sent != null) {
                    sent.incrementAndGet();
                }
                done.set((getMessagesToSend() > 0) && ((locallySent) == getMessagesToSend()));
                if (isExpectReply()) {
                    try {
                        LOG.debug("Waiting for response ...");
                        synchronized (corrId) {
                            try {
                                if (getReplyTimeOut() > 0) {
                                    corrId.wait(getReplyTimeOut());
                                } else {
                                    corrId.wait();
                                }
                            } catch (InterruptedException ie) {
                            }
                            if (receivedResponse) {
                                long duration = System.currentTimeMillis() - sendTime;
                                LOG.debug("Got response from peer in " + duration + " ms");
                            } else {
                                LOG.error("Response not received within time frame...");
                                if (timeOuts != null) {
                                    timeOuts.incrementAndGet();
                                }
                            }
                        }
                    } catch (Exception e) {
                        if (exceptions != null) {
                            exceptions.incrementAndGet();
                        }
                    }
                }
                if (sleep > 0L) {
                    try {
                        Thread.sleep(sleep);
                    } catch (InterruptedException ie) {
                    }
                }
            } catch (JMSException e) {
                if (exceptions != null) {
                    exceptions.incrementAndGet();
                }
            }
        }
    } catch (Exception e) {
    } finally {
        try {
            closeConnection();
        } catch (Throwable e) {
        }
    }
    LOG.info(">>MessageSender done...(" + sent + ")");
}

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

private Boolean submitToBackend(final String messageId) {
    Connection connection;/*  ww  w.ja v a 2 s .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: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//from w  w  w  .ja  v  a2s.  c  om
 */
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:eu.domibus.submission.jms.BackendJMSImpl.java

private Boolean submitErrorMessage(String messageId) {
    Connection connection;//from   ww  w  . j  a  va2s  .  co m
    MessageProducer producer;
    List<ErrorLogEntry> errors = this.errorLogDao.getUnnotifiedErrorsForMessage(messageId);

    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();
        for (int i = 0; i < errors.size(); ++i) {
            resMessage.setString(String.valueOf(i), errors.get(i).toString());
            errors.get(i).setNotified(new Date());
            this.errorLogDao.update(errors.get(i));
        }

        producer.send(resMessage);
        producer.close();
        session.close();

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

From source file:com.moss.veracity.core.cluster.jms.UpdateTransmitterJMSImpl.java

private void sendMessage(Object o) {

    Session session = null;//from   ww  w .j a v  a  2s. c  o  m
    MessageProducer producer = null;
    try {
        StringWriter writer = new StringWriter();
        Marshaller m = jaxbContext.createMarshaller();
        m.marshal(o, writer);
        String text = writer.getBuffer().toString();

        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic(UpdateTopic.NAME);
        producer = session.createProducer(topic);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);

        TextMessage message = session.createTextMessage(text);
        producer.send(message);

        producer.close();
        session.close();
    } catch (Exception ex) {

        if (producer != null) {
            try {
                producer.close();
            } catch (JMSException e) {
                if (log.isErrorEnabled()) {
                    log.error("Failed to close producer after failure", e);
                } else {
                    ex.printStackTrace();
                }
            }
        }

        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                if (log.isErrorEnabled()) {
                    log.error("Failed to close session after failure", e);
                } else {
                    ex.printStackTrace();
                }
            }
        }

        throw new RuntimeException("Message transmission failed: " + o, ex);
    }
}

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.
 * //from w ww  .  j ava 2s.c  o m
 * @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();
    }

}