05
Sun, May
5 New Articles

Practical RPG: Processing an IFS Directory

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

The IFS is an integral part of the today's modern IT infrastructure; this article shows you how to use it as a powerful data input device.

When the IFS was first introduced, it seemed to be almost an afterthought designed primarily to support UNIX and Java development. Sure, you could map drives to it, but the support wasn't exactly robust and you were actually better off using FTP if you wanted to drop something into an IFS folder. Fast-forward to today's IBM i, and the IFS can be easily accessed from just about anywhere, Windows to Linux, making it a simple way for people to communicate with the system using something other than a green-screen.

Monitoring the IFS

In a recent article on environment, I mentioned the concept of an IFS monitor. This is a simple program that sits in a loop and looks for work to do. Work is signaled by the presence of a file in a folder. The interface is simple enough: The user copies a file into an import folder on the IFS. The file is in a format we can decode, such as CSV. A monitor senses the presence of the file and begins processing it. How exactly we process it is a design issue and depends a lot on how sensitive the data is and how you want to log it. One standard practice would be to copy the IFS file into a CLOB record in a traditional DB2 file with a unique transaction number. From that point forward, all processing references that transaction ID. The stream file is then moved from the import folder into a received folder so that it isn't re-processed. If for whatever reason the import into the CLOB file fails, the stream file is moved to an error folder.

Because the file is moved out of the import folder immediately, the monitor is quite simple: Read through the directory and, if a file is found, process it and move it, either to the received folder or the error folder. Delay and loop. There are several nuances: identifying the folders, skipping subfolders, handling files that aren't yet complete (this often happens with large files), and so on. But the general architecture is simple enough, and it makes use of some of the many APIs that IBM provides. In this case, we use the IFS APIs.

Using the IFS APIs

Most of us who do any sort of work in the IFS learned about it by reading Scott Klement's original work on the IFS, and I'm no exception. Written in 2002, Scott's online e-book is still relevant today. If this article gets you to start thinking about using the IFS in your RPG programs, then by all means read his tutorial. It's the fastest path to learning the IFS. Here's my implementation taking advantage of free-format RPG functionality.

     dcl-s wImportDir varchar(64) inz('/import/inbound/');

     dcl-s wReceivedDir varchar(64) inz('/import/received/');

     dcl-s wErrorDir varchar(64) inz('/import/error/');

     dcl-s wFileName varchar(128);

These variables are used for the names of the files and folders that we will be processing. They are entirely arbitrary, both in length and content. In a more robust application, you would probably get the directory names from some sort of configuration file. The file name variable is not initialized; it gets populated as we process the folder. But the length is indeed arbitrary. So far 128 has been enough for my users, but be careful. There's always the person who insists on using a 200-character name. You can either gently dissuade them or else increase the size of the field.

Rafael Victória-Pereira recently wrote an article on variable naming that you may want to read. I use a little different approach; I prefer a modified Hungarian notation, with camel case for the variables and a prefix that gives a small amount of information (typically "w" is a work field, "ds" is a data structure, "p" is a pointer, and "h" is a handle, which I'll talk about in a moment). Variable naming is a personal preference, although in larger shops it definitely makes sense to try to standardize.

     dcl-s hDir pointer;

     dcl-ds dsDirEnt likeds(IFS_DirEnt) based(pDirEnt);

     dcl-ds dsStat likeds(IFS_Status);

These are the variables we actually use to process the directory. The first is hDir, which is a handle. We'll talk about handles in a moment. The other two variables are data structures. The first represents the attributes of a directory, while the other contains the status flags for an IFS file. Both of these data structures are defined by IBM, but you'll have to make your own structures for RPG, especially if you're using free-format RPG. In fact, as you continue down the path of using more and more APIs, you will be creating a lot of structures and prototypes, and it will definitely benefit you to start learning some techniques for managing all of them. Luckily for you, I will have an article devoted to just that topic shortly! Anyway, all you need to know right now is that the directory entry data structure contains the name of the file, while the status entry contains an attribute variable that tells you what kind of file it is.

     // Open directory, exit on error

      hDir = IFS_opendir(wImportDir);

     if hDir = *null;

        log( 'opendir': errno);

        return;

     endif;

As I noted above, the field hDir is a handle. A handle is an arbitrary value received from a function that represents some object. Sometimes it's a pointer, sometimes it's a large integer, sometimes it's a character string; the type doesn't really matter because the contents of that variable are meaningless to you as the caller. All you do is pass that value back to other functions in order to for them to do work. The reason we do this is to hide the inner working of the functions from the caller. It prevents clever programmers from trying to peek inside the internal structures of the called functions (those of you who have read other things I've written know that I use the term "clever" somewhat wryly). In this case, you open a directory (directory is just another name for a folder) and you get a handle. You then use that handle to process and eventually close that directory. IFS_OpenDir is my prototype for the IBM i directory open API. One thing you may run into is that the IBM i APIs often don't have consistent naming conventions and the ones that do have consistent IBM naming conventions, which are typically pretty ugly. "Qp0l" is not what I consider a programmer-friendly prefix but that's one of the many prefixes IBM uses. So instead I often create prototypes with a common prefix and use that same prefix on my data structures. In this case, every prototype and structure having to do with the IFS starts with "IFS_".

     // Spin through folder

     dou (pDirEnt = *null);

This is the primary loop. The loop is specifically until no file is available.

        // Get next directory entry, exit on null

        pDirEnt = IFS_readdir(hDir);

        if pDirEnt = *null;

          leave;

        endif;

Here we get the next entry to process. You may have noticed that dsDirEnt is a based data structure; that is, it doesn't really have any memory assigned to it. Instead, it has a pointer, and we set that pointer to some spot in memory. In this case, we set it to the address returned from the function IFS_readdir. This is a fairly common technique in C-like list APIs: they return the address of the next entry in the list or a null pointer when you've processed them all.

        // Skip subdirectories

        wFileName = %trim(%str(%addr(dsDirEnt.name)));

        IFS_stat(wImportDir + wFileName: %addr(dsStat));

        if %bitand( dsStat.mode: C_MODE_DIRMASK) = C_MODE_DIRVAL;

          iter;

        endif;

This is another example of C-like coding. C is very frugal on how it stores information; a single integer field can contain a number of different attributes. Some are a single bit; others require multiple bits. In this case, the file type requires multiple bits. The constant C_DIR_MASK is used to isolate those bits from the field dsStat.mode. Once the bits are isolated, they are compared to a specific setting, C_MODE_DIRVAL, to identify whether or not the file is a directory. If it is, we skip it using the iter opcode.

        // Route the file to the appropriate application

        Route( wErrCd: wImportDir: wFileName);

        if wErrCd = *blanks;

          MoveIFS( wImportDir: wFileName: wReceivedDir);

        else;

          MoveIFS( wImportDir: wFileName: wErrorDir);

        endif;

This part of the code is where you would start to implement your application logic. In this example, we're calling a procedure called Route, which will take the directory and file name and try to route the file to an application. The routing logic is not defined here, and it shouldn't be—it depends on your application design. The only thing this program needs to know is whether the file was successfully routed. If so, the error code comes back as blanks and we move the file to the received directory. Otherwise, we move it to the error directory. Either way, the file is no longer in the inbound folder and won't get re-processed.

     enddo;

      IFS_closedir(hDir);

     return;

Close the directory and get out. Note that we pass back the handle; that identifies the directory to close. This isn't a complete example, especially since I didn't include the Route function; you'll need to come up with that on your own. But you can use the included files to get you very close to a working example: IFS_RPGCode is the complete code above (with a control specification and *inlr = *on included), while IFS_CopyFile contains the prototypes and data structure definitions I used. Add stubs for the Route function and MoveIFS, and you can test it.

To Summarize

Using a folder or directory on the IFS is a powerful and easy way for users to provide input to your applications. A simple monitor can run in the background and process each file; all the user has to do is copy it into a pre-determined folder. Users can do this from their desktop using a mapped drive, while applications such as EDI can drop a file in using FTP. It's an easy way to provide an automated integration portal to your applications.

Joe Pluta

Joe Pluta is the founder and chief architect of Pluta Brothers Design, Inc. He has been extending the IBM midrange since the days of the IBM System/3. Joe uses WebSphere extensively, especially as the base for PSC/400, the only product that can move your legacy systems to the Web using simple green-screen commands. He has written several books, including Developing Web 2.0 Applications with EGL for IBM i, E-Deployment: The Fastest Path to the Web, Eclipse: Step by Step, and WDSC: Step by Step. Joe performs onsite mentoring and speaks at user groups around the country. You can reach him at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Joe Pluta available now on the MC Press Bookstore.

Developing Web 2.0 Applications with EGL for IBM i Developing Web 2.0 Applications with EGL for IBM i
Joe Pluta introduces you to EGL Rich UI and IBM’s Rational Developer for the IBM i platform.
List Price $39.95

Now On Sale

WDSC: Step by Step WDSC: Step by Step
Discover incredibly powerful WDSC with this easy-to-understand yet thorough introduction.
List Price $74.95

Now On Sale

Eclipse: Step by Step Eclipse: Step by Step
Quickly get up to speed and productivity using Eclipse.
List Price $59.00

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

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: