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 java.beans.PropertyEditor conversion system to convert Objects to
027 * and from String values.
028 *
029 * @version $Revision: 36321 $
030 */
031 public class PropertyEditorTypeConverter implements TypeConverter {
032
033 public <T> T convertTo(Class<T> toType, Object value) {
034
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
042 if (value.getClass() == String.class) {
043
044 // No conversion needed.
045 if (toType == String.class) {
046 return ObjectHelper.cast(toType, value);
047 }
048
049 PropertyEditor editor = PropertyEditorManager.findEditor(toType);
050 if (editor != null) {
051 editor.setAsText(value.toString());
052 return ObjectHelper.cast(toType, editor.getValue());
053 }
054
055 } else if (toType == String.class) {
056
057 PropertyEditor editor = PropertyEditorManager.findEditor(value.getClass());
058 if (editor != null) {
059 editor.setValue(value);
060 return ObjectHelper.cast(toType, editor.getAsText());
061 }
062 }
063 return null;
064 }
065
066 }