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.sdnmq.jms.PacketHandler.java

/**
 * Initialization of JMS./*from   ww  w. j a  v a  2 s.co  m*/
 */
private void initMQ() {
    log.trace("Setting up JMS ...");

    Properties jndiProps = JNDIHelper.getJNDIProperties();

    Context ctx = null;
    try {
        ctx = new InitialContext(jndiProps);
    } catch (NamingException e) {
        log.error(e.getMessage());
        releaseMQ();
        return;
    }

    TopicConnectionFactory topicFactory = null;
    try {
        topicFactory = (TopicConnectionFactory) ctx.lookup("TopicConnectionFactory");
    } catch (NamingException e) {
        log.error(e.getMessage());
        releaseMQ();
        return;
    }

    try {
        connection = topicFactory.createTopicConnection();
    } catch (JMSException e) {
        log.error("Could not create JMS connection: " + e.getMessage());
        releaseMQ();
        return;
    }

    try {
        session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    } catch (JMSException e) {
        log.error("Could not create JMS session: " + e.getMessage());
        releaseMQ();
        return;
    }

    // Get the JNDI object name of the packet-in topic object from the OpenDaylight configuration.
    String topicName = System.getProperty(PACKETIN_TOPIC_PROPERTY, DEFAULT_PACKETIN_TOPIC_NAME);
    log.info("Using the following topic for packet-in events: " + topicName);
    try {
        packetinTopic = (Topic) ctx.lookup(topicName);
    } catch (NamingException e) {
        log.error("Could not resolve topic object: " + e.getMessage());
        releaseMQ();
        return;
    }

    try {
        publisher = session.createPublisher(packetinTopic);
    } catch (JMSException e) {
        log.error(e.getMessage());
        releaseMQ();
        return;
    }

    log.trace("JMS setup finished successfully");
}

From source file:org.wso2.esb.integration.common.utils.clients.jmsclient.JMSQueueMessageProducer.java

/**
 * Method to establish the connection with the given Queue, with message persistance as specified.
 * This must be called before calling pushMessage() to send messages.
 *
 * @param persistMessage whether or not messages need to be persisted
 * @param queueName name of the queue//from  w w w.j  av a2  s .  c o  m
 * @throws JMSException if connection to the queue fails
 */
public void connect(String queueName, boolean persistMessage) throws JMSException {
    connection = connectionFactory.createConnection();
    connection.start();
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createQueue(queueName);
    producer = session.createProducer(destination);
    if (persistMessage) {
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    } else {
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
    }
}

From source file:org.openbaton.common.vnfm_sdk.amqp.VnfmSpringHelper.java

/**
 * This method should be used for receiving text message from EMS
 *
 * resp = { 'output': out, // the output of the command 'err': err, // the error outputs of the
 * commands 'status': status // the exit status of the command }
 *
 * @param queueName//from   w  w  w .  j  a  v  a2  s.c o  m
 * @return
 * @throws JMSException
 */
public String receiveTextFromQueue(String queueName)
        throws JMSException, ExecutionException, InterruptedException, VnfmSdkException {
    String res;

    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(session.createQueue(queueName));
    connection.start();
    String scriptMaxTime = properties.getProperty("script-max-time");
    if (scriptMaxTime != null) {
        TextMessage textMessage = (TextMessage) consumer.receive(Long.parseLong(scriptMaxTime));
        if (textMessage != null)
            res = textMessage.getText();
        else
            throw new VnfmSdkException("No message got from queue " + queueName + " after " + scriptMaxTime);
    } else
        res = ((TextMessage) consumer.receive()).getText();
    log.debug("Received Text from " + queueName + ": " + res);
    consumer.close();
    session.close();
    connection.close();
    return res;
}

From source file:org.apache.activemq.usecases.DurableSubscriptionHangTestCase.java

private void registerDurableSubscription() throws JMSException {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName);
    TopicConnection connection = connectionFactory.createTopicConnection();
    connection.setClientID(clientID);/*from w w  w  .ja va 2 s  .  c o  m*/
    TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic topic = topicSession.createTopic(topicName);
    TopicSubscriber durableSubscriber = topicSession.createDurableSubscriber(topic, durableSubName);
    connection.start();
    durableSubscriber.close();
    connection.close();
    LOG.info("Durable Sub Registered");
}

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

@Test(timeout = 300000)
public void testDurableWithOnePendingAfterRestartAndIndexRecovery() throws Exception {
    final File persistentDir = getPersistentDir();

    broker.getBroker().addDestination(broker.getAdminConnectionContext(), new ActiveMQTopic("durable.sub"),
            false);/*from  w ww  .  jav a 2s .  c o m*/

    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(this.brokerConnectURI);
    ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection();
    connection.setClientID("myId");
    connection.start();
    final Session jmsSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);

    TopicSubscriber durable = jmsSession.createDurableSubscriber(new ActiveMQTopic("durable.sub"), "sub");
    final MessageProducer producer = jmsSession.createProducer(new ActiveMQTopic("durable.sub"));

    final int original = new ArrayList<File>(
            FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"), TrueFileFilter.INSTANCE))
                    .size();

    // 100k messages
    final byte[] data = new byte[100000];
    final Random random = new Random();
    random.nextBytes(data);

    // run test with enough messages to create a second journal file
    final AtomicInteger messageCount = new AtomicInteger();
    assertTrue("Should have added a journal file", Wait.waitFor(new Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            final ActiveMQBytesMessage message = new ActiveMQBytesMessage();
            message.setContent(new ByteSequence(data));

            for (int i = 0; i < 100; i++) {
                producer.send(message);
                messageCount.getAndIncrement();
            }

            return new ArrayList<File>(FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"),
                    TrueFileFilter.INSTANCE)).size() > original;
        }
    }));

    // Consume all but 1 message
    for (int i = 0; i < messageCount.get() - 1; i++) {
        durable.receive();
    }

    durable.close();

    // wait until a journal file has been GC'd after receiving messages
    assertTrue("Subscription should go inactive", Wait.waitFor(new Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            return broker.getAdminView().getInactiveDurableTopicSubscribers().length == 1;
        }
    }));

    // force a GC of unneeded journal files
    getBroker().getPersistenceAdapter().checkpoint(true);

    // wait until a journal file has been GC'd after receiving messages
    assertFalse("Should not have garbage collected", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            return new ArrayList<File>(FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"),
                    TrueFileFilter.INSTANCE)).size() == original;
        }
    }, 5000, 500));

    // stop the broker so we can blow away the index
    getBroker().stop();
    getBroker().waitUntilStopped();

    // delete the index so that the durables are gone from the index
    // The test passes if you take out this delete section
    for (File index : FileUtils.listFiles(persistentDir, new WildcardFileFilter("db.*"),
            TrueFileFilter.INSTANCE)) {
        FileUtils.deleteQuietly(index);
    }

    stopBroker();
    setUpBroker(false);

    assertEquals(1, broker.getAdminView().getInactiveDurableTopicSubscribers().length);
    assertEquals(0, broker.getAdminView().getDurableTopicSubscribers().length);

    ActiveMQConnectionFactory connectionFactory2 = new ActiveMQConnectionFactory(this.brokerConnectURI);
    ActiveMQConnection connection2 = (ActiveMQConnection) connectionFactory2.createConnection();
    connection2.setClientID("myId");
    connection2.start();
    final Session jmsSession2 = connection2.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);

    TopicSubscriber durable2 = jmsSession2.createDurableSubscriber(new ActiveMQTopic("durable.sub"), "sub");

    assertEquals(0, broker.getAdminView().getInactiveDurableTopicSubscribers().length);
    assertEquals(1, broker.getAdminView().getDurableTopicSubscribers().length);

    assertNotNull(durable2.receive(5000));
}

From source file:org.apache.falcon.messaging.JMSMessageConsumerTest.java

public void sendMessages(String topic, WorkflowExecutionContext.Type type, boolean isFalconWF)
        throws JMSException, FalconException, IOException {
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
    Connection connection = connectionFactory.createConnection();
    connection.start();//w w w.j  a  v  a2 s  . c o  m

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic destination = session.createTopic(topic);
    javax.jms.MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);

    for (int i = 0; i < 5; i++) {
        Message message = null;

        switch (type) {
        case POST_PROCESSING:
            message = getMockFalconMessage(i, session);
            break;
        case WORKFLOW_JOB:
            message = getMockOozieMessage(i, session, isFalconWF);
            break;
        case COORDINATOR_ACTION:
            message = getMockOozieCoordMessage(i, session, isFalconWF);
        default:
            break;
        }
        Log.debug("Sending:" + message);
        producer.send(message);
    }
}

From source file:com.nesscomputing.jms.activemq.ServiceDiscoveryTransportFactoryTest.java

private void sendTestMessage(final Connection directConnection) throws Exception {
    final Session session = directConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    final MessageProducer producer = session.createProducer(session.createQueue(QNAME));
    producer.send(session.createTextMessage(uniqueId));
    session.close();//from   w  ww .j  a  v a 2  s .co  m
}

From source file:de.elomagic.carafile.server.bl.SeedBean.java

public MetaData seedFile(final InputStream inputStream, final String filename)
        throws IOException, GeneralSecurityException, JMSException {
    LOG.debug("Seeding file " + filename);
    MetaData md;/*from   www.ja va2s.  c  o  m*/
    md = new MetaData();
    md.setFilename(filename);
    md.setCreationDate(new Date());
    md.setChunkSize(DEFAULT_PIECE_SIZE);
    md.setRegistryURI(UriBuilder.fromUri(registryURI).build());

    MessageDigest messageDigest = DigestUtils.getSha1Digest();
    long totalBytes = 0;

    try (DigestInputStream dis = new DigestInputStream(inputStream, messageDigest)) {
        byte[] buffer = new byte[md.getChunkSize()];
        int bytesRead;
        while ((bytesRead = readBlock(dis, buffer)) > 0) {
            totalBytes += bytesRead;
            String chunkId = Hex
                    .encodeHexString(DigestUtils.sha1(new ByteArrayInputStream(buffer, 0, bytesRead)));

            repositoryBean.writeChunk(chunkId, buffer, bytesRead);

            URI uri = UriBuilder.fromUri(ownURI).build();

            ChunkData chunkData = new ChunkData(chunkId, uri);
            md.addChunk(chunkData);
        }
    }

    md.setSize(totalBytes);
    md.setId(Hex.encodeHexString(messageDigest.digest()));

    LOG.debug("File id of seed file is " + md.getId() + "; Size=" + md.getSize() + "; Chunks="
            + md.getChunks().size());

    // Initiate to register at tracker
    LOG.debug("Queue up new file for registration.");
    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer messageProducer = session.createProducer(fileQueue);

    ObjectMessage message = session.createObjectMessage(md);

    messageProducer.send(message);

    connection.close();

    return md;
}

From source file:org.wso2.andes.systest.GlobalQueuesTest.java

/**
 * Test that setting messageAge has an effect on topics
 *
 * Sets the messageAge to be half the disconnection wait timeout
 * Send 10 messages and then ensure that we get disconnected as we will
 * wait for the full timeout./*from  w  w w .j  av a 2  s  .  c  o m*/
 *
 * @throws Exception
 */
public void testTopicConsumerMessageAge() throws Exception {
    MAX_QUEUE_MESSAGE_COUNT = 10;

    setConfig("messageAge", String.valueOf(DISCONNECTION_WAIT / 2), false);

    //Start the broker
    startBroker();

    topicConsumer(Session.AUTO_ACKNOWLEDGE, false);
}

From source file:com.googlecode.fascinator.messaging.EmailNotificationConsumer.java

/**
 * Start thread running//from   w  ww .  jav a2 s  .  com
 *
 */
@Override
public void run() {
    try {
        log.info("Starting {}...", name);

        // Get a connection to the broker
        String brokerUrl = globalConfig.getString(ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL,
                "messaging", "url");
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);
        connection = connectionFactory.createConnection();

        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        consumer = session.createConsumer(session.createQueue(QUEUE_ID));
        consumer.setMessageListener(this);

        // broadcast = session.createTopic(MessagingServices.MESSAGE_TOPIC);
        producer = session.createProducer(null);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);

        connection.start();
    } catch (JMSException ex) {
        log.error("Error starting message thread!", ex);
    }
}