Skip to main content

Using the Java Gateway in a Production

This chapter describes how to use the Java Gateway in a production. It discusses the following topics:

Adding the Java Gateway Business Service

While it is possible to start the Java Gateway server from the command prompt, the simplest way to use the Java Gateway with an Ensemble production is to add and configure the EnsLib.JavaGateway.ServiceOpens in a new tab class as a business service within the production. You can only do this if the Java Gateway server is on the local machine where you are running Ensemble.

Otherwise, you need to start the Java Gateway server from the command prompt. For details, see “Using the Command Prompt.”

To add the EnsLib.JavaGateway.ServiceOpens in a new tab class as a business service in your production, use the Production Configuration page of the Management Portal. The following steps summarize the configuration procedure:

  1. Click the add icon (generated description: button addhost) next to the Services column to start the Business Service Wizard.

  2. Click the All Services tab, and choose EnsLib.JavaGateway.ServiceOpens in a new tab as the Service Class. You may accept the default values for the other settings.

  3. Click OK to display the updated production diagram.

  4. Click the new Java Gateway business service configuration item and then the Settings tab to configure it.

Unlike most business hosts in an Ensemble production, EnsLib.JavaGateway.ServiceOpens in a new tab does not handle any Ensemble messages.

Settings for the Java Gateway Business Service

The following settings specific to the Java Gateway service appear on the Settings tab. Hover the cursor over any setting name to display its help text as it appears in the Class Reference or click the setting name to display the help text in a separate pop-up window.

Address

IP address or name of the machine where the JVM to be used by the Java Gateway Server is located.

Port

Port number to which the Java Gateway connects. The default is 55555.

HeartbeatInterval

Number of seconds between each communication with the Java Gateway to check whether it is active. When enabled, the minimum value is 5 seconds and the maximum value is 3600 seconds (1 hour). The default is 10 seconds. A value of 0 disables this feature.

HeartbeatFailureTimeout

Number of seconds without responding to the heartbeat, to consider that the Java Gateway is in failure state. If this value is smaller than the HeartbeatInterval property, the gateway is in failure state every time the Java Gateway communication check fails. The maximum value is 86400 seconds (1 day). The default is 30 seconds.

HeartbeatFailureAction

Action to take if the Java Gateway goes into a failure state. Setting it to Restart (default) causes the Java Gateway to restart. Setting it to Alert generates an alert entry in the Event Log. This is independent of the Alert on Error setting.

HeartbeatFailureRetry

Time to wait before retrying the HeartbeatFailureAction if the Java Gateway server goes into failure state, and stays in failure state. The default is 300 seconds (5 minutes). A value of 0 disables this feature, meaning that once there is a failure that cannot be immediately recovered, there are no attempts at automatic recovery.

JavaHome

Location of the JVM; use the path you identified in “Prerequisites,” in the previous chapter. (This is the value that you would use for JAVA_HOME environment variable). It is used to find the target JVM and assemble the command to start the Gateway.

If there is a default JVM on the machine that is usable without the need to specify its location, you can leave this setting blank.

ClassPath

Class path containing the files to be passed as an argument when starting the JVM. You must include any jar file that define classes you are importing via the Java Gateway. There is no need to include InterSystems' .jar files used by the Java Gateway. If you are specifying file paths containing spaces or multiple files, you should quote the classpath and supply the appropriate separators for your platform.

The following is an example semicolon-separated list of file paths for a Microsoft Windows platform:

C:\Library\Ensemble\mygateway.jar;"C:\Jar files\utilities.jar"

Note that additional paths for the classpath can be specified in business operations derived from EnsLib.JavaGateway.AbstractOperationOpens in a new tab. See the property AdditionalPaths in that class.

JVMArgs

Optional arguments to be passed to the Java Virtual Machine (JVM) to include when assembling the command to start the Java Gateway. For example, you can specify system properties: Dsystemvar=value or set the maximum heap size: Xmx256m and so on, as needed.

JDKVersion

Version of JDK used to select the intended version of the InterSystems .jar files. It is used to assemble the command to start the Java Gateway. For example: Java 1.7

Logfile

Fully qualified name of a file to log all communication between the Ensemble server and the Java Gateway. Usually this setting should be left blank, except when troubleshooting. These messages include acknowledgment of opening and closing connections to the server, as well as any difficulties encountered in mapping Java classes to Ensemble proxy classes.

JavaDebug

Allow a Java debugger (such as Eclipse or JSwat) to attach. If True, enables Java debugging via TCP. The default is False.

JavaDebugPort

Specify the port on which to listen. The default is 8000.

JavaDebugSuspend

If Yes, suspend the JVM on start to wait for the debugger to attach. The default is No.

Other settings are common to most Ensemble business services. See “Settings in All Business Services” in Configuring Ensemble Productions.

Once you have added and configured the Java Gateway business service, it automatically manages the Java Gateway as follows:

  • When the production starts, the Java Gateway business service starts an instance of the Java Gateway server, using the settings that you specify on the configuration page.

  • When the production receives a signal to stop, the Java Gateway business service attaches to the Java Gateway server and instructs it to stop, as well.

For more information, see EnsLib.JavaGateway.ServiceOpens in a new tab in the Class Reference.

Calling Business Service Methods

The Java Gateway business service provides methods that you can use to start, connect to, and stop the Java Gateway engine. You can call the following methods from Ensemble code after you have configured the Java Gateway business service as a member of the production:

See the EnsLib.JavaGateway.ServiceOpens in a new tab entry in the Class Reference for details on these methods.

StartGateway() Method

EnsLib.JavaGateway.Service:StartGateway(pJavaHome As %String,
     pClassPath As %String,
     pJVMArgs As %String,
     pPort As %String,
     pLogFile As %String = "",
     pDebug As %Boolean = 0,
     pJDKVersion As %String = "",
     ByRef pDevice As %String = "",
     pAddress As %String = "127.0.0.1",
     pCmdLine As %String = "")

This class method starts the Java Gateway server using the specified arguments. If pDebug is True, then the JVM is started such that a debugger can attach to it via TCP. If pLogFile specifies a valid file name, then messages regarding gateway activities are written to this file. These messages include acknowledgment of opening and closing connections to the server, and difficulties encountered (if any) in mapping Java classes to Ensemble proxy classes.

ConnectGateway() Method

EnsLib.JavaGateway.Service:ConnectGateway(pEndpoint As %String,
     ByRef pGateway As EnsLib.JavaGateway.JavaGateway,
     pDebug As %Boolean = 0,
     pTimeout As %Integer = 5,
     pAdditionalPaths As %String = "")

This class method connects to the Java Gateway server at the specified pEndpoint (hostname:port:namespace) and returns an instance of the EnsLib.JavaGateway.JavaGatewayOpens in a new tab class. If pDebug is true, then the connection uses a much longer timeout to allow for a Java debugger (such as Eclipse or JSwat) to attach.

StopGateway() Method

EnsLib.JavaGateway.Service:StopGateway(pPort As %String,
     pAddress As %String = "127.0.0.1",
     pTimeout As %Integer = 5)

This class method connects to the Java Gateway server and shuts it down.

Creating a Business Operation

An abstract business operation is available as a base for building Java Gateway oriented business operations for Ensemble productions. You can simply subclass the abstract class EnsLib.JavaGateway.AbstractOperationOpens in a new tab and implement the appropriate message handlers.

Call the GetConnection() method to verify the connection and always access the Java Gateway connection object via the gateway connection object returned by the GetConnection() method. For example:

 Set tSC = ..GetConnection(.tJavaGateway)
     If $$$ISOK(tSC)
     {
        // Now, start using the tJavaGateway instance ...
     }  

This method returns a private gateway connection object to be used with the proxy classes.

You can configure the Java Gateway IP address and port in the business operation settings when you add the business operation to the production. Note that the connection to the Java Gateway instance is made during OnInit() and closed in OnTearDown(). You must override these methods in the business operation class to implement your own setup and tear down procedures.

See the EnsLib.JavaGateway.AbstractOperationOpens in a new tab entry in the Class Reference for details on these methods and also the AdditionalPaths, Address, ConnectTimeout, and Port properties.

Calling API Methods

In addition to using connect, disconnect, and stop from the business service, the following methods are also available in the EnsLib.JavaGateway.JavaGatewayOpens in a new tabOpens in a new tab class, which represents one connection between Ensemble and the Java Gateway server. You can use them when the business service model is not appropriate for your situation:

The EnsLib.JavaGateway.JavaGatewayOpens in a new tab class provides the following types of methods:

%Connect() Method

Method %Connect(host As %String,
                port As %Integer,
                namespace As %String,
                timeout As %Numeric = 5,
                additionalClassPaths As %ListOfDataTypes = "")
     As %Status [ Final ]

The %Connect() method establishes a connection with the Java Gateway engine. It accepts the following arguments:

Argument Description
host Identifies the machine on which the Java Gateway server is running.
port Port number over which the proxy classes communicate with the Java classes.
namespace Ensemble namespace.
timeout Number of seconds to wait before timing out, the default is 5.
additionalClassPaths Optional — use this argument to supply additional class paths; the paths are added to the system class loader and are available until the session terminates.

%Disconnect() Method

Method %Disconnect() As %Status [ Final ]

The %Disconnect() method closes a connection to the Java Gateway engine.

%Shutdown() Method

Method %Shutdown() As %Status [ Final ]

The %Shutdown() method shuts down the Java Gateway engine.

%Import() Method

Method %Import(javaClass As %String,
               ByRef imported As %ListOfDataTypes,
               additionalClassPaths As %ListOfDataTypes = "",
               exclusions As %ListOfDataTypes = "")
    As %Status [ Final ]

The %Import() method imports the given javaClass and all its dependencies by creating and compiling all the necessary proxy classes. The %Import() method returns, by reference, a list (imported) of generated Ensemble proxy classes. For details of how Java class definitions are mapped to Ensemble proxy classes, see the “Mapping Specification” chapter.

%Import() is a onetime, startup operation. You only need to call it the first time you wish to generate the Ensemble proxy classes. It is necessary again only if you recompile your Java code and wish to regenerate the proxies.

Note:

Though it was necessary in earlier versions, %Import() does not need to be called at runtime every time you connect.

The following sections provide more details about the %Import() method:

%Import() Arguments

Before you invoke %Import(), prepare the %ListOfDataTypesOpens in a new tab arguments additionalClassPaths and exclusions. That is, for each argument, create a new %ListOfDataTypesOpens in a new tab object and call its Insert() method to fill the list.

You can use the optional additionalClassPaths argument to supply additional CLASSPATH arguments, such as the name of the jar file that contains the classes you are importing via the Java Gateway. List elements should correspond to individual additional class path entries, which require one of the following formats:

"rootdirectory\..."
"rootdir\...\myjarfile.jar"

The additional paths are added to the system class loader and are available until the session terminates. Wildcards are not accepted in CLASSPATH arguments; you must use a full name.

Note:

While the examples in this topic use Windows pathname conventions, other supported Ensemble platforms work also.

Import Dependencies and Exclusions

While mapping a Java class into an Ensemble proxy class and importing it into Ensemble, the Java Gateway loops over all class dependencies discovered in the given Java class including all classes referenced as properties and in argument lists. In other words, the Java Gateway collects a list of all class dependencies that would be needed for a successful import of the given class, then walks that dependency list and generates all necessary proxy classes.

Important:

The Java Gateway import only imports classes, methods, and fields marked as public.

You can control this process by specifying a list of package and class name prefixes that you would like to exclude from this process. While this situation is rare, it does give you some flexibility to control what classes get imported. The Java Gateway automatically excludes a small subset of packages such as sun.*, COM.rsa.*, and most com.sun.* packages.

In previous releases, the Java Gateway disallowed import of all com.sun.* classes, as some of them are Java internals. However, subsequent releases have relaxed this so that you can import additional com.sun.* classes (including com.sun.tools.javac.Main and com.sun.messaging).

%ExpressImport() Method

ClassMethod %ExpressImport(name As %String,
                           port As %Integer,
                           host As %String = "127.0.0.1",
                           silent As %Boolean = 0,
                           additionalClassPaths As %ListOfDataTypes = "",
                           exclusions As %ListOfDataTypes = "")
     As %ListOfDataTypes

%ExpressImport() is a one-step convenience class method that combines calls to %Connect(), %Import(), and %Disconnect(). It returns a list of generated proxies. It also logs that list, if you set the silent argument to 0. The name argument is a semicolon-delimited list of classes or jar files.

%ClassForName() Method

Method %ClassForName(className As %String)
     As %Status [ Final ]

If you need your Caché Basic or ObjectScript code to call the Java method Class.forName to load a Java class, use the Java Gateway API method %ClassForName() to make the call. Its argument is the name of the class. Use the Ensemble proxy class name as the argument, rather than the Java class name.

%GetAllClasses() Method

Method %GetAllClasses(jarFileOrDirectoryName As %String,
                      ByRef allClasses As %ListOfDataTypes)
     As %Status

This method returns, in the ByRef argument allClasses, a list of all public classes available in the jar file or directory specified by the first argument, jarFileOrDirectoryName.

%Reconnect() Method

Method %Reconnect() As %Status

The %Reconnect() method attempts to reestablish the connection between Ensemble and the Java Gateway server after the connection is closed. More specifically, this method does one of the following:

  • If the connection had been open previously, call the %Connect() method and pass in the values contained in the connectParameters property, which represent the most recently used connection parameters.

  • If the connection had never been open, return an error:

    Unable to Reconnect since not connected previously
    

%LostConnectionCleanup() Method

Method %LostConnectionCleanup() As %Boolean

The %LostConnectionCleanup() method indicates whether the connection between Ensemble and the Java Gateway server is invalid. A connection may become invalid if the gateway server is restarted after Ensemble connects to it or if a network error occurs. Additionally, this method sets the Closed property to true and clears the ClosedProxies list when it determines that a connection is invalid.

Using the Command Prompt

Usually you start and stop the Java Gateway server automatically, by configuring the EnsLib.JavaGateway.ServiceOpens in a new tab business service as a member of the production. Once this is done, the Java Gateway server starts and stops automatically with the production. The StartGateway() class method is also available to manually start the Java Gateway server.

However, during development or debugging, or when Ensemble and the Java Gateway server run on different machines, you may find it useful to start the Java Gateway server from a command prompt. Do this by entering the following command (all on one line). Within this command, the service name has a length limit of 255 characters:

java -classpath classpath com.intersys.gateway.JavaGateway port logfile sysclasslevel host secureString

Argument Description
classpath Consists of a semicolon-separated list of paths of the files required to be passed as an argument when starting the JVM. If any path includes space characters, that path should be enclosed within double quotes. Be sure to use pathnames of the appropriate format for your platform. The jar files needed by the Java Gateway are <install-dir>\dev\java\lib\JDK18\intersystems-gateway-3.0.0.jar and <install-dir>\dev\java\lib\JDK18\intersystems-jdbc-3.0.0.jar. You can start the Java Gateway on a machine without Ensemble installed as long as you have access to these jar files. If your client code does not include a path to the jar file that contains the classes you are importing via the Java Gateway, you can add that jar file to the classpath argument.
port Port number on which to listen for the incoming requests.
logfile Optional — If specified, the command procedure creates a log file of that name. You must specify the full pathname in the string.
sysclasslevel Optional — Identifier assigned to all generated proxy classes.
host Optional — The host IP with the port that the Java Gateway is listening on. Specify null, "", or 0.0.0.0 (the default) to listen on all IP addresses local to the machine (127.0.0.1, VPN address, etc.) You can restrict the listener to one existing local IP address or listen on all of them; you cannot enter a list of acceptable addresses.
secureString Optional — Argument related to security.

Using the Java Gateway Wizard

You can import a Java class or an entire .jar file using the Java Gateway wizard built into Studio. To start the wizard:

  1. Start Studio.

  2. From the Tools menu, point to and click Add-Ins.

  3. Click Java Gateway Wizard to start the Java Gateway Wizard dialog.

  4. Click Jar File and either enter the path name or click Browse to find the appropriate .jar file. For example, the following is the name of a sample jar file included with Ensemble, where MyEnsemble is the name of the install directory:

    C:\MyEnsemble\dev\java\samples\remote\test\javagatewaysamples.jar
    

    or

    Click Class Name and either enter the full path name or click Browse to find the appropriate Java class file. For example, the following is the name of a sample Java class included with Ensemble, where MyEnsemble is the name of the install directory:

    C:\MyEnsemble\dev\java\samples\remote\test\Address.class
    
  5. Enter the Host and Port for the Java Gateway server.

  6. Enter Classpaths and Exclusions as instructed in the dialog.

  7. If you select a Jar File in Step 4, you can click View to see a list of the classes in the jar file.

    or

    If you enter a Class Name in Step 4, continue to the next step.

  8. Click Import to generate Ensemble proxy classes. The wizard displays the class name as it generates each proxy class.

  9. When the import operation is complete, click Finish to exit the wizard.

Error Checking

The Java Gateway provides error checking as follows:

  • When an error occurs while executing Ensemble proxy methods, the error is, in most cases, a Java exception, coming either from the original Java method itself, or from the Java Gateway engine. When this happens, a <ZJGTW> error is trapped.

  • Java Gateway API methods like %Import() or %Connect() return a typical Ensemble %StatusOpens in a new tab variable.

In both cases, Ensemble records the last error value returned from a Java class (which in many cases is the actual Java exception thrown) in the local variable %objlasterror.

You can retrieve the complete text of the error message by calling $system.OBJ.DisplayError(), as follows:

 Do $system.OBJ.DisplayError(%objlasterror)

Troubleshooting

When you encounter problems using the Java Gateway, it is always beneficial to turn on logging. This facilitates InterSystems staff to help you troubleshoot problems. To activate logging, simply identify a log file when you start the Java Gateway. You can do this whether you start the gateway from the command line, by configuring the business service, or using the StartGateway() business service method.

Sometimes, while using the Java Gateway in a debugging or test situation, you may encounter problems with a Terminal session becoming unusable, or with write errors in the Terminal window. It is possible that a Java Gateway connection terminated without properly disconnecting. In this case, the port used for that connection may be left open.

If you suspect this is the case, to close the port, enter the following command at the Terminal prompt:

 Close "|TCP|port"

Where port is the port number to close.

Alternatively, you can attempt to reconnect Ensemble to the Java Gateway server without closing the port by calling the %LostConnectionCleanup() method and %Reconnect method in succession. For more information, see Calling API Methods.

If you prefer to automate the process of reconnecting to the Java Gateway server in the event of a disconnection, set the AttemptReconnect property for the gateway connection object to true.

FeedbackOpens in a new tab