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:io.fabric8.mq.controller.coordination.BrokerJMXPropertiesTest.java

@Test
public void testNumberOfTopicProducers() throws Exception {
    String uriString = brokerService.getDefaultSocketURIString();
    ConnectionFactory factory = new ActiveMQConnectionFactory(uriString);
    Connection connection = factory.createConnection();
    connection.start();/*from w  ww .j av  a  2  s.c om*/
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    int numberOfProducers = 10;
    List<MessageProducer> producers = new ArrayList<>();
    Topic topic = session.createTopic("topic.test");
    for (int i = 0; i < numberOfProducers; i++) {

        MessageProducer producer = session.createProducer(topic);
        producers.add(producer);

    }
    ObjectName root = BrokerJmxUtils.getRoot(client);
    Assert.assertNotNull(root);
    List<ObjectName> list = BrokerJmxUtils.getDestinations(client, root, "Topic");
    Assert.assertNotNull(list);
    Assert.assertFalse(list.isEmpty());
    ObjectName result = null;
    for (ObjectName objectName : list) {
        if (objectName.getKeyProperty("destinationName").equals("topic.test")) {
            result = objectName;
        }
    }
    Assert.assertNotNull(result);
    Object producerCount = BrokerJmxUtils.getAttribute(client, result, "ProducerCount");
    Assert.assertNotNull(producerCount);
    int pc = Integer.parseInt(producerCount.toString());
    Assert.assertEquals(pc, numberOfProducers);
    connection.close();
}

From source file:com.mdmserver.managers.ControllerFacade.java

public void lockPhone(int accountId) throws IOException {
    Account account = databaseManager.getAccountByAccountId(accountId);
    Context ctx;/*from   w w  w .j ava2s. c  om*/
    try {
        ctx = new InitialContext();
        ConnectionFactory connectionFactory = (ConnectionFactory) ctx.lookup("jms/mdmConnectionFactory");
        Queue queue = (Queue) ctx.lookup("jms/mdmQueue");
        MessageProducer messageProducer;
        System.out.println("Naming success");
        try {

            javax.jms.Connection connection = connectionFactory.createConnection();
            javax.jms.Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            messageProducer = session.createProducer(queue);
            TextMessage message = session.createTextMessage();
            message.setStringProperty(Account.FIELD_NAME_CLOUD_ID, account.getCloudId());
            ControlClient cClient = new ControlClient();
            cClient.setCommandType(ControlClient.LOCK_PHONE_CONTROL);
            Gson gson = new Gson();
            message.setStringProperty(ControlClient.CONTROL_CLIENT_KEY, gson.toJson(cClient));
            System.out.println("It come from Servlet:" + message.getText());
            messageProducer.send(message);
            System.out.println("JMS success");
        } catch (JMSException ex) {
            //                  Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("JMS exception");
        }

    } catch (NamingException ex) {
        //                Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Naming exception");
    }
}

From source file:org.dawnsci.commandserver.core.producer.Broadcaster.java

private void createConnection() throws Exception {

    QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    this.connection = connectionFactory.createQueueConnection();
    this.qSes = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    this.queue = qSes.createQueue(queueName);

    this.session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    final Topic topic = session.createTopic(topicName);
    this.topicProducer = session.createProducer(topic);

    connection.start();/*from  w  ww  . j  a va  2 s.c  o  m*/

}

From source file:it.cnr.isti.labse.glimpse.manager.GlimpseManager.java

public void setupConnection(TopicConnectionFactory connectionFact, InitialContext initConn) {
    try {//from   w  w w . ja va  2  s  .c  o  m
        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating connection object ");
        connection = connectionFact.createTopicConnection();
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating public session object ");
        publishSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating subscribe object");
        subscribeSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Setting up destination topic ");
        connectionTopic = (Topic) initConn.lookup(serviceTopic);
        tPub = publishSession.createPublisher(connectionTopic);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Setting up reading topic ");
        tSub = subscribeSession.createSubscriber(connectionTopic, "DESTINATION = 'monitor'", true);
        tSub.setMessageListener(this);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating response dispatcher ");
        responder = new ResponseDispatcher(initConn, connectionFact, requestMap);
        DebugMessages.ok();

    } catch (JMSException e) {
        e.printStackTrace();
    } catch (NamingException e) {
        e.printStackTrace();
    }
}

From source file:net.blogracy.services.LookupService.java

public LookupService(Connection connection, PluginInterface plugin) {
    this.plugin = plugin;
    try {/*w w  w . j a  v  a  2 s  .  co  m*/
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producer = session.createProducer(null);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        queue = session.createQueue("lookup");
        consumer = session.createConsumer(queue);
        consumer.setMessageListener(this);
    } catch (JMSException e) {
        Logger.error("JMS error: creating lookup service");
    }
}

From source file:it.cnr.isti.labse.glimpse.impl.ComplexEventProcessorImpl.java

public void init(TopicConnectionFactory connectionFact, InitialContext initConn) {
    try {/*from   w ww. ja va  2  s  . c om*/
        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating connection object ");
        connection = connectionFact.createTopicConnection();
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating public session object ");
        publishSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating subscribe object ");
        subscribeSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Setting up reading topic ");
        connectionTopic = (Topic) initConn.lookup(topic);
        tSub = subscribeSession.createSubscriber(connectionTopic, null, true);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Setting up destination topic ");
        connectionTopic = publishSession.createTopic(this.topic);
        tPub = publishSession.createPublisher(connectionTopic);
        DebugMessages.ok();

        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Reading knowledge base ");
        kbase = readKnowledgeBase();
        ksession = kbase.newStatefulKnowledgeSession();
        ksession.setGlobal("EVENTS EntryPoint", eventStream);
        eventStream = ksession.getWorkingMemoryEntryPoint("DEFAULT");
        cepRuleManager = new DroolsRulesManager(kbuilder, kbase, ksession);
        DebugMessages.ok();

    } catch (JMSException e) {
        e.printStackTrace();
    } catch (NamingException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.servicemix.jms.JmsMarshalerTest.java

public void testMarshalTextMessage() throws Exception {
    JmsComponent jms = new JmsComponent();
    jms.getConfiguration().setConnectionFactory(connectionFactory);
    JmsEndpoint ep = new JmsEndpoint();
    ep.setService(ReceiverComponent.SERVICE);
    ep.setEndpoint("jms");
    ep.setTargetService(ReceiverComponent.SERVICE);
    ep.setTargetEndpoint(ReceiverComponent.ENDPOINT);
    ep.setRole(MessageExchange.Role.CONSUMER);
    ep.setDestinationStyle(AbstractJmsProcessor.STYLE_QUEUE);
    ep.setDestination(queue);/*from   www. jav  a 2  s.com*/
    ep.setDefaultMep(JbiConstants.IN_ONLY);
    ep.setMarshaler(new DefaultJmsMarshaler(ep));
    jms.setEndpoints(new JmsEndpoint[] { ep });
    container.activateComponent(jms, "servicemix-jms");

    ReceiverComponent receiver = new ReceiverComponent();
    container.activateComponent(receiver, "receiver");

    QueueConnection qConn = connectionFactory.createQueueConnection();
    QueueSession qSess = qConn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    QueueSender qSender = qSess.createSender(queue);
    TextMessage message = qSess
            .createTextMessage("<?xml version=\"1.0\" encoding=\"UTF-8\"?><hello>world</hello>");
    qSender.send(message);

    receiver.getMessageList().assertMessagesReceived(1);
    List msgs = receiver.getMessageList().flushMessages();
    NormalizedMessage msg = (NormalizedMessage) msgs.get(0);
    assertEquals("Messages match", message.getText(), new SourceTransformer().contentToString(msg));

    // Wait for DONE status
    Thread.sleep(50);
}

From source file:org.calrissian.mango.jms.stream.JmsFileTransferSupportTest.java

public void testFullCycle() throws Exception {
    try {// w  w w. j av a2  s  .  c o  m
        URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {

            @Override
            public URLStreamHandler createURLStreamHandler(String protocol) {
                if ("testprot".equals(protocol))
                    return new URLStreamHandler() {

                        @Override
                        protected URLConnection openConnection(URL u) throws IOException {
                            return new URLConnection(u) {

                                @Override
                                public void connect() throws IOException {

                                }

                                @Override
                                public InputStream getInputStream() throws IOException {
                                    return new ByteArrayInputStream(TEST_STR.getBytes());
                                }

                                @Override
                                public String getContentType() {
                                    return "content/notnull";
                                }
                            };
                        }
                    };
                return null;
            }
        });
    } catch (Error ignored) {
    }

    final ActiveMQTopic ft = new ActiveMQTopic("testFileTransfer");

    ThreadPoolTaskExecutor te = new ThreadPoolTaskExecutor();
    te.initialize();

    JmsFileSenderListener listener = new JmsFileSenderListener();
    final String hashAlgorithm = "MD5";
    listener.setHashAlgorithm(hashAlgorithm);
    listener.setStreamRequestDestination(ft);
    listener.setPieceSize(9);
    listener.setTaskExecutor(te);

    ConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
    cf = new SingleTopicConnectionFactory(cf, "test");
    JmsTemplate jmsTemplate = new JmsTemplate();
    jmsTemplate.setConnectionFactory(cf);
    jmsTemplate.setReceiveTimeout(60000);
    listener.setJmsTemplate(jmsTemplate);

    Connection conn = cf.createConnection();
    conn.start();
    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = sess.createConsumer(ft);
    consumer.setMessageListener(listener);

    JmsFileReceiver receiver = new JmsFileReceiver();
    receiver.setHashAlgorithm(hashAlgorithm);
    receiver.setStreamRequestDestination(ft);
    receiver.setJmsTemplate(jmsTemplate);
    receiver.setPieceSize(9);

    JmsFileReceiverInputStream stream = (JmsFileReceiverInputStream) receiver.receiveStream("testprot:test");
    StringBuilder buffer = new StringBuilder();
    int read;
    while ((read = stream.read()) >= 0) {
        buffer.append((char) read);
    }
    stream.close();

    assertEquals(TEST_STR, buffer.toString());

    conn.stop();

}

From source file:com.fusesource.forge.jmstest.benchmark.command.transport.JMSCommandTransport.java

public void sendCommand(BenchmarkCommand command) {
    log.debug("Sending command message: " + command.toString());
    if (getConnection() != null) {
        try {/*from ww w  .  j  a va2 s.c  o m*/
            Session session = getConnection().createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination dest = getJmsDestinationProvider().getDestination(session, getDestinationName());
            MessageProducer producer = session.createProducer(dest);
            producer.send(session.createObjectMessage((Serializable) command));
            session.close();
        } catch (Exception je) {
            log().error("Could not send Command " + command.toString() + ".", je);
        }
    } else {
        log.warn("Command not sent as JMS connection is not established.");
    }
}

From source file:org.wso2.carbon.esb.scenario.test.common.jms.ActiveMQJMSClient.java

/**
 * Function to produce message to ActiveMQ Queue
 *
 * @param queueName name of the target queue
 * @param messageStr message to place//from w ww  .ja v  a  2s .c o  m
 * @throws JMSException
 */
public void produceMessageToQueue(String queueName, String messageStr) throws JMSException {

    Connection connection = null;
    Session session = null;

    try {
        // Create a ConnectionFactory
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);

        // Create a Connection
        connection = connectionFactory.createConnection();
        connection.start();
        connection.setExceptionListener(this);

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

        // Create the destination (Topic or Queue)
        Destination destination = session.createQueue(queueName);

        // Create a MessageProducer from the Session to the Topic or Queue
        MessageProducer producer = session.createProducer(destination);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        // Create a messages
        TextMessage message = session.createTextMessage(messageStr);

        // Tell the producer to send the message
        producer.send(message);

    } finally {
        // Clean up
        if (session != null) {
            session.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}