1 | /* |
2 | * Copyright 2006-2007 the original author or authors. |
3 | * |
4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
5 | * you may not use this file except in compliance with the License. |
6 | * You may obtain a copy of the License at |
7 | * |
8 | * http://www.apache.org/licenses/LICENSE-2.0 |
9 | * |
10 | * Unless required by applicable law or agreed to in writing, software |
11 | * distributed under the License is distributed on an "AS IS" BASIS, |
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13 | * See the License for the specific language governing permissions and |
14 | * limitations under the License. |
15 | */ |
16 | |
17 | package org.springframework.batch.item.file.transform; |
18 | |
19 | import java.util.ArrayList; |
20 | import java.util.List; |
21 | |
22 | /** |
23 | * Tokenizer used to process data obtained from files with fixed-length format. |
24 | * Columns are specified by array of Range objects ({@link #setColumns(Range[])}). |
25 | * |
26 | * @author tomas.slanina |
27 | * @author peter.zozom |
28 | * @author Dave Syer |
29 | */ |
30 | public class FixedLengthTokenizer extends AbstractLineTokenizer { |
31 | |
32 | private Range[] ranges; |
33 | |
34 | /** |
35 | * Set the column ranges. Used in conjunction with the |
36 | * {@link RangeArrayPropertyEditor} this property can be set in the form of |
37 | * a String describing the range boundaries, e.g. "1,4,7" or "1-3,4-6,7" or |
38 | * "1-2,4-5,7-10". |
39 | * |
40 | * @param ranges the column ranges expected in the input |
41 | */ |
42 | public void setColumns(Range[] ranges) { |
43 | this.ranges = ranges; |
44 | } |
45 | |
46 | /** |
47 | * Yields the tokens resulting from the splitting of the supplied |
48 | * <code>line</code>. |
49 | * |
50 | * @param line |
51 | * the line to be tokenised (can be <code>null</code>) |
52 | * |
53 | * @return the resulting tokens (empty if the line is null) |
54 | */ |
55 | protected List doTokenize(String line) { |
56 | List tokens = new ArrayList(ranges.length); |
57 | int lineLength; |
58 | String token; |
59 | |
60 | lineLength = line.length(); |
61 | |
62 | for (int i = 0; i < ranges.length; i++) { |
63 | |
64 | int startPos = ranges[i].getMin() - 1; |
65 | int endPos = ranges[i].getMax(); |
66 | |
67 | if (lineLength >= endPos) { |
68 | token = line.substring(startPos, endPos); |
69 | } else if (lineLength >= startPos) { |
70 | token = line.substring(startPos); |
71 | } else { |
72 | token = ""; |
73 | } |
74 | |
75 | tokens.add(token); |
76 | } |
77 | |
78 | return tokens; |
79 | } |
80 | } |