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.soitoolkit.commons.studio.components.logger.impl.DefaultLogEventSender.java

protected void sendOneTextMessage(Session session, String queueName, String message) {

    MessageProducer publisher = null;

    try {//from  w ww .  j a  va 2s . c o m
        publisher = session.createProducer(session.createQueue(queueName));
        TextMessage textMessage = session.createTextMessage(message);
        publisher.send(textMessage);

    } catch (JMSException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (publisher != null)
                publisher.close();
        } catch (JMSException e) {
        }
    }
}

From source file:com.microsoft.azure.servicebus.samples.jmstopicquickstart.JmsTopicQuickstart.java

public void run(String connectionString) throws Exception {

    // The connection string builder is the only part of the azure-servicebus SDK library 
    // we use in this JMS sample and for the purpose of robustly parsing the Service Bus 
    // connection string. 
    ConnectionStringBuilder csb = new ConnectionStringBuilder(connectionString);

    // set up the JNDI context 
    Hashtable<String, String> hashtable = new Hashtable<>();
    hashtable.put("connectionfactory.SBCF",
            "amqps://" + csb.getEndpoint().getHost() + "?amqp.idleTimeout=120000&amqp.traceFrames=true");
    hashtable.put("topic.TOPIC", "BasicTopic");
    hashtable.put("queue.SUBSCRIPTION1", "BasicTopic/Subscriptions/Subscription1");
    hashtable.put("queue.SUBSCRIPTION2", "BasicTopic/Subscriptions/Subscription2");
    hashtable.put("queue.SUBSCRIPTION3", "BasicTopic/Subscriptions/Subscription3");
    hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
    Context context = new InitialContext(hashtable);

    ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF");

    // Look up the topic
    Destination topic = (Destination) context.lookup("TOPIC");

    // we create a scope here so we can use the same set of local variables cleanly 
    // again to show the receive side seperately with minimal clutter
    {/*from   w w  w  . j  a  v  a 2  s  .co  m*/
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        connection.start();
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

        // Create producer
        MessageProducer producer = session.createProducer(topic);

        // Send messaGES
        for (int i = 0; i < totalSend; i++) {
            BytesMessage message = session.createBytesMessage();
            message.writeBytes(String.valueOf(i).getBytes());
            producer.send(message);
            System.out.printf("Sent message %d.\n", i + 1);
        }

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

    // Look up the subscription (pretending it's a queue)
    receiveFromSubscription(csb, context, cf, "SUBSCRIPTION1");
    receiveFromSubscription(csb, context, cf, "SUBSCRIPTION2");
    receiveFromSubscription(csb, context, cf, "SUBSCRIPTION3");

    System.out.printf("Received all messages, exiting the sample.\n");
    System.out.printf("Closing queue client.\n");
}

From source file:com.microsoft.azure.servicebus.samples.jmsqueuequickstart.JmsQueueQuickstart.java

public void run(String connectionString) throws Exception {

    // The connection string builder is the only part of the azure-servicebus SDK library
    // we use in this JMS sample and for the purpose of robustly parsing the Service Bus 
    // connection string. 
    ConnectionStringBuilder csb = new ConnectionStringBuilder(connectionString);

    // set up JNDI context
    Hashtable<String, String> hashtable = new Hashtable<>();
    hashtable.put("connectionfactory.SBCF",
            "amqps://" + csb.getEndpoint().getHost() + "?amqp.idleTimeout=120000&amqp.traceFrames=true");
    hashtable.put("queue.QUEUE", "BasicQueue");
    hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
    Context context = new InitialContext(hashtable);
    ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF");

    // Look up queue
    Destination queue = (Destination) context.lookup("QUEUE");

    // we create a scope here so we can use the same set of local variables cleanly 
    // again to show the receive side separately with minimal clutter
    {/*ww w  . ja v a2  s  .co  m*/
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

        // Create producer
        MessageProducer producer = session.createProducer(queue);

        // Send messages
        for (int i = 0; i < totalSend; i++) {
            BytesMessage message = session.createBytesMessage();
            message.writeBytes(String.valueOf(i).getBytes());
            producer.send(message);
            System.out.printf("Sent message %d.\n", i + 1);
        }

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

    {
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        connection.start();
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        // Create consumer
        MessageConsumer consumer = session.createConsumer(queue);
        // create a listener callback to receive the messages
        consumer.setMessageListener(message -> {
            try {
                // receives message is passed to callback
                System.out.printf("Received message %d with sq#: %s\n", totalReceived.incrementAndGet(), // increments the tracking counter
                        message.getJMSMessageID());
                message.acknowledge();
            } catch (Exception e) {
                logger.error(e);
            }
        });

        // wait on the main thread until all sent messages have been received
        while (totalReceived.get() < totalSend) {
            Thread.sleep(1000);
        }
        consumer.close();
        session.close();
        connection.stop();
        connection.close();
    }

    System.out.printf("Received all messages, exiting the sample.\n");
    System.out.printf("Closing queue client.\n");
}

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

private Boolean submitToBackend(final String messageId) {
    Connection connection;/*from w ww  . j a v  a 2  s .c  om*/
    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:com.moss.veracity.core.cluster.jms.UpdateTransmitterJMSImpl.java

private void sendMessage(Object o) {

    Session session = null;//from   www  .  ja  v a  2 s  .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: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  va  2s. co  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:me.norman.maurer.james.queue.HornetQMailQueue.java

@Override
protected void produceMail(Session session, Map<String, Object> props, int msgPrio, Mail mail)
        throws JMSException, MessagingException, IOException {
    MessageProducer producer = null;
    try {//ww w .  j a  v  a2 s . co  m
        BytesMessage message = session.createBytesMessage();
        Iterator<String> propIt = props.keySet().iterator();
        while (propIt.hasNext()) {
            String key = propIt.next();
            message.setObjectProperty(key, props.get(key));
        }
        // set the stream to read frome
        message.setObjectProperty("JMS_HQ_InputStream",
                new BufferedInputStream(new MimeMessageInputStream(mail.getMessage())));
        Queue q = session.createQueue(queuename);
        producer = session.createProducer(q);
        producer.send(message, Message.DEFAULT_DELIVERY_MODE, msgPrio, Message.DEFAULT_TIME_TO_LIVE);
    } finally {
        if (producer != null) {
            producer.close();
        }
    }
}

From source file:com.amazon.sqs.javamessaging.SQSSession.java

void doClose() throws JMSException {
    boolean shouldClose = false;
    synchronized (stateLock) {
        if (!closing) {
            shouldClose = true;//from  w  w w .jav a2 s  . co m
            closing = true;
        }
        stateLock.notifyAll();
    }

    if (closed) {
        return;
    }

    if (shouldClose) {
        try {
            parentSQSConnection.removeSession(this);

            for (SQSMessageConsumer messageConsumer : messageConsumers) {
                messageConsumer.close();
                /** Nack the messages that were delivered but not acked */
                messageConsumer.recover();
            }

            try {
                if (executor != null) {
                    LOG.info("Shutting down " + SESSION_EXECUTOR_NAME + " executor");

                    /** Shut down executor. */
                    executor.shutdown();

                    waitForCallbackComplete();

                    sqsSessionRunnable.close();

                    for (MessageProducer messageProducer : messageProducers) {
                        messageProducer.close();
                    }

                    if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {

                        LOG.warn("Can't terminate executor service " + SESSION_EXECUTOR_NAME + " after "
                                + SESSION_EXECUTOR_GRACEFUL_SHUTDOWN_TIME
                                + " seconds, some running threads will be shutdown immediately");
                        executor.shutdownNow();
                    }
                }
            } catch (InterruptedException e) {
                LOG.error("Interrupted while closing the session.", e);
            }

        } finally {
            synchronized (stateLock) {
                closed = true;
                running = false;
                stateLock.notifyAll();
            }
        }
    } /** Blocks until closing of the session completes */
    else {
        synchronized (stateLock) {
            while (!closed) {
                try {
                    stateLock.wait();
                } catch (InterruptedException e) {
                    LOG.error("Interrupted while waiting the session to close.", e);
                }
            }
        }
    }
}

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

private void reply(Destination destination, byte[] msg) {
    MessageProducer replier = null;
    try {//from  w  ww .ja  v a  2  s . co  m
        replier = session.createProducer(destination);
        BytesMessage m = session.createBytesMessage();
        if (msg != null) {
            m.writeBytes(msg);
        }
        replier.send(m);
    } catch (JMSException e) {
        log.trace("can not reply", e);
    } finally {
        try {
            replier.close();
        } catch (JMSException e) {
        }
    }
}

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

private Boolean submitErrorMessage(String messageId) {
    Connection connection;/*w  w  w . j  a v  a  2s .  c  om*/
    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;
}