// Purpose.  Demo JMS publish-subscribe (bulletin board) messaging

import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import javax.jms.*;
import com.sun.messaging.TopicConnectionFactory;

public class TopicDemoJmq {
  public static void main( String[] args ) throws IOException {
    TopicConnectionFactory factory = new TopicConnectionFactory( args );

    java.util.HashMap map = new java.util.HashMap();
    BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
    String line, token;  java.util.StringTokenizer st;
    while (true) {
      System.out.print( "Enter pub,name sub,name quit: " );
      line = in.readLine();
      st = new java.util.StringTokenizer( line, " ," );
      token = st.nextToken();
      if      (token.equals("quit")) System.exit( 0 );
      else if (token.equals("pub"))
         map.put( token = st.nextToken(), new Publisher( factory, token ) );
      else if (token.equals("sub"))
         new Subscriber( (Publisher)map.get( token = st.nextToken() ), token );
} } }

class Publisher extends JFrame implements ActionListener {
  private TopicSession   sess;
  private Topic          topic;
  private TopicPublisher prod;
  private TextMessage    mesg;

  public Publisher( TopicConnectionFactory fact, String name ) {
    super( "Publisher - " + name );
    JTextField text = new JTextField( 30 );
    getContentPane().add( text );
    text.addActionListener( this );
    pack();     setVisible( true );
    try {
      TopicConnection conn = fact.createTopicConnection();
      conn.start();                    // should the session be transacted
      sess  = conn.createTopicSession( false, Session.AUTO_ACKNOWLEDGE );
      topic = sess.createTopic( name );
      prod  = sess.createPublisher( topic );
      mesg  = sess.createTextMessage();
    } catch (JMSException ex) { ex.printStackTrace(); }
  }
  public TopicSession getSession() { return sess; }
  public Topic        getTopic()   { return topic; }
  public void actionPerformed( ActionEvent e ) {
    try {
      mesg.setText( e.getActionCommand() );
      prod.publish( mesg );
    } catch (JMSException ex) { ex.printStackTrace(); }
    ((javax.swing.text.JTextComponent)e.getSource()).setText( "" );
} }

class Subscriber extends JFrame implements MessageListener {
  private JTextArea text;

  public Subscriber( Publisher pub, String name ) {
    super( "Subscriber - " + name );
    text = new JTextArea( 10,30 );
    getContentPane().add( text );
    pack();   setVisible( true );
    try {
      TopicSubscriber sub = pub.getSession().createSubscriber(pub.getTopic());
      sub.setMessageListener( this );
    } catch (JMSException ex) { ex.printStackTrace(); }
  }
  public void onMessage( Message m ) {
    try { text.append( ((TextMessage)m).getText() + "\n" ); }
    catch (JMSException ex) { ex.printStackTrace(); }
} }
