Tag: Topic

JMS Demo using WebLogic Durable Subscriber Topic

Ravish Mody

To configure a Durable Subscriber Topic you can follow the steps provided in the post Steps to Configure Durable Subscriber Topic on Weblogic Server.

In this post I would be using a stand-alone java code for producing messages as a Producer/Clint and  for consuming the messages as a Consumer/Listener. By which we can make sure that if something goes wrong then we can narrow down the issue if its an issue with WLS or the code, as many times their an issue with the Producer or a Consumers.

.

Steps of test the Durable Subscriber Topic

  1. Create a Directory somewhere in your file system like: “D:OracleJMSTopicDurable_Subscribers” to write the DurableTopicSend.java and DurableTopicReceive.java programs.
  2. In DurableTopicSend.java copy the below command
  3. /**
     * @DurableTopicSend Demo for Durable Subscriber
     *
     * @author Middleware Magic (c) 2010
     */
    
    import java.io.*;
    import java.util.*;
    import javax.transaction.*;
    import javax.naming.*;
    import javax.jms.*;
    import javax.rmi.*;
    
    public class DurableTopicSend
    {
    	public final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";
    
    	// Defines the JMS connection factory JNDI name.
    	public final static String CONN_FACTORY="CF";
    
    	// Defines the Topic JNDI name.
    	public final static String TOPIC="T-1";
    
    	protected TopicConnectionFactory dutconFactory;
    	protected TopicConnection dutcon;
    	protected TopicSession dutsession;
    	protected TopicPublisher dutpublisher;
    	protected Topic dutopic;
    	protected TextMessage msg;
    
    	public static void main(String[] args) throws Exception
    	{
    		if (args.length != 1)
    		{
    			System.out.println("Usage: java examples.jms.dutopic.DurableTopicSend WebLogicURL");
    			return;
    		}
    		InitialContext ic = getInitialContext(args[0]);
    		DurableTopicSend duts = new DurableTopicSend();
    		duts.init(ic, TOPIC);
    		readAndSendMsg(duts);
    		duts.close();
    	}
    
    	public void init(Context ctx, String topicName)throws NamingException, JMSException
    	{
    		dutconFactory = (TopicConnectionFactory)PortableRemoteObject.narrow(ctx.lookup(CONN_FACTORY),TopicConnectionFactory.class);
    		dutcon = dutconFactory.createTopicConnection();
    		dutsession = dutcon.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    		dutopic = (Topic) PortableRemoteObject.narrow(ctx.lookup(topicName), Topic.class);
    		dutpublisher = dutsession.createPublisher(dutopic);
    		msg = dutsession.createTextMessage();
    		dutcon.start();
    	}
    
    	protected static InitialContext getInitialContext(String url)throws NamingException
    	{
    		Hashtable<String,String> env = new Hashtable<String,String>();
    		env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
    		env.put(Context.PROVIDER_URL, url);
    		env.put("weblogic.jndi.createIntermediateContexts", "true");
    		return new InitialContext(env);
    	}
    
    	public void sendmsg(String message) throws JMSException
    	{
    		msg.setText(message);
    		dutpublisher.publish(msg);
    	}
    
    	protected static void readAndSendMsg(DurableTopicSend duts)throws IOException, JMSException
    	{
    		BufferedReader msgStream = new BufferedReader (new InputStreamReader(System.in));
    		String line=null;
    		do
    		{
    			System.out.print("Enter your message ("quit" to quit): n");
    			line = msgStream.readLine();
    			if (line != null && line.trim().length() != 0)
    			{
    				duts.sendmsg(line);
    				System.out.println("Sent JMS Message: "+line+"n");
    			}
    		}
    		while (line != null && ! line.equalsIgnoreCase("quit"));
    	}
    
    	public void close() throws JMSException
    	{
    		dutpublisher.close();
    		dutsession.close();
    		dutcon.close();
    	}
    
    }
    
  4. In DurableTopicReceive.java copy the below command
  5. /**
     * @DurableTopicReceive Demo for Durable Subscriber
     *
     * @author Middleware Magic (c) 2010
     */
    
    import java.io.*;
    import java.util.*;
    import javax.transaction.*;
    import javax.naming.*;
    import javax.jms.*;
    import javax.rmi.*;
    
    public class DurableTopicReceive implements MessageListener
    {
    
    	public final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";
    
    	// Defines the JMS connection factory JNDI name.
    	public final static String CONN_FACTORY="CF";
    
    	// Defines the Topic JNDI name.
    	public final static String TOPIC="T-1";
    
    	private TopicConnectionFactory dutconFactory;
    	private TopicConnection dutcon;
    	private TopicSession dutsession;
    	private TopicSubscriber dutsubscriber;
    	private Topic dutopic;
    	private boolean quit = false;
    
    	public void onMessage(Message msg)
    	{
    		try
    		{
    			String msgText;
    
    			if (msg instanceof TextMessage)
    			{
    				msgText = ((TextMessage)msg).getText();
    			}
    			else
    			{
    				msgText = msg.toString();
    			}
    
    			System.out.println("Received JMS Message: "+ msgText );
    
    			if (msgText.equalsIgnoreCase("quit"))
    			{
    				synchronized(this)
    				{
    					quit = true;
    					this.notifyAll();
    				}
    			}
    		}
    		catch (JMSException jmse)
    		{
    			System.err.println("An exception has occurred: "+jmse.getMessage());
    		}
    	}
    
    public static void main(String[] args) throws Exception
    	{
    		if (args.length != 1)
    		{
    			System.out.println("Usage: java examples.jms.dutopic.DurableTopicReceive WebLogicURL");
    			return;
    		}
    		InitialContext ic = getInitialContext(args[0]);
    		DurableTopicReceive tr = new DurableTopicReceive();
    		tr.init(ic, TOPIC);
    
    		System.out.println("JMS Is Now Ready To Receive Messages (To quit, send a "quit" message).");
    
    		synchronized(tr)
    		{
    			while (! tr.quit)
    			{
    				try
    				{
    					tr.wait();
    				}
    				catch (InterruptedException ie)
    				{}
    			}
    		}
    		tr.close();
    	}
    
    	private static InitialContext getInitialContext(String url)throws NamingException
    	{
    		Hashtable env = new Hashtable();
    		env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
    		env.put(Context.PROVIDER_URL, url);
    		env.put("weblogic.jndi.createIntermediateContexts", "true");
    		return new InitialContext(env);
    	}
    
    	public void close() throws JMSException
    	{
    		dutsubscriber.close();
    		dutsession.close();
    		dutcon.close();
    	}
    
    	/**
    	*
    	* Below are the code which makes it a Durable Subscriber by giving the Client ID and Subscription Name
    	*
    	*/
    
    	public void init(Context ctx, String topicName)throws NamingException, JMSException
    	{
    		dutconFactory = (TopicConnectionFactory)PortableRemoteObject.narrow(ctx.lookup(CONN_FACTORY),TopicConnectionFactory.class);
    		dutcon = dutconFactory.createTopicConnection();
    
    		// ############## Below the Clinet ID is been given which is "Ravish" #####################
    		dutcon.setClientID("Ravish");
    		dutsession = dutcon.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    		dutopic = (Topic)PortableRemoteObject.narrow(ctx.lookup(topicName),Topic.class);
    
    		// ############## Below the Subscription Name is been given which is "Test" #####################
    		dutsubscriber = dutsession.createDurableSubscriber(dutopic, "Test");
    		dutsubscriber.setMessageListener(this);
    		dutcon.start();
    	}
    
    }
    
  6. Now open 2 – command prompt windows and run “setWLSEn.cmd” in both the command windows to set the environment (PATH & CLASSPATH).
  7. Then compile the DurableTopicSend.java and DurableTopicReceive.java programs.
  8. Now run the code with the following command
  9. Prompt-1

    java DurableTopicSend t3://localhost:7003
    

    Prompt-2

    java DurableTopicReceive t3://localhost:7003
    

    Note:
    With the “java DurableTopicSend” and “java DurableTopicReceive” command you have to give the <Protocol>://<IP-address>:<Port number> of the managed servers in different prompts.

  10. Now try sending messages from prompt-1 which should get received on prompt-2 as shown below
  11. demo-1

  12. Once you are able to receive the messages properly then STOP the prompt-2 and still send few messages from prompt-1, now if this was a normal Topic then the messages should have been lost as no one is subscribed/listening on this topic, but if you check the below path from console you will able to see the messages sent to the particular subscriber.
  13. Console Path:
    JMS Modules -> MySystemModule-1 -> T-1 -> Monitoring (Tab) -> Durable Subscribers (Sub-Tab)

    demo-2

    demo-3

    demo-4demo-5

  14. Also if you again start the prompt-2 you will receive the same messages which was sent by prompt-1 when prompt-2 was down.
  15. demo-6

Conclusion:

Thus this demo makes sure that our configured durable subscriber is working fine. As we got the messages which were sent to a particular subscriber when it was down and not listing, because those messages got stored in the persistence store and were sent again by weblogic server once the subscriber again started listing.

Regards,

Ravish Mody


Steps to Configure Durable Subscriber Topic on Weblogic Server

Ravish Mody

Till now you might have figured out that Weblogic Server is one of the best application server in the market and has lot of feature in-built, from which one of it is that Weblogic server also supports JMS durable subscriptions. For demo you can have a look at this post JMS Demo using WebLogic Durable Subscriber Topic

What is a Durable Subscriptions?

Durable subscriptions means that weblogic server will store the messages in a persistent store (i.e a  file-store or a JDBC-store) until those messages are delivered to the subscribers/listener. This technic helps weblogic server to make sure that  the messages get delivered even if those subscribers/listeners are not active at the time that the message is getting delivered.

As all of us know that in Topic’s the senders/producers just send the messages to the topic and the receivers/listeners have subscribe them self to get those messages, hence senders/producers does not have any concern if the messages are been received or not. However with this feature weblogic make sure all the subscribers would get the messages as the messages gets stored in a persistence store.

This happens by-default with Queue hence we can monitor the messages on the console, but with Topic’s that’s not the case thus durable subscriptions comes into the picture.

Steps to Configure Durable Subscribers Topic:

1.  Start your WebLogic Server an Login to the Admin Console.

2.  Create a JMS Server and File store.

JMS-1 Creating JMS Server
JMS-2Creating JMS Server-1
JMS-3Selecting JMS Server Store Type
JMS-4Configuring JMS Store
JMS-5Choosing JMS Store for JMS Server
JMS-6Targeting to the JMS Server

3.  Configuring JMS Module

JMS_M-1Creating JMS Module
JMS_M-2Entering JMS Module Name
JMS_M-3Targeting JMS Module

JMS_M-4Finishing the Module Creation

4.  Creating Connection Factory

JMS_C-1Creating JMS Connection Factory
JMS_C-2Selecting Connection Factory to be Created
JMS_C-3Creating the Connection Factory

JMS_C-4Targeting the Connection Factory

5.  Creating Sub-Deployment

JMS_Sub-1Creating Sub-Deployment
JMS_Sub-2Creating the Sub Deployment

JMS_Sub-3

Targeting the Sub-Deployment

6.  Creating a Topic

JMS_T-1Creating Topic
JMS_T-2Selecting Topic
JMS_T-3Providing Name/JNDIName to the Topic
JMS_T-4Targeting the Distributed Queue with the Sub-Topic

7.  Creating Durable Subscriptions

JMS_DS-1Selecting T-1
JMS_DS-2Creating Durable subscriber
JMS_DS-3Providing Subscription Name / Client ID for the Durable Subscriber

XML file sinp-codes

– config.xml


<jms-server>
	<name>JMS Server-1</name>
	<target>MS-1</target>
	<persistent-store>FileStore-1</persistent-store>
</jms-server>
<migratable-target>
	<name>MS-1 (migratable)</name>
	<notes>This is a system generated default migratable target for a server. Do not delete manually.</notes>
	<user-preferred-server>MS-1</user-preferred-server>
	<constrained-candidate-server />
	<cluster>Cluster</cluster>
	<migration-policy>manual</migration-policy>
	<post-script-failure-fatal>true</post-script-failure-fatal>
	<non-local-post-allowed>false</non-local-post-allowed>
	<restart-on-failure>false</restart-on-failure>
	<seconds-between-restarts>30</seconds-between-restarts>
	<number-of-restart-attempts>6</number-of-restart-attempts>
</migratable-target>
<file-store>
	<name>FileStore-1</name>
	<directory>c:/JMSStore/FileStore-1</directory>
	<target>MS-1</target>
</file-store>
<jms-system-resource>
	<name>MySystemModule-1</name>
	<target>MS-1</target>
	<sub-deployment>
		<name>Sub_Topic</name>
		<target>JMS Server-1</target>
	</sub-deployment>
	<descriptor-file-name>jms/mysystemmodule-1-jms.xml</descriptor-file-name>
</jms-system-resource>

– mysystemmodule-1-jms.xml


<connection-factory name="CF">
	<default-targeting-enabled>true</default-targeting-enabled>
	<jndi-name>CF</jndi-name>
	<security-params>
		<attach-jmsx-user-id>false</attach-jmsx-user-id>
	</security-params>
</connection-factory>
<topic name="T-1">
	<sub-deployment-name>Sub_Topic</sub-deployment-name>
	<jndi-name>T-1</jndi-name>
</topic>

Regards,

Ravish Mody


Basic JMS Demo using WebLogic Topic

Hi,

Jay SenSharma

Jay SenSharma

Java Messaging Service is an API that provides reliable, asynchronous communication between applications in a distributed computing environment. It enables a Java applications that share a messaging system to exchange messages and Simplifies application development by providing a standard interface for creating, sending, and receiving messages.

What are major components of JMS system? To Know this as well as to see a Simple Demo of WebLogic Queues Please refer to: basic-jms-demo-using-weblogic-queue/

Here we are going to see how we can configure WebLogic JMS Server, JMS Modules (Topic/ConnectionFactory) how to Target them and then How to test it using a Simpel Java Programs.

Step1). Start your WebLogic Server an Login to the AdminConsole.

Step2). To Create a JMS Server Please refer to the (S t e p – 2) of  basic-jms-demo-using-weblogic-queue/

Step3). Now we need to create a JMS Module.

JMS_Module_Creation

JMS_Module_Creation

Targeting_JMS_Module

Targeting_JMS_Module

Adding_JMS_Resources

Adding_JMS_Resources

Step4). Now we need to create a ConnectionFactory.

Adding_JMS_Resource

Adding_JMS_Resource

Creating Connection_Factory

Creating Connection_Factory

Naming_ConnectionFactory

Naming_ConnectionFactory

Targeting_ConnectionFactory

Targeting_ConnectionFactory

Step5). Creating a WebLogic Topic.

Creating_Topic

Creating_Topic

Choosing_Topic_Creation

Choosing_Topic_Creation

Naming_Topic

Naming_Topic

Creating_Subdeployment

Creating_Subdeployment

Naming_Subdeployment

Naming_Subdeployment

Targeting_Topic

Targeting_Topic

Final_Configuration

Final_Configuration

Step6). Create a Directory somewhere in your file system like: “C:WebLogic_Topic_Demo” to write the TopicSend and TopicReceive programs.

Step7). Write the “TopicSend.java” program as following inside “C:WebLogic_Topic_Demo”

import java.io.*;
import java.util.*;
import javax.transaction.*;
import javax.naming.*;
import javax.jms.*;
import javax.rmi.PortableRemoteObject;
public class TopicSend
{
public final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";
public final static String JMS_FACTORY="TCF";
public final static String TOPIC="TestTopic";

protected TopicConnectionFactory tconFactory;
protected TopicConnection tcon;
protected TopicSession tsession;
protected TopicPublisher tpublisher;
protected Topic topic;
protected TextMessage msg;

public void init(Context ctx, String topicName) throws NamingException, JMSException
{
tconFactory = (TopicConnectionFactory) PortableRemoteObject.narrow(ctx.lookup(JMS_FACTORY),TopicConnectionFactory.class);
tcon = tconFactory.createTopicConnection();
tsession = tcon.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
topic = (Topic) PortableRemoteObject.narrow(ctx.lookup(topicName), Topic.class);
tpublisher = tsession.createPublisher(topic);
msg = tsession.createTextMessage();
tcon.start();
}

public void send(String message) throws JMSException {
msg.setText(message);
tpublisher.publish(msg);
}

public void close() throws JMSException {
tpublisher.close();
tsession.close();
tcon.close();
}

public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("Usage: java examples.jms.topic.TopicSend WebLogicURL");
return;
}
InitialContext ic = getInitialContext(args[0]);
TopicSend ts = new TopicSend();
ts.init(ic, TOPIC);
readAndSend(ts);
ts.close();
}

protected static void readAndSend(TopicSend ts)throws IOException, JMSException
{
BufferedReader msgStream = new BufferedReader (new InputStreamReader(System.in));
String line=null;
System.out.print("nt TopicSender Started ... Enter message ("quit" to quit): n");
do {
System.out.print("Topic Sender Says > ");
line = msgStream.readLine();
if (line != null && line.trim().length() != 0) {
ts.send(line);
}
} while (line != null && ! line.equalsIgnoreCase("quit"));
}

protected static InitialContext getInitialContext(String url)
throws NamingException
{
Hashtable<String,String> env = new Hashtable<String,String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
env.put(Context.PROVIDER_URL, url);
env.put("weblogic.jndi.createIntermediateContexts", "true");
return new InitialContext(env);
}
}

Step8). Write the “TopicReceive.java” program as following inside “C:WebLogic_Topic_Demo” to receive messages from the WebLogic Topic

import java.io.*;
import java.util.*;
import javax.transaction.*;
import javax.naming.*;
import javax.jms.*;
import javax.rmi.PortableRemoteObject;
public class TopicReceive implements MessageListener {
public final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";
public final static String JMS_FACTORY="TCF";
public final static String TOPIC="TestTopic";
private TopicConnectionFactory tconFactory;
private TopicConnection tcon;
private TopicSession tsession;
private TopicSubscriber tsubscriber;
private Topic topic;
private boolean quit = false;

public void onMessage(Message msg)
{
try {
String msgText;
if (msg instanceof TextMessage) {
msgText = ((TextMessage)msg).getText();
} else {
msgText = msg.toString();
}
System.out.println("JMS Message Received: "+ msgText );
if (msgText.equalsIgnoreCase("quit")) {
synchronized(this) {
quit = true;
this.notifyAll();
}
}
} catch (JMSException jmse) {
System.err.println("An exception occurred: "+jmse.getMessage());
}
}

public void init(Context ctx, String topicName)throws NamingException, JMSException
{
tconFactory = (TopicConnectionFactory)PortableRemoteObject.narrow(ctx.lookup(JMS_FACTORY), TopicConnectionFactory.class);
tcon = tconFactory.createTopicConnection();
tsession = tcon.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
topic = (Topic) PortableRemoteObject.narrow(ctx.lookup(topicName), Topic.class);
tsubscriber = tsession.createSubscriber(topic);
tsubscriber.setMessageListener(this);
tcon.start();
}

public void close() throws JMSException {
tsubscriber.close();
tsession.close();
tcon.close();
}

public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("Usage: java examples.jms.topic.TopicReceive WebLogicURL");
return;
}
InitialContext ic = getInitialContext(args[0]);
TopicReceive tr = new TopicReceive();
tr.init(ic, TOPIC);
System.out.println("JMS Ready To Receive Messages (To quit, send a "quit" message).");
synchronized(tr) {
while (! tr.quit) {
try {
tr.wait();
} catch (InterruptedException ie) {}
}
}
tr.close();
}

private static InitialContext getInitialContext(String url) throws NamingException
{
Hashtable<String,String> env = new Hashtable<String,String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
env.put(Context.PROVIDER_URL, url);
env.put("weblogic.jndi.createIntermediateContexts", "true");
return new InitialContext(env);
}
}

Step9). Open 3 – Command Windows and run “setWLSEn.cmd” in all the three Command Windows to set the Environment (PATH & CLASSPATH).
Then compile the “TopicSend.java” and “TopicReceive.java” programs.

Step10). Start the “TopicReceive.java” program in two Command Windows like following :
java TopicReceive t3:/localhost:7001

Step11). Now start the “TopicSend.java” program to send some messages to the WebLogic Topic….As soon as u send message you will see that the Receivers started getting those messages…(One to Many Communication….one sender multiple receiver Which is called as Publish-Subscribe Messaging…. TOPIC)

Communication_Happening

Communication_Happening


NOTE: If you want to see the Messages inside the Topic from AdminConsole then Please follow the Tips provided by Wolkenfels”  http://middlewaremagic.com/weblogic/?p=2431#comment-1496

.

.

Thanks
Jay SenSharma


Copyright © 2010-2012 Middleware Magic. All rights reserved. |