JMS Archive

Topic Send and Topic Receive demo on JBoss Application Server

1 )Create a topic

Add the following in the \deploy\messaging\destinations-service.xml file

 

    <mbean code="org.jboss.jms.server.destination.TopicService"
      name="jboss.messaging.destination:service=Topic,name=Topic1"
      xmbean-dd="xmdesc/Topic-xmbean.xml">
	<depends optional-attribute-name="ServerPeer">jboss.messaging:service=ServerPeer</depends>
	<depends>jboss.messaging:service=PostOffice</depends>
   </mbean>

2) Copy the TopicSend and TopicReceive programs to a folder.

TopicSend

import java.io.*;
import java.util.*;
import javax.transaction.*;
import javax.naming.*;
import javax.jms.*;
import javax.rmi.PortableRemoteObject;

public class TopicSend
{
// Defines the JNDI context factory.
public final static String JNDI_FACTORY=”org.jnp.interfaces.NamingContextFactory”;
// Defines the JMS connection factory.
public final static String JMS_FACTORY=”ConnectionFactory”;
// Defines the topic.
public final static String TOPIC=”/topic/Topic1″;

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 TopicSend jboss_url”);
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;
do {
System.out.print(“Enter message (\”quit\” to quit): \n”);
line = msgStream.readLine();
if (line != null && line.trim().length() != 0) {
ts.send(line);
System.out.println(“JMS Message Sent: “+line+”\n”);
}
} 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);

return new InitialContext(env);
}

}

TopicReceive

import java.io.*;
import java.util.*;
import javax.transaction.*;
import javax.naming.*;
import javax.jms.*;
import javax.rmi.PortableRemoteObject;

public class TopicReceive implements MessageListener {

// Defines the JNDI context factory.
public final static String JNDI_FACTORY=”org.jnp.interfaces.NamingContextFactory”;
// Defines the JMS connection factory for the topic.
public final static String JMS_FACTORY=”ConnectionFactory”;
// Defines the topic.
public final static String TOPIC=”/topic/Topic1″;

private TopicConnectionFactory tconFactory;
private TopicConnection tcon;
private TopicSession tsession;
private TopicSubscriber tsubscriber;
private Topic topic;
private boolean quit = false;

/**
* Message listener interface.
* @param msg message
*/
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(); // Notify main thread to quit
}
}
} 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();
}

/**
* Closes JMS objects.
*
* @exception JMSException if JMS fails to close objects due to internal error
*/
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 TopicReceive jboss_url”);
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).”);

// Wait until a “quit” message has been received.
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);

return new InitialContext(env);
}

}

 

3) Start your Jboss Server

D:\JBossEnterprisePlatform-5.1.1_New\jboss-eap-5.1\jboss-as\bin>run -c server1 -b 0.0.0.0

4) Open two command prompts, compile and run the two programs as follows.

C:\JBoss\LABS>set classpath=D:\JBossEnterprisePlatform-5.1.1_New\jboss-eap-5.1\jboss-as\client\*;.;
C:\JBoss\LABS>javac TopicReceive.java
C:\JBoss\LABS>java TopicReceive jnp://localhost:1099

C:\JBoss\LABS>set classpath=D:\JBossEnterprisePlatform-5.1.1_New\jboss-eap-5.1\jboss-as\client\*;.;
C:\JBoss\LABS>javac TopicSend.java
C:\JBoss\LABS>java TopicSend jnp://localhost:1099

You can have multiple receivers.

Please let us know if you face any issues.

Cheers!
Wonders Team

JMS Based Webservice on Weblogic Server

By default, client applications use HTTP/S as the connection protocol when invoking a WebLogic Web Service. You can, however, configure a WebLogic Web Service so that client applications can also use JMS as the transport when invoking the Web Service.When a WebLogic Web Service is configured to use JMS as the connection transport:The generated WSDL of the Web Service contains two port definitions: one with an HTTP/S binding and one with a JMS binding. When you invoke the Web Service in your client application, you can choose which port, and thus which type of transport, you want to use.Warning:     Non-WebLogic client applications, such as a .NET client, will not be able to invoke the Web Service using the JMS binding.The clientgen Ant task creates a Service implementation that contains two getPortXXX() methods, one for HTTP/S and one for JMS.Note:    You can configure any WebLogic Web Service to include a JMS binding in its WSDL. This feature is independent of JMS-implemented WebLogic Web Services.

Read more

Step1 :-

Create JMS Server and target it to the AdminServer running on http://localhost:7001Create a ConnectionFactory and a Queue targeted to the JMSServer.For Screenshots follow this article.
Step2 :- Create a JWS File

package demo;
import weblogic.jws.*;

import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.soap.SOAPBinding;

@WebService(name=”HelloWorldPortType”,serviceName=”HelloWorldService”,      targetNamespace=”http://www.bea.com”)
@SOAPBinding(style=SOAPBinding.Style.DOCUMENT,use=SOAPBinding.Use.LITERAL,           parameterStyle=SOAPBinding.ParameterStyle.WRAPPED)

@WLJmsTransport(serviceUri=”HelloWorldService”,portName=”HelloWorldServicePort”,                    contextPath=”HelloWorldService”,connectionFactory=”ConnectionFactory-0″,queue=”Queue-0″)

public class HelloWorldImpl {
@WebMethod()
public String sayHello(String s) {
return “Hello ” + s;
}
}

Step 3:- Create a Client

package demo;
import demo.HelloWorldService;
import demo.HelloWorldService_Impl;
import demo.HelloWorldPortType;
import weblogic.wsee.jaxrpc.WLStub;
import java.util.ArrayList;
import java.util.List;
import javax.xml.rpc.Stub;

public class HelloWorldClient
{
public static void main(String[] args) throws Throwable {

String wsdl = args[0];
HelloWorldService service = new HelloWorldService_Impl(wsdl);
HelloWorldPortType port = service.getHelloWorldServicePort();
Stub stub = (Stub)port;
stub._setProperty(WLStub.JMS_TRANSPORT_JNDI_URL, “t3://localhost:7001”);
String response = port.sayHello(“World”);
System.out.println(“response = ” + response);
}
}

Step 4:- Create a build

<project name=”Sample JMS Webservice” default=”all” basedir=”.”>

<property name=”ws.file” value=”HelloWorldImpl” />
<property name=”ear.dir” value=”./ear” />
<property name=”client.dir” value=”./client” />

<path id=”client.class.path”>
<pathelement path=”${client.dir}”/>
<pathelement path=”${java.class.path}”/>
</path>

<taskdef name=”jwsc”
classname=”weblogic.wsee.tools.anttasks.JwscTask” />

<taskdef name=”clientgen”
classname=”weblogic.wsee.tools.anttasks.ClientGenTask” />

<target name=”all” depends=”clean,
server,
client,
deploy” />

<target name=”build” depends=”clean,
server,
client” />

<target name=”clean”>
<delete dir=”${ear.dir}”/>
<delete dir=”${client.dir}”/>
</target>

<target name=”server”>
<mkdir dir=”${ear.dir}”/>
<jwsc
srcdir=”${basedir}”
destdir=”${ear.dir}”
classpath=”${java.class.path}”
fork=”true”
keepGenerated=”true”
deprecation=”${deprecation}”
debug=”${debug}”
verbose=”false”>
<jws file=”${ws.file}.java” explode=”true”/>
</jwsc>
</target>

<target name=”deploy”>
<wldeploy action=”deploy”
source=”${ear.dir}” user=”weblogic”
password=”weblogic” verbose=”true”
failonerror=”${failondeploy}”
adminurl=”t3://localhost:7001″
targets=”AdminServer” />
</target>

<target name=”client”>
<mkdir dir=”${client.dir}”/>
<clientgen
wsdl=”${ear.dir}/${ws.file}/WEB-INF/HelloWorldService.wsdl”
destDir=”${client.dir}”
classpath=”${java.class.path}”
packageName=”demo”/>
<javac
srcdir=”${client.dir}” destdir=”${client.dir}”
classpath=”${java.class.path}”
includes=”demo/**/*.java”/>
<javac
srcdir=”${basedir}” destdir=”${client.dir}”
classpath=”${java.class.path};${client.dir}”
includes=”HelloWorldClient.java”/>
</target>

<target name=”run” >
<java fork=”true”
classname=”demo.HelloWorldClient”
failonerror=”true” >
<classpath refid=”client.class.path”/>
<arg line=”http://localhost:7001/HelloWorldService/HelloWorldService?WSDL” />
</java>
</target>

</project>

Step 5:- Create a folder and keep the source files and the build.xml in that directory. Also copy the setWLSEnv.cmd from WL_HOME\bin to this folder. Create two folders in this folder, ear and client.

Step 6 :- Set the Environment

D:\Replications\jmswebservice>setWLSEnv.cmd

Step 7:- Create the Webservice Ear

D:\Replications\jmswebservice>ant server
Buildfile: build.xml

server:
[jwsc] JWS: processing module /HelloWorldImpl
[jwsc] Parsing source files
[jwsc] Parsing source files
[jwsc] 1 JWS files being processed for module /HelloWorldImpl
[jwsc] JWS: D:\Replications\jmswebservice\HelloWorldImpl.java Validated.
[jwsc] Since compiler setting isn’t classic or modern,ignoring fork setting
.
[jwsc] Compiling 2 source files to C:\Users\khanf\AppData\Local\Temp\_bxr00
h
[jwsc] Since compiler setting isn’t classic or modern,ignoring fork setting
.
[jwsc] Copying 1 file to D:\Replications\jmswebservice\ear\HelloWorldImpl\W
EB-INF
[jwsc] Copying 22 files to D:\Replications\jmswebservice\ear\HelloWorldImpl
\WEB-INF
[jwsc] Copying 2 files to D:\Replications\jmswebservice\ear\HelloWorldImpl\
WEB-INF\classes
[jwsc] Copying 1 file to D:\Replications\jmswebservice\ear\HelloWorldImpl
[jwsc] [EarFile] Application File : D:\Replications\jmswebservice\ear\META-
INF\application.xml
[AntUtil.deleteDir] Deleting directory C:\Users\khanf\AppData\Local\Temp\_bxr00h

BUILD SUCCESSFUL
Total time: 16 seconds

Step 8:- Deploy the Ear

D:\Replications\jmswebservice>ant deploy
Buildfile: build.xml

deploy:
[wldeploy] weblogic.Deployer -verbose -noexit -source D:\Replications\jmswebser
vice\ear -targets AdminServer -adminurl t3://localhost:7001 -user weblogic -pass
word ******** -deploy
[wldeploy] weblogic.Deployer invoked with options: -verbose -noexit -source D:
\Replications\jmswebservice\ear -targets AdminServer -adminurl t3://localhost:70
01 -user weblogic -deploy
[wldeploy] <Apr 30, 2011 2:06:34 PM IST> <Info> <J2EE Deployment SPI> <BEA-2601
21> <Initiating deploy operation for application, ear [archive: D:\Replications\
jmswebservice\ear], to AdminServer .>
[wldeploy] Task 3 initiated: [Deployer:149026]deploy application ear on AdminSe
rver.
[wldeploy] Task 3 completed: [Deployer:149026]deploy application ear on AdminSe
rver.
[wldeploy] Target state: deploy completed on Server AdminServer
[wldeploy]
[wldeploy] Target Assignments:
[wldeploy] + ear AdminServer

BUILD SUCCESSFUL

Step 9 :- Compile the client

D:\Replications\jmswebservice>ant client
Buildfile: build.xml

client:
[clientgen] Ignoring JAX-WS options – building a JAX-RPC client
[clientgen]
[clientgen] *********** jax-rpc clientgen attribute settings ***************
[clientgen]
[clientgen] wsdlURI: file:/D:/Replications/jmswebservice/ear/HelloWorldImpl/WEB-
INF/HelloWorldService.wsdl
[clientgen] serviceName : null
[clientgen] packageName : demo
[clientgen] destDir : D:\Replications\jmswebservice\client
[clientgen] handlerChainFile : null
[clientgen] generatePolicyMethods : false
[clientgen] autoDetectWrapped : true
[clientgen] jaxRPCWrappedArrayStyle : true
[clientgen] generateAsyncMethods : true
[clientgen]
[clientgen] *********** jax-rpc clientgen attribute settings end ***************

[clientgen] Package name is demo
[clientgen] DestDir is D:\Replications\jmswebservice\client
[clientgen] class name is HelloWorldPortType_Stub
[clientgen] service class name is HelloWorldService
[clientgen] Porttype name is HelloWorldPortType
[clientgen] service impl name is HelloWorldService_Impl
[javac] Compiling 4 source files to D:\Replications\jmswebservice\client
[javac] Note: D:\Replications\jmswebservice\client\demo\HelloWorldPortType_S
tub.java uses unchecked or unsafe operations.
[javac] Note: Recompile with -Xlint:unchecked for details.
[javac] Compiling 1 source file to D:\Replications\jmswebservice\client

BUILD SUCCESSFUL

Step 10:- Run the Client

D:\Replications\jmswebservice>ant run
Buildfile: build.xml

run:
[java] response = Hello World

BUILD SUCCESSFUL
Total time: 10 seconds

If you have a look at the WSDL

http://localhost:7001/HelloWorldService/HelloWorldService?WSDL

The service will look like this.

<s0:service name=”HelloWorldService”>
<s0:port binding=”s1:HelloWorldServiceSoapBinding” name=”HelloWorldServicePort”>
<s2:address location=”jms://192.168.3.8:7001/HelloWorldService/HelloWorldService?URI=Queue-0&FACTORY=ConnectionFactory-0″ />
</s0:port>
</s0:service>

Let me know if you face any issues while running this sample.

 

Download the source here : jmswebservice

JBoss MDB

This post describes usage of Jboss JMS Feature using a Message Driven Bean (MDB) consumer.

Note: In this article , we would be using the default JMS queue ‘/queue/DLQ’.

1. Create a Message Driven Bean with bean class TestMDB.java

 

import java.io.PrintStream;
import javax.ejb.MessageDrivenBean;
import javax.jms.*;
import weblogic.ejb.GenericMessageDrivenBean;
import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.ejb.EJBException;
import javax.jms.MessageListener;
import javax.jms.Message;
public class TestMDB implements MessageDrivenBean, MessageListener {
private MessageDrivenContext ctx = null;
public TestMDB() {
}
//--- MessageDrivenBean
public void setMessageDrivenContext(MessageDrivenContext ctx)
throws EJBException {
this.ctx = ctx;
}
public void ejbCreate() {}
public void ejbRemove() {ctx=null;}
//--- MessageListener
public void onMessage(Message msg)
{
try
{
System.out.println("****** Inside onMessage() *********");
String msgText;
if(msg instanceof TextMessage)
msgText = ((TextMessage)msg).getText();
else
msgText = msg.toString();
System.out.println((new StringBuilder("Message Received: ")).append(msgText).toString());
}
catch(JMSException jmse)
{
jmse.printStackTrace();
}
}
}

2. Generate the ejb-jar.xml as below.

 

<?xml version="1.0" encoding="UTF-8"?>

<ejb-jar

xmlns="http://java.sun.com/xml/ns/j2ee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd"

version="2.1">

<enterprise-beans>

<message-driven>

<ejb-name>TestMDB</ejb-name>

<ejb-class>TestMDB</ejb-class>

<transaction-type>Container</transaction-type>

<activation-config>

<activation-config-property>

<activation-config-property-name>destinationType</activation-config-property-name>

<activation-config-property-value>javax.jms.Queue</activation-config-property-value>

</activation-config-property>

</activation-config>

</message-driven>

</enterprise-beans>

</ejb-jar>

 

Note:  Specify the ejb bean class name in the attribute <ejb-class> of the element   <message-driven>.

3. Generate the jboss.xml to specify the name of the Jboss Queue, which the MDB bean would be listening to.

 

<?xml version="1.0" encoding="Cp1252"?>

<jboss>

<enterprise-beans>

<message-driven>

<ejb-name>TestMDB</ejb-name>

<configuration-name>Standard Message Driven Bean</configuration-name>

<destination-jndi-name>/queue/DLQ</destination-jndi-name>

</message-driven>

</enterprise-beans>

</jboss>

 

4. Create a jar file as below.

jar -cvf TestMDB.jar .

5. Copy the jar file and paste it under Deploy folder of any server profiles.

$JBOSS_HOME\server\default\deploy

The deployment is automatically picked up by the server and you would see the relevant messages in the server logs and the console.

****************************************************************************

21:09:18,968 INFO  [EjbDeployer] installing bean: ejb/#TestMDB,uid6458583

21:09:18,968 INFO  [EjbDeployer]   with dependencies:

21:09:18,968 INFO  [EjbDeployer]   and supplies:

21:09:18,968 INFO  [EjbDeployer]        jndi:null

21:09:19,046 INFO  [EjbModule] Deploying TestMDB

****************************************************************************

6. Open a command prompt and set the class path to the jbossall-client.jar file.

set classpath=%classpath%;G:\jboss-5.1.0.GA\client\jbossall-client.jar

7. Compile and execute the below QueueSend.java program

 

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.Hashtable;

import javax.jms.*;

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.naming.NamingException;

import java.util.Properties;

public class QueueSend

{

public final static String JNDI_FACTORY="org.jboss.naming.HttpNamingContextFactory";

public final static String JMS_FACTORY="ConnectionFactory";

public final static String QUEUE="/queue/DLQ";

private QueueConnectionFactory qconFactory;

private QueueConnection qcon;

private QueueSession qsession;

private QueueSender qsender;

private Queue queue;

private TextMessage msg;

public void init(Context ctx, String queueName)

throws NamingException, JMSException

{

qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);

qcon = qconFactory.createQueueConnection();

qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

queue = (Queue) ctx.lookup(queueName);

qsender = qsession.createSender(queue);

msg = qsession.createTextMessage();

qcon.start();

}

public void send(String message) throws JMSException {

msg.setText(message);

qsender.send(msg);

}

public void close() throws JMSException {

qsender.close();

qsession.close();

qcon.close();

}

public static void main(String[] args) throws Exception {

if (args.length != 1) {

System.out.println("Usage: java examples.jms.queue.QueueSend JBossURL");

return;

}

InitialContext ic = getInitialContext(args[0]);

QueueSend qs = new QueueSend();

qs.init(ic, QUEUE);

readAndSend(qs);

qs.close();

}

private static void readAndSend(QueueSend qs)

throws IOException, JMSException

{

BufferedReader msgStream = new BufferedReader(new InputStreamReader(System.in));

String line=null;

boolean quitNow = false;

do {

System.out.print("Enter message (\"quit\" to quit): \n");

line = msgStream.readLine();

if (line != null && line.trim().length() != 0) {

qs.send(line);

System.out.println("JMS Message Sent: "+line+"\n");

quitNow = line.equalsIgnoreCase("quit");

}

} while (! quitNow);

}

private static InitialContext getInitialContext(String url)

throws NamingException

{

Properties env = new Properties();

env.setProperty(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);

env.setProperty(Context.PROVIDER_URL,url);

return new InitialContext(env);

}

}

 

****************************************************************************

java QueueSend http://127.0.0.1:8080/invoker/JNDIFactory

The  deployed MDB will consume the messages from the Jboss Queue as shown below.

For reference I have uploaded the sample TestMDB.jar to the below link.

http://www.4shared.com/file/TjO6i_DR/TestMDB.html

Best Regards,

Wonders


WLDF generating JMS Message notifications

This post describes a simple usage of how we can leverage the WLDF functionality with JMS feature. This post would show how WLDF can generate notifications in the form of JMS messages and sends it to message Queue which can be consumed by the JMS consumer.

Before starting the configuration , we would require a JMS Queue setup. Follow the below link to create one.

http://weblogic-wonders.com/weblogic/2010/11/30/weblogic-jms-feature-using-a-queue/

1. Login into the WebLogic Administration Console and navigate to Diagnostic → Diagnostic Module.

Create a WLDF (Diagnostic) module.


2. Click on the created WLDF module.

NOTE: There are two types o RunTime MBeans.  DomainRuntime Mbean and ServerRuntime Mbean.

DomainRuntime Mbean provides access to the Domain Wide configuration and is available only for the Admin Server.

When connecting to Managed Server, the root would be ServerRuntime MBean and DomainRuntime Mbean is not available

The below post depicts the access to DomainRuntime Mbean.

Navigate to the ‘Create Metrics’ → New → Specify the Metric Collection Properties details by selecting on which type of Mbean you want to configure the Metrics. → Select DomainRuntime

3. Select the Mbean you want to collect metrics for. For demo we would select ‘weblogic.management.runtime.JVMRuntimeMBean’ → Specify which attribute of the Mbean you want to monitor. For instance select ‘HeapSizeMax’.

4. Select the server instance which you want to monitor. Click finish and the collection metrics is created.

5. Now create Watch and Notifications.

The Watch and Notification system can be used to create automated monitors that observe specific diagnostic state and send notifications based on configured rules.

Watch:- It is basically used to monitor the Mbean attributes.

Notifications: There are the events which are triggered based on the values set in the watch. There can be different kind of alerts like SNMP alerts, JMS Messages, JMX notifications etc.

We would be selecting JMS Messages from the notifiers list.

6. Specify the Queue JNDI name and the Connection Factory JNDI name which would be notified when the Watch events are triggered.

7. Once the notification is created. Create a watch to monitor the attributes of the Mbean.

8. Click on the ‘Add Expressions’ to specify the rules for the watch. There can be a set of rules monitoring different attributes.


Here we would monitor the HeapSizeMax attribute of ‘weblogic.management.runtime.JVMRuntimeMBean for demo.

9. Select DomainRuntime from the drop down → Click next and select ”weblogic.management.runtime.JVMRuntimeMBean’ from the drop down list → Select the instance of the server from the drop down list.

10.Select the attribute , you want to monitor. For example HeapSizeMax and specify a value for that rule. Click Next.

Note: Click on combine tab, if you want to have a set of rules for the watch expression.

11. Select ‘Use an automatic reset alarm’ that would reset the notification alarms automatically.

12. Select the JMS Notifier from the left side list so that we can associate the Notifier with the watch created, click finish.

13. Target the WLDF to any of the servers whose MBeans are monitored.

Note: The default polling interval of the Mbean attribute is ‘300000’ milliseconds. We can reconfigure it as per our requirements.

13. Now check the server logs or the server console and you can see the alerts being triggered.

14. Compile and execute the below QueueReceiver.java program to receive the notifications in the form of JMS Messages and listening to queue ‘Queue’.

*****************************************************************************

 

import java.util.Hashtable;

import javax.jms.*;

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.naming.NamingException;

public class QueueReceive implements MessageListener

{

public final static String JNDI_FACTORY=”weblogic.jndi.WLInitialContextFactory”;

public final static String JMS_FACTORY=”CF1″;

public final static String QUEUE=”Queue1″;

private QueueConnectionFactory qconFactory;

private QueueConnection qcon;

private QueueSession qsession;

private QueueReceiver qreceiver;

private Queue queue;

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(“Message Received: “+ msgText );

if (msgText.equalsIgnoreCase(“quit”)) {

synchronized(this) {

quit = true;

this.notifyAll(); // Notify main thread to quit

}

}

} catch (JMSException jmse) {

System.err.println(“An exception occurred: “+jmse.getMessage());

}

}

public void init(Context ctx, String queueName)

throws NamingException, JMSException

{

qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);

qcon = qconFactory.createQueueConnection();

qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

queue = (Queue) ctx.lookup(queueName);

qreceiver = qsession.createReceiver(queue);

qreceiver.setMessageListener(this);

qcon.start();

}

public void close()throws JMSException

{

qreceiver.close();

qsession.close();

qcon.close();

}

public static void main(String[] args) throws Exception {

if (args.length != 1) {

System.out.println(“Usage: java examples.jms.queue.QueueReceive WebLogicURL”);

return;

}

InitialContext ic = getInitialContext(args[0]);

QueueReceive qr = new QueueReceive();

qr.init(ic, QUEUE);

System.out.println(“JMS Ready To Receive Messages (To quit, send a \”quit\” message).”);

synchronized(qr) {

while (! qr.quit) {

try {

qr.wait();

} catch (InterruptedException ie) {}

}

}

qr.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);

return new InitialContext(env);

}}

 

*****************************************************************************

Below image shows that the JMS QueueReceiver program is reading the WLDF notifications.

You can put your own business logic inside the QueueReceiver.java’s onMessage() method to specify the business requirements.

Do let us know, if you run into any issues configuring the same.  🙂

Best Regards


JBoss JMS using HornetQ

This article shows how JBoss server can leverage the messaging capabilities of HornetQ.

“HornetQ is an open source project to build a multi-protocol, embeddable, very high performance, clustered, asynchronous messaging system.”

1. Open the command prompt and set the JBOSS_HOME environment to the JBoss installation directory

set JBOSS_HOME=C:\jboss-5.1.0.GA

set HORNETQ_HOME environment variable to the HornetQ installation directory.

set HORNETQ_HOME=C:\hornetq-2.1.1.Final

2.Run build.batunder HORNETQ_HOME/config/jboss-as-5directory

C:\hornetq-2.1.1.Final\config\jboss-as-5>build.bat

This will create 2 new profiles under $JBOSS_HOME/server directory:

–> default-with-hornetq — it corresponds to AS 5 default profile with HornetQ as its JMS provider. In this profile, HornetQ is non-clustered

–> all-with-hornetq — it corresponds to AS 5 all profile with HornetQ as its JMS provider. In this profile, HornetQ is clustered

You can then start JBoss AS 5 using one of these profiles, e.g. :

$JBOSS_HOME/bin/run.bat -c default-with-hornetq

3:- Go to $JBOSS_HOME/server/default-with-hornetq/deploy/hornetq.sar

You will find a file “hornetq-jms.xml” which contains the default ConnectionFactories and the Default Queue Destinations that can be used.

Refer the figure below.

4.  Set the CLASSPATH to the $JBOSS_HOME\client\jbossall-client.jar and all the jar files under $HORNETQ_HOME\lib folder

set classpath=%classpath%;$JBOSS_HOME\jbossall-client.jar;$HORNETQ_HOME\lib\hornetq-jms.jar ; $HORNETQ_HOME\lib\hornetq-core.jar ; $HORNETQ_HOME\lib\netty.jar;

5.  Compile and execute the below QueueSend.java program

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.Hashtable;

import javax.jms.*;

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.naming.NamingException;

import java.util.Properties;

public class QueueSend

{

public final static String JNDI_FACTORY="org.jboss.naming.HttpNamingContextFactory";

public final static String JMS_FACTORY="ConnectionFactory";

public final static String QUEUE="/queue/DLQ";

private QueueConnectionFactory qconFactory;

private QueueConnection qcon;

private QueueSession qsession;

private QueueSender qsender;

private Queue queue;

private TextMessage msg;

public void init(Context ctx, String queueName)

throws NamingException, JMSException

{

qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);

qcon = qconFactory.createQueueConnection();

qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

queue = (Queue) ctx.lookup(queueName);

qsender = qsession.createSender(queue);

msg = qsession.createTextMessage();

qcon.start();

}

public void send(String message) throws JMSException {

msg.setText(message);

qsender.send(msg);

}

public void close() throws JMSException {

qsender.close();

qsession.close();

qcon.close();

}

public static void main(String[] args) throws Exception {

if (args.length != 1) {

System.out.println("Usage: QueueSend JBossURL");

return;

}

InitialContext ic = getInitialContext(args[0]);

QueueSend qs = new QueueSend();

qs.init(ic, QUEUE);

readAndSend(qs);

qs.close();

}

private static void readAndSend(QueueSend qs)

throws IOException, JMSException

{

BufferedReader msgStream = new BufferedReader(new InputStreamReader(System.in));

String line=null;

boolean quitNow = false;

do {

System.out.print("Enter message (\"quit\" to quit): \n");

line = msgStream.readLine();

if (line != null && line.trim().length() != 0) {

qs.send(line);

System.out.println("JMS Message Sent: "+line+"\n");

quitNow = line.equalsIgnoreCase("quit");

}

} while (! quitNow);

}

private static InitialContext getInitialContext(String url)

throws NamingException

{

Properties env = new Properties();

env.setProperty(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);

env.setProperty(Context.PROVIDER_URL,url);

return new InitialContext(env);

}

}

6: Run the QueueSend.java as below

java QueueSend http://127.0.0.1:8080/invoker/JNDIFactory

6.  Compile and execute the below QueueReceive.java program

import java.util.Hashtable;

import javax.jms.*;

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.naming.NamingException;

import java.util.Properties;

public class QueueReceive implements MessageListener

{

public final static String JNDI_FACTORY="org.jboss.naming.HttpNamingContextFactory";

public final static String JMS_FACTORY="ConnectionFactory";

public final static String QUEUE="/queue/DLQ";

private QueueConnectionFactory qconFactory;

private QueueConnection qcon;

private QueueSession qsession;

private QueueReceiver qreceiver;

private Queue queue;

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("Message Received: "+ msgText );

if (msgText.equalsIgnoreCase("quit")) {

synchronized(this) {

quit = true;

this.notifyAll(); // Notify main thread to quit

}

}

} catch (JMSException jmse) {

System.err.println("An exception occurred: "+jmse.getMessage());

}

}

public void init(Context ctx, String queueName)

throws NamingException, JMSException

{

qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);

qcon = qconFactory.createQueueConnection();

qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

queue = (Queue) ctx.lookup(queueName);

qreceiver = qsession.createReceiver(queue);

qreceiver.setMessageListener(this);

qcon.start();

}

public void close()throws JMSException

{

qreceiver.close();

qsession.close();

qcon.close();

}

public static void main(String[] args) throws Exception {

if (args.length != 1) {

System.out.println("Usage: QueueReceive JBossURL");

return;

}

InitialContext ic = getInitialContext(args[0]);

QueueReceive qr = new QueueReceive();

qr.init(ic, QUEUE);

System.out.println("JMS Ready To Receive Messages (To quit, send a \"quit\" message).");

// Wait until a "quit" message has been received.

synchronized(qr) {

while (! qr.quit) {

try {

qr.wait();

} catch (InterruptedException ie) {}

}

}

qr.close();

}

private static InitialContext getInitialContext(String url)

throws NamingException

{

Properties env = new Properties();

env.setProperty(Context.INITIAL_CONTEXT_FACTORY,JNDI_FACTORY);

env.setProperty(Context.PROVIDER_URL,url);

return new InitialContext(env);

}

}

7. Run the QueueReceive.java as below

java QueueReceive http://127.0.0.1:8080/invoker/JNDIFactory

You can download HornetQ from the below link.

http://www.jboss.org/hornetq/downloads.html

Refer the below link for HornetQ documentation.

http://www.jboss.org/hornetq/docs

Cheers,

Wonders Team 🙂

WebLogic JMS feature using Topic

The following article shows a simple usage of WebLogic JMS feature using a Topic.

1. Login into the WebLogic Admin Console, navigate to Services à Messaging à JMS Servers.

JMS Server acts as a management containers for the queues and topics.

Create a JMS Server as below.

2.Target the JMS Server to any one of the WebLogic Servers.

3. Create a JMS System Module to hold the queues and topics.

Navigate to Services –> Messaging –> JMS Modules.

4. Target the JMS System Module to the server on which the JMS Server is targeted.

5. Before adding JMS Topics, create a Sub Deployment.

6. Target the Sub Deployment to the created JMS Server.

7. Under the configuration tab, click New to add resources like Connection Factories, Queues,Topics.

8. Create a JMS Connection Factory, specify a JNDI name.

9. Target the Connection Factory to the Sub Deployment.

10. Similarly create a Topic, then target to the Sub Deployment.

11. Navigate to the JMS Resources page and you would see the Connection Factory and the JMS Topic created.

12. Open  command prompt, and set the class path.

13. Execute the below, TopicSend.java program to send a message to the Topic.

*************************************************************

 

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="CF1";

public final static String TOPIC="Topic1";

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;

do {

System.out.print("Enter message (\"quit\" to quit): \n");

line = msgStream.readLine();

if (line != null && line.trim().length() != 0) {

ts.send(line);

System.out.println("JMS Message Sent: "+line+"\n");

}

} 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);

}}

 

*************************************************************

14.Execute the below TopicReceive.java program to retrieve the message from the 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="CF1";

public final static String TOPIC="Topic1";

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(); // Notify main thread to quit

}

}

} 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);

}}

 

******************************************************

Best Regards.