Sidebar

Simon's Solutions: Prepared to Be Surprised by QCMD?

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

Learn the practical techniques to take advantage of the IBM-supplied request processors.

 

In a shell environment (for example, a UNIX Shell environment, or the QShell or PASE Shell environment provided by IBM i), you can run a list of commands all at once by simply separating the commands by semicolon (;) operators. For example, to obtain an estimated running time of a time-consuming program, you can invoke the target program in a QShell or PASE Shell session via the following list of Shell commands:

date; system "call snail_run"; date

Similar utilities in the CL environment are the Start Database Reader (STRDBRDR) and the Submit Database Jobs (SBMDBJOB) commands that read a batch input stream from a database file and run the requested commands in a submitted batch job. However, they cannot be used to run requested CL commands interactively. In a post (Re: Interactive version of STRDBRDR) in the Midrange-L mailing list in 2002, Simon Coulter provided a perfect solution that allows users run a list of CL commands stored in a database file at once interactively. The mechanism of Simon's solution is quite straight forward, as quoted from Simon's original post: "Just read the source file, send each line as a request message, and then give control to QCMD."

If you're unfamiliar with request (*RQS) messages, you're probably astonished by this statement. If so, I hope the following sections of this article might fulfill your curiosity about *RQS messages, request processors, and ways to utilize the IBM-supplied request processors (QCMD and QCL) to ease your daily work.

  • The Start CL Reader (STRCLRDR) Command Provided by Simon
  • How Does a Request Processor Work?
  • An Example Request Processor That Processes Either CL Commands or SQL Statements
  • Another Example of Utilizing the IBM-Supplied Request Processors: A Simple Yet Practical Batch Machine

The Start CL Reader (STRCLRDR) Command Provided by Simon

In his 2002 post, Simon provided source of a CL command Start CL Reader (STRCLRDR) and the associated Command Processor Program (CPP) STRCLRDRC. The runnable source of the CL program STRCLRDRC and the STRCLRDR command are available at project i5/OS Programmer's Toolkit (i5toolkit) as strclrdrc.clp and strclrdr.cl-cmd, respectively.

The following is Simon's original post:

Re: Interactive version of STRDBRDR

   Subject: Re:   Interactive version of STRDBRDR

   From:   "Simon Coulter" <shc@xxxxxxxxxxxxxxxxx>;

   Date: Thu, 26   Sep 02 20:06:29 +1000

   Importance: Normal

   List-archive:   <http://archive.midrange.com/midrange-l/>;

Hello Joe,

You wrote:

>If I wanted to put a few CL commands into a source   member and just run them

>(kind of like old-fashioned OCL), can I do it? The last time I did this,

>many years ago, I used STRDBRDR, but that requires   submitting to batch. Can

>it be done interactively?

Yes. Just read the source file, send each line   as a request message, and                

then give control to   QCMD.

Here is my version.   I wrote this years ago and tidied it up just for you.

I'm sure you can write your own replacements for the   EXTQUALOBJ and STDERR

commands but if you want them too then let me know.

/* ** Start of specifications   ************************************************/

/* PARMS PGM(STRCLRDRC) ALLOW(*INTERACT *IPGM *IMOD   *IREXX)                 */

/*                                                                             */

/* Command name   . . . . . . : STRCLRDR                                     */

/*                                                                            */

/* Descriptive name   . . . . : Start CL Reader                               */

/*                                                                             */

/* Function . .   . . . . . . : To interpret a CL source member.             */

/*                                                                             */

/* Copyright:                                                                 */

/*   (C)   Copyright S.H. Coulter 1987, 2002. All rights reserved.             */

/*   (C)   Copyright FlyByNight Software. 1987, 2002. All rights reserved.     */

/*                                                                             */

/* External references:                                                       */

/*   Command   processor . . . : STRCLRDRC                                     */

/*                                                                             */

/*     Messages . . . . . . . :                                                 */

/*                                                                            */

/*   Help panel   group . . . :                                                 */

/*                                                                             */

/*     Programs . . . . . . . :                                              */

/*                                                                             */

/*   Files . . .   . . . . . . :                                                 */

/*                                                                             */

/*   Data   areas . . . . . . :                                                 */

/*                                                                             */

/* Notes:                                                                     */

/*   Dependencies   . . . . . :                                                 */

/*                                                                             */

/*     Restrictions . . . . . :                                                 */

/*                                                                          */

/*   Support . .   . . . . . . : shc@xxxxxxxxxxxxxxxxx                         */

/*                                                                             */

/* Change activity:                                                          */

/*                 Rlse &                                                       */

/* Flag Reason     Level Date   Pgmr         Comments                             */

/* ---- -------- ------ ------ ----------   -----------------------------------*/

/* $A0= D                 870228 SHC:       Initial coding   of command.         */

/* $A1= D                 920107 SHC:       Support both   S/38 and AS/400 syntax*/

/* $A2= D                 020926 SHC:       Remove dumb   defaults and make more */

/*                                           like an IBM command.               */

/*                                                                             */

/* ** End of specifications   **************************************************/

STRCLRDR:   CMD        PROMPT('Start CL Reader')

               PARM       KWD(SRCFILE) TYPE(Q1)   MIN(1) PROMPT('Source +

                         file')

               PARM       KWD(SRCMBR)   TYPE(*NAME) LEN(10) MIN(1) +

                         EXPR(*YES)   PROMPT('Member')

Q1:         QUAL       TYPE(*NAME) LEN(10) MIN(1) EXPR(*YES)

               QUAL       TYPE(*NAME) LEN(10)   DFT(*LIBL) +

                         SPCVAL((*LIBL)   (*CURLIB *CURLIB)) +

                         EXPR(*YES)   PROMPT('Library')

/* ** Start of specifications   ************************************************/

/*PARMS                                                                       */

/*                                                                             */

/* Module name . . . . . . . : STRCLRDRC                                     */

/*                                                                             */

/* Descriptive name   . . . . : Start CL Reader                               */

/*                                                                            */

/* Function . .   . . . . . . : Reads a CL source member and executes         */

/*                             each CL   statement by sending each line         */

/*                             as a *RQS   message to the *EXT message         */

/*                             queue of the job   and then calling the         */

/*                             command executor   to run them.                 */

/*                             Allows   interactive CL interpretation of         */

/*                            CL command groups   similar to STRDBRDR.       */

/*                                                                             */

/* Copyright:                                                                 */

/*   (C)   Copyright S.H. Coulter 1987, 2002. All rights reserved.             */

/*   (C)   Copyright FlyByNight Software. 1987, 2002. All rights reserved.     */

/*                                                                             */

/* Module type:                                                              */

/*   Processor .   . . . . . . : CLP                                           */

/*                                                                             */

/*   Module size   . . . . . . :                                              */

/*                                                                             */

/*     Attributes . . . . . . :                                                 */

/*                                                                            */

/* Entry:                                                                     */

/*   Entry point   . . . . . . : STRCLRDRC                                     */

/*                                                                             */

/* Purpose . . . . . . . . : (See   function)                                 */

/*                                                                             */

/*   Linkage . .   . . . . . . : CPP for STRCLRDR                             */

/*                                                                            */

/* Input . . . . . . . . . . : &QUALSRCF   - Qualified source file           */

/*                             &SRCMBR     - Member name                     */

/*                                                                          */

/* Output . . .   . . . . . . : *NONE                                         */

/*                                                                             */

/* External references:                                                    */

/*     Routines . . . . . . . :   STDERR     - Standard error   handler           */

/*                             EXTQUALOBJ -   Extract qualified object         */

/*                                                                            */

/*   Files . . .   . . . . . . :                                                 */

/*                                                                             */

/*   Data   areas . . . . . . :                                                 */

/*                                                                          */

/*   Control   blocks . . . . :                                                 */

/*                                                                             */

/*   References   from UIM . . :                                                 */

/*                                                                             */

/* Exits-- Normal   . . . . . : Return to NSI                                 */

/*     -- Error   . . . . . . : Resignal escape message to caller             */

/*                                                                             */

/* Messages:                                                                   */

/*   Generated .   . . . . . . : CPF9898 - Impromptu messages                 */

/*                                                                             */

/* Resignalled .   . . . . . : *ESCAPE messages                               */

/*                             *NOTIFY   messages                            */

/*                                                                             */

/*   Monitored .   . . . . . . : CPF9999 - Function check exceptions           */

/*                             CPF0864 - End of   file.                       */

/*                                                                          */

/* Macros/Includes . . . . . :                                                 */

/*                                                                             */

/* Data/Tables . . . . . . . :                                                 */

/*                                                                             */

/* Notes:                                                                     */

/*     Dependencies . . . . . : STDERR     - Standard error handler           */

/*                             EXTQUALOBJ -   Extract qualified object         */

/*                                                                             */

/*     Restrictions . . . . . :                                              */

/*                                                                             */

/*   Register   conventions . : N/A                                           */

/*                                                                            */

/*   Patch label   . . . . . . : N/A                                           */

/*                                                                             */

/*   Support . .   . . . . . . : shc@xxxxxxxxxxxxxxxx                         */

/*                                                                          */

/* Change activity:                                                           */

/*                 Rlse &                                                       */

/* Flag Reason     Level Date   Pgmr         Comments                             */

/* ---- -------- ------ ------ ----------   -----------------------------------*/

/* $A0= D                 870128 SHC:       Initial coding   of module.         */

/* $A1= D                 920107 SHC:       Support both   S/38 and AS/400 syntax*/

/* $A2= D                 020926 SHC:       Remove dumb   defaults and make more */

/*                                           like an IBM command.               */

/*                                                                            */

/* ** End of specifications   **************************************************/

STRCLRDRC: PGM         PARM(&QUALSRCF &SRCMBR)

/*                                                                   */

/* ---------------- Input Parameter Declarations   ----------------- */

/*                                                                   */

               DCL       VAR(&QUALSRCF)   TYPE(*CHAR) LEN(20)

                         /* Qualified source file                   */

             DCL       VAR(&SRCMBR) TYPE(*CHAR) LEN(10)

                         /* Source member name                     */

/*                                                                   */

/* ------------------- Program Declarations   ---------------------- */

/*                                                                   */

               DCLF       FILE(QCLSRC)

                         /* Source file template                   */

               DCL       VAR(&SRCF)   TYPE(*CHAR) LEN(10)

                         /* Source file                             */

               DCL       VAR(&SRCFLIB)   TYPE(*CHAR) LEN(10)

                         /* Source file library                     */

               DCL       VAR(&TYPE)   TYPE(*CHAR) LEN(1)

                         /* Source member type                     */

               DCL       VAR(&SRCTYPE)   TYPE(*CHAR) LEN(10)

                         /* Source member type                     */

               DCL       VAR(&ERROR)   TYPE(*LGL) LEN(1)

                         /* Error flag                             */

/*                                                                   */

/* ---------------- Mnemonic Value Declarations   ------------------ */

/*                                                                   */

            DCL       VAR(&BLANK) TYPE(*CHAR) LEN(1)   VALUE(X'40')

                         /* Mnemonic for 'blank'                   */

               DCL       VAR(&TRUE)   TYPE(*LGL) LEN(1) VALUE('1')

                         /* Mnemonic for 'true'                      */

               DCL       VAR(&FALSE)   TYPE(*LGL) LEN(1) VALUE('0')

                         /* Mnemonic for 'false'                   */

               DCL       VAR(&STAR)   TYPE(*CHAR) LEN(1) VALUE('*')

                         /* Mnemonic for 'asterisk'                 */

               DCL       VAR(&QUOTE)   TYPE(*CHAR) LEN(1) VALUE('''')

                         /* Mnemonic for 'quote'                   */

               DCL       VAR(&BATCH)   TYPE(*CHAR) LEN(1) VALUE('0')

                         /* Mnemonic for 'batch job'               */

               DCL       VAR(&INTER)   TYPE(*CHAR) LEN(1) VALUE('1')

                         /* Mnemonic for 'interactive job'         */

               DCL       VAR(&ZERO)   TYPE(*DEC) LEN(1 0) VALUE(0)

                        /* Mnemonic for 'zero'                     */

               DCL       VAR(&HEX00)   TYPE(*CHAR) LEN(2) VALUE(X'0000')

                         /* Mnemonic for 'binary zero'             */

/*                                                                  */

/* ------------------- Copyright Declarations   -------------------- */

/*                                                                   */

               DCL       VAR(&COPYRIGHT)   TYPE(*CHAR) LEN(80) +

                         VALUE('Copyright   (C) FlyByNight Software. +

                         1987, 2002')

/*                                                                   */

/* -------------- Global Message Monitor Intercept   --------------- */

/*                                                                  */

               MONMSG     MSGID(CPF9999)   EXEC(GOTO CMDLBL(FAILED))

/*                                                                   */

/* ---------- Force Copyright Notice in Executable Code   ---------- */

/*                                                                */

               CHGVAR     VAR(&COPYRIGHT)   VALUE(&COPYRIGHT)

             /*   Initialise error indicator                         */

               CHGVAR     VAR(&ERROR)   VALUE(&FALSE)

             /*   Find out job type. Force SBMDBJOB in batch job.   */

             /*   Belts and braces code - CDO not allowed in batch. */

               RTVJOBA   TYPE(&TYPE)

               IF         COND(&TYPE *EQ   '0') THEN(DO)

                 SNDPGMMSG MSGID(CPF9898)   MSGF(QCPFMSG) MSGDTA('STRCLRDR +

                           is only valid in   an interactive job. Use +

                           SBMDBJOB for   batch execution') +

                           MSGTYPE(*ESCAPE)

               ENDDO

             /*   Split out the qualified source file names.         */

               EXTQUALOBJ QUALOBJ(&QUALSRCF) OBJ(&SRCF) LIB(&SRCFLIB)

             /*   Ensure the source member exists and can be read.   */

               CHKOBJ       OBJ(&SRCFLIB/&SRCF) OBJTYPE(*FILE) MBR(&SRCMBR) +

                            AUT(*USE)

             /*   Check that source type is valid for CL interpreter */

               RTVMBRD     FILE(&SRCFLIB/&SRCF) MBR(&SRCMBR) SRCTYPE(&SRCTYPE)

               IF         COND( (&SRCTYPE   *NE 'CL')   *AND +

                             (&SRCTYPE   *NE 'CL38') *AND +

                             (&SRCTYPE   *NE 'CLP') *AND +

                             (&SRCTYPE   *NE 'CLP38') *AND +

                             (&SRCTYPE   *NE 'CLLE') ) THEN(DO)

               SNDPGMMSG MSGID(CPF9898)   MSGF(QCPFMSG) MSGDTA('Source +

                         type of member'   *BCAT &SRCMBR *BCAT 'in +

                         file' *BCAT   &SRCF *BCAT 'in' *BCAT +

                         &SRCFLIB *BCAT   'must be CL, CL38, CLP, +

                         CLP38, or CLLE')   MSGTYPE(*ESCAPE)

               ENDDO

             /*   Point to the correct source member.               */

               OVRDBF     FILE(QCLSRC)   TOFILE(&SRCFLIB/&SRCF) MBR(&SRCMBR)

             /*   Read each record in the source member.             */

READ:       RCVF

               MONMSG     MSGID(CPF0864)   EXEC(DO)

                 RCVMSG     MSGTYPE(*LAST)

                 GOTO CMDLBL(EOF)

               ENDDO

             /*   Send the command to the external queue as a       */

               /*   request message.                                 */

               IF         COND(&SRCDTA *NE   &BLANK) THEN(DO)

                 SNDPGMMSG MSG(&SRCDTA)   TOPGMQ(*EXT) MSGTYPE(*RQS)

               ENDDO

               GOTO       CMDLBL(READ) /* Get   the next command       */

EOF:       DLTOVR     FILE(QCLSRC)

             /*   Send message to return control to the module       */

             /*   after all source statements have been executed.   */

               SNDPGMMSG MSG(RETURN)   TOPGMQ(*EXT) MSGTYPE(*RQS)

             /*   Execute the request messages                       */

               /*   -- QCL is used for   System/38 commands           */

               IF         COND((&SRCTYPE   *EQ 'CL38') *OR +

                             (&SRCTYPE   *EQ 'CLP38')) THEN(DO)

              CALL         PGM(QCL)

               ENDDO

               /*   -- QCMD is used for AS/400   commands             */

               ELSE       CMD(DO)

                 CALL       PGM(QCMD)

               ENDDO

/*                                                                  */

/* -------------------- Send User a Message   ---------------------- */

/*                                                                   */

             /*   Send completion message. This does not guarantee   */

             /*   SUCCESSFUL completion of all commands, only that   */

             /*   the file was read and statements were processed.   */

               SNDPGMMSG MSGID(CPF9898)   MSGF(QCPFMSG) +

                         MSGDTA('Commands in   member' *BCAT &SRCMBR +

                          *BCAT 'in file' *BCAT   &SRCF *BCAT 'in' +

                         *BCAT &SRCFLIB   *BCAT 'completed') MSGTYPE(*COMP)

               SNDPGMMSG MSGID(CPF9898)   MSGF(QCPFMSG) MSGDTA('Check +

                         low-level messages   for any errors +

                          encountered')   MSGTYPE(*COMP)

EXIT:       RETURN     /* Normal   end of program                   */

/*                                                                   */

/* --------------------- Exception Routine   ----------------------- */

/*                                                                   */

FAILED:     STDERR     PGMTYPE(*CPP)

               MONMSG     MSGID(CPF9999) /*   Just in case             */

STRCLRDRX: ENDPGM

Regards,

Simon Coulter.

As shown above, the STRCLRDR command accepts a qualified database file name and a member name, reads the target file member, and sends each record as a request message (*RQS) to the external message queue (*EXT) of the job. Finally, it passes control to one of the IBM-supplied request processors according to the source type of the specified file member, the QCMD program for the IBM command environment, or the QCL program for the System/38 command environment. Note that before invoking QCMD or QCL, an additional request message, the RETURN command, is sent to the *EXT message queue to tell the request processor to quit after processing all the request messages. Without the RETURN command, the request processor will display the Command Entry display and wait for further commands entered by the user. (When a command is entered, it is placed on the *EXT message queue as a request message.)

Compile the STRCLRDR command and its CPP from strclrdr.cl-cmd and strclrdrc.clp, respectively. For example, when building from IFS stream source files, you might follow these steps:

  1. 1.Upload source files strclrdr.cl-cmd and strclrdrc.clp to an IFS path on your IBM i server, e.g., ~/my-source-dir.
  2. 2.Change the current directory to your source directory, e.g., CHDIR DIR('~/chqs/miex/111').
  3. 3.Compile the STRCLRDR command, e.g., CRTFRMSTMF OBJ(STRCLRDR) CMD(CRTCMD) SRCSTMF('strclrdr.cl-cmd') PARM('pgm(*libl/strclrdrc)').
  4. 4.Compile STRCLRDR's CPP, e.g., CRTFRMSTMF OBJ(STRCLRDRC) CMD(CRTCLPGM) SRCSTMF(strclrdrc.clp).

The CRTFRMSTMF (Create Object from STMF) command is a utility that allows you build IBM i objects such as OPM CL programs, CL commands, or Panel Group (*PNLGRP) objects from IFS source whose corresponding native building commands do not support IFS source. You may also upload the source files to the /QSYS.LIB file system and compile them via the CRTCMD and CRTCLPGM commands directly.

To test the STRCLRDR command, you may prepare a source member, say SRCLIB/SRCF,CMDS, with source type CL38, containing CL commands to execute.

   SNDMSG 'HELLO' +

           *SYSOPR

   DLYJOB 100

   DLTPGM NOSUCHONE.NOSUCHLIB

   SNDMSG 'TIME TO QUIT' *SYSOPR

Invoke the STRCLRDR command like this:

STRCLRDR SRCFILE(SRCLIB/SRCF) SRCMBR(CMDS)

Since the source type of SRCLIB/SRCF,CMDS is CL38, QCL will be invoked as the request processor. After issuing the above-shown STRCLRDR command, check the call stack of your interactive job. You can find QCL near the end of the call stack; it's marked as a request processor with the currently largest request level value. Here's an example:

Type Program                 Statement         Procedure

       QCMD       QSYS                     /0512

       QUICMENU   QSYS                     /00C1

   1   QUIMNDRV   QSYS                     /060C

   2 QUIMGFLW   QSYS                     /04C8

   3   QUICMD     QSYS                     /048D

       QUOCPP     QPDA                     /07A8

       QUOMAIN   QPDA                     /05B1

   4   QUOCMD     QSYS                     /012D

       STRCLRDRC LSBIN         22500     /00A1

   5 QCL         QSYS                     /0166

       QWCDLYJB   QSYS                     /0030

Check the job log of your interactive job. You can find out what's going on with the requested commands. For example:

5 > SNDMSG 'HELLO' +

5   >       *SYSOPR

5>>   DLYJOB 100

..   DLTPGM NOSUCHONE.NOSUCHLIB

..   SNDMSG 'TIME TO QUIT' *SYSOPR

..   RETURN

Pay attention to the above-shown example job log, where:

  • 5 is the current request level
  • A greater-than symbol (>) precedes a processed request, a double greater-than (>>)precedes the current request being processed, and a double period (..) precedes a request to process.

As an experienced IBM i developer, you might be very familiar with the QCMD program and its counterpart QCL for the System/38 command environment. Now, you've also seen how handy it is to utilize QCMD and QCL as request processors to process CL commands sent as request messages to the *EXT message queue.

How Does a Request Processor Work?

 

Generally, a request processor (a program or a procedure) receives request messages from the external message queue (*EXT) of the job, interprets each request according to a specific predefined syntax, executes the requested function, and diagnoses any errors. For example, CL commands are requests that are received and processed by the IBM-supplied CL processor QCMD for the IBM i command environment and by QCL for the System/38 command environment. A custom request processor can define its own syntax. For example, an SQL request processor would expect SQL statements as its input requests. Details about the working mechanism of a request processor can be found in the following Web pages in the Information Center: Writing request-processor procedures and programs and Receiving request messages.

For simplicity, I'll list the common tasks that a request processor should perform.

First, a program or a procedure becomes a request processor after successfully receiving a request message (*RQS) via either a RCVMSG PGMQ(*EXT) MSGTYPE(*RQS) command or the Receive Program Message (QMHRCVPM) API from the external message queue (*EXT) of a job. For example:

RCVMSG PGMQ(*EXT)

       MSGTYPE(*RQS)

       RMV(*NO)

       KEYVAR(&MK)

       MSG(&CMDSTR)

       MSGLEN(&LEN)

When any request message is received, it is moved (actually, it is removed and resent) to the call message queue of the procedure or program that specified the RCVMSG command. Therefore, the correct call message queue must be used later when the message is removed. You must specify RMV(*NO) on the RCVMSG command because the procedure or program is not a request processor if the request message is removed from the call message queue. If there is no request message on *EXT, the Command Entry display is shown. The display station user enters a command on the display. When the command is entered, it is placed on *EXT as a request message.

Second, a request processor validates and interprets the received request according to request processor?specific syntax and processes the request. For example, to validate and process a request as a CL command, you can call the Process Commands (QCAPCMD) API and specify the message reference key in order to have the command analyzer process a request message. You can get the message reference key when you receive the request message. The QCAPCMD API will update the request message in the job log and add any new value supplied. QCAPCMD also hides any parameter values, such as passwords, that are to hidden in the job log.

The request processor remains a request processor until it ends (either normally or abnormally) or until a RMVMSG command is run to remove all the request messages from the request processor's call message queuefor example, a RMVMSG PGMQ(*SAME (*)) CLEAR(*ALL) command.

Note that a request processor should monitor for request-check (CPF9901) and function-check (CPF9999) escape messages, as well as CPF1907 (end request) and CPF2415 (which indicates that the user pressed F3 or F12 on the Command Entry display) escape messages.

An Example Request Processor That Processes Either CL Commands or SQL Statements

Here's an example request processor, rqs03.clp, which processes either CL commands or SQL statements following the steps mentioned above. RQS03 regards a request message starting with a percent symbol (%) as an SQL statement and executes the SQL statement in a submitted batch job via the QShell db2 utility.

             /*************************************************************/

             /* @file rqs03.clp                                           */

             /* Example request processor   that supports CL and SQL.       */

               /*************************************************************/

             DCL       VAR(&MK) TYPE(*CHAR) LEN(4)

             DCL       VAR(&LEN) TYPE(*DEC) LEN(5 0)

             DCL       VAR(&SQLSTMT) TYPE(*CHAR)   LEN(256)

             DCL       VAR(&CPOP) TYPE(*CHAR) LEN(20) +

                        VALUE(X'00000000F1F2F0000000000000000000000+

                         00000')

             DCL       VAR(&PRCTYP) TYPE(*INT)   STG(*DEFINED) LEN(4) +

                         DEFVAR(&CPOP 1)   /* Command process type. +

                         0 = run command   directly */

             DCL       VAR(&DBCSOPT) TYPE(*CHAR)   STG(*DEFINED) +

                         LEN(1)   DEFVAR(&CPOP 5) /* DBCS data +

                         handling. '1' =   handle DBCS data */

             DCL       VAR(&PMTOPT) TYPE(*CHAR)   STG(*DEFINED) +

                         LEN(1)   DEFVAR(&CPOP 6) /* Prompter action. */

             DCL       VAR(&CMDSNX) TYPE(*CHAR)   STG(*DEFINED) +

                         LEN(1)   DEFVAR(&CPOP 7) /* Command string +

                         syntax. '0' = using   system syntax +

                         (instead of S/38   syntax) */

             DCL       VAR(&RQSMSGKEY) TYPE(*CHAR)   STG(*DEFINED) +

                         LEN(4)   DEFVAR(&CPOP 8) /* Message +

                         retrieve key identifying   a request message. */

             DCL       VAR(&CMDCCSID) TYPE(*INT)   STG(*DEFINED) +

                         LEN(4)   DEFVAR(&CPOP 12) /* CCSID of +

                         command string. 0 =   use job CCSID */

             DCL       VAR(&CPOPRSVD) TYPE(*CHAR)   STG(*DEFINED) +

                         LEN(5)   DEFVAR(&CPOP 16)

             DCL       VAR(&QUSEC) TYPE(*CHAR) LEN(16) +

                           VALUE(X'00000000000000000000000000000000')

             DCL       VAR(&CMDSTR) TYPE(*CHAR) LEN(256)

             DCL       VAR(&CMDSTRLEN) TYPE(*INT) LEN(4)   VALUE(2)

             DCL       VAR(&CPOPLEN) TYPE(*INT) LEN(4)   VALUE(20)

             DCL       VAR(&CPOPFMT) TYPE(*CHAR) LEN(8)   +

                         VALUE('CPOP0100')

            DCL       VAR(&CMDRTN) TYPE(*CHAR) LEN(256)

             DCL       VAR(&CMDRTNLEN) TYPE(*INT) LEN(4)   VALUE(256)

             DCL       VAR(&CMDRRLEN) TYPE(*INT) LEN(4)

             MONMSG     MSGID(CPF1907 CPF2415) EXEC(GOTO +

                          CMDLBL(QUIT)) /* CPF1907=End   request, +

                         CPF2415=F3 or F12.   Time to quit */

/* 1) Receive a *RQS   message from message queue *EXT */

READ:         RCVMSG     PGMQ(*EXT)   MSGTYPE(*RQS) RMV(*NO) +

                         KEYVAR(&MK)   MSG(&CMDSTR) MSGLEN(&LEN)

/* 2) Process a request */

             IF         COND(%SST(&CMDSTR 1 1) *EQ '%')   THEN(DO)

                 CHGVAR %SST(&CMDSTR 1 1)   ' '

                 CHGVAR     VAR(&SQLSTMT) VALUE('db2 "'   *CAT &CMDSTR +

                              *TCAT '"')

                 SBMJOB     CMD(STRQSH CMD(&SQLSTMT))   JOB(PRC_SQL)

             ENDDO     /* END OF SQL PROCESSING */

             ELSE       CMD(DO)

                 CHGVAR     VAR(&RQSMSGKEY) VALUE(&MK)

                 CHGVAR     VAR(&CMDSTRLEN) VALUE(&LEN)

                 CALL       PGM(QCAPCMD) PARM(&CMDSTR   &CMDSTRLEN &CPOP +

                             &CPOPLEN   &CPOPFMT &CMDRTN &CMDRTNLEN +

                             &CMDRRLEN   &QUSEC)

                 MONMSG     MSGID(CPF9901) EXEC(RCLRSC) /* Request   check */

                 MONMSG     MSGID(CPF9999) EXEC(RCLRSC) /* Function   +

                             check */

             ENDDO     /* END OF CL PROCESSING */

             GOTO       CMDLBL(READ)

/* 3) Clean-up */

QUIT:         RMVMSG     PGMQ(*SAME (*))   CLEAR(*ALL)

             SNDPGMMSG MSG('Farewell :p')

BANG:         ENDPGM

Call RQS03 and enter the following commands:

   > % CREATE TABLE   QGPL.WINTER( WDATE DATE, WTEMP DECIMAL(3,0), WRMRK CHAR(32))

     Job 553723/LJL/PRC_SQL submitted to job   queue QBATCH in library QGPL.  

   > % INSERT INTO   QGPL.WINTER VALUES('2012-12-01', 5, 'A nice   Saturday')    

     Job 553726/LJL/PRC_SQL submitted to job   queue QBATCH in library QGPL.  

   > RUNQRY *N WINTER

The output might look like the following:

                                 Display   Report                              

                                               Report width . . . . . :     51

Position to line . . . . .             Shift to column . . . . . .      

Line     ....+....1....+....2....+....3....+....4....+....5.                  

       WDATE       WTEMP   WRMRK                                              

000001 2012-12-01     5   A nice Saturday                                  

****** ******** End of report ********                                    

Another Example of Utilizing the IBM-Supplied Request Processors: A Simple Yet Practical Batch Machine


As an addition example of using QCMD and QCL, I'd like to show you a practical batch machine program, RQS01, a CL program containing merely less than 10 lines of code. To start the batch machine, you simply submit a batch job that calls RQS01, which in turn receives incoming requests from a Message Queue (*MSGQ) object, BCHMCH, and executes the requested CL commands one by one. Since rqs01 accepts requests via a *MSGQ object, a client of this batch machine program can be any program or user that is authorized to the *MSGQfor example, an operator who issues a SNDMSG TOMSGQ(BCHMCH) command, or a Java program running on a PC that accesses BCHMCH and sends a message to it via JT/Open (aka IBM Toolbox for Java).

The source for RQS01, rqs01.clp, is the following:

             DCL       VAR(&CMD) TYPE(*CHAR) LEN(1000)

             RCVMSG     MSGQ(BCHMCH) MSGTYPE(*ANY) WAIT(*MAX) +

                         RMV(*YES)   MSG(&CMD)                               /* [1] */

             IF         COND(&CMD *EQ 'QUIT') THEN(GOTO   CMDLBL(ENDPGM))   /* [2] */

             SNDPGMMSG MSG(&CMD) TOPGMQ(*EXT)   MSGTYPE(*RQS)             /* [3] */

             SNDPGMMSG MSG('CALL RQS01') TOPGMQ(*EXT)   MSGTYPE(*RQS)     /* [4] */

             RETURN                                                         /* [5] */

ENDPGM:       SNDMSG     MSG('Batch machine ended.')   TOMSGQ(*SYSOPR)

Notes:

[1] Receive an input request from *MSGQ BCHMCH.

[2] If character string 'QUIT' is received, say farewell and quit.

[3] Send the requested command as a request message to the *EXT message queue so that QCMD will see and process the requested command after control being returned to it.

[4] Send another request message, CALL RQS01, to *EXT. This way, RQS01 will be invoked again each time after a requested command is processed by QCMD.

[5] Now, pass control back to QCMD via the RETURN command and let QCMD process the previously sent two request messages.

Before actually running the batch machine program, a couple of prerequisite operations are needed:

  • Create message queue BCHMCH from which the batch machine program receives requested CL commandsfor example, CRTMSGQ BCHMCH.
  • Prepare a job description (*JOBD) object for the batch machine job. A batch job ends when the request processing program QCMD or QCL encounters an escape message whose severity is equal to or greater than the End Severity (ENDSEV) value of the batch job. To avoid the batch machine job ending due to an escape message, you should create a *JOBD for the batch machine job with the ENDSEV parameter set to a value higher than the default value 30. For example, CRTJOBD JOBD(NEVEREND) ENDSEV(99).

Now, start the batch machine by issuing a Submit Job (SBMJOB) command like this:

SBMJOB CMD(CALL PGM(RQS01)) JOB(BCHMCH) JOBD(NEVEREND)

To test the batch machine, you may let it say Hello to your interactive job via a Send Message (SNDMSG) command like this:

   SNDMSG MSG('SNDBRKMSG MSG(HELLO)   TOMSGQ(ME) MSGTYPE(*INQ)')

     TOMSGQ(BCHMCH)

Here, ME should be replaced by the actual name of the workstation message queue of your interactive job.

Also, you can issue requested CL commands to the batch machine from a remote locationfor example, via the Access Classes provided by the IBM Toolbox for Java. The following Java program, rqs02.java, can be used to send CL commands to the batch machine.

import   com.ibm.as400.access.*;

public class rqs02 {

   public static void main(String[] args) {

       if(args.length == 0) {

           System.out.println("usage:   java rqs02 cl-cmd");

           System.exit(1);

       }

       MessageQueue bchmch =

           new MessageQueue(new   AS400("system-name", "user-name", "password"),

                            "/qsys.lib/*libl.lib/bchmch.msgq");

       try {

             bchmch.sendInformational(args[0]);

       } catch(Exception e) {

           System.out.println("Oops!   " + e.getMessage());

       }

       System.out.println("Command:   " + args[0]);

   }

}

Compile rqs02.java and run it:

   java rqs02 "DSPLIB QGPL"

Then check the resulting spooled file printed by the batch machine job.

To stop the batch machine, simply order it to 'QUIT' like so:

SNDMSG MSG(QUIT) TOMSGQ(BCHMCH)

About Simon's Solutions

This series of articles memorializes Simon Coulter, an outstanding IBM i expert who contributed so much to the prosperity of the IBM i platform. Loved by many developers from the IBM i community, he was one of the giants in the industry, on whose shoulders others could stand and reach for new heights. I deeply appreciate Gwen Hanna, Simon's partner, for providing the biography of Simon at the end of the first article of this series.

Many thanks to David Gibbs, who has been running the mailing lists at Midrange.com for many years and has accumulated a vast treasure trove of knowledge for IBM i developers around the world.

I also appreciate Jon Paris and Susan Gantner, who ran a touching blog article for Simon: Happy Memories of a Good Friend.

I appreciate Victoria Mack, executive editor of MC Press Online, whose hard work has made it possible for each of the Simon's Solutions articles to be available to you, the readers.

Junlei Li

Junlei Li is a programmer from Tianjin, China, with 10 years of experience in software design and programming. Junlei Li began programming under i5/OS (formerly known as AS/400, iSeries) in late 2005. He is familiar with most programming languages available on i5/OS—from special-purpose languages such as OPM/ILE RPG to CL to general-purpose languages such as C, C++, Java; from strong-typed languages to script languages such as QShell and REXX. One of his favorite programming languages on i5/OS is machine interface (MI) instructions, through which one can discover some of the internal behaviors of i5/OS and some of the highlights of i5/OS in terms of operating system design.

 

Junlei Li's Web site is http://i5toolkit.sourceforge.net/, where his open-source project i5/OS Programmer's Toolkit (https://sourceforge.net/projects/i5toolkit/) is documented.

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

RESOURCE CENTER

  • WHITE PAPERS

  • WEBCAST

  • TRIAL SOFTWARE

  • White Paper: Node.js for Enterprise IBM i Modernization

    SB Profound WP 5539

    If your business is thinking about modernizing your legacy IBM i (also known as AS/400 or iSeries) applications, you will want to read this white paper first!

    Download this paper and learn how Node.js can ensure that you:
    - Modernize on-time and budget - no more lengthy, costly, disruptive app rewrites!
    - Retain your IBM i systems of record
    - Find and hire new development talent
    - Integrate new Node.js applications with your existing RPG, Java, .Net, and PHP apps
    - Extend your IBM i capabilties to include Watson API, Cloud, and Internet of Things


    Read Node.js for Enterprise IBM i Modernization Now!

     

  • Profound Logic Solution Guide

    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 companyare not aligned with the current IT environment.

    Get your copy of this important guide today!

     

  • 2022 IBM i Marketplace Survey Results

    Fortra2022 marks the eighth edition of the IBM i Marketplace Survey Results. Each year, Fortra captures data on how businesses use the IBM i platform and the IT and cybersecurity initiatives it supports.

    Over the years, this survey has become a true industry benchmark, revealing to readers the trends that are shaping and driving the market and providing insight into what the future may bring for this technology.

  • Brunswick bowls a perfect 300 with LANSA!

    FortraBrunswick is the leader in bowling products, services, and industry expertise for the development and renovation of new and existing bowling centers and mixed-use recreation facilities across the entertainment industry. However, the lifeblood of Brunswick’s capital equipment business was running on a 15-year-old software application written in Visual Basic 6 (VB6) with a SQL Server back-end. The application was at the end of its life and needed to be replaced.
    With the help of Visual LANSA, they found an easy-to-use, long-term platform that enabled their team to collaborate, innovate, and integrate with existing systems and databases within a single platform.
    Read the case study to learn how they achieved success and increased the speed of development by 30% with Visual LANSA.

     

  • The Power of Coding in a Low-Code Solution

    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:

    • Discover the benefits of Low-code's quick application creation
    • Understand the differences in model-based and language-based Low-Code platforms
    • Explore the strengths of LANSA's Low-Code Solution to Low-Code’s biggest drawbacks

     

     

  • Why Migrate When You Can Modernize?

    LANSABusiness 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.
    In this white paper, you’ll learn how to think of these issues as opportunities rather than problems. We’ll explore motivations to migrate or modernize, their risks and considerations you should be aware of before embarking on a (migration or modernization) project.
    Lastly, we’ll discuss how modernizing IBM i applications with optimized business workflows, integration with other technologies and new mobile and web user interfaces will enable IT – and the business – to experience time-added value and much more.

     

  • UPDATED: Developer Kit: Making a Business Case for Modernization and Beyond

    Profound Logic Software, Inc.Having trouble getting management approval for modernization projects? The problem may be you're not speaking enough "business" to them.

    This Developer Kit provides you study-backed data and a ready-to-use business case template to help get your very next development project approved!

  • What to Do When Your AS/400 Talent Retires

    FortraIT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators is small.

    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:

    • Why IBM i skills depletion is a top concern
    • How leading organizations are coping
    • Where automation will make the biggest impact

     

  • Node.js on IBM i Webinar Series Pt. 2: Setting Up Your Development Tools

    Profound Logic Software, Inc.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. In Part 2, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Attend this webinar to learn:

    • Different tools to develop Node.js applications on IBM i
    • Debugging Node.js
    • The basics of Git and tools to help those new to it
    • Using NodeRun.com as a pre-built development environment

     

     

  • Expert Tips for IBM i Security: Beyond the Basics

    SB PowerTech WC GenericIn this session, IBM i security expert Robin Tatam provides a quick recap of IBM i security basics and guides you through some advanced cybersecurity techniques that can help you take data protection to the next level. Robin will cover:

    • Reducing the risk posed by special authorities
    • Establishing object-level security
    • Overseeing user actions and data access

    Don't miss this chance to take your knowledge of IBM i security beyond the basics.

     

     

  • 5 IBM i Security Quick Wins

    SB PowerTech WC GenericIn today’s threat landscape, upper management is laser-focused on cybersecurity. You need to make progress in securing your systems—and make it fast.
    There’s no shortage of actions you could take, but what tactics will actually deliver the results you need? And how can you find a security strategy that fits your budget and time constraints?
    Join top IBM i security expert Robin Tatam as he outlines the five fastest and most impactful changes you can make to strengthen IBM i security this year.
    Your system didn’t become unsecure overnight and you won’t be able to turn it around overnight either. But quick wins are possible with IBM i security, and Robin Tatam will show you how to achieve them.

  • Security Bulletin: Malware Infection Discovered on IBM i Server!

    SB PowerTech WC GenericMalicious programs can bring entire businesses to their knees—and IBM i shops are not immune. It’s critical to grasp the true impact malware can have on IBM i and the network that connects to it. Attend this webinar to gain a thorough understanding of the relationships between:

    • Viruses, native objects, and the integrated file system (IFS)
    • Power Systems and Windows-based viruses and malware
    • PC-based anti-virus scanning versus native IBM i scanning

    There are a number of ways you can minimize your exposure to viruses. IBM i security expert Sandi Moore explains the facts, including how to ensure you're fully protected and compliant with regulations such as PCI.

     

     

  • Encryption on IBM i Simplified

    SB PowerTech WC GenericDB2 Field Procedures (FieldProcs) were introduced in IBM i 7.1 and have greatly simplified encryption, often without requiring any application changes. Now you can quickly encrypt sensitive data on the IBM i including PII, PCI, PHI data in your physical files and tables.
    Watch this webinar to learn how you can quickly implement encryption on the IBM i. During the webinar, security expert Robin Tatam will show you how to:

    • Use Field Procedures to automate encryption and decryption
    • Restrict and mask field level access by user or group
    • Meet compliance requirements with effective key management and audit trails

     

  • Lessons Learned from IBM i Cyber Attacks

    SB PowerTech WC GenericDespite the many options IBM has provided to protect your systems and data, many organizations still struggle to apply appropriate security controls.
    In this webinar, you'll get insight into how the criminals accessed these systems, the fallout from these attacks, and how the incidents could have been avoided by following security best practices.

    • Learn which security gaps cyber criminals love most
    • Find out how other IBM i organizations have fallen victim
    • Get the details on policies and processes you can implement to protect your organization, even when staff works from home

    You will learn the steps you can take to avoid the mistakes made in these examples, as well as other inadequate and misconfigured settings that put businesses at risk.

     

     

  • The Power of Coding in a Low-Code Solution

    SB PowerTech WC GenericWhen 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:

    • Discover the benefits of Low-code's quick application creation
    • Understand the differences in model-based and language-based Low-Code platforms
    • Explore the strengths of LANSA's Low-Code Solution to Low-Code’s biggest drawbacks

     

     

  • The Biggest Mistakes in IBM i Security

    SB Profound WC Generic The Biggest Mistakes in IBM i Security
    Here’s the harsh reality: cybersecurity pros have to get their jobs right every single day, while an attacker only has to succeed once to do incredible damage.
    Whether that’s thousands of exposed records, millions of dollars in fines and legal fees, or diminished share value, it’s easy to judge organizations that fall victim. IBM i enjoys an enviable reputation for security, but no system is impervious to mistakes.
    Join this webinar to learn about the biggest errors made when securing a Power Systems server.
    This knowledge is critical for ensuring integrity of your application data and preventing you from becoming the next Equifax. It’s also essential for complying with all formal regulations, including SOX, PCI, GDPR, and HIPAA
    Watch Now.

  • Comply in 5! Well, actually UNDER 5 minutes!!

    SB CYBRA PPL 5382

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

    Request your trial now!

  • Backup and Recovery on IBM i: Your Strategy for the Unexpected

    FortraRobot automates the routine 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:
    - Simplified backup procedures
    - Easy data encryption
    - Save media management
    - Guided restoration
    - Seamless product integration
    Make sure your data survives when catastrophe hits. Try the Robot Backup and Recovery Solution FREE for 30 days.

  • Manage IBM i Messages by Exception with Robot

    SB HelpSystems SC 5413Managing messages on your IBM i can be more than a full-time job if you have to do it manually. 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:
    - Automated message management
    - Tailored notifications and automatic escalation
    - System-wide control of your IBM i partitions
    - Two-way system notifications from your mobile device
    - Seamless product integration
    Try the Robot Message Management Solution FREE for 30 days.

  • Easiest Way to Save Money? Stop Printing IBM i Reports

    FortraRobot 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:

    - Automated report distribution
    - View online without delay
    - Browser interface to make notes
    - Custom retention capabilities
    - Seamless product integration
    Rerun another report? Never again. Try the Robot Report Management Solution FREE for 30 days.

  • Hassle-Free IBM i Operations around the Clock

    SB HelpSystems SC 5413For over 30 years, Robot has been a leader in systems management for IBM i.
    Manage your job schedule with the Robot Job Scheduling Solution. Key features include:
    - Automated batch, interactive, and cross-platform scheduling
    - Event-driven dependency processing
    - Centralized monitoring and reporting
    - Audit log and ready-to-use reports
    - Seamless product integration
    Scale your software, not your staff. Try the Robot Job Scheduling Solution FREE for 30 days.