Create a Java "Hello World" program with RPG.
Editor's note: This article is excerpted from the MC Press book Advanced Integrated RPG.
Welcome to Advanced Integrated RPG (AIR), where RPG and Java work together to provide RPG with all of the capabilities that Java has to offer. This article contains excerpts from my new book that will show you how to start the Java Virtual Machine (JVM) and display "Hello World" in RPG. This is a prerequisite to the upcoming article that will show you how to create PDFs from RPG!
Accessing Java Objects from Within RPG
To create reference variables within RPG for Java objects, you specify the variable as type O (Object) in column 40 of the D specification. Then, use the CLASS keyword to indicate the Java object being referred, entering *JAVA as the first parameter and specifying the Java class as a character string for the second parameter. This character string must fully qualify the object and the Java package that contains it.
Let's begin by creating a reference to a Java String object. The String object is a common object included in the JDK. It is contained in the java.lang package, so the character string to identify the class must be in the Java format of 'java.lang.String'. It's important to note that the reference to the class is case-sensitive.
Figure 5.2 shows the code to declare an RPG variable that refers to a Java String object.
D string S O CLASS(*JAVA:'java.lang.String')
Figure 5.2: RPG object variable for reference to Java String object
Java Object Constructors
The variable declared as an object type is only a reference. In order to use the string object, we first need to create an instance of the object. We do this by using the constructor method of the class. When the object is constructed, the reference variable will identify the location of the memory allocated to the object.
We call the constructor method of the class by specifying the special keyword *CONSTRUCTOR as the method name in EXTPROC. In the Java language, you construct objects by using the new keyword, so we'll name the procedure new_String, using an underscore to represent the separation of the keyword new from the class name that you would code in Java.
Figure 5.4 shows the prototype for the constructor method of the String class.
D new_String PR like(jstring)
D extproc(*JAVA:
D 'java.lang.String':
D *CONSTRUCTOR)
D argBytes 65535A varying const
Figure 5.4: RPG prototype for constructor method of the String class
When sending information from Java to RPG, you need to convert the Java String back to the array of bytes used in RPG. The Java String class includes the getBytes method to provide this capability. Figure 5.3 shows how you would write the prototype to access the getBytes method.
D String_getBytes...
D PR 65535A varying
D extproc(*JAVA:
D 'java.lang.String':
D 'getBytes')
Figure 5.3: RPG prototype for getBytes method of the String class
Starting the JVM
Before using any Java code, you need to get the JNI environment pointer. Procedure getJNIEnv (Figure 5.8), which is called by our main procedure, looks for an existing JVM to attach to. If no JVM already exists, the procedure creates one for the job.
P******************************************************************
P* getJNIEnv
P******************************************************************
P getJNIEnv...
P B EXPORT
D getJNIEnv...
D PI *
D rc s LIKE(jint)
D jvm s * DIM(1)
D env s *
D bufLen s LIKE(jsize) INZ(%elem(jvm))
D nVMs s LIKE(jsize)
D initArgs DS LIKEDS(JDK1_1InitArgs)
D attachArgs DS LIKEDS(JDK1_1AttachArgs)
D fd s 10I 0
/free
// First, ensure STDIN, STDOUT, and STDERR are open
fd = IFSopen('/dev/null': O_RDWR);
if (fd = -1);
// '/dev/null' does not exist in your IFS
// You can create it or use another known good file.
else;
dow ( fd < 2 );
fd = IFSopen('/dev/null': O_RDWR);
enddo;
endif;
// Second, attach to existing JVM
// OR create new JVM if not already running
rc = JNI_GetCreatedJavaVMs(jvm:bufLen:nVMs);
if (rc = 0 and nVMs > 0);
attachArgs = *ALLX'00';
JavaVM_P = jvm(1);
rc = AttachCurrentThread(jvm(1):env:%addr(attachArgs));
else;
initArgs = *ALLX'00';
rc = JNI_GetDefaultJavaVMInitArgs(%addr(initArgs));
if (rc = 0);
rc = JNI_CreateJavaVM(jvm(1):env:%addr(initArgs));
else;
endif;
endif;
if (rc = 0);
return env;
else;
return *NULL;
endif;
/end-free
P E
Figure 5.8: Getting a pointer to the JNI environment
Prior to working with the JVM, you need to ensure that the first three file descriptors are open by using the open API, which I have prototyped as IFSOpen. This is needed to prevent errors because the JVM expects STDIN, STDOUT, and STDERR to already be open, which may not always be the case on the IBM i. So this is done as part of the procedure.
Here is the prototype for IFSOpen:
DIFSOpen PR 10I 0 extProc('open')
D argPath * value options(*STRING)
D argFlag 10I 0 value
D argMode 10U 0 value options(*nopass)
D argToConv 10U 0 value options(*nopass)
D argFromConv 10U 0 value options(*nopass)
Garbage Collection
RPG uses JNI to load the JVM in the native application of RPG. When you program in Java, the JVM normally recognizes when an object is no longer being used and frees the resources that are no longer referenced by the program. But, because RPG uses JNI to run the JVM, only the RPG program knows when a resource is finished being used, so you will want to manually free resources to avoid excessive allocation of unused memory.
The JNI file provides the DeleteLocalRef function, which you can use directly from an RPG program to remove local object references, but the freeLocalRef wrapper procedure shown in Figure 5.11 retrieves the JNI interface pointer for use with DeleteLocalRef.
p*****************************************************************
P* freeLocalRef(Ref)
P*****************************************************************
P freeLocalRef...
P B EXPORT
D freeLocalRef...
D PI
D inRefObject like(jobject)
D env S * static inz(*null)
/free
if (env = *NULL);
env = getJNIEnv();
else;
endif;
JNIENV_p = env;
DeleteLocalRef(env: inRefObject);
/end-free
P E
Figure 5.11: Making a local reference eligible for deletion in the JVM
Hello World
We now have all of our foundation procedures established. Let's build a Hello World program that creates a Java String object, sets the value to 'Hello World', and retrieves the bytes back into RPG for display (Figure 5.14).
H THREAD(*SERIALIZE)
D**********************************************************************
D* How to Compile:
D*
D* (1. CREATE THE MODULE)
D* CRTRPGMOD MODULE(AIRLIB/AIR05_01) SRCFILE(AIRLIB/AIRSRC) +
D* DBGVIEW(*ALL) INDENT('.')
D*
D* (2. CREATE THE PROGRAM)
D* CRTPGM PGM(AIRLIB/AIR05_01)
D* MODULE(AIRLIB/AIR05_01)
D* BNDSRVPGM(AIRLIB/SVAIRFUNCAIRLIB/SVAIRJAVA)
D* ACTGRP(AIR05_01)
D**********************************************************************
D*** PROTOTYPES ***
D/COPY QSYSINC/QRPGLESRC,JNI
D/COPY AIRLIB/AIRSRC,SPAIRJAVA
D airString S like(jString)
D displayBytes S 52A
/free
JNIEnv_p = getJNIEnv();
airString = new_String('Hello World');
displayBytes = String_getBytes(airString);
DSPLY displayBytes;
freeLocalRef(airString);
*inlr = *ON;
/end-free
Figure 5.14: RPG/Java Hello World program
If you were to run this program, you would see the expected "Hello World" output displayed on your screen. The figure shows the small amount of code that is required to implement Java from RPG:
- The /COPY QSYSINC/QRPGLESRC,JNI statement includes all the prototypes and data types that are provided by IBM.
- The /COPY AIRLIB/AIRSRC,SPAIRJAVA statement provides access to the Java String methods and basic Java procedures.
- The like(jString) usage on the airString variable provides a reference variable for the Java String object.
- The getJNIEnv procedure ensures that the STDIN, STDOUT, and STDERR streams are open.
- The getJNIEnv procedure looks for an existing JVM and attaches to it, if one exists. If a JVM does not already exist, the procedure creates a new one.
- The new_String procedure calls the constructor method of the String class to create a new object and return the reference variable to the String object.
- The String_getBytes procedure converts the String content back into EBCDIC bytes to be used within RPG.
- The freeLocalRef procedure manually releases the memory allocated to the object that is referred to by the airString reference variable.
Coming Soon, PDF!
It may not seem like a big deal to be able to display a String on the screen, but this is the first big step toward getting Java started on your IBM i. In the next book excerpt article, I will do something fun with this capability and create a PDF!
LATEST COMMENTS
MC Press Online