#
SEND a message to a TOPIC
This tutorial explains to you how we can write (send) a simple message to a topic with Java EE. For testing the code I used a WebLogic Application Server.
#
JMS Topic
A JMS topic
is the channel
through which users subscribe to receive specific messages from a producer in the publish-and-subscribe model of JMS messaging. The model can be compared to subscribing to a newspaper.
In my case I used a WebLogic Topic. Here is a picture showing the Topic without any message received/ published:
After the messages are sent/ published (using the Java code in my case), you can see some messages on the queue:
You can see that there is no "Current" messages. It is because there is no durable subscriber.
#
How to publish/send a message to a WebLogic Topic using Java
For testing, I used the following: Eclipse, JDK 8, a WebLogic Server 12c, and I created a Web application using JSF (PrimeFaces).
On a JSF page (.xhtml) I put a button to send the message:
<html>
<body>
<h:form>
<p:commandbutton value="Publish Message" actionlistener="#{sendMessageTopic.sendMessage}"> </p:commandbutton>
</h:form>
</body>
</html>
Here is the SendMessageTopic.java file :
package com;
import java.util.Hashtable;
//import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
//import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.naming.*;
import javax.jms.*;
@ManagedBean (name = "sendMessageTopic")
public class SendMessageTopic {
// Defines the JNDI context factory.
public final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";
// Defines the JMS context factory.
public final static String JMS_FACTORY="ConnectionFactory2";
// Defines the topic.
public final static String MyTOPIC="jndi/Topic1";
// Defines the WebLogic URL. The port is for the Managed Server or
// the Admin Server where the JMS Server is running.
public final static String WebLogicURL="t3://pc:7004";
public void sendMessage() throws Exception {
//Create and start connection
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
env.put(Context.PROVIDER_URL, WebLogicURL);
InitialContext ic=new InitialContext(env);
TopicConnectionFactory f=(TopicConnectionFactory)ic.lookup("ConnectionFactory2") ;
TopicConnection con=f.createTopicConnection();
con.start();
//2) create topic session
TopicSession ses = con.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
//3) get the Topic object
Topic topic = (Topic)ic.lookup("jndi/Topic1");
//4)create topic publisher
TopicPublisher topicPublisher = ses.createPublisher(topic);
topicPublisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
//5) create TextMessage object
TextMessage msg=ses.createTextMessage();
msg.setText("This is my message !");
//7) send message
topicPublisher.publish(msg);
System.out.println("Message successfully published: " + msg);
//8) connection close
con.close();
}
}