C/C++ Users Journal September, 2004
There's no doubt in my mind that I became a better software developer the day I became a C++ programmer. But while I enjoy C++, there are aspects of Java that make me more productive, such as its support for strings, threads, I/O, distributed computing, and building web services. Moreover, Java has another strength that's not always taken advantage ofits ability to integrate with C++ applications.
The Java Native Interface (JNI) lets Java interface with software written in other languages, namely C++. Understanding JNI can bring the world of web services to your C++ application, without changing a line of existing C++ code. By leveraging the tools and support Java has for building web services, even a platform-specific C++ application can be exposed to the world in a platform-agnostic fashion.
To understand how Java can integrate with C++, and even augment it, consider the following scenario. Assume you have a securities trading system written and deployed as a C++/COM application on Windows. The application runs well, and is in use at many customer sites. However, there have been two overwhelming customer requests.
A potential solution is to add SOAP support to your C++ trading system and integrate it with the library internally. However, some problems quickly arise. First, in this scenario, assume the library is a UNIX library, for which you do not have the source code. Second, how do you go about adding SOAP support in C++? You could port your code to .NET or find a third-party library to use. However, the downside to these choices is that they require a great deal of change to your C++ code, and probably result in two baselines of the systemone as a standalone C++/COM application (for existing customers), and the other as a C++ web service.
An alternate solution is to use Java to build a web service around your trading system and to integrate the portfolio manager within the Java code. The result would be a web service front end to your trading system, with portfolio management support, without requiring a change to your C++ code. You can leverage all that Java has to offer when building web services.
In this scenario, the C++ trading system is implemented as a COM server written in C++ as an Active Template Library (ATL) executable. This server exposes one interfaceITradeStock.
The architecture I propose here uses JNI to provide a Java interface to the C++ application and library. The JNI code is to be exposed via a Java object that extends the java.rmi.Remote interface, making it accessible to remote Java applications via the Java Remote Method Invocation (RMI) API. Finally, a Java servlet implements the SOAP interface, and through RMI, calls the JNI layer that interfaces to the C++ code. Figure 1 illustrates the proposed system architecture.
The result is a solution that takes a C++/COM application (which must run on Windows) and a UNIX C++ library, and integrates them with Java, which can run on a variety of platforms. The integrated application is exposed via SOAP, making it platform and language independent. It is within the Java code that you solve the trading system/portfolio manager integration issue and implement the SOAP interface.
The first step in this solution is to define a Java interface that exposes methods similar to the C++ trading system and the portfolio manager, as in Listing 1.
The first three methods, GetQuote, Buy, and Sell, map to the ITradeStock COM interface implemented in the C++ trading system. GetQuote returns the current quote of the given stock symbol. Buy and Sell place market orders for the stock.
The remaining methods map to those implemented in the C++ portfolio manager library. The methods AddHolding and RemoveHolding are called after you buy and sell stock, respectively, to track your positions. EnumHoldings returns a comma-delimited list of stock symbols that are in your portfolio. Finally, GetPosition returns the number of shares held for the given stock symbol. For the sake of simplicity, the portfolio manager library in this example will be implemented as a Windows DLL. This is done so that you can run all of the demo code (the COM application, the portfolio manager, and Java) on one Windows machine.
With the interface defined, you need to generate the JNI code to integrate with the C++ trading system and the portfolio manager library. First, you define a Java class that implements the TradingSystemInterface Java interface, named TradingSystemImpl (see Listing 2).
It's within the definition of the methods marked native that you add the code to call the C++ software. However, these methods are not implemented in Java, but are instead implemented in a special layer of C++ code partially generated by javaha tool that comes with the Java Development Kit (JDK) and resides within the bin subdirectory of your JDK installation.
You compile the TradingSystemImpl class using the command:
>javac TradingSystemImpl.java
Next, use javah to generate the header files for your JNI implementation, providing the Java class file as a parameter:
>javah -jni TradingSystemImpl
If all goes well, the tool outputs the file TradingSystemImpl.h in the current directory. This file contains the function declarations for the methods that were marked "native" in the TradingSystemImpl class. An external header file, jni.h, is included at the top of the file and can be located in the include subdirectory of your JDK installation.
The final step is to implement the C++ functions. In this example, the implementation is a Windows DLL that includes the TradingSystemImpl.h file, where each function calls into the ITradeStock interface as well as the portfolio manager library. Listing 3 shows a portion of the C++ JNI code. The complete implementation can be downloaded electronically, along with all of the code for this solution.
JNI provides a C++ utility class, JNIEnv, which contains methods to help deal with conversions between C++ types and Java types. This class is defined in the header file jni.h. As an example of how to use this class, examine the JNI method Java_TradingSystemImpl_doGetQuote, in Listing 4.
This method calls the ITradeStock::GetQuote method within the C++ trading system, using the parameters passed in from the Java code. First, the parameter, Stock, is converted from a Java string to a C++ char* by calling JNIEnv::GetStringUTFChars. The resulting C++ string is converted to a COM BSTR before calling into the COM interface. The reverse occurs when the returned quote value is converted from a C++ double to a char*, and then to a Java string by calling JNIEnv::NewStringUTF.
In addition to the conversion routines, the JNIEnv class contains methods to throw Java exceptions, create Java objects, and even use Java reflection.
The JNI code needs to be accessible to other Java applications, potentially remote ones (those running on other computers). This lets you run the C++ trading system and its JNI code on a Windows PC, the portfolio manager and its JNI code on a UNIX machine, and the Java web service on a separate machine running either Windows or UNIX. Adding support for Java Remote Method Invocation (RMI) accomplishes this.
To support RMI, the interface TradingSystemInterface extends the java.rmi.Remote interface, and all of the methods throw java.rmi.RemoteExceptions. Also, the implementation class, TradingSystemImpl, extends the java.rmi.UnicastRemoteObject class. This makes the JNI code accessible to remote Java applications. The TradingSystemImpl class is then used to generate a client stub and a server skeleton for RMI. Java's stub/skeleton compiler, rmic, is called with the class name for which it is to generate the stub and skeleton classes:
>rmic TradingSystemImpl
After running successfully, you will find two new class files in the current directory, TradingSystemImpl_Stub.class and TradingSystemImpl_Skel.class. The stub class is loaded by Java for each client process that requests a reference to the TradingSystemImpl remote class. The skeleton class is loaded by Java when the RMI server process (which creates the TradingSystemImpl object) is started. The TradingSystemImpl object is only available to clients when the server process is running.
In this example, the TradingSystemImpl RMI server is defined as a Java application that performs the following tasks. First, the JNI Windows DLL is loaded via a call to System.loadLibrary. Second, an object of the TradingSystemImpl class is created; and third, a reference to this object is registered with the RMI registry running on the host machine. The code for this application, implemented in the Java class RMITradingSystem, is in Listing 5.
Prior to running the TradingSystemImpl server process, the RMI registry must be started. Executing the rmiregistry command in the background and specifying the port as an optional parameter does this. The default RMI port is 1099.
When the RMI registry is started, the TradingSystemImpl server process should be started via the command:
> java TradingSystemImpl
Now, the JNI code that integrates with the C++ trading system and portfolio manager will be available to other Java applications via RMI.
Java web services are simple to build and use. To start, download the Java Web Service Developer Pack, available on Sun's Java web site at http://java.sun.com/ webservices/downloads. This package includes a complete version of the Apache Tomcat Servlet engine, along with the Apache SOAP classes and deployment tools. The Java trading system web service for this article is implemented as a Java servlet that can run within any Java servlet engine. However, the Tomcat Servlet engine serves as an excellent environment.
The TradingSystemServlet class handles each incoming HTTP SOAP request, maps the request to RMI calls into the TradingSystemImpl class, and returns the result as a SOAP response. Example 1 shows the portion of the servlet that parses the request in the SOAP message, and ultimately calls the appropriate trading system and portfolio manager routines.
Example 2 shows how the servlet uses RMI to call into the TradingSystemImpl class. First, an attempt is made to find an object within the RMI Registry that implements the TradingSystemInterface. If successful, method calls can be made on the object.
The code to read an incoming SOAP message is implemented within the servlet's doPost method (Listing 6). First, an instance of a DocumentBuilder classimplemented in the org.apache.soap.xml.XMLParserUtils libraryis used to parse the incoming request XML into a DOM object. Next, the SOAP Envelope, which contains the SOAP message header and body, is extracted from the DOM. Finally, the SOAP body itself is extracted via a call to env.getBody.
The body contains the actual method name to call, and its parameters, which are extracted from the SOAP body by iterating through the DOM structure. Once the SOAP request is processed and the internal method calls are made, a SOAP response containing the method's return code is sent back to the caller.
With the C++ trading system and portfolio manager exposed as a web service, any SOAP-enabled client can use them, regardless of platform or language. The SOAP client included with the demo code for this article is a small Java application. The Java Web Services Developer Pack makes it as simple to build a SOAP client as it was to build our web service.
The sendSOAPMessage routine in Listing 7 shows how little code it takes to create and send an HTTP SOAP request and process a SOAP response. The client code resembles the SOAP code from the servlet, and takes the following steps:
Other potential SOAP clients include those written in C#, C++, VB.NET, Python, Perl, or any language that supports parsing and assembling SOAP messages in some way.
The sample code for this article is comprehensive, and is available at http://www.cuj.com/code/. Table 1 lists the components of the sample, along with the directory for each component.
The C++ trading system is implemented as an ATL/COM executable. The COM server must be registered on your computer by running the following command:
>TradingSystem -regserver
For the Java-based components, you need the following software downloads:
The JNI code for the trading system is implemented as a C++ Windows DLL. This DLL, and the portfolio manager DLL, must both be placed in the SOATrading\JNITradingSystem directory when built.
The Java RMI server application comes with two batch files, one to compile the source code (build.bat) and another to run it (runrmi.bat). When runrmi.bat is executed, it starts the Java RMIRegistry tool and then launches the RMITradingSystem application. The application registers its TradingSystemImpl object with the RMI registry. Both batch files contain file paths that will most likely need to change to match the locations on your computer.
The Java servlet must be deployed on a servlet-enabled web server, such as Apache Tomcat, which can be downloaded at http:// www.apache.org/. The directions for deploying the trading system servlet can be found in the file Readme.txt, in the SOATrading\TradingSystemServlet directory.
Finally, executing getquote.bat, buy.bat, or sell.bat runs the Java SOAP client. Each batch file launches the Java application, passing the web server URL and the appropriate XML file as parameters. Each XML file contains the XML body for the SOAP request. You can change the stock name, and the quantities traded, by modifying the XML files.
Java and C++ can be integrated, and there are cases where it is beneficial to do so. In the scenario I presented here, the trading system and the portfolio manager have been integrated via a Java web service and are now language and platform independent. Prior to this, the C++ application would not have been available to clients other than COM clients on Windows. This is a big achievement, and no existing C++ code needed to be changed.