Thursday, November 27, 2014

Returning multiple values from an Axis2 Service

Most of you who wants to create a quick Axis2 Service to mock a web-service would encounter a situation where you want to return more than 1 value from a service. You can simply return more than 1 value by returning a Hashmap. But this would return the values in the following format.

  value1



  value2



  value3




This would be a nightmare for any developer who would want to use the response from this service to perform message mediator or orchestration as all the XML elements share the same name ‘return’ making it impossible to extract values through XPath.

Solution for this problem is to return an object type from the Axis2 service. Given below is a sample code snippet on how this can be done.

Axis 2 service


public workOrderResponse getWorkOrders(String version){
             System.out.println( "City Works Service,get workorders ");
             return new workOrderResponse();
           
       }

WorkOrderResponse class

public class workOrderResponse {

       String workOrderId;
       String name;
       String address;

       public workOrderResponse (){
             workOrderId= "A1234";
             name= "WSO2 Inc";
             address=  "787 Castro Street, Mountain View, CA 94041";
            
       }

       public String getWorkOrderId() {
             return workOrderId;
       }

       public void setWorkOrderId(String workOrderId) {
             this.workOrderId = workOrderId;
       }

       public String getName() {
             return name;
       }

       public void setName(String name) {
             this.name = name;
       }

       public String getAddress() {
             return address;
       }

       public void setAddress(String address) {
             this.address = address;
       }

}


By returning an object, the Axis2 service would return values with correct XML elements names. XML element names would correspond to the variable names in the object. Given below is a sample response from the above service.


      A1234
      WSO2 Inc
      787 Castro Street, Mountain View, CA 94041




No comments:

Post a Comment