
package examples.jms.sender;

import java.io.*;
import javax.naming.*;
import javax.jms.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * This example shows how to submit a JMS message from a Java servlet.
 * <p>
 * Configure the server:
 * <ol>
 * <li>
 * Register the servlet in your <tt>weblogic.properties</tt> file
 * by adding this property:
 * <pre>  weblogic.httpd.register.jmssender=examples.jms.sender.SenderServlet</pre>
 * </ol>
 * <li>
 * Set the servlet classpath and reload properties in your <tt>weblogic.properties</tt> file
 * by adding the following properties:
 *<pre>  weblogic.httpd.servlet.classpath=<i>weblogic</i>/myserver/servletclasses
 *  weblogic.httpd.servlet.reloadCheckSecs=1</pre>
 * where <tt><i>weblogic</i></tt> is the directory where WebLogic is installed.
 *<li>
 * If you want to try the persistent and durable subscriber features, 
 * make sure you have defined a JMS connection pool in your 
 * <tt>weblogic.properties</tt> file. See <a href="../Package-examples.jms.html#about" target=jms>
 * JMS Examples</a> for instruction on setting up a connection pool.
 * Build the example:
 * <ol>
 * <li>
 * Set up your development shell, as described in 
 * <a href="../../../techstart/environment.html">Setting up 
 * your environment</a>.
 * <li>
 * Compile the files in this directory as shown in this examples for Windows NT:
 * <pre>  $<font face="Courier New"><b> javac -d %SERVLET_CLASSES% SenderServlet.java</b></font></pre>
 * </ol>
 * Run the example:
 * <ol>
 * <li>
 * Start the WebLogic Server in a new shell.
 * <li>
 * Load the servlet in a browser with a URL like this:
 * <pre>  http://<i>hostname</i>:<i>port</i>/jmssender</pre>
 * where:
 * <dl>
 * <dt><i><font face="Courier New" size=-1>hostname</font></i>
 * <dd>Host name of the WebLogic Server
 * <dt><i><font face="Courier New" size=-1>port</font></i>
 * <dd>Port where the WebLogic Server is listening for connections
 * (<font face="Courier New" size=-1>weblogic.system.ListenPort</font>). 
 * </dl>
 *
 * <li>
 * Enter a message to send and click the Send Message button. 
 * </ol>
 *
 * @author Copyright (c) 1999-2000 by BEA Systems, Inc. All Rights Reserved.
 */
public class SenderServlet extends HttpServlet
{
  public final static String JMS_FACTORY="javax.jms.TopicConnectionFactory";
  public final static String TOPIC="javax.jms.exampleTopic";
  public final static String QUEUE="javax.jms.exampleQueue";

  /**
   * Process HTTP requests.
   */
  public void service(HttpServletRequest req, HttpServletResponse res)
       throws IOException, ServletException
  {
    String literal;
    boolean persistent;
    boolean topicMsg;
    int priority;
    long ttl;
    String correlate;
    String replyto;
    String msgText="";
    try {
      if (req.getMethod().equals("GET")) {
        PrintWriter pw = new PrintWriter(res.getOutputStream(),true);
        printForm(pw);
      } else {
        topicMsg = 
          req.getParameterValues("dest")[0].equals("topic");
        persistent = 
          req.getParameterValues("persistent")[0].equals("persistent");
        priority =
          Integer.parseInt(req.getParameterValues("priority")[0]);
        ttl = 
          Long.parseLong(req.getParameterValues("timetolive")[0]);
        correlate = 
          req.getParameterValues("correlate")[0];
        replyto =
          req.getParameterValues("replyto")[0];
        msgText = 
          req.getParameterValues("msgtext")[0];

        if (topicMsg) {
          sendTopicMessage(persistent, priority, ttl, correlate, replyto, msgText);
        } else {
          sendQueueMessage(persistent, priority, ttl, correlate, replyto, msgText);
        }
      
        res.setContentType("text/html");
        res.setHeader("Pragma", "no-cache");
        PrintWriter pw = new PrintWriter(res.getOutputStream(),true);
        pw.println("<HTML><HEAD><TITLE>Message Status</TITLE></HEAD>");
        pw.println("<BODY BGCLOR=#FFFFFF><h1><FONT COLOR=#DB1260 FACE=\"Helvetica\">");
        pw.println("Message Status</FONT></h1>");
        pw.println("Message Submitted: "+msgText);
        pw.println("</BODY></HTML>");
        pw.close();
        return;
      }
    }
    catch (Exception e) {e.printStackTrace();
    }

  }
  /**
   * Display the web page for message input.
   */

  public void printForm(PrintWriter pw) 
       throws Exception
  {
    pw.println("<html><head><title>JMS Message Submitter</title></head>");
    pw.println("<body BGCOLOR=#FFFFFF><FONT FACE=\"Helvetica\">");
    pw.println("<h1><font color=#DB1260 face=\"HELVETICA\">");
    pw.println("Submit a JMS Message</font></h1>");
    pw.println("<FORM METHOD=\"POST\" ACTION=\"./jmssender\">");
    pw.println("<TABLE bgcolor=#EEEEEE cellpadding=2 border=0 align=center>");
    pw.println("<TR><TD>Destination:</TD>");
    pw.println("<TD><select name=dest>");
    pw.println("<option value=topic selected>JMS Topic");
    pw.println("<option value=queue>JMS Queue");
    pw.println("</select></TR>");
    pw.println("<TR><TD>Message Type:</TD>");
    pw.println("<TD><select name=persistent>");
    pw.println("<option value=persistent selected>Persistent");
    pw.println("<option value=nonpersistent>Non Persistent");
    pw.println("</select></TR>");
    pw.println("<TR><TD>Priority:</td>");
    pw.println("<TD><select name=priority>");
    pw.println("<option value=0>0");
    pw.println("<option value=1>1");
    pw.println("<option value=2>2");
    pw.println("<option value=3>3");
    pw.println("<option value=4 selected>4");
    pw.println("<option value=5>5");
    pw.println("<option value=6>6");
    pw.println("<option value=7>7");
    pw.println("<option value=8>8");
    pw.println("<option value=9>9");
    pw.println("</select>");
    pw.println("</TR><TR><TD>Time to live:</td>");
    pw.println("<TD><select name=timetolive>");
    pw.println("<option value=0 selected>Never expires");
    pw.println("<option value=60000>one minute");
    pw.println("<option value=600000>ten minutes");
    pw.println("<option value=3600000>one hour");
    pw.println("<option value=86400000>one day");
    pw.println("</select>");
    pw.println("</TR>");
    pw.println("<TR><TD>Correlation ID:</TD><TD>");
    pw.println("<INPUT NAME=\"correlate\" SIZE=20></TD></TR>");
    pw.println("<TR><TD>Reply to:</TD><TD>");
    pw.println("<select name=replyto>");
    pw.println("<option value=none selected>none");
    pw.println("<option value=queue>ExampleQueue");
    pw.println("<option value=topic>ExampleTopic");
    pw.println("</select></TR>");
    pw.println("<TR><TD>Message Text:</TD><TD><INPUT NAME=\"msgtext\" SIZE=60></TD></TR>");
    pw.println("<TR><TD colspan=2 align=center>");
    pw.println("<INPUT TYPE=\"submit\" VALUE=\"Send Message\"></TD></TR>");
    pw.println("</TABLE></FORM></FONT></BODY></HTML>");
  }

  /**
   * Send message to the Topic.
   */
  public void sendTopicMessage(boolean persistent, int priority, 
                               long ttl, String correlate,
                               String replyto, String topicMessage)
       throws NamingException, JMSException
  {
    Context ctx = new InitialContext();
    TopicConnectionFactory tconFactory;
    TopicConnection connection;
    TopicSession session;
    TopicPublisher publisher;
    Topic topic;
    Queue queue;
    TextMessage msg;

    tconFactory = (TopicConnectionFactory) ctx.lookup(JMS_FACTORY);
    connection = tconFactory.createTopicConnection();
    session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    try {
      topic = (Topic) ctx.lookup(TOPIC);
    } catch (NamingException ne) {
      topic = session.createTopic(TOPIC);
      ctx.bind(TOPIC, topic);
    }
    publisher = session.createPublisher(topic);
    msg = session.createTextMessage();
    if (correlate.length() > 0)
      msg.setJMSCorrelationID(correlate);
    if (replyto.equals("topic")) {
      msg.setJMSReplyTo(topic);
    } 
    else if (replyto.equals("queue")) {
      try {
        queue = (Queue) ctx.lookup(QUEUE);
        msg.setJMSReplyTo(queue);
      } catch (NamingException ne) {
      }
    }
    msg.setText(topicMessage);  
    connection.start();

    publisher.publish(msg, 
                      persistent ? DeliveryMode.PERSISTENT
                                 : DeliveryMode.NON_PERSISTENT,
                      priority, 
                      ttl);

    publisher.close();
    session.close();
    connection.close();
  }

  /**
   * Send a message to the Queue. 
   */
  public void sendQueueMessage(boolean persistent, int priority, 
                               long ttl, String correlate,
                               String replyto, String topicMessage)
       throws NamingException, JMSException
  {
    Context ctx = new InitialContext();
    QueueConnectionFactory qconFactory;
    QueueConnection qcon;
    QueueSession qsession;
    QueueSender qsender;
    Queue queue;
    Topic topic;
    TextMessage msg;

    qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
    qcon = qconFactory.createQueueConnection();
    qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    try {
      queue = (Queue) ctx.lookup(QUEUE);
    } catch (NamingException ne) {
      queue = qsession.createQueue(QUEUE);
      ctx.bind(QUEUE, queue);
    }
    qsender = qsession.createSender(queue);
    msg = qsession.createTextMessage();
    if (correlate.length() > 0)
      msg.setJMSCorrelationID(correlate);
    if (replyto.equals("queue")) {
      msg.setJMSReplyTo(queue);
    } 
    else if (replyto.equals("topic")) {
      topic = (Topic) ctx.lookup(TOPIC);
      if (topic == null) {
        topic = ((TopicSession) qsession).createTopic(TOPIC);
        ctx.bind(TOPIC, topic);
      }
      msg.setJMSReplyTo(topic);
    }
    msg.setText(topicMessage);

    qcon.start();
    qsender.send(msg,
                 persistent ? DeliveryMode.PERSISTENT
                            : DeliveryMode.NON_PERSISTENT,
                 priority,
                 ttl);

    qsender.close();
    qsession.close();
    qcon.close();
  }

}

