| 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.batch.item.file.mapping.DefaultFieldSet; |
| 19 | import org.springframework.batch.item.file.mapping.FieldSet; |
| 20 | import org.springframework.batch.item.transform.ItemTransformer; |
| 21 | |
| 22 | /** |
| 23 | * An {@link ItemTransformer} that expects a String[] as input and delegates to |
| 24 | * a {@link LineAggregator}. |
| 25 | * |
| 26 | * @author Dave Syer |
| 27 | * |
| 28 | */ |
| 29 | public class LineAggregatorItemTransformer implements ItemTransformer { |
| 30 | |
| 31 | private LineAggregator aggregator = new DelimitedLineAggregator(); |
| 32 | |
| 33 | /** |
| 34 | * Public setter for the {@link LineAggregator}. |
| 35 | * @param aggregator the aggregator to set |
| 36 | */ |
| 37 | public void setAggregator(LineAggregator aggregator) { |
| 38 | this.aggregator = aggregator; |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * Assume the item is an array of String (no check is made) and delegate to |
| 43 | * the aggregator. |
| 44 | * |
| 45 | * @see org.springframework.batch.item.transform.ItemTransformer#transform(java.lang.Object) |
| 46 | */ |
| 47 | public Object transform(Object item) throws Exception { |
| 48 | return aggregator.aggregate(createFieldSet(item)); |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * Extension point for subclasses. The default implementation just attempts |
| 53 | * to cast the item to String[] and creates a {@link DefaultFieldSet} from |
| 54 | * it. |
| 55 | * |
| 56 | * @param item an object (in this implementation of type String[]). |
| 57 | * @return a {@link FieldSet} representing the item |
| 58 | * |
| 59 | * @throws ConversionException if the field set cannot be created |
| 60 | */ |
| 61 | protected FieldSet createFieldSet(Object item) throws ConversionException { |
| 62 | try { |
| 63 | return new DefaultFieldSet((String[]) item); |
| 64 | } |
| 65 | catch (ClassCastException e) { |
| 66 | throw new ConversionException( |
| 67 | "Item must be of type String[] for conversion to FieldSet. " + |
| 68 | "Consider overriding this method to specify a less generic algorithm."); |
| 69 | } |
| 70 | } |
| 71 | } |