1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.rice.core.test;
17
18 import org.apache.commons.lang.StringUtils;
19
20 import static org.junit.Assert.assertEquals;
21
22 import java.io.BufferedReader;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.InputStreamReader;
26 import java.io.StringReader;
27 import java.io.StringWriter;
28
29 import javax.xml.bind.JAXBContext;
30 import javax.xml.bind.Marshaller;
31 import javax.xml.bind.Unmarshaller;
32
33
34
35
36
37
38 public final class JAXBAssert {
39
40 private JAXBAssert() {}
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58 public static void assertEqualXmlMarshalUnmarshal(Object objectToMarshal, String expectedXml, Class<?> ... classesToBeBound) {
59 String marshaledXml = null;
60 try {
61 JAXBContext jaxbContext = JAXBContext.newInstance(classesToBeBound);
62 Marshaller marshaller = jaxbContext.createMarshaller();
63
64 StringWriter stringWriter = new StringWriter();
65
66 marshaller.marshal(objectToMarshal, stringWriter);
67
68 marshaledXml = stringWriter.toString();
69
70 Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
71
72 Object actual = unmarshaller.unmarshal(new StringReader(stringWriter.toString()));
73 assertEquals("Unmarshalled object should be equal to original objectToMarshall.", objectToMarshal, actual);
74
75 if (StringUtils.isBlank(expectedXml)) {
76 throw new IllegalArgumentException("Expected XML must be specified.");
77 }
78
79 Object expected = unmarshaller.unmarshal(new StringReader(expectedXml.trim()));
80 assertEquals("Unmarshalled objects should be equal.", expected, actual);
81 } catch (Throwable e) {
82 System.err.println("Outputting marshaled XML from failed assertion:\n" + marshaledXml);
83 if (e instanceof RuntimeException) {
84 throw (RuntimeException)e;
85 } else if (e instanceof Error) {
86 throw (Error)e;
87 }
88 throw new RuntimeException("Failed to marshall/unmarshall with JAXB. See the nested exception for details.", e);
89 }
90 }
91
92 public static void assertEqualXmlMarshalUnmarshalWithResource(Object objectToMarshal, InputStream expectedXml, Class<?> ... classesToBeBound) throws IOException {
93 BufferedReader reader = new BufferedReader(new InputStreamReader(expectedXml));
94 StringWriter writer = new StringWriter();
95 int data = -1;
96 while ((data = reader.read()) != -1) {
97 writer.write(data);
98 }
99 assertEqualXmlMarshalUnmarshal(objectToMarshal, writer.toString(), classesToBeBound);
100 }
101
102
103 }