Sunday, February 8, 2015

Simple Web Page with Jaggery

In this post I'm going to explain how to write a simple Jaggery web page. It will have a single form, when user submit the form that information will be stored in a JSON file and already existing content will be shown in the page as well.

Prerequisites
  • Jaggery server or WSO2 Application server should be available on the disk
  • Basic HTML knowledge
Getting to Code
Create a directory on your disk with name as Employee. Create a file with following content and name it as something like employee.jag
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Employee Details</title>  
      </head>  
      <body>  
           <h2>Add New Employee</h2>  
           <form id="frmNewEmp" method="POST">  
                <table>  
                     <tr>  
                            <td>First Name:</td>  
                            <td><input type="text" name="fname" /></td>  
                      </tr>  
                      <tr>  
                            <td>Last Name:</td>  
                            <td><input type="text" name="lname" /></td>  
                      </tr>  
                      <tr>  
                            <td>Age:</td>  
                            <td><input type="text" name="age" /></td>  
                      </tr>  
                </table>  
                </br>  
                <input type="submit" value="Add">  
           </form>  
           <h2>Current Employees</h2>  
      </body>  
 </html>  
 <%  
      var fileName = "employees.json";  
        var file = new File(fileName);  
      if(!file.isExists()){  
           file.open("w");  
           file.write('{"employees":[]}');  
           file.close();            
      }  
      /*Load JSON object from the require function*/  
      //var employeeJson = require(fileName);  
      // Read the file and parse string as JSON object  
      file.open("r");  
      var employeeJson = parse(file.readAll());  
      file.close();  
      function printEmployees(){  
           //Iterate through the each element in the Employees array and print them  
           for(var i in employeeJson.employees){  
                print(employeeJson.employees[i].fname + " " + employeeJson.employees[i].lname + ", " + employeeJson.employees[i].age);  
                print("</br>");  
           }  
      }  
      // This section will get called when user press the Add button.  
      // Read the POST data and add new employee to the JSOPN array  
      // Save the JSOn object in the file       
      if(request.getMethod() == "POST"){  
           employeeJson.employees.push({"fname":request.getParameter("fname"), "lname":request.getParameter("lname"), "age":request.getParameter("age")});  
             file.open("w");  
             file.write(employeeJson);  
           file.close();  
      }  
      // Print existing Employees  
      printEmployees();            
 %>  

Deploy
Copy your Employee directory (Directory that contains the employee.jag file) to the apps directory in the Jaggery extract path.
Note
Read on Hello Jaggery post to understand how to deploy files, if you are not sure.
If you are using WSO2 Application Server, you must copy the directory to
 repository/deployment/server/jaggeryapps  
path in the WSO2 Application server extracted location.

Run
Open your web browser and go to the URL
http://localhost:9763/Employee/employee.jag
When you load the page for the first time it will look like
After you added few employees it will look like

Saturday, February 7, 2015

Hello Jaggery

What is Jaggery ?
Jaggery is a framework to write webapps and HTTP-focused web services for all aspects of the application: front-end, communication, Server-side logic and persistence in pure Javascript. One of the intents of this framework is to reduce the gap between writing web apps and web services. Importantly, Jaggery is open-source and released under Apache 2.0 - JaggeryJS.org

Prerequisites
Java

Getting Started
You can download the jaggery from JaggeryJS.org website. It will download all the things that you need to get your hands dirt with Jaggery.
Extract the downloaded zip folder to anywhere that you like. It will looks like
Jaggery bundles a server with it. You can start the server using the server.sh/bat script in the bin folder.

If the server get started successfully you can access its management console using the
https://localhost:9443/admin/carbon/
Use admin as both username and password.

Hello Jaggery
Now lets see how to write the simplest program that we tend to write when getting start with a new language. That is Hello World.

Open your favorite text editor and have following code on that

 <%  
     print("Hello World!");  
 %>  

Save this file with some name like hello.jag
Note
Remember file extension should be .jag

Deployment
You deploy the created file manually or through the Management console.

Option 1 - Manual
Go to the apps folder in the Jaggery. Create a new directory inside the apps folder with name Hello and copy the file that you created to that.
Option 2 - Using Management Console
Add the created file to a .zip folder and rename zip folder to Hello.zip.
If you are using ubuntu you can easily do this by terminal. Go to the directory where your file exists on the disk from the terminal and type following command.
 zip -r Hello.zip hello.jag  
In windows you can do the same thing by right click on the file and select Compressed zip folder from the Send to menu

After creating the zip folder, login to the management console and select Jaggery from the left hand side navigation pane. Then select the zip file that you created and do the upload.

Note
Remember folder name that you are using will be your application name.

Run the Hello World
Go to the following url from your browser
Here Hello is your application name. This is the name that we gave to the folder which consist of hello.jag file.

You will see Hello World! text get printed on your screen.

Wednesday, February 4, 2015

Getting Started with WSO2 ESB

In this post I'm going to explain how we can use WSO2 ESB to create a simple proxy service for a web service and how to consume that.

What is an ESB
An enterprise service bus (ESB) is a software architecture model used for designing and implementing communication between mutually interacting software applications in a service-oriented architecture (SOA). As a software architectural model for distributed computing it is a specialty variant of the more general client server model and promotes agility and flexibility with regard to communication between applications. Its primary use is in enterprise application integration (EAI) of heterogeneous and complex landscapes. - Wikipedia

WSO2 ESB is the best 100% open source ESB available in the current market. It can be considered as the highest performance, lowest footprint, and most interoperable SOA and integration middleware today. - WSO2 ESB

Prerequisites 
  • JDK should be installed in your computer
  • HelloAxis.aar (Creating HelloAxis.aar) or some other web service archive file.
  • Maven (To generate the client source)

Getting Started
You can download the latest WSO2 ESB binary distribution from the WSO2 website (WSO2 ESB Download Page). WSO2 ESB 4.8.1 is the latest stable release. Download that and extract it into any place that you like. When will you extract, it will be looks as follows.


Before creating the proxy we need to deploy our web service. Here I'm using a separate axis2 server. Refer HelloAxis2 post to see how to deploy the file in Axis2 server. You can use axis2 server bundle with WSO2 ESB to deploy the service. You are also free to deploy it anywhere that you like.

Deploy using axis2 server in WSO2 ESB
Copy the HelloAxis.aar file to wso2esb-4.8.1/samples/axis2Server/repository/services
You can start the Axis2 server using the axis2server(.bat or .sh) script in the wso2esb-4.8.1/samples/axis2Server folder. By default this axis2 server will starts on port 9000. If the server get started successfully and the web service is deployed without any iussues, you can see the HelloAxis service is available on the Web service list in localhost:9000/services/

Starting ESB
You can start the WSO2 ESB using the wso2server script in the wso2esb-4.8.1/bin directory 

Ubuntu
wso2server.sh
Windows
wso2server.bat

Note
WSO2 ESB get starts in INFO mode by default. If you like to start the ESB in debug mode, you have to do a small change. To do so
Open the log4j.properties file in the wso2esb-4.8.1/repository/conf folder. In the file you can find a entry looks 
log4j.category.org.apache.synapse=INFO
changed that to
log4j.category.org.apache.synapse=DEBUG

When you run the wso2server script you will see some log entries getting print on terminal and if the ESB get started successfully you will see something similar to

You can open the browser and go to the URL mentioned(https://localhost:9443/carbon) there the WSO2 ESB management console. Probably you will see some security warning when you go to the URL. Just ignore it this time.
You can use admin as both username and password to login to the ESB console.

Go to the Proxy services section under the Services and select Pass Through Proxy from the templates.
In the next screen you must specify information relate to your service. 
  1. Proxy service name - This will be use as the name of our proxy. You can give any name that you like
  2. Target URL - Specify the deployed web service URL. This is what you are accessing through the proxy e.g. HelloAxis service
  3. Select Specify source URL in the publishing WSDL section in the Publish WSDL Options and provide URL to WSDL of the deployed service 
  4. Press Create button.

You will see a message box saying proxy is created successfully and you should see the newly created Proxy service in the Deployed service list. 

Creating a Client
Click on the proxy service name that you created from the list. Then click the Generate Axis2 Client in the Client Operation section in the right hand side of the screen.



In the next screen you will see set of options relate to generating client code. I will just provide a custom package name, while keeping other settings as it is. Click generate button.
This will create a .zip file which consists of a pom.xml file. We can use this pom.xml file to generate the client source code.
You can use your favorite IDE or plain maven commands to generate the source code.

Before generating the source, first open the pom.xml from your favorite text editor and changed
   <properties>  
     <axis2_version>1.6.1-wso2v10</axis2_version>  
   </properties>  

to
   <properties>  
     <axis2_version>1.6.1-wso2v9</axis2_version>  
   </properties>  


e.g.
To generate the source code without any IDE support 
 mvn generate-sources  

To generate source and create eclipse project
 mvn eclipse:eclipse  

If you are using IdeaJ IDE you can import this pom.xml file and generate the source code.

After generating the source, create a simple Java class as follows.
 import org.apache.axis2.AxisFault;  
 import java.rmi.RemoteException;  

 public class ESBClient {  
   public static void main(String[] args) {  
     try {  
       SimpleProxyServiceStub stub = new SimpleProxyServiceStub("http://localhost:8280/services/SimpleProxyService");  
       SimpleProxyServiceStub.SayHello sayHello = new SimpleProxyServiceStub.SayHello();  
       sayHello.setName("Thusitha");;  
       System.out.println(stub.sayHello(sayHello).get_return());  
     } catch (AxisFault axisFault) {  
       axisFault.printStackTrace();  
     } catch (RemoteException e) {  
       e.printStackTrace();  
     }  
   }  
 }  
When you run this you will get the output
 Hello Thusitha  

This output implies that our HelloAxis2 web service get called through the proxy service that we create using WSO2 ESB.

Saturday, January 31, 2015

Hello World with Apache Axis2

Apache Axis2 is a core engine for Web services. It is a complete re-design and re-write of the widely used Apache Axis SOAP stack. Implementations of Axis2 are available in Java and C. Axis2 provides the capability to add Web services interfaces to Web applications. It can also function as a standalone server application - Wikipedia

Prerequisites 
  • JDK should be installed in your computer
Getting Started
You can download the latest Axis2 binary distribution from the Apache Axis2 website (Axis2 Download Page). Latest stable release is Axis2 1.6.2. Download that and extract it into any place that you like. When will you extract, it will be looks as follows.



After extracting the Axis2, it is better to set the AXIS2_HOME environment variable in the system.
$AXIS2_HOME should be set to  location where you extract the Axis2.
e.g. $AXIS2_HOME = /home/axis2-1.6.2

Creating Apache Archive (.aar) File
After setting up the environment let see how we can develop a simple web service using Axis2. I'm not going to use ant IDEs. But you can use any IDE that you are familiar with. You can use Axis2 plugins that are available for almost all the popular IDEs like Ecliple, IntelliJ and Netbeans too.

Open your favorite text editor/IDE and create a java class with following code.

 public class HelloAxis{  
      public String sayHello(String name){  
           return "Hello " + name;  
      }  
 }  

Save this with appropriate name.
e.g. here file name must be HelloAxis.java

Then you should get the compiled class file of the created file (HelloAxis.class).
For the clarity I'm copying that file to a new folder. Create a folder with the name META-INF in  the same folder. Then create file with the name services.xml inside the META-INF folder and copy following code segment to that file.

 <?xml version="1.0" encoding="UTF-8"?>  
 <service name="HelloAxis">  
   <Description> Hello Axis2 Web Service </Description>   
   <messageReceivers>  
       <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>  
   </messageReceivers>  
   <parameter name="ServiceClass" locked="false">HelloAxis</parameter>  
   <operation name="sayHello"/>   
 </service>  

Note
In the above code ServiceClass value should be your class full qualified name and operation name should be the method name that you are exposing from the class.

After that your folder structure looks like as follows


Then open the terminal/CMD go to the particular path. And type following command in the terminal
jar -cvf HelloAxis.aar ./*
This will create a  HelloAxis.aar in your folder that is what we should deploy.


Deploying Created .aar File
Apache Axis2 can be run as a standalone server or inside a application server like Apache Tomcat. Lets see how to deploy the created archive file in the standard Apache Axis2 server.
To start the Apache Axis2 server got to the bin folder in the Apache axis2 and execute followling command from the terminal/cmd. If you have set the $AXIS2_HOME environment variable you can start easily.

Linux
sh axis2server.sh
Windows
axis2server.bat

Note
In the default configuration server will be started in port 8080. You will see some errors if the port is already using by some other application. If so close them and retry or change the default server port to some other port using axis2.xml file in the conf folder.
You will see a segment like

 <transportReceiver name="http" class="org.apache.axis2.transport.http.SimpleHTTPServer">  
 <parameter name="port">8080</parameter>  

Change the port value to some other port that you like.

If the server get started successfully you can see something like below image on your screen. Don't close the terminal.

Now copy the created HelloAxis.aar file into repository/services path inside the Axis2 folder
e.g.
/home/thusitha/axis2-1.6.2/repository/services

When you copied the file, and you followed the steps as told, you will see a similar log entry as follows in the Terminal.
This means that our webservice have been successfully deployed to the Axis2 server.

Testing the Service
Open the web browser and type following URL

http://localhost:8080/axis2/services/HelloAxis/sayHello?name=Thusitha

You will output like

 <ns:sayHelloResponse xmlns:ns="http://ws.apache.org/axis2">  
      <ns:return>Hello Thusitha</ns:return>  
 </ns:sayHelloResponse>  

Note
check the WSDL e.g. (http://localhost:8080/axis2/services/HelloAxis?wsdl) section relate to sayHello method. It should be looks like

 <xs:element name="sayHello">  
   <xs:complexType>  
     <xs:sequence>  
       <xs:element minOccurs="0" name="name" nillable="true" type="xs:string"/>  
     </xs:sequence>  
   </xs:complexType>  
 </xs:element>  

name should be your variable name. If it is like args0 or param0, you must recompile the class using -g flag.
e.g.
javac -g HelloAxis.java
Then follows the same steps.

Wednesday, December 31, 2014

A Great Place to Work

Today was my last day at IFS. Until today morning, I didn't thought that leaving a place where you were just there for 15 months make you emotional. Though my stay at IFS is not that long I was really fond of IFS.

I get to know about IFS when I was a 2nd year student at university. It was in 2010. We had to do a project collaboration with an IT company. Through a one of the group member's contact we get a chance to go to IFS and had a discussion about a project with Dulantha aiya. We decided to do that project and got chance to visit IFS couple of times. At that time I really wanted to join IFS. But with time there were another 1 or 2 companies that changed my mind. However finally at the middle of the last year I decided to apply for IFS and got selected.

I joined IFS on 16th September 2013 just after finishing the last semester at university. We had 6 weeks of training and then I joined Technology group on November 4th. Few days before joining the group a person comes and told his name then told me that I can join Technology group. That was Mangala who was my Director. Next day when I was playing carrom a woman came and told that she want to discuss some point regarding my new assignment and she also told that she would wait until I finish my carrom game. She was Chamilka akka who was my Manager. I never expected so much humbleness and kindness from the management. That was truly fascinating. At IFS, it doesn't matter whom you talk with everyone is so humble and kind, willing to provide assistance at any point.

It is very hard to find an IT company that has work-life balance like at IFS or any IT company that pay overtime like IFS do. I can point out a long list that really bound me to that amazing culture. IFSers are really a great bunch of people that I have ever met. I really enjoyed all my work there and specially the chance that I got to be a part of organizing committee of the IFS Annual Sports Day, IFS Dinner Dance and many more events as a welfare member and also the awesome TechIgnite 2014.

Sometimes in life we have to get out of comfort zone. Leaving IFS was a very tough decision that I took in my life. Though I left IFS, those 15 months and the memories will never be fade.

Thursday, November 20, 2014

Myself and computers

I could't recall exact date that I fall in love with computers. But since I was a little kid I used to read stuffs about computers. As I remember there were some articles in Wijaya news paper which I used to bought since grade 4 ,5. There was a Tv program on Rupawahini on Mondays at 7.00 pm called "Antharjalaya obe niwahanata" I love that so much. I really wanted to try out those stuffs. But computers weren't popular that much those days. Father bought a computer for the first time when I was at grade 9. At that time Crash zone was my favorite tv show. I pretty much inspired how those kids work with computers. I wanted to be a game tester. Myself and a one of my best friend who is living next to my house used to play computer games so crazily in those ages.
 With the time I wanted to do more than just playing game. I started to play with HTML. <marquee> tag was something I was impressed so much. I wrote quite few basic html web pages at that time. I have no idea what is programming but I liked to write html stuffs.

(To be continue)

Sunday, August 31, 2014

I Dream A Lot

(Human)Life is one of the most amazing thing in the universe. People eat, drink, walk, play sleep etc.. throughout their life. I think every human on earth at least saw a one dream in their life. Not the usual dreams that we saw when we fall a sleep. But the dreams that make us motivates to do something in life. The natural thing is people have dreams and they are just a dreams.
It is very hard to find people who work to achieve or to make their dreams come true. No dream will come true automatically. Each one of us have the courage to pursuit our dreams. All dreams may never come true. But at least we should give a try.

If you are really passionate about programming (of course there are programmers who do it just for money) you may get various crazy ideas. I think that is normal. We always dreams about lot of crazy new stuffs. Some of my crazy ideas are
1. Build a system like in Person of Interest
2. Build an AI like Virgil (Crash Zone)
3. Develop a new programming language

First and second dreams are closely related with AI, image processing, computer vision like stuffs. But when it comes to the third point it is like how to think out of the box. There exist thousands of programming languages which various people have developed for various purposes. Java, C#, VB, PASCAL, PHP etc... most of the languages are designed with some specific requirements.

[Under construction]