001/*
002 * Copyright 2006-2007 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.springframework.batch.item.file.transform;
017
018import java.util.Collection;
019import java.util.Map;
020
021/**
022 * {@link FieldExtractor} that just returns the original item. If the item is an
023 * array or collection it will be returned as is, otherwise it is wrapped in a
024 * single element array.
025 * 
026 * @author Dave Syer
027 * 
028 */
029public class PassThroughFieldExtractor<T> implements FieldExtractor<T> {
030
031        /**
032         * Get an array of fields as close as possible to the input. The result
033         * depends on the type of the input:
034         * <ul>
035         * <li>A {@link FieldSet} or array will be returned as is</li>
036         * <li>For a Collection the <code>toArray()</code> method will be used</li>
037         * <li>For a Map the <code>values()</code> will be returned as an array</li>
038         * <li>Otherwise it is wrapped in a single element array.</li>
039         * </ul>
040         * Note that no attempt is made to sort the values, so passing in an
041         * unordered collection or map is probably a bad idea. Spring often gives
042         * you an ordered Map (e.g. if extracting data from a generic query using
043         * JDBC), so check the documentation for whatever is being used to generate
044         * the input.
045         * 
046         * @param item the object to convert
047         * @return an array of objects as close as possible to the original item
048         */
049    @Override
050        public Object[] extract(T item) {
051
052                if (item.getClass().isArray()) {
053                        return (Object[]) item;
054                }
055
056                if (item instanceof Collection<?>) {
057                        return ((Collection<?>) item).toArray();
058                }
059
060                if (item instanceof Map<?, ?>) {
061                        return ((Map<?, ?>) item).values().toArray();
062                }
063
064                if (item instanceof FieldSet) {
065                        return ((FieldSet) item).getValues();
066                }
067
068                return new Object[] { item };
069
070        }
071
072}