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.TypeConverter;
023 import org.apache.camel.util.ObjectHelper;
024
025 /**
026 * Uses the {@link java.beans.PropertyEditor} conversion system to convert Objects to
027 * and from String values.
028 *
029 * @version $Revision: 659798 $
030 */
031 public class PropertyEditorTypeConverter implements TypeConverter {
032
033 public <T> T convertTo(Class<T> toType, Object value) {
034 // We can't convert null values since we can't figure out a property
035 // editor for it.
036 if (value == null) {
037 return null;
038 }
039
040 if (value.getClass() == String.class) {
041 // No conversion needed.
042 if (toType == String.class) {
043 return ObjectHelper.cast(toType, value);
044 }
045
046 PropertyEditor editor = PropertyEditorManager.findEditor(toType);
047 if (editor != null) {
048 editor.setAsText(value.toString());
049 return ObjectHelper.cast(toType, editor.getValue());
050 }
051 } else if (toType == String.class) {
052 PropertyEditor editor = PropertyEditorManager.findEditor(value.getClass());
053 if (editor != null) {
054 editor.setValue(value);
055 return ObjectHelper.cast(toType, editor.getAsText());
056 }
057 }
058
059 return null;
060 }
061
062 }