Example usage for javax.jms Session rollback

List of usage examples for javax.jms Session rollback

Introduction

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

Prototype


void rollback() throws JMSException;

Source Link

Document

Rolls back any 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();//from  w  w  w.  jav a2  s . co  m
                System.out.println("Messages should have been sent");
            } else {
                TextMessage message = senderSession.createTextMessage();
                message.setText(line);
                System.out.println("Batching up:'" + message.getText() + "'");
                sender.send(message);
            }
        }
    }
}

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 ava 2  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.PushingJmsListener.java

public void afterMessageProcessed(PipeLineResult plr, Object rawMessage, Map threadContext)
        throws ListenerException {
    String cid = (String) threadContext.get(IPipeLineSession.technicalCorrelationIdKey);
    Session session = (Session) threadContext.get(jmsConnector.THREAD_CONTEXT_SESSION_KEY); // session is/must be saved in threadcontext by JmsConnector

    if (log.isDebugEnabled())
        log.debug(getLogPrefix() + "in PushingJmsListener.afterMessageProcessed()");
    try {/* w w w  .j  ava  2  s.  c  o m*/
        Destination replyTo = (Destination) threadContext.get("replyTo");

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

            log.debug("sending reply message with correlationID[" + cid + "], replyTo [" + replyTo.toString()
                    + "]");
            long timeToLive = getReplyMessageTimeToLive();
            boolean ignoreInvalidDestinationException = false;
            if (timeToLive == 0) {
                Message messageReceived = (Message) rawMessage;
                long expiration = messageReceived.getJMSExpiration();
                if (expiration != 0) {
                    timeToLive = expiration - new Date().getTime();
                    if (timeToLive <= 0) {
                        log.warn("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;
                    }
                }
            }
            Map properties = getMessagePropertiesToSet(threadContext);
            send(session, replyTo, cid, prepareReply(plr.getResult(), threadContext), getReplyMessageType(),
                    timeToLive, stringToDeliveryMode(getReplyDeliveryMode()), getReplyPriority(),
                    ignoreInvalidDestinationException, properties);
        } else {
            if (getSender() == null) {
                log.info("[" + getName() + "] has no sender, not sending the result.");
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("[" + getName()
                            + "] 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 commit too? See
        // PullingJmsListener.afterMessageProcessed() too (which does a
        // commit, but no rollback).
        if (plr != null && !isTransacted() && isJmsTransacted() && StringUtils.isNotEmpty(getCommitOnState())
                && !getCommitOnState().equals(plr.getState())) {
            if (session == null) {
                log.error(getLogPrefix() + "session is null, cannot roll back session");
            } else {
                log.warn(getLogPrefix() + "got exit state [" + plr.getState() + "], rolling back session");
                session.rollback();
            }
        }
    } catch (Exception e) {
        if (e instanceof ListenerException) {
            throw (ListenerException) e;
        } else {
            throw new ListenerException(e);
        }
    }
}

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

@Test
public void testRollback() throws Exception {
    final Connection connection = ACTIVE_MQ_NON_XA_CONNECTION_FACTORY.createConnection();
    connection.start();/*from   www .  j av  a 2s.c  om*/

    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.rollback();
    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();

    // no sign of the test queue on recovery, rollback is the default for any inflight
    // this test serves as a sanity check on existing behaviour
    try {
        getQueueSize(holdKahaDb.getQueueName());
        fail("expect InstanceNotFoundException");
    } catch (UndeclaredThrowableException expected) {
        assertTrue(expected.getCause() instanceof InstanceNotFoundException);
    }
}

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

/**
 * This test demonstrates how the "disposeOnDisonnect" feature of
 * VMTransportServer can incorrectly close all VM connections to the local
 * broker.//from  w w w.  j  av a2  s.c  o m
 */
public void testPrematureClosure() throws Exception {

    // Open a persistent connection to the local broker. The persistent
    // connection is maintained through the test and should prevent the
    // VMTransportServer from stopping itself when the local transport is
    // closed.
    ActiveMQConnection persistentConn = (ActiveMQConnection) createConnection();
    persistentConn.start();
    Session session = persistentConn.createSession(true, Session.SESSION_TRANSACTED);
    MessageProducer producer = session.createProducer(destination);

    for (int i = 0; i < NUM_ATTEMPTS; i++) {
        LOG.info("Attempt: " + i);

        // Open and close a local transport connection. As is done by by
        // most users of the transport, ensure that the transport is stopped
        // when closed by the peer (via ShutdownInfo). Closing the local
        // transport should not affect the persistent connection.
        final Transport localTransport = TransportFactory.connect(broker.getVmConnectorURI());
        localTransport.setTransportListener(new TransportListener() {
            public void onCommand(Object command) {
                if (command instanceof ShutdownInfo) {
                    try {
                        localTransport.stop();
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }

            public void onException(IOException error) {
                // ignore
            }

            public void transportInterupted() {
                // ignore
            }

            public void transportResumed() {
                // ignore
            }
        });

        localTransport.start();
        localTransport.stop();

        // Ensure that the persistent connection is still usable.
        producer.send(session.createMessage());
        session.rollback();
    }

    persistentConn.close();
}

From source file:org.apache.james.queue.jms.JMSMailQueue.java

protected static void rollback(Session session) {
    if (session != null) {
        try {/*w  w  w.j a va2s.c o m*/
            session.rollback();
        } catch (JMSException e) {
            LOGGER.error("Error while rolling session back", e);
        }
    }
}

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

public void rollbackOrRecoverIfNecessary(String sessionName) {
    try {/* w w w.j av a 2  s.  c o m*/
        final Session session = _testSessions.get(sessionName);
        synchronized (session) {
            if (session.getTransacted()) {
                session.rollback();
            } else if (session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE) {
                session.recover();
            }
        }
    } catch (final JMSException jmse) {
        throw new DistributedTestException("Unable to rollback or recover on session: " + sessionName, jmse);
    }
}

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

/**
 * rollback session if not null, catching and logging possible exceptions.
 * /*  w  w w. j  av  a2s. c o  m*/
 * @param session
 *          a JMS session
 */
private void rollbackQuietly(final Session session) {
    if (session != null) {
        try {
            session.rollback();
        } catch (final Throwable e1) {
            _log.error("Unable to rollback session", e1);
        }
    }
}

From source file:org.springframework.jms.support.JmsUtils.java

/**
 * Rollback the Session if not within a JTA transaction.
 * @param session the JMS Session to rollback
 * @throws JMSException if committing failed
 *//*from www  .j av a  2  s .  com*/
public static void rollbackIfNecessary(Session session) throws JMSException {
    Assert.notNull(session, "Session must not be null");
    try {
        session.rollback();
    } catch (javax.jms.TransactionInProgressException ex) {
        // Ignore -> can only happen in case of a JTA transaction.
    } catch (javax.jms.IllegalStateException ex) {
        // Ignore -> can only happen in case of a JTA transaction.
    }
}

From source file:org.wso2.carbon.event.output.adapter.jms.internal.util.JMSMessageSender.java

/**
 * Perform actual send of JMS message to the Destination selected
 *///w ww .  j  ava2 s. c om
public void send(Object message, JMSEventAdapter.PublisherDetails publisherDetails, String jmsHeaders) {

    Map<String, String> messageProperties = publisherDetails.getMessageConfig();

    Boolean jtaCommit = getBooleanProperty(messageProperties, BaseConstants.JTA_COMMIT_AFTER_SEND);
    Boolean rollbackOnly = getBooleanProperty(messageProperties, BaseConstants.SET_ROLLBACK_ONLY);
    Boolean persistent = getBooleanProperty(messageProperties, JMSConstants.JMS_DELIVERY_MODE);
    Integer priority = getIntegerProperty(messageProperties, JMSConstants.JMS_PRIORITY);
    Integer timeToLive = getIntegerProperty(messageProperties, JMSConstants.JMS_TIME_TO_LIVE);

    MessageProducer producer = null;
    Destination destination = null;
    Session session = null;
    boolean sendingSuccessful = false;
    JMSConnectionFactory.JMSPooledConnectionHolder pooledConnection = null;
    try {

        pooledConnection = jmsConnectionFactory.getConnectionFromPool();

        producer = pooledConnection.getProducer();
        session = pooledConnection.getSession();
        Message jmsMessage = convertToJMSMessage(message, publisherDetails.getMessageConfig(), session);
        setJMSTransportHeaders(jmsMessage, jmsHeaders);

        // Do not commit, if message is marked for rollback
        if (rollbackOnly != null && rollbackOnly) {
            jtaCommit = Boolean.FALSE;
        }

        if (persistent != null) {
            try {
                producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            } catch (JMSException e) {
                handleConnectionException("Error setting JMS Producer for PERSISTENT delivery", e);
            }
        }
        if (priority != null) {
            try {
                producer.setPriority(priority);
            } catch (JMSException e) {
                handleConnectionException("Error setting JMS Producer priority to : " + priority, e);
            }
        }
        if (timeToLive != null) {
            try {
                producer.setTimeToLive(timeToLive);
            } catch (JMSException e) {
                handleConnectionException("Error setting JMS Producer TTL to : " + timeToLive, e);
            }
        }

        // perform actual message sending
        //        try {
        if (jmsSpec11 || isQueue == null) {
            producer.send(jmsMessage);

        } else {
            if (isQueue) {
                ((QueueSender) producer).send(jmsMessage);

            } else {
                ((TopicPublisher) producer).publish(jmsMessage);
            }
        }
        sendingSuccessful = true;

        if (log.isDebugEnabled()) {

            //            // set the actual MessageID to the message context for use by any others down the line
            String msgId = null;
            try {
                msgId = jmsMessage.getJMSMessageID();
            } catch (JMSException jmse) {
                log.error(jmse.getMessage(), jmse);
            }

            log.debug(" with JMS Message ID : " + msgId + " to destination : " + producer.getDestination());
        }

    } catch (JMSException e) {
        handleConnectionException("Error sending message to destination : " + destination, e);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    } finally {
        if (jtaCommit != null) {

            try {
                if (session.getTransacted()) {
                    if (sendingSuccessful && (rollbackOnly == null || !rollbackOnly)) {
                        session.commit();
                    } else {
                        session.rollback();
                    }
                }

                if (log.isDebugEnabled()) {
                    log.debug((sendingSuccessful ? "Committed" : "Rolled back")
                            + " local (JMS Session) Transaction");
                }

            } catch (Exception e) {
                handleConnectionException("Error committing/rolling back local (i.e. session) "
                        + "transaction after sending of message "//with MessageContext ID : " +
                        + " to destination : " + destination, e);
            }
        }
        if (pooledConnection != null) {
            jmsConnectionFactory.returnPooledConnection(pooledConnection);
        }
    }
}