transactedexample.java

来自「j2ee API 开发重要工具 免费下载 欢迎使用」· Java 代码 · 共 878 行 · 第 1/3 页

JAVA
878
字号
/* * Copyright (c) 2003 Sun Microsystems, Inc.  All rights reserved.  U.S. * Government Rights - Commercial software.  Government users are subject * to the Sun Microsystems, Inc. standard license agreement and * applicable provisions of the FAR and its supplements.  Use is subject * to license terms. * * This distribution may include materials developed by third parties. * Sun, Sun Microsystems, the Sun logo, Java and J2EE are trademarks * or registered trademarks of Sun Microsystems, Inc. in the U.S. and * other countries. * * Copyright (c) 2003 Sun Microsystems, Inc. Tous droits reserves. * * Droits du gouvernement americain, utilisateurs gouvernementaux - logiciel * commercial. Les utilisateurs gouvernementaux sont soumis au contrat de * licence standard de Sun Microsystems, Inc., ainsi qu'aux dispositions * en vigueur de la FAR (Federal Acquisition Regulations) et des * supplements a celles-ci.  Distribue par des licences qui en * restreignent l'utilisation. * * Cette distribution peut comprendre des composants developpes par des * tierces parties. Sun, Sun Microsystems, le logo Sun, Java et J2EE * sont des marques de fabrique ou des marques deposees de Sun * Microsystems, Inc. aux Etats-Unis et dans d'autres pays. */import java.util.*;import javax.jms.*;public class TransactedExample {    public static String  vendorOrderQueueName = null;    public static String  retailerConfirmQueueName = null;    public static String  supplierOrderTopicName = null;    public static String  vendorConfirmQueueName = null;    /**     * The Retailer class orders a number of computers by sending     * a message to a vendor.  It then waits for the order to be     * confirmed.     *      * In this example, the Retailer places two orders, one for     * the quantity specified on the command line and one for     * twice that number.     *      * This class does not use transactions.     */    public static class Retailer extends Thread {        int  quantity = 0;        /**         * Constructor.  Instantiates the retailer with the          * quantity of computers being ordered.         *         * @param q    the quantity specified in the program         *             arguments         */        public Retailer(int q) {            quantity = q;        }        /**         * Runs the thread.         */        public void run() {            ConnectionFactory  connectionFactory = null;            Connection         connection = null;            Session            session = null;            Queue              vendorOrderQueue = null;            Queue              retailerConfirmQueue = null;            MessageProducer    producer = null;            MapMessage         outMessage = null;            MessageConsumer    orderConfirmReceiver = null;            MapMessage         inMessage = null;            try {                connectionFactory =                    SampleUtilities.getConnectionFactory();                connection =                    connectionFactory.createConnection();                session = connection.createSession(false,                    Session.AUTO_ACKNOWLEDGE);                vendorOrderQueue =                    SampleUtilities.getQueue(vendorOrderQueueName,                        session);                retailerConfirmQueue =                    SampleUtilities.getQueue(retailerConfirmQueueName,                        session);            } catch (Exception e) {                System.err.println("Connection problem: " +                    e.toString());                System.err.println("Program assumes three " +                    "queues named AQueue BQueue CQueue and " +                    "one topic named OTopic");                if (connection != null) {                    try {                        connection.close();                    } catch (JMSException ee) {}                }                System.exit(1);            }            /*             * Create non-transacted session and sender for             * vendor order queue.             * Create message to vendor, setting item and             * quantity values.             * Send message.             * Create receiver for retailer confirmation queue.             * Get message and report result.             * Send an end-of-message-stream message so vendor             * will stop processing orders.             */            try {                producer =                     session.createProducer(vendorOrderQueue);                outMessage = session.createMapMessage();                outMessage.setString("Item", "Computer(s)");                outMessage.setInt("Quantity", quantity);                outMessage.setJMSReplyTo(retailerConfirmQueue);                producer.send(outMessage);                System.out.println("Retailer: ordered " +                     quantity + " computer(s)");                orderConfirmReceiver =                    session.createConsumer(retailerConfirmQueue);                connection.start();                inMessage =                     (MapMessage) orderConfirmReceiver.receive();                if (inMessage.getBoolean("OrderAccepted") == true) {                    System.out.println("Retailer: Order filled");                } else {                    System.out.println("Retailer: Order not " +                        "filled");                }                System.out.println("Retailer: placing another " +                    "order");                outMessage.setInt("Quantity", quantity * 2);                producer.send(outMessage);                System.out.println("Retailer: ordered " +                    outMessage.getInt("Quantity") +                     " computer(s)");                inMessage =                    (MapMessage) orderConfirmReceiver.receive();                if (inMessage.getBoolean("OrderAccepted")                         == true) {                    System.out.println("Retailer: Order filled");                } else {                    System.out.println("Retailer: Order not " +                        "filled");                }                /*                 * Send a non-text control message indicating end                 * of messages.                 */                producer.send(session.createMessage());            } catch (Exception e) {                System.err.println("Retailer: Exception " +                    "occurred: " + e.toString());                e.printStackTrace();            } finally {                if (connection != null) {                    try {                        connection.close();                    } catch (JMSException e) {}                }            }        }    }    /**     * The Vendor class uses one transaction to receive the     * computer order from the retailer and order the needed     * number of monitors and disk drives from its suppliers.     * At random intervals, it throws an exception to simulate a     * database problem and cause a rollback.     *      * The class uses an asynchronous message listener to process     * replies from suppliers. When all outstanding supplier      * inquiries complete, it sends a message to the Retailer      * accepting or refusing the order.     */    public static class Vendor extends Thread {        Random  rgen = new Random();        int     throwException = 1;        /**         * Runs the thread.         */        public void run() {            ConnectionFactory     connectionFactory = null;            Connection            connection = null;            Session               session = null;            Session               asyncSession = null;            Queue                 vendorOrderQueue = null;            Topic                 supplierOrderTopic = null;            Queue                 vendorConfirmQueue = null;            MessageConsumer       vendorOrderReceiver = null;            MessageProducer       supplierOrderProducer = null;            MapMessage            orderMessage = null;            MessageConsumer       vendorConfirmReceiver = null;            VendorMessageListener listener = null;            Message               inMessage = null;            MapMessage            vendorOrderMessage = null;            Message               endOfMessageStream = null;            Order                 order = null;            int                   quantity = 0;            try {                connectionFactory =                    SampleUtilities.getConnectionFactory();                connection =                    connectionFactory.createConnection();                session =                     connection.createSession(true, 0);                asyncSession =                     connection.createSession(true, 0);                vendorOrderQueue =                    SampleUtilities.getQueue(vendorOrderQueueName,                        session);                supplierOrderTopic =                     SampleUtilities.getTopic(supplierOrderTopicName,                        session);                vendorConfirmQueue =                    SampleUtilities.getQueue(vendorConfirmQueueName,                        session);            } catch (Exception e) {                System.err.println("Connection problem: " +                    e.toString());                System.err.println("Program assumes three " +                    "queues named AQueue BQueue CQueue and " +                    "one topic named OTopic");                if (connection != null) {                    try {                        connection.close();                    } catch (JMSException ee) {}                }                System.exit(1);            }            try {                /*                 * Create receiver for vendor order queue, sender                 * for supplier order topic, and message to send                 * to suppliers.                 */                vendorOrderReceiver =                     session.createConsumer(vendorOrderQueue);                supplierOrderProducer =                     session.createProducer(supplierOrderTopic);                orderMessage = session.createMapMessage();                /*                 * Configure an asynchronous message listener to                 * process supplier replies to inquiries for                  * parts to fill order.  Start delivery.                 */                vendorConfirmReceiver =                     asyncSession.createConsumer(vendorConfirmQueue);                listener = new VendorMessageListener(asyncSession, 2);                vendorConfirmReceiver.setMessageListener(listener);                connection.start();                /*                 * Process orders in vendor order queue.                 * Use one transaction to receive order from                 * order queue and send message to suppliers'                 * order topic to order components to fulfill                 * the order placed with the vendor.                 */                while (true) {                    try {                        // Receive an order from a retailer.                        inMessage =                             vendorOrderReceiver.receive();                        if (inMessage instanceof MapMessage) {                            vendorOrderMessage =                                 (MapMessage) inMessage;                        } else {                            /*                             * Message is an end-of-message-                             * stream message from retailer.                             * Send similar messages to                             * suppliers, then break out of                              * processing loop.                             */                            endOfMessageStream =                                 session.createMessage();                            endOfMessageStream.setJMSReplyTo(vendorConfirmQueue);                            supplierOrderProducer.send(endOfMessageStream);                            session.commit();

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?