/
FixedLengthUnmarshallingContext.java
85 lines (76 loc) · 2.76 KB
/
FixedLengthUnmarshallingContext.java
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
/*
* Copyright 2011-2013 Kevin Seim
*
* 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 org.beanio.internal.parser.format.fixedlength;
import org.beanio.internal.parser.UnmarshallingContext;
/**
* The {@link UnmarshallingContext} implementation for a fixed length formatted stream.
*
* @author Kevin Seim
* @since 2.0
*/
public class FixedLengthUnmarshallingContext extends UnmarshallingContext {
private String record;
private int recordLength;
@Override
public void setRecordValue(Object value) {
this.record = (String) value;
this.recordLength = value == null ? 0 : record.length();
}
/**
* Returns the length of the record being unmarshalled.
* @return the record length
*/
public int getRecordLength() {
return recordLength;
}
/**
* Returns the field text at the given position in the record.
* @param name the field name
* @param position the position of the field in the record
* @param length the field length, or -1 if the field is at the end of the
* record and unbounded
* @param until the maximum position of the field as an offset
* of the field count, for example -2 to indicate the any position
* except the last two fields in the record
* @return the field text, or null if the record length is less than
* the position of the field
*/
public String getFieldText(String name, int position, int length, int until) {
int max = recordLength + until;
if (position < 0) {
position = recordLength + position;
position = getAdjustedFieldPosition(position);
if (position < 0) {
return null;
}
}
else {
position = getAdjustedFieldPosition(position);
if (position >= max) {
return null;
}
}
String text;
if (length < 0) {
text = record.substring(position, max);
}
else {
text = record.substring(position, Math.min(max, position + length));
}
setFieldText(name, text);
return text;
}
}