Featured Posts
  • How To Pause and Resume A Queue Using WLST

    How To Pause and Resume A Queue Using WLST

    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 ...

    Read More

  • Changing WebLogic’s WebServer Log Settings using WLST

    Changing WebLogic's WebServer Log Settings using WLST

    Hi, Based on the  Comment/Query of one of our Magic Subscriber "Kimjim" (http://middlewaremagic.com/weblogic/?p=1473#comment-4594) , We are going to see how we can edit the WebServer Logging like displaying the Client IP Adddress in the access Log of a Server by adding (Extended Loging Formats  c-ip) and changing the various attribute of ...

    Read More

  • Target and Untargeting of Multiple DataSources using WLST

    Target and Untargeting of Multiple DataSources using WLST

    Yesterday one of our subscribers Ravi Shankar Kumar had asked us using comment how to target and untarget multiple datasources in the same domian using a single generic WLST script, as they have total 5 clusters and want to target each cluster to different datasources and as per his requirement we created this simple ...

    Read More

  • WebLogic Server is in ADMIN State ?

    WebLogic Server is in ADMIN State ?

    Hi, In Response to Mr. Chris Giddings.. Comment/Query on ADMIN State. Here we are going to see a Scenario which is very common but troublesome. Many times we observe that while trying to restart the Managed Servers the Servers move to ADMIN State rather than moving to the RUNNING State.  This usually ...

    Read More

1 2 3 4

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


Target and Untargeting of Multiple DataSources using WLST

Ravish Mody

Yesterday one of our subscribers Ravi Shankar Kumar had asked us using comment how to target and untarget multiple datasources in the same domian using a single generic WLST script, as they have total 5 clusters and want to target each cluster to different datasources and as per his requirement we created this simple WLST script which can do the same things in this single script.

As usual we have used a properties file which has all the required details in it like the datasources names, targets name and number of datasoures which has to be updated. This way you would not have to modify anything in your actual WLST script.

Target and Untargeting of Multiple DataSources using WLST

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

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

userName=weblogic
password=weblogic
admin.Url=t3://localhost:7001

####### DataSources names ######
ds.Name.1 = MyJDBC_Data_Source-1
ds.Name.2 = MyJDBC_Data_Source-2

##### DataSources Target names #####
target.1= Cluster
target.2= Cluster-0

##### Total Numbers of DataSources has to be modified  #####
total.Ds.Count=2

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

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

from java.io import FileInputStream

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

userName = configProps.get("userName")
password = configProps.get("password")
adminUrl = configProps.get("admin.Url")
totalDsCount = configProps.get("total.Ds.Count")

connect(userName,password,adminUrl)
edit()
startEdit()
print ''
print '======================================================================'
print 'UnTargeting and Targeting of the DataSources has started.....'
print '======================================================================'

dsCount=1
while (dsCount <= int(totalDsCount)) :
	dsName = configProps.get("ds.Name."+ str(dsCount))
	tgName = configProps.get("target."+ str(dsCount))
	cd ('/JDBCSystemResources/'+ dsName)
	set('Targets',jarray.array([], ObjectName))
	print ''
	print 'DataSource = ', dsName ,', has been UnTargeted'
	set('Targets',jarray.array([ObjectName('com.bea:Name='+tgName+',Type=Cluster')], ObjectName))
	print 'Congrats!!! DataSource = ', dsName ,', now has been Targeted to "',tgName,'"'
	print ''
	dsCount = dsCount + 1

print '======================================================================'
print 'UnTrageting and Targeting of the DataSources has been completed !!!'
print '======================================================================'
print ''

activate()
exit()

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 Tragate_UnTragate_DS.py

Following would be the Output


java weblogic.WLST Tragate_UnTragate_DS.py

Initializing WebLogic Scripting Tool (WLST) ...

Welcome to WebLogic Server Administration Scripting Shell

Type help() for help on available commands

Connecting to t3://localhost:7001 with userid weblogic ...
Successfully connected to Admin Server 'AdminServer' 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 edit tree. This is a writable tree with
DomainMBean as the root. To make changes you will need to start
an edit session via startEdit().

For more help, use help(edit)

Starting an edit session ...
Started edit session, please be sure to save and activate your
changes once you are done.

======================================================================
UnTargeting and Targeting of the DataSources has started .....
======================================================================

DataSource =  MyJDBC_Data_Source-1 , has been UnTargeted
Congrats!!! DataSource =  MyJDBC_Data_Source-1 , now has been Targeted to " Cluster "

DataSource =  MyJDBC_Data_Source-2 , has been UnTargeted
Congrats!!! DataSource =  MyJDBC_Data_Source-2 , now has been Targeted to " Cluster-0 "

======================================================================
UnTargeting and Targeting of the DataSources has been completed !!!
======================================================================

Activating all your changes, this may take a while ...
The edit lock associated with this edit session is released
once the activation is completed.
Activation completed

Exiting WebLogic Scripting Tool.

Note:

Make sure that the Database is running while you are running the DataSource.

Regards,

Ravish Mody


Changing WebLogic’s WebServer Log Settings using WLST

Hi,

Jay SenSharma

Jay SenSharma

Based on the  Comment/Query of one of our Magic Subscriber “Kimjim” (http://middlewaremagic.com/weblogic/?p=1473#comment-4594) , We are going to see how we can edit the WebServer Logging like displaying the Client IP Adddress in the access Log of a Server by adding (Extended Loging Formats  c-ip) and changing the various attribute of Logging in one go.

This script also demonstrates how we should use the edit() , activate() and startEdit()  kind of functions inside the WLST Script if we are migrating our WLST Scripts from WebLogic 8.1  because in WebLogic 8.1 the change control (Lock & Edit)  feature was  not available in the Admin Console.

Step1). Write the following WLST Script somewhere in your file system:
“changeLogFormats.py”

connect('weblogic','weblogic1','t3://localhost:7001')
domainConfig()
managedServers=cmo.getServers()
print 'Found ' + `len(managedServers)` + ' managed servers'

for managedServer in managedServers:
	try:
		edit()
		startEdit()
		serverName = managedServer.getName()
		print '\t\t==================='+serverName+'===================='
		cd('/Servers/'+serverName+'/WebServer/'+serverName+'/WebServerLog/'+serverName)
		cmo.setLogTimeInGMT(false)
		cmo.setLogFileFormat('common')
		cmo.setELFFields('c-ip date time time-taken bytes cs-method cs-uri sc-status')
		activate()
		print ' '
		print ' '
	except java.lang.Exception, ex:
		print 'Exception on Changing the Log Attributes: ' + ex.toString()

Step2). Now we need to set  the CLASSPATH and PATH environment variables using setWLSEnv.sh or setDomainEnv.sh script.

Step3). Run the WLST Script java WebLogic.WLST changeLogFormats.py

java weblogic.WLST  changeLogFormats.py

Initializing WebLogic Scripting Tool (WLST) ...

Welcome to WebLogic Server Administration Scripting Shell

Type help() for help on available commands

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

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 DomainMBean as the root.
For more help, use help(domainConfig)

Found 2 managed servers

Location changed to edit tree. This is a writable tree with
DomainMBean as the root. To make changes you will need to start
an edit session via startEdit().

For more help, use help(edit)

Starting an edit session ...
Started edit session, please be sure to save and activate your
changes once you are done.
		===================AdminServer====================
Activating all your changes, this may take a while ...
The edit lock associated with this edit session is released
once the activation is completed.
Activation completed

Already in Edit Tree

Starting an edit session ...
Started edit session, please be sure to save and activate your
changes once you are done.
		===================MS1====================
Activating all your changes, this may take a while ...
The edit lock associated with this edit session is released
once the activation is completed.
Activation completed

.
.
Thanks

Jay SenSharma


How to run WLST script using Cronjob ?

Ravish Mody

One of our subscriber middleware_guy was having issues to run a WLST script using Cronjob and wanted us to help him out with it to solve his problem by providing him a detailed steps or the script which would do the same for him, hence we thought that it would be better if we create an article on this issue so that everyone can take the advantage and can run any WLST script using cronjob.

The requirement was to run the WLST script every hour so that they can get some information from the running Weblogic server, we had suggested to use the cronjob to this part of the job, as running WLST script continually in the background takes lot of usage and we have been reported that this causes high CPU issue as well, thus using cronjob would be a best choice in this situation. For the new guys the question would come….

What is a Cronjob ?

Cronjob is a a job scheduler which is used for time based scheduler which comes with all Unix based operating systems and one of the best tool for the all administrators. You can use cronjob to run any commands or scripts periodically in a certain time based or dates wise manner which would automate the job of an administrators like taking backup of the logs every week, clean up the logs which are older then 30 days etc.

To use cronjob there are predefined scheduling definitions which has to be used as show in the diagram, which would give you a better picture what all things are needed to activate a cronjob.

* * * * * [command/script to get executed]

┬    ┬    ┬    ┬    ┬
│    │    │    │    │
│    │    │    │    │
│    │    │    │    └───── day of week [0 to 7] (where Sunday=0 or 7)
│    │    │    └────────── month [1 to 12]
│    │    └─────────────── day of month [1 to 31]
│    └──────────────────── hour [0 to 23]
└───────────────────────── min [0 to 59]

Let’s take an example, as per the requirement middleware_guy wanted that the WLST script should be called every hour, so to get that job done following would be the command which has to go in the “crontab” file.

0 * * * * [script]

This would make sure that the given script would run every hour, however to run a WLST script we would have to make sure that the weblogic environment is set properly so that it can call the WLST script or else it would get an exception. So the below shell script would do that job to sent the weblogic environment and then call the WLST script as well. Create a file called “WLST.sh” and put the below code in it

#!/bin/bash

# ************* Setting the Environment ***********************
DOMAIN_HOME="/home/testusr/WLS103/user_projects/domains/Domain_7001"
. ${DOMAIN_HOME}/bin/setDomainEnv.sh $*

echo "Environment has been set....."

# ************* Changing the directory where all the related files are needed ***********************
cd home/testusr/WLS/App_State

echo "Calling the PYTHON script....."

# ************* Calling the WLST script  *****************
java weblogic.WLST application_status.py

NOTE:

Make sure that all the files to run the python script and the WLST.sh file should be in the same directory folder so that you would not get filenotfound error.

Hence below line would be given in the crontab file to run the WLST script given in the WLST.sh file

0 * * * * /home/testusr/WLS/App_State/WLST.sh >> home/testusr/WLS/App_State/out.log

Same way if you want to run your script in every 15 minutes (like 1:15, 1:30,1:45,2:00,2:15…) then do the following:

00,15,30,45  *   *  *  * /home/testusr/WLS/App_State/WLST.sh >> home/testusr/WLS/App_State/out.log

Regards,
Ravish Mody


Sending Email Alert for Application Current State

Ravish Mody

Yesterday evening one of your subscriber middleware_guy using comment asked us how can he can get a regular update say every 1 hour get an email showing the current state of an applications which are not in prepared or failed states, hence we updated our previous script which was written by Jay called Getting Application States using WLST to get the above requirement.

We have just added the two logic in this script which are the email and condition loop which would make sure that only shoot an email when the applications are not in Active states, however you can still modify this to fulfill your requirement and regarding the check every 1 hour I would suggest to use the Cron-Job utility to call this script.

Update:

I have updated the script to show on which server is the applications are be targeted, as this script automatically gets all the application state which are been deployed on all the servers in that domain, without giving any details of the managed servers in domain.

Steps to Create an Email Alert For Application Current State

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

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

admin.url=t3://localhost:7001
username=weblogic
password=weblogic

Step-3) Create a WLST Script somewhere in your file system with some name like “application_status.py” inside “C:\WLST” contents will be something 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("domains.properties")
configProps = Properties()
configProps.load(propInputStream)

ServerUrl = configProps.get("admin.url")
UserName = configProps.get("username")
Password = configProps.get("password")

#############  This method would send the Alert Email  #################
def sendMailString():
	os.system('/bin/mailx -s  "ALERT: Applications are currently NOT in ACTIVE state !!! " ABCD@comapny.com < currentAppState_file')
	print '*********  ALERT MAIL HAS BEEN SENT  ***********'

redirect('wlst.log','false')
connect(UserName,Password,ServerUrl)
cd ('AppDeployments')
myapps=cmo.getAppDeployments()
print '=============================================='
print 'Following Applications are not in STATE_ACTIVE'
print '=============================================='
for appName in myapps:
	domainConfig()
	cd ('/AppDeployments/'+appName.getName()+'/Targets')
	mytargets = ls(returnMap='true')
	domainRuntime()
	cd('AppRuntimeStateRuntime/AppRuntimeStateRuntime')
	for targetinst in mytargets:
		currentAppState=cmo.getCurrentState(appName.getName(),targetinst)
		if currentAppState != "STATE_ACTIVE":
			writeInFile ='Applicaiton = "'+ appName.getName() +'"   //    Targeted Server = "'+str(mytargets)+'"   //     Current STATE = "'+ currentAppState +'"'
			print '', writeInFile
			cmd = "echo " + writeInFile + " >> currentAppState_file"
			os.system(cmd)
print '=============================================='
print''
sendMailString()
cmd = "rm -f wlst.log currentAppState_file"
os.system(cmd)

Step-4) 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-5) Now run the WLST Script in the same command prompt using the following command:

java   weblogic.WLST  application_status.py

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

$java weblogic.WLST application_status.py

Initializing WebLogic Scripting Tool (WLST) ...

Welcome to WebLogic Server Administration Scripting Shell

Type help() for help on available commands

==============================================
Following Applications are not in STATE_ACTIVE
==============================================
 Applicaiton = "Mysite"   //    Targeted Server = "[AdminServer]"   //     Current STATE = "STATE_PREPARED"
 Applicaiton = "SessionTest.war#VesionB"   //    Targeted Server = "[Cluster]"   //     Current STATE = "STATE_NEW"
 Applicaiton = "_appsdir_ClassLoaderTestEAR_ear"   //    Targeted Server = "[AdminServer]"   //     Current STATE = "STATE_PREPARED"
 Applicaiton = "MDB"   //    Targeted Server = "[MS-2]"   //     Current STATE = "STATE_NEW"
 Applicaiton = "FirstEARApplication"   //    Targeted Server = "[MS-1]"   //     Current STATE = "STATE_NEW"
 Applicaiton = "SecondEARApplication"   //    Targeted Server = "[MS-1]"   //     Current STATE = "STATE_NEW"
==============================================

*********  ALERT MAIL HAS BEEN SENT  ***********

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


Regards,

Ravish Mody


[UPDATED VERSION] Deploying Applications Using JMX On managed Servers

Hi,

Jay SenSharma

Jay SenSharma

It is not a good approach to deploy an application using JMX as already there are various useful tools available to do the same like ANT, WLST or weblogic.Deployer. Still due to certain specific requirements we may want to deploy it through a Plain Java code. So we developed an article sometimes back for that http://middlewaremagic.com/weblogic/?p=483 . But as the previous code needed some enhancement to deploy the applications on the selective targets.

So based on the comment of Mr. Ram Bonala http://middlewaremagic.com/weblogic/?p=483#comment-4286 here we are going to see how we can use JMX code to deploy an application on a particular Managed Server or to a Chosen target.

NOTE:

We need to make sure that the  ”Lock & Edit” button is present in the AdminConsole. By default when we run our Server on Production mode then we can see the Change Center butttone (Lock & Edit).   If you are running in Development Mode then please make sure that the “Lock & Edit” button is present in the admin console. If it is not present then Please login to admin-console  and then click on “Preferences —> Automatically Acquire Lock and Activate Changes (UNCHECK)” this check box .

Step1). Now Suppose we want too deploy two EAR files on WebLogic Servers “FirstEAR.ear” and “SecondEAR.ear” using the JMX Code then write the following jmx code in your local or remote file system .
“ApplicationDeployment_ManagedServer.java”

import java.io.*;
import weblogic.deploy.api.tools.*;  //SesionHelper
import weblogic.deploy.api.spi .*;  //WebLogicDeploymentManager
import weblogic.deploy.api.spi.DeploymentOptions;
import javax.enterprise.deploy.spi.TargetModuleID;
import javax.enterprise.deploy.spi.status.ProgressObject;
import javax.enterprise.deploy.spi.status.DeploymentStatus;
import javax.enterprise.deploy.shared.ModuleType;
import javax.enterprise.deploy.spi.Target;

import javax.enterprise.deploy.shared.*;

public class ApplicationDeployment_ManagedServer
{
     public static void main(String ar[]) throws Exception
		{
			ApplicationDeployment_ManagedServer appDeploy=new ApplicationDeployment_ManagedServer();
			String protocol="t3";
			String hostName="10.10.10.10";
			String portString="7001";
			String adminUser="weblogic";
			String adminPassword="weblogic";

			WebLogicDeploymentManager deployManager=SessionHelper.getRemoteDeploymentManager( protocol,hostName,portString,adminUser,adminPassword);
			System.out.println("\n\t WebLogicDeploymentManager: "+deployManager);
			DeploymentOptions options = new DeploymentOptions();
                        options.setRemote(true);
                        options.setStageMode(DeploymentOptions.NOSTAGE);
                        options.setTimeout(10000);   //Deployment will timeput in 10 seconds...change it accordingly
			System.out.println("\n\t DeploymentOptions: "+options);

			Target targets[]=deployManager.getTargets();
			System.out.println("------------------------------------------------------------");
			System.out.println("\t Application Can be Deployed in the Following targets:");
			int i=0;
			for (i=0;i<targets.length;i++)
					{
					   System.out.println("\n"+i+"   => Available Deployment Targets Are Below : "+targets[i]);
				        }
                        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                        System.out.print("\n\n Please Enter the Target Number in which you want to deploy Your Application: ");
                        int targetNumber=Integer.parseInt(br.readLine());
			Target deployTargets[]=new Target[1];
			//SUPPOSE You Chose it TO BE DEPLOYWD ON Managed Server ...
			deployTargets[0]=targets[targetNumber];
                        br.close();
            //-------------DEPLOYING FIRST APPLICATION-------------//
			String applicationDisplayName="FirstEARApplication";
			options.setName(applicationDisplayName);
			ProgressObject processStatus=deployManager.distribute(deployTargets, new File("FirstEAR.ear"), null,options);
			Thread.sleep(500);
			processStatus=deployManager.deploy(deployTargets, new File("FirstEAR.ear"), null,options);
			DeploymentStatus deploymentStatus=processStatus.getDeploymentStatus() ;
			System.out.println("\n\n\t For FirstEAR.ear DeploymentStayus.getState(): "+deploymentStatus.getState() +"\n\n");

			System.out.println("Sleeping for atleast 5-Seconds. Sothat the Deployment Activation gets Completed Successfully.");
			Thread.sleep(5000);

            //-------------DEPLOYING SECOND APPLICATION-------------//
			deployManager=null;
			deployManager=SessionHelper.getRemoteDeploymentManager( protocol,hostName,portString,adminUser,adminPassword);
			applicationDisplayName="SecondEARApplication";
			options.setName(applicationDisplayName);
			processStatus=deployManager.distribute(deployTargets, new File("SecondEAR.ear"), null,options);
			Thread.sleep(500);
			Thread.sleep(5000);
			processStatus=deployManager.deploy(deployTargets, new File("SecondEAR.ear"), null,options);
			deploymentStatus=processStatus.getDeploymentStatus() ;
			System.out.println("\n\n\t For SecondEAR.ear DeploymentStayus.getState(): "+deploymentStatus.getState() +"\n\n");
                        deployManager.release();
		}
}

Step2). Now open a Shell prompt then run “. ./setWLSEnv.sh” or “setWLSEnv.cmd” to make sure that PATH and CLASSPATH are set properly. then compile and run the following program:

[UserName@localhost Deploy_WLS]$ javac ApplicationDeployment_ManagedServer.java
[UserName@localhost Deploy_WLS]$ java ApplicationDeployment_ManagedServer

	 WebLogicDeploymentManager: weblogic.deploy.api.spi.deploy.WebLogicDeploymentManagerImpl@2b3d9460

	 DeploymentOptions: {isRetireGracefully=true,isGracefulProductionToAdmin=false,isGracefulIgnoreSessions=false,rmiGracePeriod=-1,retireTimeoutSecs=-1,undeployAllVersions=false,archiveVersion=null,planVersion=null,isLibrary=false,libSpecVersion=null,libImplVersion=null,stageMode=nostage,clusterTimeout=3600000,altDD=null,altWlsDD=null,name=null,securityModel=null,securityValidationEnabled=false,versionIdentifier=null,isTestMode=false,forceUndeployTimeout=0,defaultSubmoduleTargets=true,timeout=10000deploymentPrincipalName=null}
------------------------------------------------------------
	 Application Can be Deployed in the Following targets:

0   => Available Deployment Targets Are Below : AdminServer/server
1   => Available Deployment Targets Are Below : MS-1/server
2   => Available Deployment Targets Are Below : MS-2/server
3   => Available Deployment Targets Are Below : FrontEnd_MS/server
4   => Available Deployment Targets Are Below : TestCluster/cluster

 Please Enter the Target Number in which you want to deploy Your Application: 1
<Jun 21, 2011 4:48:03 PM IST> <Info> <J2EE Deployment SPI> <BEA-260121> <Initiating distribute operation for application, FirstEARApplication [archive: FirstEAR.ear], to MS-1 .>
<Jun 21, 2011 4:48:04 PM IST> <Info> <J2EE Deployment SPI> <BEA-260121> <Initiating deploy operation for application, FirstEARApplication [archive: FirstEAR.ear], to MS-1 .>

	 For FirstEAR.ear DeploymentStayus.getState(): running

Sleeping for atleast 5-Seconds. Sothat the Deployment Activation gets Completed Successfully.
<Jun 21, 2011 4:48:09 PM IST> <Info> <J2EE Deployment SPI> <BEA-260121> <Initiating distribute operation for application, SecondEARApplication [archive: SecondEAR.ear], to MS-1 .>
<Jun 21, 2011 4:48:15 PM IST> <Info> <J2EE Deployment SPI> <BEA-260121> <Initiating deploy operation for application, SecondEARApplication [archive: SecondEAR.ear], to MS-1 .>

	 For SecondEAR.ear DeploymentStayus.getState(): running

<Jun 21, 2011 4:48:15 PM IST> <Warning> <JNDI> <BEA-050001> <WLContext.close() was called in a different thread than the one in which it was created.>

.
.
Thanks
Jay SenSharma


Getting All Server’s Lifecycle State in a Domain

Hi,

Jay SenSharma

Jay SenSharma

Based on the query of one of our Magic User  Mr. Vibhor Rastogi (http://middlewaremagic.com/weblogic/?p=2110#comment-4287) We are developing this article.   It was asked that how we can get the Server’s actual lifecycle state using JMX Code when the server is not in Running state. Earlier we developed a JMX Code “Getting ServerState (Enhanced Version) for WLS9.x & Above” but that code was able to just fetch the Servers state which already started listening on it’s Listen Port so it was easy to get it’s State using ServerRuntimeMBean.

But in the current demonstration we will see how to fetch the Server’s different lifecycle states like “Starting”, “Stand By”, “Admin” , “Resuming”, “Running” etc while the Server is coming up and the Listen port is not actually opened so far.

.
Just use the following JMX Code and compile and run it after running the “$WLS_HOME/server/bin/setWLSEnv.sh” or “setWLSEnv.cmd” script so that the CLASSPATH and PATH will contain the required set of Jars and executables.
ServerLifecycleState.java

import weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean;
import weblogic.management.runtime.*;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.naming.Context;
import weblogic.management.jmx.MBeanServerInvocationHandler;
import java.util.Hashtable;
import java.io.IOException;
import java.net.MalformedURLException;
import weblogic.management.runtime.JDBCDataSourceRuntimeMBean;
import javax.management.*;
import javax.naming.*;

public class ServerLifecycleState {

private static MBeanServerConnection connection;
private static JMXConnector connector;
private static final ObjectName service;
private static String combea = "com.bea:Name=";
private static String service1 = "DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean";
private static String service2 = "RuntimeService,Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean";

   static
      {
        try {
               service =new ObjectName(combea + service1);
            } catch (MalformedObjectNameException e) {
              throw new AssertionError(e.getMessage());
            }
      }

   public static void initConnection(String hostname, String portString, String username, String password) throws IOException,MalformedURLException
     {
	String protocol = "t3";
	Integer portInteger = Integer.valueOf(portString);
	int port = portInteger.intValue();
	String jndiroot = "/jndi/";
	String mserver = "weblogic.management.mbeanservers.domainruntime";
	JMXServiceURL serviceURL = new JMXServiceURL(protocol, hostname, port, jndiroot + mserver);
	Hashtable h = new Hashtable();
	h.put(Context.SECURITY_PRINCIPAL, username);
	h.put(Context.SECURITY_CREDENTIALS, password);
	h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES,"weblogic.management.remote");
	connector = JMXConnectorFactory.connect(serviceURL, h);
	connection = connector.getMBeanServerConnection();
     }

   public static ObjectName[] getServerRuntimes() throws Exception
    {
        return (ObjectName[]) connection.getAttribute(service,"ServerRuntimes");
    }

   public void printNameAndState() throws Exception
    {
	ObjectName arr[]=getServerRuntimes();
	ObjectName domain = (ObjectName) connection.getAttribute(service,"DomainConfiguration");
	System.out.println("\t Domain: " + domain.toString());
	ObjectName[] servers = (ObjectName[]) connection.getAttribute(domain,"Servers");
    String serverState="UNKNOWN";
	for (ObjectName server : servers)
              {
		        String aName = (String) connection.getAttribute(server,"Name");
       		    try{
 			         ObjectName ser= new ObjectName("com.bea:Name="+aName+",Location="+aName+",Type=ServerRuntime");
			         serverState=(String) connection.getAttribute(ser,"State");
			         System.out.println("\n\t Server: "+aName+"\t State: "+serverState );
		           }
		        catch(Exception e)
		           {
					 DomainRuntimeServiceMBean domainRuntimeService = (DomainRuntimeServiceMBean) MBeanServerInvocationHandler.newProxyInstance(connection, new ObjectName(DomainRuntimeServiceMBean.OBJECT_NAME));
					 DomainRuntimeMBean domainRuntime = domainRuntimeService.getDomainRuntime();
					 ServerLifeCycleRuntimeMBean serverLifeCycleRuntimeMBean = domainRuntime.lookupServerLifeCycleRuntime(aName);
			         System.out.println("\t Server: "+aName+"\t In LifeCycleState : "+ serverLifeCycleRuntimeMBean.getState());
		           }
              }
      System.out.println("\t -------------------------- data/time:\t"+new java.util.Date()+" ----------------------------");
    }

  public static void main(String[] args) throws Exception
   {
	String hostname = args[0];
	String portString = args[1];
	String username = args[2];
	String password = args[3];
	ServerLifecycleState s = new ServerLifecycleState();
	initConnection(hostname, portString, username, password);
	for(int i=0;i<1000;i++)
	   {
	       s.printNameAndState();
		   Thread.sleep(500);
	   }
	connector.close();
   }
 }

Compile and run the following program and for testing in parallel start any of your Managed Server.
you will see following kind of output Notice the Managed Server LifeCycle state is changing:

  -------------------------- data/time:  Mon Jun 20 00:16:36 IST 2011 ----------------------------
  Domain: com.bea:Name=9001_domain,Location=9001_domain,Type=Domain

  Server: AdminServer     State: RUNNING
  Server: MS1     In LifeCycleState : SHUTDOWN
  -------------------------- data/time:  Mon Jun 20 00:16:37 IST 2011 ----------------------------
  Domain: com.bea:Name=9001_domain,Location=9001_domain,Type=Domain

  Server: AdminServer     State: RUNNING
  Server: MS1     In LifeCycleState : STARTING
  -------------------------- data/time:  Mon Jun 20 00:16:38 IST 2011 ----------------------------
  Domain: com.bea:Name=9001_domain,Location=9001_domain,Type=Domain

  Server: AdminServer     State: RUNNING
  Server: MS1     In LifeCycleState : STARTING
  -------------------------- data/time:  Mon Jun 20 00:16:38 IST 2011 ----------------------------
  Domain: com.bea:Name=9001_domain,Location=9001_domain,Type=Domain

  Server: AdminServer     State: RUNNING
  Server: MS1     In LifeCycleState : STARTING
  -------------------------- data/time:  Mon Jun 20 00:16:39 IST 2011 ----------------------------
  Domain: com.bea:Name=9001_domain,Location=9001_domain,Type=Domain

  Server: AdminServer     State: RUNNING
  Server: MS1     In LifeCycleState : RESUMING
  -------------------------- data/time:  Mon Jun 20 00:16:39 IST 2011 ----------------------------
  Domain: com.bea:Name=9001_domain,Location=9001_domain,Type=Domain

  Server: AdminServer     State: RUNNING

  Server: MS1     State: RUNNING
Server State Using ServerLifeCycleRuntimeMBean

Server State Using ServerLifeCycleRuntimeMBean

.
.
Thanks
Jay SenSharma


[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


SOAP Attachment using JAXWS Style of WebService

Hi,

Jay SenSharma

Jay SenSharma

Based on the comment/query of one of our subscriber “Mauriciohttp://middlewaremagic.com/weblogic/?page_id=131#comment-4208 , Here we are going to see a very simple demonstration of using the SOAP Attachment on JAXWS Style of WebServices. Using following sample we can upoad an attachment on WebLogic DOMAIN_HOME directory (or in any other location defined in our WebService class).

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

Step2). Now create a directory with name “src” inside “C:\SOAP_Attachment”

Step3). Write the following kind of WebService “AttachmentService_Impl.java” inside “C:\SOAP_Attachment\src”

package ws;
import java.io.*;
import java.util.*;
import javax.activation.*;   //DataHandler, FileDataSource

//XML Related APIs
import javax.xml.transform.*;   // Source, Transformer, TransformerFactory
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;

//WebService APIs
import javax.jws.*;
import javax.jws.soap.SOAPBinding;

@WebService
@SOAPBinding(style=SOAPBinding.Style.DOCUMENT,use=SOAPBinding.Use.LITERAL,parameterStyle=SOAPBinding.ParameterStyle.WRAPPED)

public class AttachmentService_Impl
	{
	   public DataHandler dataHandler=null;
       public String attachAnyFile(DataHandler dataHandler, String file)
		   {
		          String filename="";
             try {
				    //DataHandler dataHandler=new DataHandler(fileDataSource);
					File f=new File(file);
					filename=f.getName();
                    System.out.println("\n\t Writing to File /" + filename);
                    BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(filename));
                    BufferedInputStream bin = new BufferedInputStream(dataHandler.getInputStream());

		            byte[] buffer = new byte[256];
				    while (true)
					{
						int bytesRead = bin.read(buffer);
		                if (bytesRead == -1)
				            break;
						bout.write(buffer, 0, bytesRead);
					}
		            bin.close();
				    bout.close();
		        }
			   catch (Exception e)
				{
					System.out.println("\n\t [AttachmentService_Impl] Exception Occured While Writing in File : "+e);
					return e.toString();
				}
               return ("\n\t File Attachment Completed Succesfully " + filename + "\t at " + new Date());
            }
}

Step4). Now write the WebService Client program inorder to send the Attachment to WebService. “Client.java” inside “C:\SOAP_Attachment\src”

package client;
import javax.activation.DataHandler;
import javax.activation.*;
import java.io.*;
public class Client
{
	public static void main(String[] ar) throws Exception
	{
		System.out.println("\n\tstart client");
		AttachmentServiceImplService service=new AttachmentServiceImplService();
		AttachmentServiceImpl port=service.getAttachmentServiceImplPort();

        String fileName_WithPath=ar[0];
		long length=new java.io.File(ar[0]).length();
		FileDataSource fileDataSource = new FileDataSource(fileName_WithPath);
        DataHandler dataHandler = new DataHandler(fileDataSource);
        System.out.println("\n\tCalling service to send a file from a customer...");

  	    BufferedInputStream bin = new BufferedInputStream(dataHandler.getInputStream());
		byte b[]=new byte[(int)length];
		bin.read(b);
        String result = port.attachAnyFile(b,fileName_WithPath);
        System.out.println("\n\t Result From Service: "+result);
        System.out.println("\n\tend client");
	}
}

Step5). Now we will write the following ANT Sctipt to completely Build, Deploy and Run the Client. “build.xml” inside “C:\SOAP_Attachment” directory.

<project name="DwAttach" default="all">
 <!-- set global properties for this build -->
 <property name="wls.username" value="weblogic" />
 <property name="wls.password" value="weblogic" />
 <property name="wls.hostname" value="localhost" />
 <property name="wls.port" value="7001" />
 <property name="wls.server.name" value="AdminServer" />

 <property name="ear.deploy.name" value="SOAP_JAXWS_AttachmentEar" />
 <property name="client-output" value="output" />
 <property name="tempjar-dir" value="${client-output}/tempjardir" />
 <property name="ear.dir" value="${client-output}/SOAP_JAXWS_AttachmentEar" />
 <property name="clientclass-dir" value="${client-output}/clientclasses" />

 <path id="client.class.path">
    <pathelement path="${clientclass-dir}"/>
    <pathelement path="${java.class.path}"/>
  <pathelement path="src"/>
 </path>

 <taskdef name="jwsc" classname="weblogic.wsee.tools.anttasks.JwscTask" />
 <taskdef name="clientgen" classname="weblogic.wsee.tools.anttasks.ClientGenTask" />

 <target name="all" depends="clean,build-service,deploy-attach,client,run" />
 <target name="clean" depends="undeploy-attach">
	 <delete dir="${client-output}"/>
 </target>

 <target name="build-service">
	  <javac srcdir="src" destdir="src" classpath="${client.class.path}" includes="*Attach*.java"/>
	  <jwsc srcdir="src" destdir="${ear.dir}" debug="true" classpathref="client.class.path">
	       <jws file="AttachmentService_Impl.java" type="JAXWS" />
	  </jwsc>
 </target>

 <target name="deploy-attach">
  <wldeploy action="deploy" name="${ear.deploy.name}"   source="${ear.dir}"
            user="${wls.username}"  password="${wls.password}"
            verbose="true"   adminurl="t3://${wls.hostname}:${wls.port}"
            targets="${wls.server.name}" />
  </target>

 <target name="undeploy-attach">
 <wldeploy action="undeploy" name="${ear.deploy.name}"   failonerror="false"
           user="${wls.username}" password="${wls.password}" verbose="true"
           adminurl="t3://${wls.hostname}:${wls.port}"  targets="${wls.server.name}" />
 </target>

 <target name="client">
    <clientgen  wsdl="http://${wls.hostname}:${wls.port}/AttachmentService_Impl/AttachmentService_ImplService?WSDL"
                destDir="${clientclass-dir}"  packageName="client" type="JAXWS"/>
             <javac   debug="true"  srcdir="${clientclass-dir}" destdir="${clientclass-dir}" includes="**/*.java"/>
             <!-- <javac  debug="true"  srcdir="client" destdir="${clientclass-dir}" includes="client/**/*.java"/>  -->
 </target>

 <target name="run">
      <javac srcdir="src" destdir="${clientclass-dir}" classpath="${client.class.path}" includes="Client.java"/>
      <java classname="client.Client"   fork="true"  failonerror="true">
               <classpath refid="client.class.path"/>
			   <jvmarg value="-Xmx512m" />
               <arg line="Cant_Stop_Dancing.mp3" /> <!-- Name of the file for SOAP Attachment -->
      </java>
 </target>
</project>

Step6). Open a command prompt and then run “. ./setWLSEnv.sh” to set the Environment (classpath/path) , then run the ant script to build, Deploy and run the WebService Client. like following


C:\SOAP_Attachment>ant
Buildfile: build.xml

undeploy-attach:
 [wldeploy] weblogic.Deployer -verbose -noexit -name SOAP_JAXWS_AttachmentEar -targets AdminServer -adminurl t3://localhost:7001 -user weblo
gic -password ******** -undeploy
 [wldeploy] weblogic.Deployer invoked with options:  -verbose -noexit -name SOAP_JAXWS_AttachmentEar -targets AdminServer -adminurl t3://loc
alhost:7001 -user weblogic -undeploy
 [wldeploy] <Jun 12, 2011 4:47:27 PM IST> <Info> <J2EE Deployment SPI> <BEA-260121> <Initiating undeploy operation for application, SOAP_JAX
WS_AttachmentEar [archive: null], to AdminServer .>
 [wldeploy] Task 8 initiated: [Deployer:149026]remove application SOAP_JAXWS_AttachmentEar on AdminServer.
 [wldeploy] Task 8 completed: [Deployer:149026]remove application SOAP_JAXWS_AttachmentEar on AdminServer.
 [wldeploy] Target state: undeploy completed on Server AdminServer
 [wldeploy]

clean:
   [delete] Deleting directory C:\SOAP_Attachment\output

build-service:
    [javac] Compiling 1 source file to C:\SOAP_Attachment\src
     [jwsc] JWS: processing module /AttachmentService_Impl
     [jwsc] Parsing source files
     [jwsc] Parsing source files
     [jwsc] 1 JWS files being processed for module /AttachmentService_Impl
     [jwsc] JWS: C:\SOAP_Attachment\src\AttachmentService_Impl.java Validated.
     [jwsc] Processing 1 JAX-WS web services...
     [jwsc] warning: Annotation types without processors: [javax.xml.bind.annotation.XmlRootElement, javax.xml.bind.annotation.XmlAccessorTy
pe, javax.xml.bind.annotation.XmlType, javax.xml.bind.annotation.XmlElement]
     [jwsc] 1 warning
     [jwsc] Compiling 3 source files to C:\DOCUME~1\DELLUS~1\LOCALS~1\Temp\_6vmlr8
     [jwsc] Building jar: C:\SOAP_Attachment\output\SOAP_JAXWS_AttachmentEar\AttachmentService_Impl.war
     [jwsc] Created JWS deployment outputFile: C:\SOAP_Attachment\output\SOAP_JAXWS_AttachmentEar\AttachmentService_Impl.war
     [jwsc] [EarFile] Application File : C:\SOAP_Attachment\output\SOAP_JAXWS_AttachmentEar\META-INF\application.xml
[AntUtil.deleteDir] Deleting directory C:\DOCUME~1\DELLUS~1\LOCALS~1\Temp\_6vmlr8

deploy-attach:
 [wldeploy] weblogic.Deployer -verbose -noexit -name SOAP_JAXWS_AttachmentEar -source C:\SOAP_Attachment\output\SOAP_JAXWS_AttachmentEar -ta
rgets AdminServer -adminurl t3://localhost:7001 -user weblogic -password ******** -deploy
 [wldeploy] weblogic.Deployer invoked with options:  -verbose -noexit -name SOAP_JAXWS_AttachmentEar -source C:\SOAP_Attachment\output\SOAP_
JAXWS_AttachmentEar -targets AdminServer -adminurl t3://localhost:7001 -user weblogic -deploy
 [wldeploy] <Jun 12, 2011 4:47:33 PM IST> <Info> <J2EE Deployment SPI> <BEA-260121> <Initiating deploy operation for application, SOAP_JAXWS
_AttachmentEar [archive: C:\SOAP_Attachment\output\SOAP_JAXWS_AttachmentEar], to AdminServer .>
 [wldeploy] Task 9 initiated: [Deployer:149026]deploy application SOAP_JAXWS_AttachmentEar on AdminServer.
 [wldeploy] Task 9 completed: [Deployer:149026]deploy application SOAP_JAXWS_AttachmentEar on AdminServer.
 [wldeploy] Target state: deploy completed on Server AdminServer
 [wldeploy]
 [wldeploy] Target Assignments:
 [wldeploy] + SOAP_JAXWS_AttachmentEar  AdminServer

client:
[clientgen]
[clientgen] *********** jax-ws clientgen attribute settings ***************
[clientgen]
[clientgen] wsdlURI: http://localhost:7001/AttachmentService_Impl/AttachmentService_ImplService?WSDL
[clientgen] packageName : client
[clientgen] destDir : C:\SOAP_Attachment\output\clientclasses
[clientgen]
[clientgen] *********** jax-ws clientgen attribute settings end ***************
[clientgen] Consider using <depends>/<produces> so that wsimport won't do unnecessary compilation
[clientgen] parsing WSDL...

[clientgen] generating code...

[clientgen] compiling code...

[clientgen] Note: C:\SOAP_Attachment\output\clientclasses\client\AttachmentServiceImplService.java uses unchecked or unsafe operations.
[clientgen] Note: Recompile with -Xlint:unchecked for details.

run:
    [javac] Compiling 1 source file to C:\SOAP_Attachment\output\clientclasses

     [java]     start client

     [java]     Calling service to send a file from a customer...

     [java]      Result From Service:
     [java]      File Attachment Completed Succesfully Cant_Stop_Dancing.mp3     at Sun Jun 12 16:47:40 IST 2011

     [java]     end client

all:

BUILD SUCCESSFUL
Total time: 14 seconds
C:\SOAP_Attachment>

Step7). NOTE: as soon as you will run the above sample …you will find that the Attachment is created inside the $DOMAIN_HOME of your WebLogic Server. The Path of Attachement creation on the server side can be defined in the WebService program in the following line:

BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(filename));
Example:
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(“/home/userone/”+filename));
OR
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(“C:/Attachements/”+filename));
.
.
Thanks
Jay SenSharma


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


  • 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