Java : Double dispatch with reflection

March 23, 2012

Double Dispatch pattern is an alternative to using “instanceof” in your code.

Example

Assume this class heirarchy:

Parent -> ChildA
Parent -> ChildB

Assume a class Operator that wants to operate differently based on the type of object (ChildA or ChildB)

Operator {
execute(Parent obj) {
if (obj instanceof ChildA) {  
execute((ChildA)obj)
} else if (obj instanceof ChildB)  {
execute(ChildB)obj)
}

   
execute(ChildA child) {
//do something with A
}

   
execute(ChildB child) {
//something different for B
}

}

Double Dispatch

If you use double dispatch pattern, you move the execute() call to the child objects.


 Operator {
 execute(Parent obj) {
 obj.runExecute(this);
 }
 }
 

 ChildA {
 runExecute(Operator operator) {
 operator.execute(this);
 }
 }
 

But the downside is you have to replicate the runExecute() method above to all child classes.

Double Dispatch with Reflection

If you want to keep the runExecute method at the parent, you can use reflection to get the appropriate method and execute it.


 Parent {
 runExecute(Operator operator) {
 Class clazz = this.getClass();   //This will return the subtype (e.g., "ChildA")
 try {
 Method method = operator.getClass().getMethod("execute", clazz);
 method.invoke(t, this);
 } catch (SecurityException e) {
 } catch (....
 }
}
 

This removes the need to write runExecute in every child class.

A little more

In case the method cannot be found for the given description, you can try the superclass type of clazz and so on.

Supervisor for node.js

March 11, 2012

After developing node.js for a while, I realized that every time I made a change in js files I had to stop and start the node server. It was not required for the .jade files though (as the actual html is built at run time).

So I found this awesome tool nodejs-autostart that will do exactly what I wanted. It will watch all the .js files for changes. And when it detects it, I will restart the node server.

I’m excited about this and I’m sure this will save a lot of my development time in the long run.

The awesome world of node.js

March 11, 2012

I just got bitten by the node.js bug. I’m building a simple web application using my favorite API – foursquare. This exercise is to mainly learn the tools that I wanted to learn for a while and get something tangible at the end.

So I’m building an application code worded “nomad” (named after the coffee shop near my apartment) that helps you find which of your foursquare will have the info about the place you are looking for. Example, if I’m in Mission District in SF on a Saturday night and I want to find a good bar who of my foursquare friends should I ping.

I’m also planning to add some kind of a security layer so that actual checkins of my friends are not stored. That would breach the policy of foursquare api. Anyways I’m not too concerned about it right now. My aim is to use the following stuff in my project.

– Node.js

– Express (framework for node.js)

– CouchDB

– Foursquare API

– fousquare-node module

– cradle (Couch DB module)

– supervisor-node (supervisor module for hot-swapping node.js)

– Deploy app in an AWS instance

I will keep (hopefully) keep posting on some of the cool stuff that I find along the way in building this app.

logrotate : handle log file rotations

January 5, 2012

log files can get very big if not rotated at appropriate periods. logrotate is the tool that usually comes installed w/ Ubuntu boxes to do this for you.

Install logrotate

$ sudo apt-get install logrotate

Configuration

$ cat /etc/logrotate.conf

Usually you may not have to make any changes to this. Explanation for the fields can be see here. Or try man logrotate.

Application specific configurations

$ ls /etc/logrotate.d/

This folder is populated with config files from different applications even if logrotate is not installed on the machine. Example

$ cat /etc/logrotate.d/apache2

If apache2 is installed in the machine, you can see this file has the log rotate policy for all the apache log files.

Cron job

logrotate is not a daemon process. It is added a daily cron job. When everyday it is run, it checks all the log files defined in the config and updates the status file.

$ cat /var/lib/logrotate/status

When “appropriate” time has elapsed, it will create a new log file and rename the old file appropriately. It also gunzips the old file so that the disk space is saved. Its pretty neat and very simple to setup.

Python & Scribe : Setting up logging to Scribe from Python

September 3, 2011

Instructions to setup Scribe in Ubuntu 10.04 and log messages from python.

Scribe is an opensource logging server developed by facebook. It is very robust and can scale across many machines. You can setup master/slave scribe configuration and forward all the logs to one place.

I am working on a python application that has to log messages to scribe. So here we go:

1. apt-get install libboost-filesystem1.40.0 (requirement)

2. Download & Install Thrift (pre-req for Scribe)

3. Download & install scribe.

4. Configure scribe. The default conf file location is /etc/scribe/scribe.conf.

– The port value is important to remember.

– The store section has details of where and how the logs are stored or sent. The primary section is tried first and if it fails for some reason, the logs are sent to secondary. So if you are making the scribe to forward logs to another server, you need to put that info in primary. But also use the local file system as a secondary in case of failure.

– If you are using a file to store logs, the location of the logs is given in file_path. Usually this points to /var/log/scribe/central.

– Most of the default values here  are pretty satisfactory, you would not need to change it.

5. Start scribe.

Start using scribed command. If you have a different config file use -c “filename”.

You can now try and send log statements to scribe using the scribecat command.

$ echo “test message to scribe” | scribecat -h 127.0.0.1:1463 server

Now you can see the /var/log/scribe/central/server/server_current file. The test message should be seen there.

6. Install Python modules for scribe.

There are 3 modules required.

– The thrift python module (This usually gets installed along with the thrift installation)

– The fb303 module. This has to be installed separately. This can be found inside the thrift/contrib/fb303/py. Build the fb303 package fully so that the py modules are built. Then $ python setup.py install inside /py folder.

– Finally scribe python modules need to be installed separately. Don’t use $ pip install scribe. This installs a different scribe module (One of my mistakes). You need to install scribe/lib/py module.

7. Test

Now you have the environment setup and running. Use python and try to “from scribe import scribe”. If successful you have installed all the required packages. Now go ahead and try the sample given here.

HTH

OpenCV : Face detection and Optical Flow

February 20, 2010

OpenCV is the open source library used to perform Computer Vision tasks. The following links would be very helpful if you are looking to do face detection and optical flow in OpenCV.

Face Detection : http://www710.univ-lyon1.fr/~bouakaz/OpenCV-0.9.5/docs/ref/OpenCVRef_Experimental.htm

Optical Flow : http://robotics.stanford.edu/~dstavens/cs223b/

Cryptography : Password based Encryption in Java

February 13, 2010

If you need to use a user password for encryption the PBKDF2 (Password-Based Key Derivation Function) is an RSA standard (PKCS #5) for that. A simple Java implementation for the same is available at http://rtner.de/software/PBKDF2.html.

The PBKDF2 requires a password string, a byte array (salt) and number of iterations (hardening mechanism).

Android : Files as raw resources

February 13, 2010

The additional files that need to be packaged with the apk file has to part of the app resources. For instance, a text file with some information needs to be loaded in with the installed app. Then, keep the file in the res/raw/file.txt. Now in the code this raw file can be accessed by

InputStream fIn = null;

fIn = getResources().openRawResource(R.raw.<fileName>);

Ogre3d : Setup Ogre3D 1.6.5 with VC ++ 2008 Express Edition

January 29, 2010

For step by step setup of Ogre with VC++ Express edition check out the link,

http://www.brighthub.com/hubfolio/matthew-casperson/articles/51992.aspx

Android : Pop ups

January 25, 2010

Easy way to code a pop up window

new AlertDialog.Builder(this)
.setTitle(“<Title>”)
.setMessage(“<Msg>”)
.setNeutralButton(“Close”, new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();