OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 142 | Rev 180 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
94 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.utils.io;
15
 
132 ilm 16
import org.openconcerto.utils.NumberUtils;
142 ilm 17
import org.openconcerto.utils.XMLDateFormat;
132 ilm 18
 
94 ilm 19
import java.awt.Color;
142 ilm 20
import java.math.BigDecimal;
21
import java.math.BigInteger;
22
import java.text.Format;
94 ilm 23
import java.util.Calendar;
142 ilm 24
import java.util.Date;
94 ilm 25
 
144 ilm 26
import com.google.gson.Gson;
27
import com.google.gson.JsonElement;
28
import com.google.gson.reflect.TypeToken;
29
 
94 ilm 30
import net.minidev.json.JSONArray;
31
import net.minidev.json.JSONObject;
132 ilm 32
import net.minidev.json.parser.JSONParser;
33
import net.minidev.json.parser.ParseException;
94 ilm 34
 
35
public class JSONConverter {
36
 
144 ilm 37
    // type-safe methods
38
 
39
    public static final <T> T fromJson(final Gson gson, String json, TypeToken<T> typeOfT) {
40
        return gson.fromJson(json, typeOfT.getType());
41
    }
42
 
43
    public static final <T> T fromJson(final Gson gson, JsonElement json, TypeToken<T> typeOfT) {
44
        return gson.fromJson(json, typeOfT.getType());
45
    }
46
 
47
    // ** net.minidev.json
48
 
142 ilm 49
    static private final Format DF = new XMLDateFormat();
50
 
51
    static synchronized private final String format(final Date d) {
52
        return DF.format(d);
53
    }
54
 
55
    public synchronized static String formatCalendar(final Calendar calendar) {
56
        return DF.format(calendar);
57
    }
58
 
59
    static synchronized private final Date parse(final String s) throws java.text.ParseException {
60
        return (Date) DF.parseObject(s);
61
    }
62
 
94 ilm 63
    public static Object getJSON(Object param) {
64
        Object result = null;
65
 
66
        if (param != null) {
132 ilm 67
            if (param instanceof HTMLable) {
68
                result = ((HTMLable) param).getHTML();
69
            } else if (param instanceof JSONAble) {
94 ilm 70
                result = ((JSONAble) param).toJSON();
142 ilm 71
            } else if (param instanceof Date) {
72
                result = format((Date) param);
132 ilm 73
            } else if (param instanceof Calendar) {
142 ilm 74
                result = formatCalendar(((Calendar) param));
94 ilm 75
            } else if (param instanceof Class<?>) {
76
                result = ((Class<?>) param).getName();
77
            } else if (param instanceof Iterable) {
78
                final Iterable<?> tmp = (Iterable<?>) param;
79
                final JSONArray jsonArray = new JSONArray();
80
                for (Object o : tmp) {
81
                    jsonArray.add(getJSON(o));
82
                }
83
                result = jsonArray;
84
            } else if (param instanceof Color) {
85
                if (param != null) {
86
                    final Color paramColor = (Color) param;
87
                    final JSONObject jsonColor = new JSONObject();
88
                    jsonColor.put("r", paramColor.getRed());
89
                    jsonColor.put("g", paramColor.getGreen());
90
                    jsonColor.put("b", paramColor.getBlue());
91
                    result = jsonColor;
92
                }
142 ilm 93
            } else if (param instanceof BigDecimal) {
94
                result = ((BigDecimal) param).doubleValue();
94 ilm 95
            } else {
96
                result = param;
97
            }
98
        }
99
 
100
        return result;
101
    }
102
 
142 ilm 103
    public static <T> T getObjectFromJSON(final Object o, final Class<T> type) {
104
        final T result;
94 ilm 105
        if (o != null && !o.equals("null")) {
142 ilm 106
            if (type.isInstance(o)) {
107
                result = type.cast(o);
108
            } else if (type.equals(Integer.class)) {
109
                final int intVal;
110
                if (o instanceof BigDecimal) {
111
                    intVal = ((BigDecimal) o).intValueExact();
112
                } else if (o instanceof BigInteger) {
113
                    // TODO use intValueExact() in Java 8
114
                    final BigInteger bigInt = (BigInteger) o;
115
                    if (bigInt.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0 || bigInt.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0)
116
                        throw new IllegalArgumentException("object (" + o.getClass().getName() + ") is not assignable for '" + type + "'");
117
                    intVal = bigInt.intValue();
94 ilm 118
                } else {
119
                    try {
142 ilm 120
                        intVal = NumberUtils.ensureInt((Long) o);
121
                    } catch (ArithmeticException ex) {
122
                        throw new IllegalArgumentException("object (" + o.getClass().getName() + ") is not assignable for '" + type + "'", ex);
94 ilm 123
                    }
124
                }
142 ilm 125
                result = type.cast(intVal);
132 ilm 126
            } else if (type.equals(Date.class)) {
94 ilm 127
                final String sparam = (String) o;
142 ilm 128
                try {
129
                    final Date c = parse(sparam);
130
                    result = type.cast(c);
131
                } catch (java.text.ParseException e) {
132
                    throw new IllegalArgumentException("object (" + o.getClass().getName() + ") is not assignable for '" + type + "', the format is not valid", e);
94 ilm 133
                }
142 ilm 134
            } else if (type.equals(Color.class)) {
135
                final JSONObject jsonColor = (JSONObject) o;
136
                final int r = JSONConverter.getParameterFromJSON(jsonColor, "r", Integer.class);
137
                final int g = JSONConverter.getParameterFromJSON(jsonColor, "g", Integer.class);
138
                final int b = JSONConverter.getParameterFromJSON(jsonColor, "b", Integer.class);
139
                result = type.cast(new Color(r, g, b));
94 ilm 140
            } else {
142 ilm 141
                result = type.cast(o);
94 ilm 142
            }
132 ilm 143
        } else {
144
            result = null;
94 ilm 145
        }
146
 
142 ilm 147
        return result;
94 ilm 148
    }
149
 
142 ilm 150
    public static <T> T getParameterFromJSON(final JSONObject json, final String key, final Class<T> type) {
94 ilm 151
        return getParameterFromJSON(json, key, type, null);
152
    }
153
 
142 ilm 154
    public static <T> T getParameterFromJSON(final JSONObject json, final String key, final Class<T> type, T defaultValue) {
155
        return json.containsKey(key) ? getObjectFromJSON(json.get(key), type) : defaultValue;
94 ilm 156
    }
157
 
132 ilm 158
    public static JSONObject convertStringToJsonObject(final String jsonString) {
159
        final JSONParser parser = new JSONParser(JSONParser.USE_HI_PRECISION_FLOAT);
160
        final JSONObject json;
161
        try {
162
            json = (JSONObject) parser.parse(jsonString);
163
        } catch (final ParseException ex) {
164
            throw new IllegalArgumentException(ex.getMessage(), ex);
165
        }
166
        return json;
167
    }
168
 
169
    public static JSONArray convertStringToJsonArray(final String jsonString) {
170
        final JSONParser parser = new JSONParser(JSONParser.USE_HI_PRECISION_FLOAT);
171
        final JSONArray json;
172
        try {
173
            json = (JSONArray) parser.parse(jsonString);
174
        } catch (final ParseException ex) {
175
            throw new IllegalArgumentException(ex.getMessage(), ex);
176
        }
177
        return json;
178
    }
94 ilm 179
}