Thursday, December 30, 2004

Java-JNI-COM-ActiveX Bridge.; Lots of jumps-n- hoops

I'm assuming reader will have basic idea of what and how Java-JNI works, if not refer to Sun's JNI Tutorial section . For Advanced Java-JNI Programming look at this site.

Now this article is not to teach JNI, this one is about my discoveries in regards to mystery of JNI communication with Microsoft native COM/ActiveX components. It is not as straight forward it as it looks like. JNI says I CAN talk to Microsoft DLL component, but it does not say that DLL has to be written in certain way. That way is again guided and defined by JNI standards. This article will explain how to go about building a compatible bridge between any form of DLL and Java application.

Requirement: (Requirements are always simple, seems easy as grabbing a beer from the refrigerator)

My requirement is to communicate with Visual Basic ActiveX component (DLL file) using Java.

Speculation: (We always speculate with lots of options and think one thing or other will get us there easily)

  • There are millions of way achieving this, Use commercial/Open source products (As mentioned on the right hand side of the article table 1)

  • Write your JNI bridge to communicate.

Facts: (When you actual fact bites you, its not pleasant)

  • You have to go thru many of the open source products, test them, make sure it do exactly same, as you expect.( Ah!!! lot of patience)

  • Some of the product you finally pick saying "Yes" this works , then you realize there is a Licensing nightmare, you can not use it freely for production deployment. Sometimes you can use it but it
    will come with good amount of per user/per machine/per processor/ (infinite loop of per thingy). So your clients or customer will decide not to buy because it needs a money to deploy ready made solution. e.g. Look at IBM's license fee for Bridge2java.

  • If you decide to write your own JNI code, well "flip this". Java does not understand Visual Basic way of defining methods/functions. So it will not understand Visual Basic Active-X DLL component. Bottom line you simply can not talk to Visual Basic DLL directly using Java.

Solution: (Sooner you figure out the solution, better it is for you)

So you are left with, either use existing open source/commercial product or write your own. In my case after trying few of the products out there decide to go with my own.

Solution Detail

As i mentioned, There is no on the earth you can make Java directly talk to Visual Basic DLL, idea is to write a COM Wrapper in C++ (VC++), which will act as bridge between Java and Visual basic. Basically Java can communicate with C++ Wrapper and C++ Wrapper knows all about Visual basic code.

Java(JNI)--> C ++ wrapper -->VB DLL

How Java Talks to VC++

Java JNI will talk to VC++ wrapper using JNI way of defining and communicating. Refer to this tutorial site about how to communicate with DLL files. Key is to follow the pattern of

Java_<Java Class Name>_<Method Name to Invoke> on your .h and .cpp files. typical
method on .h and .cpp will look like this

JNIEXPORT jobjectArray JNICALL Java_CallService_GetEarthCoOrdinates (JNIEnv *env, jobject object)

How VC++ talks to VB

I will not write in detail about this because ,there are good resources out there and one of them is
site, about how to get VC++ talking to VB.

That should give you a good idea about how to achieve, two different worlds (Java and Visual Basic) talking with each other.

What next ?; The difficult part.

Once the basic communication done, then comes the most difficult parts where you need pass parameters back and forth. If parameters are complex, then its more painful. I have listed down few points on how to get things across using different data types.

Situation : Lets look at the complex situation. Java is passing String arrays (String[ ][ ]) and Visual Basic is expecting (Variant array Dim earthParams(10, 10) As Variant).

Java VC++ VB
String[][] SAFEARRAY/VARIANT Variant array

  • You have to pass String Array as jobjectArray to VC++

  • Convert them to SAFEARRAY


  • Pass VARIANT to VB via call.

Same thing Other way round when data comes back from VB.

Convert jobjectArray (Java String[ ][ ] array) to VC++ SAFEARRAY/VARAINT (C++ Code)

VARIANT loadJavaArrayToCPPSafeArray(jobjectArray stringArray, JNIEnv * env)





SAFEARRAYBOUND rgsabound[2]; //This means 2 Dimensional

rgsabound[0].cElements = 10; // 10 rows

rgsabound[0].lLbound = 0;

rgsabound[1].cElements = 10; //10 columns

rgsabound[1].lLbound = 0;

psa=SafeArrayCreate(VT_VARIANT, 2, rgsabound); //Finally Create

//Now get First Dimension Array Length for String [][] array

jint length1Dim = (env)->GetArrayLength(stringArray);

long aiIndex[2];

for (aiIndex[0] = 0; aiIndex[0] < length1Dim; aiIndex[0]++)


jobjectArray oneDimArray= (jobjectArray)env->GetObjectArrayElement(stringArray, aiIndex[0]);

//Get Second Dimension
of the String[][] array passed.

jint length2dim = (env)->GetArrayLength(oneDimArray);

jstring oneDim;

const char* szStr;



oneDim= (jstring)env->GetObjectArrayElement(oneDimArray,

szStr = env->GetStringUTFChars( oneDim, 0 );


_bstr_t str2 = szStr; //Get Sting value from array to BSTR of

var.vt = VT_BSTR;

var.bstrVal = str2;

//Now Populate SAFEARRAY with Data.

HRESULT hrs = SafeArrayPutElement(psa,aiIndex,&var);

//Following is to Check
whether SafeArrayPutElement is successful or not. just for

if(hrs == S_OK)

cout<< "S_OK";

else if(hrs == DISP_E_BADINDEX)


else if(hrs == E_INVALIDARG)

cout<< "E_INVALIDARG";

else if(hrs == E_OUTOFMEMORY)


//Have to release
Created String.

env->ReleaseStringUTFChars( oneDim, szStr );



//Finally Create Variant



var1.parray = psa;

//Return Variant
Representing Two-Dimensional Java 's String Array String[][]

return var1;


Printing 2D BSTR SAFEARRAY Contents

void printSafeArrayContents(SAFEARRAY psa*)


long arrayIndex[2];

cout<< "=============Printing Out..==========="<<endl;

for(arrayIndex[0] = 0; arrayIndex[0] < 6; arrayIndex[0]++)


for(arrayIndex[1] = 0; arrayIndex[1] < 2; arrayIndex[1]++)


VARIANT result;

SafeArrayGetElement(psa, arrayIndex, &result);

cout<<result.bstrVal <<endl;


cout<< "========================="<<endl;


Generate 2D String array (jobjectArray) from 2D SAFEARRAY, to pass back to Java (Borrowed from
JNISnippets Site and enhanced for SAFEAARRY)

jarray Get2DArrayFromSafeArray(JNIEnv* env, SAFEARRAY *psa)


char s[200];

jarray aref;

jobject job;

jclass class1;

jarray row[1];

int rows = 10;

int cols = 10;

int i;

int j;

long biIndex[2];

// Got to build each row



// get an String object

job = (env)->NewStringUTF("");

// get String class

class1 = (env)->GetObjectClass(job);

// get the row of String array objects

row[biIndex[0]] = (env)->NewObjectArray(cols,class1,job);

// initialize the elements



VARIANT result;

SafeArrayGetElement(psa, biIndex, &result); //Get Variant out of

sprintf(s,"%S",result.bstrVal); //Get BSTR value from
VARIANTand assign to char c*

job = (env)->NewStringUTF(s);
//Create New string from the value recieved




//Now once the rows are
constructed with columns in it , now attach it to Master index
row (This is little twisted)

class1 = (env)->GetObjectClass(row[0]);

// get the base array object

aref = (env)->NewObjectArray(rows,class1,0);

// fill in the array





// return the array

return aref;



Its lots of jumps-n-hoops to get this puppy working. I thought i was long done with my VC++/VB and it came back haunting me after 8 years. No complains; its like going back memory lane, opening Visual
Studio for VC++ and VB and sitting coding. Its fun afterall.


Developer Network
Code Project
Sun's Java
Cod Guru
Java/Win32 Integration resources
Good details
Online JNI Book

Wednesday, December 22, 2004

Real FUD on Open source usage, Solution is out there. Do not be misguided by skepticism

I agree with general notion of the subject, Where Open Source software should not be treated as "pick up and go, later forget about it". There got to be real appreciation in terms of following any Licensing issue, Make sure the licensing terms and conditions and all Attributes are well understood and there is no violation. That is where companies like Apptility LLC (their .com and .net area) helps in, where they are opening up a world for Open Source Governance.
Here is one panicky article, basically says "Every software in the world is dangerous except Microsoft products". Probably only Didio will agree to it or may be few people more.
Solutions are out there, it is just a matter of adopting it intelligently, Bottom line you save hell lot of money with few right steps initially by embracing Open source platform.

Monday, December 20, 2004

Social Computing: Getting Ahead of the Blog - TechUpdate - ZDNet

A very good old article by
Social Computing: Getting Ahead of the Blog - TechUpdate - ZDNet: "Mike Gotta" about Social computing and its multi-face capability. Its true it goes beyond Blogging/Wiki concept and reaches from all directions to the community, wherever there is a room for social communication. One of my old blogs on this Welcome to longtime; Social movement of this era mentions about Online social network like Linked In.
We have much more to go!!..

Tuesday, December 07, 2004

HiveMind: Apache’s Service-Configuration Microkernel; Answer to JBoss ’s ?

Well its a chase, Slow but steadily Apache is catching up tp JBoss , on its architecture , and new kid is on the block now. Check Introduction to HiveMind
Very intresting concept, whole Service orchestration/Message Brokering capability can be extended via this framework.
Look at hivemind as replacement for service-message middleware, derive its components and service configuration aspect to create run time/dynamic service, which can integrate legacy-thru-today web service.
Going back to comparison; May it is too early. but

JBoss J2EE Engine + Hibernate = Apache Geronimo + HiveMind + Torque

I'm certainly excited to explore HiveMind and Gerinimo as it matures.

Sunday, November 07, 2004

error: can't create transaction lock [Fedora rpm installation]

A Small tip regarding rpm installtion of Fedora, whenever you are running rpm command to install any of the plug-ins or packages , you might run into transaction lock issue,

# rpm -ihv RealPlayer10GOLD.rpm
# error: can't create transaction lock

Above is nothing but Super User access problem, All you have to login as Super user (su), like following.

# su
# password:[XXXXXXXX] <------------This will be invisible
# rpm -ihv RealPlayer10GOLD.rpm
# Installation....

A Small tip, but helps a lot for beginers

Friday, October 15, 2004

SOA Meets Compliance: Shift from age old to COA

Its a old say , no matter how raw your data is, How you architect your solution, eventually you have to obey the rules of BIG. Saying that what I mean is till a little while ago, we were all putting our head on SOA, and its beautification, Now making SOA look good is not enough, MAKING SOA SECURE IS MORE IMPORTANT,
Are we following rules provided by Governance, to make SOA bullet-proof?
Good article about SOA Meeting Compliance Compliance and Integration - SOA Meets Compliance: Compliance Oriented Architectures - ebizQ
We have seen this shift for ages
Raw Text -> XML->Web Services->SOA-COA
Every organization, who implement SOA in their indiviual business units they can not leave their services loose, it needs to meet whole nine yards of compliance, SOX (Sarbanes-Oxley),
Message to them is "do it slow but do it right",

More to come on this soon...stay tuned..

Tuesday, October 05, 2004

SOA; Open source Push

Indeed Simplicity is good to understand , whether it is in life or field where we work,
Basically the way I'm trying to take SOA as a example for Open source representation, and use Michael Curry's Blog as justification for my words.
SOA started with simplistic idea, as concept and stanard around XML based communication from different systems and went ten fold from basic Web service invocation framework (WSIF) to Web service Modeling Language/Web Service Management Layer, well it will go much further to moon..
Michael Curry's words about stanards like CORBA; why it didnt fly as much as SOA/Web Service, justifies Open source widespread and its fundamental adoption in the developer community for any technology/concept/standard faster than anything that happened decades ago.
As community grows, reach becomes easy, more power to open source.

Wednesday, September 29, 2004

Backing up and restoring MySQL databases

Backing up and restoring MySQL databases: "Backing up and restoring MySQL databases"
Helps a lot in migration process. This is a good article where you can start doing things quick and clean.

Monday, September 20, 2004

Joe Walnes, Blog

Good resources for day to day work..Joe Walnes, Blog

Wednesday, September 15, 2004

Yahoo! News - Next Phase For Web Services Pioneer : Web Services in a Box

Good article with Toufic Boubez's interview.Yahoo! News - Next Phase For Web Services Pioneer: "Layer 7 Technologies"

Everyone is moving towards packaging their solution in a Hardware box and selling it as appliance, then why not web service management/security software.
Its like "Take it to Go" model for Software makers with blend of hardware appliance.
one more important point on this article was "Services orientation is an architectural principle that you can use to build anything, no matter what kind of application or architecture you do", Indeed its how people see SOA and making that useful to business derivatives like Business Process Management.

Monday, September 13, 2004

LinuxWorld | How will companies ever make money off Open Source?: Governance explained in few lines

LinuxWorld How will companies ever make money off Open Source?: "How will companies ever make money off Open Source?"
One way to present Open source and revenue model from open source, making sure creator of the Open source software and subscriber/modifier obey the rule.

Wednesday, September 08, 2004

sodaplay: amazing machine intelligence

A nice website; well nice is an understatement, i would say amazing website sodaplay. where you can go construct your own models based on fundamental mathematical co-ordinates
Its a 360 degree spin on How human visualize Maths. check out the constructor

More on this coming soon..

Thursday, September 02, 2004

What is REST ? : REST By example?: Collabrate with Web Services

Very good primer for REST.
This website defines REST in a beautiful way, absolutely must read for novice users.

REST: An Architectural Style, Not a Standard: Good definition, clears 1000 questions at the first instance itself

REST uses standards to build architecture, a very fundamental concept of any framework. Together REST with Popular web standards (HTTP, XML, SOAP) will form a Framework for innovative business solution.
Knowledge is contagious!...

Tuesday, August 31, 2004

Service Orchestration with WSML : SOA gets more power.

SOA gets more power with service orchestration via WSML.Web Services Management Layer (WSML)
WSML is Web Service Management Layer , or Web Service Model, In depth its all about Service orchestration for smooth and sweet SOA.
Enterprise Service BUS gets a a new face in the form of WSML.

Tune in for more....

Oracle Sequecnes and Cache Value "20" mystery: Sequences with "cache" option can skip numbers

Sequences with "cache" option can skip numbers Good article written here.

The default CACHE value for a sequence is 20, which means that after every 20 callsfor nextval Oracle has to update seq$ and refresh its cache.

Small tip over here about how to write sequences with or witout cache .

Monday, August 30, 2004

Uninstall Oracle 9i

Very helpful article Uninstall Oracle 9i
Saves your time, believe me without this you will waste whole day.

Wednesday, August 25, 2004

Welcome to longtime; Social movement of this era

Welcome to LinkedIn
Amazingly simple and easy to see how people can be linked to you thru your profile.
You can say what our ancestors (fathers, grand parents, way before that...) used to spend years in finding a contact linking with their friends and missing family, Linked In will do it in seconds. Its amazing to see what this age of intelligence can do and cut years of hard work into ease.
Whole social movement is driving into mass meeting time, where millions of people meet on the X * Y resolution computer screen and greet each other. Its truly a "Meet and Greet" board for people.
Are you linked in??!! , I'm.....Keep watching for new social movements like Blogging and Wiki phenomena. First Glance its "Write and Publish" but in depth its humangous in potential, to revolutionize today's social context. Stay in tune.. For more!!..

Thursday, August 19, 2004

Practical Adoption of Design Patterns: Hybrid Implementation Pattern

This article Practical Adoption of Design Patterns explains about Design patterns and Antipatterns adoption.
Applying all together creates fundamental building block for architecure and framework. It also gives birth to Anti-Pattern (different from AntiPattern) thinking .
1) Where developer/Architect has the knowledge of what design patterns he/she wants to adopt or shortlist.
2) With This knowledge come up with raw design thinking, more radical is much better
3) Apply raw design thinking into trusted design patterns. What you get is Hybrid Implementation pattern (Anti-Pattern + Design Pattern(AntiPattern))
Eventually implementattion should be reused, thats a true out come of design patterns and its study.

Monday, August 09, 2004

How to Convert and Sort Dates in XSL : Small Tip..

Sometimes small things comes pretty handy. Like this one;

Scenario : Pick the biggest date from the list of dates.


  • Converting a Date from one format to another
  • Sort them in ascending order.
  • Pick the first Date from the list ( thats the one you looking for ;) )

Assume your input XML is something like this (Date format is YYYYMMDDTHH:MM:SS)

<Date>20040931T18:31:04</Date> <Date>20040831T18:31:04</Date> <Date>20040715T18:31:04</Date> <Date>20041223T18:31:04</Date>

XSL file

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl=";
<xsl:template match="/">
<xsl:for-each select="DateList/Date">
<xsl:sort order="ascending" select="translate(.,'T::', ',')"/>
<xsl:if test="position() = last()">
<xsl:value-of select="."/>

This will print output as

This is biggest date. you can also print the date in a different format.

  • translate() : does the same job as search and replace
  • ".,'T::', ',' " : "." means Date node value, "T: : ',' " means search for T and : and replace with ' ' (blank space)
  • position() = last()" : means if current index == last index (position(): returns current index)

Happy XSLTingggg!!..

Tuesday, July 27, 2004

OpenSource OverWhelming OverPowering : 3 O's: Free Software, Pay For Services.

  • Day by day open source is becoming overwhelming, why is that ??. 'cauz indeed it is.
    Everytime you have some need for small utility, which you are quite sure exists out there on the web, you "google" and land up in some open source repository. initially you were intended to spend 5 mins in grabbing your utility and get the hell out of there, but now by the time you are out of this website you must spend hours in it, reason, its too "Overwhelming", there is tons of information out there, too hard to resist.
  • Traditional product based companies in a pre-Open source era (early to mid 90's ) wrote the dazzling products and sold it for millions. Today you go and look for similar products you will find atleast 3-5 products on an average all for "FREE" (Sounds so good!!). So what is the conclusion.

"Did all those customers wasted millions of $$ ??", probably not for their time, but todays time, yes its what "Software" should be open source and free, and what customers should pay is for "Services". So Open source is "OverPowering" over traditional/commercial sofware products.

Its all about justification of Customer's "Artha" (Money in Sanskrit) and making them happy for what they pay.

more to come soon.. on this subject. its endless.!!

Monday, July 26, 2004

MySQL / Windows XP dilemma ; Check your version


Windows XP / MySQL 4.1 (beta release) / Connection problem via MySQL Connector/J
Error like : java.sql.SQLException: Server connection failure during transaction...Attempted reconnect 3 times...

My Blah! Blah!
I learned this hard way (real hard way!!) , I wish someone would have told me this, so much for not reading product documentation. I'm not even sure whether its documentated somewhere. Well "Googling" works all the times.  I'm doing something with Apache Torque and MySQL under struts/tomcat. recently moved to Windows XP from NT for some secret business reasons (;)) . So on NT my whole setup is works like charm, as soon as i started setting up everything on XP machine, I downloaded (unstable small little beast!!) and what i see the behavior which is very frustrating and painfull search for the problem, but no clue at all what could be the problem.
  •  Downloaded & Installed MySQL 4.1 (beta release) , running Torque with this version what i see is no error, all Torque says "Connection is null...." doesnt make sense when all the parameters are right
  • Went down to much lower level, wrote my jdbc calls, connection, statement whole nine yard, what i get is following java.sql.SQLException: Server connection failure during transaction...Attempted reconnect 3 times...  absolutely ridiculous, MySQL works fine with Control center, all permissions seems to be fine, With GRANTS/ACCESS on the user.

Guessed this could be nasty version issue, uninstalled MySQL 4.1  and installed MySQL 4.0. Daeeeeeemmmnnn! it worked like a charm again.


Roll back on Old version MySQL 4.0 still rocks. They Say  for new developement use MySQL 4.1 ; Think twice before wasting 4-5 days on this and later discovering that its a version issue.  MySQL 5.0 ; Hell No!! , Dont even go there yet!. till things stabalize.!!..



Quick and Dirty Apache 2.0.48 –SSL-mod_ssl

• Download compile mod_ssl source distribution from• Unzip it and place file in following manner
o openssl.exe, libeay32.dll, ssleay32.dll in /bin directory
o in /modules directory
o ssl.conf in /conf directory
o openssl.cnf in /bin directory (this one is only needed if you want to create test site certificate; if you are buying certificate from CA then you will not need this. )
• Open /conf httpd.conf file and add following
o LoadModule ssl_module modules/
(Sometimes it’s already present in httpd.conf, in that case just uncomment the line)
• Make sure following block is present in httpd.conf
o Include conf/ssl.conf

(This will load ssl.conf when mod_ssl module is loaded, above block is usually present in default httpd.conf)
• Open ssl.conf and make sure server paths are correct in the file, especially
o DocumentRoot
o Server name
o Server admin
• Go to /bin and execute following to create self-signed server certificate. Answer questions accordingly, “Common name” will be the site name e.g.
o openssl.exe req -config openssl.cnf -new -nodes -out server.csr -keyout server.key
o openssl.exe x509 -in server.csr -out server.crt -req -signkey server.key -days 365 -set_serial 1
(Increment the serial number each time you create a certificate.)
• Move files "server.key" and "server.crt" to your apache2\conf folder. Delete files ".rnd" and "server.csr".
• Start Apache. Assuming it starts ok; test it with your preferred web browser.
• Point to https://localhost/myworld
• Now you are SSL enabled.

Quick and Dirty Apache 2.0.48 –Jk2-Tomcat 4.1.29X

• Install Tomcat, do not start tomcat
• Download compiled Jk2 Connector from Apache site which has jk2 dll/shm files also.
• Before installing Apache make sure system is not running any Web server on Port 80, like Microsoft IIS, if yes stop the web server and then Install Apache. Once Apache is installed it starts the web server on port 80
• Go and Stop Apache web server
• Go to /conf/
• Add following ; text in < shouldn’t be added>
o handler.list=channelSocket,request
o channelSocket.port=8009
o channelSocket.address=
• Go to /conf
• Open httpd.conf and add following
o LoadModule jk2_module tomcat-connector/mod_jk2-2.0.43.dll
(We will create tomcat-connector directory in next step)
• Create file called in /conf and following should be the content
o [shm:]
o file=C:\Program Files\Apache Group\Apache2\logs\jk2.shm
o size=1000000
o [channel.socket:localhost:8009]
o [uri:/examples/*]
o [uri:/myworld/*]
o [uri:/tomcat-docs/*]
• Copy jk2.shm to /logs directory
• Create tomcat-connector directory under and copy mod_jk2-2.0.43.dll file in there
• Start Tomcat first and then Apache
• Go to http://localhost/myworld , you should be able to get into your application without Application server port now.
• You are all set.

Jakarta Ant and Reflection Conflict: Power of FORK!!

Have you ever seen java.lang.NoClassDefFoundError: sun.reflect.SerializationConstructorAccessorImpl while running from your application via Ant target.???. ever wondered how come this error when you run an application, but never conflicted while compiling with current set of jar files??..
  You must have speculated reasons like
  •  Java version might be a problem , Hey jdk_14XX is not right lets switch to jdk_13..
  • May be my ant version is not rite or conflicting with jdk version.

The main reason is Ant and its Virtual machine. whenever we write (Compile task) or (Excecution task) we give control to Ant to determine and look for java in its own way,  Java is stringent in Non-Fork mode on classpaths. So in non-fork mode confusion raises for specific reflection classes above.


All you have to add  fork="true"  (some ppl do it "yes" option too..feel free to experiment:)), to your Ant and tasks,

From above tweak we say use another VM . which means it kicks in class execution in another VM.

tasks will look something like this

><javac srcdir="${src_dir}" fork="true" destdir="${deploy_dir}"><classpath refid="class.path"></javac><java classname="" fork="true"><classpath refid="class.path"></java>