Example usage for javax.jms QueueConnection start

List of usage examples for javax.jms QueueConnection start

Introduction

In this page you can find the example usage for javax.jms QueueConnection start.

Prototype


void start() throws JMSException;

Source Link

Document

Starts (or restarts) a connection's delivery of incoming messages.

Usage

From source file:org.dawnsci.commandserver.mx.example.ActiveMQProducer.java

public static void main(String[] args) throws Exception {

    QueueConnectionFactory connectionFactory = ConnectionFactoryFacade
            .createConnectionFactory("tcp://ws097.diamond.ac.uk:61616");
    Connection send = connectionFactory.createConnection();

    Session session = send.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue("testQ");

    final MessageProducer producer = session.createProducer(queue);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);

    Message message = session.createTextMessage("Hello World");
    producer.send(message);/*from   w w  w  . ja va2  s  . c o m*/

    message = session.createTextMessage("...and another message");
    producer.send(message);

    message = session.createObjectMessage(new TestObjectBean("this could be", "anything"));
    producer.send(message);

    // Test JSON
    SweepBean col = new SweepBean("fred", "d0000000001", 0, 100);

    ObjectMapper mapper = new ObjectMapper();
    String jsonString = mapper.writeValueAsString(col);

    message = session.createTextMessage(jsonString);
    producer.send(message);

    producer.close();
    session.close();
    send.close();

    // Now we peak at the queue
    // If the consumer is not going, the messages should still be there
    if (REQUIRE_PEAK) {
        QueueConnection qCon = connectionFactory.createQueueConnection();
        QueueSession qSes = qCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queue = qSes.createQueue("testQ");
        qCon.start();

        QueueBrowser qb = qSes.createBrowser(queue);
        Enumeration e = qb.getEnumeration();
        if (e.hasMoreElements())
            System.out.println("Peak at queue:");
        while (e.hasMoreElements()) {
            Message m = (Message) e.nextElement();
            if (m == null)
                continue;
            if (m instanceof TextMessage) {
                TextMessage t = (TextMessage) m;
                System.out.println(t.getText());
            } else if (m instanceof ObjectMessage) {
                ObjectMessage o = (ObjectMessage) m;
                System.out.println(o.getObject());
            }
        }

        qb.close();
        qSes.close();
        qCon.close();
    }

}

From source file:io.datalayer.activemq.consumer.SimpleQueueReceiver.java

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

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

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

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

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

From source file:org.panksdmz.jms.tibco.MessageRecieverBean.java

public void recieve() {
    try {//  w w  w  .j  a  va  2s .  c  o m
        QueueConnection connection = connectionFactory.createQueueConnection();
        QueueSession session = connection.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(this.recieveQueueName);
        QueueReceiver receiver = session.createReceiver(queue);
        connection.start();

        Message receive = receiver.receive();

        System.out.println(receive);

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

From source file:org.dawnsci.commandserver.core.consumer.RemoteSubmission.java

/**
 * Monitors a given bean in the status queue. 
 * If the bean is not there throws exception.
 * If the bean is in a final state, returns the bean straight away.
 * /* w w w.  j a  v a 2 s .  c o  m*/
 * Polls the queue for the unique id of the bean we want until it
 * encounters a final state of that bean.
 * 
 * Polling rate is less than 1s
 * 
 * NOTE this class can poll forever if the job it is looking at never finishes.
 * 
 * @param obean
 * @param string
 * @return the bean once it is in a final state.
 * @throws exception if broker or queue absent
 */
public StatusBean monitor(StatusBean obean) throws Exception {

    if (getQueueName() == null || "".equals(getQueueName()))
        throw new Exception("Please specify a queue name!");

    QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    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);

    Class clazz = obean.getClass();
    ObjectMapper mapper = new ObjectMapper();

    try {
        POLL: while (true) {

            Thread.sleep(500);

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

            while (e.hasMoreElements()) { // We must final the bean somewhere.
                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);
                    if (bean.getUniqueId().equals(obean.getUniqueId())) {
                        if (bean.getStatus().isFinal())
                            return bean;
                        System.out.println(bean.getPercentComplete());
                        continue POLL;
                    }
                }
            }

            throw new Exception(
                    "The bean with id " + obean.getUniqueId() + " does not exist in " + getQueueName() + "!");

        }
    } finally {
        qCon.close();
    }
}

From source file:com.legstar.mq.client.AbstractCicsMQ.java

/**
 * Create a JMS queue connection.//from w  w w.  jav  a2 s. com
 * <p/>
 * Starts the connection's delivery of incoming messages. (Messages will not
 * be received without this call).
 * 
 * @param userId for authentication
 * @param password for authentication
 * @return the new JMS queue connection
 * @throws CicsMQConnectionException if JMS queue connection cannot be
 *             created
 */
protected QueueConnection createQueueConnection(final String userId, final String password)
        throws CicsMQConnectionException {

    if (_log.isDebugEnabled()) {
        _log.debug("enter createQueueConnection()");
    }
    try {
        QueueConnectionFactory factory = (QueueConnectionFactory) getJndiContext()
                .lookup(getCicsMQEndpoint().getJndiConnectionFactoryName());
        if (factory == null) {
            throw new CicsMQConnectionException(
                    "JNDI lookup for " + getCicsMQEndpoint().getJndiConnectionFactoryName() + " failed");
        }
        QueueConnection connection = factory.createQueueConnection(userId, password);
        connection.start();
        return connection;
    } catch (NamingException e) {
        throw new CicsMQConnectionException(e);
    } catch (JMSException e) {
        throw new CicsMQConnectionException(e);
    }
}

From source file:org.dawnsci.commandserver.core.producer.ProcessConsumer.java

/**
 * Parse the queue for stale jobs and things that should be rerun.
 * @param bean/*from w  w w.j a  v a2  s.c  om*/
 * @throws Exception 
 */
private void processStatusQueue(URI uri, String statusQName) throws Exception {

    QueueConnection qCon = null;

    try {
        QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
        qCon = connectionFactory.createQueueConnection();
        QueueSession qSes = qCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = qSes.createQueue(statusQName);
        qCon.start();

        QueueBrowser qb = qSes.createBrowser(queue);

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

        ObjectMapper mapper = new ObjectMapper();

        Map<String, StatusBean> failIds = new LinkedHashMap<String, StatusBean>(7);
        List<String> removeIds = new ArrayList<String>(7);
        while (e.hasMoreElements()) {
            Message m = (Message) e.nextElement();
            if (m == null)
                continue;
            if (m instanceof TextMessage) {
                TextMessage t = (TextMessage) m;

                try {
                    @SuppressWarnings("unchecked")
                    final StatusBean qbean = mapper.readValue(t.getText(), getBeanClass());
                    if (qbean == null)
                        continue;
                    if (qbean.getStatus() == null)
                        continue;
                    if (!qbean.getStatus().isStarted()) {
                        failIds.put(t.getJMSMessageID(), qbean);
                        continue;
                    }

                    // If it has failed, we clear it up
                    if (qbean.getStatus() == Status.FAILED) {
                        removeIds.add(t.getJMSMessageID());
                        continue;
                    }
                    if (qbean.getStatus() == Status.NONE) {
                        removeIds.add(t.getJMSMessageID());
                        continue;
                    }

                    // If it is running and older than a certain time, we clear it up
                    if (qbean.getStatus() == Status.RUNNING) {
                        final long submitted = qbean.getSubmissionTime();
                        final long current = System.currentTimeMillis();
                        if (current - submitted > getMaximumRunningAge()) {
                            removeIds.add(t.getJMSMessageID());
                            continue;
                        }
                    }

                    if (qbean.getStatus().isFinal()) {
                        final long submitted = qbean.getSubmissionTime();
                        final long current = System.currentTimeMillis();
                        if (current - submitted > getMaximumCompleteAge()) {
                            removeIds.add(t.getJMSMessageID());
                        }
                    }

                } catch (Exception ne) {
                    System.out.println("Message " + t.getText() + " is not legal and will be removed.");
                    removeIds.add(t.getJMSMessageID());
                }
            }
        }

        // We fail the non-started jobs now - otherwise we could
        // actually start them late. TODO check this
        final List<String> ids = new ArrayList<String>();
        ids.addAll(failIds.keySet());
        ids.addAll(removeIds);

        if (ids.size() > 0) {

            for (String jMSMessageID : ids) {
                MessageConsumer consumer = qSes.createConsumer(queue, "JMSMessageID = '" + jMSMessageID + "'");
                Message m = consumer.receive(1000);
                if (removeIds.contains(jMSMessageID))
                    continue; // We are done

                if (m != null && m instanceof TextMessage) {
                    MessageProducer producer = qSes.createProducer(queue);
                    final StatusBean bean = failIds.get(jMSMessageID);
                    bean.setStatus(Status.FAILED);
                    producer.send(qSes.createTextMessage(mapper.writeValueAsString(bean)));

                    System.out.println("Failed job " + bean.getName() + " messageid(" + jMSMessageID + ")");

                }
            }
        }
    } finally {
        if (qCon != null)
            qCon.close();
    }

}

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);//w  ww . ja  va2  s. c om
    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.miloss.fgsms.bueller.Bueller.java

private String doJmsURL(boolean pooled, String endpoint) {
    try {/* w  ww  . j ava2  s  . co m*/

        boolean ok = false;
        String server = endpoint.split("#")[0];
        server = server.replace("jms:", "jnp://");
        String name = endpoint.split("#")[1];
        String msg = "";
        String[] info = DBSettingsLoader.GetCredentials(pooled, endpoint);
        String username = null;
        String password = null;
        if (info != null) {
            username = info[0];
            password = info[1];
        } else {
            info = DBSettingsLoader.GetDefaultBuellerCredentials(pooled);
            if (info != null) {
                username = info[0];
                password = info[1];
            }
        }

        if (name.startsWith("topic")) {
            try {
                Properties properties1 = new Properties();
                properties1.put(Context.INITIAL_CONTEXT_FACTORY,
                        "org.jnp.interfaces.NamingContextFactory");
                properties1.put(Context.URL_PKG_PREFIXES,
                        "org.jboss.naming:org.jnp.interfaces");
                //properties1.put(Context.PROVIDER_URL, "jnp://127.0.0.1:1099");
                properties1.put(Context.PROVIDER_URL, server);

                InitialContext iniCtx = new InitialContext(properties1);

                TopicConnectionFactory tcf = (TopicConnectionFactory) iniCtx.lookup("TopicConnectionFactory");
                TopicConnection createTopicConnection = null;
                if (info != null) {
                    createTopicConnection = tcf.createTopicConnection(username, Utility.DE(password)); //Topic topic = (Topic) iniCtx.lookup("/topic/quickstart_jmstopic_topic");
                } else {
                    createTopicConnection = tcf.createTopicConnection(); //Topic topic = (Topic) iniCtx.lookup("/topic/quickstart_jmstopic_topic");
                }
                createTopicConnection.start();
                createTopicConnection.stop();
                createTopicConnection.close();
                //Topic topic = (Topic) iniCtx.lookup("//" + name);
                ok = true;

                //topic = null;
                iniCtx.close();

            } catch (Exception ex) {
                System.out.println(ex);
                msg = ex.getLocalizedMessage();
                //return ex.getLocalizedMessage();
            }
        } else if (name.startsWith("queue")) {
            try {

                Properties properties1 = new Properties();
                properties1.put(Context.INITIAL_CONTEXT_FACTORY,
                        "org.jnp.interfaces.NamingContextFactory");
                properties1.put(Context.URL_PKG_PREFIXES,
                        "org.jboss.naming:org.jnp.interfaces");
                properties1.put(Context.PROVIDER_URL, server);
                InitialContext iniCtx = new InitialContext(properties1);
                QueueConnection conn;
                QueueSession session;
                Queue que;

                Object tmp = iniCtx.lookup("ConnectionFactory");
                QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
                if (info != null) {
                    conn = qcf.createQueueConnection(username, Utility.DE(password));
                } else {
                    conn = qcf.createQueueConnection();
                }

                que = (Queue) iniCtx.lookup(name);
                session = conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
                conn.start();

                //System.out.println("Connection Started");
                ok = true;

                conn.stop();
                session.close();
                iniCtx.close();

            } catch (Exception ex) {
                log.log(Level.WARN, "Could not bind to jms queue", ex);
                msg = ex.getLocalizedMessage();
            }
            if (ok) {
                return "OK";
            }
            return "Unable to bind to JMS queue: " + msg;
        } else {
            return "Unsupported Protocol";
        }
    } catch (Exception ex) {
        log.log(Level.WARN, "service " + endpoint + " is offline or an error occured", ex);
        return "Offline " + ex.getLocalizedMessage();
    }
    return "undeterminable";
}

From source file:org.apache.stratos.status.monitor.agent.clients.service.CEPServerClient.java

private static void executeService() throws SQLException {
    int serviceID = MySQLConnectionInitializer.getServiceID(StatusMonitorConstants.CEP);
    AuthConfigBean authConfigBean = StatusMonitorConfigurationBuilder.getAuthConfigBean();

    String userName = authConfigBean.getUserName();
    tcpUserName = userName.replace('@', '!');

    //check whether login success
    if (ServiceLoginClient.loginChecker(StatusMonitorConstants.CEP_HOST, serviceID)) {

        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, StatusMonitorAgentConstants.QPID_ICF);
        properties.put(StatusMonitorAgentConstants.CF_NAME_PREFIX + StatusMonitorAgentConstants.CF_NAME,
                getTCPConnectionURL(tcpUserName, authConfigBean.getPassword()));

        InitialContext ctx;/*from  w ww.  ja v  a 2  s .com*/
        try {
            ctx = new InitialContext(properties);

            // Lookup connection factory
            QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx
                    .lookup(StatusMonitorAgentConstants.CF_NAME);
            QueueConnection queueConnection = connFactory.createQueueConnection();
            queueConnection.start();
            QueueSession queueSession = queueConnection.createQueueSession(false,
                    QueueSession.AUTO_ACKNOWLEDGE);

            // Send message
            Queue queue = queueSession.createQueue(
                    StatusMonitorAgentConstants.QUEUE_NAME_CEP + ";{create:always, node:{durable: True}}");

            // create the message to send
            TextMessage textMessage = queueSession.createTextMessage("Test Message Hello");
            javax.jms.QueueSender queueSender = queueSession.createSender(queue);
            queueSender.setTimeToLive(100000000);

            QueueReceiver queueReceiver = queueSession.createReceiver(queue);
            queueSender.send(textMessage);

            TextMessage message = (TextMessage) queueReceiver.receiveNoWait();
            if (log.isDebugEnabled()) {
                log.debug("Message in the execute() of CEPServer Client: " + message.getText());
            }
            if (message.getText().equals("Test Message Hello")) {
                MySQLConnector.insertStats(serviceID, true);
                MySQLConnector.insertState(serviceID, true, "");
            } else {
                MySQLConnector.insertStats(serviceID, false);
                MySQLConnector.insertState(serviceID, false, "Send or retrieve messages failed");
            }
            queueSender.close();
            queueSession.close();
            queueConnection.close();

        } catch (JMSException e) {
            MySQLConnector.insertStats(serviceID, false);
            MySQLConnector.insertState(serviceID, false, e.getMessage());
            String msg = "JMS Exception in inserting stats into the DB for the CEPServerClient";
            log.warn(msg, e);
        } catch (NamingException e) {
            MySQLConnector.insertStats(serviceID, false);
            MySQLConnector.insertState(serviceID, false, e.getMessage());
            String msg = "Naming Exception in inserting stats into the DB for the CEPServerClient";
            log.warn(msg, e);
        }
    }
}

From source file:org.apache.stratos.status.monitor.agent.clients.service.MessageBrokerServiceClient.java

private static void executeService() throws SQLException {
    int serviceID = MySQLConnectionInitializer.getServiceID(StatusMonitorConstants.MESSAGING);
    AuthConfigBean authConfigBean = StatusMonitorConfigurationBuilder.getAuthConfigBean();

    String userName = authConfigBean.getUserName();
    tcpUserName = userName.replace('@', '!');

    //check whether login success
    if (ServiceLoginClient.loginChecker(StatusMonitorConstants.MESSAGING_HOST, serviceID)) {

        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, StatusMonitorAgentConstants.QPID_ICF);
        properties.put(StatusMonitorAgentConstants.CF_NAME_PREFIX + StatusMonitorAgentConstants.CF_NAME,
                getTCPConnectionURL(tcpUserName, authConfigBean.getPassword()));

        if (log.isDebugEnabled()) {
            log.debug("getTCPConnectionURL(username,password) = "
                    + getTCPConnectionURL(tcpUserName, authConfigBean.getPassword()));
        }//w  ww  .  j a  v  a2  s  .  co  m
        try {
            InitialContext ctx = new InitialContext(properties);
            // Lookup connection factory
            QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx
                    .lookup(StatusMonitorAgentConstants.CF_NAME);
            QueueConnection queueConnection = connFactory.createQueueConnection();
            queueConnection.start();
            QueueSession queueSession = queueConnection.createQueueSession(false,
                    QueueSession.AUTO_ACKNOWLEDGE);

            // Send message
            Queue queue = queueSession.createQueue(
                    StatusMonitorAgentConstants.QUEUE_NAME_MB + ";{create:always, node:{durable: True}}");

            // create the message to send
            TextMessage textMessage = queueSession.createTextMessage("Test Message Hello");
            javax.jms.QueueSender queueSender = queueSession.createSender(queue);
            queueSender.setTimeToLive(100000000);

            QueueReceiver queueReceiver = queueSession.createReceiver(queue);
            queueSender.send(textMessage);

            TextMessage message = (TextMessage) queueReceiver.receiveNoWait();

            if (message.getText().equals("Test Message Hello")) {
                MySQLConnector.insertStats(serviceID, true);
                MySQLConnector.insertState(serviceID, true, "");
            } else {
                MySQLConnector.insertStats(serviceID, false);
                MySQLConnector.insertState(serviceID, false, "Send and retrieve messages failed");
            }
            queueSender.close();
            queueSession.close();
            queueConnection.close();

        } catch (JMSException e) {
            MySQLConnector.insertStats(serviceID, false);
            MySQLConnector.insertState(serviceID, false, e.getMessage());
            String msg = "Exception in executing the client - "
                    + "Status Monitor Agent for MessageBrokerServiceClient";
            log.warn(msg, e);

        } catch (NamingException e) {
            MySQLConnector.insertStats(serviceID, false);
            MySQLConnector.insertState(serviceID, false, e.getMessage());
            String msg = "Naming exception in executing the client - "
                    + "Status Monitor agent for MessageBrokerServiceClient";
            log.warn(msg, e);
        }
    }
}