Example usage for javax.jms Session commit

List of usage examples for javax.jms Session commit

Introduction

In this page you can find the example usage for javax.jms Session commit.

Prototype


void commit() throws JMSException;

Source Link

Document

Commits all messages done in this transaction and releases any locks currently held.

Usage

From source file:example.transaction.Client.java

private static void acceptInputFromUser(Session senderSession, MessageProducer sender) throws JMSException {
    System.out.println("Type a message. Type COMMIT to send to receiver, type ROLLBACK to cancel");
    Scanner inputReader = new Scanner(System.in);

    while (true) {
        String line = inputReader.nextLine();
        if (line == null) {
            System.out.println("Done!");
            break;
        } else if (line.length() > 0) {
            if (line.trim().equals("ROLLBACK")) {
                System.out.println("Rolling back...");
                senderSession.rollback();
                System.out.println("Messages have been rolledback");
            } else if (line.trim().equals("COMMIT")) {
                System.out.println("Committing... ");
                senderSession.commit();
                System.out.println("Messages should have been sent");
            } else {
                TextMessage message = senderSession.createTextMessage();
                message.setText(line);/* ww w .j ava2 s.  co m*/
                System.out.println("Batching up:'" + message.getText() + "'");
                sender.send(message);
            }
        }
    }
}

From source file:ProducerTool.java

protected void sendLoop(Session session, MessageProducer producer) throws Exception {

    for (int i = 0; i < messageCount || messageCount == 0; i++) {

        TextMessage message = session.createTextMessage(createMessageText(i));

        if (verbose) {
            String msg = message.getText();
            if (msg.length() > 50) {
                msg = msg.substring(0, 50) + "...";
            }/*from   w w  w .  ja v a  2s .  com*/
            System.out.println("[" + this.getName() + "] Sending message: '" + msg + "'");
        }

        producer.send(message);

        if (transacted && (i % batch == 0)) {
            System.out.println("[" + this.getName() + "] Committing " + messageCount + " messages");
            session.commit();
        }
        Thread.sleep(sleepTime);
    }
}

From source file:Supplier.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    Session session = null;
    Destination orderQueue;/*  w  w  w .ja va 2s .  c  o m*/
    try {
        Connection connection = connectionFactory.createConnection();

        session = connection.createSession(true, Session.SESSION_TRANSACTED);
        orderQueue = session.createQueue(QUEUE);
        MessageConsumer consumer = session.createConsumer(orderQueue);

        connection.start();

        while (true) {
            Message message = consumer.receive();
            MessageProducer producer = session.createProducer(message.getJMSReplyTo());
            MapMessage orderMessage;
            if (message instanceof MapMessage) {
                orderMessage = (MapMessage) message;
            } else {
                // End of Stream
                producer.send(session.createMessage());
                session.commit();
                producer.close();
                break;
            }

            int quantity = orderMessage.getInt("Quantity");
            System.out.println(
                    ITEM + " Supplier: Vendor ordered " + quantity + " " + orderMessage.getString("Item"));

            MapMessage outMessage = session.createMapMessage();
            outMessage.setInt("VendorOrderNumber", orderMessage.getInt("VendorOrderNumber"));
            outMessage.setString("Item", ITEM);

            quantity = Math.min(orderMessage.getInt("Quantity"),
                    new Random().nextInt(orderMessage.getInt("Quantity") * 10));
            outMessage.setInt("Quantity", quantity);

            producer.send(outMessage);
            System.out.println(ITEM + " Supplier: Sent " + quantity + " " + ITEM + "(s)");
            session.commit();
            System.out.println(ITEM + " Supplier: committed transaction");
            producer.close();
        }
        connection.close();
    } catch (JMSException e) {
        e.printStackTrace();
    }
}

From source file:org.ahp.core.messaging.AhpJmsProducer.java

public void sendTextMessage(String pTextMessage, AhpJmsDestinationTypes pAhpJmsDestinationTypes,
        AhpJmsDestinationNames pAhpJmsDestinationNames) {
    Connection lConnection = null;
    Session lSession = null;
    try {/*from w ww.  ja  va2 s  . c  om*/
        lConnection = this.mJmsConnectionFactory.createConnection();
        lSession = lConnection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        Destination lDestination = null;
        if (pAhpJmsDestinationTypes.equals(AhpJmsDestinationTypes.Queue))
            lDestination = lSession.createQueue(pAhpJmsDestinationNames.toString());
        else
            lDestination = lSession.createTopic(pAhpJmsDestinationNames.toString());
        MessageProducer lMessageProducer = lSession.createProducer(lDestination);
        lMessageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
        //lMessageProducer.setTimeToLive( timeToLive );
        Message lTextMessage = lSession.createTextMessage(pTextMessage);
        LOGGER.debug("AhpJmsProducer sending message to Destination " + pAhpJmsDestinationNames.toString()
                + " TextMessage :: \n" + pTextMessage);
        lMessageProducer.send(lTextMessage);
        lSession.commit();
    } catch (JMSException exJms) {
        LOGGER.error("", exJms);
    } finally {
        try {
            lConnection.close();
        } catch (JMSException exJms) {
            LOGGER.error("", exJms);
        }
    }
}

From source file:Vendor.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    Session session = null;
    Destination orderQueue;/*from  w w w.  j  a  va2  s. c o  m*/
    Destination monitorOrderQueue;
    Destination storageOrderQueue;
    TemporaryQueue vendorConfirmQueue;
    MessageConsumer orderConsumer = null;
    MessageProducer monitorProducer = null;
    MessageProducer storageProducer = null;

    try {
        Connection connection = connectionFactory.createConnection();

        session = connection.createSession(true, Session.SESSION_TRANSACTED);
        orderQueue = session.createQueue("VendorOrderQueue");
        monitorOrderQueue = session.createQueue("MonitorOrderQueue");
        storageOrderQueue = session.createQueue("StorageOrderQueue");

        orderConsumer = session.createConsumer(orderQueue);
        monitorProducer = session.createProducer(monitorOrderQueue);
        storageProducer = session.createProducer(storageOrderQueue);

        Connection asyncconnection = connectionFactory.createConnection();
        asyncSession = asyncconnection.createSession(true, Session.SESSION_TRANSACTED);

        vendorConfirmQueue = asyncSession.createTemporaryQueue();
        MessageConsumer confirmConsumer = asyncSession.createConsumer(vendorConfirmQueue);
        confirmConsumer.setMessageListener(this);

        asyncconnection.start();

        connection.start();

        while (true) {
            Order order = null;
            try {
                Message inMessage = orderConsumer.receive();
                MapMessage message;
                if (inMessage instanceof MapMessage) {
                    message = (MapMessage) inMessage;

                } else {
                    // end of stream
                    Message outMessage = session.createMessage();
                    outMessage.setJMSReplyTo(vendorConfirmQueue);
                    monitorProducer.send(outMessage);
                    storageProducer.send(outMessage);
                    session.commit();
                    break;
                }

                // Randomly throw an exception in here to simulate a Database error
                // and trigger a rollback of the transaction
                if (new Random().nextInt(3) == 0) {
                    throw new JMSException("Simulated Database Error.");
                }

                order = new Order(message);

                MapMessage orderMessage = session.createMapMessage();
                orderMessage.setJMSReplyTo(vendorConfirmQueue);
                orderMessage.setInt("VendorOrderNumber", order.getOrderNumber());
                int quantity = message.getInt("Quantity");
                System.out.println("Vendor: Retailer ordered " + quantity + " " + message.getString("Item"));

                orderMessage.setInt("Quantity", quantity);
                orderMessage.setString("Item", "Monitor");
                monitorProducer.send(orderMessage);
                System.out.println("Vendor: ordered " + quantity + " Monitor(s)");

                orderMessage.setString("Item", "HardDrive");
                storageProducer.send(orderMessage);
                System.out.println("Vendor: ordered " + quantity + " Hard Drive(s)");

                session.commit();
                System.out.println("Vendor: Comitted Transaction 1");

            } catch (JMSException e) {
                System.out.println("Vendor: JMSException Occured: " + e.getMessage());
                e.printStackTrace();
                session.rollback();
                System.out.println("Vendor: Rolled Back Transaction.");
            }
        }

        synchronized (supplierLock) {
            while (numSuppliers > 0) {
                try {
                    supplierLock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        connection.close();
        asyncconnection.close();

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

}

From source file:nl.nn.adapterframework.jms.PullingJmsListener.java

public void afterMessageProcessed(PipeLineResult plr, Object rawMessage, Map threadContext)
        throws ListenerException {
    String cid = (String) threadContext.get(IPipeLineSession.technicalCorrelationIdKey);

    if (log.isDebugEnabled())
        log.debug(getLogPrefix() + "in PullingJmsListener.afterMessageProcessed()");

    try {/*from  ww  w . ja  v a  2  s. c o  m*/
        Destination replyTo = (Destination) threadContext.get("replyTo");

        // handle reply
        if (isUseReplyTo() && (replyTo != null)) {
            Session session = null;

            log.debug(getLogPrefix() + "sending reply message with correlationID [" + cid + "], replyTo ["
                    + replyTo.toString() + "]");
            long timeToLive = getReplyMessageTimeToLive();
            boolean ignoreInvalidDestinationException = false;
            if (timeToLive == 0) {
                Message messageSent = (Message) rawMessage;
                long expiration = messageSent.getJMSExpiration();
                if (expiration != 0) {
                    timeToLive = expiration - new Date().getTime();
                    if (timeToLive <= 0) {
                        log.warn(getLogPrefix() + "message [" + cid + "] expired [" + timeToLive
                                + "]ms, sending response with 1 second time to live");
                        timeToLive = 1000;
                        // In case of a temporary queue it might already
                        // have disappeared.
                        ignoreInvalidDestinationException = true;
                    }
                }
            }
            if (threadContext != null) {
                session = (Session) threadContext.get(THREAD_CONTEXT_SESSION_KEY);
            }
            if (session == null) {
                try {
                    session = getSession(threadContext);
                    send(session, replyTo, cid, prepareReply(plr.getResult(), threadContext),
                            getReplyMessageType(), timeToLive, stringToDeliveryMode(getReplyDeliveryMode()),
                            getReplyPriority(), ignoreInvalidDestinationException);
                } finally {
                    releaseSession(session);
                }
            } else {
                send(session, replyTo, cid, plr.getResult(), getReplyMessageType(), timeToLive,
                        stringToDeliveryMode(getReplyDeliveryMode()), getReplyPriority(),
                        ignoreInvalidDestinationException);
            }
        } else {
            if (getSender() == null) {
                log.debug(getLogPrefix()
                        + "itself has no sender to send the result (An enclosing Receiver might still have one).");
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(getLogPrefix()
                            + "no replyTo address found or not configured to use replyTo, using default destination"
                            + "sending message with correlationID[" + cid + "] [" + plr.getResult() + "]");
                }
                getSender().sendMessage(cid, plr.getResult());
            }
        }

        // TODO Do we still need this? Should we rollback too? See
        // PushingJmsListener.afterMessageProcessed() too (which does a
        // rollback, but no commit).
        if (!isTransacted()) {
            if (isJmsTransacted()) {
                // the following if transacted using transacted sessions, instead of XA-enabled sessions.
                Session session = (Session) threadContext.get(THREAD_CONTEXT_SESSION_KEY);
                if (session == null) {
                    log.warn("Listener [" + getName() + "] message [" + (String) threadContext.get("id")
                            + "] has no session to commit or rollback");
                } else {
                    String successState = getCommitOnState();
                    if (successState != null && successState.equals(plr.getState())) {
                        session.commit();
                    } else {
                        log.warn("Listener [" + getName() + "] message [" + (String) threadContext.get("id")
                                + "] not committed nor rolled back either");
                        //TODO: enable rollback, or remove support for JmsTransacted altogether (XA-transactions should do it all)
                        // session.rollback();
                    }
                    if (isSessionsArePooled()) {
                        threadContext.remove(THREAD_CONTEXT_SESSION_KEY);
                        releaseSession(session);
                    }
                }
            } else {
                // TODO: dit weghalen. Het hoort hier niet, en zit ook al in getIdFromRawMessage. Daar hoort het ook niet, overigens...
                if (getAckMode() == Session.CLIENT_ACKNOWLEDGE) {
                    log.debug("[" + getName() + "] acknowledges message with id [" + cid + "]");
                    ((TextMessage) rawMessage).acknowledge();
                }
            }
        }
    } catch (Exception e) {
        throw new ListenerException(e);
    }
}

From source file:nl.nn.adapterframework.unmanaged.SpringJmsConnector.java

public void onMessage(Message message, Session session) throws JMSException {
    TransactionStatus txStatus = null;/*from w ww  .j av a  2s  .  c om*/

    long onMessageStart = System.currentTimeMillis();
    long jmsTimestamp = message.getJMSTimestamp();
    threadsProcessing.increase();
    Thread.currentThread().setName(getReceiver().getName() + "[" + threadsProcessing.getValue() + "]");

    try {
        if (TX != null) {
            txStatus = txManager.getTransaction(TX);
        }

        Map threadContext = new HashMap();
        try {
            IPortConnectedListener listener = getListener();
            threadContext.put(THREAD_CONTEXT_SESSION_KEY, session);
            //            if (log.isDebugEnabled()) log.debug("transaction status before: "+JtaUtil.displayTransactionStatus());
            getReceiver().processRawMessage(listener, message, threadContext);
            //            if (log.isDebugEnabled()) log.debug("transaction status after: "+JtaUtil.displayTransactionStatus());
        } catch (ListenerException e) {
            getReceiver().increaseRetryIntervalAndWait(e, getLogPrefix());
            if (txStatus != null) {
                txStatus.setRollbackOnly();
            }
        } finally {
            if (txStatus == null && jmsContainer.isSessionTransacted()) {
                log.debug(getLogPrefix() + "committing JMS session");
                session.commit();
            }
        }
    } finally {
        if (txStatus != null) {
            txManager.commit(txStatus);
        }
        threadsProcessing.decrease();
        if (log.isInfoEnabled()) {
            long onMessageEnd = System.currentTimeMillis();

            log.info(getLogPrefix() + "A) JMSMessageTime [" + DateUtils.format(jmsTimestamp) + "]");
            log.info(getLogPrefix() + "B) onMessageStart [" + DateUtils.format(onMessageStart)
                    + "] diff (~'queing' time) [" + (onMessageStart - jmsTimestamp) + "]");
            log.info(getLogPrefix() + "C) onMessageEnd   [" + DateUtils.format(onMessageEnd)
                    + "] diff (process time) [" + (onMessageEnd - onMessageStart) + "]");
        }

        //         boolean simulateCrashAfterCommit=true;
        //         if (simulateCrashAfterCommit) {
        //            toggle=!toggle;
        //            if (toggle) {
        //               JtaUtil.setRollbackOnly();
        //               throw new JMSException("simulate crash just before final commit");
        //            }
        //         }
    }
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testQueueLargeMessageSizeTX() throws Exception {

    ActiveMQConnectionFactory acf = (ActiveMQConnectionFactory) cf;
    acf.setMinLargeMessageSize(1000);//  w w w .j  a v a  2 s . co  m
    Connection connection = cf.createConnection();
    connection.start();
    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);

    String testText = StringUtils.repeat("t", 2000);
    MessageProducer producer = session.createProducer(session.createQueue(defaultQueueName));
    ActiveMQTextMessage message = (ActiveMQTextMessage) session.createTextMessage(testText);
    for (int i = 0; i < 10; i++) {
        producer.send(message);
    }

    //not commited so should be 0
    verifyPendingStats(defaultQueueName, 0, message.getCoreMessage().getPersistentSize() * 10);
    verifyPendingDurableStats(defaultQueueName, 0, message.getCoreMessage().getPersistentSize() * 10);

    session.commit();

    verifyPendingStats(defaultQueueName, 10, message.getCoreMessage().getPersistentSize() * 10);
    verifyPendingDurableStats(defaultQueueName, 10, message.getCoreMessage().getPersistentSize() * 10);

    connection.close();

    this.killServer();
    this.restartServer();

    verifyPendingStats(defaultQueueName, 10, message.getCoreMessage().getPersistentSize());
    verifyPendingDurableStats(defaultQueueName, 10, message.getCoreMessage().getPersistentSize());
}

From source file:org.apache.activemq.bugs.AMQ7067Test.java

@Test
public void testCommit() throws Exception {
    final Connection connection = ACTIVE_MQ_NON_XA_CONNECTION_FACTORY.createConnection();
    connection.start();/*from w  ww.  j a va  2s.c o m*/

    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    Queue holdKahaDb = session.createQueue("holdKahaDb");
    MessageProducer holdKahaDbProducer = session.createProducer(holdKahaDb);
    TextMessage helloMessage = session.createTextMessage(StringUtils.repeat("a", 10));
    holdKahaDbProducer.send(helloMessage);
    Queue queue = session.createQueue("test");
    produce(connection, queue, 100, 512 * 1024);
    session.commit();
    produce(connection, queue, 100, 512 * 1024);

    System.out.println(String.format("QueueSize %s: %d", holdKahaDb.getQueueName(),
            getQueueSize(holdKahaDb.getQueueName())));
    purgeQueue(queue.getQueueName());
    Wait.waitFor(new Wait.Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            return 0 == getQueueSize(queue.getQueueName());
        }
    });

    // force gc
    broker.getPersistenceAdapter().checkpoint(true);

    connection.close();
    curruptIndexFile(getDataDirectory());

    broker.stop();
    broker.waitUntilStopped();
    createBroker();
    broker.waitUntilStarted();

    while (true) {
        try {
            TimeUnit.SECONDS.sleep(1);
            System.out.println(String.format("QueueSize %s: %d", holdKahaDb.getQueueName(),
                    getQueueSize(holdKahaDb.getQueueName())));
            break;
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            break;
        }
    }

    // THIS SHOULD NOT FAIL AS THERE SHOULD BE ONLY 1 TRANSACTION!
    assertEquals(1, getQueueSize(holdKahaDb.getQueueName()));
}

From source file:org.apache.activemq.bugs.AMQ7067Test.java

protected static void produce(Connection connection, Queue queue, int messageCount, int messageSize)
        throws JMSException, IOException, XAException {
    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    MessageProducer producer = session.createProducer(queue);

    for (int i = 0; i < messageCount; i++) {
        TextMessage helloMessage = session.createTextMessage(StringUtils.repeat("a", messageSize));
        producer.send(helloMessage);/*from  ww w.  j a v  a  2 s .co  m*/
        session.commit();

    }
}