Comments
Richard Davies wrote: The UK has a good crop of technology pioneers in cloud computing - for example ElasticHosts, FlexiScale, Flexiant, OnApp - and also some strong government initiatives such as G-Cloud. We will have to see whether this kind of technical leadership converts into swift mass-market adoption or not.
Cloud Expo on Google News


2008 West
DIAMOND SPONSOR:
Data Direct
SOA, WOA and Cloud Computing: The New Frontier for Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
GOLD SPONSORS:
Appsense
User Environment Management – The Third Layer of the Desktop
Cordys
Cloud Computing for Business Agility
EMC
CMIS: A Multi-Vendor Proposal for a Service-Based Content Management Interoperability Standard
Freedom OSS
Practical SOA” Max Yankelevich
Intel
Architecting an Enterprise Service Router (ESR) – A Cost-Effective Way to Scale SOA Across the Enterprise
Sensedia
Return on Assests: Bringing Visibility to your SOA Strategy
Symantec
Managing Hybrid Endpoint Environments
VMWare
Game-Changing Technology for Enterprise Clouds and Applications
Click For 2008 West
Event Webcasts

2008 West
PLATINUM SPONSORS:
Appcelerator
Get ‘Rich’ Quick: Rapid Prototyping for RIA with ZERO Server Code
Keynote Systems
Designing for and Managing Performance in the New Frontier of Rich Internet Applications
GOLD SPONSORS:
ICEsoft
How Can AJAX Improve Homeland Security?
Isomorphic
Beyond Widgets: What a RIA Platform Should Offer
Oracle
REAs: Rich Enterprise Applications
Click For 2008 Event Webcasts
SYS-CON.TV
Top 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.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

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?


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?
Enterprise Open Source Magazine Latest Stories . . .
Apache Deltacloud, the Red Hat-contributed ReSTful API that abstracts differences between clouds so services on any cloud can be managed – provided of course there’s a driver – has graduated from the Apache Foundation’s incubator and is now a full-fledged Top-Level Project (TLP). The...
With Cloud Expo 2012 New York (10th Cloud Expo) just four months away, what better time to start introducing you in greater detail to the distinguished individuals in our incredible Speaker Faculty for the technical and strategy sessions at the conference... We have technical and st...
AMD said late Tuesday that its chief sales officer Emilio Ghilardi had left the company and that CEO and president Rory Read is going to do his job while a replacement is sought. AMD didn’t say why Ghilardi left but it’s assumed Read wants his own people. Read is relatively new to th...
During the lifespan of M3 (Monitis Monitor Manager) there has always been something lacking – timers. M3 execution procedure was outlined in this previous article. The execution mentioned in the latter was a one-time-execution, whereas server monitoring requires periodic invocati...
Red Hat is putting its bought-in Gluster scale-out NAS storage technology, acquired in October, on the Amazon cloud. It’s styled Red Hat Virtual Storage Appliance for Amazon Web Services and other clouds are supposed to follow in short order.
A new episode of the screencast series is now available at the OpenNebula YouTube Channel. This screencast demonstrates the new easily-customizable self-service portal for cloud consumers. Its aim is to offer a simplified access to shared infrastructure for non-IT end users. The scree...
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
ADS BY GOOGLE