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