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.datalayer.activemq.consumer.SimpleQueueReceiver.java

/**
 * Main method.//from  www  .j  a  v  a  2  s  .c om
 * 
 * @param args the queue used by the example
 */
public static void main(String... args) {
    String queueName = null;
    Context jndiContext = null;
    QueueConnectionFactory queueConnectionFactory = null;
    QueueConnection queueConnection = null;
    QueueSession queueSession = null;
    Queue queue = null;
    QueueReceiver queueReceiver = null;
    TextMessage message = null;

    /*
     * Read queue name from command line and display it.
     */
    if (args.length != 1) {
        LOG.info("Usage: java " + "SimpleQueueReceiver <queue-name>");
        System.exit(1);
    }
    queueName = args[0];
    LOG.info("Queue name is " + queueName);

    /*
     * Create a JNDI API InitialContext object if none exists yet.
     */
    try {
        jndiContext = new InitialContext();
    } catch (NamingException e) {
        LOG.info("Could not create JNDI API " + "context: " + e.toString());
        System.exit(1);
    }

    /*
     * Look up connection factory and queue. If either does not exist, exit.
     */
    try {
        queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("QueueConnectionFactory");
        queue = (Queue) jndiContext.lookup(queueName);
    } catch (NamingException e) {
        LOG.info("JNDI API lookup failed: " + e.toString());
        System.exit(1);
    }

    /*
     * Create connection. Create session from connection; false means
     * session is not transacted. Create receiver, then start message
     * delivery. Receive all text messages from queue until a non-text
     * message is received indicating end of message stream. Close
     * connection.
     */
    try {
        queueConnection = queueConnectionFactory.createQueueConnection();
        queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queueReceiver = queueSession.createReceiver(queue);
        queueConnection.start();
        while (true) {
            Message m = queueReceiver.receive(1);
            if (m != null) {
                if (m instanceof TextMessage) {
                    message = (TextMessage) m;
                    LOG.info("Reading message: " + message.getText());
                } else {
                    break;
                }
            }
        }
    } catch (JMSException e) {
        LOG.info("Exception occurred: " + e.toString());
    } finally {
        if (queueConnection != null) {
            try {
                queueConnection.close();
            } catch (JMSException e) {
            }
        }
    }
}

From source file:qpid.MulticastMain.java

public static void main(String[] args) {
    Options options = getOptions();/*from w  ww  .j  a va2  s  . co m*/
    CommandLineParser parser = new GnuParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('?')) {
            usage(options);
            System.exit(0);
        }

        String exchangeType = strArg(cmd, 't', "direct");
        String exchangeName = strArg(cmd, 'e', exchangeType);
        String queueName = strArg(cmd, 'u', "");
        int samplingInterval = intArg(cmd, 'i', 1);
        int rateLimit = intArg(cmd, 'r', 0);
        int producerCount = intArg(cmd, 'x', 1);
        int consumerCount = intArg(cmd, 'y', 1);
        int producerTxSize = intArg(cmd, 'm', 0);
        int consumerTxSize = intArg(cmd, 'n', 0);
        long confirm = intArg(cmd, 'c', -1);
        boolean autoAck = cmd.hasOption('a');
        int multiAckEvery = intArg(cmd, 'A', 0);
        int prefetchCount = intArg(cmd, 'q', 0);
        int minMsgSize = intArg(cmd, 's', 0);
        int timeLimit = intArg(cmd, 'z', 0);
        List<?> flags = lstArg(cmd, 'f');
        int frameMax = intArg(cmd, 'M', 0);
        int heartbeat = intArg(cmd, 'b', 0);
        String uri = strArg(cmd, 'h', "amqp://guest:guest@/?brokerlist='localhost'");

        boolean exclusive = "".equals(queueName);
        boolean autoDelete = !exclusive;

        //setup
        String id = UUID.randomUUID().toString();
        Stats stats = new Stats(1000L * samplingInterval, producerCount > 0, consumerCount > 0,
                (flags.contains("mandatory") || flags.contains("immediate")), confirm != -1);

        System.setProperty("qpid.amqp.version", "0-91");

        Thread[] consumerThreads = new Thread[consumerCount];
        AMQConnection[] consumerConnections = new AMQConnection[consumerCount];
        for (int i = 0; i < consumerCount; i++) {
            System.out.println("starting consumer #" + i);
            AMQConnection conn = new AMQConnection(uri);
            consumerConnections[i] = conn;
            AMQSession channel = (AMQSession) conn.createSession(consumerTxSize > 0,
                    autoAck ? Session.AUTO_ACKNOWLEDGE : Session.CLIENT_ACKNOWLEDGE,
                    prefetchCount > 0 ? prefetchCount : 500);
            AMQDestination destination = new AMQAnyDestination(new AMQShortString(exchangeName),
                    new AMQShortString(exchangeType), new AMQShortString(id), exclusive, autoDelete,
                    queueName.equals("") ? null : new AMQShortString(queueName), flags.contains("persistent"),
                    null);
            channel.declareAndBind(destination);
            Thread t = new Thread(new Consumer(channel, id, destination, consumerTxSize, autoAck, multiAckEvery,
                    stats, timeLimit));
            conn.start();
            consumerThreads[i] = t;
        }
        Thread[] producerThreads = new Thread[producerCount];
        AMQConnection[] producerConnections = new AMQConnection[producerCount];
        AMQSession[] producerChannels = new AMQSession[producerCount];
        for (int i = 0; i < producerCount; i++) {
            System.out.println("starting producer #" + i);
            AMQConnection conn = new AMQConnection(uri);
            producerConnections[i] = conn;
            AMQSession channel = (AMQSession) conn.createSession(producerTxSize > 0, Session.AUTO_ACKNOWLEDGE,
                    500);
            producerChannels[i] = channel;
            if (confirm >= 0) {
                throw new UnsupportedOperationException("Publisher confirms not supported by Qpid");
            }
            AMQDestination destination = new AMQAnyDestination(new AMQShortString(exchangeName),
                    new AMQShortString(exchangeType), new AMQShortString(id), false, false, null,
                    flags.contains("persistent"), null);
            channel.declareExchange(destination.getExchangeName(), destination.getExchangeClass(), false);
            final Producer p = new Producer(channel, destination, id, flags, producerTxSize, rateLimit,
                    minMsgSize, timeLimit, confirm, stats);
            /*
            channel.addReturnListener(p);
            channel.addConfirmListener(p);
            */
            Thread t = new Thread(p);
            conn.start();
            producerThreads[i] = t;
        }

        for (int i = 0; i < consumerCount; i++) {
            consumerThreads[i].start();
        }

        for (int i = 0; i < producerCount; i++) {
            producerThreads[i].start();
        }

        for (int i = 0; i < producerCount; i++) {
            producerThreads[i].join();
            /*
            producerChannels[i].clearReturnListeners();
            producerChannels[i].clearConfirmListeners();
            */
            producerConnections[i].close();
        }

        for (int i = 0; i < consumerCount; i++) {
            consumerThreads[i].join();
            consumerConnections[i].close();
        }

    } catch (ParseException exp) {
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        usage(options);
    } catch (Exception e) {
        System.err.println("Main thread caught exception: " + e);
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:io.datalayer.activemq.producer.SimpleQueueSender.java

/**
 * Main method.//from  ww w.j  a  v a2  s . c om
 * 
 * @param args the queue used by the example and, optionally, the number of
 *                messages to send
 */
public static void main(String... args) {
    String queueName = null;
    Context jndiContext = null;
    QueueConnectionFactory queueConnectionFactory = null;
    QueueConnection queueConnection = null;
    QueueSession queueSession = null;
    Queue queue = null;
    QueueSender queueSender = null;
    TextMessage message = null;
    final int numMsgs;

    if ((args.length < 1) || (args.length > 2)) {
        LOG.info("Usage: java SimpleQueueSender " + "<queue-name> [<number-of-messages>]");
        System.exit(1);
    }
    queueName = args[0];
    LOG.info("Queue name is " + queueName);
    if (args.length == 2) {
        numMsgs = (new Integer(args[1])).intValue();
    } else {
        numMsgs = 1;
    }

    /*
     * Create a JNDI API InitialContext object if none exists yet.
     */
    try {
        jndiContext = new InitialContext();
    } catch (NamingException e) {
        LOG.info("Could not create JNDI API context: " + e.toString());
        System.exit(1);
    }

    /*
     * Look up connection factory and queue. If either does not exist, exit.
     */
    try {
        queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("QueueConnectionFactory");
        queue = (Queue) jndiContext.lookup(queueName);
    } catch (NamingException e) {
        LOG.info("JNDI API lookup failed: " + e);
        System.exit(1);
    }

    /*
     * Create connection. Create session from connection; false means
     * session is not transacted. Create sender and text message. Send
     * messages, varying text slightly. Send end-of-messages message.
     * Finally, close connection.
     */
    try {
        queueConnection = queueConnectionFactory.createQueueConnection();
        queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queueSender = queueSession.createSender(queue);
        message = queueSession.createTextMessage();
        for (int i = 0; i < numMsgs; i++) {
            message.setText("This is message " + (i + 1));
            LOG.info("Sending message: " + message.getText());
            queueSender.send(message);
        }

        /*
         * Send a non-text control message indicating end of messages.
         */
        queueSender.send(queueSession.createMessage());
    } catch (JMSException e) {
        LOG.info("Exception occurred: " + e.toString());
    } finally {
        if (queueConnection != null) {
            try {
                queueConnection.close();
            } catch (JMSException e) {
            }
        }
    }
}

From source file:io.datalayer.activemq.producer.SimpleProducer.java

/**
 * @param args the destination name to send to and optionally, the number of
 *                messages to send//from   w  w  w .  j a v  a  2  s  . c  om
 */
public static void main(String... args) {
    Context jndiContext = null;
    ConnectionFactory connectionFactory = null;
    Connection connection = null;
    Session session = null;
    Destination destination = null;
    MessageProducer producer = null;
    String destinationName = null;
    final int numMsgs;

    if ((args.length < 1) || (args.length > 2)) {
        LOG.info("Usage: java SimpleProducer <destination-name> [<number-of-messages>]");
        System.exit(1);
    }
    destinationName = args[0];
    LOG.info("Destination name is " + destinationName);
    if (args.length == 2) {
        numMsgs = (new Integer(args[1])).intValue();
    } else {
        numMsgs = 1;
    }

    /*
     * Create a JNDI API InitialContext object
     */
    try {
        jndiContext = new InitialContext();
    } catch (NamingException e) {
        LOG.info("Could not create JNDI API context: " + e.toString());
        System.exit(1);
    }

    /*
     * Look up connection factory and destination.
     */
    try {
        connectionFactory = (ConnectionFactory) jndiContext.lookup("ConnectionFactory");
        destination = (Destination) jndiContext.lookup(destinationName);
    } catch (NamingException e) {
        LOG.info("JNDI API lookup failed: " + e);
        System.exit(1);
    }

    /*
     * Create connection. Create session from connection; false means
     * session is not transacted. Create sender and text message. Send
     * messages, varying text slightly. Send end-of-messages message.
     * Finally, close connection.
     */
    try {
        connection = connectionFactory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producer = session.createProducer(destination);
        TextMessage message = session.createTextMessage();
        for (int i = 0; i < numMsgs; i++) {
            message.setText("This is message " + (i + 1));
            LOG.info("Sending message: " + message.getText());
            producer.send(message);
        }

        /*
         * Send a non-text control message indicating end of messages.
         */
        producer.send(session.createMessage());
    } catch (JMSException e) {
        LOG.info("Exception occurred: " + e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
            }
        }
    }
}

From source file:org.apache.uima.examples.as.GetMetaRequest.java

/**
 * retrieve meta information for a UIMA-AS Service attached to a broker
 * It uses the port 1099 as the JMX port on the broker, unless overridden
 *   by defining the system property activemq.broker.jmx.port with a value of another port number
 * It uses the default JMX ActiveMQ Domain "org.apache.activemq", unless overridden
 *   by defining the system property activemq.broker.jmx.domain with a value of the domain to use
 *   This normally never needs to be done unless multiple brokers are run on the same node 
 *   as is sometimes done for unit tests.
 * @param args - brokerUri serviceName [-verbose]
 *//*from ww w . ja  v  a  2s . com*/
public static void main(String[] args) {
    if (args.length < 2) {
        System.err.println("Need arguments: brokerURI serviceName [-verbose]");
        System.exit(1);
    }
    String brokerURI = args[0];
    String queueName = args[1];
    boolean printReply = false;
    if (args.length > 2) {
        if (args[2].equalsIgnoreCase("-verbose")) {
            printReply = true;
        } else {
            System.err.println("Unknown argument: " + args[2]);
            System.exit(1);
        }
    }
    final Connection connection;
    Session producerSession = null;
    Queue producerQueue = null;
    MessageProducer producer;
    MessageConsumer consumer;
    Session consumerSession = null;
    TemporaryQueue consumerDestination = null;
    long startTime = 0;

    //  Check if JMX server port number was specified
    jmxPort = System.getProperty("activemq.broker.jmx.port");
    if (jmxPort == null || jmxPort.trim().length() == 0) {
        jmxPort = "1099"; // default
    }

    try {
        //  First create connection to a broker
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI);
        connection = factory.createConnection();
        connection.start();
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                try {
                    if (connection != null) {
                        connection.close();
                    }
                    if (jmxc != null) {
                        jmxc.close();
                    }
                } catch (Exception ex) {
                }
            }
        }));

        URI target = new URI(brokerURI);
        String brokerHost = target.getHost();

        attachToRemoteBrokerJMXServer(brokerURI);
        if (isQueueAvailable(queueName) == QueueState.exists) {
            System.out.println("Queue " + queueName + " found on " + brokerURI);
            System.out.println("Sending getMeta...");
        } else if (isQueueAvailable(queueName) == QueueState.existsnot) {
            System.err.println("Queue " + queueName + " does not exist on " + brokerURI);
            System.exit(1);
        } else {
            System.out.println("Cannot see queues on JMX port " + brokerHost + ":" + jmxPort);
            System.out.println("Sending getMeta anyway...");
        }

        producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producerQueue = producerSession.createQueue(queueName);
        producer = producerSession.createProducer(producerQueue);
        consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        consumerDestination = consumerSession.createTemporaryQueue();
        //  -----------------------------------------------------------------------------
        //  Create message consumer. The consumer uses a selector to filter out messages other
        //  then GetMeta replies. Currently UIMA AS service returns two messages for each request:
        //  ServiceInfo message and GetMeta message. The ServiceInfo message is returned by the 
        //  service immediately upon receiving a message from a client. This serves dual purpose, 
        //  1) to make sure the client reply destination exists
        //  2) informs the client which service is processing its request
        //  -----------------------------------------------------------------------------
        consumer = consumerSession.createConsumer(consumerDestination, "Command=2001");
        TextMessage msg = producerSession.createTextMessage();
        msg.setStringProperty(AsynchAEMessage.MessageFrom, consumerDestination.getQueueName());
        msg.setStringProperty(UIMAMessage.ServerURI, brokerURI);
        msg.setIntProperty(AsynchAEMessage.MessageType, AsynchAEMessage.Request);
        msg.setIntProperty(AsynchAEMessage.Command, AsynchAEMessage.GetMeta);
        msg.setJMSReplyTo(consumerDestination);
        msg.setText("");
        producer.send(msg);
        startTime = System.nanoTime();

        System.out.println("Sent getMeta request to " + queueName + " at " + brokerURI);
        System.out.println("Waiting for getMeta reply...");
        ActiveMQTextMessage reply = (ActiveMQTextMessage) consumer.receive();
        long waitTime = (System.nanoTime() - startTime) / 1000000;

        System.out.println(
                "Reply from " + reply.getStringProperty("ServerIP") + " received in " + waitTime + " ms");
        if (printReply) {
            System.out.println("Reply MessageText: " + reply.getText());
        }
    } catch (Exception e) {
        System.err.println(e.toString());
    }
    System.exit(0);
}

From source file:service.emailer.Emailer.java

/**
 * Send email with parameters to emailQueue
 * @param area// w  w  w.  j ava 2s  . c om
 * @param email
 */
public static void sendEmail(String area, List<String> email) {
    try {
        //JMS QUEUE SEND
        final ConnectionFactory connectionFactory = lookup(ConnectionFactory.class, JNDI_CONNECTION_FACTORY);
        final Queue queue = lookup(Queue.class, JNDI_QUEUE);

        Connection connection = connectionFactory.createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(queue);
        MapMessage message = session.createMapMessage();
        message.setString("type", "warnFile");
        message.setString("area", area);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(email);
        message.setString("emailReceivers", json);
        producer.send(message);
    } catch (JMSException ex) {
        Logger.getLogger(Emailer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JsonProcessingException ex) {
        Logger.getLogger(Emailer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.dawnsci.commandserver.core.util.JSONUtils.java

/**
 * Generic way of sending a topic notification
 * @param connection - does not get closed afterwards nust be started before.
 * @param message// w ww .j  a va 2 s  .c  om
 * @param topicName
 * @param uri
 * @throws Exception
 */
private static final void sendTopic(Connection connection, Object message, String topicName, URI uri)
        throws Exception {

    // JMS messages are sent and received using a Session. We will
    // create here a non-transactional session object. If you want
    // to use transactions you should set the first parameter to 'true'
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    try {
        Topic topic = session.createTopic(topicName);

        MessageProducer producer = session.createProducer(topic);

        final ObjectMapper mapper = new ObjectMapper();

        // Here we are sending the message out to the topic
        TextMessage temp = session.createTextMessage(mapper.writeValueAsString(message));
        producer.send(temp, DeliveryMode.NON_PERSISTENT, 1, 5000);

    } finally {
        session.close();
    }
}

From source file:org.logicblaze.lingo.jms.impl.DefaultJmsProducer.java

public static DefaultJmsProducer newInstance(Connection connection, JmsProducerConfig config,
        boolean ownsConnection) throws JMSException {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    return new DefaultJmsProducer(connection, session, config, ownsConnection);
}

From source file:nl.nn.adapterframework.extensions.tibco.TibcoUtils.java

/**
 * return -1: no message found//from  w  w  w  . ja v  a2  s .com
 * return -2: message found, but not of type Message.
 */
public static long getQueueFirstMessageAge(String provUrl, String authAlias, String userName, String password,
        String queueName, String messageSelector) throws JMSException {
    Connection connection = null;
    Session jSession = null;
    try {
        connection = getConnection(provUrl, authAlias, userName, password);
        jSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
        return getQueueFirstMessageAge(jSession, queueName, messageSelector);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                log.warn("Exception on closing connection", e);
            }
        }
    }
}

From source file:org.apache.stratos.adc.topology.mgt.subscriber.TopologySubscriber.java

public static void subscribe(String topicName) {
    Properties initialContextProperties = new Properties();
    TopicSubscriber topicSubscriber = null;
    TopicSession topicSession = null;/*from   ww  w. j  av  a 2s  .c  o  m*/
    TopicConnection topicConnection = null;
    InitialContext initialContext = null;

    initialContextProperties.put("java.naming.factory.initial",
            "org.wso2.andes.jndi.PropertiesFileInitialContextFactory");

    String mbServerIp = System.getProperty(TopologyConstants.MB_SERVER_IP) == null
            ? TopologyConstants.DEFAULT_MB_SERVER_IP
            : System.getProperty(TopologyConstants.MB_SERVER_IP);

    String connectionString = "amqp://admin:admin@clientID/carbon?brokerlist='tcp://" + mbServerIp
            + "'&reconnect='true'";
    initialContextProperties.put("connectionfactory.qpidConnectionfactory", connectionString);

    try {
        initialContext = new InitialContext(initialContextProperties);
        TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) initialContext
                .lookup("qpidConnectionfactory");
        topicConnection = topicConnectionFactory.createTopicConnection();
        topicConnection.start();
        topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

        Topic topic = topicSession.createTopic(topicName);
        topicSubscriber = topicSession.createSubscriber(topic);

        topicSubscriber.setMessageListener(new TopologyListener());

    } catch (Exception e) {
        log.error(e.getMessage(), e);

        try {
            if (topicSubscriber != null) {
                topicSubscriber.close();
            }

            if (topicSession != null) {
                topicSession.close();
            }

            if (topicConnection != null) {
                topicConnection.close();
            }
        } catch (JMSException e1) {
            // ignore
        }

    } finally {
        // start the health checker
        Thread healthChecker = new Thread(new TopicHealthChecker(topicName, topicSubscriber));
        healthChecker.start();
    }
}