Tag: JMS

Setup JMS with Unit-Of-Order using WLST

Ravish Mody

Yesterday one of our subscribers Miguel had asked us using comment how to configure the Unit-of-Order property using WLST script, as he was already able to create a JMSServer, JMSModule and JMS Connection Factory using a wlst script but was having an issue setting the  Unit-of-Order property, hence it seemed to be a great topic to create an article on it. With below single script you can create and target following components.

  1. JMSServer
  2. JMSModule
  3. Queue
  4. ConnectionFactory
  5. Unit-Of-Order

As usual we have used a properties file which has all the required details in it like the JMSServer, JMSModule, Queue, ConnectionFactory names, targets name etc. This way you would not have to modify anything in your actual WLST script.

Setup JMS with Unit-Of-Order using WLST

Step1). Create a Directory somewhere in your file system like : “C:\WLST\JMS

Step2). Write a Properties filedomain.properties inside “C:\WLST\JMS” like following:

# 1 - Connecting details
server.url = t3://localhost:7001
username = weblogic
password = weblogic

# 2 - JMSServer details
jms.server.name = My_JMSServer
store.name = MyJDBCStore
tragated.jms.server.name = AdminServer

# 3 - SystemModule Details
system.module.name = My_SystemModule
tragated.system.module.name = AdminServer

# 4 - ConnectionFactory Details
connection.factory.name = My_ConnectionFactory
connection.factory.jndi.name = My_CF

# 5 - Unit Of Order Details
unit.of.order.value = 1

# 6 - SubDeployment & Queue Details
queue.sub.deployment.name = Sub_My_Queue
queue.name = My_Queue
queue.jndi.name = My_Q

Step2). Now in the same directory write the following WLST Script “JMS_Setup.py” like following:

#############################################################################
#
# @author Copyright (c) 2010 - 2011 by Middleware Magic, All Rights Reserved.
#
#############################################################################

from java.io import FileInputStream
import java.lang
import os
import string

propInputStream = FileInputStream("domain.properties")
configProps = Properties()
configProps.load(propInputStream)

# 1 - Connecting details
serverUrl = configProps.get("server.url")
Username = configProps.get("username")
Password = configProps.get("password")

# 2 - JMSServer details
jmsServerName = configProps.get("jms.server.name")
storeName = configProps.get("store.name")
tragatedJMSServerName = configProps.get("tragated.jms.server.name")

# 3 - SystemModule Details
systemModuleName = configProps.get("system.module.name")
tragatedSystemModuleName = configProps.get("tragated.system.module.name")

# 4 - ConnectionFactory Details
connectionFactoryName = configProps.get("connection.factory.name")
ConnectionFactoryJNDIName = configProps.get("connection.factory.jndi.name")

# 5 - Unit Of Order Details
unitOfOrderValue = configProps.get("unit.of.order.value")

# 6 - SubDeployment & Queue Details
queueSubDeploymentName = configProps.get("queue.sub.deployment.name")
queueName = configProps.get("queue.name")
queueJNDIName = configProps.get("queue.jndi.name")

redirect('wlst.log','false')

# 1 - Connecting to the Destination
connect(Username,Password,serverUrl)

edit()

# 2 - JMSServer details
print "================== JMSSever ==================="
startEdit()
cmo.createJMSServer(jmsServerName)
print "Created a JMSServer !!"
cd('/Deployments/'+jmsServerName)
cmo.setPersistentStore(getMBean('/JDBCStores/'+storeName))
print "PersistentStore has been set for the JMSServer !!"
set('Targets',jarray.array([ObjectName('com.bea:Name='+tragatedJMSServerName+',Type=Server')], ObjectName))
print "Targeted the JMSServer !!"
activate()
print ""

# 3 - SystemModule Details
print "================== SystemModule ==================="
startEdit()
cd('/')
cmo.createJMSSystemResource(systemModuleName)
print "Created a SystemModule !!"
cd('/SystemResources/'+systemModuleName)
set('Targets',jarray.array([ObjectName('com.bea:Name='+tragatedSystemModuleName+',Type=Server')], ObjectName))
print "Targeted the SystemModule !!"
activate()
print ""

# 4 - ConnectionFactory Details
print "================== ConnectionFactory ==================="
startEdit()
cd('/JMSSystemResources/'+systemModuleName+'/JMSResource/'+systemModuleName)
cmo.createConnectionFactory(connectionFactoryName)
cd('/JMSSystemResources/'+systemModuleName+'/JMSResource/'+systemModuleName+'/ConnectionFactories/'+connectionFactoryName)
cmo.setJNDIName(ConnectionFactoryJNDIName)
print "Created a ConnectionFactory !!"
cd('/JMSSystemResources/'+systemModuleName+'/JMSResource/'+systemModuleName+'/ConnectionFactories/'+connectionFactoryName+'/SecurityParams/'+connectionFactoryName)
cmo.setAttachJMSXUserId(false)
cd('/JMSSystemResources/'+systemModuleName+'/JMSResource/'+systemModuleName+'/ConnectionFactories/'+connectionFactoryName)
cmo.setDefaultTargetingEnabled(true)
print "Targeted the ConnectionFactory !!"
activate()
print ""

# 5 - Unit Of Order Details
print "================== Unit Of Order ==================="
startEdit()
cd('/JMSSystemResources/'+systemModuleName+'/JMSResource/'+systemModuleName+'/ConnectionFactories/'+connectionFactoryName+'/DefaultDeliveryParams/'+connectionFactoryName)
cmo.setDefaultUnitOfOrder(unitOfOrderValue)
print "Changed Unit Of Order !!"
activate()
print ""

# 6 - SubDeployment & Queue Details
print "================== SubDeployment & Queue ==================="
startEdit()
cd('/SystemResources/'+systemModuleName)
cmo.createSubDeployment(queueSubDeploymentName)
print "Created a SubDeployment for Queue !!"
cd('/JMSSystemResources/'+systemModuleName+'/JMSResource/'+systemModuleName)
cmo.createQueue(queueName)
print "Created a Queue !!"
cd('/JMSSystemResources/'+systemModuleName+'/JMSResource/'+systemModuleName+'/Queues/'+queueName)
cmo.setJNDIName(queueJNDIName)
cmo.setSubDeploymentName(queueSubDeploymentName)
cd('/SystemResources/'+systemModuleName+'/SubDeployments/'+queueSubDeploymentName)
set('Targets',jarray.array([ObjectName('com.bea:Name='+jmsServerName+',Type=JMSServer')], ObjectName))
print "Targeted the Queue to the created subdeployment !!"
activate()
print ""

cmd = "rm -f wlst.log"
os.system(cmd)

Step3). Now Open a Command/Shell Prompt and then run the “setWLSEnv.sh” script to set the CLASSPATH and PATH environment variables. Run the “. ./setWLSEnv.sh” by adding two DOTs separated by a single space …..before the actual script like following : (use ‘cd’ command to move inside the <BEA_HOME>/wlserver_10.3/server/bin) then run the following command….
. ./setWLSEnv.sh

Note: Here The first DOT represents that set the Environment in the current Shell, AND the second ./ represents execute the script from the current directory.

Step4). Run the Above WLST Script like following:

java weblogic.WLST JMS_Setup.py

Following would be the Output

java weblogic.WLST JMS_Setup.py

Initializing WebLogic Scripting Tool (WLST) ...

Welcome to WebLogic Server Administration Scripting Shell

Type help() for help on available commands

================== JMSSever ===================
Created a JMSServer !!
PersistentStore has been set for the JMSServer !!
Targeted the JMSServer !!

================== SystemModule ===================
Created a SystemModule !!
Targeted the SystemModule !!

================== ConnectionFactory ===================
Created a ConnectionFactory !!
Targeted the ConnectionFactory !!

================== Unit Of Order ===================
Changed Unit Of Order !!

================== SubDeployment & Queue ===================
Created a SubDeployment for Queue !!
Created a Queue !!
Targeted the Queue to the created subdeployment !!

Regards,

Ravish Mody


[Updated Version] Steps to Move Messages From One Queue To Another Queue Using WLST

Ravish Mody

Today one of our subscribers Pavan had  come back saying that the WLST script which was created by us previously How to Move Messages From One Queue To Another Queue Using WLST was only “working to move the messages from one queue to another queue which are on the same servers only“  by using comment , and as per his requirement they need to move the messages from Queue-1 to Queue-2 which are targeted to Server-1 and Server-2 respectively. Hence I have just made few modification in my previous script and thus this is the update version of it

I had to add two URL’s to get connected to the with the respective servers and also added two System Module this way you can move the messages from any Source Server to the Destination Server which can be in the same module or if the destination server is in different system module too this way its more flexible. All this can be done using the same script just give the domain and there servers details in the domain.properties files and you are good to go.

[Updated Version] Steps to Move Messages From One Queue To Another Queue Using WLST

Step1). Create a Directory somewhere in your file system like : “C:\WLST\Move_Messages”

Step2). Write a Properties filedomain.properties inside “C:\WLST\Move_Messages” like following:

######################
#    Destination
######################
new.server.url=t3://localhost:8003
new.system.module.name=SystemModule2
new.tragated.server.name=MS-2
new.jms.server.name=JMSServer2
new.queue.name=Q2

######################
#	Source
######################
old.server.url=t3://localhost:8002
old.system.module.name=SystemModule1
old.tragated.server.name=MS-1
old.jms.server.name=JMSServer1
old.queue.name=Q1

username=weblogic
password=weblogic

Step2). Now in the same directory write the following WLST Script “move_messages.py” like following:

#############################################################################
#
# @author Copyright (c) 2010 - 2011 by Middleware Magic, All Rights Reserved.
#
#############################################################################
from java.io import FileInputStream
import java.lang
import os
import string

propInputStream = FileInputStream("domain.properties")
configProps = Properties()
configProps.load(propInputStream)

newserverUrl = configProps.get("new.server.url")
newsystemModuleName = configProps.get("new.system.module.name")
newTragatedServerName = configProps.get("new.tragated.server.name")
newJmsServerName = configProps.get("new.jms.server.name")
newQueueName = configProps.get("new.queue.name")

oldserverUrl = configProps.get("old.server.url")
oldsystemModuleName = configProps.get("old.system.module.name")
oldTragatedServerName = configProps.get("old.tragated.server.name")
oldJmsServerName = configProps.get("old.jms.server.name")
oldQueueName = configProps.get("old.queue.name")

Username = configProps.get("username")
Password = configProps.get("password")

# Connecting to the Destination
connect(Username,Password,newserverUrl)
serverRuntime()

print 'Getting the traget...'
cd('/JMSRuntime/'+newTragatedServerName+'.jms/JMSServers/'+newJmsServerName+'/Destinations/'+newsystemModuleName +'!'+ newQueueName)
target = cmo.getDestinationInfo()
print 'Got the traget...'

disconnect()
print ''

# Connecting to the Source
connect(Username,Password,oldserverUrl)
serverRuntime()
cd('/JMSRuntime/'+oldTragatedServerName+'.jms/JMSServers/'+oldJmsServerName+'/Destinations/'+oldsystemModuleName +'!'+ oldQueueName)

print 'Moving the messages to the new traget...'
cmo.moveMessages('',target)
print 'Messages have been moved to the traget Successfully !!!'

print '===================================================================================='
print 'Messages from queue: "'+oldQueueName+'" have been moved to the new queue: "'+newQueueName+'" Successfully !!!'
print '===================================================================================='

Step3). Now Open a Command/Shell Prompt and then run the “setWLSEnv.sh” script to set the CLASSPATH and PATH environment variables. Run the “. ./setWLSEnv.sh” by adding two DOTs separated by a single space …..before the actual script like following : (use ‘cd’ command to move inside the <BEA_HOME>/wlserver_10.3/server/bin) then run the following command….
. ./setWLSEnv.sh

Note: Here The first DOT represents that set the Environment in the current Shell, AND the second ./ represents execute the script from the current directory.

Step4). Run the Above WLST Script like following:

java weblogic.WLST move_messages.py

Following would be the Output

java weblogic.WLST move_messages.py

Initializing WebLogic Scripting Tool (WLST) ...

Welcome to WebLogic Server Administration Scripting Shell

Type help() for help on available commands

Connecting to t3://localhost:8003 with userid weblogic ...
Successfully connected to managed Server 'MS-2' that belongs to domain 'Domain_8001'.

Warning: An insecure protocol was used to connect to the
server. To ensure on-the-wire security, the SSL port or
Admin port should be used instead.

Location changed to serverRuntime tree. This is a read-only tree with ServerRuntimeMBean as the root.
For more help, use help(serverRuntime)

Getting the traget...
Got the traget...
Disconnected from weblogic server: MS-2

Connecting to t3://localhost:8002 with userid weblogic ...
Successfully connected to managed Server 'MS-1' that belongs to domain 'Domain_8001'.

Warning: An insecure protocol was used to connect to the
server. To ensure on-the-wire security, the SSL port or
Admin port should be used instead.

Moving the messages to the new traget...
Messages have been moved to the traget Successfully !!!
====================================================================================
Messages from queue: "Q1" have been moved to the new queue: "Q2" Successfully !!!
====================================================================================

Note:

Pava you would have to change the line number – 35  & 45 as per your environment

Regards,
Ravish Mody


How to Move Messages From One Queue To Another Queue Using WLST

Ravish Mody

Two days back one of our subscribers Pavan had asked us by using comment , that is it possible to move the messages from one queue to another queue that to using WLST and the answer to that question is YES. It is possible to do the same using WLST and we have created the WLST script.

This is a very simple script which would just collect the target/destination queue where the messages has to be moved to (i.e. new.queue.name) and then would just go to the queue where the messages has to be moved from(i.e. old.queue.name). All this can be done using the same script just give the domain and there servers details in the domain.properties files and you are good to go.

Steps to Move Messages From One Queue To Another Queue Using WLST

Step1). Create a Directory somewhere in your file system like : “C:\WLST\Move_Messages”

Step2). Write a Properties filedomain.properties inside “C:\WLST\Move_Messages” like following:

server.url=t3://localhost:8001
username=weblogic
password=weblogic

system.module.name=MySystemModule

old.server.name=AdminServer
old.jms.server.name=Admin_JMSServer
old.queue.name=Admin_Queue

new.tragated.server.name=AdminServer
new.jms.server.name=MyJMSServer
new.queue.name=MyTestQueue

Step2). Now in the same directory write the following WLST Script “move_messages.py” like following:

#############################################################################
#
# @author Copyright (c) 2010 - 2011 by Middleware Magic, All Rights Reserved.
#
#############################################################################
from java.io import FileInputStream
import java.lang
import os
import string

propInputStream = FileInputStream("domain.properties")
configProps = Properties()
configProps.load(propInputStream)

serverUrl = configProps.get("server.url")
Username = configProps.get("username")
Password = configProps.get("password")

systemModuleName = configProps.get("system.module.name")

oldServerName = configProps.get("old.server.name")
oldJmsServerName = configProps.get("old.jms.server.name")
oldQueueName = configProps.get("old.queue.name")

newTragatedServerName = configProps.get("new.tragated.server.name")
newJmsServerName = configProps.get("new.jms.server.name")
newQueueName = configProps.get("new.queue.name")

connect(Username,Password,serverUrl)

serverRuntime()

print 'Getting the traget...'
cd('/JMSRuntime/'+newTragatedServerName+'.jms/JMSServers/'+newJmsServerName+'/Destinations/'+systemModuleName +'!'+ newQueueName)
target = cmo.getDestinationInfo()
print 'Got the traget...'

cd('/JMSRuntime/'+oldServerName+'.jms/JMSServers/'+oldJmsServerName+'/Destinations/'+systemModuleName +'!'+ oldQueueName)

print 'Moving the messages to the new traget...'
cmo.moveMessages('',target)
print 'Messages have been moved to the traget Successfully !!!'

print '======================================='
print 'Messages from queue: "'+oldQueueName+'" have been moved to the new queue: "'+newQueueName+'" Successfully !!!'
print '======================================='

Step3). Now Open a Command/Shell Prompt and then run the “setWLSEnv.sh” script to set the CLASSPATH and PATH environment variables. Run the “. ./setWLSEnv.sh” by adding two DOTs separated by a single space …..before the actual script like following : (use ‘cd’ command to move inside the <BEA_HOME>/wlserver_10.3/server/bin) then run the following command….
. ./setWLSEnv.sh

Note: Here The first DOT represents that set the Environment in the current Shell, AND the second ./ represents execute the script from the current directory.

Step4). Run the Above WLST Script like following:

java weblogic.WLST move_messages.py

Following would be the Output

java weblogic.WLST move_messages.py

Initializing WebLogic Scripting Tool (WLST) ...

Welcome to WebLogic Server Administration Scripting Shell

Type help() for help on available commands

Connecting to t3://localhost:8001 with userid weblogic ...
Successfully connected to Admin Server 'AdminServer' that belongs to domain 'Domain_8001'.

Warning: An insecure protocol was used to connect to the
server. To ensure on-the-wire security, the SSL port or
Admin port should be used instead.

Location changed to serverRuntime tree. This is a read-only tree with ServerRuntimeMBean as the root.
For more help, use help(serverRuntime)

Getting the traget...
Got the traget...
Moving the messages to the new traget...
Messages have been moved to the traget Successfully !!!
=======================================
Messages from queue: "Admin_Queue" have been moved to the new queue: "MyTestQueue" Successfully !!!
=======================================

Note:

Only for Pava you would have to do the following changes
- Instead for line number – 34
cd('/JMSRuntime/'+oldServerName+'.jms/JMSServers/'+oldJmsServerName+'/Destinations/'+systemModuleName +'!'+newJmsServerName+'@'+ newQueueName)
- Instead for line number - 38
cd('/JMSRuntime/'+oldServerName+'.jms/JMSServers/'+oldJmsServerName+'/Destinations/'+systemModuleName +'!'+oldJmsServerName+'@'+ oldQueueName)

Regards, Ravish Mody


How To Pause and Resume A Queue Using WLST

Ravish Mody

Today one of our subscribers Pavan had asked us by using comment , Here based on the query of Pavan we are writing the following article, which would Pause the Queue at Runtime even when the AdminServer/AdminConsole  is unavailable, thus we took out sometime and just now created a WLST script which would do the same job very easily.

In this script you can choose from which end do you want Queue to get paused, say if you want to pause the messages to be inserted then you can use pauseProduction , if you need that the consumption from the queue should stop then use pauseConsumtion and if you want that Queue should not insert or consume then use both. This way you can pause the queue as per your requirement, also with this you can resume the queue too by using resumeProduction, resumeConsumption or both of them. All this can be done using the same script just give the domain and there servers details in the domain.properties files and you are good to go.

Steps to Pause and Resume A Queue Using WLST

Step1). Create a Directory somewhere in your file system like : “C:\WLST\Pause_Queue”

Step2). Write a Properties filedomain.properties inside “C:\WLST\Pause_Queue” like following:

server.url=t3://10.10.10.10:7003
username=weblogic
password=weblogic
tragated.server.name=MS-1
jms.server.name=JMSServer-1
system.module.name=SystemModule-1
queue.name=Q-1

Step2). Now in the same directory write the following WLST Script “pause_queue.py” like following:

#############################################################################
#
# @author Copyright (c) 2010 - 2011 by Middleware Magic, All Rights Reserved.
#
#############################################################################
from java.io import FileInputStream
import java.lang
import os
import string

propInputStream = FileInputStream("domain.properties")
configProps = Properties()
configProps.load(propInputStream)

serverUrl = configProps.get("server.url")
Username = configProps.get("username")
Password = configProps.get("password")

tragatedServerName = configProps.get("tragated.server.name")
jmsServerName = configProps.get("jms.server.name")
systemModuleName = configProps.get("system.module.name")
queueName = configProps.get("queue.name")

connect(Username,Password,serverUrl)
serverRuntime()
cd('JMSRuntime/'+tragatedServerName+'.jms/JMSServers/'+jmsServerName+'/Destinations/'+systemModuleName +'!'+ queueName)

##################
# To PAUSE A Queue
##################

######## This would NOT let the messages Insert in the queue but it would let the messages get Consumed  ###########
cmo.pauseProduction()
print 'Queue: "', queueName ,'" has been PRODUCTION Paused Successfully'

######## This would let the messages Insert in the queue but it would NOT let the messages get Consumed  ###########
cmo.pauseConsumption()
print 'Queue: "', queueName ,'" has been CONSUMPTION Paused Successfully'

###################
# To RESUME A Queue
###################

#cmo.resumeProduction()
#print 'Queue: "', queueName ,'" has been PRODUCTION Resumed Successfully'

#cmo.resumeConsumption()
#print 'Queue: "', queueName ,'" has been CONSUMPTION Resumed Successfully'

Step3). Now Open a Command/Shell Prompt and then run the “setWLSEnv.sh” script to set the CLASSPATH and PATH environment variables. Run the “. ./setWLSEnv.sh” by adding two DOTs separated by a single space …..before the actual script like following : (use ‘cd’ command to move inside the <BEA_HOME>/wlserver_10.3/server/bin) then run the following command….
. ./setWLSEnv.sh

Note: Here The first DOT represents that set the Environment in the current Shell, AND the second ./ represents execute the script from the current directory.

Step4). Run the Above WLST Script like following:

java weblogic.WLST pause_queue.py

Following would be the Output

java weblogic.WLST pause_queue.py

Initializing WebLogic Scripting Tool (WLST) ...

Welcome to WebLogic Server Administration Scripting Shell

Type help() for help on available commands

Connecting to t3://10.10.10.10:7003 with userid weblogic ...
Successfully connected to managed Server 'MS-1' that belongs to domain 'Domain_7001'.

Warning: An insecure protocol was used to connect to the
server. To ensure on-the-wire security, the SSL port or
Admin port should be used instead.

Location changed to serverRuntime tree. This is a read-only tree with ServerRuntimeMBean as the root.
For more help, use help(serverRuntime)

Queue: " Q-1 " has been PRODUCTION Paused Successfully
Queue: " Q-1 " has been CONSUMPTION Paused Successfully

Regards,
Ravish Mody


How to Configure Weblogic Messaging Bridge with JBoss

Ravish Mody

One of our subscriber ravikumar was trying to configure Weblogic (10.3.0) messaging bridge with JBoss (3.24) and was getting below error

<Warning> <Connector> <BEA-190032> << eis/jms/WLSConnectionFactoryJNDINoTX > ResourceAllocationException thrown by resource adapter on call to ManagedConnectionFactory.createManagedConnection(): “javax.resource.ResourceException: Failed to start the connection “>

So I had taken some time out and configured the same and was able to send messages from weblogic server to JBoss queue successfully. Hence wanted to share the it with all other who are trying to configure weblogic messaging bridge with JBoss.

I would be using the below configuration and version of Weblogic server and JBoss server.

- Weblogic version: 10.3.0
- JBoss version: AS 5.1
- Bridge is on Weblogic
- Source Bridge Destination is Weblogic server queue
- Target Bridge Destination is JBoss queue

Now the main thing which you have to keep in mind before configuring weblogic messaging bridge with any 3rd party/any other JMS provider is that you have to get the right set of JAR files or else you would get lot of issue as the shown above and your configuration would not work properly, thus for this configuration you have to get the following JAR files from JBoss side and put it in the classpath of weblogic or put them in the Domain/lib folder.

Minimum JBoss JAR required:

From: /jboss-as/client
To: /WLS_Domain_Name/lib

  1. concurrent.jar
  2. javassist.jar
  3. jboss-aop-client.jar
  4. jboss-common-core.jar
  5. jboss-logging-spi.jar
  6. jboss-messaging-client.jar
  7. jboss-remoting.jar
  8. jnp-client.jar
  9. log4j.jar
  10. trove.jar

NOTE: These jars are from the JBoss version EAP 5.1.0 if you are using higher or lower version then you might have to put more or less jars. To get which jars you might need then the best option is to use the weblogic messaging bridge debug flags (DebugMessagingBridgeRuntime,  DebugMessagingBridgeRuntimeVerbose,  DebugMessagingBridgeStartup) which would show you the something like below error and then you have to use the SCANJAR at JBoss level to get the corresponding jars.

java.lang.ClassNotFoundException: org.jboss.logging.Logger

Now comes the configuration part from Weblogic side, to get a step by step configuration have a look at this post –> Weblogic Messaging Bridge on Weblogic Server. Here I would be only concentrating on the Source Bridge Destination and Target Bridge Destination which are shown below.

Source Bridge Destination

Name: Source_BridgeDestination
Adapter JNDI Name: eis.jms.WLSConnectionFactoryJNDINoTX
Classpath:
Connection URL: t3://<HOSTNAME or IP-ADDRESS>:<PORT>
Initial Context Factory: weblogic.jndi.WLInitialContextFactory
Connection Factory JNDI Name: <JNDI_OF_CONNECTION_FACTORY>
Destination JNDI Name: <JNDI_OF_QUEUE>
Destination Type: Queue
User Name: <USERNAME>
User Password: <PASSWORD>
Confirm User Password: <PASSWORD>

SourceBridgeDestination - Weblogic Server

SourceBridgeDestination - Weblogic Server

<jms-bridge-destination>
   <name>Source_BridgeDestination</name>
   <adapter-jndi-name>eis.jms.WLSConnectionFactoryJNDINoTX</adapter-jndi-name>
   <user-name>weblogic</user-name>
   <user-password-encrypted>{3DES}oFQLW2mB0rGKThL75ieYBQ==</user-password-encrypted>
   <classpath></classpath>
   <connection-factory-jndi-name>CF</connection-factory-jndi-name>
   <initial-context-factory>weblogic.jndi.WLInitialContextFactory</initial-context-factory>
   <connection-url>t3://localhost:7001</connection-url>
   <destination-jndi-name>Q</destination-jndi-name>
   <destination-type>Queue</destination-type>
</jms-bridge-destination>

Traget Bridge Destination

Name: Traget_Bridge_Destination
Adapter JNDI Name: eis.jms.WLSConnectionFactoryJNDINoTX
Classpath:
Connection URL: jnp://<HOSTNAME or IP-ADDRESS>:<PORT>
Initial Context Factory: org.jnp.interfaces.NamingContextFactory
Connection Factory JNDI Name: <JNDI_OF_CONNECTION_FACTORY>
Destination JNDI Name: <JNDI_OF_QUEUE>
Destination Type: Queue
User Name:
User Password:
Confirm User Password:

TragetBridgeDestination - JBoss Setting

TragetBridgeDestination - JBoss Setting

<jms-bridge-destination>
   <name>Traget_Bridge_Destination</name>
   <adapter-jndi-name>eis.jms.WLSConnectionFactoryJNDINoTX</adapter-jndi-name>
   <user-password-encrypted xsi:nil="true"></user-password-encrypted>
   <classpath></classpath>
   <connection-factory-jndi-name>XAConnectionFactory</connection-factory-jndi-name>
   <initial-context-factory>org.jnp.interfaces.NamingContextFactory</initial-context-factory>
   <connection-url>jnp://localhost:1099</connection-url>
   <destination-jndi-name>queue/TestQ</destination-jndi-name>
   <destination-type>Queue</destination-type>
</jms-bridge-destination>

Bridge

Name: Bridge
Source Bridge Destination: Source_BridgeDestination
Target Bridge Destination: Traget_Bridge_Destination
Selector:
Quality Of Service: Atmost-once
QOS Degradation Allowed: Un-checked
Maximum Idle Time: 60
Asynchronous Mode Enabled: Checked
Durability Enabled: Checked
Started: Checked
Preserve Msg Property: Un-checked

<messaging-bridge>
   <name>Bridge</name>
   <target>AdminServer</target>
   <source-destination>Source_BridgeDestination</source-destination>
   <target-destination>Traget_Bridge_Destination</target-destination>
   <selector></selector>
   <quality-of-service>Atmost-once</quality-of-service>
   <qos-degradation-allowed>false</qos-degradation-allowed>
   <durability-enabled>true</durability-enabled>
   <idle-time-maximum>60</idle-time-maximum>
   <async-enabled>true</async-enabled>
   <started>true</started>
   <preserve-msg-property>false</preserve-msg-property>
</messaging-bridge>

Testing:

Now lets test our configuration if its working fine by using the following snip-code.

In QueueSend.java copy the below command:

import java.io.*;
import java.util.Hashtable;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class QueueSend
{
public final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";

// ******* Give the CONNECTION FACTORY JNDI name which is QCF from WEBLOGIC side  ********
public final static String JMS_FACTORY="QCF";

// ******* Give the QUEUE JNDI name which is Q from WEBLOGIC side  ********
public final static String QUEUE="Q";

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 QueueSend WebLogicURL");
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
{
String line="Test Message Body with counter = ";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
boolean readFlag=true;
System.out.println("\n\tStart Sending Messages (Enter QUIT to Stop):\n");
while(readFlag)
{
System.out.print("&lt;Msg_Sender&gt; ");
String msg=br.readLine();
if(msg.equals("QUIT") || msg.equals("quit"))
{
qs.send(msg);
System.exit(0);
}
qs.send(msg);
System.out.println();
}
br.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);
return new InitialContext(env);
}
}

In QueueReceive.java copy the below command:

import java.util.Hashtable;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class QueueReceive implements MessageListener
{
// ******* Give the INITIAL CONTEXT FACTORY name which is of JBOSS side ********
public final static String JNDI_FACTORY="org.jnp.interfaces.NamingContextFactory";

// ******* Give the CONNECTION FACTORY JNDI name which is QCF from JBOSS side ********
public final static String JMS_FACTORY="/XAConnectionFactory";

// ******* Give the QUEUE JNDI name which is TestQ from JBOSS side  ********
public final static String QUEUE="/queue/TestQ";

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("\n\t<Msg_Receiver> "+ msgText );
if (msgText.equalsIgnoreCase("quit"))
{
synchronized(this)
{
quit = true;
this.notifyAll(); // Notify main thread to quit
}
}
}
catch (JMSException jmse)
{
jmse.printStackTrace();
}
}
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 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 from QueueSender.class).");
// 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
{
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
env.put(Context.PROVIDER_URL, url);
return new InitialContext(env);
}
}

- Now for QueueSend.java you have to use the t3://<HOST>:<PORT>  (i.e. as Source Bridge Destination queue is at Weblogic Server )

- And for QueueReceive.java you have to use the jnp://<HOST>:<PORT> (i.e. as Target Bridge Destination queue is at JBoss Server )

Output

Output


Sending Email Alert for JMS Using WLST

Ravish Mody

Many times we need some alert mails which can let us know the current status of the JMS resources. Jay had written a pretty good WLST script to monitor the JMS WebLogic JMS Monitoring Using WLS , Today we have created another WLST script which would send an alert mail when the Message Current Count has been exceeded.

The same WLST script can be used and modified as per your requirements and get an alert email when a Pending Message Count, Messages High Count etc gets exceeded. Following is the WLST script which would check if the count has  been exceeded the given count and would send a mail to the respective administrator and alert them about this issue.

Steps to Create an Eamil Alert for JMS

Step-1)  Create a WLST Script somewhere in your file system with some name like Alert_JMS.py”   inside “C:\WLST_JMS” contents will be something like following:

#############################################################################
#
# @author Copyright (c) 2010 - 2011 by Middleware Magic, All Rights Reserved.
#
#############################################################################

import os

def sendMail(count,dest):
   str3 = 'Queue with the NAME: '+  dest +' , has exceeded the Messages Current Count and now the CONUT is: ' + str(count)
   cmd = "echo " + str3 + " > rw_file"
   os.system(cmd)
   os.system('/bin/mailx -s  "ALERT: Messages Current Count Exceeded Limit !!! " admin@company.com < rw_file')
   print '*********  ALTERT MAIL HAS BEEN SENT  ***********'

connect('weblogic','weblogic','t3://localhost:8001')
servers = domainRuntimeService.getServerRuntimes();
if (len(servers) > 0):
	for server in servers:
		jmsRuntime = server.getJMSRuntime();
		jmsServers = jmsRuntime.getJMSServers();
		for jmsServer in jmsServers:
			destinations = jmsServer.getDestinations();
			for destination in destinations:
				if destination.getMessagesCurrentCount() > 3:
					count=destination.getMessagesCurrentCount()
					dest = destination.getName()
					print '.....Queue Exceeded the Message Current Count : ' , count
					print ''
					sendMail(count , dest)

Step-2) Open a command prompt and then run the “setWLSEnv.cmd” or “setWLSEnv.sh”  to set the CLASSPATH and PATH variables. Better you do echo %CLASSPATH%    or echo $CLASSPATH to see whether the CLASSPATH is set properly or not. If you see an Empty Classpath even after running the “setWLSEnv.sh” then please refer to the Note mentioned at Step3) in the Following post: http://middlewaremagic.com/weblogic/?page_id=1492

Step-3) Now run the WLST Script in the same command prompt like following:

java   weblogic.WLST  Alert_JMS.py

You will see the following kind of results in the command prompt

Initializing WebLogic Scripting Tool (WLST) ...

Welcome to WebLogic Server Administration Scripting Shell

Type help() for help on available commands

Connecting to t3://localhost:8001 with userid weblogic ...
Successfully connected to Admin Server 'AdminServer' that belongs to domain 'Domain_8001'.

Warning: An insecure protocol was used to connect to the
server. To ensure on-the-wire security, the SSL port or
Admin port should be used instead.

.....Queue Exceeded the Message Current Count :  5

*********  ALTERT MAIL HAS BEEN SENT  ***********

Email Alert

You can run this python script in your cron-job at the background and so the it keeps on running and send you the mails whenever the counts gets exceeded. Hope this would help all the administrators and make there job easier.

NOTE: This script is using mailx (i.e. but Windows box does not have mailx utility) so please do check if you mailx is configured properly or else script would run properly but the mail would not be sent.

Regards,

Ravish Mody


WebLogic JMS Monitoring Using WLST

Hi,

Jay SenSharma

Jay SenSharma

Many times we want to monitor the different modules available as part of our WebLogic Domain. WebLogic Scripting Tool (WLST) is one of the best utility which is based on Jython (The Java Version of Python Scripting) Option.

WLST not only allows to configure different resources in WebLogic Server/Domain as well as it allows a very easy way to monitor different resources available as part of WebLogic Server/Domain. We can monitor JMS/ DataSources/JDBC Parameters…etc using WLST.

Here we are going to see a very simple demonstration of using WLST to monitor Java Messaging Service (JMS) and the JMS Destination informations, which it holds, this part of monitoring includes both the Configuration Informations as well as the Runtime informations of the dataSource.

Step1). Create a WLST Script somewhere in your file system with some name like “Monitor_JMS.py”   inside “C:\WLST_Jdbc”  contents will be something like following:

#############################################################################
#
# @author Copyright (c) 2010 - 2011 by Middleware Magic, All Rights Reserved.
#
#############################################################################

connect('weblogic','weblogic','t3://localhost:7001')
servers = domainRuntimeService.getServerRuntimes();
if (len(servers) > 0):
	for server in servers:
		jmsRuntime = server.getJMSRuntime();
		jmsServers = jmsRuntime.getJMSServers();
		for jmsServer in jmsServers:
			destinations = jmsServer.getDestinations();
			for destination in destinations:
				print '  BytesCurrentCount           ' ,  destination.getBytesCurrentCount()
				print '  BytesHighCount              ' ,  destination.getBytesHighCount()
				print '  BytesPendingCount           ' ,  destination.getBytesPendingCount()
				print '  BytesReceivedCount          ' ,  destination.getBytesReceivedCount()
				print '  BytesThresholdTime          ' ,  destination.getBytesThresholdTime()
				print '  ConsumersCurrentCount       ' ,  destination.getConsumersCurrentCount()
				print '  ConsumersHighCount          ' ,  destination.getConsumersHighCount()
				print '  ConsumersTotalCount         ' ,  destination.getConsumersTotalCount()
				print '  ConsumptionPausedState      ' ,  destination.getConsumptionPausedState()
				print '  '
				print '  DestinationInfo             ' ,  destination.getDestinationInfo()
				print '  '
				print '  DestinationType             ' ,  destination.getDestinationType()
				print '  InsertionPaused             ' ,  destination.isInsertionPaused()
				print '  InsertionPausedState        ' ,  destination.getInsertionPausedState()
				print '  MessagesCurrentCount        ' ,  destination.getMessagesCurrentCount()
				print '  MessagesDeletedCurrentCount ' ,  destination.getMessagesDeletedCurrentCount()
				print '  MessagesHighCount           ' ,  destination.getMessagesHighCount()
				print '  MessagesMovedCurrentCount   ' ,  destination.getMessagesMovedCurrentCount()
				print '  MessagesPendingCount        ' ,  destination.getMessagesPendingCount()
				print '  MessagesReceivedCount       ' ,  destination.getMessagesReceivedCount()
				print '  MessagesThresholdTime       ' ,  destination.getMessagesThresholdTime()
				print '  Parent                      ' ,  destination.getParent()
				print '  Paused                      ' ,  destination.isPaused()
				print '  ProductionPaused            ' ,  destination.isProductionPaused()
				print '  ProductionPausedState       ' ,  destination.getProductionPausedState()
				print '  State                       ' ,  destination.getState()
				print '  Type                        ' ,  destination.getType()

Step2). Start your WebLogic Server (Make sure that you have configured some JMS Server and JMS Modules in the Server to monitor). Or plesase refer to the following page to configure some JMS Resources like Queues/Topics:
http://middlewaremagic.com/weblogic/?page_id=1976

Step3). Open a command prompt and then run the “setWLSEnv.cmd” or “setWLSEnv.sh”  to set the CLASSPATH and PATH variables. Better you do echo %CLASSPATH%    or echo $CLASSPATH to see whether the CLASSPATH is set properly or not. If you see an Empty Classpath even after running the “setWLSEnv.sh” then please refer to the Note mentioned at Step3) in the Following post:   http://middlewaremagic.com/weblogic/?page_id=1492

Step4). Now run the WLST Script in the same command prompt like following:

java       weblogic.WLST        C:\WLST_Jdbc\Monitor_JMS.py
You will see the following kind of results in the command prompt


  BytesCurrentCount            0
  BytesHighCount               0
  BytesPendingCount            0
  BytesReceivedCount           0
  BytesThresholdTime           0
  ConsumersCurrentCount        0
  ConsumersHighCount           0
  ConsumersTotalCount          0
  ConsumptionPausedState       Consumption-Enabled

  DestinationInfo              javax.management.openmbean.CompositeDataSupport(compositeType=javax.management.openmbean.CompositeType(name=DestinationInfo,items=((itemName=ApplicationName,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName=ModuleName,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName=Name,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName=Queue,itemType=javax.management.openmbean.SimpleType(name=java.lang.Boolean)),(itemName=SerializedDestination,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName=ServerName,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName=Topic,itemType=javax.management.openmbean.SimpleType(name=java.lang.Boolean)),(itemName=VersionNumber,itemType=javax.management.openmbean.SimpleType(name=java.lang.Integer)))),contents={ApplicationName=TestSystemModule, ModuleName=null, Name=TestSystemModule!Test_Q, Queue=true, SerializedDestination=rO0ABXNyACN3ZWJsb2dpYy5qbXMuY29tbW9uLkRlc3RpbmF0aW9uSW1wbFSmyJ1qZfv8DAAAeHB3gbRBABdUZXN0U3lzdGVtTW9kdWxlIVRlc3RfUQANVGVzdEpNU1NlcnZlcgAQVGVzdFN5c3RlbU1vZHVsZQEAA0FsbAICD/TBLPfeTooAAAAKAQALQWRtaW5TZXJ2ZXIALYQaAg/0wSz33k6KAAAADAEAC0FkbWluU2VydmVyAC2EGng=, ServerName=TestJMSServer, Topic=false, VersionNumber=1})

  DestinationType              Queue
  InsertionPaused              0
  InsertionPausedState         Insertion-Enabled
  MessagesCurrentCount         0
  MessagesDeletedCurrentCount  0
  MessagesHighCount            0
  MessagesMovedCurrentCount    0
  MessagesPendingCount         0
  MessagesReceivedCount        0
  MessagesThresholdTime        0
  Name                         TestSystemModule!Test_Q
  Parent                       [MBeanServerInvocationHandler]com.bea:ServerRuntime=AdminServer,Name=TestJMSServer,Location=AdminServer,Type=JMSServerRuntime
  Paused                       0
  ProductionPaused             0
  ProductionPausedState        Production-Enabled
  State                        advertised_in_cluster_jndi
  Type                         JMSDestinationRuntime
JMS_Monitoring_Using_WLST

JMS_Monitoring_Using_WLST

.

.

Thanks

Jay SenSharma


JMS Demo using Weblogic Store-and-Forward (SAF)

Ravish Mody

To configure a Messaging Bridge you can follow the steps provided in the post Steps to Configure Store-and-Forward (SAF) 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, asmany times their an issue with the Producer or a Consumers.

.

.

Steps of test the Store-and-Forward (SAF)

  1. Create a Directory somewhere in your file system like: “D:\Oracle\JMS\Queue” to write the QueueSend.java and QueueReceive.java programs.
  2. In QueueSend.java copy the below commandNote: Here we are giving the Queue JNDI as “SAF_Local” because “SAF_” was the prefix for SAF Imported Destination and “Local” was the local JNDI name for the SAF Imported Destination Queue, hence in the below JDNI tree shows the “SAF_Local”
    JNDI_Tree

    JNDI Tree of Domain-1

    
    import java.io.*;
    import java.util.Hashtable;
    import javax.jms.JMSException;
    import javax.jms.Queue;
    import javax.jms.QueueConnection;
    import javax.jms.QueueConnectionFactory;
    import javax.jms.QueueSender;
    import javax.jms.QueueSession;
    import javax.jms.Session;
    import javax.jms.TextMessage;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    
    public class QueueSend
    {
    public final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";
    
    // ******* Give the CONNECTION FACTORY JNDI name which is QCF ********
    public final static String JMS_FACTORY="QCF";
    
    // ******* Give the UNIFORM DISTRIBUTED QUEUE JNDI name which is SAF_Local ********
    public final static String QUEUE="SAF_Local";
    
    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 QueueSend WebLogicURL");
    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
    {
    String line="Test Message Body with counter = ";
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    boolean readFlag=true;
    System.out.println("\n\tStart Sending Messages (Enter QUIT to Stop):\n");
    while(readFlag)
    {
    System.out.print("&lt;Msg_Sender&gt; ");
    String msg=br.readLine();
    if(msg.equals("QUIT") || msg.equals("quit"))
    {
    qs.send(msg);
    System.exit(0);
    }
    qs.send(msg);
    System.out.println();
    }
    br.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);
    return new InitialContext(env);
    }
    }
    
  3. In QueueReceive.java copy the below command
    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";
    
    // ******* Give the CONNECTION FACTORY JNDI name which is QCF ********
    public final static String JMS_FACTORY="QCF";
    
    // ******* Give the UNIFORM DISTRIBUTED QUEUE JNDI name which is TestQ   ********
    public final static String QUEUE="TestQ";
    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("\n\t&lt;Msg_Receiver&gt; "+ msgText );
    if (msgText.equalsIgnoreCase("quit"))
    {
    synchronized(this)
    {
    quit = true;
    this.notifyAll(); // Notify main thread to quit
    }
    }
    }
    catch (JMSException jmse)
    {
    jmse.printStackTrace();
    }
    }
    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 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 from QueueSender.class).");
    // 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
    {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
    env.put(Context.PROVIDER_URL, url);
    return new InitialContext(env);
    }
    }
    
  4. Now open 2 – command promt Windows and run “setWLSEn.cmd” in all the three Command Windows to set the Environment (PATH & CLASSPATH).
  5. Then compile the QueueSend.java and QueueReceive.java programs.
  6. Now run the code with the following command
  7. Prompt-1

    java QueueSend t3://localhost:7001
     

    Prompt-2

    java QueueReceive t3://localhost:8001
     

    Note:

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

  8. Once this is been done try to send few messages in the Prompt one  which is sending to the port 7001 which the Sender in Domain-1 , if the configuration is fine then you will notice that the message would be received on Prompt-2 which is listening on port 8001 which the Receiver in Domain-2 as shown in the below snap-shot.
  9. SAF_Demo-1

    This way we can see that using weblogic Store-and-Forward (SAF) is working fine  and can transfer messages from one domain to the second domain easily.

    8.   However that was just to check if our configuration was correct or not, as its working fine now try to SHUTDOWN Domain-2 which is running on 8001 port and now send few more messages from Prompt-1.

    9.   Now again START the server for the Domain-2which is running on 8001 port and go to the following path and check if you see the messages which were sent during the Domain-2 was down, has been received as shown in the below snap-shot

    Console Path for Domain-2 :

    JMS Modules -> MySystemModule  -> MyTestQueue  -> Monitoring (tab)

    SAF_Demo-2

    Monitoring Tab of Domain-2

    Thus now we have tested that even when the Receiver was down still weblogic Store-and-Forward (SAF) was able to send the messages once the receiver came up.

    Thanks,

    Ravish Mody


Steps to Configure Store-and-Forward (SAF) on Weblogic Server

Ravish Mody

Yesterday I was chatting with one of my ex-colleague Shruti and she requested me to write a post on Store-and-Forward (SAF) as the she was having some issue in configuring it and as usual the edocs are pretty confusing to do anything. So I took out sometime and wrote this post  which would help others too. For demo check out this post JMS Demo using Weblogic Store-and-Forward (SAF)

First of all lets understand what is Store-and-Forward (SAF) and then will look into how it works, how to configure it with its advantages.

What is Store-and-Forward (SAF)

Store-and-Forward (SAF) is a service which enables weblogic server to deliver messages reliably that is weblogic server make sure that the messages are been delivered between applications that are distributed across weblogic server instances.

How does Store-and-Forward (SAF) works

As the name suggests the messages gets stored at the Sender side in the persistence store and then are forwarded to the Receiver side using the SAF Agent.

Advantages of Store-and-Forward (SAF)

The main reason or the biggest advantage of Store-and-Forward (SAF) for which weblogic server had implemented was that they wanted the messages to be delivered to the receiver even when the receiver was down when the messages where sent.

Steps to Configure Store-and-Forward (SAF)

1.  You have to follow steps from Step-1 to Step-5 from the post Basic JMS Demo using WebLogic Queue for Domain-2 running on port 8001 and again same steps BUT this time only follow steps from Step-1 to Step-4 on Domain-1 running on port 7001.

2.  Now after doing the above step creating a SAF Agent

SAF-1

Creating SAF Agent

SAF-2

Targeting SAF Agent

3.  Create Sub Deployment for SAF in the same Module

SAF_Sub-1

Creating SAF Sub Deployment

SAF_Sub-2

Targeting SAF Sub Deployment

4. Creating Remote SAF Context in the same Module

SAF_RSC-1

Creating Remote SAF Context

SAF_RSC-2

Configuring Remote SAF Context

5.  Creating SAF Imported Destination in the same Module

SAF_ID-1

Creating SAF Imported Destination

SAF_ID-2

Configuring SAF Imported Destination

SAF_ID-3

Targeting SAF Imported Destination

SAF_ID-4

Advanced Targeting SAF Imported Destination to the SAF Sub-Deployment


6.  Creating SAF Imported Destination Queue

SAF_ID-5

Selecting Created SAF Imported Destination

SAF_ID-6

Creating SAF Imported Destination Queue

SAF_ID-7

Configuring "Remote" JNDI SAF Imported Destination Queue

SAF_ID-8

Selecting Created SAF Imported Destination Queue

SAF_ID-9

Configuring "Local" JNDI for SAF Imported Destination Queue

Following are the XML configuration which would look like from the SAF point of view

In config.xml file

<sub-deployment>
<name>Sub_SAF</name>
<target>MySAFAgent</target>
</sub-deployment>
<descriptor-file-name>jms/mysystemmodule-jms.xml</descriptor-file-name>
</jms-system-resource>
<admin-server-name>AdminServer</admin-server-name>
<saf-agent>
<name>MySAFAgent</name>
<target>AdminServer</target>
<store>FileStore</store>
<service-type>Both</service-type>
</saf-agent>

In mysystemmodule-jms.xml file


<saf-imported-destinations name="SAFImportedDestinations">
<sub-deployment-name>Sub_SAF</sub-deployment-name>
<saf-queue name="MySAFQueue">
<remote-jndi-name>TestQ</remote-jndi-name>
<local-jndi-name>Local</local-jndi-name>
<non-persistent-qos>At-Least-Once</non-persistent-qos>
<time-to-live-default>0</time-to-live-default>
<use-saf-time-to-live-default>false</use-saf-time-to-live-default>
<unit-of-order-routing>Hash</unit-of-order-routing>
</saf-queue>
<jndi-prefix>SAF_</jndi-prefix>
<saf-remote-context>MyRemoteSAFContext</saf-remote-context>
<saf-error-handling xsi:nil="true"></saf-error-handling>
<time-to-live-default>0</time-to-live-default>
<use-saf-time-to-live-default>false</use-saf-time-to-live-default>
</saf-imported-destinations>
<saf-remote-context name="MyRemoteSAFContext">
<saf-login-context>
<loginURL>t3://localhost:8001</loginURL>
<username>weblogic</username>
<password-encrypted>{3DES}zMJAPP2UbO1mNu9+Zx7/DA==</password-encrypted>
</saf-login-context>
</saf-remote-context>

Yup its little bit confusing but that’s it, your configuration for Store-and-Forward (SAF) has been finished. Hope this would help.

Regards,

Ravish Mody


JMS Demo using WebLogic Messaging Bridge

Ravish Mody

To configure a Messaging Bridge you can follow the steps provided in the post Steps to Configure Messaging Bridge 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, asmany times their an issue with the Producer or a Consumers.

.

.

Steps of test the Messaging Bridge

  1. Create a Directory somewhere in your file system like: “D:\Oracle\JMS\Queue” to write the QueueSend.java and QueueReceive.java programs.
  2. In QueueSend.java copy the below command
    
    import java.io.*;
    import java.util.Hashtable;
    import javax.jms.JMSException;
    import javax.jms.Queue;
    import javax.jms.QueueConnection;
    import javax.jms.QueueConnectionFactory;
    import javax.jms.QueueSender;
    import javax.jms.QueueSession;
    import javax.jms.Session;
    import javax.jms.TextMessage;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    
    public class QueueSend
    {
    public final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";
    
    // ******* Give the CONNECTION FACTORY JNDI name which is QCF ********
    public final static String JMS_FACTORY="QCF";
    
    // ******* Give the UNIFORM DISTRIBUTED QUEUE JNDI name which is TestQ   ********
    public final static String QUEUE="TestQ";
    
    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 QueueSend WebLogicURL");
    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
    {
    String line="Test Message Body with counter = ";
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    boolean readFlag=true;
    System.out.println("\n\tStart Sending Messages (Enter QUIT to Stop):\n");
    while(readFlag)
    {
    System.out.print("&lt;Msg_Sender&gt; ");
    String msg=br.readLine();
    if(msg.equals("QUIT") || msg.equals("quit"))
    {
    qs.send(msg);
    System.exit(0);
    }
    qs.send(msg);
    System.out.println();
    }
    br.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);
    return new InitialContext(env);
    }
    }
    
  3. In QueueReceive.java copy the below command
    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";
    
    // ******* Give the CONNECTION FACTORY JNDI name which is QCF ********
    public final static String JMS_FACTORY="QCF";
    
    // ******* Give the UNIFORM DISTRIBUTED QUEUE JNDI name which is TestQ   ********
    public final static String QUEUE="TestQ";
    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("\n\t&lt;Msg_Receiver&gt; "+ msgText );
    if (msgText.equalsIgnoreCase("quit"))
    {
    synchronized(this)
    {
    quit = true;
    this.notifyAll(); // Notify main thread to quit
    }
    }
    }
    catch (JMSException jmse)
    {
    jmse.printStackTrace();
    }
    }
    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 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 from QueueSender.class).");
    // 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
    {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
    env.put(Context.PROVIDER_URL, url);
    return new InitialContext(env);
    }
    }
    
  4. Now open 2 – command promt Windows and run “setWLSEn.cmd” in all the three Command Windows to set the Environment (PATH & CLASSPATH).
  5. Then compile the QueueSend.java and QueueReceive.java programs.
  6. Now run the code with the following command
  7. Prompt-1

    java QueueSend t3://localhost:8001
     

    Prompt-2

    java QueueReceive t3://localhost:7001
     

    Note:

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

  8. Once this is been done try to send few messages in the Prompt one  which is sending to the port 8001 which the Source Detonation in Domain-1 , however you will notice that the message would be received on Prompt-2 which is listening on port 7001 which the Target Detonation in Domain-2 as shown in the below snap-shot.
  9. JMS Bridge Demo

    JMS Bridge Demo

    .
    Thus this way we can see that using weblogic messaging bridge we can transfer messages from one domain to the second domain easily.

    .

    Thanks,

    Ravish Mody


  • Testimonials

  • RSS Middleware Magic – JBoss

  • Receive FREE Updates


    FREE Email updates of our new posts Enter your email address:



  • Magic Archives

  • Sitemeter Status

  • ClusterMap 7-Nov-2011 till Date

  • ClusterMap 6-Nov-2010 till 7-Nov-2011

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