Sunday, December 28, 2008

Congratulations Kashmir

Congratulations for reaffirming democratic values in the state of Kashmir. After the height of militancy the first elections saw 10% of turnout, this time it was 63% well over the national average across states. Its not about being pro-India or pro-Pakistan or pro-freedom. Not all democracies of the world are pro-India and not all Islamic nations are pro-Pakistan but it was important for Kashmir to show that they still cherish the democratic system and its values. Mere the fact that majority has rejected the Jehadi color of the movement is a victory of Kashmiri people that has been strengthened by a call of introspection from the separatist leaders like Sajjad Lone and Mirwaiz. A strong showing of BJP in Jammu is also a reminder to the state legislation not to ignore this region and be used in pity politics. Congratulations to the young chief minister of the state Omar Abdullah as well for bringing in welcome change overdue to the state of Kashmir.

Friday, December 26, 2008

Don't we just love Pakistani Foreign Ministry?

01. Elements in Pakistan abetted, trained and sent terrorists to Orchestrate Mumbai massacre.
02. Refuses to accept the lone captured terrorist is from Faridkot Pakistan.
03. Refuses to accept the plea of that terrorist for legal help.
04. Cordons off the village from media where the captured terrorist hails from.
05. No concrete steps to punish responsible groups and closing the terror camps.
06. Creates war hysteria.
07. Blames India for Lahore blast which with in days claimed by a Pro-Taliban group.
08. After international pressure black mailing the world by mobilizing troops from Afghanistan to Indian border (Has been their trump card for years).
09. Their Airforce running low sorties creating panic among Pakistani people and building anti-India sentiments.
10. And, their national leaders passing inflammatory comments against India.
So commit the crime and then scream you were a victim. BS! And what the world is doing? Sleeping?

Wednesday, December 24, 2008

Please save this kid Tiger

A two and a half year old Tiger has been ordered to be shot dead by UP Govt, India. Reason? He has turned a man eater. This Tiger had sneaked out of it's habitat about a month ago and has been meticulously avoiding any effort to nab him since. Sadly he killed one teenager last week in search for food. If a lethal bullet can be fired so can a tranquilizer. This is a plea to wild life officials to not kill this magnificent animal. If we do not have guts to kill the hyenas who masterminded killings in Mumbai, why can't we have mercy on this little four legged Terrorist who has no guns? Be a human not an animal.

Tuesday, December 23, 2008

Coyotes in back yard

Sunday, December 21, 2008

Discovering Processor in Coherence - Part (II)

In the part (I) of this blog I touched a concept of managing the processing components in Coherence cache. In part (II) I am introducing a half-cooked implementation where agents can be looked up and downloaded in Coherence. The idea is to construct an infrastructure where Enterprise components can advertise their services on a lookup service and these services can then be downloaded and executed in Coherence grid. This implementation uses Jini with Oracle Coherence. The component targeted is EntryProcessor with some customization to manage java.rmi.Remote requirement for Jini and keeping it away from Coherence. I have uploaded probably a 70%ish implementation on Miscellanous Components site. The project is built using jDeveloper11g and requires coherence.jar and Jini2_1 libraries. It is still incomplete from where it has to go but has ample food for thoughts.
Components used:

  1. A Custom Cache
  2. Jini2_1 for discovery
  3. InvocableMap APIs to customize EntryProcessor
  4. And Coherence Infrastructure

Sunday, December 14, 2008

In defence of Bush

Being disliked at home and getting thrown a pair of shoes in Iraq - the focal point of his foreign policy, I am sure are enough reasons for any common man to go in depression and of course with depressed economy it is not good to be George Bush. But as human nature goes we forget the intangibles. Once we get a Wii to play with we forget what effort it took to get one. Look around people. Some parts of the world live under constant fear of terrorism. What happened in Mumbai is a reminder that we are not safe yet. Only stupid will question the intent, resolve and wish of organizations that attacked us to do it again. Lets not forget not a single terrorist attack has occurred in past seven years on the soil of United States of America. And don't you think that credit goes to Bush? In wave of our own anger lets not forget what good this Man has done for us. I am sure the Guy who threw shoes at Bush must have forgotten what if he had done the same to Saddam. Whether we like Bush or not but he does not deserve this hatred either by an American or an Iraqi. I hope he is remembered in history as a man of resolve who cared about his country more than he cared about himself.

Friday, December 12, 2008

Softer part of Software Architecture

Or the harder part the way you look at it. Almost 90% of applications does the following in some form or the other.

  1. Bring message (data) from one system to another.
  2. Transform the data in a form that your system recognizes.
  3. Process the data
  4. Making it available for reference
  5. Send it to another system
  6. Archive it
Critical things to consider:
  • How many components do we introduce between each of these steps?
  • How much latency does each component introduce?
  • How many jars/libraries would you need to get this system to work?
  • Can I upgrade one layer without affecting others?
  • How many systems do you need to configure?
  • If one system is unavailable can others survive?
  • How platform independent is one system from another?
  • Can we have single script/single click deployment process?
  • How many people would you need and of what different skill set?

Tuesday, December 09, 2008

Discovering Processor in Coherence - Part (I)

Besides a strong support for event driven architecture Oracle Coherence has a concept of processors running inside the grid. One construct that makes Coherence programming a little different is its ability to invoke light weight processes inside the grid instead of bring data over the wire and then processing it. To do so the application has to pass an agent to the cache that gets executed on the data. It is not necessarily required to pass a fully implemented one though.
Problem statement: To have an ability to change the implementation of the processor on the fly and without having to re-deploy it.
Following approach is inspired by Coherence's Command Pattern but lets start from the beginning. We need to create a common interface that all commands need to implement:

public interface Command extends Serializable {
public Object process (Object object);

These are the commands that will be looked up instead of being passed an instance of. Lets have a few implementations:
public class MyLogger implements Command {...} and,
public class MyProcessor implements Command {...}

We need a place to put these commands in.
<!DOCTYPE cache-config SYSTEM "cache-config.dtd">
<autostart>true </distributed-scheme>

Now how to execute these commands in such a way that execution logic can be changed but executor does not? I like Map Listeners because it can be attached to a cache in multiple ways and also provides a framework for auto-processing.
For the sake of simplicity lets implement the following logic: For each entry put in the cache run a process on that entry but process that can be changed. Listener will look something like:
public class DiscoveryListener implements MapListener {
private String cacheName;
private static NamedCache dCache;

static {
dCache = CacheFactory.getCache ("Command");

public DiscoveryListener(String cacheName) {
this.cacheName = cacheName;

public void entryInserted(MapEvent mapEvent) {
Command command = (Command)dCache.get (cacheName);
Object value = mapEvent.getNewValue();
if (command != null) {
command.process (value);

And of course load the processors in the command cache:

NamedCache cCache = CacheFactory.getCache ("Command");
cCache.put ("cache1", new MyLogger ());
cCache.put ("cache2", new MyProcessor ());

And, depending on the cache the listener is attached to it will run the corresponding command. What it gives you an ability is to change the MyLogger () to SomeProcessor () for a cache on the fly and the rest of the application remains agnostic.
What's next?
Problem statement has still not been fully implemented.
  1. We still need to deploy all the processor classes and has to be available at the deployment time. This has to change.
  2. Why to use the Command interface? Could it be something else?
  3. Who puts the Commands in the Command cache? Can we have a Command feeder? An external controller that dictates what gets executed?

Saturday, December 06, 2008

Why using static block for Singleton will not work in all cases

Probably everyone has used Singleton pattern and following is a typical implementation:

public class Single {
private static Single single;

// -- Rule#1: Make sure no one outside the class could call new
private Single () {

// -- Rule#2: Provide another channel to get an instance
public static Single getInstance () {
if (single == null) {
synchronized (Single.class) {
if (single == null) {
single = new Single ();
return single;
I came across another implementation that to be frank I never thought was used to implement singletons.

public class Single {
private static Single sing;

static {
sing = new Single ();

private Single () {

public static Single getInstance () {
return sing;
Even though its a tricky way but bluntly this is a wrong implementation for one simple reason: It does not work if the class is lazily loaded (Class.forName ("Single");) and constructor takes a parameter. So I would rather continue to stay with a good old implementation.

Saturday, November 29, 2008

I pity Zardari

Every time a civilian government takes an oath in Pakistan, Indian establishment takes a sigh of relief in hope things can be normal again. But an assumption of Government being in charge also makes it complacent. Last time with Nawaz Sharif its Army orchestrated Kargil intrusion. This time with Zardari, elements in it's intelligence did the Mumbai massacre. Actually its been pity being head of a civilian government in Pakistan. A head who does not know what goes on under his nose. Mr. Zardari we know its tough but its really sad and pity. I am sure it does not feel good to be in control of only 1/3rd of the country and your own intelligence and Army bosses running a parallel government. Its pity it is. It also shows when you made an U-turn on sending your ISI chief to Delhi to assist after promising it on phone. India I am sure does not know who to blame and talk to? It does not know how many Pakistans it is dealing with. One face of Pakistan appears to be a friend but not in control. Others actively engaged in terrorism with help of under world Dons enjoying state hospitality in Karachi for years. No one could believe that a huge stock of arms and ammunition and trained men were dispatched to Mumbai without involvement of your own intelligence agencies. And if it happened without you knowing it is really really sad and dangerous. We had very high hopes from you but are disheartened to find if you are even in control of your country but still expect you to strengthen the hand of friendship that was extended after your election. Don't make our hope short lived.

Thursday, November 27, 2008

There can't be any reason for terrorism

As humans we are all animals. But we are also blessed with brains capable of making sure that the world does not become a jungle. After what happened in Mumbai I am sure there will be a series of finger pointing to follow. But it only proves that the threat of global terrorism is still serious and refuses to die. Global terrorism is not only directed towards British and American citizens but are also that are planned, funded and coordinated from across the nation's borders. The news has already been coming out that Mumbai attacks were planned and executed with the help of groups based in Pakistan. Also comes a new phenomenon of hijacking a civilian trawler in high seas and then using it to launch an attack, a tactic that challenges security apparatus of any nation. This is a high time for countries to make a decision if they want to be part of a civilized world or choose to being a failed state. Pakistan has a new civilian administration and an onus wrests on them to make this decision. If not a direct involvement of its government but terrorist groups still operating with complete impunity with help of its intelligence agencies is not a sign of trust that two neighbors must have. A world can only be a better place when everyone works together for its better future not by sponsoring mad killings of innocent people.

Sunday, November 23, 2008

Saturday, November 22, 2008

Toplink10g to Eclipselink Migration

No brainer and Toplink team has done a great job to make it very simple and a matter of running a script. Even though the steps are clearly documented on but you may run into some gotchas. Some of the very advanced Toplink mappings use amendment methods and post insert, build events etc. These information are stored in Toplink's classes and descriptors XML files. The migration scripts of Eclipselink does not replace these classes even if the mwp file is successfully opened in the workbench. The solution is very simple.. Replace all classes starting with package name oracle.toplink to org.eclipse.persistence under the classes/ and descriptors/ directory of the Toplink workbench. And following script can be handy as well:

for i in `ls *`
sed "s/$1/$2/g" $i > t;
mv t $i;

Saturday, November 15, 2008

Timer service in Oracle Coherence

It would be nice to have a Timer Service that runs inside a Coherence Cluster and can execute pre-established Jobs at a certain time of a day, everyday? Such a component can be written as a separate application or configured inside Coherence. Not off-the-shelf available but I have uploaded a simple Quartz based implementation on Miscellaneous Components website. Please read More...

Thursday, November 13, 2008

Managing a collection of data and running Query By Example with Coherence

Problem (1): Coherence NamedCache extends java.util.Map i.e, the data to be managed in the cache must be in a <key>, <value> pair. One of the challenges to manage just a Collection of keys or elements in a cache is to associate these keys with some values. If Values are not given we need to use a Serializable Object that can become it's values (or Nulls). So your collection {a, b, c ..., z} becomes [{a, <o>}, {b, <o>}, ... {z, <o>}] with o being:

public class o implements Serializable { }
Problem (2): Running Queries against the Keys. Coherence supports KeyExtractor that extracts attribute values from cache keys instead of on the Values. The Filter will look like filter = new EqualsFilter(new KeyExtractor("getAge"), value); that matches if the getAge () method of a cache key Object is equal to the value.
Problem (3): Query By Example. This is another challenge. Coherence cache supports Filter mechanism that can be run on existing value for its attributes. Out of the box there is no mechanism that can parse Query By Example. QBE means an Object with partial attribute set is passed to find out all or any cache keys that have same attribute values. Lets introduce a Discoverer class that has following:
protected Filter getFilter(String method, String value) {
Filter filter = null;
if (!(value.equals("*") || value.equals(""))) {
filter = new EqualsFilter(new KeyExtractor(method), value);
} else {
filter = new GreaterEqualsFilter(new KeyExtractor(method), "");
return filter;
Problem (4): Combining Key searches into one service to support multiple key types. First step is to make sure that each cache stores a specific type of Keys. And if one type of Key is very different from another type of key then create dedicated Discoverer classes that specializes in finding a specific type of Key. Cache configuration could look like:


Then maintain a local map that stores cache to Object type mapping as:
XmlElement elem = null;
NamedCache nCache = null;
XmlElement cSMap =
Iterator mappings = cSMap.getElements("cache-mapping");
String dataType = null;
while (mappings.hasNext()) {
elem = (XmlElement);
nCache = CacheFactory.getCache(elem.getElement("cache-name").getString());
try {
dataType =

objToMap.put(nCache.getCacheName(), dataType);
mapToObj.put(dataType, nCache);
} catch (Exception exp) {
// -- Log the Exception and skip adding Indexes
Once mapping is known, create a Discoverer as:
public Collection getKeys(Key filterKey) {
IDiscoverer disc;
try {
disc = (IDiscoverer) keyDiscoverer.get(filterKey);
if (disc == null) {
// -- Even though the cost of Reflection is high but to it takes
// -- a microsecond to initialize an Object. To reduce the
// -- reoccuring cost use a local Map to store the instance
String cName = filterKey.getClass().getName();
String discName =
cName.substring(cName.lastIndexOf(".") + 1) + "Discoverer";
disc =
(IDiscoverer) (this.getClass().getClassLoader().loadClass("com.some." +
keyDiscoverer.put(filterKey, disc);
return disc.getKeys(filterKey);
} catch (Exception exp) {
return null;
Once the getKeys () is delegated to right Discoverer, the Discoverer object can work on the key's attributes directly. One example being:

public Collection getKeys(Key key)
throws IllegalAccessException, InvocationTargetException {

if (!(key instanceof Key1)) {
return null;

String cName = key.getClass().getName();
NamedCache nCache =
CacheFactory.getCache(cName.substring(cName.lastIndexOf (".") + 1));
Key1 pKey = (Key1) key;
Filter filters[] = new Filter[2];
filters[0] = getFilter("getAttribute1", pKey.getAttribute1());
filters[1] = getFilter("getAttribute2", pKey.getAttribute2());
Filter composite = new AllFilter(filters);
return nCache.keySet(composite);
As you see the code uses Java Reflection where ever possible but avoids it in re-occurring calls. The Specialized classes like Key1Discoverer on the other hand works on class attributes directly.
This is a simple but quite efficient approach to manage a collection of data and run Templated Queries on it. Coherence cache configuration dictates Object type to be stored in a cache. Discoverer provides a mechanism to have a specialized way of finding keys and manipulate QBE and single service class using Java reflection allows to scale the key types and its discovery to any number of types. Would be glad to see any suggested improvements...

Friday, November 07, 2008

Transfer of Power pattern

This is a little Java trick that came out of the following Problem Statement: How to call a pre-defined method of an invoking class if it is defined in it? Or, invocation through precedence.
If I have three classes Invoker1, Invoker2 and MyUtility and both Invokers call a method of MyUtility, Is it possible for MyUtility to call a method of the Invoker if defined instead of it's own? I call it a transfer of power pattern - An Invoker class dictates what to call not by condition or heirarchy but by definition of its location.

// --
public class MyUtility {
private void preInvocation () {
public void doSomething () {
System.out.println ("I am doing something");
// --
public class Invoker1 {
public void invoke () {
new MyUtility ().doSomething ();

public void preInvocation () {
System.out.println ("Invoker1's preInvocation called");
// --
public class Invoker2 {
public void invoke () {
new MyUtility ().doSomething ();
The way this application works is if preInvocation method is defined in an invoking class, MyUtility should call it instead of it's own. A workflow is defined in a way that does not require a tight integration with an Object hierarchy.

How to do it? Define MyUtility in the following way:

// --
public class MyUtility {
private void preInvocation() {
System.out.println("Pre-Invocation of MyUtility");
public void doSomething() {
Throwable t = new Throwable();
StackTraceElement[] elements = t.getStackTrace();
String callerClassName = elements[1].getClassName();
Class clz;
try {
clz = Class.forName(callerClassName);
Method method =
clz.getDeclaredMethod("preInvocation", null);
method.invoke(clz.newInstance(), new Object[] { });
} catch (Exception exp) {
// -- Any Exception and call it's own.
# Run Invoker1 => Invoker1's preInvocation called
# Run Invoker2 => Pre-Invocation of MyUtility
Have fun!

Saturday, November 01, 2008

I endorse McCain, Because...

@11/01/2008: After deep thinking and three days before Nov'4th I have decided to endorse McCain. And the reasons I will reveal after the result ;).

@11/04/2008: And the reason is that whoever I ever voted for has always won, and whoever I endorsed but did not vote has lost. And I do not have voting rights in America. Second, I did not have any goosebumps to endorse McCain. Lets not forget that he is a nice and decent man who gave his entire life to the service of this country. But, Sorry McCain this year we needed change. And a change from a Guy who is ground to earth and seems to think of us The Middle class America. We needed American troops to conclude its services in Iraq and concentrate on Osama Bin-Laden. We needed lower health care cost. And we needed a President of America and of entire free world to be at least a good Orator and able to connect to his audience. We needed someone who can bring back the respect once America enjoyed across the World. And this was an only opportunity to find a Candidate who is equally white as he is black - A nation that a future America represents.
Congratulations Obama and a Salute to McCain.

Monday, October 27, 2008

Nagle or not Nagle?

What is the Nagle algorithm in reference to TCP/IP?

Nagle's algorithm is a way of avoiding network congestion by limiting to at most one the number of "tinygrams" (that is, packets that are less than full size) an application can have outstanding at once. It does this by concatenating small segments until it has a full segment or it receives an acknowledgment of the outstanding small segment. The algorithm was proposed by John Nagle in RFC896. Its latest incarnation, which differs slightly from Nagle's original formulation, is described in RFC1122.

The Nagle algorithm can sometimes interact with the TCP's "delayed ACK" mechanism, another congestion avoidance strategy, in a way that increases network congestion and delay. For this reason, it is sometimes disabled, but this is appropriate only in very special circumstances. See the book Effective TCP/IP Programming or Rich Stevens' TCP/IP Illustrated, for complete details.

** Definition taken from

This has been a problem with Windows OS (and probably with other OS as well) that TCP connection waits to send next packets unless an acknowledgment is received. One of the Clients reported a drastically reduced performance in Coherence's multi-cluster data replication strategy. When nothing was found even after reviewing the architecture, code reviewing a number of times and involvement of upper management, we had to bring in a Top Coherence expert and he tracked the problem in 15 minutes. It was Nagle.

Friday, October 24, 2008

At last found sometime to blog

Last two weeks have been non-busingly busy. First there were some anxiety to attend the first Coherence SIG in NY. Last time I met Cameron before this SIG was at a client's site and I had screwed it up then (Not Me really but Hertz never lost) in driving directions. It was also nice to meet Alex, Rob, Brian, Peter O., Parker, Craig, Phil, Peter U., Tom and Patrick. And then it was nice seeing some of my clients as well and discussing their current challenges along with introducing Boris, Vikas and Anusha to the Coherence team members that they interact by emails and phone but had never met in person. It was also nice to listen to Brian Oliver's talk on Asynchronous Order preserving WAN Replication strategy. Nice to see someone bringing components that I had been aware of and used before, together in a more logical and robust way. And also hear Steve outline his strategy in successfully managing 'N' number of teams and establishing a centralized Architecture team.
Then I found there are many takers of my weekend project (jdbc driver for Coherence) that Rob and Brian were kind enough to allow to be submitted to Coherence's Incubator project. In fact two of my other colleagues joined hands with me as well and one of who's has a much mature implementation than mine. While I still think my broad approach is better ;). But it is hard to find ample time to do something that requires off-the-route creativity, and with work burden piling up again I am not sure when I would and should donate anytime towards it. On top of this one of the client reported problems with an earlier implementation and even though understanding their frustrations it is almost impossible to devote anytime to debug it after any active engagement ends. Probably the problem is due to Nagle (TCP connection waiting to send next packets) but need more testing. Oracle has a support structure that is very good in tackling Customer issues and works better than contacting Consultants and Product Engineers directly. I have tried my best and engaged everyone I could have to support them and is good to work with some intelligent developers who are quick to tests things out. Big Guys are already on top of it so I need not worry about it. And then there are some very exciting and technologically challenging projects coming up. I am working simultaneously with at least 5 separate teams to do architecture reviews and coding. When too many things go on in parallel I easily become a stateless machine - do not remember anything. Even simple implementations take time as Context Switching becomes a challenge.
And with watching your investments at a mercy of people who you do not know and have little trust on it has not been very easy. And with so many things to do - Working with Customers, Pending Reading materials, Lagging ideas, traveling every week on a 4 hour+ flights twice and aching body it was nice to steal few minutes to blog.

Saturday, October 18, 2008

Election participation - Go Vote

With American elections just around the corner, it reminds me of elections in India. Average percentage of voting in India is around 40-45%. Out of the rest 55 a huge majority does not go vote because they are lazy, because they do not think their vote matters, because they think their candidate will win anyway and other miscellaneous reasons like health, weather and fear of anti-social elements just to find that a candidate has won who he/she did not want. So people living in a Democratic society it is our responsibility to go out and vote. Whoever you like but go out there and vote. My parents have always encouraged us to participate in elections. Not in rhetoric but in ink. I remember whenever I was home during elections in a place I was registered to vote I and my family always went and voted. This is a way to show off your freedom to the rest of Un-democratic world that do not enjoy what we do. And remember if you did not vote then you lose your moral right to whine about the laws, bills and candidates that hurt you. Its your country and its future is your responsibility. Shape it with your vote.

Wednesday, October 08, 2008

Is surge working or Terrorists already won?

A re-run of Bill Maher show today just shook me. After seven years of 9-11 Osama Bin Laden and his lieutenant is still alive. Work on World Trade Center is still not complete. American economy is seeing unprecedented downturn. The leader of the terrorists who attacked us might be laughing today. And what do we listen in the debate? "My friends I know where he is. I know how to take him out".. and no one asks that it has been a Republican government for last eight years, If someone does know how to take him out why was it not done? More than a Trillion dollars burnt on personal egos and revenge that could have been spent on Health care, Energy and other things. We see 4000+ lives lost with the main culprit still at large, that might have only taken a few hundred million well spent dollars to take him out and destroy his network. We see a Police officer in his uniform bashing his fellow American and planting doubt of him being a Muslim and words like "Kill Him" in Sarah Palin's political rallies and no one denouncing it.. "Who is Barack? - A terrorist!" and Republicans think this is the only way to win? May be Barack does not understand may be he does not, but at least he is clear what he intends to do.. "My friends I know how to do it" is still not making it clear how will it be done. The respect I had for McCain is badly hurt by what Sarah Palin and his other apparatus is doing. I guess they both promised to run a respectable campaign. But when the time is to get together and united we are demeaning personally our own fellow citizen. What has gone wrong with us? Did Terrorists hit us on our character and values?

Monday, October 06, 2008

JDBC driver for Coherence

Okay this might be a crazy idea but as Coherence is a data source it was worth writing a JDBC driver for it. Of course spending time to write a complete SQL engine would be too much without any real motivation. But a simple proof of concept was on the cards. So here you go:

First thing is the client:

public static void main (String [] args) {
// -- Create a URL: hostname and port being of the proxy
String url = "jdbc:coh:@localhost:9099";
String sql = "SELECT * FROM Positions";

try {
// -- Load the Coherence Database Driver
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
} catch (ClassNotFoundException e) {
} catch (SQLException e) {

Now the Driver:

public class GridDriver implements Driver {

static {
try {
DriverManager.registerDriver(new GridDriver ());
} catch (SQLException e) {
// -- "jdbc:coh:@localhost:9099"
public GridDriver() {

public Connection connect(String url, Properties info) {
int hostIndex = url.indexOf("@") + 1;
int portIndex = url.lastIndexOf(":");
if (hostIndex < 0 || portIndex < 0) {
throw new IllegalStateException ("Driver URL incorrect");
String hostName = url.substring(hostIndex, portIndex);
String port = url.substring(portIndex + 1);
return new GridConnection (hostName, port);

Hmm Now the Connection:

public class GridConnection implements Connection {

public GridConnection(String hostName, String port) {
ConfigurableCacheFactory factory = CacheFactory.getConfigurableCacheFactory();
XmlElement cc = new SimpleElement("cache-config");

XmlElement sMap = cc.addElement("caching-scheme-mapping");
XmlElement cMap = sMap.addElement ("cache-mapping");

XmlElement rcs =
rcs.addElement("scheme-name").setString ("extend-dist");
XmlElement xE =
XmlElement rAs = xE.addElement("socket-address");
XmlElement add = rAs.addElement("address");
XmlElement portId = rAs.addElement("port");

// -- Now set the new XmlElement
// -- And of course you need to restart the Cache Service thread

public Statement createStatement() {
return new GridStatement();


Then the Statement:

public class GridStatement implements Statement {

public GridStatement() {

public ResultSet executeQuery(String sql) {
String command = sql.substring(0, sql.indexOf (" "));
try {
// -- There must be a way to recognize the SQL Command
ICommand cObject = (ICommand) Beans.instantiate(
this.getClass().getPackage().getName() + "." +
Set set = (Set) cObject.execute (cObject, sql);
// -- A utility to parse the SQL
Map map = SQLUtil.parseSelect(sql);
String cacheName = (String) map.get ("tables");
// -- And last the ResultSet
ResultSet rS = new GridResultSet (set, cacheName);

} catch (ClassNotFoundException e) {
} catch (IOException e) {
return null;

And before the ResultSet, lets see a half cooked SQL SELECT:

public class SELECT implements ICommand {
String token[];

// -- Select * From Dist-A where name = 'A';

public SELECT() {

public Object execute(Object obj, String command) {
Map map = SQLUtil.parseSelect(command);
NamedCache nCache = CacheFactory.getCache((String)map.get("tables"));
String clauses = (String)map.get("clauses");
// -- Lets demonstrate the Select * before going crazy
if (clauses == null) {
return nCache.entrySet(AlwaysFilter.INSTANCE);
return null;

Last but not least - The ResultSet:

public class GridResultSet implements ResultSet {

private Iterator iter;
private Set set;
private String cacheName;
private InvocableMap.Entry entry;

public GridResultSet(Set set, String cacheName) {
this.set = set;
this.cacheName = cacheName;
iter = set.iterator();

public boolean next() {
entry = (InvocableMap.Entry);
return iter.hasNext();

So here you go - another weekend project for Coherence!

Friday, October 03, 2008

Invitation to New York Coherence SIG

This is an invitation to all of you! who wants to meet Industry's finest and Customers who know what to do and how best to do when market is in slumps and each penny matters. So sign yourself up - Coherence NYCSIG and I will see you there!

PS: When I said finest - I meant the ones I am going to meet ;)

Wednesday, September 24, 2008


Racism in America: A few weeks ago I took a right turn at a red light where I was not supposed to. In Colorado there are not many traffic lights where right turn is not allowed, unlike many cities in East coast where it is quite typical. And where you least expect them they will be there. Yes Cops stopped me and gave me a ticket. And When I saw the paper closely my race was written as a "White".
Socialisism? On no!: The house prices are down 30% of its value. Thousands of dollars of losses in 401K and stock investments (even conservative ones). Gas prices and health insurance costs are sky rocketing and no one bails us out. Now our money is taken out to bail out the corporations who made wrong and risky business decisions at our expense. Bailing these huge financial corporations is still capitalism, bailing us out on main street would be socialism. Oh no, we can not be a Socialist nation. And if these steps are necessary to save the economy at least please guarantee that our $7000 dollars will be returned back at 8% yearly.
Lets not have a debate: McCain is good hearted and wants to suspend the campaign and work in Washington to resolve the economic crisis. He does not want Friday's debate. I thought during these times is the best way to connect with people on main street. Even Bush had a special speech. Is McCain avoiding direct people contact? I remember that Office episode when Steve Carell hides all day and gives Dwight to chose health care plan.
A VP that believes in witch craft?: Thats the only thing left for Americans to see!

Tuesday, September 23, 2008

Replacing proxy information on the fly

This is another neat trick under Coherence's arm. Lets say you have an *Extend client that connects to a set of Coherence proxies. If the proxies for some reason are down and none is available and you do want to connect to another cluster that you know is up (like a DR), how could you connect to it without restarting the application or using any DNS Switch? Following is a way to replace the Extend configuration on the fly:

public void changeConfigOnTheFly (String host, String port) {
ConfigurableCacheFactory factory = CacheFactory.getConfigurableCacheFactory();
XmlElement cc = new SimpleElement ("cache-config");
XmlElement rcs = cc.addElement("caching-schemes")
.addElement ("remote-cache-scheme");
XmlElement xE = rcs.addElement("initiator-config")
XmlElement rAs = xE.addElement("socket-address");
XmlElement add = rAs.addElement("address");
XmlElement port = rAs.addElement("port");

// -- Now set the new XmlElement

// -- And of course you need to restart the Cache Service thread
factory.ensureService("ExtendTcpCacheService").stop ();
factory.ensureService("ExtendTcpCacheService").start ();

Yay! And you can keep your *Extend cache configuration simple and tidy by replacing the proxy configuration on the fly. Something is missing in this configuration though - The cache mappings. Actually you do not need it. As long as cache schemes are defined, caches too can be created on the fly:

CacheService cS = (CacheService)CacheFactory.getService("ExtendTcpCacheService");
NamedCache sCache = cS.ensureCache("MyCache", null);

Don't you just love Oracle Coherence?

Saturday, September 20, 2008

Death of a Policy

History did not start on September'11th 2001. There was a world before that and roots of an evil were planted decades ago. In 1947 a country named Pakistan was born. No the country itself was not evil but the path it followed and policies it implemented resulted in a nation that its legendary creators would not have ever imagined. India pre-independence was a nation of multiple cultures. Mainly two - Hindu and Islamic traditions. For centuries a mixed culture took roots with an influence of Sufism that brought two religions together. But it was not always rosy. Uncertainties of early 1930's and some political opportunism ended up making some Muslim leaders insecure in the nation they were born in. While India continued its multi-culture secular way, Pakistan took refuge in religion. The partition which was mostly based on differences of political views was turned religious. While the leaders of North west frontiers (the region close to Afghanistan) whose cultures and traditions were very different from the main stream Pakistan never wanted a partition but they ended up abstaining from voting and hence a nation named Pakistan was born. Pakistan as it means a "Pure place" very soon got tainted and bloodied after thousands of Hindus and Sikhs were massacred in the worst ever riots of the last century. Elements in India responded with the same evil reaction and a country was split into two nations. Pakistan as its creator M.L. Jinnah thought of making - A free and progressive country rooted in Islam was soon caught in disillusions. Their suspicion and hatred for India grew and instead of strengthening the people they strengthened the Anti-India institutions of its military. With Soviet Union moving into Afghanistan Pakistan became the hot bed for US to make its presence felt in that region. While Pakistan continued to be used, Long story cut short - Taliban was formed and no one had any clue how to deactivate this Machine if it ever gets out of hand.
It was not like if the thought process followed by Taliban was any new. It was at the heart of the kings like Babar who invaded centuries ago and brought Islam to India and followed by Aurangzeb the last Mogul king of India. The soul of secular kings or leaders like Akbar and M.L. Jinnah died and replaced by a policy that was too dangerous to control. While Pakistan continued to be ruled by Military Generals that world cozied up to, it was the democratic institution of Pakistan that remained the victim. Then came Kargil misadventure, solely orchestrated by then Pakistani Military chief Musharraf. The same elements that never liked any peace initiatives by elected leaders of that country with India. Once again Pakistan came under a Military rule that only ended after 9 years. Then 9-11 happened and not the world but only West's perspective towards this long lasting evil changed. Common Americans who cared about a very small World realized that it was bigger and filled with more hatred towards US than they had earlier thought. It was a new reality beyond the cold war. Musharraf knowing exactly what he was up against chose to side with US or at least officially. He took a gamble that elements his institutions and his predecessors created and helped would be easy to deal with over a span of number of years. We all got used to the situation. Okay.. US will stay in Afghanistan. Musharraf will not allow situation to get out of hands. Iraq will get solved by itself. One day Osama Bin Laden and its kingpins will either be captured or killed. The world felt more peaceful. Then something unprecedented happened. Benazir Bhutto was assassinated. Musharraf was ousted and new elected leaders took oath in Pakistan. The most important nation in the fight against terror was back on track. Or so it seemed. A series of US strikes inside Pakistan and its Military's attempt to cross its border snowballed into an issue that has swung most of the undecided common Pakistanis towards Taliban. Marriott's bombing in one of the most protected areas is not an isolated act but a sign of changing ground realities inside Pakistan. Its a challenge that a new nascent government is ill prepared to deal with. Its a sign of failed policy and is screaming to get a new look. This problem is bigger than Iraq. People in hiding not only had their eyes set but now have a reach to not only to the deadly nuclear weapons but its delivery systems. Hope it is not a beginning of the fall of a nation we called Pakistan.

Saturday, September 06, 2008

Bringing Database application to Grid Computing in one day

So you have a Database application with Tables and Relations. Application is poorly performing, and not scaling and it is time to move. But it is so critical that rewriting it should be taken with precise planning. This is a common scenario at numerous clients. "Is there a way I can use Coherence Grid without too much programming effort by the time my IT staff learns the new technology?" Yes! as long as you know what a Map is. Follow the following steps and you are ready to Griditize your application in no time:

    Set up the tools:
  1. Download jDeveloper 10g (or latest) from Oracle.

  2. If jDev is not already enabled, Download AspectJ plugin from this link. Drop the jar in $JDEV_HOME/jdev/extenstions.

  3. Create Java Objects from Database tables:
  4. Start jDeveloper and go to Connections Tab. If Connection Tab does not appear, click the "View" Menu option and select Connection Navigator.

  5. Right click on Database connection and create a new connection. Test the connection for Success.

  6. Create a new jDeveloper project and give it a name.

  7. Right click on the Project and select Project Properties. Under Technology Scope, select Toplink to add. Don't worry, we are not mandating to use Toplink even though highly recommending it when you need database persistence and data load (Cache Stores etc). Click OK.

  8. Right click on the project and select New. A new Window appears, select Toplink option under Business Tier. Select the first option - "Java Objects from Tables". Give a name to Toplink Map and select the Database Platform and Database Connection you had created in step (3/4). Select the appropriate schema and import Tables. Select Tables that you want to create Java POJOs from. Move them from Available area to the Selected area. Click Next-> and provide a Java package name, say pkgname. Note this package name, you will have to use it later. After finishing the process you would see a bunch of Java classes in your project. You are half way there. Go and grab a cup of coffee.

  9. Kill some time:
    While you are finishing your coffee read this: Aspect programming with Coherence

    Make the Java POJOs Grid Ready:
  10. Create a new empty Java class under <pkgname>.root package. I would name it EzRoot (Motto is if it is not EZ (easy) it is useless). Copy the ELHelper class from the blog that you just read.

  11. Create a new Aspect by name EzRootAspect with the code copied from TestAspect.aj as was shown in the earlier blog. Replace all "Test." strings to "EzRoot." and add the following:
    declare parents: <pkgname>.* extends EzRoot; right below the aspect declaration. Don't forget to import EzRoot. Make sure package names of ELHelper and EzRootAspect are correct.

  12. Right click on the Project and select Rebuild. Or you can also create a new Deployment Profile and build a jar file. The compiled jar contains Coherence Grid ready Java classes. Each Java class represents a Table from your data model and now can also directly be used with Coherence.

In ten steps you have cut your week's work to half hour. The rest is your creativity. Whats next? Lets see.. I would love to give you a way to generate dirty but quickly a Coherence Cache configuration and you can go live in one day ;). May be some seasoned Domain Modeler can tell me the best way to tell a difference between an Entity and a Value Object without searching for an "ID" attribute. That way I can make an intelligent decision on how many caches should be created. The fun begins now...

Thursday, September 04, 2008

Obama vs McCain

So it is official now...
Obama's message: Enough!
McCain's message: WYSIWYG

I like McCain and salute to his services for this country, but if Democrats could not make a case this election they should forget it for another eight years. Do not Re-Kerry. Republicans have everything going against them. Economy, Last eight years, Economy, Iraq, Economy, Afghanistan, Economy, US foreign leadership, Economy, Health care and Economy but seems like divided democrats is still struggling to challenge a united republican house.
1. Why Women Clinton supporters should swing for Palin? After 42 male Presidents are all US men happy and satisfied?
2. Did they ever ask if she had won nomination, would she have picked Obama? I guess she would have picked Biden herself.
3. Why is this indirectly projected as if it is being un-American, selfish and un-patriotic to support Obama? USA, USA was a treat to hear in Beijing but why during Republican convention? Are the rest coming from Cuba?
4. Why are facts not used? Why is this being told that Obama's Tax increases will hurt common Americans? Does a common American make more than 250K a year?
5. Why McCain's Vietnam days are being repeated again and again? He did suffer tremendously and he suffered in the hands of enemies. Does anyone care how does it feel to suffer in hands of your own fellow countrymen? It is easier to defeat evil if it is recognizable. Two forces with guns out to kill each other. Yes you can see evil and defeat it. What about hate crime, racism, sexism those no-face evils? How to defeat evils that exist in character?
6. Yes, McCain is different. He will bring change and probably positive change. He is a uniter not a divider. But can anyone stand up and take responsibility for last eight years? 4000+ precious lives have been sacrificed on wrong pretexts, why were they blind folded for first five years? Why harping on the fix (surge) which should have been done from the beginning?
7. Why is there no accountability for lost 10 Billion Dollars that should have been spent to chase evil to the doors that houses them?
8. And Why experience has been such an issue? Has it been not a White house tradition lately that a President does everything that his VP tells him to do? ;) - Okay this was a humor!!
9. Republicans all kudos to you for choosing McCain as a nominee. If anyone can come victor in a face of adversity it is John McCain, his resolve and his character are his strengths. He masters this art.

After many years we have two very likable candidates. Both will bring change. They both have awesome character, sincerity and possess love for this nation and its people. You won't go wrong in choosing either of the two. But choose on policies. Choose on facts not on revenge and prejudice. Change is coming indeed but choose who can bring confidence as well, sooner than later.

Fact: Bush has more approval rating in India than in US.

Saturday, August 30, 2008

Extending Model Driven Design beyond codes

Whoever is familiar with Eric Evans should also be familiar with the following diagram:
The diagram pretty much is an essence of a good design. Even though mostly referred when working on one application and how components should be created also has a potential to extend it to higher view for Enterprise solutions. Besides the importance of Entities itself, two interesting pieces of the diagram are "Services" and "Repositories". They are not just a set of APIs but are extended to Infrastructure as well.

  • What about Services? How does a business create Services? How does it manage them? How can these services be orchestrated? And combined to produce a work flow? SOA combined with BPEL is what fills in the services gap.

  • Now what about the Repository and Aggregation? Again its not just API but how would you manage Gigabytes and gigabytes of data in a fault tolerant and high performance way? And how to maintain integrity of your Entities with this data management system. Oracle Coherence is what offers a perfect solution to address the infrastructure behind Repository and aggregation.

Concept of Entities is when an Object has an unique identity, matches perfectly for what a Map is designed for. And Coherence is built for very large data set with a simple Map interface of NamedCache. The question is what to manage in this Map? Entities or Value objects? Entities do have IDs. Vis-a-vis value objects? Why not? Objects already have a behavioral identity in its' hashCode (). Isn't there a difference between an ID and Identifiable. Last part: Factories and layered architecture. Factories can very easily hide behind services and unique interfaces for each individual applications. I can't see any centralized concept for Factories.. Can you?

Monday, August 25, 2008

This what one of the Kashmiri separatist leader has to say..

The statements have been taken from an interview taken with Gilani - A separatist leader of Kashmir wanting to merge the region with Pakistan:
Q: Why not contesting elections?
A: We believe in boycotting of the elections.
Q: Why imposing Islamic rule?
A: If America and India can have democratic rule, others can have Communism, why object to the Islamic rule?
Q: What about agitation in Jammu?
A: They are working on communal lines
Q: Aren't you like Osama bin Laden?
A: Osama has come only during the last few years. People like me have been fighting for this all our lives.
Q: What about differences in Hurriyat?
A:Some of the Hurriyat leaders did not like my being endorsed as a leader by the crowd and walked out.
Q:What do you stand for?
A: First is to impose an Islamic nizam (jurisprudence) in Kashmir. Islam should govern our lives, be it in our political thought, socio-economic plans, culture or the ongoing movement.
Q:So the transfer of land is not an issue?
A:Land is not an issue for us. It has just acted as a catalyst to shape peoples' sentiments into an upsurge.
Q:What was sudden provocation?
A:Its not about 50acres of land. People have started thinking about the 100,000 acres of land that is with the army. Under the guise of "Operation Sadhbhavana," the army has usurped huge parcels of land and seems to be expanding its network. I have information that the army has seized 23 acres of land for opening a school in Pahalgam.
Q:Aren't schools opened for Kashmiri children?
A:I know the schools are meant for Kashmiris. But they are also meant to make them sing Vande Mataram and not offer namaz. The aim of these schools is to turn Kashmiri children into pure Indians. This is cultural aggression on our Islamic values and is not acceptable to us.
Q:On division of people:
A: While I am for Kashmir going to Pakistan, there are voices that seek independence from both India and Pakistan. I also agree that there are people in Kashmir who would like to go with India. They argue that India has done so much for Kashmir. Others are fascinated by its secularism and democracy.

Its the duty of the world and Indian government to save Kashmiris from the leaders like him.

Saturday, August 23, 2008

A magic prime division

2300000/41 = 56097.56097560975609756097 and 56097 repeats itself forever... (A non 10n/3 repeatable result)

Friday, August 22, 2008

And I predicted this last November..

Kashmir - The burning desire

Kashmir has been a flash point among unresolved disputes. A problem largely created by India's neighbor and fueled by Indian government's own apathy. Kashmir as you know is one of the most beautiful places on Earth, beautiful people and a center of Sufism - a culture created by liberal Islamic and Hindu traditions. Even though this region is majority Muslim but almost divided into three equal sub-regions with majority Buddhist, Hindu and Muslim areas. It is painful and ironic that unrest in valley (one of the three regions) has dragged for two decades now with still no resolution in sight. Very recently demonstrations has picked up again and all kind of rhetorics has been coming out. But before people are manipulated again think about the following again:
1. Jammu has valid grievances too. Since the start of unrest in valley, Jammu has always been ignored as the money and power shifted to valley.
2. People listening to leaders claiming to be their sole representative must not forget an evil design that has taken lives of genuine people's leaders like Abdul Ghani Lone.
3. The recent killing of a Hurriyat leader during "Police firing" is very suspicious as per new intelligence report.
4. If Wagah border can be opened then why not Mujjafarabad's?
5. Why is there an economic blockade in Valley? And if there is none what is government doing to address these rumors?
6. You cannot build human colonies on 100 Acres of land at 10000ft.

Wednesday, August 20, 2008

How many updates per second can your UI handle?

View is very important. With any development you always end up having a GUI Application that displays the end result. The question is if there are very high number of updates happening to data, what is the realistic updates per second that any remote GUI application can handle? And even if you can handle it, will it be of any use? What experience have you had?

Saturday, August 16, 2008

A tribute to an Indian legend

No one represents India@61 more than the car on our left. This car in past 50 years has only minutely changed in its design, but is still capable of opening more Gates for you than even a Mercedes Benz. A bone white body with tinted glasses and preferably a blue or a red light at the top. Perfect on the bumpy roads that India has traveled on for past six decades. Engine that can be repaired with a hammer and a wrench like our democracy. Yes it makes noise and is not as smooth as others but it is rugged and is very comfortable inside and it moves. With this car moving don't try to jump off, you are safer behind its steel doors of centuries old values. Salute to our Amby and Happy Independence Day, India!

Friday, August 15, 2008

Managing Coherence as an IT Organization

Scenario: A development manager creates Tasks, gives it to a Technical lead who after assessing the task gives it to the developers of his team to complete. Developers run some logic and algorithms on a piece of hardware, returns the result to his lead who in turn gives it to the manager.
This is a typical workflow in any software organization. The terms and roles could be different but the flow more or less remains the same. Oracle Coherence supports an architecture starkly similar to this flow. *Extend Application (Manager) submits tasks to proxies (Leads) who passes agents like Invocable or EntryProcessors (Tasks) to developers (Storage nodes) who run the logic (Implementation) on a piece of hardware. Now if an overall Director/CTO finds the system to be slower than expected, how would you find the bottleneck? Lets see..

  • Is the manager creating enough tasks? Is your Extend application really pushing Tasks or Objects at a rate the system is designed for?

  • Are you overloading your technical leads with tasks far exceeding than they could handle? If you have too many work to do and only one lead to manage, it is obvious that the technical lead will be overloaded with work. Whats the resolution? Depending on the work load you create more lead roles. In the *Extend scenario you have to be very careful and meticulous in finding the number of Extend proxies you have to run based on the load. This number varies from system to system but I would recommend having at least 30% of total storage nodes would be a good number. If the grid size is 10 storage nodes, configure at least three storage disabled proxies.

  • Do you know if the logic was well written? It is very important in synchronous flows that tasks are short-lived. As a rule of thumb long running processes must always be asynchronous. Make sure EntryProcessors or Invocables that are run on the nodes are well written, fast and use minimum of network traffic. Short lived processes provide maximum throughput.

  • Have you hired the top developers? Make sure that JVM is not in GC frequently. Find stable nodes. Developers leaving group affects an overall delivery response. Stable team is very important.

  • Piece of hardware - Yes. Give them the best you can afford to work on. Make sure CPU has enough power. With agents running on nodes it is important that it is multi-core. Processors take CPU time. More cores the better.

  • Most important - the communication channel. How fast and clear is the communication? This translates to available network bandwidth. Always make sure you have at least 1G network with servers connected to the same switch. More switches lowers the bandwidth. As you see in any organization.. More administrative hops and slower will be the organization.

So its either organizational efficiency or a Coherence data grid, make sure before making any decision check and test where the bottleneck is.

Wednesday, August 13, 2008

Yay! I fixed my treo

I broke my Treo 680's screen a week ago by accidentally tossing a remote on the bed right on top of where my cellphone was. Ordered a replacement screen off of ebay and a Tx5 from Sears.. Yes I replaced the screen myself. While doing it though I dismounted the microphone so now I can hear the voice but they can't listen mine. Perfect as a spy gadget but need to fix it. For now, thank you bluetooth headset, at least I can use it for meaningful conversations.

Monday, August 11, 2008

Its not GM's fault

It is customary to start bashing companies that are not doing so well. GM besides being one of the greatest companies, an American Icon has been in such a receiving end. Three cars that need special mention that I as a driver was very impressed with are Toyota Camry, Ford Escape and Chevy Malibu. One of these cars is owned by GM. With rising gas prices, GM is being criticized for not going green soon enough. Being green in auto industry means Batteries. So far now, no one has any experience of how these giant batteries going to be in 5 years of hard driving. Will they be replaced every 5 years for a huge sum of money? Are they any reliable? I love gadgets at least the ones I can afford. And one thing that has always bogged me down are their batteries. In spite of tall claims of long talk times on your cell phones, the reality is they drain out soon. Once battery is dead, it is easier and more economical to replace the set than the batteries itself. I have one of the worst battery experiences for my Roomba. Twice have been replaced and the last one only ran for two sweeps. Laptop batteries getting hot is a no news. Rechargeable batteries of your home phone falter in less than two years. And if GM did not jump into the band wagon of these "battery run devices", I won't be surprised and blame them. And what else should we blame them for? Making sure that the working and health condition of their workers is decent and not like uninsured bunch working at 1/4th the salary? Yes they are behind but their research centers are at par with the best of their peers. This is one company with so much potential and instead of letting it killed, give it time and all the support needed for it to bounce back to the forefront of the auto industry.

Saturday, August 09, 2008

Oh Boy, The last Lecture!

Once in a while you do come across people who are incredibly inspirational as they speak truth from their heart. This 1hour 16mins and 27seconds lecture will be the best spent time if you can steal one. As an able orator Randy was, I was able to connect right away as he talked about two things - Virtual Reality and Childhood dreams. Not a lot of folks know that my first job out of college was with a research institute associated with Indian department of Atomic Energy. Not sure how come they hired me because I was never a smart guy but when you work with them you tend to believe you are one. One of the projects that I did while working there was on Virtual Reality. Even my manager did not know that I was doing something like that. After doing the regular work, I used to wait for 6PM when everyone was gone and I could spend hours on computer doing something I was so passionate about. The office politics never bothered me. When almost everyone knowing Computers and Programming were leaving for US, I did not bother because I was doing what I loved. I left that job and never got any opportunity to work on VRML again.
I started working for a company as a Contracted programmer. They offered me a job and in the interview process I told them about a project I was doing after hours. A futuristic desktop environment that did not require any device driver installations to use services. A system based on Jini's auto-discovery so that services running in the neighborhood could automatically download itself when you login. I was passionate and excited and discussed every detail of what I was thinking. You should know you are a contractor here, Ashish. You should only be doing what is told to you, was the response. But I am doing it after work and never billed those hours, I said. He was not pleased but they hired me anyway. The project was lost in sub-directories till the Company years later unveiled a futuristic 3D Java workspace. I collected all the courage I had and discussed my project with Hideya Kawahara, the brainchild behind the project looking glass. He was kind enough to allow me to submit my project as an incubator project for Sun Labs for looking glass. I left that company and there are no takers of that project anymore.
Speaking of Childhood dreams, I dreamt of becoming an Air force Pilot. My Mom didn't even allow me to fill an application form. I had weird career choices as well. I thought of becoming a rikshaw puller (a hand pulled taxi) and that I would never fight for money and let the customers give whatever they liked. Even though an idiotic choice but it was philanthropic. I was also fascinated with Doctors for their clean offices, fine pens and amazing hand writings. I also wanted to be a drummer and a scientist and an entrepreneur and a millionaire. Were any of these fulfilled? Came close to being a scientist and I own a drum set but thats pretty much it.

Sunday, August 03, 2008

When you let the Grid do your job

In event driven systems typically a business process needs to be executed when an event is raised. These events are usually a message received from an external system. As infrastructures grow more complex and flexible, computation is shifting from externally run applications to auto-magic processes being run inside the system of records itself. The idea is not new. For number of years companies have relied on scheduled jobs like cron invoked by Operating Systems. Timer services still play an important role in EJB driven systems. The same is true and increasingly getting popular with Oracle Coherence. Oracle Coherence manages data inside a resource called a Cache that behaves like a Map but in a clustered environment. Unlike any off-the-shelf Map implementation, Coherence' NamedCache supports events. A MapListener can be attached to any Cache that can handle events like Inserts, Updates and Deletes. Coherence supports an advanced listener called a Backing Map Listener. A backing map is a data structure that actually manages the data on a node for a given Cache. A backing map listener is like any MapListener but is attached to a backing map and listens to events being generated on a Cache on a specific partition that it is defined on. Backing map listener provides a powerful framework for in-grid-processing. It opens up a facility limited by only your creativity. If a business process is placed inside the backing map listener, these processes will be invoked upon any change in the Cache.
Things to know
1. Events are handled in a synchronous way. It means, the client that raised a Cache event has to wait for BML to return or finish what it is doing.
2. Java5's ExecutorService can be a powerful help to off-load any processing inside the BML for client to not wait for the entire processing to finish.
3. Coherence only manages the flow not how the events should be handled. Process decoupling is left to the business requirements.
Enjoy Coherence!

Saturday, July 26, 2008

India attacked...

...No you won't hear this as a shocking news on Television or any place else. This country has been bleeding from acts of terrorism for decades and decades. "29 killed in Ahmedabad", "2 killed in Bangalore", "30 killed in Benaras", "Scores killed in Jaipur"... These don't make actionable news anymore. And the perpetrators of these crimes are not always "Al Quaeda" but these home grown organizations springing up all over the world fascinated by whats going on in Iraq, Afghanistan or Pakistan. It is ironic that even after 9/11 the world does not see it as a global problem. There are talks of premature withdrawal of US troops from Iraq. Has anyone thought what will it get translated to? Do not donate your victory. It is too late to teach what a true Jihad means to these global Jihadis, they should be firmly dealt with, once and for all.

Friday, July 25, 2008

This is called a world leader

Obama in Berlin

Monday, July 21, 2008

The drama around nuclear deal

Indo-US nuclear deal has stirred a political beehive of Indian democracy. The political parties are so divided that the vote has become an issue of bringing down the government. So much so Horse trading that were never heard of on a non-local political issue. Mayawati proved smarter than Sonia. SP the most opportunistic. Left trying to erect a stronger third front and BJP a helpless lot. With Mayawati on the third front it is unlikely that BJP will try to bring down the house. It is in their favor to have a weak and divided members till the next elections. Either way, it is funny and ironic to see re-alignment of political coziness and opportunism not seen in a while. Hope the election commission and Supreme court is watching closely any trading of political loyalities.

Sunday, July 20, 2008

Is it a Pet Jealousy?

A few years ago my Sister rescued a week old Parrot and brought it home that has been a wonderful Pet since. He gets an undivided attention. Recently she rescued a chick probably a pullet and brought her home. It was hungry and thirsty. Now, whenever the new pet is given attention, our parrot leaves everything he is doing and starts watching it. And yes, everything includes eating his favorite food. We are not bird psychology experts but our parrot's less chattering is making us a little concerned. We want to see them grow together.

Saturday, July 12, 2008


Friday, July 11, 2008

Why blame George Bush?

Both the camps blame Bush for all the evils this country is facing today. May be he did not have the best of an Orator abilities. May be he did not have any idea of how to run an economy. But why to blame George Bush for scratching a wound to show the world how big of a cancer it has become underneath?


Thursday, July 10, 2008

Is GM really doing this bad?

GM stocks have plummeted and there are rumors of it filing bankruptcy. I don't know if this could be true because suddenly I see so many new Chevy's on the road. I have driven Chevys myself and don't see why it can't compete with Toyota or Hondas. And if GM is suffering of high fuel prices what is stopping it to go big at the places where this is not an issue? Middle East or even Russia? They may want to cut some brands but it still has a lot of good Cars to market. Don't get too carried away with Toyota's or Honda's "cleaner" technology scoop that always can be caught up with. Just strengthen your good brands and refocus with new strategy. I hate to see a good brand go because of mis-management and lost focus.

Tuesday, July 08, 2008

Forms of Consulting

Engaging Contractors and Consultants is a practice now being followed pretty much by all the companies. First version is when a consultant is brought in and the work is delivered by him/her. The fish is caught and the client is presented a cooked food. Mostly the client is happy but what they do not know that they are now being locked, in most cases forever. Cooked fish is good specially if it tastes good. The second version is catalytic consulting. Its not necessarily cooking the fish itself but teaching how to fish. The result is a team well prepared to take any future tasks, more trust on the product and a confident client. It takes only a few seasoned customers to understand and appreciate the catalytic consulting and unfortunately only a few understand it. What do you want?

Monday, July 07, 2008

3.6M per day?

For even overly conservative practice:
170 per second
10200 per minute
612000 per hour
3672000 per 6 hours
4896000 per 8 hours?

How could these numbers be bad?

Saturday, July 05, 2008

My Indian political dilemma

Here it goes:
1. I like Manmohan Singh and Sonia Gandhi but do not like Congress because of its second line leaders.
2. I like BJP but do not like L.K Advani
3. I like Mayawati but do not know who BSP is?
4. Dislike left parties but their socialist agenda sounds good at least on paper.
The problem is you always end up compromising.

Happy 4th of July

Happy 4th of July. A snapshot taken from a fireworks show in Grand Lake, CO. More on: Flickr

Friday, July 04, 2008

Homer, you stole my line..

"They have six pack and I have a keg.." Homer Simpson, you stole my line. Read my blog written on July'09 2005:

Tuesday, July 01, 2008

This is me on an average day

Day when I travel, I usually take late afternoon flights. Reach hotel between 11PM or 2AM next morning. Try to get ready without getting headaches. Drive fast to reach office by 9:45AM to attend the meeting. Fight fires all day. Not only mine but everyone's who knocks the door. End of day throat is always dry. Leave office between 7-8PM. Before leaving make sure say bye to any colleagues still working. Drive directly to grab dinner. Come back to Hotel and boot the laptop. Continue the work till I almost fall asleep usually by 2-3AM.
Day when I work from home, Have to wake up early by 7AM to reply emails and attend Morning meetings. By the time "immediate-response-needed" is over its almost 10AM (local) and time to brush the teeth and drink some juice. Continue the communication and anyone who wants help. Grab Lunch by 2PM (local) and continue the work till 6:30 (local). By 7 see if something to blog about or tweet. Continue the errands. Grab the dinner by 10PM while office work or some document to be read continues. Continue working on codes if pending. Sleep by the time eyes automatically close.
Non work days, I try to catch up on sleep. Run to Market for weekend stuff. Watch a movie if any. Look if any book or document can be read over. Keep the laptop close to work on anything or something thats pending or new ideas.
After these 7days of a week, no one has a f#$$% business to ask if I was doing anything. No wonder I almost forgot it was my Birthday today had my family had not called me to wish.

Saturday, June 28, 2008

Aspect Programming with Oracle Coherence

Due to the nature of Coherence APIs, it is deceptively easy to make any current application Grid ready. Coherence v3.3 requires that all the domain objects implement Coherence provides ExternalizableLite, a highly optimized Serializable interface along with ExternalizableHelper to serialize/deserialize attributes. It is required that all Cached Domain objects are updated to implement this interface. Even though this process can be made pretty trivial by using AOP (Aspect Oriented Programming). Following is an Aspect along with a Helper class that can be applied/woven to all of your domain objects to make them Coherence ready. The ELAspect makes the following assumptions:

  • Domain Objects follow standard Java Bean specification.

  • All the Domain Objects extend a single Type. Change the ELAspect code to replace "Test" with an appropriate root object or follow AspectJ's Inter-type declarations.

This Aspect can be compiled with the domain objects (Or woven) with AJC AspectJ compiler.

package com.ezduck.aop;

import org.aspectj.lang.reflect.Pointcut;


import java.lang.Exception;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

import com.tangosol.util.ExternalizableHelper;

public aspect ELAspect {

declare parents: Test implements ExternalizableLite;
Field [] Test.fields = this.getClass().getDeclaredFields();
Class Test.elHClass = ELHelper.class;

private Object Test.invokeGetter (Field field, DataInput dI) {
Class clazz = field.getType ();
String mName;
if (clazz.getPackage().getName().startsWith("java")) {
mName = "read" + clazz.getSimpleName ();
} else {
mName = "readObject";
Object value = null;
try {
Method eMethod = elHClass.getMethod (mName, DataInput.class);
value = eMethod.invoke (null, dI);
} catch (NoSuchMethodException nExp) {
try {
Method eMethod - elHClass.getMethod ("writeObject", new Class[] {DataOutput.class, Object.class});
ehMethod.invoke (this, new Object [] {dO, value});
} catch (Exception exp) {
// -- Skip it
} catch (IllegalAccessException iExp) {
} catch (InvocationTargetException tExp) {
return value;

* Add an implementation for readExternal, for example:
* in = ExternalizableHelper.readInt(dataInput);
public void Test.readExternal (DataInput dI) {
System.out.println("Inside readExternal");
String attrName;
Class clazz;

for (int i = 0; i < fields.length; i++) {
if(!fields[i].isSynthetic ()) {
attrName = fields[i].getName();
clazz = fields[i].getType ();
Method eMethod;
String setter = "set" + Character.toUpperCase(
attrName.charAt(0)) +
Method method;
try {
Object value = invokeGetter (fields[i], dI);
System.out.println("Value is: " + value.toString ());
method = getClass().getMethod(setter, clazz);
method.invoke(this, value);
} catch (NoSuchMethodException nExp) {
} catch (IllegalAccessException iExp) {
} catch (InvocationTargetException tExp) {

private void Test.invokeSetter (Field field, DataOutput dO, Object value) {
try {
Class clazz = field.getType();
String cName;
String mName;
if (clazz.getPackage().getName().startsWith("java")) {
mName = "write" + clazz.getSimpleName ();
} else {
mName = "writeObject";
clazz = Object.class;
Method ehMethod = elHClass.getMethod (mName,
new Class [] {DataOutput.class, clazz});
ehMethod.invoke (this, new Object[] {dO, value});
} catch (NoSuchMethodException _nExp) {
_nExp.printStackTrace ();
} catch (InvocationTargetException _tExp) {
_tExp.printStackTrace ();
} catch (IllegalAccessException _iExp) {
_iExp.printStackTrace ();

* Add an implementation for readExternal, for example:
* ExternalizableHelper.readInt(dataOnput, in);
public void Test.writeExternal (DataOutput dO) {
System.out.println("In writeExternal");
Class clazz;
String attrName;
for (int i = 0; i < fields.length; i++) {
if (!fields[i].isSynthetic ()) {
attrName = fields[i].getName();
attrName = Character.toUpperCase(attrName.charAt(0)) +
clazz = fields[i].getType ();
String getter = "get" + attrName;
Method method = null;
Object value = null;
try {
method = getClass().getMethod(getter, new Class[]{});
value = method.invoke(this);
System.out.println("Value: " + value.toString ());
invokeSetter (fields[i], dO, value);
} catch (NoSuchMethodException nExp) {
nExp.printStackTrace ();
} catch (IllegalAccessException iExp) {
iExp.printStackTrace ();
} catch (InvocationTargetException tExp) {
tExp.printStackTrace ();

And the Helper class is:

package com.ezduck.aop;

import com.tangosol.util.ExternalizableHelper;


public class ELHelper extends ExternalizableHelper {
public static int readInteger (DataInput dI) throws IOException {
return readInt(dI);
public static String readString (DataInput dI) throws IOException {
return readSafeUTF(dI);

public static void writeInteger (DataOutput dO, int n) throws IOException {
writeInt (dO, n);

public static void writeInteger (DataOutput dO, Integer iN) throws IOException {
writeInt (dO, iN.intValue());

public static void writeint (DataOutput dO, int i) throws IOException {
writeInt (dO, i);

public static void writeString (DataOutput dO, String s) throws IOException {
writeSafeUTF(dO, s);

Even though I tested the code with quite a few data types but feel free to update it if any Exceptions are thrown and leave a comment on this blog as well to let us all know.

Tuesday, June 24, 2008

I back Obama..

I am backing Obama. I don't want to, but I want to be part of the fairytale as well!!

Saturday, June 21, 2008

The myth of Serializable free distributed computing

For some, Domain modeling is not a science its an art. Hardcore domain modelers will tell you rules and list of good practices that will make you believe that you haven't learned anything yet. I loosely touched this subject in one of my blogs as well. A good domain object is one that does not know anything about the infrastructure it will be run inside. A domain object is not just a placeholder of getters and setters but can also have other behaviors as long as it only operates on the attributes it owns. Following is a good example of a domain object:

public class TwoInt {
private int a;
private int b;
public int getA () {..}
public void setA (int a) {..}
public int getB () {..}
public void setB (int b) {..}

// --
public int add (int a, int b) {
return a+b;

Distributed computing somewhat challenges the established notions of domain modeling. The JVM contract says if an Object is to be moved from one JVM to another it has to be Serializable. Period. This contract can not be breached. Designing a distributed application with a Single System Image has this challenge to overcome. For the example Object TwoInt to be used in a distributed environment it has to implement that the domain perfectionists will see red on. What if the application is only deployed on one single JVM? Then why Serializable? Being Serializable is a concern of an infrastructure not a requirement of the domain model.
Whats wrong with the following?

public class TwoInt implements Serializable {....}

public class App {
public static void main (String [] args) {
TwoInt key = new TwoInt ();
TwoInt value = new TwoInt ();
java.util.Map m = <??????>;
m.put (key, value);

Map is an Interface. If its implementation is to be replaced by a HashMap by far the most popular implementation of java.util.Map, then TwoInt objects are not required to implement Serializable. If this application is to be run in a Distributed Environment and Map's implementation is a NamedCache (Another implementation of a Map interface but now in a distributed environment) then TwoInt has to implement Serializable. So any change in the Map's implementation has a direct consequence on its domain model.
Aspect Oriented Programming can be a bridge between what is required in distributed computing and domain perfectionists. Good part is, a domain modeler sees a Java source and Distributed computing sees the byte codes. Hence Serializable is a cross cutting concern and with AOP if implemented at compile time both camps will be happy. Following is a sample how to do it using AspectJ, an AOP implementation:

public aspect TwoIntAspect {
declare parents: TwoInt implements Serializable;

Then compile the domain object with its Aspect using ajc (AspectJ Java compiler) as:
$ ajc
The TwoInt.class will be changed to have Serializable interface implemented.

Friday, June 20, 2008

Why solar cars won't fly

Reason is simple - I just don't trust batteries. Here is what I have at home as I write:
1. The cable wire of the AC Adapter of my laptop was somehow cut (looked like because of heat) and with no adapter the laptop is sitting idle drained. Just ordered an adapter from Amazon.
2. The new battery for one of my smoke deductor seems dead.
3. The battery of the Roomba discovery has been dead for months now and I just can't find a local replacement place.
4. I just replaced rechargeable batteries for my hand set and now seems the other one's died as well.
Either batteries don't like me or this is the least researched area of manufacturing. Go green is good, but with these experience how could anyone convince me to buy a solar paneled car?

Thursday, June 19, 2008

Custom is good

How many times have you downloaded a product to find that it comes prepackaged with products freely downloadable? You would quite often see Apache web-servers or a Java runtime bundled with a product. These are typically either open sourced products or are under a license and customized. Custom is good. And I have an evidence on the upper left. It gives products flexibility to make it work as per your requirements. Off the shelf or cookie cutters are good as well but may not be suitable for all the needs. This is quite true with Application servers that are built on top of products like Apache or Orion. A bunch of custom web server plugins and custom protocols and now I can make money on top of these freebies. JRE is another but not usually highly customized. JREs are pre-bundled to avoid having to download one or due to certification issues or a need of a specific version. I went custom too. Very recently while working for a Client I came across a .NET security issue that required DLLs to be colocated with the invoking application. It was a Java application that invokes some C# APIs. Packaging is important. Now, it was needed that the dll coexists where java.exe was. A good scenario to go custom. Many installers like Install4J provide a flexibility to bundle a JRE with the product. I am not promoting install4j as this not being an open and free product but you got my point. If I can have my own instance of JRE then I can also copy the dynamic libraries in it that the application uses. And your custom JRE is ready to be ridden.

Wednesday, June 18, 2008

Let BJP support Congress if govt falls

Every sane person knows how important is the US nuclear deal for India to address its long term energy needs. Left parties who unfortunately are part of UPA are just propagating weird agenda and do not see the benefit this country will have. Compromises here and there are part and parcel of all the deals. As long as the deal does not threaten the sovereignty of India, the Indo-US nuclear deal should go ahead. Without a stable energy resource India's economy and development is going no where, and for that it would need Nuclear reactors not a dependency on fossil fuels coming from unstable regions. As long as it reserves a right to continue doing research and development with transparency I don't see any reason for anyone to oppose it. I dare left to pull out the support if Government decides to go ahead and challenge BJP to come forward and support the govt on this issue.