Thursday, December 10, 2009

My 500LKR haircut

This incident took place on Monday. Although it is not that much of a significant incident I thought of writing a blogpost because of the funny nature of it. On Monday, I thought of getting a haircut. I was having a chat with my buddy Pandula before going to the Saloon. When I mentioned about the haircut, he asked "hey man, are you still going to that shitty place to get an haircut. You should increase your standard of living cos now that you are employed and ....." he went on preaching. In my defense this so called "shitty Saloon" was the one which I have been going to for the last 5 years after moving to Borella. Although it did not have many luxurious facilities, I could get a haircut+head massage for 140/= (including the 20/= tip).

After Pandula's comment I was a bit embarrassed and thought of going to a better Saloon. After going in I told the barber the way in which I need my hair to be trimmed. He did it. At the end of the haircut I asked the barber how much is for the haircut. He said 150/=. I thought "Somebody have to pay for these fancy lights and equipment" and said "ok cool". Then I told him to give me a head massage(a statement which I would regret later).

This bugger gave me a head massage for 20 minutes. Normally in my old place the barber would give it for 5 mins. I thought that this guy was having some short term memory loss in understanding time durations. After everything was done, I asked him how much for the haircut? He said 500/=. My first reaction was that I heard it wrong and I asked the same question again to get the same answer back. Then I asked "Damn.... you charged 350/= for a head massage?". Although I had 2000/= with me at that time; under any circumstance I would not pay for a haircut that much.

I told him "I am having 300/= with me right now and out of it I have to buy a dinner packet for 100/=. I can only give you 200/=." He had no other option but to accept my proposition. [IMO barber had another extreme option. He could have asked me to cut hair of the customers until he recovers my charge (just like people are asked to wash plates in "siwari", when they are unable to pay for the food that they have eaten :)). I guess he did not have faith in me - having a pair of scissors on my hand ]. Therefore I gave him 200/= and got myself out of that place. That was the last time that I would step on that place.

Ironically the Saloon's name was "Sayonara" :) meaning 'goodbye'. 'siy-oh-nah-rah' would be the best matching name that anybody could come up with, for a Saloon like that :D

Thursday, November 5, 2009

Use mail transport in ESB to convert the SOAP message to a plain text mail

Imagine a scenario where you are using the mail transport in ESB. You need to convert the SOAP message to a plain text mail(without any XML in it). This blogpost is written to address it.

How To:
Following steps will guide you to get your scenario up and running.

1) Uncomment the mail TransportSender and TransportReceiver from axis2.xml

<transportSender name="mailto" class="org.apache.axis2.transport.mail.MailTransportSender">
<parameter name=""></parameter>
<parameter name="mail.smtp.port">587</parameter>
<parameter name="mail.smtp.starttls.enable">true</parameter>
<parameter name="mail.smtp.auth">true</parameter>
<parameter name="mail.smtp.user">synapse.demo.0</parameter>
<parameter name="mail.smtp.password">mailpassword</parameter>
<parameter name="mail.smtp.from"></parameter>

<transportReceiver name="mailto" class="org.apache.axis2.transport.mail.MailTransportListener">

2) Add the following line to axis2.xml's MessageFormatters.

<messageFormatter contentType="text/plain" class="org.apache.axis2.format.PlainTextFormatter"/>

3) Build the SimpleStockQuote service (which is residing inside the samples). Run sample axis2Server.

4) Use the attached proxy configuration.

<!-- Using the mail transport -->
<definitions xmlns="">
<proxy name="StockQuoteProxy" transports="mailto">

<parameter name="transport.mail.Address"></parameter>
<parameter name="transport.mail.Protocol">pop3</parameter>
<parameter name="transport.PollInterval">5</parameter>
<parameter name=""></parameter>
<parameter name="mail.pop3.port">995</parameter>
<parameter name="mail.pop3.user">synapse.demo.1</parameter>
<parameter name="mail.pop3.password">mailpassword</parameter>
<parameter name="mail.pop3.socketFactory.class"></parameter>
<parameter name="mail.pop3.socketFactory.fallback">false</parameter>
<parameter name="mail.pop3.socketFactory.port">995</parameter>
<parameter name="transport.mail.ContentType">application/xml</parameter>

<property name="senderAddress" expression="get-property('transport', 'From')"/>
<log level="full">
<property name="Sender Address" expression="get-property('senderAddress')"/>

<address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
<property name="Subject" value="Custom Subject for Response" scope="transport"/>
<property name="messageType" value="text/plain" scope="axis2-client"/>
<script language="js"><![CDATA[
mc.setPayloadXML(<ns:text xmlns:ns="">Plain text received!</ns:text>);
<header name="To" expression="fn:concat('mailto:', get-property('senderAddress'))"/>
<log level="full">
<property name="message" value="Response message"/>
<property name="Sender Address" expression="get-property('senderAddress')"/>
<publishWSDL uri="file:repository/samples/resources/proxy/sample_proxy_1.wsdl"/>
5) Send an email to

6) You will receive the response in plain text.

Wednesday, October 21, 2009

Exposing a non-secured service with security using ESB

This article explains how to expose a non-secure service as a secured service using WSO2 ESB. The unsecured service is SimpleStockQuoteService. The strategy taken up is to secure SimpleStockQuoteService throught a secured proxy. A proxy service is written to enable username token authentication and logging of messages. Steps specified in the article demonstrates how to get this scenario up and running. [Read the full article for more info]

Sunday, October 11, 2009

My article on IBM Developer Works

It was one of my dreams to publish an article in IBM dW. Last week one of my articles got published in the IBM developerWorks. A special thank goes out to Chris Walden (Web Development Editor) of developerWorks who made this happen.

Saturday, October 3, 2009

Basketball @ WSO2 : How to Survive

It's been a while since I wrote a blogpost that relates to sports. Since annual basketball tournament at wso2 is coming up next week, I thought it would be the perfect time to write a blogpost on WSO2 basketball. The ideas & views expressed below can be a KnowledgeBase for anyone joining wso2 or newbie who wants to play basketball @ wso2.

Wso2 folks dont have a permanent basketball court to play basketball. Instead they have transformed the car park into a basketball court. It is car-park by day and basketball court by night. We have portable baskeball posts, so we move em to the car-park in the evening. The court is not having the ideal dimensions of a standard basketball court; it is due to the limited space available in the car park.

We started playing basketball @ wso2 around 1 year back and we followed it up with a inter-house basketball tournament, which was a blast. It was a very successful event and everyone enjoyed it a lot(apart from the people who got injured while playing lol). Now 1 year has elapsed since the introduction of basketball to wso2 and IMO I say that we are playing a different flavor of basketball.

Basketball is having several flavors ranging from Streetball to Slamball. Wso2's basketball has evolved into a unique flavor apart from these. I'd say it is a hybrid of both basketball and rugby :D. I'd like to call it RugBBall. Since I said that this would be a KB item, following are some tips to be successful(or survive lol) @ basketball court, during practice sessions.
  • You should be able to tolerate elbow shots and slaps, cos these arn't fouls :)
  • Dont ever argue with guys on "whether it was a foul or not". You could never win that argument :). Therefore it's better to carry on with the game without arguing.
  • After a practice session you'd feel like if you were scratched by a kitten and tackled by a NFL linebacker lol.
Those are the fun facts to know before you enter into the bb court.

I will follow this post up with a pre-tournament analysis of the wso2's inter-house basketball teams. So stay tuned ;) .

Thursday, September 10, 2009

Create ZIP archieve from multiple files

Following code snippet shows how to create a zip archieve from multiple files.

import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;

public class ZipDemo {
static int BUFFER_SIZE = 1024;
static String zipArchieveName = "";

public static void main(String args[]) {
try {
// Reference to the file we will be adding to the zipfile
BufferedInputStream origin = null;

// Reference to zip file
FileOutputStream dest = new FileOutputStream(zipArchieveName);

// Wrap our destination zipfile with a ZipOutputStream
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));

// Create a byte[] buffer that we will read data from the source
// files into and then transfer it to the zip file
byte[] data = new byte[BUFFER_SIZE];

List files = new ArrayList();

// Iterate over all of the files in list
for (Iterator i = files.iterator(); i.hasNext();) {
// Get a BufferedInputStream that we can use to read the source file
String filename = (String);
System.out.println("Adding: " + filename);
FileInputStream fi = new FileInputStream(filename);
origin = new BufferedInputStream(fi, BUFFER_SIZE);

// Setup the entry in the zip file
ZipEntry entry = new ZipEntry(filename);

// Read data from the source file and write it out to the zip file
int count;
while ((count =, 0, BUFFER_SIZE)) != -1) {
out.write(data, 0, count);

// Close the source file

// Close the zip file
catch (Exception e) {

Monday, August 31, 2009

How to add a Log4j Appender to WSO2 Carbon

1) Write a java class and extend AppenderSkeleton. Add the logic to the append(LoggingEvent e) method.
public class JiraAppender extends AppenderSkeleton {
protected void append(LoggingEvent loggingEvent) {
if (loggingEvent.getLevel().toString().equalsIgnoreCase("INFO")) {
System.out.println("INFO invoked!");

public boolean requiresLayout() {
return false;

public void close() {

2) Modify the file located at

a) Add the following entry to the file.
# CARBON_JIRA is set to be a MemoryAppender using a PatternLayout.
log4j.appender.CARBON_JIRA.layout.ConversionPattern=[%d] %5p - %x %m%n

b) Update the file with the following entry.

Sunday, August 23, 2009

Building OSGi bundles using Maven Bundle Plugin

I came across a good article by Sameera on "How to build OSGi bundles using Maven Bundle Plugin". It gives detailed infromation on how to use maven bundle plugin to generate OSGi bundles. In this blogpost, I will demonstrate how a sample can be run. If you are hungry for more information read the above article.

1) Download and extract the samples.

2) Build the sample01
mvn clean install
3) Download Equinox.
eg: org.eclipse.osgi_3.5.0.v20090520.jar

4) Run the jar file using following command.
java -jar org.eclipse.osgi_3.5.0.v20090520.jar -console
5) In the command prompt execute following command.
osgi> ss
Framework is launched.

id State Bundle
0 ACTIVE org.eclipse.osgi_3.5.0.v20090520
6) Install the bundle
osgi>  install file:/home/heshan/Documents/Work/OSGi/maven_bundle_plugin_samples_0/sample01/target/sample01-1.0.0.jar
Bundle id is 1

osgi> ss
Framework is launched.

id State Bundle
0 ACTIVE org.eclipse.osgi_3.5.0.v20090520
1 ACTIVE org.wso2.mbp.sample01_1.0.0
7) Use the following commands to start and stop the bundles.
osgi> start 1
Hello World!!!

osgi> stop 1
Goodbye World!!!

Tuesday, August 18, 2009

Building WSO2 Carbon from source

You can use following steps to successfully build, WSO2 Carbon from source;

1. Checkout commons. Then build caching, eventing, throttle, xkms modules.

2. Build carbon.

3. Build carbon-orbit.

4. Build synapse.

5. Build rhino.

6. Build carbon-components.

Monday, August 17, 2009

Second "First Day" @ WSO2

Today was my first day at WSO2. I joined as a Software Engineer. This was in fact my second "first day" at WSO2. My first "first day" was in February 2008, when I joined WSO2 as an undergraduate intern.

Sunday, August 16, 2009

Good Bye UCSC

Past week was my last week at UCSC. I had my final year project defense last week and it was the last commitment that I had towards my university. The only other thing that we have to do is organize the Research Symposium. It will be held on 25th August.

UCSC had been my second-home for last 4 years and have some wonderful memories associated with it. It groomed me of becoming the person that I am today and I am forever grateful to University of Colombo and UCSC.

GSoC: Experience

This was my second consecutive year as a Google Summer of Code student. During past 3 months I learned a lot of things. I discussed these in an earlier posts. In a nutshell;

1) I worked with a mentor (Matt Boersma) from a different time zone. This was the first time that I worked with a mentor from a different timezone. Our time difference was nearly 12 hours. We preferred email over chat since it was more conveinent for us.

2) It was a privilege to work as a summer of code student for Python Software Foundation (PSF). All the people who were mentoring me helped me a lot, ranging from shaping up the application (project proposal) to development.

3)It was a greatopportunity for me to work with experienced developers.

I would like to take this opportunity to thank my mentor Matt Boersma and Jython community for helping me to make my project a success. I would also take this opportunity to thank my co-mentors Jim Baker and Frank Wierzbicki.

I would like to state that it was a privilege and a honor to be selected as a GSoC student for a second time and thank Google for organizing a program like this. I am looking forward to participating in next year's GSoC as a mentor. :)

Saturday, August 15, 2009

GSoC: Update

During the development phase, I came across some problems. This is a follow up to my earlier posts. You can have a look at them here.

1) One problem is the way the API is designed to define the XML payload. I designed the WSF/Jython API in such a way that it is comparable with the WSF/Ruby implementation. Therefore WSF/Jython API should adhere to the API specified by WSF/Ruby.

When generating code using Axis2's code generation framework, you should generate it in a such a way that it should support XML object model(preferably in the case of axis2 - apache axiom). Therefore it would be better if the API supported axiom, inorder to use the code generation part. Consider the following example.

from org.wso2.wsf.jython.jythonwsclient import *

req_payload_string = "<deduct><var1>1.8</var1><var2>4.87594</var2></deduct>"
LOG_FILE_NAME = "/home/heshan/IdeaProjects/MRclient/src/python_client.log"
END_POINT = "http://localhost:8070/axis2/services/annotationScript/deduct"

client = WSClient({}, LOG_FILE_NAME)
req_message = WSMessage(req_payload_string, {"to" :END_POINT})
print " Sending OM : " , req_payload_string
res_message = client.request(req_message)
print " Response Message: " , res_message

except WSFault, e:

In above code snippet, the payload is set as a string. i.e.

req_payload_string = "<deduct><var1>1.8</var1><var2>4.87594</var2></deduct>"

What should be done is to keep the above feature intact with the API and do a feature addition that will support Apache Axiom.

2) Therefore, the existing WSF/Jython codebase should be modified to support axiom for Jython (should look into this further).

3) Modify the existing codebase to include the code generation part. Having said that there should be more work done to seamlessly integrate this(code-generation part) to WSF/Jython code. More coding have to be done on code generation module for Jython.

4) In a earlier post I said of modifying the Python deployer to support Contract First approach. This happens in the server-side code generation. It's a problem that I am still having.

5) In the same post I said that
0nly generate the client code and use the existing WSF/Jython's client API. Then before running the client code you can add the WSF/Jython client-side jar to the class path.
Now it seems like the best option out of the two options mentioned in the above post.

[The above arguments are my opinions and may subject to change.]

Friday, July 31, 2009

The Last Lecture: Achieving Your Childhood Dreams

UCSC Research Symposium

A gallant display of research prowess awaits unveiling as the country’s premiere Computer Science and Information Technology research community stages the biggest event of the year - the UCSC Research Symposium 2009. With the memories of the inaugural UCSC Research Symposium in 2008 that revolutionized the undergraduate Computer Science research in Sri Lanka, the University of Colombo School of Computing (UCSC) expands this year’s event into new bounds, embracing cutting-edge research in both quantitative and qualitative disciplines.

Tuesday, 25th of August 2009
8.00 AM to 5.00 PM

Prof V.K. Samaranayake Auditorium,
University of Colombo School of Computing,
Colombo 7,
Sri Lanka

Friday, July 10, 2009

GSoC: How to integrate with existing code base

This post will contain my arguments on "How to integrate this project to the existing WSF/Jython code base". This is a followup to my last post.

1. Modify the Python deployer to support Contract First approach.

2. To support Contract First approach you need to be able to generate a skeleton and a message receiver for your service. The generic message receiver that I have already written may not work because it works only on a limited schema structure.

3. Another way to look at the above argument(2) may be; only generate the client code and use the existing WSF/Jython's client API. Then before running the client code you can add the WSF/Jython client-side jar to the class path.

The above arguments are my opinion(for now) on integrating the gsoc code to existing code base. The above arguments may subject to change.

Sunday, July 5, 2009

GSOC: Problems faced during development

Earlier I said that I would be writing a blog post on the problems which I encountered during the development phase of my GSoC project. Here I am compiling them to a list. Some points in the list may not directly be problems but important things which came across during the process.

1. Had a problem with building axis2. This was overcome when I found a workaround for this. (This was a hard issue to regenerate because this will only happen occasionally.)

2. There were lot of dependencies inside axis2's code generation framework. Some dependencies were not set by the build script. Therefore had to manually add the dependencies and run the code. When it gives a compilation error stating a dependency is not there, had to set the dependencies. This took some time :).

3. Had to take some time to understand the existing code base and the architecture of the code generation framework.

4. Learned to work with XSLTs.

5. Another important point to note is that the WSF/Jython distribution, now needs some additional libraries to successfully run. You may have wondered "why is this happening?". As you may already know WSF/Jython is built on top of Apache Axis2. The new releases of Axis2 are having more dependencies towards other liblaries/jars (eg. wsdl4j, etc). Since I no longer work for WSO2, I do not have the access writes to change the build script for WSF/Jython. As soon as I get there, I would remember to revise the build script. Until then you could do a small workaround:)

Download Axis2 standard binary distribution. Then extract it. Add the jars which are residing in the lib folder, to the classpath. Then you could carry on with your work.

6. How to integrate this project to the existing WSF/Jython development. (I will present my arguments on this on a new post)

Monday, June 29, 2009

Mr. Lakshman Kadiragamar's Lesson

In 2005, almost fifty years after he left Oxford, Mr. Lakshman Kadiragamar's portrait was unveiled at the Oxford Union. This was a great honour bestowed by the Oxford Union on only 15 others in its 183 year history.

Mr Kadirgamar had this to say about that event;

'......I would like to, if I may, to assume that I could share the honour with the people of my country, Sri Lanka . I had my schooling there, my first university was there, I went to Law College there and by the time I came to Oxford as a postgraduate student, well, I was relatively a matured person. Oxford was the icing on the cake … but the cake was baked at home ......(applause) .'

This is indeed true. People appreciate only the icing on the cake not where it was baked first.

Saturday, June 27, 2009

Design for Jython Extension for Axis2

In a earlier post I said that I am coming up with a Jython extension for Axis2. This will be a code generation tool for jython. This will use existing infrastructure in Axis2 to support Contract First Web services in Jython. What I am planning to do is to integrate this code generation tool into WSF/Jython. Then WSF/Jython will be able to support both, contract-first and code-first approaches. Thus, making the life easier for the Jython developer :).

The code generation engine calls the extensions one by one and then calls a component what is known as the Emitter. Emitter is the actual component that does the significant bit of work in the code generation process. Emitters are usually language dependent and hence one language has one emitter associated with it. Therefore there should be an emitter to support Jython code generation. This simple yet powerful architecture is shown in the above illustration.

The Emitter processes the WSDL and builds a object model. The object model is simply an XML file which contains the object model of the WSDL with respect to Axis2 information model (ie. axis service, axis operation, axis message, etc). The template is a XSLT file which contains information on how the code should be generated. Then the built object model is parsed against the template to build the jython source code.

wsdl2java Code Generation

Axis2's wsdl2java code generation tool can be used to auto-generate programming language code for a given WSDL file. It can either generate code to invoke a Web service, or it can auto-generate the skeleton code that will adhere to the specification described within the WSDL file so that the generated code can be deployed as a Web service.

$HOME = Small Miracle

My $HOME sweet home - Sri Lanka :).

Friday, June 26, 2009

Axis2 Code Generator

This is a follow up to my earlier post. What I am planning to do is to come up with a mechanism to generate jython code for a given WSDL. For this purpose I am planning to use Axis2's Code Generation module.

When you consider a SOAP processing engine, one of the key value additions will be code generation based on WSDL. It is normally considered as a tool and importance of it can be seen as;
  1. User convenience - Code generation tool helps users, to use the framework in easy and efficient way.
  2. Make use of the framework to it's full potential.
Now let's have a look at the architecture of Axis2 Code generator.

The tool's architecture is pretty straight forward. The core processes the WSDL and builds a object model. Then the built object model is parsed against the template to build the source code.

King of Pop - MJ

Michael Jackson died yesterday. He was considered the King of Pop and a megastar of music industry. Despite all accusations, he is one of those people who really made a difference. RIP MJ.

Thursday, June 25, 2009

Building Axis2

This is a bug (I think) which I came across a couple of times, while building Axis2. To overcome this you have to follow 2 simple instructions ;). For the completeness of this blog post, I will direct you through he complete build process.

1. First checkout the source.
svn co

2. Build the project from the source. Do not skip the tests, when you do a fresh build.
mvn clean install

Now is the tricky part. If you are not getting build errors, then no problems at all :). If you start getting build errors related to plugins, then do the following to overcome it.

1. First build the axis2-aar-maven-plugin.

2. Then build the axis2-mar-maven-plugin.

3. Afterwards, build axis2. This should pretty much overcome the build error :).

Jython extension for Apache Axis2

In a earlier post I mentioned that my proposal for GSoC 2009 was accepted. There I didn't give much details on what my project is about. Here is a description of my project.

If you have tried out WSO2 WSF/Jython, you will know that it is based on code-first approach. Web services, is a technology to deliver the architectural style defined in SOA. Although there seems to be a general confusion about the relationship between SOA and Web services, it is important to know that Web services are an implementation methodology that adopts standard protocols to execute SOA. There are two widely used techniques in Web service development, ie.
  1. Code First
  2. Contract First
With the contract-first approach, the contract for the Web service is determined first and then the supporting tools are used to generate the implementation code. In contrast, in the code-first approach, first the implementation code is created and then the Web service development framework is used to produce the contract for the Web service.

In simpler terms; in WSF/Jython what I am doing is asking you to write the web service and the client. Then based on the service, a WSDL is generated and exposed as a Web service. Afterwards jython client can be used to invoke the service (ie. code-first).

When it comes to contract-first it is vice versa of the above scenario. First we will have to take the provided WSDL in to consideration. Then based on this WSDL, the code should be generated. Following are the advantages of using contract first approach.
  • Loose coupling between applications
  • Interoperability between multiple services
  • Abstraction hides underlying implementation details
  • Collaboration and agreement between all parties

Saturday, June 20, 2009

Prof: V. K. Samaranayake Commemoration

The Students' Union of UCSC commemorated late Prof. V.K. Samaranayake by donating equipment to Army Hospital at Narahenpita on 18.06.2009. Prof. Samaranayake was considered the "Father of Information Technology" in Sri Lanka.

Tuesday, June 2, 2009

Writing a Web Server in C

Though the above heading may give you a headache when thinking "how to do it?", in practical sense it is pretty simple. I'm not talking about a fully functioning Web Server with wide array of functionalities, but a simple Web Server that will cater basic requirements of a Web Server. Through web surfing I found out some interesting web links which helped me to write my simple Web Server.

The way in which I did it was,
  1. First, got hold of a chat server (I used a one which I have written already).
  2. Then implemented the logic for handling http.

Following links helped me a lot in understanding the domain knowledge. If you'd like to have a look at the code feel free to drop a comment, I will be more than happy to share it with you :) .

MPI vs Pthread

I did a performance comparison between my MPI & pthread codes for Matrix multiplication. Matrices used were 1000*1000 and MPI code was run on UCSC's swelanka cluster (using 4 CPUs). While the MPI code took only 2.6 seconds to multiply two 1000*1000 matrices, the pthread code took more that 45 seconds(on avg).

Checking Hardware configuration of your Linux Distribution

Following are some useful commands to check your h/w configuration in linux.

1.Linux Flavor
$ cat /etc/issue

$ cat /proc/cpuinfo

$ cat /proc/meminfo

4.Hard Disk
$ df -h

Thursday, May 21, 2009

Wednesday, May 13, 2009

Matrix Multiplication using MPI

MPI(Message Passing Interface) is a library specification for message-passing. MPI was designed for high performance on both massively parallel machines and on workstation clusters. Following matrix multiplication is written in accordance to MPI. You could download the code from here.

* Matrix Multiplication Program
* Heshan Suriyaarachchi
* Master task distributes a matrix multiply
* operation to numtasks-1 worker tasks.

#include <stdio.h>
#include "mpi.h"
#define NRA 512 /* number of rows in matrix A */
#define NCA 512 /* number of columns in matrix A */
#define NCB 512 /* number of columns in matrix B */
#define MASTER 0 /* taskid of first task */
#define FROM_MASTER 1 /* setting a message type */
#define FROM_WORKER 2 /* setting a message type */

MPI_Status status;

double a[NRA][NCA], /* matrix A to be multiplied */
b[NCA][NCB], /* matrix B to be multiplied */
c[NRA][NCB]; /* result matrix C */

main(int argc, char **argv)
int numtasks, /* number of tasks in partition */
taskid, /* a task identifier */
numworkers, /* number of worker tasks */
source, /* task id of message source */
dest, /* task id of message destination */
nbytes, /* number of bytes in message */
mtype, /* message type */
intsize, /* size of an integer in bytes */
dbsize, /* size of a double float in bytes */
rows, /* rows of matrix A sent to each worker */
averow, extra, offset, /* used to determine rows sent to each worker */
i, j, k, /* misc */

struct timeval start, stop;

intsize = sizeof(int);
dbsize = sizeof(double);

MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &taskid);
MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
numworkers = numtasks-1;

//printf(" size of matrix A = %d by %d\n",NRA,NCA);
//printf(" size of matrix B = %d by %d\n",NRA,NCB);
/*---------------------------- master ----------------------------*/
if (taskid == MASTER) {
printf("Number of worker tasks = %d\n",numworkers);
for (i=0; i<NRA; i++)
for (j=0; j<NCA; j++)
a[i][j]= i+j;
for (i=0; i<NCA; i++)
for (j=0; j<NCB; j++)
b[i][j]= i*j;

gettimeofday(&start, 0);

/* send matrix data to the worker tasks */
averow = NRA/numworkers;
extra = NRA%numworkers;
offset = 0;
mtype = FROM_MASTER;
for (dest=1; dest<=numworkers; dest++) {
rows = (dest <= extra) ? averow+1 : averow;
//printf(" Sending %d rows to task %d\n",rows,dest);
MPI_Send(&offset, 1, MPI_INT, dest, mtype, MPI_COMM_WORLD);
MPI_Send(&rows, 1, MPI_INT, dest, mtype, MPI_COMM_WORLD);
count = rows*NCA;
MPI_Send(&a[offset][0], count, MPI_DOUBLE, dest, mtype, MPI_COMM_WORLD);
count = NCA*NCB;
MPI_Send(&b, count, MPI_DOUBLE, dest, mtype, MPI_COMM_WORLD);

offset = offset + rows;

/* wait for results from all worker tasks */
mtype = FROM_WORKER;
for (i=1; i<=numworkers; i++) {
source = i;
MPI_Recv(&offset, 1, MPI_INT, source, mtype, MPI_COMM_WORLD, &status);
MPI_Recv(&rows, 1, MPI_INT, source, mtype, MPI_COMM_WORLD, &status);
count = rows*NCB;
MPI_Recv(&c[offset][0], count, MPI_DOUBLE, source, mtype, MPI_COMM_WORLD,


#ifdef PRINT
printf("Here is the result matrix\n");
for (i=0; i<NRA; i++) {
for (j=0; j<NCB; j++)
printf("%6.2f ", c[i][j]);
printf ("\n");

gettimeofday(&stop, 0);

fprintf(stdout,"Time = %.6f\n\n",

} /* end of master section */

/*---------------------------- worker (slave)----------------------------*/
if (taskid > MASTER) {
mtype = FROM_MASTER;
source = MASTER;
#ifdef PRINT
printf ("Master =%d, mtype=%d\n", source, mtype);
MPI_Recv(&offset, 1, MPI_INT, source, mtype, MPI_COMM_WORLD, &status);
#ifdef PRINT
printf ("offset =%d\n", offset);
MPI_Recv(&rows, 1, MPI_INT, source, mtype, MPI_COMM_WORLD, &status);
#ifdef PRINT
printf ("row =%d\n", rows);
count = rows*NCA;
MPI_Recv(&a, count, MPI_DOUBLE, source, mtype, MPI_COMM_WORLD, &status);
#ifdef PRINT
printf ("a[0][0] =%e\n", a[0][0]);
count = NCA*NCB;
MPI_Recv(&b, count, MPI_DOUBLE, source, mtype, MPI_COMM_WORLD, &status);
#ifdef PRINT
printf ("b=\n");
for (k=0; k<NCB; k++)
for (i=0; i<rows; i++) {
c[i][k] = 0.0;
for (j=0; j<NCA; j++)
c[i][k] = c[i][k] + a[i][j] * b[j][k];

//mtype = FROM_WORKER;
#ifdef PRINT
printf ("after computer\n");
//MPI_Send(&offset, 1, MPI_INT, MASTER, mtype, MPI_COMM_WORLD);
//MPI_Send(&rows, 1, MPI_INT, MASTER, mtype, MPI_COMM_WORLD);
//MPI_Send(&c, rows*NCB, MPI_DOUBLE, MASTER, mtype, MPI_COMM_WORLD);
#ifdef PRINT
printf ("after send\n");
} /* end of worker */

} /* end of main */

Matrix Multiplication using pthread

Following code shows how pthreads can be used for matrix multiplication. Pthread is a POSIX standard for threads. The standard defines an API for creating and manipulating threads.You can download the code here.

* Matrix Multiplication Program
* Heshan Suriyaarachchi
* Matrix multiplication is done via pthreads

#include <stdio.h>
#include <sys/types.h>
#include <pthread.h>

#define MAX_THREAD 20 /* number of threads */
#define NDIM 200 /* number of NDIMs */
double a[NDIM][NDIM];
double b[NDIM][NDIM];
double c[NDIM][NDIM];

typedef struct
int id; /* identification */
int noproc; /* process */
int dim; /* number of threads */
double (*a)[NDIM][NDIM],(*b)[NDIM][NDIM],(*c)[NDIM][NDIM];
} parm;

void mm(int me_no, int noproc, int n, double a[NDIM][NDIM], double b[NDIM][NDIM], double c[NDIM][NDIM])
int i,j,k;
double sum;
while (i<n) {

for (j = 0; j < n; j++) {
sum = 0.0;
for (k = 0; k < n; k++) {
sum = sum + a[i][k] * b[k][j];
c[i][j] = sum;


void * worker(void *arg)
parm *p = (parm *) arg;
mm(p->id, p->noproc, p->dim, *(p->a), *(p->b), *(p->c));

void main(int argc, char *argv[])
int j, k, noproc, me_no;
double sum;
double t1, t2;

pthread_t *threads;

parm *arg;
int n, i;

for (i = 0; i < NDIM; i++)
for (j = 0; j < NDIM; j++)
a[i][j] = i + j;
b[i][j] = i + j;

if (argc != 2)
printf("Usage: %s n\n where n is no. of thread\n", argv[0]);
n = atoi(argv[1]);

if ((n < 1) || (n > MAX_THREAD))
printf("The no of thread should between 1 and %d.\n", MAX_THREAD);
threads = (pthread_t *) malloc(n * sizeof(pthread_t));

arg=(parm *)malloc(sizeof(parm)*n);
/* setup barrier */

/* Start up thread */

/* Spawn thread */
for (i = 0; i < n; i++)
arg[i].id = i;
arg[i].noproc = n;
arg[i].dim = NDIM;
arg[i].a = &a;
arg[i].b = &b;
arg[i].c = &c;
pthread_create(&threads[i], NULL, worker, (void *)(arg+i));

for (i = 0; i < n; i++)
pthread_join(threads[i], NULL);

/* print_matrix(NDIM); */

int dim;
int i,j;

printf("The %d * %d matrix is\n", dim,dim);
printf("%lf ", c[i][j]);

int dim;
int i,j,k;
int error=0;

printf("Now checking the results\n");
for(j=0;j<dim;j++) {
double e=0.0;

for (k=0;k<dim;k++)

if (e!=c[i][j]) {
printf("(%d,%d) error\n",i,j);
if (error)
printf("%d elements error\n",error);

Monday, May 11, 2009

Monday, May 4, 2009

Setting up NS2 in Ubuntu

1. Download ns-allinone-2.33.tar from here.

2. Place it in somewhere and extract it.
$ cd /home/installations
$ tar -xvf ns-allinone-2.33.tar
3. Download & install some packages from repository.
$ sudo apt-get install build-essential autoconf automake libxmu-dev
4. Install the ns2.
$ cd ns-allinone-2.33
$ ./install
5. Edit paths.
$ gedit ~/.bashrc
Add follwoing lines on that file.


6. Validate it.
$ cd ns-2.33
$ ./validate
7. Create a symlink.
$ sudo ln -s /home/installations/ns-allinone-2.33/ns-2.33/ns /usr/bin/ns
8. Run it.
$ ns

Tuesday, April 21, 2009

Google Summer of Code Accepted Projects Announced

Yesterday I received an email from Google stating that my project proposal for Google Summer of Code 2009 has been selected. I am thrilled of being selected as a GSoC student for Python Software Foundation. I would like to take this oppertunity to thank Jim Baker and Keith Chapman for helping me to iron out my proposal. My mentor for this project will be Matt Boersma. Frank Wierzbicki and Jim Baker will be actively involved in this project as well. I am looking foreward to having a great summer with GSoC.

Thursday, April 2, 2009

Nenapiyasa TV Program on ITN

නැණ පියස TV program is telecast on ITN every Saturday at 5.30 pm. It discusses what is happening in the IT industry of Sri Lanka. Last year we had the opportunity to participate in one of it's discussions on Google Summer of Code. Nishantha and I represented UCSC & Vajira and Hiranya represented University of Moratuwa for this discussion as Google Summer of Code students.

Wednesday, April 1, 2009

Online Sinhala Unicode Keyboard

Although I have been using this for a while, I didn't have a chance to blog about it. It is developed by Language Technology Research Laboratory (LTRL) of UCSC. With the help of this tool you can easily blog or update your status messages in Sinhala.

I'm a SlideShare RockStar - PRANK!

Today, I received an email from SlideShare team stating
Hi heshans,

We've noticed that your slideshow on SlideShare has been getting a LOT of views in the last 24 hours. Great job ... you must be doing something right. ;-)

Why don't you tweet or blog this? Use the hashtag #bestofslideshare so we can track the conversation.

-SlideShare Team

It was the presentation I did for our junior batch on January. Upto now it had 50058 number of views. :) I thought that "would this much of people would want to look at my presentation?"

My stay at the limelight was short lived. Since it was the 1st of April ,I needed to verify whether this was correct or incorrect, before posting the blog. So I went googling to find out whether others have received similar emails from Slideshare. Then found out that it was a April 1st prank.

SlideShare was very useful for me, when I wanted to embed my powerpoint presentations to my blog. It is very sad that they have used a cheap way to market their website like that. In reality they do not have to market their website because everyone who uses SlideShare knows it's true value. In the end the marketing guys of SlideShare managed to tarnish the reputation of SlideShare.

Nice going guys you did great job!

Monday, March 23, 2009

Sahana 2009 Conference

The Free and Open Source Software Community of Sri Lanka is hosting the 1st Annual SAHANA Conference on March 24 & 25, 2009. In its inaugural year, the conference will provide opportunities for anyone involved in Disaster/Emergency management to network and share best practices with each other.

The conference is aptly named SAHANA, meaning Relief in Sinhala and is named after the SAHANA Disaster Management System, which was created as a Free/Open Source software solution in response to the 2004 South Asian Tsunami.

I am planning to attend this conference.

Saturday, March 14, 2009

Problems Associated with Natural Language Processing (NLP)

There are lot of problems associated with Natural Language Processing. Such as,
  1. Prepositional Phrase Attachment
  2. Word Sense Disambiguation
  3. Ambiguity
  4. Ellipsis
  5. Dark Side of Machine Translation
Here is an interesting compilation of cartoons which further helps us to understand these problems.

Friday, March 13, 2009

Google Summer of Code is Back!

Google will be hosting their annual Open Source event this year as well. This will be it's 5th consecutive year. Check out the following video.

Thursday, January 8, 2009

Lexical Analyzers and Parsers

Today I did a presentation to our junior batch mates on Lexical Analyzers and Parsers. It was the final lecture of the course Compiler Theory (before the end semester exams) and Dr. Damith Karunaratne was good enough to lend me a time slot out of his lecture. Similarly I did a presentation on JLex to my batch mates when I was in my 3rd year on behalf of Dr Damith. This time around I added more content on parsers. I gave a demonstration as well. I think the students liked the demo more than the presentation :). I would like to thank Dr. Damith Karunaratne for giving me this opportunity. Thank you sir.

Lexical Analyzers and Parsers
View SlideShare presentation or Upload your own. (tags: dom sax)

Back to Blogging

I have been away from blogging for the last two months due to various reasons :O . Mainly due to University assignments and final year project. I never thought that doing a fourth year would require me to work this much. Anyway I like it :) . So stay tuned to my blog. ahh.... I almost forgot Wish you a happy New Year 2009!