Skip to main content

This version of the product is no longer supported, and this documentation is no longer updated regularly. See the latest version of this content.Opens in a new tab

Sample Code

You can find sample Java Gateway code in Ensemble installations in the EnsLib.JavaGateway.Test class. These samples demonstrate how to generate and use Ensemble proxy classes. They are presented in the following example sections:

For each method described in this chapter, the port argument is the port number over which the proxy classes communicate with the Java classes, and host identifies the machine on which the Java Gateway server is running. The port argument is required; host is optional and defaults to "127.0.0.1" (the local machine) if not provided.

Setting Up Java Gateway Examples

To prepare to run sample code, in each of the examples described in this chapter, you must complete the following steps:

  1. Start the Java Gateway server (for JMS, start the JMS Gateway server).

  2. Start a Terminal session and change to an Ensemble namespace (for JMS examples you need two Terminal sessions).

  3. Make sure to run Import code if this is the first time you are running the sample code or if you have modified or recompiled your Java classes.

To prepare to run any of the sample code located under EnsLib.JavaGateway.Test — either for the first time, or after you update or recompile your Java code — you must run the corresponding Import methods found under EnsLib.JavaGateway.InterfaceEnablerOpens in a new tab. This imports the necessary Java classes. The specific sample Import method depends on the type of example you are running. For example:

  • To import the sample Java classes provided with Ensemble:

     Do ##class(EnsLib.JavaGateway.InterfaceEnabler).ImportJGSamples(port,host)
  • To import the JDBC interface:

     Do ##class(EnsLib.JavaGateway.InterfaceEnabler).ImportJDBC(port,host)
  • To import the InterSystems JBoss Person EJBs, enter the following command (all on one line):

     Do ##class(EnsLib.JavaGateway.InterfaceEnabler).ImportPersonJBoss(PersonEJBJar,
     j2eeJarFile,port,host)
    

    Where PersonEJBJar points to the PersonEJB.jar file (as generated by the InterSystems EJB Boss projection) and j2eeJarFile points to the J2EE jar file on your system, for example:

    c:/myj2ee/j2ee.jar

  • To import SonicMQ ConnectionFactory (Queue and Topic), allowing connectivity to the SonicMQ JMS Server, enter the following command (all on one line):

     Do ##class(EnsLib.JavaGateway.InterfaceEnabler).ImportSonicJMS(sonicBrokerJar,
     sonicContextJar,port,host)
    

    Where sonicBrokerJar points to the Sonic broker.jar file, for example:

    C:/Program Files/SonicSoftware/SonicMQ/lib/broker.jar

    And sonicContextJar points to the Sonic mfcontext.jar file, for example:

    C:/Program Files/SonicSoftware/SonicMQ/lib/mfcontext.jar

  • To import all J2EE interfaces (EJB, JCA, JTA, Java XML, JTA, etc.), enter the following command (all on one line):

     Do ##class(EnsLib.JavaGateway.InterfaceEnabler).ImportJ2EE(j2eeJarFile,
     port,host)
    

    Where j2eeJarFile points to the J2EE jar file on your system, for example:

    c:/myj2ee/j2ee.jar

In addition to these Import methods, the EnsLib.JavaGateway.InterfaceEnablerOpens in a new tab class provides a convenience method that, given a jar file or a directory name, displays all available classes in that jar file or directory:

 Do ##class(EnsLib.JavaGateway.InterfaceEnabler).Browse(jarName,port,host)

Running Plain Java Examples

The Test() method shows how to use the sample basic classes delivered with Ensemble. To run it, first set up the example, using ImportJGSamples() if you need to import. Then enter:

 Do ##class(EnsLib.JavaGateway.Test).Test(port,host)

The TestArrays() method shows how to use arrays. To run it, first set up the example, using ImportJGSamples() if you need to import. Then enter:

 Do ##class(EnsLib.JavaGateway.Test).TestArrays(port,host)

Running JDBC Examples

The following example establishes a connection with Caché JDBC driver, then executes some standard JDBC code. To run it, first set up the example, using ImportJDBC() if you need to import. Then enter:

 Do ##class(EnsLib.JavaGateway.Test).JDBC(port,host,jdbcPort,jdbcHost)

This sample code should work against any database that has a compliant JDBC driver. Simply replace the connection parameters (JDBC driver class name, URL, username, and password) with appropriate values. See the Class Reference entry for the JDBCOpens in a new tab method for details.

Note:

The value of jdbcPort defaults to 1972; in many cases, this is not correct for your Ensemble instance.

Running EJB Gateway Examples

The following example shows how Caché Basic or ObjectScript code can access a sample Entity Bean (generated by Caché EJB projections) using JBoss version 4.0.1. To run it, first set up the example, using ImportPersonJBoss() if you need to import. Then enter:

 Do ##class(EnsLib.JavaGateway.Test).PersonJBoss(JBossRoot,port, host)

Where JBossRoot points to your JBoss root, for example:

c:/jboss-4.0.1sp1

You can easily modify this example to work against any application server. Simply set the CLASSPATH accordingly and use appropriate connection and context parameters.

Running JMS Gateway Examples

The following examples show how to use Pub/Sub (Topic) and P2P (Queue) JMS Gateways against the SonicMQ JMS Server. The sample Topic/Queue shipped with SonicMQ is used throughout the examples.

Important:

To use the JMS Gateway you must have the java.jms.* libraries which are included in the J2EE SDK j2ee.jar file.

The examples below can be modified to work against any JMS Server. Simply set the CLASSPATH accordingly and use appropriate Queue/Topic Connection factories. You must also modify the ImportSonicJMS() method to import corresponding connection factories, and you need to use appropriate sample Topics/Queues.

JMS Point-to-Point (P2P) Example

The following example shows how to generate a JMS-based Queue message sender and receiver and control them from an Ensemble session. To run the example, first set it up, using ImportSonicJMS() if you need to import. Then:

  1. In one Terminal session, type:

     Do ##class(EnsLib.JavaGateway.Test).JMSQueueReceiver(sonicBrokerJar,port,host)

    Where sonicBrokerJar points to the Sonic broker.jar file, for example:

    C:/Program Files/SonicSoftware/SonicMQ/lib/broker.jar

    The example connects to the SonicMQ JMS Server using the sample queue that SonicMQ provides. After that, it waits for incoming messages and displays any received messages on the Terminal screen.

  2. In the other Terminal session, type:

     Do ##class(EnsLib.JavaGateway.Test).JMSQueueSender(sonicBrokerJar,port,host)

    The example connects to the SonicMQ JMS Server using the sample queue that SonicMQ provides. After that, it sits in a loop, prompting the user to type a message.

  3. On the Sender side, you are prompted to type a message.

  4. Type a message and press Enter.

  5. The message appears on the Receiver side.

  6. The example runs until you close both Terminal sessions, or until you enter QUIT as the message text.

JMS Publish/Subscribe (Pub/Sub) Example

The following example shows how Caché Basic or ObjectScript code can generate a JMS-based Topic Publisher and Subscriber and use them to send messages. To run it, first set up the example, using ImportSonicJMS() if you need to import. Then:

  1. In one Terminal session, run:

     Do ##class(EnsLib.JavaGateway.Test).JMSSubscriber(sonicBrokerJar,port,host)

    Where sonicBrokerJar points to the Sonic broker.jar file, for example:

    C:/Program Files/SonicSoftware/SonicMQ/lib/broker.jar

    The example connects to the SonicMQ JMS Server using the sample topic that SonicMQ provides. After that, it establishes a topic connection and waits to receive a single message.

  2. In the other Terminal session, run:

     Do ##class(EnsLib.JavaGateway.Test).JMSPublisher(sonicBrokerJar,port,host)

    The example connects to the SonicMQ JMS Server using the sample topic that SonicMQ provides. After that, it establishes a topic connection and creates and sends a single message.

  3. The publisher sends one message to the subscriber ("Hello JMS!") and both quit.

Java Naming and Directory Interface (JNDI) Example

This example is exactly the same as the JMS Pub/Sub example, except that the JNDIPublisher() method establishes a connection by looking up a TopicConnectionFactory object in the JNDI registry, whereas JMSPublisher() actually creates the connection. If JNDIPublisher() does not find the object, it tries to (re)bind the object, then return and try to look it up.

Note:

The JMS with JNDI example is customized for JMS. However, you can use JNDI to obtain a factory object in other contexts, such as with Enterprise Java Beans (EJB).

To run the example, first set it up, using ImportSonicJMS() if you need to import. Then:

  1. In one Terminal session, type:

     Do ##class(EnsLib.JavaGateway.Test).JMSSubscriber(sonicBrokerJar,port,host)

    Where sonicBrokerJar points to the Sonic broker.jar file, for example:

    C:/Program Files/SonicSoftware/SonicMQ/lib/broker.jar

  2. In the other Terminal session, type (all on one line):

     Do ##class(EnsLib.JavaGateway.Test).JNDIPublisher(sonicBrokerJar,
     sonicContextJar,port,host)

    Where sonicContextJar points to the Sonic mfcontext.jar file, for example:

    C:/Program Files/SonicSoftware/SonicMQ/lib/mfcontext.jar

  3. The publisher sends one message to the subscriber ("Hello JMS!") and both exit.

Stateless Service Mode Example

Here is a simple implementation using GSON which gets the Google directions between two cities and sends them back to Caché in JSON format. For more info on GSON go to: https://code.google.com/p/google-gson/Opens in a new tab.

Java code:

package jsonservice;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.net.URL;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class Directions implements com.intersys.gateway.Service {

        public byte[] execute(byte[] args) throws Throwable {
                 JsonElement inputJSON = new JsonParser().parse(new
                                  BufferedReader(new InputStreamReader(new ByteArrayInputStream(args), "UTF-8")));
		JsonObject jsonObject = inputJSON.getAsJsonObject();
		String origin = jsonObject.get("origin").toString();
		String destination = jsonObject.get("destination").toString();

		URL URLsource = new URL("http://maps.googleapis.com/maps/api/directions/json?
				origin="+origin+"&destination="+destination+"&sensor=false");
		BufferedReader in = new BufferedReader(new  InputStreamReader(URLsource.openStream(),"UTF-8"));
		JsonElement outputJSON = new JsonParser().parse(in);
		in.close();
		jsonObject = outputJSON.getAsJsonObject();
		String response = jsonObject.toString();
		return response.getBytes();
	}
}

To invoke the above service from Caché/Ensemble, simply do:

Set classPath=##class(%ListOfDataTypes).%New()
// add GSON to the classpath
Do classPath.Insert("c:/service/gson-1.4.jar")
// add the location of the above Service to the classpath
Do classPath.Insert("c:/service/")
// invoke the service
Write  ##class(%Net.Remote.Gateway).%RemoteService("127.0.0.1",55555,"jsonservice.Directions","{""origin"" : 
                         ""philadelphia"", ""destination"" : ""boston""}",classPath) 

Note:

The JSON parsing tool (GSON) is not strictly necessary in this simple example.

FeedbackOpens in a new tab