javawaveblogs-20

Saturday, October 13, 2007

Java Excel API

Where to get the jexcelapi?


Get the API download form --> http://jexcelapi.sourceforge.net/

What is jexcelapi ?

A Java API to read, write, and modify Excel spreadsheets.

Now java developers can read Excel spreadsheets, modify them with a convenient and

simple API, and write the changes to any output stream (e.g. disk, HTTP, database, or

any socket).


Because it is Java, the API can be invoked from within a servlet, thus giving access to

Excel spreadsheets over internet and intranet web applications.


Features of jexcelapi

Reads data from Excel 95, 97, 2000, XP, and 2003 workbooks
Reads and writes formulas (Excel 97 and later only)
Generates spreadsheets in Excel 2000 format Supports font, number and date formatting Supports shading, bordering, and coloring of cells Modifies existing worksheets Is internationalized, enabling processing in almost any locale, country, language, or character encoding (formulas are currently only supported in English, French, Spanish, and German, but more can be added if translated) Supports copying of charts Supports insertion and copying of images into spreadsheets Supports logging with Jakarta Commons Logging, log4j, JDK 1.4 Logger, etc ...and much more.

Technical notes ==> http://www.andykhan.com/jexcelapi/technotes.html

JExcelApi JavaDoc ==> http://jexcelapi.sourceforge.net/resources/javadocs/index.html



Pre-Requirements:
  • Should be knowing basic concepts of Java.
  • Should know how to set class path to use third party Api's.


Now we will see how to read a spread sheet using this API:


First of all we will create a spread sheet like the one below and store it in our local folder.

I am saving this file in "D:testmyFile.xls"



To read the spread sheet content using jxl Api, first we have to create an object called
Workbook. Once you create the Workbook then you will get access to individual sheets.
Note that these sheets are Zero indexed.
So you have to use some thing like workbook.getSheet(0);

Once you get the sheet then you can easily get the cells and their content as string.
If you want it is also possible to get the data with out changing the type as it is.

See the sample code below (SpreadsheetReader.java).

package com.jxl.dhanago;

import java.io.File;
import java.io.IOException;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

/**
* This Java program is used to read the spread sheet and print it in
* console output.
*
* @author dhanago
*/
public class SpreadsheetReader
{

/**
* This method is used to read a spread sheet and print it in console.
*
* @param xlsPath
*/
public void readSpreadSheet( String xlsPath )
{
try
{
/*
* To read the spread sheet , first we have to create a workbook
* object like one shown below.
*/
Workbook workbook = Workbook.getWorkbook( new File( xlsPath ) );
/*
* then get the sheet index 0. Note the index starts with 0.
*/
Sheet sheet = workbook.getSheet( 0 );
/*
* get the cell form the sheet object like below.
*/
Cell cell00 = sheet.getCell( 0, 0 );
Cell cell01 = sheet.getCell( 0, 1 );
Cell cell02 = sheet.getCell( 0, 2 );

/*
* now we will display the cell values as string in console output.
*/
System.out.println( "Cell00 value: " + cell00.getContents() );
System.out.println( "Cell01 value: " + cell01.getContents() );
System.out.println( "Cell02 value: " + cell02.getContents() );
// free up memory
workbook.close();
}
catch (BiffException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}

/**
* This is the main executable method used to test the spread sheet
* reader.
*
* @param args
*/
public static void main( String[] args )
{
SpreadsheetReader readSpreadsheet = new SpreadsheetReader();
String xlsPath = "D:\test\myFile.xls";
readSpreadsheet.readSpreadSheet( xlsPath );
}
}

OutPut for the above code:

Cell00 value: Name
Cell01 value: Muthukumar Dhanagopal
Cell02 value: Krish

The above code displays the cell values as string. How to get the same
data type and display them with out converting them to string. Is that
possible using this API?

Yes, it is possible.
Here is the code which does the same for you.
It checks the cell type for LABEL, NUMBER or DATE and then gets the value from
the cell type cast the value to that particular data type and displays it on the console.

package com.jxl.dhanago;

import java.io.File;
import java.io.IOException;

import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;
import jxl.LabelCell;
import jxl.NumberCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

/**
* This java program is used to get and display the xls data according to
* the type.
*
* @author dhanago
*/
public class ReadXLWithExactDataType
{

/**
* This method is used to display the xls data with exact type.
*
* @param xlsPath
*/
public void readDataWithType( String xlsPath )
{
try
{
/*
* To read the spread sheet , first we have to create a workbook
* object like one shown below.
*/
Workbook workbook = Workbook.getWorkbook( new File( xlsPath ) );
/*
* then get the sheet index 0. Note the index starts with 0.
*/
Sheet sheet = workbook.getSheet( 0 );
/*
* get the cell form the sheet object like below.
*/
Cell cell00 = sheet.getCell( 0, 0 );

if (cell00.getType() == CellType.LABEL)
{
System.out.println( "Type LABEL" );
LabelCell labelCell = (LabelCell) cell00;
System.out.println( "Label Cell: " + labelCell.getString() );
}
else if (cell00.getType() == CellType.NUMBER)
{
System.out.println( "Type NUMBER" );
NumberCell numberCell = (NumberCell) cell00;
System.out.println( "Number Cell: " + numberCell.getValue() );
}
else if (cell00.getType() == CellType.DATE)
{
System.out.println( "Type DATE" );
DateCell dateCell = (DateCell) cell00;
System.out.println( "Date Cell: " + dateCell.getDate() );
}
else
{
System.out.println( "Type not supported." );
}

/*
* now we will display the cell values as string in console output.
*/
System.out.println( "Cell00 value: " + cell00.getContents() );
// free up memory
workbook.close();
}
catch (BiffException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}

/**
* This is the main executable method used to test the spread sheet
* reader.
*
* @param args
*/
public static void main( String[] args )
{
ReadXLWithExactDataType readXL = new ReadXLWithExactDataType();
String xlsPath = "D:\test\myFile.xls";
readXL.readDataWithType( xlsPath );
}

}

The Output for the above code is:
Type LABEL
Label Cell: Name
Cell00 value: Name


Wednesday, October 10, 2007

Rule Engine - Drools

What is a Rule Engine?

Artificial Intelligence (A.I.) is a very broad research area that focuses on "Making computers think like people" and includes disciplines such as Neural Networks, Genetic Algorithms, Decision Trees, Frame Systems and Expert Systems. Knowledge representation is the area of A.I. concerned with how knowledge is represented and manipulated. Expert Systems use Knowledge representation to facilitate the codification of knowledge into a knowledge base which can be used for reasoning - i.e. we can process data with this knowledge base to infer conclusions. Expert Systems are also known as Knowledge-based Systems and Knowledge-based Expert Systems and are considered 'applied artificial intelligence'. The process of developing with an Expert System is Knowledge Engineering. EMYCIN was one of the first "shells" for an Expert System, which was created from the MYCIN medical diagnosis Expert System. Where-as early Expert Systems had their logic hard coded, "shells" separated the logic from the system, providing an easy to use environment for user input. Drools is a Rule Engine that uses the Rule Based approached to implement an Expert System and is more correctly classified as a Production Rule System.

The term "Production Rule" originates from formal grammar - where it is described as "an abstract structure that describes a formal language precisely, i.e., a set of rules that mathematically delineates a (usually infinite) set of finite-length strings over a (usually finite) alphabet" (wikipedia).

For more information visit the following URL
https://hudson.jboss.org/hudson/job/drools/lastSuccessfulBuild/artifact/trunk/target/docs/html/ch02.html



JBoss server in Eclipse

Defining JBoss server in Eclipse:

Step 1 : Open Eclipse WTP all in one pack in a new work space.

Step 2 : Change the perspective to J2EE Perspective if it is not currently in J2EE Perspective.

Step 3 : Once the Perspective is changed to J2EE, you can see a tab called Servers in the bottom right panel along with Problems, Tasks, Properties.

Step 4 : If the Servers tab is not found. Go to Eclipse menu : Windows > Show view and click on Servers, so that Server tab will be displayed.

Step 5 : Go to Servers tab window and right click the mouse. You will get a pop up menu called "New".

Step 6 : Clicking on the New menu you will get one more pop up called "Server". Click on it.

Step 7 : Now you will get Define New Server Wizard.

Step 8 : In the wizard there are options to define many servers. One among them is JBoss. Click on JBoss and Expand the tree.

Step 9 : Select JBoss v 4.0 and click next.

Step 10 : Now give the JDK directory and JBoss home directory. Click Next.

Step 11 : Now the wizard will show you the default Address, port, etc., Leave it as it is and click on Next.

Step 12 : Click on finish.

Step 13 : Now you can see the JBoss server listed in the Servers window and the status is Sopped.

Step 14 : JBoss server is now defined in Eclipse now and its ready to use from with in Eclipse IDE.

Monday, October 8, 2007

DOM parsing technique

This class follows the DOM parsing technique and does the following.

1.Parse the demoxml.xml file.
2.Search for the xml node by the name "parent1" from the xml.
3.Create a new child node by the name "newChild"
4.Create a text("new child of the parent1") to the "newChild" node
5.Append the "newChild" node to "parent1" node.
6.Save the changes (transform) to the xml.


Sample Code: (
DOMParser.java)
package com.dom.dhanago;

/*
* This class follows the DOM parsing technique and does the following.
* 1.Parse the demoxml.xml file. 2.Search for the xml node by the name
* "parent1" from the xml. 3.Create a new child node by the name "newChild"
* 4.Create a text("new child of the parent1") to the "newChild" node
* 5.Append the "newChild" node to "parent1" node. 6.Save the changes
* (transform) to the xml.
*/

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class DOMParser
{

public static void main( String[] args )
{
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document;
document = builder.parse( new File( "C:\\demoxml.xml" ) );
/*
* You can pass either xml file or string.To fetch the root element
* of the xml document.
*/
Element rootEle = document.getDocumentElement();
/*
* To fetch all the child nodes of the root element.
*/
NodeList childNodes = rootEle.getChildNodes();
/*
* To search an element from the whole document.
*/
NodeList parentNode = document.getElementsByTagName( "parent1" );
/*
* To create a new child element by the name "newChild".
*/
Element newChild = document.createElement( "newChild" );
/*
* Adding text data to "newChild".
*/
newChild.appendChild( document
.createTextNode( "new Child of the parent1 node" ) );

/*
* To append the "newChild" ,created above.
*/
parentNode.item( 0 ).appendChild( newChild );

TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();

/*
* Preparing the source which is the document created above.
*/
Source srcDocument = new DOMSource( document );
/*
* Destination will be same different xml.
*/
Result destxml = new StreamResult( new File( "C:\\demoxml.xml" ) );
/*
* Transforming document to destination xml.
*/
aTransformer.transform( srcDocument, destxml );
System.out.println( "Successfully transformed" );
}
catch (Exception e)
{
System.out.println( "exec " + e );
}
}
}

Friday, October 5, 2007

Code to convert from Xml-String to Document and Document to String

package ora.in;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
* Code to convert from Xml-String to Document and Document to String.
*
* @author Muthu
*/
public class S2DandD2S
{
public static Document loadXmlFileToDocument( String strXml,
boolean ignoreComments )
{
Document docRet = null;
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
factory.setIgnoringComments( ignoreComments );
DocumentBuilder docBuilder = factory.newDocumentBuilder();
docRet = docBuilder.parse( new InputSource( new StringReader(
strXml ) ) );
}
catch (SAXException e)
{
System.out.println( "SAXException" );
}
catch (IOException e)
{
System.out.println( "IOException" );
}
catch (ParserConfigurationException e)
{
System.out.println( "ParserConfigurationException" );
}
catch (FactoryConfigurationError e)
{
System.out.println( "FactoryConfigurationError" );
}
return docRet;
}

/**
* @param args
*/
public static void main( String[] args )
{
try
{
String xml = "Some exception file as string";

Document document = loadXmlFileToDocument( xml, false );
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();

Source srcDocument = new DOMSource( document );

// Preparing the source which is the document created above.
StringWriter writer = new StringWriter();
Result destxml = new StreamResult( writer );

// Transformingdocument to destination xml.
aTransformer.transform( srcDocument, destxml );

System.out.println( writer.toString() );
System.out.println( "Successfully transformed" );
}
catch (Exception e)
{
System.out.println( "exec " + e );
}
}
}

Parsing Java InputStream To Text and Vice Versa

Here are couple of useful methods to convert from InputStream to String
and vice versa.

Input Stream to String


public String parseISToString(java.io.InputStream is){
java.io.DataInputStream din = new java.io.DataInputStream(is);
StringBuffer sb = new StringBuffer();
try{
String line = null;
while((line=din.readLine()) != null){
sb.append(line+"\n");
}
}catch(Exception ex){
ex.getMessage();
}finally{
try{
is.close();
}catch(Exception ex){}
}
return sb.toString();
}

String to InputStream


public java.io.InputStream parseStringToIS(String xml){
if(xml==null) return null;
xml = xml.trim();
java.io.InputStream in = null;
try{
in = new java.io.ByteArrayInputStream(xml.getBytes("UTF-8"));
}catch(Exception ex){
}
return in;
}

Friday, September 21, 2007

Happy Axis

Introduction

Axis is a web service engine. It is the third generation of apache soap.
To know about webservices it is mandatory to know about SOAP.

This artical will gives you the brief introduction on SOAP.

Then it will introduce you to Apache Axis 1.4. Then we will also tell about the diffrent styles

of webservices in brief.

The article will conclude by giving a sample application, explaining how to deploy webservice

in axis? How to call the deployed webservice?

Pre-Requesties

  • This artical assumes that you already know how to write a java code, compile and run.
  • You should also have a servlet engine or an application server already configured.
  • You should be familiar with web application deployment scenarios and how to start and
stop the server.
  • We recommend Jakarta Tomcat. [If you are installing Tomcat, get the latest 4.1.x version,
and the full distribution, not the LE version for Java 1.4, as that omits the Xerces XML parser].
Other servlet engines are supported, provided they implement version 2.2 or greater of the
servlet API.
  • Make sure you have the latest version of JDK installed in your system and JAVA_HOME is set.
  • Note also that Axis client and server requires Java 1.3 or later.


Things to know before diving into Web Service

  • Core Java and concepts of java.
  • How to diagnose trouble from exception traces.
  • What is a web application? what is the folder structure of web application? how to pack
libraries to web application? how to make a war file? to deploy web application to the application
server. Should also have knowledge on servlets.
  • Basic knowledge about XML. [XML parsing not mandatary]
  • Should also have knowledge about HTTP, TCP/IP


Software used in this artical

  • Apache Axis 1.4
  • JDK 1.5.x
  • Jakarta Tomcat 5.x
  • Netbeans 5.5.1 for java coding.

SOAP

SOAP is an XML-based communication protocol and encoding format for inter-application

communication. The current spec is version, SOAP 1.2, though version1.1 is more widespread.

SOAP is the backbone of Web Services.

Below shown is the sample SOAP request message.

						
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Body>
<ns1:echoString xmlns:ns1="http://javawave.net/">
<arg0 xsi:type="xsd:string">Hi There!</arg0>
</ns1:echoString>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Web Service

Web service is a new generation cross-platform, cross-language distributed computing

applications.

Apache Axis

Axis is a SOAP engine. It is a SOAP processer framework. The current version of Axis if written

fully in Java.

Axis has full support for the Web Service Description Language(WSDL). It has tools to generate

java code (Client stubs) from WSDL as well as generate WSDL automatically from java code.

Axis also has a simple stand alone server. It also has a server which plugs in to other servlet

engins, like Tomcat.

Axis also has a monitoring tool to monitor TCP/IP packets.

Please note that this is an open-source effort. And in case you're wondering what Axis stands

for, it's Apache EXtensible Interaction System - a fancy way of implying it's a very configurable

SOAP engine.

Axis is compiled in the JAR file axis.jar; it implements the JAX-RPC API declared in the JAR files

jaxrpc.jar and saaj.jar. It needs various helper libraries, for logging, WSDL processing and

introspection. All these files can be packaged into a web application, axis.war, that can be

dropped into a servlet container.

Diffrent Style of Web Services in Axis

There are four style of web services axis supports. They are:

  • RPC
  • Document
  • Wrapped, and
  • Message

we will take about these services after we see how to write deployment descriptor's to deploy

a service

Installing Axis

  • Download the latest version of Axis. Here we are using Axis version 1.4
  • Unzip the package downloaded to a folder say "myAxis".
  • Inside the unpacked folder, we can see a folder by name "axis".(<myAxis>axis-1_4webapps)
  • Copy the folder to tomcat webapps folder.(this article uses tomcat and we assume that your
tomcat is up and running in port 8080, if it is not running in 8080 please configure your tomcat to
run on 8080 if you are using some other application servers please see the reference document on
deploying web application in the server you are using)
  • The folder name "axis" can be renamed if you want diffrent context name. The rest of this
document assumes that the default webapp name, "axis" has been used; rename these references
if appropriate.
  • Axis needs a xml parser to work. If your application server does not provide one, please download
xml-xerces distribution (http://xml.apache.org/dist/xerces-j/) and add the parser libraries to
axis/WEB-INF/lib.
  • Axis also needs jaxrpc.jar and saaj.jar in the application path. jaxrpc.jar and saaj.jar contain
javax packages, so they may not get picked up. Copy them from
axis/WEB-INF/lib to CATALINA_HOME/common/lib and restart Tomcat.
  • Now we are ready to go... :)

Validating the Installation

  • Make sure tomcat is running. Navigate to http://127.0.0.1:8080/axis/, if you have changed the
context name or the port change it accordingly in your URL. Now you should see the Apache-Axis start
page. If you are not able to see the page then probably your web application is not deployed properly.
  • Click on the validate link on the Apache Axis start page. This will lead you to happyaxis.jsp.
This is the test page that checks if the needed libraries and optional libraries are present or not.
  • If any of the needed libraries are missing, Axis will not work, then first you have to fix it and then
proceed.
  • Optional components are optional; install them as your need arises. If you see nothing but an internal
server error and an exception trace, then you probably have multiple XML parsers on the CLASSPATH,
and this is causing version confusion. Eliminate the extra parsers, restart the app server and try again.
  • Once the happyaxis page is happy. Navigate to the Apache-Axis start page
(http://127.0.0.1:8080/axis/). Select view list of deployed web services link. This will lead to a page
which will list all the deployed web services. On this page, You should be able to click on (wsdl) for
each deployed Web service to make sure that your web service is up and running.

Deploying new Web Services

New Web services installation process

  • Get the classes and libraries of your new service into the Axis WAR directory tree, and
  • Tell the AxisEngine about the new file. The latter is done by submitting an XML deployment descriptor
to the service via the Admin web service, which is usually done with the AdminClient program. AdminClient
run the Axis SOAP client to talk to the Axis adminstration service, which is a SOAP service in its own right.
It's also a special SOAP service.

Implementing the process

Prepare a batch file which will set all the axis related jar files to the classpath.
Here is the list of jars needed to set in the class path

  • axis-ant.jar
  • axis.jar
  • commons-discovery-0.2.jar
  • commons-logging-1.0.4.jar
  • jaxrpc.jar
  • log4j-1.2.8.jar
  • saaj.jar
  • wsdl4j-1.5.1.jar
  • xml-apis.jar(download this jar)
  • xercesImpl.jar(download this jar)

First we will write a simple java code like below

                            
/*
* HappyAxis.java
*
* Created on 9 Aug, 2007, 7:16:36 PM
*
*/

package myapp;

/**
*
* @author Muthukumar Dhanagopal
*/
public class HappyAxis
{

public HappyAxis()
{
}

public String sayHello(String name)
{
return "Hello " + name;
}

}


Compile the code and make a jar file. Here we created the jar file by name myApp.jar which contains

the above code.

Once myApp.jar is created, drop the jar inside axisWEB-INFlib folder in inside your application server.

Now it is time to write a deployment descriptor file to deploy our service in axis.

Web Service Deployment descriptor is nothing but a xml file with .wsdd extention. You can find a

sample deployment descriptor below, which is used to deploy our example service HappyAxis packed

into myApp.jar library.

                            
<deployment xmlns="http://xml.apache.org/axis/wsdd/"
xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">

<service name="MyService" provider="java:RPC">
<parameter name="className" value="myapp.HappyAxis"/>
<parameter name="allowedMethods" value="*"/>
</service>

</deployment>

The service element has a name attribute which will contain the service name you want to expose.

provider attribute will contain the provider used for the service. here we are using the java:RPC

provider. Insted of provider attribute we can also use style attribute where we can define the

style of webservice like document or messaging style. Our service name we defined here is "MyService".

service element has two child element named parameter. The first parameter element's name attribute

will hold the value className and the value attribute will contain the exact class name including the

package. Here our value is "myapp.HappyAxis". In the next parameter tag you can specify all the

methods you like to expose in that class. If you want to expose all the methods in the class specify * in

the value attribute. If you want to specify only one method or couple of methods, then specify the

method name seperated by space.

Save the above deployment descriptor as deploy.wsdd.

Run the bath file which we prepared earlier to set classpath. Execute the following command from the

directory where you have saved the deploy.wsdd. If you are not in this directory you will get a

"java.io.FileNotFoundException: deploy.wsdd (The system cannot find the file specified)" exception

java org.apache.axis.client.AdminClient 
-lhttp://localhost:8080/axis/services/AdminService deploy.wsdd

If you get some java client error (like ClassNotFoundException), then you haven't set up your

CLASSPATH variable right, mistyped the classname, or did some other standard error. Tracking down

such problems are foundational Java development skills--if you don't know how to do these things,

learn them now!

If you don't get any error then that means you have successfully deployed your web service.

Now visit the Apache-Axis start page and navigate to the web service listing page. Here you can

see your service getting displayed. Just click on the WSDL link, Axis will automaticly generate

WSDL for your deployed service.

Now we will see the styles of webservices possible in Axis

As we have already seen there are four types of webservices supported in Axis.

They are RPC(1), Document(2), Wrapped(3) and Message(4)

RPC services

RPC services are the default in Axis. They are what you get when you deploy services with

<service ... provider="java:RPC"> or <service ... style="RPC">.

RPC services follow the SOAP RPC and encoding rules. Axis will deserialize XML into Java objects which

can be fed to your service, and will serialize the returned Java object(s) from your service back into XML.

Since RPC services default to the soap section 5 encoding rules, objects will be encoded via "multi-ref"

serialization, which allows object graphs to be encoded.

Document / Wrapped service

Document and Wrapped services are similar, both use SOAP encoding for data.(means its plain xml schema).

Axis binds java objects for the xml schema here. so in the end you will end up using java objects. You will

not use the xml directly here.

The document or wrapped style is indicated in WSDD as follows:


<service ... style="document"> for document style
<service ... style="wrapped"> for wrapped style

Message service

Message service should be used when you want Axis to step back and let your code at the actual XML

instead of turning it into Java objects. There are four valid signatures for your message-style service methods:


public Element [] method(Element [] bodies);
public SOAPBodyElement [] method (SOAPBodyElement [] bodies);
public Document method(Document body);
public void method(SOAPEnvelope req, SOAPEnvelope resp);

Consuming the deployed Web Services

Basic simple way to consume a Web Service

First we will see the basic way of calling a web service with out generating stubs from WSDL

The code below is used to call our deployed web service "MyService"

                        
/*
* TestClient.java
*
* Created on 9 Aug, 2007, 9:05:40 PM
*/

package myapp;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import javax.xml.namespace.QName;

/**
*
* @author Muthukumar Dhanagopal
*/
public class TestClient
{

public TestClient()
{
}

public static void main(String[] args)
{
try
{
String endpoint = "http://localhost:8080/axis/services/MyService";

Service service = new Service();
Call call = (Call) service.createCall();

call.setTargetEndpointAddress(new java.net.URL(endpoint));
call.setOperationName(new QName("http://javawave.blogspot.com/", "sayHello"));

String ret = (String) call.invoke( new Object[] { "Hello!" } );

System.out.println("Sent 'Hello!', got '" + ret + "'");
}
catch (Exception e)
{
System.err.println(e.toString());
}
}
}


The program can be run as follows

                        
java myapp.TestClient
Sent 'Hello', got 'Hello Hello'

Consume a Web Service by creating stubs from WSDL

Before getting into creating stubs, we will have a quick look at what is WSDL?

The Web Service Description Language is a specification authored by IBM and Microsoft,

and supported by many other organizations. WSDL serves to describe Web Services in

a structured way. A WSDL description of a service tells us, in a machine-understandable

way, the interface to the service, the data types it uses, and where the service is located.

Axis supports WSDL in three ways:

  • After you deploy the web service, you can access the URL with a web browser
appending ?wsdl to end of it. Then Axis will automatically generate a wsdl document for you.
  • Axis provides a WSDL2Java tool which will generate proxy stubs and skeletons for
service with WSDL description.
  • Axis also provides Java2WSDL tool which will generate WSDL from a Java code.

With this information, Now we will see how to build stubs from WSDL to call our deployed

web service

Client-side binding

Axis provides WSDL-to-Java tool in org.apache.axis.wsdl.WSDL2Java. The basic invocation looks

like this:

java org.apache.axis.wsdl.WSDL2Java (WSDL file URL)

This command will generate the java stubs with those bindings necessary for the client.

Axis follows JAX-RPC specification when generating the client binding from WSDL description.

For our client stub generation, First we will save the wsdl to a perticular location. Then

we will invoke the following command as this:

java org.apache.axis.wsdl.WSDL2Java MyService.wsdl

Once this invocation happens, then we can see the stubs getting generated in the same

directory from where we invocked the command. Now we are ready to go. Just compile

the stubs and write a CLI (Command Line Interface) which will make use of the generated

stub and calls the web service.

Conclusion

So we came across Axis webservices by touching on some of the features of axis. We do

came across a sample webservice wich uses RPC style. We also saw how to generate the

stubs and call the web service. Here I whould say we just had a dip in to the sea of

webservice by just going through a sample application deployment in axis. There are lot

to learn about it. Please dive deep in to the sea called webservice for the treasure of

knowledge about it.

Happy Axis.. :)

diggthis