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.apache.flume.source.jms.TestIntegrationActiveMQ.java

private void putTopic(List<String> events) throws Exception {
    ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER_BIND_URL);
    Connection connection = factory.createConnection();
    connection.start();/*w w w.  j  a  v a2  s.c o  m*/

    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createTopic(DESTINATION_NAME);
    MessageProducer producer = session.createProducer(destination);

    for (String event : events) {
        TextMessage message = session.createTextMessage();
        message.setText(event);
        producer.send(message);
    }
    session.commit();
    session.close();
    connection.close();
}

From source file:org.springframework.jms.connection.ConnectionFactoryUtils.java

/**
 * Obtain a JMS Session that is synchronized with the current transaction, if any.
 * @param cf the ConnectionFactory to obtain a Session for
 * @param existingCon the existing JMS Connection to obtain a Session for
 * (may be {@code null})/*from  ww w .  jav  a  2s. co m*/
 * @param synchedLocalTransactionAllowed whether to allow for a local JMS transaction
 * that is synchronized with a Spring-managed transaction (where the main transaction
 * might be a JDBC-based one for a specific DataSource, for example), with the JMS
 * transaction committing right after the main transaction. If not allowed, the given
 * ConnectionFactory needs to handle transaction enlistment underneath the covers.
 * @return the transactional Session, or {@code null} if none found
 * @throws JMSException in case of JMS failure
 */
@Nullable
public static Session getTransactionalSession(final ConnectionFactory cf,
        @Nullable final Connection existingCon, final boolean synchedLocalTransactionAllowed)
        throws JMSException {

    return doGetTransactionalSession(cf, new ResourceFactory() {
        @Override
        @Nullable
        public Session getSession(JmsResourceHolder holder) {
            return holder.getSession(Session.class, existingCon);
        }

        @Override
        @Nullable
        public Connection getConnection(JmsResourceHolder holder) {
            return (existingCon != null ? existingCon : holder.getConnection());
        }

        @Override
        public Connection createConnection() throws JMSException {
            return cf.createConnection();
        }

        @Override
        public Session createSession(Connection con) throws JMSException {
            return con.createSession(synchedLocalTransactionAllowed, Session.AUTO_ACKNOWLEDGE);
        }

        @Override
        public boolean isSynchedLocalTransactionAllowed() {
            return synchedLocalTransactionAllowed;
        }
    }, true);
}

From source file:com.googlecode.fascinator.indexer.SolrWrapperQueueConsumer.java

/**
 * Start thread running//from  www .  j a va2 s .  c o  m
 * 
 */
@Override
public void run() {
    try {
        MDC.put("name", name);
        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);
        connection.start();

        // Solr
        solr = initCore("solr");
        // Timeout 'tick' for buffer (10s)
        timer = new Timer("SolrWrapper:" + toString(), true);
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                checkTimeout();
            }
        }, 0, 10000);
    } catch (JMSException ex) {
        log.error("Error starting message thread!", ex);
    }
}

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

@Override
public void run() {
    CallbackEntry callbackEntry = null;/*from  ww  w  .j  a v  a2  s  .c o  m*/
    try {
        while (true) {
            try {
                if (closed) {
                    break;
                }
                synchronized (callbackQueue) {
                    callbackEntry = callbackQueue.pollFirst();
                    if (callbackEntry == null) {
                        try {
                            callbackQueue.wait();
                        } catch (InterruptedException e) {
                            /**
                             * Will be retried on the next loop, and
                             * break if the callback scheduler is closed.
                             */
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("wait on empty callback queue interrupted: " + e.getMessage());
                            }
                        }
                        continue;
                    }
                }

                MessageListener messageListener = callbackEntry.getMessageListener();
                MessageManager messageManager = callbackEntry.getMessageManager();
                SQSMessage message = (SQSMessage) messageManager.getMessage();
                SQSMessageConsumer messageConsumer = messageManager.getPrefetchManager().getMessageConsumer();
                if (messageConsumer.isClosed()) {
                    nackReceivedMessage(message);
                    continue;
                }

                try {
                    // this takes care of start and stop
                    session.startingCallback(messageConsumer);
                } catch (JMSException e) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Not running callback: " + e.getMessage());
                    }
                    break;
                }

                try {
                    /**
                     * Notifying consumer prefetch thread so that it can
                     * continue to prefetch
                     */
                    messageManager.getPrefetchManager().messageDispatched();
                    int ackMode = acknowledgeMode.getOriginalAcknowledgeMode();
                    boolean tryNack = true;
                    try {
                        if (messageListener != null) {
                            if (ackMode != Session.AUTO_ACKNOWLEDGE) {
                                acknowledger.notifyMessageReceived(message);
                            }
                            boolean callbackFailed = false;
                            try {
                                messageListener.onMessage(message);
                            } catch (Throwable ex) {
                                LOG.info("Exception thrown from onMessage callback for message "
                                        + message.getSQSMessageId(), ex);
                                callbackFailed = true;
                            } finally {
                                if (!callbackFailed) {
                                    if (ackMode == Session.AUTO_ACKNOWLEDGE) {
                                        message.acknowledge();
                                    }
                                    tryNack = false;
                                }
                            }
                        }
                    } catch (JMSException ex) {
                        LOG.warn("Unable to complete message dispatch for the message "
                                + message.getSQSMessageId(), ex);
                    } finally {
                        if (tryNack) {
                            nackReceivedMessage(message);
                        }
                    }

                    /**
                     * The consumer close is delegated to the session thread
                     * if consumer close is called by its message listener's
                     * onMessage method on its own consumer.
                     */
                    if (consumerCloseAfterCallback != null) {
                        consumerCloseAfterCallback.doClose();
                        consumerCloseAfterCallback = null;
                    }
                } finally {
                    session.finishedCallback();
                }
            } catch (Throwable ex) {
                LOG.error("Unexpected exception thrown during the run of the scheduled callback", ex);
            }
        }
    } finally {
        if (callbackEntry != null) {
            nackReceivedMessage((SQSMessage) callbackEntry.getMessageManager().getMessage());
        }
        nackQueuedMessages();
    }
}

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

/**
 * Test that setting messageAge has an effect on topics
 *
 * Ensure we set the delete-persistent option
 *
 * Sets the messageAge to be 1/5 the disconnection wait timeout (or 1sec)
 * Send 10 messages and then ensure that we get disconnected as we will
 * wait for the full timeout./*  w ww. jav a  2s . c om*/
 *
 * @throws Exception
 */
public void testTopicDurableConsumerMessageAge() throws Exception {
    MAX_QUEUE_MESSAGE_COUNT = 10;

    setConfig("messageAge", String.valueOf(DISCONNECTION_WAIT / 5), true);

    //Start the broker
    startBroker();

    topicConsumer(Session.AUTO_ACKNOWLEDGE, true);
}

From source file:org.wso2.carbon.event.output.adapter.jms.JMSEventAdapter.java

@Override
public void testConnect() throws TestConnectionNotSupportedException {

    try {//www. j  av  a 2  s.  c  om
        Hashtable<String, String> adaptorProperties = new Hashtable<String, String>();
        adaptorProperties.putAll(eventAdapterConfiguration.getStaticProperties());
        JMSConnectionFactory jmsConnectionFactory = new JMSConnectionFactory(adaptorProperties,
                eventAdapterConfiguration.getName(),
                adaptorProperties.get(JMSEventAdapterConstants.ADAPTER_JMS_DESTINATION), 1);
        Connection connection = jmsConnectionFactory.createConnection();
        connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        connection.close();
        jmsConnectionFactory.close();
    } catch (Exception e) {
        throw new OutputEventAdapterRuntimeException(e);
    }
}

From source file:org.ct.amq.jdbc.security.JdbcAuthenticationPluginTest.java

public void testSecurityContextClearedOnPurge() throws Exception {

    connection.close();//ww w  .j  av  a2 s .  c om
    ActiveMQConnectionFactory tcpFactory = new ActiveMQConnectionFactory(
            broker.getTransportConnectors().get(0).getPublishableConnectString());
    ActiveMQConnection conn = (ActiveMQConnection) tcpFactory.createConnection("user", "password");
    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    conn.start();

    final int numDests = broker.getRegionBroker().getDestinations().length;
    for (int i = 0; i < 10; i++) {
        MessageProducer p = sess.createProducer(new ActiveMQQueue("USERS.PURGE." + i));
        p.close();
    }

    assertTrue("dests are purged", Wait.waitFor(new Wait.Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            LOG.info(
                    "dests, orig: " + numDests + ", now: " + broker.getRegionBroker().getDestinations().length);
            return (numDests + 1) == broker.getRegionBroker().getDestinations().length;
        }
    }));

    // verify removed from connection security context
    TransportConnection brokerConnection = broker.getTransportConnectors().get(0).getConnections().get(0);
    TransportConnectionState transportConnectionState = brokerConnection
            .lookupConnectionState(conn.getConnectionInfo().getConnectionId());
    assertEquals("no destinations", 0,
            transportConnectionState.getContext().getSecurityContext().getAuthorizedWriteDests().size());
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.jms.factory.JMSConnectionFactory.java

public JMSConnectionFactory(Properties properties) {
    try {//from w w w.  ja  v a  2s . c om
        ctx = new InitialContext(properties);
    } catch (NamingException e) {
        logger.error("NamingException while obtaining initial context. " + e.getMessage(), e);
    }

    String connectionFactoryType = properties.getProperty(JMSConstants.CONNECTION_FACTORY_TYPE);
    if ("topic".equals(connectionFactoryType)) {
        this.destinationType = JMSConstants.JMSDestinationType.TOPIC;
    } else {
        this.destinationType = JMSConstants.JMSDestinationType.QUEUE;
    }

    if (properties.getProperty(JMSConstants.PARAM_JMS_SPEC_VER) == null || JMSConstants.JMS_SPEC_VERSION_1_1
            .equals(properties.getProperty(JMSConstants.PARAM_JMS_SPEC_VER))) {
        jmsSpec = JMSConstants.JMS_SPEC_VERSION_1_1;
    } else if (JMSConstants.JMS_SPEC_VERSION_2_0
            .equals(properties.getProperty(JMSConstants.PARAM_JMS_SPEC_VER))) {
        jmsSpec = JMSConstants.JMS_SPEC_VERSION_2_0;
    } else {
        jmsSpec = JMSConstants.JMS_SPEC_VERSION_1_0;
    }

    if ("true".equalsIgnoreCase(properties.getProperty(JMSConstants.PARAM_IS_SHARED_SUBSCRIPTION))) {
        isSharedSubscription = true;
    } else {
        isSharedSubscription = false;
    }

    noPubSubLocal = Boolean.valueOf(properties.getProperty(JMSConstants.PARAM_PUBSUB_NO_LOCAL));

    clientId = properties.getProperty(JMSConstants.PARAM_DURABLE_SUB_CLIENT_ID);
    subscriptionName = properties.getProperty(JMSConstants.PARAM_DURABLE_SUB_NAME);

    if (isSharedSubscription) {
        if (subscriptionName == null) {
            logger.info("Subscription name is not given. Therefor declaring a non-shared subscription");
            isSharedSubscription = false;
        }
    }

    String subDurable = properties.getProperty(JMSConstants.PARAM_SUB_DURABLE);
    if (subDurable != null) {
        isDurable = Boolean.parseBoolean(subDurable);
    }
    String msgSelector = properties.getProperty(JMSConstants.PARAM_MSG_SELECTOR);
    if (msgSelector != null) {
        messageSelector = msgSelector;
    }
    this.connectionFactoryString = properties.getProperty(JMSConstants.CONNECTION_FACTORY_JNDI_NAME);
    if (connectionFactoryString == null || "".equals(connectionFactoryString)) {
        connectionFactoryString = "QueueConnectionFactory";
    }

    this.destinationName = properties.getProperty(JMSConstants.DESTINATION_NAME);
    if (destinationName == null || "".equals(destinationName)) {
        destinationName = "QUEUE_" + System.currentTimeMillis();
    }

    String strTransactedSession = properties.getProperty(JMSConstants.SESSION_TRANSACTED);
    if (strTransactedSession == null || "".equals(strTransactedSession)
            || !strTransactedSession.equals("true")) {
        transactedSession = false;
    } else if ("true".equals(strTransactedSession)) {
        transactedSession = true;
    }

    String strSessionAck = properties.getProperty(JMSConstants.SESSION_ACK);
    if (null == strSessionAck) {
        sessionAckMode = 1;
    } else if (strSessionAck.equals("AUTO_ACKNOWLEDGE")) {
        sessionAckMode = Session.AUTO_ACKNOWLEDGE;
    } else if (strSessionAck.equals("CLIENT_ACKNOWLEDGE")) {
        sessionAckMode = Session.CLIENT_ACKNOWLEDGE;
    } else if (strSessionAck.equals("DUPS_OK_ACKNOWLEDGE")) {
        sessionAckMode = Session.DUPS_OK_ACKNOWLEDGE;
    } else if (strSessionAck.equals("SESSION_TRANSACTED")) {
        sessionAckMode = Session.SESSION_TRANSACTED;
    } else {
        sessionAckMode = 1;
    }

    createConnectionFactory();
}

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

public void seedChunk(final InputStream inputStream, final String chunkId)
        throws IOException, GeneralSecurityException, JMSException {
    LOG.debug("Seeding chunk " + chunkId);
    Chunk chunk = chunkDAO.findByIdentifier(chunkId);

    if (chunk == null) {
        throw new FileNotFoundException(
                "Chunk id " + chunkId + " not found. File already registered at registry?");
    }/*from  w w  w . ja  v  a2s .  c  o  m*/

    byte[] buf = new byte[chunk.getFileMeta().getChunkSize()];
    int bufferSize;
    try (InputStream in = inputStream) {
        bufferSize = readBlock(in, buf);
    } catch (IOException ex) {
        throw ex;
    }

    // Check SHA-1
    String sha1 = Hex.encodeHexString(DigestUtils.sha1(Arrays.copyOf(buf, bufferSize)));
    if (!chunk.getHash().equalsIgnoreCase(sha1)) {
        throw new GeneralSecurityException(
                "Chunk SHA-1 validation failed (Expected " + chunk.getHash() + ", but is " + sha1 + ")");
    }

    repositoryBean.writeChunk(chunkId, buf, bufferSize);

    LOG.debug("Chunk id " + chunkId + " seed");

    // 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(chunkQueue);

    TextMessage message = session.createTextMessage(chunkId);
    messageProducer.send(message);
    connection.close();
}

From source file:fr.xebia.springframework.jms.support.converter.JaxbMessageConverterTest.java

@Before
public void before() throws Exception {
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
            "vm://localhost?broker.persistent=false&broker.useJmx=false");
    Connection connection = connectionFactory.createConnection();
    connection.start();//from  ww w  . j  a v  a2  s  .  com
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

}