YOUR FEEDBACK
johnpetersen wrote: Great post. You hit some good points, and hopefully me sending this post. It wil...


2008 East
DIAMOND SPONSOR:
Data Direct
Frontiers in Data Access: The Coming Wave in Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
Intel
Virtualization – Path to Predictive Enterprise
Green Hills
IT Security in a Hostile World
JBoss / freedom oss
Practical SOA Approach
GOLD SPONSORS:
Software AG
The Art & Science of SOA: How Governance Enables Adoption
PlateSpin
Effective Planning for Virtual Infrastructure Growth
Fujitsu
Automated Business Process Discovery & Virtualization Service
Ceedo
Workspace Virtualization
Click For 2007 West
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
SYS-CON.TV
TOP THREE LINKS YOU MUST CLICK ON


Hosting ActiveX/.NET Controls in a Java Application...the Direct Way
"Care For Some .NET With Your Java...?"

This article describes how to host an ActiveX/.NET control in a Java application that is targeted for the Microsoft Windows Platform. I'll assume you know the fundamentals of Java, C++, JNI (Java Native Interface), Win32, COM (Component Object Model), and ATL (Active Template Library).

Because a .NET control can be exposed as a COM component by using the COM interoperability services provided by the .NET Framework, I'll start by hosting the ActiveX control. I'll be using the control, the ActiveX control, and the COM component interchangeably.

The ActiveX Control and Its Container Review
In short, ActiveX controls are COM controls that implement a set of standard COM interfaces. An ActiveX control is hosted by a container, which must provide a window to act as the parent for the child control and implement a set of COM interfaces for communication between the control and the container. Figure 1 shows the major interfaces implemented by the container and the control. (Please refer to the Microsoft Platform SDK for more information about ActiveX control.)

Creating the ActiveX Control and Its Container in C++
As shown in Figure 1, an ActiveX control container needs to implement a lot of interfaces. Creating such a container could be very complex. Luckily ATL provides a CAxWindowT class template that simplifies this process. (For more information about ATL, please refer to the book, ATL Internals.) Listing 1 shows how easy it is to create a control and its container by using ATL (all the error-checking code in this article is omitted for clarity).

CJavaCOMBridge is a class derived from an ATL CWindowImpl class template, which provides its derived classes with Windowing functionality. CJavaCOMBridge is defined in Listing 2.

All the dirty work of creating the container and control is done by axwnd_, whose type is CAxWindow, which is one of the greatest classes from ATL.

ActiveX Control Java Wrapper, Hooking an ActiveX Control to an AWT Native Interface
Adding an ActiveX control to any AWT/Swing container should be as easy as adding a button or other standard widget. To achieve this convenience, a Java wrapper, say the JAxControl, is needed. It will work as the proxy of the ActiveX control on the Java side. Naturally the JAxControl should extend from an AWT/Swing component and in one of its native methods Listing 1 will be called.

However, in Listing 1 there is a HWND typed parameter parentWnd, which is the parent window of the control container. Where does this native window handle come from?

Remember that for any AWT/Swing heavyweight component, there is a native peer associated with it. So the aforementioned native window handle could be an AWT/Swing heavyweight component's native window and it is. How to obtain it? Until Java 1.5 the only documented way to get a native window handle was through the java.awt.Canvas class (please refer to jawt.h file, which is under the %jdkhome%\include directory). Listing 3 shows the relevant code.

This means that the JAxControl has to be a derived class of java.awt.Canvas and Listing 1 will be modified as shown in Listing 4.

Though the native handle can be obtained anytime after the Canvas is realized, a reasonable place is the addNotify method in which the native peer will be created. Then the JAxControl could be something like Listing 5.

Unfortunately Listing 5 won't work. The addNotify method is executed in the Main-Method thread while the Canvas native window is created in the Toolkit thread in which the native Windows message loop is served. (See below for more discussion about Sun Hotspot JVM threads.) This means the control created this way is useless because it can't process Windows messages. (For more information about Windows programming, please see Win32 Programming.) To fix this problem, the control could be created in its own native thread. Listing 6 shows one way to do it. (Listings 6-13 can be downloaded from www.sys-con.com/java/sourcec.cfm.)

Please notice that the native thread should be attached to the existing JVM to enable it to work with the JVM's synchronization scheme.

This approach solves the messaging problem, however, it has several drawbacks. First, it increases the interthread communication. Second, it violates the basic Win32 GUI programming rule because the control is created in a different thread from its parent. This could easily cause deadlock.

A better approach is subclassing an AWT Canvas native window class. A native window class is just a WNDCLASSEX structure containing all the information to describe a window. The most important member of WNDCLASSEX is the window procedure function (often called WndProc) pointer. A window procedure function is used to handle Windows messages. Remember that most of the Win32 APIs are written in C, which is not an object-oriented language. There is no Win32 API to let you derive a window class from an existing one. However, it does use object modeling to some extent. It provides some sort of polymorphic behavior for a window class by replacing its window procedure function pointer with the subclass's function pointer. If the subclass function doesn't handle a Windows message, it will pass the message to the super-class function. This is the so-called subclassing.

To subclass an AWT Canvas window class (it's named as SunAwtCanvas, however, the class name is not important here), a native subclassNativePeer method is added to the JAxControl class. Listing 7 shows the magic.

Note how a user-defined Windows message is used to create the control in the Toolkit thread. (For more information about how to define a user-defined Windows message, please see "Message Management.")

Subclassing the AWT Canvas native window class opens the back door to a mixed usage of the native window and a Java AWT/Swing component. It is efficient and powerful. The only downside is that it's relying on the AWT implementation detail.

Garbage Collection and Resource Management
JAxControl contains native resources by wrapping the ActiveX control. Though any JAxControl instance will be garbage collected eventually, it doesn't guarantee that the native resources will be freed. To avoid a memory/resource leak, special care has to be taken. A common mistake is to abuse the finalizer to reclaim resources. Unfortunately this is the wrong approach in general.

The solution is to provide an explicit termination method. Here, I'm applying the Dispose pattern that the .NET Framework has promoted, i.e., all the classes that intend to manage resources specially should implement the IDisposable interface, which has a dispose method. The dispose method will clean all the native resources, such as close a database connection and terminate child threads. Actually this pattern is applied internally by Sun; java.awt.Window, java.awt.Graphics, and some other classes all have a dispose method. Unfortunately this pattern is not abstracted to a higher level.

In addition to applying the Dispose pattern, it's necessary to override the removeNotify method. removeNotify is called by the toolkit internally to destroy the native peer. The ActiveX control and other native resources need to be reclaimed before the native peer is destroyed.

To summarize, the Java ActiveX control wrapper should look similar to Listing 8. The ComponentListener is used to adjust the control's size accordingly.

About Stanley Wang
Stanley Wang is a lead software developer at Vcom3D, Inc., and the author of JTL. He received his MS in computer science from the University of Florida. He is interested in system programming, generic programming, and computer graphics.

YOUR FEEDBACK
James Schumacher wrote: the article states: "To fix this problem, the control could be created in its own native thread. Listing 6 shows one way to do it. (Listings 6-13 can be downloaded from www.sys-con.com/java/sourcec.cfm.)" When I access this URL I see: File Not Found Request /sourcec.cfm BlueDragon Time @ Server: 11:19:45.866 Thursday, 8 June 2006 How can I access the full sources?
LATEST JAVA STORIES & POSTS
JavaScript is pretty much everywhere you look these days, reaching far beyond your desktop browser. Adobe AIR lets you use JavaScript to create desktop installed HTML and AJAX apps. Apple uses it in its gadgets and in the iPhone's browser. And Nokia recently announced support for...
The Java Community Process (JCP) Program Management Office has announced the final results of the 2008 JCP Executive Committees (EC) elections. After two ballot rounds – for ratified and elected seats – the winners are Ericsson, SpringSource, SAP, Intel, and Werner Keil for t...
If you think your network is safe from the new strains of content security threats, think again. Today’s cybercriminals use sophisticated attacks that multiply quickly and thwart traditional defenses, rendering conventional security ineffective and unmanageable. To protect your...
Tidal Software has announced Intersperse 8.0, a product that monitors J2EE and .NET applications and their transaction component performance to produce meaningful metrics for managing applications and high-level business processes. The product leverages a combination of lightwei...
ILOG has announced ILOG JViews 8.5, the latest version of ILOG’s Java-based visualization suite, with new features that enhance the creation of Rich Internet Applications as well as desktop applications. ILOG JViews 8.5 adds support for the Eclipse platform including the new IL...
Emulex has announced that it will offer Fibre Channel Host Bus Adapters (HBA) and Fibre Channel over Ethernet (FCoE) Converged Network Adapters (CNAs) for use with OpenSolaris’ Common Multiprotocol SCSI Target (COMSTAR), thereby providing end-to-end Fibre Channel and FCoE suppo...
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


SYS-CON FEATURED WHITEPAPERS

SPONSORED BY INFRAGISTICS
In every field of design one of the first things students do is learn from the work of others. They ...
There are many forces that influence technological evolution. After a decade of building enterprise ...
2008 is going to be an important year for Rich Internet Applications. Most organizations are deliver...
The OpenAjax Alliance is developing an Ajax industry wishlist for future browsers, using a dedicated...
Infragistics announced the availability of two Community Technology Preview (CTP) User Interface (UI...
The YUI development team has released version 2.5.2; you can download the new release from SourceFor...
ADS BY GOOGLE