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