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.apache.activemq.network.BrokerNetworkWithStuckMessagesTest.java

@SuppressWarnings({ "unchecked", "unused" })
private Object[] browseQueueWithJms(BrokerService broker) throws Exception {
    Object[] messages = null;//from   www . j  a  v a2s  .  co  m
    Connection connection = null;
    Session session = null;

    try {
        URI brokerUri = connector.getUri();
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUri.toString());
        connection = connectionFactory.createConnection();
        connection.start();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue destination = session.createQueue(queueName);
        QueueBrowser browser = session.createBrowser(destination);
        List<Message> list = new ArrayList<Message>();
        for (Enumeration<Message> enumn = browser.getEnumeration(); enumn.hasMoreElements();) {
            list.add(enumn.nextElement());
        }
        messages = list.toArray();
    } finally {
        if (session != null) {
            session.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
    LOG.info("+Browsed with JMS: " + messages.length);

    return messages;
}

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

/**
 * Helper method to establish one Connection and associated Session.
 *
 * @throws JMSException If some JMS error occurred during the creation of
 *                      the required JMS connection and session
 */// w  w  w.  j  av  a  2  s .  co m
private void establishConnectionAndSession() throws JMSException {
    // Establish a queue connection and a session
    connection = getConnectionFactory().createConnection();
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    connection.setExceptionListener(this);
    connection.start();
}

From source file:org.gss_project.gss.server.ejb.AdminAPIBean.java

public void indexFile(Long fileId, boolean delete) {
    Connection qConn = null;/*  ww  w.j  av  a  2  s  .  c  om*/
    Session session = null;
    MessageProducer sender = null;
    try {
        Context jndiCtx = new InitialContext();
        ConnectionFactory factory = (QueueConnectionFactory) jndiCtx.lookup("java:/JmsXA");
        Queue queue = (Queue) jndiCtx.lookup("queue/gss-indexingQueue");
        qConn = factory.createConnection();
        session = qConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        sender = session.createProducer(queue);

        MapMessage map = session.createMapMessage();
        map.setObject("id", fileId);
        map.setBoolean("delete", delete);
        sender.send(map);
    } catch (NamingException e) {
        logger.error("Index was not updated: ", e);
    } catch (JMSException e) {
        logger.error("Index was not updated: ", e);
    } finally {
        try {
            if (sender != null)
                sender.close();
            if (session != null)
                session.close();
            if (qConn != null)
                qConn.close();
        } catch (JMSException e) {
            logger.warn(e);
        }
    }
}

From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java

protected synchronized String config(ServletContext context) {
    String error = null;//from   w  w w . jav  a2 s  .c o  m
    try {
        props = loadConfig();
        // default output format
        formatDefault = props.getProperty("format.default");

        // editor backup save dir
        backupDir = props.getProperty("edit.backupDir");

        // identifiers/namespaces
        minterDefault = props.getProperty("minters.default");
        idMinters = new HashMap<String, String>();
        String minterList = props.getProperty("minters.list");
        String[] minterNames = minterList.split(",");
        for (int i = 0; i < minterNames.length; i++) {
            idMinters.put(minterNames[i], props.getProperty("minters." + minterNames[i]));
        }
        nsmap = TripleStoreUtil.namespaceMap(props);
        idNS = nsmap.get("damsid");
        prNS = nsmap.get("dams");
        rdfNS = nsmap.get("rdf");
        madsNS = nsmap.get("mads");

        // load valid class/predicate lists
        validClasses = loadSet(context, "/WEB-INF/valid-classes.txt");
        validProperties = loadSet(context, "/WEB-INF/valid-properties.txt");

        // xslt config
        encodingDefault = props.getProperty("solr.encoding");
        xslBase = context.getRealPath("/WEB-INF/xsl") + File.separatorChar;
        log.info("Fedora xsl files directory: " + xslBase);

        // access control
        localCopyright = props.getProperty("role.localCopyright");
        roleDefault = props.getProperty("role.default");
        roleLocal = props.getProperty("role.local");
        roleAdmin = props.getProperty("role.admin");
        roleAdmin2 = props.getProperty("role.admin2");
        roleSuper = props.getProperty("role.super");
        String roleList = props.getProperty("role.list");
        String[] roles = roleList.split(",");
        roleMap = new TreeMap<String, String[]>();
        try {
            for (int i = 0; i < roles.length; i++) {
                String ipList = props.getProperty("role." + roles[i] + ".iplist");
                String[] ipArray = ipList.split(",");
                roleMap.put(roles[i], ipArray);
            }
        } catch (Exception ex) {
            log.error("Error parsing roles: " + ex.toString(), ex);
        }

        // triplestores
        tsDefault = props.getProperty("ts.default");
        tsEvents = props.getProperty("ts.events");

        // files
        fsDefault = props.getProperty("fs.default");
        fsStaging = props.getProperty("fs.staging");
        maxUploadCount = getPropInt(props, "fs.maxUploadCount", -1);
        maxUploadSize = getPropLong(props, "fs.maxUploadSize", -1L);
        fsUseMap = new HashMap<String, String>();
        for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
            String key = (String) e.nextElement();
            if (key != null && key.startsWith("fs.usemap.")) {
                String ext = key.substring(10);
                String use = props.getProperty(key);
                if (use != null) {
                    fsUseMap.put(ext, use);
                }
            }
        }

        // fedora compat
        fedoraObjectDS = props.getProperty("fedora.objectDS");
        fedoraRightsDS = props.getProperty("fedora.rightsDS");
        fedoraLinksDS = props.getProperty("fedora.linksDS");
        fedoraSystemDS = props.getProperty("fedora.systemDS");
        sampleObject = props.getProperty("fedora.samplePID");
        adminEmail = props.getProperty("fedora.adminEmail");
        fedoraCompat = props.getProperty("fedora.compatVersion");
        if (props.getProperty("fedora.debug") != null) {
            fedoraDebug = props.getProperty("fedora.debug").equals("true");
        }

        // derivative list
        derivativesExt = props.getProperty("derivatives.ext");
        String derList = props.getProperty("derivatives.list");
        derivativesRes = new HashMap<String, String>();
        derivativesUse = new HashMap<String, String>();
        loadDerivativesConfig(derList, derivativesRes, derivativesUse);

        // video derivative list
        String derVideoList = props.getProperty("derivatives.video.list");
        videoDerivativesRes = new HashMap<String, String>();
        videoDerivativesUse = new HashMap<String, String>();
        loadDerivativesConfig(derVideoList, videoDerivativesRes, videoDerivativesUse);

        // ImageMagick convert command
        magickCommand = props.getProperty("magick.convert");
        if (magickCommand == null)
            magickCommand = "convert";

        // Ffmpeg convert command
        ffmpegCommand = props.getProperty("ffmpeg");
        if (ffmpegCommand == null)
            ffmpegCommand = "ffmpeg";

        // Jhove configuration
        String jhoveConf = props.getProperty("jhove.conf");
        if (jhoveConf != null)
            MyJhoveBase.setJhoveConfig(jhoveConf);
        // Jhove zip model configuration
        String jhoveZipModelCommand = props.getProperty("jhove.zipModel.command");
        if (StringUtils.isNotBlank(jhoveZipModelCommand))
            MyJhoveBase.setZipModelCommand(jhoveZipModelCommand);
        // Jhove gzip model configuration
        String jhoveGzipModelCommand = props.getProperty("jhove.gzipModel.command");
        if (StringUtils.isNotBlank(jhoveGzipModelCommand))
            MyJhoveBase.setGzipModelCommand(jhoveGzipModelCommand);

        jhoveMaxSize = getPropLong(props, "jhove.maxSize", -1L);

        // ldap for group lookup
        ldaputil = new LDAPUtil(props);

        // cache size
        cacheSize = getPropInt(props, "ts.cacheSize", 0);
        cacheClear(); // clear cache

        // queue
        queueUrl = props.getProperty("queue.url");
        queueName = props.getProperty("queue.name");
        if (queueEnabled && queueUrl != null) {
            try {
                queueConnectionFactory = new ActiveMQConnectionFactory(queueUrl);
                queueConnection = queueConnectionFactory.createConnection();
                queueConnection.start();
                queueSession = queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                queueProducer = queueSession.createProducer(queueSession.createTopic(queueName));
                queueProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
                log.info("JMS Queue: " + queueUrl + "/" + queueName);
            } catch (Exception ex) {
                log.error("Error initializing JMS queue: " + ex.toString(), ex);
            }
        }

        // doi minter
        ezidTargetUrl = props.getProperty("ezid.target.url");
        String ezidHost = props.getProperty("ezid.host");
        String ezidShoulder = props.getProperty("ezid.shoulder");
        String ezidUser = props.getProperty("ezid.user");
        String ezidPass = props.getProperty("ezid.pass");
        if (ezidHost != null && ezidShoulder != null && ezidUser != null && ezidPass != null) {
            ezid = new Ezid(ezidHost, ezidShoulder, ezidUser, ezidPass);
        } else {
            ezid = null;
        }

        // ffmpeg codec params for derivative creation
        ffmpegCodecParamsMap = new HashMap<String, String>();
        String ffmpegCodecParams = props.getProperty("ffmpeg.codec.params");
        if (StringUtils.isNotBlank(ffmpegCodecParams)) {
            String[] codecParams = ffmpegCodecParams.split("\\;");
            for (String codecParam : codecParams) {
                String[] keyValPair = codecParam.trim().split("\\|");
                ffmpegCodecParamsMap.put(keyValPair[0].trim(), keyValPair[1]);
            }
        }
    } catch (Exception ex) {
        log.error("Error initializing", ex);
        error = ex.toString();
    }

    return error;
}

From source file:org.wso2.carbon.andes.core.QueueManagerServiceImpl.java

/**
 * Publish message to given JMS queue/* www . j  a v a2s. c o m*/
 *
 * @param nameOfQueue queue name
 * @param userName username
 * @param accessKey access key
 * @param jmsType jms type
 * @param jmsCorrelationID message correlation id
 * @param numberOfMessages number of messages to publish
 * @param message message body
 * @param deliveryMode delivery mode
 * @param priority message priority
 * @param expireTime message expire time
 * @throws QueueManagerException
 */
private void send(String nameOfQueue, String userName, String accessKey, String jmsType,
        String jmsCorrelationID, int numberOfMessages, String message, int deliveryMode, int priority,
        long expireTime) throws QueueManagerException {
    QueueConnectionFactory connFactory;
    QueueConnection queueConnection = null;
    QueueSession queueSession = null;
    QueueSender queueSender = null;
    try {
        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, ANDES_ICF);
        properties.put(CF_NAME_PREFIX + CF_NAME, Utils.getTCPConnectionURL(userName, accessKey));
        properties.put(QUEUE_NAME_PREFIX + nameOfQueue, nameOfQueue);
        properties.put(CarbonConstants.REQUEST_BASE_CONTEXT, "true");
        InitialContext ctx = new InitialContext(properties);
        connFactory = (QueueConnectionFactory) ctx.lookup(CF_NAME);
        queueConnection = connFactory.createQueueConnection();
        Queue queue = (Queue) ctx.lookup(nameOfQueue);
        queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queueSender = queueSession.createSender(queue);
        queueConnection.start();
        TextMessage textMessage = queueSession.createTextMessage();
        if (queueSender != null && textMessage != null) {
            if (jmsType != null) {
                textMessage.setJMSType(jmsType);
            }
            if (jmsCorrelationID != null) {
                textMessage.setJMSCorrelationID(jmsCorrelationID);
            }

            if (message != null) {
                textMessage.setText(message);
            } else {
                textMessage.setText("Type message here..");
            }

            for (int i = 0; i < numberOfMessages; i++) {
                queueSender.send(textMessage, deliveryMode, priority, expireTime);
            }
        }
    } catch (FileNotFoundException | NamingException | UnknownHostException | XMLStreamException
            | JMSException e) {
        throw new QueueManagerException("Unable to send message.", e);
    } finally {
        try {
            if (queueConnection != null) {
                queueConnection.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue connection", e);
        }
        try {
            if (queueSession != null) {
                queueSession.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue session", e);
        }
        try {
            if (queueSender != null) {
                queueSender.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue sender", e);
        }
    }
}

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

protected Collection<StatusBean> getStatusBeans(final URI uri, final String queueName,
        final IProgressMonitor monitor) throws Exception {

    QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    monitor.worked(1);//from   w  ww  .  j  a  va2 s .c  o  m
    QueueConnection qCon = connectionFactory.createQueueConnection(); // This times out when the server is not there.
    QueueSession qSes = qCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = qSes.createQueue(queueName);
    qCon.start();

    QueueBrowser qb = qSes.createBrowser(queue);
    monitor.worked(1);

    @SuppressWarnings("rawtypes")
    Enumeration e = qb.getEnumeration();

    Class clazz = getBeanClass();
    ObjectMapper mapper = new ObjectMapper();

    final Collection<StatusBean> list = new TreeSet<StatusBean>(new Comparator<StatusBean>() {
        @Override
        public int compare(StatusBean o1, StatusBean o2) {
            // Newest first!
            long t1 = o2.getSubmissionTime();
            long t2 = o1.getSubmissionTime();
            return (t1 < t2 ? -1 : (t1 == t2 ? 0 : 1));
        }
    });

    while (e.hasMoreElements()) {
        Message m = (Message) e.nextElement();
        if (m == null)
            continue;
        if (m instanceof TextMessage) {
            TextMessage t = (TextMessage) m;
            final StatusBean bean = mapper.readValue(t.getText(), clazz);
            list.add(bean);
        }
    }
    return list;
}

From source file:org.gss_project.gss.server.ejb.ExternalAPIBean.java

private void indexFile(Long fileId, boolean delete) {
     Connection qConn = null;//from   w  w w. ja  va  2  s .  c o m
     Session session = null;
     MessageProducer sender = null;
     try {
         Context jndiCtx = new InitialContext();
         ConnectionFactory factory = (QueueConnectionFactory) jndiCtx.lookup("java:/JmsXA");
         Queue queue = (Queue) jndiCtx.lookup("queue/gss-indexingQueue");
         qConn = factory.createConnection();
         session = qConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
         sender = session.createProducer(queue);

         MapMessage map = session.createMapMessage();
         map.setObject("id", fileId);
         map.setBoolean("delete", delete);
         sender.send(map);
     } catch (NamingException e) {
         logger.error("Index was not updated: ", e);
     } catch (JMSException e) {
         logger.error("Index was not updated: ", e);
     } finally {
         try {
             if (sender != null)
                 sender.close();
             if (session != null)
                 session.close();
             if (qConn != null)
                 qConn.close();
         } catch (JMSException e) {
             logger.warn(e);
         }
     }
 }

From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java

/**
 * Purge destinations for clean test setup. Especially applicable to WMQ tests, as messages from
 * other tests may still exist from other tests' runs.
 * <p/>//from   w w w. j  a v a  2  s  .co m
 * Well-behaving tests should drain both inbound and outbound destinations, as well as any intermediary ones.
 * @param destination destination name without any protocol specifics
 */
protected void purge(final String destination) throws JMSException {
    Connection c = null;
    Session s = null;
    try {
        logger.debug("purging queue : " + destination);
        c = getConnection(false, false);
        assertNotNull(c);
        c.start();

        s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination d = s.createQueue(destination);
        MessageConsumer consumer = s.createConsumer(d);

        while (consumer.receiveNoWait() != null) {
            logger.debug("Destination " + destination + " isn't empty, draining it");
        }
    } catch (Exception e) {
        logger.error("unable to purge : " + destination);
    } finally {
        if (c != null) {
            c.stop();
            if (s != null) {
                s.close();
            }
            try {
                c.close();
            } catch (JMSException e) {
                logger.warn("Failed to close jms connection: " + e.getMessage());
            }
        }
    }
}

From source file:nl.nn.adapterframework.extensions.ifsa.jms.IfsaFacade.java

public void setAcknowledgeMode(String acknowledgeMode) {

    if (acknowledgeMode.equalsIgnoreCase("auto") || acknowledgeMode.equalsIgnoreCase("AUTO_ACKNOWLEDGE")) {
        ackMode = Session.AUTO_ACKNOWLEDGE;
    } else if (acknowledgeMode.equalsIgnoreCase("dups")
            || acknowledgeMode.equalsIgnoreCase("DUPS_OK_ACKNOWLEDGE")) {
        ackMode = Session.DUPS_OK_ACKNOWLEDGE;
    } else if (acknowledgeMode.equalsIgnoreCase("client")
            || acknowledgeMode.equalsIgnoreCase("CLIENT_ACKNOWLEDGE")) {
        ackMode = Session.CLIENT_ACKNOWLEDGE;
    } else {//from  w ww .j a  v a2 s  .co  m
        // ignore all ack modes, to test no acking
        log.warn("[" + name + "] invalid acknowledgemode:[" + acknowledgeMode + "] setting no acknowledge");
        ackMode = -1;
    }

}

From source file:org.codehaus.stomp.StompTest.java

protected void setUp() throws Exception {
    connectionFactory = createConnectionFactory();
    stompConnect = new StompConnect(connectionFactory);
    stompConnect.setUri("tcp://localhost:" + port);
    stompConnect.start();//  w  ww . j a va 2  s.c o  m

    stompSocket = createSocket();
    inputBuffer = new ByteArrayOutputStream();

    connection = connectionFactory.createConnection();
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    queue = session.createQueue(getQueueName());
    connection.start();
}