Friday, December 11, 2015

How to Use Facebook Connector with WSO2 ESB

The Facebook connector allows you to access the exposed Facebook Graph API from WSO2 ESB. Facebook is an online social networking website that allows registered users to create profiles, upload photos and videos, send messages, and keep in touch with their family, friends, and colleagues. The Graph API is the primary way to get data back and forth, from and to Facebook's social graph [1]
You can download the latest facebook connector from the store[2]

Prerequisite
  • Facebook Connector
  • WSO2 ESB 4.9.0  
  • Facebook App
You also need to enable following MessageFormatter and MessageBuilder in the axis2.xml file in the $ESB_Home/repository/conf/axis2
 <messageFormatter contentType="multipart/form-data"  
             class="org.wso2.carbon.relay.ExpandingMessageFormatter"/>  
 <messageBuilder contentType="multipart/form-data"  
             class="org.wso2.carbon.relay.BinaryRelayBuilder"/>  
By default these setting are commented on the axis2.xml file. You have to un-comment those 2.

Add Connector to WSO2 ESB
In order to install the connector to the ESB, you can go to the ESB management console page and click Add in the Connector section of the Manage menu. There you can select the facebook connector zip while which you have already downloaded and upload it.
When you successfully upload the connector, it will be available in the connectors list as below

By default connector will be in Disable status. You need to click on the Disable button in order to enable the connector.


Now you can create a simple proxy to invoke the Facebook operations via the connector. For that you can use the sample proxies that I've attached here.

To add the proxies, go to Add Proxy Services in the ESB management console. Click custom proxy.
Click switch to source view and paste the facebook proxy. Follow same steps to create another proxy for multipart operations.

Sample Operations
Here I've list down some basic facebook operations that I've tried via the connector. I've used postman REST client to call the proxies.
  • Get access token
Sample request
 curl -X POST -H "Action: urn:getAppAccessToken" -H "Content-Type: application/json" -H "Cache-Control: no-cache" -H "Postman-Token: 6f8c38a8-66e0-83d6-4641-1a33473e97d9" -d '{  
 "apiUrl":"https://graph.facebook.com",  
 "apiVersion":"v2.5",  
 "clientId":"<YOUR_CLIENT_ID>",  
 "clientSecret":"<YOUR_CLIENT_SECRET>"  
 }' 'http://localhost:8280/services/facebook'  

Sample Response
 {  
  "access_token": "940843329284937|8VL4m0zH8r0TP9lE5mB6IVlXIEY"  // This is the access token
 }  
  • Post a message to a Facebook Page
Sample Request
 curl -X POST -H "Action: urn:publishPagePost" -H "Content-Type: application/json" -H "Cache-Control: no-cache" -H "Postman-Token: 85eacc74-b6af-9171-96d0-d563ec078fb6" -d '{  
 "apiUrl":"https://graph.facebook.com",  
 "accessToken":"<YOUR_ACCESS_TOKEN>",  
 "pageId":"562960547187253",  
 "message":"This is a test message"  
 }' 'http://10.100.7.26:8280/services/facebook'  

Sample Response
 {  
  "id": "562960547187253_564344377048870"  // This is the post id
 }  

  • Post photo to a facebook page
There are 2 ways to post a photo to the facebook page. Either you can use an online photo or upload a photo.

Upload a Photo
Sample Request
 curl -X POST -H "Action: urn:addPhotoToPage" -H "Cache-Control: no-cache" 
-H "Postman-Token: 252bcb70-1459-4c36-88cd-eb0db33892ba" 
-H "Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" -F "source=@iumage.png" 'http://10.100.7.26:8280/services/multipart?apiUrl=https://graph.facebook.com&accessToken=<YOUR_ACCESS_TOKEN>&pageId=<PAGE_ID>&apiVersion=v2.5&caption=This is a sample uploaded photo'  
Sample Response
 {  
  "id": "114619305575881",  
  "post_id": "562960547187253_114619305575881"  
 }  

Use a online photo. Here we use photoUrl parameter to specify the online image url
Sample Request
 curl -X POST -H "Action: urn:addPhotoToPage" 
-H "Cache-Control: no-cache" 
-H "Postman-Token: 11e136d7-5f4d-102c-1520-d833ddb916f8" 
'http://10.100.7.26:8280/services/multipart?apiUrl=https://graph.facebook.com&accessToken=<ACCESS_TOKEN>&pageId=<PAGE_ID>&apiVersion=v2.5&caption=This is a sample uploaded photo&photoUrl=http://www.sweethome3d.com/blog/common/images/feed-icon-10x10.png'  


  • Post Video to a facebook page
Here again you have 2 options. Either you can use an online video or upload an local video.

Upload a video
Sample Request
 curl -X POST -H "Action: urn:addPageVideo" -H "Cache-Control: no-cache" 
-H "Postman-Token: e06bd9dd-48b3-6ada-99ac-2d4daf5dd46c" 
-H "Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" -F "source=@SampleVideo_1080x720_1mb.mp4" 'http://10.100.7.26:8280/services/multipart?apiUrl=https://graph.facebook.com&accessToken=<ACCESS_TOKEN>&pageId=<PAGE_ID>&apiVersion=v2.5&contentCategory=<CATEGORY>&title="Test video for upload"'  

Sample Response
{ "id": "114619305575881", }

Use Online Video to upload to page. Here we use fileUrl parameter to specify the online image url
 curl -X POST -H "Action: urn:addPageVideo" -H "Cache-Control: no-cache" 
-H "Postman-Token: 109e80dc-8b1a-049f-9c97-94277dd6beb6" 
'http://10.100.7.26:8280/services/multipart?apiUrl=https://graph.facebook.com&accessToken=<ACCESS_TOKEN>&pageId=<PAGE_ID&apiVersion=v2.5&contentCategory=<CATEGORY>&title="Test video for upload"&fileUrl=https://d3ldtt2c6t0t08.cloudfront.net/files/rhn4phpt3rh4u/2015/06/17/Z7EO2GVADLFBG6WVMKSD5IBOFI/main_OUTPUT.tmp.mp4'  


  • Get Likes of a Post
Sample Request
 curl -X POST -H "Action: urn:getLikes" -H "Content-Type: application/json" -H "Cache-Control: no-cache" -H "Postman-Token: 9770f6e5-de0f-c85e-097b-ebfac40765ed" -d '{  
 "apiUrl":"https://graph.facebook.com",  
 "apiVersion":"v2.5",  
 "accessToken":"<ACCESS_TOKEN>",  
 "resourceId":"<POST_ID>"  
 }' 'http://10.100.7.26:8280/services/facebook'  


  • Get Comments of a Post
 curl -X POST -H "Action: urn:getComments" -H "Content-Type: application/json" -H "Cache-Control: no-cache" -H "Postman-Token: f35f9ff4-b5cc-11a9-fea2-ba77ef2fd37e" -d '{  
 "apiUrl":"https://graph.facebook.com",  
 "apiVersion":"v2.5",  
 "accessToken":"<ACCESS_TOKEN>",  
 "objectId":"<POST_ID>"  
 }' 'http://10.100.7.26:8280/services/facebook'  

Facebook allow you to pass summary=true parameter to get the summary of the particular post. To use this feature you need to manually edit the connector and append the parameter to the request.

Edited facebook connector can be found at https://drive.google.com/open?id=0B-jZl7AY9hiiMTZWVVRSa0pIZFk
If you like to manually edit you can do the following.

  1. Download the Original connector from the wso2 store
  2. Unzip the connector
  3. Open facebook-likes/getLikes.xml file. Add following code segment before the <call> tag in the file

 <script language="js">  
       <![CDATA[  
       var params = mc.getPayloadJSON().summary;  
       if (params != null && params.toString().toLowerCase() === "true")  
       {  
         params = "true";  
       }  
       else  
       {  
         params = "false";  
       }  
       mc.setProperty('uri.var.summary', params);  
       ]]>  
     </script>  
and append &amp;summary={uri.var.summary} to the end of the uri-template value

You can follow the same steps to enable summary for comments as well. You need to do the same modifications in the facebook-comments/getComments.xml  file.
After the modifications, zip the connector again and redeploy the connector. You need to remove the connector first and then redeploy the new connector.

Then you can append summary=true parameter to getLikes and getCommnets functionalities and it will return response like below
 {  
  "data": [  
   {  
    "id": "108057549565823"  
   }  
  ],  
  "paging": {  
   "cursors": {  
    "after": "MTA4MDU3NTQ5NTY1ODIz",  
    "before": "MTA4MDU3NTQ5NTY1ODIz"  
   }  
  },  
  "summary": {  
   "total_count": 1,  
   "can_like": true,  
   "has_liked": false  
  }  
 }  
Note - In order to post messages you need to have publish_action and publish_pages permissions. You can assign these permission to the particular user through the facebook. Here I've used a test user which can be easily create by the facebook.

[1] - https://docs.wso2.com/display/ESBCONNECTORS/Facebook+Connector
[2] - https://storepreview.wso2.com/store/assets/esbconnector/b615c2a4-a4a6-48f0-bbb2-c516af0cdd37

Tuesday, December 1, 2015

Using Carbon Metrics with WSO2 Products

"WSO2 Carbon Metrics" provides an API for WSO2 Carbon Components to use Metrics library[1]
This has been pre installed in some of the latest wso2 products such as WSO2 MB 3.0.0, WSO2 ML and WSO2 DAS 3.0.0. Those products also extends the carbon-metrics and implemented added some new features to those products.
If you like you can install and try the carbon metrics in most of the WSO2 products. I've installed it with WSO2 ESB 4.9.0, WSO2 DSS 3.5.0, WSO2 AS 5.3.0 and WSO2 IS 5.0.0

You can easily install the feature through the ui. To install the carbon-metric feature in the product you can follow the below steps
  1. Use [2] to add features through the UI and use Wilkes repository [3]
  2. After adding the repository, deselect Group features by category and click Find features
  3. From the feature list select Metrics Group and install.
  4. Restart the product when the installation complete.
When the feature successfully installed you will see a Metrics menu item in the configuration menu. When you go to that item you will see as follows

At the moment current implementation doesn't supports multi tenancy or RBAC. Feature can be only use with super tenant and super tenant admin.

These information are stored in a H2 database. You can configure the datasource metrics-datasources.xml. Even you can use the same database for all the products. To do so you have to use the same datasource in the $Produc_Home/repository/conf/datasource/metrics-datasources.xml

By default carbon metric uses hostname as the source. Therefore if you are using same database for all the products you can un-comment the 
<Source>Carbon</Source> under JDBC section in the $Product_Home/repository/conf/metrics.xml and change source for each product

 <JDBC>  
       <Enabled>true</Enabled>  
       <!-- Source of Metrics, which will be used to  
         identify each metric in database -->  
       <!-- Commented to use the hostname  
         <Source>Carbon</Source>  
       -->  
       <!--  
         JNDI name of the data source to be used by the JDBC Reporter.  
         This data source should be defined in a *-datasources.xml  
         file in conf/datasources directory.  
       -->  
e.g. for esb <Source>WSO2ESB</Source>, for DSS <Source>WSO2DSS</Source>
 <JDBC>  
       <Enabled>true</Enabled>  
       <!-- Source of Metrics, which will be used to  
         identify each metric in database -->  
       <Source>WSO2ESB</Source>  
       <!--  
         JNDI name of the data source to be used by the JDBC Reporter.  
         This data source should be defined in a *-datasources.xml  
         file in conf/datasources directory.  
       -->  

[1] - https://github.com/wso2/carbon-metrics

Friday, November 20, 2015

Prgrammatically Control WSO2 Registry Resources' Permission

  1. Open $EMM_Home/repository/conf/cartbon.xml and change the value of HideAdminServiceWSDLs to false
  2. Start the WSO2 EMM
  3. You can check the ResourceAdminService wsdl file by browsing https://<host>:9443/services/ResourceAdminService?wsdl
  4. Create a new soap project in the SoapUI using the ResourceAdminService.wsdl
  5. Send a changeRolePermissions request. Sample Soap request will be looks as follows
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.resource.registry.carbon.wso2.org">
       <soapenv:Header/>
       <soapenv:Body>
          <ser:changeRolePermissions>
             <ser:resourcePath>/_system/governance/mobileapps/admin/android/TestApp</ser:resourcePath>
            <ser:permissionsInput>internal/everyone:ra^true:wa^true:da^true:aa^true|internal/private_admin:ra^true</ser:permissionsInput>
          </ser:changeRolePermissions>
       </soapenv:Body>
    </soapenv:Envelope>
    
In the request
  • resourcePath should be the registry resource that you want to manipulate
  • permissionsInput must be in following format
    roleName:<permission_id>^true:<permission_id>^true:...:<permission_id>^true|roleName2:<permission_id>^true:<permission_id>^true|roleName3:<permission_id>^true
    
Permission can be as follows
PermissionPermission ID
Allow Readra
Deny Readrd
Allow Writewa
Deny Writewd
Allow Deleteda
Deny Deletedd
Allow Authorizeaa
Deny Authorizead
For example
internal/everyone:ra^true:wa^true:da^true:aa^true|internal/private_admin:ra^true:wd^true:dd^true:ad^true
This will allow read/write/delete/authorize permissions to the internal/everyone role and only read permission to internal/private_admin. Write/Delete/Authorize permissions of the internal/private_admin will be set to deny.
Note that if you don't specifically set all 4 permission, then the missing permission will be reset.
You can create a simple client using the ResourceAdminService wsdl and programmatically manipulate the permission.

Friday, November 6, 2015

WSO2 Carbon Extension Points - Tomcat Extensions

Valves

A Valve element represents a component that will be inserted into the request processing pipeline for the associated Catalina container (Engine, Host, or Context). Individual Valves have distinct processing capabilities. Simply a valves provide a way of inserting custom functionality within the Tomcat request/response stream.
In WSO2 products users can either extend Tomcat generic org.apache.catalina.valve.ValveBase abstract class or carbon specific org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve in order to create a custom valve.
You can refer to Tomcat Valve documentation  for further info regarding the Tomcat specific valve implementation https://tomcat.apache.org/tomcat-7.0-doc/config/valve.html

Sample Valve

 public class CarbonSimpleValve extends ValveBase {  
   public CarbonSimpleValve() {  
     //enable async support  
     super(true);  
   }  
   @Override  
   public void invoke(Request request, Response response) throws IOException, ServletException {  
     //valve specific logic    
   }  
 }  

You can refer to the following valves in the carbon kernel to get a better idea


If you extend CarbonTomcatValve and implement your own Valve you need to add that to the Valve pipe using the TomcatValveContainer. You can refer to how the GhostWebappValve and TenantLazyLoaderValve added in the WebappManagementServiceComponent

If you extend the ValveBase then the valve need to be added to the Engine, Host or to the Context.
e.g. Adding a Host level valve in the $PRODUCT_HOME/repository/conf/tomcat/catalina-server.xml
 <Server>  
  <Service>  
    <Engine>  
     <Host>  
       …..  
       <Valve className="org.wso2.carbon.sample.CarbonSimpleValve"/>  
       …..  
     </Host>  
    </Engine>  
  </Service>  
 </Server>  

Filters

A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both. Filters perform filtering in the doFilter method. Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, a reference to the ServletContext.

Sample Filter

 public class MyFilter implements Filter {  
  public void init(FilterConfig filterConfig) throws ServletException {  
  }  
  public void destroy() {  
  }  
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)  
   throws IOException, ServletException {  
  servletResponse.setContentType("text/html");  
  //Pre filter logic  
  filterChain.doFilter(servletRequest, servletResponse);  
                //post filter logic  
  }  
 }  

This filter can be defined in the web.xml in order to use this. e,g. in the $Product_Home/repository/conf/tomcat/web.xml for product wide filter or you can use the web.xml in your application.

 <?xml version="1.0" encoding="ISO-8859-1"?>  
 <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  <filter>  
  <filter-name>MyFilter</filter-name>  
  <filter-class>MyFilter</filter-class>  
  <init-param>  
   <param-name>my-param</param-name>  
   <param-value>my-param-value</param-value>  
  </init-param>  
  </filter>  
  <filter-mapping>  
  <filter-name>MyFilter</filter-name>  
  <url-pattern>/*</url-pattern>  
  </filter-mapping>  
 </web-app>  

You can refer to following filters in the carbon kernel for more implementation details.

  • org.wso2.carbon.ui.filters.CSRFPreventionFilter
  • org.wso2.carbon.ui.filters.CRLFPreventionFilter
  • org.wso2.carbon.tomcat.ext.filter.CharacterSetFilter

Tuesday, November 3, 2015

WSO2 Carbon Kernel 5.0.0 - Alpha Released

WSO2 Carbon Kernel 5.0.0 - Alpha Released !

We are pleased to announce the alpha release of WSO2 Carbon Kernel 5.0.0. It is now available to download from here. The source and tag location for this release are available here.

WSO2 Carbon Kernel 5.0.0 is the core of the next-generation WSO2 Carbon platform. We have completely rearchitected Carbon Kernel from the ground up with the latest technologies and patterns. Additionally, the Carbon Kernel is now a lightweight, general-purpose OSGi runtime specializing in hosting servers, providing key functionality for server developers. The result is a streamlined and even more powerful middleware platform than ever before.

The alpha release of the WSO2 Carbon Kernel 5.0.0 includes the following key features. For further details please see the documentation.

Key Features
  • Transport Management Framework
  • Logging Framework with Log4j 2.0 as the Backend
  • Carbon Startup Order Resolver
  • Dropins Support for OSGi Ready Bundles
  • Jar to Bundle Conversion Tool
  • Pluggable Runtime Support

      Fixed Issues

      How To Contribute

      You can find more instructions on how to contribute on our documentation site.
      If you have any suggestions or are interested in Carbon Kernel 5.0.0 discussions, you can join the dev@wso2.org or architecture@wso2.org mailing lists.

      Reporting Issues

      We encourage you to report issues, documentation errors regarding WSO2 Carbon Kernel 5.0.0 through the public issue tracking system.


      Thanks,
      WSO2 Carbon Team

      Saturday, August 8, 2015

      WSO2 Carbon Kernel 4.4.1 Released

      WSO2 Carbon team has released the Carbon kernel 4.4.1 . Following are the bug fixes and improvements included in the release.

      Improvements
      • [CARBON-15248 Make resource cache timeout configurable
      • [CARBON-15254 Improving SQL query used to retrieve resource properties

      Fixed Bugs
      • [CARBON-15146 [SSO for carbon servers] username is printed as null in logout logs
      • [CARBON-15251 Hazelcast coordinator issue after cluster partitioning
      • [CARBON-15257 Student-Manager Sample is broken in Carbon 4.4.0 release
      • [CARBON-15265 Dead-Lock occurred at cluster startup
      • [CARBON-15311 Upgrade Eclipse ECJ compiler version to 4.4.2
      • [CARBON-15313 Teants cannot login to Management console until the password is reset when connecting to Active Directory
      • [CARBON-15320 Add webapp-classloading.xml to carbon webapp
      • [CARBON-15203 Gson builder validates the order of input parameters in the JSON payload - DSS
      • [CARBON-15231 NPE when PayloadFactory mediator is used with json message type and chunking is disabled
      • [CARBON-15255 Make the cookie.setSecure(true) and cookie.setHttpOnly(true);
      • [CARBON-15262 [Cluster] - NPE when Invoke GET method for a REST service
      • [CARBON-15276 Upgrade Hazelcast version to 3.5
      • [CARBON-15290 When namespace empty in Part element generated wsdl namespace prefix contains null:
      • [CARBON-15304 Remove obsolete parameters in wso2server.sh
      • [CARBON-15301] Fix UM/Reg related Oracle RAC DB scripts
      • [CARBON-15280]    Service with GET resources returns fault String if it has url path params similar to the service name

      Known Issues

      How to Contribute 
      Contact Us

      WSO2 Carbon developers can be contacted via following mailing lists:

      You can download the released distribution from the following location.

      Monday, April 27, 2015

      Maven Shade Plugin to bundle all the SCIs

      We are having an Tomcat OSGi bundle which consist of following dependencies.
      <artifactId>tomcat-dbcp</artifactId>
      <artifactId>tomcat-embed-core</artifactId>
      <artifactId>tomcat-embed-jasper</artifactId>
      <artifactId>tomcat-embed-websocket</artifactId>
      Both tomcat-embed-jasper and tomcat-embed-websocket contains SCIs. I wanted to bundle these dependencies to a single OSGi bundle with all their SCIs. If we use maven-bundle plugin as follows

      Since all the SCIs use the same interface javax.servlet.ServletContainerInitializer, based on the order we specify the resource previous references get override and only the last resource SCI will get bundle.

      We can use maven-shade-plugin to overcome the issue. It has lot of other features as well. You can refer to the official documentation page for more details about shade-plugin
      Maven-shade-plugin

      If you wanna combine all the META-INF/services (like what I wanted to do) you can use following configuration

      Saturday, April 18, 2015

      Image Filtering with OpenCV

      Last year I wanted put my hands on JavaCV and play little bit with that. But with time I couldn't continue that. Few weeks back I again got that crazy feel "The Machine" :D So I wanna start it again. But this time with c++.

      Install OpenCV
      I found a nice post that describe step by step to install OpenCV on ubuntu. You can follow that tutorial and get OpenCV on your machine. (If you are on Windows then it is just installing the .exe)
      Installing OpenCV 3.0.0 on Ubuntu 14.04
      In the post he is using OpenCV 3.0 alpha version. But now beta version is also available. I'm using the Beta version here. Just download the beta release from the officail OpenCV website. http://opencv.org/downloads.html
      Then you can follow the same steps as mentioned.

      Image Filtering
      I'm not going to describe about what is image filtering or why we need that. You can find plenty of information about these topics if you really keen on. I'm just gonna show up the code that can be use to do Mode filtering and Median filtering.

      Median Filtering
      In Mode filtering what we do is simply break image into 3x3 segments and assign the median of those pixel values of each segment to the center pixel of the each segment.

      Mode Filtering
      In Mode filtering what we do is simply break image into 3x3 segments and assign the mode value of each segment to the center pixel of the each segment.

      Sunday, April 12, 2015

      How to Change WSO2 Carbon Version

      Few days ago I faced a problem where, when I trying to build the carbon-commons with Tomcat 8 supports though I changed the Tomcat version it is picking dependencies from previous Tomcat bundle. I tried clean repo, deleting local repo several times but couldn't get through this. When I changed the carbon kernel version and build the commons with that then problem get fixed.

      In order to change the carbon version
      1. Change version in all the pom.xml files in the Carbon-kernel. At the moment it is 4.4.0-SNAPSHOT. You can easily do this by a Replace All command in your IDE or if you are a terminal guy, you can use grep/find commands
      2. Then you must change the version in distribution/kernel/carbon.product file. It has version in 2 places. Changed both occurrences to your new version.

      Then can do the build without any issues. 

      Monday, March 2, 2015

      Embedding Tomcat inside Java Program

      Apache Tomcat is one of the most popular open source application servers that is been use today. What we usually do is run Tomcat server and deploy our webapps inside the Tomcat.
      But we also can embed Tomcat inside our java application and do all stuffs through our own program. This is just a simple example showing how to embed the tomcat, start the server and put a servlet inside that.

      I'm using Intellij Idea IDE. But you can use any IDE that you like. First create a new maven project and give an artifact id, group id and version that you like.
      We need to add following tomcat dependencies to the pom file.

      Finally pom file looks like
      Now create a Java file with following content

      Now run this class. When your program starts to run you will see some log entries getting on your console. If the sever get started successfully go to your web browser and type http://localhost:8888/
      You will see something like following image on browser.

      Friday, February 27, 2015

      Getting Started with SonarQube

      What is SonarQube?
      SonarQube is an open platform to manage code quality. It covers following aspects of a project
      1. Architecture and Design
      2. Duplication
      3. Unit Testing
      4. Complexity
      5. Potential Bugs
      6. Coding Rules
      7. Comments
      There are about 20 plugins available for SonarCube to analyze most of the common programming languages such as Java, C#, C++ etc..

      Analyzing a Project with SonarQube Runner
      Prerequisites
      • Java should be installed on your machine
      First go to the SonarQube official site and download the SonarQube and SonarQube Runner
      Extract both SonarQube and SonarQube runner to desired locations. In my machine I've extracted SonarQube to 
      /home/thusitha/Training/sonarqube-5.0
      and SonarQube Runner to
      /home/thusitha/Training/sonar-runner-2.4

      Inside the SonarQube you can find there are many directories for each platform. Find the matching platform based on your OS. 
      e.g.
      If you are using ubuntu x64 bit OS then you must go to linux-x86-64 directoty

      Go to the particular directory through the console and run the Sonar script to start the Sonar sever
      To start the server run the sonar script in the directory
      In Linux
      sh sonar.sh console

      In Windows
      StartSonar.bat

      Then open your browser and type following URL there. If Sonar server started successfully you will direct to Sonar dashboard.
      Sonar Dashboard http://localhost:9000/

      Now go to the project root folder that you want to analyze and create a file and name it as 
      sonar-project.properties and have following content to that file In the file you can provide details relate to your project.
      Then we can run SonarQube Runner to analyze the project using this file. To do that run the following command from the location where the created file resides.
      On Linux
      sonar-runner

      On Windows
      sonar-runner.bat


      After a successful execution you can see the project and its' status on the Sonar Dashboard. In the dashboard you can go through the issues etc...

      Tuesday, February 24, 2015

      Writing First WSO2 Carbon Component

      What is Carbon?
      WSO2 Carbon is the award-winning, component-based, service oriented platform for the enterprise-grade WSO2 middleware products stack. It is 100% open source and delivered under Apache License 2.0. The WSO2 Carbon platform is lean, high-performant and consists of a collection of OSGi bundles.  - WSO2
      Prerequisites
      • Java
      • Maven
      • IDE (eclipse/IdeaJ or any other IDE that supports maven project)
      • Internet connection
      • Any WSO2 Carbon product (I'm using WSO2 Application server. You can download any product that you like from WSO2 products page)
      Getting Started
      Here I'm going to create a simple order manager carbon component. This will consist of 3 modules.
      1. Back-end service
      2. Service stub
      3. Front-end (UI) 
      I'm using Intellij IdeaJ IDE in order to create the project but you can use any IDE that you prefer.

      Create a new maven project and give appropriate group ID and artifact ID. I'm using following group id and artifact id. These are very basic names. (Not based on standards naming conventions) You can use anything that you like.
       <groupId>org.wso2.carbon.sample</groupId>  
       <artifactId>ordar-manager</artifactId>  
      

      After creating the maven project you can delete the src folder if you like, because this will not contain any source code.
      After creating the main project we must add 3 modules to that project. Make sure you set the parent of each module as the main project that was created first. If you are using IdeaJ, select the main project and then select File -> New Module. It will correctly point to the parent project. You just have to give the artifact Id.
      In my project my modules are as follows

      Back end Service Module
       <parent>  
          <artifactId>ordar-manager</artifactId>  
          <groupId>org.wso2.carbon.sample</groupId>  
          <version>1.0-SNAPSHOT</version>  
       </parent>  
       <artifactId>backend</artifactId>  
      

      Service Stub
       <parent>  
          <artifactId>ordar-manager</artifactId>  
          <groupId>org.wso2.carbon.sample</groupId>  
          <version>1.0-SNAPSHOT</version>  
       </parent>  
       <artifactId>service-stub</artifactId>  
      

      Front end
       <parent>  
          <artifactId>ordar-manager</artifactId>  
          <groupId>org.wso2.carbon.sample</groupId>  
          <version>1.0-SNAPSHOT</version>  
       </parent>  
       <artifactId>frontend</artifactId>  
      

      After adding the 3 modules your pom file of the main project should be similar to
       <?xml version="1.0" encoding="UTF-8"?>  
       <project xmlns="http://maven.apache.org/POM/4.0.0"  
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
            xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
         <modelVersion>4.0.0</modelVersion>  
         <groupId>org.wso2.carbon.sample</groupId>  
         <artifactId>ordar-manager</artifactId>  
         <packaging>pom</packaging>  
         <version>1.0-SNAPSHOT</version>  
         <modules>  
           <module>Backend</module>  
           <module>ServiceStub</module>  
           <module>Frontend</module>  
         </modules>  
       </project>  
      

      1. Creating the Back-end Service
      My service class is OrderManager. I've created that inside the org.wso2.sample.carbon.order.manager package. This will have 2 service methods. One to add Items and other one is to retrieve the existing Items.

      Item class
       package org.wso2.sample.carbon.order.manager.beans;  
       
       import java.io.Serializable;  
         
       public class Item implements Serializable{  
         private int no;  
         private String name;  
         private float price;  
      
         public Item(int itemNo, String itemName, float itemPrice) {  
           this.no = itemNo;  
           this.name = itemName;  
           this.price = itemPrice;  
         }
        
         public Item(){}  
      
         public int getNo() {  
           return no;  
         }  
      
         public void setNo(int no) {  
           this.no = no;  
         }
        
         public String getName() {  
           return name;  
         }
        
         public void setName(String name) {  
           this.name = name;  
         }
        
         public float getPrice() { return price; }  
      
         public void setPrice(float price) {  
           this.price = price;  
         }  
       }  
      

      Note
      I have implement the Serializable interface, since I'm going to use Carbon registry to store the Items in the registry.
      Other thing to remember is if you overload the default constructor, You must explicitly define the default constructor, since you must adhere to the JavaBeans standards, which are use in underlying Axis2.

      OrderManager class
       package org.wso2.sample.carbon.order.manager;
      
      import org.wso2.carbon.context.CarbonContext;
      import org.wso2.carbon.context.RegistryType;
      import org.wso2.carbon.registry.api.Registry;
      import org.wso2.carbon.registry.api.RegistryException;
      import org.wso2.carbon.registry.api.Resource;
      import org.wso2.sample.carbon.order.manager.beans.Item;
      
      import java.io.*;
      import java.util.HashMap;
      import java.util.logging.Level;
      import java.util.logging.Logger;
      
      public class OrderManager {
          private static int orderID = 1;
          Registry registry = null;
          private static final String ORDER_PATH = "order_location";
      
          private static Logger logger = Logger.getLogger(OrderManager.class.getName());
      
          public OrderManager() {
              HashMap orders = new HashMap();
      
              orders.put(orderID++, new Item(1, "LG G3", 99900.00f));
              orders.put(orderID++, new Item(3, "Iphone 6", 102000.00f));
              orders.put(orderID++, new Item(3, "Sony Z3", 80000.00f));
              orders.put(orderID++, new Item(4, "Nexus 6", 112000.00f));
              orders.put(orderID++, new Item(5, "HTC M8", 88000.00f));
      
              registry = CarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.valueOf(RegistryType.LOCAL_REPOSITORY.toString()));
      
              try {
                  Resource orderRes = registry.newResource();
                  orderRes.setContent(serialize(orders));
                  registry.put(ORDER_PATH, orderRes);
              } catch (RegistryException e) {
                  logger.log(Level.SEVERE, e.getMessage());
              } catch (IOException e) {
                  logger.log(Level.SEVERE, e.getMessage());
              }
          }
      
          public Item[] getOrders() {
              Resource orderRes = null;
              try {
                  orderRes = registry.get(ORDER_PATH);
                  if (orderRes != null) {
                      HashMap tmp = (HashMap) deserialize((byte[]) orderRes.getContent());
                      return tmp.values().toArray(new Item[tmp.values().size()]);
                  }
              } catch (IOException e) {
                  logger.log(Level.SEVERE, e.getMessage());
              } catch (ClassNotFoundException e) {
                  logger.log(Level.SEVERE, e.getMessage());
              } catch (RegistryException e) {
                  logger.log(Level.SEVERE, e.getMessage());
              }
              return new Item[]{};
          }
      
          public void addOrder(Item item) {
              Resource orderRes = null;
              try {
                  orderRes = registry.get(ORDER_PATH);
                  if (orderRes != null) {
                      HashMap tmp = (HashMap) deserialize((byte[]) orderRes.getContent());
                      tmp.put(orderID++, item);
                      orderRes.setContent(serialize(tmp));
                      registry.put("orders_location", orderRes);
                  }
              } catch (RegistryException e) {
                  logger.log(Level.SEVERE, e.getMessage());
              } catch (ClassNotFoundException e) {
                  logger.log(Level.SEVERE, e.getMessage());
              } catch (IOException e) {
                  logger.log(Level.SEVERE, e.getMessage());
              }
          }
      
          private static byte[] serialize(Object obj) throws IOException {
              ByteArrayOutputStream b = new ByteArrayOutputStream();
              ObjectOutputStream o = new ObjectOutputStream(b);
              o.writeObject(obj);
              return b.toByteArray();
          }
      
          private static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
              ByteArrayInputStream b = new ByteArrayInputStream(bytes);
              ObjectInputStream o = new ObjectInputStream(b);
              return o.readObject();
          }
      }
       
      

      Since we are using Carbon registry following dependencies should be added to the back-end module.
       <dependencies>  
           <dependency>  
             <groupId>org.wso2.carbon</groupId>  
             <artifactId>org.wso2.carbon.registry.core</artifactId>  
             <version>4.2.0</version>  
           </dependency>  
           <dependency>  
             <groupId>org.wso2.carbon</groupId>  
             <artifactId>org.wso2.carbon.registry.api</artifactId>  
             <version>4.2.0</version>  
           </dependency>  
       </dependencies>  
      
      Remember to use byte arrays when you are storing the values in the Carbon registry.

      Now we should write the service configuration (services.xml) for our service.
      Create a folder called META-INF inside the resource folder of the back-end module. Inside the META-INF folder create services.xml file with following content. Change the service and service class names according to your project.

      services.xml
       <serviceGroup>  
         <service name="OrderManager" scope="transportsession">  
           <transports>  
             <transport>https</transport>  
           </transports>  
           <parameter name="ServiceClass">org.wso2.sample.carbon.order.manager.OrderManager</parameter>  
         </service>  
         <parameter name="adminService" locked="true">true</parameter>  
         <parameter name="hiddenService" locked="true">true</parameter>  
         <parameter name="AuthorizationAction" locked="true">/permission/protected/manage</parameter>  
       </serviceGroup>  
      

      Now we must package the back-end module as a OSGI bundle. We are using maven-bundle-plugin to do that. We should also mentioned what are the packages that we are exporting from this module.
      After adding the dependency and the plugin, pom file of the back-end module will be similar to following pom.
       <?xml version="1.0" encoding="UTF-8"?>  
       <project xmlns="http://maven.apache.org/POM/4.0.0"  
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
            xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
         <parent>  
           <artifactId>ordar-manager</artifactId>  
           <groupId>org.wso2.carbon.sample</groupId>  
           <version>1.0-SNAPSHOT</version>  
         </parent>  
         <modelVersion>4.0.0</modelVersion>  
         
         <artifactId>backend</artifactId>  
         <packaging>bundle</packaging>  
         
         <dependencies>  
           <dependency>  
             <groupId>org.wso2.carbon</groupId>  
             <artifactId>org.wso2.carbon.registry.core</artifactId>  
             <version>4.2.0</version>  
           </dependency>  
           <dependency>  
             <groupId>org.wso2.carbon</groupId>  
             <artifactId>org.wso2.carbon.registry.api</artifactId>  
             <version>4.2.0</version>  
           </dependency>  
         </dependencies>  
         
         <build>  
           <plugins>  
             <plugin>  
               <groupId>org.apache.felix</groupId>  
               <artifactId>maven-bundle-plugin</artifactId>  
               <extensions>true</extensions>  
               <configuration>  
                 <instructions>  
                   <Bundle-SymbolicName>${pom.artifactId}</Bundle-SymbolicName>  
                   <Bundle-Name>${pom.artifactId}</Bundle-Name>  
                   <Export-Package>org.wso2.sample.carbon.order.manager.*</Export-Package>  
                 </instructions>  
               </configuration>  
             </plugin>  
           </plugins>  
         </build>  
       </project>  
      

      Now go to the back-end module pom file location from the terminal and use mvn clean install to build the module. If the build get success you will get a jar file like backend-1.0-SNAPSHOT.jar inside the target directory.
      Then copy the created jar file to repository/components/dropins directory in the WSO2 product that you are using. Since I'm using WSO2 AS full path is like /home/thusitha/WSO2/wso2as-5.2.1/repository/components/dropins

      We can't see the WSDL file of the created service directly accessing the https://localhost:9443/services/OrderManager?wsdl . That is because we have added this as a admin service and by default admin services WSDLs are hidden. In order to view the WSDL file open the carbon.xml file in the repository/conf and set the value of HideAdminServiceWSDLs as false
       <HideAdminServiceWSDLs>false</HideAdminServiceWSDLs>  
      

      Now start the WSO2 AS and put the above URL in the browser (last part should be the Service name that you provide in the services.xml). Save the WSDL file in the disk. I'm saving it inside the resource folder of the service-stub module.
      (If you want to check whether your service works as you expected, you can use SOAP UI like a tool. It is easy to comment out AutorizationAction in the services.xml if you do so)

      2. Creating the Service-stub
      We are using wsdl2java utility to create the stub. Other than that axiom, axis2, maven-antrun-plugin, build-helper-maven-plugin and maven-bundle-plugin are used.
      Use following repository in the pom file of service-stub module.
       <repository>  
             <id>wso2-nexus</id>  
             <name>WSO2 internal Repository</name>  
             <url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>  
             <releases>  
               <enabled>true</enabled>  
               <updatePolicy>daily</updatePolicy>  
               <checksumPolicy>ignore</checksumPolicy>  
             </releases>  
       </repository>  
      

      At the end pom file of the service-stub module should be look like

       <?xml version="1.0" encoding="UTF-8"?>  
       <project xmlns="http://maven.apache.org/POM/4.0.0"  
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
            xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
         <parent>  
           <artifactId>ordar-manager</artifactId>  
           <groupId>org.wso2.carbon.sample</groupId>  
           <version>1.0-SNAPSHOT</version>  
         </parent>  
         <modelVersion>4.0.0</modelVersion>  
         <packaging>bundle</packaging>  
         <artifactId>service-stub</artifactId>  
      
         <repositories>  
           <repository>  
             <id>wso2-nexus</id>  
             <name>WSO2 internal Repository</name>  
             <url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>  
             <releases>  
               <enabled>true</enabled>  
               <updatePolicy>daily</updatePolicy>  
               <checksumPolicy>ignore</checksumPolicy>  
             </releases>  
           </repository>  
         </repositories>  
      
         <dependencies>  
           <dependency>  
             <groupId>org.apache.axis2.wso2</groupId>  
             <artifactId>axis2</artifactId>  
             <version>1.6.1.wso2v10</version>  
           </dependency>  
           <dependency>  
             <groupId>org.apache.axis2.wso2</groupId>  
             <artifactId>axis2-client</artifactId>  
             <version>1.6.1.wso2v10</version>  
           </dependency> 
           <dependency>  
             <groupId>org.apache.ws.commons.axiom.wso2</groupId>  
             <artifactId>axiom</artifactId>  
             <version>1.2.11.wso2v4</version>  
           </dependency>  
           <dependency>  
             <groupId>wsdl4j.wso2</groupId>  
             <artifactId>wsdl4j</artifactId>  
             <version>1.6.2.wso2v4</version>  
           </dependency>  
         </dependencies>  
      
         <build>  
           <plugins>  
             <plugin>  
               <groupId>org.apache.maven.plugins</groupId>  
               <artifactId>maven-antrun-plugin</artifactId>  
               <version>1.1</version>  
               <executions>  
                 <execution>  
                   <id>source-code-generation</id>  
                   <phase>process-resources</phase>  
                   <goals>  
                     <goal>run</goal>  
                   </goals>  
                   <configuration>  
                     <tasks>  
                       <path id="wsdl2java.classpath">  
                         <pathelement location="${settings.localRepository}/org/apache/ws/commons/axiom/wso2/axiom/1.2.11.wso2v4/axiom-1.2.11.wso2v4.jar"/>  
                         <pathelement location="${settings.localRepository}/org/apache/axis2/wso2/axis2-client/1.6.1.wso2v10/axis2-client-1.6.1.wso2v10.jar" />  
                         <pathelement location="${settings.localRepository}/org/apache/axis2/wso2/axis2/1.6.1.wso2v10/axis2-1.6.1.wso2v10.jar" />  
                       </path>  
                       <java classname="org.apache.axis2.wsdl.WSDL2Java" fork="true">  
                         <classpath refid="wsdl2java.classpath" />  
                         <arg line="-uri src/main/resources/OrderManager.wsdl -u -uw  
                          -o target/generated-code -p org.wso2.sample.carbon.order.manager.stub"/>  
                       </java>  
                     </tasks>  
                   </configuration>  
                 </execution>  
               </executions>  
             </plugin>  
             <plugin>  
               <groupId>org.codehaus.mojo</groupId>  
               <artifactId>build-helper-maven-plugin</artifactId>  
               <executions>  
                 <execution>  
                   <id>add-source</id>  
                   <phase>generate-sources</phase>  
                   <goals>  
                     <goal>add-source</goal>  
                   </goals>  
                   <configuration>  
                     <sources>  
                       <source>target/generated-code/src</source>  
                     </sources>  
                   </configuration>  
                 </execution>  
               </executions>  
             </plugin>  
             <plugin>  
               <groupId>org.apache.felix</groupId>  
               <artifactId>maven-bundle-plugin</artifactId>  
               <extensions>true</extensions>  
               <configuration>  
                 <instructions>  
                   <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>  
                   <Bundle-Name>${project.artifactId}</Bundle-Name>  
                   <Private-Package>  
                   </Private-Package>  
                   <Export-Package>  
                     org.wso2.sample.carbon.order.manager.*  
                   </Export-Package>  
                   <Import-Package>  
                     !org.wso2.sample.carbon.order.manager.*  
                   </Import-Package>  
                   <DynamicImport-Package>*</DynamicImport-Package>  
                 </instructions>  
               </configuration>  
             </plugin>  
           </plugins>  
         </build>  
       </project>  
      
      In the above pom file you can see that I've used the previously saved WSDL file. Do the necessary modifications to the pom file according to the your project.
      Go to pom file location of the service-stub and do a maven clean build. If you check the target folder inside the service stub module you can see the generated stub there. Final step is to create the UI to access the created service.

      3. Creating the Front-end (UI)
      We need to add the service stub module as a dependency to the front-end module since we need to use the generated stub to access the service.  To do that open the pom file of the front-end module and add the service-stub as follows
       dependency>  
             <groupId>org.wso2.carbon.sample</groupId>  
             <artifactId>service-stub</artifactId>  
             <version>1.0-SNAPSHOT</version>  
       </dependency>  
      

      Finally full pom file of the front-end module should be like
       <?xml version="1.0" encoding="UTF-8"?>  
       <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
            xmlns="http://maven.apache.org/POM/4.0.0"  
            xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
         <parent>  
           <artifactId>ordar-manager</artifactId>  
           <groupId>org.wso2.carbon.sample</groupId>  
           <version>1.0-SNAPSHOT</version>  
         </parent>  
         <modelVersion>4.0.0</modelVersion>  
         
         <artifactId>frontend</artifactId>  
         <packaging>bundle</packaging>  
            
         <dependencies>  
           <dependency>  
             <groupId>org.wso2.carbon.sample</groupId>  
             <artifactId>service-stub</artifactId>  
             <version>1.0-SNAPSHOT</version>  
           </dependency>  
         </dependencies>  
         
         <build>  
           <plugins>  
             <plugin>  
               <groupId>org.apache.felix</groupId>  
               <artifactId>maven-bundle-plugin</artifactId>  
               <extensions>true</extensions>  
               <version>2.5.3</version>  
               <configuration>  
                 <instructions>  
                   <Bundle-SymbolicName>${pom.artifactId}</Bundle-SymbolicName>  
                   <Bundle-Name>${project.artifactId}</Bundle-Name>  
                   <Export-Package>  
                     org.wso2.sample.carbon.order.manager.*  
                   </Export-Package>  
                   <Import-Package>  
                     *;resolution:=optional  
                   </Import-Package>  
                   <Carbon-Component>UIBundle</Carbon-Component>  
                 </instructions>  
               </configuration>  
             </plugin>  
           </plugins>  
         </build>  
       </project>  
      

      Next I'm creating the Client inside the front-end module, which will use the generated stub to access the back-end service.

      Client class
       package org.wso2.sample.carbon.order.manager.ui;  
         
       import org.apache.axis2.client.Options;  
       import org.apache.axis2.client.ServiceClient;  
       import org.apache.axis2.context.ConfigurationContext;  
       import org.apache.axis2.transport.http.HTTPConstants;  
       import org.wso2.sample.carbon.order.manager.beans.xsd.Item;  
       import org.wso2.sample.carbon.order.manager.stub.OrderManagerStub;  
         
       import java.rmi.RemoteException;  
         
       public class Client {  
         private OrderManagerStub stub;  
         
         public Client(ConfigurationContext ctx, String backendServerUrl, String cookie) throws Exception{  
           String serviceUrl = backendServerUrl + "OrderManager";  
           stub = new OrderManagerStub(ctx, serviceUrl);  
           ServiceClient serviceClient = stub._getServiceClient();  
           Options options = serviceClient.getOptions();  
           options.setManageSession(true);  
           options.setProperty(HTTPConstants.COOKIE_STRING, cookie);  
         
         }  
         
         public Item[] getItems() throws RemoteException {  
           return stub.getOrders();  
         }  
         
         public void addItem(Item item) throws RemoteException {  
           stub.addOrder(item);  
         }  
       }  
         
      

      Then create a directory named web inside resource folder. Inside the web folder, create another directory and named it as order-manager.
      Create a file names index.jsp inside that. This is the jsp page that consist of the UI part. I will have a table of existing Items and a form to add new Items.

      index.jsp
       <%@ page import="org.apache.axis2.context.ConfigurationContext" %>  
       <%@ page import="org.wso2.carbon.CarbonConstants" %>  
       <%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %>  
       <%@ page import="org.wso2.carbon.utils.ServerConstants" %>  
       <%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %>  
       <%@ page import="org.wso2.sample.carbon.order.manager.ui.Client" %>  
       <%@ page import="org.wso2.sample.carbon.order.manager.beans.xsd.Item" %>  
       <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>  
       <%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>  
       <%  
           String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);  
           ConfigurationContext configContext =  
               (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);  
           String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);  
         
           Client client;  
           Item[] orders;  
         
           try {  
             client = new Client(configContext, serverURL, cookie);  
             orders = client.getItems();  
           } catch (Exception e) {  
             CarbonUIMessage.sendCarbonUIMessage(e.getMessage(), CarbonUIMessage.ERROR, request, e);  
             return;  
           }  
         
           if ("POST".equalsIgnoreCase(request.getMethod())) {  
             try{  
               int itemCode = Integer.parseInt(request.getParameter("itemCode"));  
               String itemName = request.getParameter("itemName");  
               float itemPrice = Float.parseFloat(request.getParameter("itemPrice"));  
                     Item newItem = new Item();  
                     newItem.setNo(itemCode);  
                     newItem.setName(itemName);  
               newItem.setPrice(itemPrice);  
         
               client.addItem(newItem);  
             }catch(Exception e){  
               e.printStackTrace();  
             }  
           }  
       %>  
         
       <div id="middle">  
         <h2>Order Management</h2>  
         
         <div id="workArea">  
           <table class="styledLeft" id="moduleTable">  
               <thead>  
                 <tr>  
                   <th width="20%">Order ID</th>  
                   <th width="40%">Item Name</th>  
                   <th width="40%">Price</th>  
                 </tr>  
               </thead>  
               <tbody>  
             <%  
               for(Item order:orders){  
             %>  
                 <tr>  
                   <td><%=order.getNo()%></td>  
                   <td><%=order.getName()%></td>  
                   <td><%=order.getPrice()%></td>  
                 </tr>  
             <%  
               }  
             %>  
               </tbody>  
            </table>  
            </br>  
            </br>  
            </br>  
            <form action="" method="POST">  
              <table>  
                <tr>  
                  <td>Item Code</td>  
                  <td><input type="text" id="itemCode" name="itemCode"></td>  
                </tr>  
                <tr>  
                  <td>Item Name</td>  
                  <td><input type="text" id="itemName" name="itemName"></td>  
                </tr>  
                <tr>  
                  <td>Item Price</td>  
                  <td><input type="text" id="itemPrice" name="itemPrice"></td>  
                </tr>  
                <tr>  
                  <input type="submit" value="Add">  
                </tr>  
              </table>  
            </form>  
         </div>  
       </div>  
      
      Here you can see I've used some style classes and IDs. Those are predefined classes and IDs in the Carbon. Don't forget to import the carbon tag library as well.
      (Since IdeaJ community edition is not supporting JSP, you may find it very difficult to format and write the code. If you feel so use eclipse and copy back the code to IdeaJ)

      Now we must add the UI component as a menu item. In order to do that you must create the component.xml file.
      First create a folder named META-INF inside the resource folder of the front-end module and create a file named component.xml inside the META-INF folder with following content.

      component.xml
       <component xmlns="http://products.wso2.org/carbon">  
         <menus>  
           <menu>  
             <id>orderservice_menu</id>  
             <i18n-key>orderservice.menu</i18n-key>  
             <i18n-bundle>org.wso2.sample.carbon.order.manager.ui.i18n.Resources</i18n-bundle>  
             <parent-menu>manage_menu</parent-menu>  
             <link>../order-manager/index.jsp</link>  
             <region>region1</region>  
             <order>50</order>  
             <style-class>manage</style-class>  
             <require-permission>/permission/protected/manage</require-permission>  
           </menu>  
         </menus>  
       </component>  
      
      Here i18n-bundle
      value depend on the package that the created Client resides. Create folder structure according to the package name inside the web folder.
      e.g my Client class resides in org.wso2.sample.carbon.order.manager.ui package. Therefore I must create folder structure as
      org/wso2/sample/carbon/order/manager/ui

      Then we have to create the resource bundle. To do so create a file named Resource.properties file. inside the above created folder structure.
      e.g.
      org/wso2/sample/carbon/order/manager/ui/Resources.properties
      File content is
       orderservice.menu = Order Service  
      
      Note
      orderservice.menu is the i18n-key that we define in component.xml file.

      Go to the pom file location of the front-end module and do a maven clean install

      Deploy the Component
      Now copy the generated jar files inside the back-end module and front-end module (No need of service-stub jar) in to the earlier mentioned dropins folder and restart the WSO2 AS and log back to the server.

      You will see a menu item called Order Manager on left hand side menu bar and when you go to that menu item you will see something like

      Note
      If you don't get the menu item and don't get any errors in the console probably you might have some issues in resource bundle. Check if the location is correct according to the structure.

      You can download the sample code from
      https://drive.google.com/file/d/0B-jZl7AY9hiibE01X0hFYVg0SkU/view?usp=sharing