Sunday 11 March 2012

About Certification

Hi Friends,
Sorry for removing  the  certification materials from my blog.
If any one need information about OCJP (1Z0-851), OCPJWCD (1Z0-899) and SOA (1Z0-451) i will provide sufficient information to you feel free to post your queries


Srinivasulu Reddy Kummitha

Saturday 3 March 2012

Java Web Services


                                                     Contents

S.No Description Page No  
1 Web Services Example 1 – GetBalanceWS 5  
2 Web Services Example 2 – LendingRatesWS 12  
3 Web Services Example 3 – AccountBalWS (Securing Webservice) 19  
4 Web Services Example 4 – AccountBalCheckingWS (with Database) 29  
5 Web Services Example 5 – Calling External web service 60  
6 Publishing and Inquiring a Web service in JUDDI 66  
7 Dynamic invocation of all Lending rates web services 74


Web services Work Book

This document describes the basics of developing JAX web services using Apache Axis Server. Initially we create a web service program and later we create web service client programs that use the web service over a network, which is called “invoking” a web service. The client programs are Java Swings and JSP pages in web application.  
Axis Server:
Apache Axis is an open source, XML based Web service framework. It consists of a Java and a C++ implementation of the SOAP server, and various utilities and APIs for generating and deploying Web service applications. Using Apache Axis, developers can create interoperable, distributed computing applications. Axis is developed under the auspices of the Apache Software Foundation.
Axis for Java:
When using the Java versions of Axis there are two ways to expose Java code as web service. The easiest one is to use Axis native JWS (Java Web Service) files. Another way is to use custom deployment. Custom deployment enables you to customize resources that should be exposed as web service.
JWS Web service creation:
JWS files contain Java class source code that should be exposed as web service. The main difference between an ordinary java file and jws file is the file extension. Another difference is that jws files are deployed as source code and not compiled class files.
JWS web service deployment:
Once the Axis server is deployed, you need only to copy the jws file to the Axis directory on the server. This will work if you are using an Apache Tomcat container. In the case that you are using another web container, custom WAR archive creation will be required.
JWS web service access:
              JWS web service is accessible using the URL "http://localhost:8080/axis/service.jws". If you are running a custom configuration of Apache Tomcat or a different container, the URL might be different.
Custom deployed web service:
Custom web service deployment requires a specific deployment descriptor called WSDD (Web Service Deployment Descriptor) syntax. It can be used to specify resources that should be exposed as web services.
Automated generation of WSDL
When a Web service is exposed using Axis it will generate a WSDL file automatically when accessing the web service URL with ?WSDL appended to it.
Deploying Axis in Tomcat Web Server:
Install the Tomcat 5.5 web server.
Copy the folder axis-1_3 in axis-bin-1_3 into the webapps folder of Tomcat i.e. “C:\Program Files\Apache Software Foundation\Apache Tomcat 6.0.26\webapps”
Examples Covered:
   1. GetBalancWS
   2. LendingRatesWS
   3. AccountBalanceWS (Securing the webservice)
   4. AccountBalanceCheckingWS (Database Example)
   5. Publishing services in jUDDI.
 Software and resources:

Software Resource Version Required  
Java Development Kit (JDK) Version 1.5  
Web Server Tomcat 5.5, Axis 1.3
Web Services Example 1 - GetBalanceWS
Description:
This Web service example describes us, how to call the web service by client giving account number and retrieving constant balance as a result from the web service. Here the web service returns constant amount as a balance when the client giving any account number as input to the web service.
Input – output parameters:
Input – Account number (client program enters)
Output – Your balance in account 3018938  is: 500000
1. Creating a Web Service:
 Step 1: Create the following program and save it as “GetBalanceWS.java”.
GetBalanceWS.java:

public class GetBalanceWS
{
public String balance(String accno)
{
return("Your balance in account "+accno+" is "+500000);
}
}

The Axis web services are with the extension of .jws. Since .jws files can’t be compiled directly, we are creating java files initially to check for compilation errors and later we are saving it as .jws file.
 Step 2: Compile the created GetBalanceWS.java.
Step 3: If the program is compiled successfully, then save the compiled program with .jws extension. i.e, “GetBalanceWS.jws”.

2. Deploying a Web Service:
Step 4: Copy the “GetBalanceWS.jws” into the axis folder of Tomcat.

3. JWS webservice access
Step 5: Type the URL http://localhost:8080/axis/GetBalanceWS.jws in the web browser.
The following window will be displayed.

Now click on “Click to see the WSDL” to see WSDL file.

The URL http://localhost:8080/axis/GetBalanceWS.jws?wsdl is used to access the web service while writing a web service client program. The WSDL file contains complete information about the web service.
4. Creating a Web Service Client Programs:
The client program can be coded in different ways. Here we have given 2 way of creating the client program.
1. JSP:
Step 6: Write the following code and Save it as Balance.jsp
Balance.jsp
<html>
<body bgcolor="wheat">
<h1><center>Welcome to IDRBT</center></h1>
<form action="hello.jsp" method="POST" >
<table align="center" width="75%">
<tr>
<td width="33%"></td>
<td width="22%">Enter Your Account Number: </td>
<td width="78%">
<input type="text" name="accno"/></td>
<td>
<tr width="33%"><td/><td width="22%" align="center">
<input type="submit" name="Submit" value="Submit Account" />
<input type="reset" name="Reset" value="Reset form" />
</td>
</tr>
</table>
<p>

</p>
</form>
<%

%>
</body>
</html>


Step 7: Write the following code and Save it as hello.jsp
This program(hello.jsp) establishes the link between the web service(GetBalanceWS.jws) and client program(Balance.jsp).
hello.jsp
<html>
<head>
<title>Amount Details</title>
</head>
<body bgcolor="wheat" text="black">
<h1><center>Welcome to ABC Bank<center></h1>
<br/><br/>
<%@page import="javax.xml.rpc.Call,javax.xml.rpc.Service,javax.xml.rpc.JAXRPCException,javax.xml.namespace.QName,javax.xml.rpc.ServiceFactory, javax.xml.rpc.ParameterMode,javax.xml.rpc.ServiceException,javax.xml.rpc.*,com.sun.xml.rpc.client.*,com.sun.xml.rpc.soap.*, com.sun.xml.rpc.spi.tools.SOAPConstants,com.sun.xml.messaging.saaj.util.ByteInputStream,com.sun.xml.rpc.client.dii.BasicCall"
 %>
<%
String num = request.getParameter("accno");
%>
<h4><u>Your Account Details</u><br/><br/></h4>



<%! String qnameService="GetBalanceWSService";
     String qnamePort="GetBalanceWS";
     String BODY_NAMESPACE_VALUE="http://localhost:8080/axis/GetBalanceWS.jws";
     String ENCODING_STYLE_PROPERTY="javax.xml.rpc.encodingstyle.namespace.uri";
    String NS_XSD="http://www.w3.org/2001/XMLSchema";
    String URI_ENCODING="http://schemas.xmlsoap.org/soap/encoding";

%>

<%
try{
             
                javax.xml.rpc.ServiceFactory factory=javax.xml.rpc.ServiceFactory.newInstance();

                Service service=factory.createService(new QName(qnameService));
             
                QName port=new QName(qnamePort);
               
                Call call=service.createCall(port);
                call.setTargetEndpointAddress("http://localhost:8080/axis/GetBalanceWS.jws?wsdl");
call.setProperty(Call.SOAPACTION_USE_PROPERTY,new Boolean(true));
                call.setProperty(Call.SOAPACTION_URI_PROPERTY, "");
                call.setProperty(Call.ENCODINGSTYLE_URI_PROPERTY,"");
               // call.setProperty(Call.ENCODING_STYLE_PROPERTY,URI_ENCODING);
                call.setProperty(Call.OPERATION_STYLE_PROPERTY, "rpc");
                QName QNAME_TYPE_STRING=new QName(NS_XSD,"string");
               // call.setProperty(Call.OPERATION_STYLE_PROPERTY, "document");
                call.setReturnType(QNAME_TYPE_STRING);

                call.setOperationName( new QName(BODY_NAMESPACE_VALUE,"balance"));
                call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);
                Object[] params={num};//account number passed as argument
             
                String result=(String)call.invoke(params);
out.println(result);
             
%>

<%
        }
        catch(Exception e){
            out.println("Ramesh! There is an Exception Occured");
out.println(e);
            e.printStackTrace();}
%>

</body>
</html>
Step 8: Copy the two client programs “Balance.jsp” and “hello.jsp” into the axis folder of Tomcat.
Step 9:  Open the browser and type the following URL.
http://localhost:8080/axis/Balance.jsp


Step 10: Enter the Account Number and submit it.

Step 11: Balance is displayed as follows.

2. Java Swings:
Step 12: Create a file with the following code and Save it as GetBalance.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/*import javax.xml.rpc.Call;
import javax.xml.rpc.Service;
//import javax.xml.rpc.JAXRPCException;
/*import javax.xml.rpc.ServiceFactory;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.ServiceException;*/
import javax.xml.rpc.*;
import javax.xml.namespace.QName;
import com.sun.xml.rpc.client.*;
import com.sun.xml.rpc.soap.*;
import com.sun.xml.rpc.spi.tools.SOAPConstants;
import com.sun.xml.messaging.saaj.util.ByteInputStream;
import com.sun.xml.rpc.client.dii.BasicCall;
public class GetBalance
{
     String qnameService="DBBalanceService";
     String qnamePort="DBBalance";
     String BODY_NAMESPACE_VALUE="http://localhost:8080/axis/DBBalance.jws";
     String ENCODING_STYLE_PROPERTY="javax.xml.rpc.encodingstyle.namespace.uri";
    String NS_XSD="http://www.w3.org/2001/XMLSchema";
    String URI_ENCODING="http://schemas.xmlsoap.org/soap/encoding";


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

JFrame f=new JFrame();
JLabel label1=new JLabel("Enter your Account Number here: ");


final JTextField text1=new JTextField(30);
//final JTextField text2=new JTextField(20);
final JLabel label2=new JLabel();
JButton button=new JButton("Invoke");
JPanel p=new JPanel(new GridLayout(4,2));
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
String num=text1.getText();
javax.xml.rpc.ServiceFactory factory=javax.xml.rpc.ServiceFactory.newInstance();
GetBalance gb=new GetBalance();
Service service=factory.createService(new QName(gb.qnameService));
QName port=new QName(gb.qnamePort);
Call call=service.createCall(port);
call.setTargetEndpointAddress("http://localhost:8080/axis/GetBalanceWS.jws?wsdl");
call.setProperty(Call.SOAPACTION_USE_PROPERTY,new Boolean(true));
call.setProperty(Call.SOAPACTION_URI_PROPERTY, "");
call.setProperty(Call.ENCODINGSTYLE_URI_PROPERTY,"");
call.setProperty(Call.OPERATION_STYLE_PROPERTY, "rpc");
QName QNAME_TYPE_STRING=new QName(gb.NS_XSD,"string");
call.setReturnType(QNAME_TYPE_STRING);
call.setOperationName( new QName(gb.BODY_NAMESPACE_VALUE,"balance"));
call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);
Object[] params={num};
String result=(String)call.invoke(params);
System.out.println(result);
label2.setText(result);
}//end of try
catch(Exception ex)
{
System.out.println(ex);
}//end of catch
}
});
        p.add(label1);
        p.add(text1);
        p.add(label2);
       // p.add(text2);
        p.add(button);
        f.add(p);
        f.setVisible(true);
        f.pack();

}
}



Step 13: Compile and Run the above program in command prompt.
>javac GetBalance.java
>java GetBalance










Web Services Example 2 - LendingRatesWS
Description:
In this example, we invoke the web service which gives different lending rates offered by the bank. The client program never passes any input parameter to the web service.
Input – output parameters:
Input – Nothing
            Output – Different Lending Rates.
1. Creating a Web Service:
Step 1: Create the following program and save it as “GetRates.java”.
GetRates.java
public class GetRates
{
public String getPLR(String str)
{
return "10.25%";
}
public String  getHLR(String str)
{
return "9.5%";
}
public String getPeLR(String str)
{
return "11.25%";
}
public String getVeLR(String str)
{
return "13.25%";
}

public String getName(String str){
return "HCU BANK";   }
}
Step 2: Compile the created GetRates.java.
Step 3: If the program is compiled successfully, then save the compiled program with .jws extension. i.e,“GetRates.jws”.
2. Deploying a Web Service:
Step 4: Copy the “GetRates.jws” into the axis folder of Tomcat.
3. JWS web service access
Step 5: Type the URL http://localhost:8080/axis/GetRates.jws the web browser.
The following window will be displayed.

Now click on “Click to see the WSDL” to see WSDL file.

4. Creating a Web Service Client Program:
1. JSP
Step 6: Write the following code and Save it as GetRates.jsp
GetRates.jsp:
<html>
<head>
<title>Amount Details</title>
</head>
<body bgcolor="white" text="blue">
<h1><center>Welcome to Our Bank<center></h1>
<br/><br/>
<%@page import="javax.xml.rpc.Call,javax.xml.rpc.Service,javax.xml.rpc.JAXRPCException,javax.xml.namespace.QName,javax.xml.rpc.ServiceFactory,javax.xml.rpc.ParameterMode,javax.xml.rpc.ServiceException,javax.xml.rpc.*,com.sun.xml.rpc.client.*,com.sun.xml.rpc.soap.*,com.sun.xml.rpc.spi.tools.SOAPConstants,com.sun.xml.messaging.saaj.util.ByteInputStream,com.sun.xml.rpc.client.dii.BasicCall"
 %>
 <%! String qnameService="GetRatesService";
     String qnamePort="GetRates";
     String BODY_NAMESPACE_VALUE="http://localhost:8080/axis/GetRates.jws";
     String ENCODING_STYLE_PROPERTY="javax.xml.rpc.encodingstyle.namespace.uri";
     String NS_XSD="http://www.w3.org/2001/XMLSchema";
     String URI_ENCODING="http://schemas.xmlsoap.org/soap/encoding";
%>
<%
try{
 javax.xml.rpc.ServiceFactory factory=javax.xml.rpc.ServiceFactory.newInstance();
                //ServiceFactory factory=ServiceFactory.newInstance();
                Service service=factory.createService(new QName(qnameService));
                QName port=new QName(qnamePort);
                Call call=service.createCall(port);
                call.setTargetEndpointAddress("http://localhost:8080/axis/GetRates.jws?wsdl");
                call.setProperty(Call.SOAPACTION_USE_PROPERTY,new Boolean(true));
                call.setProperty(Call.SOAPACTION_URI_PROPERTY, "");
                call.setProperty(Call.ENCODINGSTYLE_URI_PROPERTY,"");
               // call.setProperty(Call.ENCODING_STYLE_PROPERTY,URI_ENCODING);
                call.setProperty(Call.OPERATION_STYLE_PROPERTY, "rpc");
                QName QNAME_TYPE_STRING=new QName(NS_XSD,"string");
               // call.setProperty(Call.OPERATION_STYLE_PROPERTY, "document");
                call.setReturnType(QNAME_TYPE_STRING);
   String[] params={""};
  String result="";
  call.removeAllParameters();
               call.setOperationName( new QName(BODY_NAMESPACE_VALUE,"getName"));
                call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);
                result=(String)call.invoke(params);
%><center><h2><i><%=result%> Rate are Displayed here</i></h2></center>
<table  align="center"       border="2"><th>PLR</th><th>HLR</th><th>PeLR</th><th>VeLR</th>
<tr>
<%
call.removeAllParameters();
call.setOperationName( new QName(BODY_NAMESPACE_VALUE,"getPLR"));
            call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);
             result=(String)call.invoke(params);
%>
<td> <%=result%> </td>
<%
call.removeAllParameters();
call.setOperationName( new QName(BODY_NAMESPACE_VALUE,"getHLR"));
            call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);
            result=(String)call.invoke(params);
%>
<td> <%=result%> </td>
<%
call.removeAllParameters();
call.setOperationName( new QName(BODY_NAMESPACE_VALUE,"getPeLR"));
            call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);
            result=(String)call.invoke(params);
%>
<td> <%=result%> </td>
<%          
call.removeAllParameters();
call.setOperationName( new QName(BODY_NAMESPACE_VALUE,"getVeLR"));
            call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);
            result=(String)call.invoke(params);
%>
<td> <%=result%> </td></table>
<%
}
catch(Exception e)
{
            out.println("There is an Exception ");
            e.printStackTrace();
}
%>
</body>
</html>
Step 7: Copy the client program “GetRates.jsp” into the axis folder of Tomcat.
Step 8:  Open the browser and type the following URL. http://localhost:8080/axis/GetRates.jsp


The Lending Rates are displayed as follows.


2. Java Swings
Step 8: Write the following code and save it as GetRatesSwing.java

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.xml.rpc.Service;
import javax.xml.rpc.*;
import javax.xml.namespace.QName;
import com.sun.xml.rpc.client.*;
import com.sun.xml.rpc.soap.*;
import com.sun.xml.rpc.spi.tools.SOAPConstants;
import com.sun.xml.messaging.saaj.util.ByteInputStream;
import com.sun.xml.rpc.client.dii.BasicCall;
public class GetRatesSwing
{
     String qnameService="GetRatesService";
     String qnamePort="GetRates";
     String BODY_NAMESPACE_VALUE="http://localhost:8080/axis/GetRates.jws"; String ENCODING_STYLE_PROPERTY="javax.xml.rpc.encodingstyle.namespace.uri";
String NS_XSD="http://www.w3.org/2001/XMLSchema";
    String URI_ENCODING="http://schemas.xmlsoap.org/soap/encoding";
public static void main(String[] args) throws Exception
{

JFrame f=new JFrame();
JLabel label1=new JLabel("PLR of the ABC Bank displayed here");
final JLabel label2=new JLabel();
JButton button=new JButton("Invoke");
JPanel p=new JPanel();//new GridLayout(4,2));
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
javax.xml.rpc.ServiceFactory factory=javax.xml.rpc.ServiceFactory.newInstance();
GetBalance gb=new GetBalance();
Service service=factory.createService(new QName(gb.qnameService));
QName port=new QName(gb.qnamePort);
Call call=service.createCall(port);
call.setTargetEndpointAddress("http://localhost:8080/axis/GetRates.jws?wsdl");
call.setProperty(Call.SOAPACTION_USE_PROPERTY,new Boolean(true));
call.setProperty(Call.SOAPACTION_URI_PROPERTY, "");
call.setProperty(Call.ENCODINGSTYLE_URI_PROPERTY,"");
call.setProperty(Call.OPERATION_STYLE_PROPERTY, "rpc");
QName QNAME_TYPE_STRING=new QName(gb.NS_XSD,"string");
call.setReturnType(QNAME_TYPE_STRING);
call.setOperationName( new QName(gb.BODY_NAMESPACE_VALUE,"getPLR"));
call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);
Object[] params={""};
String result="PLR=";
result+=(String)call.invoke(params);
call.removeAllParameters();
           call.setReturnType(QNAME_TYPE_STRING);
call.setOperationName( new QName(gb.BODY_NAMESPACE_VALUE,"getHLR"));
call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);
           result+="\n  HLR="+(String)call.invoke(params);
call.removeAllParameters();
call.setReturnType(QNAME_TYPE_STRING);
call.setOperationName( new QName(gb.BODY_NAMESPACE_VALUE,"getPeLR"));
call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);
            result+="\n  PeLR="+(String)call.invoke(params);
call.removeAllParameters();
call.setReturnType(QNAME_TYPE_STRING);
call.setOperationName( new QName(gb.BODY_NAMESPACE_VALUE,"getVeLR"));
call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);
result+="\n  VeLR="+(String)call.invoke(params);
label2.setText(result);
System.out.println(result);

}//end of try
catch(Exception ex)
{
System.out.println(ex);
}//end of catch
}
});
 p.add(label1);
     p.add(label2);
     p.add(button);
     f.add(p);
     f.setVisible(true);
     f.pack();
}
}
Step 9: Run the GetRatesSwing.java
javac GetRates.java
java GetRates



Click on “Invoke”.





Web Services Example 3 – AccountBalWS (Securing Webservice)
Description:
This web service describes us how to secure the Account Number provided by user at client application.

The Account number is encrypted using DES Encryption algorithm at client side. And Pass encrypted text to the web service, and then web service decrypts the Account number and returns the result in Encrypted form. The client program decrypts the encrypted result returned by the web service.
Input – output parameters:
Input – Account number Encrypted Form
Output – Decrypted Account Number i.e. Plain Text
1. Creating a Web Service:
Step 1: Create the following program and save it as “DesEncrypter.java”.
import javax.crypto.*;
import java.security.*;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.UnsupportedEncodingException;
public class DesEncrypter
{
    Cipher ecipher;
    Cipher dcipher;
    File f=new File("C:\\keyfile.txt");
   public String getResult(String enstr)
  {
DesEncrypter de=new DesEncrypter();
String decry=de.decrypt(enstr);
String str1="Amount in "+decry+"is Rs 25434";
String result=de.encrypt(str1);
return result;
//return "Decrypted Response"+decry;
}
public SecretKey generateKey() throws NoSuchAlgorithmException {
    KeyGenerator keygen = KeyGenerator.getInstance("DES");
    return keygen.generateKey();
  }
  /** Save the specified TripleDES SecretKey to the specified file */
public void writeKey(SecretKey key, File f) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException
{
 SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DES");
 DESKeySpec keyspec = (DESKeySpec) keyfactory.getKeySpec(key,
        DESKeySpec.class);
 byte[] rawkey = keyspec.getKey();
    FileOutputStream out = new FileOutputStream(f);
    out.write(rawkey);
    out.close();
  }
public   SecretKey readKey(File f) throws IOException, NoSuchAlgorithmException,  InvalidKeyException,
      InvalidKeySpecException {
        DataInputStream in = new DataInputStream(new FileInputStream(f));
    byte[] rawkey = new byte[(int) f.length()];
    in.readFully(rawkey);
    in.close();
DESKeySpec keyspec = new DESKeySpec(rawkey);
    SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DES");
    SecretKey key1 = keyfactory.generateSecret(keyspec);
    return key1;
  }
public DesEncrypter()
{
        try {
            SecretKey key=readKey(f);
 System.out.println("*******************************"+key);
            ecipher = Cipher.getInstance("DES");
            dcipher = Cipher.getInstance("DES");
            ecipher.init(Cipher.ENCRYPT_MODE, key);
            dcipher.init(Cipher.DECRYPT_MODE, key);
        } catch (javax.crypto.NoSuchPaddingException e) {
        } catch (java.security.NoSuchAlgorithmException e) {
        } catch (java.security.InvalidKeyException e) {
        }catch(IOException e){
System.out.println("Exception in reading key form the file"+e);
}
        catch(java.security.spec.InvalidKeySpecException e){}
    }
 public String encrypt(String str)
{
        try {
            // Encode the string into bytes using utf-8
            byte[] utf8 = str.getBytes("UTF8");
            // Encrypt
            byte[] enc = ecipher.doFinal(utf8);
            // Encode bytes to base64 to get a string
            return new sun.misc.BASE64Encoder().encode(enc);
        } catch (javax.crypto.BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        } catch (java.io.IOException e) {
        }
        return null;
    }
public String decrypt(String str)
{
        try {
              byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
              byte[] utf8 = dcipher.doFinal(dec);
              return new String(utf8, "UTF8");
        } catch (javax.crypto.BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        } catch (java.io.IOException e) {
        }
        return null;
    }
}
Step 2: Compile the created DesEncrypter.java.
Step 3: If the program is compiled successfully, then save the compiled program with .jws extension. i.e,“DesEncrypter.jws”.
2. Deploying a Web Service:
Step 4: Copy the “DesEncrypter.jws” into the axis folder of Tomcat.
3. JWS web service access
Step 5: Type the URL http://localhost:8080/axis/DesEncrypter.jws the web browser.
The following window will be displayed.

Now click on “Click to see the WSDL” to see WSDL file.

4. Creating a Web Service Client Program:
1. JSP
Step 6: Write the following code and Save it as Encrypt.jsp
Encrypt.jsp:
<html>
<head>
<title>Amount Details</title>
</head>
<body bgcolor="white" text="blue">
<h1><center>Welcome to ABC Bank<center></h1>
<br/><br/>
<%@page import="javax.xml.rpc.Call,javax.xml.rpc.Service,javax.xml.rpc.JAXRPCException,javax.xml.namespace.QName,javax.xml.rpc.ServiceFactory,javax.xml.rpc.ParameterMode,javax.xml.rpc.ServiceException,javax.xml.rpc.*,com.sun.xml.rpc.client.*,com.sun.xml.rpc.soap.*,com.sun.xml.rpc.spi.tools.SOAPConstants,com.sun.xml.messaging.saaj.util.ByteInputStream,com.sun.xml.rpc.client.dii.BasicCall"
 %>
<h4><u>Your Account Details</u><br/><br/></h4>

<%
String num=request.getParameter("accno");
%>
<%! String qnameService="DesEncrypterService";
     String qnamePort="DesEncrypter";
     String BODY_NAMESPACE_VALUE="http://localhost:8080/axis/DesEncrypter.jws";
     String ENCODING_STYLE_PROPERTY="javax.xml.rpc.encodingstyle.namespace.uri";
    String NS_XSD="http://www.w3.org/2001/XMLSchema";
    String URI_ENCODING="http://schemas.xmlsoap.org/soap/encoding";
%>
<%
try
{
javax.xml.rpc.ServiceFactory        factory=javax.xml.rpc.ServiceFactory.newInstance();
           Service service=factory.createService(new QName(qnameService));
           QName port=new QName(qnamePort);
           Call call=service.createCall(port);
call.setTargetEndpointAddress("http://localhost:8080/axis/DesEncrypter.jws?wsdl");
call.setProperty(Call.SOAPACTION_USE_PROPERTY,new Boolean(true));
call.setProperty(Call.SOAPACTION_URI_PROPERTY, "");
                call.setProperty(Call.ENCODINGSTYLE_URI_PROPERTY,"");
                call.setProperty(Call.OPERATION_STYLE_PROPERTY, "rpc");
                QName QNAME_TYPE_STRING=new QName(NS_XSD,"string");
                call.setReturnType(QNAME_TYPE_STRING);
call.setOperationName( new QName(BODY_NAMESPACE_VALUE,"encrypt"));
   call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);
                String[] params={num};//account number passed as argument
                String cipher=(String)call.invoke(params);
%>
<table align="center" border="1">
<td><tr>Encrypted Account No:<%=cipher%><br></tr></td>
<%
call.removeAllParameters();
call.setOperationName(new QName(BODY_NAMESPACE_VALUE,"getResult"));
call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);
String[] encryptedResult={cipher};
String resp=(String)call.invoke(encryptedResult);
%>
<td><tr>Encrypted Response is:<%=resp%><br></tr></td>
<%
call.removeAllParameters();
call.setOperationName(new QName(BODY_NAMESPACE_VALUE,"decrypt"));
call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);
String[] params2={resp};
String original=(String)call.invoke(params2);
out.println("Decrypted value is:"+original);
        }
        catch(Exception e){
            out.println("There is an Exception ");
out.println(e);
            e.printStackTrace();}
%>
</table>
</body>
</html>
Step 7: Create a file with the following code and Save it as GetAccno.jsp
GetAccno.jsp:
<html>
<body bgcolor="white">
<h1>Welcome to IDRBT</h1>
<form action="Encrypt.jsp" method="POST" >
<table width="75%">
<tr>
<td width="48%">Enter your Account Number here</td>
<td width="52%">
<input type="text" name="accno" /></td>
</tr>
</table>
<p>
<input type="submit" name="Submit" value="Submit Account" />
<input type="reset" name="Reset" value="Reset form" />
</p>
</form>
</body>
</html>
Step 8: Open the browser and type the following URL http://localhost:8080/axis/GetAccno.jsp


Step 9: Enter the Account number and submit it.

Step 10: The Encrypted and Decrypted Result is displayed as follows.



2. Java Swings
Step 11: Write the following code and save it as EncryptSwing.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.xml.rpc.Service;
import javax.xml.rpc.*;
import javax.xml.namespace.QName;
import com.sun.xml.rpc.client.*;
import com.sun.xml.rpc.soap.*;
import com.sun.xml.rpc.spi.tools.SOAPConstants;
import com.sun.xml.messaging.saaj.util.ByteInputStream;
import com.sun.xml.rpc.client.dii.BasicCall;
public class EncryptSwing
{
     String qnameService="DesEncrypterService";
     String qnamePort="DesEncrypter";
     String BODY_NAMESPACE_VALUE="http://localhost:8080/axis/DesEncrypter.jws";
     String ENCODING_STYLE_PROPERTY="javax.xml.rpc.encodingstyle.namespace.uri";
     String NS_XSD="http://www.w3.org/2001/XMLSchema";
     String URI_ENCODING="http://schemas.xmlsoap.org/soap/encoding";
public static void main(String[] args) throws Exception
{
JFrame f=new JFrame();
JLabel label1=new JLabel("Enter your Account Number here: ");
final JTextField text1=new JTextField(30);
final JTextArea area=new JTextArea(20,20);
JButton button=new JButton("Invoke");
JPanel p=new JPanel();//(new GridLayout(2,2));
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try{
String num=text1.getText();
javax.xml.rpc.ServiceFactory factory=javax.xml.rpc.ServiceFactory.newInstance();
GetBalance gb=new GetBalance();
Service service=factory.createService(new QName(gb.qnameService));
          QName port=new QName(gb.qnamePort);
          Call call=service.createCall(port);
       call.setTargetEndpointAddress("http://localhost:8080/axis/DesEncrypter.jws?wsdl");
call.setProperty(Call.SOAPACTION_USE_PROPERTY,new Boolean(true));
call.setProperty(Call.SOAPACTION_URI_PROPERTY, "");
call.setProperty(Call.ENCODINGSTYLE_URI_PROPERTY,"");
call.setProperty(Call.OPERATION_STYLE_PROPERTY, "rpc");
QName QNAME_TYPE_STRING=new QName(gb.NS_XSD,"string");
call.setReturnType(QNAME_TYPE_STRING);
call.setOperationName( new QName(gb.BODY_NAMESPACE_VALUE,"encrypt"));
call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);
Object[] params={num};
String cipher=(String)call.invoke(params);
String ct="\nEncrypted Account Number is:  "+cipher;
area.setText(cipher);
call.removeAllParameters();
call.setReturnType(QNAME_TYPE_STRING);
call.setOperationName(new QName(gb.BODY_NAMESPACE_VALUE,"getResult"));
call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);
String[] encryptedResult={cipher};
String resp=(String)call.invoke(encryptedResult);
String rct="\nEncrypted text form server   :  "+resp;
call.removeAllParameters();
call.setReturnType(QNAME_TYPE_STRING);
call.setOperationName(new QName(gb.BODY_NAMESPACE_VALUE,"decrypt"));
call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);
String[] params2={resp};
String original=(String)call.invoke(params2);
String rt="\nDecrypted value is:"+original;
String result=ct+rct+rt;
area.setText(result);
}//end of try
catch(Exception ex){ System.out.println(ex); }//end of catch
}
});
p.add(label1);
          p.add(text1);
          p.add(area);
        p.add(button);
        f.add(p);
        f.setVisible(true);
        f.pack();
    }}
Step 12: Run the EncryptSwing.java
javac EncryptSwing.java
java EncryptSwing


























Web Services Example 4 – AccountBalCheckingWS (with Database)
Description:
This Example describes us how to access multiple web services into client application (who seeks the services).Here multiple web services towards multiple banks
That is, integrating different organizations into one system.
For example bellow is the snapshot will clear understanding of this example:



For the above figure, assuming client application is IDRBT. This client consuming different bank web services. Above, the Client and web services having individual databases.
Flow of the above Diagram:
User logins with username and password at client: IDRBT (Assuming IDRBT database having user’s login details)
After Login a window is displayed showing the User Account Number’s of various banks.
If the user clicks any one of the Account Number,
(Suppose user clicks on SBI account number, SBI web service is accessed into Client Application and returns the transaction details of his SBI account to the client application)
The Balance details and other transaction details of which bank account he clicked are displayed through his account number.
 Input – output parameters:
Input – User Name and Password and Clicks on any bank account number
Output – Transaction Details of which bank he clicked
  In this example we use MySql database to create Account Table and Transactions Table.
1. Creating Database:
My SQL Commands:
Step 1: Account:

create table account(accno varchar(11),name varchar(20),balance int(6),bankname varchar(10),password varchar(10));

insert into account values(‘30856349329’,’Vijay’,50000,’SBI’,’vijay123’);
insert into account values(‘30189393346’,’Ramesh’,10000,’SBI’,’ramesh’);
insert into account values(‘30189546981’,’Vinayak’,30000,’SBI’,’vinayak’);
insert into account values(‘41204568231’,’ramesh’,12000,’PNB’,’ramesh’);

Step 2: Transactions:
create table transactions(accno varchar(11),date date,amount int(6), transaction_id varchar(5), transaction_type varchar(10));

insert into transactions values(‘30856349329’,curdate(),5000,’T1221’,’deposit’);
insert into transactions values(‘30189393346’,curdate(),2000,’T1222’,’deposit’);

Step 3: Pnbtrans:
create table pnbtrans(accno varchar(12), date date, amount int(6), transaction_id varchar(5), transaction_type varchar(10));

insert into pnbtrans values(‘41204568231’,curdate(),12000,’T231’,’credit’);




2. Creating a Web Service:
Step 3: Create the following program and save it as “MSConn.java”.
import java.sql.*;
import java.sql.SQLException;
public class  MSConn
{
   String s;
    String url,url2,url1;
    String usr,pwd,rs;
        public java.sql.ResultSet rs1;
    public String T;
    public java.sql.Statement stmt;
    public java.sql.Connection conn;
    int accno;
String result="";
public String getBalance(String username,String password)
{
usr=username;
pwd=password;

try{
url1="com.mysql.jdbc.Driver";
url="jdbc:mysql://localhost/mysql";
Class.forName(url1);
conn = DriverManager.getConnection(url,"root","root");
stmt = conn.createStatement();
String Query = "SELECT * from account where name='"+usr+"' and password='"+pwd+"'";
                rs1 = stmt.executeQuery(Query);
while (rs1.next())
{
String s5 = rs1.getString("accno");
String s6=rs1.getString("name");
String s7 = rs1.getString("bankname");
String T1 = s5 + "//" + s6 + "//" + s7;
result += T1+"$";
}
}
catch (ClassNotFoundException e)
{
result+=e.getMessage();
}

catch (SQLException e)
{
result+=e.getMessage();
}
return result;
}
}
Step 4: Compile the created MSConn.java.
Step 5: If the program is compiled successfully, then save the compiled program with .jws extension. i.e,“MSConn.jws”.
Step 6: Copy the MSConn.jws file into Axis folder of Tomcat and type the url “http://localhost:8080/axis/MSConn.jws”in the browser.
Step  7: Create the following program and save it as “MSTransactions.java”.


import java.sql.*;
import java.sql.SQLException;
public class  MSTransactions
{
    String s;
    String url,url2,url1;
    String usr,pwd,rs;
   public java.sql.ResultSet rs1;
    public String T;
    public java.sql.Statement stmt;
    public java.sql.Connection conn;
    String accno;
String result="";
public String getTransactions(String acc)
{
accno=acc;

 try{
url1="com.mysql.jdbc.Driver";
url="jdbc:mysql://localhost/mysql";
              Class.forName(url1);
          conn = DriverManager.getConnection(url,"root","root");
stmt = conn.createStatement();
String Query = "SELECT * from  transactions where accno='"+accno+"'";
rs1 = stmt.executeQuery(Query);
while (rs1.next())
{
int s5 = rs1.getInt("amount");
String s6=rs1.getString("date");
String s7 = rs1.getString("transaction_type");
String T1 = s5 + ";" + s6 + ";" + s7;
result += T1+"$";
}
}
catch (ClassNotFoundException e)
 {
result+=e.getMessage();
}
catch (SQLException e)
{
result+=e.getMessage();
}
return result;
}
}
Step 8: Compile the created MSTransactions.java.
Step 9: If the program is compiled successfully, then save the compiled program with .jws extension. i.e,“MSTransactions.jws”.


Step 10:  Write the following program and save it as PNBConn.java

import java.sql.*;
import java.sql.SQLException;
public class  PNBConn
{
   String s;
    String url,url2,url1;
    String usr,pwd,rs;
    public java.sql.ResultSet rs1;
    public String T;
    public java.sql.Statement stmt;
    public java.sql.Connection conn;
    int accno;
String result="";
public String getBalance(String username,String password)
{
usr=username;
pwd=password;
 try{
url1="com.mysql.jdbc.Driver";
url="jdbc:mysql://localhost/mysql";
Class.forName(url1);
conn = DriverManager.getConnection(url,"root","root");
stmt = conn.createStatement();
String Query = "SELECT * from pnbtrans  where name='"+usr+"' and password='"+pwd+"'";
rs1 = stmt.executeQuery(Query);
while (rs1.next())
{
String s5 = rs1.getString("accno");
String s6=rs1.getString("name");
String s7 = rs1.getString("bankname");
String T1 = s5 + "//" + s6 + "//" + s7;
result += T1+";";
}
}
 catch (ClassNotFoundException e)
{
result+=e.getMessage();
}
catch (SQLException e)
{
result+=e.getMessage();
}
return result;
}
}
Step 11: Compile the created PNBConn.java.
Step 12: If the program is compiled successfully, then save the compiled program with .jws extension. i.e,“PNBConn.jws”.
Step  13: Create the following program and save it as “PNBTransactions.java”.

import java.sql.*;
import java.sql.SQLException;

public class  PNBTransactions
{
String s;
    String url,url2,url1;
    String usr,pwd,rs;
   
    public java.sql.ResultSet rs1;
    public String T;
    public java.sql.Statement stmt;
    public java.sql.Connection conn;
    String accno;
String result="";
public String getTransactions(String acc)
{
accno=acc;

try{

url1="com.mysql.jdbc.Driver";
url="jdbc:mysql://localhost/mysql";

Class.forName(url1);

conn = DriverManager.getConnection(url,"root","root");
//result+="Connected" + conn;

stmt = conn.createStatement();
//result+="Create Statement is Executed";
String Query = "SELECT * from  pnbtrans where accno='"+accno+"'";

rs1 = stmt.executeQuery(Query);

while (rs1.next()) {
//result+="in While";
int s5 = rs1.getInt("amount");
//result+=s5;

String s6=rs1.getString("date");

String s7 = rs1.getString("transaction_type");

//accno=Integer.parseInt(s5);

String T1 = s5 + ";" + s6 + ";" + s7;
result += T1;

}
} catch (ClassNotFoundException e) {
result+=e.getMessage();
} catch (SQLException e) {
result+=e.getMessage();
}
return result;

}
}
Step 14: Compile the created PNBTransactions.java.
Step 15: If the program is compiled successfully, then save the compiled program with .jws extension. i.e,“PNBTransactions.jws”.
Step 16: Copy the MSConn.jws file into Axis folder of Tomcat and type the url “http://localhost:8080/axis/PNBTranctions.jws”in the browser.

2. Deploying a Web Service:
Step 12: Copy the “MSConn.jws” into the axis folder of Tomcat.
Step 13: Copy the “MSTransactions.jws” into the axis folder of Tomcat.
Step 14: Copy the “PNBConn.jws” into the axis folder of Tomcat.
Step 15: Copy the “PNBTransactions.jws” into the axis folder of Tomcat.

3. JWS web service access
Step 15: Type the URL http://localhost:8080/axis/MSConn.jws the web browser.
The following window will be displayed.


Now click on “Click to see the WSDL” to see WSDL file.



Step 16: Type the URL http://localhost:8080/axis/MSTransactions.jws the web browser.
The following window will be displayed.

Now click on “Click to see the WSDL” to see WSDL file.






Step 17: Type the URL http://localhost:8080/axis/PNBConn.jws the web browser.



Now click on “Click to see the WSDL” to see WSDL file.




Step 18: Type the URL http://localhost:8080/axis/PNBTransactions.jws the web browser.

Now click on “Click to see the WSDL” to see WSDL file.

5. Creating a Web Service Client Program:
Step 18: Write the following code and Save it as Enquiry.jsp

Enquiry.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
            String appPath = request.getContextPath();
%>
<html>
    <head>
        <script type="text/javascript">
            function fnValidate(){
                if(document.loginform.all['username'].value == ""){
                    alert("Please enter a valid username");
                    document.loginform.username.focus();
                    return false;
                }
                if(document.loginform.passWd.value == -1){
                    alert("Please enter the password");
                    document.loginform.passWd.focus();
                    return false;
                }
                return true;
            }
            function fnSubmit(){
                if(fnValidate()){
                    alert("coming here");
                    document.loginform.action ="AccountSearch.jsp";
                    document.loginform.submit();
                }
            }
        </script>
        <style>
        </style>
    </head>
    <body>
<link rel="shortcut icon" href="idrbt.ico"/>
        <form name="loginform" method="post" action="DBEnquiry.jsp" onSubmit=   "return fnValidate();">
            <table width="320px" border=0 align="center" style="background-color:#3399FF;">

                <tr>
                    <td colspan=2 align="center" style="font-weight:bold;font-size:20pt;" align="center">Account Details</td>
                </tr>
       
       <tr>
                    <td colspan=2>&nbsp;</td>

                </tr>

                <tr>
                    <td style="font-size:12pt; color:#FFFFFF"  align="right">User Name</td>
                    <td align="left"><input type="text" name="username" value=""  size="18"></td>
                </tr>
                <tr>
                    <td style="font-size:12pt;color:#FFFFFF" align="right">Password </td>
                    <td align="left">
                        <input type=password name="passwd" maxlength="10" size="18">
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" name="submit" value="Get Details"></td>
                </tr>
            </table>
        </form>
    </body>
</html>
Step 19: Write the following code and save it as DBEnquiry.jsp
<html>
<head>
<title>Amount Details</title>
</head>
<body>
<link rel="shortcut icon" href="idrbt.ico"/>
        <h2 align="center">Account Deatils</h2>
        <table  border="1" method="post" action="" align= "center" bgcolor="yellow" width = 50%>
            <tr>
                <th align= center bgcolor="#3399FF" style="color:#FFFFFF">
                    <b>Account Number</b>
                </th>
                <th align= center bgcolor="#3399FF" style="color:#FFFFFF" >
                    <b>User Name</b>
                </th>
                <th align= center bgcolor="#3399FF" style="color:#FFFFFF">
                    <b> Bank Name </b>
                </th>
<th align= center bgcolor="#3399FF" style="color:#FFFFFF">
                    <b> Description </b>
                </th>
            </tr>
<%@page import="javax.xml.rpc.Call,javax.xml.rpc.Service,javax.xml.rpc.JAXRPCException,javax.xml.namespace.QName,javax.xml.rpc.ServiceFactory, javax.xml.rpc.ParameterMode,javax.xml.rpc.ServiceException,javax.xml.rpc.*,com.sun.xml.rpc.client.*,com.sun.xml.rpc.soap.*, com.sun.xml.rpc.spi.tools.SOAPConstants,com.sun.xml.messaging.saaj.util.ByteInputStream,com.sun.xml.rpc.client.dii.BasicCall"
 %>
<%
//String name="Ramesh";
//String password="ramesh";
String name=request.getParameter("username");
String password=request.getParameter("passwd");
%>


<%! String qnameService="MSConnService";
     String qnamePort="MSConn";
     String BODY_NAMESPACE_VALUE="http://localhost:8080/axis/MSConn.jws";
     String ENCODING_STYLE_PROPERTY="javax.xml.rpc.encodingstyle.namespace.uri";
    String NS_XSD="http://www.w3.org/2001/XMLSchema";
    String URI_ENCODING="http://schemas.xmlsoap.org/soap/encoding";
String str,tkn,bname,accno,url;
%>

<%
try{

                javax.xml.rpc.ServiceFactory factory=javax.xml.rpc.ServiceFactory.newInstance();
Service service=factory.createService(new QName(qnameService));
QName port=new QName(qnamePort);
               
                Call call=service.createCall(port);
                call.setTargetEndpointAddress("http://localhost:8080/axis/MSConn.jws");
call.setProperty(Call.SOAPACTION_USE_PROPERTY,new Boolean(true));
                call.setProperty(Call.SOAPACTION_URI_PROPERTY, "");
                call.setProperty(Call.ENCODINGSTYLE_URI_PROPERTY,"");
               // call.setProperty(Call.ENCODING_STYLE_PROPERTY,URI_ENCODING);
                call.setProperty(Call.OPERATION_STYLE_PROPERTY, "rpc");
                QName QNAME_TYPE_STRING=new QName(NS_XSD,"string");
               // call.setProperty(Call.OPERATION_STYLE_PROPERTY, "document");
                call.setReturnType(QNAME_TYPE_STRING);
call.setOperationName( new QName(BODY_NAMESPACE_VALUE,"getBalance"));
                call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);
call.addParameter("String_2",QNAME_TYPE_STRING, ParameterMode.IN);
                Object[] params={name,password};//account number passed as argument
String result=(String)call.invoke(params);
//out.println(result);
//java.util.StringTokenizer t = new java.util.StringTokenizer(result,"//");
java.util.StringTokenizer d=new java.util.StringTokenizer(result,"$");
//changes.....

while(d.hasMoreTokens()){
int x=0;
tkn=d.nextToken();
java.util.StringTokenizer t = new java.util.StringTokenizer(tkn,"//");
//changes...
%>

            <tr>
             <%
int i = 0;
while (t.hasMoreTokens()) {
String str = t.nextToken();
            %>
                <% if (i == 0) {
accno=str;
                %>
<td align= center>
<%=str%>

</td>
<% }
                %>
<% if (i == 1) {
                %>

<td align= center>
<%=str %>
</td>
                <%
}
                %>
                <% if (i == 2) {
bname=str;
%>
<td align= center>

<%=str %>
</td>
<td align= center>
<%
if(bname.equals("SBI"))
url="MSTransactions.jsp?accno="+accno;
if(bname.equals("PNB"))
url="PNBTransactions.jsp?accno="+accno;


%>
<a  href=<%=url%>>Transaction details</a>
</td>
                <%
} //End of if
                %>
                <%
                i++;
                } //end of while;
%>
</tr></br>
<%

}//End of outer while loop
            }  //end of try
           
            catch(Exception e){ System.out.println("Error occured");}
                %>
            </tr>
            <%--
            }--%>

        </table>
    </body>
</html>

Step 20: Write the following code and Save it as MSTransactions.jsp
MSTransactions.jsp:
<html>
<head>
<title>Amount Details</title>
</head>
<body>
<link rel="shortcut icon" href="SBI_Logo.ico"/>
        <h2 align="center">SBI Transaction Deatils</h2>
        <table  border="1" method="post" action="" align= "center" bgcolor="yellow" width = 50%>
            <tr>
                <th align= center bgcolor="#3399FF" style="color:#FFFFFF">
                    <b>Amount</b>
                </th>
                <th align= center bgcolor="#3399FF" style="color:#FFFFFF" >
                    <b>Date</b>
                </th>
                <th align= center bgcolor="#3399FF" style="color:#FFFFFF">
                    <b>Type of Transaction</b>
                </th>
            </tr>
<%@page import="javax.xml.rpc.Call,javax.xml.rpc.Service,javax.xml.rpc.JAXRPCException,javax.xml.namespace.QName,javax.xml.rpc.ServiceFactory,javax.xml.rpc.ParameterMode,javax.xml.rpc.ServiceException,javax.xml.rpc.*,com.sun.xml.rpc.client.*,com.sun.xml.rpc.soap.*,com.sun.xml.rpc.spi.tools.SOAPConstants,com.sun.xml.messaging.saaj.util.ByteInputStream,com.sun.xml.rpc.client.dii.BasicCall"
 %>
<%
String accno=request.getParameter("accno");
%>
<%! String qnameService="MSTransactionsService";
     String qnamePort="MSTransactions";
String BODY_NAMESPACE_VALUE="http://localhost:8080/axis/MSTransactions.jws";
String ENCODING_STYLE_PROPERTY="javax.xml.rpc.encodingstyle.namespace.uri";
    String NS_XSD="http://www.w3.org/2001/XMLSchema";
    String URI_ENCODING="http://schemas.xmlsoap.org/soap/encoding";
String str,tkn;
%>
<%
try{
javax.xml.rpc.ServiceFactory factory=javax.xml.rpc.ServiceFactory.newInstance();
Service service=factory.createService(new QName(qnameService));
QName port=new QName(qnamePort);
           Call call=service.createCall(port);
           call.setTargetEndpointAddress("http://localhost:8080/axis/MSTransactions.jws");
call.setProperty(Call.SOAPACTION_USE_PROPERTY,new Boolean(true));
           call.setProperty(Call.SOAPACTION_URI_PROPERTY, "");
           call.setProperty(Call.ENCODINGSTYLE_URI_PROPERTY,"");
           // call.setProperty(Call.ENCODING_STYLE_PROPERTY,URI_ENCODING);
           call.setProperty(Call.OPERATION_STYLE_PROPERTY, "rpc");
QName QNAME_TYPE_STRING=new QName(NS_XSD,"string");
           // call.setProperty(Call.OPERATION_STYLE_PROPERTY, "document");
           call.setReturnType(QNAME_TYPE_STRING);
call.setOperationName( new QName(BODY_NAMESPACE_VALUE,"getTransactions"));
call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);
Object[] params={accno};//account number passed as argument
String result=(String)call.invoke(params);
java.util.StringTokenizer d=new java.util.StringTokenizer(result,"$");
//changes.....

while(d.hasMoreTokens()){
int x=0;
tkn=d.nextToken();
java.util.StringTokenizer t = new java.util.StringTokenizer(tkn,";");
//changes...
%>

            <tr>
             <%
            int i = 0;
            while (t.hasMoreTokens()) {
             String str = t.nextToken();
            %>
                <% if (i == 0) {
                %>
                <td align= center>
                    <%=str %>
                </td>
                <% }
                %>
                <% if (i == 1) {
                %>

                <td align= center>
                   <%=str %>
                </td>
                <%
                }
                %>
                <%if (i == 2) {%>
                <td align= center>
                    <%=str %>
                </td>
                <%
                } //End of if
                %>
                <%
                i++;
                } //end of while;
%>
</tr></br>
<%

}//End of outer while loop
            }  //end of try
            catch(Exception e){ System.out.println("Error occured");}
                %>
         
            <%--
            }--%>
        </table>
    </body>
</html>
Step 21: Write the following code and Save it as PNBTransactions.jsp

PNBTransactions.jsp:
<html>
<head>
<title>Amount Details</title>
</head>
<body>
<link rel="shortcut icon" href="PNB_logo.ico"/>
        <h2 align="center">PNB Transaction Deatils</h2>
        <table  border="1" method="post" action="" align= "center" bgcolor="yellow" width = 50%>
            <tr>
                <th align= center bgcolor="#3399FF" style="color:#FFFFFF">
                    <b>Amount</b>
                </th>
                <th align= center bgcolor="#3399FF" style="color:#FFFFFF" >
                    <b>Date</b>
                </th>
                <th align= center bgcolor="#3399FF" style="color:#FFFFFF">
                    <b>Type of Transaction</b>
                </th>
            </tr>
<%@page import="javax.xml.rpc.Call,javax.xml.rpc.Service,javax.xml.rpc.JAXRPCException,javax.xml.namespace.QName,javax.xml.rpc.ServiceFactory, javax.xml.rpc.ParameterMode,javax.xml.rpc.ServiceException,javax.xml.rpc.*,com.sun.xml.rpc.client.*,com.sun.xml.rpc.soap.*, com.sun.xml.rpc.spi.tools.SOAPConstants,com.sun.xml.messaging.saaj.util.ByteInputStream,com.sun.xml.rpc.client.dii.BasicCall"
 %>
<%
//String name="Ramesh";
//String password="ramesh";
//String accno=request.getParameter("accno");
String accno=request.getParameter("accno");

%>


<%! String qnameService="PNBConnService";
     String qnamePort="PNBConn";
     String BODY_NAMESPACE_VALUE="http://localhost:8080/axis/PNBConn.jws";
     String ENCODING_STYLE_PROPERTY="javax.xml.rpc.encodingstyle.namespace.uri";
    String NS_XSD="http://www.w3.org/2001/XMLSchema";
    String URI_ENCODING="http://schemas.xmlsoap.org/soap/encoding";
%>

<%
try{

                javax.xml.rpc.ServiceFactory factory=javax.xml.rpc.ServiceFactory.newInstance();
Service service=factory.createService(new QName(qnameService));
QName port=new QName(qnamePort);
               
                Call call=service.createCall(port);
                call.setTargetEndpointAddress("http://localhost:8080/axis/PNBTransactions.jws");
call.setProperty(Call.SOAPACTION_USE_PROPERTY,new Boolean(true));
                call.setProperty(Call.SOAPACTION_URI_PROPERTY, "");
                call.setProperty(Call.ENCODINGSTYLE_URI_PROPERTY,"");
               // call.setProperty(Call.ENCODING_STYLE_PROPERTY,URI_ENCODING);
                call.setProperty(Call.OPERATION_STYLE_PROPERTY, "rpc");
                QName QNAME_TYPE_STRING=new QName(NS_XSD,"string");
               // call.setProperty(Call.OPERATION_STYLE_PROPERTY, "document");
                call.setReturnType(QNAME_TYPE_STRING);
call.setOperationName( new QName(BODY_NAMESPACE_VALUE,"getTransactions"));
                call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);

                Object[] params={accno};//account number passed as argument
String result=(String)call.invoke(params);
java.util.StringTokenizer t = new java.util.StringTokenizer(result,";");
%>
            <tr>
             <%
            int i = 0;
            while (t.hasMoreTokens()) {
             String str = t.nextToken();
            %>
                <% if (i == 0) {
                %>
                <td align= center>
                    <%=str %>
                </td>
                <% }
                %>
                <% if (i == 1) {
                %>

                <td align= center>
                   <%=str %>
                </td>
                <%
                }
                %>
                <%if (i == 2) {%>
                <td align= center>
                    <%=str %>
                </td>
                <%
                }
                %>
                <%
                i++;
                }
            }
            catch(Exception e){ System.out.println("Error occured");}
                %>
            </tr>
            <%--
            }--%>

        </table>
    </body>
</html>
Step 22: Open the browser and type the following URL http://localhost:8080/axis/Enquiry.jsp



Step 23: Enter Username and Password and click “GetDetails”.






Step 24: Click on SBI Account Number to get the Transaction Details.

Step 25: Go back and Click on PNB Account Number to get pnb transaction details.

2. Java Swings
Step 26: Write the following code and save it as DBEnquirySwing.java
import java.awt.*;
import java.sql.*;
import javax.swing.*;
import java.awt.event.*;
import javax.xml.rpc.Service;
import javax.xml.rpc.*;
import javax.xml.namespace.QName;
import com.sun.xml.rpc.client.*;
import com.sun.xml.rpc.soap.*;
import com.sun.xml.rpc.spi.tools.SOAPConstants;
import com.sun.xml.messaging.saaj.util.ByteInputStream;
import com.sun.xml.rpc.client.dii.BasicCall;
class DBEnquirySwing
{
String qnameService="MSConnService";
String qnamePort="MSConn";
     String BODY_NAMESPACE_VALUE="http://localhost:8080/axis/MSConn.jws";
String ENCODING_STYLE_PROPERTY="javax.xml.rpc.encodingstyle.namespace.uri";
String NS_XSD="http://www.w3.org/2001/XMLSchema";
    String URI_ENCODING="http://schemas.xmlsoap.org/soap/encoding";
public static void main(String[] args)
{
JFrame f=new JFrame();
final JLabel label1=new JLabel("User Name:");
final JLabel label2=new JLabel("Password :");

final JTextField text1=new JTextField(30);
final JPasswordField password = new JPasswordField(10);
final JTextArea area=new JTextArea(20,20);
final JLabel label3=new JLabel();
JButton button=new JButton("Invoke");
JPanel p=new JPanel(new GridLayout(1,6));
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
try{
String ta="";
String usr=text1.getText();
String pwd=password.getText();
javax.xml.rpc.ServiceFactory factory=javax.xml.rpc.ServiceFactory.newInstance();
GetBalance gb=new GetBalance();
Service service=factory.createService(new QName(gb.qnameService));
QName port=new QName(gb.qnamePort);
Call call=service.createCall(port);
call.setTargetEndpointAddress("http://localhost:8080/axis/MSConn.jws");
call.setProperty(Call.SOAPACTION_USE_PROPERTY,new Boolean(true));
call.setProperty(Call.SOAPACTION_URI_PROPERTY, "");
call.setProperty(Call.ENCODINGSTYLE_URI_PROPERTY,"");
call.setProperty(Call.OPERATION_STYLE_PROPERTY, "rpc");
QName QNAME_TYPE_STRING=new QName(gb.NS_XSD,"string");
call.setReturnType(QNAME_TYPE_STRING);
call.setOperationName(new QName(gb.BODY_NAMESPACE_VALUE,"getBalance"));
call.addParameter("String_1",QNAME_TYPE_STRING, ParameterMode.IN);
call.addParameter("String_2",QNAME_TYPE_STRING, ParameterMode.IN);
Object[] params={usr,pwd};
String result=(String)call.invoke(params);
System.out.println(result);
area.setText(result);
java.util.StringTokenizer t = new java.util.StringTokenizer(result,";");
int j=0;
String str1="";
String str2="";
while(t.hasMoreTokens())
{
String res=t.nextToken();
if(j==0)
{
str1=res;
}
if(j==1)
{
str2=res;
}
j++;
}
java.util.StringTokenizer st=new java.util.StringTokenizer(str1,"//");
int i = 0;
while (st.hasMoreTokens())
{
String str = st.nextToken();
if (i == 0)
{
System.out.println(str);
ta+="\n"+str;
}
if (i == 1)
{
 System.out.println(str);
 ta+="\n"+str;
}
if( i==2)
{
System.out.println(str);
ta+="\n"+str;
}
i++;
}
int k = 0;
java.util.StringTokenizer st1=new java.util.StringTokenizer(str2,"//");
while (st1.hasMoreTokens())
{
String str = st1.nextToken();
if (k == 0)
{
System.out.println(str);
ta+="\n"+str;
}
if(k==1)
{
System.out.println(str);
ta+="\n"+str;
}
if(k==1)
{
System.out.println(str);
ta+="\n"+str;
}
}
area.setText(ta);
}
catch(Exception ex)
{
System.out.println(ex);
}
}
});
        p.add(label1);
        p.add(text1);
        p.add(label2);
        p.add(password);
        p.add(area);
        p.add(button);
        f.add(p);
        f.setVisible(true);
        f.pack();
}
}
Step 27: Run the DBEnquirySwing.java
javac DBEnquirySwing.java
java DBEnquirySwing

Enter Username and Password.

Click on Invoke.











5. Invoking External Web Service
Description:
External web services can be invoked from our resources. For this purpose we need to identify which web service is existed in the internet. For example the following “Number Conversion” web service is existed in the internet at the following location.
http://www.dataaccess.com/webservicesserver/numberconversion.wso
Here there exist 2 services named by
Number to words
Number to dollars
Number to dollars web service takes the decimal value as input and returns the output in the text format. i.e., if input is ‘123’ the result is ‘one hundred and  twenty three dollars”.
The following is the input to call the web service in the SOAP format.
innum.xml:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <NumberToDollars xmlns="http://www.dataaccess.com/webservicesserver/">
      <dNum>123</dNum>
    </NumberToDollars>
  </soap:Body>
</soap:Envelope>

Step 1: Create a file with  the following code and save it as Number2Dollar.java
Number2Dollar.java
import java.io.*;
import java.net.*;
import org.w3c.dom.*;
import javax.xml.xpath.*;
import javax.xml.parsers.*;
import java.io.IOException;
import org.xml.sax.SAXException;
public class Number2Dollar
 {
public static void main(String[] args) throws Exception
{
String SOAPUrl = "http://www.dataaccess.com/webservicesserver/numberconversion.wso";
    String xmlFile2Send = "innum.xml"; //args[1];
String SOAPAction = "";
System.setProperty("http.proxyHost","cipher.idrbt.net"); //Enter proxy settings here
System.setProperty("http.proxyPort","8080");
System.setProperty("http.proxyUser","upenders");
System.setProperty("http.proxyPassword","uppy2011*");
// Create the connection where we're going to send the file.
        URL url = new URL(SOAPUrl);
        URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
// Open the input file. After we copy it to a byte array, we can see
// how big it is so that we can set the HTTP Cotent-Length
        // property. (See complete e-mail below for more on this.)
FileInputStream fin = new FileInputStream(xmlFile2Send);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
// Copy the SOAP file to the open connection.
copy(fin,bout);
                 fin.close();
byte[] b = bout.toByteArray();
// Set the appropriate HTTP parameters.
       httpConn.setRequestProperty( "Content-Length", String.valueOf( b.length ) );
       httpConn.setRequestProperty("Content-Type","text/xml; charset=utf-8");
       httpConn.setRequestProperty("SOAPAction",SOAPAction);
       httpConn.setRequestMethod( "POST" );
       httpConn.setDoOutput(true);
       httpConn.setDoInput(true);
        // Everything's set up; send the XML that was read in to b.
        OutputStream out = httpConn.getOutputStream();
        out.write( b );  
        out.close();
InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
FileOutputStream fout=new FileOutputStream("Numresult.xml");
PrintStream p=new PrintStream( fout );
String inputLine;
        while ((inputLine = in.readLine()) != null)
{
                     System.out.println(inputLine);
p.println (inputLine);
}
        in.close();
}
  // copy method from From E.R. Harold's book "Java I/O"
public static void copy(InputStream in, OutputStream out) throws IOException
{
    // do not allow other threads to read from the input or write to the output while copying //is taking place
    synchronized (in) {
      synchronized (out) {
        byte[] buffer = new byte[256];
        while (true) {
          int bytesRead = in.read(buffer);
          if (bytesRead == -1) break;
          out.write(buffer, 0, bytesRead);
        }
      }
    }
  }
}
The web service takes the input in the soap format. So, we will send the input in the form of soap massage. For this purpose we are using the ‘innum.xml’.
After compiling and executing the web service client the web service is invoked and sends result in the soap format as shown below.


This output is saved in another file called ‘Numresult.xml’ to parse.

To have the clear output we need to parse the xml file. To parse the xml file we need to use the XML parsers as shown in the below program.
Number2DollarConverter.java:
import java.io.*;
import java.net.*;
import org.w3c.dom.*;
import javax.xml.xpath.*;
import javax.xml.parsers.*;
import java.io.IOException;
import org.xml.sax.SAXException;
class Number2DollarConverter
{
public static void main(String[] args)
{
try{
DocumentBuilderFactory domFactory =
DocumentBuilderFactory.newInstance();
       // domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
//Document doc = builder.parse("C:\\Users\\gnvkdramesh\\Desktop\\excute\\Numresult.xml");
Document doc = builder.parse("Numresult.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
       // XPath Query for showing all nodes value
XPathExpression  expr = xpath.compile("//NumberToDollarsResponse/*/text()");

Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {

System.out.println(nodes.item(i).getNodeValue());
}
}
catch(Exception ex){
System.out.println(ex);
}
}
}
After executing the above java file the output is displayed on the Console as shown below.