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);

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.

PHP is one of the famous choice, when it comes to develop a web site. As the web evolve with the emerge of web service, REST (REpresentational State Transfer) concepts, the PHP language is also adapted to the new requirements specially with the availability of new SOA (Service Oriented Architecture), REST frameworks and libraries. Anyway there were hardly any guides, references or samples that properly describe the methodologies of developing REST applications using PHP.

The book “RESTful PHP Web Services‘ by Samisa Abeysinghe certainly fill this gap. It can be used as a step by step guideline for newbies to learn the concepts and write simple RESTful PHP applications and Mashups. And even experienced developers would find this a great reference to keep nearby while working with RESTful Web Services in PHP. And it has lot of code samples, utility functions that developers can use it in their applications.

RESTful PHP Web Services - Samisa Abeysinghe

About the Author

Samisa Abeysinghe is a well recognized name in the web services world. He lead the development of Apache Axis2/C and WSO2 WSF/PHP, two famous open source web service frameworks for ‘C’ and PHP. In addition to his deep knowledge in the subject, his experience in involving with the community and the enterprise for years and working as a lecturer in universities, should have influenced a lot in writing this book.

The Arrangement and the Content

The arrangement of the book is done really well to make sure the reader can go through it in the right sequence. All the content is bundled just within 200 pages. So you don’t need to allocate a lot of time to go through the whole book. It is organized into 7 chapters and two appendixes which are mostly independent from each other.

The first chapter is completely devoted to explain the concepts of RESTful web services. It basically explains what is RESTful web service and why it is needed. And it briefly mentions about the currently available REST Frameworks for PHP.

The second chapter introduce some PHP codes that do REST web service requests and handles the XML responses using both DOM and SimpleXML APIs. And in the third chapter it shows more code samples specially about consuming real world web services like BBC, Yahoo and an earthquakes information service. Theses codes are written as mashups mostly combining two services to produce more meaningful information.

The forth chapter is about  designing and writing web service providers. Its counterpart, writing web service consumers is described in the chapter five. There it demonstrate a library system that operate using RESTful webservices. You can map this example to any system that you may like to develop to run with RESTful web services. The chapter five of the book is available as a free download, RESTful PHP Web Services – Chapter 5.

The forth and fifth chapters are not using any framework to write the sample codes on consuming and providing web services. But in the sixth chapter it shows the use of Zend framework to do write them. There it rewrites the same example (The RESTful library system) in MVC (Model -View – Controller) approach using the functionalities of Zend framework. (In fact the View in the service is omitted).

The seventh chapter is about debugging web services. Debugging is a much needed step in any software development cycle. So if you are a newbie, you should read this chapter before start writing any of your own code. This introduces tools and methodologies to make your debugging easy and effective.

The book contains two appendixes. They are too really useful as the chapters of the book. In the first appendix it explains another REST web service framework, WSO2 Web Services Framework for PHP (WSF/PHP). To demonstrate it uses, some selected functionalities of the example library system (that is mentioned in chapters 4, 5, 6) is re-implemented using WSF/PHP. And it shows you how you can convert this RESTful system to a SOAP system in a minute. The second appendix provides you a code of a class (RESTClient), that you can use in consuming web services very effectively.

Recommended Readers

This book assume you have some knowledge in PHP. But it doesn’t require you to know anything related to web services, REST or XML. As you read the first few chapters, you will have a good understanding on the concepts and the basic applications of REST and XML using PHP. And the later chapters will guide to get deeper knowledge in writing complex and real world applications.

If you are a professional developer, you can skip the introduction chapters and jump directly to where you need to refer. For an example, if you use this book as a reference in designing and developing RESTful web service providers, you can directly read the chapter4 – Resource Oriented Services, chapter6- Resource Oriented Clients and Services with Zend Framework and probably the chapter 7 – Debugging Web Services.

This book contains the same example system (the library system) written in three different approaches, first without using any framework support, second using the Zend Framework, third using WSF/PHP. Each of them has its own pros and cons. So if you want to determine the approach more suitable to your requirements, or thinking of migrating from one to another, this book will be an ideal resource for you.

As you may have already noticed, this book contains lot of code samples. All the concepts are followed by simple code samples that explain the concept. In appendix it gives you a complete code for RESTClient class that you can use to call any REST service. Apart from the code of the example library system written using different frameworks, it has lot of codes for calling public web service APIs. And the explanation of the code is also done really well.

So it is clear this book is more targetting readers who like to implement PHP RESTful Systems in practice. And it covers enough concepts that you needed to know in writing practicle applications. So this book can take you from the zero knowlege to a deeper knowlege of RESTful PHP Web Services.

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.

Organic Reaction Simulator

It is a tool that simulates the organic reactions and automatically generate the IUPAC names for the organic compounds drawn by you. This covers most of the syllabus of the Organic Chemistry for G.C.E. A/L examination.

Features

  • Nice Canvas to draw your Organic compounds.
  • Generates IUPAC names for the drawn component as possible. (It generates IUPAC names for almost all the compounds which G.C.E A/L examination expect students to know)
  • You can simulate reaction for organic compounds with preferred inorganic/organic compounds and the selected conditions. (Currently supporting 168 reactions)
  • Extensibility of adding IUPAC naming rules without the need of recompiling the code.
  • Extensibility of adding custom reactions, again without compiling a single line of code.

Here is a screen shot of the main panel when ‘Aldole reaction’ is simulated for some simple reactants.

Aldole Reaction - Reaction Simulator

Aldole Reaction - Reaction Simulator

The Drawing Panel

The ‘Reaction Simulator’ app provides 2 views for the user. One is the main panel which shows and manages reactions which is shown in the above figure. The other view is the drawing panel. It will be not much different from your favorite drawing application.

Drawing Panel - Reaction Simulator

Drawing Panel - Reaction Simulator

Here you can select elements and bond types to draw your organic compound. Additionally It has tools to move or delete selected parts of your drawing.

The other thing you may have already noticed, you don’t need to complete all the bonds for a particular element. Rather if you keep one side of a single bond unconnected, it will be automatically connected to a ‘H’(Hydrogen) at the rendering, similarly for double bond the default connecting element would be ‘O’(Oxygen), and for triple bond it is ‘N’ (Nytrogen). And you don’t even need to bother about connecting bonds with an element, as if you connected only one bond to ‘C’ all the other 3 possible bonds will be considered as connected with ‘H’s.

Just check the drawing panel on your own and find its user friendliness. Now after you finish designing your compound, just press “RETURN”.

IUPAC Name Generator - Reaction Simulator

IUPAC Name Generator - Reaction Simulator

Yea it will nicely render our compound, and look at the bottom, it has generated the IUPAC name for the compound.

The Main Panel

This contain a canvas that you can add, edit and delete organic compounds (so you will be directed to the ‘Drawing Panel’), some sidebar panels to select Inorganic compounds and additional conditions requires for the reactions and a set of buttons to start reactions and manage the result set. At the end of the sidebar there is a ‘help’ button that directed you to the user guide.

Extending IUPAC Naming Rules

If you go to the “Data/IUPAC/” directory (you can view svn from here, http://svn.dimuthu.org/organic_chemistry/Organic_Reaction_Simulator/Data/IUPAC/) you can find there are set of .txt files (infact xmls) that defines the IUPAC rules.

If you open one of them (we will take al.txt), it would be something like this

<IUPAC basename="al" subname="oxo" level="6" nonumber="true" affectto="1">
	<bond type="2">
		<element type="7">
		</element>
	</bond>
	<bond type="1">
		<element type="1">
		</element>
	</bond>
</IUPAC>

It is the naming rules for aldehyde compounds. (H-C=O). First it identify the the aldehyde by checking double bond to ‘O’ (which is the element type ’7′), and a single bond to ‘H’ (which is the element type ’1′). If the element group found, it will give the name ‘al’ or ‘oxo’ depending on whether it defines the main group of elements of the compound or not.

If you take a look at all these rules, you can have a good idea what each of these syntax mean. And may be you can add your own rules, if you find something missing or incorrect there.

Extending the Reactions

The reaction rules are stored in the “Data/Reactions/” directory ( http://svn.dimuthu.org/organic_chemistry/Organic_Reaction_Simulator/Data/Reactions/).

I will take the first reaction we studied in the ‘Organic Chemistry’ Class.

CH4 + Cl2 + hv (dim light) —————-> CCl4 + H2

Here is the rule defining that reaction. (cl2hv.txt)

<reaction inorganics="Cl2" conditions="hv">
	<check>
		<bond type="1">
			<element type="H">
			</element>
		</bond>
	</check>

	<reordering activity="remain">
		<bond type="1">
			<check>
				<element type="H">
				</element>
			</check>
			<reordering activity="remain">
				<element type="H">
					<reordering activity="replace" to="Cl">
					</reordering>
				</element>
			</reordering>
		</bond>
	</reordering>
</reaction>

If you take a close look at, what it says is if there exist inorganic ‘Cl2′ and condition ‘hv’ (reactions inorganics=”Cl2″ conditions=”hv”), check for a ‘H’ (element type=”H”) elements that is connected to a ‘C’ element (which is the root of the XML) through a single bond (bond type=”1″), then don’t replace the ‘C’ (reordering activity=”remain”) and don’t replace the bond type (reordering activity=”remain”), just replace the ‘H’ with ‘Cl’ (reordering activity=”replace” to=”Cl”). It is so simple as that.

These rules are applied to all the C elements in reactants. Look at the following figure for this rule in application.

Alkane + Cl2 Reaction - Reaction Simulator

Alkane + Cl2 Reaction - Reaction Simulator

These reaction rules can be as complex as you want. Specially when two or more reactants are involved in a reaction, rules defining that reaction will be little complex. Look at how aldole reaction (which is applied in the first figure of this post) is written in aldole.txt.

There are all together 168 reactions currently defined in this way. If you found some reaction is missing, feel free to add a another rule file defining that reaction. And if you want to share that with others, just let me know :) , so I can integrate it in to the distribution.

Download

This software application is not yet in a official release. I just thought use this post to do a pre release of the ‘Reaction Simulator’. You can download the windows binary of the pre release version (343KB) from http://downloads.dimuthu.org/bins/chemistry/reaction_simulator_pre_release/reaction_simulator_pre_release.zip

Source Code

SVN location for the source code of ‘Reaction Simulator’ is http://svn.dimuthu.org/organic_chemistry/Organic_Reaction_Simulator/

Known Limitations – Possible Improvements

  • Generation of IUPAC names and simulations of reactions are not supported for compounds which involves Benzene ring.
  • IUPAC names generation is not supported for cyclic compounds which are anyway not part of the G.C.E. A/L syllabus.
  • The set of elements, available in drawing compounds, set of inorganic compounds and conditions, available in reactions are fixed and cannot be extended without changing the code and recompiling.
  • You can’t start with an IUPAC name and derive the compound. Currently you always have to start with drawing the compound and then generate the IUPAC.
  • Only for windows!

Little Background

4 years ago, When I was a level 2 student in the University of Moratuwa, I participated to a competition for making educational software tools organized by C.S.E and N.I.E (National Institute of Education). I submitted a software that teaches Organic Chemistry. It consisted of interactive tutorials targeting local G.C.E A/L exams with exercises and revisions in both Sinhala(My Mother tongue) and English languages(not in Unicode though). I got the second price for that.

After the award I decided to improve my software application by adding an ‘Organic Reaction Simulator’. In fact in the vacation of 2 weeks for the New Year, I could complete it.

Although the N.I.E supposed to distribute the applications submitted to the competition throughout the country, it didn’t happened. So I decided to publish at least the ‘Reaction Simulator’ application which I actually didn’t submitted to the competition.

Technologies Used

This is completely written in C++. It hasn’t use MFC, because I thought MFC is too heavy for such a small application. I used a lightweight, small image library code taken with some custom changes from some windows game programming book.

This is using XML to load data about reactions and IUPAC names which I have described in details in the early part of the blog. It uses a small inbuilt xml parser (just one recursive function) to parse these xmls.

So it has no depenedencies to third party libraries, You can just chekcout the souce code from the svn, open the visual studio project and compile it (press ‘F7′).

November 19th, 2008WS-SecurityPolicy With PHP

WS-SecurityPolicy specification defines standards for defining security policies for your web service. WSF/PHP allows you to declare your security policies according to these standards.

You can take one of following approaches to associate policies to your web service or client.

  • PHP Array to represent your policies
  • Policy file compliant with WS-Security Policy.
  • Declaring policies inline with the WSDL.

Declaring Policies with a PHP Array

This is a WSF/PHP specific API to declare policies for a web service. You don’t need to learn WS-Security Policy to write policies with this approach. You can set whether you want to use encryption, signing or usernameToken in a PHP array and create a WSPolicy object using it.

// here is the security array to declare your policies in simple manner
$sec_array = array("encrypt" => TRUE,
 "algorithmSuite" => "Basic256Rsa15",
 "securityTokenReference" => "IssuerSerial");

// creating WSPolicy instance using the policy array
$policy = new WSPolicy(array("security"=> $sec_array));

You can use this policy object to create a service along with a WSSecurityToken which contain the user parameters like the server private key and the client certificate.

$sec_token = new WSSecurityToken(array(
 "privateKey" => $server_pvt_key,
 "receiverCertificate" => $client_pub_key));

$svr = new WSService(array("actions" => $actions,
 "operations" => $operations,
 "policy" => $policy,
 "securityToken" => $sec_token)); // here is the policy object you just created

$svr->reply();

You can invoke this service just by writing a simple web service client. There also you need to provide the policies declared in the service, so the client can build his request to validate with server policies. You will be using a similar WSPolicy object to set these policies at the client side too, as show in the below code segment.

 $sec_token = new WSSecurityToken(array(
   "privateKey" => $pvt_key,
   "receiverCertificate" => $rec_cert));

 $client = new WSClient(array("useWSA" => TRUE,
    "policy" => $policy, /* the policy object */
    "securityToken" => $sec_token));

 $resMessage = $client->request($reqMessage);

Declaring Policies with a Policy File

You can set your policies in the server or client side using a policy file compliant with WS-Security Policy specification. You have to take this approach if your policy requirements are too complicated, like you want to sign only some parts of the message or you want to encrypt some soap headers.

Similar to the above method, here too you will use the WSPolicy object to set your policies. But unlike the above where you give the policies as a PHP array , here you can just give the policy file as an argument to the WSPolicy constructor.

// creating the WSPolicy instance from a policy file
$policy_xml = file_get_contents("policy.xml");
$policy = new WSPolicy($policy_xml);

Here is an example of a complete policy file written according to the WS-Security Policy standards. And you can find a quick guide on WS-Security Policy from the article Understanding WS-Security Policy Language written by Nandana, a key leader of Apache Rampart project.

Declaring Policies inline in a WSDL

We use WSDL to describe our web services. WSDL has the information about the service endpoint, the transport protocols (e.g. http), messaging protocols (e.g. SOAP) and the message schemas and many others about the service. You can attach your policies inside a WSDL.

Here is an example of a WSDL with inline policies. The difference in this approach is you can set your policies separately for each messages or each operations or each endpoints of your service. The following segment of a WSDL shows how you refer to different policies which are declared in the early part of the WSDL.

     <wsdl:binding name="CalendarSOAP12Binding" type="ns1:CalendarPortType">
       <!-- Endpoint policies are declared here.
          these are common to all messages transferring
          through this protocols (i.e. SOAP12, http)-->
        <wsp:PolicyReference URI="#transport_binding_policy"/>
        <soap12:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
        <wsdl:operation name="login">
           <soap12:operation soapAction="urn:login" style="document"/>
           <wsdl:input>
              <!-- policy specific to the 'login' operation -->
              <wsp:PolicyReference URI="#username_token_policy"/>
              <soap12:body use="literal"/>
           </wsdl:input>
           <wsdl:output>
              <soap12:body use="literal"/>
           </wsdl:output>
         </wsdl:operation>
         <wsdl:operation name="register">
            <!-- no specific policies are set for the 'register' operation
            <soap12:operation soapAction="urn:register" style="document"/>
            <wsdl:input>
              <soap12:body use="literal"/>
            </wsdl:input>
            <wsdl:output>
               <soap12:body use="literal"/>
            </wsdl:output>
         </wsdl:operation>
           ....
       </wsdl:binding>

This is the binding section of a WSDL where we bind messaging protocol and transport protocols with a service endpoint. Here we have “login” and “register” operations. Note that we are referring to “transport_binding_policy” from the parent level of each operation elements. That means these policies are common to all the operation in that binding. And inside the “login” operation we are referring to “username_token_policy”, so in order to invoke this operation, you have to send username token headers. And “register” doesn’t require any operation specific policies allowing users to register without any prior authentications.

You can select any of the above mentioned approach to define policies of your web service or to invoke a web service that support WS-Policy. If your policy requirements are simple, it will be easy to use the array based approach. If your policy requirements are complex or you have a good understanding of WS-Policy and WS-Security Policy you can rely on the policy file based approach or defining policy inline with WSDL. And the former 2 methods will give you a nice separation of the logic code and security configurations. The selection is yours:)

As many of other languages, XML schema too have data types. Basically it can be categorized in to two groups.

  1. Simple Types
  2. Complex Types

The different between these 2 types are so easy to identify. Say you have a schema element with a simple type like this.

<xs:element name="xx" type="someSimpleType"/>

Then a possible xml to validate against this schema is

<xx>Bingo</x>

Inside the ‘xxx’ you can only find texts, But in a case of a  schema element with complex types,

<xs:element name="xx" type="someComplexType"/>

The XML will be set of nested elements.

<xx>
  <yy>hi</yy>
  <zz>Nested elements</zz>
</xx>

Simply complex type contains elements with simple types or complex types similar to the class types in OOP languages which contain member variables with different types.

But unlike most of the other languages, in schema simple types are not always primitive types. There can be user derived simple types as well.

I will talk about each of these variations in schema types and their PHP representation of WSDL2PHP tool.

  • Primitive Types & Built-in Types
  • List Types
  • Union Types
  • Faceted Types

Primitive Types & Built-in Types

The XML schema specification talks about 19 primitive types. Some of the common of these simple types and the corresponding PHP types generated by WSDL2PHP tool are,

Schema Type PHP Type
string string
boolean boolean
decimal float
float float
double double
duration string
dateTime string (from above wsf/php 2.0 it is an integer – representing timestamp)

You may have noticed the famous types like ‘integer’, ‘byte’, ‘short’ are missing out of the above list. In fact these types exist, but they are not primitive types. They are derived from decimal (special cases when the fraction digits are 0 :) . Anyway still these types are considered built-in types in xml schema. Here is the complete list of built-in types (both primitive and non-primitive built-in types)

‘integer’, ‘byte’ and ‘short’ are mapped to PHP integer types by the WSDL2PHP tool.

To show an example how WSDL2PHP tool generating code for simple types, I will take the following schema Element.

<xs:element name="myName" type="xs:string"/>

And WSDL2PHP will generate a simple public variable (Assuming this is generating inside some class) for that element with a comment to describing it.

    /**
     * @var string
     */
     public $myName;

So if I specified some value for the variable (Taking the variable name of the parent class is $parent),

$parent->myName = "James";

I will get the following nice XML.

<myName>James</myName>

This is the same approach for all the other built-in types as well.

List Types

The list types are derived from list of simple types. It still a simple type because it list all the element in the list as a white-space separated text inside the parent element.

Here is how you may declare a list type in an xml schema.

<xs:simpleType name="mylist">
    <xs:list itemType="xs:int"/>
</xs:simpleType>

<!-- example element to have the above list value -->
<xs:element name="xCoordinates" type="tns:mylist"/>

Then the WSDL2PHP generated PHP code would be something like,

    /**
     * @var array of int
     */
    public $xCoordinates;

As the comment implies, you have to feed the values in an php array.

$parent->xCoordinates = array(1, 3, 8, 7, 9);

And Here is the XML you are getting,

<xCoordinates>1 3 8 7 9</xCoordinates>

Similarly you can have list of any simple types regardless whether it is built-in or derived.

Union Types

The union in schema is similar to the unions in ‘C’. In C variables of a union can have one (and not more than one) of the types declared inside the union type. Similarly in schema elements with union types can have one and only one simple type among the member types declared in the union. Here is an example of declaring union type,

<xs:simpleType name="myIntStringUnion">
    <xs:union memberTypes="xs:int xs:string"/>
</xs:simpleType>

<!-- example element to have the above union value -->
<xs:element name="garbage" type="tns:myIntStringUnion"/>

And the WSDl2PHP generated code,

    /**
     * @var int/string
     */
    public $garbage;

So if you read the comment you can have an idea that this variable accept either ‘in’ or ‘string’ type without digging in to the WSDL.

Faceted Types

You can apply facets and restrict the value space of a simple type.

  • length
  • minLength
  • maxLength
  • pattern
  • enumeration
  • whiteSpace
  • maxInclusive
  • maxExclusive
  • minExclusive
  • minInclusive
  • totalDigits
  • fractionDigits

Some facets are specific to some built-in data types or types derived from these built-in datatypes. Here is a table of valid facets for each of the above mentioned catagory of types.

I have earlier blogged about how you work on faceted types in PHP in the post “Coding Schema Inheritance in PHP“. So Here I will list out a similar example  to demonstrate the PHP generated code by WSDL2PHP tool for facets.

Here is a schema with the ‘enumeration’ facet.

<!-- applying enumeration facet to the xs:string -->
<xs:simpleType name="mySubject">
    <xs:restriction base="xs:string">
         <xs:enumeration value="Maths"/>
         <xs:enumeration value="Physics"/>
         <xs:enumeration value="Chemistry"/>
    </xs:restriction>
</xs:simpleType>

<!-- example element to have the above faceted value -->
<xs:element name="subject" type="tns:mySubject"/>

And here is the WSDL2PHP generated code,

    /**
     * @var string
     *     NOTE: subject should follow the following restrictions
     *     You can have one of the following value
     *     Maths
     *     Physics
     *     Chemistry
     */
    public $subject;

It clearly says your variable ‘subject’ is only allowed to have the list of values mentioned in the ‘enumeration’.

So I just wrote about some variations of simple schema types and how they are represented in the WSDL2PHP generated code. As you may have observed, you don’t need to know any thing about the WSDL or the schema to write a PHP code around that, since WSDL2PHP gives you a generated code mentioning all the guidelines, restrictions about using them.

In XML Schema we declare an array or a multiple occurrence of a schema element by setting its maxOccurs attribute to a value greater than 1 or to the value “unbounded” in a case of no maximum boundary.

<xs:element maxOccurs="unbounded"
            minOccurs="0"
            name="params"
            nillable="true"
            type="xs:int"/>

If you generate PHP code to such a schema using wsdl2php tool, you will get a code for the class variable named “params” similar to this.

    /**
     * @var array[0, unbounded] of int
     */
    public $params;

So if you have a variable (say $object) for the object of this class you can fill the “params” field like this,

$object->params = array(1, 5, 8);

This will create the xml with the expected array of elements.

<wrapper>
    <params>1</params>
    <params>5</params>
    <params>8</params>
</wrapper>

Not only for simple types, you can have arrays of complex types too.

<xs:element maxOccurs="unbounded"
            minOccurs="0"
            name="params"
            nillable="true"
            type="tns:MyComplexType"/>

Instead of giving simple integers like earlier case, this time you will feed the “params” variable with an array of PHP objects of ‘MyComplexType’ class.

$obj1 = new MyComplexType();
/* feeding data to obj1 variables */

$obj2 = new MyComplexType();
/* feeding data to obj2 variables */

$obj3 = new MyComplexType();
/* feeding data to obj3 variables */

$object->params = array($obj1, $obj2, $obj3);

This will create a xml containing array of params similar to this,

<wrapper>
    <params>
        <elementx/> <!-- elements in the MyComplexType type -->
        <elementy/>
    </params>
    <params>
        ... <!-- elements in the MyComplexType type -->
    </params>
    <params>
        ... <!-- elements in the MyComplexType type -->
    </params>
</wrapper>

PHP2WSDL feature of the WSF/PHP allows you to generate the WSDL for your service when you access the URL formed by adding “?wsdl” to the service URL ( or you can use service URL + “?wsdl2″ to access the wsdl version 2.0). It will generate the schema types for the wsdl from the classes you use to build the request message + the annotations you provided describing the types of the variables.

Sometime you may need to generate schema types with different names to the corresponding PHP classes. May be you need to have a ‘-’ in the schema type which is not valid in PHP class syntax or you like to have a different naming convention for PHP and wsdl.  Similarly you may need to have the operation names different in the WSDL and the PHP code.

Here is how you do it with WSF/PHP.

Different Names for Operations

/**
 * Service logic for the echo operation
 * @namespace http://ws.dimuthu.org/php/myecho/operations
 * @param object testObject $param
 * @return object testObject $return
 */
function echoMe($param) {
  return $param;
}

/* The Service operation name to PHP function name map */
$operations = array("echo" => "echoMe");

There I want my actual operation name to be echo. But I can’t declare a function name echo since PHP already has a library function echo (Yea, the one you regularly use to echo output). So I don’t have option other than declaring a function with different name (here it is “echoMe”) and mapped it in to echo operation in the operation map. We are going to feed this $operation variable at the WSService creation as its constructor argument.

Lets see how different names are used in schema types and corresponding php class names.

Different names for Types and Classes

/**
 * @namespace http://ws.dimuthu.org/php/myecho/types
 */
class testObject {

	/**
	 * @var integer aint
	 */
	public $aint;

	/**
	 * @var string astring
	 */
	public $astring;
}

/* The mapping of schema types to PHP class */
$classmap = array("test-object" => "testObject");

It is similar how we mapped operation in the previous section. Just use $classmap variable which map the schema type name to the php class name.

Here is the type section and the interface section of the WSDL 2.0 generated using above codes. Observe the operation names and the types names are formed the way we expected.

  <types>
    <xsd:schema xmlns:ns0="http://ws.dimuthu.org/php/myecho/types"
        xmlns:ns1="http://ws.dimuthu.org/php/myecho/types"
        elementFormDefault="qualified"
        targetNamespace="http://ws.dimuthu.org/php/myecho/operations/xsd">
      <xsd:import namespace="http://ws.dimuthu.org/php/myecho/types"/>
      <xsd:element name="param" type="ns0:test-object"/>
      <xsd:element name="return" type="ns1:test-object"/>
    </xsd:schema>
    <xsd:schema elementFormDefault="qualified"
                targetNamespace="http://ws.dimuthu.org/php/myecho/types">
      <xsd:complexType name="test-object">
        <xsd:sequence>
          <xsd:element name="aint" type="xsd:integer"/>
          <xsd:element name="astring" type="xsd:string"/>
        </xsd:sequence>
      </xsd:complexType>
    </xsd:schema>
  </types>
  <interface name="myEchoPortType">
    <operation name="echo" pattern="http://www.w3.org/ns/wsdl/in-out">
      <input element="tnx:param"/>
      <output element="tnx:return"/>
    </operation>
  </interface>

Here is the complete code (Combining all the previously mentioned code segments). You can check the complete wsdl generation (wsdl  1.1 or wsdl 2.0 as your preference) by copying and pasting this code to the online php2wsdl generator at the WSF/PHP Demo Site.

<?php

/**
 * Service logic for the echo operation
 * @namespace http://ws.dimuthu.org/php/myecho/operations
 * @param object testObject $param
 * @return object testObject $return
 */
function echoMe($param) {
  return $param;
}

/**
 * @namespace http://ws.dimuthu.org/php/myecho/types
 */
class testObject {

	/**
	 * @var integer aint
	 */
	public $aint;

	/**
	 * @var string astring
	 */
	public $astring;
}

/* The Service operation name to PHP function name map */
$operations = array("echo" => "echoMe");

/* Telling that we input MIX types for the parameters */
$opParams = array("echo" => "MIXED");

/* The mapping of schema types to PHP class */
$classmap = array("test-object" => "testObject");

/* Creating the WSService and serving the Request */
$service = new WSService(array(
			"operations" => $operations,
			"classmap" => $classmap,
			"opParams" => $opParams,
			"serviceName" => "myEcho"));

$service->reply();

?>

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