MENU

Code for IBM i: Creating and Executing a Translation Program Using the DeepL API

Code for IBM i | Part 7: Creating and Executing a Translation Program Using the DeepL API
By Makoto Ogawa, T&Trust K.K.

 

Finally, let’s create and run a program with VSCode that uses the DeepL API discussed in another feature in this issue of the magazine, “Introduction to APIs for IBM i Users.

Preparation 

Item: Contents
Program name: DEEPLAPI
Name of Created Library: IMAG2023
Source Code File Name: deeplapi.sqlrpgle
Storage: Local (development PC)
User Profile: IMAG23WINT
User Class: *SECOFR
Special Permissions: *USRCLS
Execution environment: PASE

This time, the program is not run on the 5250 emulator but in the PASE environment to display the results. To connect to the PASE environment via ssh and display the results on the same screen, it is necessary to use the printf function in the C/C++ runtime library (Stsnfsrf output; output stdout).

Let’s first change the shell used to connect via ssh to bash. Bash shell allows you to use the cursor keys to move the cursor, delete keys, etc., just like at the Windows DOS prompt.

To change the default shell to bash, you need to know where bash is located. There is a which command to check the full path of a file in a PASE environment, so let’s use this to check the full path of bash.

Connect to the PASE terminal (click on Terminals on the status bar and select PASE) and execute the which command (Figure 67).

Figure 67   Displaying the full path of bash
Figure 67   Displaying the full path of bash

Then, using IBM i notebooks, change the default shell for the user to connect to, specifying the full path identified in which. The procedure used is the QSYS2.SET_PASE _SHELL_INFO procedure, which is changed using the SQL CALL statement (Figure 68).

Figure 68   Changing the default SHELL to bash
Figure 68   Changing the default SHELL to bash

To check if the change has been made, search with SQL for the USER_INFO view (https://www.ibm.com/docs/ja/i/7.3?topic=services-user-info-view), which contains information about the user profile. 

If the column PASE_SHELL_PATH is set to the full path of the specified bash, the set is complete (Figure 69).

Figure 69   Checking if the user's default SHELL has been changed
Figure 69   Checking if the user’s default SHELL has been changed

After confirming that bash is set as the shell for the PASE environment, click the trash can icon in the upper right corner of the terminal screen to close the screen, disconnect from the IBM i and reconnect (Figure 70).

Figure 70   Closing the PASE Terminal
Figure 70   Closing the PASE Terminal

Then click Terminals on the taskbar and select PASE to display the terminal. If it appears as shown in Figure 71, it is OK (4.4 is a version, so that it may vary depending on your environment).

Figure 71   Confirming that the default shell is used to start
Figure 71   Confirming that the default shell is used to start

Coding 

Now let’s code the program. First, the initial settings (creation of a folder to save the code, Deploy destination settings, and creation of .vscode/actions.json in the folder) should be completed regarding the maintenance of the local source code.

Open the folder created by VSCode and create the file deeplapi.sqlrpgle. When entering sample code, a code assist function is available for some, but not all. If a candidate appears that you want to enter, try selecting it.

For example, if you want to enter a data structure and enter “dcl,” the candidates will appear as shown in Figure 72.

Figure 72   Display of candidates starting with dcl
Figure 72   Display of candidates starting with dcl

If you select dcl-ds, the code will be inserted as shown in Figure 73.

Figure 73   Selecting dcl-ds
Figure 73   Selecting dcl-ds

The cursor is set at “name,” and you can enter the name of the data structure you want to enter.

If you do not find the one you want to input, press the space key to clear the candidates and continue typing. Note that if you press the Enter key while the candidates are displayed, you have selected the topmost candidate.

The following is the full code for a program that calls the DeepL API, which was introduced in another feature in i Magazine 2023 Winter, “An Introduction to APIs Dedicated to IBM i Users.

**free
//
// DeepL翻訳APIの利用
// https://api-free.deepl.com/v2/translate
//
ctl-opt copyright(‘(C) 2018-2023 tat.co.jp All Rights Reserved.’);
ctl-opt text(‘DeepL翻訳APIの利用’);

ctl-opt dftactgrp(*no);
ctl-opt main(main);

dcl-pr printf Int(10) extproc(‘printf’);
input Pointer value options(*string);
end-pr;

dcl-proc main;

   Dcl-ds Request Qualified;
       URL Char(128);
       Head Char(1024);
       Body Char(1024);
   end-ds;

   // HTTPPOSTCLOBVERBOSE用パラメータ変数
   dcl-s replyStmf char(10000);
   dcl-s replyHdr char(10000);

   dcl-s detectedSourceLanguage char(2);
   dcl-s translaedText char(10000);
   dcl-s Auth_key varchar(40);
   dcl-s SendMessage char(1000);
   dcl-c LF const(x’25’);
   dcl-ds httpHeader qualified;
       responseCode char(3);
       responseMessage varchar(100);
       dcl-ds header dim(40);
          name varchar(100);
          value varchar(100);
       end-ds;
   end-ds;

   SendMessage = ‘トンネルを抜けると、そこは雪国だった。’;

   Auth_key = ‘b16abxxc-ffff-8bcc-111c-00ad6f222d57:fx’;

   Request.URL = ‘https://api-free.deepl.com/v2/translate’;

   Request.Body =
       ’auth_key=’ + %trim(Auth_key)
      + ‘&text=”‘ + %trim(SendMessage) +'”‘
      + ‘&target_lang=EN’;

   Request.Head =
      '<httpHeader>’
      + ‘<header name=”Content-Type” value=”application/x-www-form-urlencoded” />’
      + ‘<header name=”Content-Length” value=”‘ + %char(%len(%trim(Request.body))) + ‘” />’
      + ‘</httpHeader>’;

   exec sql select responsemsg,
       RESPONSEHTTPHEADER into :replyStmf, :replyHdr
from table( SYSTOOLS.HTTPPOSTCLOBVERBOSE(
       trim(:Request.URL),
       trim(:Request.Head),
       trim(:Request.Body)
   ) ) as x;

   // DeepLから戻されたjsonファイルの内容を変数にセット
   exec sql select * into :detectedSourceLanguage,:translaedText
       from JSON_TABLE(
           trim(:replystmf),
           ’$’
           columns(
              nested ‘$.translations[*]’ columns(
              ”detected_source_language” varchar(2),
              ”text” varchar(10000)
           )
        )
   ) x;

   //応答ヘッダーXMLを分解してデータ構造httpHeaderにセット
   xml-into httpHeader %xml(%trim(replyHdr):’ccsid=ucs2 +
       allowmissing=yes +
       doc=string +
       case=any +
       path=httpHeader’);

   printf(%trim(translaedText) + LF);

end-proc;

In the sample coding, the Japanese language set in the SendMessage variable is passed to the DeepL API, and the result of the English translation is received and Output to stdout by printf. In addition, the Japanese for the conversion source is set to “トンネルを抜けると雪国だった(in Japanese)” is set.

Press Ctrl + s to save the file when all the code has been entered.

Compile 

When you have finished entering the code, let’s compile it. First, the library where the object is created should be set IMAG2023 in the USER LIBRARY LIST, since the current library is an abbreviation (Figure 74).

Figure 74  Change the current library
Figure 74   Change the current library

Ctrl + E will display candidate commands at the top and select the action Create SQLRPGLE Program. Next, the IFS directory where the source code is to be Deployed and the selection of the file to be pushed are displayed at the top. Since we will only push the newly created deeplapi.sqlrpgle, we select Changes 1 change detected since last upload (Figure 75).

Figure 75   Selecting the deployment destination and the source to push
Figure 75   Selecting the deployment destination and the source to push

Then, the message Deploy completed displayed in the lower right corner of the screen, followed by the execution result of the action Create SQLRPGLE Program (CRTSQLRPGI command) (Figure 76).

Figure 76   Execution result of Compile
Figure 76   Execution result of Compile

The details of the execution result of the action can be checked by clicking on the expansion symbol for the notification that appears when the cursor is placed over the message (Figure 77, Figure 78).

Figure 77  Before message expansion
Figure 77   Before message expansion
Figure 78   After message expansion
Figure 78    After message expansion

If compilation fails, click Output on the status bar to display the compilation list, check the error location, modify the source code, and execute the compilation action, repeating until there are no more errors.

Execution

Once the program has been created, let’s execute it. First, click Terminals on the status bar and select PASE (Figure 79).

Figure 79  Displaying the PASE Terminal
Figure 79    Displaying the PASE Terminal

To execute the program from the PASE environment, specify the system command followed by the IBM i CALL command (Figure 80).

     system “call imag2023/deeplapi” Figure 80

Figure 80   Running the created program from the PASE terminal
Figure 80   Running the created program from the PASE terminal

The DeepL API translated “トンネルを抜けると雪国だった(in Japanese)” as follows.

     When I went through the tunnel, I found myself in a snowy country.

Summary

We hope you understand that the Code for IBM i extension to Visual Studio Code can be used as an alternative to the SEU/PDM environment and that source code’s version control, including RPG III, can be performed in Git. We also hope you have been able to visualize that the CL and RPGLE extensions can be used as a code completion function for coding CL and RPG programs at a very high level.

Furthermore, IBM i Notebooks allows the following operations within a single file in VSCode (without the need to display the execution of SQL scripts on the 5250 screen or ACS).

・Execution of CL commands
・Execution of SQL statements
・Execution of Shell Script
・Write documents in Markdown in a notebook

Above all, it is worth mentioning that this notebook is also managed by Git, which enables information and execution commands to be shared in team development.

The first commit of Code for IBM i to GitHub was on February 21, 2021, and as of January 9, 2023, the total number of commits is 1626 (2.36 commits/day by simple calculation). There are approximately 35 committers. The latest version is 1.6.8, which has been tagged 177 times; in December 2022 (one month), there were 69 commits; there are 44 open issues on GitHub, and the tool is evolving daily.

In the verification process for writing this paper, there were some cases where Code for IBM i did not work as expected. For example, when compiling local code, the compile list is displayed. Still, the list of error items only is not displayed (Note: The problem of displaying the list of error items only has been resolved since this report was written). However, since the tool is under such active development, we expect the problems to improve rapidly.

Development tools for other platforms are freely selectable, whether proprietary or open source. IBM i, on the other hand, has had only proprietary tools as a choice, which has been a problem for many years. I thank Mr.Liam Barry Allan for bringing Code for IBM i to the world.

While RDi is still the best choice in terms of functionality, VSCode + Code for IBM i is also fully available. I hope this article will help you take the next step in your development environment.

Author
Makoto Ogawa

President and CTO,CIO
T&Trust K.K.
https://www.tat.co.jp/

Since 1989, he has been responsible for system development and programming training on AS/400. He learned how IFS works on OS/400 V3R1 through Linux, and since then, he has been deeply interested in open source in IBM i. His theory is that developer needs knowledge of Linux to understand IBM i. He has also written many articles for i Magazine.

[i Magazine・IS magazine]    https://www.imagazine.co.jp/

新着