OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 174 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
174 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.xml;
15
 
16
import org.openconcerto.utils.StringUtils;
17
import org.openconcerto.utils.cache.CacheResult;
18
import org.openconcerto.utils.cache.ICache;
19
import org.openconcerto.utils.cc.ExnTransformer;
20
 
21
import java.beans.XMLDecoder;
22
import java.beans.XMLEncoder;
23
import java.lang.reflect.Array;
24
import java.lang.reflect.Constructor;
25
import java.lang.reflect.InvocationTargetException;
26
import java.lang.reflect.Method;
27
import java.util.ArrayList;
28
import java.util.HashMap;
29
import java.util.LinkedList;
30
import java.util.List;
31
import java.util.Map;
32
import java.util.Stack;
33
 
34
/**
35
 * To decode XML in {@link XMLEncoder} format.
36
 *
37
 * @author Sylvain CUAZ
38
 * @param <S> type of source
39
 * @param <E> type of exception
40
 */
41
public abstract class AbstractXMLDecoder<S, E extends Exception> {
42
 
43
    protected static interface Children<C> {
44
        C getNextChild();
45
    }
46
 
47
    private static final ICache<Object, Method, Object> cache = new ICache<Object, Method, Object>(60, -1, "methods for " + XMLCodecUtils.class);
48
    private static final ICache<Object, Constructor<?>, Object> cacheCtor = new ICache<Object, Constructor<?>, Object>(60, -1, "constructors for " + XMLCodecUtils.class);
49
 
50
    protected abstract String getLocalName(S elem);
51
 
52
    protected abstract String getAttributeValue(S elem, final String attrName);
53
 
54
    protected abstract String getElementText(S elem) throws E;
55
 
56
    protected abstract S getFirstChild(S elem);
57
 
58
    protected abstract String toString(S elem);
59
 
60
    protected abstract Children<S> createChildren(S elem) throws E;
61
 
62
    public final <K, V> Map<K, V> decodeFromArray(final S elem, final Class<K> keyClass, final Class<V> valueClass) {
63
        return XMLCodecUtils.decodeFromArray((Object[]) this.decode1(elem), keyClass, valueClass);
64
    }
65
 
66
    /**
67
     * Tries to decode an xml element parsed from a string obtained from XMLEncoder. This doesn't
68
     * use {@link XMLDecoder} as it requires outputting it first to string which is inefficient.
69
     * NOTE: this decoder supports only a subset of XMLDecoder.
70
     *
71
     * @param javaElem a "java" element.
72
     * @return the decoded object.
73
     */
74
    public final Object decode1(S javaElem) {
75
        final S elem = getFirstChild(javaElem);
76
        try {
77
            return eval(elem, new Stack<Object>(), new HashMap<String, Object>());
78
        } catch (Exception e) {
79
            throw new IllegalStateException("error decoding " + toString(javaElem), e);
80
        }
81
    }
82
 
83
    private final Object eval(S elem, Stack<Object> context, final Map<String, Object> ids)
84
            throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, E {
85
        preEval(elem);
86
        final Object res = this._eval(elem, context, ids);
87
        postEval(elem, res);
88
        return res;
89
    }
90
 
91
    protected void preEval(S elem) throws E {
92
    }
93
 
94
    protected void nullDecoded(S elem) throws E {
95
    }
96
 
97
    protected void idRefDecoded(S elem) throws E {
98
    }
99
 
100
    protected void postEval(S elem, final Object res) throws E {
101
    }
102
 
103
    private final Object _eval(S elem, Stack<Object> context, final Map<String, Object> ids)
104
            throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, E {
105
        final String n = getLocalName(elem);
106
        // Ordered from real world scenario
107
        // string : 80k
108
        // void : 53k
109
        // int : 18k
110
        // object : 9k
111
        // null : 6k
112
        switch (n) {
113
        case "string":
114
            return getElementText(elem);
115
        case "void":
116
        case "object":
117
            final String idref = getAttributeValue(elem, "idref");
118
            if (idref != null) {
119
                if (!ids.containsKey(idref))
120
                    throw new IllegalStateException("id '" + idref + "' wasn't defined");
121
                idRefDecoded(elem);
122
                return ids.get(idref);
123
            }
124
            final String id = getAttributeValue(elem, "id");
125
            final String targetClass = getAttributeValue(elem, "class");
126
            final Object target = targetClass == null ? context.peek() : Class.forName(targetClass);
127
            final String propAttr = getAttributeValue(elem, "property");
128
            final String indexAttr = getAttributeValue(elem, "index");
129
            final String methodAttr = getAttributeValue(elem, "method");
180 ilm 130
            final String fieldAttr = getAttributeValue(elem, "field");
174 ilm 131
 
132
            // statement or expression
133
            final Object res = evalContainer(elem, context, ids, new ExnTransformer<List<Object>, Object, Exception>() {
134
                @Override
135
                public Object transformChecked(List<Object> args) throws Exception {
136
                    // call the statement
137
                    final Object res;
138
 
139
                    if (propAttr != null) {
140
                        final String methodName = (args.size() == 0 ? "get" : "set") + StringUtils.firstUp(propAttr);
141
                        res = invoke(target, methodName, args);
142
                    } else if (indexAttr != null) {
143
                        final String methodName;
144
                        if (target instanceof List) {
145
                            methodName = args.size() == 0 ? "get" : "set";
146
                            // get(index) or set(index, value)
147
                            args.add(0, Integer.valueOf(indexAttr));
148
                            res = invoke(target, methodName, args);
149
                        } else if (target.getClass().isArray()) {
150
                            final Class<?> componentType = target.getClass().getComponentType();
151
                            // in Array there's set(array, int index, Object value) or
152
                            // setPrimitive(array, int index, primitive value)
153
                            methodName = (args.size() == 0 ? "get" : "set") + (componentType.isPrimitive() ? StringUtils.firstUp(componentType.getSimpleName()) : "");
154
                            args.add(0, target);
155
                            args.add(1, Integer.valueOf(indexAttr));
156
                            res = invoke(Array.class, methodName, args);
157
                        } else
158
                            throw new IllegalStateException("use index with neither List nor array: " + target);
159
                    } else if (methodAttr != null) {
160
                        res = invoke(target, methodAttr, args);
180 ilm 161
                    } else if (fieldAttr != null) {
162
                        res = ((Class<?>) target).getField(fieldAttr).get(null);
163
                    } else {
174 ilm 164
                        res = getCtor((Class<?>) target, args).newInstance(args.toArray());
180 ilm 165
                    }
174 ilm 166
                    return res;
167
                }
168
            });
169
            // not very functional but it works
170
            if (id != null)
171
                ids.put(id, res);
172
            return res;
173
        case "int":
174
            return Integer.valueOf(getElementText(elem));
175
        case "null":
176
            nullDecoded(elem);
177
            return null;
178
        case "boolean":
179
            return Boolean.valueOf(getElementText(elem));
180
        case "byte":
181
            return Byte.valueOf(getElementText(elem));
182
        case "char":
183
            return Character.valueOf(getElementText(elem).charAt(0));
184
        case "short":
185
            return Short.valueOf(getElementText(elem));
186
        case "long":
187
            return Long.valueOf(getElementText(elem));
188
        case "float":
189
            return Float.valueOf(getElementText(elem));
190
        case "double":
191
            return Double.valueOf(getElementText(elem));
192
        case "array":
193
            final String classAttr = getAttributeValue(elem, "class");
194
            final String lengthAttr = getAttributeValue(elem, "length");
195
 
196
            final Class<?> componentClass = parseClassName(classAttr);
197
            if (lengthAttr != null) {
198
                context.push(Array.newInstance(componentClass, Integer.parseInt(lengthAttr)));
199
                final Children<S> children = createChildren(elem);
200
                S child;
201
                while ((child = children.getNextChild()) != null) {
202
                    eval(child, context, ids);
203
                }
204
                return context.pop();
205
            } else {
206
                final List<Object> items = new LinkedList<>();
207
                final Children<S> children = createChildren(elem);
208
                S child;
209
                while ((child = children.getNextChild()) != null) {
210
                    items.add(eval(child, context, ids));
211
                }
212
                final Object resArray = Array.newInstance(componentClass, items.size());
213
                int i = 0;
214
                for (final Object item : items)
215
                    Array.set(resArray, i++, item);
216
                return resArray;
217
            }
218
        case "class":
219
            return Class.forName(getElementText(elem));
220
        default:
221
            throw new UnsupportedOperationException("doesn't yet support " + n);
222
        }
223
    }
224
 
225
    private final Object evalContainer(final S parent, Stack<Object> context, final Map<String, Object> ids, final ExnTransformer<List<Object>, Object, ? extends Exception> transf)
226
            throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, E {
227
        final List<Object> args = new ArrayList<Object>();
228
        final Children<S> children = createChildren(parent);
229
        boolean noVoid = true;
230
        S child = null;
231
        while (noVoid && (child = children.getNextChild()) != null) {
232
            if (getLocalName(child).equals("void"))
233
                noVoid = false;
234
            else {
235
                args.add(eval(child, context, ids));
236
            }
237
        }
238
 
239
        // call the statement
240
        final Object res = transf.transformCheckedWithExn(args, false, InvocationTargetException.class, InstantiationException.class, IllegalAccessException.class);
241
 
242
        context.push(res);
243
 
244
        // now call the voids
245
        if (child != null) {
246
            do {
247
                eval(child, context, ids);
248
            } while ((child = children.getNextChild()) != null);
249
        }
250
        return context.pop();
251
    }
252
 
253
    private static final Object invoke(final Object target, String methodName, final List<Object> args) throws IllegalAccessException, InvocationTargetException {
254
        // <object class="Cell" method="createEmpty" >
255
        // for static methods the target is already a class
256
        final Class clazz = target instanceof Class ? (Class) target : target.getClass();
257
        final Method m = getMethod(clazz, methodName, args);
258
        return m.invoke(target, args.toArray());
259
    }
260
 
261
    private static final Method getMethod(Class<?> clazz, String name, List<Object> actualArgs) {
262
        final List<Class<?>> actualClasses = objectsToClasses(actualArgs);
263
        final List<Object> key = new ArrayList<Object>(3);
264
        key.add(clazz);
265
        key.add(name);
266
        key.add(actualClasses);
267
 
268
        final CacheResult<Method> cacheRes = cache.check(key);
269
        if (cacheRes.getState() == CacheResult.State.VALID)
270
            return cacheRes.getRes();
271
 
272
        final Method res = findMethod(clazz, name, actualClasses);
273
        if (res == null)
274
            throw new IllegalStateException("No matching method " + name + " found in " + clazz);
275
        cache.put(key, res);
276
        return res;
277
    }
278
 
279
    private static final Constructor getCtor(Class<?> clazz, List<Object> actualArgs) {
280
        final List<Class<?>> actualClasses = objectsToClasses(actualArgs);
281
        final List<Object> key = new ArrayList<Object>(3);
282
        key.add(clazz);
283
        key.add(actualClasses);
284
 
285
        final CacheResult<Constructor<?>> cacheRes = cacheCtor.check(key);
286
        if (cacheRes.getState() == CacheResult.State.VALID)
287
            return cacheRes.getRes();
288
 
289
        final Constructor res = findCtor(clazz, actualClasses);
180 ilm 290
        if (res == null)
291
            throw new IllegalStateException("No constructor in " + clazz + " for arguments " + actualClasses);
174 ilm 292
        cacheCtor.put(key, res);
293
        return res;
294
    }
295
 
296
    private static final List<Class<?>> objectsToClasses(List<Object> actualArgs) {
297
        final List<Class<?>> actualClasses = new ArrayList<Class<?>>(actualArgs.size());
298
        for (final Object actualArg : actualArgs)
299
            actualClasses.add(actualArg == null ? null : actualArg.getClass());
300
        return actualClasses;
301
    }
302
 
303
    // TODO return the most specific matching method instead of the first one
304
    // (handle both Sub/Superclass and primitive/object type)
305
    private static final Method findMethod(Class<?> clazz, String name, List<Class<?>> actualArgs) {
306
        for (final Method m : clazz.getMethods()) {
307
            if (m.getName().equals(name) && callableWith(m.getParameterTypes(), actualArgs)) {
308
                return m;
309
            }
310
        }
311
        return null;
312
    }
313
 
314
    // TODO see findMethod()
315
    private static final Constructor findCtor(Class<?> clazz, List<Class<?>> actualArgs) {
316
        for (final Constructor m : clazz.getConstructors()) {
317
            if (callableWith(m.getParameterTypes(), actualArgs)) {
318
                return m;
319
            }
320
        }
321
        return null;
322
    }
323
 
324
    private static final boolean callableWith(Class<?>[] formalArgs, List<Class<?>> actualArgs) {
325
        if (formalArgs.length != actualArgs.size())
326
            return false;
327
        int i = 0;
328
        for (final Class<?> argClass : formalArgs) {
329
            final Class<?> actualArg = actualArgs.get(i);
330
            // null match everything
331
            if (actualArg != null && !argClass.isAssignableFrom(actualArg) && argClass != getPrimitive(actualArg))
332
                return false;
333
            i++;
334
        }
335
 
336
        return true;
337
    }
338
 
339
    private static Class<?> getPrimitive(Class<?> argClass) {
340
        if (argClass == Boolean.class)
341
            return Boolean.TYPE;
342
        else if (argClass == Character.class)
343
            return Character.TYPE;
344
        else if (argClass == Byte.class)
345
            return Byte.TYPE;
346
        else if (argClass == Short.class)
347
            return Short.TYPE;
348
        else if (argClass == Integer.class)
349
            return Integer.TYPE;
350
        else if (argClass == Long.class)
351
            return Long.TYPE;
352
        else if (argClass == Float.class)
353
            return Float.TYPE;
354
        else if (argClass == Double.class)
355
            return Double.TYPE;
356
        else
357
            return null;
358
    }
359
 
360
    private static final Map<String, Class> primitiveNames = new HashMap<String, Class>();
361
 
362
    static {
363
        primitiveNames.put("boolean", boolean.class);
364
        primitiveNames.put("byte", byte.class);
365
        primitiveNames.put("char", char.class);
366
        primitiveNames.put("short", short.class);
367
        primitiveNames.put("int", int.class);
368
        primitiveNames.put("long", long.class);
369
        primitiveNames.put("float", float.class);
370
        primitiveNames.put("double", double.class);
371
    }
372
 
373
    /**
374
     * Parse class names (including primitive).
375
     *
376
     * @param className a class name, eg "java.lang.String" or "int".
377
     * @return the matching class, eg java.lang.String.class or Integer.TYPE.
378
     * @throws ClassNotFoundException if the passed name doesn't exist.
379
     */
380
    private static Class<?> parseClassName(String className) throws ClassNotFoundException {
381
        final Class<?> primitive = primitiveNames.get(className);
382
        if (primitive != null)
383
            return primitive;
384
        else
385
            return Class.forName(className);
386
    }
387
}