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