Example usage for javax.jms QueueSession createReceiver

List of usage examples for javax.jms QueueSession createReceiver

Introduction

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

Prototype


QueueReceiver createReceiver(Queue queue) throws JMSException;

Source Link

Document

Creates a QueueReceiver object to receive messages from the specified queue.

Usage

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

/**
 * Main method.// w  w  w . j  a v  a2 s .  c  om
 * 
 * @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.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  www. ja  v a2  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()));
        }//from w  w w  .j ava2 s.c om
        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);
        }
    }
}

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

public void recieve() {
    try {/*  ww  w  . j a va 2 s  .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.smartfrog.avalanche.shared.jms.MessageListener.java

public MonitoringEvent receive() throws Exception {
    MonitoringEvent event = null;// w  ww  .  ja v  a2  s.  co m
    // TODO : no need to open a new session every time .. fix it
    QueueSession qs = null;
    QueueReceiver qr = null;
    try {
        qs = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        qr = qs.createReceiver(queue);
        // TODO : Fix message timeout
        log.info("MonitoringEvent.receive() : Checking for new message on Queue");
        MapMessage mm = (MapMessage) qr.receive(jmsTimeout);

        if (mm != null) {
            log.info("Message received");
            event = new MonitoringEventDefaultImpl();
            event.setHost(mm.getString(MonitoringEvent.HOST));
            event.setInstanceName(mm.getString(MonitoringEvent.INSTANCE_NAME));
            event.setModuleId(mm.getString(MonitoringEvent.MODULEID));
            event.setModuleState(mm.getString(MonitoringEvent.MODULE_STATE));
            event.setMsg(mm.getString(MonitoringEvent.MODULE_STATE));
            event.setMessageType(mm.getInt(MonitoringEvent.MESSAGE_TYPE));
            log.info("MessageListener.receive() - " + event);

        } else {
            log.info("No message found in queue");
        }
        return event;
    } finally {
        qr.close();
        qs.close();
    }
}

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

@Before
public void setup() throws Exception {
    broker = new BrokerService();
    broker.setPersistent(false);/*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 www  .  j  av  a 2  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:com.zotoh.maedr.device.JmsIO.java

private void inizQueue(Context ctx, Object obj) throws Exception {

    QueueConnectionFactory f = (QueueConnectionFactory) obj;
    final JmsIO me = this;
    QueueConnection conn;//from  ww w. j  av  a  2s .  c  o m
    Queue q = (Queue) ctx.lookup(_dest);

    if (!isEmpty(_jmsUser)) {
        conn = f.createQueueConnection(_jmsUser, _jmsPwd);
    } else {
        conn = f.createQueueConnection();
    }

    _conn = conn;

    QueueSession s = conn.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
    QueueReceiver r;

    r = s.createReceiver(q);
    r.setMessageListener(new MessageListener() {
        public void onMessage(Message msg) {
            me.onMessage(msg);
        }
    });
}

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

/**
 * Gets the queueReceiver, by utilizing the <code>getInputQueue()</code> method.<br/>
 * For serverside getQueueReceiver() the creating of the QueueReceiver is done
 * without the <code>selector</code> information, as this is not allowed
 * by IFSA.<br/>/*  w w  w .j av  a2  s . c  o m*/
 * For a clientconnection, the receiver is done with the <code>getClientReplyQueue</code>
 * @see javax.jms.QueueReceiver
 */
protected QueueReceiver getServiceReceiver(QueueSession session) throws IfsaException {

    try {
        QueueReceiver queueReceiver;

        if (isProvider()) {
            String selector = getProviderSelector();
            if (StringUtils.isEmpty(selector)) {
                queueReceiver = session.createReceiver(getServiceQueue());
            } else {
                //log.debug(getLogPrefix()+"using selector ["+selector+"]");
                try {
                    queueReceiver = session.createReceiver(getServiceQueue(), selector);
                } catch (JMSException e) {
                    log.warn("caught exception, probably due to use of selector [" + selector
                            + "], falling back to non-selected mode", e);
                    queueReceiver = session.createReceiver(getServiceQueue());
                }
            }
        } else {
            throw new IfsaException("cannot obtain ServiceReceiver: Requestor cannot act as Provider");
        }
        if (log.isDebugEnabled() && !isSessionsArePooled()) {
            log.debug(getLogPrefix() + "got receiver for queue [" + queueReceiver.getQueue().getQueueName()
                    + "] " + ToStringBuilder.reflectionToString(queueReceiver));
        }
        return queueReceiver;
    } catch (JMSException e) {
        throw new IfsaException(e);
    }
}