Sunday, October 4, 2015

Consuming a RESTful Web Service with C++ using QT libraries

After a long time I got a chance to work again with QT framework, Here are some of the findings about how to invoke RESTful webservices using QT. It's pretty easy really!!

g++  or compatible c++ compiler
QT5 or later with QtNetwork module

#include <QCoreApplication>
#include <QtCore/QUrl>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>

int main(int argc, char *argv[])
    QCoreApplication app(argc, argv);

    QEventLoop eventLoop;
    QNetworkAccessManager mgr;
    QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
    QNetworkRequest req( QUrl( QString(",lk") ) );
    QNetworkReply *reply = mgr.get(req);

    if (reply->error() == QNetworkReply::NoError) {
        QString strReply = (QString)reply->readAll();
        QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8());
        QJsonObject jsonObj = jsonResponse.object();
        qDebug() << "name: " << jsonObj["name"].toString();
        qDebug() << "latitude: " << jsonObj.value(QString("coord")).toObject()["lat"].toDouble();
        qDebug() << "longitude: " << jsonObj.value(QString("coord")).toObject()["lon"].toDouble();
        delete reply;
    else {
        qDebug() << "Failure" <<reply->errorString();
        delete reply;
    return 0;

g++ -c -m64 -pipe -O2 -Wall -W -D_REENTRANT -fPIE -DQT_NO_DEBUG -DQT_NETWORK_LIB -DQT_CORE_LIB -I/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++-64 -I. -I/usr/include/qt5 -I/usr/include/qt5/QtNetwork -I/usr/include/qt5/QtCore -I. -o main.o main.cpp

g++ -m64 -Wl,-O1 -o jsonWSClinetTest main.o   -lQt5Network -L/usr/lib/x86_64-linux-gnu -lQt5Core -lpthread 

name: "Colombo"
lat: 6.93
lat: 79.85

Monday, August 18, 2014

Hello World using OpenCL

I've recently acquired a new laptop with an API Radeon GPU. I'm always interested in HPC and how it is used in various industries and research areas. I had experience with MPI/OpenMP earlier but not got a chance to look into GPU style frameworks such as CUDA or OpenCL. I've a lot of free time these days, so I studied some online tutorials and got a little bit familiar with OpenCL and it's very interesting to me.

I'm using AMD's APP SDK 2.9 for my work, my first OpenCL code as below, it can be compiled using gcc with -lOpenCL

#include <stdio.h>
#include <string.h>
#include <CL/cl.h>

const char source[] = "       \
__kernel void hello( __global char* buf, __global char* buf2 ){ \
       int x = get_global_id(0);     \
       buf2[x] = buf[x];      \

int main() {
        char buf[]="Hello, World!";
        char build_c[4096];
        size_t srcsize, worksize=strlen(buf);

        cl_platform_id platform;
        cl_device_id device;
        cl_uint platforms, devices;
        /* Fetch the Platforms, we only want one. */
        clGetPlatformIDs(1, &platform, &platforms);

        /* Fetch the Devices for this platform */
        clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 1, &device, &devices);

        /* Create a memory context for the device we want to use  */
        cl_context_properties properties[]={CL_CONTEXT_PLATFORM, (cl_context_properties)platform,0};
        cl_context context=clCreateContext(properties, 1, &device, NULL, NULL, NULL);

        /* Create a command queue to communicate with the device */
        cl_command_queue cq = clCreateCommandQueue(context, device, 0, NULL);

        const char *src=source;
        const char *srcptr[]={src};
        /* Submit the source code of the kernel to OpenCL, and create a program object with it */
        cl_program prog=clCreateProgramWithSource(context, 1, srcptr, &srcsize, NULL);

        /* Compile the kernel code (after this we could extract the compiled version) */
        clBuildProgram(prog, 0, NULL, "", NULL, NULL);

        /* Create memory buffers in the Context where the desired Device is. These will be the pointer 
        parameters on the kernel. */
        cl_mem mem1, mem2;
        mem1=clCreateBuffer(context, CL_MEM_READ_ONLY, worksize, NULL, NULL);
        mem2=clCreateBuffer(context, CL_MEM_WRITE_ONLY, worksize, NULL, NULL);

        /* Create a kernel object with the compiled program */
        cl_kernel k_hello=clCreateKernel(prog, "hello", NULL);

        /* Set the kernel parameters */
        clSetKernelArg(k_hello, 0, sizeof(mem1), &mem1);
        clSetKernelArg(k_hello, 1, sizeof(mem2), &mem2);

        /* Create a char array in where to store the results of the Kernel */
        char buf2[sizeof buf];
        /* Send input data to OpenCL */
        clEnqueueWriteBuffer(cq, mem1, CL_FALSE, 0, worksize, buf, 0, NULL, NULL);

        /* Tell the Device, through the command queue, to execute que Kernel */
        clEnqueueNDRangeKernel(cq, k_hello, 1, NULL, &worksize, &worksize, 0, NULL, NULL);

        /* Read the result back into buf2 */
        clEnqueueReadBuffer(cq, mem2, CL_FALSE, 0, worksize, buf2, 0, NULL, NULL);

        /* Await completion of all the above */

        /* Finally, output the result */

Friday, September 27, 2013

Quick Start Apache Stratos from EC2 images

In this blog post I focus on deploying the pre-built EC2 image of Apache Stratos.

Note : This blog post is based on "Stratos Quick Start Guide", 

Starting the Apache Stratos demo image

Common Prerequisites

The following are the recommended prerequisites when running the Apache Stratos demo setup in a single node. Please note that for production deployment the prerequisites will vary based on the scalability requirements.

 System Requirements

Processor : 2.8GHz CPU
Memory : At least 8GB memory. However, 16GB is recommended.
Disk : 40G hard disk space

The following are the memory allocations for Amazon EC2 instance types that you may require:

m1.large = 7.5 GB
m1.xlarge =15 GB
m3.xlarge= 15 GB

Software Requirements

  • Git
  • Facter
  • Java (JDK1.6.x)
  • ZIP
  • MySQL Server
  • Gitblits

A Git repository is needed. For more information, see Configuring a Git Server

Environment Compatibility

Operating Systems : Linux (Ubuntu 12.04 64bit server or SUSE Linux Enterprise 11 SP2).

EC2 Account

To follow this blog post, you need an EC2 account. Create an AWS account, if you do not have an account. For more information, see Sign Up for Amazon EC2. This account must be authorized to manage EC2 instances (including start and stop instances, create security groups and key pairs).

Apache Stratos EC2 images

You can find Apache Stratos EC2 AMI information from Dinesh's floowing blog post

 Creating a security group

Before launching the instance, you need to create the right security group. This security group defines the firewall rules for your instances, which are a list of ports that are used as part of the default Apache Stratos deployment. These rules specify which incoming network traffic is delivered to your instance. All other traffic is ignored. For more information on which ports should be defined, see Common IaaS Configurations.

To create the security group and configure it:

  1. On the Network and Security menu, click Security Groups
  2. Click Create Security Group.
  3. Enter the name and description of the security group.
  4. Click Yes, Create.
  5. Click Inbound.

  6. Select the "Custom TCP rule" option from the Create a new rule drop-down list.

    All the UDP and TCP ports can be opened by adding the following two rules. Note that the latter mentioned two rules are a demo only setting. Individual rules with the specified ports must be added for security purposes in a production environment.

    Rule type Port Range
    All TCP 0 - 65535
    All UDP 0 - 65535
  7. Enter the port or port range
    There are two kinds of ports listed in the common configurations, which are namely open for outside access and restricted internal access. You will have to ideally enter each of the ports as separate rules.
  8. You can set the Source to be
    Note that setting the Source to be is a demo only setting, which must be changed for security purposes in a production environment. For more information, see Using Network Security.
  9. Click Add Rule and then click Apply Rule Changes.
    Always apply rule changes, as your rule will not get saved unless the rule changes are applied. Repeat steps 6 to 9 to add all the ports mentioned, as each port or port range has to be added as a separate rule.

 Creating a Key Pair

Before launching the instance, it is recommended to create a Key Pair. Save your private key in a safe place on your computer. Note the location because you will need the Key Pair to connect to your instance.

To create a Key Pair and download it:

  1. On the Network and Security menu, click Key Pairs.
  2. Click Create New Key Pair.
  3. Enter a name for your Key Pair.
  4. Click Yes, Create.
  5. Click Create. After the Key Pair automatically downloads, click Close.

 Gathering data

The following data is required:

  • Access key and Secret key of your EC2 account
    To get your Access Key ID and Secret Access Key:
    1. On the EC2 account details menu, click My Account.
    2. Click Security Credentials on the left-bar menu.
    3. Click on the Access Keys tab.
    4. Create an access key for this setup.
    5. Then note the Access Key ID and Secret Access Key.
  • Owner ID
    To view the Owner ID:
    • On the EC2 account details menu, click My Account.
    • Your account number will appear, which is your Owner ID. Omit the hyphens when entering the Owner ID.
  • Availability zone
    This is the zone where the virtual machines will be launched. If you set the Availability zone to "No Preference", the system will set the default value. Only Asia Pacific Singapore and US East 1 are available at this point, and therefore the potential values are:
    • us-east-1
      This will be the default value, if you want to let the system choose the availability zone. Otherwise, provide us-east-1a,us-east-1b or us-east-1c.
    • ap-southeast-1
      This will be the default value, if you want to let the system choose the availability zone. Otherwise, provide ap-southeast-1a or ap-southeast-1b.
  • Domain name
    This is the CNAME for your Apache Stratos domain, such as

Spawning the Apache Stratos instance

  1. Sign in to the Amazon Web Services (AWS) Management Console and open the Amazon EC2 console at
  2. Click EC2 on the home console.
  3. Select either the Asia Pacific (Singapore) or US - East (North Virginia) region for the instance from the region drop down list. In the rest of the steps, we assume that you have chosen North Virginia.
  4. Launch Instance.
  5. Select Quick Launch Wizard.
  6. Name your instance, for example ApacheStratosDemo.
  7. Select the Key Pair that you created
  8. Select More Amazon Machine Images and click Continue.
  9. On the next page, specific the image ID as per the table above and click Search
  10. Click on your search result and click Continue
  11. Click Edit Details
  12. Edit the image size.
    1. Select the Instance Details option.
    2. Change the image type to either m1.xlarge or m3.xlarge (15GB of memory).
  13. Select a security group.
    1. Select the Security Settings option.
    2. Click Select Existing Security Groups.
    3. Select the Apache Stratos security group that you created previously.
  14. Add user data.
    1. Click Advanced Details.
    2. Enter the following parameters with your own values in the User Data text-box and do not keep spaces in between the user data text.

      User Data Description
      EC2_KEY_PATH The path that you will upload your EC2 key.
      ACCESS_KEY See Access key and Secret key of your EC2 account
      SECRET_KEY See Access key and Secret key of your EC2 account
      OWNER_ID See Owner ID
      AVAILABILITY_ZONE See Availability zone
      SECURITY_GROUP See Creating a Security Group
      KEY_PAIR_NAME See Creating a Key Pair
      DOMAIN This is the CNAME for your Stratos domain



    3. You can either enter a part of the parameters or skip this entire step. If you do not enter the required configurations in this step,
    4. then you will be prompted for those configurations at a later step.
  15. Click Save details.
  16. Review the information and click Launch to start the EC2 instance.
  17. Click Close.

Configuring the Apache Stratos instance

Uploading your key pair file

You need to upload the key pair file that you created during the image configuration (for example, ApacheStratosKeyPair.pem) to the running
Apache Stratos instance. This file will be used to securely copy files to the run-time instances (Cartridges).

  1. Change the key pair file permissions.
    By default your key pair file will be unprotected.
    When uploading your key pair file, if it is unprotected it will be rejected. Use the following command to secure your key pair file so that
    others will not have access to it:

    chmod 0600 <path to the private key>
  2. Upload the key pair using the following scp command: 
    scp -i <path to the private key> <path to the private key> ubuntu@ <EC2 instance hostname>:
    In the above command the private key will be uploaded to /home/ubuntu directory on the Apache Stratos instance.
    For example:
    scp -i ApacheStratosKeyPair.pem ApacheStratosKeyPair.pem

    Once the command mentioned in the example completes, the key pair file will be uploaded to the /tmp directory on the Apache Stratos instance.
  3. The following output will appear. Say 'yes' to connect and add the RSA fingerprint to your known hosts list.
    The authenticity of host ' (' can't be established.
    RSA key fingerprint is b2:6c:c1:0e:fd:a2:05:d6:6a:4e:cc:c5:8b:ef:ce:64.
    Are you sure you want to continue connecting (yes/no)? yes

Locating your EC2 instance hostname

To get your EC2 instance hostname:.

  1. On the Instances menu in the navigation panel, click the Instances sub-menu.
    The list of instances that you own appears.
  2. Search and select the correct instance.
    The EC2 instance hostname will appear in the second line of the bottom pane that contains descriptions on the instance.

Once the instance is successfully launched, you need to configure several settings that will be used by Apache Stratos to manage and launch the virtual machines (Cartridges) available.
  1. Login to the instance using ssh with ubuntu as the username and the key pair that you downloaded when you were spawning the
    instance as the password.
    If you have navigated to the directory of the key pair, enter only the name of the key pair in the following ssh command; otherwise, enter
    the full path of the private key.
    ssh -i <private key path> ubuntu@<EC2 instance hostname>
    For example:

    ssh -i ApacheStratosKeyPair.pem

  2. Once connected, start a root session.

    sudo -i
  3. Navigate to the /opt/stratos-installer directory.

    cd /opt/stratos-installer

  4. Run the script located in this directory.


    The script prompts you to override data.

    root@ip-172-31-43-213:/opt/stratos-installer# ./
    Please confirm whether you want to be prompted, irrespective of the data
    available in user-data? [y/n]

    Enter [n]
    As we have provided user data when launching the instance you can use this option. However, you will be prompted for the
    values that are not found in the user data section.
    Enter [y]
    This will discard the values in the User Data section, and will prompt for the user data details that need to be configured
    according to your EC2 account. This is useful if you have mistakenly added incorrect values for fields in the User Data section.
    Answer to the list of questions, using the data gathered above.

    Once all questions are answered, the script will configure the various deployment scripts and Apache Stratos will be ready to
    create tenants and allows them to use Cartridges.
  5. The WSO2 MB will be started and you will be prompted to select the user:
    If you wish to change the user at this point, enter the username of the desired user, or else press "enter" to continue with the default user
    that has the username=ubuntu.

    user provided in conf/setup.conf is ubuntu. If you want to provide some other
    username please specify it at the prompt.
    If you want to continue with ubuntu just press enter to continue
  6. Answer 'y' to the next question and all the servers will be started.

    Apache Stratos setup has successfully completed
    Do you want to start the servers [y/n]?

    The following message appears:

    Servers started. Please look at /var/log/apache-stratos/stratos-setup.log file
    for server startup details
    Management Console :

Once the Apache Stratos main servers have been started, you can connect to the Apache Stratos controller (which is the "heart" of Apache Stratos) to create a tenant. A tenant is an organization that will use the PaaS. Inside an organization, one or N Cartridges (runtimes) can be subscribed to.

The Apache Stratos controller runs at: https://:9445 (for example, Once you are connected, login using the default admin user (admin/admin). This logs you in as the super tenant administrator.
  1. Change your default super tenant admin password.
  2. Create a Tenant.
  3. Subscribe to Cartridges. For more information, see Subscribing to a Cartridge and Connecting to another Cartridge when subscribing.
  4. If you wish, map a domain to the newly created Cartridge.
  5. Map the host name to Apache Stratos ELB IP.

Friday, April 12, 2013

How to automate the installation of Eclipse plugins with ant task

In this blog post I suggest a simple way to automate the installation of Eclipse plugins with ant task and maven-antrun-plugin.

${project.basedir}/target/eclipse = eclipse dir (extract using maven dependency plugin)
${project.basedir}/target/p2-repo = p2 dir of plugins  (extract using maven dependency plugin),,.... = sample feature group names

a snippet of my code follows.

      <java classname="org.eclipse.equinox.launcher.Main" failonerror="true" fork="true" maxmemory="1024m" spawn="false">
       <fileset dir="${project.basedir}/target/eclipse/plugins" includes="org.eclipse.equinox.launcher*.jar">
      <arg value="-nosplash"/>
      <arg value="-application"/>
      <arg value="org.eclipse.equinox.p2.director"/>
      <arg value="-repository"/>
      <arg value="file:${project.basedir}/target/p2-repo"/>
      <arg value="-destination"/>
      <arg value="${project.basedir}/target/eclipse"/>
      <arg value="-installIU"/>
      <arg value=""/>
      <arg value="-installIU"/>
      <arg value=""/>
      <arg value="-installIU"/>
      <arg value=""/>
      <arg value="-installIU"/>
      <arg value=""/>
      <arg value="-installIU"/>
      <arg value=""/>

Wednesday, September 19, 2012

How to change the mouse icon/feedback when we drag a node to the canvas from the tool palette in a GEF/GMF based editor

In this blog post I suggest a simple way to change the drag icon/feedback to indicate to the user that it is to drop or illegal to drop what they are dragging at the current location in a GEF or GMF based editor.

You can do it simply by implementing custom DragDropEditPolicy and installing to your EditPart.

a snippet of my code follows.

import java.awt.MouseInfo;
import java.awt.Point;

import org.eclipse.draw2d.FigureCanvas;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.ImageFigure;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.requests.ChangeBoundsRequest;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeCompartmentEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.DragDropEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.requests.CreateUnspecifiedTypeRequest;
import org.eclipse.swt.widgets.Control;
import org.eclipse.wb.swt.SWTResourceManager;

 * Installing FeedbackIndicateDragDropEditPolicy will indicate a feedback when drag a node
 * to the canvas from the tool palette
public class FeedbackIndicateDragDropEditPolicy extends DragDropEditPolicy {
 private IFigure feedbackFigure;
 private Image feedbackImage;

 private static final String ALLOW_DROP_ICON_PATH = "/icons/custom/check.png";
 private static final String NOT_ALLOW_DROP_ICON_PATH = "/icons/custom/exclamation.png";

  * {@inheritDoc}
 protected Command getDropCommand(ChangeBoundsRequest request) {
  if ((getHost() instanceof ShapeCompartmentEditPart)) {
   //avoiding drag and drop nodes between compartments.
   return null;
  return super.getDragCommand(request);

  * {@inheritDoc}
 public void showTargetFeedback(Request request) {
  if (request instanceof CreateUnspecifiedTypeRequest) {
   if (getHost() instanceof ShapeCompartmentEditPart) {
    ShapeCompartmentEditPart host = (ShapeCompartmentEditPart) getHost();
    Command command = host.getCommand(request);
    if (command != null) {
     if (command.canExecute()) {
     } else {
    } else {
   } else {

  * {@inheritDoc}
 public void eraseTargetFeedback(Request request) {
  if (feedbackFigure != null) {
   feedbackFigure = null;

  * Get feedback figure
  * @param allowDrop
  * @return
 public IFigure getFeedbackFigure(boolean allowDrop) {
  if (feedbackFigure == null) {
   Image feedbackImage = SWTResourceManager.getImage(this.getClass(),
   IFigure figure = new ImageFigure(feedbackImage);
   this.feedbackImage = feedbackImage;
   feedbackFigure = figure;
  return feedbackFigure;

  * Show feedback figure in canvas
  * @param allowDrop
 private void showFeedBackFigure(boolean allowDrop) {
  Point pointer = MouseInfo.getPointerInfo().getLocation();
  IFigure feedbackFigure = getFeedbackFigure(allowDrop);
  int x = (int) pointer.getX();
  int y = (int) pointer.getY();
  Control ctrl = getHost().getViewer().getControl();
  FigureCanvas canvas = (FigureCanvas) ctrl;
  int horizontal = canvas.getHorizontalBar().getSelection();
  int vertical = canvas.getVerticalBar().getSelection();
  horizontal += 15;
  vertical -= 15; p = canvas.toDisplay(0, 0);
  feedbackFigure.setBounds(new Rectangle((x - p.x) + horizontal, (y - p.y) + vertical,
    feedbackImage.getBounds().width, feedbackImage.getBounds().height));


Tuesday, June 12, 2012

How to develop CXF based JAX-WS with WSO2 Developer Studio

This blog post shows the basics of using the WSO2 Developer Studio to develop a JAX-WS. After creating the web service, you can write web services clients that use the web service on a network.

Java API for XML-Based Web Services (JAX-WS), which is also known as JSR-224, is the next generation Web services programming model that extends the foundation provided by the Java API for XML-based RPC (JAX-RPC) programming model. Using JAX-WS, developing Web services and clients is simplified with greater platform independence for Java applications by the use of dynamic proxies and Java annotations.

Apache CXF is an open source web service framework that provides an easy to use, standard-based programming model for developing web services. Web services can be implemented using different application protocols like SOAP, XML, JSON, RESTful HTTP, and support various transport protocols like HTTP or JMS.

WSO2 Developer Studio (formerly named WSO2 Carbon Studio) is a complete Eclipse-based SOA development environment for the award-winning WSO2 Carbon platform, WSO2 Developer Studio supports the development of Web applications, gadgets, services, business processes and more, enabling a developer to first build an application and then deploy and debug it from the IDE itself

In my articles I will use following software:

SoftwareVersion Required
WSO2 Developer Studio2.0.0
Java Development Kit (JDK)JDK 6 Update 32
WSO2 Application Server4.5.0 M3
Apache CXF2.5.4

  1. Creating a Web Service
    1. Creating a Web Service Project
    2. Creating a Web Service from a Java Class
  2. Deploying the Web Service
  3. Testing the Web Service
  4. Consuming the Web Service
  5. Samples

Creating a Web Service

Creating a Web Service Project

First, we create an empty JAX-WS service Project, to create a JAX-WS Service Project,
  1. Go to the J2EE perspective

  2. select File->New->Project and select WSO2 category

  3. under WSO2 category select Service Hosting->Project Types->JAX-WS Service Project from the new project wizard dialog

  4. There are two ways to create a JAX-WS project. "Create a JAX-WS Project" and "Create a JAX-WS Project using WSDL", to create a empty project we select  "Create a JAX-WS Project"

  5. Name the project AccountServiceProject. Select a location for the project. Click Finish.

  1. Right-click the AccountServiceProject porject and choose New > JAX-WS Service Class

  2. Name the web service class 'AccountServiceImpl' and type "org.example.webservice" (or any other qualified package name) in package name field
  3. In Service Interface section, name the web service interface class 'AccountService' and type "org.example.webservice" (or any other qualified package name) in package name field
  4. deselect "Add sample web service method to new class".
  5. Click Finish. The Projects Explore view displays the structure of the project and the source code is shown in the java editor area.

  6. open service interface class (  that you generated in the previous steps and add following method to interface

    public int createAccount(boolean print);
    public boolean checkAccount(int accountNo);
    public int checkAccountBalance(int accountNo);
    public boolean creditAccount(int accountNo, int amount);
    public boolean debitAccount(int accountNo, int amount);

    AccountService interface would look like this
    package org.example.webservice;
    import javax.jws.WebService;
    public interface AccountService {
     public int createAccount(boolean print);
     public boolean checkAccount(int accountNo);
     public int checkAccountBalance(int accountNo);
     public boolean creditAccount(int accountNo, int amount);
     public boolean debitAccount(int accountNo, int amount);
  7. open web service implementation class ( and implement missing methods as below
    package org.example.webservice;
    import java.util.Hashtable;
    import java.util.Random;
    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    @WebService(serviceName = "AccountServiceImpl")
    public class AccountServiceImpl implements AccountService {
     // account no list of the customers
     static Hashtable<integer, integer> accountStore = new Hashtable<integer, integer>();
      * generates the random account no at registration
      * @return the random account number integer
     private int randomAccountGenerate() {
      Random randomGenerator = new Random();
      return randomGenerator.nextInt(1000);
      * create a new account and store
      * @return accountNo
    @WebMethod(operationName = "createAccount")
     public int createAccount(@WebParam(name = "printOnConsole") boolean print) {
      int accountNo = 0;
      // Generate the random account no
      accountNo = randomAccountGenerate();
      // create the entry in the account store
      accountStore.put(accountNo, 0);
       System.out.println("New account created, No= " + accountNo);
      return accountNo;
      * check whether the account is available
      * @param accountNo
      * @return isAvailable
     @WebMethod(operationName = "checkAccount")
     public boolean checkAccount(@WebParam(name = "accountNo") int accountNo) {
      if (accountStore.containsKey(accountNo)) {
       return true;
      return false;
      * @param accountNo
      * @return balance
     @WebMethod(operationName = "checkAccountBalance")
     public int checkAccountBalance(@WebParam(name = "accountNo") int accountNo) {
      if (checkAccount(accountNo)) {
       return accountStore.get(accountNo);
      return 0;
      * Increase the balance by credit amount
      * @param accountNo
      * @param amount
      * @return success
     @WebMethod(operationName = "creditAccount")
     public boolean creditAccount(@WebParam(name = "accountNo") int accountNo,
       @WebParam(name = "amount") int amount) {
      if (checkAccount(accountNo)) {
         (accountStore.remove(accountNo) + amount));
       return true;
      return false;
      * Decrease the balance by the debit amount
      * @param accountNo
      * @param amount
      * @return Operation successfulness
     @WebMethod(operationName = "debitAccount")
     public boolean debitAccount(@WebParam(name = "accountNo") int accountNo,
       @WebParam(name = "amount") int amount) {
      if (checkAccount(accountNo) && (accountStore.get(accountNo) >= amount)) {
         (accountStore.remove(accountNo) - amount));
       return true;
      return false;

Deploying the Web Service

There are two method to deploy our JAX-WS service into WSO2 Application server

We can export JAX-WS project as a web application (war) file and deploy it on WSO2 Appliation server via web console
To create a deployable archive (WAR) and deploy on WSO2 Application server
  1. Right-click on project, 
  2. Select Export Project as Deployable Archive
  3. Then choose destination location.
  4. log into WSO2 Application server
  5. In the navigator, under Manage/JAX-WS/JAX-RS, click Add .
  6. Click Browse to locate the file you want to upload. If you want to add multiple JAX-WS/JAX-RS apps at the same time, click on the '+' sign at the right side, and new additional entry to upload a JAX-WS/JAX-RS archive will appear each time you click. So you can select all the archives you want and deploy them at the same time.
  7. Click Upload. The Running JAX-WS/JAX-RS Applications page appears. Subsequently, if the deployment is successful, it will appear in the list. If the application is faulty, a Faulty JAX-WS/JAX-RS Application link will appear. You can click the link to view the errors
We can add it as dependency of Carbon Application project which can deploy on WSO2 Application Server. 

To do this,
  1. Select File->New->Project...
  2. Select "Carbon Application Project" under WSO2 category
  3. Named the project as "CappProject" and select "AccountServiceProject" under dependencies and click Finish.  
  4. Go to Servers view, Right-click on the blank space -> New-> Server
  5. Select WSO2 Carbon 4.0 based server under WSO2 category
  6. Provide name for server name (e.g. WSO2 Application Server 4.5) and click next
  7. You will need to specify location of the WSO2 Application Server instance and click next. 
  8. In Next window, you can change configuration setting for server instance such as Carbon server port, server offset, etc.. You can change ports if you want. If the default ports are not used by any other application, you can keep them as they are. After setting the ports click  next. 
  9. In Next window, You will able to view available carbon application project in left panel, select   "CappProject" and click Add, then click finish 

Testing the Web Service

we can test our web service using WSO2 Application server's web console

log into WSO2 Application server console, In the navigator, under Manage/JAX-WS/JAX-RS, click List. The Running JAX-WS/JAX-RS Applications page appears.

Click on "Find Services", It will list all SOAP and RESTful services deployed through our web service project

We can copy WSDL's of the services  (e.g. and try those services using the external Try-It tool which can be found under Tools/Try-It menu of WSO2 Application server.

we can try out "createAccount" method, it will return the account number of newly created account.

Consuming the Web Service

To consume our web service, we need to create web service client. CXF provides us with many options to build clients for our services. you can use CXF wsdl2java tool to generate web service client stubs. Make sure you installed and configured the Apache CXF runtime environment in your system and CXF Tools available in your system path.

wsdl2java -client <wsdl-path>

wsdl2java -client

You will need to endorse the JAX-WS API 2.2 jar, otherwise run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1 compliant code instead.

wsdl2java tool  generates all of the code needed to consume our web service including sample client with main(), would look like this (AccountService_AccountServicePort_Client)

package org.example.webservice;

 * Please modify this class to meet your needs
 * This class is not complete

import javax.xml.namespace.QName;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;

 * This class was generated by Apache CXF 2.5.2
 * 2012-06-12T17:33:20.094+05:30
 * Generated source version: 2.5.2
public final class AccountService_AccountServicePort_Client {

    private static final QName SERVICE_NAME = new QName("", "AccountServiceService");

    private AccountService_AccountServicePort_Client() {

    public static void main(String args[]) throws java.lang.Exception {
        URL wsdlURL = AccountServiceService.WSDL_LOCATION;
        if (args.length > 0 && args[0] != null && !"".equals(args[0])) { 
            File wsdlFile = new File(args[0]);
            try {
                if (wsdlFile.exists()) {
                    wsdlURL = wsdlFile.toURI().toURL();
                } else {
                    wsdlURL = new URL(args[0]);
            } catch (MalformedURLException e) {
        AccountServiceService ss = new AccountServiceService(wsdlURL, SERVICE_NAME);
        AccountService port = ss.getAccountServicePort();  
        System.out.println("Invoking debitAccount...");
        int _debitAccount_arg0 = 0;
        int _debitAccount_arg1 = 0;
        boolean _debitAccount__return = port.debitAccount(_debitAccount_arg0, _debitAccount_arg1);
        System.out.println("debitAccount.result=" + _debitAccount__return);

        System.out.println("Invoking checkAccount...");
        int _checkAccount_arg0 = 0;
        boolean _checkAccount__return = port.checkAccount(_checkAccount_arg0);
        System.out.println("checkAccount.result=" + _checkAccount__return);

        System.out.println("Invoking creditAccount...");
        int _creditAccount_arg0 = 0;
        int _creditAccount_arg1 = 0;
        boolean _creditAccount__return = port.creditAccount(_creditAccount_arg0, _creditAccount_arg1);
        System.out.println("creditAccount.result=" + _creditAccount__return);

        System.out.println("Invoking createAccount...");
        boolean _createAccount_arg0 = false;
        int _createAccount__return = port.createAccount(_createAccount_arg0);
        System.out.println("createAccount.result=" + _createAccount__return);

        System.out.println("Invoking checkAccountBalance...");
        int _checkAccountBalance_arg0 = 0;
        int _checkAccountBalance__return = port.checkAccountBalance(_checkAccountBalance_arg0);
        System.out.println("checkAccountBalance.result=" + _checkAccountBalance__return);



We modify this class to meet our requirements as below
package org.example.webservice;

import javax.xml.namespace.QName;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;

public final class AccountService_AccountServicePort_Client {

 private static final QName SERVICE_NAME = new QName(
   "", "AccountServiceService");

 private AccountService_AccountServicePort_Client() {

 public static void main(String args[]) throws java.lang.Exception {
  URL wsdlURL = AccountServiceService.WSDL_LOCATION;
  if (args.length > 0 && args[0] != null && !"".equals(args[0])) {
   File wsdlFile = new File(args[0]);
   try {
    if (wsdlFile.exists()) {
     wsdlURL = wsdlFile.toURI().toURL();
    } else {
     wsdlURL = new URL(args[0]);
   } catch (MalformedURLException e) {

  AccountServiceService ss = new AccountServiceService(wsdlURL,
  AccountService port = ss.getAccountServicePort();
  int accountNo = 0;
  int accountBalance = 0;

  // Invoke the create account service.
  boolean printOnConsole = false; // print details on server's console
  accountNo = port.createAccount(printOnConsole);
    "Account Created Under Account Number :%d", accountNo));

  // Invoke the check account service
  System.out.println("Verifying Account Existence......");
  System.out.println("Account Existence Verifyied : "
    + port.checkAccount(accountNo));

  // Invoke the credit account service.
  boolean creditAccountResponse = port.creditAccount(accountNo, 20000);
  System.out.println("Account Credited by US$ 20000 : "
    + creditAccountResponse);

  // Invoke the check account balance service.
  accountBalance = port.checkAccountBalance(accountNo);
  System.out.println(String.format("Current Account Balance (US$): %d",

  // Invoke the debit account service.
  boolean debitAccountResponse = port.debitAccount(accountNo, 8000);
  System.out.println("Account Debited by  US$ 8000 : "
    + debitAccountResponse);

  // Invoke the check account balance service.
  accountBalance = port.checkAccountBalance(accountNo);
  System.out.println(String.format("Current Account Balance (US$): %d",



output of client program would look like this

Sunday, December 25, 2011

How to register an eclipse editor by file content

Sometimes you may want to register an eclipse editor by reading file content. As an example if we need to open Maven POM file with specificity packing type with your editor or if you need to use different files without file extension, so we have to write a custom ContentDescriber to handle it. 

We can write custom ContentDescriber by extending or implementing following classes/ interfaces.

So let's write a custom ContentDescriber by extending XMLContentDescriber


import org.eclipse.core.runtime.content.IContentDescription;
import org.eclipse.core.runtime.content.XMLContentDescriber;

public class MyDescriber extends XMLContentDescriber {

 public int describe(InputStream input, IContentDescription description)
   throws IOException {
   /** Implement logics to validate content by reading input stream  
    *  if success, return VALID;   
  return INVALID;

let's modify plugin.xml to register custom ContentDescriber
            name="My Editor">
   <extension point="org.eclipse.core.contenttype.contentTypes">
  <content-type base-type="org.eclipse.core.runtime.xml"
   name="My File" priority="high">