07 | 01 | 2009
Main Menu
Affiliates
Who's Online
We have 12 guests online
Alexa
Invoking Win32 API and Activex Components (Com dlls) from Java II
Java Concepts
Written by rajesh   
Thursday, 03 July 2008 17:06

Rating 3.1/5 (7 votes)

Invoking Win32 API and Activex Components (Com dlls) from  Java

In the second part of this series we shall see some more libraries that all you to use Win32 APIs and Com components from you java application without writing any native code.

 

JNA https://jna.dev.java.net

JNA is also a library that allows you to access . JNA provides Java programs easy access to native shared libraries (DLLs on Windows) without writing anything but Java code-no JNI or native code is required. This functionality is comparable to Windows' Platform/Invoke and Python's ctypes. Access is dynamic at runtime without code generation.

 

JNA's design aims to provide native access in a natural way with a minimum of effort. No boilerplate or generated code is required. While some attention is paid to performance, correctness and ease of use take priority.

 

The JNA library uses a small native library stub to dynamically invoke native code. The developer uses a Java interface to describe functions and structures in the target native library. This makes it quite easy to take advantage of native platform features without incurring the high overhead of configuring and building JNI code for multiple platforms.

 

/**
 * {Java By Example}
 * Licensed under GPL 3.0 http://www.gnu.org/licenses/gpl-3.0.html
 */
package org.jbe.win32.jna; 
import com.jinvoke.JInvoke;
import com.jinvoke.NativeImport;
import com.sun.jna.Function;
import com.sun.jna.NativeLibrary; 
/**
 * @author Rajesh
 *
 */
public class BlockInput
{
 
 public static void main(String[] args)
 {
 NativeLibrary lib = NativeLibrary.getInstance("User32");
 Function fun = lib.getFunction("BlockInput");
 fun.invoke(new Object[]{Boolean.TRUE});
 try
 {
 Thread.sleep(10000);
 }
 catch(InterruptedException ie)
 {
 
 }
 lib.dispose();
 }
}

Usage is pretty simple, first you have to get an instance of the "NativeLibrary" class corresponding  to the dll that you want to access. Then get the instance of the "Function" class corresponding to the Win32 function that you wish to invoke. Finally invoke the function. Finally dispose the "NativeLibrary" instance. This is better that other libraries which we saw before in that you need to dispose only the library not each an every function that you invoked.

 

Pros: Easy to use, good documentation, excellent support and active development, Java.netJ, and support for a large variety of OS.

Cons: Cannot invoke ActiveX components.

 

 

JACOB http://danadler.com/jacob/

JACOB is a JAVA-COM Bridge that allows you to call COM Automation components from Java. It uses JNI to make native calls into the COM and Win32 libraries. The JACOB project started in 1999 and is being actively used by thousands of developers worldwide. As an open-source project, it has benefitted from the combined experience of these users, many of whom have made modifications to the code and submitted them back for inclusion in the project. Unlike the libraries that we saw before JACOB is for accessing com interfaces and cannot be used to directly invoke Win32 API.

For the same reason, usage of JACOB is entirely different.

/**
 * {Snipcode.org}
 * Licensed under GPL 3.0 http://www.gnu.org/licenses/gpl-3.0.html
 */
package org.jbe.win32.jacob; 
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant; 
public class DispatchTest
{
 public static void main(String[] args)
 {
 ActiveXComponent xl = new ActiveXComponent("Excel.Application");
 Dispatch xlo = xl.getObject();
 try {
 System.out.println("version="+xl.getProperty("Version"));
 System.out.println("version="+Dispatch.get(xlo, "Version"));
 xl.setProperty("Visible", new Variant(true));
 Dispatch workbooks = xl.getProperty("Workbooks").toDispatch();
 Dispatch workbook = Dispatch.get(workbooks,"Add").toDispatch();
 Dispatch sheet = Dispatch.get(workbook,"ActiveSheet").toDispatch();
 Dispatch a1 = Dispatch.invoke(sheet, "Range", Dispatch.Get,
 new Object[] {"A1"},
 new int[1]).toDispatch();
 Dispatch a2 = Dispatch.invoke(sheet, "Range", Dispatch.Get,
 new Object[] {"A2"},
 new int[1]).toDispatch();
 Dispatch.put(a1, "Value", "123.456");
 Dispatch.put(a2, "Formula", "=A1*2");
 System.out.println("a1 from excel:"+Dispatch.get(a1, "Value"));
 System.out.println("a2 from excel:"+Dispatch.get(a2, "Value"));
 Variant f = new Variant(false);
 Dispatch.call(workbook, "Close", f);
 } catch (Exception e) {
 e.printStackTrace();
 } finally {
 xl.invoke("Quit", new Variant[] {});
 }
 }
}
`

 

You need to create an instance of the "ActiveXComponent" class specifying the name of the active component that you wish to invoke. Then  get the different functions in that active X object using the getProperty method. The finally invoke using the invoke method             .

 

Pros: Easy to use

Cons: decent Documentation and Support, Development seems to be inactive.

JCOM http://sourceforge.net/projects/jcom/

JCom is also a bridge library between Java and Com to enable COM object access from Java classes. Example: Creating an Excel worksheet, or using Visual Basic COM application from a Java application.

Usage of JCOM is very similar to that of JACOB.

package org.jbe.win32.jcom; 
import jp.ne.so_net.ga2.no_ji.jcom.*; 
public class testWord { 
 public static void main(String[] args) throws Exception {
 ReleaseManager rm = new ReleaseManager();
 try {
 System.out.println("Word‚");
 IDispatch wdApp = new IDispatch(rm, "Word.Application"); 
 wdApp.put("Visible", new Boolean(true));     
 IDispatch wdDocuments = (IDispatch)wdApp.get("Documents");
 Object[] arglist1 = new Object[1];
 arglist1[0] = "D:\\Java Experiments\\win32\\jcom224\\jcom224\\demo\\word\\JCom.doc";
 IDispatch wdDocument = (IDispatch)wdDocuments.method("Open", arglist1);
 String fullname = (String)wdDocument.get("FullName");
 System.out.println("fullname="+fullname); 
 IDispatch wdWords = (IDispatch)wdDocument.get("Words");
 int word_count = ((Integer)wdWords.get("Count")).intValue();
 for(int i=0; i<word_count; i++) {
 Object[] index = new Object[1];
 index[0] = new Integer(i+1);        
 IDispatch wdWord = (IDispatch)wdWords.method("Item", index);
 String text = (String)wdWord.get("Text");
 System.out.println(text);
 } 
 IDispatch wdTables = (IDispatch)wdDocument.get("Tables");
 System.out.println(wdTables);
 int table_count = ((Integer)wdTables.get("Count")).intValue();
 System.out.println("Testing"+table_count);
 for(int i=0; i<table_count; i++) {
 Object[] index = new Object[1];
 index[0] = new Integer(i+1);        
 IDispatch wdTable = (IDispatch)wdTables.method("Item", index);
 System.out.println(""+i+"="+wdTable);
 } 
 System.out.println("printing");
 Thread.sleep(3000);    // 3sec
 wdApp.method("Quit", null);
 System.out.println("Over");
 }
 catch(Exception e) { e.printStackTrace(); }
 finally { rm.release(); }
 }
}

Pros: Easy to use, decent documentation, free, small size.

Cons: Development is not active

 

com4j https://com4j.dev.java.net/

com4j is the best and the most powerful library for accessing com components. It consists of two things.

  1. A Java library that allows Java applications to seemlessly interoperate with Microsoft Component Object Model.
  2. A Java tool that imports a COM type library and generates the Java definitions of that library.

You can read about the usage of com4j here

 

 

 

 

 

 

 

 



Add this page to your favorite Social Bookmarking websites
Reddit! Del.icio.us! JoomlaVote! Google! Live! Facebook! StumbleUpon! Yahoo! Free social bookmarking plugins and extensions for Joomla! websites!
Comments
Add New Search
dilas   |201.34.236.xxx |2008-07-19 20:09:58
Maybe talking about free/open-source products you listed all options, but for
commercial development my company is considering use J-Integra
(http://j-integra.intrinsyc.com/)

Take a look later !

=)
Andrew Davison  - J/Invoke     |202.12.73.xxx |2008-07-21 04:04:27
Take a look at J/Invoke at
http://www.jinvoke.com/about

There's more
examples at:
http://fivedots.coe.psu.ac.th/~ad/winJava/
John Patterson  - JNA usage   |72.85.185.xxx |2008-08-09 15:58:01
I think you've overlooked how most users of JNA would actually use the
library. The following equivalent code is more friendly to users of
a given native library, with a much more natural function
invocation:

Code:

import com.sun.jna.win32.W32API;

public class BlockInput {

public
interface User32 extends W32API {
void BlockInput(boolean flag);

  }

public static void main(String[] args) {

  User32
user32 =

 (User32)Native.loadLibrary("user32", User32.class,
W32API.DEFAULT_OPTIONS);
 user32.BlockInput(true);
try {

 Thread.sleep(10000);
}

 catch(InterruptedException ie) {
}
 }
}
John Patterson  - (reformatted example)   |72.85.185.xxx |2008-08-15 17:50:19
Code:

import com.sun.jna.win32.W32API;

public class BlockInput {
public
interface User32 extends W32API {
void BlockInput(boolean flag);

  }
public static void main(String[] args) {
  User32 user32
= (User32)Native.loadLibrary("user32",User32 .class,W32API.DEF
AULT_OPTIONS);

 user32.BlockInput(true);

try {

  Thread.sleep(10000);
}
 catch(InterruptedException
ie) {
}
}
}
parshant chandrakar   |121.247.65.xxx |2008-08-28 08:10:18
there is no any class
name WinAPI inside
import com.sun.jna.win32.W32API;
murad  - syria   |82.137.200.xxx |2008-10-16 10:17:48
thank you for all
Write comment
Name:
Email:
 
Website:
Title:
UBBCode:
[b] [i] [u] [url] [quote] [code] [img] 
 
:angry::0:confused::cheer:B):evil::silly::dry::lol::kiss::D:pinch:
:(:shock::X:side::):P:unsure::woohoo::huh::whistle:;):s
:!::?::idea::arrow:
Please input the anti-spam code that you can read in the image.

3.22 Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved."

Last Updated ( Thursday, 03 July 2008 17:34 )
 
Bottom Ad
Your Ad Here

Subscribe in a reader

Most Popular Articles
Ads
Popular Tags