13
Wed, Nov
5 New Articles

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..


Don Denoncourt

Don Denoncourt is a freelance consultant. He can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Don Denoncourt available now on the MC Press Bookstore.

Java Application Strategies for iSeries and AS/400 Java Application Strategies for iSeries and AS/400
Explore the realities of using Java to develop real-world OS/400 applications.
List Price $89.00

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: