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:com.googlecode.fascinator.portal.HouseKeeper.java

/**
 * Start thread running// ww  w . j av a 2  s  .  c o m
 * 
 */
@Override
public void run() {
    openLog();
    try {
        globalConfig = new JsonSimpleConfig();
        // 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();

        // Sessions are not thread safe, to send a message outside
        // of the onMessage() callback you need another session.
        cSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        pSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        Destination destination = cSession.createQueue(QUEUE_ID);
        consumer = cSession.createConsumer(destination);
        consumer.setMessageListener(this);

        // Producer
        destHouseKeeping = pSession.createQueue(QUEUE_ID);
        producer = pSession.createProducer(null);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);

        connection.start();

        // Database prep work
        try {
            // Look for our table
            checkTable(NOTIFICATIONS_TABLE);
            // Sync in-memory actions to database
            syncActionList();
            // Purge any old 'block' entries since we just (re)started
            for (UserAction ua : actions) {
                if (ua.block) {
                    removeAction(ua.id);
                }
            }
        } catch (SQLException ex) {
            log.error("Error during database preparation:", ex);
        }
        log.debug("Derby house keeping database online!");

        // Quartz Scheduler
        try {
            scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.start();
            quartzScheduling();
        } catch (SchedulerException ex) {
            log.error("Scheduled failed to start: ", ex);
        }

        // Start our callback timer
        log.info("Starting callback timer. Timeout = {}s", timeout);
        timer = new Timer("HouseKeeping", true);
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                onTimeout();
            }
        }, 0, timeout * 1000);

    } catch (IOException ex) {
        log.error("Unable to read config!", ex);
    } catch (JMSException ex) {
        log.error("Error starting message thread!", ex);
    }
    closeLog();
}

From source file:org.dawnsci.commandserver.core.process.ProgressableProcess.java

/**
 * Starts a connection which listens to the topic and if
 * a cancel is found published, tries to terminate the subprocess.
 * /*www.ja v  a  2s  .  c  o  m*/
 * @param p
 */
protected void createTerminateListener() throws Exception {

    ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    ProgressableProcess.this.topicConnection = connectionFactory.createConnection();
    topicConnection.start();

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

    final Topic topic = session.createTopic(statusTName);
    final MessageConsumer consumer = session.createConsumer(topic);

    final Class clazz = bean.getClass();
    final ObjectMapper mapper = new ObjectMapper();

    MessageListener listener = new MessageListener() {
        public void onMessage(Message message) {
            try {
                if (message instanceof TextMessage) {
                    TextMessage t = (TextMessage) message;
                    final StatusBean tbean = mapper.readValue(t.getText(), clazz);

                    if (bean.getStatus().isFinal()) { // Something else already happened
                        topicConnection.close();
                        return;
                    }

                    if (bean.getUniqueId().equals(tbean.getUniqueId())) {
                        if (tbean.getStatus() == Status.REQUEST_TERMINATE) {
                            bean.merge(tbean);
                            out.println("Terminating job '" + tbean.getName() + "'");

                            terminate();
                            topicConnection.close();

                            bean.setStatus(Status.TERMINATED);
                            bean.setMessage("Foricibly terminated before finishing.");
                            broadcast(bean);

                            return;
                        }
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    };
    consumer.setMessageListener(listener);

}

From source file:org.apache.activemq.apollo.JmsQueueBrowserTest.java

public void testBrowseClose() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");

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

    TextMessage[] outbound = new TextMessage[] { session.createTextMessage("First Message"),
            session.createTextMessage("Second Message"), session.createTextMessage("Third Message") };

    MessageProducer producer = session.createProducer(destination);
    producer.send(outbound[0]);
    producer.send(outbound[1]);
    producer.send(outbound[2]);

    // create browser first
    QueueBrowser browser = session.createBrowser((Queue) destination);
    Enumeration enumeration = browser.getEnumeration();

    // browse some messages
    assertEquals(outbound[0], (Message) enumeration.nextElement());
    assertEquals(outbound[1], (Message) enumeration.nextElement());
    //assertEquals(outbound[2], (Message) enumeration.nextElement());

    browser.close();

    // create consumer
    MessageConsumer consumer = session.createConsumer(destination);

    // Receive the first message.
    TextMessage msg = (TextMessage) consumer.receive(1000);
    assertEquals("Expected " + outbound[0].getText() + " but received " + msg.getText(), outbound[0], msg);
    msg = (TextMessage) consumer.receive(1000);
    assertEquals("Expected " + outbound[1].getText() + " but received " + msg.getText(), outbound[1], msg);
    msg = (TextMessage) consumer.receive(1000);
    assertEquals("Expected " + outbound[2].getText() + " but received " + msg.getText(), outbound[2], msg);

    consumer.close();
    producer.close();

}

From source file:dk.netarkivet.common.distribute.JMSConnectionSunMQ.java

@Override
public synchronized QueueSession getQueueSession() throws JMSException {
    if (qConnection == null) {
        qConnection = getConnectionFactory().createQueueConnection();
    }//w w  w. j ava  2s .c  o m
    boolean transacted = false;
    return qConnection.createQueueSession(transacted, Session.AUTO_ACKNOWLEDGE);
}

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

/**
 * TEST TEMPORARY TOPICS/*from   w  ww .java 2  s .  com*/
 */
public void testTempTopic(String prod_broker_url, String cons_broker_url) throws Exception {
    Connection conn;
    Session sess;
    Destination cons_dest;
    int num_msg;

    num_msg = 5;

    LOG.debug("TESTING TEMP TOPICS " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg
            + " messages)");

    //
    // Connect to the bus.
    //
    conn = createConnection(cons_broker_url);
    conn.start();
    sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    //
    // Create the destination on which messages are being tested.
    //
    LOG.trace("Creating destination");
    cons_dest = sess.createTemporaryTopic();

    testOneDest(conn, sess, cons_dest, num_msg);

    //
    // Cleanup
    //
    sess.close();
    conn.close();
}

From source file:org.jbpm.ejb.impl.CommandListenerBean.java

private Session createSession() throws JMSException {
    if (jmsConnection == null) {
        // lookup factory and create jms connection
        try {/*from w  w  w  . j  a  va  2s .c o  m*/
            Context initial = new InitialContext();
            ConnectionFactory jmsConnectionFactory = (ConnectionFactory) initial
                    .lookup("java:comp/env/jms/JbpmConnectionFactory");
            jmsConnection = jmsConnectionFactory.createConnection();
        } catch (NamingException e) {
            throw new EJBException("error retrieving jms connection factory", e);
        }
    }
    /*
     * if the connection supports xa, the session will be transacted, else the
     * session will auto acknowledge; in either case no explicit transaction
     * control must be performed - see ejb 2.1 17.3.5
     */
    return jmsConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
}

From source file:org.overlord.sramp.events.jms.JMSEventProducer.java

private void initActiveMQ(ConnectionFactory connectionFactory, String[] topicNames, String[] queueNames)
        throws Exception {
    connection = connectionFactory.createConnection();
    connection.start();/*from   ww  w. j a  v a  2  s  .c  om*/
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    for (String topicName : topicNames) {
        destinations.add(session.createTopic(topicName));
    }

    for (String queueName : queueNames) {
        destinations.add(session.createQueue(queueName));
    }
}

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

/**
 * This method checks for pending messages received by another gateway and processes them to a JMS destination
 *
 * @param ctx//from   w  w  w . j  a  va2s .c om
 */
public void executeInternal(final JobExecutionContext ctx) {
    try {

        final Collection<String> ids = this.messageRetriever.listPendingMessages();

        if (!ids.isEmpty() || ids.size() > 0) {
            final String[] messageIds = ids.toArray(new String[ids.size()]);

            Connection connection;
            MessageProducer producer;

            connection = this.cf.createConnection();
            for (final String messageId : messageIds) {
                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();
        } else {
            BackendJMSImpl.LOG.debug("No pending messages to send");
        }

    } catch (final JMSException | ValidationException ex) {
        BackendJMSImpl.LOG.error(ex);
    }
}

From source file:com.seajas.search.profiler.service.profiler.ProfilerService.java

/**
 * Default constructor.//w  w w  . ja va 2s  . c o m
 * 
 * @param jobNames
 * @param jobDescriptions
 * @param availableApplicationLanguages
 * @param availableSearchLanguages
 * @param jmsRequestQueue
 * @param jmsConnectionFactory
 * @throws Exception
 */
@Autowired
public ProfilerService(@Value("${profiler.project.search.enricher.jobs}") final String jobNames,
        @Value("${profiler.project.search.enricher.jobs.descriptions}") final String jobDescriptions,
        @Value("${profiler.project.languages.available}") final String availableApplicationLanguages,
        @Value("${profiler.project.search.languages}") final String availableSearchLanguages,
        @Qualifier("jmsPrimaryRequestQueue") final ActiveMQQueue jmsRequestQueue,
        @Qualifier("connectionFactory") final ConnectionFactory jmsConnectionFactory) throws Exception {
    /* InputStream caCertificate = getClass().getClassLoader().getResourceAsStream("ca.crt"); LicenseValidator.validateLicenseFile(caCertificate, licenseFile);
     * 
     * try { caCertificate.close(); } catch (IOException e) { logger.error("Could not close the CA certificate stream."); } */

    String[] names = jobNames.split(",");
    String[] descriptions = jobDescriptions.split(",");

    this.jobNames = new LinkedHashMap<String, String>();

    for (int i = 0; i < names.length; i++)
        this.jobNames.put(names[i].trim(), descriptions[i].trim());

    this.availableApplicationLanguages = Arrays
            .asList(StringUtils.tokenizeToStringArray(availableApplicationLanguages, ",", true, true));
    this.availableSearchLanguages = Arrays
            .asList(StringUtils.tokenizeToStringArray(availableSearchLanguages, ",", true, true));

    // Keep track of the active consumers on the request channel

    Connection connection = jmsConnectionFactory.createConnection();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);

    connection.start();

    Destination destinationAdvisory = AdvisorySupport.getConsumerAdvisoryTopic(jmsRequestQueue);
    MessageConsumer consumerAdvisory = session.createConsumer(destinationAdvisory);

    consumerAdvisory.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(final Message message) {
            try {
                Object consumerCount = ((ActiveMQMessage) message).getProperty("consumerCount");

                if (consumerCount != null) {
                    String clientId = ((ActiveMQMessage) message).getConnection().getConnectionInfo()
                            .getClientId();

                    if (activeContenderClients.contains(clientId) && ((Integer) consumerCount == 0)) {
                        if (staticLogger.isInfoEnabled())
                            staticLogger.info("Client with ID " + clientId
                                    + " was dropped from the current consumer-clients");

                        activeContenderClients.remove(clientId);
                    } else if (!activeContenderClients.contains(clientId) && ((Integer) consumerCount > 0)) {
                        if (staticLogger.isInfoEnabled())
                            staticLogger.info("Client with ID " + clientId
                                    + " was added to the current consumer-clients");

                        activeContenderClients.add(clientId);
                    }
                }
            } catch (IOException e) {
                staticLogger.error("Could not retrieve consumer count from connection message", e);
            }
        }
    });
}

From source file:org.apache.camel.component.sjms.SjmsConsumer.java

/**
 * Creates a {@link MessageConsumerResources} with a dedicated
 * {@link Session} required for transacted and InOut consumers.
 *///ww w  .j a  v a2  s .  com
private MessageConsumerResources createConsumer() throws Exception {
    MessageConsumerResources answer;
    Connection conn = getConnectionResource().borrowConnection();
    try {
        Session session = conn.createSession(isTransacted(),
                isTransacted() ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE);
        Destination destination = getEndpoint().getDestinationCreationStrategy().createDestination(session,
                getDestinationName(), isTopic());
        MessageConsumer messageConsumer = JmsObjectFactory.createMessageConsumer(session, destination,
                getMessageSelector(), isTopic(), getDurableSubscriptionId());
        MessageListener handler = createMessageHandler(session);
        messageConsumer.setMessageListener(handler);

        answer = new MessageConsumerResources(session, messageConsumer);
    } catch (Exception e) {
        log.error("Unable to create the MessageConsumer", e);
        throw e;
    } finally {
        getConnectionResource().returnConnection(conn);
    }
    return answer;
}