OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
 * 
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each file.
 */
 
 package org.openconcerto.xml;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.beans.BeanInfo;
import java.beans.DefaultPersistenceDelegate;
import java.beans.Encoder;
import java.beans.ExceptionListener;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PersistenceDelegate;
import java.beans.PropertyDescriptor;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.RandomAccess;
import java.util.Set;

import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

/**
 * To encode and decode using {@link XMLEncoder} and {@link XMLDecoder}.
 * 
 * @author Sylvain CUAZ
 */
public class XMLCodecUtils {

    private static final String END_DECL = "?>";

    // the same as XMLEncoder
    private static final Charset CS = Charset.forName("UTF-8");

    // just to get to java.beans.MetaData :
    // Encoder.setPersistenceDelegate() actually add its arguments to a static object,
    // which is used by all instances of Encoder.
    private static final Encoder bogus = new Encoder();
    private static PersistenceDelegate defaultPersistenceDelegate = new DefaultPersistenceDelegate();
    private static final Map<Class, PersistenceDelegate> persDelegates = new HashMap<Class, PersistenceDelegate>();

    /**
     * Just throws an {@link IllegalStateException}.
     */
    public static final ExceptionListener EXCEPTION_LISTENER = new ExceptionListener() {
        @Override
        public void exceptionThrown(Exception e) {
            throw new IllegalStateException(e);
        }
    };

    public static final XMLDecoderJDOM XML_DECODER_JDOM = new XMLDecoderJDOM();
    public static final XMLDecoderStAX XML_DECODER_STAX = new XMLDecoderStAX();

    /**
     * Register a {@link PersistenceDelegate} for the passed class. This method tries to set
     * <code>del</code> as the default for any subsequent {@link Encoder}, but with the current JRE
     * this cannot be guaranteed.
     * 
     * @param c a {@link Class}.
     * @param del the delegate to use.
     */
    public synchronized static void register(Class c, PersistenceDelegate del) {
        persDelegates.put(c, del);
        bogus.setPersistenceDelegate(c, del);
    }

    public synchronized static void unregister(Class c) {
        persDelegates.remove(c);
        // cannot put null, the implementation uses a Hashtable
        bogus.setPersistenceDelegate(c, defaultPersistenceDelegate);
    }

    private static final byte[] encode2Bytes(Object o) {
        // converting the encoder to a field, only improves execution time by 10%
        // but the xml is no longer enclosed by <java> and the encoder is never closed
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final XMLEncoder enc = new XMLEncoder(out);
        synchronized (XMLCodecUtils.class) {
            for (final Entry<Class, PersistenceDelegate> e : persDelegates.entrySet()) {
                enc.setPersistenceDelegate(e.getKey(), e.getValue());
            }
        }
        // we want to know if some objects are discarded
        enc.setExceptionListener(EXCEPTION_LISTENER);
        // ATTN this only prints exception name (no stacktrace) and continue
        // MAYBE use enc.setExceptionListener();
        enc.writeObject(o);
        enc.close();
        final byte[] res = out.toByteArray();
        try {
            out.close();
        } catch (IOException exn) {
            // shouldn't happen on a ByteArrayOutputStream
            throw new IllegalStateException(exn);
        }
        return res;
    }

    public static final String encodeAsArray(final Map<?, ?> m) {
        return encodeAsArray(m, new StringBuilder(1024)).toString();
    }

    /**
     * Encode a map as an array. Useful since parsing an array is faster than parsing a map.
     * 
     * @param m the map to encode.
     * @param sb where to encode.
     * @return <code>sb</code>.
     * @see AbstractXMLDecoder#decodeFromArray(Object, Class, Class)
     */
    public static final StringBuilder encodeAsArray(final Map<?, ?> m, final StringBuilder sb) {
        final Object[] array = new Object[m.size() * 2];
        int i = 0;
        for (final Entry<?, ?> e : m.entrySet()) {
            array[i++] = e.getKey();
            array[i++] = e.getValue();
        }
        assert i == array.length;
        return encodeSimple(array, sb);
    }

    public static final <K, V> Map<K, V> decodeFromArray(final Object[] array, final Class<K> keyClass, final Class<V> valueClass) {
        return decodeFromArray(array, keyClass, valueClass, null);
    }

    public static final <K, V> Map<K, V> decodeFromArray(final Object[] array, final Class<K> keyClass, final Class<V> valueClass, Map<K, V> m) {
        final int l = array.length;
        if (m == null)
            m = new HashMap<K, V>((int) (l / 2 / 0.8f) + 1, 0.8f);
        for (int i = 0; i < l; i += 2) {
            final K key = keyClass.cast(array[i]);
            final V value = valueClass.cast(array[i + 1]);
            m.put(key, value);
        }
        return m;
    }

    /**
     * Encodes an object using {@link XMLEncoder}, stripping the XML declaration.
     * 
     * @param o the object to encode.
     * @return the xml string suitable to pass to {{@link #decode1(String)}.
     */
    public static final String encode(Object o) {
        final String res = new String(encode2Bytes(o), CS);
        // see XMLEncoder#flush(), it adds an xml declaration
        final int decl = res.indexOf(END_DECL);
        return res.substring(decl + END_DECL.length());
    }

    /**
     * Encodes an object using the same format as {@link XMLEncoder}. This method can be up until 70
     * times faster than XMLEncoder but doesn't handle cycles.
     * 
     * @param o the object to encode.
     * @return the xml without the XML declaration.
     * @see #encode(Object)
     */
    public static final String encodeSimple(Object o) {
        final StringBuilder sb = new StringBuilder(256);
        return encodeSimple(o, sb).toString();
    }

    public static final StringBuilder encodeSimple(final Object o, final StringBuilder sb) {
        sb.append("<java version=\"1.6.0\" class=\"java.beans.XMLDecoder\">");
        encodeSimpleRec(o, sb);
        sb.append("</java>");
        return sb;
    }

    private static final void createElemEscaped(final String elemName, final Object o, final StringBuilder sb) {
        createElem(elemName, JDOM2Utils.OUTPUTTER.escapeElementEntities(o.toString()), sb);
    }

    private static final void createElem(final String elemName, final Object o, final StringBuilder sb) {
        assert o != null;
        sb.append('<');
        sb.append(elemName);
        sb.append('>');
        sb.append(o.toString());
        sb.append("</");
        sb.append(elemName);
        sb.append('>');
    }

    // TODO support cycles, perhaps by using an IdentityMap<Object, Element> since we need to add an
    // id attribute afterwards (only when we know that the object is encountered more than once)
    private static final void encodeSimpleRec(final Object o, final StringBuilder sb) {
        if (o == null) {
            sb.append("<null/>");
            return;
        }

        final Class<?> c = o.getClass();
        if (c == Boolean.class) {
            createElem("boolean", o, sb);
        } else if (c == String.class) {
            createElemEscaped("string", o, sb);
        } else if (c == Character.class) {
            createElemEscaped("char", o, sb);
        } else if (c == Integer.class) {
            createElem("int", o, sb);
        } else if (c == Long.class) {
            createElem("long", o, sb);
        } else if (c == Float.class) {
            createElem("float", o, sb);
        } else if (c == Double.class) {
            createElem("double", o, sb);
        } else if (c == Class.class) {
            createElem("class", ((Class) o).getName(), sb);
        } else if (c == Short.class) {
            createElem("short", o, sb);
        } else if (c == Byte.class) {
            createElem("byte", o, sb);
        } else if (o instanceof Enum) {
            sb.append("<object class=\"");
            sb.append(c.getName());
            sb.append("\" method=\"valueOf\"><string>");
            sb.append(((Enum) o).name());
            sb.append("</string></object>");
        } else if (c.isArray()) {
            sb.append("<array class=\"");
            sb.append(c.getComponentType().getName());
            sb.append("\">");

            final int stop = Array.getLength(o);
            for (int j = 0; j < stop; j++) {
                encodeSimpleRec(Array.get(o, j), sb);
            }

            sb.append("</array>");
        } else
        // see java.beans.*_PersistenceDelegate
        if (o instanceof Map) {
            sb.append("<object class=\"");
            // TODO handle like java_util_Collections
            if (c.getName().startsWith("java.util.Collections$"))
                sb.append("java.util.HashMap");
            else
                sb.append(c.getName());
            sb.append("\">");

            final Map<?, ?> m = (Map<?, ?>) o;
            for (final Entry<?, ?> e : m.entrySet()) {
                sb.append("<void method=\"put\" >");
                encodeSimpleRec(e.getKey(), sb);
                encodeSimpleRec(e.getValue(), sb);
                sb.append("</void>");
            }

            sb.append("</object>");
        } else if (o instanceof Collection) {
            sb.append("<object class=\"");
            // TODO handle like java_util_Collections
            if (c.getName().startsWith("java.util.Arrays$")) {
                sb.append("java.util.ArrayList");
            } else if (c.getName().startsWith("java.util.Collections$")) {
                if (o instanceof Set)
                    sb.append("java.util.HashSet");
                else
                    sb.append("java.util.ArrayList");
            } else {
                sb.append(c.getName());
            }
            sb.append("\">");

            if (o instanceof RandomAccess && o instanceof List) {
                final List<?> list = (List<?>) o;
                final int stop = list.size();
                for (int i = 0; i < stop; i++) {
                    sb.append("<void method=\"add\" >");
                    encodeSimpleRec(list.get(i), sb);
                    sb.append("</void>");
                }
            } else {
                for (final Object item : (Collection<?>) o) {
                    sb.append("<void method=\"add\" >");
                    encodeSimpleRec(item, sb);
                    sb.append("</void>");
                }
            }

            sb.append("</object>");
        } else if (o instanceof Point) {
            final Point p = (Point) o;
            sb.append("<object class=\"java.awt.Point\">");
            encodeSimpleRec(p.x, sb);
            encodeSimpleRec(p.y, sb);
            sb.append("</object>");
        } else if (o instanceof Dimension) {
            final Dimension p = (Dimension) o;
            sb.append("<object class=\"java.awt.Dimension\">");
            encodeSimpleRec(p.width, sb);
            encodeSimpleRec(p.height, sb);
            sb.append("</object>");
        } else if (o instanceof Rectangle) {
            final Rectangle p = (Rectangle) o;
            sb.append("<object class=\"java.awt.Rectangle\">");
            encodeSimpleRec(p.x, sb);
            encodeSimpleRec(p.y, sb);
            encodeSimpleRec(p.width, sb);
            encodeSimpleRec(p.height, sb);
            sb.append("</object>");
        } else {
            final BeanInfo info;
            try {
                info = Introspector.getBeanInfo(c);
            } catch (IntrospectionException e) {
                throw new IllegalStateException("Couldn't inspect " + o, e);
            }

            sb.append("<object class=\"");
            sb.append(c.getName());
            sb.append("\">");

            // Properties
            for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
                final Method getter = pd.getReadMethod();
                final Method setter = pd.getWriteMethod();

                if (getter != null && setter != null && pd.getValue("transient") != Boolean.TRUE) {
                    try {
                        sb.append("<void method=\"" + setter.getName() + "\">");
                        encodeSimpleRec(getter.invoke(o, new Object[0]), sb);
                        sb.append("</void>");
                    } catch (Exception e) {
                        throw new RuntimeException("Couldn't get the value of the '" + pd.getDisplayName() + "' property for " + o, e);
                    }
                }
            }

            sb.append("</object>");
        }
    }

    /**
     * Encodes an object using {@link XMLEncoder} returning the root element.
     * 
     * @param o the object to encode.
     * @return the "java" element suitable to pass to {{@link #decode1(Element)}.
     */
    public static final Element encodeToJDOM(Object o) {
        final SAXBuilder builder = new SAXBuilder();
        try {
            return (Element) builder.build(new ByteArrayInputStream(encode2Bytes(o))).getRootElement().detach();
        } catch (JDOMException e) {
            // shouldn't happen since the JRE is supposed to generate valid XML
            throw new IllegalStateException(e);
        } catch (IOException e) {
            // shouldn't happen since we're using byte[] streams
            throw new IllegalStateException(e);
        }
    }

    public static final Object decode1(String s) {
        final ByteArrayInputStream ins = new ByteArrayInputStream(s.getBytes(CS));
        final XMLDecoder dec = new XMLDecoder(ins);
        dec.setExceptionListener(EXCEPTION_LISTENER);
        final Object res = dec.readObject();
        dec.close();
        return res;
    }

    /**
     * Tries to decode an xml element parsed from a string obtained from XMLEncoder. This doesn't
     * use {@link XMLDecoder} as it requires outputting it first to string which is inefficient.
     * NOTE: this decoder supports only a subset of XMLDecoder.
     * 
     * @param javaElem a "java" element.
     * @return the decoded object.
     */
    public static final Object decode1(Element javaElem) {
        return XML_DECODER_JDOM.decode1(javaElem);
    }

    private XMLCodecUtils() {
    }
}