Example usage for javax.jms Connection start

List of usage examples for javax.jms Connection start

Introduction

In this page you can find the example usage for javax.jms Connection start.

Prototype


void start() throws JMSException;

Source Link

Document

Starts (or restarts) a connection's delivery of incoming messages.

Usage

From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java

private void sendMessage(BrokerService brokerService, String body) throws Exception {
    TransportConnector connector = brokerService.getTransportConnectors().get(0);
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connector.getConnectUri());
    Connection connection = factory.createConnection();
    try {//from   w  ww. j  av  a  2s  .c o  m
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(session.createQueue("FOO"));
        producer.send(session.createTextMessage(body));
    } finally {
        connection.close();
    }
}

From source file:org.wso2.carbon.esb.scenario.test.common.jms.ActiveMQJMSClient.java

/**
 * Function to retrieve message from specified message queue
 *
 * @param queueName Name of the queue/*from www. j a v  a2  s.co m*/
 * @param timeout Timeout value (in milliseconds)
 * @return Retrieved message from the queue
 * @throws JMSException if error occurred
 */
public Message consumeMessageFromQueue(String queueName, long timeout) throws JMSException {

    Connection connection = null;
    Session session = null;
    MessageConsumer consumer = null;

    try {
        // Create a ConnectionFactory
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);

        // Create a Connection
        connection = connectionFactory.createConnection();
        connection.start();
        connection.setExceptionListener(this);

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

        // Create the destination (Topic or Queue)
        Destination destination = session.createQueue(queueName);

        // Create a MessageConsumer from the Session to the Topic or Queue
        consumer = session.createConsumer(destination);

        // Wait for a message
        return consumer.receive(timeout);

    } finally {
        if (consumer != null) {
            consumer.close();
        }
        if (session != null) {
            session.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java

private ArrayList<String> browseMessagesViaJMS(BrokerService brokerService) throws Exception {
    ArrayList<String> rc = new ArrayList<String>();
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
            "tcp://localhost:" + connectPort(brokerService));
    Connection connection = factory.createConnection();
    try {//from ww w .j  a va 2  s  .  c  o m
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        QueueBrowser browser = session.createBrowser(session.createQueue("FOO"));
        Enumeration enumeration = browser.getEnumeration();
        while (enumeration.hasMoreElements()) {
            TextMessage textMessage = (TextMessage) enumeration.nextElement();
            rc.add(textMessage.getText());
        }
    } finally {
        connection.close();
    }
    return rc;
}

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

protected TopicSubscriber createDurableSubscriber(Connection conn, Destination dest, String name)
        throws Exception {
    conn.setClientID(name);/*from  w  ww .  j av a 2s.  com*/
    connections.add(conn);
    conn.start();

    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    final TopicSubscriber consumer = sess.createDurableSubscriber((javax.jms.Topic) dest, name);

    return consumer;
}

From source file:org.eclipse.smila.connectivity.queue.worker.internal.task.impl.Send.java

/**
 * {@inheritDoc}// ww w  . ja  v a 2  s.c  o m
 * 
 */
@Override
public String[] executeInternal(final TaskExecutionEnv env, final SendType config,
        final Map<String, Properties> idPropertyMap)
        throws TaskExecutionException, BlackboardAccessException, RecordFilterNotFoundException {
    Connection connection = null;
    Session session = null;
    try {
        // get cached connection, if do not cache connections -> socket error when many records pushed
        connection = env.getServices().getBrokerConnections().getConnection(config, true);
        connection.start();
        session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        final Destination destination = session.createQueue(config.getQueue());
        final MessageProducer producer = session.createProducer(destination);
        if (config.isPersistentDelivery()) {
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        } else {
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        }

        final Iterator<Entry<String, Properties>> entries = idPropertyMap.entrySet().iterator();
        while (entries.hasNext()) {
            final Entry<String, Properties> entry = entries.next();
            // get message record, optionally a filtered copy.
            final Record record = createMessageRecord(entry.getKey(), config, env);
            // prepare queue message. messages are actually sent on session.commit() below.
            producer.send(createMessage(config, record, entry.getValue(), session));
        }

        // we must commit here so that the message consumer find the correct record version in storages.
        env.getBlackboard().commit();
        env.setCommitRequired(false);
        // finally send the messages.
        session.commit();

        return idPropertyMap.keySet().toArray(new String[idPropertyMap.size()]);
    } catch (final Throwable e) {
        _log.error(msg("Error"), e);
        rollbackQuietly(session);
        throw new TaskExecutionException(e);
    } finally {
        closeQuietly(session);
        closeQuietly(connection);
    }
}

From source file:biz.fstechnology.micro.server.jms.AbstractJmsService.java

/**
 * @see biz.fstechnology.micro.server.Service#init()
 *///from ww w . ja  v  a  2s.c om
@Override
public void init() throws Exception {
    Connection connection = createJmsTemplate().getConnectionFactory().createConnection();
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(session.createTopic(getListenTopic()));
    consumer.setMessageListener(this);

    replyProducer = session.createProducer(null);
    replyProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

    connection.start();
}

From source file:org.apache.activemq.artemis.tests.integration.amqp.SaslKrb5LDAPSecurityTest.java

public void dotestJAASSecurityManagerAuthorizationPositive(String jaasConfigScope, String artemisRoleName)
        throws Exception {

    createArtemisServer(jaasConfigScope);

    Set<Role> roles = new HashSet<>();
    roles.add(new Role(artemisRoleName, true, true, true, true, true, true, true, true, true, true));
    server.getConfiguration().putSecurityRoles(QUEUE_NAME, roles);
    server.start();//ww w.j ava 2s . c  o  m

    JmsConnectionFactory jmsConnectionFactory = new JmsConnectionFactory(
            "amqp://localhost:5672?amqp.saslMechanisms=GSSAPI");
    Connection connection = jmsConnectionFactory.createConnection("client", null);

    try {
        connection.start();

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

        javax.jms.Queue queue = session.createQueue(QUEUE_NAME);

        // PRODUCE
        final String text = RandomUtil.randomString();

        try {
            MessageProducer producer = session.createProducer(queue);
            producer.send(session.createTextMessage(text));
        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail("should not throw exception here");
        }

        // CONSUME
        try {
            MessageConsumer consumer = session.createConsumer(queue);
            TextMessage m = (TextMessage) consumer.receive(1000);
            Assert.assertNotNull(m);
            Assert.assertEquals(text, m.getText());
        } catch (Exception e) {
            Assert.fail("should not throw exception here");
        }
    } finally {
        connection.close();
    }
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.jms.factory.JMSConnectionFactory.java

public void start(Connection connection) {
    try {//from  www . j  a  va  2  s . co m
        connection.start();
    } catch (JMSException e) {
        logger.error("JMS Exception while starting connection for factory '" + this.connectionFactoryString
                + "' " + e.getMessage(), e);
    }
}

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

public void startConnections() {
    // start connections for consumers
    // it would be better if we could track consumer connections and start
    // only those
    if (!_testConsumers.isEmpty()) {
        for (final Map.Entry<String, Connection> entry : _testConnections.entrySet()) {
            final Connection connection = entry.getValue();
            try {
                connection.start();
            } catch (final JMSException e) {
                throw new DistributedTestException(
                        "Failed to start connection '" + entry.getKey() + "' :" + e.getLocalizedMessage());
            }//  w  w w . j  av  a2 s. c  o  m
        }
    }
}

From source file:org.aludratest.service.jms.impl.JmsActionImpl.java

/**
 * Creates a dynamic connection for the given subscriptionName.
 *
 * According to JavaDoc of {@link TopicSession#createDurableSubscriber(Topic, String, String, boolean)}
 * durablesubscriptions must use the same clientIds on every connection to a particular subscription.
 * Therefore the clientId used for dynamic-connections is derived from the folloging rule:
 *
 * this.userName + "@" + this.getClass().getSimpleName() + "[" + @param subscriptionName + "]"
 *
 * Even new Instances of JmsActionImpl will produce a clientId that is abled to reconnect to existing
 * durable subscriptions.//from   w w  w .  j av a2 s.  co m
 *
 * @param subscriptionName   the subscriptionname
 * @return   The connection.
 *
 * @throws JMSException
  */
private Connection getDynamicConnection(String subscriptionName) throws JMSException {

    final String dynClientID = this.userName + "@" + this.getClass().getSimpleName() + "[" + subscriptionName
            + "]";
    Connection dynC = this.dynamicConnections.get(dynClientID);
    if (dynC == null) {
        dynC = buildConnection(dynClientID);
        this.dynamicConnections.put(dynClientID, dynC);
        dynC.start();
    }
    return dynC;

}