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