Project Management

Setting up a simple Web service using Java

Web services form the basis for machine interoperability over a network. This guide aims to provide an insight into quickly setting up and deploying a simple Web service using Java, Eclipse, Apache Tomcat and Axis2.

Web services form the basis for machine interoperability over a network. The most common of these are APIs provided by Web sites such as Google for Google Maps and the Facebook API to access user information to develop applications within Facebook.

Custom and private Web services are also widely used for transactional purposes over the Internet. This guide aims to provide an insight into quickly setting up and deploying a simple Web service using Java, Eclipse, Apache Tomcat and Axis2.

Getting started

A number of applications are pre-requisites to ensure successful completion of this guide. These are as follows:

  1. Java SDK, version 6 or above is recommended,
  2. Eclipse, either the Classic or Java Developers package is recommended,
  3. Axis2, one should obtain the WAR (Web Archive) Distribution,
  4. Apache Tomcat, and
  5. Web Tools Platform, this is a set of packages for Eclipse to enable Web services functionality. (Refer to "Setting up Eclipse" for further instructions)

Note that the applications above are platform agnostic and supports the majority of operating systems.

Setting up Eclipse

Besides downloading all the required software above, most of the time spent is configuring Eclipse to function as an IDE for Web services development.

To install the Web Tools Platform, it is required to download the pre-requisites: Eclipse Modeling Framework (EMF, XSD InfoSet, SDO), Graphical Editing Framework (GEF), Data Tools Platform (DTP) and finally the non-SDK package of the Web Tools Platform referred to as "Web App Developers". Installing simply involves unzipping the archives and copying and/or replacing the files in the corresponding folders "plugins" and "features" with those in the Eclipse folder.

Eclipse Preferences

Upon completion to verify if the Web Tools Platform has been successfully installed, go to the Eclipse preferences and you should see additional options -- namely Server and Web services.

Expand the Web services tree to expose further setting options we will need to setup: "Axis2 Preferences", "Scenario Defaults", and "Server and Runtime". In "Axis2 Preferences" supply the location of the WAR file downloaded, it should return a confirmation text within the dialog on successful installation. For "Scenario Defaults" we only need to set the scenarios to both "Start service" and "Start client" while leaving the types as they are. As for "Server and Runtime" please select for server "Tomcat v6.0 Server" and "Apache Axis2" for the Web service runtime.

Now we need to set-up the Apache Tomcat as our server within the "Server" setting. After expanding the "Server" tree, select "Installed Runtimes" and click to "Add" a new server. Since we are dealing with Apache Tomcat we will expand the "Apache" folder and select the appropriate Apache Tomcat version we have. You will then be asked to supply the location of the Apache Tomcat, simply provide the root directory.

Eclipse Project Wizard steps

Creating a new project

With Eclipse successfully configured we can now create a new "Dynamic Web Project" under the "Web" folder of the New Project Wizard. Choose any name for the project as you desire, "Webservice" will be used for the purposes of this guide.

When you get to the "Project Facets" step of the wizard please remember to select the checkbox next to "Axis2 Web Services", this will include the Axis2 libraries and configuration within our newly created Web services project.

Once Eclipse has successfully generated our new project it is now time for some coding, finally!

Coding the Web service

Start by creating a new Java class by right-clicking the "src" folder and selecting New -> Class in the resultant menu, give it a capitalised name like "WS" and keep the rest of the default options. The following is some code to return a string array of some hashed text that will be used as our Web service function:


import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import sun.misc.BASE64Encoder;


public class WS {

	public String[] return_hash(String name){
		String[] result = new String[2];
		
		//Set position 0 of resultant string to the supplied name
		result[0] = name;
		//Set position 1 of resultant string to the hash of supplied name
		result[1] = getHash(name);
		
		return result;
	}
	
	//Simple hashing of a text field
	public static String getHash(String input){
		
		MessageDigest md = null;
		
		try
	    {
	      md = MessageDigest.getInstance("SHA");
	    }catch(NoSuchAlgorithmException e){
	    	System.out.println("No SHA");
		}
	    try
	    {
	      md.update(input.getBytes("UTF-8"));
	    }
	    catch(UnsupportedEncodingException e)
	    {
	    	System.out.println("Encoding error.");
	    }
	    
	    byte raw[] = md.digest();
	    String hash = (new BASE64Encoder()).encode(raw);
	    
	    return hash;
	}
}

Starting a Web service

With the code inserted into our new class we can now start a Web service by right-clicking on the java class file and selecting Web Services -> Create Web service. Keep the default options, which should be the default settings we applied earlier in the preferences, and select Finish. On success, Eclipse will have created another project with which the Web service client will interact with the newly created Web service based on the code above. The client project contains stubs for the exposed methods in the Web service so the client can call it appropriately, more in the "Coding the client to interacting with the Web service" section.

At this stage Apache Tomcat should be running with the Web service and can be accessed at the following URL: http://localhost:8080/PROJECT_NAME/services/JAVA_FILENAME/ (eg. http://localhost:8080/Webservice/services/WS/). You should see some xml generated and complaining that there is no endpoint, this is normal as you are going to the URL directly without any data.

Coding the client to interact with the Web service

With the Web service now running and a client project created we now have to create a new Java class in the client project to interact with the Web service. Do this by creating a new Java class within the Axis2 package that was generated; it should be something like "org.apache.ws.axis2". Note that this new Java class should have a main function as it will be run as a normal Java application when completed. Insert the following code:


package org.apache.ws.axis2;

import java.rmi.RemoteException;
import org.apache.axis2.AxisFault;
import org.apache.ws.axis2.WSStub.*;

public class WSClient {

	private final static String TARGET_EPR = "http://localhost:8080/Webservice/services/WS";
	// CLIENT_TIMEOUT is in milliseconds. It indicates how long the client 
	// should wait for a response from the Web service before it times out (in milliseconds)
	private final static int CLIENT_TIMEOUT = (10*60*1000);
	
	public static void main(String[] args) {
		String name = "James Ho";
		String[] response = hashString(name);
		
		if(response != null){
			
			System.out.println("Returned name:"+response[0]);
			System.out.println("Returned hash::"+response[1]);
			
		}
	}
	
	public static String[] hashString(String name) {
		String[] result = null;
		try {
			Return_hashResponse response;
			
			WSStub stub = new WSStub(TARGET_EPR);
			stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(CLIENT_TIMEOUT);
			Return_hash returnHash = new Return_hash();
			returnHash.setName(name);
			response = stub.return_hash(returnHash);
			
			result = response.get_return();
			
		} catch (AxisFault e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		
		return result;
	}
}


As mentioned, when we created the Web service client project, Eclipse created Axis2 stubs for the exposed Web service methods. These are within the WSStub.java file (in this scenario) and should contain the return_hash() method, which is now a class of its own called "Return_hash". To understand what methods to use the best thing to do is to examine the class's methods through Eclipse by specifying the class and pausing after typing the period (.) to let Eclipse specify options, or you can examine it within the Java class file.

Running this as a Java application should elicit a response from the Web service and print out it out in the Eclipse console indicating it has passed through the Web service successfully. You have now created your very first Web service -- congratulations you have made it!

Note, with a Mac, especially on Leopard, there appears to be a bug with the way Axis2 parses Java's http.nonProxyHosts option when it has an *, this is solved by setting the following in the VM arguments: -Dhttp.nonProxyHosts=localhost

If you would like to know more information and specifications on Web services please visit the World Wide Web Consortium (W3C) here.

2 comments
cjmei7
cjmei7

All graphics are missing? What's the quality of the post? If the graphics are not necessary, why are they there? May I ask to be fixed? C.-J.

wizard57m-cnet
wizard57m-cnet

Since the original article is over 4 years old, it is unlikely to be "fixed". So, maybe some of the information will be helpful without the images.

Editor's Picks