Thursday, December 24, 2009

Singleton Pattern with Lazy Initialization On Demand Holder

This is one of the better ways to implementing a singleton class (class which lets user create one and only one instance).

It uses Initialization on demand holder pattern.


public class Singleton {
private static class LazyHolder {
private static final Singleton instance = new Singleton();
}

public static Singleton getInstance() {
return LazyHolder.instance;
}
}

Tuesday, December 22, 2009

Using Apache Thrift for RPC over TCP socket

Apache thrift is a framework for cross language RPC service/client implementation. Thrift has a small IDL (interface definition language) and comes with an IDL compiler that generates code to be used to easily build RPC clients and servers that communicate seamlessly across programming languages.

First you need to download thrift and then install Cygwin (i used 1.7 version of Cygwin).

Since the thrift is distributed in source form so we first need to build the thrift.exe IDL compiler. Follow this document to generate the compiler exe on windows (mine is Windows 7 home premium x64).

Following is an example usage. We intend to write a C# service and a Java client that implement the following interface (hello.thrift):

namespace java hello
namespace csharp hello

enum Operation {
ADD = 1,
SUBTRACT = 2,
MULTIPLY = 3,
DIVIDE = 4
}


struct Work {
1: i32 num1 = 0,
2: i32 num2,
3: Operation op,
4: string comment,
}


exception InvalidOperation {
1: i32 what,
2: string why
}


service HelloService {

void ping(),

i32 add(1:i32 num1, 2:i32 num2),

i32 calculate(1:i32 logid, 2:Work w) throws (1:InvalidOperation ouch),

string greeting(),

}



Compile the above thrift file with the thrift compiler to generate both java and c# code.



thrift.exe -r --gen java hello.thrift



thrift.exe –r –gen csharp hello.thrift



Following is the service (Program.cs):



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Thrift;
using Thrift.Transport;
using Thrift.Protocol;
using Thrift.Server;
using hello;

namespace thriftcsserv
{
class Program
{
static void Main(string[] args)
{
try
{
HelloServiceHandler handler = new HelloServiceHandler();
HelloService.Processor processor = new HelloService.Processor(handler);
TServerTransport transport = new TServerSocket(34568);
TServer server = new TSimpleServer(processor, transport);

// Use this for a multithreaded server
// server = new TThreadPoolServer(processor, serverTransport);

Console.WriteLine("Starting the server...");
server.Serve();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}

public class HelloServiceHandler : HelloService.Iface
{
public void ping()
{ }
public int add(int num1, int num2)
{
return (num1 + num2);
}
public int calculate(int logid, Work w)
{
int val = 0;
switch (w.Op)
{
case Operation.ADD:
val = w.Num1 + w.Num2;
break;
case Operation.SUBTRACT:
val = w.Num1 - w.Num2;
break;
case Operation.MULTIPLY:
val = w.Num1 * w.Num2;
break;
case Operation.DIVIDE:
if (w.Num2 == 0)
{
InvalidOperation io = new InvalidOperation();
io.What = (int)w.Op.GetTypeCode();
io.Why = "Cannot divide by 0";
throw io;
}
val = w.Num1 / w.Num2;
break;
default:
InvalidOperation io1 = new InvalidOperation();
io1.What = (int)w.Op.GetTypeCode();
io1.Why = "Unknown operation";
throw io1;
}
return val;
}
public string greeting()
{
return "Hello world of RPC using thrift from c# service";
}
}
}
}


And the HelloClient.java is below:



package hello.client;

import hello.HelloService;
import hello.InvalidOperation;
import hello.Operation;
import hello.Work;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

public class HelloClient {
public static void main(String[] args) {
try {

TTransport transport = new TSocket("localhost", 34568);
TProtocol protocol = new TBinaryProtocol(transport);
HelloService.Client client = new HelloService.Client(protocol);

transport.open();

client.ping();
System.out.println("ping()");

String str = client.greeting();
System.out.println(str);

int sum = client.add(1, 1);
System.out.println("1+1=" + sum);

Work work = new Work();

work.op = Operation.DIVIDE;
work.num1 = 1;
work.num2 = 0;
try {
int quotient = client.calculate(1, work);
System.out.println("Whoa we can divide by 0");
} catch (InvalidOperation io) {
System.out.println("Invalid operation: " + io.why);
}

work.op = Operation.SUBTRACT;
work.num1 = 15;
work.num2 = 10;
try {
int diff = client.calculate(1, work);
System.out.println("15-10=" + diff);
} catch (InvalidOperation io) {
System.out.println("Invalid operation: " + io.why);
}

transport.close();

} catch (TException x) {
x.printStackTrace();
}
}
}


Now run the service and then the client. The o/p is as follows:



ping()

Hello world of RPC using thrift from c# service


1+1=2


Invalid operation: Cannot divide by 0


15-10=5



Hope you find this useful. I did not find a direct C# service example but i could easily translate the Java server example to C#.

Thursday, December 10, 2009

JSON-RPC between .NET service and Java client

Recently i experimented with Jayrock .NET library for JSON-RPC and following its tutorial it was very simple to run a .NET JSON-RPC service on my Win7 Home Premium (IIS 7.5). From my earlier experience with JSON-RPC in Java, i wrote a Java client using json-rpc-client library and could get the RPC communication happening without any issue.

The ease with which the code samples worked for the below helloworld-ish sample, motivated me to write about it. JSON-RPC is simpler to debug and implement than SOAP and can be secured by implementing it over https. Most of the time in systems integration all we need is getting the .NET software to communicate with the Java software and in such simpler scenarios where RPC mechanism which is firewall friendly like SOAP is needed then thats where JSON-RPC is a good option.

helloworld.ashx - the JSONRPCHandler



using System;
using System.Web;
using Jayrock.Json;
using Jayrock.JsonRpc;
using Jayrock.JsonRpc.Web;


namespace jayrockserv
{
public class HelloWorld : JsonRpcHandler
{
[JsonRpcMethod("greetings")]
public string Greetings()
{
return "Welcome to Jayrock!";
}

[JsonRpcMethod("add")]
public int sum(int a, int b)
{
return (a+b);
}
}

}




The Java JSON-RPC client:

Main.java:

import org.apache.commons.httpclient.HttpState;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codebistro.jsonrpc.Client;
import org.codebistro.jsonrpc.HTTPSession;
import org.codebistro.jsonrpc.TransportRegistry;

public class Main {
private static final Log log = LogFactory.getLog(Main.class);
private static final String rootURL= "http://localhost/jayrock/helloworld.ashx";
/**
* @param args
*/
public static void main(String[] args) {
// Register HTTP
HTTPSession.register(TransportRegistry.i());
HTTPSession httpSession= (HTTPSession)TransportRegistry.i().createSession(rootURL);
HttpState state= new HttpState();
httpSession.setState(state);
Client client= new Client(httpSession);
RpcIF rpc = client.openProxy(null, RpcIF.class);
String str = rpc.greetings();
log.debug("Output:" + str);
}

}


RpcIF.java:
public interface RpcIF {
String greetings();
}


O/P on client side:

JSON RPC REQUEST ==> {"id":1,"method":"greetings","params":[]}
JSON RPC RESPONSE ==> {"id":1,"result":"Welcome to Jayrock!"}

Saturday, October 17, 2009

No screens found error for X server in Ubuntu Jaunty

I recently encountered an error when all of a sudden after a reboot X server will not start up.


It stated the following:
(EE) intel(0): No kernel modesetting driver detected. (EE) Screen(s) found, but none have a usable configuration.
My configuration at the time of this error was:
9.04 x64, kernel 2.6.28-15-generic, with intel GM965 graphics running xserver-xorg-video-intel:  2:2.9.0~git20091007.03e8e64f-0ubuntu0tormod3~jaunty
First i selected recovery mode to boot into last good configuration.

I struggled with it for a while trying some of the suggestions i could find on google searches. In the process i tried upgrading to the linux kernel 2.6.30-020630 and tried enabling the KMS (Kernel Mode Setting) for Jaunty as described here and that fixed the issue.

Sunday, September 27, 2009

Enabling RDP on Windows Vista Home Premium 64 Bit (SP2)

I found the hack mentioned in this blog http://andrewblock.net/?p=411 work for me pretty well. Am able to RDP from Win XP Pro to my Vitsa Home Premium 64 Bit SP2 with no issue so far.


Update: For enabling RDP on Windows 7 Home Premium, refer to this forum post. It worked for me.

Wednesday, August 05, 2009

Some useful Eclipse shortcut keys

  • Cnrtl + O - show all methods and properties of the current editor's class.
  • Cntl + Shift + O - fix import statements.
  • Cntl + Shift + F - format code.
  • Cntl + 1 - show quick fix recommendations.
  • Cntl + F6 - toggle between editors
  • Cntl + E - show all open editors
  • Alt + left/right arrow - move to last edit location
  • Cntl + M - toggle maximize and minimize current editor
  • Cntl + J - incremental search (searches as you type)
  • Cntl + Shift + J - incremental backwards search.
  • Cntl + K - find next
  • Cntl + Shift + K - find previous
  • Cntl + Shift + L - Shows currently defined shortcut keys (same as Help > Key Assist).
  • Cntl + L - go to line.
  • Cntl + Shift + G - generate getters/setters.
  • Cntl + Alt + G - find text in workspace.

Thursday, July 23, 2009

Eclipse 3.5 Galileo and clearcase plug-in

I installed the Eclipse Galileo recently and found that the Rational Clearcase plugin by IBM does not work anymore in 3.5. Of course the latest plug-in explicitly mentions its just for Eclipse 3.4. But i tried anyways and it did not work. Fortunately, there is a clearcase plugin that works with Eclipse 3.5 at this point (http://eclipse-ccase.sourceforge.net/documents/user_guide.pdf). May be soon IBM clearcase plug-in will also be released that is compatible with Eclipse 3.5.


Updated: IBM Rational clearcase SCM Adapter version is available too now for Eclipse 3.5.

Friday, April 24, 2009

Upgrade to Ubuntu 9.04

I was pleasantly surprised to see the dist upgrade to Ubuntu 9.04 from the previous 8.10 installation going well. It did not work so well last time during upgrade from 8.04 to 8.10. It crashed the root file system for me then. But the lazy me, hoped that it will work this time and it did and upgrade went fine. Web is already replete with praises for jaunty release.

Monday, March 16, 2009

Installing Subversion 1.5.3 on windows

Steps are:

svnadmin create "C:\svnrepo"

  • Edit C:\svnrepo\conf\svnserve.conf and uncomment the following lines:

anon-access = read
auth-access = write
password-db = passwd

  • Edit C:\svnrepo\conf\passwd file:add users in the format username = password one per line and remove the default users.
  • Set environment variable SVN_EDITOR to your favorite text editor (say Textpad.exe).
  • Set Subversion as a service with the following command at cmd prompt:
    • sc create Subversion binpath= "c:\svn\bin\svnserve.exe --service --root c:\svnrepo --listen-port 9999" displayname= "Subversion Repo" depend= Tcpip start= auto
    • Go to service control manager to start the Subversion service or type the following on :
      net start “Subversion Repo”





  • Import an existing project in subversion repo:




svn import C:\myproject svn://localhost:9999/myproject





  • After importing data, note that the original tree is not under version control. To start working, you still need to svn checkout a fresh working copy of the tree.




svn checkout svn://localhost:9999/myproject





  • Install 32 or 64 bit version of tortoise SVN from http://tortoisesvn.net/. After installing you will need to reboot your system. Tortoise SVN is a windows shell extension which makes the use of SVN from windows explorer very easy and intuitive.



There's a standard convention in Subversion to start with the "TTB folders" at the root of any project:



Because Subversion uses regular directory copies for branching and tagging (see Chapter 4, Branching and Merging), the Subversion community recommends that you choose a repository location for each project root -- the "top-most" directory which contains data related to that project -- and then create three subdirectories beneath that root: trunk, meaning the directory under which the main project development occurs; branches, which is a directory in which to create various named branches of the main development line; tags, which is a collection of tree snapshots that are created, and perhaps destroyed, but never changed.

So make it a practice to add the trunk, tags and branches directories to your project and all your project files will go under trunk then.

Monday, February 16, 2009

Introduction to Vim for Programmers

Vim editor:

It has 3 modes:

Ex mode <----> Command mode <-----> Insert mode.

You can never go from Insert to Ex mode directly or vice versa. You always
first need to go to command mode. Enter command mode by typing Esc and enter Ex mode by typing :.

For cursor movement:


k
h l
j
Cursor movement commands: {motion} commands:
G - Last line in file
gg - First line in file
% - Jump to matching brace (()}{[])
m{1etter} - example ma to mark a line. There can be at
max 26 marks in the file.
`{mark} - example `a to jump to the named mark.
`` - Jump to the last line where you jumped or searched from.
/expr - forward search where expr = is a regex.
?expr - backward search.
n - repeat last search in the same direction.
N - repeat last search in the opposite direction.
w - move cursor forward by one word.
b - move cursor backward by one word.
Some more cursor movement commands:
Cntl + F - move one screen forward.
Cntl + B - move one screen backward.
f{char} - position cursor at the matching {char} to the right.
t{char} - position cursor just before the matching {char} to the right.
F{char} - position cursor at the matching {char} to the left.
T{char} - position cursor just before the matching {char} to the left.


Basic insert commands:
i - enter insert mode.
a - enter insert mode after character under cursor.
I - enter insert mode starting before first non blank character on the line.
A - enter insert mode starting after last non blank character on the line.
o - enter insert mode starting on a new line after current cursor line.
O - enter insert mode starting on a new line before current cursor line.


Change commands:
C - delete everything from cursor to end of line.
c{motion} - delete everything from cursor position as determined by the motion (one of the cursor movement commands).
Example:
c5{h}
- deletes 5 chars to the left (as h is for
left movement).
c2w - deletes 2 words and puts in insert mode.
S - Substitute/change current line entirely. Delete all text on current line and put in insert mode.


Patterns for using change commands:
2cw - change 2 words.
cta - delete everything upto next occurrence of letter a.
5cta - delete everything upto 5th occurrence of letter a.
5S - delete current line and subsequent 4 lines.


Miscellaneous commands:
u - undo
Cntl + R - redo
Cntl + N/Cntl + P - autocompletion with text that already exists in the in the document.
. - repeat the last change.
zt - redraw the screen placing current line to top of screen.
zz - redraw the screen placing current line to the center of screen.
zb - redraw the screen placing current line to the bottom of screen.

Delete, cut and paste commands:
D - Delete from current cursor position to the end of line.
d{motion} - delete from current curson position to the position determined by {motion} command. Example,
d5w - delete next 5 words.
dn - delete till next matching search pattern.
d`a - delete till marked line named a.
y{motion} - yank or copy from current cursor position to the position
determined by {motion} command. Example,
y5w - copy next 5 words.
yG - copy till the end of file.
p - put the character in registry/clipboard after current character under cursor.
P - put the character in registry/clipboard before current character under cursor.
dfa - delete until character first character a from current cursor position.
dta - delete upto character first character a from current cursor position.
yy4p - copy current line and paste it 4 times.
dG - delete everything from current line till end of file.
y50G - copy everything from current line till line 50.
d5l - delete 5 characters to the right (l is for right motion).
5dd - delete 5 lines including current one.


Ex mode:
Ex mode commands are of the form:
:[firstline][,lastline]command


Example:
:25,30d - delete lines from 25 to 30.
Line numbers are optional.
If no line number is specified, command applies to current line.
If only one line number is specified, command applies to that line.
To affect a range of lines, we need to specify both firstline and lastline.

Shortcuts for specifying line numbers in Ex mode:
. - current line number. Example- :.,50d - delete from current to line 50.
$ - last line number in file.
% - entire file - same as specifying 1,$.
`a - line number of bookmarked line a.
/expr/ - next line that matches expr.
?expr? - previous line that matches expr.
\/ - next line that matches the most recent expr.
\? - prev line that matches the most recent expr.
\& - next line that matches the most recent substitution.


Examples:
:/Begin/,/End/d - deletes lines from first line that has word Begin till
last line which has word End.

10,40w bkup.dat - saves the lines 10 to 40 in a file bkup.dat.

Essential Ex Commands:
:w {filename} - save the current buffer to filename.
:q - quite the current buffer.
:x - same as :wq - quite and save unsaved data.
:e {filename} - open named file for editing in a new buffer.
:d - delete current line or range of lines
:map {a} {b} - remap the keys used in command mode.
:set {arguments} - configure vim (mostly to be used in .vimrc)
:help - vim help.


Search and Replace:
:s/search/replacement/flags


If search or replacement string contains / character then either we can
escape it with a \ or use a different delimiter (like #) other than / for
eg:
:s#/usr/share/file1#/usr/share/file2/#


Usage examples:
  1. first occurrence single line :s/bash/perl/
  2. all occurrences single line :s/bash/perl/g
  3. first occurrence between line range: :23,100s/bash/perl/
  4. all occurrences between line range: :23,100s/bash/perl/g
  5. first occurrence in whole text: :%s/bash/perl/
  6. all occurrences whole text: :%s/bash/perl/g
Code browsing:
Run ctags as follows in the source directory and it generates an index file
called tags of source files in current directory and its subdirectories.

ctags -R

Now in vim we can use each source file as a web page with each symbol
(variable, function) having hyperlinks, such that, if you do a cntl + ] on
the current symbol then it will take you to the definition of the symbol.

Following are commands for browsing code in vim:
Cntl + ] - jump to the tag under cursor (ie go to definition of function,
class, declaration of variable).
Cntl + T - Return to current tag from most recent jump off point.
:pop - Same as Cntl + T except that we can specify count to go back
multiple levels.
:tn - Jump to next match (when tag produces more than one match in
case of C++ overloaded functions).
:tp - Jump to previous match (in case of multiple matches).
:ts name - Shows a list of matching tags you can select from.
:tags - Show current tag stack with one line for each tag.

Lastly, to build c/c++ code:
:make {args} - invokes the make program. We can change the make program in to say ant by using Ex mode (or in .vimrc) as
:set makeprg=ant

One nice .vimrc can be found at:
http://research.iiit.ac.in/~masatran/config/.vimrc

Use
wget http://research.iiit.ac.in/~masatran/config/.vimrc
to get it.