001/*
002 * Copyright 2002-2019 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 */
016
017package org.springframework.beans.propertyeditors;
018
019import java.beans.PropertyEditorSupport;
020import java.lang.reflect.Array;
021import java.util.ArrayList;
022import java.util.Collection;
023import java.util.LinkedHashSet;
024import java.util.List;
025import java.util.SortedSet;
026import java.util.TreeSet;
027
028import org.springframework.lang.Nullable;
029import org.springframework.util.Assert;
030import org.springframework.util.ReflectionUtils;
031
032/**
033 * Property editor for Collections, converting any source Collection
034 * to a given target Collection type.
035 *
036 * <p>By default registered for Set, SortedSet and List,
037 * to automatically convert any given Collection to one of those
038 * target types if the type does not match the target property.
039 *
040 * @author Juergen Hoeller
041 * @since 1.1.3
042 * @see java.util.Collection
043 * @see java.util.Set
044 * @see java.util.SortedSet
045 * @see java.util.List
046 */
047public class CustomCollectionEditor extends PropertyEditorSupport {
048
049        @SuppressWarnings("rawtypes")
050        private final Class<? extends Collection> collectionType;
051
052        private final boolean nullAsEmptyCollection;
053
054
055        /**
056         * Create a new CustomCollectionEditor for the given target type,
057         * keeping an incoming {@code null} as-is.
058         * @param collectionType the target type, which needs to be a
059         * sub-interface of Collection or a concrete Collection class
060         * @see java.util.Collection
061         * @see java.util.ArrayList
062         * @see java.util.TreeSet
063         * @see java.util.LinkedHashSet
064         */
065        @SuppressWarnings("rawtypes")
066        public CustomCollectionEditor(Class<? extends Collection> collectionType) {
067                this(collectionType, false);
068        }
069
070        /**
071         * Create a new CustomCollectionEditor for the given target type.
072         * <p>If the incoming value is of the given type, it will be used as-is.
073         * If it is a different Collection type or an array, it will be converted
074         * to a default implementation of the given Collection type.
075         * If the value is anything else, a target Collection with that single
076         * value will be created.
077         * <p>The default Collection implementations are: ArrayList for List,
078         * TreeSet for SortedSet, and LinkedHashSet for Set.
079         * @param collectionType the target type, which needs to be a
080         * sub-interface of Collection or a concrete Collection class
081         * @param nullAsEmptyCollection whether to convert an incoming {@code null}
082         * value to an empty Collection (of the appropriate type)
083         * @see java.util.Collection
084         * @see java.util.ArrayList
085         * @see java.util.TreeSet
086         * @see java.util.LinkedHashSet
087         */
088        @SuppressWarnings("rawtypes")
089        public CustomCollectionEditor(Class<? extends Collection> collectionType, boolean nullAsEmptyCollection) {
090                Assert.notNull(collectionType, "Collection type is required");
091                if (!Collection.class.isAssignableFrom(collectionType)) {
092                        throw new IllegalArgumentException(
093                                        "Collection type [" + collectionType.getName() + "] does not implement [java.util.Collection]");
094                }
095                this.collectionType = collectionType;
096                this.nullAsEmptyCollection = nullAsEmptyCollection;
097        }
098
099
100        /**
101         * Convert the given text value to a Collection with a single element.
102         */
103        @Override
104        public void setAsText(String text) throws IllegalArgumentException {
105                setValue(text);
106        }
107
108        /**
109         * Convert the given value to a Collection of the target type.
110         */
111        @Override
112        public void setValue(@Nullable Object value) {
113                if (value == null && this.nullAsEmptyCollection) {
114                        super.setValue(createCollection(this.collectionType, 0));
115                }
116                else if (value == null || (this.collectionType.isInstance(value) && !alwaysCreateNewCollection())) {
117                        // Use the source value as-is, as it matches the target type.
118                        super.setValue(value);
119                }
120                else if (value instanceof Collection) {
121                        // Convert Collection elements.
122                        Collection<?> source = (Collection<?>) value;
123                        Collection<Object> target = createCollection(this.collectionType, source.size());
124                        for (Object elem : source) {
125                                target.add(convertElement(elem));
126                        }
127                        super.setValue(target);
128                }
129                else if (value.getClass().isArray()) {
130                        // Convert array elements to Collection elements.
131                        int length = Array.getLength(value);
132                        Collection<Object> target = createCollection(this.collectionType, length);
133                        for (int i = 0; i < length; i++) {
134                                target.add(convertElement(Array.get(value, i)));
135                        }
136                        super.setValue(target);
137                }
138                else {
139                        // A plain value: convert it to a Collection with a single element.
140                        Collection<Object> target = createCollection(this.collectionType, 1);
141                        target.add(convertElement(value));
142                        super.setValue(target);
143                }
144        }
145
146        /**
147         * Create a Collection of the given type, with the given
148         * initial capacity (if supported by the Collection type).
149         * @param collectionType a sub-interface of Collection
150         * @param initialCapacity the initial capacity
151         * @return the new Collection instance
152         */
153        @SuppressWarnings({"rawtypes", "unchecked"})
154        protected Collection<Object> createCollection(Class<? extends Collection> collectionType, int initialCapacity) {
155                if (!collectionType.isInterface()) {
156                        try {
157                                return ReflectionUtils.accessibleConstructor(collectionType).newInstance();
158                        }
159                        catch (Throwable ex) {
160                                throw new IllegalArgumentException(
161                                                "Could not instantiate collection class: " + collectionType.getName(), ex);
162                        }
163                }
164                else if (List.class == collectionType) {
165                        return new ArrayList<>(initialCapacity);
166                }
167                else if (SortedSet.class == collectionType) {
168                        return new TreeSet<>();
169                }
170                else {
171                        return new LinkedHashSet<>(initialCapacity);
172                }
173        }
174
175        /**
176         * Return whether to always create a new Collection,
177         * even if the type of the passed-in Collection already matches.
178         * <p>Default is "false"; can be overridden to enforce creation of a
179         * new Collection, for example to convert elements in any case.
180         * @see #convertElement
181         */
182        protected boolean alwaysCreateNewCollection() {
183                return false;
184        }
185
186        /**
187         * Hook to convert each encountered Collection/array element.
188         * The default implementation simply returns the passed-in element as-is.
189         * <p>Can be overridden to perform conversion of certain elements,
190         * for example String to Integer if a String array comes in and
191         * should be converted to a Set of Integer objects.
192         * <p>Only called if actually creating a new Collection!
193         * This is by default not the case if the type of the passed-in Collection
194         * already matches. Override {@link #alwaysCreateNewCollection()} to
195         * enforce creating a new Collection in every case.
196         * @param element the source element
197         * @return the element to be used in the target Collection
198         * @see #alwaysCreateNewCollection()
199         */
200        protected Object convertElement(Object element) {
201                return element;
202        }
203
204
205        /**
206         * This implementation returns {@code null} to indicate that
207         * there is no appropriate text representation.
208         */
209        @Override
210        @Nullable
211        public String getAsText() {
212                return null;
213        }
214
215}