OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 94 | Rev 142 | 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;
17
 
94 ilm 18
import java.awt.Color;
19
import java.sql.Date;
20
import java.sql.Timestamp;
21
import java.text.SimpleDateFormat;
22
import java.util.Calendar;
23
import java.util.List;
24
import java.util.regex.Matcher;
25
import java.util.regex.Pattern;
26
 
27
import javax.xml.bind.DatatypeConverter;
28
 
29
import net.minidev.json.JSONArray;
30
import net.minidev.json.JSONObject;
132 ilm 31
import net.minidev.json.parser.JSONParser;
32
import net.minidev.json.parser.ParseException;
94 ilm 33
 
34
public class JSONConverter {
35
    final static Pattern pattern = Pattern.compile("d{4}-[01]d-[0-3]dT[0-2]d:[0-5]d:[0-5]d.d+([+-][0-2]d:[0-5]d|Z)");
36
 
37
    public static Object getJSON(Object param) {
38
        Object result = null;
39
 
40
        if (param != null) {
132 ilm 41
            if (param instanceof HTMLable) {
42
                result = ((HTMLable) param).getHTML();
43
            } else if (param instanceof JSONAble) {
94 ilm 44
                result = ((JSONAble) param).toJSON();
45
            } else if (param instanceof Timestamp) {
46
                final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
47
                result = df.format((Timestamp) param);
132 ilm 48
            } else if (param instanceof Calendar) {
49
                final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
50
                result = df.format(((Calendar) param).getTime());
94 ilm 51
            } else if (param instanceof Class<?>) {
52
                result = ((Class<?>) param).getName();
53
            } else if (param instanceof Iterable) {
54
                final Iterable<?> tmp = (Iterable<?>) param;
55
                final JSONArray jsonArray = new JSONArray();
56
                for (Object o : tmp) {
57
                    jsonArray.add(getJSON(o));
58
                }
59
                result = jsonArray;
60
            } else if (param instanceof Color) {
61
                if (param != null) {
62
                    final Color paramColor = (Color) param;
63
                    final JSONObject jsonColor = new JSONObject();
64
                    jsonColor.put("r", paramColor.getRed());
65
                    jsonColor.put("g", paramColor.getGreen());
66
                    jsonColor.put("b", paramColor.getBlue());
67
                    result = jsonColor;
68
                }
69
            } else {
70
                result = param;
71
            }
72
        }
73
 
74
        return result;
75
    }
76
 
132 ilm 77
    public static <T extends Object> T getObjectFromJSON(final Object o, final Class<T> type) {
78
        return getObjectFromJSON(o, type, null);
79
    }
94 ilm 80
 
132 ilm 81
    public static <T extends Object> T getObjectFromJSON(final Object o, final Class<T> type, final Object defaultValue) {
82
        Object result = defaultValue;
83
 
94 ilm 84
        if (o != null && !o.equals("null")) {
132 ilm 85
            if (type.equals(Integer.class)) {
94 ilm 86
                if (!o.getClass().isAssignableFrom(Long.class)) {
87
                    throw new IllegalArgumentException("object (" + o.getClass().getName() + ") is not assignable for '" + type + "'");
88
                } else {
89
                    try {
90
                        result = NumberUtils.ensureInt((Long) o);
91
                    } catch (IllegalArgumentException ex) {
92
                        throw new IllegalArgumentException("object (" + o.getClass().getName() + ") is not assignable for '" + type + "', " + ex.getMessage());
93
                    }
94
                }
132 ilm 95
            } else if (type.equals(Date.class)) {
94 ilm 96
                if (!o.getClass().isAssignableFrom(String.class)) {
97
                    throw new IllegalArgumentException("object (" + o.getClass().getName() + ") is not assignable for '" + type + "'");
98
                }
99
                final String sparam = (String) o;
100
                final Matcher matcher = pattern.matcher(sparam);
101
                if (matcher.find()) {
102
                    final Calendar c = DatatypeConverter.parseDateTime(sparam);
103
                    result = c.getTime();
104
                } else {
105
                    throw new IllegalArgumentException("object (" + o.getClass().getName() + ") is not assignable for '" + type + "', the format is not valid");
106
                }
107
            } else {
108
                if (!o.getClass().isAssignableFrom(type)) {
109
                    throw new IllegalArgumentException("object (" + o.getClass().getName() + ") is not assignable for '" + type + "'");
110
                }
111
                result = o;
112
            }
132 ilm 113
        } else {
114
            result = null;
94 ilm 115
        }
116
 
132 ilm 117
        return (T) result;
94 ilm 118
    }
119
 
132 ilm 120
    public static <T extends Object> T getParameterFromJSON(final JSONObject json, final String key, final Class<T> type) {
94 ilm 121
        return getParameterFromJSON(json, key, type, null);
122
    }
123
 
132 ilm 124
    public static <T extends Object> T getParameterFromJSON(final JSONObject json, final String key, final Class<T> type, Object defaultValue) {
94 ilm 125
        Object o = defaultValue;
126
        if (json.containsKey(key)) {
127
            o = json.get(key);
128
            if (o == null || o.equals("null")) {
129
                o = null;
130
            } else {
132 ilm 131
                if (type.equals(Integer.class)) {
94 ilm 132
                    if (!o.getClass().isAssignableFrom(Long.class)) {
132 ilm 133
                        throw new IllegalArgumentException("value  " + o + " for '" + key + "' is invalid");
94 ilm 134
                    } else {
135
                        try {
136
                            o = NumberUtils.ensureInt((Long) o);
137
                        } catch (IllegalArgumentException ex) {
132 ilm 138
                            throw new IllegalArgumentException("value  " + o + " for '" + key + "' is invalid, " + ex.getMessage());
94 ilm 139
                        }
140
                    }
132 ilm 141
                } else if (type.equals(Color.class)) {
142
                    if (!(o instanceof JSONObject)) {
143
                        throw new IllegalArgumentException("value  " + o + " for '" + key + "' is invalid");
144
                    }
145
 
146
                    final JSONObject jsonColor = (JSONObject) o;
147
                    final int r = (Integer) JSONConverter.getParameterFromJSON(jsonColor, "r", Integer.class);
148
                    final int g = (Integer) JSONConverter.getParameterFromJSON(jsonColor, "g", Integer.class);
149
                    final int b = (Integer) JSONConverter.getParameterFromJSON(jsonColor, "b", Integer.class);
150
                    o = new Color(r, g, b);
94 ilm 151
                } else {
152
                    if (!o.getClass().isAssignableFrom(type)) {
132 ilm 153
                        throw new IllegalArgumentException("value  " + o + " for '" + key + "' is invalid");
94 ilm 154
                    }
155
                }
156
            }
157
        }
132 ilm 158
        return (T) o;
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
    }
182
 
94 ilm 183
    // TODO move to another class
184
    public static boolean listInstanceOf(Object object, Class<?> c) {
185
        if (object instanceof List<?>) {
186
            final List<?> list = (List<?>) object;
187
            final int listSize = list.size();
188
            for (int i = 0; i < listSize; i++) {
189
                if (!c.isInstance(list.get(i))) {
190
                    return false;
191
                }
192
            }
193
        } else {
194
            return false;
195
        }
196
        return true;
197
    }
198
}