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 | import org.springframework.batch.item.file.mapping.DefaultFieldSet; |
23 | import org.springframework.batch.item.file.mapping.FieldSet; |
24 | |
25 | |
26 | /** |
27 | * Abstract class handling common concerns of various {@link LineTokenizer} implementations |
28 | * such as dealing with names and actual construction of {@link FieldSet} |
29 | * |
30 | * @author Dave Syer |
31 | * @author Robert Kasanicky |
32 | * @author Lucas Ward |
33 | */ |
34 | public abstract class AbstractLineTokenizer implements LineTokenizer { |
35 | |
36 | protected String[] names = new String[0]; |
37 | |
38 | /** |
39 | * Setter for column names. Optional, but if set, then all lines must have |
40 | * as many or fewer tokens. |
41 | * |
42 | * @param names |
43 | */ |
44 | public void setNames(String[] names) { |
45 | this.names = names; |
46 | } |
47 | |
48 | /** |
49 | * @return <code>true</code> if column names have been specified |
50 | * @see #setNames(String[]) |
51 | */ |
52 | public boolean hasNames() { |
53 | if (names != null && names.length > 0) { |
54 | return true; |
55 | } |
56 | return false; |
57 | } |
58 | |
59 | /** |
60 | * Yields the tokens resulting from the splitting of the supplied |
61 | * <code>line</code>. |
62 | * |
63 | * @param line the line to be tokenised (can be <code>null</code>) |
64 | * |
65 | * @return the resulting tokens |
66 | */ |
67 | public FieldSet tokenize(String line) { |
68 | |
69 | if(line == null){ |
70 | line = ""; |
71 | } |
72 | |
73 | List tokens = new ArrayList(doTokenize(line)); |
74 | |
75 | String[] values = (String[]) tokens.toArray(new String[tokens.size()]); |
76 | |
77 | if (names.length==0) { |
78 | return new DefaultFieldSet(values); |
79 | } |
80 | else if(values.length != names.length){ |
81 | throw new IncorrectTokenCountException(names.length, values.length); |
82 | } |
83 | return new DefaultFieldSet(values, names); |
84 | } |
85 | |
86 | protected abstract List doTokenize(String line); |
87 | |
88 | } |