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.servicemix.jms.AbstractJmsProcessor.java

public void init() throws Exception {
    try {/*from   w  w w .j  a va2s .co  m*/
        InitialContext ctx = getInitialContext();
        ConnectionFactory connectionFactory = null;
        connectionFactory = getConnectionFactory(ctx);
        connection = connectionFactory.createConnection();
        connection.start();

        // set up the Store
        if (endpoint.store != null) {
            store = endpoint.store;
        } else if (endpoint.storeFactory != null) {
            store = endpoint.storeFactory.open(endpoint.getService().toString() + endpoint.getEndpoint());
        } else {
            store = new MemoryStoreFactory().open(endpoint.getService().toString() + endpoint.getEndpoint());
        }

        doInit(ctx);
    } catch (Exception e) {
        shutdown();
    }
}

From source file:fr.xebia.springframework.jms.support.converter.JaxbMessageConverterTest.java

@Before
public void before() throws Exception {
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
            "vm://localhost?broker.persistent=false&broker.useJmx=false");
    Connection connection = connectionFactory.createConnection();
    connection.start();// w w w .  ja  v a 2 s  .c o  m
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

}

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

@Override
public void startup() {
    if (SrampConfig.isJmsEnabled()) {
        try {//from w  w  w  .j ava2s. co m
            String connectionFactoryName = SrampConfig.getConfigProperty(
                    SrampConstants.SRAMP_CONFIG_EVENT_JMS_CONNECTIONFACTORY, "ConnectionFactory"); //$NON-NLS-1$

            // 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 = SrampConfig.getConfigProperty(SrampConstants.SRAMP_CONFIG_EVENT_JMS_TOPICS,
                    ""); //$NON-NLS-1$
            String[] topicNames = new String[0];
            if (StringUtils.isNotEmpty(topicNamesProp)) {
                topicNames = topicNamesProp.split(","); //$NON-NLS-1$
            }
            String queueNamesProp = SrampConfig.getConfigProperty(SrampConstants.SRAMP_CONFIG_EVENT_JMS_QUEUES,
                    ""); //$NON-NLS-1$
            String[] queueNames = new String[0];
            if (StringUtils.isNotEmpty(queueNamesProp)) {
                queueNames = queueNamesProp.split(","); //$NON-NLS-1$
            }

            try {
                // First, see if a ConnectionFactory and Topic/Queue exists on JNDI.  If so, assume JMS is properly
                // setup in a Java EE container and simply 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 (NamingException e) {
                // Otherwise, JMS wasn't setup. Assume we need to start an embedded
                // ActiveMQ broker and create the destinations.

                String bindAddress = "tcp://localhost:" //$NON-NLS-1$
                        + SrampConfig.getConfigProperty(SrampConstants.SRAMP_CONFIG_EVENT_JMS_PORT, "61616"); //$NON-NLS-1$

                LOG.warn(Messages.i18n.format("org.overlord.sramp.events.jms.embedded_broker", bindAddress)); //$NON-NLS-1$

                session = null;
                destinations.clear();

                BrokerService broker = new BrokerService();
                broker.addConnector(bindAddress);
                broker.start();

                // Event though we added a TCP connector, above, ActiveMQ also exposes the broker over the "vm"
                // protocol. It optimizes performance for connections on the same JVM.
                ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost"); //$NON-NLS-1$
                initActiveMQ(connectionFactory, topicNames, queueNames);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
    }
}

From source file:org.apache.falcon.messaging.JMSMessageConsumerTest.java

public void sendMessages(String topic, WorkflowExecutionContext.Type type, boolean isFalconWF)
        throws JMSException, FalconException, IOException {
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
    Connection connection = connectionFactory.createConnection();
    connection.start();/*  www .j  av a2  s. c om*/

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic destination = session.createTopic(topic);
    javax.jms.MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);

    for (int i = 0; i < 5; i++) {
        Message message = null;

        switch (type) {
        case POST_PROCESSING:
            message = getMockFalconMessage(i, session);
            break;
        case WORKFLOW_JOB:
            message = getMockOozieMessage(i, session, isFalconWF);
            break;
        case COORDINATOR_ACTION:
            message = getMockOozieCoordMessage(i, session, isFalconWF);
        default:
            break;
        }
        Log.debug("Sending:" + message);
        producer.send(message);
    }
}

From source file:com.mdmserver.managers.ControllerFacade.java

public void lockPhone(int accountId) throws IOException {
    Account account = databaseManager.getAccountByAccountId(accountId);
    Context ctx;//from  w  ww  .  jav a 2s .  c om
    try {
        ctx = new InitialContext();
        ConnectionFactory connectionFactory = (ConnectionFactory) ctx.lookup("jms/mdmConnectionFactory");
        Queue queue = (Queue) ctx.lookup("jms/mdmQueue");
        MessageProducer messageProducer;
        System.out.println("Naming success");
        try {

            javax.jms.Connection connection = connectionFactory.createConnection();
            javax.jms.Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            messageProducer = session.createProducer(queue);
            TextMessage message = session.createTextMessage();
            message.setStringProperty(Account.FIELD_NAME_CLOUD_ID, account.getCloudId());
            ControlClient cClient = new ControlClient();
            cClient.setCommandType(ControlClient.LOCK_PHONE_CONTROL);
            Gson gson = new Gson();
            message.setStringProperty(ControlClient.CONTROL_CLIENT_KEY, gson.toJson(cClient));
            System.out.println("It come from Servlet:" + message.getText());
            messageProducer.send(message);
            System.out.println("JMS success");
        } catch (JMSException ex) {
            //                  Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("JMS exception");
        }

    } catch (NamingException ex) {
        //                Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Naming exception");
    }
}

From source file:com.mdmserver.managers.ControllerFacade.java

public void uninstallApp(int accountId, String appPackageName) {
    Account account = databaseManager.getAccountByAccountId(accountId);
    Context ctx;/*from  ww  w  .j a v a 2s  .c  om*/
    try {
        ctx = new InitialContext();
        ConnectionFactory connectionFactory = (ConnectionFactory) ctx.lookup("jms/mdmConnectionFactory");
        Queue queue = (Queue) ctx.lookup("jms/mdmQueue");
        MessageProducer messageProducer;
        System.out.println("Naming success");
        try {

            javax.jms.Connection connection = connectionFactory.createConnection();
            javax.jms.Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            messageProducer = session.createProducer(queue);
            TextMessage message = session.createTextMessage();
            message.setStringProperty(Account.FIELD_NAME_CLOUD_ID, account.getCloudId());
            ControlClient cClient = new ControlClient();
            cClient.setCommandType(ControlClient.UNINSTALL_APP_CONTROL);
            cClient.setJsonCommandDetails(appPackageName);
            Gson gson = new Gson();
            message.setStringProperty(ControlClient.CONTROL_CLIENT_KEY, gson.toJson(cClient));
            System.out.println("It come from Servlet:" + message.getText());
            messageProducer.send(message);
            System.out.println("JMS success");
        } catch (JMSException ex) {
            //                  Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("JMS exception");
        }

    } catch (NamingException ex) {
        //                Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Naming exception");
    }
}

From source file:org.geoserver.wfs.notification.StaticJMSEventHelper.java

protected JMSInfo createJMSInfo(Properties p) throws NamingException, JMSException {
    JMSInfo info = null;//from   www .java2 s.  c o  m

    Context ctx = new InitialContext(p);
    ConnectionFactory factory = (ConnectionFactory) ctx.lookup(coalesce(
            (String) p.getProperty("connectionFactoryName"), connectionFactoryName, "connectionFactory"));
    Connection connection = factory.createConnection();

    // Find a list of destination names.

    // Try a provided list first
    List<String> destinationNames = this.destinationNames;

    if (destinationNames == null) {
        // If none were provided, scan the properties for likely suspects
        destinationNames = new ArrayList<String>();
        for (String e : (((Map<String, String>) (Object) p).keySet())) {
            if (e.startsWith(DESTINATION_PREFIX)) {
                destinationNames.add(e.substring(DESTINATION_PREFIX.length()));
            }
        }
    }

    if (destinationNames.isEmpty()) {
        throw new IllegalArgumentException("No destination names were provided or found.");
    }

    List<Destination> destinations = new ArrayList<Destination>(destinationNames.size());
    for (String name : destinationNames) {
        destinations.add((Destination) ctx.lookup(name));
    }
    info = new JMSInfo(connection, destinations);

    return info;
}

From source file:com.adaptris.core.jms.JmsConnection.java

protected void createConnection(ConnectionFactory factory) throws JMSException {
    try {//  www.  j  a  v a  2  s. com
        if (isEmpty(configuredUserName())) {
            connection = factory.createConnection();
        } else {
            connection = factory.createConnection(configuredUserName(),
                    Password.decode(ExternalResolver.resolve(configuredPassword())));
        }
    } catch (JMSException e) {
        throw e;
    } catch (Exception e) {
        JmsUtils.rethrowJMSException(e);
    }
}

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

/**
 * WARNING - starts infinite loop - you have to kill 
 * @param uri//from   w ww.  ja v a  2s. co m
 * @param submitQName
 * @param statusTName
 * @param statusQName
 * @throws Exception
 */
private void monitorSubmissionQueue(URI uri, String submitQName, String statusTName, String statusQName)
        throws Exception {

    ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue(submitQName);

    final MessageConsumer consumer = session.createConsumer(queue);
    connection.start();

    System.out.println("Starting consumer for submissions to queue " + submitQName);
    while (isActive()) { // You have to kill it or call stop() to stop it!

        try {

            // Consumes messages from the queue.
            Message m = consumer.receive(1000);
            if (m != null) {

                // TODO FIXME Check if we have the max number of processes
                // exceeded and wait until we dont...

                TextMessage t = (TextMessage) m;
                ObjectMapper mapper = new ObjectMapper();

                final StatusBean bean = mapper.readValue(t.getText(), getBeanClass());

                if (bean != null) { // We add this to the status list so that it can be rendered in the UI

                    if (!isHandled(bean))
                        continue; // Consume it and move on

                    // Now we put the bean in the status queue and we 
                    // start the process
                    RemoteSubmission factory = new RemoteSubmission(uri);
                    factory.setLifeTime(t.getJMSExpiration());
                    factory.setPriority(t.getJMSPriority());
                    factory.setTimestamp(t.getJMSTimestamp());
                    factory.setQueueName(statusQName); // Move the message over to a status queue.

                    factory.submit(bean, false);

                    final ProgressableProcess process = createProcess(uri, statusTName, statusQName, bean);
                    if (process != null) {
                        if (process.isBlocking()) {
                            System.out.println("About to run job " + bean.getName() + " messageid("
                                    + t.getJMSMessageID() + ")");
                        }
                        processCount++;
                        process.start();
                        if (process.isBlocking()) {
                            System.out.println(
                                    "Ran job " + bean.getName() + " messageid(" + t.getJMSMessageID() + ")");
                        } else {
                            System.out.println("Started job " + bean.getName() + " messageid("
                                    + t.getJMSMessageID() + ")");
                        }
                    }

                }
            }

        } catch (Throwable ne) {
            // Really basic error reporting, they have to pipe to file.
            ne.printStackTrace();
            setActive(false);
        }
    }

}

From source file:org.openhie.openempi.notification.impl.NotificationServiceImpl.java

public void registerListener(String eventTypeName, MessageHandler handler) {
    if (brokerService == null || !brokerInitialized) {
        log.debug("The broker service is not running in registerListener.");
        return;//from  w  w  w .ja v  a2  s .co  m
    }

    log.info("Registering handler for event " + eventTypeName);
    if (!isValidHandler(handler)) {
        return;
    }

    Topic topic = topicMap.get(eventTypeName);
    if (topic == null) {
        log.error("Caller attempted to register interest to events of unknown type " + eventTypeName);
        throw new RuntimeException("Unknown event type specified in registration request.");
    }

    if (isListenerRegistered(handler, eventTypeName)) {
        log.warn("Caller attempted to register interest for the same event again.");
        return;
    }
    ConnectionFactory connectionFactory = jmsTemplate.getConnectionFactory();
    try {
        TopicConnection connection = (TopicConnection) connectionFactory.createConnection();
        if (connection.getClientID() == null) {
            connection.setClientID(handler.getClientId());
        }
        log.debug("Connection is of type " + connection);
        TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        TopicSubscriber subscriber = topicSession.createSubscriber(topic);
        MessageListenerImpl listener = new MessageListenerImpl(connection, topicSession, subscriber, handler);
        saveListenerRegistration(listener, eventTypeName);
        subscriber.setMessageListener(listener);
        connection.start();
    } catch (JMSException e) {
        log.error("Failed while setting up a registrant for notification events. Error: " + e, e);
        throw new RuntimeException("Unable to setup registration for event notification: " + e.getMessage());
    }
}