Example usage for javax.jms QueueConnectionFactory createQueueConnection

List of usage examples for javax.jms QueueConnectionFactory createQueueConnection

Introduction

In this page you can find the example usage for javax.jms QueueConnectionFactory createQueueConnection.

Prototype


QueueConnection createQueueConnection() throws JMSException;

Source Link

Document

Creates a queue connection with the default user identity.

Usage

From source file:com.npower.dm.multiplexor.Multiplexor.java

public void init(ActionServlet arg0, ModuleConfig arg1) throws ServletException {
    log.info("Starting SMS Multiplexor Daemon ...");
    connection = null;//from w w  w.  j  a v a2s.c  o  m
    session = null;
    try {
        // Load Mapping Table
        this.mappingTable = this.loadMappingTable(this.getMappingFile());

        // Initialize and connect to JMS Queue
        JndiContextFactory jndiFactory = JndiContextFactory.newInstance(new Properties());
        Context jndiCtx = jndiFactory.getJndiContext();
        JMSManager jmsManager = JMSManager.newInstance(jndiCtx);

        QueueConnectionFactory connectionFactory = jmsManager.getQueueConnectionFactory();
        connection = connectionFactory.createQueueConnection();
        session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

        // Create or get outgoing queue
        Queue queue = jmsManager.getQueue(this.getIncomingQueueName(), null);
        QueueReceiver receiver = session.createReceiver(queue);
        receiver.setMessageListener(this);

        // Start JMS Listener
        connection.start();

        log.info("SMS Multiplexor Daemon has been started.");
    } catch (Exception e) {
        log.error("failure to initialize " + this.getClass().getCanonicalName(), e);
    } finally {
    }
}

From source file:org.wso2.mb.integration.common.clients.operations.queue.QueueMessageSender.java

public QueueMessageSender(String connectionString, String hostName, String port, String userName,
        String password, String queueName, AtomicInteger messageCounter, int numOfMessagesToSend,
        int delayBetweenMessages, String filePath, int printNumberOfMessagesPer, boolean isToPrintEachMessage,
        Long jmsExpiration) {/*from  www.j a  v  a  2s . c o  m*/

    this.hostName = hostName;
    this.port = port;
    this.connectionString = connectionString;
    this.messageCounter = messageCounter;
    this.queueName = queueName;
    this.numOfMessagesToSend = numOfMessagesToSend;
    this.delay = delayBetweenMessages;
    this.filePath = filePath;
    if (filePath != null && !filePath.equals("")) {
        readFromFile = true;
    }
    this.printNumberOfMessagesPer = printNumberOfMessagesPer;
    this.isToPrintEachMessage = isToPrintEachMessage;
    this.jmsExpiration = jmsExpiration;

    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, QPID_ICF);
    properties.put(CF_NAME_PREFIX + CF_NAME, getTCPConnectionURL(userName, password));
    properties.put("queue." + queueName, queueName);

    log.info("getTCPConnectionURL(userName,password) = " + getTCPConnectionURL(userName, password));

    try {
        InitialContext ctx = new InitialContext(properties);
        // Lookup connection factory
        QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup(CF_NAME);
        queueConnection = connFactory.createQueueConnection();
        queueConnection.start();
        queueSession = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);

        // Send message
        Queue queue = (Queue) ctx.lookup(queueName);
        queueSender = queueSession.createSender(queue);

    } catch (NamingException e) {
        log.error("Error while looking up for queue", e);
    } catch (JMSException e) {
        log.error("Error while initializing queue connection", e);
    }

}

From source file:org.easybatch.jms.JmsIntegrationTest.java

@Test
public void testJmsSupport() throws Exception {
    Context jndiContext = getJndiContext();
    QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) jndiContext
            .lookup("QueueConnectionFactory");
    Queue queue = (Queue) jndiContext.lookup("q");

    QueueConnection queueConnection = queueConnectionFactory.createQueueConnection();
    QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    QueueSender queueSender = queueSession.createSender(queue);
    queueConnection.start();//from   ww  w.  jav a2s. c  o m

    //send a regular message to the queue
    TextMessage message = queueSession.createTextMessage();
    message.setText(MESSAGE_TEXT);
    queueSender.send(message);

    //send a poison record to the queue
    queueSender.send(new JmsPoisonMessage());

    Job job = aNewJob().reader(new JmsQueueRecordReader(queueConnectionFactory, queue))
            .filter(new JmsPoisonRecordFilter()).processor(new RecordCollector())
            .jobListener(new JmsQueueSessionListener(queueSession))
            .jobListener(new JmsQueueConnectionListener(queueConnection)).build();

    JobReport jobReport = JobExecutor.execute(job);

    assertThat(jobReport).isNotNull();
    assertThat(jobReport.getParameters().getDataSource()).isEqualTo(EXPECTED_DATA_SOURCE_NAME);
    assertThat(jobReport.getMetrics().getTotalCount()).isEqualTo(2);
    assertThat(jobReport.getMetrics().getFilteredCount()).isEqualTo(1);
    assertThat(jobReport.getMetrics().getSuccessCount()).isEqualTo(1);

    List<JmsRecord> records = (List<JmsRecord>) jobReport.getResult();

    assertThat(records).isNotNull().isNotEmpty().hasSize(1);

    JmsRecord jmsRecord = records.get(0);
    Header header = jmsRecord.getHeader();
    assertThat(header).isNotNull();
    assertThat(header.getNumber()).isEqualTo(1);
    assertThat(header.getSource()).isEqualTo(EXPECTED_DATA_SOURCE_NAME);

    Message payload = jmsRecord.getPayload();
    assertThat(payload).isNotNull().isInstanceOf(TextMessage.class);

    TextMessage textMessage = (TextMessage) payload;
    assertThat(textMessage.getText()).isNotNull().isEqualTo(MESSAGE_TEXT);

}

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.
 * /*from  w  w w  .ja va 2s. 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:org.dawnsci.commandserver.core.producer.ProcessConsumer.java

/**
 * Parse the queue for stale jobs and things that should be rerun.
 * @param bean//from ww w .j av  a  2  s. 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:eu.planets_project.tb.impl.system.batch.backends.ifwee.TestbedWEEBatchProcessor.java

public void submitTicketForPollingToQueue(String ticket, String queueName, String batchProcessorSystemID)
        throws Exception {
    Context ctx = null;/*from   w  ww. j  a  v  a 2s.c om*/
    QueueConnection cnn = null;
    QueueSession sess = null;
    Queue queue = null;
    QueueSender sender = null;
    try {
        ctx = new InitialContext();
        QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup(QueueConnectionFactoryName);
        queue = (Queue) ctx.lookup(queueName);
        cnn = factory.createQueueConnection();
        sess = cnn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);

        //create the message to send to the MDB e.g. a TextMessage
        TextMessage message = sess.createTextMessage(ticket);
        message.setStringProperty(BatchProcessor.QUEUE_PROPERTY_NAME_FOR_SENDING, batchProcessorSystemID);

        //and finally send the message to the queue.
        sender = sess.createSender(queue);
        sender.send(message);
        log.debug("TestbedWEEBatchProcessor: sent message to queue, ID:" + message.getJMSMessageID());
    } finally {
        try {
            if (null != sender)
                sender.close();
        } catch (Exception ex) {
        }
        try {
            if (null != sess)
                sess.close();
        } catch (Exception ex) {
        }
        try {
            if (null != cnn)
                cnn.close();
        } catch (Exception ex) {
        }
        try {
            if (null != ctx)
                ctx.close();
        } catch (Exception ex) {
        }
    }
}

From source file:org.grouter.common.jms.QueueListenerDestination.java

/**
 * Connect to queue  and open a session.
 *//*w ww. ja  v a2  s . c  om*/
@Override
public void bind() {
    try {
        // Find ConnectionFactory
        final QueueConnectionFactory queueConnectionFactory = getInstance()
                .getQueueConnectionFactory(connectionFactory, context);
        // Get queue
        queue = getInstance().getQueue(destinationName, context);
        // Create conneciton to queue
        queueConnection = queueConnectionFactory.createQueueConnection();
        // Register an exceptionlistener
        queueConnection.setExceptionListener(exceptionListener);
        queueSession = queueConnection.createQueueSession(isTransactional, acknowledgeMode);

        messageConsumer = queueSession.createReceiver(queue);

        // Sets the receiver which onMessage method will be called.
        messageConsumer.setMessageListener(listener);

        queueConnection.start();
        logger.info("Bound to destination " + destinationName);
    } catch (JMSException e) {
        logger.error("Got exception with JMS provider during bind to destination " + destinationName
                + ". Got error message :" + e.getMessage());
        rebind(this);
    } catch (ServiceLocatorException ex) {
        logger.error("Got exception with JMS provider during bind to destination " + destinationName
                + ". Got error message : " + ex.getMessage());
        rebind(this);
    }
}

From source file:org.sdnmq.jms.PacketForwarder.java

/**
 * Setup MQ/*  w  ww. j av  a  2s  .  c om*/
 */
private boolean initMQ() {
    log.trace("Setting up MQ system");

    Properties jndiProps = JNDIHelper.getJNDIProperties();

    Context ctx = null;
    try {
        ctx = new InitialContext(jndiProps);
    } catch (NamingException e) {
        log.error(e.getMessage());
        releaseMQ();
        return false;
    }

    QueueConnectionFactory queueFactory = null;
    try {
        queueFactory = (QueueConnectionFactory) ctx.lookup("QueueConnectionFactory");
    } catch (NamingException e) {
        log.error(e.getMessage());
        releaseMQ();
        return false;
    }

    try {
        connection = queueFactory.createQueueConnection();
    } catch (JMSException e) {
        log.error(e.getMessage());
        releaseMQ();
        return false;
    }

    try {
        session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    } catch (JMSException e) {
        log.error(e.getMessage());
        releaseMQ();
        return false;
    }

    String queueName = System.getProperty(PACKETOUT_QUEUE_PROPERTY, DEFAULT_PACKETOUT_QUEUE_NAME);
    log.info("Using the following queue for packet forwarding requests: " + queueName);
    try {
        packetOutQueue = (Queue) ctx.lookup(queueName);
    } catch (NamingException e) {
        log.error(e.getMessage());
        releaseMQ();
        return false;
    }

    try {
        receiver = session.createReceiver(packetOutQueue);
    } catch (JMSException e) {
        log.error(e.getMessage());
        releaseMQ();
        return false;
    }

    return true;
}

From source file:org.socraticgrid.taskmanager.TaskManagerImpl.java

/**
 * Queue the message to the task handler.
 *
 * @param msgObject/*from   w  w  w  .  j av  a 2s. c om*/
 * @return
 */
private QueueResponse queueMessage(java.io.Serializable msgObject) {
    QueueResponse response = new QueueResponse();
    String taskQ = null;
    QueueConnection queueConnection = null;

    try {
        //Get task queue name & queue factory
        taskQ = PropertyAccessor.getProperty(TASKMANAGER_PROPERTY_FILE, PROPERTY_TASK_QUEUE);
        String taskQFactory = PropertyAccessor.getProperty(TASKMANAGER_PROPERTY_FILE,
                PROPERTY_TASK_QUEUE_FACTORY);

        //Get queue connection
        Context jndiContext = new InitialContext();
        QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) jndiContext
                .lookup(taskQFactory);
        Queue queue = (Queue) jndiContext.lookup(taskQ);

        //Create connection session
        queueConnection = queueConnectionFactory.createQueueConnection();
        QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        QueueSender queueSender = queueSession.createSender(queue);

        //Create message
        ObjectMessage message = queueSession.createObjectMessage(msgObject);

        //Send message
        queueSender.send(message);

        //Set response info
        response.ticket = message.getJMSMessageID();
        response.detail = TASK_MESSAGE_SUCCESS;
    } catch (PropertyAccessException pae) {
        String msg = TASK_MESSAGE_FAILURE + ": error accessing task properties in file:"
                + TASKMANAGER_PROPERTY_FILE + ".";
        log.error(msg, pae);
        response.ticket = TASK_MESSAGE_FAILURE_ID;
        response.detail = msg;
    } catch (NamingException ne) {
        String msg = TASK_MESSAGE_FAILURE + ": error creating connection to queue: " + taskQ + ".";
        log.error(msg, ne);
        response.ticket = TASK_MESSAGE_FAILURE_ID;
        response.detail = msg;
    } catch (JMSException jmse) {
        String msg = TASK_MESSAGE_FAILURE + ": error occurred trying to send notificaiton to task queue: "
                + taskQ + ".";
        log.error(msg, jmse);
        response.ticket = TASK_MESSAGE_FAILURE_ID;
        response.detail = msg;
    } finally {
        //Close queue
        if (queueConnection != null) {
            try {
                queueConnection.close();
            } catch (JMSException e) {
            }
        }
    }

    return response;
}

From source file:com.att.ajsc.csilogging.common.QueueConnector.java

@PostConstruct
public void init() {

    if (csiEnable && StringUtils.isNotEmpty(initialContextFactoryName)
            && StringUtils.isNotEmpty(connectionFactoryName) && StringUtils.isNotEmpty(providerURL)) {

        if (StringUtils.isNotEmpty(System.getenv(("com_att_aft_config_file")))) {
            System.setProperty("com.att.aft.config.file", System.getenv("com_att_aft_config_file"));
        }/*from w w w . j a  va 2  s .c o m*/

        if (StringUtils.isEmpty(System.getProperty("com.att.aft.config.file"))) {
            logger.error("Environment or System properties dont have the property com.att.aft.config.file");
            return;
        }

        QueueConnectionFactory queueConnectionFactory;
        InitialContext jndi = null;
        ConnectionFactory connectionFactory = null;
        try {

            Properties env = new Properties();
            env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactoryName);
            env.put(Context.PROVIDER_URL, providerURL);
            jndi = new InitialContext(env);
            connectionFactory = (ConnectionFactory) jndi.lookup(connectionFactoryName);
            queueConnectionFactory = (QueueConnectionFactory) connectionFactory;
            if (StringUtils.isNotEmpty(auditDestinationName)) {
                auditQueueConnection = queueConnectionFactory.createQueueConnection();
                auditQueueSession = auditQueueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                Queue auditQueue = (Queue) auditQueueSession.createQueue(auditDestinationName);
                auditQueueSender = auditQueueSession.createSender(auditQueue);
                auditQueueConnection.start();
                logger.info("*************CONNECTED :" + auditDestinationName + "*************");

            }

            if (StringUtils.isNotEmpty(perfDestinationName)) {
                pefQueueConnection = queueConnectionFactory.createQueueConnection();
                pefQueueSession = pefQueueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                Queue perfQueue = (Queue) pefQueueSession.createQueue(perfDestinationName);
                pefQueueSender = pefQueueSession.createSender(perfQueue);
                pefQueueConnection.start();
                logger.info("*************CONNECTED :" + perfDestinationName + "*************");
            }

        } catch (Exception e) {
            logger.error("Error while connecting to the Queue" + e);
        }
    }

}