Example usage for javax.jms Connection createSession

List of usage examples for javax.jms Connection createSession

Introduction

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

Prototype


Session createSession(boolean transacted, int acknowledgeMode) throws JMSException;

Source Link

Document

Creates a Session object, specifying transacted and acknowledgeMode .

Usage

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 w  w .  ja  v a2s. 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:de.klemp.middleware.controller.Controller.java

public static void sendMessageFast(String message, String topic) {
    String url = ActiveMQConnection.DEFAULT_BROKER_URL;
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);

    // Create a Connection
    Connection connection;
    try {//  ww  w.  j a  v a2  s.  c om
        connectionFactory.setOptimizeAcknowledge(true);
        connectionFactory.setUseAsyncSend(true);
        connection = connectionFactory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // Create the destination (Topic or Queue)
        Destination destination = session.createTopic(topic);
        // Create a MessageProducer from the Session to the Topic or Queue
        MessageProducer producer = session.createProducer(destination);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        // Create a messages
        TextMessage message1 = session.createTextMessage(message);
        // Tell the producer to send the message
        producer.send(message1);
        session.close();
        connection.close();
    } catch (JMSException e) {
        logger.error("Message could not be sended to activemq", e);
    }

}

From source file:eu.domibus.submission.jms.BackendJMSImpl.java

private Boolean submitErrorMessage(String messageId) {
    Connection connection;
    MessageProducer producer;/* ww  w. jav  a 2 s.c  om*/
    List<ErrorLogEntry> errors = this.errorLogDao.getUnnotifiedErrorsForMessage(messageId);

    try {
        connection = this.cf.createConnection();
        final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producer = session.createProducer(this.receivingQueue);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        final MapMessage resMessage = session.createMapMessage();
        for (int i = 0; i < errors.size(); ++i) {
            resMessage.setString(String.valueOf(i), errors.get(i).toString());
            errors.get(i).setNotified(new Date());
            this.errorLogDao.update(errors.get(i));
        }

        producer.send(resMessage);
        producer.close();
        session.close();

        connection.close();
    } catch (JMSException e) {
        BackendJMSImpl.LOG.error("", e);
        return false;
    }
    return true;
}

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

@Override
public void subscribeTopic(MessageListener listener, @TechnicalLocator String destinationName,
        @TechnicalArgument String messageSelector, @TechnicalArgument String subscriptionName,
        @TechnicalArgument boolean durable) throws JMSException {
    if (StringUtils.isEmpty(subscriptionName)) {
        throw new IllegalArgumentException("subscriptionName must be provided to subscribe!");
    }//from  w w w  .  j av a  2s.c o m
    Topic topic;
    try {
        topic = (Topic) context.lookup(destinationName);
    } catch (NamingException e) {
        throw new AutomationException("Could not lookup destination " + destinationName, e);
    }

    LOGGER.debug("Creating topic-subscriber for topic " + destinationName + " and subscriptionname "
            + subscriptionName);
    Connection c = getDynamicConnection(subscriptionName);

    TopicSession ts = (TopicSession) c.createSession(false, Session.AUTO_ACKNOWLEDGE);
    if (durable) {
        TopicSubscriber subscriber = ts.createDurableSubscriber(topic, subscriptionName, messageSelector,
                false);
        subscriber.setMessageListener(listener);
        this.durableConsumers.put(subscriptionName, subscriber);
    } else {
        ts.createSubscriber(topic, messageSelector, true).setMessageListener(listener);
    }

}

From source file:org.apache.activemq.store.jdbc.JmsTransactionCommitFailureTest.java

private Message receiveMessage(String queueName, long receiveTimeout) throws JMSException {
    Message message = null;//from   w  w  w  .  ja  va 2  s . co  m
    Connection con = connectionFactory.createConnection();
    try {
        con.start();
        try {
            Session session = con.createSession(true, Session.SESSION_TRANSACTED);
            try {
                Queue destination = session.createQueue(queueName);
                MessageConsumer consumer = session.createConsumer(destination);
                try {
                    message = consumer.receive(receiveTimeout);
                    session.commit();
                } finally {
                    consumer.close();
                }
            } finally {
                session.close();
            }
        } finally {
            con.stop();
        }
    } finally {
        con.close();
    }
    return message;
}

From source file:org.apache.activemq.store.kahadb.SubscriptionRecoveryTest.java

private int consumeFromInactiveDurableSub(Topic topic) throws Exception {
    Connection connection = cf.createConnection();
    connection.setClientID("Inactive");
    connection.start();/*w ww .j a va 2s .  co m*/
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createDurableSubscriber(topic, "Inactive");

    int count = 0;

    while (consumer.receive(10000) != null) {
        count++;
    }

    consumer.close();
    connection.close();

    return count;
}

From source file:drepcap.frontend.jms.JmsAdapter.java

/**
 * // w  ww.  j ava 2  s .c  o m
 * Components are typically pcap-sensors or packet-mergers. The component
 * name is the name without any additional suffix, e.g.,
 * "pcap.single.raw.2".
 * 
 * @param connection
 * @param componentName
 * @throws JMSException
 */
public JmsAdapter(Connection connection, String componentName) throws JMSException {
    this.componentName = componentName;
    this.connection = connection;
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    commandTopic = session.createTopic(componentName + ".command");
    commandConsumer = session.createConsumer(commandTopic);
    commandConsumer.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message msg) {
            if (msg instanceof TextMessage) {
                TextMessage textMsg = (TextMessage) msg;
                try {
                    final String txt = textMsg.getText();

                    for (StringReceiver cmdReplyReceiver : commandReplyReceivers) {
                        if (cmdReplyReceiver != null && txt.startsWith("reply")) {
                            cmdReplyReceiver.process(txt.replaceFirst("reply ", ""));
                        }
                    }
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    commandProducer = session.createProducer(commandTopic);

    monitorTopic = session.createTopic(componentName + ".monitor");
    monitorConsumer = session.createConsumer(monitorTopic);
    monitorConsumer.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message msg) {
            if (msg instanceof TextMessage) {
                TextMessage textMsg = (TextMessage) msg;
                try {
                    final String txt = textMsg.getText();

                    for (StringReceiver monReceiver : monitorReceivers) {
                        if (monReceiver != null) {
                            monReceiver.process(txt);
                        }
                    }

                    if (statsDataReceivers.size() > 0) {
                        processStatsFromString(txt);
                    }
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    });
}

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

public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception {
    bridge(SPOKE, HUB);//from   www. j  av  a 2s .com
    startAllBrokers();

    verifyDuplexBridgeMbean();

    // Setup connection
    URI hubURI = brokers.get(HUB).broker.getTransportConnectors().get(0).getPublishableConnectURI();
    URI spokeURI = brokers.get(SPOKE).broker.getTransportConnectors().get(0).getPublishableConnectURI();
    ActiveMQConnectionFactory facHub = new ActiveMQConnectionFactory(hubURI);
    ActiveMQConnectionFactory facSpoke = new ActiveMQConnectionFactory(spokeURI);
    Connection conHub = facHub.createConnection();
    Connection conSpoke = facSpoke.createConnection();
    conHub.setClientID("clientHUB");
    conSpoke.setClientID("clientSPOKE");
    conHub.start();
    conSpoke.start();
    Session sesHub = conHub.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Session sesSpoke = conSpoke.createSession(false, Session.AUTO_ACKNOWLEDGE);

    ActiveMQTopic topic = new ActiveMQTopic("TEST.FOO");
    String consumerName = "consumerName";

    // Setup consumers
    MessageConsumer remoteConsumer = sesHub.createDurableSubscriber(topic, consumerName);
    sleep(1000);
    remoteConsumer.close();

    // Setup producer
    MessageProducer localProducer = sesSpoke.createProducer(topic);
    localProducer.setDeliveryMode(DeliveryMode.PERSISTENT);

    final String payloadString = new String(new byte[10 * 1024]);
    // Send messages
    for (int i = 0; i < MESSAGE_COUNT; i++) {
        Message test = sesSpoke.createTextMessage("test-" + i);
        test.setStringProperty("payload", payloadString);
        localProducer.send(test);
    }
    localProducer.close();

    final String options = "?persistent=true&useJmx=true&deleteAllMessagesOnStartup=false";
    for (int i = 0; i < 2; i++) {
        brokers.get(SPOKE).broker.stop();
        sleep(1000);
        createBroker(new URI("broker:(tcp://localhost:61616)/" + SPOKE + options));
        bridge(SPOKE, HUB);
        brokers.get(SPOKE).broker.start();
        LOG.info("restarted spoke..:" + i);

        assertTrue("got mbeans on restart", Wait.waitFor(new Wait.Condition() {
            @Override
            public boolean isSatisified() throws Exception {
                return countMbeans(brokers.get(HUB).broker, "networkBridge", 20000) == (dynamicOnly ? 1 : 2);
            }
        }));
    }
}

From source file:com.opengamma.examples.analyticservice.ExampleAnalyticServiceUsage.java

private void pushTrade(String securityId, Connection connection, String destinationName,
        JmsConnector jmsConnector, JmsByteArrayMessageDispatcher jmsDispatcher) {
    String providerId = generateTrade(securityId, destinationName, jmsConnector);
    String topicStr = PREFIX + SEPARATOR + providerId + SEPARATOR + "Default" + SEPARATOR
            + ValueRequirementNames.FAIR_VALUE;
    try {//from w ww.j  a va2 s.com
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic(topicStr);
        final MessageConsumer messageConsumer = session.createConsumer(topic);
        messageConsumer.setMessageListener(jmsDispatcher);
    } catch (JMSException e) {
        throw new OpenGammaRuntimeException("Failed to create subscription to JMS topics ", e);
    }
}

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  w  w  w  .jav a2  s.co  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]);
}