View Javadoc

1   /**
2    * Copyright (C) cedarsoft GmbH.
3    *
4    * Licensed under the GNU General Public License version 3 (the "License")
5    * with Classpath Exception; you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at
7    *
8    *         http://www.cedarsoft.org/gpl3ce
9    *         (GPL 3 with Classpath Exception)
10   *
11   * This code is free software; you can redistribute it and/or modify it
12   * under the terms of the GNU General Public License version 3 only, as
13   * published by the Free Software Foundation. cedarsoft GmbH designates this
14   * particular file as subject to the "Classpath" exception as provided
15   * by cedarsoft GmbH in the LICENSE file that accompanied this code.
16   *
17   * This code is distributed in the hope that it will be useful, but WITHOUT
18   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19   * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
20   * version 3 for more details (a copy is included in the LICENSE file that
21   * accompanied this code).
22   *
23   * You should have received a copy of the GNU General Public License version
24   * 3 along with this work; if not, write to the Free Software Foundation,
25   * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26   *
27   * Please contact cedarsoft GmbH, 72810 Gomaringen, Germany,
28   * or visit www.cedarsoft.com if you need additional information or
29   * have any questions.
30   */
31  
32  package com.cedarsoft.serialization.stax;
33  
34  import com.cedarsoft.version.Version;
35  import com.cedarsoft.version.VersionRange;
36  import com.cedarsoft.serialization.AbstractXmlSerializer;
37  
38  import javax.annotation.Nonnull;
39  import javax.annotation.Nullable;
40  import javax.xml.stream.XMLOutputFactory;
41  import javax.xml.stream.XMLStreamException;
42  import javax.xml.stream.XMLStreamReader;
43  import javax.xml.stream.XMLStreamWriter;
44  import java.io.IOException;
45  import java.io.OutputStream;
46  import java.lang.reflect.Constructor;
47  
48  /**
49   * Abstract base class for serializer using stax.
50   *
51   * @param <T> the type
52   */
53  public abstract class AbstractStaxSerializer<T> extends AbstractStaxBasedSerializer<T, XMLStreamWriter> {
54    /**
55     * Creates a new serializer
56     *
57     * @param defaultElementName the default element name
58     * @param nameSpaceUriBase   the name space uri base
59     * @param formatVersionRange the format version range
60     */
61    protected AbstractStaxSerializer( @Nonnull String defaultElementName, @Nonnull String nameSpaceUriBase, @Nonnull VersionRange formatVersionRange ) {
62      super( defaultElementName, nameSpaceUriBase, formatVersionRange );
63    }
64  
65    @Override
66    public void serialize( @Nonnull T object, @Nonnull OutputStream out ) throws IOException {
67      try {
68        XMLOutputFactory xmlOutputFactory = StaxSupport.getXmlOutputFactory();
69        XMLStreamWriter writer = wrapWithIndent(xmlOutputFactory.createXMLStreamWriter(out));
70  
71        //Sets the name space
72        String nameSpace = getNameSpace();
73        writer.setDefaultNamespace( nameSpace );
74  
75        writer.writeStartElement( getDefaultElementName() );
76        writer.writeDefaultNamespace( nameSpace );
77  
78        serialize( writer, object, getFormatVersion() );
79        writer.writeEndElement();
80  
81        writer.close();
82      } catch ( XMLStreamException e ) {
83        throw new IOException( e );
84      }
85    }
86  
87    @Nullable
88    private static final Constructor<?> INDENTING_WRITER_CONSTRUCTOR = getIndentingConstructor();
89  
90    @Nullable
91    private static Constructor<?> getIndentingConstructor() {
92      try {
93        Class<?> indentingType = Class.forName("com.sun.xml.internal.txw2.output.IndentingXMLStreamWriter");
94        return indentingType.getConstructor(XMLStreamWriter.class);
95      } catch (Exception ignore) {
96        return null;
97      }
98    }
99  
100   @Nonnull
101   protected static XMLStreamWriter wrapWithIndent(@Nonnull XMLStreamWriter xmlStreamWriter) {
102     if (INDENTING_WRITER_CONSTRUCTOR == null) {
103       return xmlStreamWriter;
104     }
105 
106     try {
107       return (XMLStreamWriter) INDENTING_WRITER_CONSTRUCTOR.newInstance(xmlStreamWriter);
108     } catch (Exception ignore) {
109       //We could not instantiate the writer
110       return xmlStreamWriter;
111     }
112   }
113 
114   /**
115    * Serializes the elements of a collection
116    *
117    * @param objects       the objects that are serialized
118    * @param type          the type
119    * @param elementName   the element name
120    * @param serializeTo   the object the elements are serialized to
121    * @param formatVersion the format version
122    * @throws XMLStreamException if there is an xml problem
123    * @throws IOException if there is an io problem
124    */
125   protected <T> void serializeCollection( @Nonnull Iterable<? extends T> objects, @Nonnull Class<T> type, @Nonnull String elementName, @Nonnull XMLStreamWriter serializeTo, @Nonnull Version formatVersion ) throws XMLStreamException, IOException {
126     AbstractXmlSerializer<? super T, XMLStreamWriter, XMLStreamReader, XMLStreamException> serializer = getSerializer( type );
127     Version resolvedVersion = getDelegatesMappings().resolveVersion( type, formatVersion );
128 
129     for ( T object : objects ) {
130       serializeTo.writeStartElement( elementName );
131       serializer.serialize( serializeTo, object, resolvedVersion );
132       serializeTo.writeEndElement();
133     }
134   }
135 
136   protected <T> void serializeCollection( @Nonnull Iterable<? extends T> objects, @Nonnull Class<T> type, @Nonnull XMLStreamWriter serializeTo, @Nonnull Version formatVersion ) throws XMLStreamException, IOException {
137     AbstractXmlSerializer<? super T, XMLStreamWriter, XMLStreamReader, XMLStreamException> serializer = getSerializer( type );
138     Version resolvedVersion = getDelegatesMappings().resolveVersion( type, formatVersion );
139 
140     for ( T object : objects ) {
141       serializeTo.writeStartElement( serializer.getDefaultElementName() );
142       serializer.serialize( serializeTo, object, resolvedVersion );
143       serializeTo.writeEndElement();
144     }
145   }
146 }