-
Notifications
You must be signed in to change notification settings - Fork 9
/
FixedLengthUtil.qm
1024 lines (885 loc) · 41.7 KB
/
FixedLengthUtil.qm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- mode: qore; indent-tabs-mode: nil -*-
# @file FixedLengthUtil.qm Qore user module for working with files with fixed lines length
/* FixedLengthUtil.qm Copyright 2012 - 2015 Qore Technologies, sro
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
# minimum required Qore version
%requires qore >= 0.8.12
%requires Util
%require-types
%enable-all-warnings
%new-style
module FixedLengthUtil {
version = "1.0";
desc = "user module for working with files with fixed length lines";
author = "Jiri Vaclavik <jiri.vaclavik@qoretechnologies.com>, Zdenek Behan <zdenek.behan@qoretechnologies.com>";
url = "http://qore.org";
license = "MIT";
}
/* see release notes below for version history
*/
/** @mainpage FixedLengthUtil Module
@tableofcontents
@section fixedlengthutilintro Introduction to the FixedLengthUtil Module
The %FixedLengthUtil module provides functionality for parsing files with fixed length lines. This means that we have at least one line type and each line type is described as several data items with fixed length.
To use this module, use \c "%requires FixedLengthUtil" in your code.
All the public symbols in the module are defined in the FixedLengthUtil namespace.
Currently the module provides the following classes:
- @ref FixedLengthUtil::FixedLengthAbstractIterator "FixedLengthAbstractIterator": Iterator class allowing for fixed-length-line data to be processed line by line on a record basis
- @ref FixedLengthUtil::FixedLengthFileIterator "FixedLengthFileIterator": Iterator class allowing for fixed-length-line file to be processed line by line on a record basis
- @ref FixedLengthUtil::FixedLengthDataIterator "FixedLengthDataIterator": Iterator class allowing for fixed-length-line strings to be processed line by line on a record basis
- @ref FixedLengthUtil::FixedLengthAbstractWriter "FixedLengthAbstractWriter": Fixed length line writer
- @ref FixedLengthUtil::FixedLengthFileWriter "FixedLengthFileWriter": Fixed length line writer into a file
- @ref FixedLengthUtil::FixedLengthDataWriter "FixedLengthDataWriter": Fixed length line writer into a variable
@section fixedlengthglobals Global Options
Valid options are:
- \c "date_format": the default date format for \c "date" fields (see @ref date_formatting for the value in this case)
- \c "encoding": the output encoding for strings parsed or returned
- \c "file_flags": additional writer @ref file_open_constants; @ref Qore::O_WRONLY | @ref Qore::O_CREAT are used by default. Use eg. @ref Qore::O_EXCL to ensure not to overwrite the target or @ref Qore::O_TRUNC to replace any existing file
- \c "ignore_empty": if @ref Qore::True "True" then ignore empty lines
- \c "number_format": the default number format for \c "float" or \c "number" fields (see @ref Qore::parse_number() and @ref Qore::parse_float() for the value in these cases)
- \c "timezone": a string giving a time zone region name or an integer offset in seconds east of UTC
@section fixedlengthspec Specification Hash
Fixed length specification hash is in the form of a hash, where each hash key is the name of a record, and each value
is a @ref fixedlengthspecrecordhash "record description hash" describing the record; see the following example:
@code
# the following spec is suitable for input and output
const Specs = (
"header": (
"flow_type": ("length": 3, "type": "string"),
"record_type": ("length": 3, "type": "int", "padding_char": "0"),
"number_of_records": ("length": 8, "type": "int", "padding_char": "0"),
),
"line": (
"flow_type": ("length": 3, "type": "string"),
"record_type": ("length": 3, "type": "int", "padding_char": "0"),
"processing_id": ("length": 10, "type": "int", "padding_char": "0"),
"processing_name": ("length": 10, "type": "string"),
"po_number": ("length": 10, "type": "int", "padding_char": "0"),
),
"trailer": (
"flow_type": ("length": 3, "type": "string"),
"record_type": ("length": 3, "type": "int", "padding_char": "0"),
"number_of_records": ("length": 8, "type": "int", "padding_char": "0"),
),
);
@endcode
In the example above, \c "header", \c "line", and \c "trailer" are record names, and the values of each key are @ref fixedlengthspecrecordhash "record description hashes".
@subsection fixedlengthspecrecordhash Record Description Hash
Each record will have a number of fields described in the record description hash. The record description hash keys
represent the names of the fields, and the values are @ref fixedlengthspecrow "field specification hashes".
In the \c "header" record in the example above, the fields are \c "flow_type", \c "record_type",
and \c "number_of_records", and the values of each of those keys are @ref fixedlengthspecrow "field specification hashes"
for the given fields.
@subsection fixedlengthspecrow Field Specification Hash
The field specification hash has the following format:
|!Key|!Type|!Description
| \c length|integer|the size of the field in bytes
| \c type|string|the type of data bound to the field @ref fixedlengthspectypes
| \c format|string|a date mask if the \a type of the field is \c "date"; see @ref date_formatting for more information
| \c timezone|string|override global timezone for current "date" field
| \c padding|string|set padding of the field "left" (default) or "right"; used only in writers; if not given then the default padding depends on the field's \a type: \c "int" fields get left padding (right justification) and all others get right padding (left justification)
| \c padding_char|string|a string with size 1 to use for \c padding. Default \c " " (space). Used only in writers
@subsection fixedlengthspectypes Field Data Types
- \c "date"
- \c "float"
- \c "int"
- \c "number"
- \c "string"
@section fixedlengthformat Fixed Length Data Format
Input and output data are formatted in a hash with two mandatory keys:
- \c "type": a string with name of the type
- \c "record": a hash with line data in field - value map
@code
("type": "type1", "record": {"col1" : 11111, "col2" : "bb"}),
@endcode
<b>Example of reading:</b>
@code
#!/usr/bin/env qr
%requires FixedLengthUtil
hash specs = (
"type1" : (
"col1": ("length": 5, "type": "int"),
"col2": ("length": 2, "type": "string"),
),
"type2": (
"col3": ("length": 1, "type": "string"),
"col4": ("length": 3, "type": "string"),
"col5": ("length": 8, "type": "date", "format": "DDMMYYYY",
# "timezone" : "Europe/Prague", # use global if omitted
),
),
);
hash global_options = (
"encoding" : "UTF-8",
"eol" : "\n",
"ignore_empty" : True,
"timezone" : "Europe/Prague", # used if not overridden in a date field specification
);
FixedLengthFileIterator i(file, specs, global_options);
while (i.next()) {
operation_with_hash(i.getValue())
}
@endcode
<b>Example of writing:</b>
@code
#!/usr/bin/env qr
%requires FixedLengthUtil
list data = (
("type": "type1", "record": {"col1" : 11111, "col2" : "bb"}),
("type": "type2", "record": {"col3" : "c", "col4" : "ddd", "col5" : "31122014"}),
("type": "type1", "record": {"col1" : 22222, "col2" : "gg"}),
);
hash specs = (
"type1" : (
"col1": ("length": 5, "type": "int"),
"col2": ("length": 2, "type": "string"),
),
"type2" : (
"col3" : ("length": 1, "type": "string"),
"col4" : ("length" : 3, "type": "string"),
"col5" : ("length" : 8, "type": "date", "format": "DDMMYYYY", "timezone" : "Europe/Prague"),
),
);
hash global_options = (
"eol" : "\n",
);
FixedLengthFileWriter w(file, specs, global_options);
w.write(data);
@endcode
@section fixedlengthutil_relnotes Release Notes
@subsection fixedlengthutil_v1_0 Version 1.0
- initial version of module
*/
#! The FixedLengthUtil namespace contains all the definitions in the FixedLengthUtil module
public namespace FixedLengthUtil {
#! Unix end of line character sequence (for new OS X too)
public const EOL_UNIX = "\n";
#! MS DOS/Windows end of line character sequence
public const EOL_WIN = "\r\n";
#! Old (pre-OSX) Macintosh end of line character sequence
public const EOL_MACINTOSH = "\r";
# helper list of end of line values
const EOLS = (EOL_UNIX, EOL_WIN, EOL_MACINTOSH);
}
#! Structured line iterator for abstract data allowing efficient "pipelined" processing
public class FixedLengthUtil::FixedLengthAbstractIterator {
private {
hash m_specs;
hash m_line_lengths;
string m_state;
#! hash of conflicting records; key = record length, value = list of conflicting record names
hash m_conflicts;
*hash m_opts; # encoding, eol, ignore_empty, timezone, etc
}
#! Instantiates the FixedLengthAbstractIterator object
/**
@param spec Fixed-length line specification; see @ref fixedlengthspec for more information
@param opts Global options; see @ref fixedlengthglobals for more information
@throw FIXED-LENGTH-UTIL-INVALID-SPEC invalid record specification; invalid type or missing field length
*/
constructor(hash spec, *hash opts) {
m_specs = spec;
m_opts += checkOptions(opts);
# Determine line lengths of each spec, for use by the default identifyType() method. We do this by building a reverse length -> type table.
m_line_lengths = hash();
foreach string k in (m_specs.keyIterator()) {
if (m_specs{k}.typeCode() != NT_HASH)
throw "FIXED-LENGTH-UTIL-INVALID-SPEC", sprintf("expecting a record description hash assigned to record key %y; got type %y instead (value: %y)", k, m_specs{k}.type(), m_specs{k});
int len = 0;
foreach string c in (m_specs{k}.keyIterator()) {
if (!m_specs{k}{c}.length)
throw "FIXED-LENGTH-UTIL-INVALID-SPEC", sprintf("Length missing for field %y", c);
len += m_specs{k}{c}.length;
}
# If any two type line lengths are not unique, save the conflicting length so that only conflicting records must be identified
if (m_line_lengths{len})
m_conflicts{len} += (k,);
else
m_line_lengths{len} = k;
}
}
abstract *string getLine();
#! Returns the current record as a hash
/** @par Example:
@code
my hash $h = $i.getValue();
@endcode
@return The current record as a hash with the following keys:
- \c "type": a string giving the record type name
- \c "record": a hash giving the parsed record data
*/
*hash getValue() {
*string line = getLine();
if (!line)
return;
hash result = hash();
string type = identifyType(line);
result.type = type;
if (!checkTransition(m_state, type)) {
throw "FIXED-LENGTH-UTIL-INVALID-TRANSITION", sprintf("record %y cannot follow record %y for line %y", (type ?? "<START>"), (type ?? "<START>"), line);
}
m_state = type;
int pos = 0;
foreach string col in (m_specs{type}.keyIterator()) {
hash field = m_specs{type}{col};
if (!field.timezone) {
field.timezone = m_opts.timezone;
}
result.record{col} = transform(line.substr(pos, field.length), field);
pos += field.length;
}
return result;
}
any transform(any value, hash type) {
switch (type.type) {
case "int": {
return int(value);
}
case NOTHING:
case "string": {
if (value.typeCode() == NT_STRING) {
trim value;
return m_opts.encoding ? convert_encoding(value, m_opts.encoding) : value;
}
return string(value);
}
case "float": {
if (value.typeCode() == NT_STRING) {
*string nf = type.format ? type.format : m_opts.number_format;
return nf ? parse_float(value, nf) : float(value);
}
return float(value);
}
case "number": {
if (value.typeCode() == NT_STRING) {
*string nf = type.format ? type.format : m_opts.number_format;
return nf ? parse_number(value, nf) : number(value);
}
return number(value);
}
case "date": {
if (value.empty()) {
return 1970-01-01;
}
TimeZone tz;
if (type.timezone)
tz = type.timezone.type() == "object" ? type.timezone : new TimeZone(type.timezone);
else if (m_opts.timezone)
tz = m_opts.timezone;
int t = value.typeCode();
if (t == NT_STRING) {
*string fmt = type.format;
if (!fmt)
fmt = m_opts.date_format;
return tz ? tz.date(value, fmt) : date(value, fmt);
}
if (t != NT_DATE && tz)
value = date(value);
return tz ? tz.date(value) : date(value);
}
default: {
throw "FIELD-TYPE-ERROR", sprintf("output type %y not supported", type.type);
}
}
}
#! Validate and prepare global fixed-length options
/**
@param opts Options passed during class instantiation.
*/
private *hash checkOptions(*hash opts) {
string errname = 'RECORD-ITERATOR-ERROR';
foreach my hash i in (opts.pairIterator()) {
switch (i.key) {
case "eol": {
if (i.value.typeCode() != NT_STRING) {
throw errname, sprintf("expecting a string value to option %y; got %y (type %s) instead", i.key, i.value, i.value.type());
}
if (!inlist(i.value, EOLS)) {
throw errname, sprintf("expecting a known end of line value to option %y; got %y (type %s) instead", i.key, i.value, i.value.type());
}
opts.eol = i.value;
break;
}
case "timezone": {
opts.timezone = new TimeZone(opts.timezone);
break;
}
case "ignore_empty": {
opts.ignore_empty = boolean(opts.ignore_empty);
break;
}
case "encoding": {
# TODO: check encoding name here
break;
}
case "number_format": {
# TODO: check here
break;
}
case "date_format": {
# TODO: check here
break;
}
}
}
return opts;
}
#! Identify a fixed-length line type using a second method %identifyTypeImpl, that may be overridden if necessary.
/**
@param input_line Input line to be identified
@return the name of the record corresponding to the input line
@throw FIXED-LENGTH-UTIL-NON-MATCHING-TYPE input line cannot be matched to a known record
*/
string identifyType(string input_line) {
*string type = identifyTypeImpl(input_line);
if (!type || !m_specs.hasKey(type))
throw "FIXED-LENGTH-UTIL-NON-MATCHING-TYPE", sprintf("Line identified to be of type that is not present in the spec '%s'", input_line);
return type;
}
#! Identify a fixed-length line type, given the raw line string. This method performs a lookup to a precalculated table based on line lengths (see constructor()). In case a different criteria is needed, eg. when two line types in a spec have the same length, this method needs to be overridden, and will throw an exception, because the precalculated mapping will be empty.
/**
@param input_line Input line to be identified
@return the record name or @ref nothing if the input cannot be matched
@throw FIXED-LENGTH-UTIL-NON-MATCHING-TYPE input line cannot be matched to a known record or the input line's length does not match the expected length
*/
*string identifyTypeImpl(string input_line) {
if (m_conflicts{input_line.size()})
throw "FIXED-LENGTH-UTIL-NON-MATCHING-TYPE", sprintf("Line with byte length %d was not automatically matched since the following records have this length: %y; you need to provide your own identifyTypeImpl() method (record: %s)", input_line.size(), m_conflicts{input_line.size()}, input_line);
*string rv = m_line_lengths{input_line.size()};
if (!rv)
throw "FIXED-LENGTH-UTIL-NON-MATCHING-TYPE", sprintf("Line of unexpected length %d found; known lengths: %y (record: %s)", input_line.size(), (map $1.toInt(), m_line_lengths.keyIterator()), input_line);
return rv;
}
#! A verification function to be called for each line. This method can be overridden to achieve a begin-to-end validation of the whole input file.
/**
@param from Type of previous line being processed
@param to Type of the current line being processed
*/
bool checkTransition(*string from, *string to) {
return True;
}
}
#! Structured line iterator for fixed-length line files allowing efficient "pipelined" processing.
/**
@par Example:
@code
#!/usr/bin/env qr
%requires FixedLengthUtil
hash specs = (
"type1" : (
"col1": ("length": 5, "type": "int"),
"col2": ("length": 2, "type": "string"),
),
"type2" : (
"col3": ("length": 1, "type": "string"),
"col4": ("length": 3, "type": "string"),
"col5": ("length": 8, "type": "date", "format": "DDMMYYYY",
#"timezone": "Europe/Prague", # use global if omitted
),
),
);
hash global_options = (
"encoding" : "UTF-8",
"eol" : "\n",
"ignore_empty" : True,
"timezone" : "Europe/Prague", # used if not overridden in a date field specification
);
FixedLengthFileIterator i(file, specs, global_options);
# output all records
map printf("%y\n", $1), i;
@endcode
*/
public class FixedLengthUtil::FixedLengthFileIterator inherits FixedLengthUtil::FixedLengthAbstractIterator, Qore::FileLineIterator {
#! Instantiates the FixedLengthFileIterator object.
/**
@param file_name File path to read
@param spec Fixed-length line specification; see @ref fixedlengthspec for more information
@param opts Global options; see @ref fixedlengthglobals for more information
*/
constructor(string file_name, hash spec, *hash opts) : FixedLengthUtil::FixedLengthAbstractIterator(spec, opts), FileLineIterator(file_name, opts.encoding.typeCode() == NT_STRING ? opts.encoding : NOTHING, opts.eol.typeCode() == NT_STRING ? opts.eol : NOTHING) {
# do not convert every string to the same encoding
m_opts.input_encoding = remove m_opts.encoding;
}
#! returns a line
private string getLine() {
return FileLineIterator::getValue();
}
#! Moves the current line / record position to the next line / record; returns @ref False if there are no more lines to iterate
/** This method will return @ref True again after it returns @ref False once if the file being iterated has data that can be iterated, otherwise it will always return @ref False. The iterator object should not be used to retrieve a value after this method returns @ref False.
@return @ref False if there are no lines / records to iterate (in which case the iterator object is invalid and should not be used); @ref True if successful (meaning that the iterator object is valid)
@note that empty lines are ignored if "ignore_empty" option is in effect
*/
bool next() {
bool status = FileLineIterator::next();
if (m_opts.ignore_empty) {
while (status && getLine() == '') {
status = FileLineIterator::next();
}
}
return status;
}
}
#! Structured line iterator for fixed-length line strings allowing efficient "pipelined" processing.
/**
@par Example:
@code
hash specs = (
"type1" : (
"col1": ("length": 5, "type": "int"),
"col2": ("length": 2, "type": "string"),
),
"type2": (
"col3": ("length": 1, "type": "string"),
"col4": ("length": 3, "type": "string"),
"col5": ("length": 8, "type": "date", "format": "DDMMYYYY",
# "timezone" : "Europe/Prague", # use global if omitted
),
),
);
hash global_options = (
"encoding" : "UTF-8",
"eol" : "\n",
"ignore_empty" : True,
"timezone" : "Europe/Prague", # used if not overridden in a date field specification
);
FixedLengthDataIterator i(string, specs, global_options);
while (i.next()) {
operation_with_hash(i.getValue())
}
@endcode
*/
public class FixedLengthUtil::FixedLengthDataIterator inherits FixedLengthUtil::FixedLengthAbstractIterator, Qore::DataLineIterator {
private {
int position;
int max_index;
list lines;
int lines_pos;
string data;
}
#! Instantiates the FixedLengthFileIterator object
/** @par Example:
@code
hash specs = (
"type1" : (
"col1": ("length": 5, "type": "int"),
"col2": ("length": 2, "type": "string"),
),
"type2": (
"col3": ("length": 1, "type": "string"),
"col4": ("length": 3, "type": "string"),
"col5": ("length": 8, "type": "date", "format": "DDMMYYYY",
# "timezone" : "Europe/Prague", # use global if omitted
),
),
);
hash global_options = (
"encoding" : "UTF-8",
"eol" : "\n",
"ignore_empty" : True,
"timezone" : "Europe/Prague", # used if not overridden in a date field specification
);
FixedLengthDataIterator i(string, specs, global_options);
while (i.next()) {
operation_with_hash(i.getValue())
}
@endcode
@param input_data The input string to process
@param spec Fixed-length line specification; see @ref fixedlengthspec for more information
@param opts Global options; see @ref fixedlengthglobals for valid values
*/
constructor(string input_data, hash spec, *hash opts) : FixedLengthUtil::FixedLengthAbstractIterator(spec, opts), DataLineIterator(input_data, opts.eol.typeCode() == NT_STRING ? opts.eol : NOTHING, opts.trim.typeCode() == NT_BOOLEAN ? opts.trim : NOTHING) {
data = input_data;
}
#! Moves the current line / record position to the next line / record; returns @ref False if there are no more lines to iterate
/** This method will return @ref True again after it returns @ref False once if the file being iterated has data that can be iterated, otherwise it will always return @ref False. The iterator object should not be used to retrieve a value after this method returns @ref False.
@return @ref False if there are no lines / records to iterate (in which case the iterator object is invalid and should not be used); @ref True if successful (meaning that the iterator object is valid)
@note that empty lines are ignored if "ignore_empty" option is in effect
*/
bool next() {
any status = DataLineIterator::next();
if (m_opts.ignore_empty) {
while (status && DataLineIterator::getValue() == "") { # skip empty lines
status = DataLineIterator::next();
}
}
return status;
}
}
#! Structured abstract writer for fixed-length lines
public class FixedLengthUtil::FixedLengthAbstractWriter {
private {
hash m_specs;
string m_state;
int m_linescount = 0;
hash m_opts = {};
}
#! creates the FixedLengthAbstractWriter object
/**
@param specs Fixed-length line specification; see @ref fixedlengthspec for more information
@param opts Global options; see @ref fixedlengthglobals for valid values
*/
constructor(hash specs, *hash opts) {
m_specs = specs;
delete opts.eol;
m_opts = m_opts + checkOptions(opts);
# validate padding options
HashIterator hit(specs);
while (hit.next()) {
HashIterator cit(hit.getValue());
while (cit.next()) {
if (cit.getValue(){"padding"}) {
if (cit.getValue(){"padding"} != "left" && cit.getValue(){"padding"} != "right")
throw "FIXED-LENGTH-UTIL-PADDING-ERROR", sprintf("record type: %s; field: %s; Key: padding; value must be 'left' or 'right'. Got: %s",
hit.getKey(), cit.getKey(), cit.getValue(){"padding"});
}
if (cit.getValue(){"padding_char"} && cit.getValue(){"padding_char"}.length() != 1) {
throw "FIXED-LENGTH-UTIL-PADDING-ERROR", sprintf("record type: %s; field: %s; Key: padding; value must have a character length of 1; got: %d instead",
hit.getKey(), cit.getKey(), cit.getValue(){"padding_char"}.length());
}
}
}
}
private *hash checkOptions(*hash opts) {
string errname = 'RECORD-WRITER-ERROR';
foreach my hash i in (opts.pairIterator()) {
switch (i.key) {
case "eol": {
if (i.value.typeCode() != NT_STRING) {
throw errname, sprintf("expecting a string value to option %y; got %y (type %s) instead", i.key, i.value, i.value.type());
}
if (!inlist(i.value, EOLS)) {
throw errname, sprintf("expecting a known end of line value to option %y; got %y (type %s) instead", i.key, i.value, i.value.type());
}
opts.eol = i.value;
break;
}
}
}
return opts;
}
#! get processed lines count
int linesCount() {
return m_linescount;
}
#! Formats a single line from a hash describing the record type and its contents
/**
@param line a hash describing the record to be formatted; the hash must have the following keys:
- \c "type": a string giving the record type (must be defined in @ref fixedlengthspec given in the constructor)
- \c "record": a hash giving the input record to be rendered (with keys as defined in the @ref fixedlengthspecrecordhash for the record identified by the \a type argument)
@throw INVALID-LINE-DATA line argument missing either \a type or \a record keys
@throw INVALID-RECORD record name (\a type key in the record hash) not recognized
@throw FIELD-INPUT-ERROR the input value is too large to render into the output field
@throw RECORD-TRANSITION-ERROR a record transition error occurred; an invalid record sequence was given in the input data
*/
string formatLine(hash line) {
if (!line.type)
throw "INVALID-LINE-DATA", sprintf("invalid line data; missing \"type\" key; got keys: %y", line.keys());
if (!line.record)
throw "INVALID-LINE-DATA", sprintf("invalid line data; missing \"record\" key; got keys: %y", line.keys());
string type = line.type;
if (!m_specs{type})
throw "INVALID-RECORD", sprintf("unknown record type %y; valid records: %y", type, m_specs.keys());
string result = "";
foreach string field in (m_specs{type}.keyIterator()) {
# field description
hash fh = m_specs{type}{field};
any value = line.record{field};
# format output
switch (fh.type) {
case "float":
case "number": {
*string fmt = fh.format ?? m_opts.number_format;
if (fmt)
value = format_number(fmt, value);
else if (value.typeCode() != NT_STRING)
value = string(value);
break;
}
case "date": {
switch (value.typeCode()) {
case NT_DATE: {
*string fmt = fh.format ?? m_opts.date_format;
value = fmt ? value.format(fmt) : string(value);
break;
}
case NT_STRING:
break;
default:
value = string(value);
break;
}
}
default:
if (value.typeCode() != NT_STRING)
value = string(value);
break;
}
int len = value.length();
# Validate
if (len > fh.length)
throw "FIELD-INPUT-ERROR", sprintf("Value %y (len %d) too large to pack into field: %s (len %d)", value, len, field, fh.length);
# do output justification
int spacingsize = fh.length - len;
if (spacingsize) {
string spacing = strmul(fh.padding_char ?? " ", spacingsize);
if (fh.padding == "left" || (!fh.padding && fh.type == "int"))
result += spacing + value;
else
result += value + spacing;
}
else
result += value;
}
if (!checkTransition(m_state, type)) {
throw "RECORD-TRANSITION-ERROR", sprintf("record %y cannot follow record %y for line %y", (type ?? "<START>"), (m_state ?? "<START>"), result);
}
m_state = type;
++m_linescount;
return result;
}
#! A verification function to be called for each line. This method can be overridden to achieve a begin-to-end validation of the whole input file.
/**
@param from Type of previous line being processed
@param to Type of the current line being processed
*/
bool checkTransition(*string from, *string to) {
return True;
}
}
#! Writer for fixed-length-line output files
/** @par Example:
@code
#!/usr/bin/env qr
%requires FixedLengthUtil
list data = (
("type": "type1", "record": {"col1" : 11111, "col2" : "bb"}),
("type": "type2", "record": {"col3" : "c", "col4" : "ddd", "col5" : "31122014"}),
("type": "type1", "record": {"col1" : 22222, "col2" : "gg"}),
);
hash specs = (
"type1" : (
"col1": ("length": 5, "type": "int"),
"col2": ("length": 2, "type": "string"),
),
"type2" : (
"col3" : ("length": 1, "type": "string"),
"col4" : ("length" : 3, "type": "string"),
"col5" : ("length" : 8, "type": "date", "format": "DDMMYYYY", "timezone" : "Europe/Prague"),
),
);
hash global_options = (
"eol" : "\n",
);
FixedLengthFileWriter w(file, specs, global_options);
w.write(data);
@endcode
@see FixedLengthDataWriter
*/
public class FixedLengthUtil::FixedLengthFileWriter inherits FixedLengthUtil::FixedLengthAbstractWriter {
private {
string file;
File m_file();
}
#! Instantiates the FixedLengthFileWriter object
/**
@param file_name the output file path
@param specs Fixed-length line specification; see @ref fixedlengthspec for more information
@param opts Global options; see @ref fixedlengthglobals for valid values
*/
constructor(string file_name, hash specs, *hash opts) : FixedLengthUtil::FixedLengthAbstractWriter(specs, opts) {
file = file_name;
m_opts.eol = m_opts.eol ?? "\n";
m_file.open2(file, O_WRONLY | O_CREAT | m_opts.file_flags);
}
#! Return the file name
string getFileName() {
return file;
}
#! Renders a single line for a single input record hash to the output file
/** @par Example:
@code
const Spec = (
"header": (
"flow_type": ("length": 3, "type": "string"),
"record_type": ("length": 3, "type": "int", "padding_char": "0"),
"number_of_records": ("length": 8, "type": "int", "padding_char": "0"),
),
);
hash hh = (
"type": "header",
"record": (
"flow_type": "WTS",
"record_type": "950",
"number_of_records": 1,
),
);
FixedLengthFileWriter w(Spec);
w.write(hh);
@endcode
@param line A hash representing input data to be writen to the file; the hash must have the following keys:
- \c "type": a string giving the record type (must be defined in @ref fixedlengthspec given in the constructor)
- \c "record": a hash giving the input record to be rendered (with keys as defined in the @ref fixedlengthspecrecordhash for the record identified by the \a type argument)
@throw INVALID-RECORD record name (\a type key in the record hash) not recognized
@throw FIELD-INPUT-ERROR the input value is too large to render into the output field
@throw RECORD-TRANSITION-ERROR a record transition error occurred; an invalid record sequence was given in the input data
*/
write(hash line) {
m_file.write(formatLine(line) + m_opts.eol);
}
#! iterates the input records and writes rendered versions of all input records to the file
/** @par Example:
@code
FixedLengthFileWriter w(output_file, Spec);
w.write(i);
@endcode
@param lines An iterator to stream input records; each iterator value must be a hash with the following keys:
- \c "type": a string giving the record type (must be defined in @ref fixedlengthspec given in the constructor)
- \c "record": a hash giving the input record to be rendered (with keys as defined in the @ref fixedlengthspecrecordhash for the record identified by the \a type argument)
@throw INVALID-RECORD record name (\a type key in the record hash) not recognized
@throw FIELD-INPUT-ERROR the input value is too large to render into the output field
@throw RECORD-TRANSITION-ERROR a record transition error occurred; an invalid record sequence was given in the input data
*/
write(list lines) {
map m_file.write(formatLine($1) + m_opts.eol), lines;
}
#! iterates the input records and writes rendered versions of all input records to the file
/** @par Example:
@code
FixedLengthFileWriter w(output_file, Spec);
w.write(i);
@endcode
@param lines An iterator to stream input records; each iterator value must be a hash with the following keys:
- \c "type": a string giving the record type (must be defined in @ref fixedlengthspec given in the constructor)
- \c "record": a hash giving the input record to be rendered (with keys as defined in the @ref fixedlengthspecrecordhash for the record identified by the \a type argument)
@throw INVALID-RECORD record name (\a type key in the record hash) not recognized
@throw FIELD-INPUT-ERROR the input value is too large to render into the output field
@throw RECORD-TRANSITION-ERROR a record transition error occurred; an invalid record sequence was given in the input data
*/
write(Qore::AbstractIterator lines) {
map m_file.write(formatLine($1) + m_opts.eol), lines;
}
}
#! Writer class for fixed-length-line data
/** @par Example:
@code
const Spec = (
"header": (
"flow_type": ("length": 3, "type": "string"),
"record_type": ("length": 3, "type": "int", "padding_char": "0"),
"number_of_records": ("length": 8, "type": "int", "padding_char": "0"),
),
"line": (
"flow_type": ("length": 3, "type": "string"),
"record_type": ("length": 3, "type": "int", "padding_char": "0"),
"processing_id": ("length": 10, "type": "int", "padding_char": "0"),
"processing_name": ("length": 10, "type": "string"),
"po_number": ("length": 10, "type": "int", "padding_char": "0"),
),
"trailer": (
"flow_type": ("length": 3, "type": "string"),
"record_type": ("length": 3, "type": "int", "padding_char": "0"),
"number_of_records": ("length": 8, "type": "int", "padding_char": "0"),
),
);
FixedLengthDataWriter w(Spec);
AbstractIterator i = get_record_iterator();
string data = w.write(i);
@endcode
@see FixedLengthFileWriter
*/
public class FixedLengthUtil::FixedLengthDataWriter inherits FixedLengthUtil::FixedLengthAbstractWriter {
#! Instantiates the FixedLengthDataWriter object.
/**
@param specs Fixed-length line specification; see @ref fixedlengthspec for more information
@param opts Global formatting options; see @ref fixedlengthglobals for valid values
*/
constructor(hash specs, *hash opts) : FixedLengthUtil::FixedLengthAbstractWriter(specs, opts) {
}
#! iterates the input records and returns a string corresponding to the rendered versions of all input records
/** @par Example:
@code
FixedLengthDataWriter w(Spec);
string file = w.write(input_list);
@endcode
@param lines An iterator to stream input records; each iterator value must be a hash with the following keys:
- \c "type": a string giving the record type (must be defined in @ref fixedlengthspec given in the constructor)
- \c "record": a hash giving the input record to be rendered (with keys as defined in the @ref fixedlengthspecrecordhash for the record identified by the \a type argument)
@return the rendered string for all input records
@throw INVALID-RECORD record name (\a type key in the record hash) not recognized
@throw FIELD-INPUT-ERROR the input value is too large to render into the output field
@throw RECORD-TRANSITION-ERROR a record transition error occurred; an invalid record sequence was given in the input data
*/
string write(list lines) {
string result = "";
string eol = m_opts.eol ? m_opts.eol : "\n";
map result += formatLine($1) + eol, lines;
return result;
}
#! Return a single line for a single input record hash
/** @par Example:
@code
const Spec = (
"header": (
"flow_type": ("length": 3, "type": "string"),
"record_type": ("length": 3, "type": "int", "padding_char": "0"),
"number_of_records": ("length": 8, "type": "int", "padding_char": "0"),
),
);
hash hh = (
"type": "header",
"record": (
"flow_type": "WTS",
"record_type": "950",
"number_of_records": 1,
),
);
FixedLengthDataWriter w(Spec);
string line = w.write(hh);
@endcode
@param line A hash representing input data to be rendered as a string; the hash must have the following keys:
- \c "type": a string giving the record type (must be defined in @ref fixedlengthspec given in the constructor)
- \c "record": a hash giving the input record to be rendered (with keys as defined in the @ref fixedlengthspecrecordhash for the record identified by the \a type argument)
@return a single line for a single input record hash
@throw INVALID-RECORD record name (\a type key in the record hash) not recognized
@throw FIELD-INPUT-ERROR the input value is too large to render into the output field
@throw RECORD-TRANSITION-ERROR a record transition error occurred; an invalid record sequence was given in the input data
*/
string write(hash line) {
return formatLine(line) + (m_opts.eol ? m_opts.eol : "\n");
}