Saturday, October 24, 2015

WSO2 ESB: Polling a database for changes

WSO2 ESB has DBLookup mediator to read data from a database. But in some cases, you may need ESB to keep polling a database and proceed with some operations only if there's a change in it. Although this is not supported out-of-the-box, we can easily write a simple class mediator to implement this requirement.

One problem that arises when doing this is that there's no way to keep a value in-memory across multiple messages, since the properties used in ESB artifacts are local to the message context. To overcome this, we can consider two options:
  1. Writing a class mediator that keeps the last read value in an instance variable and performs any comparisons required to identify changes in the database.

  2. Simply store the last read value to another table/field and compare it with the current field (this requires multiple DBLookup/Report calls).

In this blog post, we'll explore how we can implement the first option.

So the basic flow will be:
  • A scheduled task keeps calling a sequence
  • In the called sequence, we have a DBLookup mediator that fetches a field from a database table (includes a column that indicates a change, such as a timestamp)
  • The change indicator field is extracted and added to a property
  • Class mediator is called, it compares the property's current value with the previously stored value and sets the result (changed or not) to another property
  • With a filter on the resultant property, we can identify a change and proceed with necessary operations

A sample configuration is as follows.

The scheduled task that keeps calling a sequence:


The sequence that does the DB lookup and identifies if there's a change:


Sample code for the class mediator used in the above sequence can be found here.

Wednesday, October 21, 2015

WSO2 ESB: Transferring data from files to a database

In some integration scenarios you may want to use ESB to poll a directory for files and store the content to a database.

Following steps can be used to read CSV files from a directory, extract their data and then store them in a database.

We use a VFS proxy to poll the directory and look for new files. The parameters transport.vfs.FileURI and transport.vfs.FileNamePatter are used to indicate where/what types of files to look for (any regular expression can be used here).
Once a file is read, we need to convert it to a format that is supported by the DB Report mediator of the ESB. In this case we convert the csv data to xml using the Smooks mediator.

Once the conversion is done, we can easily use the converted xml data inside the DB Report mediator to enter them to a DB with XPath expressions.

In addition, we can specify some actions such as where the file to be placed (or deleted) after storing in the DB (transport.vfs.ActionAfterProcess),  what actions to be taken if a failure occurs (transport.vfs.ActionAfterFailure) etc

The complete proxy configuration is given below. Please note that you have to enable vfs transport in axis2.xml in order to get this working.

In addition to the above proxy, you have to add the smooks-config xml file to the location specified in the proxy configuration. The smooks configuration for this sample is as follows:

You also need to add a local entry to the esb configuration to point to the smooks config file. (the above proxy configuration points to this local entry key for smooks configuration)

Thursday, September 17, 2015

Switching from HTTP/HTTPS to VFS in WSO2 ESB

In some cases, there can be requirements to transfer some content arriving through the HTTP transport to an FTP/SFTP location synchronously and then acknowledge the http client with the status of the transfer. This can easily be accomplished with a proxy similar to the following in WSO2 ESB 4.8.x.

Here we use the OUT_ONLY property when calling the VFS endpoint since we are not going to receive a response from it. We use the call mediator to synchronously call it. Also we append retry counts and and reconnection timeouts to the VFS URI to retry transfer in case the endpoint is temporarily unavailable. Finally we build a payload with the status and send it back to the client using respond mediator. 





Saturday, January 31, 2015

Disabling http access logs in WSO2 CEP and other carbon products

When you use the http input adaptor of CEP 3.1.0, after some time you may notice that the http access log files are growing large when there are frequent http requests.  (this happens when we use the servlet transport, hence this does not apply to ESB and other products with synapse engine)

You can disable the http access logs as follows:
Goto repository/conf/tomcat/catalina-server.xml. At the bottom part of the file, you'll find an entry like following
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="${carbon.home}/repository/logs" prefix="http_access_" suffix=".log" pattern="combined" />

Comment this out or remove this entry to disable the access log and restart the server.

Sunday, March 31, 2013

Writing a Relational Database broker for the WSO2 Complex Event Processor


WSO2 Complex Event Processor (CEP) has a pluggable architecture where users can write and plug 'brokers' to send events from an event source to CEP engine and also receive output events from the CEP engine and send them to an event sink. Currently there are quite a few broker types available with the CEP supporting JMS, WS-Events, Email etc. If you want to persist events in a relational database, here's how you can achieve it by writing an RDBMS broker.

There are two classes you have to extend in order to implement a custom broker.

    1. org.wso2.carbon.broker.core.BrokerType
    2. org.wso2.carbon.broker.core.BrokerTypeFactory

These classes are available in org.wso2.carbon.broker.core package which can be added as a maven dependency as follows:

<dependency>
    <groupId>org.wso2.carbon</groupId>
    <artifactId>org.wso2.carbon.broker.core</artifactId>
    <version>4.0.7</version>
</dependency>


Depending on the RDBMS vendor you are going to support, you'll have to add a dependency to the relevant JDBC driver as well. Here for this example we will be using the MySQL driver.


<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>


BrokerType implementation class contains the methods that will receive events from the CEP engine. It also has a way to define the broker specific configuration parameters (such as database host ip/username) that will be available in the web console at runtime.

Out of the methods in BrokerType, you'll have to implement following two methods.

1. getBrokerTypeDto() - this should return the BrokerTypeDto object that contains the required configuration parameters for the Broker.

When implementing getBrokerTypeDto(), you should populate the BrokerTypeDto with all the parameters that are going to be adjusted at runtime. Here's an example how you can add the hostname field so that user is asked to fill it when configuring a new broker.


    Property hostName = new Property(“Hostname”);
    hostName.setRequired(true);
    hostName.setDisplayName(“Host name”));
    getBrokerTypeDto().addProperty(hostName);

2. publish(String topic, Object message, BrokerConfiguration brokerConfiguration) - this is where the output events from the CEP engine will be received and written to the database.

The parameter 'topic' used here maps to a database table name and the user can give it when configuring a new CEP bucket. The 'message' parameter will contain the output and if you choose the output mapping to be 'Map mapping' (which is again available at the time when configuring a new CEP bucket), you will receive a java.util.Map with all the output key/value pairs. The brokerConfiguration contains all the configuration parameters you requested in the getBrokerTypeDto() method, including hostname, username etc. The first thing you have to do here is to check whether the given table exists and create a new one using the topic name if it doesn't already exist. You can infer its column names and data types by examining the Map received. Once it is done, you can simply create an statement and feed the values to the table.

BrokerTypeFactory, as its name implies, is responsible for creating/providing BrokerType objects. All you have to do here is to implement getBrokerType() method to return an instance of the BrokerType implementation class.

Once you complete writing the code, package it and put the jar file into repository/components/lib folder. Also remember to add the JDBC driver to the same directory. Then put an entry to repository/conf/broker.xml as follows (create a new broker.xml file if it does not exist):


    <brokerTypes xmlns="http://wso2.org/carbon/broker">
    <brokerType class="org.wso2.cep.broker.RDBMSBrokerTypeFactory"/>
    </brokerTypes>


Now start the server and select 'Configure' in the web console. When you select Broker -> Add, you will see that the newly deployed broker is listed under the 'Broker Type' dropdown. You can configure the broker instance from there.

An example implementation can be found here.

Thursday, February 9, 2012

International shipping for Amazon, eBay and other U.S.-only shipping sites

Some popular online merchants like Amazon and eBay often have products with restricted delivery to U.S. only.

If you live outside U.S. and want to buy any such item, here's how:

- Register yourself at a mail/package forwarding service. Some of the popular sites include: MyUS.com, Shipito.com and BongoUS.com.

- They will ask your current address and you may have to pay a small fee for registration. Once the registration is complete, you will receive a U.S. address from them. This is actually their address with your name assigned to it. So it can be used as your own residential address to receive anything from mail/couriers.

- Now you can buy anything from Amazon/eBay and others without bothering whether it has worldwide shipping or not. Just use your newly received US-address as the shipping address.

- Whenever the forwarding service receives any mail/package to your name, they will forward it to your real residential address. You'll have to pay a handling fee to them with the postage/courier fees.

I tried this once recently and it worked fine. Items arrived within a week as the forwarding service sent it via a courier. Note however that this can sometimes be costly and not worth it for receiving cheaper items.

Sunday, October 30, 2011

Tuesday, June 14, 2011

BitTorrent over HTTP

Sometimes your computer may be behind a proxy, or your ISP may be blocking bittorrent traffic, making you unable to use P2P bittorrent protocol. Torrific provides an awesome solution for such situations. This website accepts a link to a torrent file and then almost in no time they expose the contents of the torrent as direct HTTP downloads free of charge. It's still in Alpha stage, but worked fine for all the files I downloaded so far.

Thursday, February 17, 2011

Math puzzles to beef up your brain

Today I accidentally came across a few interesting math puzzles and tried to solve them. Here's one which put me in trouble.

"The following is what seems to be a mathematical proof that ten equals 9.999999.... What's wrong with it?

               a =  9.999999...
10a = 99.999999...
10a - a = 90
9a = 90
a = 10 "


You can find more puzzles here - many of them are straightforward though.
Give it a try. Good luck!

Friday, January 7, 2011

Project epZilla - recent events...

After a couple of months of silence, events are happening once again for Project epZilla. This time, we've moved the official project website to http://www.epzilla.org.

We've also updated the website with more recent happenings, including our paper presentation in ICTer 2010 conference held in Colombo. The paper we presented - 'Scalable fault tolerant architecture for Complex event processing systems' is now available at IEEE Xplore digital library.

Saturday, December 4, 2010

Solution to the Lenovo G530 Display flickering problem

I've been using a Lenovo G530 laptop for more than an year now. Recently it started having some display problems. The display started to flicker at random intervals, especially when playing videos. Initially it was not irritating as it occurred only rarely until the last week. However during the last few days it occurred so frequently that I just couldn't watch any videos, so I was trying to diagnose the problem.

I was a bit disappointed as the symptoms suggested that the problem can most probably be with the video adapter, which requires replacing of the main-board.

I found a solution to a similar issue posted as a comment to a review here, which says that the problem occurs when the video cable running from main-board to the display loosens. However, I was not quite sure whether it is the same problem my laptop was having, since the problem often occurred only when playing full-screen videos. So to figure out where the problem was, I plugged an external monitor to the laptop and tried playing a video. The monitor was displaying it smoothly while the laptop's display was continuously flickering. Obviously, the problem was not with the video adapter, but with either the LCD display or the video cable running from main-board to the display.

The video cable starts from underneath the keyboard, so I disassembled the power-board, key-board and reseated the display cable and tested whether the problem is still there... Luckily, it was no longer there and now it is working without any problems!

I found that many G530 users are having this problem and many of the forum posts asking this question don't have the correct solution mentioned. If you've also faced such an issue, you'll find this forum post really useful.

Tuesday, April 6, 2010

Moving to Airtel HSPA

I've had a Dialog Mobile Broadband (HSPA) connection for an year now. I don't have much to complain about its connectivity issues like most of the others do. But definitely I'm not satisfied with their service....It's too costly for what they offer.

They have a very unreal fair usage policy - After the downloads exceed 5GB, the speed goes down to 384kbps and then after 6GB....it becomes 64kbps! That's totally useless stone-age connection and it always remembers me how I went online in 2002 with a dial-up modem. What can you accomplish with a 64kbps dial-up like connection?

I waited for some time thinking that they will change their FUP to be more practical, but it never seemed to happen. Now that the time has come for a change and today I bought an Airtel HSPA connection. Here are the speeds they promise they are offering:

Downloads upto 10 GB -> 1.8 Mbps downlink (384 kbps uplink)
10 GB - 40 GB -> 512 kbps downlink
40 GB onwards -> 256 kbps downlink

This looks to be a much more usable connection compared to the Dialog's one. Both connections have the same tariff rates. I haven't tested the connection yet.... But hope this will produce a better Mobile Broadband experience.

Monday, March 15, 2010

Simple stuff missing in .NET and Visual Studio

I'm a Java programmer, but today I had to deal with C#.NET to create a simple Windows Forms application which had some mathematical and algorithmic stuff.

I've heard a lot of positive comments about Visual Studio, but what I experienced today was not up to the level of usual praises it gets from a lot of developers. Compared to IntelliJ IDEA, which is my favorite IDE, there are several stuff missing in Visual Studio (2008 edition). First thing was auto-complete. Of course it does have a reasonable auto-complete facility, but it's partial (at least with the default settings - I don't know whether there's a way to change it). Whenever a method name is completed, we have to manually code '(' and ')' parts of the method call, which I found a bit inconvenient. The same seems to be the case with strings, once I open a double-quote, the IDE doesn't automatically close it - it's inconvenient when there's a lot of such coding to be done.

Second noticeable thing was that most often it doesn't automatically point out the coding errors unless we build it manually, this is troublesome when there's a lot of coding to be done. Then there was no way of altering editor's background color - it's set to bright white by default and can be really troublesome for the eyes in the long run.

Finally, the most weird part, I wanted to use a Hashtable to have access to some values using keys. I defined one and then wrote code to add a lot of stuff. Then when I was looking for a method to retrieve them based on keys......there was no such simple method retrieve elements like in Java's Hashtables. (there was a method to check whether an item exists, but can't fetch it directly - how terrible is it?) After a Google search, I found a lot of articles teaching how to fetch an item in C# Hashtable - iterate through all elements....! This is really useless and a terrible hashtable implementation I've ever seen. Of course they might have written efficient methods to put stuff (I assume at least those Add methods are efficient), but there was no efficient or an easy way of retrieving them back. For algorithms which have a lot of get calls rather than inserting elements, this will cause unnecessary overhead.

Although I have no idea of moving to .NET, hope these will be fixed in upcoming Visual Studio 2010 edition.

Sunday, February 14, 2010

Is 'private' really 'private'?

I've got the following Java class with private methods.

class ClassX {

private void methodX() {
System.out.println("methodX: this is private.");
}

private void methodY() {
System.out.println("methodY: this is private.");
}
}


How to invoke these methods from an outside class without modifying this code?
If you've studied Java, you might have learnt that it's impossible.

Truth is, you can access anything from anywhere.
Just use Reflection.

class Main {
public static void main(String[] args) throws Exception {
ClassX cx = new ClassX();
Method method = ClassX.class.getDeclaredMethod("methodX", null);
method.setAccessible(true);
method.invoke(cx, null);
}
}

All you have to do is to take the method using 'getDeclaredMethod', then set it as 'accessible' (previously it was not accessible since it was private). Now you can do any damn thing with it. How simple is it?

Still not enough? You can iterate through all declared methods in a class. (in case it is a compiled one and you don't already know what private methods are there)

Method[] ms = ClassX.class.getDeclaredMethods();
for (Method m: ms) {
System.out.println(m.toString()); // see what it is.
m.setAccessible(true);
m.invoke(cx, null); // invoking each method.
}

You can do the same thing for variables as well.

Is 'private' really 'private'? No.
Then how to make something really 'private'? Who knows?
That's not the important point here. If you don't know about reflection, then go ahead and learn it. Reflection is what enables real 'dependency injection' in Java.

Sunday, December 20, 2009

Total Freedom

Recently I accidentally found a completely new software license called WTFPL. It is a license which is dedicated to deliver true freedom and to make the lives of the people easier.

Initially I thought this was something created just for fun, but that was not the case. I found several real open source projects licensed under WTFPL. :D

At a glance, it appeared to me as this license should be compatible with most of the other licenses as it allows you to do whatever you want (I'm avoiding the original way used by the license creator to say this :P).

When I first read GPL and BSD license statements, I couldn't understand anything. I had to find articles written in simple language which explain what the licenses were all about. But this is much more simpler. Obviously, this is the first license I understood at the first glance. :P

So if you're concerned about giving total freedom to the users/developers, then WTFPL is something you should consider when you decide a license for your project. Seriously.

Wednesday, November 25, 2009

Microsoft Fonts for Firefox on Ubuntu...

When I first started using Ubuntu, I found that the default fonts come with its Firefox are a bit difficult to read. By default, Ubuntu doesn't have popular Microsoft fonts such as 'Times New Roman' pre-installed. So the first task I did was to install Microsoft True Type core fonts bundle on Ubuntu. It can be done with a simple apt-get command as following:

sudo apt-get install msttcorefonts


This installs all the required Microsoft fonts. Then all I had to do was just to change the font settings in Firefox to be similar to Firefox on Windows.


Preferences -> Content

Default Font: Times New Roman
Size: 16

In Advanced Settings:

Fonts for: Western
Propotional: Serif Size: 16
Serif: Times New Roman
Sans-serif: Arial
Monospace: Courier New Size: 13


Note that these settings are similar to Firefox on Windows 7.
That's it.

Thursday, October 29, 2009

Progress of epZilla

I'm involved in doing a research on a scalable and a fault-tolerant distributed architecture for complex event processing (epZilla) as my final year undergraduate project with three other colleagues. So far it has been all research and no coding, which makes life a bit harder for us coz we are not very good readers and also it makes life even harder in evaluations by the department since we don't have anything other than some research papers and some ideas and concepts in mind which doesn't seem to be very much convincing for the evaluators.

So far we have read several dozens of research papers on many related areas and now about to finalize the architecture. Meanwhile we are about to start some coding even before we finalize the architecture since we gotta have something working before the next evaluation - for demonstration purposes.

I'm posting this here so that I can look back later and find how our project evolved.

Monday, September 21, 2009

Ideas from Code Jam....

Recently, I accidentally got to know about Google's Code Jam competition. After getting to know that it is an algorithmic problem solving competition, I decided to give it a try. I've never had much experience in this area, so I did not have any hope of advancing to the semi-finals or finals but thought that this is a good opportunity to sharpen thinking ability.

I got through the qualification round with ease as it contained two problems which could be solved without knowing any advanced problem solving technique. But for the next round, it clearly appeared like knowing only to solve number theory, brute-forcing/backtracking and ad-hoc problems wouldn't help. So I Googled a bit to find what to learn.......and found several problem type classifications which were based on different programming competitions. Here's Hal Burch's classification based on ICPC which is somewhat applicable to Code Jam too:

  1. Dynamic Programming
  2. Greedy
  3. Complete Search
  4. Flood Fill
  5. Shortest Path
  6. Recursive Search Techniques
  7. Minimum Spanning Tree
  8. Knapsack
  9. Computational Geometry
  10. Network Flow
  11. Eulerian Path
  12. Two-Dimensional Convex Hull
  13. BigNums
  14. Heuristic Search
  15. Approximate Search
  16. Ad Hoc Problems

Of course, many of these types can be solved using simple brute-force algorithms, but they will end up taking a few million years to give you an answer for some of the inputs..... so definitely you need to learn some efficient and easy to implement techniques to tackle such problems. The best resource I found for this is TopCoder's algorithm tutorials, which contain no-nonsense and easy to understand tutorials on most of these areas.

Having said that, I should now come to the point.......that is, some of the smart tricks used by the competitors in this Code Jam competition. One is that, since the solutions are executed in competitor's mahine itself, it gives competitors the ability to generate all solutions to a problem using brute-force which might take a couple of hours (before downloading the input, coz once you download inputs you'll have only 8 minutes to solve them), save it, then download the actual input and then just lookup the already generated results to directly find answers to the input. No DP, no efficient algorithms, but still perfectly legal and effective! (if your computer has enough processing power). I actually found a few guys who had advanced to round 2 using this technique.

Second one is writing multi-threaded programs. It feels like a crazy idea trying to implement a multi-threaded algorithm.....but think about it.....you might have a Core 2 Duo processor, if you write a normal inefficient algorithm, it will execute on only one core.....and your program might take 8 minutes plus a couple more seconds to execute and you'll be out of the competiton. What a waste.....you might have implemented the same program to have multiple threads and execute over both cores and could have solved it within 8 minutes! (this is a rare case, but actually happened in Round 1A - Problem A) Now some of the competitors are interested in writing toolkits to provide concurrent execution over all cores they have on all computers at home, be it a desktop computer, a laptop or a netbook. What a fantastic idea!....they've turned this competition into a concurrent programming competition too. By the way, I have only one single-core machine at home, so I'm trying to find an online supercomputer service which can offer some computing time for me to execute my horrible brute-force programs to advance to the next round :) Just another different idea ;)

Anyway, the competition is getting fierce....so there's a very little chance (most probably no chance at all) to advance through round 2 (which takes only top 500 contestants). But if you too give it a try, you'll certainly discover some fantastic techniques to tackle problems.