Web services use SOAP faults to report fault cases back to clients. The faults can be generated from the SOAP framework in a case of invalid SOAP messages, invalid security tokens or they can be generated from the service business logic itself. The fault messages may contain simply a string indicating the error, or it may contain lot of details which could be useful to the clients find the problem. In fact the format of the SOAP fault is a standard. But services can send custom details within the details element in a SOAP fault.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <soapenv:Fault>
         <faultcode>soapenv:Sender</faultcode>
         <faultstring>..</faultstring>
         <detail> You Custom Message </detail>
      </soapenv:Fault>
   </soapenv:Body>
</soapenv:Envelope>

And you can define the schema of your custom fault message in a WSDL, so the clients can prepare to handle fault scenarios. In facts tools like Apache Axis2 WSDL2C, WSDL2Java tool will help you to work with custom faults when they are defined in the WSDL.  Here is an example section of a WSDL with an operation which can throw two faults “MyFirstException”, “MySecondException”.

<!-- fault schemas -->
<types>
 <schema ..>
  <element name="MyFirstException">
   <complexType>
    <sequence>
     <element name="text" type="xsd:string"/>
    </sequence>
   </complexType>
  </element>
  <!-- fault element -->
  <element name="MySecondException">
   <complexType>
    <sequence>
     <element name="number" type="xsd:int"/>
    </sequence>
   </complexType>
  </element>
 </schema>
</types>

<!-- the fault messages -->
<message name="MySecondExceptionFault">
 <part name="fault" element="ns1:MySecondException"/>
</message>

<message name="MyFirstExceptionFault">
 <part name="fault" element="ns1:MyFirstException"/>
</message>

<!-- operation to throw fault -->
<portType name="MyType">
 <operation name="myOperation">
  <input message="tns:myOperationRequest"/>
  <output message="tns:myOperationResponse"/>
  <fault name="MySecondException" message="tns:MySecondExceptionFault"/>
  <fault name="MyFirstException" message="tns:MyFirstExceptionFault"/>
 </operation>
</portType>

Note that the operation “myOperation” is throwing faults “MyFirstException”, “MySecondExcpetion”. If you generate the Java code for this operation, it would be simple as this,

public MyOperationRequest
MyOperation(MyOperationRequest) throws
          MyFirstExcpetion,
          MySecondExcpetion {
  // here is your business logic
}

Anyway we are going to write codes in ‘C’ language, which doesn’t have similar exception mechanism. Let see how we can do it, starting with writing the service and then writing a client.

Writing Services With Custom SOAP Faults

Once you generate the ‘C’ codes for the WSDL using WSDL2C tool, you should first have a look at the skeleton header file.

    /**
     * the generated fault union for operation "myOperation|urn:myuri:1.0",
     * in a case you want to return a fault, put the appropriate adb object for
     * the union variable pointer comes as the last parameter of the method
     */
    typedef union
    {
        adb_MyFirstException_t* MyFirstException;
        adb_MySecondException_t* MySecondException;

    } axis2_skel_MyService_myOperation_fault;

    /**
     * auto generated function declaration
     * for "myOperation|urn:myuri:1.0" operation.
     * @param env environment ( mandatory)
     * @param _myOperation of the adb_myOperation_t*
     *
     * @return adb_myOperationResponse_t*
     */
    adb_myOperationResponse_t* axis2_skel_MyService_myOperation(const axutil_env_t *env,
                                      adb_myOperation_t* _myOperation,
                                      axis2_skel_MyService_myOperation_fault *fault);

And at the very end of the header file, you will see an enumeration of constants corresponding to each fault is generated.

    typedef enum
    {
        AXIS2_SKEL_MYSERVICE_ERROR_NONE = AXIS2_SKEL_MYSERVICE_ERROR_CODES_START,

        AXIS2_SKEL_MYSERVICE_MYOPERATION_FAULT_MYFIRSTEXCEPTION,
        AXIS2_SKEL_MYSERVICE_MYOPERATION_FAULT_MYSECONDEXCEPTION,

        AXIS2_SKEL_MYSERVICE_ERROR_LAST

    } axis2_skel_MyService_error_codes;

That’s all you need to aware of. The plan is whenever you need to report the fault, you have to do three things inside the business logic.

  1. Create the adb object for the fault, in this case either “adb_MyFirstException_t” or “adb_MySecondException_t” and set it to the fault pointer variable.
  2. Set the constant corresponding to the fault using “AXIS2_ERROR_SET” function
  3. return NULL

Here is an example how you do it inside the actual business logic code.

    adb_myOperationResponse_t* axis2_skel_MyService_myOperation(const axutil_env_t *env,
                                      adb_myOperation_t* myOperation,
                                      axis2_skel_MyService_myOperation_fault *fault )
    {
        /* the buisness logic */

        ....

        if(/* checking some condition to throw the "MyFirstException" fault */)
        {
          /* 1. Creating the adb object and set it to the fault pointer variable */
          adb_MyFirstException_t *exp = NULL;
          exp = adb_MyFirstException_create(env);
          adb_MyFirstException_set_text(exp, env, "this is the exception 1"); /* custom value */

          fault->MyFirstException = exp;

          /* 2. Setting the error constant corrosponding to the fault */
          AXIS2_ERROR_SET(env->error,
                      AXIS2_SKEL_MYSERVICE_MYOPERATION_FAULT_MYFIRSTEXCEPTION,
                      AXIS2_FAILURE);

          /* 3. Returning NULL */
          return NULL;
        }

        else if(/* checking some condition to throw the "MySecondException" fault */)
        {
          /* 1. Creating the adb object and set it to the fault pointer variable */
          adb_MySecondException_t *exp = NULL;
          exp = adb_MySecondException_create(env);
          adb_MySecondException_set_number(exp, env, 2);/* custom value */

          fault->MySecondException = exp;

          /* 2. Setting the error constant corrosponding to the fault */
          AXIS2_ERROR_SET(env->error,
                      AXIS2_SKEL_MYSERVICE_MYOPERATION_FAULT_MYSECONDEXCEPTION,
                      AXIS2_FAILURE);
          /* 3. Returning NULL */
          return NULL;
        }

        /* return the response in no fault scenario */
        return response;
    }

That’s all you have to do, Axis2/C will make sure to build the fault and put your custom message inside the details element.

Writing Clients to Handle custom SOAP Faults

After generating the code for clients using WSDL2C tool, this time you should look at the generated stub header file first. It is just similar to the skeleton header files may be except all the “skel” prefixes are renamed to “stub” and additional parameter “stub” for the operation.

    /**
     * the generated fault union for operation "myOperation|urn:myuri:1.0",
     * in a case the server return a fault, the corresponding adb object will be loaded for
     * the union variable pointer comes as the last parameter of the method
     */
    typedef union
    {
        adb_MyFirstException_t* MyFirstException;
        adb_MySecondException_t* MySecondException;

    } axis2_stub_MyService_myOperation_fault;

    /**
     * auto generated function declaration
     * for "myOperation|urn:myuri:1.0" operation.
     * @param env environment ( mandatory)
     * @param _myOperation of the adb_myOperation_t*
     *
     * @return adb_myOperationResponse_t*
     */
    adb_myOperationResponse_t* axis2_stub_MyService_myOperation(axis2_stub_t* stub, const axutil_env_t *env,
                                      adb_myOperation_t* _myOperation,
                                      axis2_stub_MyService_myOperation_fault *fault);

    typedef enum
    {
        AXIS2_STUB_MYSERVICE_ERROR_NONE = AXIS2_STUB_MYSERVICE_ERROR_CODES_START,

        AXIS2_STUB_MYSERVICE_MYOPERATION_FAULT_MYFIRSTEXCEPTION,
        AXIS2_STUB_MYSERVICE_MYOPERATION_FAULT_MYSECONDEXCEPTION,

        AXIS2_STUB_MYSERVICE_ERROR_LAST

    } axis2_stub_MyService_error_codes;

Looking at this, you may have got the idea how to differentiate what fault is being thrown by the server and how to extract the parameters of the custom fault. Here is an example client code correctly handling exceptions.

    /* the structure to keep the fault */
    axis2_stub_MyService_myOperation_fault fault;

    ..... /* the part preparing the request is ignored here */

    /* invoking the "myOperation" operation */
    response = axis2_stub_op_MyService_myOperation(stub, env, op, &fault);

    /* checking the response == NULL implies fault is sent  */
    if(response == NULL)
    {
        /* getting the error number to distinguish the fault */
        error_code = env->error->error_number;

        /* compare error code with constants of each faults */
        if(error_code == AXIS2_STUB_MYSERVICE_MYOPERATION_FAULT_MYFIRSTEXCEPTION) {

            /* extracting out the adb objects */
            axis2_char_t *text = adb_MyFirstException_get_text(fault.MyFirstException, env);

            /* do a printf of the message */
            printf("My First Exception called: with param %s\\n", text);

        }
        else if(error_code == AXIS2_STUB_MYSERVICE_MYOPERATION_FAULT_MYSECONDEXCEPTION) {
            /* extracting out the adb objects */
            int number = adb_MySecondException_get_number(fault.MySecondException, env);

            /* do a printf of the message */
            printf("My Second Exception called: with param %d\\n", number);

        }

    }

Note that this feature is available only in the very latest WSDL2C tool. Try to get latest build from Axis2/Java to use this up to date tool.

You can download the WSDL and codes used in this example from here, https://issues.apache.org/jira/secure/attachment/12399724/case45.zip

Once you have a web service, you can write clients to invoke that service from any language, mostly with the help of a framework written in to that particular language. When it comes to C, the most popular choice is Apache Axis2/C framework. When you are using Axis2/C to write web service clients, you need to learn about AXIOM which is a easy to use high performing XML model and the service client API which can be used to actually invoke the service. Lets look at the code.

#include <stdio.h>
#include <axiom.h>
#include <axis2_util.h>
#include <axiom_soap.h>
#include <axis2_client.h>

axiom_node_t *build_om_payload_for_helloworld_svc(
    const axutil_env_t * env);

int
main()
{
    const axutil_env_t *env = NULL;
    const axis2_char_t *address = NULL;
    axis2_endpoint_ref_t *endpoint_ref = NULL;
    axis2_options_t *options = NULL;
    const axis2_char_t *client_home = NULL;
    axis2_svc_client_t *svc_client = NULL;
    axiom_node_t *payload = NULL;
    axiom_node_t *ret_node = NULL;

    /* Set up the environment */
    env = axutil_env_create_all("helloworld.log", AXIS2_LOG_LEVEL_TRACE);

    /* Set end point reference of helloworld service */
    address = "http://localhost:9090/axis2/services/helloworld";

    /* Create EPR with given address */
    endpoint_ref = axis2_endpoint_ref_create(env, address);

    /* Setup options */
    options = axis2_options_create(env);
    axis2_options_set_to(options, env, endpoint_ref);
    axis2_options_set_action(options, env,
                             "http://ws.apache.org/axis2/c/samples/helloworldString");

    /* Set up deploy folder. It is from the deploy folder, the configuration is picked up
     * using the axis2.xml file. You need to set the AXIS2C_HOME variable to the axis2/c
     * installed dir.
     */
    client_home = AXIS2_GETENV("AXIS2C_HOME");
    if (!client_home || !strcmp(client_home, ""))
        client_home = "../..";

    /* Create service client */
    svc_client = axis2_svc_client_create(env, client_home);
    if (!svc_client)
    {
        /* reporting the error */
        printf
            ("Error creating service client, Please check AXIS2C_HOME again\\n");
        AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI,
                        "Stub invoke FAILED: Error code:" " %d :: %s",
                        env->error->error_number,
                        AXIS2_ERROR_GET_MESSAGE(env->error));
        return -1;
    }

    /* Set service client options */
    axis2_svc_client_set_options(svc_client, env, options);

    /* Build the SOAP request message payload using OM API. */
    payload = build_om_payload_for_helloworld_svc(env);

    /* Send request */
    ret_node = axis2_svc_client_send_receive(svc_client, env, payload);

    if (ret_node)
    {
        /* extracting out the content from the response */
        axis2_char_t *om_str = NULL;
        om_str = axiom_node_to_string(ret_node, env);
        if (om_str)
            printf("\\nReceived OM : %s\\n", om_str);
        printf("\\nhelloworld client invoke SUCCESSFUL!\\n");

        AXIS2_FREE(env->allocator, om_str);
        ret_node = NULL;
    }
    else
    {
        AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI,
                        "Stub invoke FAILED: Error code:" " %d :: %s",
                        env->error->error_number,
                        AXIS2_ERROR_GET_MESSAGE(env->error));
        printf("helloworld client invoke FAILED!\\n");
    }

    /* freeing the allocated memory */
    if (svc_client)
    {
        axis2_svc_client_free(svc_client, env);
        svc_client = NULL;
    }

    if (env)
    {
        axutil_env_free((axutil_env_t *) env);
        env = NULL;
    }

    return 0;
}

Here is the implementation of the “build_om_payload_for_helloworld_svc” function that build the request SOAP message using Axiom/C. Note that axiom_element and axiom_node has one to one association. We use node to to navigate the XML, where as axiom_element to store the data.

/* build SOAP request message content using OM
           <ns1:greet xmlns:ns1="http://ws.apache.org/axis2/services/helloworld">
                <text>Hello World</text>
           </ns1:greet>
*/
axiom_node_t *
build_om_payload_for_helloworld_svc(
    const axutil_env_t * env)
{
    axiom_node_t *helloworld_om_node = NULL;
    axiom_element_t *helloworld_om_ele = NULL;
    axiom_node_t *text_om_node = NULL;
    axiom_element_t *text_om_ele = NULL;
    axiom_namespace_t *ns1 = NULL;
    axis2_char_t *om_str = NULL;

    ns1 =
       axiom_namespace_create(env, "http://ws.apache.org/axis2/services/helloworld",
                               "ns1");
    helloworld_om_ele =
        axiom_element_create(env, NULL, "greet", ns1, &helloworld_om_node);
    text_om_ele =
        axiom_element_create(env, helloworld_om_node, "text", NULL, &text_om_node);
    axiom_element_set_text(text_om_ele, env, "Hello World!", text_om_node);
    om_str = axiom_node_to_string(helloworld_om_node, env);

    if (om_str)
    {
        printf("\\nSending OM : %s\\n", om_str);
        AXIS2_FREE(env->allocator, om_str);
        om_str = NULL;
    }
    return helloworld_om_node;
}

So lets see how the same thing is done with C++. For C++ we use WSO2 WSF/C++

#include <stdio.h>
#include <WSSOAPClient.h>
#include <OMElement.h>
#include <iostream>
#include <AxisFault.h>
using namespace std;
using namespace wso2wsf;

OMElement build_om_payload_for_helloworld_svc();

int main()
{
    WSSOAPClient * sc = new WSSOAPClient("http://localhost:9090/axis2/services/helloworld");
    sc->initializeClient("helloworld_blocking.log", AXIS2_LOG_LEVEL_TRACE);
    {
        /* generating the payload */
        OMElement * payload = build_om_payload_for_helloworld_svc();

        OMElement * response;
        try
        {
            /* invoking the web service */
            response = sc->request(payload, "http://ws.apache.org/axis2/c/samples/helloworldString");

            /* printing the response */
            if (response)
            {
                cout << endl << "Response: " << response << endl;
            }
        }

        /* handling the fault */
        catch (AxisFault & e)
        {
            if (sc->getLastSOAPFault())
            {
                cout << endl << "Response: " << sc->getLastSOAPFault() << endl;
            }
            else
            {
                cout << endl << "Response: " << e << endl;
            }
        }
        delete payload;
    }
    delete sc;
}

You can see lines of code is reduced a lot. And you can see it from the code to build the request XML as well.

/* building the request soap message
   <ns1:greet xmlns:ns1="http://ws.apache.org/axis2/services/helloworld">
        <text>Hello World</text>
   </ns1:greet>
 */
OMElement build_om_payload_for_helloworld_svc()
{
    OMNamespace * ns = new OMNamespace("http://ws.apache.org/axis2/services/helloworld", "ns1");
    OMElement * payload = new OMElement(NULL,"greet", ns);
    OMElement * child = new OMElement(payload,"text", NULL);
    child->setText("Hello World!");

    return payload;
}

WSF/C++ is build on top of Axis2/C. You can see the WSF/C++ API is designed very carefully to make it easy to use without breaking the flexibility provided in the C API. So C++ developers can straightaway use WSF/C++ to develop their web service consumers. Anyway Axis2/C API still has the power of embedding easily in to scripting languages (Like it is done in WSF/PHP, WSF/Ruby) and probably deploy in legacy systems that doesn’t support C++ compiled binaries. So you have the options to select the most sutiable one for your application.

In Apache Axis2/C AXIOM is used as the basic object model to represent XML. AXIOM provide a DOM like API that allows to traverse and build the XML very easily.

Anyway in underneath, AXIOM is different from DOM, as it has used some techniques to optimize the parsing of the XML as suited specially for SOAP message processing in web services. For an example the SOAP processor can validate a SOAP message by reading only some parts of the SOAP header fields, and if it is not valid, they can completely skip processing the body part. And since AXIOM is designed to built from a stream of data retrieved from a transport, sometimes SOAP processors can validate the message without the need of reading the full stream.

Anyway there should be lot of application that needs this optimization in parsing XMLs. They can easily adapt AXIOM/C to their application. Here is an AXIOM/C tutorial that covers both parsing and building XMLs from AXIOM. In this post I’d like to mention a code that can be used to retrieve an AXIOM from a String (char buffer) which we call as deserialization.

    axiom_node_t* AXIS2_CALL
    deserialize_my_buffer (
        const axutil_env_t * env,
        char *buffer)
    {
        axiom_xml_reader_t *reader = NULL;
        axiom_stax_builder_t *builder = NULL;
        axiom_document_t *document = NULL;
        axiom_node_t *payload = NULL;

        reader = axiom_xml_reader_create_for_memory (env,
            buffer, axutil_strlen (buffer),
            AXIS2_UTF_8, AXIS2_XML_PARSER_TYPE_BUFFER);

        if (!reader)
        {
            return NULL;
        }

        builder = axiom_stax_builder_create (env, reader);

        if (!builder)
        {
            return NULL;
        }
        document = axiom_stax_builder_get_document (builder, env);
        if (!document)
        {
            AXIS2_LOG_ERROR (env->log, AXIS2_LOG_SI,
                    "Document is null for deserialization");
            return NULL;
        }

        payload = axiom_document_get_root_element (document, env);

        if (!payload)
        {
            AXIS2_LOG_ERROR (env->log, AXIS2_LOG_SI,
                    "Root element of the document is not found");
            return NULL;
        }
        axiom_document_build_all (document, env);

        axiom_stax_builder_free_self (builder, env);

        return payload;
    }

Regardless of the fact this piece of code is been used many time by Axis2 and application that uses Axis2, it has never been identified as a core AXIOM function. I think it is better we have this function as an alternative method to create an axiom.

axiom_node_t *AXIS2_CALL
axiom_node_create_from_buffer(const axutil_env_t *env, axis2_char_t *buffer);

I already suggested this in Axis2/C mailing list and hopefully it will be included from the next release.

Here when we create the axiom tree function from the character buffer, we used “axiom_xml_reader_create_for_memory” function. Anyway whenever transport read data stream from wire it always uses the “axiom_xml_reader_create_for_io” function.

    /**
     * This create an instance of axiom_xml_reader to
     * parse a xml document in a buffer. It takes a callback
     * function that takes a buffer and the size of the buffer
     * The user must implement a function that takes in buffer
     * and size and fill the buffer with specified size
     * with xml stream, parser will call this function to fill the
     * buffer on the fly while parsing.
     * @param env environment MUST NOT be NULL.
     * @param read_input_callback() callback function that fills
     * a char buffer.
     * @param close_input_callback() callback function that closes
     * the input stream.
     * @param ctx, context can be any data that needs to be passed
     * to the callback method.
     * @param encoding encoding scheme of the xml stream
     */
    AXIS2_EXTERN axiom_xml_reader_t *AXIS2_CALL
    axiom_xml_reader_create_for_io(
        const axutil_env_t * env,
        AXIS2_READ_INPUT_CALLBACK read_callback,
        AXIS2_CLOSE_INPUT_CALLBACK close_callback,
        void *ctx,
        const axis2_char_t * encoding);

As you may have noticed it requires us to implement a “read_callback” function. Here is an example function prototype to implement this callback.

    int AXIS2_CALL
    some_function(
            char *buffer,
            int size,
            void *ctx);

This function will be called by the parser as required to parse the XML read from some stream.

So if your application involves reading data from a stream you are always recommended to use this function (i.e. “axiom_xml_reader_create_for_io”) instead of “axiom_xml_read_create_for_buffer” to create the AXIOM model more effectively.

Axis2/C ADB is a C language binding to the XML schema. ADB object model represents an XML specific to a given schema in a WSDL. You can use the Axis2 codegen tool to generate ADB codes for your WSDL and use that to build and parse your XMLs. The idea is, if you use ADB to build and parse your xmls, it will be really easy to do that and you don’t need to know or understand anything about the schema or the wsdl.

Apache Axis2/C to can be used to send and receive binaries as MTOM, SWA or base64 encoded. But ADB generated code still support to send and receive base64 encoded binaries only. So if you use contract first approach  with Axis2/C (i.e start with the WSDL, then write the service based on that), you have to use base64-encoded (non-optimized) as the binary transferring method. Note that you can use the other methods like MTOM or SWA, if you write the code to build and parse the xmls from AXIOM which is a general model for XML like DOM.

Say you have an element with base64Binary type in your request XML. So the schema for that element would be,

<xs:complexType name="Person">
    <xs:sequence>
        <xs:element name="image" type="xs:base64Binary"/>
        ... <!-- some more elements -->
    </xs:sequence>
</xs:complexType>

After you code generated, you will get the adb_person.h and adb_person.c files with the following function prototypes and the implementations,

        /**
         * Constructor for creating adb_Person_t
         * @param env pointer to environment struct
         * @return newly created adb_Person_t object
         */
        adb_Person_t* AXIS2_CALL
        adb_Person_create(
            const axutil_env_t *env );

        /**
         * Free adb_Person_t object
         * @param  _Person adb_Person_t object to free
         * @param env pointer to environment struct
         * @return AXIS2_SUCCESS on success, else AXIS2_FAILURE
         */
        axis2_status_t AXIS2_CALL
        adb_Person_free (
            adb_Person_t* _Person,
            const axutil_env_t *env);

        /**
         * Getter for image.
         * @param  _Person adb_Person_t object
         * @param env pointer to environment struct
         * @return axutil_base64_binary_t*
         */
        axutil_base64_binary_t* AXIS2_CALL
        adb_Person_get_image(
            adb_Person_t* _Person,
            const axutil_env_t *env);

        /**
         * Setter for image.
         * @param  _Person adb_Person_t object
         * @param env pointer to environment struct
         * @param arg_image axutil_base64_binary_t*
         * @return AXIS2_SUCCESS on success, else AXIS2_FAILURE
         */
        axis2_status_t AXIS2_CALL
        adb_Person_set_image(
            adb_Person_t* _Person,
            const axutil_env_t *env,
            axutil_base64_binary_t*  arg_image);

So you can manipulate the person element in c language using the create, get, set and free function.

    /* here the env is the axutil_env_t* instance - the axis2/c environment */
    FILE *f = fopen("./images/person.png", "r+");
    int binary_count;
    /* binary read a function you may write to read the binary data to the
     variable binary and the count to the variable binary_count */
    unsigned char *binary = binary_read(f, env, &binary_count);
    axutil_base64_binary_t *base64 = axutil_base64_binary_create_with_plain_binary(
                                        env, binary, binary_count);

    adb_Person_t *person = adb_Person_create(env);
    adb_Person_set_image(person, env, base64);

You can set this adb person directly to your request or to a setter of another adb instance to complete the ADB tree. So this way you can send binaries (as base64 encoded) using the Axis2/C ADB generated code.

Few weeks back I wrote a blog post about Writing RESTful Services in C which explain the use of Axis2/C REST API. Basically when you provide a HTTP Method (GET, POST, PUT or DELETE) and a HTTP URL, it is matched with a given HTTP method and a URL pattern in order to identify the operation and extract out the request parameters. For the example mentioned in the above blog, we can summarize the URL mapping like this.

Operation HTTP Method URL Pattern Example Requests
getSubjects GET subjects GET subjects
getSubjectInfoPerName GET subjects/{name} GET subjects/maths
getStudnets GET students GET students
getStudnetsInfoPerName GET students/{name} GET students/john
getMarksPerSubjectPerStudent GET students/{student}/marks/{subject} GET students/john/marks/maths

You can watch an application with this URL mapping in live, written using WSF/PHP which in fact run Axis2/C algorithms underneath.

Last week I updated this REST mapping algorithm and started a discussion about the changes on Axis2/C Dev list. I thought it would be better explain the idea on by blog too.

What the early algorithm (before my changes) did was, it search each pattern in the order it was declared, and returns when a match is found. Sequential searching for a matching pattern can reduce the performance as the number of operations grows. So my solutions was to keep the url pattern in a multi level (recursive) structure and match the url from one level to another.

Here is the structure of the ‘c struct’. (defined in src/core/util/core_utils.c)

/* internal structure to keep the rest map in a multi level hash */
typedef struct {
    /* the structure will keep as many as following fields */

    /* if the mapped value is directly the operation */
    axis2_op_t *op_desc;

    /* if the mapped value is a constant, this keeps a hash map of
    possible constants => corrosponding map_internal structure */
    axutil_hash_t *consts_map;

    /* if the mapped value is a param, this keeps a hash map of
    possible param_values => corrosponding_map_internal structre */
    axutil_hash_t *params_map;

} axutil_core_utils_map_internal_t;

Here is how it will looks like when the above URL pattern set (shown in the above table) is kept inside this multi-level (recursive) structure.

svc->op_rest_map  (hash)
                |
            "GET:students" --------- axutil_core_utils_map_internal_t (instance)
                |                                            |
                |                                        op_desc (axis2_op_t* for "GET students" op)
                |                                            |
                |                                        consts_map (empty hash)
                |                                            |
                |                                        params_map (hash)
                |                                                         |
                |                                                      "{student_id}" ------------- axutil_core_utils_map_internal_t (instance)
                |                                                                                            |
                |                                                                                op_desc (axis2_op_t* for "GET students/{student_id}" op)
                |                                                                                            |
                |                                                                                parms_map (empty hash)
                |                                                                                            |
                |                                                                                 const_map (hash)
                |                                                                                            |
                |                                                                                        "marks" ------------------- axutil_core_utils_map_internal_t (instance)
                |                                                                                                                            |
                |                                                                                                                    op_desc (NULL)
                |                                                                                                                            |
                |                                                                                                                   consts_map (empty hash)
                |                                                                                                                            |
                |                                                                                                                   params_map (hash)
                |                                                                                                                            |
                |                                                                                                                      "{subject_id}" ----------- axutil_core_utils_map_internal_t (instance)
                |                                                                                                                                                                               |
                |                                                                                                                                       op_desc (axis2_op_t* for "GET students/{student_id}/marks/{subject_id}" op)
                |                                                                                                                                                                               |
                |                                                                                                                                                                 consts_map / params_map (Both NULL)
                |
            "GET:students" --------- axutil_core_utils_map_internal_t (instance)
                                                            |
                                                        op_desc (axis2_op_t* for "GET students" op)
                                                            |
                                                        consts_map (empty hash)
                                                            |
                                                        params_map (hash)
                                                            |
                                                      "{student_id}" ------------- axutil_core_utils_map_internal_t (instance)
                                                                                                          |
                                                                                  op_desc (axis2_op_t* for "GET students/{student_id}" op)
                                                                                                          |
                                                                                             consts_map / params_map (Both NULL)

This structure is build at the time the server initialize the services. (from the “axis2_svc_get_rest_op_list_with_method_and_location” function in src/core/description/svc.c)

As each request hit the service, the request HTTP method and the URL is matched (which we call ‘rest dispatching’) with the above structure using the following algorithm. (defined in the “axis2_rest_disp_find_op” function in src/core/engine/rest_disp.c). Note that here we are extracting out the user REST parameters as well, but it is not shown in here.

  1. The request URL is spitted in to URL components from ‘/’ character. Retrive the instance of axutil_core_utils_map_internal_t  from the svc->rest_map to the varaible ‘mapping_struct’.
  2. Check the existance of URL components, count(URL components) > 0.
  3. If it doesn’t exist any URL components, get the value of mapping_struct->op_desc where the mapping_struct is the current mapping instance of axutil_core_utils_map_internal_t. if the mapping_struct->op_desc is not NULL, we found the operation. If it is NULL just exit returning NULL.
  4. Else If some URL component(s) exist, check the most former URL component in the mapping_struct->const_map hash. If mapping_struct->const_map['former_url_component'] is not NULL, assign the mapping struct->const_map['former_url_component'] value to mapping_struct and follow the step 2 with the remaining URL components. (note that here hash['key'] syntax is used to take the value for the key from the hash ‘hash’. If that returns TRUE, we found the opeartion, if not countine to step5.
  5. if mapping_struct->const_map['former_url_component'] is NULL, match the former url component with each key (which is a URL component pattern) in mapping_struct->param_map hash. (We use the function  “axis2_core_utils_match_url_component_with_pattern” in src/core/util/core_utils.c to map URL component with the URL component pattern). If matching pattern found assign the mapping_struct->param_map['key'] to mapping struct and follow the step 2 with the remaining URL components. If that returns TRUE for some key it will be the matching operation.

Where as the earlier algorithm can be simplified to,

  1. Match the request URL with URL patterns of each operation. This will be like calling the function “axis2_core_utils_match_url_component_with_pattern” (mentioned in step5 of the above algorithm) for the complete URL rather than for a URL component
  2. If the pattern is matched, matching operation is the selected operation for the request.

I approximately calculated the time complexity of both of these algorithm.

Here is the time complexity of the later described algorithm.

Average time complexity of iterating ‘n’ number of operations n/2 = O(n)
Time complexity of matching pattern with a URL with the length ‘p’ (complexity of the ‘axis2_core_utils_match_url_component_with_pattern’ function) O(p^2)
Complete time complexity of the algorithm O(n*p^2)

Time complexity of the formerly described algorithm. (which is currently in the SVN).

Time Complexity of a Hash Search O(1)
Average Number of has searches required. This is the average number of levels in the tree of recursive structures drawn above long(n)/2 = O(log(n))
Time complexity of matching pattern with a URL component with the average length ‘d’, d < p (p = the length of the complete URL) O(d^2)
Number of time pattern matching is required = number of param components in the URL = k, k < p/d (p = the length of the url, d = average length of the URL component)/ k = O(k)
Complete time complexity of the algorithm O(log(n)*d^2*k)

Considering the facts, O(logn) < O(n),d < p and k < p/d we can safely conclude

O(long(n)*d^2*k) < O(n*p^2)  => The newer algorithm has better (low) time complexity.

However the time complexity is valid only it takes high values for the parameters. For low values  the actual time taken by the newer algorithm can have high values, considering the constant overhead of the recursions and the hash search. So in order to judge the performance of the algorithm, we have to run some test cases and measure the actual times. Possibly a task for the weekend :)

October 18th, 2008Write RESTful Services in C

You can write REST as well as SOAP web services using Apache Axis2/C web services framework. There you can make existing Axis2/C web services RESTful just by providing the URL patterns and the HTTP methods to each operation in  the services.xml which act as a simple descriptor for an Axis2/C service.

So if we rewrite the RESTful Demo (Written in PHP) using Axis2/C, the services.xml would be something like following.

<service name="RESTfulSchool">
    <!-- mentioning the service library-->
    <parameter name="ServiceClass" locked="xsd:false">RESTfulSchool</parameter>

    <!-- some description -->
    <description>
        The RESTful School demo
    </description>

    <!-- list of operations -->
    <operation name="getSubjects">
            <parameter name="RESTMethod">GET</parameter>
            <parameter name="RESTLocation">subjects</parameter>
    </operation>
    <operation name="getSubjectInfoPerName">
            <parameter name="RESTMethod">GET</parameter>
            <parameter name="RESTLocation">subjects/{name}</parameter>
    </operation>
    <operation name="getStudents">
            <parameter name="RESTMethod">GET</parameter>
            <parameter name="RESTLocation">students</parameter>
    </operation>
    <operation name="getStudentInfoPerName">
            <parameter name="RESTMethod">GET</parameter>
            <parameter name="RESTLocation">students/{name}</parameter>
    </operation>
    <operation name="getMarksPerSubjectPerStudent">
            <parameter name="RESTMethod">GET</parameter>
            <parameter name="RESTLocation">students/{student}/marks/{subject}</parameter>
    </operation>
</service>

We will check how to write the service logic for a operation like “getMarksPerSubjectPerStudent”.

axiom_node_t *
RESTfulSchool_getMarksPerSubjectPerStudent(
    const axutil_env_t * env,
    axiom_node_t * request_payload)
{
    axiom_node_t *student_node = NULL;
    axiom_node_t *subject_node = NULL;

    /* Extracting out the child nodes from the request */
    student_node = axiom_node_get_first_child(request_payload, env);
    subject_node = axiom_node_get_next_sibling(student_node, env);

    /* now we can write the logic to retrieve the marks
       for the given student and subject and build and
       return the response payload */

    return response_payload;
}

As you can see the variables {student} and {subject} given in the services.xml can be easily accessed from your business logic, so we can build the response accordingly.

This way you can build a RESTful web services easily using C language.

I have been working in Linux for a long time and recently moved to windows for a little change. (Hopefully for a little time :) . I find it is really easy to create a project for an Axis2/C client or service with Visual Studio. (I’m using Visual Studio 2005). Anyway I thought it is better to write down it somewhere so someone may find it useful.

Compiling Axis2/C Client

I’m using the math sample for this guide. You can find the source code inside “samples\client\math” directory of any  axis2/c binary or source.

  1. Create a new Visual Studio C++ Project, Select the project type to ‘Win32 Console Application’. Give a name to the project (say ‘math_client’) and in the wizard choose ‘Empty Project’. Then you will have an empty C/C++ project.
  2. Add the source files of the math samples to the project. You can do this by right clicking the project name in the Solution Explorer and clicking Add->Existing Item. After this step you will have axis2_math_stub.h in the Header Files section and the axis2_math_stub.c and math_client.c in the Source files section.
  3. Add Axis2/C include file directory. For this, go to ‘Tools->Options’ from the menu and select ‘Projects and Solutions->VC++ Directories’ from the Tree menu. Select the ‘Include files’ from ‘Show Directories for:’ drop down menu and add the ‘Axis2/C installed dir/includes’ directory. Note that if you follow this to add include directories you only need to do this only once for all the projects. If you want to do this only specifically to this project Go to ‘Project->Properties’ from the menu and Go to ‘Configuration Properties->C/C++->General and add the directories under ‘Additional Include Directories’)
  4. Add Axis2/C library directory. Here is how you do this. Go to the VC++ Directories form mentioned in the step 3 and select ‘Library files’ from the ‘Show Directories for:’ drop down menu. Then add the ‘Axis2/C installed dir/lib’ directory. If you add this here all the following project will use this directory to search for libraries. If you want this only to this project just skip this step and do what is specially mentioned in the step 5.
  5. Declare what libraries to link. For this, go to ‘Project->Properties’ from the menu and select “Configuration Properties->Linker->Input’ from the tree menu. In the ‘Additional Dependencies’ Text box add the following Axis2/C libraries.
    • axiom.lib
    • axutil.lib
    • axis2_engine.lib
    • axis2_parser.lib

    If you skipped the step 4, you have to type the complete path for the libraries.

  6. So that’s all you have to do.  You can compile and run the client using F5 or Ctrl+F5.

Debugging Axis2/C Client

  1. Since by default new project is created with the debug configurations, you can debug the program straight away. To test set a breakpoint at the start of the main function (in the math_client.c) and Run with Debugging (F5)

Compiling Axis2/C Service

We will use the corrosponding math service to create a Visual Studio project. It is same as how you created the math client project. But it has very little differences. (It requires only one additional step)

  1. Create a project in Visual Studio. This time select “Win32 Project” as the project type. Give a name to the project (“math_service”) and continue to the wizard. In there select the “Application Type” to be “DLL” and tick the “Empty Project” so we will have an empty project to build a DLL.
  2. Add the math service sample files to the project. You can find the source for the sample inside “samples\client\math” directory of the Axis2/c distribution.
  3. Add the Axis2/C include directory. If you have done it earlier using “Tools->Options” dialog box you don’t need to do that again since that settings persist over every project. But if you did it using “Project->Properties” dialog box you have to redo the step3 described in compiling client section for this project too.
  4. Add the Axis2/C library directory. Same as the step 4 in compiling client section.
  5. Declare the libraries to link. Same as the step 5 in the comping client section.
  6. Declare the “AXIS2_DECLARE_EXPORT” preprocessor constant. For this go to the “Project->Properties” and click the “Configuration Properties->C/C++->Preprocessor” and add the “AXIS2_DECLARE_EXPORT” at the end separated with a semi column.
  7. That is all needed to compile the service. Now you can build the project using “Build->BuildSolution or just type F7.

Debugging Axis2/C Service

  1. After you compile the source, you cand find the resulted DLL inside the debug directory of your project directory. Just copy it to the <axis2 installed dir>\services\math directory replacing math.dll file.
  2. Then Run the simple Axis2 Http Server in the <axis2 installed dir>\bin.
  3. Start the project you just created for the math service and go to “Debug->Attach To Process”. There you can see the list of running processes. Just select the axis2_http_server process.
  4. Now as a test create a breakpoint at the start of axis2_math_add function in the math.c file. (You will get a warning that no symbol is loaded for the file, but you can ignore that for the moment)
  5. Now send a request using the math client that you compiled earlier. You will see the breakpoint is hit in the service project. So you can debug the service as you like.

If you have ever written an Apache Axis2/C service, there is a 99.9% chance that you have used the codegen tool to generate the code for the service. If so you only need to write your business logic inside functions generated by the the tool.

But there may be situations that you can’t use the codegen tool to get your work done. May be you don’t have a WSDL. Or codegen tool fails generating code for you WSDL (very few chance ;) .

In these situations you have to go to writing the complete service manually, I.e. You will write the code for the business logic + Axis2 Skeleton (code to plug the service logic to axis2/c).

Axis2/C service consists on:

  • service.xml – Simple way to describe the service and operation. (Far simpler than a wsdl)
  • Skeleton – c pseudo class inherited from axis2_svc_skeleton
  • Service logic – You service logic per service operation

services.xml

This contain the name and some description of the service, the name of the .dll (in windows) or .so (in linux) to load the service and list of operations with their parameters.

E.g.

<service name="echo">
  <!-- dll or so name of the service -->
  <parameter name="ServiceClass" locked="xsd:false">echo</parameter>
  <description>This is a testing service, to test whether the system is working or not</description> 

  <!-- list of operations -->
  <operation name="echoString">
    <!-- addressing information for the operation-->
    <parameter name="wsamapping">http://ws.dimuthu.org/axis2/echoString</parameter>
  </operation>
</service>

In addition to shown ones, there are a bunch of parameters available to customize your service. Visit Axis2/C manual for more.
Skeleton
This is the code that form the dll for your service. At least you should implement the following set of functions there.

  • Required function to create any axis2/c DLL
    • axis2_get_instance – Call at the creation of the DLL
    • axis2_remove_instance – Call at the removal of the DLL
  • Functions to be implement the axis2_svc_skeleton interface (sorry I’m using the java jargons)
    • init- Initialize the service (execute per start of the server)
    • invoke – invocation of the service (execute per each client request)
    • on_fault – invocation of the fault (execute if invoke returns NULL with error set)
    • free – Freeing the service (execute per stop of the server)
  • In addition to these mandatory functions I will be using axis2_echo_create to create the service skeleton for the echo service.

I will start with showing the structure of the service skeleton functions first.

/**
 * echo free method
 */
int AXIS2_CALL echo_free(
    axis2_svc_skeleton_t * svc_skeleton,
    const axutil_env_t * env);

/**
 * echo invoke method
 */
axiom_node_t *AXIS2_CALL echo_invoke(
    axis2_svc_skeleton_t * svc_skeleton,
    const axutil_env_t * env,
    axiom_node_t * node,
    axis2_msg_ctx_t * msg_ctx);

/**
 * echo init method
 */
int AXIS2_CALL echo_init(
    axis2_svc_skeleton_t * svc_skeleton,
    const axutil_env_t * env);

/**
 * echo on_fault method
 */
axiom_node_t *AXIS2_CALL echo_on_fault(
    axis2_svc_skeleton_t * svc_skeli,
    const axutil_env_t * env,
    axiom_node_t * node);

Note that you have the freedom to give any name to each of these function. In fact you should give a name with your service name as the prefix to avoid name conflicts. Then you can specify service skeleton to take these functions to represent to init, invoke, on_fault, free methods using the following code.

/**
 * you should specify your functions set exactly in the order
 * init, invoke, on_fault, free
 */
static const axis2_svc_skeleton_ops_t echo_svc_skeleton_ops_var = {
    echo_init,
    echo_invoke,
    echo_on_fault,
    echo_free
};

/**
 * Create function
 */
axis2_svc_skeleton_t *
axis2_echo_create(
    const axutil_env_t * env)
{
    axis2_svc_skeleton_t *svc_skeleton = NULL;
    /* Allocate memory for the structs */
    svc_skeleton = AXIS2_MALLOC(env->allocator, sizeof(axis2_svc_skeleton_t));

    /* you give the function pointers array to the ops of the skeleton */
    svc_skeleton->ops = &echo_svc_skeleton_ops_var;

    svc_skeleton->func_array = NULL;

    return svc_skeleton;
}

So you create the service skeleton for your echo service inside the axis2_echo_create function. In fact you need to call this function from the DLL creation function (i.e. ‘axis2_get_instance’ funciton). And in the ‘axis2_remove_instance’ function you call the macro AXIS2_SVC_SKELETON_FREE which in fact call the echo_free function to free the resource at the removal of DLL. Here are the implementation for the DLL creation and removal functions in this particular service.

/**
 * Calls at the creation of the dll.
 */
AXIS2_EXPORT int
axis2_get_instance(
    axis2_svc_skeleton_t ** inst,
    const axutil_env_t * env)
{
    *inst = axis2_echo_create(env);
    if (!(*inst))
    {
        return AXIS2_FAILURE;
    }

    return AXIS2_SUCCESS;
}

/**
 * Calls at the removal of the dll.
 */
AXIS2_EXPORT int
axis2_remove_instance(
    axis2_svc_skeleton_t * inst,
    const axutil_env_t * env)
{
    axis2_status_t status = AXIS2_FAILURE;
    if (inst)
    {
        status = AXIS2_SVC_SKELETON_FREE(inst, env);
    }
    return status;
}

Up to this, it was all about preparing the service skeleton, So where you put your business logic?.

Service logic

Just create a function with the following format.

axiom_node_t *axis2_echo_echo(
    const axutil_env_t * env,
    axiom_node_t * input_node) {

    /* Write your business logic Right Here */
}

Here you extract out the input parameters from the the input_node and build the return node based on your output parameters. (Note that even though this is an echo example you can’t return the same input node as the output node, instead you have to replicate the input node and return it to avoid the double freeing)
Since this particular example you only have one operation you can call your business logic right inside of your echo_invoke function. But it doens’t work for cases where multiple operations present. Here is the right way to do it.

/*
 * This method invokes the right service logic
 */
axiom_node_t *AXIS2_CALL
echo_invoke(
    axis2_svc_skeleton_t * svc_skeleton,
    const axutil_env_t * env,
    axiom_node_t * node,
    axis2_msg_ctx_t * msg_ctx)
{
	axis2_op_ctx_t *operation_ctx = NULL;
	axis2_op_t *operation = NULL;
	axutil_qname_t *op_qname = NULL;
	axis2_char_t *op_name = NULL;

	/* logic to get the op name from message context */
	operation_ctx = axis2_msg_ctx_get_op_ctx(msg_ctx, env);
	operation = axis2_op_ctx_get_op(operation_ctx, env);
	op_qname = (axutil_qname_t *)axis2_op_get_qname(operation, env);
	op_name = axutil_qname_get_localpart(op_qname, env);

	/* compare it with our operation name, this is useful when
	   there are multiple operations exist */
	if (op_name)
	{
		if (!axutil_strcmp(op_name, "echoString"))
		{
			return axis2_echo_echo(env, node);
		}
	}

	/* set error in the failure path */
	AXIS2_ERROR_SET(env->error, AXIS2_ERROR_OP_NAME_MISSING, AXIS2_FAILURE);

	/* log the error */
	AXIS2_LOG_ERROR( env->log, AXIS2_LOG_SI, "op name %s is not known", op_name);

	return NULL;
}

So that’s the part you write the code. Compile the code linking necessary libraries in the lib directory of your axis2/c pack and don’t forget to include the necessary axis2/c headers.

  • Necessary libraries for linux (Note: Some libraries are not directly called from your code, but it s better link all as some systems may complain about missing symbols in run time)
    • libaxutil.so
    • libaxis2_axiom.so
    • libaxis2_engine.so
    • libaxis2_parser.so
    • libpthread.so
    • libaxis2_http_sender.so
    • libaxis2_http_receiver.so
    • libguththila.so
  • Necessary libraries for Windows
    • axiom.lib
    • axis2_engine.lib
    • axis2_parser.lib
    • axutil.lib
  • Necessary header files (for both windows and linux)
    • axis2_svc_skeleton.h – To create instance of svc_skeleton
    • axis2_msg_ctx.h – Required in retrieving the dispatched operation name

If you follow this post up to now, this is the time you deploy the service with Axis2/C. Create a directory called ‘echo’ inside the services directory of axis2 repository (the root directory of you put axis2/c binary) and copy the services.xml and the dll in to that. (The DLL should be in the name echo.dll or libecho.so, if you change the dll name you should update the services.xml “ServiceClass” parameter).

Start the axis2 simple server (which is located in the <axis2_c_repo>/bin) and you are done. Your service will be deployed in “http://localhost/axis2/services/echo”. Use this endpoint to access your brand new service.

WSDL2Java and WSDL2C tools shipped with the Axis2/Java project are used to generate Stubs(client side) and Skeletons(Server Side) respectively for Axis2/Java and Axis2/C codes. This make the development of web services and consumers more quicker and easier.

The tools come with many options allowing the user to customize the code generation. One of the such option is ‘-uw’ which used to turn on the ‘unwrapping’ mode. WSDL2Java project had this option for a long time, But it is just Today I was able to enable that option in the WSDL2C tool. So lets see how it make the code easier.

Say you have the ’simpleAdd’ operation with the following schema,

            <xs:element name="simpleAdd">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element minOccurs="0" name="param0" type="xs:int"/>
                        <xs:element minOccurs="0" name="param1" type="xs:int"/>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
            <xs:element name="simpleAddResponse">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element minOccurs="0" name="return" type="xs:int"/>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>

When you generate the code for server side with Java using the following command, (note the option -uw which stands for ‘unwrapping’)

wsdl2java.sh -uri xxx.wsdl -u -ss -sd -uw

it gives you the following service function.

public int simpleAdd(int param0, int param1)
{
    //TODO : fill this with the necessary business logic
}

Note the input and output parameters of the function are simple types. If you don’t give the ‘-uw’ option, You will instead get a function with input and output variables as class names wrapping these simple types which is not this much straight forward.

So now the same is available with C. You can use WSDl2C tool with the same option set to generate a very simple service API.

wsdl2c.sh -uri xxx.wsdl -u -ss -sd -uw

And here is the service logic you may write, Can you think of an API simpler than this,

        /**
         * auto generated function definition signature
         * for "simpleAdd|http://ws.apache.org/axis2" operation.
         * @param env environment ( mandatory)
         * @param _param0 of the int
         * @param _param1 of the int
         *
         * @return int
         */
        int axis2_skel_UnwrappedAdder_simpleAdd(const axutil_env_t *env,
                                              int _param0,
                                              int _param1 )

        {
          return _param0 + _param1;
        }

You can find the code for complete case (wsdl, skel and stub) in the Axis2/C Jira Attachment space for the ‘unwrapping’ issue. Note that this update is only available in the nightly build and not in the release. You can download the nightly build from wso2’s axis2/java nightly build page.

I have been working for Axis2/C codegen tool for sometime now and I found lot of users who want to edit the codegen templates for a more optimized code specific to their use cases. This is mainly because codegen tool generates a very general code (For an example lot of unused variables generated for some WSDLs, but they are used in some other WSDLs) where as mostly ‘C’ people prefer to be as optimized as possible. Axis2 Java templates are more stable and not needed to customized as much as C templates, but Java developers too may find it is really useful to edit them in a case they need some customizations.

Both Axis2 C and Java tools comes with Axis2/Java project. So you may already have downloaded the latest Axis2/Java release or the Axis2/Java nightly build. As per title you can do this customization not only in the source but also in the binary pack. So I assume you have the binary pack.

Codegen tool mainly comes within two jars inside the lib directory of your Axis2/Java pack. (Here xxxx should be replaced with the particular jar version, it can be 1.4, 1.4.1 or SNAPSHOT)

  • axis2-codegen-xxxx.jar – The core classes of the codegen (This is where WSDL2C and WSDL2Java classes reside)
  • axis2-adb-codegen-xxxx.jar – This is the library containing the adb component of the codegen tool. ADB (Axis2 Data Binding) is the native databinding format of Axis2 which convert your xml schema to a more programmer friendly set of java classes or ‘C’ structures. The XSD2Java class comes in this jar.

Editing the Stub and Skeleton templates

When you unpack the axis2-codegen-xxxx.jar

jar xf axis2-codegen-xxxx.jar

you can find the template for Stub and Skel in org/apache/axis2/wsdl/template/c or org/apache/axis2/wsdl/template/java directories.

  • Stub For C – org/apache/axis2/wsdl/template/c/StubSourceTemplate.xsl (source) and org/apache/axis2/wsdl/template/c/StubHeaderTemplate.xsl (header)
  • Skeleton for C – org/apache/axis2/wsdl/template/c/SkelSourceTemplate.xsl (source) and org/apache/axis2/wsdl/template/c/SkelHeaderTemplate.xsl (header)
  • Stub For Java – org/apache/axis2/wsdl/template/java/InterfaceImplementationTemplate.xsl
  • Skel For Java – org/apache/axis2/wsdl/template/java/MessageReceiverTemplate.xsl (Message Reciever) and org/apache/axis2/wsdl/template/java/SkeletonTemplate.xsl (skeleton)

These templates are written is XSL. Even if you are an XSL expert, you may find little difficult to understand whole lot of codes in there. But if you really know what you need to change, you can track back the lines (may be using comment or some specific static set of code). So you don’t actually need to know any XSL to do these little customizations.

After you do the change simply pack the classes (which are in the ‘org’ directory) as the jar with the same name.

jar cf axis2-codegen-xxxx.jar org

Editing the ADB templates

You can similarly observe the axis2-adb-codegen-xxxx.jar. All the templates are in the org/apache/axis2/schema/template/ directory.

  • C ADB templates – org/apache/axis2/schema/template/CADBBeanTemplateHeader.xsl (Source) and org/apache/axis2/schema/template/CADBBeanTemplateHeader.xsl (Header)
  • Java ADB template – org/apache/axis2/schema/template/ADBBeanTemplate.xsl

You will find the template for the Java classes and C structures there. In C code generation if you find some variables are not used throughout your WSDLs, you can remove directly if from the templates. And some constants which are defined to allocate memory can be changed to suit to your application.

Anyway after all these notes, I have to say it is not really recommended to hack a code specific to your application. If you found a change general to all the applications you better submit the patch to the Axis2 community, so others too can use it. Otherwise whenever you do a upgrade you have to do this again on your own. But I hope these tips may be useful specially when you are working with ADB to do your own experiments.


© 2007 Dimuthu’s Blog | iKon Wordpress Theme by Windows Vista Administration | Powered by Wordpress