package dk.topsecurity;
import javax.jms.*;
import javax.naming.*;
import java.text.SimpleDateFormat;
/**
* The publish/subscribe (pub/sub) messaging model enables an application to
* send a message to multiple applications. Pub/sub messaging applications
* send and receive messages by subscribing to a topic. A topic publisher
* (producer) sends messages to a specific topic. A topic subscriber
* (consumer) retrieves messages from a specific topic.
*/
public class JMSTopicPublisher {
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.TopicConnectionFactory"
public static void main(String[] args) {
try {
//requires definition of in java.naming.factory.initial,java.naming.provider.url in jndi.properties
Context ctx = new InitialContext();
TopicConnectionFactory factory =
(TopicConnectionFactory) ctx.lookup(JMS_FACTORY); //get Topic Connection Factory by JNDI
TopicConnection conn = factory.createTopicConnection(); //create a new Topic Connection
TopicSession session = conn.createTopicSession(false,
Session.AUTO_ACKNOWLEDGE); //create a non-transactional TopicSession
Topic topic = null;
try {
topic = (Topic) ctx.lookup(TOPIC_NAME); //check if someone has already created the topic
}
catch (NameNotFoundException exc) {
topic = session.createTopic(TOPIC_NAME);
ctx.bind(TOPIC_NAME, topic); //if not, create a new topic and store it in JNDI directory
}
TopicPublisher sender = session.createPublisher(topic); //create a publisher to publish msg
conn.start(); //tell Topic Connection you are ready to interact with the message service
for (;;) {
String messageTxt = "Hello from publisher at " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new java.util.Date());
TextMessage message = session.createTextMessage(messageTxt); //create simple text message
sender.publish(message); //publish the message
try { Thread.sleep(5000); } catch (Exception ignore) { } //5 secs pause before another message
}
}
catch (Exception exc)
{
exc.printStackTrace();
}
}
}