Hi guys,
well as you know today every software uses web services to extend their functionality.Because of that and many other reasons web services becoming more reliable and powerful technology in the software industry.
What am i going to do?
In this post i am going to explain to you how to write a simple web service and a client which uses those. To do this i am going to use following tools.
- Apache AXIS2 web service engine (JAVA)
- JAVA JDK for you OS
- WSO2 Developer Studio
Apache AXIS2 is a web service engine which means that this is a helper to create web services and clients with soap communication very easily. more information can found here.
WSO2 Developer Studio is a Eclipse IDE with additional features to develop WSO2 product based applications. WSO2 is a one of the best open source middleware platform development company in the world and owner of many mind blowing open source products which are takes web services to the edge. you can find more about WSO2 here and about WSO2 developer studio from here
Lets get started then! :)
How to setup your environment?
Okay.. don't get scared now, most of the people scared of hearing the word setup your environment, setting up the environment is pretty much easy.
Setting up AXIS2
- Download the AXIS2 from here. Get the latest version. Get the .zip package.
- Now extract it to a folder you want.
- Now lets install JAVA JDK for your OS.
If you are using windows
you can download the JDK and just install and set the environment path to the JAVA bin folder. All instruction can be found here.
If you are using Linux
you can download and setup JDK by using these instruction given here.
- Okay now installing Java is done. Lets setup the environment variable for the AXIS2.
If you are using windows
just add a new environment variable "AXIS2_HOME" in the environment variable dialog. set the path to "drive:\your\path\to\axis2-1.5" just get the path to folder where the axis2 and open that folder and copy the path from the window. Also add another variable "JAVA_HOME" and set it's value to "C:\Program Files\Java\jdk1.6.0_16" ( can be different in your machine).
If you are using Linux
open up the ~/.bashrc file and add both paths for jdk and axis2 home paths as follow. you can find java path as to the above installation guide for JAVA in linux.
Run following command in terminal
$gedit ~/.bashrc
Then add following two lines at end of the file with the correct path strings to each home folder in your computer and save.
export JAVA_HOME="/usr/lib/jvm/java-7-openjdk-amd64/jre"
export AXIS2_HOME="/home/marcus/Documents/Installed_Programs/axis2-1.5"
- Now you can run the AXIS2 server and see.
In Windows
In Linux
open up the terminal and go to the location of you axis2 home folder
$cd /home/axis2-1.5/bin
then run the axis2server.sh using
$./axis2server.sh
(If this did not work give execution rights using
$chmod +x axis2server.sh
and run again)
Setting up WSO2 Developer Studio
- Download the IDE from here
- Extract the package to a location of your choise
- Just double click the eclipse.exe if you are using windows. If you are using Linux, click on the eclipse.sh. (if clicking eclipse.sh didn't work give execution right to it using $chmod +x eclipse.sh command on terminal by navigating to the eclipse home folder).
- Now eclipse should be up and running.
Creating the Service
In this section I'm going to talk about how to create a service. There are two ways that can create a web service.
- Top Down - Generate the service using WSDL
- Bottom Up - Create the service from sketch
Here I'm going to talk about how to create web service using Bottom Up method, form sketch. Top Down generation can be found in this article.
Before going in to service creation we can define the axis2 runtime location. For that open the developer studio and then navigate to Window -> Preferences -> Web Services -> Axis2 Preferences
In the Axis2 runtime location browse the path to your axis2 home folder and click Apply and OK.
Let's create a axis 2 service project! :D
1. Let's create a axis2 service project by navigating to Developer Studio->Open Dashboard->Axis2 Service Project
or File->New->Other->WSO2->Service Hosting->Project Types->Axis2 Service Project
2. Click on the Axis2 Service Project and you will get the following dialog to choose to Create a New Axis2 Service or to Create a New Axis2 Service using WSDL File.
Choose the Create a New Axis2 Service option.
3. Click Next and Give a Project name and Package name. In this example Project name is "MySimpleService" and Packagename is "com.example.simpleservice".
Class name is "Service".
4. Click Finish and you just created your service project. Your project structure will look like following image.
5. Now just write the code to your service. My service code is shown below.
package com.example.simpleservice;
import java.util.HashMap;
import java.util.Map;
/**
* @author marcus
* @class Service
* @description Class which holds the services.
*/
public class Service {
// Collection of items in the order processing system
private static HashMap<String, String> itemList = new HashMap<String, String>();
/**
* Constructor for the service class.
*/
public Service() {
itemList.put("Fruits", "Apple");
itemList.put("Animal", "Cat");
}
/**
* Get the list of available items
*
* @return Item[]
* @return
*/
public String[] getItems() {
int iterator = 0;
int count = itemList.size();
String[] items = new String[count];
// Get the items available in the itemlist map
for (Map.Entry<String, String> entry : itemList.entrySet()) {
String item = entry.getValue();
items[iterator] = item;
iterator++;
}
// Return array of items
return items;
}
/**
* Set the items to the order system
*
* @return void
* @param item
*/
@SuppressWarnings("static-access")
public void setItem(String type, String item) {
this.itemList.put(type, item);
}
/**
* Find a item by name
*
* @return Item
* @param name
*/
public String findItem(String type) {
return (String) itemList.get(type);
}
}
6. Now we have to export this as a deployable archive. To do that
right click on the project folder inside the explorer -> select "Export Project as Deployable Archive"
or
Right click on the project-> Export->WSO2 Platform Distribution->Deployable WSO2 Archive
7. Click Next and Deploying dialog will appear. Browse a place to create the archive. I choose the desktop ... always :D
8. Now if you go to the place you choose to create the archive you see a file like as follow.
9. Now service creation is finished.
Deploying the Service in Axis2 Server
1. To deploy the service navigate to the repository folder in the axis2 home folder.
2. Now go in to the repository folder and select the services folder.
3. Copy the MySimpleService_1.0.0.aar file in to the services folder.
4. Then go to the axis2 front end using http://localhost:8080/axis2/services/
5. Your service will be listed there.
Writing a Client to access the services
Deploying the service to the axis server is done. now what we have to do is access those services and use them to do some work.
To create a client we can use the WSO2 developer studio and it will be easy to create a client.
1. Go to the file->new->Other->WSO2->Service Hosting->Project Types and select Generate Axis2 Service Client. Then click Next.
2. Then a client wizard will appear. From that dialog select WSDL URI option and copy the WSDL URL that can be found by clicking you deployed service in axis2 server. By clicking on the service shown in the axis2 server service list, will direct you to your service WSDL. In this case URL will look like follow
http://localhost:8080/axis2/services/Service?wsdl
copy this link and put it in the text box of the client wizard. (make sure that your axis2server is up and running)
3. Click next and then a dialog will appear to select a project for the client to be generated in. But in this case we don't have a project created for the client. So we can create a new project by clicking the create a new project link which placed below the Browse button.
4. After clicking the create a new project link you'll get a dialog to create the project. It is the normal project creation window. Add the project name as MySimpleClient and click Next
5. Now we have to set class paths to the libraries available in the axis2 lib folder. From the dialog which appear after clicking Next select the libraries tab
From above window click the
Add External Libraries from the right hand side menu. Then navigate to you
axis2 home folder and go to the
lib folder and select all the Jars,
except folder called
endorsed
Now we have to add another Jar called wso2 secure vault to the libraries.
This can be downloaded from here.
6. Now click finish and you will be directed to the following dialog
click Next.
7. Following dialog will appear.
check all the above configuration as to the above image configured. Or you can go with the default configuration which comes when the dialog open. but select the Namespace to you application Namespace. Which is here shown as "http://simpleservice.example.com".
For this example we will use this configurations.
Then click finish.
8. Then your client project generation is done and now all we have to do is write the client program. After generation with above configuration project structure will look like follow.
9. Now add a class with main method. In this example that class is called "Client".
10. Now all we have to do is call the Services and use them to do our work.
Following code will use all the services in this example service. All code explanation available as comments in the code.
package com.example.simpleservice;
/**
* @author marcus
* @class Client
* @description Client program to access the service and use the exposed services
*/
public class Client {
// URL for the service deployed in axis2 server
private static final String URL = "http://localhost:8080/axis2/services/Service";
/**
* Main method to run the program
* @return void
* @param args
*/
public static void main(String[] args) {
// Declare serviceStub: which defines all the attribute in service as to the WSDL
ServiceStub stub = null;
try {
// Initialize the service stub by providing the URL to service
stub = new ServiceStub(URL);
// Define the SetItem service
SetItem setIt = new SetItem();
/** Set the parameters to the service method
* Each set methods has the parameter name of the method:
* Ex: for "type" parameter set method is setType()
**/
setIt.setItem("Elephant");
setIt.setType("Nia");
// Calling the setItem function using service stub
stub.setItem(setIt);
System.out.println("\nGet the available Items\n");
// Define the GetItem service
GetItems getItems = new GetItems();
/**
* getItem service doesn't take parameters but give out a response
* here it is a captured by the GetItemResponse type
**/
GetItemsResponse response = stub.getItems(getItems);
// Get the return from the getItem service and put it to the suitable data structure
String[] items = response.get_return();
for (String item : items) {
System.out.println("Name: " + item);
}
// Define the FindItem service
FindItem findItem = new FindItem();
// Set the parameter for the findItem service method
findItem.setType("Animal");
// Capture the response of the findItem service
FindItemResponse findResponse = stub.findItem(findItem);
// Get the response and add it to the suitable data structure
String foundItem = findResponse.get_return();
if (foundItem != null) {
System.out.println("\nFound Item by name\n");
System.out.println("Name: " + foundItem);
} else {
System.out.println("No Item Found");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
11. Now all you have to do is run the Client and see the output. In this example output can be like
Warning are about the logging mechanism which we can ignore for now :D
So this is how we write a service using axis2 and write a client to access them.
If you have any doubts or problems please leave a comment with prefix of "Question" or "Doubt". I'll do my best to answer those.