001/**
002 *   GRANITE DATA SERVICES
003 *   Copyright (C) 2006-2013 GRANITE DATA SERVICES S.A.S.
004 *
005 *   This file is part of the Granite Data Services Platform.
006 *
007 *   Granite Data Services is free software; you can redistribute it and/or
008 *   modify it under the terms of the GNU Lesser General Public
009 *   License as published by the Free Software Foundation; either
010 *   version 2.1 of the License, or (at your option) any later version.
011 *
012 *   Granite Data Services is distributed in the hope that it will be useful,
013 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
014 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
015 *   General Public License for more details.
016 *
017 *   You should have received a copy of the GNU Lesser General Public
018 *   License along with this library; if not, write to the Free Software
019 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
020 *   USA, or see <http://www.gnu.org/licenses/>.
021 */
022package org.granite.messaging.amf.io.convert.impl;
023
024import java.lang.reflect.Array;
025import java.lang.reflect.Type;
026
027import org.granite.messaging.amf.io.convert.Converter;
028import org.granite.messaging.amf.io.convert.Converters;
029import org.granite.messaging.amf.io.convert.IllegalConverterArgumentException;
030
031/**
032 * @author Franck WOLFF
033 */
034public class String2CharArray extends Converter {
035
036    public String2CharArray(Converters converters) {
037        super(converters);
038    }
039
040    @Override
041        protected boolean internalCanConvert(Object value, Type targetType) {
042        if (targetType instanceof Class<?>) {
043            Class<?> targetClass = (Class<?>)targetType;
044            return (
045                targetClass.isArray()
046            ) && (
047                targetClass.getComponentType().equals(Character.TYPE) ||
048                targetClass.getComponentType().equals(Character.class)
049            ) && (
050                value == null || value instanceof String
051            );
052        }
053        return false;
054    }
055
056    @Override
057        protected Object internalConvert(Object value, Type targetType) {
058        if (value == null)
059            return null;
060
061        Class<?> componentType = ((Class<?>)targetType).getComponentType();
062
063        if (componentType.equals(Character.TYPE)) // char[]
064            return ((String)value).toCharArray();
065
066        if (componentType.equals(Character.class)) { // Character[]
067            String s = (String)value;
068            Object array = Array.newInstance(Character.class, s.length());
069            for (int i = 0; i < s.length(); i++)
070                Array.set(array, i, Character.valueOf(s.charAt(i)));
071            return array;
072        }
073
074        throw new IllegalConverterArgumentException(this, value, targetType);
075    }
076}