OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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
 *
182 ilm 4
 * Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
94 ilm 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<?>) {
182 ilm 76
                if (param == String.class) {
77
                    result = "string";
78
                } else {
79
                    result = ((Class<?>) param).getName();
80
                }
94 ilm 81
            } else if (param instanceof Iterable) {
82
                final Iterable<?> tmp = (Iterable<?>) param;
83
                final JSONArray jsonArray = new JSONArray();
84
                for (Object o : tmp) {
85
                    jsonArray.add(getJSON(o));
86
                }
87
                result = jsonArray;
88
            } else if (param instanceof Color) {
182 ilm 89
                String hexString = Integer.toHexString(((Color) param).getRGB());
90
                if (hexString.length() > 6) {
91
                    hexString = hexString.substring(2, hexString.length());
94 ilm 92
                }
182 ilm 93
                result = "#" + hexString;
142 ilm 94
            } else if (param instanceof BigDecimal) {
95
                result = ((BigDecimal) param).doubleValue();
94 ilm 96
            } else {
97
                result = param;
98
            }
99
        }
100
 
101
        return result;
102
    }
103
 
142 ilm 104
    public static <T> T getObjectFromJSON(final Object o, final Class<T> type) {
105
        final T result;
94 ilm 106
        if (o != null && !o.equals("null")) {
142 ilm 107
            if (type.isInstance(o)) {
108
                result = type.cast(o);
109
            } else if (type.equals(Integer.class)) {
110
                final int intVal;
111
                if (o instanceof BigDecimal) {
112
                    intVal = ((BigDecimal) o).intValueExact();
113
                } else if (o instanceof BigInteger) {
114
                    // TODO use intValueExact() in Java 8
115
                    final BigInteger bigInt = (BigInteger) o;
116
                    if (bigInt.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0 || bigInt.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0)
117
                        throw new IllegalArgumentException("object (" + o.getClass().getName() + ") is not assignable for '" + type + "'");
118
                    intVal = bigInt.intValue();
94 ilm 119
                } else {
120
                    try {
142 ilm 121
                        intVal = NumberUtils.ensureInt((Long) o);
122
                    } catch (ArithmeticException ex) {
123
                        throw new IllegalArgumentException("object (" + o.getClass().getName() + ") is not assignable for '" + type + "'", ex);
94 ilm 124
                    }
125
                }
142 ilm 126
                result = type.cast(intVal);
132 ilm 127
            } else if (type.equals(Date.class)) {
94 ilm 128
                final String sparam = (String) o;
142 ilm 129
                try {
130
                    final Date c = parse(sparam);
131
                    result = type.cast(c);
132
                } catch (java.text.ParseException e) {
133
                    throw new IllegalArgumentException("object (" + o.getClass().getName() + ") is not assignable for '" + type + "', the format is not valid", e);
94 ilm 134
                }
142 ilm 135
            } else if (type.equals(Color.class)) {
182 ilm 136
                result = type.cast(Color.decode(o.toString()));
94 ilm 137
            } else {
142 ilm 138
                result = type.cast(o);
94 ilm 139
            }
132 ilm 140
        } else {
141
            result = null;
94 ilm 142
        }
143
 
142 ilm 144
        return result;
94 ilm 145
    }
146
 
142 ilm 147
    public static <T> T getParameterFromJSON(final JSONObject json, final String key, final Class<T> type) {
94 ilm 148
        return getParameterFromJSON(json, key, type, null);
149
    }
150
 
142 ilm 151
    public static <T> T getParameterFromJSON(final JSONObject json, final String key, final Class<T> type, T defaultValue) {
180 ilm 152
        if (json == null) {
153
            throw new IllegalArgumentException("null JSON");
154
        }
155
        if (key == null) {
156
            throw new IllegalArgumentException("null key");
157
        }
142 ilm 158
        return json.containsKey(key) ? getObjectFromJSON(json.get(key), type) : defaultValue;
94 ilm 159
    }
160
 
132 ilm 161
    public static JSONObject convertStringToJsonObject(final String jsonString) {
162
        final JSONParser parser = new JSONParser(JSONParser.USE_HI_PRECISION_FLOAT);
163
        final JSONObject json;
164
        try {
165
            json = (JSONObject) parser.parse(jsonString);
166
        } catch (final ParseException ex) {
167
            throw new IllegalArgumentException(ex.getMessage(), ex);
168
        }
169
        return json;
170
    }
171
 
172
    public static JSONArray convertStringToJsonArray(final String jsonString) {
173
        final JSONParser parser = new JSONParser(JSONParser.USE_HI_PRECISION_FLOAT);
174
        final JSONArray json;
175
        try {
176
            json = (JSONArray) parser.parse(jsonString);
177
        } catch (final ParseException ex) {
178
            throw new IllegalArgumentException(ex.getMessage(), ex);
179
        }
180
        return json;
181
    }
94 ilm 182
}