Accessing RPG from JavaServer Pages

Java
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times
For this article, I was given the task of writing a JavaServer Page (JSP) that accesses an RPG program. The RPG program, shown in Figure 1, takes input parameters (a character, a decimal, and a date) and returns output parameters (a character, a decimal, a date, and an array of dates). The JSP code required to invoke the RPG, as you can see in Figure 2, is trivial. Sample output from the JSP example is shown in Figure 3. The code for the JSP is trivial because the complexity of accessing RPG from Java is encapsulated in a JavaBean, shown in Figure 4. All these figures are shown directly below.
      *-------------------------------------------------------------- 
      * Simple RPG program to act as stored procedure.
      *-------------------------------------------------------------- 
      * Input parameters:
      *
      *       inChar     - a 10 character field
      *       inDecimal  - a 10 digit, 0 decimal place field
      *       inDate     - a date
      *
      * Output parameters:
      *
      *       outchar    - inChar translated to all lowercase alpha
      *       outDecimal - the original inDecimal
      *       outDate    - the original inDate
      *       outArray   - an array of 10 dates, where outArray(n)
      *                    is inDate+n days
      *-------------------------------------------------------------- 
     D i               s              5u 0
     D inChar          s             10a
     D inDate          s               d
     D inDecimal       s             10p 0
     D outArray        s               d   dim(10)
     D outChar         s             10a
     D outDate         s               d
     D outDecimal      s             10p 0

     D @LOWER          c                   const('abcdefghijklmnop+
     D                                            qrstuvwxyz')
     D @UPPER          c                   const('ABCDEFGHIJKLMNOP+
     D                                            QRSTUVWXYZ')

     C     *entry        plist
     C                   parm                    inChar
     C                   parm                    inDecimal
     C                   parm                    inDate
     C                   parm                    outChar
     C                   parm                    outDecimal
     C                   parm                    outDate
     C                   parm                    outArray

     C     @UPPER:@LOWER xlate     inChar        outChar
     C                   eval      outDecimal = inDecimal
     C                   eval      outDate    = inDate

     C                   for       i = 1 to %size(outArray)
     C     inDate        adddur    i:*days       outArray(i)
     C                   endfor

     C                   return

Figure 1: RPG programs often take and receive aggregate data.

 
<% // create then invoke the RPG JavaBean:
mc.Rpg001 rpg = new mc.Rpg001();
rpg.call("input",
new java.math.BigDecimal("1.98"),
new java.sql.Date(new java.util.Date().getTime()));
java.util.Date dates[] = rpg.getOutArrayOfDates();
%>

outChar: <%=rpg.getOutChar() %>

outDate: <%=rpg.getOutDate() %>

outDecimal: <%=rpg.getOutDecimal() %>



Date array:

<% for (int i = 0; i < 10; i++) { %>
   <%= dates[i] %>

<% } %>


Figure 2: A properly encapsulated JavaBean makes invoking RPG from JSP easy.

http://www.mcpressonline.com/articles/images/2002/DenoncourtV300.jpg

Figure 3: The code within a JSP should present information, not manipulate it.

package mc;

import java.sql.Connection;
import java.sql.CallableStatement;
import java.sql.SQLException;
import java.sql.Date;
import java.math.BigDecimal;
import java.util.Calendar;

/** Encapsulate access to RPG program RPG001 */
public class Rpg001 {
  private static Connection con;
  private static CallableStatement rpg;
  private String outChar;
  private BigDecimal outDecimal;
  private Date outDate;
  private java.util.Date outDateArray[] = new java.util.Date[10];

  /** create an Rpg001 object with an SQL connection,
      create a SQL callable statement, and register
      the output parameters
   */
  public Rpg001 () {
    if (con != null) return;

    try {
      Class.forName("com.ibm.as400.access.AS400JDBCDriver");
    } catch( ClassNotFoundException e) {
System.out.println("JDBC Driver not found: " + e);
      System.exit(0);
    }
    try {
      con = java.sql.DriverManager.getConnection (
        "jdbc:as400://207.212.90.50", "denoncourt", "vo2max");
      rpg = con.prepareCall("CALL denoncourt.rpg001 (?,?,?,?,?,?,?)");
      rpg.registerOutParameter(4, java.sql.Types.CHAR);
      rpg.registerOutParameter(5, java.sql.Types.DECIMAL);
      rpg.registerOutParameter(6, java.sql.Types.DATE);
      rpg.registerOutParameter(7, java.sql.Types.CHAR);
    } catch (SQLException e) {
      System.out.println("SQL error creating call statement: " + e);
      return;
    }
  }

  /** call the RPG program */
  public void call(String inChar,
            BigDecimal inDecimal,
            java.sql.Date inDate) throws SQLException {
    rpg.setString (1, inChar);
    rpg.setBigDecimal(2, inDecimal);
    rpg.setDate(3, inDate);

    rpg.executeUpdate();

    outChar = rpg.getString(4);
    outDecimal = rpg.getBigDecimal(5);
    outDate = rpg.getDate(6);
    String tenDates = rpg.getString(7);

    Calendar cal = Calendar.getInstance();

    // Stored Procedures don't handle dates well
    // so we use an array of 10 character dates
    // where the format is "CCYY-MM-DD"
    for (int i = 0; i < 100; i += 10) {
      String dateStr = tenDates.substring(i, i+10);
      int ccyy = new Integer(dateStr.substring(0, 4)).intValue();
      String temp = dateStr.substring(5, 7);
      int mm = new Integer(dateStr.substring(5, 7)).intValue();
      int dd = new Integer(dateStr.substring(8, 10)).intValue();
      cal.set(ccyy, mm-1, dd-1);
      if (i == 0 )
        outDateArray[0] = cal.getTime();
      else
        outDateArray[i/10] = cal.getTime();
    }

  }
  public String     getOutChar()         { return outChar;}
  public Date       getOutDate()         { return outDate;}
  public BigDecimal getOutDecimal()      { return outDecimal;}
  public java.util.Date[]     getOutArrayOfDates() {return outDateArray; }

  // unit test
  public static void main (String[] pList) {
    Rpg001 app = new Rpg001();
    try {
        app.call("input", new BigDecimal("4.57"),
                  new java.sql.Date(new java.util.Date().getTime()));
    } catch (SQLException e) {
        System.out.println(e);
    }
    System.out.println("outChar: "+app.getOutChar()+" ");
    System.out.println("outDate: "+app.getOutDate()+" ");
    System.out.println("outDecimal: "+app.getOutDecimal()+" ");
    java.util.Date dates[] = app.getOutArrayOfDates();
    for (int i = 0; i < 10; i++) {
      System.out.println(dates[i]+" ");
    }
    System.exit(0);
  }
}

Figure 4: Each RPG program you access from Java should be encapsulated with a JavaBean.

To access the RPG program, a JSP merely has to create the mc.Rpg001 JavaBean, invoke the call method (passing the required input string, decimal, and date arguments), then retrieve the output parameters with four getter methods: getOutChar, getOutDate, getOutDecimal, and getOutArrayOfDates. That's the way it should work. The JSP itself should not contain the complex code required to invoke the RPG program. If it did, other JSPs requiring access to that RPG routine would have to contain similar code. And, to include such complex code in the JSP, the developer would have to be knowledgeable about RPG programming.

The Bean Interface

Though the JSP code is trivial, the JavaBean shown in Figure 4 is moderately complex and, therefore, requires a more in-depth explanation. I called my RPG JavaBean Rpg001 so it would have the same name as the RPG program that it wrappered. The JavaBean's constructor establishes a JDBC connection. It then creates a CallableStatement object to invoke the RPG via the Connection object's prepareCall method:

rpg = con.prepareCall("CALL denoncourt.rpg001 (?,?,?,?,?,?,?)");


The string argument passed to the prepareCall statement qualifies the name of the stored procedure that wrappers the RPG program (which I'll explain later). It then lists the seven arguments required by that procedure as question mark (?) placeholders. One requirement for using stored procedures in Java is that all output arguments must have their datatypes registered with the CallableStatement's registerOutParameter method:

rpg.registerOutParameter(5, java.sql.Types.DECIMAL);


Note that the number 5 correlates to the fifth question-mark placeholder in the string passed to the prepareCall method.

The prepareCall method would not have worked if I hadn't earlier created the stored procedure, shown in Figure 5, with interactive SQL.

CREATE PROCEDURE DENONCOURT.RPG001
(IN inChar CHAR(10),
 IN inDecimal DEC(10, 2),
 IN inDate DATE,
 OUT outChar CHAR(10),
 OUT outDecimal DEC(10, 2),
 OUT outDate DATE,
 OUT outDateArray CHAR(100))
LANGUAGE RPG

Figure 5: SQL stored procedures can be created to wrapper access to an RPG program.

Of that stored procedure, all parameters but the last are self-explanatory. That last argument is to store an array of 10 dates, but SQL doesn't support arrays for procedure parameters, so I had to stuff them into a string of ten 10-character values. (RPG dates are stored in the CCYY-MM-DD format).

The Call Method

To make it easy to invoke the RPG program, I created a call method that takes the three parameters required by the Rpg001 program: a 10-character field, a 10-digit packed field with no decimals, and a date. The associated Java datatypes for those three fields are String, BigDecimal, and Date, so the prototype for the call method is as follows:

public void call(String inChar, BigDecimal inDecimal, Date inDate) 


The Rpg001 class's call method then uses setter methods to insert the passed parameters into the values required by the CallableStatement. The decimal argument, for instance, is set with the following setter method:

rpg.setBigDecimal(2, inDecimal);


Note that the number 2 correlates to the second question-mark placeholder qualified in the prepareCall method. Once each of the three input arguments is set, the CallableStatement's executeUpdate method is called to invoke the RPG program. When the RPG routine is completed, the return arguments are retrieved with the
CallableStatement getter method that correlates to the appropriate datatype: getString, getDate, or getDecimal. For instance, the decimal return value was retrieved with the following method call:

outDecimal = rpg.getBigDecimal(5);


Note, once again, that the number 5 correlates to the fifth question-mark placeholder.

After the three atomic values were set, the Rpg001 class's call method had to convert the 100-character string into 10 dates. The code looks a little complex, but, with the help of the String class's substring method and the Integer class, I was able to reconstruct the 10 dates from the returned string.

The Bean API

The Rpg001 JavaBean contains a simple API: a call method and four getter methods. The call method takes the input values required by the RPG program, and four getter methods contain the RPG program's return values. The JSP author--whom I hesitate to call a programmer, because he may be a Web developer with little or no programming expertise--is able to easily use that API without implicit knowledge of the RPG program.

There is a caveat, however, with the strategy shown in this article. The RPG program runs in the same job as the JSP, that of the Web application server. This means that if 100 Web-browsing users access Rpg001.jsp, 100 users are hitting at the same RPG program instance. For this itty-bitty RPG program, that may not be much of a problem, but with more robust programs, you may experience a performance bottleneck.

You can avoid performance bottlenecks by using data queues to communicate between Java and RPG. The RPG program reads the input parameters from a sequential data queue and then places the response to a keyed data queue. The Java application writes a request to that sequential data queue, with a unique number (such as the HttpSession number), and then reads the RPG's response from the keyed data queue, using that unique number. The RPG data-queue server is launched as a batch job, and, if it becomes overly taxed, you can simply launch again and have multiple RPG servers handling the same data queue.

Don Denoncourt is a Java consultant, trainer, and mentor. He is author of Java Application Strategies for iSeries and AS/400--Second Edition, co-author of Understanding Linux Web Hosting and editor of iSeries & AS/400 Java at Work. He can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it..


BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$