Example usage for javax.jms Session AUTO_ACKNOWLEDGE

List of usage examples for javax.jms Session AUTO_ACKNOWLEDGE

Introduction

In this page you can find the example usage for javax.jms Session AUTO_ACKNOWLEDGE.

Prototype

int AUTO_ACKNOWLEDGE

To view the source code for javax.jms Session AUTO_ACKNOWLEDGE.

Click Source Link

Document

With this acknowledgment mode, the session automatically acknowledges a client's receipt of a message either when the session has successfully returned from a call to receive or when the message listener the session has called to process the message successfully returns.

Usage

From source file:org.frameworkset.mq.ReceiveDispatcher.java

public ReceiveDispatcher(Connection connection, String destination) throws JMSException {
    this(connection, false, Session.AUTO_ACKNOWLEDGE, MQUtil.TYPE_QUEUE, destination);
}

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
 *
 *//*from w w w .  j a  va  2  s.  co  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:net.blogracy.controller.FileSharing.java

public FileSharing() {
    try {//from  w  w  w  .java2  s  . c  om
        connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL);
        connection = connectionFactory.createConnection();
        connection.start();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producer = session.createProducer(null);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        seedQueue = session.createQueue("seed");
        downloadQueue = session.createQueue("download");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ProducerTool.java

public void run() {
    Connection connection = null;
    try {/*from w w  w.j a v  a 2 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:org.trellisldp.app.triplestore.TrellisApplicationTest.java

@BeforeEach
public void aquireConnection() throws Exception {
    final ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");
    connection = connectionFactory.createConnection();
    connection.start();/*w w  w  . j a v  a2 s.  co  m*/
    final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    final Destination destination = session.createQueue("trellis");
    consumer = session.createConsumer(destination);
    consumer.setMessageListener(this);
}

From source file:org.apache.activemq.bugs.AMQ6133PersistJMSRedeliveryTest.java

private void sendMessages() throws Exception {
    Connection connection = createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination queue = session.createQueue(QUEUE_NAME);
    Destination retainQueue = session.createQueue(QUEUE_NAME + "-retain");
    MessageProducer producer = session.createProducer(null);

    final byte[] payload = new byte[1000];
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    BytesMessage message = session.createBytesMessage();
    message.writeBytes(payload);/*  w ww  .  jav  a 2s.  c o m*/

    // Build up a set of messages that will be redelivered and updated later.
    while (getLogFileCount() < 3) {
        producer.send(queue, message);
    }

    // Now create some space for files that are retained during the test.
    while (getLogFileCount() < 6) {
        producer.send(retainQueue, message);
    }

    connection.close();
}

From source file:org.artificer.events.jms.JMSEventProducer.java

@Override
public void startup() {
    if (ArtificerConfig.isJmsEnabled()) {
        try {//from  w  ww. ja v  a  2s  .com
            String connectionFactoryName = ArtificerConfig.getConfigProperty(
                    ArtificerConstants.ARTIFICER_CONFIG_EVENT_JMS_CONNECTIONFACTORY, "ConnectionFactory");

            // Note that both properties end up doing the same thing.  Technically, we could combine both into one
            // single sramp.config.events.jms.destinations, but leaving them split for readability.
            String topicNamesProp = ArtificerConfig
                    .getConfigProperty(ArtificerConstants.ARTIFICER_CONFIG_EVENT_JMS_TOPICS, "");
            String[] topicNames = new String[0];
            if (StringUtils.isNotEmpty(topicNamesProp)) {
                topicNames = topicNamesProp.split(",");
            }
            String queueNamesProp = ArtificerConfig
                    .getConfigProperty(ArtificerConstants.ARTIFICER_CONFIG_EVENT_JMS_QUEUES, "");
            String[] queueNames = new String[0];
            if (StringUtils.isNotEmpty(queueNamesProp)) {
                queueNames = queueNamesProp.split(",");
            }

            // See if a ConnectionFactory and Topic/Queue exists on JNDI.  If so, assume JMS is properly
            // setup in a Java EE container and use it.

            ConnectionFactory connectionFactory = (ConnectionFactory) jndiLookup(connectionFactoryName);
            connection = connectionFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            for (String topicName : topicNames) {
                Topic topic = (Topic) jndiLookup(topicName);
                destinations.add(topic);
            }

            for (String queueName : queueNames) {
                Queue queue = (Queue) jndiLookup(queueName);
                destinations.add(queue);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
    }
}

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

private void sendMessage(Object o) {

    Session session = null;// ww  w  .ja  va  2 s.co  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:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java

@Override
public boolean subscribe(String jobname, String selector) {
    this.topic = getTopic();
    if (this.topic != null) {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                if (!isConnected()) {
                    if (!connect()) {
                        return false;
                    }/*  ww w.j  a  va 2s. co m*/
                }
                if (subscriber == null) {
                    log.info("Subscribing job '" + jobname + "' to '" + this.topic + "' topic.");
                    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                    Topic destination = session.createTopic(this.topic);

                    subscriber = session.createDurableSubscriber(destination, jobname, selector, false);
                    log.info("Successfully subscribed job '" + jobname + "' to '" + this.topic
                            + "' topic with selector: " + selector);
                } else {
                    log.fine("Already subscribed to '" + this.topic + "' topic with selector: " + selector
                            + " for job '" + jobname);
                }
                return true;
            } catch (JMSException ex) {

                // Either we were interrupted, or something else went
                // wrong. If we were interrupted, then we will jump ship
                // on the next iteration. If something else happened,
                // then we just unsubscribe here, sleep, so that we may
                // try again on the next iteration.

                log.log(Level.SEVERE, "JMS exception raised while subscribing job '" + jobname
                        + "', retrying in " + RETRY_MINUTES + " minutes.", ex);
                if (!Thread.currentThread().isInterrupted()) {

                    unsubscribe(jobname);

                    try {
                        Thread.sleep(RETRY_MINUTES * 60 * 1000);
                    } catch (InterruptedException ie) {
                        // We were interrupted while waiting to retry.
                        // We will jump ship on the next iteration.

                        // NB: The interrupt flag was cleared when
                        // InterruptedException was thrown. We have to
                        // re-install it to make sure we eventually
                        // leave this thread.
                        Thread.currentThread().interrupt();
                    }
                }
            }
        }
    }
    return false;
}

From source file:org.apache.qpid.client.ssl.SSLTest.java

/**
 * Create an SSL connection using the SSL system properties for the trust and key store, but using
 * the {@link ConnectionURL} ssl='true' option to indicate use of SSL at a Connection level,
 * without specifying anything at the {@link ConnectionURL#OPTIONS_BROKERLIST} level.
 *///w  w  w .  j  a v a2 s  . com
public void testSslConnectionOption() throws Exception {
    if (shouldPerformTest()) {
        //Start the broker (NEEDing client certificate authentication)
        configureJavaBrokerIfNecessary(true, true, true, false);
        super.setUp();

        //Create URL enabling SSL at the connection rather than brokerlist level
        String url = "amqp://guest:guest@test/?ssl='true'&brokerlist='tcp://localhost:%s'";
        url = String.format(url, QpidBrokerTestCase.DEFAULT_SSL_PORT);

        Connection con = getConnection(new AMQConnectionURL(url));
        assertNotNull("connection should be successful", con);
        Session ssn = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
        assertNotNull("create session should be successful", ssn);
    }
}