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.carewebframework.jms.GlobalEventDispatcher.java

/**
 * Connect to the JMS server.//from   w w  w  .ja  va2s  .  c o m
 * 
 * @return True if successful.
 */
private boolean connect() {
    if (this.factory == null) {
        return false;
    }

    if (isConnected()) {
        return true;
    }

    try {
        this.connection = this.factory.createConnection();
        this.session = (TopicSession) this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        this.connection.start();
        updateConnectionStatus(true);
        assertSubscriptions();
        return true;
    } catch (final Exception e) {
        log.error("Error communicating with JMS server: " + e.getMessage());
        disconnect(false);
        return false;
    }
}

From source file:eu.learnpad.simulator.mon.manager.ResponseDispatcher.java

public static void sendResponse(Object object, String enablerName, String answerTopic) {
    try {/*w w  w. j a v  a2s.c o  m*/
        publicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        connectionTopic = publishSession.createTopic(answerTopic);
        tPub = publishSession.createPublisher(connectionTopic);

        ObjectMessage sendMessage = publishSession.createObjectMessage();
        sendMessage.setObject((Serializable) object);
        sendMessage.setStringProperty("DESTINATION", enablerName);
        tPub.publish(sendMessage);
    } catch (JMSException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.activemq.JmsConnectionStartStopTest.java

public void testConcurrentSessionCreateWithStart() throws Exception {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(50, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>());
    final Vector<Throwable> exceptions = new Vector<Throwable>();
    final Random rand = new Random();
    Runnable createSessionTask = new Runnable() {
        @Override//  ww w  . j a  v  a  2s.com
        public void run() {
            try {
                TimeUnit.MILLISECONDS.sleep(rand.nextInt(10));
                stoppedConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            } catch (Exception e) {
                exceptions.add(e);
            }
        }
    };

    Runnable startStopTask = new Runnable() {
        @Override
        public void run() {
            try {
                TimeUnit.MILLISECONDS.sleep(rand.nextInt(10));
                stoppedConnection.start();
                stoppedConnection.stop();
            } catch (Exception e) {
                exceptions.add(e);
            }
        }
    };

    for (int i = 0; i < 1000; i++) {
        executor.execute(createSessionTask);
        executor.execute(startStopTask);
    }

    executor.shutdown();
    assertTrue("executor terminated", executor.awaitTermination(30, TimeUnit.SECONDS));
    assertTrue("no exceptions: " + exceptions, exceptions.isEmpty());
}

From source file:org.wso2.carbon.event.core.internal.delivery.jms.JMSDeliveryManager.java

public void subscribe(Subscription subscription) throws EventBrokerException {

    if (isDeactivated()) {
        return;// www.  j a v a 2  s  .c  o  m
    }

    // in a multi tenant envirionment deployment synchronizer may creates subscriptions before
    // the event observer get activated.
    if (this.subscriptionIDSessionDetailsMap.containsKey(subscription.getId())) {
        log.warn(
                "There is an subscription already exists for the subscription with id " + subscription.getId());
        return;
    }
    JMSMessageListener jmsMessageListener = new JMSMessageListener(this.notificationManager, subscription);
    try {
        TopicConnection topicConnection = getTopicConnection(subscription.getOwner());
        TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

        String topicName = "";
        if (subscription.getTenantDomain() != null && (!subscription.getTenantDomain()
                .equals(org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME))) {

            if (!subscription.getTopicName().startsWith("/")) {
                topicName = getTopicName(subscription.getTenantDomain() + "/" + subscription.getTopicName());
            } else {
                topicName = getTopicName(subscription.getTenantDomain() + subscription.getTopicName());
            }
        } else {
            topicName = getTopicName(subscription.getTopicName());
        }
        Topic topic = topicSession.createTopic(topicName);
        //Some times we are not getting the proper topic with the required syntax, if it is not
        //appropriate we need to check and add the BURL syntax to fix the issue https://wso2.org/jira/browse/MB-185
        if (!topic.toString().startsWith("topic://amq.topic")) {
            topic = topicSession.createTopic("BURL:" + topicName);
        }
        TopicSubscriber topicSubscriber = topicSession.createDurableSubscriber(topic, subscription.getId());
        topicSubscriber.setMessageListener(jmsMessageListener);

        this.subscriptionIDSessionDetailsMap.put(subscription.getId(),
                new JMSSubscriptionDetails(topicSubscriber, topicSession, topicConnection));
    } catch (JMSException e) {
        throw new EventBrokerException(
                "Can not subscribe to topic " + subscription.getTopicName() + " " + e.getMessage(), e);
    }
}

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

private Boolean submitToBackend(final String messageId) {
    Connection connection;// w  w  w . j a v a 2  s.com
    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:org.fusesource.mq.itests.MQDistroTest.java

@Test
public void testWebConsoleAndClient() throws Exception {
    // send message via webconsole, consume from jms openwire
    HttpClient client = new HttpClient();

    // set credentials
    client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD));

    // need to first get the secret
    GetMethod get = new GetMethod(WEB_CONSOLE_URL + "send.jsp");
    get.setDoAuthentication(true);// ww  w .ja v a  2 s .c o m

    // Give console some time to start
    for (int i = 0; i < 20; i++) {
        Thread.currentThread().sleep(1000);
        try {
            i = client.executeMethod(get);
        } catch (java.net.ConnectException ignored) {
        }
    }
    assertEquals("get succeeded on " + get, 200, get.getStatusCode());

    String response = get.getResponseBodyAsString();
    final String secretMarker = "<input type=\"hidden\" name=\"secret\" value=\"";
    String secret = response.substring(response.indexOf(secretMarker) + secretMarker.length());
    secret = secret.substring(0, secret.indexOf("\"/>"));

    final String destination = "validate.console.send";
    final String content = "Hi for the " + Math.random() + "' time";

    PostMethod post = new PostMethod(WEB_CONSOLE_URL + "sendMessage.action");
    post.setDoAuthentication(true);
    post.addParameter("secret", secret);

    post.addParameter("JMSText", content);
    post.addParameter("JMSDestination", destination);
    post.addParameter("JMSDestinationType", "queue");

    // execute the send
    assertEquals("post succeeded, " + post, 302, client.executeMethod(post));

    // consume what we sent
    ActiveMQConnection connection = (ActiveMQConnection) new ActiveMQConnectionFactory()
            .createConnection(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD);
    connection.start();
    try {
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        TextMessage textMessage = (TextMessage) session.createConsumer(new ActiveMQQueue(destination))
                .receive(10 * 1000);
        assertNotNull("got a message", textMessage);
        assertEquals("it is ours", content, textMessage.getText());
    } finally {
        connection.close();
    }

    // verify osgi registration of cf
    ConnectionFactory connectionFactory = getOsgiService(ConnectionFactory.class);
    assertTrue(connectionFactory instanceof ActiveMQConnectionFactory);
    ActiveMQConnection connectionFromOsgiFactory = (ActiveMQConnection) connectionFactory
            .createConnection(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD);
    connectionFromOsgiFactory.start();
    try {
        assertEquals("same broker", connection.getBrokerName(), connectionFromOsgiFactory.getBrokerName());
    } finally {
        connectionFromOsgiFactory.close();
    }

    // verify mq-client
    Process process = Runtime.getRuntime()
            .exec("java -jar extras" + File.separator + "mq-client.jar producer --count 1 --user "
                    + USER_NAME_ND_PASSWORD + " --password " + USER_NAME_ND_PASSWORD, null, // env
                    new File(System.getProperty("user.dir")));
    process.waitFor();
    assertEquals("producer worked, exit(0)?", 0, process.exitValue());

    process = Runtime.getRuntime()
            .exec("java -jar extras" + File.separator + "mq-client.jar consumer --count 1 --user "
                    + USER_NAME_ND_PASSWORD + " --password " + USER_NAME_ND_PASSWORD, null, // env
                    new File(System.getProperty("user.dir")));
    process.waitFor();
    assertEquals("consumer worked, exit(0)?", 0, process.exitValue());

    System.out.println(executeCommand("activemq:bstat"));
}

From source file:eu.learnpad.simulator.mon.probe.GlimpseAbstractProbe.java

/**
 * This method setup a {@link TopicConnection} object.
 * //from   w  ww  . j  av  a  2s .  c  om
 * @param initConn the InitialContext object generated using the method {@link #initConnection(Properties, boolean)}.
 * @param settings can be generated automatically using {@link Manager#createProbeSettingsPropertiesObject(String, String, String, String, String, String, boolean, String, String)}
 * @param probeChannel
 * @param settings
 * @param debug
 * @return a {@link TopicPublisher} object
 * @throws NamingException
 * @throws JMSException
 */
protected TopicPublisher createConnection(InitialContext initConn, String probeChannel, Properties settings,
        boolean debug) throws NamingException, JMSException {
    if (debug)
        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating ConnectionFactory with settings ");
    TopicConnectionFactory connFact = (TopicConnectionFactory) initConn
            .lookup(settings.getProperty("connectionFactoryNames"));
    if (debug) {
        DebugMessages.ok();
        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating TopicConnection ");
    }
    connection = connFact.createTopicConnection();
    if (debug) {
        DebugMessages.ok();
        DebugMessages.line();
    }
    if (debug) {
        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), "Creating Session ");
    }
    publishSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    if (debug) {
        DebugMessages.ok();
        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Looking up for channel ");
    }
    connectionTopic = (Topic) initContext.lookup(probeChannel);
    if (debug) {
        DebugMessages.ok();
        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), "Creating Publisher ");
    }
    return tPub = publishSession.createPublisher(connectionTopic);
}

From source file:com.cws.esolutions.core.utils.MQUtils.java

/**
 * Puts an MQ message on a specified queue and returns the associated
 * correlation ID for retrieval upon request.
 *
 * @param connName - The connection name to utilize
 * @param authData - The authentication data to utilize, if required
 * @param requestQueue - The request queue name to put the message on
 * @param targetHost - The target host for the message
 * @param value - The data to place on the request. MUST be <code>Serialiable</code>
 * @return <code>String</code> - the JMS correlation ID associated with the message
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 *//*from   www.j  av a  2 s. c  om*/
public static final synchronized String sendMqMessage(final String connName, final List<String> authData,
        final String requestQueue, final String targetHost, final Serializable value) throws UtilityException {
    final String methodName = MQUtils.CNAME
            + "sendMqMessage(final String connName, final List<String> authData, final String requestQueue, final String targetHost, final Serializable value) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", connName);
        DEBUGGER.debug("Value: {}", requestQueue);
        DEBUGGER.debug("Value: {}", targetHost);
        DEBUGGER.debug("Value: {}", value);
    }

    Connection conn = null;
    Session session = null;
    Context envContext = null;
    InitialContext initCtx = null;
    MessageProducer producer = null;
    ConnectionFactory connFactory = null;

    final String correlationId = RandomStringUtils.randomAlphanumeric(64);

    if (DEBUG) {
        DEBUGGER.debug("correlationId: {}", correlationId);
    }

    try {
        try {
            initCtx = new InitialContext();
            envContext = (Context) initCtx.lookup(MQUtils.INIT_CONTEXT);

            connFactory = (ConnectionFactory) envContext.lookup(connName);
        } catch (NamingException nx) {
            // we're probably not in a container
            connFactory = new ActiveMQConnectionFactory(connName);
        }

        if (DEBUG) {
            DEBUGGER.debug("ConnectionFactory: {}", connFactory);
        }

        if (connFactory == null) {
            throw new UtilityException("Unable to create connection factory for provided name");
        }

        // Create a Connection
        conn = connFactory.createConnection(authData.get(0),
                PasswordUtils.decryptText(authData.get(1), authData.get(2), authData.get(3),
                        Integer.parseInt(authData.get(4)), Integer.parseInt(authData.get(5)), authData.get(6),
                        authData.get(7), authData.get(8)));
        conn.start();

        if (DEBUG) {
            DEBUGGER.debug("Connection: {}", conn);
        }

        // Create a Session
        session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

        if (DEBUG) {
            DEBUGGER.debug("Session: {}", session);
        }

        // Create a MessageProducer from the Session to the Topic or Queue
        if (envContext != null) {
            try {
                producer = session.createProducer((Destination) envContext.lookup(requestQueue));
            } catch (NamingException nx) {
                throw new UtilityException(nx.getMessage(), nx);
            }
        } else {
            Destination destination = session.createTopic(requestQueue);

            if (DEBUG) {
                DEBUGGER.debug("Destination: {}", destination);
            }

            producer = session.createProducer(destination);
        }

        if (producer == null) {
            throw new JMSException("Failed to create a producer object");
        }

        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        if (DEBUG) {
            DEBUGGER.debug("MessageProducer: {}", producer);
        }

        ObjectMessage message = session.createObjectMessage(true);
        message.setJMSCorrelationID(correlationId);
        message.setStringProperty("targetHost", targetHost);

        if (DEBUG) {
            DEBUGGER.debug("correlationId: {}", correlationId);
        }

        message.setObject(value);

        if (DEBUG) {
            DEBUGGER.debug("ObjectMessage: {}", message);
        }

        producer.send(message);
    } catch (JMSException jx) {
        throw new UtilityException(jx.getMessage(), jx);
    } finally {
        try {
            // Clean up
            if (!(session == null)) {
                session.close();
            }

            if (!(conn == null)) {
                conn.close();
                conn.stop();
            }
        } catch (JMSException jx) {
            ERROR_RECORDER.error(jx.getMessage(), jx);
        }
    }

    return correlationId;
}

From source file:org.fusesource.fabric.itests.paxexam.mq.MQDistroTest.java

@Test
public void testMQ() throws Exception {

    // send message via webconsole, consume from jms openwire
    HttpClient client = new HttpClient();

    // set credentials
    client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD));

    // need to first get the secret
    GetMethod get = new GetMethod(WEB_CONSOLE_URL + "send.jsp");
    get.setDoAuthentication(true);// w w  w.  j av a2  s.  com

    // Give console some time to start
    for (int i = 0; i < 20; i++) {
        Thread.currentThread().sleep(1000);
        try {
            i = client.executeMethod(get);
        } catch (java.net.ConnectException ignored) {
        }
    }
    assertEquals("get succeeded on " + get, 200, get.getStatusCode());

    String response = get.getResponseBodyAsString();
    final String secretMarker = "<input type=\"hidden\" name=\"secret\" value=\"";
    String secret = response.substring(response.indexOf(secretMarker) + secretMarker.length());
    secret = secret.substring(0, secret.indexOf("\"/>"));

    final String destination = "validate.console.send";
    final String content = "Hi for the " + Math.random() + "' time";

    PostMethod post = new PostMethod(WEB_CONSOLE_URL + "sendMessage.action");
    post.setDoAuthentication(true);
    post.addParameter("secret", secret);

    post.addParameter("JMSText", content);
    post.addParameter("JMSDestination", destination);
    post.addParameter("JMSDestinationType", "queue");

    // execute the send
    assertEquals("post succeeded, " + post, 302, client.executeMethod(post));

    // consume what we sent
    ActiveMQConnection connection = (ActiveMQConnection) new ActiveMQConnectionFactory()
            .createConnection(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD);
    connection.start();
    try {
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        TextMessage textMessage = (TextMessage) session.createConsumer(new ActiveMQQueue(destination))
                .receive(10 * 1000);
        assertNotNull("got a message", textMessage);
        assertEquals("it is ours", content, textMessage.getText());
    } finally {
        connection.close();
    }

    // verify osgi registration of cf
    ConnectionFactory connectionFactory = getOsgiService(ConnectionFactory.class);
    assertTrue(connectionFactory instanceof ActiveMQConnectionFactory);
    ActiveMQConnection connectionFromOsgiFactory = (ActiveMQConnection) connectionFactory
            .createConnection(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD);
    connectionFromOsgiFactory.start();
    try {
        assertEquals("same broker", connection.getBrokerName(), connectionFromOsgiFactory.getBrokerName());
    } finally {
        connectionFromOsgiFactory.close();
    }

    // verify mq-client
    Process process = Runtime.getRuntime()
            .exec("java -jar extras" + File.separator + "mq-client.jar producer --count 1 --user "
                    + USER_NAME_ND_PASSWORD + " --password " + USER_NAME_ND_PASSWORD, null, // env
                    new File(System.getProperty("user.dir")));
    process.waitFor();
    assertEquals("producer worked, exit(0)?", 0, process.exitValue());

    process = Runtime.getRuntime()
            .exec("java -jar extras" + File.separator + "mq-client.jar consumer --count 1 --user "
                    + USER_NAME_ND_PASSWORD + " --password " + USER_NAME_ND_PASSWORD, null, // env
                    new File(System.getProperty("user.dir")));
    process.waitFor();
    assertEquals("consumer worked, exit(0)?", 0, process.exitValue());

}

From source file:gov.nih.nci.cabig.caaers.esb.client.impl.CtmsCaaersMessageConsumer.java

/**
 * This Method is invoked by spring to initialize the connections to the queues. 
 * @throws Exception//from  w  w  w  .ja v a2  s  .  c o  m
 */
public void initialize() throws Exception {
    String esbURL = configuration.get(Configuration.ESB_URL);
    if ("".equals(esbURL) || esbURL == null) {
        logger.error("Could not start CtmsCaaersMessageConsumer, ESB URL not specified");
        return;
    }
    try {
        mqConnectionFactory.setBrokerURL(esbURL);
        connectionFactory = mqConnectionFactory;
        connection = connectionFactory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        consumer = session.createConsumer(ctmsCaaersRecvQueue);
        consumer.setMessageListener(this);
        producer = session.createProducer(ctmsCaaersResponseQueue);
        logger.debug("starting connection....");
        connection.start();
    } catch (Exception e) {
        //logger.error("Error Initializing CtmsCaaersMessageConsumer" , e);
        logger.info("CtmsCaaersMessageConsumer not available");
    }
}