it.delli.mwebc.utils.DefaultCastHelper.java Source code

Java tutorial

Introduction

Here is the source code for it.delli.mwebc.utils.DefaultCastHelper.java

Source

/*
 * (C) Copyright 2010, by Francesco Delli Paoli.
 * 
 * Project Info:  http://mwebc.sourceforge.net/
 * 
 * This file is part of mwebc - Model Web Controller.
 * 
 * mwebc is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * mwebc is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with mwebc; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

package it.delli.mwebc.utils;

import java.awt.Color;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.time.DateUtils;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

public class DefaultCastHelper implements CastHelper {

    private static String[] datePatterns;

    public static SimpleDateFormat isoDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss");

    static {
        List<String> parsePatterns = new ArrayList<String>();
        parsePatterns.add("yyyy-MM-dd'T'HH:mm:ss.sssZZ");
        parsePatterns.add("yyyy-MM-dd'T'HH:mm:ss.sss");
        parsePatterns.add("yyyy-MM-dd'T'HH:mm:ssZZ");
        parsePatterns.add("yyyy-MM-dd'T'HH:mm:ss");
        parsePatterns.add("yyyy-MM-dd'T'HH:mmZZ");
        parsePatterns.add("yyyy-MM-dd'T'HH:mm");
        parsePatterns.add("yyyy-MM-dd");
        parsePatterns.add("yyyy-MM");
        parsePatterns.add("yyyy");
        datePatterns = (String[]) parsePatterns.toArray(new String[parsePatterns.size()]);
    }

    public Object toType(String value, Class<?> type) {
        Object obj = null;
        try {
            if (value != null) {
                if (type.getName().equals(String.class.getName())) {
                    obj = toString(value);
                } else if (type.getName().equals(String[].class.getName())) {
                    obj = toStringArray(value);
                } else if (type.getName().equals(Character.class.getName())) {
                    obj = toCharacter(value);
                } else if (type.getName().equals(Character[].class.getName())) {
                    obj = toCharacterArray(value);
                } else if (type.getName().equals(Integer.class.getName())) {
                    obj = toInteger(value);
                } else if (type.getName().equals(Integer[].class.getName())) {
                    obj = toIntegerArray(value);
                } else if (type.getName().equals(Long.class.getName())) {
                    obj = toLong(value);
                } else if (type.getName().equals(Long[].class.getName())) {
                    obj = toLongArray(value);
                } else if (type.getName().equals(Double.class.getName())) {
                    obj = toDouble(value);
                } else if (type.getName().equals(Double[].class.getName())) {
                    obj = toDoubleArray(value);
                } else if (type.getName().equals(Boolean.class.getName())) {
                    obj = toBoolean(value);
                } else if (type.getName().equals(Boolean[].class.getName())) {
                    obj = toBooleanArray(value);
                } else if (type.getName().equals(Date.class.getName())) {
                    obj = toDate(value);
                } else if (type.getName().equals(Date[].class.getName())) {
                    obj = toDateArray(value);
                } else if (type.getName().equals(Color.class.getName())) {
                    obj = toColor(value);
                } else if (type.getName().equals(Color[].class.getName())) {
                    obj = toColorArray(value);
                } else if (type.isEnum()) {
                    for (int i = 0; i < type.getEnumConstants().length; i++) {
                        if (type.getEnumConstants()[i].toString().equals(value)) {
                            obj = type.getEnumConstants()[i];
                        }
                    }
                } else if (type.isArray() && type.getComponentType().isEnum()) {
                    String[] tmp = value.split(",");
                    Enum[] array = new Enum[tmp.length];
                    for (int j = 0; j < tmp.length; j++) {
                        String item = tmp[j].trim();
                        for (int i = 0; i < type.getComponentType().getEnumConstants().length; i++) {
                            if (type.getComponentType().getEnumConstants()[i].toString().equals(item)) {
                                array[j] = (Enum) type.getComponentType().getEnumConstants()[i];
                            }
                        }
                    }
                    obj = array;
                } else if (type.getName().equals(Map.class.getName())
                        || type.getName().equals(HashMap.class.getName())
                        || type.getName().equals(LinkedHashMap.class.getName())) {
                    obj = toMap(value, type);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    private String toString(String value) {
        return value.toString();
    }

    private String[] toStringArray(String value) {
        String[] array = value.split(",");
        return array;
    }

    private Character toCharacter(String value) {
        return value.toCharArray()[0];
    }

    private Character[] toCharacterArray(String value) {
        String[] tmp = value.split(",");
        Character[] array = new Character[tmp.length];
        for (int i = 0; i < tmp.length; i++) {
            String item = tmp[i].trim();
            array[i] = toCharacter(item);
        }
        return array;
    }

    private Integer toInteger(String value) {
        return Integer.parseInt(value);
    }

    private Integer[] toIntegerArray(String value) {
        String[] tmp = value.split(",");
        Integer[] array = new Integer[tmp.length];
        for (int i = 0; i < tmp.length; i++) {
            String item = tmp[i].trim();
            array[i] = toInteger(item);
        }
        return array;
    }

    private Long toLong(String value) {
        return Long.parseLong(value);
    }

    private Long[] toLongArray(String value) {
        String[] tmp = value.split(",");
        Long[] array = new Long[tmp.length];
        for (int i = 0; i < tmp.length; i++) {
            String item = tmp[i].trim();
            array[i] = toLong(item);
        }
        return array;
    }

    private Double toDouble(String value) {
        return Double.parseDouble(value);
    }

    private Double[] toDoubleArray(String value) {
        String[] tmp = value.split(",");
        Double[] array = new Double[tmp.length];
        for (int i = 0; i < tmp.length; i++) {
            String item = tmp[i].trim();
            array[i] = toDouble(item);
        }
        return array;
    }

    private Boolean toBoolean(String value) {
        return Boolean.parseBoolean(value);
    }

    private Boolean[] toBooleanArray(String value) {
        String[] tmp = value.split(",");
        Boolean[] array = new Boolean[tmp.length];
        for (int i = 0; i < tmp.length; i++) {
            String item = tmp[i].trim();
            array[i] = toBoolean(item);
        }
        return array;
    }

    private Date toDate(String value) throws ParseException {
        return DateUtils.parseDate(value, datePatterns);
    }

    private Date[] toDateArray(String value) throws ParseException {
        String[] tmp = value.split(",");
        Date[] array = new Date[tmp.length];
        for (int i = 0; i < tmp.length; i++) {
            String item = tmp[i].trim();
            array[i] = toDate(item);
        }
        return array;
    }

    private Color toColor(String value) throws ParseException {
        return new Color(Integer.parseInt(value.replaceFirst("#", ""), 16));
    }

    private Color[] toColorArray(String value) throws ParseException {
        String[] tmp = value.split(",");
        Color[] array = new Color[tmp.length];
        for (int i = 0; i < tmp.length; i++) {
            String item = tmp[i].trim();
            array[i] = toColor(item);
        }
        return array;
    }

    private Map toMap(String value, Class<?> type) throws Exception {
        Map map = (Map) type.newInstance();
        JsonObject data = new GsonBuilder()
                .registerTypeAdapter(JsonObject.class, new JsonDeserializer<JsonObject>() {
                    public JsonObject deserialize(JsonElement json, Type arg1, JsonDeserializationContext arg2)
                            throws JsonParseException {
                        return json.getAsJsonObject();
                    }
                }).create().fromJson(value, JsonObject.class);
        for (Map.Entry<String, JsonElement> entry : data.entrySet()) {
            map.put(entry.getKey(), entry.getValue().getAsString());
        }
        return map;
    }

}