How to Create WSO2 Stratos ESB proxy service and invoke by BlackBerry Mobile Client


This is very basic usage of ESB and you can do many things inside this proxy service(Calling few actual web services, mediate message, logging, ,message reformat). I used this example to just demonstrate how we can use ESB with BlackBerry client.
WSO2 Strstos
WSO2 Stratos is the most complete, enterprise-grade, open PaaS, with support for more core services than any other available PaaS today. The open nature of WSO2 Stratos makes it the perfect environment for hosting companies, ISVs and System Integrators to build and customize Industry-specific PaaS and SaaS platforms for vertical markets; for example, creating a Mobile PaaS for telecom companies.The WSO2 StratosLive Java PaaS, hosted by WSO2, enables developers to instantly provision and pay for just the middleware services they use.
Enterprises can use the WSO2 StratosLive to host business process flows between business partners as well as implement cloud-based services that access internal systems.Developers get all the benefits of the complete WSO2 Carbon enterprise middleware platform and the multi-tenant, elastic WSO2 Stratos cloud middleware platform without the hassles of setting up machines and middleware

WSO2 ESB
WSO2 ESB is unique Enterprise Service Bus from the ground up relying on innovative Carbon technology to give you a smooth start-to-finish project experience you cannot find elsewhere.
Easy configuration through an intuitive graphical interface allows you to get started – and into production – much faster.
Lean, high-performance design conserves resources through maximum efficiency.
Built on the WSO2 Carbon OSGi platform: adding new capabilities as you need them is a snap.

http://wso2.com/wp-content/themes/wso2ng-v3/images/stratoslive-diagram.gif
In this post i will describe how to deploy a simple proxy service in stratoslive and how we can invoke it by BlackBerry mobile device. First we need to setup eclipse IDE(Which use widely in enterprise level to develop BlackBerry Applications) to develop BlackBerry Apps. In my previous post i have describe this topic clearly you will find it here.
First we will see how we can deploy simple proxy service with StratosLive.
First to
https://stratoslive.com/ . you can create new account freely.Then login to the system go to ESB home page. See the figure

Screenshot 

Figure : Services Home WSO2 StratosLive
Then click on source view to edit configurations.
Screenshot44
Figure : Edit window for edit source of Configuration
Typically the ESB is deployed between the actual client and a backend service implementation to mediate the message flow in between. Thus WSO2 ESB can accept a message on behalf of the actual service, perform authentication, validation, transformation, logging, routing based on the content etc. and then decide the destination target endpoint for the message and direct it to an actual service implementation.We have to write configuration for those operations. These configuration are written using the Synapse configuration language which is a simple and easy to learn domain specific language based on XML. It is always recommended to use the graphical wizards and tools provided in the WSO2 ESB management console to setup the mediation configuration, thus avoiding having to write XML configurations manually. But for this simple configuration we will use XML writing method. See following configuration.
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="
http://ws.apache.org/ns/synapse">
    <registry provider="org.wso2.carbon.mediation.registry.WSO2Registry"/>
    <proxy name="EchoProxy" transports="https" startOnLoad="true" trace="disable">
        <target inSequence="response"/>
        <policy key="conf:/repository/axis2/service-groups/EchoProxy/services/EchoProxy/policies/UTOverTransport"/>
        <enableSec/>
    </proxy>
    <proxy name="loginproxy" transports="https http" startOnLoad="true" trace="disable">
        <target inSequence="main"/>
    </proxy>
    <sequence name="response">
        <script language="js">mc.setPayloadXML(
            &lt;greeting&gt;Hello World&lt;/greeting&gt;
            );</script>
        <header name="To" action="remove"/>
        <property name="NO_ENTITY_BODY" scope="axis2" action="remove"/>
        <property name="RESPONSE" value="true"/>
        <send/>
        <log level="full"/>
    </sequence>
    <sequence name="fault">
        <log level="full"/>
    </sequence>
    <sequence name="main">
        <log/>
        <drop/>
    </sequence>
</definitions>
There you will see EchoProxy which is use to set set XML Payload to response message.if you need you can do some thing more inside this proxy(Do Authentication check, send request to actual web service/data service and send response back).
Yo have to copy this configuration to your configuration and update
Next go to services and you will see deployed proxy service as follows



Screenshot-3 

figure : Deployed services window to view Proxy Services Deployed

Then click on the service and you will see following window. There you can edit your service/ generate WSDL/ Try service etc... Then click on try it and test your service by sending request. you will see the response with greeting message


Screenshot-7 
Figure : Service home window Edit and modify the service

Now we have created our proxy service successfully now we will see how we can invoke this by BlackBerry.First setup your Eclipse IDE using this guideline document.
Then download esb_client source code for here.Unzip it and open with eclipse ide.
You have to set your proxy service url properly in the code.for me it was

http://esb.stratoslive.wso2.com:8280/services/t/sanjeewa.info/EchoProxy"

In blackBerry mobile devices before send request to some url we have to append some part to it. It must contain [deviceside=true;apn=Apnkey]. When i developed my first application in 2009 i found simple solution for this.I was able to store some known apns with relative Mobile Network Code(MNC) and Mobile Country Code (MCC).
and retrive them when necessary.you will see more information on MCC/MNC here[
http://en.wikipedia.org/wiki/Mobile_Network_Code]. I have written separate post how to use that method, click here[http://sanjeewamalalgoda.blogspot.com/2009/09/run-blackberry-application-without-apn.html] to view it. I used same method for this example.
Here we will do simple http get() to that proxy service and get greeting message. you will see very basic UI for service invocation.

Then build project and run it on blackberry Device simulator.
Go to downloads for your Mobile device.You will see SendT program click on it you will see the following window

                                      clip_image002

Then Click on left button and press send request.Then you will see the status and response message as shown below
clip_image002[6]                 clip_image002[8]



so you can modify ESB configuration and client source code as you need for different kind of usages. if you need to test this program with actual device copy cod,jad or jar file to your mobile device using BlackBerry Desktop Software [http://us.blackberry.com/apps-software/desktop/]. And install program to your device.


Source Code for BlackBerry Client:


package senddTpkg;

//********************************************************
//@Auther  - MALALGODA S.R.B.(sanjeewa190@gmail.com)
//   
//@Date    -2009/07/04
//
//@Project -Blackberry Mobile application 
//
//@Code      - Java Blackberry application to send Http request to WSO2 Stratos ESB  
//            proxy service
//
//********************************************************
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.file.FileConnection;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.RadioInfo;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;

public class sendTCls extends UiApplication {

    public static void main(String[] args) {
        sendTCls theApp = new sendTCls();
        theApp.enterEventDispatcher();
    }

    public sendTCls() {
        pushScreen(new UserInterfaceScreen());
    }
}

final class UserInterfaceScreen extends MainScreen {
    String words;
    String apn;
    HorizontalFieldManager _fieldManagerTop;
    VerticalFieldManager _fieldManagerMiddle;
    HorizontalFieldManager _fieldManagerBottom;
    BitmapField _bitmap;
    Bitmap _canadaImage;
    LabelField _label;
    static BasicEditField _input;
    String _canadaCapital;
    int displayed = 0;
    private static final int IMAGE_SIZE = 2430;
    private byte[] data = new byte[IMAGE_SIZE];

    RichTextField rtf = new RichTextField("");

    public UserInterfaceScreen() {
        super();
        LabelField title = new LabelField("WSO2 ESB Test Service",
                LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH);
        setTitle(title);
        _fieldManagerTop = new HorizontalFieldManager();
        _fieldManagerMiddle = new VerticalFieldManager();
        _fieldManagerBottom = new HorizontalFieldManager();
        add(_fieldManagerTop);
        add(new SeparatorField());
        add(_fieldManagerMiddle);
        add(new SeparatorField());
        add(_fieldManagerBottom);
        _label = new LabelField(
                "This is WSO2 Stratos ESB Proxy service test program."
                        + " press the left menu and click on send request buttion then you will send"
                        + " request to Hellow Service. Response will show below.");
        _fieldManagerMiddle.add(_label);
        add(rtf);
        FieldChangeListener listenerCanada = new FieldChangeListener() {
            public void fieldChanged(Field field, int context) {
                displayed = 0;
            }
        };
    };

    protected void makeMenu(Menu menu, int instance) {
        menu.add(_changeCapital);
        menu.add(_close);
    }

    private MenuItem _changeCapital = new MenuItem("Sent Request", 110, 10) {
        public void run() {
            try {
                String mcc = Integer.toHexString(RadioInfo.getMCC(RadioInfo
                        .getCurrentNetworkIndex()));
                String mnc = Integer.toHexString(RadioInfo.getMNC(RadioInfo
                        .getCurrentNetworkIndex()));
                String responseStr = getHttpResponce1("http://esb.stratoslive.wso2.com:8280/services/t/sanjeewa.info/EchoProxy"
                        + ";deviceside=true;apn="
                        + getTag(ReadFile(), mcc + "," + mnc));
                rtf.setText(responseStr);
                Dialog.alert("Successfull");
            } catch (Exception e) {
                Dialog.alert("Error In connecting=" + e.toString());
            }
        }
    };

    private MenuItem _close = new MenuItem("Close", 110, 10) {
        public void run() {
            onClose();
        }
    };

    public boolean onClose() {
        Dialog.alert("Goodbye!");
        System.exit(0);
        return true;
    }

   

    public String ReadFile() {
        try {
            Class classs = Class.forName("senddTpkg.sendTCls");
            // Source Package neme and Class name
            InputStream is = classs.getResourceAsStream("/test.txt");
            byte[] data = new byte[is.available()];
            is.read(data, 0, is.available());
            String c = new String(data);
            return c;
        } catch (Exception ioe) {
            Dialog.alert("Error");
            return null;
        }
    }

    public static String getTagFromStringXML(String XML, String TagName) {
        try {
            String returnStr = "";
            String frontTag1 = "<" + TagName;
            String backTag1 = "=";
            String front = "<" + TagName + ">";
            String back = "";
            String[] arrayGet = splitToArr(XML, frontTag1);
            if (arrayGet.length > 0) {
                String[] arrayGet1 = splitToArr(arrayGet[1], back);
                return arrayGet1[0];
            }
            arrayGet = splitToArr(XML, front);
            if (arrayGet.length > 0) {
                String[] arrayGet1 = splitToArr(arrayGet[1], back);
                return arrayGet1[0];
            }

            return returnStr;
        } catch (Exception e) {
            return "";
        }

    }

    private static String[] splitToArr(String inString, String delimeter) {

        String[] retAr = new String[0];
        try {
            Vector vec = new Vector();
            int indexA = 0;
            int indexB = inString.indexOf(delimeter);

            while (indexB != -1) {
                if (indexB > indexA)
                    vec.addElement(new String(inString
                            .substring(indexA, indexB)));
                indexA = indexB + delimeter.length();
                indexB = inString.indexOf(delimeter, indexA);
            }
            vec.addElement(new String(inString.substring(indexA, inString
                    .length())));
            retAr = new String[vec.size()];
            int intIteration = vec.size();
            for (int i = 0; i < intIteration; i++) {
                retAr[i] = vec.elementAt(i).toString();
            }
        } catch (Exception e) {

        }
        return retAr;
    }

    public static String getTag(String XML, String TagName) {
        try {
            String ans = "error";
            String front1 = "<" + TagName;
            String arrayGet = "=";
            String[] sssnew = split(XML, front1);
            if (sssnew.length > 1) {
                String back1 = null;
                String[] sss1new = split(sssnew[1], back1);
                if ((sss1new[0]).compareTo(" i:nil") < 1) {
                    ans = "";
                    return ans;
                }
            }
            String front = "<" + TagName + ">";
            String back = "";
            String[] sss = {};
            sss = split(XML, front);
            if (sssnew.length > 1) {
                String[] sss1 = {};
                sss1 = split(sss[1], back);
                ans = sss1[0];
            }

            return ans;
        } catch (Exception e) {
            return "";
        }

    }

    private static String[] split(String inString, String delimeter) {

        String[] retAr = new String[0];
        try {
            Vector vec = new Vector();
            int indexA = 0;
            int indexB = inString.indexOf(delimeter);

            while (indexB != -1) {
                if (indexB > indexA)
                    vec.addElement(new String(inString
                            .substring(indexA, indexB)));
                indexA = indexB + delimeter.length();
                indexB = inString.indexOf(delimeter, indexA);
            }
            vec.addElement(new String(inString.substring(indexA, inString
                    .length())));
            retAr = new String[vec.size()];
            int intIteration = vec.size();
            for (int i = 0; i < intIteration; i++) {
                retAr[i] = vec.elementAt(i).toString();
            }
        } catch (Exception e) {

        }
        return retAr;
    }

    public static String getHttpResponce1(String URL) {

        try {
            HttpConnection httpConnection = (HttpConnection) Connector
                    .open(URL);
            httpConnection.setRequestMethod(HttpConnection.GET);
            InputStream inputStream = httpConnection.openInputStream();

            StringBuffer sb = new StringBuffer();
            int C;

            while (-1 != (C = inputStream.read())) {
                sb.append((char) C);
            }

            return sb.toString();

        } catch (Exception e) {
            return "-1";
        }
    }
}
 common APN keys stored in test.txt file
<310,12>
<310,4> verizon
<310,38>     AT&T
<310,90>
<310,150>
<310,680>
<310,410>
<310,160>wap.voicestream.com
<310,170>wap.voicestream.com
<310,260>wap.voicestream.com
<310,490>wap.voicestream.com
<310,26>wap.voicestream.com
<890,126>wap.voicestream.com
<413,2>dialogbb
<302,720>internet.com
<22e2,0>
 Download full source code
http://wso2.org/files/proxy_service_test_BB_client_src.zip

No comments:

Post a Comment

Empowering the Future of API Management: Unveiling the Journey of WSO2 API Platform for Kubernetes (APK) Project and the Anticipated Alpha Release

  Introduction In the ever-evolving realm of API management, our journey embarked on the APK project eight months ago, and now, with great a...