|
|
|||
|
|
||
EarthWeb sites:
|
|
Chapter 20Calling COM Objects from Javaby Bryan Morgan
What separates Visual J++ and the Microsoft Virtual Machine from all other Java tools is the integration between Java and Microsoft's component object model (COM). Previous chapters provide an introduction to those readers new to using COM projects or, in particular, programming with COM objects. This chapter is primarily example oriented, illustrating how Java code can be written to call COM objects using Visual J++ and the Microsoft Virtual Machine. A Mix of COM with Your Java (or Java with Your COM!)When you have to use some combination of COM and Java (whether through COM objects, ActiveX controls, or some other means), you have three options:
Examples in this chapter examine the first two of these options. Both specifically deal with calling a COM object from within a Java program. The third option is presented in Chapter 21, "Building COM Objects with Java." Ground Rules for Calling COM Objects from JavaWhenever software components are integrated to form a working application, some setup and system configuration are required to ensure that the various components work together correctly. For instance, when a Visual Basic developer uses an OCX control on a form, this control must be registered with the operating system. When a UNIX programmer distributes a set of shared objects for use by one or more applications, the system path must be set to include the directory containing these libraries. Likewise, Java programmers must go through two primary steps before a COM object can be successfully compiled and used in a Java program. First, the COM object must be registered on the local system. Following this, the contents of the COM object's type library must be extracted using tools provided with Visual J++. Another step is required to actually distribute the completed Java classes to other users. This step requires the classes to be digitally signed for security purposes. Registering the ObjectThe first step applies to not only Java programmers, but programmers developing in any language: You need to register the COM object in the Windows Registry using the CLSIDs stored in the object. (Recall from Chapter 15, "GUI Development Using the Visual J++ Resource Wizard," that CLSIDs are globally unique identification numbers that are used to identify a COM object.) You can register COM objects several different ways.
At the simplest, you can record and manually add the required
Registry settings using the Registry tool, named REGEDIT.EXE
under Windows 95 and REGEDT32.EXE under Windows NT. You
can also write and run registration script files that will automatically
register the script's settings into the Registry. Perhaps the
simplest way to register many COM objects is by using the REGSVR32.EXE
tool.
REGSVR32 takes advantage of the fact that all COM in-process servers (DLLs and OCXs) are required to be self-registering by definition. REGSVR32 simply calls the necessary commands in the object to register it in the Registry. If an application is run without a corresponding COM object being registered, it is common to see an error message such as "Object Not Found" or something along those lines. When an application using OLE controls is originally run with errors, it is common to find that the set of controls was not registered.
REGSVR32 is a command-line tool that has a simple set
of options (see Table 20.1).
The REGSVR32 tool is used with the following command-line syntax: regsvr32 <options> filename.xxx The /s option is commonly used during an application's installation process to register a control in the background without alerting the user. Microsoft Internet Explorer uses the silent registration option to register ActiveX components as they are downloaded from remote locations. Creating Java Classes Using the Java Type Library WizardAfter a COM object has been registered with the system, it is still simply a DLL/OCX/EXE binary object residing on the hard drive. To allow the Java programmer to use this object, Microsoft could have simply added a thinly disguised native method interface to COM objects. However, because of the many similarities between Java and COM (see Chapter 16, "Java and the Component Object Model"), Microsoft provides a method to seamlessly combine COM and Java objects in source code. In other words, COM objects can be instantiated and used side by side with other Java objects with no special syntax or keywords required. This magic was accomplished by creating a tool that could examine the contents of a COM type library, extract them, and produce the corresponding Java class files to match the contents of the type libraries. As you know by now, after the class files are created, the import statement can be used to import a package or class into another Java class. The Java Type Library Wizard is used to build these class files in Visual J++. This wizard can be run from the Visual J++ IDE by selecting the Tools | Java Type Library Wizard main menu option. The application that responds to this menu selection is actually JAVATLB.EXE, located in your installation directory's \bin subdirectory. The Type Library Wizard can also be run from the command line with a set of extended options using the following syntax: javatlb <options> type_library_filename
Keep in mind that a type library can exist in a standalone .tlb
file. It can also be stored as a resource within a COM object
(.exe, .dll, .ocx, .olb).
When run on a type library, a directory (named with the type library's
filename) will be created in the trusted libraries directory on
the local machine.
One Java class file is created for each class or interface in
the type library. Options that can be used in combination with
the Java Type Library Wizard are listed in Table 20.2.
When run from the Developer Studio menu selection, the Java Type Library Wizard always produces a file named SUMMARY.TXT and places that file in the type library's trusted directory. This file contains the signatures for each method in the class file. In effect, the Java Type Library Wizard runs JAVATLB with the following syntax: javatlb /U:T library.tlb > SUMMARY.TXT Handling Security During Distribution
Security options become significantly more complex when Java classes
are combined with COM objects to build applications. First, using
ActiveX controls implies an entirely new set of security precautions
that may be new even to the veteran Java programmer. Second, Java
class files generated from a COM type library must be contained
in a CAB file and digitally signed using Microsoft's Code Signing
standard. Applets or applications that make use of these Java
classes will not run outside the Visual J++ Developer Studio unless
they are contained in a CAB file and have been signed. Security
issues are addressed in detail in Chapter 23, "Security with
ActiveX Authenticode." For now, let's assume that the samples
shown in this chapter (and Chapters 21, "Building COM Objects
with Java," 22, "Using ActiveX Documents to Convey Information,"
and 23) will be run from Developer Studio to avoid this problem.
Again, be sure to run all Java/COM examples included with Visual J++ or with this book from the Developer Studio environment. Because none of these classes have been signed and are not contained in a CAB file, a java.lang.VerifyError error may occur. Calling a COM Object from JavaThis section gives an example to illustrate how a COM object can be called from a Java applet or application. It would have been possible to create a COM in-process server DLL that exported a class or interface to be called from Java. However, the topic of creating COM objects using C or C++ is outside the scope of this book. (In addition, creating COM objects in Java is not discussed until Chapter 21.) Therefore, for purposes of illustration, the JavaCallingCOM sample included with Visual J++ is studied. The JavaCallingCOM sample application consists of a COM automation server DLL, Java applet, and set of HTML files used to display and document the sample application. The server DLL, comserver.dll, contains a set of available system sound IDs (stored as constants) along with the IComBeeper interface, which provides helper functions to select and play the sounds. Although it might seem a little odd because of the underlying complexity of what is actually happening, when the object's structure has been extracted into Java class files, it is extremely easy to use that object in Java source code. Following the steps outlined in "Registering the Object" before the COM DLL can be accessed from a Java program, the DLL must be registered and class files must be generated using the Java Type Library Wizard. Therefore, take the following steps: First, execute the following statement in the directory containing the COMServer DLL: c:\windows\system\regsvr32 comserver.dll. Following this exercise, use the Java Type Library Wizard to select the COMServer 1.0 Type Library to generate class files (see Figure 20.1). Figure 20.1 : The Java Type Library Wizard.
When the wizard has successfully generated the class files for the COMServer DLL, you can verify the classes by examining the \WINDOWS\SYSTEM\JAVA\TRUSTLIB\COMSERVER directory (or the trusted classes directory on your machine). In this directory, the following class files should have been created: BeeperConstants.class A file named SUMMARY.TXT also should have been created. This file will contain the signatures for all public methods and variables contained in each class or interface in the DLL of the COM. Listing 20.1 shows the contents of the generated SUMMARY.TXT file. Listing 20.1. The contents of the COMSERVER.DLL summary file.
Each constant defined in the BeeperConstants interface represents a system sound that will be played by calling the Play() method found in the IComBeeper interface. As described in Chapter 16, COM objects are always referenced by one of their exposed interfaces. This particular COM object can be accessed by the ICOMBeeper interface. By examining the usecom applet class in the usecom.java source file, you can see the COM object declared exactly like any other Java object: ICOMBeeper m_beeper; Later on, the COM object is instantiated using the standard Java new keyword: m_beeper = new CCOMBeeper(); From there, the Java list box is simply filled with text, and the sound associated with that list's index is set using the following lines of code: m_beeper.putSound(BeeperConstants.Asterisk); m_nameList[1].name = m_beeper.getSoundName(); m_nameList[1].value = m_beeper.getSound(); As you can see, the putSound(), getSoundName(), and getSound() methods are all defined in the ICOMBeeper interface in Listing 20.1. Figure 20.2 shows the JavaCallingCOM applet being run in Internet Explorer 3.0. Figure 20.2 : The JavaCallingCOM applet.
By selecting one of the sounds displayed in the list box and pressing the Play the Sound button, you will play the default sounds currently registered under Windows. This is an example of integrating Java with a COM object to do something that is simply not possible using Java alone. Because of security restrictions the Java security model places on Java applets, system resources such as hard drives, audio, or printers cannot be accessed using Java. Providing Active Content with Java Applets and ActiveX ControlsBecause ActiveX controls are compliant with the COM, you can also access them from Java code. This functionality gives you a huge existing base of ActiveX controls that can be used to build powerful Web pages. To provide truly active functionality to the user, several approaches can be used. Perhaps the most obvious starting point for a Java programmer is to build a Web page consisting entirely of Java classes. This allows you to design a page that can be viewed on many operating systems, including Windows, Macintosh, OS/2, and UNIX. This is a huge advantage that does not exist for the ActiveX developer. However, hundreds if not thousands of production-quality ActiveX controls currently exist that you can immediately use. The same cannot be said for third-party Java classes. Therefore, under certain circumstances, it may be necessary to build a Web-based application using existing ActiveX components. When this decision has been reached, you can choose to script the controls on a page using VBScript or some other ActiveX scripting language. For many ActiveX developers, this may be a viable option. However, this will not be a cure-all for many others. When ActiveX controls must be used in conjunction with some other powerful user-interface capabilities, a combination of Java and ActiveX offers the widest range of opportunities. The example used throughout the remainder of this chapter illustrates the use of Java with an ActiveX control to build an interactive charting application. Introduction to the Java/ActiveX ExampleThe program developed in this chapter makes use of an ActiveX control that can be downloaded from the Microsoft Web site at no cost. This control is combined with Java to build a charting application. Data is plotted in an ActiveX charting control based on a variety of user selections in the Java applet. As is shown in the example, a tiny bit of VBScript is used to "glue" the Java applet and ActiveX control together. A knowledge of VBScript is not necessary to understand the example; when the scripting language is used, it is explained. To download the ActiveX component and run this application, you must use Microsoft Internet Explorer 3.0 (or higher). If another browser appears on the market with ActiveX support, however, this example still might not work. Remember that the Java/COM integration is made possible with the Microsoft Virtual Machine. Any browser that does not support Microsoft's extensions to the Java Virtual Machine will not be able to run the sample application. (For the foreseeable future, it appears that the Internet Explorer is the only browser with ActiveX and Java support.) Retrieving the ActiveX ControlThe control used to build this example is available free from Microsoft's ActiveX Web site. To download this control, go to http://www.microsoft.com/activex/gallery/default.htm and select the Chart control listed with the other Microsoft entries. When downloading the control, make sure that your security settings in Microsoft Internet Explorer are set correctly. When loading ActiveX controls embedded in an HTML page or installing these controls over the Internet using Internet Explorer 3.0, make sure that IE's security options are set to the Medium level. While the control is downloading, a digital certificate displays to verify that the software has been signed (see Figure 20.3). Figure 20.3 : The Chart control's verification certificate.
When downloaded, the Chart control is automatically registered onto your local system. Whereas Java classes are only temporarily cached to the local drive for a finite period of time by most browsers, ActiveX controls are permanently installed to your hard drive. Because this "feature" is unpopular with many users, Microsoft has stated that the permanent installation of ActiveX controls will be a user-configurable option in the future. To look at it from another angle, ActiveX controls have a temporary advantage over Java classes in this area for intranet developers: One of the frustrating aspects of Java development is that each time a user loads a page, he or she may have to reload entire Java classes even if the user just visited the site recently. This happens often with intranet applications, where corporate users are visiting a page constantly. ActiveX controls must be downloaded only once and are then installed on the user's system. The next time the user visits the page, the control loads instantly with no download time. Fortunately for "pure" Java developers, the Java Beans 1.0 specification provides for items known as jars, which store groups of Java classes to the local hard drive. This should greatly improve the startup performance of most Web-based Java applications. While Microsoft's Internet Explorer browser does not allow users to disable persistent caching of ActiveX controls, hopefully Java-enabled browsers will allow users to disable the caching of Java classes if they choose to do so. Also note that the documentation for this ActiveX control is available at http://www.microsoft.com/activex/gallery/ms/ieprog/chart.htm. This document includes a description of the properties, events, and methods supported by this object. Building Java Classes from the Control's Type LibraryAfter retrieving the ActiveX Chart control from the Microsoft Web site, you must retrieve the contents of its type library for a Java class to be able to converse with the control at runtime. To do this, use the Java Type Library Wizard, as described in the section "Calling a COM Object from Java." In Visual J++, select the Tools | Java Type Library Wizard menu option and then select the IE Chart object when prompted by the dialog box shown in Figure 20.1. When completed, the following class files will be located in the \iechart subdirectory in your \windows\java\trustlib directory (or the current trusted libraries directory on your machine): DiechartEvents.class The contents of the SUMMARY.TXT file (see Listing 20.2) show the properties, classes, and interfaces exposed in the Chart control. Listing 20.2. The SUMMARY.TXT file for the IEChart ActiveX control.
As you can see, the majority of the classes defined in the Chart
control are used to provide constants that the Chart
control uses for display purposes. All the functionality contained
in the control can be accessed through the Iiechart interface.
Note the naming convention used for the methods in the Iiechart
interface. Thanks to the propget and propput
keywords used in the type library definition, the Java Type Library
Wizard can determine whether these methods are get or
put methods.
In short, methods that begin with get are property-accessor methods. Those that begin with put are property-setting methods. Building an HTML Page Using the ActiveX ControlChances are very good that by now you have built your own HTML page for viewing in a Web browser. Possibly you have even added Java applets to a page or are at least aware of the <APPLET> HTML tag used to embed Java applets in a page. However, it is far less likely that you have ever actually built Web pages containing ActiveX controls. Although this chapter is not intended to be an HTML tutorial (see Chapter 26, "HTML and Web Page Design," for that), you can use the contents of Listing 20.3 to build a "starter" Web page using the ActiveX Chart control. Listing 20.3. The contents of Example1.html.
This HTML source code constructs a page using an HTML table to
contain the Java applet (nonexistent at this point) and the ActiveX
Chart control. Note the large number of param
tags passed to the ActiveX object. These parameters directly correspond
to various properties of the control. Passing these parameters
allows you to set some properties at design time so that there
is not a lot of initialization when the Java applet starts up.
Among the properties being set are ChartType, BackColor
and ForeColor, Rows, Columns, and ColorScheme.
Figure 20.4 shows the Example1.html file loaded and running in Internet Explorer 3.0. Figure 20.4 : Example1.html in Internet Explorer 3.0.
This small amount of HTML coding constitutes virtually all the COM work you have to do to build the remainder of the example. From this point on, except for one line of VBScript code to be added to the Web page, the application is written entirely in Java. Creating an ActiveX-Aware Java AppletListing 20.3 is used to demonstrate how ActiveX properties are set at startup through parameter passing. You now have an ActiveX (COM) object sitting all alone on a Web page. Earlier the Java Type Library Wizard was used to build class files corresponding to the contents of the ActiveX Chart control. Before you can simply import these classes and begin writing Java code, one last hurdle must be cleared: Java applets cannot directly trap ActiveX control events; instead, these controls must be "hooked" together using VBScript. When an event is fired by the Chart control, VBScript must trap that event and send it to the applet. Likewise, a Java applet cannot directly access an ActiveX control's properties or methods without a little help from VBScript. For a Java class to access a control (using a COM interface), that control must be passed to the applet using VBScript as an object of type java.lang.Object. The applet can then typecast this Object parameter to the appropriate interface. Accessing the Chart control from within a Java class is rather straightforward because the Chart control only supports properties and methods, not events. Therefore, you must simply create a Java applet that has a method that accepts an Object as a parameter. Inside this method, the Object parameter is typecast to an object of type Iiechart. The following method demonstrates what your applet's method will look like:
When this method is created, a single VBScript function is declared that will pass the control to the Java applet. This function is contained in the HTML source file and looks like this: <script language=VBScript> <!-- ' Send the controls to the applet Sub window_onLoad document.TheApplet.setCtrl TheChart end sub !--> </script> The onLoad() VBScript method is called after the page has been loaded in Internet Explorer. The one line of code in this method calls the applet's setCtrl() method and passes it the ActiveX Chart control as a parameter. Creating a Java Applet to Control the Chart
All the pieces are now in place. The ActiveX control has been
downloaded and registered. Java class files have been generated
to provide access to the ActiveX object. The HTML file has been
created to contain the Java applet and ActiveX control. All that
is left is to build an applet to control the chart!
First, the ChartApplet applet performs two basic operations:
When the user changes either of these specifications, the chart is automatically updated. The three chart color schemes are presented as radio button selections (java.awt.Checkbox components), and the various chart types are displayed in a list box. An Update button is provided; when clicked, it updates the chart with the user's settings. Listing 20.4 shows the source code for the ChartApplet class. Listing 20.4. The ChartApplet class.
The majority of the ChartApplet class is a standard Java program. A Layout Manager is added to handle the layout of components on the applet. Again, the VBScript calls the setCtrl() method so that the applet can access the ActiveX object in the HTML page. The action() method is used to trap the button click, and this is where the Chart's methods are called (putChartType() and putColorScheme()). Using these two methods, the chart's type and color scheme can be set remotely in Java. Figure 20.5 shows the Example2.html file loaded in Internet Explorer 3.0. Changing any of the options on the left side and then clicking the Update Chart button automatically updates the chart. Figure 20.5 : A Java applet and an ActiveX control coexisting.
SummaryCOM objects can be easily integrated into Java applets or applications, thanks to the Java Type Library Wizard included with Visual J++. This tool extracts the type library information stored in a COM object (such as an ActiveX control) and creates the corresponding Java class files for the COM interfaces, classes, and constants contained in the type library. When these class files have been created, they can be imported into a Java class. From that point, these classes appear to the Java programmer to be identical to standard Java classes. Of particular interest to many Java developers is the ability to integrate existing ActiveX/OLE controls and Java applets in Web pages. This integration is made possible with the Microsoft Virtual Machine and the Java Type Library Wizard. |
|
|
|
|
Use of this site is subject certain Terms & Conditions. Copyright (c) 1996-1998 EarthWeb, Inc.. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of EarthWeb is prohibited. |