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:com.fusesource.forge.jmstest.tests.AsyncProducer.java

public void run() {

    try {//from ww w  .ja v  a 2s . co  m
        Connection conn = getConnection();
        Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

        if (isExpectReply()) {
            Destination replyTo = getDestinationProvider().getDestination(session, getReplyDestination());
            MessageConsumer consumer = session.createConsumer(replyTo);
            consumer.setMessageListener(this);
        }

        Destination dest = getDestinationProvider().getDestination(session, getDestinationName());
        MessageProducer producer = session.createProducer(dest);
        producer.setDeliveryMode(getDeliveryMode().getCode());
        getConnection().start();

        LOG.info(">>Starting Message send loop");
        while (!done.get()) {
            try {
                locallySent++;
                Destination replyDest = null;
                Message msg = getMessageFactory().createMessage(session);
                if (getMsgGroup() != null) {
                    LOG.debug("Setting message group to : " + getMsgGroup());
                    msg.setStringProperty("JMSXGroupID", getMsgGroup());
                    if (getMessagesToSend() > 0) {
                        if (locallySent == getMessagesToSend()) {
                            LOG.debug("Closing message group: " + getMsgGroup());
                            msg.setIntProperty("JMSXGroupSeq", 0);
                        }
                    }
                }
                msg.setLongProperty("MsgNr", locallySent);
                if (isExpectReply()) {
                    corrId = getReplyDestination() + "Seq-" + locallySent;
                    msg.setStringProperty("JMSCorrelationID", corrId);
                    replyDest = getDestinationProvider().getDestination(session, getReplyDestination());
                    msg.setJMSReplyTo(replyDest);
                    receivedResponse = false;
                }
                long sendTime = System.currentTimeMillis();
                producer.send(msg, deliveryMode.getCode(), 4, ttl);
                if (sent != null) {
                    sent.incrementAndGet();
                }
                done.set((getMessagesToSend() > 0) && ((locallySent) == getMessagesToSend()));
                if (isExpectReply()) {
                    try {
                        LOG.debug("Waiting for response ...");
                        synchronized (corrId) {
                            try {
                                if (getReplyTimeOut() > 0) {
                                    corrId.wait(getReplyTimeOut());
                                } else {
                                    corrId.wait();
                                }
                            } catch (InterruptedException ie) {
                            }
                            if (receivedResponse) {
                                long duration = System.currentTimeMillis() - sendTime;
                                LOG.debug("Got response from peer in " + duration + " ms");
                            } else {
                                LOG.error("Response not received within time frame...");
                                if (timeOuts != null) {
                                    timeOuts.incrementAndGet();
                                }
                            }
                        }
                    } catch (Exception e) {
                        if (exceptions != null) {
                            exceptions.incrementAndGet();
                        }
                    }
                }
                if (sleep > 0L) {
                    try {
                        Thread.sleep(sleep);
                    } catch (InterruptedException ie) {
                    }
                }
            } catch (JMSException e) {
                if (exceptions != null) {
                    exceptions.incrementAndGet();
                }
            }
        }
    } catch (Exception e) {
    } finally {
        try {
            closeConnection();
        } catch (Throwable e) {
        }
    }
    LOG.info(">>MessageSender done...(" + sent + ")");
}

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

private void sendMessages(Destination destination, int count) throws Exception {
    Connection connection = cf.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    for (int i = 0; i < count; ++i) {
        TextMessage message = session.createTextMessage("Message #" + i + " for destination: " + destination);
        producer.send(message);/*  w ww.  j  a v a2s .  c  o  m*/
    }
    connection.close();
}

From source file:com.jaliansystems.activeMQLite.impl.RepositoryService.java

/**
 * Instantiates a new repository service.
 *
 * The queueNamePrefix is used to create a JMS queue with the name appending "-request" to it.
 * //from w w w .  java  2  s.  c om
 * @param connection the connection
 * @param brokerURL the broker url
 * @param queueNamePrefix the queue name prefix
 * @param objectRepository the object repository
 * @param client the client
 * @throws Exception the exception
 */
public RepositoryService(Connection connection, String brokerURL, String queueNamePrefix,
        ObjectRepository objectRepository, RepositoryClient client) throws Exception {
    this.objectRepository = objectRepository;
    this.client = client;

    sessionService = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination requestQueue = sessionService.createQueue(queueNamePrefix + "-request");
    MessageConsumer requestConsumer = sessionService.createConsumer(requestQueue);
    requestConsumer.setMessageListener(this);

    responseProducer = sessionService.createProducer(null);
    responseProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
}

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();//from  w w  w  .j  a  v a  2  s.co  m

    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:org.genemania.broker.Worker.java

private void startNewConnection() throws JMSException {
    PooledConnectionFactory connectionFactory = new PooledConnectionFactory(brokerUrl);
    Connection connection = connectionFactory.createConnection();
    connection.setExceptionListener(this);
    connection.start();//from   ww  w.  ja  v a 2 s  . c o m
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    responseHandler = session.createProducer(null);
    Queue requestsQueue = session.createQueue(mqRequestsQueueName);
    requestHandler = session.createConsumer(requestsQueue);
    requestHandler.setMessageListener(this);
    LOG.info("Listening to " + requestsQueue.getQueueName());
}

From source file:com.jaliansystems.activeMQLite.impl.RepositoryClient.java

/**
 * Instantiates a new repository client.
 * /*from   w  w w. j  ava 2  s.  c om*/
 * @param connection
 *            the connection
 * @param brokerURL
 *            the broker url
 * @param objectRepository
 *            the object repository
 * @throws Exception
 *             the exception
 */
public RepositoryClient(Connection connection, String brokerURL, ObjectRepository objectRepository)
        throws Exception {
    this.objectRepository = objectRepository;

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

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

    responseQueue = session.createTemporaryQueue();
    responseConsumer = session.createConsumer(responseQueue);
    responseConsumer.setMessageListener(this);
}

From source file:org.apache.camel.component.sjms.SjmsConsumer.java

/**
 * Creates a {@link MessageConsumerResources} with a dedicated
 * {@link Session} required for transacted and InOut consumers.
 *///from   www.j a  v  a  2s  .  c o m
private MessageConsumerResources createConsumer() throws Exception {
    MessageConsumerResources answer;
    Connection conn = getConnectionResource().borrowConnection();
    try {
        Session session = conn.createSession(isTransacted(),
                isTransacted() ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE);
        Destination destination = getEndpoint().getDestinationCreationStrategy().createDestination(session,
                getDestinationName(), isTopic());
        MessageConsumer messageConsumer = JmsObjectFactory.createMessageConsumer(session, destination,
                getMessageSelector(), isTopic(), getDurableSubscriptionId());
        MessageListener handler = createMessageHandler(session);
        messageConsumer.setMessageListener(handler);

        answer = new MessageConsumerResources(session, messageConsumer);
    } catch (Exception e) {
        log.error("Unable to create the MessageConsumer", e);
        throw e;
    } finally {
        getConnectionResource().returnConnection(conn);
    }
    return answer;
}

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

private void sendMessage(String queueName, int count, boolean transacted) throws JMSException {
    Connection con = connectionFactory.createConnection();
    try {/*from w  ww  .  j  a v  a  2  s  .  c o m*/
        Session session = con.createSession(transacted,
                transacted ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE);
        try {
            Queue destination = session.createQueue(queueName);
            MessageProducer producer = session.createProducer(destination);
            try {
                for (int i = 0; i < count; i++) {
                    TextMessage message = session.createTextMessage();
                    message.setIntProperty("MessageId", messageCounter);
                    message.setText("Message-" + messageCounter++);
                    producer.send(message);
                }
                if (transacted) {
                    session.commit();
                }
            } finally {
                producer.close();
            }
        } finally {
            session.close();
        }
    } finally {
        con.close();
    }
}

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

private void createInactiveDurableSub(Topic topic) throws Exception {
    Connection connection = cf.createConnection();
    connection.setClientID("Inactive");
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createDurableSubscriber(topic, "Inactive");
    consumer.close();/*from  w  ww .ja va 2  s . c  o  m*/
    connection.close();
}

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

/**
 * This method checks for pending messages received by another gateway and processes them to a JMS destination
 *
 * @param ctx//from  www . ja  v  a  2  s .c o  m
 */
public void executeInternal(final JobExecutionContext ctx) {
    try {

        final Collection<String> ids = this.messageRetriever.listPendingMessages();

        if (!ids.isEmpty() || ids.size() > 0) {
            final String[] messageIds = ids.toArray(new String[ids.size()]);

            Connection connection;
            MessageProducer producer;

            connection = this.cf.createConnection();
            for (final String messageId : messageIds) {
                final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                producer = session.createProducer(this.receivingQueue);
                producer.setDeliveryMode(DeliveryMode.PERSISTENT);
                final MapMessage resMessage = session.createMapMessage();
                this.downloadMessage(messageId, resMessage);
                producer.send(resMessage);
                producer.close();
                session.close();
            }
            connection.close();
        } else {
            BackendJMSImpl.LOG.debug("No pending messages to send");
        }

    } catch (final JMSException | ValidationException ex) {
        BackendJMSImpl.LOG.error(ex);
    }
}