OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 144 | Rev 182 | Go to most recent revision | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | RSS feed

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