29
Fri, Nov
0 New Articles

CGI RPG IV--Getting Started

RPG
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

What's keeping you from doing Web-based development? Are you considering it? When I go to a client to train their staff, I'm training them on intermediate to advanced RPG IV. I teach this over a two-day period followed by a third day of hands-on lab. Lately, however, on the last day, I'm being asked to "do a little on Web development with CGI and RPG IV."

I love writing CGI RPG IV. In fact, lately, it is the only RPG IV programming I do. But what is CGI RPG IV? For that matter, what is CGI?

Overview of CGI

Nearly every Web server includes support for the Common Gateway Interface (CGI). The only exception is Apple Computer's Macintosh Web server, but it supports a technology that is somewhat similar to CGI.

In the world of movie-making, CGI stands for Computer Generated Images. But to the World Wide Web, CGI is the interface that provides a Web server with the ability to facilitate program call requests. In other words, it is the interface that allows RPG IV programs to be called as a result of pressing the Submit button on an HTML page. CGI programs can generate dynamic HTML, update databases, and do just about anything a normal program might do.

The best thing about CGI is that it is language-neutral. That is, if you only know one programming language, the odds are pretty good that it can be used for CGI programming. On AS/400 and iSeries systems, any ILE-targeted language can be used as a CGI language. This includes RPG IV, C, C++, COBOL, and even the ILE version of CL. RPG III can be used as a CGI program, but it cannot easily interface with the OS/400 CGI APIs. It is also possible, obviously, to call RPG III programs from CGI programs written in other programming languages.

What Is a CGI Program?

Filling in an HTML form with your name and address and other information seems to be an ongoing theme on most Web sites today. After the data has been typed into the form, the end user typically presses a button marked Submit. The data is sent to the Web server, and your information is forever in someone's data warehouse. But what really happens when the Submit button is pressed?

Pressing the Submit button on an HTML Web page usually causes a program on a server to be called. The Web server itself actually calls the CGI program in response to a request made by a Web browser. The Web browser gathers up the data from the HTML form and makes it available to the called program. The called program retrieves the data entered on the HTML form, processes it, and usually sends the Web server a reply. The program being called on the server is known as a CGI program.

Calling CGI Programs

CGI programs are called by the Web server, but they are requested by the Web browser. Effectively, the Web browser sends the name of the program to be called to the Web server. The Web server then calls the CGI program.

The syntax for calling a CGI program is nearly the same as typing a Web address into a Web browser. This syntax, known as URL encoding, can be either typed in by the end user to evoke a program (rarely) or embedded in an HTML page and called up by some other mechanism. The syntax to call a CGI program is as follows:

http://www.ibm.com/eserver/iseries/mycgi.pgm?USRPRF=COZZI&PWD=STARFISH

This URL-encoded string breaks down as follows:

URL Encoded String Component
Description
http://www.ibm.com
The URL of the server
/eserver/iseries/
The virtual path on the server where the file or CGI program is located. This may or may not be a real path on the server. The HTTP configuration file (on the server) can map this virtual path into whatever real path the application requires.
mycgi.pgm
The CGI Program name to be called
?USRPRF=COZZI&PWD=STARFISH
The data passed to the program. The question mark identifies the start of the parameter list. The USRPRF keyword identifies the name of the first parameter, and COZZI is the value assigned to that parameter. The ampersand (&) between the first parameter's value COZZI and the PWD keyword is a parameter separator. It identifies the start of the next parameter. In this case, the second parameter name is PWD (password), and it is assigned the value STARFISH.

A CGI program can be called by using any of the following methods. Each method uses the same URL-encoded string syntax.

  • In response to the SUBMIT button on an HTML form
  • In response to an end user clicking on a hyperlink
  • As a URL address entered directly by an end user
  • As a server-side include

When a CGI program is called in response to a Submit button request, the compete URL-encoded string is generated by the Web browser. The other methods require the programmer to build the URL-encoded string correctly.

CGI Application Programming Interfaces (APIs)

IBM OS/400 includes a set of APIs that enables RPG IV to function as a CGI programming language. Since CGI programming is based on the UNIX operating system's I/O processing, most programming languages not originating on the IBM midrange product line have CGI functionality built in. These other languages--including C, Java, and C++--can avoid utilizing many of the APIs featured in this section.

The CGI APIs provide a method of communication between a Web browser and programs, through the Web server. In addition, a few utility APIs provide additional functionality directly related to CGI programming issues. The available APIs for CGI programming include the following.

API Name
Description
QtmhGetEnv
Get a value from the CGI environment
QtmhPutEnv
Change a value in the CGI environment
QtmhRdStin
Read a string from the standard-input device (i.e., read data sent to a CGI program from an HTML form)
QtmhWrStout
Write a string to the standard-output device (i.e., write to the Web browser)
QtmhCvtDB
Convert URL-encoded string to an externally described data structure
QzhbCgiParse
Parse the data from an HTML form
QzhbCgiUtils
"Utilities" to create a full HTTP response

These APIs are referred to as bindable APIs. That is, they are procedure calls, not program calls. Consequently, in RPG IV, the CALLB or CALLP operation codes must be used to call these APIs. In addition, the API names are case-sensitive.

These APIs exist in a service program (*SRVPGM) object in OS/400. The service program name is QZHBCGI and is located in the QHTTPSVR library.

To avoid incorrectly specifying the names of the bindable APIs, named constants are often created and referenced instead of the API names themselves. This allows case-insensitive names to be specified in Factor 2 of the CALLB operation code and the EXTPROC keyword. The example that follows illustrates a set of name constants that can be used in place of the API names.

.....DName+++++++++++EUDS.......Length+TDc.Functions+++++++++++++++++++
     D cgiGetEnv                         Const('QtmhGetEnv')
     D cgiPutEnv                         Const('QtmhPutEnv')
     D cgiRdStin                         Const('QtmhRdStin')
     D cgiWrStout                        Const('QtmhWrStout')
     D cgiCvtDB                          Const('QtmhCvtDB')
     D cgiParse                          Const('QzhbCgiParse')
     D cgiUtils                          Const('QzhbCgiUtils')

One of the most frequently used interfaces is the QtmhWrStout API. This API allows you to send HTML or other source to the Web browser. Many of the things you need to send to the Web browser require a line-feed character. For example, the heading for your HTML text usually includes one of the various CGI Headers, such as Content-Type, Status, or Location. Each of these requires a line-feed character to follow them.

Unfortunately, the compiler writers didn't include any native support for CGI programming RPG IV. So even something as simple as a line-feed character needs to be embellished in RPG IV. The line-feed character translates to X'15' in RPG IV, which means concatenation is required. For example, to create "Content-type: text/html" followed by two-line feed characters, the following RPG IV statement can be used:

     C                   Eval      html = 'Content-type: text/html' + X'1515'

In all other CGI languages, the line-feed character is represented by a symbolic "escape" character. That is, if you embed a backslash followed by a lower case n, the symbol is converted into a line-feed character. If this support were provided in RPG IV, the following would be allowed:

     C                   Eval      html = 'Content-type: text/html '

By supporting this symbolic line feed, numerous concatenations can be avoided. Fortunately, I got fed up with constantly doing concatenations and wrote a wrapper API around QtmhWrStout. I call this wrapper STDOUT (Write to Standard Output).

The STDOUT procedure wraps the CGI QtmhWrStout API by allowing the caller to simply specify the HTML text to be sent to the browser without concern for embedding X'15'. It does this by scanning the input text for embedded symbols and translates them into X'15' before sending the HTML text to the QtmhWrStout API.

Syntax and Parameters

html-text-length = STDOUT( 'html-text' )

The first parameter is the HTML text to be sent to the browser. Any valid HTML may be specified. In addition, embedded symbols are automatically translated to X'15' for use by the QtmhWrStout API. The parameter is a VARYING length field, which is used to determine the true length of the data being sent to the browser. This avoids requiring the length to be specified on the STDOUT API itself.

The return value is the length of the text that was sent to the browser.

Rather than post the entire STDOUT procedure's source in this issue, I've made it available for free download as a source member (ASCII text file). To download the source code for the STDOUT procedure, follow this link.

--Bob Cozzi

BOB COZZI

Bob Cozzi is a programmer/consultant, writer/author, and software developer. His popular RPG xTools add-on subprocedure library for RPG IV is fast becoming a standard with RPG developers. His book The Modern RPG Language has been the most widely used RPG programming book for more than a decade. He, along with others, speaks at and produces the highly popular RPG World conference for RPG programmers.


MC Press books written by Robert Cozzi available now on the MC Press Bookstore.

RPG TnT RPG TnT
Get this jam-packed resource of quick, easy-to-implement RPG tips!
List Price $65.00

Now On Sale

The Modern RPG IV Language The Modern RPG IV Language
Cozzi on everything RPG! What more could you want?
List Price $99.95

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: