Integrating Java and COM

The main challenge I faced was to integrate Java with COM objects. I tried few java2com bridges but I was not satisfied with the solutions. It was too completed and tend to break at the edges.

I decided to use vbscript. It is very simple to work with and it (obviously) has very good COM integration. The problem with vbscript is that it missing very impotent feature, it don't have the option to work as an interpreter. I need this flexibility to build the vbscript dynamically as the Java code is executed.

The first step was to build a vbscript interpreter. Following is the code I used:

do while true
    set ln = Nothing
    ln = wscript.stdin.readline
    if lcase(trim(ln)) = "exit" then exit do
    on error resume next
    err.clear
    wscript.echo "stdout: <"
    execute ln
    wscript.echo ">" & vbCrLf
    wscript.echo "errorCode: <"
    wscript.echo err.number
    wscript.echo ">" & vbCrLf
    wscript.echo "errorInfo: <"
    wscript.echo err.description
    wscript.echo ">" & vbCrLf
    wscript.stdout.write("vbscript# ")
loop

To work with the script you should save it to a file, open command shell and execute the script using the following command:

cscript.exe shell.vbs

Now it work like shell application. I can execute vbscript command one by one.

The problem is now in new domain, working with the script from within your java program.

The next java file do just that. It enable script deployment, for every command I get the standard output, the error code and the error description, and pass it to upper layers as exception.

 In this link you can find the full java utility file

Following is a java code example:

public static void main(String[] args){
	VbShell vb = new VbShell(new File(System.getProperty("user.dir")));
	try {
		vb.launch();
		
		ShellCommand sc = new ShellCommand("Set Word = CreateObject(\"Word.Application\")", null);
		vb.executeCommand(sc);
		System.out.println(sc.toString());
		sc = new ShellCommand("Word.Visible = True", null);
		vb.executeCommand(sc);
		System.out.println(sc.toString());
		sc = new ShellCommand("Word.Documents.Add", null);
		vb.executeCommand(sc);
		System.out.println(sc.toString());
		Thread.sleep(2000);
		sc = new ShellCommand("Word.Quit", null);
		vb.executeCommand(sc);
		System.out.println(sc.toString());
		vb.exit();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	vb.exit();
}

Comments