Example usage for javax.jms QueueSession createQueue

List of usage examples for javax.jms QueueSession createQueue

Introduction

In this page you can find the example usage for javax.jms QueueSession createQueue.

Prototype


Queue createQueue(String queueName) throws JMSException;

Source Link

Document

Creates a queue identity given a Queue name.

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  .j av a2s.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:org.panksdmz.jms.tibco.MessageRecieverBean.java

public void recieve() {
    try {// w  ww. j a  va  2 s.com
        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.panksdmz.jms.tibco.MessageSenderBean.java

public void send() {
    try {// w w w. j ava 2  s  . c o  m
        QueueConnection connection = connectionFactory.createQueueConnection();
        QueueSession session = connection.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(sendQueueName);
        QueueSender sender = session.createSender(queue);
        TextMessage message = session
                .createTextMessage("Message @ " + CaliHDateTime.now().getTimeInMillis() + " from thread "
                        + Thread.currentThread().getId() + " from session [" + session.toString() + "]");

        sender.send(message);
        session.close();

    } catch (JMSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:de.adorsys.jmspojo.JMSJavaFutureAdapterTest.java

@Before
public void setup() throws Exception {
    broker = new BrokerService();
    broker.setPersistent(false);/*from w w w  .ja va2  s. c  o  m*/

    // configure the broker
    broker.addConnector("vm://test");
    broker.setBrokerName("test");
    broker.setUseShutdownHook(false);

    broker.start();

    cf = new ActiveMQConnectionFactory("vm://localhost?create=false");
    qc = cf.createQueueConnection();
    QueueSession createQueueSession = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    testQueue = createQueueSession.createQueue("TestQueue");
    createQueueSession.createReceiver(testQueue).setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
            try {
                boolean sendTimeout = message.getBooleanProperty("timeout");
                boolean sendError = message.getBooleanProperty("error");
                if (sendError) {
                    JMSJavaFutureAdapter<PingMessage> jmsSender = new JMSJavaFutureAdapter<PingMessage>(
                            objectMapper, cf, null, TIMEOUT);
                    HashMap<String, Object> messageProperties = new HashMap<String, Object>();
                    messageProperties.put("ERROR", "test error");
                    jmsSender.send(message.getJMSReplyTo(), messageProperties, null);
                } else if (!sendTimeout) {
                    JMSJavaFutureAdapter<PingMessage> jmsSender = new JMSJavaFutureAdapter<PingMessage>(
                            objectMapper, cf, null, TIMEOUT);
                    jmsSender.send(message.getJMSReplyTo(), null, ((TextMessage) message).getText());
                }

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

}

From source file:de.adorsys.jmspojo.JMSServiceAdapterFactoryTest.java

@Before
public void setup() throws Exception {
    broker = new BrokerService();
    broker.setPersistent(false);/*from ww  w . ja v a2  s  .  c om*/

    // configure the broker
    broker.addConnector("vm://test");
    broker.setBrokerName("test");
    broker.setUseShutdownHook(false);

    broker.start();

    cf = new ActiveMQConnectionFactory("vm://localhost?create=false");
    qc = cf.createQueueConnection();
    QueueSession createQueueSession = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    defaultQueue = createQueueSession.createQueue("TestQueue");
    createQueueSession.createReceiver(defaultQueue).setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
            try {
                boolean sendTimeout = message.getBooleanProperty("timeout");
                if (!sendTimeout) {
                    JMSJavaFutureAdapter<PingMessage> jmsSender = new JMSJavaFutureAdapter<PingMessage>(
                            OBJECT_MAPPER, cf, null, JMS_TIMEOUT);
                    jmsSender.send(message.getJMSReplyTo(), null, ((TextMessage) message).getText());
                }
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    });

    dedicatedQueue = createQueueSession.createQueue("DedicatedQueue");
    createQueueSession.createReceiver(dedicatedQueue).setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
            try {
                JMSJavaFutureAdapter<PingMessage> jmsSender = new JMSJavaFutureAdapter<PingMessage>(
                        OBJECT_MAPPER, cf, null, JMS_TIMEOUT);
                PingMessage data = new PingMessage();
                data.setPing("dedicted response");
                jmsSender.send(message.getJMSReplyTo(), null, data);
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    });
    qc.start();

    JMSServiceAdapterFactory jmsServiceStubFactory = new JMSServiceAdapterFactory(OBJECT_MAPPER, cf,
            defaultQueue, JMS_TIMEOUT);
    service = jmsServiceStubFactory.generateJMSServiceProxy(JMSSampleService.class);

}

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.
 * /* www  .  jav  a  2  s .co  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: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 av  a 2s .c o m
 * @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  . j  a  v a 2  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.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;/*  w  ww  . ja  v  a  2  s  . c  o m*/
        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.  ja v a 2  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);
        }
    }
}