RTE Reference Guide 5.1.1 EN

Download as pdf or txt
Download as pdf or txt
You are on page 1of 242

w w w. g e n e r i x g r o u p .

c o m

User’s Guide

TradeXpress ®

RTE

Product version 5.1


Document version 5.1.1

Solutions de Generix Group


RTE / COPYRIGHT

Disclaimer
INFLUE reserves the right to make changes to this document without prior notice. Except where otherwise stated,
names of companies, organizations, products, persons or events mentioned in this document are given as example
only. Any resemblance to actual names or events is coincidental. Users must comply with the Copyright law applicable
in the country of use. No part of this document shall be reproduced, stored or entered into a retrieval system, or dis-
seminated for any reason or by any means whatsoever, without the express written consent of INFLUE.

Copyright
INFLUE may hold patents, applications for patents, or may own rights to trademark, copyright or other intellectual prop-
erty rights covering all or part of the components covered by this document. This guide does not constitute in any
case a license for these above-mentioned patents, trademarks copyrights or intellectual property rights, unless other-
wise stated in a written license agreement issued by INFLUE.

© 2009 GENERIX GROUP. All rights reserved. INFLUE is a registered trademark of GENERIX Group.

Trademarks
The names of companies and products mentioned in this document are trademarks or registered trademarks of their
respective owners.

TradeXpress ®
Generix Group - All rights reserved
CONTENTS

USER’S GUIDE 4 Program statements 41


Overview 42
1 Introduction 7
Assignment Statements 43
Prerequisites 8 Text Assignments 43
Overview of RTE 9 Numeric Assignments 43
Operating Principle 11 Boolean Assignments 44
The Window Model 11 File Assignments 44
RTE Compilation 12 Database Assignments 44
Array Assignments 44
2 Tutorial 14 Increment and Decrement Statements 45
Control Statements 46
Overview 15
Conditional Statement 46
The First Program 16 Boolean Expressions 46
A Line Counter 17 Loop Statements 47
Building an EDI Message 19 General Loop Statement 47
Specifying the Message 20 Array Scanning 47
Data Lines 20 List Scanning 47
End Statement List 21 Directory Scanning 48
User Functions 21 Database Scanning 49
RTE Program Source Code 22 Switch Statement 49
The Inhouse Data File 25 Switch Expression 49
The Resulting Messages 25 Switch Statement with Coprocesses 50
The Resulting Log File 26 Break Statement 50
Receiving an EDI Message 27 Continue Statement 50
Specifying the Message 27 Next Statement 51
Buffered Output 27 Statement 51
RTE Program Source Code 27 RTE exceptions 51
The Original Messages 29 Principle 52
The Resulting Data File 29 Syntaxe 53
Use 54
RTE internal exceptions 54
3 Program structure 30 Limitations 55
Overview 31 Inline C Block Statement 55
Inline C Statement 55
Statement Lists 32
Line Matching 34 5 EDI translation 57
Text at a Given Position 34
Text Anywhere 34 Overview 58
Line Number 34 Operating Principle 59
Logical Operators 34 Specifying the Message 60
Regular Expression Matching 35 Naming the Elements 61
Multi Matching 36 Building Messages 64
Definitions 37 Segment Building Statement 64
Message Definition 37 Element Assignments 65
Database Definition 37 Packing Data in Repeating Elements 66
Functions 39 Decimal Separator Conversion 67
Comments 40 Specifying the Segment Location 67
Source Code Documentation 40 Specifying the Segment Repetition 69
Runtime Information 40 Checking the Syntax 70

TradeXpress ®
Generix Group - All rights reserved 3
CONTENTS

Segment Counter 70 Definition 102


Independent Segments 72 Database Fields 103
Receiving EDI Messages 73 Database Files 104
Decimal Separators 74 Finding an Entry 105
Receiving Direction Error Handling 75 Creating a New Entry 107
Ignoring Erroneous Messages 75 Removing an Entry 108
Using a Separate Error Routine 75
Processing Erroneous Messages in Statement Lists 75 8 Running RTE Programs 109
Preparing for the EDIFACT CONTRL Message 76
Checking the Validity of a Segment 77 Overview 110
Checking the Validity of a Group 77 Options 110
Examples 78 Parameters 112
Error Codes 79 Arguments 114
Startup File 115
6 Input and Output 81
Standard Streams 82 9 Built-in Functions Reference 117
Input 83 Overview 118
Window Model 83 Function Categories 119
Picking 83
Process Control 119
Returning a Line 83
Text Handling 119
Line Numbers 84
End of File 84 File Handling 120
Read 84 Output 120
Output 85 Database Access 121
Printing 85 Input 121
Newline Character 85 Multi Purpose 122
Redirection 86 Time 122
Using Coprocesses 87
Functions Reference 123
Redirecting the Standard Streams 88 background 123
Buffered Output 89 build 123
close 125
Putting Text in the Buffer 89
compare 125
Flushing the Output Buffer 90
copy 126
Examples 90
debug 127
Print List 92
edierrordump 128
Print Items 93 edierrorlist 129
Print Format 94 exec 129
Text Print Format 94 exit 131
Numeric Print Format 94 find 131
Time Printing 95 flush 132
Logging 97 index 133
File Variables 98 length 134
File Attributes 98 link 135
Assignment 99 load 136
Usage 99 log 139
new 139
7 Database Interface 100 number 140
peel 141
Background Information 101 pick 141

TradeXpress ®
Generix Group - All rights reserved 4
CONTENTS

print 142 Character Classes 182


put 143 Compiling Character Sets 183
read 144 Sample Character Set 183
redirect 145
remove 146 Annex E Code Conversion in RTE 185
rename 147
replace 148 Annex F Advanced Utilities 188
spawn 149
Introduction 189
split 150
strip 151 Pass-through Mode in RTE 190
substr 152 Receiving an EDI Message in Pass-through Mode 190
system 153 Building an EDI Message in Pass-through Mode 191
time 154 Segment Look-ahead in the Receiving Translator 195
tolower 158 RTE Function 195
toupper 158 peeksegment, bfPeeksegment 195
valid 159 C Programming in RTE 198
In-line C Block Statement 198
Annex A Identifier Types 161 In-line C Statements 199
RTE Coprocess Communications 201
Overview 162
Coprocess Communication Basics 201
Basic Types 163 RTE Functions for Coprocess Communications 202
Special Types 166 RTE Extension for Coprocess Communications 205
Database Entry 166 Example 1: FTP Session Driven by the RTE Translator 206
TIME 166 Example 2: SQL Interpreter Session Driven by the RTE
Translator 207
Annex B Regular Expressions 167 RTE FTP Client Routine Library 209
Compiling RTE Source Code with the FTP Client Routine Li-
Regular Expression Usage 168 brary 209
Regular Expression Definition 169 RTE Functions for FTP Communication 210
Examples 171 General functions for FTP 210
Specific FTPS RTE functions 215
Using REs with the Line Statement 171 Specific SFTP RTE functions 217
Using REs with the Split Function 171 SFTP test program 220

Annex C Message Storage Format 173 Annex G RTE SQL Access Library 223
Message World 174 Introduction 224
Message Description Files 175 Requirements 224
Identifiers 175 Compilation 224
Message Structure 175 Execution Environment 225
Segment Line 176 RTE SQL Access Library Reference List 226
Group Line 176 bfSqlOracle ("DBID", "User", "Passwd", "DBLink") 226
Message Usage 176
bfSqlSet ("DBID", "SqllD", "SQLString") 226
Segment Description 177
Simple Data Element 177 tfSqlGetField("DBID","SqlID","Field") 226
Composite Data Element 177 nfSqlGetField("DBID", "SqlID","Field") 227
Component Data Element 178 bfSqlExec("DBID", "SqlID") 227
bfSqlOpen("DBID", SqlID") 227
Annex D Character Sets 180 bfSqlFetch("DBID", "SqlID") 228
bfSqlFetchArray("DBID", "SqlID", taVar) 228
Character Set Definition 181
bfSqlFree("DBID", SqlID") 228
The Description Language 182 bfSqlClose("DBID") 229

TradeXpress ®
Generix Group - All rights reserved 5
CONTENTS

ODBC interface 230


Installation 230
Use 230
Compilation 230
JDBC Interface 231
Installation 231
Configuration 231
Use 232
Compilation 233
Example of an RTE Program with SQL Access 234

TradeXpress ®
Generix Group - All rights reserved 6
1/ Introduction

Prerequisites
Overview of RTE
Operating Principle
RTE Compilation

TradeXpress ®
Generix Group - All rights reserved 7
Introduction / Prerequisites

Prerequisites

This manual assumes that you are somewhat familiar with the EDI syntax you are using. Terms
such as “message,” “segment,” and “data element” are used without explanation. A basic under-
standing of computer operation is also assumed, including the use of terms such as “executable
program,” “input file,” “output file,” and “program source code.”

Parts of this manual assume that you have at least a basic knowledge of computer programming
with a high-level language such as C, PASCAL, or FORTRAN. You should be familiar with terms such
as “variables,” “functions”, “expressions,” and “statements” in order to understand the entire
structure of the language.

These assumptions aside, RTE is easy to program and programming is rarely needed in EDI trans-
lations. The translators usually contain only simple assignments or references to data elements,
and often these are automatically produced by the TradeXpress tools.

When programming is needed, RTE is much easier to handle than conventional high-level lan-
guages. Most of the tedious work relating to memory management, file handling, process
startup, and other advanced features are taken care of transparently.

TradeXpress ®
Generix Group - All rights reserved 8
Introduction / Overview of RTE

Overview of RTE

Although RTE was originally designed for EDI translation, it is suitable for a wide range of other
applications. In many ways, it resembles a Unix text processing program called awk. Like awk, it
is data driven, it supports associative memory, variables are used with no prior definition, and so
on. The most obvious differences are the EDI translation module, links to EDIBASE databases, and
a large suite of built-in functions in RTE. Also, RTE programs are compiled into executable mod-
ules, whereas awk is an interpreter.

RTE is a high-level programming language with its own memory management and associative
memory. These features allow you to concentrate on building your application rather than worry-
ing about reserving room for all variables, checking array boundaries, freeing unused memory
segments, and similar tasks common to conventional high- level languages.

The EDI translator module has no EDI syntax (like EDIFACT or ANSIX12) rules built into it, but the
syntax used is derived from the message description files. RTE can then be used to create a
translator for a specific grammar, but since the rules are not a part of RTE, future versions and
completely new grammars can also be supported with the same tool.

Outgoing EDI messages are built one segment at a time. The order in which the segments are
built is completely free: the EDI translator module inserts the segments in their respective posi-
tions in the message. This architecture obviates the need for any of the tailored preprocessors
commonly used today to “translate the inhouse data into a format ready to be translated to EDI
format.” Data segments are referenced by their names and positions in the message tree. Data
elements in segments are referenced by their names.

Associative memory makes it possible to use free form text as an array index side by side with
numeric indexes. The length of the array index or the value is almost unlimited (“almost” is a nec-
essary qualifier because each computer has only a finite amount of memory).

Input from files can be taken one line at a time and run through the matching line statement list
(data-driven operation), or the program can be designed in a linear way so that the input is
explicitly read in. Text can be retrieved from a specified position in a file and in output it can be
inserted in a specified position.

RTE contains text processing functions to perform various tasks for text data. These include tak-
ing a substring, stripping off extraneous characters, combining several strings to one, and con-
verting strings to upper or lower case.

RTE supports numeric data types that can be used in arithmetic calculations. Numeric values can
be integers or floating point numbers.

TradeXpress ®
Generix Group - All rights reserved 9
Introduction / Overview of RTE

RTE supports user written functions. Functions can be written to handle actions that are per-
formed at several instances to avoid redundant coding. These functions can receive arguments
and return values. Recursive functions are not supported.

The file system interface provides mechanisms to scan directories, print and remove files, and
access file attributes. Multiple files can be read line by line, and likewise the output of the pro-
gram can be written to several files.

The code conversion facility aids in mapping between different coding systems used by commu-
nicating partners. A single conversion table can be used for multiple partners and in both direc-
tions.

RTE contains built-in functions to start new processes. These processes can be waited for, they
can be put to background mode, or they can be used to replace the running program. Copro-
cesses can be used just like regular text files in input and output operations.

With the C-language interface, any software library with a C-interface can be linked to an RTE pro-
gram. This makes it possible, for example, to use an SQL library to fetch data elements directly
from a relational database with no intermediate file.

The C-preprocessor can be used to define symbols and macros, include code from other files,
and perform conditional compilation.

TradeXpress ®
Generix Group - All rights reserved 10
Introduction / Operating Principle

Operating Principle

By default, an RTE program is data driven and reads input one line at a time.

The Window Model


There is an imaginary window that slides over the data. The window is anchored at a position by
matching a given condition in the file. The matched line becomes the first line of the window and
the window size is determined by the furthest reference relative to the matched line. These refer-
ences are made with the built-in function pick. The size of a window can range from one line to a
maximum of 1024 lines.

In the following figure, the input file is read in line by line. The line “SAMPLE” matches the first line
matching condition, which describes the operation principle of the translator when dealing with
line matching conditions, so the entire line statement list is executed. The line statement list
itself reads two additional lines from the input by doing a pick from lines two and three relative to
the matching line. The next line read from the file is “other text,” which does not match any line
statement list. The line “SINGLE” again matches a condition and the second line statement list is
executed.

begin
beginprint (“starting...”, NL)
endbegin

line (1:”SAMPLE”)
other text tONE := pick (1,1,3)
SAMPLE tTWO := pick (2,1,EOL)
THREE LINE
WINDOW tTHREE := pick (3,1,EOL)
other text endline
SINGLE
line (1:”SINGLE”)
tONLY := pick (1,1,EOL)
INPUT endline

TradeXpress ®
Generix Group - All rights reserved 11
Introduction / RTE Compilation

RTE Compilation

RTE programs are compiled into executable programs. The source code contains the reference to
the message description that may be used, and this is loaded by mktr at compile time. Depend-
ing on the functionality used (that is, which built-in functions are called), runtime libraries are
loaded automatically by mktr. The figure below gives a quick overview of the compilation and run-
time environments. There are no additional references to the actual message description file at
runtime, since it is compiled into the executable module.

Compilation RTE source code


environment

mktr

Runtime libraries Message description

executable
translator

INPUT OUTPUT

Runtime LOGGING
environment

The RTE compiler is named mktr (for make translator). The compiler is started from the command
line, as follows:

mktr [options] filename [filename, ...]

For example:

$ mktr sample.RTE

Several options can be used to affect the behavior of the compiler.

-a Causes all matching statement lists to be executed instead of the default action,
where only the first match is executed.

TradeXpress ®
Generix Group - All rights reserved 12
Introduction / RTE Compilation

-Afile File to be used instead of $EDIHOME/lib/ccargs.

-Copt The option is given to the C-compiler.

-Dopt The option is defined when preprocessing RTE.

-e Does not generate code, just checks the grammar. This option is used by the TradeX-
press editor to perform RTE grammar checks.

-g Produces symbol table information for symbolic debugging. This option is not availa-
ble in Windows NT.

-h Gives a summary of available options.

-Idir Adds pathname to the list of directories to be searched when an #include file is not
found in the directory containing the current source file, $HOME/include, $EDIHOME/
include, or whenever angle brackets (< >) enclose the file name. If the file cannot be
found in directories in this list, directories in a standard list are searched. -I can be
used several times, but only applies to source files appearing after it on the command
line.

-m The resulting translator keeps the message after the print and log commands and it
must be explicitly removed. This enables the writing of the same message to several
files.

-o file The resulting file is named after this argument. The default name for the resulting
translator is the source file name without the .RTE extension. For example:

$ mktr sample.RTE -o test

would produce an executable file named test.

-v Does not generate code, just produces a list of used variables. This list can be used, for
example, to detect errors caused by mistyping a variable name and therefore not
getting the expected results. The listing shows the number of assignments and refer-
ences for each variable.

-V Prints out various command lines before they are executed.

-w The resulting translator keeps the write buffer after the flush command and it must be
explicitly removed. This allows for writing the buffer at several stages of filling, for
debugging purposes, for example.

TradeXpress ®
Generix Group - All rights reserved 13
2/ Tutorial

Overview
The First Program
A Line Counter
Building an EDI Message
Receiving an EDI Message

TradeXpress ®
Generix Group - All rights reserved 14
Tutorial / Overview

Overview

This chapter provides a tutorial introduction to the RTE functionality. The intention is to get you
started writing your own programs, since that is the only way you can really learn a program-
ming language. For this reason, most of the advanced features are not covered here.

The first part of this chapter covers the basic principles and simple text processing tasks. The
second part explains how an EDI message is built, and the third part presents an example in
which an EDI message is received.

TradeXpress ®
Generix Group - All rights reserved 15
Tutorial / The First Program

The First Program

Here is the first program you can try:

!- - - - - - - - - - - - - - - -
! A humble beginning...
!- - - - - - - - - - - - - - - -
begin
print ("The first program", NL)
endbegin

The exclamation mark starts a comment that continues to the end of the line. The program above
contains only one statement list (begin), which in turn contains only one statement. The begin
statement list is terminated with the keyword endbegin, which in this case is the end point of the
entire program.

Save the program to a file. You can name the file anything as long as you use an .rte extension so
that the translator maker (mktr) will recognize it. Let’s assume the program was saved under the
name “first.rte”:

$ mktr first.rte
$

The mktr command generates an executable program named “first” that can now be run from the
command line.

$ first
The first program
$

You have now completed your first program.

TradeXpress ®
Generix Group - All rights reserved 16
Tutorial / A Line Counter

A Line Counter

In this section, we write a simple line counter that counts the number of empty and non-empty
lines in a file. We use three statement lists to accomplish this task: two line statement lists that
are triggered by the lines in the file, and an end statement list to print out the information at the
end.

!=====================================
! A simple line counter
!=====================================
!-------------------------------------
! Lines that contain no characters
! trigger this statement list.
!-------------------------------------
line ("")
nEmpty++
endline

!-------------------------------------
! Lines that contain any characters
! trigger this statement list.
!-------------------------------------
line (not "")
nNonEmpty++
endline

!-------------------------------------
! Having read all the lines in the
! input this statement list is run.
!-------------------------------------
end
print ("There were ", nEmpty, " empty lines", NL)
print ("and ", nNonEmpty, " lines with text.", NL)
endend

Variables do not need to be defined before they are used. Numeric variables, such as nEmpty and
nNonEmpty above, always start with a lower case “n” and initially contain the value zero.

The print function takes as its arguments a variable number of text and numeric items. There is
no automatic line feed insertion, so we use the built-in newline character, NL. Note that inserting
an actual line feed in the middle of the print function will cause an error. If you try something like:

print ("and ", nNonEmpty, " lines


with text.")

the RTE compiler will produce an error message about a new line in a string.

After compiling the above program under the name “counter,” you can test it. If you do not redi-
rect the input to be from a file, the program waits for you to type the text from the keyboard. To

TradeXpress ®
Generix Group - All rights reserved 17
Tutorial / A Line Counter

terminate the input, press ctrl-d at the beginning of a line in the Unix environment, or ctrl-z in the
NT environment.

$ counter
TEXT
TEXT

TEXT

TEXT

There were 2 empty lines


and 4 lines with text.
$

Now, assume that you have a file named model.txt that contains the following lines:

some text
some text

again some text


You could run your new counter for the file, as shown below:

$ counter < model.txt


There were 1 empty lines
and 3 lines with text.
$

TradeXpress ®
Generix Group - All rights reserved 18
Tutorial / Building an EDI Message

Building an EDI Message

For the sake of simplicity, we will use a very small subset of the UN/EDIFACT INVOIC.2.912-mes-
sage. This subset is not usable in any actual application, but for the sake of this example, it allows
us to cover the most basic principles of building an EDI message.

The governing principle in the translator is to read the input file one line at a time and collect and
insert the data to the segments. When all the necessary segments have been inserted, the mes-
sage is written to the output. A segment must be written as one unit, but the segments can be
written in any order.

!- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
! Segment UNT (mandatory)
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
segment UNT
e0062 := eUNH.006 ! M an..14 MESSAGE REFERENCE NUMBER
e0074 := build(SEGMENTS + 1) ! M n..6 NUMBER OF SEGMENTS IN MSG
endsegment

The elements can be assigned values in any order in the segment building statement. Only text
values can be assigned to the elements. Values can be assigned only to the elements in the cur-
rent segment, but values from previously inserted segments can be referenced (see the refer-
ence to an element in UNH above).

An element is always referenced by its own name preceded by a lower case “e”.

TradeXpress ®
Generix Group - All rights reserved 19
Tutorial / Building an EDI Message

Specifying the Message


The program states at the beginning which message it applies to.

message "UN-EDIFACT/91.2/invoic.msg" building

The path for the file containing the message description is given first, and then the working direc-
tion. In this case we are building EDIFACT from inhouse data, so we define the direction as “build-
ing.”

Data Lines
The sample inhouse file contains only two types of records: lines starting with the text
“INVOICE#” contain header information for the entire message, and lines starting with “LINE#”
contain detailed information for line items.

INVOICE#123001 INVOICE FOR DISTRIBUTOR


LINE#1 3 007234110128.50
LINE#2 30072341502120.00

The translator reads the input file and executes a matching line statement list for each line. The
program contains two line statement lists:

line (1:"INVOICE#")
...
endline

line (1:"LINE#")
...
endline

For each line starting with “INVOICE#,” the first line statement list is executed. In the line state-
ment list, a user-written function, nfCompletePrevious(), is called first to complete the previous
message (see below). Then, segments UNH, BGM, and UNS are inserted in the message. Data for
UNH and BGM is partly constant and partly retrieved from the inhouse file. The figure below illus-

TradeXpress ®
Generix Group - All rights reserved 20
Tutorial / Building an EDI Message

trates the principle of the pick function used in the line statement lists to retrieve data from the
inhouse file.

line (1:”INVOICE#”)
...
segment UNH
...
e0062 := pick (1,9, 14)
...
endsegment
endline

column 9

line 1 INVOICE#123001 INVOICE FOR DISTRIBUTOR

14 character positions

Segment UNS is mandatory in the invoice message (although it would not be necessary in this
application), so we must insert it in the message. The UNS segment must come after the line
items, but it can be inserted here.

For lines starting with “LINE#,” the second line statement list is executed. From group seven, we
use only the LIN segment. Note that in this subset there is no actual group seven, because there
is only one segment (LIN), but the segments are always named and referenced according to the
full message description.

segment LIN g7
...
endsegment

End Statement List


In the end statement list, we call the function nfCompletePrevious to ensure that the last mes-
sage is properly terminated and written to the output. We also write the total number of mes-
sages to the logging file.

User Functions
Functions can be used whenever exactly the same action must be taken in two or more
instances. For this EDI message, we call the function nfCompletePrevious each time we start a
new message and after the entire input has been processed. This function inserts segments MOA
(in group 15) and UNT in the message. If the message is valid (that is, if it complies with all the
requirements for the INVOIC message), it is written to the output. If not, it is written to the logging
file together with all the error messages.

TradeXpress ®
Generix Group - All rights reserved 21
Tutorial / Building an EDI Message

RTE Program Source Code


The complete RTE source code is shown below. This program must be compiled with the mktr
command to generate the actual translator. See the program comments for details.

!====================================================================
=
!
! TradeXpress 4.0
! Translator from a sample inhouse file to INVOIC.2.912
!
!====================================================================
=
message “/usr/edi/messages/UN-EDIFACT/91.2/invoic.msg” building
!====================================================================
=
! For each line starting with “INVOICE#” there starts a new message.
! Previous message is completed first and then segments UNH, BGM and
! UNS are inserted to the new message.
!====================================================================
=
line(1:”INVOICE#”)
!------------------------------------------------------------------
!Fill up and write the previous message if there was one.
!----------------------------------------------------------------
--
nfCompletePrevious ()
!----------------------------------------------------------------
--
! Prepare the UNH segment: the reference number is picked from the

! inhouse, all other fields are constants.


!----------------------------------------------------------------
--
segment UNH
e0062 := pick(1,9,14) ! M an..14 MESSAGE REFERENCE NUMBER
eS009.0065 := “INVOIC” ! M an..6 Message type identifier
eS009.0052 := “2” ! M an..3 Message type version number
eS009.0054 := “912” ! M an..3 Message type release number
eS009.0051 := “UN” ! M an..2 Controlling agency
endsegment
bIncomplete := TRUE
!----------------------------------------------------------------
--
! Segment BGM (mandatory)
! The current system time is inserted in format YYMMDD to element
! C507.1.2380. The qualifier for time format is set accordingly
! to “101”.
!----------------------------------------------------------------
--

segment BGM
eC002.1000 := pick(1,23,35)!C an..35 Document/message name
eC507.1.2005 := “3”!M an..3 Date/time/period qualifier
eC507.1.2380 := time(“%y%m%d”)
!M an..35 Date/time/period
eC507.1.2379 := “101”!M an..3 Date/time format qualifier
endsegment

TradeXpress ®
Generix Group - All rights reserved 22
Tutorial / Building an EDI Message

!-------------------------------------------------
! Segment UNS (mandatory)
!-------------------------------------------------
segment UNS
e0081 := “S”! M a1 SECTION IDENTIFICATION
endsegment
endline

!===================================================================
! Lines starting with “LINE#” are line items to the
! current message. The only segment used in the group here is LIN.
! Most data is picked from the in-house file.
!====================================================================
line(1:”LINE#”)
!--------------------------------------------------------------
! Segment LIN g7 (mandatory)
!--------------------------------------------------------------
segment LIN g7
e1233 := “1”! M an..3 RELATIONAL QUALIFIER
e1082 := pick(1,6,8)! C n..6 LINE ITEM NUMBER
eC511.1.7139 := pick(1,14,3)! M an..3 Item qualifier
eC511.1.7140 := pick(1,17,35)! C an..35 Item number
eC186.6063 := “1”! M an..3 Quantity qualifier
eC186.6060 := pick(1,52,17)! M n..15 Quantity
eC509.1.5125 := “INV”! M an..3 Price qualifier
eC509.1.5118 := pick(1,69,17)
!------------------------------------------------------
! Add this line item to the total sum. Note that we have
! to convert the element values to numeric types before
! performing any arithmetic operations.
!------------------------------------------------------
nTotal := nTotal + number(eC186.6060) * number(eC509.1.5118)
endsegment
endline
!====================================================================
! This statement list is executed after the entire input has been
! consumed.
!====================================================================
end

!--------------------------------------------------------------
!Fill up and write the previous message if there was one.
!--------------------------------------------------------------
nfCompletePrevious ()
log (“There were “, nMessages, “ completed messages.”, NL)
if nErroneous > 0 then
log (“(Discarded “, nErroneous, “ erroneous messages.)”, NL)
endif
endend
!====================================================================
! This function is called each time a new message is started to fill
! up and output the previous message.
!====================================================================
function nfCompletePrevious ()
if bIncomplete = FALSE then
return 0

TradeXpress ®
Generix Group - All rights reserved 23
Tutorial / Building an EDI Message

endif
!----------------------------------------------------------------
-
! Segment MOA g15 (mandatory)
!----------------------------------------------------------------
-
segment MOA g15
e5007 := “3”! M an..3 MONETARY FUNCTION QUALIFIER
eC516.1.5025 := “9” ! M an..3 Monetary amount type qualifier
eC516.1.5004 := build(nTotal:1.2)
! C n..18 Monetary amount
eC516.1.6345 := “USD”! C an..3 Currency, coded
endsegment
!--------------------------------------------
! Segment UNT (mandatory)
!--------------------------------------------
segment UNT
e0062 := eUNH.0062 !M an..14 MESSAGE REFERENCE NUMBER
e0074 := build(SEGMENTS + 1)
!M n..6 NUMBER OF SEGMENTS IN A MSG
endsegment
!-------------------------------------------------------
! Check the message.
! If the message is OK it is written to the output, otherwise to
the log file.
!-------------------------------------------------------
if valid(MESSAGE) then
log (“Message “, eUNH.0062, “ completed.”, NL)
print (MESSAGE)
nMessages++
else
log (“Message “, eUNH.0062, “ contained errors:”, NL)
log (MESSAGE)
nErroneous++
endif
!-------------------------------------------------------
! Reset the variables.
!-------------------------------------------------------
bIncomplete := FALSE
nTotal := 0
endfunction

TradeXpress ®
Generix Group - All rights reserved 24
Tutorial / Building an EDI Message

The Inhouse Data File


This sample inhouse file contains data for three messages. To show how an error situation is han-
dled, the last message includes an intentional error in a numeric field.

INVOICE#123001 INVOICE FOR DISTRIBUTOR


LINE#1 3 007234110 1 28.50
LINE#2 3 007234150 2 120.00
LINE#3 3 007234199 1 28.50
INVOICE#123002 INVOICE FOR SUPPLIER
LINE#1 3 007234110 1 28.50
LINE#2 3 007234150 2 120.00
LINE#3 3 007234199 1 28.50
INVOICE#123003 INVOICE FOR SUPPLIER
LINE#1 3 007234110 N 28.50
LINE#2 3 007234150 2 120.00
LINE#3 3 007234199 1 28.50

The Resulting Messages


The translator sends two complete messages to the output. For easier debugging, the messages
are printed one segment per line. The modules that create the interchanges are responsible for
removing extraneous line feeds.

UNH+123001+INVOIC:2:912:UN’
BGM+:::INVOICE FOR DISTRIBUTOR++3:930125:101’
LIN+1+1++3:007234110++1:1+INV:28.50’
LIN+1+2++3:007234150++1:2+INV:120.00’
LIN+1+3++3:007234199++1:1+INV:28.50’
UNS+S’
MOA+3+9:297.00:USD’
UNT+8+123001’

UNH+123002+INVOIC:2:912:UN’
BGM+:::INVOICE FOR SUPPLIER++3:930125:101’
LIN+1+1++3:007234110++1:1+INV:28.50’
LIN+1+2++3:007234150++1:2+INV:120.00’
LIN+1+3++3:007234199++1:1+INV:28.50’
UNS+S’
MOA+3+9:297.00:USD’
UNT+8+123002’

TradeXpress ®
Generix Group - All rights reserved 25
Tutorial / Building an EDI Message

The Resulting Log File


All user-written logging statements appear in the logging file, together with the system-written
warnings. Note the system’s initial warning about the character “N” in the numeric field.
Message 123001 completed.
Message 123002 completed.
invoic: Line 85 (data line 10)
WARNING: String “N” contains non numeric
characters.Conversion yields 0.
Message 123003 contained errors:
UNH+123003+INVOIC:2:912:UN’
BGM+:::INVOICE FOR SUPPLIER++3:930125:101’
LIN+1+1++3:007234110++1:N+INV:28.50’
^ C186.6060: Invalid type NUMERIC field
LIN+1+2++3:007234150++1:2+INV:120.00’
LIN+1+3++3:007234199++1:1+INV:28.50’
UNS+S’
MOA+3+9:268.50:USD’
UNT+8+123003’
There were 2 completed messages.
(Discarded 1 erroneous messages.)

TradeXpress ®
Generix Group - All rights reserved 26
Tutorial / Receiving an EDI Message

Receiving an EDI Message

In this example, the translator receives the INVOIC.2.912 messages built in the previous example
and converts the data to the same inhouse format that was used at the starting point. One excep-
tion is made: the message total is written to the header line to demonstrate the possibilities
achieved with buffered output.

The received EDI message is traversed through segment by segment, starting from the begin-
ning. Each user-supplied segment statement list is executed as the named segment is reached in
the message. The data elements in the segment are usable as text constants with their own
names (the name again preceded by a lower case “e”).

You can reference elements in previous segments by stating the segment name before the ele-
ment name. In this case a lower case “e” precedes the entire name.

segment UNT
print (e0062, NL) ! 0062 in UNT
print (eUNH.0062, NL) ! 0062 in UNH
endsegment

Specifying the Message


The program states at the beginning which message it applies to:

message "UN-EDIFACT/91.2/invoic.msg" receiving

At this point we are receiving EDIFACT, so we define the direction as “receiving.”

Buffered Output
When building the EDI messages, we were able to insert the segments in the message in any
order, thus freeing up the order in which the data appeared in the inhouse file. The counterpart in
the receiving direction is the concept of buffered output. The basic idea is that the output is writ-
ten to a dynamic-sized matrix in any order and then flushed to the file. This makes it possible to
insert data from later segments into the output file before data from earlier segments.

RTE Program Source Code


Here is the listing of the complete source code to generate the translator. Again, this source must
be compiled with mktr before the translator can be used.

!================================================================
!
!TradeXpress 4.0
!Translator from UN/EDIFACT INVOIC.2.912 to sample inhouse.

TradeXpress ®
Generix Group - All rights reserved 27
Tutorial / Receiving an EDI Message

!================================================================
message “/usr/edi/messages/UN-EDIFACT/91.2/invoic.msg” receiving

!----------------------------------------------------------------
! For each new message write the text “INVOICE#”
! followed by the message reference number to the inhouse file.
!----------------------------------------------------------------
segment UNH
put(1,1,”INVOICE#”)
put(1,9,e0062)! M an..14 MESSAGE REFERENCE NUMBER
!----------------------------------------------------------
! Start line items from line two relative to this first line.
!----------------------------------------------------------
nLINE := 2
endsegment
!-----------------------------------------------------------------
! Also the message name is written to the header line.
!-----------------------------------------------------------------

segment BGM
put(1,23,eC002.1000)! C an..35 Document/message name
endsegment

!------------------------------------------------------------------
! Line items are inserted to the buffer.
!------------------------------------------------------------------
segment LIN g7
put(nLINE, 1, “LINE#”)
put(nLINE, 6, e1082) ! C n..6 LINE ITEM NUMBER
put(nLINE, 14, eC511.1.7139) ! M an..3 Item qualifier
put(nLINE, 17, eC511.1.7140) ! C an..35 Item number
put(nLINE, 52, eC186.6060:o17)! M n..15 Quantity
put(nLINE, 69, eC509.1.5118:o17)
!-----------------------------------------------------------
! Add up the line total to the grand total of this message.
!We will do a cross check in the summary section.
!-----------------------------------------------------------
nTotal := nTotal + number (eC186.6060) * number
(eC509.1.5118)
nLINE++
endsegment

!------------------------------------------------------------------
! Check the total sum against the calculated total. Write the sum
! to the header line.
!------------------------------------------------------------------
segment MOA g15
if nTotal <> number (eC516.1.5004) then
log (“The total sum (“, eC516.1.5004, “) for “, eUNH.0062, NL)
log (“does not match line item sums (“, nTotal, “)”, NL)
put (1,58,”(Total unknown)”)
else
put (1,58,build(“(Total: “, number (eC516.1.5004):1.2, “
USD)”))
endif
endsegment
!----------------------------------------------------------------

TradeXpress ®
Generix Group - All rights reserved 28
Tutorial / Receiving an EDI Message

! Flush the buffer out to the output file and reset the line item total
to zero.
! The arguments to flush specify the minimum and the maximum width for
the resulting
! lines. Giving a value zero to both values the lines are written to
the file exactly as ! they were in the buffer.
!----------------------------------------------------------------
segment UNT
nTotal := 0
flush(0, 0, NL)
endsegment

The Original Messages


The EDIFACT messages that we started with are displayed below.

UNH+123001+INVOIC:2:912:UN’
BGM+:::INVOICE FOR DISTRIBUTOR++3:930125:101’
LIN+1+1++3:007234110++1:1+INV:28.50’
LIN+1+2++3:007234150++1:2+INV:120.00’
LIN+1+3++3:007234199++1:1+INV:28.50’
UNS+S’
MOA+3+9:297.00:USD’
UNT+8+123001’
UNH+123002+INVOIC:2:912:UN’
BGM+:::INVOICE FOR SUPPLIER++3:930125:101’
LIN+1+1++3:007234110++1:1+INV:28.50’
LIN+1+2++3:007234150++1:2+INV:120.00’
LIN+1+3++3:007234199++1:1+INV:28.50’
UNS+S’
MOA+3+9:297.00:USD’
UNT+8+123002’

The Resulting Data File


The translator produces a data file that is identical to the original data file used in building the
messages in the previous example. The only exception is the insertion of the total sum at the end
of the INVOICE line.

INVOICE#123001 INVOICE FOR DISTRIBUTOR (Total: 297.00 USD)


LINE#1 3 007234110 1 28.50
LINE#2 3 007234150 2 120.00
LINE#3 3 007234199 1 28.50
INVOICE#123002 INVOICE FOR SUPPLIER (Total: 297.00 USD)
LINE#1 3 007234110 1 28.50
LINE#2 3 007234150 2 120.00
LINE#3 3 007234199 2 28.50

TradeXpress ®
Generix Group - All rights reserved 29
3/ Program structure

Overview
Statement Lists
Line Matching
Definitions
Functions
Comments

TradeXpress ®
Generix Group - All rights reserved 30
Program structure / Overview

Overview

An RTE program consists of one or more statement lists, optional message and database defini-
tions, and possible functions. Statement lists and functions are built from statements. The
source program may also contain comments that document and clarify the implemented solu-
tions. This chapter provides a full description of these main components in RTE. Statements and
expressions are covered in subsequent chapters.

TradeXpress ®
Generix Group - All rights reserved 31
Program structure / Statement Lists

Statement Lists

Each statement list is supplied with a rule that is matched against the input line (or segment).
The first matching rule causes the statement list to be executed. Line and segment statement
lists cannot both appear in the same RTE program.

line The matching rule can be either a given text at a given position, the appearance of
a given text anywhere on the line, or an absolute line number, or any of the above
combined with the logical operators and, or and not.

segment The matching rule is the name of the segment and its position in the message tree.

The physical order of the statement lists in the program file determines the order
in which the rules are compared against the input lines. Since the programs are
data driven, the order of the statement lists does not determine the sequence in
which they are executed, which depends entirely on the data.

Four special statement lists are provided by the system.

begin Executed before any lines (or segments) are read from the input. Must appear
before all other statement lists in the program file.

default Executed if none of the line (or segment) statements is triggered by the input line
(or segment). Must appear after all line (or segment) statement lists, but before
any end statement lists.

end Executed after the entire input has been processed. Must appear as the last state-
ment lists in the program.

function Executed when this function is explicitly called.

database “description file” DBSYMBOL


message “description file” mode

begin
!--------------------------------------
! Statements here are executed before
! anything is read from the input.
!--------------------------------------
endbegin

line segment
!-----------------!---------------
! Executed based! Executed based
! on the rule! on the rule
!-----------------!---------------
endlineendsegment

TradeXpress ®
Generix Group - All rights reserved 32
Program structure / Statement Lists

default
!--------------------------------------
! Statements here are executed if no
! line (or segment) statement list
! matched the input line.
!--------------------------------------
enddefault

end
!--------------------------------------
! Statements here are executed after
! the input has been processed.
!--------------------------------------
endend

function
!--------------------------------------
! Statements here are executed when
! this function is explicitly called.
!--------------------------------------
endfunction

TradeXpress ®
Generix Group - All rights reserved 33
Program structure / Line Matching

Line Matching

The basic line matching rules -- text at a given position, text anywhere on the line, or a line num-
ber -- can be used alone, or they can be combined with the logical operators and, or, and not.

Text at a Given Position


This kind of matching allows the user to trigger a statement list if the input line has the specified
text at an exact position. The text can be given as a constant string if it is known at compile time.
It can also be a variable or any other text expression, which is evaluated at run time.

line (3:”TEXT”)
line (2:tTRIGGER)

A special case is the matching at the end of the line. The position indicator is EOL.

line (EOL:”LAST”)

Text Anywhere
If the text position does not matter, the matching statement is as follows.

line (“FIND ME”)

Line Number
An absolute line number is specified with a single integer. This line number is matched against
the actual line number in the input. The first line in the input is one (1).

line (3)
line (100)

Logical Operators
The basic rules can be combined with logical operators to form more complex matching rules.

line (3 and “FIND ME”)


line (“FIND ME” or 3:”ME TOO”)
line (not ““)
line (“ONE” and “TWO”)

The precedence of the logical operators from highest to lowest is:

not

TradeXpress ®
Generix Group - All rights reserved 34
Program structure / Line Matching

and
or

You can alter this precedence by using parentheses. The line matching rule:

line (“ONE” or “TWO” and “THREE”)

reads, “Line contains either the text ‘ONE’ in any position or alternatively both ‘TWO’ and ‘THREE’
in any position.” If instead you want to specify, “Line contains either ‘ONE’ or ‘TWO’ in any position
and must contain ‘THREE,’” you must write:

line ((“ONE” or “TWO”) and “THREE”)

Note that if the back slash character (\) is to be matched, it must be doubled, because a single
back slash character constitutes the escape character.

line (“^\\R1032\\”)

The above example would match a line beginning with:

\R1032\

Regular Expression Matching


The basic matching rules provide for a wide range of possibilities, but you may sometimes need
more advanced capabilities. Advanced matching rules can be implemented with regular expres-
sions. These are widely used in Unix systems and novice users often find them difficult, but once
you get familiar with them you will find them very powerful. Regular expressions are also used
elsewhere in RTE, and their syntax is presented in Appendix B, Regular Expressions.

Regular expressions are not available in the NT environment.

A regular expression is inserted between single quotation marks following the line keyword. No
parentheses are allowed.

line ‘regular expression’

For example, the matching rule

line ‘^[A-Z]+[A-Za-z]*’

specifies, “Line where the first character on the line is an upper case letter that may optionally be
followed by any number of upper or lower case letters.”

Here is an example of a case where the expression power of the basic rules is insufficient: we
need to match a line that contains the word “TEXT” and nothing else. The rule

TradeXpress ®
Generix Group - All rights reserved 35
Program structure / Line Matching

line (1:”TEXT” and EOL:”TEXT”)

is a good attempt, but the line “TEXT-TEXT” (to give one example) would match this rule also. A
regular expression can be used to solve the problem:

line ‘^TEXT$’

Multi Matching
An RTE program can be directed to execute all matching statement lists instead of executing only
the first match. You can achieve this by compiling the source program with the a-option.

TradeXpress ®
Generix Group - All rights reserved 36
Program structure / Definitions

Definitions

Because RTE is a very high-level programming language, you do not have to define variables,
worry about memory allocation and deallocation, or work with awkward file I/O functions.

There are, however, two types of definitions that you must make: message and database defini-
tions. Both define an interface to external data.

Message Definition
Message definition is required when the RTE translator is used to build or receive EDI messages.
A program can contain only one message definition.

The message definition states the name of the message description file and the intended usage.
The usage is either building or receiving. The interpretation of the message description file
depends on the keyword used in front of the file name. The keyword message implies that all
governing message-level rules are in force and that the segments are handled as part of the
message. The keyword segments implies that segments in the message description file are used
independently, with no governing message-level rules applied to them.

message “UN-EDIFACT/91.2/INVOIC.msg” building


message “ANSIX12/810.msg” receiving
segments “UN-EDIFACT/91.2/UN-segments.msg” building

The chapter 5 EDI Translation describes EDI translation in full detail.

Database Definition
If an RTE program refers to EDIBASE databases, there must be a separate database definition for
each database used. These definitions must appear before any statement lists. The syntax to be
used is the following:

base "configuration_file" entry_identifiers, option

Example:

base "syslog.cfg" LOG


base "syslog.cfg" LOGENTRY THISLOG DUPLICATE, autoflush off

If the configuration file name does not include the entire path from the root directory, it is
assumed to be relative to a directory named $HOME/database or, secondarily, $EDIHOME/data-
base.

The possible database options are:

TradeXpress ®
Generix Group - All rights reserved 37
Program structure / Definitions

• readonly: if added this option states that the RTE instructions should not write into the data-
base. Setting this option allows improving database performance.
• autoflush on/off: this option states whether the RTE is used in a autoflush mode. If autoflush
is on, data are written to the database as they are assigned, if autoflush is off, the database
writing operations are written only when flushed. By default this option is on.
The actual database instance used at run time does not have to exist at compile time; the data-
base definition file is sufficient.

TradeXpress ®
Generix Group - All rights reserved 38
Program structure / Functions

Functions

You can write your own functions to perform various tasks. The functions can receive the basic
data types and arrays as parameters and they can return the basic data types as their values.

All user-defined functions must be located after all statement lists. The order of the functions is
not relevant. A function located later in the code can be called from an earlier function.

User-defined function names start with one of the letters “t,” “n,” or “b,” and always have a lower
case “f” as the second letter. The first letter identifies the return type and the second letter identi-
fies the symbol as a function name (in contrast to a text variable, for example). The third charac-
ter must be an upper case letter. The remaining characters can be letters, digits, and
underscores.

function tfGetTime ()
return time ("%d.%m.%y")
endfunction

function nfSum (nFirst, nSecond)


return nFirst + nSecond
endfunction
function bfEqual (tOne, tTwo)
return (tOne = tTwo)
endfunction

Any passed parameters are local variables to the function. All other variables used in the function
are global and can thus be referenced outside the function as well.

All text variables passed as function parameters should be treated as read-only variables and
they should be used as a left side of an assignment operation.

The return value must be the same type as the function. This is checked for at compile time.

A function must include a return statement if the code that invokes it makes use of the value
returned by the function. Examples include numeric functions that make use of the maths copro-
cessor. However, we recommend that you use a return statement in any case, to make the code
more readable.

Do not use a global variable as return value, instead use local variable. If you do so, calling a function many times inside
another function will set the same value for each parameter.

TradeXpress ®
Generix Group - All rights reserved 39
Program structure / Comments

Comments

There are the following ways to write comments in the source code.

Source Code Documentation


An exclamation mark (!) starts a comment that extends to the end of the line. Comments can
appear anywhere in the program. Commenting the source code is highly encouraged; a clearly
commented program is easy to read and maintain.

Runtime Information
RTE provides a facility to retrieve information about the executable translator module. This infor-
mation can be used to document the purpose, methods of use, required arguments, and other
items for the translator.

Information comments are started with the percent sign (%) and extend to the end of the line like
regular comments. These comments can be freely distributed in the source code, but when
printed they are concatenated together.

After an RTE program has been compiled with mktr, this information can be retrieved by running
the translator with the i-option.

%
% A sample information comment
%
begin
!- - - - - - - - - - - - - - - - -
! Imagine there is some actual code here.
!- - - - - - - - - - - - - - - - -
endbegin

$ mktr sample.rte
$ sample -i
A sample information comment
$

TradeXpress ®
Generix Group - All rights reserved 40
4/ Program statements

Overview
Assignment Statements
Increment and Decrement Statements
Control Statements
Loop Statements

TradeXpress ®
Generix Group - All rights reserved 41
Program statements / Overview

Overview

An RTE program consists of statement lists that contain statements. The statements can be
assignments, increment and decrement statements, control statements, and function calls.
Statements are separated by the newline character.

TradeXpress ®
Generix Group - All rights reserved 42
Program statements / Assignment Statements

Assignment Statements

In assignment statements, variables of all types can be given new values. The variables can be
system or user defined, database entries, or items in arrays. The allowed variables for all types
are covered in detail below.

Text Assignments
On the left side, a text assignment can contain a user-defined text variable, a textual system vari-
able (APPL_DEC_SEP, MSG_ DEC_SEP, FILL_CHAR, RETURN_BUF-FER, NL), an element in a text array,
or a text or time field in a database or parameter. Note that inside a function, none of the function
arguments can be used on the left side of an assignment. The right side of the assignment must
be a text expression.

tText := "sample text"


taTexts[1] := tText
APPL_DEC_SEP := "."
MSG_DEC_SEP := tfGetSeparator ()
FILL_CHAR := pick (1,1,1)
RETURN_BUFFER := taTexts[2]
NL := "\n"
ENTRY.NAME := "myname"
ENTRY.EXPIRES := "31.12.1999"
pSAMPLE := ENTRY.NAME

Text constants can be concatenated as follows:

"str""ing"

which becomes

"string"

The above-mentioned concatenation is useful with cpp macros, for example.

Numeric Assignments
On the left side, a numeric assignment can contain a user-defined numeric variable, a numeric
system variable (LOGLEVEL), an element in a numeric array, or a numeric field in a database. The
right side of the assignment must be a numeric expression.

nNumber := 3
naNumbers[1] := nNumber
naNumbers["text"] := nfGetValue ()
ENTRY.AGE := 45
LOGLEVEL := 1

TradeXpress ®
Generix Group - All rights reserved 43
Program statements / Assignment Statements

Boolean Assignments
On the left side, a boolean assignment can contain a user-defined boolean variable, a boolean
system variable (PROCESS_ER-RONEOUS), or an element in a boolean array. The right side of the
assignment must be a boolean expression.

bBoolean := TRUE
baBooleans[1] := FALSE
baBooleans[2] := nNumber > 2
PROCESS_ERRONEOUS := TRUE

File Assignments
A file assignment applies only to user-defined file variables. The right side of the assignment
must be a text expression.

fFile := "/etc/hosts"

Database Assignments
A database assignment is used to link a database identifier to a physical record in the database.
The left side must be a predefined database entry, and the right side must contain either “find” or
a new function.

ENTRY := find ("mybase", NAME="myname")


ENTRY := new ("mybase")

Array Assignments
An array assignment is used to copy an array to another array.

taArray1 := taArray2

TradeXpress ®
Generix Group - All rights reserved 44
Program statements / Increment and Decrement Statements

Increment and Decrement Statements

Increment and decrement statements are used with numeric variables only. An increment state-
ment adds one to the value of the variable, and a decrement statement subtracts one from the
value.

nNumber++
naNumbers[2]--

The effect shown above could also be achieved with the following assignment statements. In this
case, the advantage of increment and decrement statements over an assignment statement is
more compact code.

nNumber := nNumber + 1
naNumbers[2] := naNumbers[2] - 1

TradeXpress ®
Generix Group - All rights reserved 45
Program statements / Control Statements

Control Statements

You can use the following control statements in the source code.

Conditional Statement
With a conditional statement, one or more statements can be executed conditionally.

if boolean expression then


!- - - - - - - - - - - - - - - - -
! One or more statements
!- - - - - - - - - - - - - - - - -
endif

The conditional statement may contain an optional "else" part.


if boolean expression then
!- - - - - - - - - - - - - - - - -
! One or more statements
!- - - - - - - - - - - - - - - - -
else
!- - - - - - - - - - - - - - - - -
! One or more statements
!- - - - - - - - - - - - - - - - -
endif

if bDoIt = TRUE then


print ("I am doing it...", NL)
else
print ("Did not do it", NL)
endif

Boolean Expressions
Boolean expressions can contain comparisons of boolean, text, and numeric expressions, alone
or combined with the logical operators and, or, and not.

3 >= nNumber
LOGLEVEL > 1
naNumbers[2] = 12
nNumber < 18.24
13.67 <= naNumbers[3]

tText <> "comparison"


taArray[1] = tText
bBoolean = TRUE
baBooleans[4] <> FALSE

3 >= nNumber and tText <> "comparison"


nNumber < 18.24 or bBoolean = TRUE
not taArray[1] = tText

TradeXpress ®
Generix Group - All rights reserved 46
Program statements / Loop Statements

Loop Statements

RTE supports five different loop statements. A general loop is controlled with a boolean expres-
sion. In addition, there are special loop statements to traverse arrays, lists, databases, and file
system directories.

General Loop Statement


In the general form of a “while” statement, the loop is controlled with a boolean expression.

while booleanexpr do
!- - - - - - - - - - - - - - - - -
! One or more statements
!- - - - - - - - - - - - - - - - -
endwhile

The following program prints the members from one to ten.

nIndex := 1
while nIndex <= 10 do
print (nIndex, NL)
nIndex++
endwhile

Array Scanning
The array scanning loop statement makes it possible to scan arrays with no prior knowledge
about the number of items or the naming of the related indexes. The loop scans the array indexes
in alphabetical order. For each repetition, the index variable (tIndex) is assigned to the index of
the array element.

while tIndex in taArray do


!- - - - - - - - - - - - - - - - -
! One or more statements
!- - - - - - - - - - - - - - - - -
endwhile
while tTmp in taNames do
print (tTmp, " has value ", taNames[tTmp], NL)
endwhile

List Scanning
The list scanning loop statement simplifies the scanning of the lists created by a load command.
The scanned list must be an element in an array that has been created with the load function.

while tValue in taArray[tIndex] do


!- - - - - - - - - - - - - - - - -

TradeXpress ®
Generix Group - All rights reserved 47
Program statements / Loop Statements

! One or more statements.


!
! Each item in the list is
! referenced as tValue.
!- - - - - - - - - - - - - - - - -
endwhile

while tValue in taArray[tIndex] do


print (tValue, NL)
endwhile

For details, see the chapter 9, section Functions Reference, load.

The list scanning loop can also be implemented with a split function with the use of the general
form of the loop statement to scan the generated array. The array scanning loop can also be used
to scan the array. These are the only ways to scan a list when the list is not an element in an
array created by the load function.

nCount := split (taArray[tIndex], taTmp, ":")


nIndex := 1
while nIndex <= nCount do
print (taTmp[nIndex])
nIndex++
endwhile

nCount := split (taArray[tIndex], taTmp, ":")


while tTmp in taTmp do
print (taTmp[tTmp])
endwhile

Directory Scanning
A directory in the Unix file system can be scanned with the directory scanning loop statement.

The directory and the template for file names are stated in a text expression (tFilename). The
template can contain wild characters in the actual file name, but not in the directory path. The
scanning loop cannot process any subdirectories.

The running variable (fFile) contains the current file for each repetition. The order in which the
files arrive depends on the physical order in which they are stored in the directory, and is thus
undefined.

while fFile in tFilename do


!- - - - - - - - - - - - - - - - -
! One or more statements
!- - - - - - - - - - - - - - - - -
endwhile

TradeXpress ®
Generix Group - All rights reserved 48
Program statements / Loop Statements

This example counts the total size for all files that start with “MyFile” in the directory “/tmp.”
nTotal := 0
while fFile in "/tmp/MyFile*" do
nTotal := nTotal + fFile.SIZE
endwhile
print ("My files occupy total ", nTotal, " bytes.", NL)

Database Scanning
while database entry in filtered database do
!- - - - - - - - - - - - - - - - -
! One or more statements
!- - - - - - - - - - - - - - - - -
endwhile

The following example shows how all entries that have been created over three days are removed
from the database.

while entry in ("mybase", CREATED < "now - 3d") do


remove (entry)
endwhile

Switch Statement
The switch statement can be used to make a selection between several text values.

switch tSelector
case tOpt1:
!- - - - - - - - - - - - - - - - -
! One or more statements
!- - - - - - - - - - - - - - - - -
case tOpt2:
!- - - - - - - - - - - - - - - - -
! One or more statements
!- - - - - - - - - - - - - - - - -
default:
!- - - - - - - - - - - - - - - - -
! The default branch is optional.
! One or more statements
!- - - - - - - - - - - - - - - - -
endswitch

The statements after the matching case expression are executed. If none of the options matches
the selection, then the statements in the optional default section are executed. If the default is
used, it must be the last option in the switch statement.

Switch Expression
Switch expressions are related to the switch statement. The switch expression is type text and its
syntax is as follows:

TradeXpress ®
Generix Group - All rights reserved 49
Program statements / Loop Statements

switch (tSelect, tOpt1:tRes1, tOpt2:tRes2, default:tResDef)\

As its value, the expression gets the result that was paired with the option which is equal to the
first argument (tSelect). If none of the options matches the selector, then the value of the expres-
sion is EMPTY.

The following example shows a basic switch expression.

tCurrency := eC516.1.6345 ! C an..3 Currency, coded

print ( "The currency used for this transaction was ", switch( tCur-
rency, "USD":"the Greenback", "FIM":"Finnish Marks", default:"other
than FIM or USD"))

Switch Statement with Coprocesses


The switch statement can be used together with the TradeXpress coprocess library to provide an
easy way of matching input data from coprocesses.

switch expect <PID> <time-out>


case <string>:
<RTE statements>
...
endswitch

For a more comprehensive explanation of the coprocess library and the switch statement, see
the appendix F Advanced Utilities.

The switch statement with coprocesses is not available in the Windows environment.

Break Statement
The break statement causes the termination of the innermost enclosing loop. This action is illus-
trated in the example below.

Continue Statement
The continue statement causes the execution to skip the remaining statements of the innermost
enclosing loop. The execution continues from the first statement if the looping does not termi-
nate in the comparison.

TradeXpress ®
Generix Group - All rights reserved 50
Program statements / Loop Statements

while bLoop = TRUE do


if bWantToBreak = TRUE then
break
endif
!---------------------------
!

Next Statement
The next statement can only be used within the line statement or segment statement lists. It
causes the execution to skip the rest of the current statement list and causes new input to be
read.

line (1:"sample")
if bIgnoreSample = TRUE then
next
endif

Statement
The statement can only be used in programs that receive EDI messages. It causes the program to
ignore the remaining segments in the current message and a new message to be read in.

segment UNH
if valid (MESSAGE) = FALSE then

endif
endsegment

RTE exceptions
The RTE language, as any high level language, offers a significant of abstractions in comparision
with low-level operations such as writing /reading files. One of the consequences of this abstrac-
tion is that it is difficult, or even impossible to handel low-level errors.

TradeXpress ®
Generix Group - All rights reserved 51
Program statements / Loop Statements

In standard mode, these errors trigger, according to their severity, either a warning , either a fatal
error. Warnings may be ignored or cause the program’s termination, according to the log level.
Fatal errors cause consistently the program’s termination. This basic mechanism does not to tol-
erate unexpected errors, and requires to anticipate at best all error cases, which is almost
impossible and involves an excess of tests into the program. Handling exceptions is a simple
and standard means to deal with this kind of errors.

Principle
An exception handling is declared by using the try ...catch...finally ...endtry instructions into the
program’s lines.

try begins a protected section

catch states the end of a protected section, and the start of exceptions processing

finally states the end of a protected section (if not done previously with the catch instruc-
tion) and the start of an inconditional processing

endtry states the end of an exception handling

The program located after the try instruction is executed as if no exception handler existed. If
when the program is running an error occurs, then, the standard sequence is interrupted and the
program goes to the first line preceding the catch instruction. Then the program is executed until
the end. If no error occurs during the execution of the bloc located between the try and the catch
instruction, then the catch bloc is ignored and the program goes to the finally bloc. The protec-
tion ends with the catch or finally instruction. If an exception occurs and no processing has been
previsted for this exception, then the exception is spread after the endtry instruction (which
leads to the program termination, unless this occurs in a higher level protected section)

The exception handling may be conditional, i.e. is executed only for some exception classes.

An additional instruction throw() allows to trigger its own exceptions which may be then pro-
cessed with an exception handler.

TradeXpress ®
Generix Group - All rights reserved 52
Program statements / Loop Statements

Syntaxe

try begins a protected section

[catch [exp1,[exp2,..[exp n]...]]] ends a protected section, begins an exception processing, and can-
cel the exception if the exception class is as argument in the whole
expressions.
exp1...expn are character strings (or any instruction/function
returning a character string).
The catch instruction is optional, but it can be multiple in a pro-
tected section.

finally ends the preceding section and begins the inconditional process-
ing; does not cancel the current exception.
The finally instruction is optional.

For now, the finally section is not always be executed. Most notable cases
are :
- when you return, break, exit out in any section
- when you decide to throw an exception in a catch statement.
This behaviour may change in future versions.

You need to have at least one catch instruction or one finally instruction in an exception handler

endtry ends the exception handler bloc

EXCEPTION_CLASS, allow respectively to retrieve the exception class, its cause, its code
EXCEPTION_REASON, and its associated message.
Code is in numeric format
EXCEPTION_CODE,
Other fields are text values
EXCEPTION_MESSAGE
throw([class[, reason[, reason- triggers an exception. When parameters are missing, allows to
code, [message]]]]) spread the exception

bfPrintExceptionStack() prints the exceptions stack in the standard output

You can interleave as many exceptions handler as necesary

TradeXpress ®
Generix Group - All rights reserved 53
Program statements / Loop Statements

Use
Example 1: protecting a calling to a number function which allows to ensure the running of a pro-
gram whatever the log level is, and to convert it into a string non-convertible to -1 (as standard,
number would trigger a warning ad return 0)

try
nNum := number(tNumber)
catch
nNum := -1
endtry

Example 2 : intercepting of all warnings excluding the fatal erros (or any other exception classes)

try
nNum1 := number(tNumber)
nNum2 := nNum3 / nNum4
catch "general"
switch EXCEPTION_CODE
case 1 : nNum1 := -1
log(EXCEPTION_MESSAGE, " Valeur non numérique remplacée par -1", NL)
default : throw()
endswitch
endtry

Example 3 : interleaving handlers

try
try
nNum1 := number(tNumber)
nNum2 := nNum3 / nNum4

catch "general"
switch EXCEPTION_CODE
case 1 : nNum1 := -1
default : throw()
endswitch
endtry
catch
print(« Ce programme à provoqué une erreur non récupérable », NL)
finally
print(« Merci d’avoir utilisé ce programme », NL)
endtry

RTE internal exceptions


All internal exceptions are "general" class exceptions

TradeXpress ®
Generix Group - All rights reserved 54
Program statements / Loop Statements

• Warning : class exception "general", reason « warning », code=1 ; triggered if internal non-
blocking error (eg: conversion into numeric of a non-convertible string), if log level higher than
2;
• Fatal : class exception "general", reason « fatal », code=2 ; triggered if severe internal (eg :
segmentation fault)
If the exception is protected, the message may be retrieved on the EXCEPTION_MESSAGE field.

Limitations
Handling exceptions should not be used into programs implementing multi-threading (which is
not the case into RTE standard programs).

Handling exceptions does not allow to correct a failing program, especially in case of serious
error. we advise you against intercepting an exception in order to continue the program as if no
error had occured. On the other hand, handling exceptions may bu useful to cleanly end a pro-
gram by attempting to close started transactions, freeing connections...

A section try ... endtry should be included into the same instructions bloc and cannot bu used as
main bloc at the same level as begin ... endbegin or line ... endline.

Inline C Block Statement


The inline C block statement provides access to the description area of an RTE program. Users
can use inline C block statements to define their own C functions and data structures.

Syntax:
inline<nl>
<C source code>
endinline<nl>

For a more comprehensive explanation of the inline statement, see the appendix F Advanced
Utilities.

Inline C Statement
The inline C statement provides access to the RTE program user statement area, allowing users to
define their own C statements, such as function calls and data structures. Inline C statements
are also useful when a user attaches API functions such as database access directly to an RTE
program.

Syntax:
inline "<C source code %N >",%0, %1, ..., %n<nl>

TradeXpress ®
Generix Group - All rights reserved 55
Program statements / Loop Statements

where %N represents a replaceable, ordinal macro variable. These variables can be located any-
where within the C source code. The variables obtain values from the argument list correspond-
ing to the order in the list. There is no limit to the number of variables.

For a more comprehensive explanation of the inline statement, see the appendix F Advanced
Utilities.

TradeXpress ®
Generix Group - All rights reserved 56
5/ EDI translation

Overview
Operating Principle
Specifying the Message
Naming the Elements
Building Messages
Independent Segments
Receiving EDI Messages
Receiving Direction Error Handling

TradeXpress ®
Generix Group - All rights reserved 57
EDI translation / Overview

Overview

The RTE EDI translator module can handle various EDI syntaxes. The most widely used syntax is
UN/EDIFACT (United Nations Rules for Electronic Data Interchange for Accounting, Commerce and
Transport). Other supported syntaxes include ANSI ASC X12, TRADACOMS, VDA, and SPEC2000.

TradeXpress ®
Generix Group - All rights reserved 58
EDI translation / Operating Principle

Operating Principle

The translator is based on data segments and their elements, which can be either simple data ele-
ments or composite data elements that consist of two or more component data elements. The
highest level in the hierarchy is the message. A message definition consists of a list of segments
and their status and repetition information. The segments in a message can be gathered into
groups, each with its own status and repetition information. For more details on describing mes-
sages, see the appendix C Message Storage Format.

The status of a segment in a message can be mandatory, conditional, or floating, which also
implies conditional status.

One RTE program works for one message in one direction.

TradeXpress ®
Generix Group - All rights reserved 59
EDI translation / Specifying the Message

Specifying the Message

The message definition file and the working direction are specified at the beginning of the pro-
gram, before any statement lists.

message "EDIFACT/UN/91.2/invoic.msg" receiving


message "EDIFACT/UN/91.1/orders.msg" building
segments "EDIFACT/UN/91.1/ifcsum.msg" building

The message definition file is an ordinary ASCII file that contains all the included segments and
grouping information. For more information, see the appendix C Message Storage Format. The
keyword (message or segments) before the definition file name specifies how the message defi-
nition is to be interpreted. The keyword (building or receiving) after the file name specifies the
direction in which the program works.

message The definition file is interpreted to contain one message with all specified repeti-
tion and grouping information.

building The resulting program collects the segments into a message that is validated and
printed as one unit.

receiving The resulting program reads one message at a time from input and hands the
segments one at a time to user-written segment statement lists.

segments The definition file is interpreted to contain independent segments with no govern-
ing message structure. None of the repetition or grouping information is applica-
ple. The description file must follow the same rules as when used for a message
(that is, segment status and repetition information must be present for correct
presentation syntax, even though they are not used).

building The resulting program writes individual segments to the output.

receiving The resulting program reads input one segment at a time. These segments are
processed in the user-written segment statement lists.

TradeXpress ®
Generix Group - All rights reserved 60
EDI translation / Naming the Elements

Naming the Elements

All data elements are referenced by a unique name, which is always preceded by a lower case “e.”
Elements are always handled within an enclosing segment building statement (when building a
message), or within a segment statement list (when receiving a message). Thus each segment
has a unique name.

Simple data elements that appear only once in a segment are written as shown below.

e1445

A simple data element that appears more than once in a segment will be followed by a period and
then an ordinal number.

e1338.1
e1338.2

Component data elements are named so that the governing composite name comes first, fol-
lowed by a period and the name of the data element.

eC507.2005

For a component data element that appears more than once in a segment, the ordinal number is
specified immediately after the name of the composite. Again, all parts of the name are sepa-
rated by periods.

Here is a list of references to the segment CUX elements shown in the previous figure:

TradeXpress ®
Generix Group - All rights reserved 61
EDI translation / Naming the Elements

eC504.1.6347
eC504.1.6345
eC504.2.6347
eC504.2.6345

If a component data element appears more than once in a composite, it will be followed by a
period and an ordinal number.

Here is a list of references to the TOD segment elements shown in the previous figure:

eC100.4052.1
eC100.4052.2

Finally, here is the rule for all component data elements that appear more than once in a compos-
ite which in turn appears in the segment more than once: the ordinal number for the composite
comes between the names, and the ordinal number for the component inside the composite
comes last.

TradeXpress ®
Generix Group - All rights reserved 62
EDI translation / Naming the Elements

Here is a list of references to the previous segment LOC elements:

eC517.1.1131.1
eC517.1.3055.1
eC517.1.1131.2
eC517.1.3055.2
eC517.2.1131.1
eC517.2.3055.1
eC517.2.1131.2
eC517.2.3055.2

TradeXpress ®
Generix Group - All rights reserved 63
EDI translation / Building Messages

Building Messages

Messages are built from the application data. This data may come to the program as input, it may
be extracted directly from a database, it may be totally or partially constant, or any combination
of the above. A message building RTE program is a description of how a set of application data is
converted to a given message structure. The complexity of this program depends entirely on the
complexity of the inhouse data: it may contain only straightforward assignments, or it may be
fully loaded with conditional statements, calls to external programs, and databases.

Data is inserted in the message tree one segment at a time with the segment statements. After
all segments have been inserted, the message syntax can be checked. Depending on the validity
of the message, the user can choose to ignore the message or send it to output.

The segments can be inserted in the message in any order.

Segment Building Statement


The segment statement can be viewed as a work area where the elements are assigned their val-
ues. The segment statement starts with the keyword segment, followed by the segment name
and possible location specification. You can also specify repetition information for each enclos-
ing group (see Specifying the Segment Location in this chapter).

The segment building statements can contain a selection of any other available statements,
excluding another segment building statement. At its simplest, the segment building statement
is a list of assignment statements:

segment UNH
e0062 := build (nMessages)
eS009.0065 := "INVOIC"
eS009.0052 := "1"
eS009.0054 := "911"
eS009.0051 := "UN"
endsegment

Message constants such as name and version can be obtained through the use of message variables such as mMESSAGE, mVER-
SION, mRELEASE, and mAGENCY.

At the end of the statement, the segment is inserted in the message. It cannot be changed later
in the program. The data in the elements is available for reference up to the point in the program
where the next segment statement for the same segment is entered.

TradeXpress ®
Generix Group - All rights reserved 64
EDI translation / Building Messages

Here is a sample segment building statement that contains a conditional statement:

segment BGM
eC002.1001 := pick (1, 1, 3)
if eC002.1001 = "AAA" then
eC002.1131 := "BBB"
else
eC002.1131 := "CCC"
endif
eC002.3055 := pick (1, 4, EOL)
endsegment

A segment building statement can also be part of a conditional statement:

if bIncludeFreeText = TRUE then


segment FTX
e4451 := "100"
eC108.4440.1 := "Free form text"
endsegment
endif

Element Assignments
Element values are given in assignment statements. All element assignment statements must
be enclosed in the governing segment statement, and assignments can be made only to ele-
ments that belong to the current segment.

Elements are always type text in RTE. The EDI related types (such as alphanumeric, alpha, and
numeric) specify the data representation for the element (that is, which characters are allowed).
These two different concepts are explained below.

EDIFACT element e1082 is numeric as far as content is concerned, but since all elements are type
text in RTE, the line below would result in a compiler error.

e1082 := 3C n..6 Line item number

The RTE compiler is satisfied with the following assignment, since the element is assigned type
text. However, the EDI translator module will report an “invalid type” error at run time, because
“N” is not a number.

e1082 := "N"C n..6 Line item number

The following assignment satisfies both the compiler and the EDI translator module. The right
side of the assignment is type text that represents numeric data.

e1082 := "3"! C n..6 Line item number

If you have a value in a numeric variable that needs to be assigned to an element, you can use
the build function to make the conversion from numeric type to type text.

e1082 := build (nNum)! C n..6 Line item number

TradeXpress ®
Generix Group - All rights reserved 65
EDI translation / Building Messages

Element values can be assigned in free order within a segment statement. The following seg-
ment statement contains the elements for the UNH segment, but in reverse order compared to
the example above. The result is exactly the same.

segment UNH
eS009.0051 := "UN"
eS009.0054 := "911"
eS009.0052 := "1"
eS009.0065 := "INVOIC"
e0062 := build (nMessages)
endsegment

Packing Data in Repeating Elements


By default, the TradeXpress translator packs repeating elements and components of the compos-
ite element. This default cannot be changed through the user interface. The changes must be
made in $HOME/.tclrc.

When a segment contains repeating elements, the translator module packs the data to the begin-
ning of the repeating set. The following example shows how a CST segment is built from five sep-
arate lines of input. Each input line provides information for one composite data element, C246.

TradeXpress ®
Generix Group - All rights reserved 66
EDI translation / Building Messages

segment CST
e1496 := "1"
eC246.1.7361 := pick (1,1,18)
eC246.1.3055 := pick (1,19,3)
if eC246.1.3055 != EMPTY then eC246.1.1131 := "101"
endif
eC246.2.7361 := pick (2,1,18)
eC246.2.3055 := pick (2,19,3)
if eC246.2.3055 != EMPTY then eC246.2.1131 := "25"
endif
eC246.3.7361 := pick (3,1,18)
eC246.3.3055 := pick (3,19,3)
if eC246.3.3055 != EMPTY then eC246.3.1131 := "38"
endif
eC246.4.7361 := pick (4,1,18)
eC246.4.3055 := pick (4,19,3)
if eC246.4.3055 != EMPTY then eC246.4.1131 := "104"
endif
eC246.5.7361 := pick (5,1,18)
eC246.5.3055 := pick (5,19,3)
if eC246.5.3055 != EMPTY then eC246.5.1131 := "110"
endif
endsegment

By way of example, here is some sample inhouse data:

CODE1 AA
(empty line)
(empty line)
CODE4 AB
CODE5 AE

The segment will contain the following data. The second and third composites do not receive any
values and are left empty. The translator module packs the composites so that the empty ones
come last, which means that no extra separators are needed.

CST+1+CODE1:101:AA+CODE4:104:AB+CODE5:110:AE'

Decimal Separator Conversion


The character set used in an EDI message may have been configured to contain a different deci-
mal separator from the one used in the application data file. RTE provides for automatic decimal
separator conversion for numeric data elements. The application decimal separator is stored in
the variable APPL_DEC_SEP, and the one used in the EDI message is stored in MSG_DEC_SEP.

Specifying the Segment Location


Each segment in the message tree has a unique identification by which it can be located in the
message hierarchy. The identification is the segment name alone for segments that are not
enclosed in any group.

TradeXpress ®
Generix Group - All rights reserved 67
EDI translation / Building Messages

segment UNH
segment BGM
segment UNT

If the segment is enclosed in a group, its name is the segment name plus the names of all the
enclosing groups. The list below contains all the CUX segments that are included in the UN/EDI-
FACT message CUSDEC.2.912.

segment CUX g6
segment CUX g7, g8
segment CUX g7, g14
segment CUX g7, g15, g16
segment CUX g7, g15, g22
segment CUX g23, g26
segment CUX g23, g34, g35

The group identifiers are separated by commas, and all group identifiers must be included.

If a segment appears more than once in the same group path or outside any groups, an ordinal
number in front of the segment name is used to distinguish the segments. This example is also
taken from the UN/EDIFACT CUSDEC.2.912 message.

segment 1.UNS
e0081 := "D"
endsegment
segment 2.UNS
e0081 := "S"
endsegment

The ordinal number can be left out for the first segment. Thus this:

segment UNS
e0081 := "D"
endsegment

is the same as the first UNS specification above.

TradeXpress ®
Generix Group - All rights reserved 68
EDI translation / Building Messages

segment UNH
.
.
.
endsegment

segment UNS
.
.
.
endsegment

segment BGM
.
.
.
endsegment

Specifying the Segment Repetition


Depending on the structure of the inhouse data, it may be necessary to insert segments in mixed
order. The following examples show how repetition can be specified for the DTM segment in group
23 in the UN/EDIFACT CUSDEC.2.912 message.

segment DTM g23

The DTM segment is inserted in the next available slot under group 23.

segment DTM=2 g23

The DTM segment is inserted in the second slot (out of five) under group 23.

TradeXpress ®
Generix Group - All rights reserved 69
EDI translation / Building Messages

segment DTM g23=2

The DTM segment is inserted in the next available slot under group 23, when group 23 is in its
second repetition.

segment DTM=3 g23=3

The DTM segment is inserted in the third slot (out of five) under group 23, when group 23 is in its
third repetition.

Checking the Syntax


The segments created with the segment statement lists form the message structure in the sys-
tem’s memory. The validity of the message can be checked with the general purpose function
valid before the message is written to the output. If the message contains no EDI errors, the
function returns the value TRUE; otherwise it returns the value FALSE.

You can print the message with the print function by specifying the keyword MESSAGE as the
only argument to print.

The message will be removed from memory immediately after it has been printed. To keep the
message in memory after printing, you must compile the RTE source code with the -m option.

if valid (MESSAGE) = TRUE then


print (MESSAGE)
else
!- - - - - - - - - - - - - - - - - - -
! User specified alarms, counters
! for erroneous messages go here.
!- - - - - - - - - - - - - - - - - - -
log (MESSAGE)
endif

If the message contains errors, the error messages are included at


appropriate places in the printed message.
UNH+123001+INVOIC:2:912:UN'
BGM+:::INVOICE FOR DISTRIBUTOR++3:930301:101'
LIN++1++3:007234110++1:1+INV:28.50'
^ 1233: Missing mandatory element (11)
LIN+1+2++3:007234150++1:2+INV:120.00'
LIN+1+3++3:007234199++1:1+INV:28.50'
UNS+S'
UNT+8+123001'
Too few groups 15 (0), 1 minimum

Segment Counter
A numeric read-only variable, SEGMENTS, contains the number of segments that have been
inserted in a message so far. Most EDI grammars require the segment count in the trailer seg-
ment.

TradeXpress ®
Generix Group - All rights reserved 70
EDI translation / Building Messages

Since the RTE EDI translator module is completely independent of any grammar, it does not know
which data element should contain the segment count. This means it is the user’s responsibility
to insert the count in the appropriate segment. The example below shows how this is done in an
EDIFACT message in which the trailer segment is UNT. The segment count in UNT includes the UNT
itself, and since SEGMENTS gives the number of segments inserted so far, we must add one to it
to get the grand total.

segment UNT
e0074 := build (SEGMENTS + 1)
e0062 := eUNH.0062
endsegment

For a complete but compact example of building and sending EDI messages, see the chapter 2
Tutorial Introduction.

TradeXpress ®
Generix Group - All rights reserved 71
EDI translation / Independent Segments

Independent Segments

If the message definition keyword is segments instead of message, then the segments in the
message description are treated independently from the message structure. Each segment
statement list causes the segment to be written immediately to the output. If the segment con-
tains errors, there will be no output. This condition can be checked for after the segment state-
ment list.

segment UNH
e0062 := build (nMessages)
eS009.0065 := "INVOIC"
eS009.0052 := "1"
eS009.0054 := "911"
eS009.0051 := "UN"
endsegment
if valid (SEGMENT) = FALSE then
log ("Segment UNH contained errors.", NL)
edierrordump (SEGMENT)
endif

Note that the segment statement list shown above does not output anything if an error occurs. The content of the segment, with
appropriate error messages, can be printed with the edierrordump function, which prints by default to the logging stream instead
of to the output.

TradeXpress ®
Generix Group - All rights reserved 72
EDI translation / Receiving EDI Messages

Receiving EDI Messages

The translator reads messages one at a time from the input and checks them for correct syntax.
If the message is valid according to the message description being used, it is then delivered one
segment at a time to be processed by the user-written statements.

An RTE program for processing incoming messages consists of segment statement lists that are
triggered by incoming segments. The elements can be referenced as if they were constants of
type text. They cannot be assigned any values.

The segments come in the traversal order of the message tree. The physical order in which the
statement lists appear in the control file does not affect the processing order, but for better main-
tainability, we recommend that the statement lists be written to reflect the order of the message.

The figure below shows the traversal order for a small subset of UN/EDIFACT INVOIC.2.912 where
there are two line items.

1 2 5 7

3 4 6

The segment statement list starts with the keyword segment, which is followed by the possible
location information. The segment statement list looks very much like the segment building
statement.

line (1:"HEADER")
segment UNH
! - - - - - - - - - - - - - - - - - - - -
! This is a segment building statement and
! must be contained in a statement list.
!
! Elements are assigned values.
!- - - - - - - - - - - - - - - - - - - - -
e0062 := "MSGREF"
endsegment
endline

TradeXpress ®
Generix Group - All rights reserved 73
EDI translation / Receiving EDI Messages

segment UNH
!- - - - - - - - - - - - - - - - - - - - -
! This is a segment statement list used
! in the receiving direction.
! It can contain any other statements except
! segment building statements.
!
! Elements values are printed to the
! application data file.
!- - - - - - - - - - - - - - - - - - - - -
print (e0062, NL)
endsegment

The segment statement list is executed separately for each occurrence of the identified seg-
ment. All elements belonging to the current segment can be referenced by their names (see
Naming the Elements earlier in this chapter), but elements in earlier segments must also contain
the segment name.

segment UNT
print (eBGM.C002.1000, NL)
! C an..35 Document/Message name
print (eUNH.0062, NL)
! M an..14 MESSAGE REFERENCE NUMBER
print (e0074, NL)
! M n..6 NUM OF SEGMENTS
endsegment

Only the latest occurrence of any received segment is available at any given time. For example,
you cannot reference elements in previous LIN segments while processing the current LIN. If the
data in given elements must be carried along, you can use text variables or text tables.

For a complete but compact example on receiving EDI messages, see the chapter 2 Tutorial Intro-
duction.

Decimal Separators
All decimal separators in numeric data elements are converted to the inhouse decimal separator
before the segments are delivered to the user statements. For more information, see Decimal
Separator Conversion in this chapter.

TradeXpress ®
Generix Group - All rights reserved 74
EDI translation / Receiving Direction Error Handling

Receiving Direction Error Handling

When erroneous messages are received, there are three ways to handle them:

• ignore erroneous messages completely


• handle erroneous messages in a separate routine
• handle erroneous messages in segment statement lists.
RTE provides two built-in functions, edierrorlist and edierrordump, that can be used to diagnose
erroneous messages. The statement skips over the remaining segments in the current message.

Ignoring Erroneous Messages


The default action is to ignore incoming erroneous messages completely. If the translator module
detects an erroneous message, it skips it and reads in the next message. The segment state-
ment lists are activated only by segments in valid messages.

Using a Separate Error Routine


You may want to get information about erroneous messages; their number, for example. If you
include a function called bfIncomingError in a program, all erroneous messages will be directed
to that routine. Below is an example of a bfIncomingError routine:

function bfIncomingError ()
edierrordump (MESSAGE)
exit (1)
endfunction

The bfIncomingError function must be the first user function that is defined.

bfIncomingError can provide for tasks such as counting, logging, and reacting to erroneous mes-
sages, but it does not give you access to the individual data segments. Therefore, this method
cannot be used when specific information about the message (for example, the message identi-
fier) must be retrieved from the segments.

Processing Erroneous Messages in Statement Lists


To gain access to the individual segments, you must process the erroneous messages in the seg-
ment statement lists. The translator module will deliver the segments to the segment statement
lists when the boolean variable PROCESS_ERRONEOUS is TRUE. The default value for this variable

TradeXpress ®
Generix Group - All rights reserved 75
EDI translation / Receiving Direction Error Handling

is FALSE. If PROCESS_ERRONEOUS is TRUE, it will override the bfIncomingError function, which will
no longer be called.

With this method, it is up to the user to detect and handle all erroneous messages. Either the
validity of the entire message can be checked in the first incoming segment (for example, UNH
for EDIFACT), or you can check the validity for each individual segment. These are just sugges-
tions; you can adopt any strategy that fits your needs and that can be implemented with the
tools you have available.

Preparing for the EDIFACT CONTRL Message


The following example shows how data can be collected for the EDIFACT CONTRL message. The
edierrorlist function provides all the error data for the segments, but in order to get to the mes-
sage header information, we need to process the UNH segment.

!- - - - - - - - - - - - - - - - - - -
! allow user’s error handling
!- - - - - - - - - - - - - - - - - - -
begin
PROCESS_ERRONEOUS:=TRUE
Endbegin
!- - - - - - - - - - - - - - - - - - -
! Verify the validity of the message
! in the very first segment.
!- - - - - - - - - - - - - - - - - - -
segment UNH
if valid (MESSAGE) = FALSE then
bfCONTRLsupport ()

endif
!- - - - - - - - - - - - - - - - - - - - - -
! Normal processing for UNH
!- - - - - - - - - - - - - - - - - - - - - -
endsegment

!- - - - - - - - - - - - - - - - - - -
! All other segment lists...
!- - - - - - - - - - - - - - - - - - -
!- - - - - - - - - - - - - - - - - - -
! Write error information to the log.
!- - - - - - - - - - - - - - - - - - -
function bfCONTRLsupport ()
!- - - - - - - - - - - - - - - - - - - - - -
! Write the start of a new
! message to the log file.
!- - - - - - - - - - - - - - - - - - - - - -
log ("*** CONTROL NEW ", eUNH.0062, ":", \
eUNH.S009.0065, ":", \
eUNH.S009.0052, ":", \
eUNH.S009.0054, ":", \
eUNH.S009.0051, NL)
!- - - - - - - - - - - - - - - - - - - - - -
! Write all error conditions and

TradeXpress ®
Generix Group - All rights reserved 76
EDI translation / Receiving Direction Error Handling

! skip the rest of the message.


!- - - - - - - - - - - - - - - - - - - - - -
edierrorlist (MESSAGE)

endfunction

Checking the Validity of a Segment


The validity of a single segment can be checked with the valid function in the same way that we
checked the message. The edierrordump and edierrorlist functions can also be applied to seg-
ments. Only the current segment and its errors are written to the log file.

segment UNH
if valid (SEGMENT) = FALSE then
log ("Segment UNH contained errors", NL)
edierrordump (SEGMENT)
endif
!- - - - - - - - - - - - - - - - - - - - - -
! Normal processing for UNH
!- - - - - - - - - - - - - - - - - - - - - -
endsegment

segment BGM
if valid (SEGMENT) = FALSE then
log ("Segment BGM contained errors", NL)
edierrordump (SEGMENT)
endif

!- - - - - - - - - - - - - - - - - - - - - -
! Normal processing for BGM
!- - - - - - - - - - - - - - - - - - - - - -
endsegment

Segment statement will be executed only if PROCESS_ERRONEOUS=TRUE (see section Process Erroneous Messages in State-
ment Lists)

Checking the Validity of a Group


The validity of a single group can be checked with the valid function in the same way that we
checked the message.

if valid (GROUP g25) = FALSE then


print ("Groupe non valide", NL)
else
print ("Groupe valide", NL)
endif

TradeXpress ®
Generix Group - All rights reserved 77
EDI translation / Receiving Direction Error Handling

Examples
The following INVOIC message contains three errors:

• The element 1233 in the first LIN segment is missing.


• The component 6063 in composite C186 in the second LIN segment is missing.
• Segment MOA, which starts group 15, is missing after the UNS segment.
UNH+123001+INVOIC:2:912:UN'
BGM+:::INVOICE FOR DISTRIBUTOR++3:930301:101'
LIN++1++3:007234110++1:1+INV:28.50'
LIN+1+2++3:007234150++:2+INV:120.00'
LIN+1+3++3:007234199++1:1+INV:28.50'
UNS+S'
UNT+8+123001'

The bfCONTRLsupport function in the example earlier in this chapter would produce the following
data in the log file. The first line results from the log function call that we made in bfCONTRLsup-
port. The last three lines are the output from the edierrorlist function.

*** CONTROL NEW 123001:INVOIC:2:912:UN


*** CONTROL ELEM 3:1:11:LIN:1233
*** CONTROL COMP 4:6:2:12:LIN:C186.6063
*** CONTROL MSG 7

The lines produced by the edierrorlist function are explained below. The common string “*** CON-
TROL ” at the beginning of each error line makes it simple to extract this data from the log file.

The segment that the error


appeared in was the third
The error appeared segment in this message
in an element

Name of the
element

*** CONTROL ELEM 3:1:11:LIN:1233

Name of the
segment

First element Error number 11


in the segment. (Missing mandatory element)

TradeXpress ®
Generix Group - All rights reserved 78
EDI translation / Receiving Direction Error Handling

The segment that the error


appeared in was the
fourth segment in this message.

Name of the component


The error appeared in and the enclosing
a component data element.
composite.

*** CONTROL COMP 4:6:2:12:LIN:C186.6063

Sixth element Name of the segment


in the segment.

Error number 12
Second component (Missing mandatory
in the composite. component)

The error cannot be attached to any individual


segment and thus appears on the message level.

*** CONTROL MSG 7

Error number 7
(Too few groups 15 (0), 1 minimum)

The edierrordump function outputs the message in EDI format, with all error messages attached
in the appropriate positions.

UNH+123001+INVOIC:2:912:UN'
BGM+:::INVOICE FOR DISTRIBUTOR++3:930301:101'
LIN++1++3:007234110++1:1+INV:28.50'
^ 1233: Missing mandatory element (11)
LIN+1+2++3:007234150++:2+INV:120.00'
^ C186.6063: Missing mandatory component (12)
LIN+1+3++3:007234199++1:1+INV:28.50'
UNS+S'
UNT+8+123001'
Too few groups 15 (0), 1 minimum

Error Codes
The meaningful error codes from the translator module are listed below. These error codes refer
to the contents of the messages either directly or indirectly. There are other error messages in
addition to these, but they relate more to the internal functions of the translating module.

1 Too much data in the element


3 Too short: %d minimum
4 Too many %s groups (%d), %d maximum
5 Too many %s segments (%d), %d maximum
6 Too long: %d maximum

TradeXpress ®
Generix Group - All rights reserved 79
EDI translation / Receiving Direction Error Handling

7 Too few groups %s (%d), %d minimum


8 Too few segments %s (%d), %d minimum
9 Cannot find character set %s.
11 Missing mandatory element
12 Missing mandatory component
16 Segment '%s' does not belong to the message
17 Excess data in the segment
20 Corrupted character set %s
21 Message contains errors
22 Segment contains errors
23 Invalid type %s field%s

TradeXpress ®
Generix Group - All rights reserved 80
6/ Input and Output

Standard Streams
Input
Output
Redirection
Buffered Output
Print List
Print Items
Print Format
Logging
File Variables

TradeXpress ®
Generix Group - All rights reserved 81
Input and Output / Standard Streams

Standard Streams

By default, an RTE program reads its standard input, outputs to standard output, and writes the
logging information to the standard error. In Unix systems, these file descriptors are inherited
from the parent process.

executable
translator

INPUT OUTPUT

Runtime LOGGING
environment

The RTE language provides an easy access to the file system.

TradeXpress ®
Generix Group - All rights reserved 82
Input and Output / Input

Input

The RTE programs are data driven by default. This means that the incoming data determines
which statement lists are executed, instead of the programs being linearly executed (although
this is possible, too).

Window Model
The data is read in line by line. The maximum line length is 4096 characters. Each line is com-
pared with the line matching rules for each line statement until a match is found. The rules are
checked in the order in which they appear in the source file. If there is no match, then the optional
default statement list is executed.

Any number of lines from the input file can be processed. The process matches the statements in
the statement list to the lines in the input file (“window”). These lines form an imaginary window
view of a file that is visible to the current statement list process. The lines in the window will not
be available to the next statement list. The system moves to the next unread line and does the
matching based on the rules in the statement list.

Picking
Pick is the built-in function used to read from a file. It always works relative to the line that
matched the matching rule for the statement list. The matched line is the first one in the window.

The following function call will read the entire first line from the window:

pick (1, 1, EOL)

The size of the window is always determined by the furthest pick. The size of the window is not
affected by whether or not all intermediate lines are explicitly read.

The following line statement list always processes two lines from the input.

line (1:"SAMPLE)
tTmp1 := pick (1, 1, EOL)
tTmp2 := pick (2, 1, EOL)
endline

Returning a Line
The internal variable RETURN_BUFFER can be used as an input replacement buffer. Assigning this
variable a value causes the program to read its content as the next input line. The content is auto-
matically erased after it has been used. Only one line can be returned.

TradeXpress ®
Generix Group - All rights reserved 83
Input and Output / Input

Line Numbers
The numeric constant LINE contains the current input line number. The value is meaningful only
when text data is being read.

End of File
The pick function returns the constant string EOF when end of file is encountered. An error mes-
sage is also written to the logging stream, and if the LOGLEVEL is high enough, the execution of
the program is terminated.

Read
The read function reads a line from a file or a process, and returns the line just read (or EOF if
there are no more lines). The file from which the lines are read must be closed before it can be
reread. It is also good practice to close all processes that are read from. The read function takes a
file name as its argument.

read (tFile)

The following example reads the /etc/passwd file and prints it.

tFile := "/etc/passwd"
print("List of registered users:", NL)
tLine := read(tFile)
while tLine <> EOF do
print(tLine,NL)
tLine := read(tFile)
endwhile
close(tFile)

The following example reads the machine name from the command uname, using it as a copro-
cess. Note the “|” character at the beginning of the command line.

tFile := "|uname -a"


tLine := read(tFile)
close(tFile)
print("Machine ", tLine, NL)

Redirection can also be used with the read function to redirect the input.

TradeXpress ®
Generix Group - All rights reserved 84
Input and Output / Output

Output

RTE supports two types of output: direct and buffered. Direct output writes the given text to the
output stream in the order in which the print functions are called in the program. Buffered output
allows you to build the file image in memory, and that image is then output to an actual file at the
desired time.

Printing
The built-in function print prints its arguments to standard output. The arguments are written as
a print list (see Print List later in this chapter). The output of a single print statement can be redi-
rected to a named file or process, as shown below.

! Print contents of tTMP plus a new line


print (tTMP, NL)

Newline Character
The text variable NL contains the line separator used by the internal functions that produce mul-
tiple lines. By default, this is the newline character (ASCII 012 in octal presentation). Note that the
print function does not automatically produce a new line; you have to include it in the print list.
The value of the NL variable can be set in the source code.

TradeXpress ®
Generix Group - All rights reserved 85
Input and Output / Redirection

Redirection

You can redirect the output from print commands to any file or coprocess by using the redirec-
tion symbols after the call to the print function.

print (print list) > tFilename


print (print list) >> tFilename

The symbol “>” opens the specified file in overwrite mode. A new file is created, or the possibly
existing file is truncated to length zero. The append symbol “>>” always writes after the current
end of file.

The symbols have a different meaning only at the first invocation of any redirected output. The
subsequent print statements redirected to the same file (or process) work in append mode. This
is illustrated in the following example.

begin
!- - - - - - - - - - - - - - - - -
! This call creates file "/tmp/file"
! or truncates it if it existed.
!- - - - - - - - - - - - - - - - -
print ("Input lines:", NL) > "/tmp/file"
endbegin

default
!- - - - - - - - - - - - - - - - -
! This call continues to write to
! the same file ("/tmp/file")
!- - - - - - - - - - - - - - - - -
print (pick (1, 1, EOL), NL) > "/tmp/file"
enddefault

end
!- - - - - - - - - - - - - - - - -
! Close the file "/tmp/file".
!- - - - - - - - - - - - - - - - -
close ("/tmp/file")
endend

This program appends another line to the file created in the previous example and then reads that
file line by line.

begin
!- - - - - - - - - - - - - - - - -
! This call opens file "/tmp/file"
! in append mode.
!- - - - - - - - - - - - - - - - -
print ("ANOTHER PROGRAM:", NL) >> "/tmp/file"
close ("/tmp/file")
!- - - - - - - - - - - - - - - - -
! Start reading from the same file.

TradeXpress ®
Generix Group - All rights reserved 86
Input and Output / Redirection

! Note that we closed the file so


! that all data will be available.
!- - - - - - - - - - - - - - - - -
tLine := read ("/tmp/file")
while tLine <> EOF do
log (tLine, NL)
tLine := read ("/tmp/file")
endwhile
close ("/tmp/file")
endbegin

The file name must be the same for each statement; even one extra space in front of a file name
will cause the system to regard it as a different file. This approach avoids file descriptors and low-
level file handling routines, but in return requires the user to be very precise and careful with file
names. A safe way to handle multiple redirections is to store the used file name in a text variable
and use that variable globally.

The file can be closed with the close function. All operating system buffers are flushed to the disk
and the internal file descriptor is returned for reuse. Files do not have to be closed, but note the
following: if you first write to a file and then plan to read from the same file, you must close it to
be sure that all the lines you wrote are indeed in the file. Another reason for closing files is that
they are a limited resource: only 40 different files can be in use at any given time.

Using Coprocesses
In addition to regular files, the output can be redirected to a coprocess. This means that there will
be another process running and the output is redirected to the standard input of that process.

A coprocess is indicated by a “|” character as the first character in the file name. No spaces are
allowed before the “pipe” indicator. The file name may be a complete shell command line with its
own arguments.
print ("TESTMESSAGE", NL) > "|mailx friend@machine"
print ("See you tonite!", NL) > "|mailx
friend@machine"
close ("|mailx friend@machine")

The file name must be exactly the same after each statement; otherwise a new coprocess is cre-
ated. It pays to use a text variable instead of always writing out the entire command line.

tMailer := "|mailx friend@machine"


print ("TESTMESSAGE", NL) > tMailer
print ("See you tonite!", NL) > tMailer
close (tMailer)
The read function can also read output from another program. In the example below, we read
lines from the program tr (a Unix character translator utility) that in turn reads the file /tmp/file.

tToLower := "|tr \"[A-Z]\" \"[a-z]\" < /tmp/file"


tLine := read (tToLower)
while tLine <> EOF do
...

TradeXpress ®
Generix Group - All rights reserved 87
Input and Output / Redirection

tLine := read (tToLower)


endwhile

Redirecting the Standard Streams


The standard streams can be directed to a regular file or a coprocess. The redirect function
reopens the given stream and the file assigned to the stream is read/written from the beginning.

redirect (INPUT, tFilename)


redirect (OUTPUT, tFilename)
redirect (LOGGING, tFilename)

The following example reads the input from a Unix utility, strings, and prints the lines to the sort
program. Logging is closed so nothing will be written to the standard error stream.

begin
redirect (INPUT, "| strings /tmp/exefile")
close (LOGGING)
redirect (OUTPUT, "| sort >/tmp/strings.sorted")
endbegin

default
print (pick (1, 1, EOL), NL)
enddefault

TradeXpress ®
Generix Group - All rights reserved 88
Input and Output / Buffered Output

Buffered Output

Buffered output lets you print data to the output in non-linear order. The buffer is filled with the
put function and printed with the flush function.

Putting Text in the Buffer


In the put function, the line and column of the output buffer are given as arguments.

put (nLine, nPos, print item)

Arguments nLine and nPos are numeric values and the print item can be either a number or text
value. The print item can also have a format definition. See the description of the print item later
in this chapter.

put (1, 1, "ordinary")


put (nTmp, nColumn + 2, 38)
put (nTmp + 1, nColumn, nCount:10.2)

If there are untouched areas in the output, they are filled with the FILL_CHAR character. For exam-
ple, if the line text does not begin in the first column or is shorter than the specified minimum
width, the filling mechanism is used. By default, FILL_CHAR is the space character, but it can be
set to any character in the RTE program.

FILL_CHAR := "#"

If print formats are used, the fill character for those formats is always a space.

put (1, 1, "Begin":5)

The previous example prints the text “Begin” at the beginning of the first line in the output buffer,
followed by five spaces. These characters are not considered an untouched area and are not
filled with the FILL_CHAR character.

The buffer used by the put function can be set to a user-defined buffer. The buffer type is text
array.

put (taArray, nLine, nPos, print item)


put (taTmp, 1, nColumn, tText)

TradeXpress ®
Generix Group - All rights reserved 89
Input and Output / Buffered Output

Flushing the Output Buffer


The content of the output buffer is written with the flush function. The flush function takes the
line minimum length, line maximum length, and line separator character as arguments.

flush ( nMin, nMax, tSeparator)


flush ( taArray, nMin, nMax, tSeparator)

nMin and nMax are numeric values. If their value is zero, they have no meaning. Otherwise they
behave as follows.

• min - All printed lines contain at least nMin characters. If the line contains fewer characters
than nMin, the line is filled with the FILL_CHAR character.
• max - Only nMax characters are printed per line. If the line has more than nMax characters, the
entire line and the descriptive error message are printed in the logging stream. The printed
line contains only nMax characters.
flush (80, 0, NL)
flush (0, 80, NL)
flush (72, 72, NL)

Flush works only with those buffers that are filled with the put function. Other buffers (arrays)
can be printed with the print function.

The buffer can be flushed to file with the redirection mechanisms.

flush (80, 0, NL) > "lines"


flush (0, 80, NL) >> "lines"
flush (72, 72, NL) > "| teletex 564221"

The buffer content is destroyed after flush is completed. If the user wants to keep the buffer con-
tents after the flush operation, the RTE program must be compiled with the -w option. When the
buffer is no longer needed, it can be removed with the remove function.

If no buffer name is given in the put function, the default buffer is used (BUFFER).

Examples
FILL_CHAR := "#"
put (1, 4, "BEGIN")
put (1, 12, "END")
flush (20, 20, NL)

###BEGIN###END######
FILL_CHAR := "#"
put (1, 4, "BEGIN":6)
put (1, 12, "END")
flush (20, 20, NL)

###BEGIN ##END######

TradeXpress ®
Generix Group - All rights reserved 90
Input and Output / Buffered Output

nNumber := 345.67
put (1, 1, nNumber:08.3)
put (2, 1, nNumber)
put (2, 6, "OVERRUN")
flush (0, 0, NL)

0345.670
345.6OVERRUN

TradeXpress ®
Generix Group - All rights reserved 91
Input and Output / Print List

Print List

The following built-in functions use a print list:

• print
• log
• debug
• build.
The print list consists of printable items separated with commas. The number of items is unlim-
ited. There is no automatic line feed in any of the printing functions.

print ("The total sum is ", nTOTAL, " FMK", NL)

TradeXpress ®
Generix Group - All rights reserved 92
Input and Output / Print Items

Print Items

Print items are text and numeric values. A print format specification can be added in all allowed
contexts. Print items are used in print lists and in the put function.

TradeXpress ®
Generix Group - All rights reserved 93
Input and Output / Print Format

Print Format

Print format can be used with print items. The format always begins with a colon immediately fol-
lowing the print item. The min and max values can be either constant numbers, or “*” characters
indicating that the value is to be evaluated at run time from the following argument.

Text Print Format


The formal presentation for the text print format is:

:[LR]min[.max]

where the colon and the value that specifies the minimum width are mandatory. Optionally, a let-
ter can immediately follow the colon to indicate justification. The possible values are:

L left justification
R right justification

For text data, a missing justification specification will result in left justification. The optional max-
imum length is separated with a period (“.”) from the minimum width value. The max value dic-
tates the maximum number of characters that will be extracted from the text argument.

"TEXT":8 "TEXT "


"TEXT":L8 "TEXT "
"TEXT":8.2 "TE "
"TEXT":L8.2 "TE "

"TEXT":*, 6 "TEXT "


"TEXT":L*, 6 "TEXT "
"TEXT":L*.*, 6, 3 "TEX "

"TEXT":R8 "TEXT "


"TEXT":R8.2 "TE "
"TEXT":R*, 6 "TEXT "
"TEXT":R*.*, 6, 3 "TEX "

Numeric Print Format


Numeric print format is the following:

:[LR][0]min[.decimals]

The starting colon and the minimum width are mandatory. A possible decimal separator is
included in the total width. Before the width specification, the letter R or L can indicate justifica-
tion, and the character “0” can indicate filling with zeroes. For numeric data, default justification is
to the right. The number of decimals can be specified in the last field, separated by a period (“.”)
from the minimum width value.

TradeXpress ®
Generix Group - All rights reserved 94
Input and Output / Print Format

nVALUE := 345.67
nVALUE "345.67 "
nVALUE:8 " 345.67"
nVALUE:08 "00345.67"
nVALUE:R8 " 345.67"
nVALUE:R08 "00345.67"
nVALUE:8.3 " 345.670"
nVALUE:08.3 "0345.670"
nVALUE:L8 "345.67 "
nVALUE:L08 "345.67 "
nVALUE:L8.3 "345.670 "

Time Printing
Time values are printed with the time function, which returns the time in the requested text for-
mat. For full details on how to use this function, see the chapter 9, section Functions Reference,
time.

print (time ("%d.%m.%y"), NL)


print (ENTRY.EXPIRES, "%y%m%d%H%S", NL)

The format string can contain regular characters, in addition to the following special fields.

print (time ("Just now the time is %H:%S"), NL)

Fields with special meaning in time printing are:

%T Time in AM/PM notation (HH:MM AM|PM)


%t Time in AM/PM notation (HH:MM:SS AM|PM)

%M Minutes (00-59)
%H Hours (00-24)
%S Seconds (00-59)
%d Day of the month (01-31)
%m Month of the year (01-12)
%y Year in two digits (..98,99,00,01..)
%Y Absolute year

%N Month of the year in long format


(e.g. January)
%n Month of the year in short format
(e.g. Jan)

%W Day of the week in long format


(e.g. Monday)
%w Day of the week in abbreviated format
(e.g. Mon)
%k Week of the year (1 - 53)
%j Day of the year (1 - 366)
%a Absolute value
(in seconds since Jan 1, 1970 GMT)
%eM Elapsed minutes to current system time
%eH Elapsed hours
%ed Elapsed days
%ew Elapsed weeks

TradeXpress ®
Generix Group - All rights reserved 95
Input and Output / Print Format

A negative value in elapsed time indicates that the given time is in the future.

TradeXpress ®
Generix Group - All rights reserved 96
Input and Output / Logging

Logging

Logging can be used to track the execution of a program and to collect applicable information for
later review. The logging stream is by default the standard error.

• log
• debug
The LOGLEVEL numeric variable indicates the logging level being used. The values are interpreted
as follows:

• 0 - No system warnings are written and the debug commands are not active.
• 1 - All system warnings are written to the logging stream.
• 2 - The debug commands are active.
• 3 - All system warnings are considered fatal and the execution of the entire program is termi-
nated.
The higher values imply the lower values. For example, at level two, in addition to the debug com-
mands, the system warnings are also active.

The initial value can also be set with the command line option -l.

The logging stream is by default the standard error. It can be directed to another file or process
with the redirect command.

redirect (LOGGING, "/tmp/log")


redirect (LOGGING, "| grep ERROR > /tmp/errors")

If you do not want to see any logging information, the logging stream can also be closed.

close (LOGGING)

After closing the logging stream, you can reopen it to the desired file.

redirect (LOGGING, "/tmp/newlog")

TradeXpress ®
Generix Group - All rights reserved 97
Input and Output / File Variables

File Variables

Files and their attributes can be accessed conveniently with file variables. A file variable is an
identifier that can be used alone as an argument to the built-in functions print, log, debug and
remove.

File Attributes
The following table lists all the possible file attributes. The data type and a short explanation are
provided for each attribute.

Name Type Description

EXIST BOOLEAN Is true if the file exists. This is a useful attribute to check before doing any
other operations on the file.

NAME TEXT Contains the name component of the file.

PATH TEXT Contains the path component of the file.

FULLNAME TEXT Contains the full name of the file.

OWNER TEXT Contains the user name of the file owner.

GROUP TEXT Contains the owner group for the file.

SIZE NUMBER Contains the number of bytes in the specified file.

LINES NUMBER Contains the number of lines in the file. For non-ASCII files, this value is mean-
ingless.

ATIME TIME Time of last access to the file. This information is updated every time the data
in the file is accessed.

MTIME TIME Time of last data modification. This information is updated every time the data
in the file is modified.

CTIME TIME Creation time.

READ BOOLEAN Is true if the user has a read access to the file.

WRITE BOOLEAN Is true if the user has a write access to the file.

EXEC BOOLEAN Is true if the user has an execute access to the file.

TYPE TEXT Contains either “REGULAR” for regular files, “DIRECTORY” for directories, or
“SPECIAL” for any other types.

CONTENT TEXT This value is retrieved from an external program that is used to determine file
content.

TradeXpress ®
Generix Group - All rights reserved 98
Input and Output / File Variables

Assignment
File variable assignment is as follows:

fFile := tFileName

Where fFile is the file variable and tFileName is the name of the file.

The file variable can also be assigned in the while statement:

while fFile in "/usr/tmp/A*" do


!
! File manipulation actions.
! Here the fFile variable gets a different
! content for each loop.
endwhile

Usage
A file variable is most useful in the following situations:

• file existence and permission checks


fFile := tOutputFile
if fFile.EXIST = TRUE then
print ("File exists", NL)
endif

• file name manipulation; for example, base name and directory name extractions
fFile := tTestFile
print ("Filename: ", fFile.NAME)
print ("Dirname : ", fFile.PATH)
print ("Fullname: ", fFile.FULLNAME)

• directory scanning for selected files


while fFile in "/usr/tmp/A*" do
print ("File: ", fFile.NAME)
endwhile

• getting the file size in bytes


fFile := tTestFile
print ("Size: ", fFile.SIZE, " bytes")

TradeXpress ®
Generix Group - All rights reserved 99
7/ Database Interface

Background Information
Definition
Database Fields
Database Files
Finding an Entry
Creating a New Entry
Removing an Entry

TradeXpress ®
Generix Group - All rights reserved 100
Database Interface / Background Information

Background Information

An EDIBASE database is a small general purpose database system designed to provide easy
access to textual, numeric, and time data. The data consists of key fields and an undefined
amount of additional information stored in related files. The EDIBASE database system contains
an interface to RTE and a command line package. Only the RTE interface is covered here.

The key fields must be defined in the configuration file. The number of related files does not have
to be known at configuration time. Below is a sample configuration file:

#==============================================
# User defined fields.
#==============================================
FIELD=NAME,16,%-16.16s, Name
FIELD=ADDRESS,32,%-32.32s, Address
FIELD=AGE,N,%3.0lf, Age
FIELD=EXPIRES,T,%d.%m.%Y %H:%M, Order expires
#=============================================
# Our names for the standard system fields.
#=============================================
INDEX=INDEX,%4.0lf,
MTIME=MODIFIED,%d.%m.%Y %H:%M, Modified
CTIME=CREATED,%d.%m.%Y %H:%M, Created

The configuration file specifies that the database contains four user-defined key fields: NAME,
ADDRESS, AGE, and EXPIRES. NAME is text and contains a maximum of 16 characters. ADDRESS is
also text but can contain up to 32 characters. AGE is numeric and EXPIRES is a time field. The two
last comma-separated fields for each definition contain the default output format and the header
for that column. Only the default print format for time fields is applicable to RTE; otherwise these
two fields affect the command line package.

Each EDIBASE database contains the fields INDEX, MTIME, and CTIME. These fields are controlled
by the system: they can be referenced by the user but no values can be assigned to them. In the
configuration file, the user can give new names to these fields.

TradeXpress ®
Generix Group - All rights reserved 101
Database Interface / Definition

Definition

Unlike all other variables, the database entries must be defined at the beginning of the program.

base "/usr/tmp/mybase.cfg" ENTRY

Several entries can be given in the same base statement.

base "/usr/tmp/mybase.cfg" ENTRY1 ENTRY2

Several base statements can exist in one RTE program file.

base "/usr/tmp/mybase.cfg" MY_ENTRY


base "/usr/tmp/extrabase.cfg" EXTRA_ENTRY

The following options are possible:

• readonly
• autoflush (on/off)
• default (on/off)
The database definition shown above causes the configuration file to be read into the RTE com-
piler. If the definition does not contain the complete path, it is assumed to be relative to the
$HOME/database or (on a secondary basis) the $EDIHOME/database directory.

TradeXpress ®
Generix Group - All rights reserved 102
Database Interface / Database Fields

Database Fields

Database fields are referenced by specifying the entry and the field name, separated by a period.
These fields can now be used anywhere a variable of the same type can be used.

If text is assigned to the text field and the text is longer than the field, the value is truncated to
the maximum length. This is not an error situation in RTE and no error or warning messages are
printed.

Field Description

ENTRY.NAME Corresponds to a text variable.

ENTRY.NAME := pick (1, 1, EOL)


print (ENTRY.NAME, NL)

ENTRY.ADDRESS Corresponds to a text variable.

ENTRY.ADDRESS := tfGetAddress(ENTRY.NAME)
log (“Address is “, ENTRY.ADDRESS, NL)

ENTRY.AGE Corresponds to a numeric variable.

ENTRY.AGE := 38
nYearsToWork := 65 - ENTRY.AGE

ENTRY.EXPIRES Type time. The values for this field are assigned with a text expression. The
value can be referenced with the time function.

ENTRY.EXPIRES := “1.10.1994”
print (time (ENTRY.EXPIRES), NL)

TradeXpress ®
Generix Group - All rights reserved 103
Database Interface / Database Files

Database Files

Files related to a database entry are referenced by specifying the entry identifier and the file
extension, separated by a period. The actual physical file name and path are hidden from the
user.

ENTRY ENTRY.data

ENTRY.info
.
.
. ENTRY.log

TradeXpress ®
Generix Group - All rights reserved 104
Database Interface / Finding an Entry

Finding an Entry

The function find is used to assign a database identifier to an actual database entry. The database
given as an argument must be an actual EDIBASE database and its schema must match the defi-
nition.
ENTRY := find (database name [, filter]) [sort field]

The database name must specify the complete path for the physical database. If the path does
not start from the root directory, it is assumed to be relative to the $HOME environment variable.
All the examples in this chapter assume that there is a database called “mybase” in the user’s
home directory.

The filter can consist of one or more specifications that are in the format:

field op value

Field must be included in the defined database. Operator can be:

• “=” and “<>” for type TEXT


• “<”, “<=”, “>=”, or “>” for NUMERIC and TIME fields
With text fields, comparisons can be done with wild card characters.

NAME="RISC*"

Several comparison operations can be given. If more than one operation is given, the operations
are gathered with the logical operator AND. The same field can be used as many times as needed.

find ("mybase", NAME="myname", AGE<10)

If more complex filters are needed, users can write their own code to handle the comparison
operations. For example, you can implement the logical operator OR by retrieving all entries and
doing the comparison in the RTE code.

while ENTRY in ("mybase") do


if (ENTRY.NAME=”myname” or ENTRY.SIZE<10) then
!
! Matching actions.
!
endif
endwhile

The sort field specifies the sort order. The order can be either ascending or descending. A lower
case “a” in front of the field name defines it as ascending; a lower case “d” defines it as descend-
ing.

TradeXpress ®
Generix Group - All rights reserved 105
Database Interface / Finding an Entry

aNAME
dEXPIRES

The ENTRY identifier is assigned the first entry that matches the given filter. If no sort field is
specified, the index is used as the sort key. Find does not support secondary sort keys.

If the filter matches more than one entry in the database, you can retrieve the next entries by
calling the find function with no arguments. The same filter and sort order are applied as in the
previous call to find, with the same ENTRY identifier. Assigned values to different identifiers from
the same database operate independently from each other.

ENTRY := find ()

The existence of an entry in a database can be checked with the valid function.

ENTRY := find ("mybase", NAME="myname")


if valid (ENTRY) = FALSE then
log ("Could not find an entry.", NL)
endif

Using an ENTRY without checking its validity causes the system to write error messages to the
logging stream.

TradeXpress ®
Generix Group - All rights reserved 106
Database Interface / Creating a New Entry

Creating a New Entry

A new entry to a database can be created with the new function. It takes as its only parameter the
name of the actual database.

ENTRY := new (database name)

The initial values are assigned after the call to the new function.

ENTRY := new ("mybase")


ENTRY.NAME := "myname"
ENTRY.ADDRESS := "myaddress"
ENTRY.AGE := 45
ENTRY.EXPIRES := "now+10d"

print ("Created :", time (ENTRY.CREATED), NL) > ENTRY.log

TradeXpress ®
Generix Group - All rights reserved 107
Database Interface / Removing an Entry

Removing an Entry

To remove an entry from the database, call the general purpose function remove with the data-
base identifier as the only argument.

remove (ENTRY)

This call removes the key information and all related files.

The following example shows how all entries that have been created over three days are removed
from the database.
while ENTRY in ("mybase", CREATED < "now - 3d") do
remove (ENTRY)
endwhile

TradeXpress ®
Generix Group - All rights reserved 108
8/ Running RTE Programs

Overview
Parameters
Arguments
Startup File

TradeXpress ®
Generix Group - All rights reserved 109
Running RTE Programs / Overview

Overview

An RTE program command line can contain options, parameters, and arguments. All options must
be specified before the parameters, which in turn must appear before any free form arguments.

$ program [options] [parameters] [arguments]

Options
Options can be either user options or system-specified control options. An option is a one-letter
flag preceded by a minus sign.

User options are always upper case letters from A to Z. You have access to 26 option variables in
an RTE program. The option variables are named oA to oZ. By default, these options contain the
value FALSE. When you give an option on the command line, the value automatically becomes
TRUE.

begin
if oA = TRUE then
print ("Option A selected.", NL)
else
print ("Option A not selected", NL)
endif
endbegin

$ myprog -A
Option A selected

$ myprog
Option A not selected

System options are written in lower case letters and they are mainly used to initialize system
variables.

The following list includes all the system options.

l Sets the logging level; that is, gives an initial value to the variable LOGLEVEL.

c Specifies the character set file that is to be used in the translation.

d Specifies the path component for the character set file. This option can repeat up to
sixteen times and the directories are searched in the specified order. The current
working directory is always checked last.

f Takes the input from the following file.

TradeXpress ®
Generix Group - All rights reserved 110
Running RTE Programs / Overview

p Reads the parameters from the following file name. The parameters must be specified
as name-value pairs and the separator is an equal sign. The parameters, possibly
changed, are written back to this file at the termination of the program.

s Sets the separators to contain the following values. The values are specified as one
character string containing CS, ES, ST, RC, and optionally also TS and RS.

CS - Component separator. Used in EDIFACT to separate component data


elements.

ES - Element separator. Used in all grammars to separate data elements.

ST - Segment terminator. Used in all grammars to indicate the end of a data


segment.

RC - Release character. Used in all EDI grammars (except ANSI X12) to


cancel the special function of a reserved charac-ter in data.

TS - Tag separator. Used in GTDI to separate the segment tag from the actual
data. If this is not specified, the value from the element separator is used here.

RS - Repetition Separator. Used in ANSI X12 to separate repeating stan-


dalone or composite data.

a Sets the application decimal separator to the following value.

m Sets the message decimal separator to the following value.

i Prints information about the program. This information is collected from the source
file comments that start with a percent sign.

q Cancels the updating of the possible parameter file at the termination of the program.

b Sets the output and logging to be unbuffered. The default is to use system-defined I/O
buffers for all input and output.

TradeXpress ®
Generix Group - All rights reserved 111
Running RTE Programs / Parameters

Parameters

Parameters are special text variables in RTE. Parameters are name-value pairs that can get their
value from a named file and/or from the command line. They are referenced with the parameter
name preceded by a lower case “p.”

begin
if pFILE = EMPTY then
log ("No file given.", NL)
exit (1)
else
print ("File was ", pFILE, ".", NL)
endif
endbegin

$ myprog FILE=tmp001
File was tmp001.

$ myprog
No file given.

Assume the content of the file params is as follows:

FILE=tmp002
ACTION=remove

The parameters can be read from a specified file. They must be specified as name-value pairs,
one per line, and the separator is the equal sign.

$ myprog -p params
File was tmp002.

If the parameters were read from a file, they are automatically written back to the same file when
the program terminates. The parameters set on the command line and those created in the pro-
gram are also written to the file. If the command line contains the -q option, the parameter file is
not updated. After the call:

$ myprog -p params NEW=newparam

the file params has the following content:

ACTION=remove
FILE=tmp002
NEW=newparam

Finally, if the source for myprog is changed to contain the creation of a new parameter:

begin
if pFILE = EMPTY then
log ("No file given.", NL)

TradeXpress ®
Generix Group - All rights reserved 112
Running RTE Programs / Parameters

exit (1)
else
print ("File was ", pFILE, ".", NL)
endif
pMADE_IN_PROGRAM := "Created in the program"
endbegin

then after running the following command line (assuming that the file params contains what
was put there in the previous example):

$ myprog -p params NEWEST=another

the file params now has the following content:

ACTION=remove
FILE=tmp002
MADE_IN_PROGRAM=Created in the program
NEW=newparam
NEWEST=another

TradeXpress ®
Generix Group - All rights reserved 113
Running RTE Programs / Arguments

Arguments

Free form arguments come after all the options and parameters on the command line. RTE con-
tains two built-in variables to control the arguments:

ARGC A numeric variable that contains the number of arguments given to the program. The
ARGV[0] variable is not counted in this number.

ARGV A text array that contains all the arguments. ARGV[0] is the name of the program and
must always be present. The other arguments are from ARGV[1] to ARGV[ARGC].

The options and parameters are not counted as arguments and do not appear in the ARGV vari-
able.

begin
print (ARGC, NL)
print (ARGV)
endbegin

$ myprog -A -l3 NEWPARAM=test first second


2

0001=first
0002=second

TradeXpress ®
Generix Group - All rights reserved 114
Running RTE Programs / Startup File

Startup File

When an RTE program is started, the user’s home directory is checked for a special startup file.
The file is named .RTErc and it contains initial values for three different purposes. The startup file
is optional and no error message is produced if it does not exist. The three different categories
are described below.

EDI exceptions

These values specify which types of EDI translation exceptions are ignored and which
ones cause an error condition. The default for each exception is to cause an error
condition.

Initial values

Initial values can be given to decimal separators and the logging level. These values
are overwritten if other values are given on the command line and in the code.

System tuning

These values affect the program’s behavior. The value ARRAY_ INDEX_WIDTH specifies
the way in which numeric array indexes are converted to text indexes. The value
CODE_CONVERSION_BUFFER specifies how many lines of the code conversion files are
kept in memory.

EOF_STRING

Contains the text string that is used to signal the end of file condition. This needs to be
changed only if the processed data may contain the default indicator “__EOF__”.

A sample startup file.

#- - - - - - - - - - - - - - - - - - #
@ (#)TradeXpress RTE start-up file
# Exceptions causing an error in segment
# translation.
#- - - - - - - - - - - - - - - - - - -
INVALID_CONTENT=1
MISSING_ELEMENTS=1
MISSING_COMPONENTS=1
EXCESS_COMPONENTS=1
EXCESS_ELEMENTS=1
TOO_LONG_ELEMENTS=1
TOO_SHORT_ELEMENTS=1
MISSING_SEGMENTS=1
MISSING_GROUPS=1
TOO_MANY_SEGMENTS=1

TradeXpress ®
Generix Group - All rights reserved 115
Running RTE Programs / Startup File

TOO_MANY_GROUPS=1
GARBAGE_OUTSIDE=1
GARBAGE_INSIDE=1
EMPTY_SEGMENTS=1
PACK_COMPONENTS=1
PACK_ELEMENTS=1
#- - - - - - - - - - - - - - - - - - -
# Defaults for selected values.
#- - - - - - - - - - - - - - - - - - -
INHOUSE_DECIMAL_SEP=.
MESSAGE_DECIMAL_SEP=.
LOGGING_LEVEL=1
#- - - - - - - - - - - - - - - - - - -
# System tuning.
#- - - - - - - - - - - - - - - - - - -
ARRAY_INDEX_WIDTH=4
CODE_CONVERSION_BUFFER=1024
EOF_STRING=__EOF__

TradeXpress ®
Generix Group - All rights reserved 116
9/ Built-in Functions Reference

Overview
Function Categories
Functions Reference

TradeXpress ®
Generix Group - All rights reserved 117
Built-in Functions Reference / Overview

Overview

This chapter provides a reference for every RTE built-in function and gives the following informa-
tion for each function.

Usage A function prototype with explanatory arguments.

Arguments A detailed description of each argument.

Returns A description of the return value.

Description A comprehensive description of the function.

See also References to the functions related to this topic.

Example One or two examples of the most common function usage.

The functions are arranged in alphabetical order.

TradeXpress ®
Generix Group - All rights reserved 118
Built-in Functions Reference / Function Categories

Function Categories

The functions are grouped in categories depending on their nature and behavior. These catego-
ries and their functions are described in the following sections.

Process Control
The process control functions are related to Unix processes. They allow the user to run programs
from the RTE program in a similar way to running programs in Unix.

Function Description

background Creates a new process and executes


the given command as a daemon
process.

exec Executes the command by replacing


the existing process.

exit Terminates the current process.

spawn Executes the command and waits


until the process ends.

system Executes the given command with


the shell.

Text Handling
The text functions are used with text strings. They allow the user to create, manipulate, and
transform text strings in various ways.

Function Description

build Constructs a new string from given


strings.

compare Compares text strings.

index Finds the location of a given character


in the given string.

length Counts the characters in the given


string.

number Transforms a string to a number.

peel Peels unwanted characters from the


given string.

TradeXpress ®
Generix Group - All rights reserved 119
Built-in Functions Reference / Function Categories

Function Description

replace Replaces given characters in the given


string.

split Splits the given string.

strip Strips the given characters from the


given string.

substr Extracts a substring from the given


string.

toupper Transforms lower case letters to


uppercase letters.

tolower Transforms upper case letters to lower


case letters.

File Handling
The file handling functions allow the user to manipulate files in the Unix file system. See also the
chapter 6 Input and Output, for a more comprehensive description of all the RTE file handling
capabilities.

Function Description

close Closes the given file.

copy Copies the given file to another file.

link Creates a new link to the given file.

redirect Redirects the given i/o stream.

remove Removes the given file.

rename Renames the given file.

Output
The functions in this category allow the user to write to various targets. The functions can handle
different data types automatically, such as strings, arrays, and so on. See Chapter 6, Input and
Output, for a more comprehensive description of RTE I/O mechanisms.

Function Description

debug Writes a message to the logging


stream depending on the logging
level.

TradeXpress ®
Generix Group - All rights reserved 120
Built-in Functions Reference / Function Categories

Function Description

edierrorlist Writes an error list of the EDI errors


found to the logging stream.

edierrordump Writes the erroneous EDI message to


the logging stream.

flush Flushes the given buffers built with


the put function.

log Writes the given text to the logging


stream.

print Writes the given text to standard out-


put.

put Writes the given text to a buffer.

Database Access
RTE contains functions used to access the TradeXpress database system. Databases and pro-
gramming with databases is explained in the chapter 7 Database Interface.

Function Description

find Finds an entry in the given database


with the given filter.

new Creates a new entry in the given data-


base.

Input
The functions in this category allow the user to read data from various sources. The functions can
handle different data types automatically, such as strings, arrays, name-value pairs, and so on.
See the chapter 6 Input and Output, for a more comprehensive description of RTE I/O mecha-
nisms.

Function Description

load Loads name-value pairs from the given


file.

pick Picks a text string from the given posi-


tion in the current input window.

read Reads a line from the given file or pro-


cess.

TradeXpress ®
Generix Group - All rights reserved 121
Built-in Functions Reference / Function Categories

Multi Purpose
Some of the RTE functions can handle different types of arguments. The function’s behavior and
actions depend on the given argument type.

Function Description

remove Removes the given object.

valid Checks the validity of the given object.

Time
RTE has access to the system time, which can be fetched with the time function. The time print
format conversion is also supplied.

Function Description

time Converts system time, file access times,


database times, or user-given times to
text.

TradeXpress ®
Generix Group - All rights reserved 122
Built-in Functions Reference / Functions Reference

Functions Reference

The rest of this chapter contains documentation for all the RTE functions.

background
Usage
background (tCommand, taArgs, tStdin, tStdout, tStderr)

Arguments
tCommand command to execute

taArgs argument list for the command

tStdin text file to be fed in to process standard input

tStdout writes data from the standard output to a text file

tStderr writes data from the standard error list to a text file

Returns
Nothing.

Description
Creates a new process that runs the program specified by tCommand as a daemon. Items in the
table taArgs are given as arguments to the program. The standard file descriptors stdin, stdout,
and stderr are redirected to files specified by the respective arguments.

The process will become a child of the unit process and all relationships with this process are ter-
minated.

See also
exec, spawn, system

Example

build
Usage
build ( print list )

TradeXpress ®
Generix Group - All rights reserved 123
Built-in Functions Reference / Functions Reference

begin
! Run the mailchecker process as a daemon process
! with environment variable LOGIN and number 60 as
! arguments.
!
taArgs[1] := sLOGIN
taArgs[2] := “60”
background (“mailchecker”, taArgs, “/dev/null”, \
“/dev/null”, “/dev/null”)
endbegin
Arguments
print list

See the chapter 6 Input and Output, for a print list description.

Returns
A new text string.

Description
Combines all print items in the print list to form a single text, and returns it. This is similar to the
print function, but the result is returned as a value instead of being printed to a file.

This function is used with a single numeric argument to convert from numeric representation to
text format.

See also
Print list

Note
The resulting text string cannot be more than eight kilobytes in size. Longer strings result in
internal buffer overflow and immediate termination of the program.

Any print format enhancement can be used.

Example
begin
! Build database name for later use.
! Variable sHOME refers to environment
! variable HOME
!
tBASE := build(sHOME, “/example”)
! Build logfile name and redirect logging
redirect(LOGGING, build(time(“%y%m%d”), “.log”))
endbegin

TradeXpress ®
Generix Group - All rights reserved 124
Built-in Functions Reference / Functions Reference

close
Usage
close (tFile)

Arguments
tFilefile name to be closed

Returns
Exit code of the waited process, if tFile is a process.

Description
Closes the file tFile. All data buffered by the operating system is written to the named file, and
internally the file descriptor is released for reuse. If tFile is a process, then it is terminated and
waited for. The exit code of the process is returned.

A subsequent write or read to the same file identifier causes the file to be reopened or, in the case
of a process, the process to be restarted.

The argument tFile can also specify any of the built-in streams (INPUT, OUTPUT, LOGGING).

Note
If the user has written to a file and wants to read from that file, the file must be closed first.

See also
print, read, redirect

Example
end
! Print the ending time and close the file
print(“Ending time “, time(), NL) > tFile
close(tFile)
endend

compare
Usage
compare (tObject, tWildcard)

Arguments
tObject text to be compared

tWildcard comparison text

TradeXpress ®
Generix Group - All rights reserved 125
Built-in Functions Reference / Functions Reference

Returns
Boolean value TRUE if matched and FALSE otherwise.

Description
Compares the text tObject with the text tWildcard and returns TRUE if they matched and FALSE
otherwise. tWildcard can contain the following wildcards:

* Matches any number of characters.

? Matches a single character.

[] Specifies a set of characters that are a valid match at a given point. The set can contain
ranges specified with a minus sign. In the range, the earlier character must be alpha-
betically less than the later character.

If any of the special wildcards must be used to represent itself, it must be escaped by double
backslashes. For example, the text “\\**” used as tWildcard will find all texts that start with an
asterisk and then contain any number of characters.

Examples
! Example 1
! Comparison results with various wildcard strings.
compare (“Sample Text”, “Sam*”)-> TRUE
compare (“Sample Text”, “*T*”)-> TRUE
compare (“Sample Text”, “*a”)-> FALSE
compare (“Sample Text”, “[Ss]* [Tt]*”)-> TRUE
compare (“Sample Text”, “Sa??le *”)-> TRUE

! Example 2
! Function nfGetType returns special purpose type of
! given argument.
function nfGetType(tParameter)
if compare(tParameter, “*TEXT*”) then
! text contains “TEXT”
return(1)
endif
if compare(tParameter, “[Aa]*”) then
! text begins with ’a’ or ’A’
return(2
) endif
if compare(tParameter, “\\**”) then
! text begins with ’*’
return(3)
else
return(0)
endif
endfunction

copy
Usage

TradeXpress ®
Generix Group - All rights reserved 126
Built-in Functions Reference / Functions Reference

copy (tSource, tDestination)

Arguments
tSource file name to copy from

tDestination destination file name

Returns
Boolean value TRUE if the copy succeeds; otherwise FALSE.

Description
The file tSource is copied to the file tDestination. If the copying is successful, TRUE is returned;
otherwise the return value is FALSE and the reason for the failure is written to the logging stream.
The file names cannot contain any wildcards.

See also
link, remove, rename

Examples
! Example 1
copy (“.profile”, tFilename)

! Example 2
copy (build (sEDIHOME, “/sample”), “/tmp/sample”)

! Example 3
% copies first argument (filename) to /tmp directory
begin
if ARGV[1] = EMPTY then
print(“Usage: “, ARGV[0], “ filename”, NL)
print(“ copies ‘filename’ to /tmp”, NL)
else
! copy argument file to /tmp directory
! under the same name
fFile := ARGV[1]
tFile := fFile.NAME
copy(ARGV[1], build(“/tmp/”, tFile))
endif
endbegin

debug
Usage
debug ( print list )

TradeXpress ®
Generix Group - All rights reserved 127
Built-in Functions Reference / Functions Reference

Arguments
print list

See the chapter 6 Input and Output, for a print list description.

Returns
Nothing.

Description
The print list is written to the logging stream if the built-in variable LOGLEVEL is set to value 2 or
higher. Otherwise, no output is produced.

See also
log

Example
% run with parameter -l2 to test debug
begin
debug(“Run time is “, time(), NL)
tBASE := build(sHOME, “/database”)
debug(“Database is “, tBASE, NL)
endbegin

edierrordump
Usage
edierrordump (MESSAGE)

edierrordump (SEGMENT)

Arguments
MESSAGE EDI

message to be dumped

SEGMENT a single segment to be dumped

Returns
Nothing.

Description
Dumps the erroneous message or a segment into the logging stream. The dumped message or
segment contains the error references placed in the message.

See also

TradeXpress ®
Generix Group - All rights reserved 128
Built-in Functions Reference / Functions Reference

edierrorlist, valid

Example
segment UNH
if not valid(MESSAGE) then
edierrordump (MESSAGE)
endif
endsegment

edierrorlist
Usage
edierrorlist (MESSAGE)

edierrorlist (SEGMENT)

Arguments
MESSAGE EDI message from which the list is generated

SEGMENT a single segment from which the list is generated

Return
Nothing.

Description
Creates an error list for an EDI message and prints the error list into the logging stream. Similarly,
if SEGMENT is given as the argument, the error list is printed for the current segment only.

See also
edierrordump, valid

Example
! This segment statement list processes
! incoming BGM segment.
segment BGM
if valid(SEGMENT) then
edierrorlist(SEGMENT)
endif
...
endsegment

exec
Usage
exec (tCommand, taArgs)

TradeXpress ®
Generix Group - All rights reserved 129
Built-in Functions Reference / Functions Reference

exec (tCommand, tArg1, tArg2, ... , tArgN)

Arguments
tCommand command to be executed

taArgs arguments for the command in array form

tArg1, tArg2, ... , tArgN

arguments for the command in list form

Returns
Nothing.

Description
Executes the program tCommand without creating a new process. Arguments to the new pro-
gram can be given in a table or as an argument list. The list can be used only when the number of
arguments is known at compile time.

A successful call to exec() never returns.

See also
background, spawn, system

Examples
! Example 1
taArgs[1] := build (nIndex)
taArgs[2] := tFilename
exec (“transport”, taArgs)

! Example 2
exec (“transport”, build (nIndex), tFilename)
% executes command ‘ls -la [param [param...]]’
begin
taArgs[0] := “-la”
!
nParam := 1
while ARGV[nParam] <> EMPTY do
taArgs[nParam] := ARGV[nParam]
nParam++
endwhile
exec(“ls”, taArgs)
print(“This should never print”, NL)
endbegin

end
print(“This point is never reached”, NL)
exec(“not.exist”, “dummy”, “parameter”)
endend

TradeXpress ®
Generix Group - All rights reserved 130
Built-in Functions Reference / Functions Reference

exit
Usage
exit (nExitcode)

Arguments
nExitcode value to pass to the waiting process

Returns
Never returns.

Description
Terminates the current program and passes the value nExitcode to the waiting process as the
exit status. Normally a successful program returns a zero and other values are used to indicate
error conditions.

See also
exec, spawn

Examples
! Example 1
if bAllOK = TRUE then
exit (0)
else
exit (1)
endif

! Example 2
% Return 0 if parameter file exists. Else
return 1.
begin
fFile := ARGV[1]
if fFile.EXIST then
exit(0)
else
exit(1)
endif
endbegin

find
Usage
find (tDatabase, filter) [ sort order ]

Arguments
tDatabase database name

filter filter definition

TradeXpress ®
Generix Group - All rights reserved 131
Built-in Functions Reference / Functions Reference

sort order sort order definition

Returns
Database entry.

Description
Used only with assignment to a database entry.

This command, used with the database name and filter, finds the first entry that matches the fil-
ter. When no arguments are given, this command finds the next entry with the previous filter.
Sort order specifies a field that is used as the sort key. The field must be preceded with “a” or “d”
denoting ascending or descending sort order.

Examples
! Example 1
base “sample.cfg” ENTRY
begin
ENTRY := find (tSample, NAME=”*i*”) dAGE
endbegin

! Example 2
base “example.cfg” ENTRY
begin
tBASE := build(sHOME, “/example”)

! Ascending list of all names containing “i”


ENTRY := find(tBASE, NAME=”*i*”) aNAME
while valid(ENTRY) do
print(ENTRY.NAME, NL)
ENTRY := find()
endwhile
endbegin

flush
Usage
flush ([taMatrix], nMin, nMax, tLinesep)

flush (logentry)

Arguments
taMatrix buffer to be flushed

nMin minimum length of the printed line

nMax maximum length of the printed line

tLinesep separator used at the end of the line

TradeXpress ®
Generix Group - All rights reserved 132
Built-in Functions Reference / Functions Reference

logentry logentry to be flushed

Returns
Nothing.

Description
Flush prints the contents of the buffer. If the buffer is not defined, the default buffer named BUF-
FER is used. If the nMin or nMax are zeros, they are ignored; otherwise they are used. If the line to
be printed contains fewer characters than the nMin, the space is filled with the defined fill char-
acter named FILL_CHAR.

If the line to be printed is longer than the nMax, only nMax characters are printed and the error
message is written to the logging stream.

If the autoflush off option has been stated, the variables in question are never written implicitly
to the system, and a call to flush (logentry) is needed. By default, the variable is written in each
assignment, so flushing is not necessary.

See also
put

Example
begin
put (1, 2, “|1st line 2nd column”)
put (2, 5, “|2nd line 5th column”)
flush (0, 80, NL) > “/tmp/example”
endbegin

index
Usage
index (tOriginal, tSearch)

Arguments
tOriginal string to be searched

tSearch searched string

Returns
Numeric value containing the character position.

Description
Returns the position of tSearch in tOriginal. If tSearch does not appear, the return value is zero.

Example

TradeXpress ®
Generix Group - All rights reserved 133
Built-in Functions Reference / Functions Reference

!- - - - - - -------- - - -- -
! nPosition gets 10 as its value
!- - - - - - -------- - - -- -
nPosition := index (“Sample string”, “ring”)

!- - - - - - - - - - - - - - - - - - -
! ...and here nPosition gets 0.
!- - - - - - - - - - - - - - - - - - -
nPosition := index (“Sample string”, “not there”)

% Underlines existence of arg2 in arg1


begin
print(ARGV[1], NL)

nCount := index(ARGV[1], ARGV[2])


if nCount > 1 then
while nCount > 1 do
print(“ “)
nCount--
endwhile
nCount := length(ARGV[2])
while nCount > 0 do
print(“-”)
nCount--
endwhile
endif
print(NL)
endbegin

length
Usage
length (tText)

Arguments

tText text string

Returns
Numeric value containing the text string length.

Description
Returns the length of the argument.

Example
begin
print(“Printing length of input lines”, NL)
endbegin

default
tLine := pick(1,1,EOL)
print(length(tLine), “ chars: “, tLine, NL)

TradeXpress ®
Generix Group - All rights reserved 134
Built-in Functions Reference / Functions Reference

enddefault

end
print(“All done”, NL)
endend

link
Usage
link (tOriginal, tLink)

Arguments
tOriginal target file name

tLink link name

Returns
Boolean value TRUE if successful; otherwise FALSE.

Description
The file referred to with the name tOriginal gets a new link named tLink. Both links refer to the
same physical file. If the linking was successful, then TRUE is returned; otherwise the return
value is FALSE and the reason for the failure is written to the logging stream. The file names can-
not contain any wildcard characters.

Note
This function works only under UNIX.

Link can't be made if the two files are located on different files system.

See also
copy, remove, rename

TradeXpress ®
Generix Group - All rights reserved 135
Built-in Functions Reference / Functions Reference

Example
link (“.profile”, tFilename)
link (build (sEDIHOME, “/sample”), “/tmp/sample”)
% Simple command procedure to build a link to a file
begin
tOriginal := build(sEDIHOME, “/database/example.cfg
tLink := build(sHOME, “/example.cfg”)
print(“Enter commands”, NL)
endbegin
line ’[Hh][Ee][Ll][Pp]’
print(“Help not installed”, NL)
endline
line (1:”S” or 1:”s”)
link(tOriginal, tLink)
endline
line (1:”R” or 1:”r”)
remove(tLink)
endline
line (1:”Q” or 1:”q”)
exit(0)
endline
default
print(“Unknown command.”)
print(“Valid commands are S, R and Q”, NL)
enddefault

load
Usage
load ([nMode,] tSrcFile, taArray [,tMultisep [,tSeparator]])

load ([nMode,] SrcLog, tSrcExt, taArray [,tMultisep [,tSeparator]])

Arguments
nMode load mode

tSrcFile source file


(in NAME=VALUE format)

taArray text array to load into

SrcLog database entry of the source

tSrcExt “name” of the database table to load

tMultisep separator character for multiple entry value

tSeparator separator character for single entry value

TradeXpress ®
Generix Group - All rights reserved 136
Built-in Functions Reference / Functions Reference

Returns
A numeric value that contains the number of entries generated in the taArray.

Description
Loads name-value pairs from the source file (tSrcFile) or database table (SrcLog. tSrcExt) to the
elements in the text array (taArray).

The content of the file is loaded line by line. The first token on the line is assumed to be the name,
followed by the separator, which in turn is immediately followed by the value. The default separa-
tor is ‘=’.

Load Mode
0. Creates a new table. May create multivalues. Used as a default.

1. Overwrites existing values. The values already in the table are left intact if the speci-
fied file does not contain new values for them; otherwise they are replaced with the
new values. Only the last value for each new name is used, since no multivalue fields
are generated.

2. Appends to existing values. This may turn some single values to multivalue fields.

3. Adds new entries. Only new values are read in, so the existing values will not change,
but there may be additions.

4. The same as load mode 1, but this mode deletes all empty parameters merged from
the file.

Parameters at the Beginning of a Data File


If the data file contains parameters followed by other data, parameters can be loaded
from the beginning of the file with the load function. Parameters and data must be
separated with a line that contains only a single separator character, such as the
equal sign (=). After a successful load function call, the file is left open and the file
pointer points to the beginning of the data.

Example
Example file "acronyms.txt":
AA=Amazing Acronyms
BB=Baked Beans
BB=Bank Bill

If the file (or table) contains more than one line with the same name, the result depends on
the loadmode being used. With load modes other than 1, all these values are loaded to the same
table entry, separated by the tMultisep. The default value for tMultisep is ':'. Thus the com-
mand
load (0, "acronyms.txt", taFORM)
or load ("acronyms.txt", taFORM)
would result in:
taFORM["AA"] contains "Amazing Acronyms"

TradeXpress ®
Generix Group - All rights reserved 137
Built-in Functions Reference / Functions Reference

taForm["BB"] contains "Baked Beans:Bank Bill"


On the other hand,
load (1, "acronyms.txt", taFORM)
would result in:
taFORM["AA"] contains "Amazing Acronyms"
taForm["BB"] contains "Bank Bill"
Effect of different load modes, "load.rte"
! A simple RTE-program to demonstrate different load modes

begin
! Set the load mode to the one given in command ! line,
! or use 0 (zero) as a default if none given
if ARGC <> 1 then
nMode := 0
else
nMode := number(ARGV[1])
endif
! Fill in some data
taFORM["ONE"] := "First line"
taFORM["TWO"] := "Second line"
! Print out the original contents of the table
print (“Array taFORM contains: (before loading)”,NL
print(taFORM)
print(NL)
! Load the file "table.txt" into table taFORM
load(nMode, "table.txt", taFORM)
! Print out the new contents of the table
print("Array taFORM contains: (after loading,\ mode=",nMode,")",NL)
print(taFORM)
endbegin
And a sample file, "table.txt":
ONE=Number one
TWO=Number two
And sample usage and output:
$ load 0
Array taFORM contains: (before loading)
ONE=First line
TWO=Second line
Array taFORM contains: (after loading, mode=0)
ONE=Number one
TWO=Number two
$ load 1
Array taFORM contains: (after loading, mode=1)
ONE=Number one
TWO=Number two
$ load 2
Array taFORM contains: (before loading)
ONE=First line
TWO=Second line
Array taFORM contains: (after loading, mode=2)
ONE=First line
ONE=Number one
TWO=Second line
TWO=Number two
$ load 3
Array taFORM contains: (before loading)
ONE=First line
TWO=Second line
Array taFORM contains: (after loading, mode=3)

TradeXpress ®
Generix Group - All rights reserved 138
Built-in Functions Reference / Functions Reference

ONE=First line
TWO=Second line
$ load 4
Array taFORM contains: (before loading)
ONE=First line
TWO=Second line
Array taFORM contains: (after loading, mode=4)
ONE=Number one
TWO=Number two

log
Usage
log ( print list )

Arguments
print list

See the chapter 6 Input and Output, for a print list description.

Returns
Nothing.

Description
Writes the print list to the logging stream.

See also
print

Example
! Print a log entry.
begin
redirect(LOGGING, build(time(“%y%m%d”), “.log”))
log(“Running “, ARGV[0], NL)
log(“Run time “, time(), NL)
endbegin

new
Usage
new (tDatabase)

Arguments
tDatabase name of the database

Returns
Database entry.

TradeXpress ®
Generix Group - All rights reserved 139
Built-in Functions Reference / Functions Reference

Description
Creates an empty entry to the named database.

See also
find

Example
! new creates an empty entry to the database.
! No values for fields are set except CTIME
! (creation time)
! if addprog is defined for database it is called.

base “example.cfg” ENTRY

begin
! Database is located in home directory

tBASE := build(sHOME, “/example”)

! Create new entry and set default values

ENTRY := new(tBASE)
if valid(ENTRY) then
ENTRY.NAME := “Nick Noname”
ENTRY.ADDRESS := “Quezon City”
ENTRY.AGE := 999
endif
endbegin

number
Usage
number (tNumText)

Arguments
tNumText text string

Returns
A numeric value that contains the converted value.

Description
This function converts the argument tNumText to its numeric representative. If the text does not
represent a valid number, the return value is zero and an error message is written to the logging
stream.

See also
build

TradeXpress ®
Generix Group - All rights reserved 140
Built-in Functions Reference / Functions Reference

Example
! Calculate the sum of numbers given on input lines
line ’[0-9]*’
nGot := number(pick(1,1,EOL))
nSum := nSum + nGot
print(“Number=”, nGot, “ Sum=”, nSum, NL)
endline

peel
Usage
peel (tOriginal, tExtras)

Arguments
tOriginal original text string

tExtras text string containing the extraneous characters

Returns
A text string that contains the peeled string.

Description
Peels off all characters included in tExtras from the beginning and end of the tOriginal and
returns the resulting text. tOriginal always remains unaltered. The order of characters in tExtras
is insignificant and the characters are not combined to form strings. In other words, peeling is
done on a character-by-character basis and no strings can be specified. The peeling stops in one
direction as soon as a character appears that is not included in tExtras.

See also
replace

Example
! Example 1
tResult := peel (“ Sample text “, “ “)

! tResult contains as its value “Sample text”.

! Example 2
! peeling spaces and tabs
default
print(peel(pick(1,1,EOL), “ “), NL)
enddefault

pick
Usage

TradeXpress ®
Generix Group - All rights reserved 141
Built-in Functions Reference / Functions Reference

pick (nLine, nPosition, nLength)

Arguments
nLine line position

nPosition column position

nLength number of characters to be picked

Returns
A text string that contains the pick value.

Description
nLine specifies the line relative to the top of the current window in the input stream. nPosition
gives the position on that line and nLength the number of characters to be picked. The last argu-
ment can also be EOL, which directs the picking to retrieve all characters up to the end of the line.

See also
read

Example
! Example 1
line (1:”SAMPLE”)
tText1 := pick (1, 8, EOL)
tText2 := pick (2, 1, 10)
endline

! Example 1 with data lines:


SAMPLE PICKING
A SECOND LINE

tText1 contains “PICKING”


tText2 contains “A SECOND L”

! Example 2
! example of pick function
! run executable with source as input file
!
!SAMPLE PICKING
!SECOND SAMPLE LINE
!
line (2:”SAMPLE”)
tText1 := pick(1, 9, EOL)
tText2 := pick(2, 8, 7)
print(“HIT - “, tText1, tText2, NL)
endline

print
Usage

TradeXpress ®
Generix Group - All rights reserved 142
Built-in Functions Reference / Functions Reference

print (print list)

Arguments
print list

See the chapter 6 Input and Output, for a print list description.

Returns
Nothing.

Description
Prints the print list to standard output.

Example
! print can take any kind of arguments including
! numeric and ascii variables and tables...

! Print example
begin
nX := 1
nY := 2.37
tC := “ASCII”

print(“This appears on the stdout”, NL)


print(“Today is “, time(), NL)
print(“Value of variable nX is “, nX, NL)
print(“Value of variable nY is “, nY, NL)
print(“Value of variable nY is “, nY:6, NL)
print(“Variable tC (tC) ‘”, tC, “‘”, NL)
print(“Variable tC (tC:3) ‘”, tC:3, “‘”, NL)
print(“Variable tC (tC:7) ‘”, tC:7, “‘”, NL)

print(“This goes to file ‘/tmp/tmp’”, NL) > “/tmp/tmp”


print(“This is echoed by /bin/more”, NL) > “|/bin/more”

redirect(OUTPUT, “/tmp/tmp”)
print(“Now every printed line “)
print(“goes to file /tmp/tmp”, NL)
endbegin

put
Usage
put ([taMatrix,] nLine, nPos, print item)

Arguments
taMatrix output buffer

nLine line in the output buffer

TradeXpress ®
Generix Group - All rights reserved 143
Built-in Functions Reference / Functions Reference

nPos column of the output buffer

print item See the chapter 6 Input and Output, for a print item description.

Returns
Nothing.

Description
The put function is used when buffered output is needed. The function prints its print item to the
given buffer or to the default output buffer named BUFFER. The print item is put in the print buffer
position assigned with nLine and nPos. nLine is the line number in the output buffer and nPos is
the column in the output buffer.

If there are undefined places in the output buffer, they are filled with the fill character named
FILL_CHAR, which must be set before put is used for the first time for the buffer.

If a formatted print item is used, the fill character for the print formats is always a space, regard-
less of the FILL_CHAR value.

See also
flush

Example
! If a fill character is used it must be
! set before the first call to put function.
! Fill character is used in any output
! location that is not explicitly set.
! Build output in unforeseen order
begin
! If used, fill char must be set before
! printing
FILL_CHAR := “+”
put(3, 1, “first”)
put(2, 21, “second”)
! use 8 characters wide field for “third”
put(1, 21, “third”:8)
put(2, 11, “fourth”)
put(2, 1, “fifth”)
put(1, 1, “sixth”)
put(3, 21, “seventh”)
put(1, 11, “eighth”)
put(3, 11, “ninth”)
! Print every line exactly 30 characters long
flush(30, 30, NL)
endbegin

read
Usage

TradeXpress ®
Generix Group - All rights reserved 144
Built-in Functions Reference / Functions Reference

read (tFile)

Arguments
tFile file name of the file to be read from

Returns
A text string that contains the read value.

Description
The read function reads a line from a file or from a process. The function returns the line just read
(or EOF if there are no more lines). The file from which lines are read must be closed before it can
be reread. It is also good practice to close all processes that are read from.

See also
load, pick

Example
! List of registered users in this machine
begin
tFile := “/etc/passwd”
print(“List of registered users:”, NL)
tLine := read(tFile)
while tLine <> EOF do
print(substr(tLine, 1, index(tLine, “:”) - 1), NL)
tLine := read(tFile)
endwhile
close(tFile)
endbegin

end
tFile := “|uname -a”
tLine := read(tFile)
close(tFile)
print(“in machine “, tLine, NL)
endend

redirect
Usage
redirect (stream, tFile)

Arguments
stream name of the stream

tFile file name of the file to be opened

Returns

TradeXpress ®
Generix Group - All rights reserved 145
Built-in Functions Reference / Functions Reference

Nothing.

Description
There are three standard I/O devices named INPUT, OUTPUT, and LOGGING. By default, they refer to
stdin, stdout, and stderr, respectively. Any of them can be redirected to any file or process, but
after redirection, there is no way to return them to their default values. Note that if you start a
new process after redirection, it will also inherit the redirected I/O devices.

Example

! Redirection example
! Prints users with initial letter ’r’
begin
print(“Output will be in file /tmp/tmp”, NL)

redirect(INPUT, “/etc/passwd”)
redirect(OUTPUT, “/tmp/tmp”)
redirect(LOGGING, build(time(“%y%m%d”),“.log”))

log(“Running “, ARGV[0], NL)


log(“Run time “, time(), NL)

print(“Usernames with initial letter ’r’:”, NL)


endbegin

line (1:”r”)
print(pick(1, 1, EOL), NL)
endline

remove
Usage
remove (tFile)
remove (log entry)
remove (MESSAGE)
remove (taArray)
remove (naArray)
remove (baArray)
Arguments
tFile file name of the file to be removed

log entry log entry handle of the log entry to be removed

MESSAGE MESSAGE to be removed

TradeXpress ®
Generix Group - All rights reserved 146
Built-in Functions Reference / Functions Reference

taArray text array to be removed

naArray numeric array to be removed

baArray Boolean array to be removed

Returns
The Boolean value TRUE if the remove is successful; otherwise FALSE.

Description
The remove function removes the given object, which can be a file, log entry, MESSAGE, text
array, Boolean array, or numeric array. If the removal succeeds, the Boolean value TRUE is
returned; otherwise, FALSE is returned and an error message is written to the logging stream.

Example
! Print /etc/passwd
begin
! Load userlines in username indexed table
! print table in file
! print file line by line

tWorkFile := “/tmp/tmp”
load(“/etc/passwd”, taUsers, “@”, “:”)
print(taUsers) > tWorkFile
close(tWorkFile)
remove(taUsers)
redirect(INPUT, tWorkFile)
endbegin

default
print(pick(1, 1, EOL), NL)
enddefault

end
remove(tWorkFile)
endend

rename
Usage
rename (tOldname, tNewname)

Arguments
tOldname file name of the file to be renamed

tNewname new file name for the file

Returns
The Boolean value TRUE if the rename is successful; otherwise FALSE.

TradeXpress ®
Generix Group - All rights reserved 147
Built-in Functions Reference / Functions Reference

Description
This function renames the file tOldname to tNewname. If the rename is successful, the Boolean
value TRUE is returned; otherwise, the function returns FALSE and writes an error message to the
logging stream. Rename works by first creating a new link to the file’s inode, and then removing
the old name from the inode. This allows the system to give more detailed reports if an error
occurs.

Example
! rename example and verification
begin
tFile1 := “/tmp/tmp”
tFile2 := “/tmp/tmp.tmp”

system(build(“touch “, tFile1))
system(“ls -al /tmp/tmp*”)

rename(tFile1, tFile2)
system(“ls -al /tmp/tmp*”)

remove(tFile2)
endbegin

replace
Usage
replace (tOriginal, tRemoved, tReplacements)

Arguments
tOriginal original text string

tRemoved text string containing characters to be removed

tReplacements

text string containing substituting characters

Returns
A text string that contains the replaced string.

Description
This function replaces in the text tOriginal all the characters in tRemoved that have correspond-
ing characters in tReplacements, and returns the resulting text. tOriginal is unaltered.

tOriginal is scanned for all characters in tRemoved individually, so no strings can be specified to
be replaced. As a character is found, it is replaced with a character from the same position in
tReplacements. If there is no character at that position, then the character specified in tRem-
oved is removed from tOriginal.

TradeXpress ®
Generix Group - All rights reserved 148
Built-in Functions Reference / Functions Reference

See also
peel, strip

Example
! Example 1
tResult := replace (“ Sample text “, “ e”, “.E”)
! tResult contains “..SamplE.tExt..”. All spaces were replaced by a period and all lower
! case e’s with a capital E.

! Example 2
tResult := replace (“ Sample text “, “ et”, “.E”)
! tResult contains “..SamplE.Ex..”. All spaces were replaced by a period and all lower case
! e’s with a capital
! E and all lower case t’s were removed since there was no character at the third position in
! the tReplacements
! (“.E”).

! Example 3
! Prints all lines in /etc/passwd starting with ’r’
! Some changes are made...
begin
redirect(INPUT, “/etc/passwd”)
endbegin

line (1:”r”)
tLine := pick(1, 1, 30)
print(tLine, NL)
print(replace(tLine, “r:/”, “R \\”), NL, NL)
endline

spawn
Usage
spawn (tCommand, taArgs)

spawn (tCommand [,tArg1 [,tArg2 [, ...[, tArgN]]]])

Arguments
tCommand command to be spawned

taArgs arguments for the command in table form

tArg1, tArg2, ..., tArgN

arguments for the command in list form

Returns
A numeric value that contains the exit code from the spawned process.

TradeXpress ®
Generix Group - All rights reserved 149
Built-in Functions Reference / Functions Reference

Description
The function spawn creates a new child process. The process that calls spawn waits until the
spawned process returns. Spawn returns the exit code from the spawned process. Note that the
spawned process inherits the environment of the calling process.

See also
background, exec, system

Example
! spawns command ‘ls -la [param [param...]]’
begin
taArgs[0] := “-la”

nParam := 1
while ARGV[nParam] <> EMPTY do
taArgs[nParam] := ARGV[nParam]
nParam++
endwhile
spawn(“ls”, taArgs)
print(“This will be printed”, NL)
endbegin

end
spawn(“not.exist”, “dummy”, “parameter”)
print(“This will be printed, too”, NL)
endend

split
Usage
split (tSource, taArray, tSeparator)
split (tSource, taArray, regular expression)
Arguments
tSource text string to be split

taArray resulting text array

tSeparator text string containing separator character

regular expression
regular expression reguused in splitting

Returns
A numeric value that contains the number of items created in taArray.

Description

TradeXpress ®
Generix Group - All rights reserved 150
Built-in Functions Reference / Functions Reference

This function splits tSource into substrings that are cut wherever the separator character tSepa-
rator exists. The resulting substrings are put into the taArray text array, and the number of sub-
strings is returned.

If a regular expression is used instead of the separator character, tSource is split according to the
named sub-expressions in the regular expression if the regular expression matches tSource. The
name of the sub-expression must be a number from 0 to 9. taArray is filled such that sub-
expression names are used as indexes to the taArray.

Note
Regular expressions are not available in Windows NT.

See also
substr

Example
! Example of split
begin
tText1 := “one,two,three,four,five,six,seven”
tText2 := “user@machine”

nNumbers := split(tText1, taNumbers, “,”)


nFields := split(tText2, taAddr, ’^([^@]+)$0@(.+)$1’)

print(“There are “, nNumbers, “ numbers:”, NL)


print(taNumbers)

print(“Addr should have 2 fields (“, nFields, “)”, NL)


print(taAddr)
endbegin

strip
Usage
strip (tOriginal, tExtras)

Arguments
toriginal original text string

tExtras text string containing characters to be removed

Returns
The text string that results from the stripping operation.

Description

TradeXpress ®
Generix Group - All rights reserved 151
Built-in Functions Reference / Functions Reference

This function strips away from tOriginal all the characters contained in tExtras and returns the
resulting text. tOriginal is unchanged. The order of characters in tExtras does not matter, and the
characters are not combined to form strings. In other words, stripping is done on character-by-
character basis and no strings can be specified in tExtras.

See also
peel, replace

Example
! Example 1
tResult := strip (“ Sample text “, “ “)

! tResult contains “Sampletext” as its value


! since all spaces have been stripped away.

! Example 2
begin
redirect(INPUT, “/etc/passwd”)
endbegin

line (1:”r”)
! strip all r’s, :’s and /’s
! print both stripped and unstripped
! lines

tLine := pick(1, 1, 30)


print(tLine, NL)
print(strip(tLine, “r:/”), NL, NL)
endline

substr
Usage
substr (tOriginal, nPosition, nLength)

Arguments
tOriginal original text string

nPosition start position of the substring

nLength number of characters in the substring

Returns
A text value that contains the extracted substring.

Description
From the text tOriginal, this function extracts a substring that starts from nPosition and is
nLength long.

TradeXpress ®
Generix Group - All rights reserved 152
Built-in Functions Reference / Functions Reference

See also
index

Example
! Substr sample
begin
tText := “Sample string for examples”

! This will print “Sampling”

print(substr(tText, 1, 5))
print(substr(tText, 11, 3), NL)
endbegin

system
Usage
system (tCommandLine)

Arguments
tCommandLine

command line to be executed

Returns
A numeric value, which is the exit code of the executed shell.

Description
The system causes the tCommandLine to be given to the shell as input, as if the tCommandLine
had been typed as a command at a terminal. The current process waits until the shell has com-
pleted, then returns the exit status of the shell.

See also
background, exec, spawn

TradeXpress ®
Generix Group - All rights reserved 153
Built-in Functions Reference / Functions Reference

Example
! runs system with command ‘ls -la [param [param...]]
begin
tCommand := “ls -la”

nParam := 1
while ARGV[nParam] <> EMPTY do
tCommand := build(tCommand, “ “, ARGV[nParam])
nParam++
endwhile
print(“This will be printed before”, NL)
system(tCommand)
print(“This will be printed after”, NL)
endbegin

time
Usage
time ([TIME] [,tFormat])

Arguments
TIME time specifier

tFormat time print format

Returns
A text string that contains the specified time.

Description
Time provides access to the system time and the time values in the database and file system.

When called with no arguments, time returns the current system time in the default format
(dd.mm.yyyy HH:MM).

When tFormat is provided, the current system time is returned in the specified format.

time ()
time (tFormat)
time (TIME)
time (TIME, format)
The format string can contain time components and regular characters. The time components are
marked with a percent sign.

The time format fields are:

TradeXpress ®
Generix Group - All rights reserved 154
Built-in Functions Reference / Functions Reference

%T time in AM/PM notation (HH:MM AM|PM)

%t time in AM/PM notation (HH:MM:SS AM|PM)

%d day of the month

%m month

%y year in two digits (...98, 99, 00, 01)

%Y absolute year

%H hour

%M minute

%S seconds

%W day of the week in long format

%w day of the week in abbreviated format

%k week of the year (1 - 53)

%j day of the year (1 - 366)

%a absolute value, used in comparisons

%eM elapsed minutes to current system time

%eH elapsed hours

%eW elapsed weeks

A negative value in elapsed time indicates that the given time is in the future.

The time format specifiers are today, yesterday, tomorrow, now, and none. Any of these specifi-
ers except “none” can be followed by the + or - operator and a formatted value.

Examples

! time() example
begin
print ("a)", NL)
print("Time is now ( ) ", time(), NL)
print(" in AM/PM notation (T) ", time("%T"), NL)
print(" in AM/PM notation (%t) ", time("%t"), NL)
print("Minutes (%M) ", time("%M"), NL)

TradeXpress ®
Generix Group - All rights reserved 155
Built-in Functions Reference / Functions Reference

print("Hours (%H) ", time("%H"), NL)


print("Seconds (%S) ", time("%S"), NL)
print("Day of the month (%d) ", time("%d"), NL)
print("Month of the year (%m) ", time("%m"), NL)
print("Short year (%y) ", time("%y"), NL)
print("=> year 2001 (short) (%y) ", \
time ("31.1.2001", "%y"), NL)
print("Day of week (long) (%W) ", time("%W"), NL)
print("Day of week (short) (%w) ", time("%w"), NL)
print("Week of the year (%k) ", time("%k"), NL)
print("Day of the year (%j) ", time("%j"), NL)
print("=> days in 1999 (%j) ", \
time("31.12.1999", "%j"), NL)
print("=> days in 2000 (%j) ", \
time("12/31/00", "%j"), NL)
print("Absolute value (%a) ", time("%a"), NL)
print("Elapsed minutes (%eM) ", time("%eM"), NL)
print("Elapsed hours (eH) ", time("%eH"), NL)
print("Elapsed days (%ed) ", time("%ed"), NL)
print("Elapsed weeks (%ew) ", time("%ew"), NL)
print("b)", NL)
print("After a minute it will be ", \
time("now + 1M", "%d.%m.%y %t"), NL)
print("After an hour it will be ", \
time("now + 1H", "%d.%m.%y %t"), NL)
print("After a day it will be ", \
time("now + 1d", "%d.%m.%y %t"), NL)
print("After a week it will be ", \
time("now + 1w", "%d.%m.%y %t"), NL)
print("c)", NL)
print("Date 20000229 printed ", \
time("20000229", "%d.%m.%Y"), NL)
print("Date 02/29/00 printed ", \
time("02/29/00", "%d.%m.%Y"), NL)
print("Date 29.2.2000 printed ", \
time("29.2.2000", "%d.%m.%Y"), NL)
print ("d)", NL)
! Different outputs from same input format
print("Date 20000229 printed ", \
time("20000229", "%d.%m.%Y"), NL)
print("Date 20000229 printed ", \
time("20000229", "%m/%d/%Y"), NL)
print("Date 20000229 printed ", \
time("20000229", "%d%m%Y"), NL)
print (NL)
! NOTE: Year 2001 is not a leap year, so there is no February 29th.
print("Date 29.2.2001 printed ", \
time("29.2.2001", "%d.%m.%y"), NL)
endbegin

produces the following output:


a)
Time is now ( ) 10.01.2000 10:03
in AM/PM notation (%T) 10:03 AM
in AM/PM notation (%t) 10:03:20 AM
Minutes (%M) 03
Hours (%H) 10
Seconds (%S) 20
Day of the month (%d) 10

TradeXpress ®
Generix Group - All rights reserved 156
Built-in Functions Reference / Functions Reference

Month of the year (%m) 01


Short year (%y) 00
=> year 2001 (short) (%y) 01
Day of week (long) (%W) Monday
Day of week (short) (%w) Mon
Week of the year (%k) 2
Day of the year (%j) 10
=> days in 1999 (%j) 365
=> days in 2000 (%j) 366
Absolute value (%a) 947491400
Elapsed minutes (%eM) 0
Elapsed hours (%eH) 0
Elapsed days (%ed) 0
Elapsed weeks (%ew) 0
b)
After a minute it will be 10.01.00 10:04:20 AM
After an hour it will be 10.01.00 11:03:20 AM
After a day it will be 11.01.00 10:03:20 AM
After a week it will be 17.01.00 10:03:20 AM
c)
Date 20000229 printed 29.02.2000
Date 02/29/00 printed 29.02.2000
Date 29.2.2000 printed 29.02.2000
d)
Date 20000229 printed 29.02.2000
Date 20000229 printed 02/29/2000
Date 20000229 printed 29022000
Date 29.2.2001 printed 01.03.01

Example 2:
!
! Comparing time-fields from system logs with given range.
!
! Entries older than ARGV[1] are printed as old,
! entries newer than ARGV[2] are printed as new.
!
base "syslog.cfg" LOG

...

nOLD := number(time(ARGV[1], "%Y%m%d"))


nNEW := number(time(ARGV[2], "%Y%m%d"))

while LOG in (sSYSLOG) then


if (number(time(LOG.CREATED, "%Y%m%d")) < nOLD) then
print("old ")
else
if (number(time(LOG.CREATED, "%Y%m%d")) > nNEW) then
print("new ")
else
print(" ")
endif
endif
print(LOG.INDEX, " ", time(LOG.CREATED), " ",\
LOG.INFO, NL)
endwhile

TradeXpress ®
Generix Group - All rights reserved 157
Built-in Functions Reference / Functions Reference

tolower
Usage
tolower (tOriginal)

Arguments
tOriginal text string to be converted

Returns
A text string that contains the mapped string.

Description
This function converts all upper case letters in tOriginal to lower case and returns the result.
tOriginal remains unchanged. The conversion takes place according to the currently loaded char-
acter set.

See also
toupper

Example
! Converts all input to lowercase characters
default
print(tolower(pick(1, 1, EOL)), NL)
enddefault

toupper
Usage
toupper (tOriginal)

Arguments
tOriginal text string to be converted

Returns
A text string that contains the mapped string.

Description
This function converts all lower case letters in tOriginal to upper case letters and returns the
result. tOriginal remains unchanged. The conversion takes place according to the currently
loaded character set.

See also
tolower

TradeXpress ®
Generix Group - All rights reserved 158
Built-in Functions Reference / Functions Reference

Example
! Converts all input to uppercase characters
default
print(toupper(pick(1, 1, EOL)), NL)
enddefault

valid
Usage
valid (MESSAGE)
valid (SEGMENT)
valid (GROUP <group specifier>)
valid (<log entry>)
valid (<objecttype>, <text>)
Arguments
MESSAGE check validity of message

SEGMENT check validity of current segment

GROUP <group>

check validity of a given group

<log entry> check validity of a given log entry

<objecttype> object type to check against

<text> text to be checked

Returns
The Boolean value TRUE if valid; otherwise FALSE.

Description
Valid checks the validity of the item against the rules set for each of its arguments.

For MESSAGE, SEGMENT, and <group specifier>, various syntax and message definition related
checks are made.

For log entries, validity means the existence of the log entry.

TradeXpress ®
Generix Group - All rights reserved 159
Built-in Functions Reference / Functions Reference

If object is given, the tText is validated against the rules set for that particular object class. The
object can be one of the following: ALPHA, ALPHANUM, DATE, DECIMAL, ID, INTEGER, NUMERIC,
STRING, TIME.

Example
segment UNH
if valid (MESSAGE) = FALSE then
edierrordump(MESSAGE)
endif
...
endsegment

Group
if valid (GROUP g25)=FALSE then
endif

TradeXpress ®
Generix Group - All rights reserved 160
Annex A: Identifier Types

Overview
Basic Types
Special Types

TradeXpress ®
Generix Group - All rights reserved 161
Identifier Types / Overview

Overview

RTE does not contain declarations for identifiers. The names of the identifiers are used to distin-
guish the different types.

TradeXpress ®
Generix Group - All rights reserved 162
Identifier Types / Basic Types

Basic Types

All user-defined data types and other objects are identified with the first one or two letters of the
identifier name. This convention obviates the need for variable definitions. The letter following the
type tag must be an upper case letter. Here is a list of all the identifier types.

e Data element. These are always type text. For complete information about element
naming, see the chapter 5 EDI Translation.

g Group symbol. These can be used only to specify the position of a segment in a
message.

m Message variable. These are type text. Variables that are always available are mMES-
SAGE, mVERSION, mRELEASE, and mAGENCY. Other variables can be defined in the
message description file. These behave like constants and you cannot assign values
to them.

c Static counter. These are numeric values that can be referenced and set to a value. The
identifier name after the initial “c” is a file name in the directory $HOME/.counters. The
numeric content of that file is the next value received when the counter is referenced.
The value is incremented each time the counter is referenced and a locking mecha-
nism is used to guarantee that no two references receive the same value.

To assign a value to a counter, (and reset it if needed) :

cMYCOUNTER := <anynumber>

Counters are not automatically reset when they reach their limit.
You need to reset the counter in the rte.

s Environment variable. All those Unix shell variables (also called environment varia-
bles) that were set when the program started can be referenced. The identifier name
after the initial “s” must be the exact name of the shell variable. You cannot set new
shell variables or change the existing values.

o Command line option. These are Boolean values. An RTE program considers all upper
case flags (a single letter preceded by a minus sign) as user options and their values
can be referenced with these identifiers. An option identifier name consists of the
initial “o” followed by a single upper case letter. If the option was specified on the
command line, the option identifier is TRUE; otherwise it is FALSE.

TradeXpress ®
Generix Group - All rights reserved 163
Identifier Types / Basic Types

p Parameter. These are text values. Initial parameters can be specified in a parameter
file or on the command line. You can modify existing parameters and create new ones.
For more details, see the chapter 8 Running RTE Programs.

f File. These are special types of objects that are used to reference various attributes
for files. For details, see the chapter 6, section File Variables.

t Text variable. These can contain text of unlimited (for all practical purposes) length.

n Numeric variable. The content can be an integer or a double precision floating point
number.

b Boolean variable. This can contain only the values TRUE or FALSE.

ta An array containing text items. The array can contain an unlimited number of text
items and the index can be either text or an integer.

na An array containing numeric items. The array can contain an unlimited number of
numeric items and the index can be either text or an integer.

ba An array containing Boolean items. The array can contain an unlimited number of
Boolean values (TRUE or FALSE) and the index can be either text or an integer.

tf Function returning text.

nf Function returning a number.

bf Function returning a Boolean value.

Local variables

To avoid name conflicts, it is recommended to use local variables inside functions. This will result
in a better memory handling, and allow the use of recursivity.

Local variables are marked as local by using the letter 'l' in the "type" part of a variable name. The
idea is just to extend the type part (n,t,b,na,ta,b,f) of the naming convention to be able to define
local variables.

Some examples:

• blBoolean,
• nlNumeric,
• tlText,
• balBooleanTable,
• nalNumericTable,

TradeXpress ®
Generix Group - All rights reserved 164
Identifier Types / Basic Types

• talTextTable,
• flFileVar.
The scope of local variables is limited to blocs function endfunction.

TradeXpress ®
Generix Group - All rights reserved 165
Identifier Types / Special Types

Special Types

Database Entry
Database entries must be defined before any statement lists. The indentifier can contain upper
case and lower case letters, digits, and an underscore. The first character cannot be a digit. The
definition is required because the RTE compiler must know the types and lengths of the database
fields at compile time. For a complete description, see the chapter 7 Database Interface.

TIME
This type can be used as an argument to the time function. The database and file system inter-
faces contain this type. Assignments to the time fields of the data base entries are made in text
format.

There is no variable type TIME.

TradeXpress ®
Generix Group - All rights reserved 166
Annex B: Regular Expressions

Regular Expression Usage


Regular Expression Definition
Examples

TradeXpress ®
Generix Group - All rights reserved 167
Regular Expressions / Regular Expression Usage

Regular Expression Usage

RTE supports a limited form of regular expression notation. Regular expressions are used in line
statements to specify line matching rules and in split functions to specify the portions of a text
expression that are to be extracted.

A regular expression must be enclosed in quotation (‘ ’) marks so that RTE will handle them cor-
rectly. Regular expressions are constant expressions (not text strings), and they cannot be
assigned to any variable.

Regular expressions in RTE are defined in a similar way as in the Unix command editor.

Regular expressions can be used in Unix only.

TradeXpress ®
Generix Group - All rights reserved 168
Regular Expressions / Regular Expression Definition

Regular Expression Definition

A regular expression (RE) specifies a set of character strings. A member of this set of strings is
said to be matched by the RE. The REs allowed by RTE are constructed as follows.

The following one-character REs match a single character:

1.1 An ordinary character (not one of those discussed in 1.2 below) is a one-character RE
that matches itself.

1.2 A backslash (\) followed by any special character is a one-character RE that matches the
special character itself. The special characters are:

a. ., *, [, and \ (period, asterisk, left square bracket, and backslash, respectively), which
are always special, except when they appear within square brackets ([ ]; see 1.4 below).

b. ^ (caret or circumflex), which is special at the beginning of an entire RE (see 3.1 and
3.2 below), or when it immediately follows the left of a pair of square brackets ([ ]) (see
1.4 below).

c. $ (dollar sign), which is special at the end of an entire RE (see 3.2 below).

d. The character used to bound (that is, delimit) an entire RE, which is special for that RE
(for example, see how slash (/) is used in the g command, below.)

1.3 A period (.) is a one-character RE that matches any character except newline.

1.4 A non-empty string of characters enclosed in square brackets ([ ]) is a one-character RE


that matches any one character in that string. If, however, the first character of the string is
a circumflex (^), the one-character RE matches any character except newline and the
remaining characters in the string. The ^ has this special meaning only if it occurs first in the
string. The minus (-) can be used to indicate a range of consecutive ASCII characters; for
example, [0-9] is equivalent to [0123456789]. The - loses this special meaning if it occurs
first (after an initial ^, if any) or last in the string. The right square bracket (]) does not termi-
nate such a string when it is the first character within it (after an initial ^, if any); for example,
[ ]a-f] matches either a right square bracket (]) or one of the letters a through f, inclusive.
The four characters listed in 1.2.a above stand for themselves within such a string of charac-
ters.

The following rules can be used to construct REs from one- character REs:

2.1 A one-character RE is an RE that matches whatever the one-character RE matches.

TradeXpress ®
Generix Group - All rights reserved 169
Regular Expressions / Regular Expression Definition

2.2 A one-character RE followed by an asterisk (*) is an RE that matches zero or more occur-
rences of the one-character RE. If there is any choice, the longest leftmost string that
permits a match is chosen.

2.3 A one-character RE followed by \{m\}, \{m,\}, or \{m,n\} is an RE that matches a range of


occurrences of the one-character RE. The values of m and n must be non-negative integers
less than 256; \{m\} matches exactly m occurrences; \{m,\} matches at least m occurrenc-
es; \{m,n\} matches any number of occurrences between m and n, inclusive. Whenever a
choice exists, the RE matches as many occurrences as possible.

2.4 The concatenation of REs is an RE that matches the concatenation of the strings
matched by each component of the RE.

2.5 An RE enclosed between the character sequences \‹ and \› is an RE that matches what-
ever the unadorned RE matches.

2.6 The expression \n matches the same string of characters as was matched by an expres-
sion enclosed between \‹ and \› earlier in the same RE. Here, n is a digit; the sub-expression
specified is that beginning with the nth occurrence of \‹, counting from the left. For example,
the expression ^\‹.*\›\1$ matches a line consisting of two repeated appearances of the
same string.

Finally, an entire RE may be constrained to match only an initial segment or final segment of a
line (or both).

3.1 A circumflex (^) at the beginning of an entire RE constrains that RE to match an initial
segment of a line.

3.2 A dollar sign ($) at the end of an entire RE constrains that RE to match a final segment of
a line.

The construction ^ entire RE$ constrains the entire RE to match the entire line.

TradeXpress ®
Generix Group - All rights reserved 170
Regular Expressions / Examples

Examples

Using REs with the Line Statement


To match a line containing product codes in the form shown below (two digits, one upper case let-
ter, three digits and one lower case letter):

12M456l
45J897k

use the following regular expression:

line ’[0-9]{2}[A-Z][0-9]{3}[a-z]’

To match a line containing just a tag in the form shown below (the text string TAG at the beginning
of the line, followed by a numeric portion containing at least 1 and up to 4 digits, followed by the
# mark and nothing other than a newline character):

TAG145#
TAG12#

use the following line statement:

line ’^TAG[0-9]{1,4}#$’

Using REs with the Split Function


The split function is a string function that can be used to split a string to substrings. Normal use
would be something like:

split ("1,2,3,4", taNumbers, ",")

If a string cannot be split with just the separator character, a regular expression can be used
instead of the separator character.

To split the product code in the earlier example into its components, we can use a regular expres-
sion, as shown below:

split (tCode, taCode, \


’([0-9]{2})$0([A-Z])$1([0-9]{3})$2([a-k]) $3’)

After this function has been executed with the example code shown above, the text table taCode
contains the following strings:

taCode[0] = "12"
taCode[1] = "M"
taCode[2] = "456"
taCode[3] = "l"

TradeXpress ®
Generix Group - All rights reserved 171
Regular Expressions / Examples

The content of the taCode table is formed such that the string matched by the RE is split into sub-
strings, formed of the substrings that match the RE enclosed in ( ) parentheses. The notation $n
in the RE assigns the substring to the nth component in the taCode table (n can be from 0 to 9).

TradeXpress ®
Generix Group - All rights reserved 172
Annex C: Message Storage Format

Message World
Message Description Files

TradeXpress ®
Generix Group - All rights reserved 173
Message Storage Format / Message World

Message World

The messages used in TradeXpress are described in regular text files in a human readable format.
The message definition file contains only a list of segments and groups in the message; the con-
tent for each segment is specified in a separate file. This provides for consistency and allows for
a more compact presentation.

A message description is a starting point for all the work that is required to generate an EDI mes-
sage from application data, and vice-versa. A message description defines what is included in a
message, what is mandatory and what is conditional, and how many times items are allowed to
repeat. A message description is not tied to any application area, translation type, or direction.
Instead, it defines the framework for later, more detailed specifications.

The TradeXpress Message Manager obeys all the definitions set in the message description. This
means, for example, that you cannot use the Message Manager to change a mandatory segment
to a conditional one. If you must actually alter a message description, rather than just defining a
subset of it, you must edit the description manually.

It is possible to define a completely new message from scratch, or to change existing ones. This
is technically a straightforward task, but the use of standard messages is strongly recom-
mended.

Message descriptions usually represent standard messages that are distributed by a controlling
agency, such as the UN or ANSI. Standard messages often contain only a few mandatory seg-
ments and a wide selection of conditional segments, allowing various business areas and inter-
est groups to tailor subsets of the message to suit their specific needs.

TradeXpress ®
Generix Group - All rights reserved 174
Message Storage Format / Message Description Files

Message Description Files

The message description file contains identifiers, a segment list, and a section that describes the
use of the segments. The rest of this appendix explains these items in the order in which they
appear in the file.

Identifiers
There are a few mandatory identifiers that are presented as name-value pairs. Since the file
name by itself is not sufficient to uniquely identify the message, the identification strings are
stored in predefined identifiers:

MESSAGE
The name of the message, e.g. “CUSRES.”

VERSION
The version number, e.g. “2.”

RELEASE
Release for the message, e.g. “912.”

AGENCY
Controlling agency for the message, e.g. “UN.”

The name and value are separated by an equal sign.

Users can also include free form comments and set their own identifiers. Comments are written
to a line that starts after the keyword COMMENT and expands an unlimited number of lines up to
a line that starts with the keyword ENDCOMMENT. User-defined identifiers are in name-value-pair
format. Mandatory and user-defined identifiers can be used in RTE programs.

The file can also contain explanatory comments, which start from a “#” character and continue to
the end of the line. As the message is read in, these comments are ignored. They are not usable in
RTE and cannot be seen in the Message Manager.

Message Structure
The message structure is described by specifying all included segments and groups on separate
lines in the order in which they appear in the message. These lines start immediately following
the line that contains the keyword SEGMENTS.

That line can optionally contain a directory where the segment files reside. If there is no directory
name, then the segments are assumed to be in directory “segs” relative to the directory where
the message description resides.

TradeXpress ®
Generix Group - All rights reserved 175
Message Storage Format / Message Description Files

Segment Line
name Gives the unique name for the segment. This name is used as
such in the RTE files.

status The status can be either mandatory (M), conditional (C), or float-
ing (F). EDIFACT messages contain only mandatory and condi-
tional segments, whereas ANSIX12 messages can contain float-
ing segments as well.

repeat information Specifies how many times the segment can or must repeat in the
message.

Group Line

group 1 C 50

. repeat informati
. status
. group name
group tag
endgroup 1
group end tag

Each segment group is started with the keyword group, which is followed by the name (usually a
number) and the status and repeating information. There is always a matching endgroup key-
word for each group. The groups are usually indented a few spaces to make the file more readable
for human readers. In the case of segment files, the indentations are used for the reading pro-
gram as well (see Segment Description, below).

Message Usage
Optionally, there can be a usage description for each segment and group. Usage texts start from
the keyword USAGE and extend to the end of the file. Each segment is identified with the name
and enclosing group (if any). A group is identified by its name preceded by a lower case “g.” The
identification tag starts with an exclamation mark followed by the name enclosed in square
brackets.

![g3]
Segment Group 3: PCI-GIN
A group of segments identifying markings and labels on individual shipping or
packing units subject to customs action
![PCI 3]
Package identification
A segment identifying markings and labels on individual shipping or packing
units.

TradeXpress ®
Generix Group - All rights reserved 176
Message Storage Format / Message Description Files

This usage can be viewed with the Message Manager and it is also included in the documents
produced. The usage texts are not usable from RTE.

Segment Description
All segments are described in separate text files. The files are named after the segment names;
for example, the segment named UNH resides in a file named UNH.

On the first meaningful line, the file contains a long name for the segment. Starting from the sec-
ond meaningful line, there is a short explanation of the intended use of the segment. This expla-
nation ends when the keyword ELEMENTS is found. Comments start with a “#” sign and extend to
the end of the line.

From the line following the keyword ELEMENTS, there is a list of all the elements included in the
segment. Elements can be of three different types: simple, composite, and component. These
types are explained below.

Simple Data Element


A simple data element contains one piece of information. The specification starts from the first
column and contains the name, status, type, and an explanation.

0062 M an..14 MESSAGE REFERENCE NUMBER

name type

status explanation

Composite Data Element


Composite data elements are constructed of one or more component data elements. The specifi-
cation giving the name and status for the entire composite starts from the first column and con-
tains the name, status, and an explanation. The name of the element does not always reveal
whether it is a simple or a composite (in EDIFACT there is a clear distinction, however). A specifi-
cation for a composite data element has no type specification (e.g., an..14) and this is used here
to distinguish the two types.

S009 M MESSAGE IDENTIFIER

name explanation

status

TradeXpress ®
Generix Group - All rights reserved 177
Message Storage Format / Message Description Files

Component Data Element


Component data elements are listed on the lines immediately following the specification for the
governing composite data element. The lines for component data elements must be indented
with at least one space to distinguish them from simple data elements.

S009 M MESSAGE IDENTIFIER


0065 M an..6 Message type identifier
0052 M an..3 Message type version number
0054 M an..3 Message type release number
0051 M an..2 Controlling agency
0057 C an..6 Association assigned code

NAME The name for the element. Cannot contain spaces.

STATUS Status can be either mandatory (M) or conditional (C).

TYPE This field specifies the data type and the dimensions. Data type can be one of the
following:

a Alphabetic. All extraneous spaces at the end of the string are stripped.
an Alphanumeric. All extraneous spaces at the end of the string are stripped.
n Numeric. Can include a decimal separator (which can be defined in the charac-
ter set; usually a comma or period) and a sign (+ or -). There must be one digit
both in front of the decimal separator and after it. The decimal separator and the
sign are not counted in the total amount of characters. All leading zeroes are
compressed.
AN Alphanumeric. No space compression is done.

Nn Numeric, where “n” specifies the fixed number of decimals. No decimal separator
is allowed. No compression is done for leading zeroes. Sign characters are not
counted in the total amount of characters.

R Decimal number. A period is the only allowed decimal separator and it can appear
as the last character as well (for example, 3.). Sign characters and decimal separa-
tors are not counted in the total amount of characters.

ID Identifier. At the lower level, this is the same as AN, but at the message level, these
can contain only values listed as separate code lists.

DT Date. The format is YYMMDD, where YY must be from 00 to 99, MM takes values
from 01 to 12, and DD can be from 01 to 31.

TM Time. The format is HHMM[S..S], where HH ranges from 00 to 23, and MM from 00
to 59. There is no fixed length for seconds.

TradeXpress ®
Generix Group - All rights reserved 178
Message Storage Format / Message Description Files

The length of the element is specified immediately after the content type specifier. If there is only
a number following the specifier, the element is taken to be fixed length. Two periods before the
length specifier indicate that the element is variable length and the number indicates the maxi-
mum length.

Note that the examples here represent parts of the UNH segment in EDIFACT, and there are some
additional ways to distinguish between different types of elements. All composite data elements
in service segments start with a capital “S,” in regular segments they start with a capital “C,” and
in both cases three digits follow the initial letter. Names for simple and component data elements
are always four digits. The explanation for composite and simple data elements is often written
with all capital letters, and for components with lower case letters. However, since the TradeX-
press translator supports other grammars besides EDIFACT, these naming conventions cannot
be relied on.

MESSAGE HEADER
#Release:(88.1) 90.2
To head, identify and specify a message.
#- - - - - - - - - - - - - - - - - - - - - - - -
ELEMENTS
#- - - - - - - - - - - - - - - - - - - - - - - -
0062 M an..14 MESSAGE REFERENCE NUMBER
S009 M MESSAGE IDENTIFIER
0065 M an..6 Message type identifier
0052 M an..3 Message type version number
0054 M an..3 Message type release number
0051 M an..2 Controlling agency
0057 C an..6 Association assigned code
0068 C an..35 COMMON ACCESS REFERENCE
S010 C STATUS OF THE TRANSFER
0070 M n..2 Sequence message transfer number
0073 C a1 First/last sequence message transfer indication

TradeXpress ®
Generix Group - All rights reserved 179
Annex D: Character Sets

Character Set Definition


The Description Language

TradeXpress ®
Generix Group - All rights reserved 180
Character Sets / Character Set Definition

Character Set Definition

TradeXpress allows users to define their own character sets. The TradeXpress distribution
includes all the standard character sets used in the UN/EDIFACT and X12 community. These sets
can be used as a template when creating new ones.

Character sets are defined with a description language especially designed for the EDI syntax
usage. The definition file is compiled and placed in the character set directory, which is normally
$EDIHOME/charsets.

Character set definitions can be stored either in the $EDIHOME/charsets or $HOME/charsets


directory. The TradeXpress system modules will search the user’s home directory for character
sets first. If a valid character set definition is not found, the system’s charsets directory is used.

Character sets are handled automatically by the TradeXpress system modules. If the user exe-
cutes the RTE translator as a stand-alone program, character sets can be defined with command
line arguments. The following options are used for character sets:

-d <directory path>

-c <character set>

The command line can have as many -d options as required to specify all the possible places for
character set definitions. Only one -c option can be given. For example:

invoic.rec.911 -cB -d$HOME/charsets -d$EDIHOME/charsets

The example above would implement the default character set search policy for the
invoic.rec.911 translator.

TradeXpress ®
Generix Group - All rights reserved 181
Character Sets / The Description Language

The Description Language

Character Classes
The following table introduces the different character classes for TradeXpress character class
definitions.

Character
Description
class

seps separator characters in the following order


seps: <cs><es><st><ri><ts>, where
cs - component separator
es - element separator
st - segment tag
ri - release indicator
ts - tag separator; if missing equals es

alpha alphabetic characters

alnum alphabetic and numeric characters

digit digit character class

sign sign character

decimalpoint decimal point character

discard characters to be discarded

locale allowed character set


<UPPERCASE><UPPERCASE>...<lowercase><lowercase>...
for example, Scandinavian characters in 7 bit ASCII set:
locale: \]\[\\\}`\| (Notice escape characters)
Characters A-Z need not be explicitly defined in the locale description.

id identification character set (ANSI)

time characters used to describe the time data type (ANSI)

string characters used in string data (ANSI)

decimal decimal character (ANSI)

date characters used to describe the date data type (ANSI)

Character classes are written as follows:

TAG : CHARACTER CLASS DEFINITION

TradeXpress ®
Generix Group - All rights reserved 182
Character Sets / The Description Language

A character class definition is a set of characters that belong to a class. The following rules apply
to character set definition:

\NEWLINE class definition continues to following line

\OCTAL NUMBER octal number representation of a character

\CHARACTER escape character for special characters; use also with the minus (-) sign

^CHARACTER control character representation (^C == 003)

ANY-ANY range of characters including delimiting characters

Compiling Character Sets


Character set definitions must be compiled before they are valid for RTE translators. Compilation
works as follows:

cclass < definition > target

The cclass compiler reads the definition file from its standard input and writes the machine read-
able character set file to its standard output.

Standard practice with TradeXpress is that character set definition files are kept in the charsets/
src directory and the machine readable forms are kept in the charsets directory.

For example, to compile a character set definition for character set B, give the following com-
mand.

cclass < charsets/src/B > charsets/B

Sample Character Set


The following character set definition describes the UN/EDIFACT character set A.

#
# UNOA
#

seps: :+'?
alpha: \ A-Z
alnum: \ !"%&'()*+,\-./0-9:;<=>?A-Z
digit: 0-9
sign: \-
decimalpoint: ,.
discard: \000\011\012\014\015
whitespace: \011\012\015\040

The following character set definition describes the Finnish national character set, including
Scandinavian characters.

TradeXpress ®
Generix Group - All rights reserved 183
Character Sets / The Description Language

#
# UNOY
#
seps: 037\035\034\000
alpha: \ A-Za-z\133-\136\173-\176
alnum: !"%&'()*+,\-./0-9:;<=>?A-Za-z\
133-\136\173-\176
digit: 0-9
sign: \-
decimalpoint: .
discard: \000\011\012\014\015
whitespace: \011\012\015\040

The following character set definition describes the ISO 8859-1 character set; that is, UN/EDIFACT
character set C:

#
# UNOC (8859-1)
#
seps: :+'?
alpha: \ A-Za-z
#
# <tab>, <space> - <tilde>, <inverted !> - <small y with diaeresis>
#
alnum: \011\040-\176\241-\377
digit: 0-9
sign: +\-
decimalpoint: ,.
#
# NUL, NL, FF, CR
#
discard: \000\012\014\015
#
# upper- and lowercase special characters
#
locale: \300-\326\330-\337\340-\366\
370-\377
string: \001-\377
integer: 0-9
decimal: 0-9
#
# <tab>, NL, FF, CR, <space>
#
whitespace: \011\012\015\040

TradeXpress ®
Generix Group - All rights reserved 184
Annex E: Code Conversion in RTE

TradeXpress ®
Generix Group - All rights reserved 185
Code Conversion in RTE /

The RTE code conversion mechanism is based on code tables stored in ordinary ASCII files that
have two or more columns of data. For example, the following file, codes/owncode, could be used
as a code table.

BUYER BY 1

PAYER PY 2

VENDOR VE 3

The columns can be accessed by means of a special RTE expression that allows the user to
define (a) the key column and (b) the column from which the actual data item is picked.

The RTE expression syntax for code conversion has three variants:

<code file> {<key>, <col. separator>}


<code file> {<key>, <output col.>,
<col. separator>}
<code file> {<key col.>, <key>, <output col.>, <col. separator>}

The first variant assumes that the code file has a two- column layout. <key> is used as the key
value, and it is searched for from the first column. If a matching value is found, the value from the
second column is returned.

e2971 := "codes/owncodes" { "BUYER" , " " }

The above expression would produce “BY” as its value. The column separator character can be
any valid character, with a space or Tab being the most commonly used.

The second variant can be used with multi-column code files. This variant works like the first one,
except that the value is taken from the column specified by the second argument, <output col.>.

e2971 := "codes/owncodes" { "BUYER" , 3, " " }

The above expression would produce 1 as its value.

The last variant can be used when the key column is not the first column. This enables, for exam-
ple, the use of the code conversion table for both coding and decoding values.

e2971 := "codes/owncodes" { 2, "VENDOR" , 3, " " }

The above expression would produce 3 as its value.

The following technique is useful when writing RTE programs. The idea is that the user should always check the existence of the
actual code file in order to produce meaningful error messages and cause the desired results when errors occur.

TradeXpress ®
Generix Group - All rights reserved 186
Code Conversion in RTE /

! Th! This piece of RTE code would come before the begin section.
#define OWNCODE (A) fCodeFile.FULLNAME
{ A, " " }
...
! And this would be where code conversion is required.
e2971 := OWNCODE ("BUYER")
is piece of RTE code could be in the begin section
fCodeFile := build (sHOME, "codes/owncode")
if not fCodeFile.EXIST then
log ("Code conversion file for...not found,
resuming execution.", NL)
exit (1)
endif
...
! And this would be where code conversion is required
e2971 := fCodeFile.FULLNAME { "BUYER" , " " }

Another useful programming technique is to use macro definitions for code conversion expres-
sion. This helps reduce the excessive writing of code conversion expressions when writing trans-
lator programs.

! This piece of RTE code would come before the


! begin section.
#define OWNCODE (A) fCodeFile.FULLNAME { A, " " }
...
! And this would be where code conversion is
! required.
e2971 := OWNCODE ("BUYER")

TradeXpress ®
Generix Group - All rights reserved 187
Annex F: Advanced Utilities

Introduction
Pass-through Mode in RTE
Segment Look-ahead in the Receiving Translator
C Programming in RTE
RTE Coprocess Communications
RTE FTP Client Routine Library

TradeXpress ®
Generix Group - All rights reserved 188
Advanced Utilities / Introduction

Introduction

This appendix provides a thorough explanation of some of the advanced features of the RTE lan-
guage. These features will not necessarily be used in your daily work, but they provide tools for
the advanced use of TradeXpress. This appendix covers the following topics:

• pass-through mode in RTE


• segment look-ahead in the receiving translator
• C programming in RTE
• RTE - coprocess communications
• RTE FTP routine library
The first two topics cover EDI translation. They explain how the user can process very large mes-
sages with the minimum processing effort.

The C programming section explains how to interface existing function libraries or API’s to the RTE
translator. This feature can be used if the customer has ready-made functions for data manipula-
tion, or if the user wants to integrate the translator to a database using an API (application pro-
gram interface).

The coprocess communications section explains how to interface the translator to the existing
system using coprocess communications facilities. This kind of interface can be used with data-
bases or with application interfaces.

The FTP library section explains how users can easily program their own FTP procedures using
the TradeXpress FTP library. This library provides tools that help you rapidly develop new routines
for sample application interfaces using TCP/IP FTP functionality.

TradeXpress ®
Generix Group - All rights reserved 189
Advanced Utilities / Pass-through Mode in RTE

Pass-through Mode in RTE

In many business environments, operative systems tend to process large amounts of data infre-
quently, instead of processing smaller amounts more often. For example, the invoices containing
a week’s sales may be sent once a week, on Friday. On the other hand, the data involved in a busi-
ness transaction is usually repetitive by its nature. Orders, invoices, or dispatch advices, to men-
tion just a few, all consist of an unlimited number of line items.

With this in mind, the TradeXpress RTE translator has been enhanced to perform better with sin-
gle messages containing huge amounts of data. Performance is increased, and some problems
caused by system resource limitations are avoided. Pass-through mode enables the system to
process huge messages, as well as speeding up normal processing and releasing a lot of the
memory expended during normal operation.

The idea behind pass-through mode is that the message is read into memory segment by seg-
ment. In the sending direction, the user decides how many segments reside in memory simulta-
neously before memory is released. In the receiving direction, only one segment at a time is kept
in memory. In other words, a segment flows through the translator without being stored after it
has been processed. Because the entire message is never in memory at the same time, only
local syntax or message integrity checking can be performed. The user is responsible for doing
integrity checking for the whole message, using the appropriate RTE facilities, such as valid().

Receiving an EDI Message in Pass-through Mode


Pass-through mode for the receiving RTE translator is indicated in the message statement at the
beginning of the translator.

message "UN-EDIFACT/91.2/invoic.msg" receiving, passthru

In normal (non-pass-through) operations, the RTE translator first evaluates the EDI message,
checks the syntax and message structure integrity, and then passes the message segment by
segment to user-defined segment statements.

In pass-through mode, the RTE translator checks the syntax of the segment and the validity of
the message so far, and passes the segment immediately to the user-defined segment state-
ment. The memory used by the segment and the related data structures is released after the seg-
ment statement has been executed.

For the programmer, this means that elements outside the current segment cannot be accessed
(that is, elements in the previously processed segments). Of course, the data from the earlier ele-
ments can be stored in RTE variables and tables, but it is the programmer’s responsibility to take
care of resource management after having used the saved values.

TradeXpress ®
Generix Group - All rights reserved 190
Advanced Utilities / Pass-through Mode in RTE

Pass-through mode imposes new requirements on the translator in terms of inhouse file build-
ing. The conventional method is to build inhouse records immediately after each segment is
parsed. If there are errors in the message, the inhouse file constructed is inconsistent and must
be discarded in most cases. Thus it is good programming practice to build inhouse file from each
message into a buffer or temporary file. After the entire message is processed, the buffer or file is
concatenated into standard output.

Example:

segment UNH
put (1, 1, "UNH")
put (1, 4, e0062:14.14)
!- - - - - - - - - - - - - - - - -
! Save reference number for later use
!- - - - - - - - - - - - - - - - -
tRefNo := e0062
endsegment
...
segment UNT
if e0062 <> tRefNo then
log ("Inconsistent reference number.", NL)
exit (1)
endif
flush ()
endsegment

Building an EDI Message in Pass-through Mode


In normal (non-pass-through) operations, the RTE translator builds an EDI message guided by
the user-defined segment building statements. After the message is complete, the syntax and
validity are checked and the message is released to be output to the interchange construction
module.

The pass-through mode for the sending RTE translator is always available without any mode set-
tings. The pass-through-enhanced RTE translator builds the message into memory until the user
performs the flush function to output the message built so far. The memory used by the message
structure, segments, and related data structures is released after the flush has been executed.

For the programmer, this means that the elements built before the last flush cannot be accessed.
The data from the earlier elements can be stored in RTE variables and tables, but the programmer
is responsible for dealing with resource management after having used the saved values.

The user is responsible for validity checking of the message portions to be flushed. The user
must check for the validity of the segments and segment groups, as well as the appearance of
the mandatory segments outside any groups (segments in the 0- and 1-level of the message).

Here are the steps you would follow to use pass-through mode when constructing an effective
translator for an INVOIC message:

TradeXpress ®
Generix Group - All rights reserved 191
Advanced Utilities / Pass-through Mode in RTE

1. Build the header segments and the beginning section of the message and validate each
segment/group built.

2. Build the line item group.

3. In the appropriate segment of the line item group, validate the line item group and execute
the flush function.

4. Build the trailer part of the message, validate each segment/group built, and flush the
message.

The user will probably encounter difficulties while performing the validation and flushing proce-
dures, because the EDI message to be processed contains mostly optional segments. In many
cases, the only mandatory segment in a segment group is its leading segment. Thus, the checks
must be performed with the segment building operation that is always performed. The best
places for validation and flushing are usually the service segments (for example, EDIFACT UNS,
UNT) and the leading segments of the groups.

Example:

base "syslog.cfg" LOG

begin
...
! intermediate file for message part flushing
fTmpFile := LOG.temp
endbegin
line (1:"BGM")
!- - - - - - - - - - - - - - - - -
! Initiate message variables
!- - - - - - - - - - - - - - - - -
nERRORS:= 0
bUNH := FALSE
bBGM := FALSE
bUNS := FALSE
bUNT := FALSE
!
nMSG++
segment UNH
e0062 := build (nMSG)
eS009.0065 := "INVOIC"
eS009.0052 := "1"
eS009.0054 := "911"
endsegment
nUNH := bfValidSegment()

segment BGM
e1004 := pick (1, 4, 35)
eC507.2005 := "22"
eC507.2380 := time ("%Y%m%d")
eC507.2379 := "102"
endsegment
bBGM := bfValidSegment ()

TradeXpress ®
Generix Group - All rights reserved 192
Advanced Utilities / Pass-through Mode in RTE

endline
...
line (1:"LIN")
!- - - - - - - - - - - - - - - - -
! Output previous group (and header section
! segments)
!- - - - - - - - - - - - - - - - -
if bNewGroup then
if valid (GROUP g21) then
flush (MESSAGE) >>fTmpFile
else
log ("Errors found.", NL)
edierrordump (MESSAGE)
nERRORS++
endif
endif
segment LIN g21
e1233 := pick (1, 4, 3)
e1082 := pick (1, 7, 8)
endsegment
bNewGroup := TRUE
endline
line (1:"RFF")
segment RFF g21
eC506.1153 := "AAK"
eC506.1154 := pick (1, 15, 10)
endsegment
endline
line (1:"UNS")
!- - - - - - - - - - - - - - - - -
! Output the last group
!- - - - - - - - - - - - - - - - -
if valid (GROUP g21) then
flush (MESSAGE) >>fTmpFile
else
log ("Errors found.", NL)
edierrordump (MESSAGE)
nERRORS++
endif
segment UNS
e0081 := pick (1, 4, 1)
endsegment
bUNS := bfValidSegment()
endline
...
line (1: "UNT")
segment UNT
e0074 := pick (1, 4, 8)
e0062 := build (nMSG)
endsegment
bUNT := bfValidSegment()
!- - - - - - - - - - - - - - - - -
! Check the presence of mandatory 0- and
! 1-level segments
!- - - - - - - - - - - - - - - - -
if bUNH and bBGM and bUNS and bUNT then
flush (MESSAGE) >>fTmpFile
else
log ("Errors found.", NL)

TradeXpress ®
Generix Group - All rights reserved 193
Advanced Utilities / Pass-through Mode in RTE

edierrordump (MESSAGE)
nERRORS++
endif

TradeXpress ®
Generix Group - All rights reserved 194
Advanced Utilities / Segment Look-ahead in the Receiving Translator

Segment Look-ahead in the Receiving Translator

The RTE translator passes segments to user-defined segment statements in the same order as
segments occur in the message (tree traversal order). This order may sometimes cause extra
work when the message translator is built, which makes it useful to be able to “look ahead” at
segments while receiving an EDI message.

The statement peeksegment enables you to access segments before they are processed in the
user statements. It replaces the previous bfPeeksegment function described below.

Syntax:
peeksegment(text array, [[group/occurrence, spec.], name, number)

Limitations:
This statement cannot be used in EDI or AnyToAny syntax with passthru mode.

RTE Function

peeksegment, bfPeeksegment

The peeksegment statement replaces the formerly-used bfPeeksegment function.

Segment look-ahead function in receiving translators is available in both modes (standard and
passthru).

The passthru mode is not supported in Syntax to Syntax with passthru mode.

The bfPeekSegment function fetches a segment specified by the group and the repeat informa-
tion. If the segment is found, the contents of the elements are written in the array such that the
array index is the element name. The function returns TRUE if successful; otherwise FALSE.

bfPeekSegment(text array, [group/occurrence. spec.], name, number)

TradeXpress ®
Generix Group - All rights reserved 195
Advanced Utilities / Segment Look-ahead in the Receiving Translator

text array place for the element content

group/ group name and group occurrence


occurrence spec. number pairs for the entire path
from 0-level down to nearest group
level

name segment name to be accessed

number occurrence of the segment

The text array that is used to store the element contents is emptied every time the bfPeekSeg-
ment function is called.
The example below shows a look-ahead for the first occurrence of the DTM segment in group 5
repetition 2 under group 4 repetition 3.

bfPeekSegment(taPEEK, "4", 3, "5", 2, "DTM", 1)

bfPeekSegment takes a variable number of arguments, depending on the position (depth) of the segment to be accessed.

Example
The following example will skip all INVOIC messages having zero total amount in the MOA seg-
ment.

!
! Message Manager 0.0
!
! DATE: Mon Jun 13 11:45:40 1999
!

message "UN-EDIFACT/91.2/invoic.msg" receiving

segment UNH
nUNH := nGLB
put(nUNH, 1, "UNH_#")
put(nUNH + 0, 6, e0062:14)
put(nUNH + 0, 20, eS009.0065:6)
put(nUNH + 0, 26, eS009.0052:3)
put(nUNH + 0, 29, eS009.0054:3)
put(nUNH + 0, 32, eS009.0051:2)
put(nUNH + 0, 34, eS009.0057:6)
put(nUNH + 0, 40, e0068:35)
put(nUNH + 0, 75, eS010.0070:4)
put(nUNH + 0, 79, eS010.0073:1)
nGLB := nUNH + 0 + 1

if not bfPeekSegment(taPEEK, "15", 1, "MOA", 1) then


log("The peeked segment was not there", NL)
else

TradeXpress ®
Generix Group - All rights reserved 196
Advanced Utilities / Segment Look-ahead in the Receiving Translator

if number (taPEEK["C516.5004"]) = 0 then


log("Total amount is 0 skipping.", NL)

else
log("That much money, wow!!!", NL)
endif
endif
endsegment

segment BGM
nBGM := nGLB
put(nBGM, 1, "BGM_#")
put(nBGM + 0, 6, eC002.1001:3)
.
.
.
endsegment

.
.
.
segment UNT
nUNT := nGLB
put(nUNT, 1, "UNT_#")
put(nUNT + 0, 6, e0074:8)
put(nUNT + 0, 14, e0062:14)
nGLB := nUNT + 0 + 1

flush (0, 0, NL)


endsegment

end
.
.
.
endend

For more details about using peeksegment, bfPeeksegment for RTE traslator with XML
syntax, refer to the User’s Guide, Chapter Syntaxes, section XML.

TradeXpress ®
Generix Group - All rights reserved 197
Advanced Utilities / C Programming in RTE

C Programming in RTE

TradeXpress supports the use of the C programming language within the RTE programs. This fea-
ture is called RTE In-line C. It is a valuable tool, especially for advanced RTE programmers familiar
with C. The In-line C facility lets you insert your own C-written modules, functions, and libraries
directly into the RTE code. Furthermore, all the C run-time functions are at your disposal, in addi-
tion to RTE built-in functions, when you are coding translators and other RTE programs.

In-line C statements are passed directly to the C compiler without any modification by the RTE
compiler. In addition, the C preprocessor, a facility that existed in the earlier versions of RTE, can
be used to define symbols and macros, include code from other files, and perform conditional
compilation.

In-line C Block Statement


The In-line C block statement provides access to the description area of an RTE program. Users
can use this statement to define their own C functions and data structures.

Syntax:

inline<nl>
<C source code>
endinline<nl>

In-line C block statements can be located in any statement list or function part in the RTE file. The
order of appearance of the In-line C functions and their calls is not significant to RTE; a function
can be called before it is presented in the RTE file. And there are no limitations to the naming of
In-line C functions, as long as the calls are made as In-line C statements, described below.

The functions presented in the In-line C blocks can also be called as normal RTE statements. In
this case, the function names and return value types must meet the RTE requirements. The
name of a function begins with tf, nf, or bf, corresponding to the return value types text, numeric,
and Boolean, respectively. The associated C variable types are presented as follows:

C variable
Function name RTE variable type
type

tf<name> text char *

nf<name> numeric double

bf<name> Boolean int

Example:

TradeXpress ®
Generix Group - All rights reserved 198
Advanced Utilities / C Programming in RTE

inline
bfPrintHello ()
{
printf ("Greetings from \Inline\n");
}
double nfCounter (double x, double y)
{
return (x + y);
}
endinline

...

end
bfPrintHello()
nSum := nfCounter(1,2)
endend

In-line C Statements
In-line C statements provide access to the RTE program user statement area. Users can define
their own C statements, such as function calls and data structures, in this way. In-line C state-
ments are also useful when the user attaches API functions such as database access directly to
the RTE program.

Syntax:

inline "<C source code %N >",%0, %1, ..., %n<nl>

where %N represents a replaceable, ordinal macro variable.

These variables can be located anywhere in the C source code and they are replaced with argu-
ments from the argument list. Example: %0 is replaced with the first argument, %1 with the sec-
ond argument, etc. There is no limit to the number of variables.

Example:

inline
bfPrintHello (char *greetings)
{
printf ("Greetings\n\t%s \n" greetings);
}
endinline

...

end
bfPrintHello("from Paris.")

endend

Example 2
begin

TradeXpress ®
Generix Group - All rights reserved 199
Advanced Utilities / C Programming in RTE

inline "SQL_Connect(%0, %1, %2);", \"srv", ARGV[1], ARGV[2]


endbegin

...
line "1:DATA"
split (taData, pick(1,1,EOL), ",")
inline "SQL_Insert (%0, %1);", \taData[1], number (taData[2])
endline

...

end
inline "SQL_Disconnect();"
endend

TradeXpress ®
Generix Group - All rights reserved 200
Advanced Utilities / RTE Coprocess Communications

RTE Coprocess Communications

Coprocesses are normal Unix processes that are executed within a parent process, and their
input and output data is fed or processed by the parent process. Coprocesses are usually used
to perform tasks that are not programmed into the parent process, such as data communication
and database access.

RTE coprocess communication is not available in the NT environment.

Coprocess communication within RTE is implemented as a set of functions that can accomplish
the following:

• start the coprocess


• write input for the coprocess
• read output from the coprocess
• match text from the coprocess output stream.
In addition, the RTE switch statement has a new extension for matching and expecting coprocess
output.

Coprocess communication dedicated functions are different from the RTE runtime functions in
the sense that by default, they reside in their own library, called libcopro.a. If the default actions
of the functions do not meet the user’s needs, then the functions can be written like RTE func-
tions at the end of the RTE program.

Coprocess Communication Basics


Coprocess is a Unix process that is executed by another process as a child process. Characteris-
tic of the coprocess is that it is fed by data from the parent process, and/or the parent process
reads data from the coprocess. This conversation with the parent process distinguishes the
coprocess from the plain child process.

When working with coprocesses, you must always consider one-way versus two-way communi-
cations. One-way communications (either writing to the coprocess or reading from the copro-
cess) are comparatively straightforward. When writing to the coprocess, you must make sure
that the coprocess is ready for input, and when reading from the coprocess, you must take care
of timeouts while waiting for input.

Two-way traffic is more complicated because of the need for synchronization (for example, in
deadlock situations). There is a wide range of literature that deals with this subject.

TradeXpress ®
Generix Group - All rights reserved 201
Advanced Utilities / RTE Coprocess Communications

When starting different programs as a coprocess, you must also consider the startup environ-
ment. For example, some programs require a properly defined terminal environment (tty) or cer-
tain environment variables to be set before execution.

RTE Functions for Coprocess Communications


RTE provides a set of functions to handle the above- mentioned aspects of coprocess communi-
cations. There are functions for the startup environment setting, data input and output to and
from the coprocess, and synchronization.

When calls are made to the coprocess functions, they are read from libraries and perform default
actions. When specific tailoring, exception handling, or logging is needed, you can define your
own actions for any of these functions. These are user-provided functions that the user can cre-
ate and add to the end of the RTE file, similar to the other, ordinary user functions.

nPID := nfLaunchCoProcess (tCOMMAND)

Starts a coprocess given in tCOMMAND, with /bin/sh -c tCOMMAND. If tCOMMAND is empty,


just /bin/sh is started. Returns the pid of the started process, or 0 in case of failure.

The process is started on a pseudo terminal (pty), which has 256 columns and 25 lines. The
coprocess is given its own session if the underlying system supports it, or a process group
if not. The variables TERM=dumb, LINES=25, and COLUMNS=256 are inserted into the envi-
ronment of the coprocess. The pty is initialized to contain no-echo, no-postprocess, 8bit no-
parity, no-xon/xoff, canonical input. The control characters are the common ones, intr ^C,
quit ^\, erase ^H, kill ^U, eof ^D, and eol ^J. Before the command is executed, a call is
made to function bfCoProcessStartup(). This function can be tailored by the user to either
set different tty modes (with system("stty ...") for example), or execute coprocesses differ-
ently.

nRV := nfCloseCoProcess (nPID)

Closes the pty of the coprocess and waits for the process to exit. Returns the exit status of
the process: 0 if no coprocess was found or -1 on system error. Even though the process may
already have finished, this function is still needed to free memory that has been used for
managing the coprocess (the exit status is returned).

nHIT := nfExpectCoProcess (nPID, nSECONDS, tTOKEN0, tTOKEN1, ...,


EMPTY)

Wait until any of the given tokens appears on the input, or nSECONDS elapse. nSECONDS
equal to 0 means an immediate return, and any negative value means an infinite waiting
time. If a token is found, its order number on the argument list is returned; for example, the
appearance of tTOKEN1 would return 1. If no match is found in the given time, -1 is returned.
If the process dies unexpectedly, -2 is returned. -1 is returned if the user-supplied function
bfCoProcessNoMatch() returns TRUE for any line. Each call of this function flushes the read-
queue up to the last match.

TradeXpress ®
Generix Group - All rights reserved 202
Advanced Utilities / RTE Coprocess Communications

The pattern matching algorithm for tokens is simple. The characters ^ and $ are special if
they appear at the beginning or end, respectively. They can be used to anchor the token to
BOL and/or EOL. Other tokens can be found anywhere on a line. Lines end with a newline
character that should be added to a token when necessary. Prompts that do not end in
newline are best found with “^csh % $”. Complete lines require “^line\n$”.

tTTY :=tfCoProcessTty (nPID)

Returns the name of the pseudo terminal where the coprocess runs.

tTXT :=tfReadCoProcess (nPID)

Returns one line from the coprocess, waiting for one to appear if no lines were queued
already.

tTXT :=tfCollectCoProcess (nPID)

Returns one queued line from the coprocess and does not wait for more. Lines accumulated
between expects can be picked up with this function if it is called repeatedly until it returns
EMPTY.

bOK := bfCoProcessOkay (nPID)

Returns TRUE if the coprocess can be found and no errors have been detected during the
process.

bOK :=bfKillCoProcess (nPID, nSIGNAL)

Sends the nSIGNAL to the process given in nPID. Returns TRUE if the system call kill was
successful.

bOK := bfWriteCoProcess (nPID, tTXT)

Appends the data given in the text to the write queue of the coprocess, and tries to write
some amount to pty. Returns TRUE if the coprocess was found and no errors have been
detected.

bOK := bfFlushCoProcess (nPID)

Flushes (forgets) the read and write queues associated with the coprocess, and clears any
error condition. Returns TRUE if the coprocess was found.

bOK := bfDrainCoProcess (nPID)

Waits until all output has been written to the pseudo terminal of the coprocess from the write
queue. Returns TRUE if the process was found and the output completed without errors.

nOLD := nfDebugCoProcess (nHOW)

TradeXpress ®
Generix Group - All rights reserved 203
Advanced Utilities / RTE Coprocess Communications

Activation of debugging output. Any generated output is logged to stderr. The default state
is all debug output off. nOLD returns the old debug state, and nHOW sets the new one. Avail-
able bits for nHOW:

1 - input (data read from pty)


2 - output (data written to pty)
4 - expect matches (token that matched in expect)

The following functions can be supplied by the user and are called by the other functions in
the coprocess library.

Boolean bfCoProcessStartup (tTTY)

Called in the new process just before the command is to be executed. This is the proper
place, for example, to alter the terminal settings with the command system(“stty”). The
environment can also be changed here without disturbing the parent’s environment. If this
command returns TRUE, the command given to nfLaunchCoProcess() is executed. If it
returns FALSE, this is taken to indicate an error, and nfLaunchCoProcess() fails.

Boolean bfCoProcessInput (nPID, tTXT, nTXTLEN)

Called before a complete line from the coprocess is appended to a read queue. tTXT contains
the line whose length is nTXTLEN. This function should return FALSE if the line is to be
ignored. Can be used to filter uninteresting lines, or to process input line-by-line during nfEx-
pectCoProcess() or tfReadCoProcess().

Boolean bfCoProcessNoMatch (nPID, tTXT, nTXTLEN)

Called after a complete line has been tested against all tokens in nfExpectCoProcess(). tTXT
contains the line whose length is nTXTLEN. This function should return FALSE if expect is to
be continued. If it returns TRUE, expect terminates and returns -1. This could also be useful
for processing input lines during expect.

Boolean bfCoProcessExit (nPID, nEXITSTATUS)

This is called whenever the coprocess exits unexpectedly, for example during nfExpectCo-
Process().

Boolean bfCoProcessError (nPID, tSYSCALL, nERRNO, nRETVAL)

This is called after an io error is detected. The tSYSCALL can have the values “read” or “write”.
nERRNO is the system errno variable and nRETVAL is the return value from the failed system
call. If this function returns FALSE, the error is ignored. These functions are mainly used for
debugging or very special cases, and require the use of the C language in RTE.

int coprocess_expect_match (char *token, char *line, int linelen)

This function determines whether an expect token matches with an input. The token is the
user-supplied argument in nfExpectCoProcess(). Arguments line and linelen contain the

TradeXpress ®
Generix Group - All rights reserved 204
Advanced Utilities / RTE Coprocess Communications

input string that is to be matched and its length. A line can be terminated with a newline char-
acter, in which case it is a complete line. Otherwise the line may not yet be complete.

The function should return zero if no match was detected, or the number of bytes this match
removes from the line. One special case for this function is to support regular expressions
when matching input.

The default function supports only these special cases:

^text matches text at the beginning of the line

text$ matches text at the end of the line

These two can be mixed, in which case only exact lines will match. An example of a token that
would match a prompt from program foo would be “^foo> ”.

Note that $ does not imply a new line, so complete lines should be matched with ^line\n$.
This requires knowledge of the terminal modes. In normal use, the terminal is configured to
produce only a newline character, but programs could change the modes so that a carriage
return is also appended to output lines.

int coprocess_input_cleanup(char *text, int len)

Function to clean up text that has been read from the terminal. The function should modify
the text as appropriate and return the modified length of the line. The original length (len)
should not be exceeded.

int coprocess_debug_flags;
Void coprocess_debug_input (char *text, int len) flag 1
Void coprocess_debug_output (char *text, int len) flag 2
Void coprocess_debug_match (char *token) flag 4

These functions are called after a match is found in nfExpectCoProcess(), after reading
some amount of data from the terminal, and after writing data to the terminal, respectively.
The default functions log to stderr, if the corresponding bit is set in the flag integer. By
default, nothing is logged.

RTE Extension for Coprocess Communications


The RTE language has an extension of the switch statement for use by the coprocess library.

switch expect <PID> <time-out>


case <string>:
<RTE statements>
...
endswitch

A parameter timeout of 0 means an immediate return and any negative value means infinite
waiting.

TradeXpress ®
Generix Group - All rights reserved 205
Advanced Utilities / RTE Coprocess Communications

This example shows the wait for the string Password: at the beginning of the input line from the
coprocess that is executing the FTP file transfer program:

switch expect nPID 5


case "^Password:":
bfFlushCoProcess (nPID)
inline "sleep (1);"
bfWriteCoProcess (nPID, tPasswd)
case "^55":
bfErrorProcessing ()
endswitch

Example 1: FTP Session Driven by the RTE Translator


begin
tCommand := "ftp -n"
tHost := "open localhost 10021\n"
tUser := "user xxxx\n"
tPasswd := "yyyy\n"
tQuit := "quit\n"
nPID := nfLaunchCoProcess(tCommand)
if nPID = 0 then
log ("Cannot execute:: ", tCommand, NL)
exit (1)
endif
nfExpectCoProcess(nPID, -1, "^ftp>", EMPTY)
bfWriteCoProcess(nPID, tHost)
nfExpectCoProcess(nPID, -1, "^ftp>", EMPTY)
bfWriteCoProcess(nPID, tUser)
nfExpectCoProcess(nPID, -1, "^Password:", EMPTY)
bfWriteCoProcess(nPID, tPasswd)
nfExpectCoProcess(nPID, -1, "^ftp>", EMPTY)
bfWriteCoProcess(nPID, "ls\n")
nfExpectCoProcess(nPID, -1, "^ftp>", EMPTY)
tLine := tfCollectCoProcess(nPID)
while tLine <> EMPTY do
if compare (tLine, "ftp>") then
break
endif
print (tLine)
tLine := tfCollectCoProcess(nPID)
endwhile
bfWriteCoProcess(nPID, tQuit)
nfCloseCoProcess(nPID)
endbegin
function bfCoProcessInput (nPid, tLine, tLen)
log ("FTP:: ", tLine, NL)
return TRUE
endfunction

===========>

$ ftp -n
ftp> open localhost
Connected to localhost.

TradeXpress ®
Generix Group - All rights reserved 206
Advanced Utilities / RTE Coprocess Communications

220 mymmeli FTP server (Version 1.7.109.2 Mon Aug 3 22:28:13 GMT
1992) ready.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> user xxxx
331 Password required for solid.
Password:
230 User xxxx logged in.
ftp> ls
200 PORT command successful.
150 Opening ASCII mode data connection for /bin/ls.
total 52
-rw-r--r-- 1 solid users 377 Feb 23 10:37 .login
-rw-r--r-- 1 solid users 551 Mar 6 14:15 .profile
drwxr-xr-x 2 solid users 1024 Mar 10 17:56 base
drwxr-xr-x 2 solid users 1024 Feb 27 10:34 bin
drwxr-xr-x 5 solid users 1024 May 4 11:41 src
drwxr-xr-x 3 solid users 1052 Mar 20 18:00 work
226 Transfer complete.
ftp> quit
221 Goodbye.

Example 2: SQL Interpreter Session Driven by the RTE Translator


begin
tCommand := "exec solsql \"tcpip mymmeli
1313\""
tUser := "xxxx\n"
Passwd := "yyyyy\n"
Quit := "quit;\n"
nPID := nfLaunchCoProcess(tCOMMAND)
if nPID = 0 then
log ("Cannot execute:: ", tCommand, NL)
exit (1)
endif
if oX then
!
! Debug input, output and matches.
!
nfDebugCoProcess(7)
endif

switch expect nPID -1


case "^Username:":
bfFlushCoProcess(nPID)
bfWriteCoProcess(nPID, tUser)
endswitch

switch expect nPID 5


case "^Password:":
bfFlushCoProcess(nPID)
inline "sleep(1);"
bfWriteCoProcess(nPID, tPasswd)
endswitch

switch expect nPID -1


case "^SOLID SQL Editor":

TradeXpress ®
Generix Group - All rights reserved 207
Advanced Utilities / RTE Coprocess Communications

bfFlushCoProcess(nPID)
break
endswitch
bfWriteCoProcess(nPID, "SELECT * FROM CARS;\n")
switch expect nPID -1
case " rows fetched.\n":
break
endswitch

while bfGetLine() do
print (tLine)
endwhile

bfWriteCoProcess(nPID, tQuit)

nEXIT := nfCloseCoProcess(nPID)
endbegin

function bfCoProcessInput (nPID, tLine)


if oD then
log ("INPUT:: ", tLine, NL)
endif
return TRUE
endfunction

function bfGetLine ()
tLine := tfCollectCoProcess(nPID)
if tLine <> EMPTY then
return TRUE
else
return FALSE
endif
endfunction

=======>

select * from cars


MODELCOLORPRICE
-----------
-----
Volvo 850Yellow250000
Peugeot 405Red150000
Lada 1200White25000
Fiat UnoBlack50000
4 rows fetched

TradeXpress ®
Generix Group - All rights reserved 208
Advanced Utilities / RTE FTP Client Routine Library

RTE FTP Client Routine Library

TradeXpress’s basic facilities provide FTP send and FTP fetch functionality for the most common
file transfer purposes. These routines have parameters to meet users’s needs, from file type def-
inition to acknowledgement facilities. However, there are a number of FTP file transfer situations
which these predefined routines cannot handle; for example, specialized login procedures and
file transfer actions where several files are transferred during a single session.

The RTE FTP Client Routine Library has all atomic FTP client commands as RTE functions. These
functions are available from RTE programs (such as EDI translators or any general purpose RTE
programs). These functions contain three basic features:

• timeout processing
• log information processing
• user-defined error detection

Compiling RTE Source Code with the FTP Client Routine Library
An RTE program using the FTP Client Routine Library must be compiled using the following mktr
command:

$ mktr ownftp.rte -lnetlib (Unix)

%EDIHOME%\lib\libnetlib.lib (Windows NT)

The FTP Client Routine Library includes a component that manages the password encryption and
decryption.

The user must write the function bfExit(tErrorMsg) in the RTE program. This function is called
automatically when an error is encountered. It is possible to call the function manually as well.
This function should not return.

Parameters used:

• pFTP.HOST - string
• pFTP.USER - string
• pFTP.PASSWORD - string
• pFTP.PASSWORD.ENCRYPTED-string (overrides PASSWORD)
• pFTP.ACCOUNT - string
• pFTP.SITE - string (\\n line separator)
• pFTP.XFER.TYPE - IMAGE,ASCII, a.s.o.

TradeXpress ®
Generix Group - All rights reserved 209
Advanced Utilities / RTE FTP Client Routine Library

• pFTP.BINARY - “1” or not


• pFTP.USE_PASV - “1” or not
• pFTP.XFER.WATCHDOG - (numeric) string, minutes

RTE Functions for FTP Communication

General functions for FTP


Generally, all Boolean functions return FALSE when any error occurs, but the severity of the error
depends on the function. Text functions return EMPTY on error.

taFTP_ALL
taFTP_OK
taFTP_ERROR

RTE arrays containing user-defined errors and notes. OK contains patterns that should be
accepted as okay; ERROR contains patterns that should be rejected as error responses.

bfFTP_watchdog(nMinutes)

Either sets the timeout (in minutes) or resets it (when the given time is zero). If any activity
lasts longer than the timeout, transfer is aborted.

bfFTP_initialize()

Initializes the system, rewinds log history, and loads user-defined errors.

bfFTP_open(tHost, tUser, tPassWord, tAccount)

Makes an implicit call to bfFTP_initialize if this has not already been done.

Opens a control connection to a given host. If the account is non-empty, it is sent immedi-
ately after logging in and remembered. When an activity requires an account, the same
account is used again.

If necessary, the remote server port can be given after the host name as a service name or a
port number, separated with a “:”; for example, host.name:ftp or 1.2.3.4:2002.

bfFTP_close()

Closes the current connection.

tfFTP_logtext()

Returns and rewinds the log history collected so far.

bfFTP_setlogging(nLevel)

TradeXpress ®
Generix Group - All rights reserved 210
Advanced Utilities / RTE FTP Client Routine Library

Sets the detail of logging. Levels above 2 log the session continuously into the LOGGING
stream.

bfFTP_ascii()
bfFTP_binary()
bfFTP_ebcdic()
bfFTP_type(tType)

Sets the active transfer type, which can be one of the following:

- IMAGE, image, i, I
- binary, BINARY, bin, BIN
- ASCII, ascii, ASC, asc, a, A
- EBCDIC, ebcdic, e, E
tfFTP_command(tCmd)

Sends the given command and returns the response.

tfFTP_site(tCmd)

Sends the given command prepend with “SITE” and returns the response.

tfFTP_pwd()

Returns the current directory.

tfFTP_lastreply()

Returns the last response received.

nfFTP_size(tRemotefile)

Returns the size of a given file. May not be supported by all FTP servers. Return value is -1 if
the size could not be determined (if the file is nonexistent, for example).

tfFTP_modtime(tRemotefile)

Returns the modification time of the given file. EMPTY on error. The FTP server should format
the response in the format yyyymmddHHMMSS in UTC time. This can vary with nonstandard
servers.

bfFTP_del(tRemotefile)

Deletes the given file.

bfFTP_rename(tFrom, tTo)

Renames tFrom to tTo.

TradeXpress ®
Generix Group - All rights reserved 211
Advanced Utilities / RTE FTP Client Routine Library

bfFTP_cd(tRemotedir)

Changes the directory. If tRemotedir is “..”, then CDUP is used instead of CWD.

bfFTP_putas(tLocal, tRemote)

Stores local file tLocal as tRemote.

bfFTP_putas_uniq(tLocal, tRemote)

Stores the local file tLocal as tRemote. In addition, the FTP server constructs a unique file
name by appending a running number to the remote name.

This should prevent file overwriting, but again, nonstandard FTP servers may cause prob-
lems. The actual remote file name can be collected, after the put has completed, with the call
tfFTP_lastuniq().

bfFTP_appendas (tLocal, tRemote)

Appends local file TLocal to tRemote. If tRemote does not exist, it is created.

tfFTP_lastuniq()

Returns the last unique file name received from the FTP server.

bfFTP_getas(tRemote, tLocal)

Retrieves the given remote file to the local file.

bfFTP_put(tFilename)
bfFTP_get(tFilename)

A put and get that use the base name of the given file as the other name. When putting local
file /etc/passwd, the remote name is passwd; and when getting remote file /etc/passwd,
the local file is passwd.

bfFTP_dir(tRemote, taArray)
bfFTP_nlist(tRemote, taArray)

Long or short directory listing. The array is first cleared, then filled line-by-line from the
output from the command (LIST or NLST).

tfFTP_clean_multiline(tCommandSequence)

Replaces every “\\n” in sequence with a real new line.

tfFTP_user_reject_check(tResponse)

Can be used to detect user-defined errors. First the OK patterns are searched for a match to
screen out valid responses, and then the ERROR patterns are searched. Returns EMPTY
when the response is OK, and an error string if a match is found in ERRORs.

TradeXpress ®
Generix Group - All rights reserved 212
Advanced Utilities / RTE FTP Client Routine Library

bfLogIn()

Loads user-defined errors. They are searched from $FTPERR, $HOME/.ftperr, and finally
$EDIHOME/lib/ftperr. Logs in if not already logged in. Retries twice to connect. Exits if the
connection cannot be opened. Runs the site command sequence from pFTP.SITE.

bfLogInTSI( sBase, tType, nIndex )

Needs to replace bfLogIn() if pFTP.PASSWORD is encrypted (e.g.: pFTP.PASS-


WORD={tsi}1egdSgBs9AsUy)

sBase : Path environment variable to the database where the password is stored. (e.g.:
sPARTNER)

tType : Database type (partner or edisend).

nIndex : Encrypted password entry of the database index.

The behaviour is the same as with bfLogIn, plus the password decryption.

bfLogOut()

Closes the connection if necessary and resets directory-changing variables.

bfCWD(tDir)

Changes the remote directory. An empty tDir is taken as the initial login directory. Never
fails; bfExit() is called if chdir does not succeed. Keeps the current remote directory in tFtp-
CurDir, and logs in when necessary.

bfSizeOK(tRemote, tLocal)

Checks that the local and remote files have the same size. Diagnostic is always logged in
case of a mismatch, but an error is returned only when using IMAGE transfer.

bfSetSafetyTimeout()

Sets the timeout in pFTP.XFER.WATCHDOG.

bfDoSiteCommands(tCmds)

Text in pFTP.SITE is cleaned and sent line-by-line to the server.

TradeXpress ®
Generix Group - All rights reserved 213
Advanced Utilities / RTE FTP Client Routine Library

Example: A Simple FTP Send Program

!=====================================================================
! pFTP.ACK.DIR - remote directory for the acknowledge flag files
!
! FTP.SITE=UMASK 022\nIDLE 3333
! FTP.REMOTENAME=remfil
! FTP.REMOTEDIR=remdir
! FTP.ACCOUNT=account
! FTP.PASSWORD=password
! FTP.USER=testuser
! FTP.HOST=host
! FTP.DIRNAME=dirname
!====================================================================

!---------------------------------------------------------------------
! Generic rte-routines for manipulating FTP.
!---------------------------------------------------------------------

begin
! ---------------------------------------------------------------
! The remote_file_ is constructed in transport, from remote_name_
and counters. We should do that
! here, but...
! ---------------------------------------------------------------
if pFTP.REMOTEFILE = EMPTY then
pFTP.REMOTEFILE := pFTP.REMOTENAME
endif

if ARGV[1] = EMPTY then


log ("Need filename to send\n")
exit (3)
endif
fFILE := ARGV[1]
if fFILE.EXIST = FALSE then
log ("Cannot open file \"", ARGV[1], "\" (does not exist)\n")
exit (3)
endif
if fFILE.READ = FALSE then
log ("Cannot open file \"", ARGV[1], "\"\n")
exit (3)
endif

!-----------------------------------------------------------------
----------------------------------
! Log in
! if pFTP.PASSWORD is not crypted −> bfLogIn()
! if pFTP.PASSWORD is crypted -> bfLogInTSI(sPARTNER,”part-
ner”,100)
!-----------------------------------------------------------------
----------------------------------

bfLogIn()
!-----------------------------------------------------------------
----------------------------------

TradeXpress ®
Generix Group - All rights reserved 214
Advanced Utilities / RTE FTP Client Routine Library

! Send datafile (and flag file, if necessary), close and exit.


Simple...
!----------------------------------------------------------------
-----------------------------------

bfSendFiles()
bfFTP_close()
bfExit(EMPTY)
endbegin

function bfSendFiles ()
!----------------------------------------------------------------
-----------------------------------
! Transfer directly to final filename.
!----------------------------------------------------------------
-----------------------------------
tRem := build(pFTP.REMOTEFILE, pFTP.SPECIAL)
if not bfFTP_putas(fFILE.FULLNAME, tRem) then
bfExit("Send failed")
endif
endfunction
!---------------------------------------------------------------------
----------------------------------
! Exit program. If errortext is nonempty, there was an error. Log ses-
sion on errors or if debugging.
!---------------------------------------------------------------------
----------------------------------
function bfExit (tErrorText)
if tErrorText <> EMPTY then
log("INFO: ", tErrorText, NL)
endif
if tErrorText <> EMPTY or LOGLEVEL > 0 then
log("\n*** FTP Session log follows: \n", tfFTP_logtext(),
"\n*** End of session log\n")
endif
if tErrorText <> EMPTY then
exit(1)
endif
exit(0)
endfunction

Specific FTPS RTE functions


Creating a RTE program for ftpfetch and ftpsend fitted to secure transfer of data over a FTP ses-
sion is possible:

Switch to secure FTP by just adding a simple function call to an initialisation function at the very
beginning of your RTE. And after this call all subsequent transfers will be encrypted automati-
cally. The only thing you have to remember is a single function name if you want to switch to
secure FTP over SSL.

TradeXpress ®
Generix Group - All rights reserved 215
Advanced Utilities / RTE FTP Client Routine Library

Hereafter a description of the FUNCTION:

bfSet_security_ssl

This function allows to link the C code with the RTE code so that a user can decide to start
secure FTP communications. After this function is run successfully, all subsequent calls will
be encrypted

Hereunder, the INPUT descriptions:

tPriv_key_file

Name of the file containing the User's private key (it can contain prefix such as : tx: or ldap:
or file: )

tPriv_key_pwd

Name of the file containing the private key's password (or passphrase)

tCacert_fichier

Name of the file containing the trusted certificates list (Server certificate)
(it can contain prefix such as : tx: or ldap: or file: )

tClientcert_fichier

Name of the file containing the client certificate (user certificate)


(it can contain prefix such as : tx: or ldap: or file: )

tSecBase

True if security base has been disabled, false otherwise.


This option allows to shortcut the security database if necessary, but it is recommended not
to use it (it is useful mostly for problems diagnostic), thus you should put “FALSE” (upper or
lowercase).

tClient_Auth_Server

True if the client Must authenticate the server, false otherwise.


This option allows to state whether the client should check the server’s certificate or not.

tPartner_Name

Name of partner used to find a default server certificate when tCacert_fichier field is empty.
Notice that this field is not mandatory if tCacert_fichier is not empty, but if tCacert_fichier is
empty, tPartner_Name MUST be filed to retrieve the Server’s certificate.

TradeXpress ®
Generix Group - All rights reserved 216
Advanced Utilities / RTE FTP Client Routine Library

Example of RTE function with FTPS

begin

/*
We suppose here that the necessary parameters are given to the program
when program is launched. In other words the program will probably be
called with a parameter file given as follows :
./my_ssl_test -p <param_filename>
That’s the reason why we have access to all necessary arguments for the
function “bfSet_security_ssl” since the beginning of the RTE program.
*/

bRet := bfSet_security_ssl(FTP.SSL.PRIVATE_KEY_FILE,
pFTP.SSL.PRIVATE_KEY_PASSWORD, pFTP.SSL.CACERT_FILE,
pFTP.SSL.CLIENTCERT_FILE, pFTP.SSL.SECURITY_BASE_DISABLED,
pFTP.SSL.SERVER_AUTH, pFTP.SSL.PARTNER_NAME )

if bRet then
log("+++ ERROR: SSL Security initialization failed",
NL )
bfExit("Can't proceed, exiting")
else
log("SSL Security setting....[SUCCESS]\n")
endif

endbegin

Specific SFTP RTE functions


TradeXpress users may use these functions to write or develop directly and dynamically RTE pro-
cedures to build their data transfer services, by relaying on the SFTP protocol.

The RTE library for SFTP communication in TradeXpress offers primitive functions whose descrip-
tion is listed hereafter.

Most of these SFTP functions are SFTP equivalent to existing FTP functions.

Opening an closing a SFTP connection


These functions are used to open, establish, close a SFTP connection on a remote workstation

bfSFTP_Open (tHost, tUser, tPassword, tAccount)

Opens a SFTP connection

bfSFTP_Close ()

Closes an established connection

TradeXpress ®
Generix Group - All rights reserved 217
Advanced Utilities / RTE FTP Client Routine Library

bfSFTP_Initialize ()

Initializes the system, rewinds log history,and loads user-defined errors.

bfSFTP_LogIn ()

Logs in if not already logged in.

bfSFTP_LogOut ()

Closes the connection if necessary.

bfSFTP_LogInPwd(tPassword)

Allows to log in to an opened SFTP connection

bfSFTP_LogInTSI (sBase, tType, nIndex)

Refer to the description of the bfLogInTSI( sBase, tType, nIndex ) function

bfSFTP_Open_Ex (tHost, tUser, tPrivFile, tPubFile, tPassphrase,tAc-


count)

Opens a SFTP connection using the public and private key files

Handling operations on the remote workstation


Users who need to handle and receive extra information from a file or a directory may use the fol-
lowing functions.

tfSFTP_pwd ()

Refer to the description of the tfFTP_pwd() function

bfSFTP_del (tRemoteFile)

Removes a remote file

bfSFTP_rename (tFrom, tTo)

Renames a remote file (tFrom to tTo)

bfSFTP_CWD (tRemoteDir)

Refer to the description of the bfCWD(tDir) function

bfSFTP_SizeOk (tRemote, tLocal)

Refer to the desription of the bfSizeOK function

nfSFTP_size ()

TradeXpress ®
Generix Group - All rights reserved 218
Advanced Utilities / RTE FTP Client Routine Library

Refer to the description oif the nfFTP_size function

tfSFTP_modtime (tRemoteFile)

Refer to the description of the tfFTP_modtime function

Transfering files or data


These functions are used to send files from the local workstation to the remote workstation and
receive files from the remote workstation to the local workstation

bfSFTP_putas (tLocal, tRemote)

Sends a file from the local workstation to the remote workstation

bfSFTP_getas (tRemote, tLocal)

Receives a file from the remote workstation to the local workstation

bfSFTP_nlist (tRemote, taArray)

Retrieves the list of files from a directory

Refer to the description of the bfFTP_nlist function

Managing Logs
tfSFTP_lastreply ()

Returns the last error message from the SFTP server in case of error only.

This function differs from the tfFTP_lastreply () which returns the last received answering from the FTP server in case of
error or success.

bfSFTP_logtext ()

Returns the log history collected so far.

bfSFTP_setlogging (nLevel)

Refer to the description of the bfFTP_setlogging(nLevel)function

Error management
taSFTP_ALL
taSFTP_OK
taSFTP_ERROR

Refer to the description of the FTP error arrays

TradeXpress ®
Generix Group - All rights reserved 219
Advanced Utilities / RTE FTP Client Routine Library

SFTP test program


This section describes the RTE programs used to test the RTE SFTP library. These programs are
given here as examples.

Usable parameters
Use the following parameter to log in and to handle operations on the SFTP server.

• For ClientSendSFTP program

Parameter Description

FTP.ACK.DIR remote directory for acknowledge flag files

FTP.REMOTEFILE remote file

FTP.REMOTEDIR remote directory

FTP.HOST host name

FTP.USER login user

FTP.PASSWORD login password

FTP.SSH.PRIVATE_KEY_REALPATH private key file path

FTP.SSH.PUBLIC_KEY_REALPATH public key file path

FTP.SSH.PRIVATE_KEY_PASSPHRASE private key pass phrase

FTP.DIRNAME directory name

RECIPIENT index name of database PARTNER

• For ClientFetchSFTP program

Parameter Description

FTP.ACK.DIR remote directory for acknowledge flag files

FTP.LOCALFILE local file

FTP.REMOTEDIR remote directory

FTP.HOST host name

FTP.USER login user

FTP.PASSWORD login password

FTP.SSH.PRIVATE_KEY_REALPATH private key file path

FTP.SSH.PUBLIC_KEY_REALPATH public key file path

TradeXpress ®
Generix Group - All rights reserved 220
Advanced Utilities / RTE FTP Client Routine Library

Parameter Description

FTP.SSH.PRIVATE_KEY_PASSPHRASE private key pass phrase

FTP.DIRNAME directory name

FTP.FILEMASK file mask

CONNECTION index name of database EDISEND

Windows environnement
• Connection in a « username and password » mode
ClientSendSFTP.exe
FTP.HOST=aixpress
FTP.USER=edimanu
FTP.PASSWORD=edimanu
FTP.REMOTEFILE=WAB_04.xml WAB.xml
ClientFetchSFTP.exe
FTP.HOST=aixpress
FTP.USER=edimanu
FTP.PASSWORD=edimanu
FTP.REMOTEDIR=dao
FTP.LOCALFILE=WAB_04.xml WAB.xml

• Connection in a « public and private keys » mode


ClientSendSFTP.exe
FTP.HOST=aixpress
FTP.USER=edimanu
FTP.SSH.PRIVATE_KEY_REALPATH=c:\demo\id_rsa
FTP.SSH.PUBLIC_KEY_REALPATH=c:\demo\id_rsa.pub
FTP.SSH.PRIVATE_KEY_PASSPHRASE=pass1
FTP.REMOTEFILE=WAB_04.xml WAB.xml

ClientFetchSFTP.exe
FTP.HOST=aixpress
FTP.USER=edimanu
FTP.SSH.PRIVATE_KEY_REALPATH=c:\demo\id_rsa
FTP.SSH.PUBLIC_KEY_REALPATH=c:\demo\id_rsa.pub
FTP.SSH.PRIVATE_KEY_PASSPHRASE=pass1
FTP.REMOTEDIR=dao
FTP.LOCALFILE=WAB_04.xml WAB.xml

• Connection « using a PARTNER database entry »

ClientSendSFTP.exe
RECIPIENT=SFTPAixpress
FTP.REMOTEFILE=WAB_04.xml WAB.xml

ClientFetchSFTP.exe
CONNECTION=SendSFTPAixpress
FTP.LOCALFILE=WAB_04.xml WAB.xml

Linux and other Unix environnements


• Connection in a « username and password » mode

TradeXpress ®
Generix Group - All rights reserved 221
Advanced Utilities / RTE FTP Client Routine Library

ClientSendSFTP
FTP.HOST=aixpress
FTP.USER=edimanu
FTP.PASSWORD=edimanu
FTP.REMOTEFILE=WAB_04.xml WAB.xml

ClientFetchSFTP
FTP.HOST=aixpress
FTP.USER=edimanu
FTP.PASSWORD=edimanu
FTP.REMOTEDIR=dao
FTP.LOCALFILE=WAB_04.xml WAB.xml

• Connection in a « public and private keys » mode


ClientSendSFTP
FTP.HOST=aixpress
FTP.USER=edimanu
FTP.SSH.PRIVATE_KEY_REALPATH=c:\demo\id_rsa
FTP.SSH.PUBLIC_KEY_REALPATH=c:\demo\id_rsa.pub
FTP.SSH.PRIVATE_KEY_PASSPHRASE=pass1
FTP.REMOTEFILE=WAB_04.xml WAB.xml

ClientFetchSFTP
FTP.HOST=aixpress
FTP.USER=edimanu
FTP.SSH.PRIVATE_KEY_REALPATH=c:\demo\id_rsa
FTP.SSH.PUBLIC_KEY_REALPATH=c:\demo\id_rsa.pub
FTP.SSH.PRIVATE_KEY_PASSPHRASE=pass1
FTP.REMOTEDIR=dao
FTP.LOCALFILE=WAB_04.xml WAB.xml

• Connection « using a PARTNER database entry »

ClientSendSFTP
RECIPIENT=SFTPAixpress
FTP.REMOTEFILE=WAB_04.xml WAB.xml

ClientFetchSFTP
CONNECTION=SendSFTPAixpress
FTP.LOCALFILE=WAB_04.xml WAB.xml

• Compilation:
Use the following command line to compile the rte files.

mktr ClientSendSFTP.rte $EDIHOME/lib/libnetlib_sftp.a -L/usr/lib


$EDIHOME/lib/libcurl.a $EDIHOME/lib/libssh2.a $EDIHOME/lib/lib-
crypto.a
$EDIHOME/lib/libz.a $EDIHOME/lib/libssl.a -ldl

mktr ClientFetchSFTP.rte $EDIHOME/lib/libnetlib_sftp.a -L/usr/lib


$EDIHOME/lib/libcurl.a $EDIHOME/lib/libssh2.a $EDIHOME/lib/libssl.a
$EDIHOME/lib/libcrypto.a $EDIHOME/lib/libz.a -ldl

TradeXpress ®
Generix Group - All rights reserved 222
Annex G: RTE SQL Access Library

Introduction
RTE SQL Access Library Reference List
ODBC interface
JDBC Interface
Example of an RTE Program with SQL Access

TradeXpress ®
Generix Group - All rights reserved 223
RTE SQL Access Library / Introduction

Introduction

TradeXpress has a new facility that lets you access the relational databases using SQL syntax.
Access is provided directly from the RTE translators. SQL access is provided by a set of RTE run-
time functions, which access relational databases using SQL syntax. They also enable automatic
database variable binding with the RTE variables.

The RTE SQL access library and its functions are designed in such a way that they can be used
seamlessly with any commercially recognized relational database that provides SQL access.
Depending on the underlying database system, the access can be local or networked.

The RTE SQL library gives access to a Oracle database in native mode (OCI), or to any other SQL-
type database via an ODBC or JDBC connector.

An RTE translator using RTE SQL access becomes a database client program, and its behavior,
resource requirements, and database access license issues are like those of any general pur-
pose database access client within the database environment that is being used.

Requirements
RTE translators that use RTE SQL access require, at a minimum, the database provider’s runtime
environment (Oracle7 / Oracle8) to be installed and configured.

Compilation
An RTE translator using the RTE SQL access library is compiled like normal RTE translators. The
linking phase requires special libraries for database access functions. The ccargs file (EDIHOME/
lib/ccargs) can be used with TradeXpress. Here are examples of the ccargs file on different plat-
forms:

Windows NT:
libruntime.lib liblogsystem.lib libedi.lib
Z:\orant\oci73\lib\msvc\ociw32.lib libessqlora.lib libodbsys.lib
wsock32.lib

SUN SOLARIS
-L/u/tradexpress4.0/lib -L/usr/local/oracle7/lib -lruntime -llogsystem
-ledi -lclntsh -lm -lsocket -lnsl -lessqlora -lodbsys -lruntime

IBM AIX:
-L/u/tradexpress4.0/lib -L/home/oracle7/lib -llogsystem -ledi -lclntsh
-lm -lessqlora -lodbsys -lruntime

TradeXpress ®
Generix Group - All rights reserved 224
RTE SQL Access Library / Introduction

Execution Environment
The database clients using shared libraries often require special user environment settings to be
able to locate and access database libraries and resources correctly. The following environment
settings can be used with the TradeXpress and Oracle 7 / Oracle 8 databases. These settings are
found in the oraenv file located at $EDIHOME/lib/oraenv.

ORACLE_HOME=/usr/local/oracle7
export ORACLE_HOME

PATH=$PATH:$ORACLE_HOME/bin
NLS_LANG=American_America. WE8ISO8859P1
ORACLE_BASE=$ORACLE_HOME
ORACLE_SID=ES
ORA_NLS=$ORACLE_HOME/ocommon/nls/admin/data
ORACLE_DOC=$ORACLE_HOME/doc
NLS_ADMIN=$ORACLE_HOME/network/admin
ORACLE_TERM=$TERM
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME lib
export PATH NLS_LANG ORACLE_BASE ORACLE_SID ORA_NLS ORACLE_DOC
NLS_ADMIN
ORACLE_TERM LD_LIBRARY_PATH

TradeXpress ®
Generix Group - All rights reserved 225
RTE SQL Access Library / RTE SQL Access Library Reference List

RTE SQL Access Library Reference List

bfSqlOracle ("DBID", "User", "Passwd", "DBLink")


Function
Establishes connection to Oracle database.

Parameters
• "DBID" Database ID. Used with other functions to identify connection. Value can be any string.
• "User" Oracle user ID. If the operating system authentication is used, set this to “/”.
• "Passwd" Oracle user’s password. If the operating system authentication is used, leave this
empty; i.e., “”.
• "DBLink" Database connection ID (SQLNet V2 connect descriptor).
Return value
TRUE, if succeeds.

bfSqlSet ("DBID", "SqllD", "SQLString")


Function
Creates new or modifies existing SQL command.

Parameters
• "DBID" Database ID. Created with the bfSqlOracle function.
• "SqlID" SQL command identification. Value can be any string.
• "SQLString" SQL command string. RTE numeric and text variables can be used as part of the
SQL command. For example:
"UPDATE table_x SET field1 = :tTclVariable
WHERE field2 >= :nTclVariable2"

Return value
TRUE, if succeeds.

If the SQL command is an Oracle database administration command (for example, CREATE TABLE), it is executed immediately.

tfSqlGetField("DBID","SqlID","Field")
Function

TradeXpress ®
Generix Group - All rights reserved 226
RTE SQL Access Library / RTE SQL Access Library Reference List

Retrieves the value of the fetched SQL field as a text string.

Parameters
• "DBID" Database ID. Created with the bfSqlOracle function.
• "SqlID" SQL command identification. Created with the bfSqlSetNew function.
• "Field" SQL field name. Fields are the result of an SQL SELECT command. Value of the field is
available after successful bfSqlOpen and bfSqlFetch commands.
Return value
Value of fetched field as an RTE text string.

nfSqlGetField("DBID", "SqlID","Field")
Function
Retrieves the value of the fetched SQL field as a numeric string.

Parameters
• "DBID" Database ID. Created with the bfSqlOracle function.
• "SqlID" SQL command identification. Created with the bfSqlSetNew function.
• "Field" SQL field name. Field or fields are the result of an SQL SELECT command. Value of the
field is available after successful bfSqlOpen and bfSqlFetch commands.
Return value
Value of the fetched field as an RTE numeric value.

bfSqlExec("DBID", "SqlID")
Function
Executes an SQL modify command (INSERT, UPDATE, or DELETE).

Parameters
• "DBID" Database ID. Created with the bfSqlOracle function.
• "SqlID" SQL command identification. Created with the bfSqlSetNew function.
Return value
TRUE, if succeeds, otherwise FALSE.

bfSqlOpen("DBID", SqlID")
Function
Executes an SQL SELECT command. Rows will be selected from the database for further fetching.

Parameters

TradeXpress ®
Generix Group - All rights reserved 227
RTE SQL Access Library / RTE SQL Access Library Reference List

• "DBID" Database ID. Created with the bfSqlOracle function.


• "SqlID" SQL command identification. Created with the bfSqlSetNew function.
Return value
TRUE, if succeeds, otherwise FALSE.

bfSqlFetch("DBID", "SqlID")
Function
Fetches the next row, produced by the previous bfSqlOpen. Can be called repeatedly until the last
row is fetched.

Parameters
• "DBID" Database ID. Created with the bfSqlOracle function.
• "SqlID" SQL command identification. Created with the bfSqlSetNew function.
Return value
TRUE, if succeeds. FALSE, if there are no rows left.

bfSqlFetchArray("DBID", "SqlID", taVar)


Function
Fetches the next row, produced by the previous bfSqlOpen, directly to an existing RTE text array
variable. Can be called repeatedly until the last row is fetched.

Parameters
• "DBID" Database ID. Created with the bfSqlOracle function.
• "SqlID" SQL command identification. Created with the bfSqlSetNew function.
• taVar, RTE text array that will receive fetched fields as name-value pairs. The name of the field
is the index of the array variable, and the fetched value is the value of the array variable.
Return value
TRUE, if succeeds. FALSE, if there are no rows left.

bfSqlFree("DBID", SqlID")
Function
Frees the SQL command from memory.

Parameters
• "DBID" Database ID. Created with the bfSqlOracle function.
• "SqlID" SQL command identification. Created with the bfSqlSetNew function.
Return value

TradeXpress ®
Generix Group - All rights reserved 228
RTE SQL Access Library / RTE SQL Access Library Reference List

TRUE, if succeeds, otherwise FALSE.

bfSqlClose("DBID")
Function
Closes the database connection. Frees all open SQL commands and closes the database connec-
tion.

Parameters
• "DBID" database connection ID. Created with the bfSqlOracle function.
Return value
TRUE, if succeeds, otherwise FALSE.

TradeXpress ®
Generix Group - All rights reserved 229
RTE SQL Access Library / ODBC interface

ODBC interface

Available for TradeXpress 4.4 and higher

Installation
Requirements : ODBC interface need working ODBC connector to the related database (see NT
manuals to setup ODBC connection).

Libessqlodbc.lib must exists in $EDIHOME/lib directory

Use
Odbc interface is very similar with Oracle interface the only difference is that function “bfSqlOra-
cle” is replaced by “bfSqlOdbc” that use exactly the same parameters (see bfSqlOracle ("DBID",
"User", "Passwd", "DBLink")” ).

Compilation
To compile your Rte program use the following command line :

mktr -Codbc32.lib test_odbc.rte libessqlodbc.lib

TradeXpress ®
Generix Group - All rights reserved 230
RTE SQL Access Library / JDBC Interface

JDBC Interface

Available for TradeXpress 4.4 and higher

Installation
Requirements :
JDBC interface needs a working Java environment (JDK 1.2 to 1.5.0) and a JDBC driver installed
for the related database, depending on this driver, you may also need a working database client
(if not “Thin” driver).

No installation required, as the setup is included when installing TradeXpress (according to you
licence)

Configuration
Rename the file options.xmpl in options.txt in $EDIHOME/lib directory. This file
contains locations to used classes, libraries and drivers. Following, an example of
options.txt:

[OPTION]
-Djava.compiler = NONE
# Specify the path to jdbc interface programs and the path to jdbc
driver
-Djava.class.path=/usr/TradeXpress/lib; /usr/jdbc/classes12.jar
# for debugging information
-verbose:class,gc,jni
[DRIVER]
# jdbc driver name
oracle.jdbc.driver.OracleDriver

“#” puts the line into comment.

Update then the environment variable $LD_LIBRARY_PATH (PATH on Windows OS,


SHLIB_PATH on HP) to your libjvm.a (or .lib, .so) emplacement.

It is possible to have access to different JDBC databases from two RTE in the same environment.
It is even possible on the same RTE.

TradeXpress ®
Generix Group - All rights reserved 231
RTE SQL Access Library / JDBC Interface

You have to:

• Own all the jar available for all the users, usually in $EDIHOME/lib.
• Update the classpath inside the $EDIHOME/lib/options.txt to point to the jar files
and $EDIHOME/lib where you can find RTE_JDBC.class used for the connection
between JDBC and RTE.
Sun is maintaining a driver database at http://developers.sun.com/product/jdbc/drivers

Under the $EDIHOME/lib/options.txt you have to list all the classes you want to be able
to use. For example, to use oracle and SQLServer you will have:

oracle.jdbc.driver.OracleDriver
com.mysql.jdbc.Driver
#org.postgresql.Driver
#com.microsoft.jdbc.sqlserver.SQLServerDriver

Uncomment only the ones which are used, otherwise we will try to setup the others too.

Use
Jdbc interface is very similar to Oracle interface the only difference is that the function
“bfSqlOracle” is replaced by “bfSqlJdbc” that uses exactly the same parameters (see
bfSqlOracle ("DBID", "User", "Passwd", "DBLink")” ).

bfSqlJdbc("DBID", "User","Passwd","DbLink")

Function: Establishes a connection to a JDBC database

Parameters:

• "DBID" Database ID.


Used with other functions to identify connection.
Value can be any string.
• "User" Database user ID.
• "Passwd" Database user’s password.
• "DBLink" Database connection ID.
You need to use a specific URL to connect to your database.
This all depend on the database used. Here are some examples:
jdbc:odbc:maBase;CacheSize=30;ExtensionCase=LOWER
jdbc:mysql://localhost/maBase
jdbc:oracle:oci8@:maBase
jdbc:oracle:thin@://localhost:8000:maBase

TradeXpress ®
Generix Group - All rights reserved 232
RTE SQL Access Library / JDBC Interface

jdbc:sybase:Tds:localhost:5020/maBase
jdbc:microsoft:sqlserver://fulbert:1433;Data-
baseName=synchro;SelectMethod=Cursor
For example, to initialise a connection to a mysql database, you will use the following:

bfSqlInit()
bfSqlJdbc("DBID","user","passwd","jdbc:mysql://localhost/maBase")

Compilation
To compile your Rte program use the following command line :

Unix

mktr -C ljvm -C L/path/to/libjvm.a sample.rte -lessqljdbc

Windows

mktr.exe source.rte libessqljdbc.lib [path-to-]\jvm.lib

The jvm.lib is usually supplied with Oracle (for instance: C:\oracle\ora92\jdk\lib\jvm.lib), or the
Java sdk (for instance: C:\Sun\AppServer\jdk\lib\jvm.lib).

TradeXpress ®
Generix Group - All rights reserved 233
RTE SQL Access Library / Example of an RTE Program with SQL Access

Example of an RTE Program with SQL Access

begin

!--------------------------------------------------------------------
-----------------------------------
!--------------------------------------- OPENING CONNECTION

bfSqlInit()

if sfSqlOracle( "DB", "/", "", "sohvi_ES-tcp" ) = FALSE then


print( "bfSqlSet: Failed", NL )
endif

!--------------------------------------------------------------------
-----------------------------------
!--------------------------------------- SELECT

if bfSqlSet( "DB", "SQL", "SELECT IN_INDEX,EX_STATUS FROM ESD_SYSLOG"


) = FALSE then
print ( "bfSqlSet: Failed", NL)
endif

if bfSqlOpen( "DB", "SQL" ) = FALSE then


print( "bfSqlOpen: Failed", NL )
endif

while bfSqlFetch( "DB", "SQL" ) = TRUE do


print( nfSqlGetField( "DB", "SQL", "IN_INDEX" ), " ", tfSqlGet-
Field ( "DB", "SQL", "EX_STATUS" ), NL )
endwhile

!--------------------------------------------------------------------
-----------------------------------!---------------------------------
------------ DROP TABLE

if bfSqlSet( "DB", "SQL", "DROP TABLE MY_TABLE" ) = FALSE then


print( "bfSqlSet: DROP TABLE Failed", \ NL )
endif

!--------------------------------------------------------------------
----------------------------------!----------------------------------
----------- CREATE TABLE

if bfSqlSet( "DB", "SQL", "CREATE TABLE MY_TABLE ( F_TEXT VARCHAR(50),


F_NUM NUMBER(10) )" ) = FALSE then
print( "bfSqlSet: CREATE TABLE Failed", NL )
endif

!--------------------------------------------------------------------
-----------------------------------!---------------------------------
------------ INSERT TABLE

tText := "SOME TEXT"


nNum := 1234

TradeXpress ®
Generix Group - All rights reserved 234
RTE SQL Access Library / Example of an RTE Program with SQL Access

if bfSqlSet( "DB", "INSERT", " INSERT INTO MY_TABLE (F_TEXT,F_NUM VAL-


UES) (:tText, :nNum)" ) = FALSE then
print ( "bfSqlSet: INSERT TABLE Failed", NL )
endif

if bfSqlExec( "DB", "INSERT" ) = FALSE then


print( "bfSqlExec: INSERT TABLE Failed", NL )
endif
if bfSqlCommit( "DB", "INSERT" ) = FALSE then
print( "bfSqlCommit: INSERT TABLE Failed", NL )
endif

if bfSqlSet( "DB", "SELECT", "SELECT F_TEXT, F_NUM FROM MY_TABLE" ) =


FALSE then
print( "bfSqlSet: SELECT1 TABLE Failed", NL )
endif

if BfSqlOpen( "DB", "SELECT" ) = FALSE then


print( "bfSqlOpen: SELECT1 TABLE Failed", NL )
endif

while bfSqlFetch( "DB", "SELECT" ) = TRUE then


print( tfSqlGetField( "DB", "SELECT", "F_TEXT" ), " ", nfSqlGet-
Field ( "DB", "SELECT", F_NUM" ), NL )
endwhile

!--------------------------------------------------------------------
-----------------------------------
!-------------------------------------------- UPDATE TABLE

tText := "CHANGED"
nNum := 5678

if BfSqlSet( "DB", "SQL", "UPDATE MY_TABLE SET F_TEXT = :tText, F_NUM


= :nNum " ) = FALSE then
print( "bfSqlSet: UPDATE TABLE Failed", NL )
endif

if bfSqlExec( "DB", "SQL" ) = FALSE then


print( "bfSqlExec: UPDATE TABLE Failed", NL )
endif

if bfSqlCommit( "DB", "SQL" ) = FALSE then


print( "bfSqlCommit: UPDATE TABLE Failed", NL )
endif

if bfSqlOpen( "DB", "SELECT" ) = FALSE then


print( "bfSqlOpen: SELECT2 TABLE Failed", NL )
endif

while bfSqlFetch( "DB", "SELECT" ) = TRUE do


print( "tfSqlGetField( "DB", "SELECT", "F_TEXT" ), " ",
nfSqlGetField ( "DB", "SELECT", "F_NUM" ), NL endwhile

!--------------------------------------------------------------------
-----------------------------------
!--------------------------------------------Insert More Rows

TradeXpress ®
Generix Group - All rights reserved 235
RTE SQL Access Library / Example of an RTE Program with SQL Access

tText := "Third"
nNum := 3333

if bfSqlExec( "DB", "INSERT" ) = FALSE then


print( "bfSqlExec: INSERT TABLE Failed", NL )
endif

if bfSqlCommit( "DB", "INSERT" ) = FALSE then


print( "bfSqlCommit: INSERT TABLE Failed", NL )
endif

tText := "Second"
nNum := 2222
if bfSqlExec( "DB", "INSERT" ) = FALSE then
print( "bfSqlExec: INSERT TABLE Failed", NL )
endif

if bfSqlCommit( "DB", "INSERT" ) = FALSE then


print( "bfSqlCommit: INSERT TABLE Failed", NL )
endif

!--------------------------------------------------------------------
-----------------------------------!---------------------------------
------------- FETCH ARRAY
if bfSqlOpen( "DB", "SELECT" ) = FALSE then
print( "bfSqlOpen: SELECT3 TABLE Failed", NL )
endif

while bfSqlFetchArray( "DB", "SELECT" ) = TRUE do


print( taDummy )
endwhile

if bfSqlSet( "DB", "SQL", "SELECT * FROM ESD_SYSLOG" ) = FALSE then


print( "bfSqlSet: Failed", NL )
endif
if bfSqlOpen( "DB", "SQL" ) = FALSE then
print( "bfSqlOpen: SELECT4 TABLE Failed", NL )
endif

while bfSqlFetchArray( "DB", "SQL", taDummy ) = TRUE do


while tIndex in taDummy do
print( tIndex, "=", taDummy[tindex], NL )
endwhile
endwhile

!--------------------------------------------------------------------
-----------------------------------!---------------------------------
--------- CLOSING CONNECTION
if bfSqlFree( "DB", "SQL" ) = FALSE then
print( "bfSqlFree: Failed", NL )
endif

! bfSqlDump()
if bfSqlClose( "DB" ) = FALSE then

TradeXpress ®
Generix Group - All rights reserved 236
RTE SQL Access Library / Example of an RTE Program with SQL Access

print( "bfSqlClose: Failed", NL )


endif

endbegin

TradeXpress ®
Generix Group - All rights reserved 237
INDEX

Symbols pick ........................................................................................... 141


print .......................................................................................... 142
.rte extension ................................................................................... 16 put ............................................................................................. 143
$HOME environment variable ......................................................105 read ........................................................................................... 144
redirect ..................................................................................... 145
A remove ..................................................................................... 146
rename ..................................................................................... 147
arguments ......................................................................................114
replace ..................................................................................... 148
ARGC ..........................................................................................114
spawn ....................................................................................... 149
ARGV ..........................................................................................114
split ........................................................................................... 150
assignment statements
strip .......................................................................................... 151
array assignments ................................................................... 44
substr ....................................................................................... 152
boolean assignments .............................................................. 44
system ..................................................................................... 153
database assignments ............................................................ 44
time ........................................................................................... 154
file assignments ....................................................................... 44
tolower ..................................................................................... 158
numeric assignments .............................................................. 43
toupper ..................................................................................... 158
text assignments ...................................................................... 43
valid .......................................................................................... 159

B C
buffered output .........................................................................27, 89
C programming in RTE ................................................................... 198
flushing ...................................................................................... 90
in-line C block statements .................................................... 198
putting text in buffer ................................................................ 89
in-line C statements ............................................................... 199
building
character classes .......................................................................... 182
messages ...........................................................................19, 64
character sets
built-in function categories .........................................................119
compiling ................................................................................. 183
database access .....................................................................121
samples ................................................................................... 183
file handling .............................................................................120
c-language interface ....................................................................... 10
input ..........................................................................................121
code conversion ............................................................................ 185
multi purpose ..........................................................................122
key value .................................................................................. 186
output .......................................................................................120
multicolumn code files .......................................................... 186
process control .......................................................................119
comments ........................................................................................ 40
text handling ...........................................................................119
compiling character sets ............................................................. 183
time ...........................................................................................122
composite data elements ............................................................ 177
built-in functions ...........................................................................123
NAME ......................................................................................... 178
background ..............................................................................123
STATUS ...................................................................................... 178
build ..........................................................................................123
TYPE .......................................................................................... 178
close .........................................................................................125
control statements
compare ...................................................................................125
boolean expressions ................................................................ 46
copy ..........................................................................................126
conditional statement ............................................................. 46
debug ........................................................................................127
coprocess communications ........................................................ 201
edierrordump ..........................................................................128
basics ....................................................................................... 201
edierrorlist ...............................................................................129
extensions ............................................................................... 205
exec ...........................................................................................129
functions .................................................................................. 202
exit ............................................................................................131
creating
find ............................................................................................131
database entries .................................................................... 107
flush ..........................................................................................132
index .........................................................................................133
length .......................................................................................134 D
link ............................................................................................135 data lines .......................................................................................... 20
load ...........................................................................................136 LINE# .......................................................................................... 21
log ..............................................................................................139 database definitions
new ...........................................................................................139 $EDIHOME/database ................................................................ 37
number .....................................................................................140 database entries
peel ...........................................................................................141

TradeXpress ®
Generix Group - All rights reserved 238
INDEX

creating ....................................................................................107 F
defining ....................................................................................102
find function ............................................................................105 file attributes ................................................................................... 98
removing ..................................................................................108 file variables
database fields ..............................................................................103 assignment ............................................................................... 99
database interface ........................................................................100 file attributes ............................................................................. 98
decimal separators ......................................................................... 74 usage .......................................................................................... 99
definitions finding database entries .............................................................. 105
database definitions ................................................................ 37 FTP client routine library .............................................................. 209
message definitions ................................................................ 37 RTE functions for FTP ............................................................. 210
source code ............................................................................. 209
functions .......................................................................................... 39
E
EDI messages G
building ....................................................................................... 19
data lines ................................................................................... 20 group lines ...................................................................................... 176
elements .................................................................................... 19
end statement lists .................................................................. 21 I
inhouse data files ..................................................................... 25
identifiers .............................................................................161, 175
LINE# .......................................................................................... 21
b ................................................................................................ 164
nfCompletePrevious ................................................................. 21
ba .............................................................................................. 164
receiving ..................................................................................... 27
basic types .............................................................................. 163
resulting log files ...................................................................... 26
bf ............................................................................................... 164
resulting messages .................................................................. 25
c ................................................................................................. 163
RTE source code ........................................................................ 22
database entries .................................................................... 166
segments ................................................................................... 19
e ................................................................................................. 163
specifying .................................................................................. 20
f ................................................................................................. 164
user functions ........................................................................... 21
g ................................................................................................. 163
values ......................................................................................... 19
m ............................................................................................... 163
EDI translation ................................................................................. 57
n ................................................................................................ 164
EDI translator .............................................................................. 9, 58
na .............................................................................................. 164
EDIBASE ......................................................................................9, 101
nf ............................................................................................... 164
elements ........................................................................................... 19
o ................................................................................................. 163
assignments ............................................................................. 65
p ................................................................................................ 164
naming ....................................................................................... 61
s ................................................................................................. 163
packing data .............................................................................. 66
special types ........................................................................... 166
end statement lists ......................................................................... 21
t ................................................................................................. 164
nfCompletePrevious ................................................................. 21
ta ............................................................................................... 164
environment variables
tf ................................................................................................ 164
$HOME ......................................................................................105
TIME .......................................................................................... 166
error handling ................................................................................... 75
increment and decrement statements ....................................... 45
CONTRL message ...................................................................... 76
inhouse data files ............................................................................ 25
edierrordump ............................................................................ 75
input .................................................................................................. 83
edierrorlist ................................................................................. 75
picking ........................................................................................ 83
error codes ................................................................................. 79
read ............................................................................................. 84
group validity ............................................................................ 77
window model ........................................................................... 83
ignoring erroneous messages ................................................ 75
PROCESS_ERRONEOUS ............................................................... 75
processing in statement lists ................................................. 75 L
segment validity ....................................................................... 77 line
separate error routines ............................................................ 75 and .............................................................................................. 32
not ............................................................................................... 32
or ................................................................................................. 32
line counters .................................................................................... 17

TradeXpress ®
Generix Group - All rights reserved 239
INDEX

numeric variables ..................................................................... 17 newline characters (NLs) ....................................................... 85


variables ..................................................................................... 17 printing ....................................................................................... 85
line matching rules ......................................................................... 34 redirect function ....................................................................... 88
line number ................................................................................ 34 redirection ................................................................................. 86
logical operators ....................................................................... 34
multi matching .......................................................................... 36 P
regular expressions .................................................................. 35
text anywhere ........................................................................... 34 packing data in repeating elements ............................................ 66
text at given position ............................................................... 34 parameters ..................................................................................... 112
logging ............................................................................................... 97 pass-through mode in RTE ........................................................... 190
levels .......................................................................................... 97 building EDI messages .......................................................... 191
loop statements receiving EDI messages ........................................................ 190
array scanning .......................................................................... 47 picking ............................................................................................... 83
break statement ....................................................................... 50 End of File .................................................................................. 84
continue statement ................................................................. 50 line numbers ............................................................................. 84
coprocess library ...................................................................... 50 returning lines ........................................................................... 83
database scanning ................................................................... 49 print formats
directory scanning ................................................................... 48 numeric ...................................................................................... 94
general loop statement ........................................................... 47 text .............................................................................................. 94
inline C ........................................................................................ 55 time values ................................................................................ 95
inline C block .............................................................................. 55 print function ................................................................................... 85
list scanning .............................................................................. 47 print lists ........................................................................................... 92
next statement ......................................................................... 51 program statements ....................................................................... 41
nextmessage ............................................................................. 51 array assignments ................................................................... 44
switch expression ..................................................................... 49 array scanning .......................................................................... 47
switch statement ..................................................................... 49 asisignment statements ......................................................... 43
boolean assignments .............................................................. 44
boolean expressions ................................................................ 46
M
break statement ....................................................................... 50
message description files ............................................................175 conditional statement ............................................................. 46
message storage ...........................................................................173 continue statement ................................................................. 50
composite data element .......................................................177 control statements .................................................................. 46
group line .................................................................................176 database assignments ............................................................ 44
identifiers .................................................................................175 database scanning ................................................................... 49
message structure .................................................................175 decrement statements ........................................................... 45
message usage .......................................................................176 directory scanning ................................................................... 48
segment description ..............................................................177 file assignments ....................................................................... 44
segment line ............................................................................176 general loop statement ........................................................... 47
simple data element ..............................................................177 increment statements ............................................................ 45
message structure ........................................................................175 inline C ........................................................................................ 55
mktr ................................................................................................... 12 inline C block ............................................................................. 55
list scanning .............................................................................. 47
N loop statements ....................................................................... 47
next statement ......................................................................... 51
naming elements ............................................................................ 61 nextmessage ............................................................................ 51
newline characters (NLs) .............................................................. 85 numeric assignments .............................................................. 43
numeric print format ....................................................................... 94 switch expression .................................................................... 49
switch statement ..................................................................... 49
O text assignments ..................................................................... 43
program structure ........................................................................... 30
original messages comments ................................................................................. 40
receiving EDI messages .......................................................... 29 functions .................................................................................... 39
output ................................................................................................ 85 line matching rules ................................................................... 34
coprocesses .............................................................................. 87 runtime information ................................................................. 40

TradeXpress ®
Generix Group - All rights reserved 240
INDEX

source code documentation ................................................... 40 S


statement lists .......................................................................... 32
segment descriptions .................................................................. 177
segment lines ................................................................................ 176
R segment look-ahead in receiving translators ........................... 195
read function .................................................................................... 84 segments ......................................................................................... 19
receiving ........................................................................................... 73 counter ....................................................................................... 70
decimal separators .................................................................. 74 independent .............................................................................. 72
edierrordump ............................................................................ 75 location ...................................................................................... 67
edierrorlist ................................................................................. 75 repetition ................................................................................... 69
handling errors .......................................................................... 75 segment building statement .................................................. 64
receiving EDI messages ................................................................. 27 simple data elements ................................................................... 177
buffered output ......................................................................... 27 specifying
original messages .................................................................... 29 messages .................................................................................. 20
resulting data files .................................................................... 29 receiving EDI messages .......................................................... 27
RTE source code ........................................................................ 27 specifying messages ..................................................................... 60
specifying .................................................................................. 27 standard streams ............................................................................ 82
redirecting output ........................................................................... 86 startup file ...................................................................................... 115
regular expressions ......................................................................167 EDI exceptions ........................................................................ 115
entire REs .................................................................................170 EOF_STRING .............................................................................. 115
examples ..................................................................................171 initial values ............................................................................ 115
one-character REs ..................................................................169 system tuning ......................................................................... 115
removing statement lists ................................................................................ 32
database entries .....................................................................108 begin ........................................................................................... 32
resulting data files default ........................................................................................ 32
receiving EDI messages .......................................................... 29 end .............................................................................................. 32
resulting log files ............................................................................. 26 function ...................................................................................... 32
resulting messages ........................................................................ 25 line .............................................................................................. 32
RTE compilation ............................................................................... 12 segment ..................................................................................... 32
RTE compiler ..................................................................................... 12 statement variables ....................................................................... 43
RTE programs .................................................................................109 syntax
arguments ...............................................................................114 checking ..................................................................................... 70
parameters ..............................................................................112 system options .............................................................................. 110
startup file ...............................................................................115 character set ........................................................................... 110
RTE source code ............................................................................... 22 input ......................................................................................... 110
receiving EDI messages .......................................................... 27 LOGLEVEL ................................................................................. 110
RTE SQL access library ..................................................................223 name-value pairs .................................................................... 111
bfSqlExec ..................................................................................227 output ....................................................................................... 111
bfSqlFetch ................................................................................228 separators ............................................................................... 111
bfSqlFetchArray ......................................................................228
bfSqlFree( ................................................................................228 T
bfSqlOracle ...............................................................................226
bfSqlSetNew ............................................................................226 text print format .............................................................................. 94
compilation ..............................................................................224 time printing ..................................................................................... 95
reference list ...........................................................................226 translating messages .................................................................... 57
requirements ...........................................................................224 translation ........................................................................................ 58
tfSqlGetAsNum ........................................................................227 application data ........................................................................ 64
tfSqlGetAsText .........................................................................226 ASCII files .................................................................................... 60
RTE Technology (RTE) building messages ................................................................... 64
prerequisites ................................................................................8 checking syntax ....................................................................... 70
running RTE programs ..................................................................109 convertion .................................................................................. 64
decimal separator conversion ................................................ 67
decimal separators .................................................................. 74
element assignments .............................................................. 65

TradeXpress ®
Generix Group - All rights reserved 241
INDEX

handling errors .......................................................................... 75


independent segments ........................................................... 72
naming elements ...................................................................... 61
ordinal number .......................................................................... 62
packing data in repeating elements ...................................... 66
receiving ..................................................................................... 73
segment building statement .................................................. 64
mAGENCY .......................................................................................... 64
mMESSAGE ........................................................................................ 64
mRELEASE ........................................................................................ 64
mVERSION ......................................................................................... 64
segment counter ...................................................................... 70
segment location ...................................................................... 67
segment repetition ................................................................... 69
specifying messages ............................................................... 60
translator module ............................................................................ 58

U
UN/EDIFACT ....................................................................................... 58
user functions .................................................................................. 21

V
Valid (GROUP g*) .............................................................................. 77
values ................................................................................................ 19
variables ........................................................................................... 17

W
window model .................................................................................. 83

TradeXpress ®
Generix Group - All rights reserved 242

You might also like