Shell script to monitor weblogic log for exception

Summary:

This script is going to monitor weblogic AdminServer.log to for any Exception and trigger email with exception stack.

WeblogiServerLogWatcher.sh:

=====================

#!/bin/bash
#set -xv
# The script to verify the error from AdminServer.log logs

Path=/scratch/Oracle/Middleware/user_projects/domains/Testing/servers/AdminServer/logs

#removing the old scripting logs
if [ -s “$Path/script/file.txt” ]
then
rm $Path/script/file.txt
fi

#date based on the log format
date=`date “+%b %-d, %Y”`

#Log Details
log1=$Path/AdminServer.log

#checking logs
grep -i “$date” $log1 | egrep -A20 -B5 -i ‘Exception’ >> $Path/script/file.txt

#email

if [ -s “$Path/script/file.txt” ]
then
#echo ‘file has data’
cat $Path/script/file.txt | mail  -s “Exception in Weblogic Server” sxyz@oracle.com,xrct@gmail.com
# do something as file has data
#else
# do something as file is empty
fi

#cat $Path/script/output | mail  -s “Exception in Weblogic Server” sxyz@oracle.com,xrct@gmail.com

# END

===================================

Add it to Cron job:

Type the below command

crontab -e

Add the below line to run the script for every 4 hours

0 */4 * * * /scratch/Oracle/Middleware/user_projects/domains/Testing/servers/AdminServer/logs/script/WeblogiServerLogWatcher.sh

Summary:

Above script I wrote for internal use, please customize according to your need. You can monitor multiple servers and also read email from external file etc.

Posted in Uncategorized | Leave a comment

Weblogic – displaying Runtime server status in a JSP

* Overview:

This blog is to display Server status in a JSP. This sample can be used to apply weblogic Administrator credentials to deployed applications. Meaning, you can deploy an application and provide BASIC authorization to that application and we can link the authorization to default weblogic authorization , so that the username/password which we use for weblogic console can be used to login to this application. You dont need to create any new user credentials, I recommend to use this feature to admin specific applications.

In this case , we are creating an application to monitor server status. You can create such applications to monitor very specific use case. For ex, stack holders might be interested to see very specific monitoring, they dont want to use JConcole or any monitoring tool in which they have to traverse through hundreds of MBeans to get to see what they want. Instead you can develop a simple application and give one URL with admin username/password and they see what they want on that page itself.

* What we are going to do:

We are going to create a simple web application with one JSP , the page retrieves server status by looking up DomainRuntime Mbeans. We are going to use the sample listed under “Listing 4-2 Example: Print the Name and State of Servers” in  https://docs.oracle.com/cd/E13222_01/wls/docs90/jmx/accessWLS.html.

* Application Implementation:

Create following files/directories under a directory, for ex: /blog/sample/wlxmbeanapp

bash-3.2$ ls -R -ltr
.:
total 8
drwxr-xr-x 2 <user> dba 4096 Dec 12 14:53 WEB-INF
-rw-r–r– 1 <user> dba 2296 Dec 18 15:06 hello.jsp

./WEB-INF:
total 12
-rw-r–r– 1 <user> dba 1066 Dec 12 14:46 ~
-rw-r–r– 1 <user> dba 1064 Dec 12 14:48 web.xml
-rw-r–r– 1 <user> dba  550 Dec 12 14:53 weblogic.xml

hello.jsp

=====

1 <html>
2
3 <body>
4 Server Status:
5 <table border=”1″ style=”width:100%”>
6 <tr><td>No</td><td>Server Name</td><td>Server State</td></tr>
7 <%
8          javax.management.MBeanServerConnection connection;
9          javax.management.remote.JMXConnector connector=null;
10          javax.management.ObjectName service;
11         try {
12                 String protocol = “wlx”;
13                 String jndiroot = “/jndi/”;
14                 String mserver = “weblogic.management.mbeanservers.domainruntime”;
15                 javax.management.remote.JMXServiceURL serviceURL =
16                  new javax.management.remote.JMXServiceURL(“service:jmx:wlx:///jndi/weblogic.management.mbeanservers.domainruntime”);
17                 java.util.Hashtable h = new java.util.Hashtable();
18                 h.put(javax.naming.Context.SECURITY_PRINCIPAL,”weblogic” );
19                 h.put(javax.naming.Context.SECURITY_CREDENTIALS, “welcome1″);
20                 h.put(javax.management.remote.JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES,”weblogic.management.remote”);
21                 connector = javax.management.remote.JMXConnectorFactory.connect(serviceURL,h);
22                 connection = connector.getMBeanServerConnection();
23                 javax.management.ObjectName service1 = new javax.management.ObjectName(“com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbea    nservers.domainruntime.DomainRuntimeServiceMBean”);
24                 javax.management.ObjectName[] serverRT = (javax.management.ObjectName[])connection.getAttribute(service1,”ServerRuntimes”);
25                 int length = (int) serverRT.length;
26                 for (int i = 0; i < length; i++) {
27                       out.println(“<tr>”);
28                       out.println(“<td>”+i+”</td>”);
29                        String name = (String) connection.getAttribute(serverRT[i],
30                         “Name”);
31                         out.println(“<td>”+name+”</td>”);
32                        String state = (String) connection.getAttribute(serverRT[i],
33                         “State”);
34                         out.println(“<td>”+state+”</td>”);
35                    out.println(“</tr>”);
36                 }
37
38         } catch (Exception ex)
39         {
40          out.println(“error , look into the server out”);
41          ex.printStackTrace();
42         }
43         finally{
44                 if(connector !=null)
45                         connector.close();
46         }
47
48  %>
49 </table>
50 </body>
51 </html>

WEB-INF/web.xml:

=============

1 <?xml version = ‘1.0’ encoding = ‘windows-31j’?>
2 <web-app xmlns=”http://java.sun.com/xml/ns/javaee&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
3          xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221;
4          version=”2.5″>
5 <security-constraint>
6                 <web-resource-collection>
7                       <web-resource-name>Success</web-resource-name>
8                       <url-pattern>/hello.jsp</url-pattern>
9                      <http-method>GET</http-method>
10                      <http-method>POST</http-method>
11                 </web-resource-collection>
12                <auth-constraint>
13                     <role-name>Admin</role-name>
14                 </auth-constraint>
15           </security-constraint>
16           <login-config>
17               <auth-method>BASIC</auth-method>
18               <realm-name>myrealm</realm-name>
19           </login-config>
20            <security-role>
21                <role-name>Admin</role-name>
22            </security-role>
23 </web-app>

WEB-INF/weblogic.xml

=================

1 <?xml version = ‘1.0’ encoding = ‘windows-31j’?>
2 <weblogic-web-app xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://xmlns.oracle.com/weblogic/weblogic-web-app http://xm    lns.oracle.com/weblogic/weblogic-web-app/1.1/weblogic-web-app.xsd” xmlns=”http://xmlns.oracle.com/weblogic/weblogic-web-app”&gt;
3     <context-root>wlxmbeanapp</context-root>
4      <security-role-assignment>
5          <role-name>Admin</role-name>
6          <principal-name>weblogic</principal-name>
7      </security-role-assignment>
8   </weblogic-web-app>

* Deploy the application:

Start weblogic Adminserver and deploy the application ( wlxmbeanapp ) as exploded form by traversing into the directory /blog/sample. Target the application into AdminServer.

* Access the application:

After deploying the application, access the application using http://<hostname&gt;:7001/wlxmbeanapp/hello.jsp and when the pop up comes up provide weblogic console username and password.  The page displays similiar to the one below.

Server Status:

No Server Name Server State
0 ms1 RUNNING
1 myserver RUNNING

Summary:

Hope this application helped. Please let me know if you have any further questions.

Posted in Uncategorized | Leave a comment

My Unix Commands

This blog is to keep my Unix commands which I often use it in my weblogic environment.

http://www.eng.hawaii.edu/Tutor/vi.html

Vi Editor:
———
:q –> to quit
:q! –> quit without save
:w –> save
:wq –> save and quite
:w filename2 –> Save as filename2
? –> backward search
/ —> forward search
G –> Go to End of the file
:<line#> –> to go to specific line

Setting Path
————

PATH=$PATH:/usr/java/j2sdk1.4.2/bin
export PATH
bash-3.00$ JAVA_HOME=/usr/java5_64/bin
bash-3.00$ export PATH=$JAVA_HOME:$JAVA_HOME/bin:$PATH
bash-3.00$ java -version

PS command
———-

http://www.cyberciti.biz/faq/show-all-running-processes-in-linux/

bash-2.05b$ pgrep -U schellap java

pgrep -U schellap java

Set Classpath
————-
bash-3.00$ CLASSPATH=/u01/CR-root/Arun/wls923/weblogic92/server/lib/weblogic.jar
bash-3.00$ export CLASSPATH

create a file
————-
cat filename
rm unwantedfile

rm -r directoryname –> to remove a directory

[slcruser@sllinux8 schellap]$ cat > examplesServer.log00004

919943629191
francis.rajamohan@sbcglobel.net

——>

mv –> move

to un tar –> tar xvf ./logs_030410.tar
to unjar .Z file –> uncompress ./aims_srv_01.log.Z

http://kb.iu.edu/data/acsy.html

grep:
[oracle@linas1 aixblhspa01_sunone]$ grep rLRDLQRQgQR8Yjh7vhGDf43RcH1WpW1Bn1TqjL2vjqwGwW8cTf0y wlproxy.log | wc -l

grep “string” filename | more

zcat *sass.Z|grep “machan”

grep “string” filename | grep -v “exclude” filename

grep -c “Error” logfile.txt –> to count the # of occurences

http://javarevisited.blogspot.com/2011/06/10-examples-of-grep-command-in-unix-and.html#.Th8-hGFtNpg

grep –context=6 successful logfile.txt
grep -C 2 ‘hello’ *

egrep ‘Error|Exception’ logfile.txt

grep -i Error logfile –> case in sensitive
zgrep -i Error *.gz

grep -w ERROR logfile
grep ‘ERROR>’ *

ps command
———-

http://lowfatlinux.com/linux-gzip-gunzip.html

sar –> http://en.wikipedia.org/wiki/Sar_in_UNIX –> System Activiy Reporter
mpstat –> Report per-processor or per-processor-set-statiscs

http://www.cyberciti.biz/faq/how-do-i-find-out-what-ports-are-listeningopen-on-my-linuxfreebsd-server/

—> install wls

$ chmod +x wls1036_linux64.bin
$ ./wls1036_linux64.bin

–> zip
to compress:
zip squash.zip file1 file2 file3

to uncompress:

unzip squash.zip

–> gz
gunzip file.gz
$ gzip -d file.gz

— Unix search commads

./find . -name “foo.txt” -print

— start Weblogic where save all the System.out
. ./startWebLogic.sh 2>&1 | tee -a out.log

Posted in Uncategorized | Leave a comment

Sample JDBC Module deployment part of an Appplication in Weblogic

This document is to provide a sample application of configuration mentioned in the below link

http://docs.oracle.com/cd/E15051_01/wls/docs103/jdbc_admin/packagedjdbc.html

Customers could create JDBC connections by creating a JDBC module and deploy it part of an EAR application. Which in turn inherit all the deployment specific properties..meaning you can attach a deployment plan and edit the environmental specific details username/password such that..when you move the application across different environments.

Below is a sample implementation of JDBC module deployment part of an EAR. The EAR has a WAR which in fact uses the same JDBC..please edit JDBC connection specific properties..feel free to ask any questions if you have.

https://www.dropbox.com/s/vhkxgb1d4ypwv0s/TestWeb.ear

Posted in Uncategorized | Leave a comment

Taking Threaddump in .Net environment using Microsoft’s Debug Diagnostic Tool

Overview:

Getting a dump or thread dump is necessary when your java application interacts with .Net client..for ex. An .Net client accessing java based services hosted in an JEE container, .Net client access Coherence Cache. I have used Microsoft’s Diagnostic Tool to resolve many performance related issues with .Net based applications.

Download and Installation:

Download the tool from Microsoft.com, http://www.microsoft.com/en-us/download/details.aspx?id=26798 link works so far. Download and install the installer to your local machine, I installed it in D:\Coherence\DebugDiag(Image 1).

DebugDiag.exe –> exe  To open the tool

log/Misc –> folder where the dump files go after capture.

Image # 1:

Start Debug Diagnostic:

We can start the tool by double clicking DebugDiag.exe. The tool has “Rules”, “Advanced Analysis” and “Process” tabs.Process list all the process running on the System, we will be using that tab mainly to capture data and Advanced Analysis will be used to analyze any existing data.

Image # 2:

Capture Dump/Dumps:

In my environment, I am running a C# application called ContactCache.Windows eventually it run an exe ContactCache.Windows.vshost.exe. If you click on the processes tab, it lists all the running process from the system and you could see the application ContactCache.Windows which is running inside C# 2010 express edition.

Image #3:

If you right click on the process which your going to debug, you will the following options(Image 4),

i) Monitor For Leaks –> This is capture memory data, which we are not discussing on this blog

ii) Create Full Userdump –> Capture one dump, which is mainly to find out dead lock situations were threads never get release.

iii) Create Mini Userdump –> As of now I couldn’t find out the difference between Full Userdump and Mini Userdump other than the file size.

iv) Create Userdump series –> This is to capture series of dumps, this helps to find out intermittent performance issues. This is the most used option based on my experience.

v) Terminate Process –> This you don’t want to perform in a production environment.

vi) Copy –> This is to copy certain information about the process.

As I mentioned before dump files will be captured into <DebugDiag_Folder>Logs/Misc folder with file name as <exe name> <PID><Data and Time> <Dump Category> ..for ex: ContactCache.Windows.vshost.exe__PID__3096__Date__10_04_2012__Time_10_09_58AM__95__Manual Dump..

Image #4:

Getting Full Userdump or Mini Userdump is easy, just choose that option DebugDiag tool capture the dump. If you want to capture series of dumps, then we need to select the options. By default (Image # 5) it capture 10 mini dumps for every 3 seconds, we might need to modify this according to your issue. If the hang happens longer period of time, you might need to increase the between time and more or less dumps.

Image # 5:

Analyze Dump/Dumps:

As I mentioned before, to analyze an existing dump we will use “Advanced Analysis” tab. Make sure Crash/Hang Analyzers is chosen from the category, by default tool chose that anyway. We can import single dump/multiple dumps using Add Data files button. Remove Data files are used to remove dump files from the list. Start Analysis button analyze the chosen file and open up the report in the IE explorer.

Image # 6:

Adding dump series by clicking Add Data Files button (Image # 7)  and click Open.

Image # 7:

Now choose one of the file and click start analysis button(Image # 8) , it will take few minutes and will open up the report in an explore(Image # 9).

Image # 8:

Image # 9:

Summary:

Understanding the report is as simple as looking into java thread dump, look for threads that not moving. This tool helps me to resolve many .Net performance issues hopefully it helps you guys as well.

Posted in Uncategorized | 2 Comments

Shell script to take multiple thread dumps from multiple JVMs

Summary:

In Weblogic and Coherence, we often require thread dumps from all the nodes or servers when the issue happens.

Description:

For intermittent hung issues, we might need thread dump when Customer sees the issue and we want the thread dump from all the JVMs. The below script should help in that situation, we can provide the list process first and then just call the script.

#takeTd.sh

#take thread dumps for every 10 seconds for the listed PIDs

array=(10338,10389,10689)
len=${#array[*]}
echo “The array has $len members. They are:”
i=0
while [ 1 ]
do
while [ $i -lt $len ]; do
#echo ‘date “+%Y-%m-%d %H:%M:%S”‘
echo “PID $i: ${array[$i]}”
kill -3 ${array[$i]}
let i++
done
sleep 10
echo “starting next set of thread dumps”
i=0
done

Summary:

The above one should solve the basic need, will update the script if I come across any different use cases.

Posted in Uncategorized | 1 Comment

Keeping Http-Sessions in Coherence cache

Overview:

This article talks about keeping your Http Sessions in Coherence cache , instead of keeping it as part of app server’s in memory or any other external device ..file/DB. We will integrate Weblogic to use Coherence cache and will play around the Http session a little bit.

Why we need:

1) Considering the Coherence cache storage running on a separate JVM even if the app server JVM was down for some reason, if the app server is back within the session timeout period, Customer can access the same session. In fact if the Coherence cache server is running in a separate  box, you even can replace a hardware which belongs to that App server JVM.

2) Having a separate HTTPSession layer, we can store huge data in the session without worrying about OutOfMemory from the application server layer.

3) Not quite sure if this is possible practically, but theoretically different app servers  can share the same Http Session if needed( at least in the future).

What we need:

1) Weblogic 10.3.3 server

2) Coherence 3.6.1

Setup: I am referring Oracle Coherence documentation for the same

http://download.oracle.com/docs/cd/E14526_01/coh.350/e14536/wslinstall.htm#BABDFAEF

i) Copy coherence.jar in the domain lib directory, in my machine I copied the same into the following directory

E:\oracle\bea1033\user_projects\domains\coherence_web_domain\lib

ii) Start the Weblogic Admin Server and create a Cluster of two servers

iii) Deploy coherence-web-spi.war as a shared library –> One of the reasons behind deploying this war is , I believe this carries the coherence cache config for the session.
iv) create a war, below are the file contents.

File Contents:

E:\coherence\CoherenceWeb\machanmama –>test.jsp
|
WEB-INF–
|
–weblogic.xml
–web.xml
|
lib –> empty folder
classes –> empty folder

File contents:

weblogic.xml:
————
Basically this file is telling

1) Replicate my session if the servers are Clustered
2) Reference to the coherence web library we deployed a little while ago.

<?xml version=”1.0″ encoding=”ISO-8859-1″?>

<weblogic-web-app xmlns=”http://www.bea.com/ns/weblogic/90″&gt;
<session-descriptor>
<persistent-store-type>replicated_if_clustered</persistent-store-type>
</session-descriptor>
<library-ref>
<library-name>coherence-web-spi</library-name>
<specification-version>1.0.0.0</specification-version>
<implementation-version>1.0.0.0</implementation-version>
<exact-match>false</exact-match>
</library-ref>
</weblogic-web-app>

Web.xml:
——
since I am just playing with jsp alone, there is no content in there

<web-app xmlns=”http://java.sun.com/xml/ns/j2ee&#8221; version=”2.4″>
</web-app>

Test.jsp:
——–

<%

out.println(“– Start —“);

try {

if(session.getAttribute(“obj1″) != null){
out.println(” Inside the getAttribute “);
session.getAttribute(“obj1″);
}else{
out.println(” Inside the setAttribute “);
session.setAttribute(“obj1″,”obj1”);
}

}
catch(java.lang.Exception ex){
out.println(“– Exception —“);
ex.printStackTrace();
}
out.println(“– End —“);

%>

Coherence Cluster setup:

1) I do little customization from Coherence cluster perspective, I would like to specify an override file with some unique values to make sure my Coherence Servers are forming an unique Cluster, I am still trying to Multicast as the Cluster messaging mode. To do that, create a file name test-override. xml with the following content in it, the values which are more important are  Cluster name and multicast address.

<?xml version=’1.0′?>

<!DOCTYPE coherence SYSTEM “coherence.dtd”>

<coherence>
<logging-config>
<severity-level system-property=”tangosol.coherence.log.level”>9</severity-level>
</logging-config>
<cluster-config>
<member-identity>
<cluster-name>Machan</cluster-name>
</member-identity>
<multicast-listener>
<address>224.3.6.0</address>
<!– <time-to-live system-property=”tangosol.coherence.ttl”>0</time-to-live> –>
<port>8901</port>
</multicast-listener>
</cluster-config>

</coherence>

2) Add the below -D option as part of the server start up

-Dtangosol.coherence.override=E:\temp\eclipse-workspace\hello-grid\src\test-override.xml

I put the same in E:\oracle\bea1033\user_projects\domains\coherence_web_domain\bin\setDomainEnv.cmd

and added as part of the JAVA_OPTIONS

set JAVA_OPTIONS=%JAVA_OPTIONS% %JAVA_PROPERTIES% -Dwlw.iterativeDev=%iterativeDevFlag% -Dwlw.testConsole=%testConsoleFlag% -Dwlw.logErrorsToConsole=%logErrorsToConsoleFlag% -Dtangosol.coherence.override=E:\temp\eclipse-workspace\hello-grid\src\test-override.xml

Testing:

1) Start the Coherence Cache Server using the below command,  and you can see the output from my machine as well, keep it running.

E:\coherence\coherence-java-3.6.1.0b19636\coherence\lib>java -server -cp coherence.jar;coherence-web-spi.war  -Dtangosol.coherence.management.remote=true -Dtangosol.coherence.management=all -Dtangosol.coherence.management.remote=true -Dtangosol.coherence.cacheconfig=WEB-INF/classes/session-cache-config.xml -Dtangosol.coherence.session.localstorage=true -Dtangosol.coherence.override=E:\temp\eclipse-workspace\hello-grid\src\test-override.xml com.tangosol.net.DefaultCacheServer

2) Start the Weblogic Admin and the two ManagedServers: After this you pretty much see four command prompts running, i) Weblogic Admin ii) Weblogic Managed Server 1 iii) Weblogic Managed Server 2 iv) And the Coherence Cache Server

3) Now go to the Console and deploy the test.war and target to the Weblogic Cluster ( server1 and server2).

4) To verify the setup , please open a jConsole and see the details, you see a Coherence-> Cluster –> Attributes–> Cluster Size = 3 and you also see Coherence –> Cache –> DistributedSessions, like below and this tells you, the Cluster is formed correctly and the Session Cache got initialized.

5) Now open a browser and invoke the test.jsp

http://localhost:7004/machanmama/test.jsp

output: –> meaning first time , it is creating a new session keeping it in Coherence cache.

— Start — Inside the setAttribute — End —

6) Now restart both the Weblogic Servers and hit the same URL again–> This time , though the servers are rebooted, still the session is active

— Start — Inside the getAttribute — End —

7) Now change the URL to hit the second server, you will get the same output as

— Start — Inside the getAttribute — End —

Summary:

I believe this explains the basic  feature of using Conherence cache as Weblogic’s HttpSession holder. Please feel free to ping me about any questions with regard to this test case.

Posted in Uncategorized | Leave a comment

Having your own SOAP Client

Overview:

This blog is the outcome of my support experience with Oracle Weblogic Web service’s stack for quite sometime. After this exercise  we should understand, how Webservice layer talk to a client and also  how we can write our own java client to test a web service irrespective of the implementation i.e., web sphere or .net. Often I use this sample to explain to Customers that the issue we are dealing with is not specific to Weblogic.

Let’s start:

If you have a running Webservice already in any of the container, you can skip the following setup and move directly to “Getting the SOAP Request”

Start Weblogic:

Download and install ( Weblogic 10.3 ) and make sure you have the examples domain which comes along with Weblogic and start Weblogic from that domain. In my local box, I have started Weblogic(startWeblogic) from D:\oracle\bea103\wlserver_10.3\samples\domains\wl_server

Deploy a  sample Web service which comes with Weblogic:

For this example I am deploying jws_basic Webservice example which comes with Weblogic 10.3

steps:

1) Open a cmd and run setExamplesEnv.cmd from the domain

2) Go to the samples folder ( for ex, D:\oracle\bea103\wlserver_10.3\samples\server\examples\src\examples\webservices\jws_basic\simple)

3) and type “ant”, that compile and create all the necessary webservice stuff and deploy it to the samples domain.

4) And now if you go to your weblogic console, you should see a application deployed with the name “webservicesJwsSimpleEar”

5) Now if you run “ant run” on the same cmd you will see output from Web service “[java] Got result: Here is the message: ‘Hi there!'” , to make sure the sample web service we just deployed is working.

Getting the SOAP Request:

There are many ways you can get the SOAP request i) By enabling some debug flags in Weblogic, I am sure all the containers should have some debug flag which spit the SOAP Request ii) You can use any of existing tools SOAP UI or SOAP Sonar ..etc…and I prefer SOAP UI because its java based and it’s free. iii) Even you can form the particular SOAP request based on your WSDL, it is hard as complex object grows, but you can try it out 🙂

In this case, I am going to stick with SOAP UI as I want to provide a non container specific and a simple way to get the SOAP Request.

I am using SOPA UI 2.5, if you have installed please open SOAP UI and go to File and create a new project, after giving some name, add the WSDL URL for your project for ex, http://localhost:7001/jws_basic_simple/SimpleService?WSDL and click OK, that should pull all operations published by that WSDL and select one operation, in my case I just had one operation, it will take a string “mama” and returns “Here is the message: ‘mama'”

Copy the SOAP Request from that and that’s what we are going to try from our Java program.

Simple Java program which executes this SOAP Request for testing purpose:

TestingSOAP.java

——————

import java.io.*;

import java.net.*;

public class TestingSOAP

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

TestingSOAP.sayHello();
}

private static void sayHello() {
//our SOAP Request
/** <soapenv:Envelope xmlns:soapenv=”http://schemas.xmlsoap.org/soap/envelope/&#8221; xmlns:exam=”http://example.org”&gt;
<soapenv:Header/>
<soapenv:Body>
<exam:sayHello>
<exam:message>mama</exam:message>
</exam:sayHello>
</soapenv:Body>
</soapenv:Envelope>
*/

String message = “<soapenv:Envelope xmlns:soapenv=’http://schemas.xmlsoap.org/soap/envelope/&#8217; xmlns:exam=’http://example.org’>”+
“<soapenv:Header/>”+
“<soapenv:Body>”+
“<exam:sayHello>”+
“<exam:message>mama</exam:message>”+
“</exam:sayHello>”+
“</soapenv:Body>”+
“</soapenv:Envelope>”;

//make a simple HTTP URL connection

HttpURLConnection uc = null;
URL url = null;
byte[] data = message.getBytes();
try {
//Put your URL to connect to the server,in your case it should be “http://localhost:7001/jws_basic_simple/SimpleService?UserName=username&amp;Password=password&#8221;
url = new URL(“http://localhost:7001/jws_basic_simple/SimpleService&#8221;);
//Below the way you set the proxy details, just same as any HTTPURLConnection
//Properties sysProps = System.getProperties();
//sysProps.put( “proxySet”, “true” );
//sysProps.put( “proxyHost”, “proxy.myproxy.com”);
//sysProps.put( “proxyPort”, “3128” );
} catch (MalformedURLException e1) {
System.err.println(“URL EXCEPTION”);
e1.printStackTrace();
}
try {

uc = (HttpURLConnection) url.openConnection();

uc.setDoInput(true);
uc.setDoOutput(true);
uc.setUseCaches(false);
uc.setRequestProperty(“Content-Length”, ” ” + message.length());
uc.setRequestProperty(“Content-Type”, “text/xml; charset=UTF-8”);
//set SOAP Action –> in my case we don’t have one..so it is empty.
//uc.setRequestProperty(“SOAPAction”, “SOAPAction defined in the WSDL”);
uc.setRequestMethod(“POST”);
uc.connect();
DataOutputStream dos = new DataOutputStream(uc.getOutputStream());
dos.write(data, 0, data.length);
dos.flush();
dos.close();
BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String res = null;
while ((res = br.readLine()) != null)
System.out.println(res);
br.close();
} catch (IOException e) {
System.err.println(“From client: ” + e);
e.printStackTrace(System.out);
uc.disconnect();
System.err.println(“Disconnected…”);
}

}

}

Output:

Compiling and running the above java code should have the following results

Conclusion:

Considering we have tons of tools to run Web services, my intention wasn’t creating a new SOAP client tool but to explain how Web services works from the basic level, you can see, still it is a basic HttpURL Connection with SOAP message. All your understanding with Http/TCP layers are still applicable with Web services. If you are a weblogic admin or any Container admin, I hope this code would give a clear understanding to debug any Web service layer issues.

Please feel free to ask any questions associated with this blog.

Posted in Uncategorized | 2 Comments

Hello world!

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!

Posted in Uncategorized | 1 Comment