Common Gateway Interface (CGI) is a standard method of programming for Web browsers. It is a client/server architecture by which a Web browser client communicates with a host-based server program. CGI is a new twist to the ancient technology on which UNIX and PC operating systems are based. Many of us did our first PC programming in some version of BASIC, probably BASICA or GW-BASIC. I wrote PRINT commands to write to the screen and INPUT statements to read from the keyboard. CGI programming works much the same way, except that the screen and keyboard are on a different computer than the one running the program and the Web browser replaces the old scrolling text-based display.
Green-screen lovers can think of the browser as a cutesy replacement for the dumb terminal. RPG doesnt have equivalents for BASICs PRINT and INPUT commands, but the ILE version of RPG does have access to two bindable APIs that do the same things. Like BASICs PRINT command, the QtmhWrStout API writes to the screen, and like BASICs INPUT command, the QtmhRdStin API reads (albeit indirectly) from the keyboard.
However, you do not have to write AS/400 CGI programs in RPG. You can use other ILE languages (such as COBOL or C), scripting languages (such as REXX and Perl), Java, or C++. The basic idea of CGI is to create HTML dynamically from host- based application data. User input comes from fields of HTML forms, whose values are read by QtmhRdStin, and output comes from HTML generated by your language of choice and is passed back to the user by QtmhWrStout. Ive written the example program in this article in RPG, and I direct my discussion toward RPG programmers.
The CGI standard has what I consider to be two glaring faults. The first fault is that CGI programs handle stream I/O, not record I/O. Although stream I/O has its place in computing, record I/O is much easier to work with, especially in typical data processing applications.
The second fault is that, on most server platforms, CGI programs treat every request as a brand-new interactive session. Whenever you click a Web browsers Submit button, you execute a script or program that that goes through initialization (which may include opening files), runs until the end of the job, shuts down (which includes closing files), and is removed from memory. The AS/400, however, is no ordinary server platform. With activation groups and not setting on LR, the RPG CGI program is available
to handle remote requests iteratively. The problem with CGI programs is that they indiscriminately service Web requests from multiple users and dont remember you from one time to the next. During your think/wait time, other Internet users can invoke the same instance of that RPG CGI program, thus repositioning file cursors and changing the value of program variables.
IBM and others have been working on this second fault. In this article, I show you how you can make CGI applications work like the green-screen apps I so love, in which you open one instance of a CGI specifically for one user. Consequently, you maintain cursors, and variables retain their values between responses from the user. In short, you can make a Web browser converse with an AS/400 the way a dumb terminal converses with an interactive RPG or COBOL program. This is known as persistent CGI.
Persistent CGI
Making a CGI program persistent is not difficult. You just have to send a little more code to the Web browser, change the program as necessary so you can enter it repeatedly without reactivation, and compile the program to run in a named activation group. Ill examine each of these steps in more detail.
Sending a Little More Code
Whereas the first data a typical CGI program sends to a Web browser is the phrase Content-type: text/html followed by two end-of-line sequences, a persistent CGI program precedes this with two other strings of text. The first is Accept-HTSession: followed by a series of characters that serves as a session identifier. (Each instance of the persistent CGI program should have a unique identifier.) The method I have used is to store a number in a data area and increment it by one every time the program is activated. That is, in the onetime calcs, I generate a new session ID that must be sent to the browser and placed both after the Accept-HTSession header and at the end of the URL for the Submit button, which the user must click to reenter the program. A slash (/) separates the session ID.
Following the Accept-HTSession: header appears the text HTTimeout: followed by a nonnegative integer specifying the timeout interval for the session in minutes. The HTTimeout header is ignored if it does not follow the Accept-HTSession header.
Figure 1 shows part of the HTML code produced by program TKTINQ02RG. The session ID is the string 0000021, and the timeout interval is 5 minutes. The FORM tag refers to the same program and session ID, causing the same instance of the program to be entered again when the user clicks Submit on the browser page.
Changing the Program
Changing a CGI program so you can reenter it without reactivation should be a no-brainer for RPG programmers because they are used to writing programs that are called repeatedly and exited without setting on the LR indicator. The first time a program is called, files must be opened, variables must be initialized, etc. On subsequent calls, however, the program skips those tasks. Persistent CGI programs should behave similarly.
Compiling the Program
Compiling a CGI program into a named activation group is also no problem. Pick a name, any name. In working up the examples for this article, I had roaring success using BBBBB as an activation group name. I could carry out separate conversations with the server from different browsers at the same time, and even though they used the same activation group name, neither interfered with the other, because they had separate session identifiers.
An Example
I worked up an example that you can download from the Midrange Computing Web site at www.midrangecomputing.com/mc/. Its an order inquiry program based on a CGI application I wrote for a client of mine. The RPG IV program, portions of which are shown in Figure 2, reads two database files: an order header file called TKTHDR and an order detail file called TKTITM. (My client refers to a sales order as a ticket, hence the TKT prefixes.) Each order has one record in TKTHDR and a line in TKTITM for each item purchased. The one-time-only code executed in subroutine *INZSR generates a new session ID, and the LR indicator is not set on.
The program prompts the user for an order number, which the user sends back to the CGI program through standard in. The program looks up the order and displays it on the browser along with another prompt for an order number.
The code isnt pretty, but I wanted to make it as simple as possible for you to run. I combined all the source members, prototypes and modules, into one source member for your convenience and used character literals to build everything to be sent to the Web browser instead of using my usual method of storing HTML in an array or file. I also removed all the JavaScript from the HTML. The routine that extracts the order number has no intelligence, so rather than extract the order number from a free-format string, it assumes the number is exactly five characters long and begins at position 8. For production programming, I have service programs that do all these things. IBMs CGIDEVD library, which you can find on the Web at www.as400.ibm.com/net.data/tstudio/ workshop/snippets/newsnip.mac/viewsavf, is a save file containing plenty of code that handles these tasks and more.
Compilation and Execution
To install the example application, upload source member TKTINQ02RG to an RPGLE source file member of your choice and follow the compilation instructions at the beginning of the program. Then, create a data area for assigning session IDs by running the following Create Data Area (CRTDTAARA) command: Running the program may take some tweaking of the HTTP configuration via the Work with HTTP Configuration (WRKHTTPCFG) command. I had never run a CGI program on Midrange Computings 170 box, so I had to create my own HTTP configuration and server instance. The configuration I copied had Map directives like the following: However, I did not have to specify the .PGM suffix, because the Map directives would append .PGM to any URL with path CGI-BIN and look for those programs in library MYCGILIB.
Those Map directives would not work for persistent CGI, though, because the session ID must follow the URL, including the .PGM portion. I modified the Map directives as follows, meaning I would have to specify the .PGM suffix on all programs from that point forward:
CRTDTAARA DTAARA(xxx/SESSIONSEQ) +
TYPE(*DEC) LEN(7 0)
Map /cgi-bin/* /QSYS.LIB/MYCGILIB.LIB/*.PGM
Map /CGI-BIN/* /QSYS.LIB/MYCGILIB.LIB/*.PGM
Map /CGI-BIN/* /QSYS.LIB/MYCGILIB.LIB/*
Map /cgi-bin/* /QSYS.LIB/MYCGILIB.LIB/*
The other issue is how to terminate the program. Well, you dont; it just times out according to the HTTimeOut: header.
Insist on Persistence
In addition to the RPG program, Ive included in the code on the Web a CGI program written in C from the end of Chapter 4 of the Web Programming Guide V4R3. I started my investigation of persistent CGI by trying to make this program run. I figured I should begin with bug-free code so I wouldnt have to worry about programming errors and could concentrate on making the program run persistently. Boy, was I surprised! The program had several bugs in it, at least some of which I found and removed. Once I had the C program working, making RPG do the same thing was easy. If youve tried to get that program to work without success, maybe the debugged version will work for you.
Ive not been a big fan of CGI, but persistent CGI makes more sense to me than plain old vanilla CGI. The only downside of persistent CGI is that new CGI program instances are created for each remote user, potentially overworking main memory. In contrast, with standard CGI, one program instance handles all remote requests. Nevertheless, I like persistent CGI because it works more like the interactive RPG programs Ive been writing since my System/34 days. I dont know how much success Ill end up having with CGI in my consulting practice, but if CGI is to be successful for me, I suspect it will be persistent CGI.
Reference
Web Programming Guide V4R3 (GC41-5435-02, CD-ROM QB3AEQ02)
Related Materials
CGI Template Programming with IBMs Snippets Library, Don Denoncourt, AS/400 Internet Expert, August/September 1998
Persistent CGI and RPG, Randy Dufault, AS/400 NetJava Expert, April/May 1999
Accept-HTSession: 0000021
HTTimeout: 5
Content-type: text/html
Jacks Sales
... (more HTML code omitted)
FTktHdr if e k disk rename(TH: TicketHdr)
FTktItm if e k disk rename(TI: TicketLine)
... (procedure prototypes omitted)
D sds
D Proc *proc
D Color s 10
D NewLine c const(X'15')
D SessionID s 7
D SessionSeq s 7p 0
D Ticket s 5p 0
D ViewedCounter s 10u 0
D X s 1024 varying
D XPrice s 9p 2
C TicketKey klist
C kfld THORDR
C
C callp GetTicketNbr (Ticket)
C exsr PrtHeadings
Figure 1: Persistent CGI programs refer to themselves through session identifiers.
Ticket ' + %editc(Ticket: '3') +C if Ticket > *zero
C eval THORDR = Ticket
C TicketKey chain TicketHdr 90
C if *in90
C eval X = '
C ' was not found; please re-enter .'
C callp WrtStdOut (X + NewLine)
C else
C exsr DspTicket
C endif
C endif
C exsr PrtFooter
C
C return *****
C DspTicket begsr
C
C eval ViewedCounter = ViewedCounter + 1 ... (code to display the order header info omitted)
C callp WrtStdOut (X + NewLine)
C exsr PrtDetails ... (code omitted)
C
C endsr *****
C PrtDetails begsr
C
C eval Color = 'red'
C TicketKey chain TicketLine 92
C dow *in92 = *off
C eval Xprice = TIQTY * TIUPRC
C eval X = '+ '
C '+ +
C TIPART +'
C + +
C '+
C %editc(TIQTY: 'J') +'
C + +
C '+
C %editc(TIUPRC: 'J') +'
C + +
C '+
C %editc(XPRICE: 'J') +'
C
C callp WrtStdOut (X + NewLine)
C if Color = 'red'
C eval Color = 'blue'
C else
C eval Color = 'red'
C endif
C TicketKey reade TicketLine 92
C enddo
C
C endsr ***************
C PrtHeadings begsr
C
C eval X = 'Accept-HTSession:' + SessionID
C callp WrtStdOut (X + NewLine)
C eval X = 'HTTimeout: 5'
C callp WrtStdOut (X + NewLine)
C eval X = 'Content-type: text/html'
C callp WrtStdOut (X + NewLine + NewLine)
C eval X = '
C Order Inquiry
C callp WrtStdOut (X + NewLine)
C eval X = 'C LINK="#CC0033" VLINK="#330066" +
C ALINK=#FF0000>'
C callp WrtStdOut (X + NewLine)
C eval X = 'Jack''s Sales
+
C
'
C callp WrtStdOut (X + NewLine)
C eval X = '
Orders viewed:' +C
C endsr
C*****
C PrtFooter begsr
C eval X = '
C %editc(ViewedCounter: '1')
C callp WrtStdOut (X + NewLine)
C eval X = ''
C callp WrtStdOut (X + NewLine)
C
C endsr
*****
C *inzsr begsr
C
C *dtaara define SessionSeq SessionSeq
C *lock in SessionSeq
C eval SessionSeq = SessionSeq+ 1
C out SessionSeq
C move SessionSeq SessionID
C
C endsr *****
* Write to Standard Output
P WrtStdOut b
D pi
D OutDta 1024 value varying ... (code omitted)
P e *****
* Read from Standard Input
P RdStdIn b
D pi
D RcvRec 4096
D RcvLen 10i 0 ... (code omitted)
P e *****
P GetTicketNbr b
D GetTicketNbr pi
D Ticket 5p 0
D InData S 4096
D InLen s 10i 0
D TicketChar s 5
C
C eval Ticket = *ZERO
C callp RdStdIn (InData: InLen)
C if InLen > *zero
C eval TicketChar = %subst(InData: 8: 5)
C move TicketChar Ticket
C endif
P e
LATEST COMMENTS
MC Press Online