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 java.util.Collection; |
19 | import java.util.Map; |
20 | |
21 | /** |
22 | * {@link FieldExtractor} that just returns the original item. If the item is an |
23 | * array or collection it will be returned as is, otherwise it is wrapped in a |
24 | * single element array. |
25 | * |
26 | * @author Dave Syer |
27 | * |
28 | */ |
29 | public class PassThroughFieldExtractor<T> implements FieldExtractor<T> { |
30 | |
31 | /** |
32 | * Get an array of fields as close as possible to the input. The result |
33 | * depends on the type of the input: |
34 | * <ul> |
35 | * <li>A {@link FieldSet} or array will be returned as is</li> |
36 | * <li>For a Collection the <code>toArray()</code> method will be used</li> |
37 | * <li>For a Map the <code>values()</code> will be returned as an array</li> |
38 | * <li>Otherwise it is wrapped in a single element array.</li> |
39 | * </ul> |
40 | * Note that no attempt is made to sort the values, so passing in an |
41 | * unordered collection or map is probably a bad idea. Spring often gives |
42 | * you an ordered Map (e.g. if extracting data from a generic query using |
43 | * JDBC), so check the documentation for whatever is being used to generate |
44 | * the input. |
45 | * |
46 | * @param item the object to convert |
47 | * @return an array of objects as close as possible to the original item |
48 | */ |
49 | public Object[] extract(T item) { |
50 | |
51 | if (item.getClass().isArray()) { |
52 | return (Object[]) item; |
53 | } |
54 | |
55 | if (item instanceof Collection<?>) { |
56 | return ((Collection<?>) item).toArray(); |
57 | } |
58 | |
59 | if (item instanceof Map<?, ?>) { |
60 | return ((Map<?, ?>) item).values().toArray(); |
61 | } |
62 | |
63 | if (item instanceof FieldSet) { |
64 | return ((FieldSet) item).getValues(); |
65 | } |
66 | |
67 | return new Object[] { item }; |
68 | |
69 | } |
70 | |
71 | } |