package dk.topsecurity;
import javax.jms.*;
import javax.naming.*;
import java.io.*;
import java.io.InputStreamReader;
import java.util.Properties;
public class JMSChat implements javax.jms.MessageListener {
public final static String TOPIC_NAME = "dk.topsecurity.topic";
public final static String JMS_FACTORY = "weblogic.jms.ConnectionFactory";
// public final static String JMS_FACTORY = "javax.jms.QueueConnectionFactory";
private TopicSession pubSession, subSession;
private TopicPublisher publisher;
private TopicConnection connection;
private String username;
/* Constructor. Establish JMS publisher and subscriber */
public JMSChat(String topicName, String logonusername, String logonpassword)
throws Exception {
//requires definition of in java.naming.factory.initial,java.naming.provider.url in jndi.properties
InitialContext jndi = new InitialContext();
TopicConnectionFactory conFactory =
(TopicConnectionFactory)jndi.lookup(JMS_FACTORY); //look up a JMS connection factory
connection =
conFactory.createTopicConnection(); //conFactory.createTopicConnection(logonusername,logonpassword); //create a JMS connection
pubSession =
connection.createTopicSession(false,Session.AUTO_ACKNOWLEDGE); // create 2x JMS session objects
subSession =
connection.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);
Topic chatTopic = (Topic)jndi.lookup(topicName); //look up a JMS topic
publisher =
pubSession.createPublisher(chatTopic); //create a JMS publisher and subscriber
TopicSubscriber subscriber =
subSession.createSubscriber(chatTopic);
subscriber.setMessageListener(this); //set a JMS message listener
username = logonusername;
connection.start(); //start JMS connection; allows messages to be delivered
}
public void onMessage(Message message) { //receive message from topic subscriber
try {
System.out.println( ((TextMessage) message).getText() );
} catch (JMSException jmse){ jmse.printStackTrace( ); }
}
protected void writeMessage(String text) throws JMSException { //create and send message using topic publisher
TextMessage message = pubSession.createTextMessage( );
message.setText(username+" : "+text);
publisher.publish(message);
}
public void close( ) throws JMSException { //close the JMS connection
connection.close( );
}
public static void main(String [] args) { //run chat client
try {
if (args.length!=3)
System.out.println("Topic or username missing");
// args[0]=topicName; args[1]=username; args[2]=password
JMSChat chat = new JMSChat(args[0],args[1],args[2]);
BufferedReader commandLine = new
java.io.BufferedReader(new InputStreamReader(System.in)); //read from command line
for(;;){ //loop until the word "exit" is typed
String s = commandLine.readLine( );
if (s.equalsIgnoreCase("exit")){
chat.close( ); // close down connection
System.exit(0);// exit program
} else
chat.writeMessage(s);
}
} catch (Exception e){ e.printStackTrace( ); }
}
}