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;
33
34 import com.cedarsoft.AssertUtils;
35 import org.jdom.Document;
36 import org.jdom.Element;
37 import org.jdom.JDOMException;
38 import org.jdom.Namespace;
39 import org.jdom.input.SAXBuilder;
40 import org.jdom.output.Format;
41 import org.jdom.output.XMLOutputter;
42
43 import javax.annotation.Nonnull;
44 import java.io.ByteArrayInputStream;
45 import java.io.IOException;
46
47
48
49
50
51
52
53
54
55
56
57 public abstract class AbstractXmlSerializerTest2<T> extends AbstractSerializerTest2<T> {
58 protected void verify( @Nonnull byte[] current, @Nonnull byte[] exectedXml ) throws Exception {
59 if ( addNameSpace() ) {
60 String expectedWithNamespace = addNameSpace( ( AbstractXmlSerializer<?, ?, ?, ?> ) getSerializer(), exectedXml );
61 AssertUtils.assertXMLEquals( expectedWithNamespace, new String( current ) );
62 } else {
63 AssertUtils.assertXMLEquals( new String( exectedXml ), new String( current ) );
64 }
65 }
66
67 @Override
68 protected void verifySerialized( @Nonnull Entry<T> entry, @Nonnull byte[] serialized ) throws Exception {
69 verify( serialized, entry.getExpected() );
70 }
71
72 protected boolean addNameSpace() {
73 return true;
74 }
75
76
77 @Nonnull
78
79 public static String addNameSpace( @Nonnull AbstractXmlSerializer<?, ?, ?, ?> serializer, @Nonnull byte[] xmlBytes ) throws Exception {
80 return addNameSpace( serializer.createNameSpace( serializer.getFormatVersion() ), xmlBytes );
81 }
82
83 public static String addNameSpace( @Nonnull String nameSpaceUri, @Nonnull byte[] xml ) throws JDOMException, IOException {
84 Document doc = new SAXBuilder().build( new ByteArrayInputStream( xml ) );
85
86 Element root = doc.getRootElement();
87 if ( root.getNamespaceURI().length() == 0 ) {
88 Namespace namespace = Namespace.getNamespace( nameSpaceUri );
89
90 addNameSpaceRecursively( root, namespace );
91 }
92
93 return new XMLOutputter( Format.getPrettyFormat() ).outputString( doc );
94 }
95
96 public static void addNameSpaceRecursively( @Nonnull Element element, @Nonnull Namespace namespace ) {
97 element.setNamespace( namespace );
98 for ( Element child : ( ( Iterable<? extends Element> ) element.getChildren() ) ) {
99 addNameSpaceRecursively( child, namespace );
100 }
101 }
102
103 @Nonnull
104 protected static <T> Entry<? extends T> create( @Nonnull T object, @Nonnull String expected ) {
105 return new Entry<T>( object, expected.getBytes() );
106 }
107 }