001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.camel.impl.converter;
018    
019    import java.beans.PropertyEditor;
020    import java.beans.PropertyEditorManager;
021    
022    import org.apache.camel.Exchange;
023    import org.apache.camel.TypeConverter;
024    import org.apache.camel.util.ObjectHelper;
025    
026    /**
027     * Uses the {@link java.beans.PropertyEditor} conversion system to convert Objects to
028     * and from String values.
029     *
030     * @version $Revision: 46981 $
031     */
032    public class PropertyEditorTypeConverter implements TypeConverter {
033    
034        public <T> T convertTo(Class<T> toType, Object value) {
035            // We can't convert null values since we can't figure out a property
036            // editor for it.
037            if (value == null) {
038                return null;
039            }
040    
041            if (value.getClass() == String.class) {
042                // No conversion needed.
043                if (toType == String.class) {
044                    return ObjectHelper.cast(toType, value);
045                }
046    
047                PropertyEditor editor = PropertyEditorManager.findEditor(toType);
048                if (editor != null) {
049                    editor.setAsText(value.toString());
050                    return ObjectHelper.cast(toType, editor.getValue());
051                }
052            } else if (toType == String.class) {
053                PropertyEditor editor = PropertyEditorManager.findEditor(value.getClass());
054                if (editor != null) {
055                    editor.setValue(value);
056                    return ObjectHelper.cast(toType, editor.getAsText());
057                }
058            }
059    
060            return null;
061        }
062    
063        public <T> T convertTo(Class<T> type, Exchange exchange, Object value) {
064            return convertTo(type, value);
065        }
066    }