-
Notifications
You must be signed in to change notification settings - Fork 79
/
VRLRecordReader.scala
239 lines (197 loc) · 8.73 KB
/
VRLRecordReader.scala
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
/*
* Copyright 2018 ABSA Group Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package za.co.absa.cobrix.cobol.reader.iterator
import za.co.absa.cobrix.cobol.internal.Logging
import za.co.absa.cobrix.cobol.parser.Copybook
import za.co.absa.cobrix.cobol.parser.headerparsers.RecordHeaderParser
import za.co.absa.cobrix.cobol.reader.parameters.ReaderParameters
import za.co.absa.cobrix.cobol.reader.extractors.raw.RawRecordExtractor
import za.co.absa.cobrix.cobol.reader.stream.SimpleStream
import za.co.absa.cobrix.cobol.reader.validator.ReaderParametersValidator
/**
* This iterator is used to read fixed length and variable length records from a binary COBOL-generated file.
* It returns a pair of (segment_id, raw_data_byte_array) without actually decoding the data.
*
* @param cobolSchema A parsed copybook.
* @param dataStream A source of bytes for sequential reading and parsing. It should implement [[SimpleStream]] interface.
* @param readerProperties Additional properties for customizing the reader.
* @param recordHeaderParser A record parser for multisegment files
* @param recordExtractor A record extractor that can be used instead of the record header parser.
* @param startRecordId A starting record id value for this particular file/stream `dataStream`
* @param startingFileOffset An offset of the file where parsing should be started
*/
class VRLRecordReader(cobolSchema: Copybook,
dataStream: SimpleStream,
readerProperties: ReaderParameters,
recordHeaderParser: RecordHeaderParser,
recordExtractor: Option[RawRecordExtractor],
startRecordId: Long,
startingFileOffset: Long) extends Iterator[(String, Array[Byte])] with Logging {
type RawRecord = (String, Array[Byte])
private var cachedValue: Option[RawRecord] = _
private val copyBookRecordSize = cobolSchema.getRecordSize
private var byteIndex = startingFileOffset
private var recordIndex = startRecordId - 1
private val (lengthField, lengthFieldExpr) = ReaderParametersValidator.getEitherFieldAndExpression(readerProperties.lengthFieldExpression, cobolSchema)
private val segmentIdField = ReaderParametersValidator.getSegmentIdField(readerProperties.multisegment, cobolSchema)
private val recordLengthAdjustment = readerProperties.rdwAdjustment
private val useRdw = lengthField.isEmpty && lengthFieldExpr.isEmpty
private val minimumRecordLength = readerProperties.minimumRecordLength
private val maximumRecordLength = readerProperties.maximumRecordLength
fetchNext()
override def hasNext: Boolean = cachedValue.nonEmpty
@throws(classOf[IllegalStateException])
@throws(classOf[NoSuchElementException])
override def next(): RawRecord = {
cachedValue match {
case None => throw new NoSuchElementException
case Some(value) =>
fetchNext()
recordIndex = recordIndex + 1
value
}
}
@throws(classOf[IllegalStateException])
private def fetchNext(): Unit = {
var recordFetched = false
while (!recordFetched) {
val binaryData = recordExtractor match {
case Some(extractor) =>
if (extractor.hasNext) {
Option(extractor.next())
} else {
None
}
case None =>
if (useRdw) {
fetchRecordUsingRdwHeaders()
} else if (lengthField.nonEmpty) {
fetchRecordUsingRecordLengthField()
} else {
fetchRecordUsingRecordLengthFieldExpression(lengthFieldExpr.get)
}
}
binaryData match {
case None =>
cachedValue = None
recordFetched = true
case Some(data) if data.length < minimumRecordLength || data.length > maximumRecordLength =>
recordFetched = false
case Some(data) =>
val segmentId = getSegmentId(data)
val segmentIdStr = segmentId.getOrElse("")
cachedValue = Some(segmentIdStr, data)
recordFetched = true
}
}
}
def getRecordIndex: Long = recordIndex
def getByteIndex: Long = byteIndex
private def fetchRecordUsingRecordLengthField(): Option[Array[Byte]] = {
if (lengthField.isEmpty) {
throw new IllegalStateException(s"For variable length reader either RDW record headers or record length field should be provided.")
}
val lengthFieldBlock = lengthField.get.binaryProperties.offset + lengthField.get.binaryProperties.actualSize
val binaryDataStart = dataStream.next(readerProperties.startOffset + lengthFieldBlock)
byteIndex += readerProperties.startOffset + lengthFieldBlock
if (binaryDataStart.length < readerProperties.startOffset + lengthFieldBlock) {
return None
}
val recordLength = lengthField match {
case Some(lengthAST) =>
cobolSchema.extractPrimitiveField(lengthAST, binaryDataStart, readerProperties.startOffset) match {
case i: Int => i + recordLengthAdjustment
case l: Long => l.toInt + recordLengthAdjustment
case s: String => s.toInt + recordLengthAdjustment
case _ => throw new IllegalStateException(s"Record length value of the field ${lengthAST.name} must be an integral type.")
}
case None => copyBookRecordSize
}
val restOfDataLength = recordLength - lengthFieldBlock + readerProperties.endOffset
byteIndex += restOfDataLength
if (restOfDataLength > 0) {
Some(binaryDataStart ++ dataStream.next(restOfDataLength))
} else {
Some(binaryDataStart)
}
}
private def fetchRecordUsingRecordLengthFieldExpression(expr: RecordLengthExpression): Option[Array[Byte]] = {
val lengthFieldBlock = expr.requiredBytesToread
val evaluator = expr.evaluator
val binaryDataStart = dataStream.next(readerProperties.startOffset + lengthFieldBlock)
byteIndex += readerProperties.startOffset + lengthFieldBlock
if (binaryDataStart.length < readerProperties.startOffset + lengthFieldBlock) {
return None
}
expr.fields.foreach{
case (name, field) =>
cobolSchema.extractPrimitiveField(field, binaryDataStart, readerProperties.startOffset) match {
case i: Int => evaluator.setValue(name, i)
case l: Long => evaluator.setValue(name, l.toInt)
case s: String => evaluator.setValue(name, s.toInt)
case _ => throw new IllegalStateException(s"Record length value of the field ${field.name} must be an integral type.")
}
}
val recordLength = evaluator.eval()
val restOfDataLength = recordLength - lengthFieldBlock + readerProperties.endOffset
byteIndex += restOfDataLength
if (restOfDataLength > 0) {
Some(binaryDataStart ++ dataStream.next(restOfDataLength))
} else {
Some(binaryDataStart)
}
}
private def fetchRecordUsingRdwHeaders(): Option[Array[Byte]] = {
val rdwHeaderBlock = recordHeaderParser.getHeaderLength
var isValidRecord = false
var isEndOfFile = false
var headerBytes = Array[Byte]()
var recordBytes = Array[Byte]()
while (!isValidRecord && !isEndOfFile) {
headerBytes = dataStream.next(rdwHeaderBlock)
val recordMetadata = recordHeaderParser.getRecordMetadata(headerBytes, dataStream.offset, dataStream.size, dataStream.totalSize, recordIndex)
val recordLength = recordMetadata.recordLength
byteIndex += headerBytes.length
isValidRecord = recordMetadata.isValid && recordLength >= minimumRecordLength && recordLength <= maximumRecordLength
if (recordLength > 0) {
recordBytes = dataStream.next(recordLength)
byteIndex += recordBytes.length
} else {
isEndOfFile = true
}
}
if (!isEndOfFile) {
if (recordHeaderParser.isHeaderDefinedInCopybook) {
Some(headerBytes ++ recordBytes)
} else {
Some(recordBytes)
}
} else {
None
}
}
private def getSegmentId(data: Array[Byte]): Option[String] = {
segmentIdField.map(field => {
val fieldValue = cobolSchema.extractPrimitiveField(field, data, readerProperties.startOffset)
if (fieldValue == null) {
logger.error(s"An unexpected null encountered for segment id at $byteIndex")
""
} else {
fieldValue.toString.trim
}
})
}
}