1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.flatfile;
18
19 import java.io.ByteArrayInputStream;
20 import java.io.InputStream;
21
22 import org.apache.commons.flatfile.util.ConcatenatedInputStream;
23 import org.apache.commons.flatfile.util.RepeatingInputStream;
24
25
26
27
28
29 public abstract class PadJustifyFieldSupport extends FieldSupport {
30
31 private static final long serialVersionUID = -4953059253157670418L;
32
33
34
35
36 public static final byte DEFAULT_PAD = 0x20;
37
38
39
40
41 public enum Justify implements FieldOption {
42
43 LEFT {
44
45
46
47 protected InputStream getInputStream(byte[] src, PadJustifyFieldSupport dest) {
48 final InputStream is = new ByteArrayInputStream(src);
49 final int dlen = dest.getPadJustifyLength();
50 return dlen <= src.length ? is : new ConcatenatedInputStream(
51 is, RepeatingInputStream.withLimit(dlen - src.length,
52 dest.getPad()));
53 }
54 },
55
56
57 RIGHT {
58
59
60
61 protected InputStream getInputStream(byte[] src, PadJustifyFieldSupport dest) {
62 final int dlen = dest.getPadJustifyLength();
63 if (dlen < src.length) {
64 return new ByteArrayInputStream(src, src.length - dlen,
65 dlen);
66 }
67 final InputStream is = new ByteArrayInputStream(src);
68 return dlen == src.length ? is : new ConcatenatedInputStream(
69 RepeatingInputStream.withLimit(dlen - src.length,
70 dest.getPad()), is);
71 }
72 },
73
74
75 CENTER {
76
77
78
79 protected InputStream getInputStream(byte[] src, PadJustifyFieldSupport dest) {
80 final int dlen = dest.getPadJustifyLength();
81
82
83 if (dlen < src.length) {
84 return new ByteArrayInputStream(src,
85 (src.length - dlen) / 2, dlen);
86 }
87 final InputStream is = new ByteArrayInputStream(src);
88 if (dlen == src.length) {
89 return is;
90 }
91 final byte pad = dest.getPad();
92 return new ConcatenatedInputStream(
93 RepeatingInputStream
94 .withLimit((dlen - src.length) / 2, pad),
95 is, RepeatingInputStream.of(pad));
96 }
97 };
98
99
100
101
102
103
104
105 protected abstract InputStream getInputStream(byte[] src, PadJustifyFieldSupport dest);
106 }
107
108 private byte pad = DEFAULT_PAD;
109 private Justify justify;
110
111
112
113
114
115 public Justify getJustify() {
116 return justify == null ? Justify.LEFT : justify;
117 }
118
119
120
121
122
123 public void setJustify(Justify justify) {
124 this.justify = justify;
125 }
126
127
128
129
130
131 public byte getPad() {
132 return pad;
133 }
134
135
136
137
138
139 public void setPad(byte pad) {
140 this.pad = pad;
141 }
142
143
144
145
146
147 public void setValue(byte[] b) {
148 dieOnExceptionRead(getJustify().getInputStream(b, this));
149 }
150
151
152
153
154
155 protected abstract int getPadJustifyLength();
156 }