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.ruyicai.msgcenter.jms.WithoutTMJmsConfiguration.java

/**
 * Creates a {@link JmsOperations} object used for request/response using a request timeout value
 *//*ww w .j ava  2  s. com*/
public JmsOperations createInOutTemplate(JmsEndpoint endpoint, boolean pubSubDomain, String destination,
        long requestTimeout) {
    JmsOperations answer = createInOnlyTemplate(endpoint, pubSubDomain, destination);
    if (answer instanceof JmsTemplate && requestTimeout > 0) {
        JmsTemplate jmsTemplate = (JmsTemplate) answer;
        jmsTemplate.setExplicitQosEnabled(true);

        // prefer to use timeToLive over requestTimeout if both specified
        long ttl = timeToLive > 0 ? timeToLive : requestTimeout;
        if (ttl > 0 && !isDisableTimeToLive()) {
            // only use TTL if not disabled
            jmsTemplate.setTimeToLive(ttl);
        }

        jmsTemplate.setSessionTransacted(isTransactedInOut());
        if (isTransactedInOut()) {
            jmsTemplate.setSessionAcknowledgeMode(Session.SESSION_TRANSACTED);
        } else {
            if (acknowledgementMode >= 0) {
                jmsTemplate.setSessionAcknowledgeMode(acknowledgementMode);
            } else if (acknowledgementModeName != null) {
                jmsTemplate.setSessionAcknowledgeModeName(acknowledgementModeName);
            } else {
                // default to AUTO
                jmsTemplate.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE);
            }
        }
    }
    return answer;
}

From source file:org.seedstack.jms.internal.JmsPlugin.java

private void configureMessageListeners(Collection<Class<?>> listenerCandidates) {
    for (Class<?> candidate : listenerCandidates) {
        if (MessageListener.class.isAssignableFrom(candidate)) {
            //noinspection unchecked
            Class<? extends MessageListener> messageListenerClass = (Class<? extends MessageListener>) candidate;
            String messageListenerName = messageListenerClass.getCanonicalName();
            JmsMessageListener annotation = messageListenerClass.getAnnotation(JmsMessageListener.class);

            boolean isTransactional;
            try {
                isTransactional = transactionPlugin
                        .isTransactional(messageListenerClass.getMethod("onMessage", Message.class));
            } catch (NoSuchMethodException e) {
                throw SeedException.wrap(e, JmsErrorCodes.UNEXPECTED_EXCEPTION);
            }/*ww w  .ja  v a  2s. c  o m*/

            Connection listenerConnection = connections.get(annotation.connection());

            if (listenerConnection == null) {
                throw SeedException.createNew(JmsErrorCodes.MISSING_CONNECTION_FACTORY)
                        .put(ERROR_CONNECTION_NAME, annotation.connection())
                        .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName);
            }

            Session session;
            try {
                session = listenerConnection.createSession(isTransactional, Session.AUTO_ACKNOWLEDGE);
            } catch (JMSException e) {
                throw SeedException.wrap(e, JmsErrorCodes.UNABLE_TO_CREATE_SESSION)
                        .put(ERROR_CONNECTION_NAME, annotation.connection())
                        .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName);
            }

            Destination destination;
            DestinationType destinationType;

            if (!annotation.destinationTypeStr().isEmpty()) {
                try {
                    destinationType = DestinationType
                            .valueOf(application.substituteWithConfiguration(annotation.destinationTypeStr()));
                } catch (IllegalArgumentException e) {
                    throw SeedException.wrap(e, JmsErrorCodes.UNKNOWN_DESTINATION_TYPE)
                            .put(ERROR_DESTINATION_TYPE, annotation.destinationTypeStr())
                            .put(ERROR_CONNECTION_NAME, annotation.connection())
                            .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName);
                }
            } else {
                destinationType = annotation.destinationType();
            }
            try {
                switch (destinationType) {
                case QUEUE:
                    destination = session
                            .createQueue(application.substituteWithConfiguration(annotation.destinationName()));
                    break;
                case TOPIC:
                    destination = session
                            .createTopic(application.substituteWithConfiguration(annotation.destinationName()));
                    break;
                default:
                    throw SeedException.createNew(JmsErrorCodes.UNKNOWN_DESTINATION_TYPE)
                            .put(ERROR_CONNECTION_NAME, annotation.connection())
                            .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName);
                }
            } catch (JMSException e) {
                throw SeedException.wrap(e, JmsErrorCodes.UNABLE_TO_CREATE_DESTINATION)
                        .put(ERROR_DESTINATION_TYPE, destinationType.name())
                        .put(ERROR_CONNECTION_NAME, annotation.connection())
                        .put(ERROR_MESSAGE_LISTENER_NAME, messageListenerName);
            }

            Class<? extends MessagePoller> messagePollerClass = null;
            if (annotation.poller().length > 0) {
                messagePollerClass = annotation.poller()[0];
            }

            registerMessageListener(new MessageListenerDefinition(messageListenerName,
                    application.substituteWithConfiguration(annotation.connection()), session, destination,
                    application.substituteWithConfiguration(annotation.selector()), messageListenerClass,
                    messagePollerClass));
        }
    }
}

From source file:org.dawnsci.commandserver.ui.view.StatusQueueView.java

/**
 * Listens to a topic//from   ww  w .j ava2  s.c  o  m
 */
private void createTopicListener(final URI uri) throws Exception {

    // Use job because connection might timeout.
    final Job topicJob = new Job("Create topic listener") {

        @Override
        protected IStatus run(IProgressMonitor monitor) {
            try {
                ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
                StatusQueueView.this.topicConnection = connectionFactory.createConnection();
                topicConnection.start();

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

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

                final Class clazz = getBeanClass();
                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 bean = mapper.readValue(t.getText(), clazz);
                                mergeBean(bean);
                            }
                        } catch (Exception e) {
                            logger.error("Updating changed bean from topic", e);
                        }
                    }
                };
                consumer.setMessageListener(listener);

                // Create a listener for administrator broadcast messages.
                topic = session.createTopic(Constants.ADMIN_MESSAGE_TOPIC);
                consumer = session.createConsumer(topic);
                listener = new MessageListener() {
                    public void onMessage(Message message) {
                        try {
                            if (message instanceof TextMessage) {
                                // AdministratorMessage shows a message to the user.
                                final Class msgClass = AdministratorMessage.class;

                                TextMessage t = (TextMessage) message;
                                final AdministratorMessage bean = mapper.readValue(t.getText(), msgClass);

                                getSite().getShell().getDisplay().syncExec(new Runnable() {
                                    public void run() {
                                        MessageDialog.openError(getViewSite().getShell(), bean.getTitle(),
                                                bean.getMessage());

                                        viewer.refresh();
                                    }
                                });
                            }
                        } catch (Exception e) {
                            // Not a big deal if they do not get admin messages.
                        }
                    }
                };
                consumer.setMessageListener(listener);

                return Status.OK_STATUS;

            } catch (Exception ne) {
                logger.error("Cannot listen to topic changes because command server is not there", ne);
                return Status.CANCEL_STATUS;
            }
        }

    };

    topicJob.setPriority(Job.INTERACTIVE);
    topicJob.setSystem(true);
    topicJob.setUser(false);
    topicJob.schedule();
}

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

/**
 * TEST TOPICS/*from  w w  w.  j  a  v  a  2s  . c  o m*/
 */
public void testTopic(String prod_broker_url, String cons_broker_url) throws Exception {
    int num_msg;

    Connection conn;
    Session sess;
    String topic_name;

    Destination cons_dest;

    num_msg = 5;

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

    conn = createConnection(cons_broker_url);
    conn.start();
    sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    //
    // Create the destination on which messages are being tested.
    //
    topic_name = "topotest2.perm.topic";
    LOG.trace("Removing existing Topic");
    removeTopic(conn, topic_name);
    LOG.trace("Creating Topic, " + topic_name);
    cons_dest = sess.createTopic(topic_name);

    testOneDest(conn, sess, cons_dest, num_msg);

    //
    // Cleanup
    //
    removeTopic(conn, topic_name);
    sess.close();
    conn.close();
}

From source file:com.cws.esolutions.agent.AgentDaemon.java

public void start() {
    final String methodName = AgentDaemon.CNAME + "#start()";

    if (DEBUG) {//from  ww  w .jav a2s  . c  o  m
        DEBUGGER.debug(methodName);
    }

    try {
        this.connFactory = new ActiveMQConnectionFactory(
                AgentDaemon.agentBean.getConfigData().getServerConfig().getConnectionName());

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

        this.conn = this.connFactory.createConnection(
                AgentDaemon.agentBean.getConfigData().getServerConfig().getUsername(),
                PasswordUtils.decryptText(AgentDaemon.agentBean.getConfigData().getServerConfig().getPassword(),
                        AgentDaemon.agentBean.getConfigData().getServerConfig().getSalt(),
                        AgentDaemon.agentBean.getConfigData().getServerConfig().getEncryptionAlgorithm(),
                        AgentDaemon.agentBean.getConfigData().getServerConfig().getIterations(),
                        AgentDaemon.agentBean.getConfigData().getServerConfig().getKeyBits(),
                        AgentDaemon.agentBean.getConfigData().getServerConfig().getEncryptionAlgorithm(),
                        AgentDaemon.agentBean.getConfigData().getServerConfig().getEncryptionInstance(),
                        AgentDaemon.agentBean.getConfigData().getServerConfig().getEncoding()));

        this.conn.setExceptionListener(new MQExceptionHandler());
        this.conn.setClientID(AgentDaemon.agentBean.getConfigData().getServerConfig().getClientId());
        this.conn.start();

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

        this.session = this.conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

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

        this.request = this.session
                .createTopic(AgentDaemon.agentBean.getConfigData().getServerConfig().getRequestQueue());
        this.response = this.session
                .createQueue(AgentDaemon.agentBean.getConfigData().getServerConfig().getResponseQueue());

        if (DEBUG) {
            DEBUGGER.debug("Destination: {}", this.request);
            DEBUGGER.debug("Destination: {}", this.response);
        }

        this.consumer = this.session.createConsumer(this.request,
                "targetHost='" + AgentDaemon.agentBean.getHostName() + "'");
        this.consumer.setMessageListener(new MQMessageHandler());

        if (DEBUG) {
            DEBUGGER.debug("MessageConsumer: {}", this.consumer);
        }

        this.producer = this.session.createProducer(this.response);

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

        AgentDaemon.agentBean.setResponseQueue(this.response);
        AgentDaemon.agentBean.setSession(this.session);
        AgentDaemon.agentBean.setProducer(this.producer);
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        this.exitCode = 1;
        stop();
    } catch (JMSException jx) {
        ERROR_RECORDER.error(jx.getMessage(), jx);

        this.exitCode = 1;
        stop();
    }
}

From source file:com.datatorrent.lib.io.jms.ActiveMQBase.java

/**
 *  Get session acknowledge.//w w w. ja  v a2s . com
 *  Converts acknowledge string into JMS Session variable.
 */
public int getSessionAckMode(String ackMode) {
    if ("CLIENT_ACKNOWLEDGE".equals(ackMode)) {
        return Session.CLIENT_ACKNOWLEDGE;
    } else if ("AUTO_ACKNOWLEDGE".equals(ackMode)) {
        return Session.AUTO_ACKNOWLEDGE;
    } else if ("DUPS_OK_ACKNOWLEDGE".equals(ackMode)) {
        return Session.DUPS_OK_ACKNOWLEDGE;
    } else if ("SESSION_TRANSACTED".equals(ackMode)) {
        return Session.SESSION_TRANSACTED;
    } else {
        return Session.CLIENT_ACKNOWLEDGE; // default
    }
}

From source file:org.firstopen.singularity.util.JMSUtil.java

public static void deliverMessageToTopic(String host, String topicName, String xml) {
    log.debug("IntegrationMod.deliverMessageToQueue queueName = " + topicName + " and doc = " + xml);

    char test = topicName.charAt(0);

    if (test == '/')
        topicName = topicName.substring(1);

    try {//w  ww .j a  va2 s .  co  m

        InitialContext context = JNDIUtil.getInitialContext(host);

        Connection connection = null;
        Session session = null;
        MessageProducer publisher = null;
        ConnectionFactory tcf = (ConnectionFactory) context.lookup("ConnectionFactory");

        Topic topic = (Topic) context.lookup(topicName);

        connection = tcf.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        publisher = session.createProducer(topic);

        TextMessage message = session.createTextMessage();

        log.debug("message value is -> " + xml);

        message.setText(xml);

        publisher.send(message);

    } catch (Exception e) {
        log.error("unable to send message on topic", e);
    } finally {

    }
}

From source file:com.oneops.sensor.util.InstanceManager.java

private SensorListenerContainer buildOpsMQListenerContainer(String host) {

    int port = Integer.valueOf(System.getProperty(OPSMQ_PORT_PARAM, "61616"));
    String opsmqPass = System.getenv(OPSMQ_PASS_ENV_VAR);
    if (opsmqPass == null) {
        throw new RuntimeException(OPSMQ_PASS_ENV_VAR + " env var needs to be set!");
    }/* w  ww.  jav  a  2  s.c  om*/

    ActiveMQConnectionFactory opsmqConnectionFactory = new ActiveMQConnectionFactory();
    opsmqConnectionFactory.setBrokerURL(opsMQURI.build(host, port));
    opsmqConnectionFactory.setUserName(OPSMQ_USER);
    opsmqConnectionFactory.setPassword(opsmqPass);

    SensorListenerContainer listenerContainer = new SensorListenerContainer();

    listenerContainer.setConnectionFactory(opsmqConnectionFactory);
    listenerContainer.setMaxConcurrentConsumers(Integer.valueOf(System.getProperty(OPSMQ_MAX_SESSIONS, "24")));
    listenerContainer.setConcurrentConsumers(Integer.valueOf(System.getProperty(OPSMQ_MAX_SESSIONS, "24")));
    listenerContainer.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE);
    listenerContainer.setMessageListener(this.sensorListener);

    return listenerContainer;

}

From source file:org.wildfly.camel.test.jms.TransactedJMSIntegrationTest.java

private void sendMessage(Connection connection, String jndiName, String message) throws Exception {
    InitialContext initialctx = new InitialContext();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = (Destination) initialctx.lookup(jndiName);
    MessageProducer producer = session.createProducer(destination);
    TextMessage msg = session.createTextMessage(message);
    producer.send(msg);//from w ww  .j a v  a2 s  .  c o  m
    connection.start();
}

From source file:org.seedstack.seed.ws.internal.jms.WSJmsPlugin.java

@Override
public InitState init(InitContext initContext) {
    Configuration wsConfiguration = null;

    for (Plugin plugin : initContext.pluginsRequired()) {
        if (plugin instanceof JmsPlugin) {
            jmsPlugin = (JmsPlugin) plugin;
        }/*from w  w w .  ja va  2 s. com*/

        if (plugin instanceof WSPlugin) {
            wsPlugin = (WSPlugin) plugin;
        }

        if (plugin instanceof ApplicationPlugin) {
            wsConfiguration = ((ApplicationPlugin) plugin).getApplication().getConfiguration()
                    .subset(WS_CONFIGURATION_PREFIX);
        }
    }

    if (wsConfiguration == null) {
        throw new PluginException("Missing required application plugin");
    }

    int cacheSize = wsConfiguration.getInt("jms.transport-cache.max-size", DEFAULT_CACHE_SIZE);
    final Configuration finalWsConfiguration = wsConfiguration;
    connectionCache = CacheBuilder.newBuilder().maximumSize(cacheSize)
            .concurrencyLevel(wsConfiguration.getInt("transport-cache.concurrency", DEFAULT_CACHE_CONCURRENCY))
            .initialCapacity(wsConfiguration.getInt("transport-cache.initial-size", cacheSize / 4))
            .build(new CacheLoader<SoapJmsUri, Connection>() {
                private AtomicInteger atomicInteger = new AtomicInteger(0);

                @Override
                public Connection load(SoapJmsUri soapJmsUri) throws NamingException, JMSException {
                    String lookupVariant = soapJmsUri.getLookupVariant();
                    JmsFactory jmsFactory = jmsPlugin.getJmsFactory();
                    Connection connection;

                    if (SoapJmsUri.JNDI_LOOKUP_VARIANT.equals(lookupVariant)) {
                        String jndiConnectionFactoryName = soapJmsUri.getParameter("jndiConnectionFactoryName");
                        if (StringUtils.isBlank(jndiConnectionFactoryName)) {
                            throw new IllegalArgumentException(
                                    "Missing jndiConnectionFactoryName parameter for JMS URI "
                                            + soapJmsUri.toString());
                        }

                        String connectionName = soapJmsUri.getConnectionName();
                        if (connectionName == null) {
                            connectionName = String.format(ANONYMOUS_CONNECTION_PATTERN,
                                    atomicInteger.getAndIncrement());
                        }

                        ConnectionDefinition connectionDefinition = jmsFactory.createConnectionDefinition(
                                connectionName, soapJmsUri.getConfiguration(finalWsConfiguration),
                                (ConnectionFactory) SoapJmsUri.getContext(soapJmsUri)
                                        .lookup(jndiConnectionFactoryName));

                        connection = jmsFactory.createConnection(connectionDefinition);
                        jmsPlugin.registerConnection(connection, connectionDefinition);
                    } else if (SoapJmsUri.SEED_QUEUE_LOOKUP_VARIANT.equals(lookupVariant)
                            || SoapJmsUri.SEED_TOPIC_LOOKUP_VARIANT.equals(lookupVariant)) {
                        String connectionName = soapJmsUri.getConnectionName();

                        if (StringUtils.isBlank(connectionName)) {
                            throw new IllegalArgumentException(
                                    "Missing connectionName parameter for JMS URI " + soapJmsUri.toString());
                        }

                        connection = jmsPlugin.getConnection(connectionName);
                    } else {
                        throw new IllegalArgumentException("Unsupported lookup variant " + lookupVariant
                                + " for JMS URI " + soapJmsUri.toString());
                    }

                    if (connection == null) {
                        throw new PluginException(
                                "Unable to resolve connection for JMS URI " + soapJmsUri.toString());
                    }

                    return connection;
                }
            });

    for (Map.Entry<String, EndpointDefinition> endpointEntry : wsPlugin
            .getEndpointDefinitions(SUPPORTED_BINDINGS).entrySet()) {
        EndpointDefinition endpointDefinition = endpointEntry.getValue();
        String endpointName = endpointEntry.getKey();
        String serviceName = endpointDefinition.getServiceName().getLocalPart();
        String portName = endpointDefinition.getPortName().getLocalPart();
        String serviceNameAndServicePort = serviceName + "-" + portName;

        SoapJmsUri uri;
        try {
            uri = SoapJmsUri.parse(new URI(endpointDefinition.getUrl()));
            uri.setEndpointName(endpointName);
        } catch (URISyntaxException e) {
            throw new PluginException("Unable to parse endpoint URI", e);
        }

        Configuration endpointConfiguration = uri.getConfiguration(wsConfiguration);
        Connection connection;
        try {
            connection = connectionCache.get(uri);
        } catch (Exception e) {
            throw new PluginException("Unable to create JMS connection for WS " + serviceNameAndServicePort, e);
        }

        Session session;
        try {
            session = connection.createSession(endpointConfiguration.getBoolean("transactional", true),
                    Session.AUTO_ACKNOWLEDGE);
        } catch (JMSException e) {
            throw new PluginException("Unable to create JMS session for WS " + serviceNameAndServicePort, e);
        }

        Destination destination;
        try {
            destination = SoapJmsUri.getDestination(uri, session);
        } catch (Exception e) {
            throw new PluginException("Unable to create JMS destination for WS " + serviceNameAndServicePort,
                    e);
        }

        WSJmsMessageListener messageListener = new WSJmsMessageListener(uri,
                new JmsAdapter(wsPlugin.createWSEndpoint(endpointDefinition, null)), session);

        String messageListenerName = String.format(LISTENER_NAME_PATTERN, endpointName);
        try {
            Class<? extends MessagePoller> poller = getPoller(endpointConfiguration);

            jmsPlugin.registerMessageListener(
                    new MessageListenerInstanceDefinition(messageListenerName, uri.getConnectionName(), session,
                            destination, endpointConfiguration.getString("selector"), messageListener, poller));
        } catch (Exception e) {
            throw SeedException.wrap(e, WSJmsErrorCodes.UNABLE_TO_REGISTER_MESSAGE_LISTENER)
                    .put("messageListenerName", messageListenerName);
        }
        wsJmsMessageListeners.add(messageListener);
    }

    return InitState.INITIALIZED;
}