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 | package org.springframework.batch.item.file.transform; |
17 | |
18 | import org.springframework.util.Assert; |
19 | |
20 | /** |
21 | * An abstract {@link LineAggregator} implementation that utilizes a |
22 | * {@link FieldExtractor} to convert the incoming object to an array of its |
23 | * parts. Extending classes must decide how those parts will be aggregated |
24 | * together. |
25 | * |
26 | * @author Dan Garrette |
27 | * @since 2.0 |
28 | */ |
29 | public abstract class ExtractorLineAggregator<T> implements LineAggregator<T> { |
30 | |
31 | private FieldExtractor<T> fieldExtractor = new PassThroughFieldExtractor<T>(); |
32 | |
33 | /** |
34 | * Public setter for the field extractor responsible for splitting an input |
35 | * object up into an array of objects. Defaults to |
36 | * {@link PassThroughFieldExtractor}. |
37 | * |
38 | * @param fieldExtractor The field extractor to set |
39 | */ |
40 | public void setFieldExtractor(FieldExtractor<T> fieldExtractor) { |
41 | this.fieldExtractor = fieldExtractor; |
42 | } |
43 | |
44 | /** |
45 | * Extract fields from the given item using the {@link FieldExtractor} and |
46 | * then aggregate them. Any null field returned by the extractor will be |
47 | * replaced by an empty String. Null items are not allowed. |
48 | * |
49 | * @see org.springframework.batch.item.file.transform.LineAggregator#aggregate(java.lang.Object) |
50 | */ |
51 | public String aggregate(T item) { |
52 | Assert.notNull(item); |
53 | Object[] fields = this.fieldExtractor.extract(item); |
54 | |
55 | // |
56 | // Replace nulls with empty strings |
57 | // |
58 | Object[] args = new Object[fields.length]; |
59 | for (int i = 0; i < fields.length; i++) { |
60 | if (fields[i] == null) { |
61 | args[i] = ""; |
62 | } |
63 | else { |
64 | args[i] = fields[i]; |
65 | } |
66 | } |
67 | |
68 | return this.doAggregate(args); |
69 | } |
70 | |
71 | /** |
72 | * Aggregate provided fields into single String. |
73 | * |
74 | * @param fields An array of the fields that must be aggregated |
75 | * @return aggregated string |
76 | */ |
77 | protected abstract String doAggregate(Object[] fields); |
78 | } |