Monday, March 30, 2009

Integrating Oracle Business Rules with Coherence

"Do something if something happens" - believe me is a problem statement of 99% of applications running today. Wise men spend a number of years tuning these somethings. Oracle Coherence is one such infrastructure where something happens all the time. Objects are being put, mutated, removed, evicted and events are continuously generated. Components like EntryProcessors provide a mechanism to perform some functions that can be easily integrated with these events. So "Do" and "happenings" are covered with EntryProcessors and Events respectively. Next thing is "If" and the other something ("what should happen?"). Lets take a concrete scenario, what IF we want to approve all drivers in the Coherence Cache of age greater than 21 to have a license? Easy to implement. Execute an EntryProcessor for drivers whose age is greater than or equal to 21. Now, what IF business decides they will approve all drivers of ages 17 and more in the future? Even though there are quite a few ways of incorporating ever-changing-rules in an application but Oracle Business Rules is tailored made for such IFs that change. Lets implement our scenario... Application is continuously adding new Drivers in the Coherence Cache and we want automatic processes to approve these Drivers based on their age. Implementation is simple. Just add a BackingMapListener to the Driver's cache and with each driver being added assert the Driver's age using Business Rules APIs (JSR-94). How would this BML look like? Following is one sample using File as a Rule Repository (Or use WebDav):

public class RuleListener implements MapListener {

private RuleSession session;
private String ruleSet;
private RuleDictionary dict;

public RuleListener(String repoPath, String dictionary, String ruleSet) {
this.ruleSet = ruleSet;
RepositoryType jarType =
RepositoryManager.getRegisteredRepositoryType(Keys.CONNECTION);
try {
RuleRepository repo =
RepositoryManager.createRuleRepositoryInstance(jarType);
RepositoryContext jarCtx = new RepositoryContext();
jarCtx.setProperty(Keys.PATH, repoPath);
repo.init(jarCtx);

dict = repo.loadDictionary(dictionary);
String dmrl = dict.dataModelRL();
String rsrl = dict.ruleSetRL(ruleSet);

session = new RuleSession();
session.executeRuleset(dmrl);
session.executeRuleset(rsrl);
} catch (RepositoryException e) {
e.printStackTrace();
} catch (RLException e) {
e.printStackTrace();
} catch (RuleSetException e) {
e.printStackTrace();
}
}

private void process(MapEvent mapEvent) {
System.out.println("Processing Event");
try {
Object obj = mapEvent.getNewValue();
Object key = mapEvent.getKey();

Driver driver =
(Driver)(obj instanceof Binary ?
ExternalizableHelper.fromBinary((Binary)obj) : obj);
if (session != null) {
session.callFunctionWithArgument("assert", driver);
Integer isSuccess =
(Integer) session.callFunctionWithArgument("run", ruleSet);
// -- Is the following necessary?
if (isSuccess != null && isSuccess.intValue () == 1) {
// -- Do Something
}

}
} catch (RLException e) {
e.printStackTrace();
} catch (RuleSetException e) {
e.printStackTrace();
}

}
public void entryInserted(MapEvent mapEvent) {
process(mapEvent);
}
....
}
Even better implementation would be if even the "Do Something" is taken out of this code and is run as a Business Rule function. So what does a Business user do? They change the RuleSet for the business conditions and also what to do when it is met. Another business use case is to buy n-stocks if the price of a Stock is at $x. This $x can be changed using Business Rules while Coherence continues to process stocks in it's system. More codes and a sample project to follow...
What's next? If I am using Coherence as an Execution engine for data (BML + EntryProcessors), how to control the EntryProcessor's execution? With no human interaction to build an auto-process-configurer engine that changes the RuleSet dynamically inside the Cluster based on certain state of data. Stay tuned while I go and discuss it more with the Wise men I know.

Saturday, March 28, 2009

Wealth as Energy

Not the cash, not the money and not the individuals but total wealth on Earth is like Energy - it can't be gained and it can't be lost. The trick is to convert the potential wealth to kinetic wealth the one that moves and can be used to run economies like a mechanical work. All is required are the tools to be able to do this wealth conversion. These tools are technology, research and human resources. So feeling bad about economy? Invest in these tools so as to gain an ability to convert the dormant wealth to an active one.
Remember folks (mv2/2 + mgh = k (constant)) where,

  • m is your assets - can be gained, can be shelved. Companies acquire companies or get rid of some to adjust the 'm'.
  • h is the height of potential of growth of the industry you are in.
  • v is the velocity of growth. Remember v is a vector it has direction. For example, the direction could be emerging areas, it could be making hybrid cars or making more railway tracks.
  • So what is g? g is for Government and everything it affects - security, direction, environment, stimulus etc. Typically constant but better (lower) it is more kinetic wealth can be generated.
So if g does it's work and we tune our m, v and hs it won't take long to see mechanical movement in our economy.

Thursday, March 19, 2009

20 days worth of political review

Its been 20 days, five or six Indian cities, train travels, lots of waiting and tons of people watch and I am armed with enough material to review the current Indian political crossword.

  • Confusion with in "other" parties of UP and Bihar means Mayawati and Nitish Kumar is doing better and will come out likely winners.
  • Varun Gandhi's infamous speech has left his partymen red faced but has won a lot of ground support. Its not clear if his speech was well orchestrated to win over some of the hardcore militant Hindu votes or counter balance Modi's weight. Probably it has back fired for now but is a concrete foundation for his future political clout. A Gandhi/RSS is a rare combination.
  • Contrary to beliefs UPA is not breaking up. Its an internal tussle to win over the biggest pie.
  • Advani is the biggest hurdle in NDA's win and probably one reason why they will win the seats they do.
  • People still look for not what leaders say but how they say it.
  • Congress will come out strong from South.
  • Third front will breakup after elections.

Friday, March 13, 2009

mod_coherence for Apache webserver

After the advent of Servlet and ServletFilters importance of webserver plugins (ISAPI, NSAPI, Apache etc) have slowly subsided. But plugin's raw speed and low level content, connection and protocol capture still makes it a viable candidate for plenty of scenarios. Caching is an integral part of a web server and mod_cache is possibly the most used plugin. Not to replace it but lets write something that uses Oracle Coherence as the content repository. Apache being at the core of most App/webservers lets write one mod_coherence for Apache webserver....

#include <httpd.h>
#include <http_protocol.h>
#include <http_config.h>


static int coherence_handler (request_rec *r) {
if (!r->handler || strcmp(r->handler, "coherence")) {
return DECLINED;
}
char* uri = r->uri;
// -- useThisUri (uri);
// -- Open to implementation
// -- Scroll down for options
// -- Assuming we get the content (parsed) here using C++ API

NamedCache::Handle pCache = CacheFactory::getCache(<cache_name>);
String::View cnt = cast<String::View>(pCache->get (uri));
ap_set_content_type(r, "text/html;charset=ascii");
ap_rputs(cnt, r);
return OK;
}

static void coherence_hooks (apr_pool_t *pool) {
ap_hook_handler(coherence_handler, NULL, NULL, APR_HOOK_MIDDLE);
}

module AP_MODULE_DECLARE_DATA coherence_module = {
STANDARD20_MODULE_STUFF,
NULL,
NULL,
NULL,
NULL,
NULL,
coherence_hooks
};
Now compile this source to a shared object and put it under Apache modules/ directory and configure httpd.conf as:
LoadModule coherence_module modules/mod_coherence.so
<Location /*>
SetHandler coherence
</Location>
And thats all you need on the Apache side. The question is what to do with the uri and how to do it in coherence_handler? First depending on which language you are more comfortable with use Java with Java Invocation Framework or use Coherence's native C++ API. Second, use the uri (or some part of uri) as a Cache key and get the content from Coherence Cache. If using JNI we have an option to make Apache webserver plugin be made a storage disabled member of the Coherence cluster. If native C++ APIs are used make sure the cache configuration is *Extend instead. The option of implementations are:
  • Cache and UriCache are new C++ Objects that use Java Invocation Interface to work with Coherence Java APIs.

      // -- Following implementation is using JNI
      Cache* pCache = new UriCache ("Content");
      SomeObject* cnt = (SomeObject*) pCache->get (uri);
      // -- This SomeObject could be simple HTML String or an
      // -- XML Content to be parsed in the next few lines
  • All Java and no Cache implementation in C++
  • Using Coherence native C++ API
      NamedCache::Handle pCache = CacheFactory::getCache(cacheName);
      String::View cnt = cast<String::View>(pCache->get (uri));

Enjoy!

Tuesday, March 03, 2009

Why would NDA win 2013 Elections

The state of BJP and it's partners this year does not project any sign of them winning the upcoming elections. But there are some positive signs for them to be favorites for the elections after next.

  1. With Congress's win most likely in the next elections their old regional factions like Trinamool Congress and NCP are coming back to it's fore. Upon INC's failure at center these regional parties will be the biggest losers whose seats will go to NDA.
  2. A strong show of SP-Congress in UP will bring BJP and BSP closer for next elections.
  3. This is Advani's last elections. Next four years will see a younger and more refreshing leadership in BJP.
  4. Poor global economy and increased threats from Terrorism in South Asia will strengthen hard line Nationalist elements.
  5. NDA's current partners will stay close to them. Their allies are regionally stronger.
  6. There will be a third front again. A stronger third front depletes INC's vote bank.
  7. Defeat in this elections will see BJP go grass root again.

Sunday, March 01, 2009

Five suggestions for my fellow countrymen

Of course its not necessarily for everyone but I met quite a few in my trip..

  1. By returning the smile he is not going to steal your job.
  2. Tuck your shirts. Untucked shirt with an oversized jacket doesn't make you look cool.
  3. Start doing your small little things. Don't ask your colleague to bring you coffee just because he reports to you.
  4. Keep your distance in a queue. Pushing in the line will not bring destination closer to you.
  5. Ogling will not win her over.