Here is a problem that many people have asked me how to do it. “Returning an array of string” with the code first approach. The API or WSDL generation annotation guide, http://wso2.org/project/wsf/php/2.0.0/docs/wsdl_generation_api.html contain all the things required in details. Here is an example of a service that return an array of string.

<?php

/** splitMe function
 * @param string $string_to_split string to split
 * (maps to the xs:string XML schema type )
 * @return array of string $result split to array
 *(maps to the xs:double XML schema type )
 */
function splitMe($string_to_split)
{
    return array("result" => split(":", $string_to_split));

}

$operations = array("splitMe"=>"splitMe");
$opParams = array("splitMe"=>"MIXED");

$svr = new WSService(array("operations"=>$operations,
                           "bindingStyle"=>"doclit",
                           "opParams"=>$opParams));

$svr->reply();
?>

Note that the annotation corresponding to the return value.

 * @return array of spring $result split to array

This will generate an schema with an element of maxOccurs=’unbounded’. Note that you can get the wsdl from the ’serviceurl?wsdl’.

<xsd:element name="splitMeResponse">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:element name="result" maxOccurs="unbounded" type="xsd:string"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>

Now just generate a client for this service using wsdl2php and try invoke it. You will get an array of string as the response.

    $input = new splitMe();
    $input->string_to_split = "a:b:c:d";

 
    // call the operation
    $response = $proxy->splitMe($input);
    print_r($response);

If you want to write rules in a Java program you have lot of choices. You can use a third party library like Drools or use the JAVA built-in JSR-94 reference implementation. In WSO2 Carbon, there is a component that abstract the behaviour of different rule engine and give you a unified API. Currently it has plugged into Drools and JAVA built-in JSR-94 implementation.

The rule component in WSO2 Carbon platform mainly used by WSO2 ESB product to mediate messages according to the given business rules. But the component is written to facilitate any requirement of using business rules in WSO2 Carbon platform. I had such a requirement in past few days and manage to use the rule component easily with the help of the component author, indika@wso2.com. So I thought it is worth sharing my experience in here.

Here You will be preparing the following stuff.

1. Rule configuration -

We can use this to provide the information about the rule implementation we are going to use, the rules (You can write rules inline or provide a reference to an external file) and the input and output adapter information.

<configuration xmlns="http://www.wso2.org/products/rule/drools">
<executionSet uri="simpleItemRuleXML">
<source key="file:src/test/resources/rules/simple-rules.drl"/>

<!-- <source>

<x><![CDATA[
 rule InvokeABC
 // rules inbuilt to the rule conf
 end

 ]]>
</x>
</source> -->
<creation>
<property name="source" value="drl"/>

</creation>
</executionSet>
<session type="stateless"/>
<input name="facts" type="itemData" key="dataContext"></input>

<output name="results" type="itemData" key="dataContext"></output>
</configuration>


2. The Rules  -

You can write rules inline in the above configuration or put it in a file and refer it from a key which can be refered from the ResourceHelper (described below).

import java.util.Calendar;

rule YearEndDiscount
when
$item : org.test.pojo.SimpleItem(price > 100 )

then

Calendar calendar = Calendar.getInstance();
if (calendar.get(Calendar.MONTH) == Calendar.JANUARY) {

$item.setPrice($item.getPrice() * 80/100);
}

end

3. Data Context -

The context object that can be used to feed and retrieve data from and to rule engine. Here is the data context for my application.

public class SimpleDataContext {

    public List<NameValuePair> getInput() {

        // in reality the data will be retrieve from a database or some datasource 
        List<NameValuePair> itemPairList = new ArrayList<NameValuePair>();
        SimpleItem item1 = new SimpleItem();
        item1.setName("item1");
        item1.setPrice(50);
        itemPairList.add(new NameValuePair(item1.getName(), item1));

        SimpleItem item2 = new SimpleItem();
        item2.setName("item2");
        item2.setPrice(120);
        itemPairList.add(new NameValuePair(item2.getName(), item2));

        SimpleItem item3 = new SimpleItem();
        item3.setName("item3");
        item3.setPrice(130);
        itemPairList.add(new NameValuePair(item3.getName(), item3));

        return itemPairList;
    }

    public void setResult(Object result) {

        if (!(result instanceof SimpleItem)) {
            System.out.println("it is not a SimpleItem");
        }

        SimpleItem item = (SimpleItem)result;
        System.out.println("Item: " + item.getName() + ", Price: " + item.getPrice());
    }

}

And the Item I’m going to manipulate using rule is a simple bean like this,

public class SimpleItem {
    String name;
    int price;
    public String getName() {

        return name;
    }

    public void setName(String name) {

        this.name = name;
    }

    public int getPrice() {

        return price;
    }

    public void setPrice(int price) {

        this.price = price;
    }
}

4. Data Adapter

You have to adapt the input and output with the rule engine. Mostly here you only have to wrap the data context. The advantage of having the data adapter is, a data adapter always associated with a input/output type. So in the rule configuration I can provide the type for the input and output. If you see my rule configuration above, you see the input/output type is marked as “ItemData”. Here is my custom data adapter that is associated with the “itemData” type.

public class SimpleDataAdapter implements
        ResourceAdapter, InputAdaptable, OutputAdaptable {

    // the type associated with the adapter
    private final static String TYPE = "itemData";
    public String getType() {

        return TYPE;
    }

    public Object adaptInput(ResourceDescription resourceDescription, Object tobeadapted) {

        if (!(tobeadapted instanceof SimpleDataContext)) {
            return null;
        }

        SimpleDataContext dataContext = (SimpleDataContext)tobeadapted;
        return dataContext.getInput();
    }

    public boolean adaptOutput(ResourceDescription description,
                               Object value,
                               Object context,
                               ResourceHelper resourceHelper) {

        if (!(context instanceof SimpleDataContext)) {
            return false;
        }

        ((SimpleDataContext)context).setResult(value);
        return true;
    }

    public boolean canAdapt(ResourceDescription description, Object ouptput) {
        String key = description.getKey();
        return key != null && !"".equals(key);
    }

}

5. Resource Helper

Resource Helper will map the keys refered from the configuration to JAVA objects. This is mostly used in mediation rule configurations which can extract the message data using a key or an xpath. In this example, we don’t have much keys refering from the configuration only the rule file and the data context.

public class SimpleResourceHelper extends ResourceHelper {

    public ReturnValue findByKey(String key, Object source, Object defaultValue) {

        if (!(source instanceof SimpleDataContext)) {
            return new ReturnValue(defaultValue);
        }

        SimpleDataContext dataContext = (SimpleDataContext)source;
        if (key.startsWith("file:")) {

            String filename = key.substring("file:".length());
            try {

                BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename));
                return new ReturnValue(in);
            } catch (Exception e) {

                return new ReturnValue(defaultValue);
            }
        }
        if (key.startsWith("dataContext")) {

            return new ReturnValue(dataContext);
        }
        return new ReturnValue(defaultValue);
    }

    // there are few more methods to be implemented, which can just leave not implemented for this example
    }
}

That is all the accessories. Now you will be able to write the rule engine execution code.

File ruleConfigFile = new File(ruleConfigFilename);
XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(ruleConfigFile));

//create the builder
StAXOMBuilder builder = new StAXOMBuilder(parser);
//get the root element (in this case the envelope)

OMElement ruleConfig =  builder.getDocumentElement();
EngineConfiguration configuration =
        new EngineConfigurationFactory().create(ruleConfig, new AXIOMXPathFactory());

EngineController
        engineController = new EngineController(configuration, new SimpleResourceHelper());
        final ResourceAdapterFactory factory = ResourceAdapterFactory.getInstance();

ResourceAdapter adapter = new SimpleDataAdapter();
String adapterType = adapter.getType();
if (!factory.containsResourceAdapter(adapterType)) {

    factory.addResourceAdapter(adapter);
}

SimpleDataContext simpleContext = new SimpleDataContext();

if (!engineController.isInitialized()) {
    engineController.init(simpleContext);

}

if (engineController.isInitialized()) {
    engineController.execute(simpleContext, simpleContext);

}

If you want to store binary in database, you can use BLOB as the data type of that column. In Mysql you can use TINYBLOB, BLOB, MEDIUMBLOB, LONGBLOB depending on your space requirement. Here is an example of database table using BLOB as a column type.

CREATE TABLE BloBTest (
    id INT NOT NULL AUTO_INCREMENT,
    filename VARCHAR( 32 ) NOT NULL,
    content BLOB NOT NULL,
    PRIMARY KEY ( id )
)

Storing Data

PHP:

$filename = "myimage.png";
$filecontent = file_get_contents($filename);
$filecontent_escaped = mysql_real_escape_string($filecontent);

$sql = "INSERT INTO BloBTest(filename, content) " +
       "VALUES('$filename','$filecontent_escaped')";
mysql_query($sql, $link);

Java:

String filename = "myimage.png";
InputStream filecontent = new FileInputStream(filename);

String sql = "INSERT INTO BloBTest(filename, content) VALUES(?, ?)";

int size = filecontent.available();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, filename);
ps.setBinaryStream(2, filecontent, size);
ps.executeUpdate();

Retrieving Data

PHP

$sql = "SELECT filename, content FROM BloBTest";
$result = mysql_query($sql, $link);
while ($row = mysql_fetch_assoc($result)) {

    $filename = $row["filename"];
    $content = $row["content"];
    $new_filename = "new_" . $filename;
    file_put_contents($new_filename, $content);
}

Java:

String sql = "SELECT filename, content FROM BloBTest";

PrepareStatement ps  = conn.prepareStatement(resourceContentSQL);
ResultSet result = ps.executeQuery();

if (result.next()){
    String filename = result.getString("filename");
    InputStream contentStream = result.getBinaryStream("content");
    String newFilename = "new_" + filename;
    // storing the input stream in the file

    OutputStream out=new FileOutputStream(newFilename);
    byte buf[]=new byte[1024];
    int len;
    while((len=contentStream.read(buf))>0)

    out.write(buf,0,len);
    out.close();
}

Retrieving the Size of the Blob

After you store your data as a blob, you can manipulate or query the data with some of the in-built String functions in mysql. For an example if you want to query the size of the blob you just stored, you can use OCTET_LENGTH function. Here is an example,  (this will give you the size in bytes.)

SELECT OCTET_LENGTH(content) FROM BloBTest WHERE filename='myimage.png'
.

WSO2 Governance as a Service is an online multi-tenant supported instance of WSO2 Governance Registry which is the solution for SOA Governance from the WSO2 SOA stack. You can start trying out WSO2 Governance as a Service by accessing the http://governance.cloud.wso2.com and creating an account for your organization (free for limited use).

In order to identify your account, you have to provide the domain name of your organization. I will demonstrate how to create an account using the “ws.dimuthu.org” as my domain name.

1. First go to http://governance.cloud.wso2.com from a web browser and click the ‘Register’ button. You will be asked to enter the domain name as the first step.

Enter the domain

Enter the domain

After that, you have the option of validating the ownership of the domain right at the registration process, or you can skip the validation and continue to the next step in which case your domain will be appended ‘-trial’ suffix. You can validate the ownership of the domain later at any stage.

Here I want to validate the domain right now, so I click ‘Take me to the domain ownership confirmation page straight-away’ and click the ‘Submit’ button.

2. This will redirect you to the domain ownership validation page. You can validate the ownership of your domain in one of two ways.

Method i). Just create a text file named ‘wso2gaas.txt’ in the web root of your domain and enter the given text. This is the most simplest method of two.

Validate domain name using Textfile

Validate domain name using Textfile

Method ii). You can put a DNS entry according to the given instructions. This is a little tedious approch to validate the domain. In fact it may take a while to propagate the new DNS information, so you may have to wait hours without refreshing the page until you finally validate the domain ownership.

Click the continue button after the domain validation done. Then you will be redirected to a page requesting more information.

3. Tenant Registration Page

Tenant Registration

Tenant Registration

4) After this step, you will be notified to check for your email which will contain a mail with a link to proceed with the registration. There you will be able to select a theme for your organization and finalize creating your account. Login to the admin account for your tenant with the credential you provided a the time of the registration.

The domain ownership validation was introduced to WSO2 Governance as a Service account registration only now. So for organizations who have already have account will have a message similar to this when they are trying to login to their account.

Info box at login

Info box at login

So the account I have registered using the domain name ‘example.com’ has been renamed to ‘example.com-trial’. As the instruction of the message says you can go to the account management page after the login and validate the domain ownership.

Account Management Page

Account Management Page

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

January 31st, 2009Making Good SOA Great

WSO2 is preparing for the first major release of their enterprise java product series after adapting the OSGI technology. You can already try out the betas from the wso2.org site.

  1. WSO2 Web Services Application Server (WSAS)
  2. WSO2 Enterprise Service Bus (ESB)
  3. WSO2 Registry
  4. WSO2 Business Process Server (BPS)

With the power of OSGI you will be able to customize these products for your need just by mixing and matching the components within these products. If you like to learn more about this, just have a loot at the following ebook released by WSO2.

Making Good SOA Great

Making Good SOA Great

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.

Now you can view the article I wrote titling “Introduction to PHP Data Services“. There I explain how you can design and implement Data Services in PHP using WSF/PHP Data Services Library.

This article covers,

  1. Designing your Data Service API.
  2. Writing the Data Service.
  3. Deploying and Testing Data Service.
  4. Make the Data Service available in both SOAP and RESTful form.
  5. Use of WS-* features in your Data Service.

If you are thinking of adapting SOA in to your database backed PHP applications, this article will be a good starting point.

Same as web pages, web services also sometime require  client authentication. The most frequent way of authentication is the use of WS-Security Username token which authenticate clients based on the username and passwords. There can be situations where clients need to be authenticated based on its IP or its domain.

If you are writing web services from PHP (Using some PHP web service framework like WSF/PHP), You can use the PHP variables, $_SERVER["REMOTE_ADDR"] and $_SERVER["REMOTE_HOST"] to find the clients ip within the service logic code. If the client’s IP is static you can directly use the $_SERVER["REMOTE_ADDR"] and if it is dynamic you can use the $_SERVER["REMOTE_HOST"] which will be derived by reverse DNS look of the clients IP.

Here is one example of the use of these $_SERVER[] variables inside service logic.

 
function members_only_func($in_message) {

    // getting the clients IP.
    $remote_addr = $_SERVER["REMOTE_ADDR"];

    if($remote_addr == "67.205.26.154" ||
       $remote_addr == "124.43.59.95") {
       // generates the message for authenticated clients.

       return $valid_out_message;
    }

    // otherwise throw an exception
    throw new WSFault("Sender", "Failed to Authenticate");
}

$operations = array("membersOnlyOp" => "members_only_func");

$service = new WSService(array("operations" => $operations));

$service->reply();

“WSO2 carbon is a componentized, customizable SOA Platform, You can adapt the middleware to your enterprise architecture, rather than adapt your architecture to the middleware”.


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