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.falcon.entity.parser.ClusterEntityParser.java

protected void validateMessagingInterface(Cluster cluster) throws ValidationException {
    // Validate only if user has specified this
    final Interface messagingInterface = ClusterHelper.getInterface(cluster, Interfacetype.MESSAGING);
    if (messagingInterface == null) {
        LOG.info("Messaging service is not enabled for cluster: {}", cluster.getName());
        return;//  ww w  . j  a v  a 2 s.  com
    }

    final String messagingUrl = ClusterHelper.getMessageBrokerUrl(cluster);
    final String implementation = StartupProperties.get().getProperty("broker.impl.class",
            "org.apache.activemq.ActiveMQConnectionFactory");
    LOG.info("Validating messaging interface: {}, implementation: {}", messagingUrl, implementation);

    try {
        @SuppressWarnings("unchecked")
        Class<ConnectionFactory> clazz = (Class<ConnectionFactory>) getClass().getClassLoader()
                .loadClass(implementation);
        ConnectionFactory connectionFactory = clazz.getConstructor(String.class, String.class, String.class)
                .newInstance("", "", messagingUrl);
        connectionFactory.createConnection();
    } catch (Exception e) {
        throw new ValidationException(
                "Invalid Messaging server or port: " + messagingUrl + " for: " + implementation, e);
    }
}

From source file:org.jbpm.bpel.integration.jms.IntegrationControl.java

void openJmsConnection(InitialContext initialContext) throws NamingException, JMSException {
    ConnectionFactory jmsConnectionFactory = getConnectionFactory(initialContext);
    jmsConnection = jmsConnectionFactory.createConnection();
}

From source file:org.dawnsci.commandserver.ui.view.ConsumerView.java

/**
 * Listens to a topic/*  w  w  w  .  jav  a 2s . com*/
 */
private void createTopicListener(final URI uri) throws Exception {

    // Use job because connection might timeout.
    final Job topicJob = new Job("Create topic listener") {

        @Override
        protected IStatus run(IProgressMonitor monitor) {
            try {
                ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
                topicConnection = connectionFactory.createConnection();
                topicConnection.start();

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

                final Topic topic = session.createTopic(Constants.ALIVE_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);
                                bean.setLastAlive(System.currentTimeMillis());
                                consumers.put(bean.getConsumerId(), bean);
                            }
                        } catch (Exception e) {
                            logger.error("Updating changed bean from topic", e);
                        }
                    }
                };
                consumer.setMessageListener(listener);
                return Status.OK_STATUS;

            } catch (Exception ne) {
                logger.error("Cannot listen to topic changes because command server is not there", ne);
                return Status.CANCEL_STATUS;
            }
        }

    };

    topicJob.setPriority(Job.INTERACTIVE);
    topicJob.setSystem(true);
    topicJob.setUser(false);
    topicJob.schedule();
}

From source file:org.calrissian.mango.jms.stream.JmsFileTransferSupportTest.java

public void testFullCycle() throws Exception {
    try {//  w  w  w  . java 2 s .  c  om
        URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {

            @Override
            public URLStreamHandler createURLStreamHandler(String protocol) {
                if ("testprot".equals(protocol))
                    return new URLStreamHandler() {

                        @Override
                        protected URLConnection openConnection(URL u) throws IOException {
                            return new URLConnection(u) {

                                @Override
                                public void connect() throws IOException {

                                }

                                @Override
                                public InputStream getInputStream() throws IOException {
                                    return new ByteArrayInputStream(TEST_STR.getBytes());
                                }

                                @Override
                                public String getContentType() {
                                    return "content/notnull";
                                }
                            };
                        }
                    };
                return null;
            }
        });
    } catch (Error ignored) {
    }

    final ActiveMQTopic ft = new ActiveMQTopic("testFileTransfer");

    ThreadPoolTaskExecutor te = new ThreadPoolTaskExecutor();
    te.initialize();

    JmsFileSenderListener listener = new JmsFileSenderListener();
    final String hashAlgorithm = "MD5";
    listener.setHashAlgorithm(hashAlgorithm);
    listener.setStreamRequestDestination(ft);
    listener.setPieceSize(9);
    listener.setTaskExecutor(te);

    ConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
    cf = new SingleTopicConnectionFactory(cf, "test");
    JmsTemplate jmsTemplate = new JmsTemplate();
    jmsTemplate.setConnectionFactory(cf);
    jmsTemplate.setReceiveTimeout(60000);
    listener.setJmsTemplate(jmsTemplate);

    Connection conn = cf.createConnection();
    conn.start();
    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = sess.createConsumer(ft);
    consumer.setMessageListener(listener);

    JmsFileReceiver receiver = new JmsFileReceiver();
    receiver.setHashAlgorithm(hashAlgorithm);
    receiver.setStreamRequestDestination(ft);
    receiver.setJmsTemplate(jmsTemplate);
    receiver.setPieceSize(9);

    JmsFileReceiverInputStream stream = (JmsFileReceiverInputStream) receiver.receiveStream("testprot:test");
    StringBuilder buffer = new StringBuilder();
    int read;
    while ((read = stream.read()) >= 0) {
        buffer.append((char) read);
    }
    stream.close();

    assertEquals(TEST_STR, buffer.toString());

    conn.stop();

}

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

public void registerListener(List<String> eventTypeNames, MessageHandler handler) {
    if (brokerService == null || !brokerInitialized) {
        log.debug("The broker service is not running in registerListener.");
        return;/*  w w w  .j  av  a  2s  .co m*/
    }

    if (!isValidHandler(handler)) {
        return;
    }

    ConnectionFactory connectionFactory = jmsTemplate.getConnectionFactory();
    Connection connection = null;
    try {
        connection = connectionFactory.createConnection();
        connection.setClientID(handler.getClientId());
    } 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());
    }

    for (String eventTypeName : eventTypeNames) {
        log.info("Registering handler for event " + eventTypeName);
        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;
        }

        try {
            Session topicSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            TopicSubscriber subscriber = topicSession.createDurableSubscriber(topic, topic.getTopicName());
            MessageListenerImpl listener = new MessageListenerImpl(connection, topicSession, subscriber,
                    handler);
            saveListenerRegistration(listener, eventTypeName);
            subscriber.setMessageListener(listener);
        } 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());
        }
    }

    try {
        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());
    }
}

From source file:org.apache.activemq.usecases.ConcurrentProducerDurableConsumerTest.java

public void x_testSendWithInactiveAndActiveConsumers() throws Exception {
    Destination destination = createDestination();
    ConnectionFactory factory = createConnectionFactory();
    startInactiveConsumers(factory, destination);

    Connection connection = factory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);

    final int toSend = 100;
    final int numIterations = 5;

    double[] noConsumerStats = produceMessages(destination, toSend, numIterations, session, producer, null);

    startConsumers(factory, destination);
    LOG.info("Activated consumer");

    double[] withConsumerStats = produceMessages(destination, toSend, numIterations, session, producer, null);

    LOG.info("With consumer: " + withConsumerStats[1] + " , with noConsumer: " + noConsumerStats[1]
            + ", multiplier: " + (withConsumerStats[1] / noConsumerStats[1]));
    final int reasonableMultiplier = 15; // not so reasonable but improving
    assertTrue(//  www.  j a v a2s.c o  m
            "max X times as slow with consumer: " + withConsumerStats[1] + ", with no Consumer: "
                    + noConsumerStats[1] + ", multiplier: " + (withConsumerStats[1] / noConsumerStats[1]),
            withConsumerStats[1] < noConsumerStats[1] * reasonableMultiplier);

    final int toReceive = toSend * numIterations * consumerCount * 2;
    Wait.waitFor(new Wait.Condition() {
        public boolean isSatisified() throws Exception {
            LOG.info("count: " + allMessagesList.getMessageCount());
            return toReceive == allMessagesList.getMessageCount();
        }
    }, 60 * 1000);

    assertEquals("got all messages", toReceive, allMessagesList.getMessageCount());
}

From source file:org.dawnsci.commandserver.core.process.ProgressableProcess.java

/**
 * Starts a connection which listens to the topic and if
 * a cancel is found published, tries to terminate the subprocess.
 * /* www  .  j  a  v a2  s  .co m*/
 * @param p
 */
protected void createTerminateListener() throws Exception {

    ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    ProgressableProcess.this.topicConnection = connectionFactory.createConnection();
    topicConnection.start();

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

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

    final Class clazz = bean.getClass();
    final ObjectMapper mapper = new ObjectMapper();

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

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

                    if (bean.getUniqueId().equals(tbean.getUniqueId())) {
                        if (tbean.getStatus() == Status.REQUEST_TERMINATE) {
                            bean.merge(tbean);
                            out.println("Terminating job '" + tbean.getName() + "'");

                            terminate();
                            topicConnection.close();

                            bean.setStatus(Status.TERMINATED);
                            bean.setMessage("Foricibly terminated before finishing.");
                            broadcast(bean);

                            return;
                        }
                    }

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

    };
    consumer.setMessageListener(listener);

}

From source file:org.apache.activemq.usecases.ConcurrentProducerDurableConsumerTest.java

public void testSendRateWithActivatingConsumers() throws Exception {
    final Destination destination = createDestination();
    final ConnectionFactory factory = createConnectionFactory();
    startInactiveConsumers(factory, destination);

    Connection connection = factory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = createMessageProducer(session, destination);

    // preload the durable consumers
    double[] inactiveConsumerStats = produceMessages(destination, 500, 10, session, producer, null);
    LOG.info("With inactive consumers: ave: " + inactiveConsumerStats[1] + ", max: " + inactiveConsumerStats[0]
            + ", multiplier: " + (inactiveConsumerStats[0] / inactiveConsumerStats[1]));

    // periodically start a durable sub that has a backlog
    final int consumersToActivate = 5;
    final Object addConsumerSignal = new Object();
    Executors.newCachedThreadPool(new ThreadFactory() {
        @Override//from   ww w .j  a v a 2 s . c  o  m
        public Thread newThread(Runnable r) {
            return new Thread(r, "ActivateConsumer" + this);
        }
    }).execute(new Runnable() {
        @Override
        public void run() {
            try {
                MessageConsumer consumer = null;
                for (int i = 0; i < consumersToActivate; i++) {
                    LOG.info("Waiting for add signal from producer...");
                    synchronized (addConsumerSignal) {
                        addConsumerSignal.wait(30 * 60 * 1000);
                    }
                    TimedMessageListener listener = new TimedMessageListener();
                    consumer = createDurableSubscriber(factory.createConnection(), destination,
                            "consumer" + (i + 1));
                    LOG.info("Created consumer " + consumer);
                    consumer.setMessageListener(listener);
                    consumers.put(consumer, listener);
                }
            } catch (Exception e) {
                LOG.error("failed to start consumer", e);
            }
        }
    });

    double[] statsWithActive = produceMessages(destination, 500, 10, session, producer, addConsumerSignal);

    LOG.info(" with concurrent activate, ave: " + statsWithActive[1] + ", max: " + statsWithActive[0]
            + ", multiplier: " + (statsWithActive[0] / statsWithActive[1]));

    while (consumers.size() < consumersToActivate) {
        TimeUnit.SECONDS.sleep(2);
    }

    long timeToFirstAccumulator = 0;
    for (TimedMessageListener listener : consumers.values()) {
        long time = listener.getFirstReceipt();
        timeToFirstAccumulator += time;
        LOG.info("Time to first " + time);
    }
    LOG.info("Ave time to first message =" + timeToFirstAccumulator / consumers.size());

    for (TimedMessageListener listener : consumers.values()) {
        LOG.info("Ave batch receipt time: " + listener.waitForReceivedLimit(10000) + " max receipt: "
                + listener.maxReceiptTime);
    }

    //assertTrue("max (" + statsWithActive[0] + ") within reasonable
    // multiplier of ave (" + statsWithActive[1] + ")",
    //        statsWithActive[0] < 5 * statsWithActive[1]);

    // compare no active to active
    LOG.info("Ave send time with active: " + statsWithActive[1] + " as multiplier of ave with none active: "
            + inactiveConsumerStats[1] + ", multiplier=" + (statsWithActive[1] / inactiveConsumerStats[1]));

    assertTrue(
            "Ave send time with active: " + statsWithActive[1]
                    + " within reasonable multpler of ave with none active: " + inactiveConsumerStats[1]
                    + ", multiplier " + (statsWithActive[1] / inactiveConsumerStats[1]),
            statsWithActive[1] < 15 * inactiveConsumerStats[1]);
}

From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java

public ClientJmsDelegate(final Context context) {
    try {/*from   www .j a  v a  2  s  .  c om*/
        _context = context;
        final ConnectionFactory connectionFactory = (ConnectionFactory) _context.lookup("connectionfactory");
        _controllerConnection = connectionFactory.createConnection();
        _controllerConnection.start();
        _controllerQueue = (Destination) context.lookup(DistributedTestConstants.CONTROLLER_QUEUE_JNDI_NAME);
        _controllerSession = _controllerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        _controlQueueProducer = _controllerSession.createProducer(_controllerQueue);
        _clientName = UUID.randomUUID().toString();
        _testConnections = new HashMap<String, Connection>();
        _testSessions = new HashMap<String, Session>();
        _testProducers = new HashMap<String, MessageProducer>();
        _testConsumers = new HashMap<String, MessageConsumer>();
        _testSubscriptions = new HashMap<String, Session>();
        _testMessageProviders = new HashMap<String, MessageProvider>();
        _defaultMessageProvider = new MessageProvider(null);
    } catch (final NamingException ne) {
        throw new DistributedTestException("Unable to create client jms delegate", ne);
    } catch (final JMSException jmse) {
        throw new DistributedTestException("Unable to create client jms delegate", jmse);
    }
}

From source file:org.apache.activemq.usecases.ConcurrentProducerDurableConsumerTest.java

protected void startConsumers(ConnectionFactory factory, Destination dest) throws Exception {
    MessageConsumer consumer;//from www .j a v a  2 s  .  co m
    for (int i = 0; i < consumerCount; i++) {
        TimedMessageListener list = new TimedMessageListener();
        consumer = createDurableSubscriber(factory.createConnection(), dest, "consumer" + (i + 1));
        consumer.setMessageListener(list);
        consumers.put(consumer, list);
    }
}