Saturday, December 6, 2008

Parse and replace the XML elements using java

This example helps to find the xml tag values and replace with new values at runtime

Prerequisites

Following jar files are required in the class path in order to run this application J

1)      xalan-2.6.0.jar

2)      xercesImpl.jar

3)      example.xml

In this example I am using java 1.6

 

Example.xml

<Request xmlns="http://javatch.blogspot.com">

      <Details>

      <name>James</name>

      <pin>9901260200041906233</pin>

      <contact>1234567890</contact>

      </Details>

      <Details>

      <name>Bill</name>

      <pin>7701260200041906244</pin>

      <contact>0987654321</contact>

      </Details>

</Request>

 

This java application tries to find out the <pin> element from xml and replace with new value to this element

package com.javatch.xml;

 

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

import java.io.StringWriter;

import java.util.Iterator;

import java.util.Random;

import javax.xml.namespace.NamespaceContext;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.xml.serialize.XMLSerializer;

import org.apache.xpath.XPathAPI;

import org.w3c.dom.Document;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

import com.sun.org.apache.xml.internal.utils.PrefixResolver;

import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault;

 

public class XMLUpdate {

     

      InputStream stream = null;

      DocumentBuilderFactory xmlFact = null;

      DocumentBuilder builder = null;

      Document doc = null;

      NamespaceContext ctx = null;

     

      public XMLUpdate() {

                  initialization();

 

      }

      private void initialization(){

            try {

      stream = new FileInputStream(new File("example.xml"));

            if(stream == null) {

                  System.out.println("Cannot find xml file" + "example.xml");

                  return;

            }

        xmlFact = DocumentBuilderFactory.newInstance();

        xmlFact.setNamespaceAware(false);

        builder = xmlFact.newDocumentBuilder();

        doc = builder.parse(stream);

        // following declaring is required if there is any namespace in your xml

        final PrefixResolver resolver = new PrefixResolverDefault(doc.getDocumentElement());

              ctx = new NamespaceContext() {

                  public String getNamespaceURI(String prefix) {

                      return resolver.getNamespaceForPrefix(prefix);

                  }

                  public Iterator getPrefixes(String val) {

                      return null;

                  }

                  // Dummy implemenation - not used!

                  public String getPrefix(String uri) {

                      return null;

                  }

              };

            }catch(ParserConfigurationException pce) {

                 

            } catch (FileNotFoundException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

            } catch (SAXException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

            } catch (IOException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

            }

      }

      private void xmlTagValueReplace(){

        try {

            String xpathStr = "/Request/Details/pin";

            NodeList nodes =  XPathAPI.selectNodeList(doc, xpathStr);

            for(int i=0; i<nodes.getLength(); i++) {

                  nodes.item(i).setTextContent((new Random().nextInt())+"");

            }

                StringWriter stringOut = new StringWriter ();

                XMLSerializer serial = new XMLSerializer();

                serial.setOutputCharStream(stringOut);

                serial.serialize(doc);

                System.out.println(stringOut.toString());

        }catch (Exception ex) {

                ex.printStackTrace();

        }

      }

      public static void main(String args[]) {

                  XMLUpdate update = new XMLUpdate();

                  update.xmlTagValueReplace();

      }

 

}

 

 

Sunday, November 9, 2008

What is web services? How to create a web service?

Web services provide a standard way of interoperating between different applications (heterogeneous), running on different platforms, and it provides the integration of web based application using the XML, SOAP, WSDL and UDDI

 XML is used to tag the data, SOAP is used to transfer the data, WSDL is used for describing the services available and UDDI is used for listing what services are available. 

The Web Services Description Language (WSDL) forms the basis for Web Services. The following figure illustrates the use of WSDL. At the left is a service provider. At the right is a service consumer. The steps involved in providing and consuming a service are:

 

  1. A service provider describes its service using WSDL. This definition is published to a directory of services. The directory could use Universal Description, Discovery, and Integration (UDDI). Other forms of directories can also be used.
  2. A service consumer issues one or more queries to the directory to locate a service and determine how to communicate with that service. 
  3. Part of the WSDL provided by the service provider is passed to the service consumer. This tells the service consumer what the requests and responses are for the service provider.
  4. The service consumer uses the WSDL to send a request to the service provider.
  5. The service provider provides the expected response to the service consumer.

Ok Lets talks about WSDL !

 WSDL is an XML grammar for describing web services. The specification itself is divided into six major elements:

definitions

The definitions element is the root element of all WSDL. It defines the name of the web service and also declares multiple namespaces.

types

The type’s element describes all the data types used between the client and server. To define complex data type will be using XSD

      <xs:element name="helloUser">

        <xs:complexType>

          <xs:sequence>

            <xs:element name="name" type="xs:string"/>

          </xs:sequence>

        </xs:complexType>

      </xs:element>

 message

This describes the parameter (input/output)and its types  being exchanged between the Web service client and server.

 <s0:message name="helloUser">

    <s0:part element="s1:helloUser" name="parameters"/>

  </s0:message>

portType

This element defines operation (method name) with input and output parameter.

  <s0:portType name="Hello">

    <s0:operation name="helloUser" parameterOrder="parameters">

      <s0:input message="s1:helloUser"/>

      <s0:output message="s1:helloUserResponse"/>

    </s0:operation>

</s0:portType>

binding

This element includes supported operations, as well as the input and output for each operation. The bindings provide concrete information on what protocol is being used, how the data is being transported, and where the service is located

  <s0:binding name="HelloServiceSoapBinding" type="s1:Hello">

    <s2:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>

    <s0:operation name="helloUser">

      <s2:operation soapAction="" style="document"/>

      <s0:input>

        <s2:body parts="parameters" use="literal"/>

      </s0:input>

      <s0:output>

        <s2:body parts="parameters" use="literal"/>

      </s0:output>

    </s0:operation>

</s0:binding>

 Service

 The service element defines the address for invoking the specified service.

  <s0:service name="HelloService">

    <s0:port binding="s1:HelloServiceSoapBinding" name="HelloSoapPort">

      <s2:address location="http://localhost:7001/Hello/Hello"/>

    </s0:port>

  </s0:service>

How to create a simple webservice application?

                The following things are required to run this application

1)       Weblogic10.3/x   

http://www.oracle.com/technology/software/products/ias/htdocs/wls_main.html

2)       Ant 1.6.5  or latest

http://ant.apache.org/bindownload.cgi

3)       Jdk.15 or above

http://java.sun.com/javase/downloads/index.jsp

 

The following example shows how to create a Web Service called HelloWorld that includes two operations, helloByDefault and helloByUserName.

package com.javatch;

import javax.jws.WebService;

@WebService(name="HelloSoapPort", serviceName="HelloService")

public class HelloWorld{

// By default, all public methods are exposed as Web Services operation, else you can use @WebMethod()

  public String helloByDefault(){

     String saySomething = "Hello, Welcome come to Webservice world";

     System.out.println(saySomething);

     return saySomething;

  }

  public String helloByUserName(String name){

    return "Hello "+name + "Welcome come to javatch" ;

  }

}

Now we are ready with our service, next step is to generate WSDL. Umm..How?

We have create ant script to generate our service using jwsc task (for weblogic 10x)

Create a build.xml file and copy the following in to that

<project default="all">

            <target name="all" depends="clean, build"/>

            <target name="clean">

                            <delete dir="output"/>

             </target>

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

             <target name="build">

                            <jwsc

                                            srcdir="com"

                                            destdir="output">

                                            <jws  file="Hello.java"/>

                           </jwsc>

            </target>

</project>

J We are ready with our service and ant script lets create the WSDL file  

Note: set ANT_HOME - should point to the ant extract directory  ex- c:\ apache-ant-1.6.5

            Add this line in the path - %ANT_HOME%\bin

Open a command prompt and navigate to web logic directory (C:\bea10\wlserver_10.3\server\bin) and execute “setWLSEnv.sh”

 

รจ  Then go to directory were we have our build.xml and execute it. (just type ant press enter)

Create Client.java, before we do this, we need to create client stub. This is done by the following ant script

<project default="jar">

            <path id="client-path">

                            <pathelement path="src"/>

            </path>

            <taskdef name="clientgen"

                            classname="weblogic.wsee.tools.anttasks.ClientGenTask"/>

            <target name="build">

                            <clientgen

                                            wsdl="http://192.168.1.2:7001/HelloWorld/HelloWorld?WSDL"

                                            destdir="output"

                                            packageName="com.javatch"/>

                            <javac

                                            srcdir="output"

                                            destdir="output"

                                            includes="**/*.java"/>

            </target>

            <target name="jar" depends ="build">

                            <jar jarfile="client.jar" >

                                            <fileset dir="output" />

                            </jar>

   </target>

</project>

 Client.java

package com.javatch;

public class Client{

  public static void main(String args[])

  throws Exception{

    String wsdl="http://192.168.1.2:7001/HelloWorld/HelloWorld?WSDL";

    HelloService service = new HelloService_Impl(wsdl);

    HelloSoapPort h=service.getHelloSoapPortSoapPort();

    String name="My Friend";

    String msg=h.helloByUserName(name);

    System.out.println("The server message : "+msg);

  }

}

Here you go with simple webservice application :-)