OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

Rev Author Line No. Line
17 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 java.awt.Dimension;
17
import java.awt.Point;
18
import java.awt.Rectangle;
19
import java.beans.BeanInfo;
20
import java.beans.DefaultPersistenceDelegate;
21
import java.beans.Encoder;
22
import java.beans.ExceptionListener;
23
import java.beans.IntrospectionException;
24
import java.beans.Introspector;
25
import java.beans.PersistenceDelegate;
26
import java.beans.PropertyDescriptor;
27
import java.beans.XMLDecoder;
28
import java.beans.XMLEncoder;
29
import java.io.ByteArrayInputStream;
30
import java.io.ByteArrayOutputStream;
31
import java.io.IOException;
32
import java.lang.reflect.Array;
33
import java.lang.reflect.Method;
34
import java.nio.charset.Charset;
35
import java.util.Collection;
36
import java.util.HashMap;
37
import java.util.List;
38
import java.util.Map;
80 ilm 39
import java.util.Map.Entry;
17 ilm 40
import java.util.RandomAccess;
41
import java.util.Set;
42
 
83 ilm 43
import org.jdom2.Element;
44
import org.jdom2.JDOMException;
45
import org.jdom2.input.SAXBuilder;
17 ilm 46
 
47
/**
48
 * To encode and decode using {@link XMLEncoder} and {@link XMLDecoder}.
49
 *
50
 * @author Sylvain CUAZ
51
 */
52
public class XMLCodecUtils {
53
 
54
    private static final String END_DECL = "?>";
55
 
56
    // the same as XMLEncoder
57
    private static final Charset CS = Charset.forName("UTF-8");
58
 
59
    // just to get to java.beans.MetaData :
60
    // Encoder.setPersistenceDelegate() actually add its arguments to a static object,
61
    // which is used by all instances of Encoder.
62
    private static final Encoder bogus = new Encoder();
63
    private static PersistenceDelegate defaultPersistenceDelegate = new DefaultPersistenceDelegate();
64
    private static final Map<Class, PersistenceDelegate> persDelegates = new HashMap<Class, PersistenceDelegate>();
65
 
80 ilm 66
    /**
67
     * Just throws an {@link IllegalStateException}.
68
     */
69
    public static final ExceptionListener EXCEPTION_LISTENER = new ExceptionListener() {
17 ilm 70
        @Override
71
        public void exceptionThrown(Exception e) {
72
            throw new IllegalStateException(e);
73
        }
74
    };
75
 
174 ilm 76
    public static final XMLDecoderJDOM XML_DECODER_JDOM = new XMLDecoderJDOM();
77
    public static final XMLDecoderStAX XML_DECODER_STAX = new XMLDecoderStAX();
78
 
17 ilm 79
    /**
80
     * Register a {@link PersistenceDelegate} for the passed class. This method tries to set
81
     * <code>del</code> as the default for any subsequent {@link Encoder}, but with the current JRE
82
     * this cannot be guaranteed.
83
     *
84
     * @param c a {@link Class}.
85
     * @param del the delegate to use.
86
     */
87
    public synchronized static void register(Class c, PersistenceDelegate del) {
88
        persDelegates.put(c, del);
89
        bogus.setPersistenceDelegate(c, del);
90
    }
91
 
92
    public synchronized static void unregister(Class c) {
93
        persDelegates.remove(c);
94
        // cannot put null, the implementation uses a Hashtable
95
        bogus.setPersistenceDelegate(c, defaultPersistenceDelegate);
96
    }
97
 
98
    private static final byte[] encode2Bytes(Object o) {
99
        // converting the encoder to a field, only improves execution time by 10%
100
        // but the xml is no longer enclosed by <java> and the encoder is never closed
101
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
102
        final XMLEncoder enc = new XMLEncoder(out);
103
        synchronized (XMLCodecUtils.class) {
104
            for (final Entry<Class, PersistenceDelegate> e : persDelegates.entrySet()) {
105
                enc.setPersistenceDelegate(e.getKey(), e.getValue());
106
            }
107
        }
108
        // we want to know if some objects are discarded
109
        enc.setExceptionListener(EXCEPTION_LISTENER);
110
        // ATTN this only prints exception name (no stacktrace) and continue
111
        // MAYBE use enc.setExceptionListener();
112
        enc.writeObject(o);
113
        enc.close();
114
        final byte[] res = out.toByteArray();
115
        try {
116
            out.close();
117
        } catch (IOException exn) {
118
            // shouldn't happen on a ByteArrayOutputStream
119
            throw new IllegalStateException(exn);
120
        }
121
        return res;
122
    }
123
 
174 ilm 124
    public static final String encodeAsArray(final Map<?, ?> m) {
125
        return encodeAsArray(m, new StringBuilder(1024)).toString();
126
    }
127
 
17 ilm 128
    /**
174 ilm 129
     * Encode a map as an array. Useful since parsing an array is faster than parsing a map.
130
     *
131
     * @param m the map to encode.
132
     * @param sb where to encode.
133
     * @return <code>sb</code>.
134
     * @see AbstractXMLDecoder#decodeFromArray(Object, Class, Class)
135
     */
136
    public static final StringBuilder encodeAsArray(final Map<?, ?> m, final StringBuilder sb) {
137
        final Object[] array = new Object[m.size() * 2];
138
        int i = 0;
139
        for (final Entry<?, ?> e : m.entrySet()) {
140
            array[i++] = e.getKey();
141
            array[i++] = e.getValue();
142
        }
143
        assert i == array.length;
144
        return encodeSimple(array, sb);
145
    }
146
 
147
    public static final <K, V> Map<K, V> decodeFromArray(final Object[] array, final Class<K> keyClass, final Class<V> valueClass) {
148
        return decodeFromArray(array, keyClass, valueClass, null);
149
    }
150
 
151
    public static final <K, V> Map<K, V> decodeFromArray(final Object[] array, final Class<K> keyClass, final Class<V> valueClass, Map<K, V> m) {
152
        final int l = array.length;
153
        if (m == null)
154
            m = new HashMap<K, V>((int) (l / 2 / 0.8f) + 1, 0.8f);
155
        for (int i = 0; i < l; i += 2) {
156
            final K key = keyClass.cast(array[i]);
157
            final V value = valueClass.cast(array[i + 1]);
158
            m.put(key, value);
159
        }
160
        return m;
161
    }
162
 
163
    /**
17 ilm 164
     * Encodes an object using {@link XMLEncoder}, stripping the XML declaration.
165
     *
166
     * @param o the object to encode.
167
     * @return the xml string suitable to pass to {{@link #decode1(String)}.
168
     */
169
    public static final String encode(Object o) {
170
        final String res = new String(encode2Bytes(o), CS);
171
        // see XMLEncoder#flush(), it adds an xml declaration
172
        final int decl = res.indexOf(END_DECL);
173
        return res.substring(decl + END_DECL.length());
174
    }
175
 
176
    /**
177
     * Encodes an object using the same format as {@link XMLEncoder}. This method can be up until 70
178
     * times faster than XMLEncoder but doesn't handle cycles.
179
     *
180
     * @param o the object to encode.
181
     * @return the xml without the XML declaration.
182
     * @see #encode(Object)
183
     */
184
    public static final String encodeSimple(Object o) {
185
        final StringBuilder sb = new StringBuilder(256);
174 ilm 186
        return encodeSimple(o, sb).toString();
187
    }
188
 
189
    public static final StringBuilder encodeSimple(final Object o, final StringBuilder sb) {
17 ilm 190
        sb.append("<java version=\"1.6.0\" class=\"java.beans.XMLDecoder\">");
191
        encodeSimpleRec(o, sb);
192
        sb.append("</java>");
174 ilm 193
        return sb;
17 ilm 194
    }
195
 
196
    private static final void createElemEscaped(final String elemName, final Object o, final StringBuilder sb) {
142 ilm 197
        createElem(elemName, JDOM2Utils.OUTPUTTER.escapeElementEntities(o.toString()), sb);
17 ilm 198
    }
199
 
200
    private static final void createElem(final String elemName, final Object o, final StringBuilder sb) {
201
        assert o != null;
202
        sb.append('<');
203
        sb.append(elemName);
204
        sb.append('>');
205
        sb.append(o.toString());
206
        sb.append("</");
207
        sb.append(elemName);
208
        sb.append('>');
209
    }
210
 
211
    // TODO support cycles, perhaps by using an IdentityMap<Object, Element> since we need to add an
212
    // id attribute afterwards (only when we know that the object is encountered more than once)
213
    private static final void encodeSimpleRec(final Object o, final StringBuilder sb) {
214
        if (o == null) {
215
            sb.append("<null/>");
216
            return;
217
        }
218
 
219
        final Class<?> c = o.getClass();
220
        if (c == Boolean.class) {
221
            createElem("boolean", o, sb);
222
        } else if (c == String.class) {
223
            createElemEscaped("string", o, sb);
224
        } else if (c == Character.class) {
225
            createElemEscaped("char", o, sb);
226
        } else if (c == Integer.class) {
227
            createElem("int", o, sb);
228
        } else if (c == Long.class) {
229
            createElem("long", o, sb);
230
        } else if (c == Float.class) {
231
            createElem("float", o, sb);
232
        } else if (c == Double.class) {
233
            createElem("double", o, sb);
234
        } else if (c == Class.class) {
235
            createElem("class", ((Class) o).getName(), sb);
236
        } else if (c == Short.class) {
237
            createElem("short", o, sb);
238
        } else if (c == Byte.class) {
239
            createElem("byte", o, sb);
240
        } else if (o instanceof Enum) {
241
            sb.append("<object class=\"");
242
            sb.append(c.getName());
243
            sb.append("\" method=\"valueOf\"><string>");
244
            sb.append(((Enum) o).name());
245
            sb.append("</string></object>");
246
        } else if (c.isArray()) {
247
            sb.append("<array class=\"");
248
            sb.append(c.getComponentType().getName());
249
            sb.append("\">");
250
 
251
            final int stop = Array.getLength(o);
252
            for (int j = 0; j < stop; j++) {
253
                encodeSimpleRec(Array.get(o, j), sb);
254
            }
255
 
256
            sb.append("</array>");
257
        } else
258
        // see java.beans.*_PersistenceDelegate
259
        if (o instanceof Map) {
260
            sb.append("<object class=\"");
261
            // TODO handle like java_util_Collections
262
            if (c.getName().startsWith("java.util.Collections$"))
263
                sb.append("java.util.HashMap");
264
            else
265
                sb.append(c.getName());
266
            sb.append("\">");
267
 
268
            final Map<?, ?> m = (Map<?, ?>) o;
269
            for (final Entry<?, ?> e : m.entrySet()) {
270
                sb.append("<void method=\"put\" >");
271
                encodeSimpleRec(e.getKey(), sb);
272
                encodeSimpleRec(e.getValue(), sb);
273
                sb.append("</void>");
274
            }
275
 
276
            sb.append("</object>");
277
        } else if (o instanceof Collection) {
278
            sb.append("<object class=\"");
279
            // TODO handle like java_util_Collections
280
            if (c.getName().startsWith("java.util.Arrays$")) {
281
                sb.append("java.util.ArrayList");
282
            } else if (c.getName().startsWith("java.util.Collections$")) {
283
                if (o instanceof Set)
284
                    sb.append("java.util.HashSet");
285
                else
286
                    sb.append("java.util.ArrayList");
287
            } else {
288
                sb.append(c.getName());
289
            }
290
            sb.append("\">");
291
 
292
            if (o instanceof RandomAccess && o instanceof List) {
293
                final List<?> list = (List<?>) o;
294
                final int stop = list.size();
295
                for (int i = 0; i < stop; i++) {
296
                    sb.append("<void method=\"add\" >");
297
                    encodeSimpleRec(list.get(i), sb);
298
                    sb.append("</void>");
299
                }
300
            } else {
301
                for (final Object item : (Collection<?>) o) {
302
                    sb.append("<void method=\"add\" >");
303
                    encodeSimpleRec(item, sb);
304
                    sb.append("</void>");
305
                }
306
            }
307
 
308
            sb.append("</object>");
309
        } else if (o instanceof Point) {
310
            final Point p = (Point) o;
311
            sb.append("<object class=\"java.awt.Point\">");
312
            encodeSimpleRec(p.x, sb);
313
            encodeSimpleRec(p.y, sb);
314
            sb.append("</object>");
315
        } else if (o instanceof Dimension) {
316
            final Dimension p = (Dimension) o;
317
            sb.append("<object class=\"java.awt.Dimension\">");
318
            encodeSimpleRec(p.width, sb);
319
            encodeSimpleRec(p.height, sb);
320
            sb.append("</object>");
321
        } else if (o instanceof Rectangle) {
322
            final Rectangle p = (Rectangle) o;
323
            sb.append("<object class=\"java.awt.Rectangle\">");
324
            encodeSimpleRec(p.x, sb);
325
            encodeSimpleRec(p.y, sb);
326
            encodeSimpleRec(p.width, sb);
327
            encodeSimpleRec(p.height, sb);
328
            sb.append("</object>");
329
        } else {
330
            final BeanInfo info;
331
            try {
332
                info = Introspector.getBeanInfo(c);
333
            } catch (IntrospectionException e) {
334
                throw new IllegalStateException("Couldn't inspect " + o, e);
335
            }
336
 
337
            sb.append("<object class=\"");
338
            sb.append(c.getName());
339
            sb.append("\">");
340
 
341
            // Properties
342
            for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
343
                final Method getter = pd.getReadMethod();
344
                final Method setter = pd.getWriteMethod();
345
 
346
                if (getter != null && setter != null && pd.getValue("transient") != Boolean.TRUE) {
347
                    try {
348
                        sb.append("<void method=\"" + setter.getName() + "\">");
349
                        encodeSimpleRec(getter.invoke(o, new Object[0]), sb);
350
                        sb.append("</void>");
351
                    } catch (Exception e) {
352
                        throw new RuntimeException("Couldn't get the value of the '" + pd.getDisplayName() + "' property for " + o, e);
353
                    }
354
                }
355
            }
356
 
357
            sb.append("</object>");
358
        }
359
    }
360
 
361
    /**
362
     * Encodes an object using {@link XMLEncoder} returning the root element.
363
     *
364
     * @param o the object to encode.
365
     * @return the "java" element suitable to pass to {{@link #decode1(Element)}.
366
     */
367
    public static final Element encodeToJDOM(Object o) {
368
        final SAXBuilder builder = new SAXBuilder();
369
        try {
370
            return (Element) builder.build(new ByteArrayInputStream(encode2Bytes(o))).getRootElement().detach();
371
        } catch (JDOMException e) {
372
            // shouldn't happen since the JRE is supposed to generate valid XML
373
            throw new IllegalStateException(e);
374
        } catch (IOException e) {
375
            // shouldn't happen since we're using byte[] streams
376
            throw new IllegalStateException(e);
377
        }
378
    }
379
 
380
    public static final Object decode1(String s) {
381
        final ByteArrayInputStream ins = new ByteArrayInputStream(s.getBytes(CS));
382
        final XMLDecoder dec = new XMLDecoder(ins);
383
        dec.setExceptionListener(EXCEPTION_LISTENER);
384
        final Object res = dec.readObject();
385
        dec.close();
386
        return res;
387
    }
388
 
389
    /**
390
     * Tries to decode an xml element parsed from a string obtained from XMLEncoder. This doesn't
391
     * use {@link XMLDecoder} as it requires outputting it first to string which is inefficient.
392
     * NOTE: this decoder supports only a subset of XMLDecoder.
393
     *
394
     * @param javaElem a "java" element.
395
     * @return the decoded object.
396
     */
397
    public static final Object decode1(Element javaElem) {
174 ilm 398
        return XML_DECODER_JDOM.decode1(javaElem);
17 ilm 399
    }
400
 
401
    private XMLCodecUtils() {
402
    }
403
}