Package openjms.examples.client.console

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

/**
* 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: TemporaryTopic.java,v 1.13 2002/05/07 16:40:47 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.TopicConnectionFactory;
import javax.jms.TopicConnection;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.jms.MessageListener;
import javax.jms.Message;
import javax.jms.Topic;
import javax.jms.TopicRequestor;
import javax.jms.TopicPublisher;
import javax.jms.TextMessage;
import javax.jms.TopicConnectionFactory;
import javax.jms.JMSException;
import org.exolab.jms.util.CommandLine;
import org.exolab.jms.client.JmsTopicConnectionFactory;
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;

/**
* TemporaryTopic are testd through the TopicRequestor class. A publisher
* and subscriber set up for the specified topic name and then temporary
* topic is used for the publisher to receive a reply from the publisher
* <p>
* This is an RMI based example
*/
public class TemporaryTopic
{

    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 specified, print the usage
                // information
                usage();
            } else if (cmdline.exists("topic")) {
                // 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
                TopicConnectionFactory factory = (TopicConnectionFactory)
                context.lookup("JmsTopicConnectionFactory");

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

                TopicConnection connection = factory.createTopicConnection();
                connection.start();

                TopicSession session =
                    connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

                // this is not the preferred way to get a topic
                Topic topic = session.createTopic(topic_name);

                if (topic == null)
                {
                    System.err.println("Failed to create topic");
                }
                else
                {
                    // create a receiver of the request in a separate thread and
                    // start it running
                    if (cmdline.exists("standalone")) {
                        if (cmdline.value("standalone").equals("A")) {
                            RequestReply server = new RequestReply(props, topic);
                            server_thread = new Thread(server);
                            server_thread.start();
                        }
                    } else {
                        RequestReply server = new RequestReply(props, topic);
                        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)
                                {
                                    // the thread has been interrupted
                                    break;
                                }
                            }
                        }
                    }
                   
                   
                    // set up a TopicRequestor and send a request
                    TopicRequestor request = new TopicRequestor(session, topic);

                    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 topic");

                }

                if (server_thread != null) {
                    server_thread.join();
                }
                connection.close();
            }
            else
            {
               System.err.println("Cannot subscribe to messages under null topic");
            }
        }
        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.TemporaryTopic");
    out.println("====================================================================");
    out.println("\nopenjms.examples.console.client.TemporaryTopic");
    out.println("    [-help | -topic <topic name> ]\n");
    out.println("\t-help   displays this screen\n");
    out.println("\t-topic   topic name to subscriber under.\n");
    }
}



/**
* This class setsup a subscriber to the specified topic. It basically
* creates a session using the specified connection and subscribes to
* the registered topic. When it receives a message it simply creates
* a publishers and replies to the reply-to destination in the message.
*/
class RequestReply implements Runnable
{
    public RequestReply(Hashtable props, Topic topic)
    {
        properties_ = props;
        topic_ = topic;
    }

    public void run()
    {
        try
        {
            // get a reference to the context and lookup the connection factory
            Context context = new InitialContext(properties_);
            TopicConnectionFactory factory =
                (TopicConnectionFactory)context.lookup("JmsTopicConnectionFactory");

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

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

            session_ = connection_.createTopicSession(
                false, Session.AUTO_ACKNOWLEDGE);
            if ((topic_ != null) &&
                (session_ != null))
            {
                // create a subscriber for the specified session and then
                // wait for a message to arrive.
                subscriber_ = session_.createSubscriber(topic_);
            }
            else
            {
                System.err.println("Error in run : topic=" + topic_ +
                    " 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 = subscriber_.receive();
   
                // create a publisher and then publish the message back to
                // the sender
                TopicPublisher publisher = session_.createPublisher(topic_);
                publisher.publish((Topic)message.getJMSReplyTo(), message);
            }

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


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


    Hashtable properties_ = null;
    Topic topic_ = null;
    TopicSession session_ = null;
    TopicConnection connection_ = null;
    TopicSubscriber subscriber_ = null;
}
TOP

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

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.