Example usage for javax.jms Session SESSION_TRANSACTED

List of usage examples for javax.jms Session SESSION_TRANSACTED

Introduction

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

Prototype

int SESSION_TRANSACTED

To view the source code for javax.jms Session SESSION_TRANSACTED.

Click Source Link

Document

This value may be passed as the argument to the method createSession(int sessionMode) on the Connection object to specify that the session should use a local transaction.

Usage

From source file:Supplier.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    Session session = null;//from   w  w  w  . j av  a 2  s  .c o  m
    Destination orderQueue;
    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:Vendor.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    Session session = null;/*w  ww.  j a v  a 2s . com*/
    Destination orderQueue;
    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:com.oneops.controller.jms.InductorListener.java

/**
 * Inits the./*w  w  w .  j  a  v  a 2 s  .  c o  m*/
 *
 * @throws JMSException the jMS exception
 */
public void init() throws JMSException {

    connection = connFactory.createConnection();
    //session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    // lets make it transactional
    session = connection.createSession(true, Session.SESSION_TRANSACTED);
    Queue controllerQueue = session.createQueue(ctrlrQueueName);

    MessageConsumer consumer = session.createConsumer(controllerQueue);

    consumer.setMessageListener(this);
    connection.start();

    logger.info(">>>>>>>>>>>>>>>>Inductor Listener Waiting for messages...");
}

From source file:com.oneops.controller.jms.CmsListener.java

/**
 * Inits the.//  w w w .  j  a v  a 2  s. co  m
 *
 * @throws JMSException the jMS exception
 */
public void init() throws JMSException {

    connection = connFactory.createConnection();
    connection.setClientID(consumerName);
    session = connection.createSession(true, Session.SESSION_TRANSACTED);

    Queue queue = session.createQueue(queueName);

    MessageConsumer consumer = session.createConsumer(queue);
    consumer.setMessageListener(this);
    connection.start();

    logger.info(">>>>>>>>>>>>>>CmsListener Waiting for messages...");
}

From source file:com.amazon.sqs.javamessaging.SQSConnection.java

/**
 * Creates a <code>Session</code>
 * //from www.  j  a v a  2 s.c o  m
 * @param transacted
 *            Only false is supported.
 * @param acknowledgeMode
 *            Legal values are <code>Session.AUTO_ACKNOWLEDGE</code>,
 *            <code>Session.CLIENT_ACKNOWLEDGE</code>,
 *            <code>Session.DUPS_OK_ACKNOWLEDGE</code>, and
 *            <code>SQSSession.UNORDERED_ACKNOWLEDGE</code>
 * @return a new session.
 * @throws JMSException
 *             If the QueueConnection object fails to create a session due
 *             to some internal error or lack of support for the specific
 *             transaction and acknowledge mode.
 */
@Override
public Session createSession(boolean transacted, int acknowledgeMode) throws JMSException {
    checkClosed();
    actionOnConnectionTaken = true;
    if (transacted || acknowledgeMode == Session.SESSION_TRANSACTED)
        throw new JMSException("SQSSession does not support transacted");

    SQSSession sqsSession;
    if (acknowledgeMode == Session.AUTO_ACKNOWLEDGE) {
        sqsSession = new SQSSession(this,
                AcknowledgeMode.ACK_AUTO.withOriginalAcknowledgeMode(acknowledgeMode));
    } else if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE
            || acknowledgeMode == Session.DUPS_OK_ACKNOWLEDGE) {
        sqsSession = new SQSSession(this,
                AcknowledgeMode.ACK_RANGE.withOriginalAcknowledgeMode(acknowledgeMode));
    } else if (acknowledgeMode == SQSSession.UNORDERED_ACKNOWLEDGE) {
        sqsSession = new SQSSession(this,
                AcknowledgeMode.ACK_UNORDERED.withOriginalAcknowledgeMode(acknowledgeMode));
    } else {
        LOG.error("Unrecognized acknowledgeMode. Cannot create Session.");
        throw new JMSException("Unrecognized acknowledgeMode. Cannot create Session.");
    }
    synchronized (stateLock) {
        checkClosing();
        sessions.add(sqsSession);

        /**
         * Any new sessions created on a started connection should be
         * started on creation
         */
        if (running) {
            sqsSession.start();
        }
    }

    return sqsSession;
}

From source file:com.ruyicai.msgcenter.jms.WithoutTMJmsConfiguration.java

/**
 * Creates a {@link JmsOperations} object used for request/response using a request timeout value
 *//*from ww w . j  a  va2 s  . c  om*/
public JmsOperations createInOutTemplate(JmsEndpoint endpoint, boolean pubSubDomain, String destination,
        long requestTimeout) {
    JmsOperations answer = createInOnlyTemplate(endpoint, pubSubDomain, destination);
    if (answer instanceof JmsTemplate && requestTimeout > 0) {
        JmsTemplate jmsTemplate = (JmsTemplate) answer;
        jmsTemplate.setExplicitQosEnabled(true);

        // prefer to use timeToLive over requestTimeout if both specified
        long ttl = timeToLive > 0 ? timeToLive : requestTimeout;
        if (ttl > 0 && !isDisableTimeToLive()) {
            // only use TTL if not disabled
            jmsTemplate.setTimeToLive(ttl);
        }

        jmsTemplate.setSessionTransacted(isTransactedInOut());
        if (isTransactedInOut()) {
            jmsTemplate.setSessionAcknowledgeMode(Session.SESSION_TRANSACTED);
        } else {
            if (acknowledgementMode >= 0) {
                jmsTemplate.setSessionAcknowledgeMode(acknowledgementMode);
            } else if (acknowledgementModeName != null) {
                jmsTemplate.setSessionAcknowledgeModeName(acknowledgementModeName);
            } else {
                // default to AUTO
                jmsTemplate.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE);
            }
        }
    }
    return answer;
}

From source file:com.datatorrent.lib.io.jms.ActiveMQBase.java

/**
 *  Get session acknowledge./*from   ww w  .j  av  a  2 s .co m*/
 *  Converts acknowledge string into JMS Session variable.
 */
public int getSessionAckMode(String ackMode) {
    if ("CLIENT_ACKNOWLEDGE".equals(ackMode)) {
        return Session.CLIENT_ACKNOWLEDGE;
    } else if ("AUTO_ACKNOWLEDGE".equals(ackMode)) {
        return Session.AUTO_ACKNOWLEDGE;
    } else if ("DUPS_OK_ACKNOWLEDGE".equals(ackMode)) {
        return Session.DUPS_OK_ACKNOWLEDGE;
    } else if ("SESSION_TRANSACTED".equals(ackMode)) {
        return Session.SESSION_TRANSACTED;
    } else {
        return Session.CLIENT_ACKNOWLEDGE; // default
    }
}

From source file:com.ruyicai.msgcenter.jms.WithoutTMJmsConfiguration.java

/**
 * Creates a {@link JmsOperations} object used for one way messaging
 *//*from   w  w  w  .  ja v a2  s  .c  o m*/
public JmsOperations createInOnlyTemplate(JmsEndpoint endpoint, boolean pubSubDomain, String destination) {
    if (jmsOperations != null) {
        return jmsOperations;
    }

    ConnectionFactory factory = getTemplateConnectionFactory();
    JmsTemplate template = new CamelJmsTemplate(this, factory);

    template.setPubSubDomain(pubSubDomain);
    if (destinationResolver != null) {
        template.setDestinationResolver(destinationResolver);
        if (endpoint instanceof DestinationEndpoint) {
            LOG.debug(
                    "You are overloading the destinationResolver property on a DestinationEndpoint; are you sure you want to do that?");
        }
    } else if (endpoint instanceof DestinationEndpoint) {
        DestinationEndpoint destinationEndpoint = (DestinationEndpoint) endpoint;
        template.setDestinationResolver(createDestinationResolver(destinationEndpoint));
    }
    template.setDefaultDestinationName(destination);

    template.setExplicitQosEnabled(isExplicitQosEnabled());
    template.setDeliveryPersistent(deliveryPersistent);
    if (messageConverter != null) {
        template.setMessageConverter(messageConverter);
    }
    template.setMessageIdEnabled(messageIdEnabled);
    template.setMessageTimestampEnabled(messageTimestampEnabled);
    if (priority >= 0) {
        template.setPriority(priority);
    }
    template.setPubSubNoLocal(pubSubNoLocal);
    if (receiveTimeout >= 0) {
        template.setReceiveTimeout(receiveTimeout);
    }
    // only set TTL if we have a positive value and it has not been disabled
    if (timeToLive >= 0 && !isDisableTimeToLive()) {
        template.setTimeToLive(timeToLive);
    }

    template.setSessionTransacted(transacted);
    if (transacted) {
        template.setSessionAcknowledgeMode(Session.SESSION_TRANSACTED);
    } else {
        // This is here for completeness, but the template should not get
        // used for receiving messages.
        if (acknowledgementMode >= 0) {
            template.setSessionAcknowledgeMode(acknowledgementMode);
        } else if (acknowledgementModeName != null) {
            template.setSessionAcknowledgeModeName(acknowledgementModeName);
        }
    }
    return template;
}

From source file:ConsumerTool.java

public void setAckMode(String ackMode) {
    if ("CLIENT_ACKNOWLEDGE".equals(ackMode)) {
        this.ackMode = Session.CLIENT_ACKNOWLEDGE;
    }//from  w  ww.  j a v a  2s .  c o m
    if ("AUTO_ACKNOWLEDGE".equals(ackMode)) {
        this.ackMode = Session.AUTO_ACKNOWLEDGE;
    }
    if ("DUPS_OK_ACKNOWLEDGE".equals(ackMode)) {
        this.ackMode = Session.DUPS_OK_ACKNOWLEDGE;
    }
    if ("SESSION_TRANSACTED".equals(ackMode)) {
        this.ackMode = Session.SESSION_TRANSACTED;
    }
}

From source file:com.chinamobile.bcbsp.comm.ConsumerTool.java

/** Set ackMode state. */
public void setAckMode(String ackMode) {
    if ("CLIENT_ACKNOWLEDGE".equals(ackMode)) {
        this.ackMode = Session.CLIENT_ACKNOWLEDGE;
    }// w  w  w  .  j a  va 2s.  c o  m
    if ("AUTO_ACKNOWLEDGE".equals(ackMode)) {
        this.ackMode = Session.AUTO_ACKNOWLEDGE;
    }
    if ("DUPS_OK_ACKNOWLEDGE".equals(ackMode)) {
        this.ackMode = Session.DUPS_OK_ACKNOWLEDGE;
    }
    if ("SESSION_TRANSACTED".equals(ackMode)) {
        this.ackMode = Session.SESSION_TRANSACTED;
    }
}