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 | * @author Dave Syer |
28 | * @author Robert Kasanicky |
29 | * |
30 | */ |
31 | public abstract class AbstractLineTokenizer implements LineTokenizer { |
32 | |
33 | protected String[] names = new String[0]; |
34 | |
35 | /** |
36 | * Setter for column names. Optional, but if set, then all lines must have |
37 | * as many or fewer tokens. |
38 | * |
39 | * @param names |
40 | */ |
41 | public void setNames(String[] names) { |
42 | this.names = names; |
43 | } |
44 | |
45 | /** |
46 | * @return <code>true</code> if column names have been specified |
47 | * @see #setNames(String[]) |
48 | */ |
49 | public boolean hasNames() { |
50 | if (names != null && names.length > 0) { |
51 | return true; |
52 | } |
53 | return false; |
54 | } |
55 | |
56 | /** |
57 | * Yields the tokens resulting from the splitting of the supplied |
58 | * <code>line</code>. |
59 | * |
60 | * @param line the line to be tokenised (can be <code>null</code>) |
61 | * |
62 | * @return the resulting tokens |
63 | */ |
64 | public FieldSet tokenize(String line) { |
65 | |
66 | if (line == null || line.length()==0) { |
67 | return new DefaultFieldSet(new String[0]); |
68 | } |
69 | |
70 | List tokens = new ArrayList(doTokenize(line)); |
71 | for (int i=tokens.size(); i<names.length; i++) { |
72 | tokens.add(null); |
73 | } |
74 | |
75 | String[] values = (String[]) tokens.toArray(new String[tokens.size()]); |
76 | if (names.length==0) { |
77 | return new DefaultFieldSet(values); |
78 | } |
79 | return new DefaultFieldSet(values, names); |
80 | } |
81 | |
82 | protected abstract List doTokenize(String line); |
83 | |
84 | } |