Example usage for javax.jms ConnectionFactory createConnection

List of usage examples for javax.jms ConnectionFactory createConnection

Introduction

In this page you can find the example usage for javax.jms ConnectionFactory createConnection.

Prototype


Connection createConnection() throws JMSException;

Source Link

Document

Creates a connection with the default user identity.

Usage

From source file:org.apache.flume.source.jms.TestIntegrationActiveMQ.java

private void putTopic(List<String> events) throws Exception {
    ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER_BIND_URL);
    Connection connection = factory.createConnection();
    connection.start();//from w  w w.j av a 2 s  .c o  m

    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createTopic(DESTINATION_NAME);
    MessageProducer producer = session.createProducer(destination);

    for (String event : events) {
        TextMessage message = session.createTextMessage();
        message.setText(event);
        producer.send(message);
    }
    session.commit();
    session.close();
    connection.close();
}

From source file:org.artificer.events.jms.JMSEventProducer.java

@Override
public void startup() {
    if (ArtificerConfig.isJmsEnabled()) {
        try {//w ww  . ja  va  2  s. c o  m
            String connectionFactoryName = ArtificerConfig.getConfigProperty(
                    ArtificerConstants.ARTIFICER_CONFIG_EVENT_JMS_CONNECTIONFACTORY, "ConnectionFactory");

            // Note that both properties end up doing the same thing.  Technically, we could combine both into one
            // single sramp.config.events.jms.destinations, but leaving them split for readability.
            String topicNamesProp = ArtificerConfig
                    .getConfigProperty(ArtificerConstants.ARTIFICER_CONFIG_EVENT_JMS_TOPICS, "");
            String[] topicNames = new String[0];
            if (StringUtils.isNotEmpty(topicNamesProp)) {
                topicNames = topicNamesProp.split(",");
            }
            String queueNamesProp = ArtificerConfig
                    .getConfigProperty(ArtificerConstants.ARTIFICER_CONFIG_EVENT_JMS_QUEUES, "");
            String[] queueNames = new String[0];
            if (StringUtils.isNotEmpty(queueNamesProp)) {
                queueNames = queueNamesProp.split(",");
            }

            // See if a ConnectionFactory and Topic/Queue exists on JNDI.  If so, assume JMS is properly
            // setup in a Java EE container and use it.

            ConnectionFactory connectionFactory = (ConnectionFactory) jndiLookup(connectionFactoryName);
            connection = connectionFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            for (String topicName : topicNames) {
                Topic topic = (Topic) jndiLookup(topicName);
                destinations.add(topic);
            }

            for (String queueName : queueNames) {
                Queue queue = (Queue) jndiLookup(queueName);
                destinations.add(queue);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
    }
}

From source file:org.apache.falcon.oozie.workflow.FalconPostProcessingTest.java

private void consumer(String brokerUrl, String topic, boolean checkUserMessage) throws JMSException {
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);
    Connection connection = connectionFactory.createConnection();
    connection.start();/*from  ww  w . j a  v a  2 s .  c  om*/

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createTopic(topic);
    MessageConsumer consumer = session.createConsumer(destination);

    latch.countDown();

    // Verify user message
    if (checkUserMessage) {
        verifyMesssage(consumer);
    }

    // Verify falcon message
    verifyMesssage(consumer);

    connection.close();
}

From source file:org.trellisldp.app.triplestore.TrellisApplicationTest.java

@BeforeEach
public void aquireConnection() throws Exception {
    final ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");
    connection = connectionFactory.createConnection();
    connection.start();//from  w ww  .ja v  a2  s.  c o m
    final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    final Destination destination = session.createQueue("trellis");
    consumer = session.createConsumer(destination);
    consumer.setMessageListener(this);
}

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

protected void createTerminateListener() throws Exception {

    ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    this.terminateConnection = connectionFactory.createConnection();
    terminateConnection.start();/* w  ww  .  jav a2 s  .com*/

    Session session = terminateConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    final Topic topic = session.createTopic(Constants.TERMINATE_CONSUMER_TOPIC);
    final MessageConsumer consumer = session.createConsumer(topic);

    final ObjectMapper mapper = new ObjectMapper();

    MessageListener listener = new MessageListener() {
        public void onMessage(Message message) {
            try {
                if (message instanceof TextMessage) {
                    TextMessage t = (TextMessage) message;
                    final ConsumerBean bean = mapper.readValue(t.getText(), ConsumerBean.class);

                    if (bean.getStatus().isFinal()) { // Something else already happened
                        terminateConnection.close();
                        return;
                    }

                    if (consumerId.equals(bean.getConsumerId())) {
                        if (bean.getStatus() == ConsumerStatus.REQUEST_TERMINATE) {
                            System.out.println(getName() + " has been requested to terminate and will exit.");
                            cbean.setStatus(ConsumerStatus.REQUEST_TERMINATE);
                            Thread.currentThread().sleep(2500);
                            System.exit(0);
                        }
                    }

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

    };
    consumer.setMessageListener(listener);

}

From source file:org.overlord.sramp.events.jms.JMSEventProducer.java

private void initActiveMQ(ConnectionFactory connectionFactory, String[] topicNames, String[] queueNames)
        throws Exception {
    connection = connectionFactory.createConnection();
    connection.start();//from   ww w .ja  v a2 s .c  o  m
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    for (String topicName : topicNames) {
        destinations.add(session.createTopic(topicName));
    }

    for (String queueName : queueNames) {
        destinations.add(session.createQueue(queueName));
    }
}

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

protected void startNotifications() throws Exception {

    if (uri == null)
        throw new NullPointerException("Please set the URI before starting notifications!");
    this.cbean = new ConsumerBean();
    cbean.setStatus(ConsumerStatus.STARTING);
    cbean.setName(getName());/* ww w.  ja v a2 s.c o m*/
    cbean.setConsumerId(consumerId);
    cbean.setVersion(consumerVersion);
    cbean.setStartTime(System.currentTimeMillis());
    try {
        cbean.setHostName(InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
        // Not fatal but would be nice...
        e.printStackTrace();
    }

    System.out.println("Running events on topic " + Constants.ALIVE_TOPIC + " to notify of '" + getName()
            + "' service being available.");

    final Thread aliveThread = new Thread(new Runnable() {
        public void run() {

            try {
                ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
                aliveConnection = connectionFactory.createConnection();
                aliveConnection.start();

                final Session session = aliveConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                final Topic topic = session.createTopic(Constants.ALIVE_TOPIC);
                final MessageProducer producer = session.createProducer(topic);

                final ObjectMapper mapper = new ObjectMapper();

                // Here we are sending the message out to the topic
                while (isActive()) {
                    try {
                        Thread.sleep(Constants.NOTIFICATION_FREQUENCY);

                        TextMessage temp = session.createTextMessage(mapper.writeValueAsString(cbean));
                        producer.send(temp, DeliveryMode.NON_PERSISTENT, 1, 5000);

                        if (ConsumerStatus.STARTING.equals(cbean.getStatus())) {
                            cbean.setStatus(ConsumerStatus.RUNNING);
                        }

                    } catch (InterruptedException ne) {
                        break;
                    } catch (Exception neOther) {
                        neOther.printStackTrace();
                    }
                }
            } catch (Exception ne) {
                ne.printStackTrace();
                setActive(false);
            }
        }
    });
    aliveThread.setName("Alive Notification Topic");
    aliveThread.setDaemon(true);
    aliveThread.setPriority(Thread.MIN_PRIORITY);
    aliveThread.start();
}

From source file:org.exist.messaging.JmsMessageSender.java

@Override
public NodeImpl send(JmsMessagingConfiguration config, MessagingMetadata metadata, Item content)
        throws XPathException {

    // JMS specific checks
    config.validateContent();//from w  ww .ja  v a2 s  .  co  m

    // Retrieve relevant values
    String initialContextFactory = config.getInitalContextProperty(Context.INITIAL_CONTEXT_FACTORY);
    String providerURL = config.getInitalContextProperty(Context.PROVIDER_URL);
    String connectionFactory = config.getConnectionFactory();
    String destination = config.getDestination();

    // TODO split up, use more exceptions, add better reporting
    try {
        Properties props = new Properties();
        props.setProperty(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
        props.setProperty(Context.PROVIDER_URL, providerURL);
        javax.naming.Context context = new InitialContext(props);

        // Setup connection
        ConnectionFactory cf = (ConnectionFactory) context.lookup(connectionFactory);
        Connection connection = cf.createConnection();

        // Lookup queue
        Destination dest = (Destination) context.lookup(destination);

        // Create session
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // Create message producer
        MessageProducer producer = session.createProducer(dest);

        // Create message
        Message message = createMessage(session, content, metadata, xqcontext);

        // Write properties
        Map<String, String> kvs = metadata.getValueMap();
        for (String key : kvs.keySet()) {
            message.setStringProperty(key, kvs.get(key));
        }

        // Send message
        producer.send(message);

        // Close connection
        // TODO keep connection open for re-use, efficiency
        connection.close();

        return createReport(message, xqcontext);

    } catch (Throwable ex) {
        LOG.error(ex);
        throw new XPathException(ex);
    }
}

From source file:org.jbpm.ejb.impl.CommandListenerBean.java

private Session createSession() throws JMSException {
    if (jmsConnection == null) {
        // lookup factory and create jms connection
        try {// ww w. j  av a2 s .  c om
            Context initial = new InitialContext();
            ConnectionFactory jmsConnectionFactory = (ConnectionFactory) initial
                    .lookup("java:comp/env/jms/JbpmConnectionFactory");
            jmsConnection = jmsConnectionFactory.createConnection();
        } catch (NamingException e) {
            throw new EJBException("error retrieving jms connection factory", e);
        }
    }
    /*
     * if the connection supports xa, the session will be transacted, else the
     * session will auto acknowledge; in either case no explicit transaction
     * control must be performed - see ejb 2.1 17.3.5
     */
    return jmsConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
}

From source file:org.mule.transport.jms.Jms11Support.java

public Connection createConnection(ConnectionFactory connectionFactory) throws JMSException {
    if (connectionFactory == null) {
        throw new IllegalArgumentException("connectionFactory cannot be null");
    }/*w  ww  .  j  av  a2 s.  co  m*/
    return connectionFactory.createConnection();
}