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.aludratest.service.jms.impl.JmsActionImpl.java

@Override
public void unsubscribeTopic(@TechnicalArgument String subscriptionName) throws JMSException {
    if (StringUtils.isEmpty(clientId)) {
        throw new IllegalArgumentException("Client-Id must be provided to unsubscribe");
    }//from   www .jav  a  2s.  c o  m
    LOGGER.debug("Unsubscribing from subscription " + subscriptionName);
    Connection c = getDynamicConnection(subscriptionName);
    c.stop();

    TopicSubscriber subscriber = this.durableConsumers.get(subscriptionName);
    if (subscriber != null) {
        subscriber.close();
        c.createSession(false, Session.AUTO_ACKNOWLEDGE).unsubscribe(subscriptionName);
        this.durableConsumers.remove(subscriptionName);
    }
    c.close();
    this.dynamicConnections.remove(c);

}

From source file:org.apache.axis2.transport.jms.JMSOutTransportInfo.java

/**
 * Create a one time MessageProducer for this JMS OutTransport information.
 * For simplicity and best compatibility, this method uses only JMS 1.0.2b API.
 * Please be cautious when making any changes
 *
 * @return a JMSSender based on one-time use resources
 * @throws JMSException on errors, to be handled and logged by the caller 
 *///from ww  w .j  av a  2  s .  c o  m
public JMSMessageSender createJMSSender() throws JMSException {

    // digest the targetAddress and locate CF from the EPR
    loadConnectionFactoryFromProperies();

    // create a one time connection and session to be used
    String user = properties != null ? properties.get(JMSConstants.PARAM_JMS_USERNAME) : null;
    String pass = properties != null ? properties.get(JMSConstants.PARAM_JMS_PASSWORD) : null;

    QueueConnectionFactory qConFac = null;
    TopicConnectionFactory tConFac = null;

    int destType = -1;
    // TODO: there is something missing here for destination type generic
    if (JMSConstants.DESTINATION_TYPE_QUEUE.equals(destinationType)) {
        destType = JMSConstants.QUEUE;
        qConFac = (QueueConnectionFactory) connectionFactory;

    } else if (JMSConstants.DESTINATION_TYPE_TOPIC.equals(destinationType)) {
        destType = JMSConstants.TOPIC;
        tConFac = (TopicConnectionFactory) connectionFactory;
    } else {
        //treat jmsdestination type=queue(default is queue)
        destType = JMSConstants.QUEUE;
        qConFac = (QueueConnectionFactory) connectionFactory;
    }

    Connection connection = null;
    if (user != null && pass != null) {
        if (qConFac != null) {
            connection = qConFac.createQueueConnection(user, pass);
        } else if (tConFac != null) {
            connection = tConFac.createTopicConnection(user, pass);
        }
    } else {
        if (qConFac != null) {
            connection = qConFac.createQueueConnection();
        } else if (tConFac != null) {
            connection = tConFac.createTopicConnection();
        }
    }

    if (connection == null) {
        connection = jmsConnectionFactory != null ? jmsConnectionFactory.getConnection() : null;
    }

    Session session = null;
    MessageProducer producer = null;

    if (connection != null) {
        if (destType == JMSConstants.QUEUE) {
            session = ((QueueConnection) connection).createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            producer = ((QueueSession) session).createSender((Queue) destination);
        } else {
            session = ((TopicConnection) connection).createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
            producer = ((TopicSession) session).createPublisher((Topic) destination);
        }
    }

    return new JMSMessageSender(connection, session, producer, destination,
            jmsConnectionFactory == null ? JMSConstants.CACHE_NONE : jmsConnectionFactory.getCacheLevel(),
            false, destType == -1 ? null : destType == JMSConstants.QUEUE ? Boolean.TRUE : Boolean.FALSE);

}

From source file:com.web.server.EJBDeployer.java

@Override
public void run() {
    EJBJarFileListener jarFileListener = new EJBJarFileListener(registry, this.servicesRegistryPort, jarEJBMap,
            jarMDBMap, jms, connectionFactory);
    DefaultFileMonitor fm = new DefaultFileMonitor(jarFileListener);
    FileObject listendir = null;//from  ww  w .j  a va 2s  . c om
    StandardFileSystemManager fsManager = new StandardFileSystemManager();
    String[] dirsToScan = scanDirectory.split(";");
    EJBContext ejbContext;
    try {
        File scanDirFile = new File(dirsToScan[0]);
        File[] scanJarFiles = scanDirFile.listFiles();
        System.out.println("SCANDIRECTORY=" + scanDirectory);
        if (scanJarFiles != null) {
            for (File scanJarFile : scanJarFiles) {
                if (scanJarFile.isFile() && scanJarFile.getAbsolutePath().endsWith(".jar")) {
                    URLClassLoader classLoader = new URLClassLoader(
                            new URL[] { new URL("file:///" + scanJarFile.getAbsolutePath()) },
                            Thread.currentThread().getContextClassLoader());
                    ConfigurationBuilder config = new ConfigurationBuilder();
                    config.addUrls(ClasspathHelper.forClassLoader(classLoader));
                    config.addClassLoader(classLoader);
                    org.reflections.Reflections reflections = new org.reflections.Reflections(config);
                    EJBContainer container = EJBContainer
                            .getInstance("file:///" + scanJarFile.getAbsolutePath(), config);
                    container.inject();
                    Set<Class<?>> cls = reflections.getTypesAnnotatedWith(Stateless.class);
                    Set<Class<?>> clsMessageDriven = reflections.getTypesAnnotatedWith(MessageDriven.class);
                    Object obj;
                    System.gc();
                    if (cls.size() > 0) {
                        ejbContext = new EJBContext();
                        ejbContext.setJarPath(scanJarFile.getAbsolutePath());
                        ejbContext.setJarDeployed(scanJarFile.getName());
                        for (Class<?> ejbInterface : cls) {
                            //BeanPool.getInstance().create(ejbInterface);
                            obj = BeanPool.getInstance().get(ejbInterface);
                            System.out.println(obj);
                            ProxyFactory factory = new ProxyFactory();
                            obj = UnicastRemoteObject.exportObject((Remote) factory.createWithBean(obj),
                                    servicesRegistryPort);
                            String remoteBinding = container.getRemoteBinding(ejbInterface);
                            System.out.println(remoteBinding + " for EJB" + obj);
                            if (remoteBinding != null) {
                                //registry.unbind(remoteBinding);
                                registry.rebind(remoteBinding, (Remote) obj);
                                ejbContext.put(remoteBinding, obj.getClass());
                            }
                            //registry.rebind("name", (Remote) obj);
                        }
                        jarEJBMap.put("file:///" + scanJarFile.getAbsolutePath().replace("\\", "/"),
                                ejbContext);
                    }
                    System.out.println("Class Message Driven" + clsMessageDriven);
                    if (clsMessageDriven.size() > 0) {
                        System.out.println("Class Message Driven");
                        MDBContext mdbContext;
                        ConcurrentHashMap<String, MDBContext> mdbContexts;
                        if (jarMDBMap.get(scanJarFile.getAbsolutePath()) != null) {
                            mdbContexts = jarMDBMap.get(scanJarFile.getAbsolutePath());
                        } else {
                            mdbContexts = new ConcurrentHashMap<String, MDBContext>();
                        }
                        jarMDBMap.put("file:///" + scanJarFile.getAbsolutePath().replace("\\", "/"),
                                mdbContexts);
                        MDBContext mdbContextOld;
                        for (Class<?> mdbBean : clsMessageDriven) {
                            String classwithpackage = mdbBean.getName();
                            System.out.println("class package" + classwithpackage);
                            classwithpackage = classwithpackage.replace("/", ".");
                            System.out.println("classList:" + classwithpackage.replace("/", "."));
                            try {
                                if (!classwithpackage.contains("$")) {
                                    //System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
                                    //System.out.println();
                                    if (!mdbBean.isInterface()) {
                                        Annotation[] classServicesAnnot = mdbBean.getDeclaredAnnotations();
                                        if (classServicesAnnot != null) {
                                            for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) {
                                                if (classServicesAnnot[annotcount] instanceof MessageDriven) {
                                                    MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount];
                                                    ActivationConfigProperty[] activationConfigProperties = messageDrivenAnnot
                                                            .activationConfig();
                                                    mdbContext = new MDBContext();
                                                    mdbContext.setMdbName(messageDrivenAnnot.name());
                                                    for (ActivationConfigProperty activationConfigProperty : activationConfigProperties) {
                                                        if (activationConfigProperty.propertyName()
                                                                .equals(MDBContext.DESTINATIONTYPE)) {
                                                            mdbContext.setDestinationType(
                                                                    activationConfigProperty.propertyValue());
                                                        } else if (activationConfigProperty.propertyName()
                                                                .equals(MDBContext.DESTINATION)) {
                                                            mdbContext.setDestination(
                                                                    activationConfigProperty.propertyValue());
                                                        } else if (activationConfigProperty.propertyName()
                                                                .equals(MDBContext.ACKNOWLEDGEMODE)) {
                                                            mdbContext.setAcknowledgeMode(
                                                                    activationConfigProperty.propertyValue());
                                                        }
                                                    }
                                                    if (mdbContext.getDestinationType()
                                                            .equals(Queue.class.getName())) {
                                                        mdbContextOld = null;
                                                        if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                            mdbContextOld = mdbContexts
                                                                    .get(mdbContext.getMdbName());
                                                            if (mdbContextOld != null
                                                                    && mdbContext.getDestination().equals(
                                                                            mdbContextOld.getDestination())) {
                                                                throw new Exception(
                                                                        "Only one MDB can listen to destination:"
                                                                                + mdbContextOld
                                                                                        .getDestination());
                                                            }
                                                        }
                                                        mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                        Queue queue = (Queue) jms
                                                                .lookup(mdbContext.getDestination());
                                                        Connection connection = connectionFactory
                                                                .createConnection("guest", "guest");
                                                        connection.start();
                                                        Session session;
                                                        if (mdbContext.getAcknowledgeMode() != null
                                                                && mdbContext.getAcknowledgeMode()
                                                                        .equals("Auto-Acknowledge")) {
                                                            session = connection.createSession(false,
                                                                    Session.AUTO_ACKNOWLEDGE);
                                                        } else {
                                                            session = connection.createSession(false,
                                                                    Session.AUTO_ACKNOWLEDGE);
                                                        }
                                                        MessageConsumer consumer = session
                                                                .createConsumer(queue);
                                                        consumer.setMessageListener(
                                                                (MessageListener) mdbBean.newInstance());
                                                        mdbContext.setConnection(connection);
                                                        mdbContext.setSession(session);
                                                        mdbContext.setConsumer(consumer);
                                                        System.out.println("Queue=" + queue);
                                                    } else if (mdbContext.getDestinationType()
                                                            .equals(Topic.class.getName())) {
                                                        if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                            mdbContextOld = mdbContexts
                                                                    .get(mdbContext.getMdbName());
                                                            if (mdbContextOld.getConsumer() != null)
                                                                mdbContextOld.getConsumer()
                                                                        .setMessageListener(null);
                                                            if (mdbContextOld.getSession() != null)
                                                                mdbContextOld.getSession().close();
                                                            if (mdbContextOld.getConnection() != null)
                                                                mdbContextOld.getConnection().close();
                                                        }
                                                        mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                        Topic topic = (Topic) jms
                                                                .lookup(mdbContext.getDestination());
                                                        Connection connection = connectionFactory
                                                                .createConnection("guest", "guest");
                                                        connection.start();
                                                        Session session;
                                                        if (mdbContext.getAcknowledgeMode() != null
                                                                && mdbContext.getAcknowledgeMode()
                                                                        .equals("Auto-Acknowledge")) {
                                                            session = connection.createSession(false,
                                                                    Session.AUTO_ACKNOWLEDGE);
                                                        } else {
                                                            session = connection.createSession(false,
                                                                    Session.AUTO_ACKNOWLEDGE);
                                                        }
                                                        MessageConsumer consumer = session
                                                                .createConsumer(topic);
                                                        consumer.setMessageListener(
                                                                (MessageListener) mdbBean.newInstance());
                                                        mdbContext.setConnection(connection);
                                                        mdbContext.setSession(session);
                                                        mdbContext.setConsumer(consumer);
                                                        System.out.println("Topic=" + topic);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }
                    classLoader.close();
                    System.out.println(scanJarFile.getAbsolutePath() + " Deployed");
                }
            }
        }
        FileSystemOptions opts = new FileSystemOptions();
        FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
        fsManager.init();
        for (String dir : dirsToScan) {
            if (dir.startsWith("ftp://")) {
                listendir = fsManager.resolveFile(dir, opts);
            } else {
                listendir = fsManager.resolveFile(dir);
            }
            fm.addFile(listendir);
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    fm.setRecursive(true);
    fm.setDelay(1000);
    fm.start();
}

From source file:org.apache.camel.component.jms.JmsConfiguration.java

/**
 * Creates a {@link JmsOperations} object used for request/response using a request timeout value
 *//*w w w. ja v  a  2s .c om*/
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);
        if (timeToLive < 0) {
            // If TTL not specified, then default to
            jmsTemplate.setTimeToLive(requestTimeout);
        }
        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.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testTopicNonPersistentMessageSize() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.setClientID("clientId");
    connection.start();//ww w .ja v  a 2s . c o m
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(session.createTopic(defaultTopicName));

    publishTestTopicMessages(200, DeliveryMode.NON_PERSISTENT, publishedMessageSize);

    verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get());

    // consume all messages
    consumeTestMessages(consumer, 200);

    // All messages should now be gone
    verifyPendingStats(defaultTopicName, 0, 0);

    connection.close();
}

From source file:com.chinamobile.bcbsp.comm.ConsumerTool.java

/** Set ackMode state. */
public void setAckMode(String ackMode) {
    if ("CLIENT_ACKNOWLEDGE".equals(ackMode)) {
        this.ackMode = Session.CLIENT_ACKNOWLEDGE;
    }//from w w  w . ja  v a  2s.  c o  m
    if ("AUTO_ACKNOWLEDGE".equals(ackMode)) {
        this.ackMode = Session.AUTO_ACKNOWLEDGE;
    }
    if ("DUPS_OK_ACKNOWLEDGE".equals(ackMode)) {
        this.ackMode = Session.DUPS_OK_ACKNOWLEDGE;
    }
    if ("SESSION_TRANSACTED".equals(ackMode)) {
        this.ackMode = Session.SESSION_TRANSACTED;
    }
}

From source file:org.apache.synapse.transport.jms.JMSConnectionFactory.java

/**
 * Listen on the given destination from this connection factory. Used to
 * start listening on a destination associated with a newly deployed service
 *
 * @param destinationJNDIname the JMS destination to listen on
 */// w  w  w  .  j a  va 2s  .  co  m
public void startListeningOnDestination(String destinationJNDIname, String destinationType) {

    Session session = (Session) jmsSessions.get(destinationJNDIname);
    // if we already had a session open, close it first
    if (session != null) {
        try {
            session.close();
        } catch (JMSException ignore) {
        }
    }

    try {
        session = JMSUtils.createSession(connection, false, Session.AUTO_ACKNOWLEDGE, destinationType);
        Destination destination = null;

        try {
            destination = (Destination) context.lookup(destinationJNDIname);

        } catch (NameNotFoundException e) {
            log.warn("Cannot find destination : " + destinationJNDIname + ". Creating a Queue");
            destination = JMSUtils.createDestination(session, destinationJNDIname, destinationType);
        }

        MessageConsumer consumer = JMSUtils.createConsumer(session, destination);
        consumer.setMessageListener(jmsMessageReceiver);
        jmsSessions.put(destinationJNDIname, session);

        // catches NameNotFound and JMSExceptions and marks service as faulty    
    } catch (Exception e) {
        if (session != null) {
            try {
                session.close();
            } catch (JMSException ignore) {
            }
        }

        BaseUtils.markServiceAsFaulty((String) serviceJNDINameMapping.get(destinationJNDIname),
                "Error looking up JMS destination : " + destinationJNDIname, cfgCtx.getAxisConfiguration());
    }
}

From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java

private void sendMessage(BrokerService brokerService, String body) throws Exception {
    TransportConnector connector = brokerService.getTransportConnectors().get(0);
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connector.getConnectUri());
    Connection connection = factory.createConnection();
    try {/*  w w w . j  av  a2s  .  c  o m*/
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(session.createQueue("FOO"));
        producer.send(session.createTextMessage(body));
    } finally {
        connection.close();
    }
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testTopicPersistentAndNonPersistentMessageSize() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();
    AtomicLong publishedNonPersistentMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.setClientID("clientId");
    connection.start();//from  w  w  w  .  j a v a  2s. c o m
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(session.createTopic(defaultTopicName));

    publishTestTopicMessages(100, DeliveryMode.NON_PERSISTENT, publishedNonPersistentMessageSize);
    publishTestTopicMessages(100, DeliveryMode.PERSISTENT, publishedMessageSize);

    verifyPendingStats(defaultTopicName, 200,
            publishedMessageSize.get() + publishedNonPersistentMessageSize.get());

    // consume all messages
    consumeTestMessages(consumer, 200);

    // All messages should now be gone
    verifyPendingStats(defaultTopicName, 0, 0);

    connection.close();
}

From source file:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java

@Override
public boolean sendMessage(Run<?, ?> build, TaskListener listener, MessageUtils.MESSAGE_TYPE type, String props,
        String content) {/*from w w w .  j a  va  2  s .c  om*/
    Connection connection = null;
    Session session = null;
    MessageProducer publisher = null;

    try {
        String ltopic = getTopic();
        if (provider.getAuthenticationMethod() != null && ltopic != null && provider.getBroker() != null) {
            ActiveMQConnectionFactory connectionFactory = provider.getConnectionFactory();
            connection = connectionFactory.createConnection();
            connection.start();

            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createTopic(ltopic);
            publisher = session.createProducer(destination);

            TextMessage message;
            message = session.createTextMessage("");
            message.setJMSType(JSON_TYPE);

            message.setStringProperty("CI_NAME", build.getParent().getName());
            message.setStringProperty("CI_TYPE", type.getMessage());
            if (!build.isBuilding()) {
                message.setStringProperty("CI_STATUS",
                        (build.getResult() == Result.SUCCESS ? "passed" : "failed"));
            }

            StrSubstitutor sub = new StrSubstitutor(build.getEnvironment(listener));

            if (props != null && !props.trim().equals("")) {
                Properties p = new Properties();
                p.load(new StringReader(props));
                @SuppressWarnings("unchecked")
                Enumeration<String> e = (Enumeration<String>) p.propertyNames();
                while (e.hasMoreElements()) {
                    String key = e.nextElement();
                    message.setStringProperty(key, sub.replace(p.getProperty(key)));
                }
            }

            message.setText(sub.replace(content));

            publisher.send(message);
            log.info("Sent " + type.toString() + " message for job '" + build.getParent().getName()
                    + "' to topic '" + ltopic + "':\n" + formatMessage(message));
        } else {
            log.severe("One or more of the following is invalid (null): user, password, topic, broker.");
            return false;
        }

    } catch (Exception e) {
        log.log(Level.SEVERE, "Unhandled exception in perform.", e);
    } finally {
        if (publisher != null) {
            try {
                publisher.close();
            } catch (JMSException e) {
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
            }
        }
    }
    return true;
}