1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 package com.cedarsoft.serialization.jdom;
33
34 import com.cedarsoft.Version;
35 import com.cedarsoft.VersionException;
36 import com.cedarsoft.VersionRange;
37 import com.cedarsoft.serialization.AbstractXmlSerializer;
38 import org.jdom.Document;
39 import org.jdom.Element;
40 import org.jdom.JDOMException;
41 import org.jdom.Namespace;
42 import org.jdom.input.SAXBuilder;
43 import org.jdom.output.Format;
44 import org.jdom.output.XMLOutputter;
45 import org.jetbrains.annotations.NonNls;
46 import org.jetbrains.annotations.NotNull;
47
48 import java.io.IOException;
49 import java.io.InputStream;
50 import java.io.OutputStream;
51
52
53
54
55
56
57 public abstract class AbstractJDomSerializer<T> extends AbstractXmlSerializer<T, Element, Element, IOException> {
58 @NotNull
59 @NonNls
60 protected static final String LINE_SEPARATOR = "\n";
61
62 protected AbstractJDomSerializer( @NotNull @NonNls String defaultElementName, @NonNls @NotNull String nameSpaceUriBase, @NotNull VersionRange formatVersionRange ) {
63 super( defaultElementName, nameSpaceUriBase, formatVersionRange );
64 }
65
66 @NotNull
67 public Element serializeToElement( @NotNull T object ) throws IOException {
68 Element element = new Element( getDefaultElementName() );
69 serialize( element, object );
70 return element;
71 }
72
73 @Override
74 public void serialize( @NotNull T object, @NotNull OutputStream out ) throws IOException {
75 Document document = new Document();
76
77
78 Namespace namespace = Namespace.getNamespace( getNameSpaceUri() );
79
80
81 Element root = new Element( getDefaultElementName(), namespace );
82 document.setRootElement( root );
83
84 serialize( root, object );
85 new XMLOutputter( Format.getPrettyFormat().setLineSeparator( LINE_SEPARATOR ) ).output( document, out );
86 }
87
88 @Override
89 @NotNull
90 public T deserialize( @NotNull InputStream in ) throws IOException, VersionException {
91 try {
92 Document document = new SAXBuilder().build( in );
93
94 String namespaceURI = document.getRootElement().getNamespaceURI();
95 Version formatVersion = parseVersionFromNamespaceUri( namespaceURI );
96
97 Version.verifyMatch( getFormatVersion(), formatVersion );
98
99 return deserialize( document.getRootElement(), formatVersion );
100 } catch ( JDOMException e ) {
101 throw new IOException( "Could not parse stream due to " + e.getMessage(), e );
102 }
103 }
104 }