Package openjms.examples.client.console

Source Code of openjms.examples.client.console.QueueRequestReply

/**
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
*    statements and notices.  Redistributions must also contain a
*    copy of this document.
*
* 2. Redistributions in binary form must reproduce the
*    above copyright notice, this list of conditions and the
*    following disclaimer in the documentation and/or other
*    materials provided with the distribution.
*
* 3. The name "Exolab" must not be used to endorse or promote
*    products derived from this Software without prior written
*    permission of Exoffice Technologies.  For written permission,
*    please contact info@exolab.org.
*
* 4. Products derived from this Software may not be called "Exolab"
*    nor may "Exolab" appear in their names without prior written
*    permission of Exoffice Technologies. Exolab is a registered
*    trademark of Exoffice Technologies.
*
* 5. Due credit should be given to the Exolab Project
*    (http://www.exolab.org/).
*
* THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
* EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved.
*
* $Id: TemporaryQueue.java,v 1.13 2002/05/07 16:25:48 jima Exp $
*
* Date         Author  Changes
* 04/25/2000   jima    Created
*/
package openjms.examples.client.console;

import java.io.PrintStream;
import java.util.Hashtable;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.jms.Session;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueConnection;
import javax.jms.QueueSession;
import javax.jms.QueueReceiver;
import javax.jms.MessageListener;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.QueueRequestor;
import javax.jms.QueueSender;
import javax.jms.TextMessage;
import javax.jms.QueueConnectionFactory;
import javax.jms.JMSException;
import org.exolab.jms.util.CommandLine;
import org.exolab.jms.client.JmsQueueConnectionFactory;
import org.exolab.core.logger.LoggerFactory;
import org.exolab.core.logger.LoggerIfc;
import org.exolab.core.logger.LogEventType;
import org.exolab.jms.jndi.JndiConstants;
import org.exolab.jms.jndi.mipc.IpcJndiInitialContextFactory;
import org.exolab.jms.jndi.rmi.RmiJndiInitialContextFactory;

/**
* TemporaryQueue are tested through the QueueRequestor class. A sender
* and receiver set up for the specified queue name and then temporary
* queue is used for the publisher to receive a reply from the publisher
* <p>
* This is an RMI based example
*/
public class TemporaryQueue {

    static public void main(String[] args) {
        try {
            CommandLine cmdline = new CommandLine(args);
            Thread server_thread = null;

            if (cmdline.exists("help")) {
                // the help option has been speifie, print the usage
                // information
                usage();
            } else if (cmdline.exists("queue")) {
                String queue_name = cmdline.value("queue");
                // connect to the JNDI server and get a reference to
                // root context
                Hashtable props = new Hashtable();
                String topic_name = cmdline.value("topic");
                String host = "localhost";
                String port = null;
                String jndiname = "JndiServer";

                String mode = null;
                if (cmdline.exists("mode")) {
                    mode = cmdline.value("mode");
                } else {
                    mode = "rmi";
                }

                String modeType =
                    RmiJndiInitialContextFactory.class.getName();

                if (cmdline.exists("jndiport")) {
                    port = cmdline.value("jndiport");
                }

                if (cmdline.exists("jndihost")) {
                    host = cmdline.value("jndihost");
                }

                // override the default server name if specified on the
                // command line.
                if (cmdline.exists("jndiname")) {
                    jndiname = cmdline.value("jndiname");
                }

                if (mode.equals("ipc") || mode.equals("tcp")) {
                    if (port == null) {
                        port = "3035";
                    }

                    props.put(Context.PROVIDER_URL,
                        "tcp://" + host + ":" + port + "/");
                    modeType =
                        "org.exolab.jms.jndi.mipc.IpcJndiInitialContextFactory";
                } else if (mode.equals("http")) {
                    System.out.println("Using HTTP");
                    String type = "http://";
                    if (cmdline.exists("secure")) {
                        if (port == null) {
                            port = "8443";
                        }
                        type = "https://";
                        modeType =
                            "org.exolab.jms.jndi.http.SslHttpJndiInitialContextFactory";
                    } else {
                        if (port == null) {
                            port = "8080";
                        }
                        modeType =
                            "org.exolab.jms.jndi.http.HttpJndiInitialContextFactory";
                    }

                    props.put(Context.PROVIDER_URL,
                        type + host + ":" + port + "/" +
                        "openjms/servlet/OpenJMSJndi");

                    String url = cmdline.value("url");
                    if (url == null) {
                        url = type + "localhost:8080";
                    }

                    // Client URL to allow server to send messages
                    // to registered consumers/receivers
                    System.getProperties().setProperty
                        (JndiConstants.HTTP_CLIENT_URL_PROPERTY, url);

                } else {
                    if (port == null) {
                        port = "1099";
                    }

                    props.put(Context.PROVIDER_URL,
                        "rmi://" + host + ":" + port + "/" + jndiname);
                }

                System.err.println("Using provider url " + props.get(Context.PROVIDER_URL));
                props.put(Context.INITIAL_CONTEXT_FACTORY, modeType);
                Context context = new InitialContext(props);

                // lookup the connection factory from the context
                QueueConnectionFactory factory = (QueueConnectionFactory)
                context.lookup("JmsQueueConnectionFactory");

                // if we can't find the factory then throw an exception
                if (factory == null) {
                    throw new RuntimeException(
                        "Failed to locate connection factory");
                }

                QueueConnection connection = factory.createQueueConnection();
                connection.start();

                QueueSession session =
                    connection.createQueueSession(false, ackMode__ );

                // this is not the preferred way to get a queue
                Queue queue = session.createQueue(queue_name);

                if (queue == null) {
                    System.err.println("Failed to create queue");
                } else {
                    // create a receiver of the request in a separate thread and
                    // start it running
                    QueueRequestReply server = new QueueRequestReply(context, queue);
                    server_thread = new Thread(server);
                    server_thread.start();

                    // wait some time while it gets ready
                    synchronized (server) {
                        while (true) {
                            try {
                                server.wait();
                                break;
                            } catch (InterruptedException exception) {
                            }
                        }
                    }

                    // set up a QueueRequestor and send a request
                    QueueRequestor request = new QueueRequestor(session, queue);

                    for (int index = 0; index < 10; index++) {
                        Message message = session.createTextMessage(
                            "Message to send " + index);
                        Message received_msg = request.request(message);
                    }

                    System.err.println("Processed 10 messages through the temporary queue");

                }

                server_thread.join();
                connection.close();
            } else {
                System.err.println("Cannot subscribe to messages under null queue");
            }

        } catch (Exception exception) {
            System.err.println("Fatal error: " + exception + "\nExiting.....");
            exception.printStackTrace();
            System.exit(-1);
        }
    }

    /**
     * Return a reference to the logger
     */
    static LoggerIfc getLogger() {
        return LoggerFactory.getLogger();
    }

    /**
     * Print out information on running this sevice
     */
    static protected void usage() {
        PrintStream out = System.out;

        out.println("\n\n");
        out.println("====================================================================");
        out.println("Usage information for openjms.examples.client.console.TemporaryQueue");
        out.println("====================================================================");
        out.println("\nopenjms.examples.console.client.TemporaryQueue");
        out.println("    [-help | -queue <queue name> ] |  -mode <rmi/ipc>\n");
        out.println("\t-help   displays this screen\n");
        out.println("\t-queue   queue name to subscriber under.\n");
        out.println("\t-mode    connect in either ipc mode or rmi mode.\n");
    }


    // Define the ack mode for the session. It defaults to client ack
    static int ackMode__ = Session.AUTO_ACKNOWLEDGE;
}



/**
* This class setsup a subscriber to the specified queue. It basically
* creates a session using the specified connection and subscribes to
* the registered queue. When it receives a message it simply creates
* a publishers and replies to the reply-to destination in the message.
*/
class QueueRequestReply implements Runnable {
    public QueueRequestReply(Context context, Queue queue) {
        context_ = context;
        queue_ = queue;
    }

    public void run() {
        try {
            // lookup the connection factory from the context
            QueueConnectionFactory factory =
                (QueueConnectionFactory)context_.lookup("JmsQueueConnectionFactory");

            // if we can't find the factory then throw an exception
            if (factory == null) {
                throw new RuntimeException("Failed to locate connection factory");
            }

            connection_ = factory.createQueueConnection();
            connection_.start();

            session_ = connection_.createQueueSession(
                false, Session.AUTO_ACKNOWLEDGE);
            if ((queue_ != null) &&
                (session_ != null)) {
                // create a subscriber for the specified session and then
                // wait for a message to arrive.
                receiver_ = session_.createReceiver(queue_);
            } else {
                System.err.println("Error in run : queue=" + queue_ +
                    " and session is " + session_);
            }

            // we are ready to notify the waiting thread to
            // continue
            synchronized (this) {
                notifyAll();
            }

            for (int index = 0; index < 10; index++) {
                Message message = receiver_.receive();
                // create a publisher and then publish the message back to
                // the sender
                QueueSender sender = session_.createSender(null);
                sender.send((Queue)message.getJMSReplyTo(), message);
            }

            // close the session and exit
            connection_.close();

        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }


    /**
     * Return a reference to the logger
     */
    LoggerIfc getLogger() {
        return LoggerFactory.getLogger();
    }

    Context context_ = null;
    Queue queue_ = null;
    QueueSession session_ = null;
    QueueConnection connection_ = null;
    QueueReceiver receiver_ = null;
}
TOP

Related Classes of openjms.examples.client.console.QueueRequestReply

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.