1   /*
2    * Copyright 2006 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.oxm.xstream;
18  
19  import java.io.ByteArrayOutputStream;
20  import java.io.StringWriter;
21  import java.util.Arrays;
22  import java.util.Collections;
23  import java.util.Map;
24  import java.util.Properties;
25  import javax.xml.parsers.DocumentBuilder;
26  import javax.xml.parsers.DocumentBuilderFactory;
27  import javax.xml.stream.XMLEventWriter;
28  import javax.xml.stream.XMLOutputFactory;
29  import javax.xml.stream.XMLStreamWriter;
30  import javax.xml.transform.dom.DOMResult;
31  import javax.xml.transform.sax.SAXResult;
32  import javax.xml.transform.stream.StreamResult;
33  
34  import com.thoughtworks.xstream.converters.Converter;
35  import com.thoughtworks.xstream.converters.extended.EncodedByteArrayConverter;
36  import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
37  import org.custommonkey.xmlunit.XMLTestCase;
38  import org.easymock.MockControl;
39  import org.w3c.dom.Document;
40  import org.w3c.dom.Element;
41  import org.w3c.dom.Text;
42  import org.xml.sax.ContentHandler;
43  
44  import org.springframework.xml.transform.StaxResult;
45  import org.springframework.xml.transform.StringResult;
46  import org.springframework.xml.transform.StringSource;
47  
48  public class XStreamMarshallerTest extends XMLTestCase {
49  
50      private static final String EXPECTED_STRING = "<flight><flightNumber>42</flightNumber></flight>";
51  
52      private XStreamMarshaller marshaller;
53  
54      private Flight flight;
55  
56      protected void setUp() throws Exception {
57          marshaller = new XStreamMarshaller();
58          Properties aliases = new Properties();
59          aliases.setProperty("flight", Flight.class.getName());
60          marshaller.setAliases(aliases);
61          flight = new Flight();
62          flight.setFlightNumber(42L);
63      }
64  
65      public void testMarshalDOMResult() throws Exception {
66          DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
67          DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
68          Document document = builder.newDocument();
69          DOMResult domResult = new DOMResult(document);
70          marshaller.marshal(flight, domResult);
71          Document expected = builder.newDocument();
72          Element flightElement = expected.createElement("flight");
73          expected.appendChild(flightElement);
74          Element numberElement = expected.createElement("flightNumber");
75          flightElement.appendChild(numberElement);
76          Text text = expected.createTextNode("42");
77          numberElement.appendChild(text);
78          assertXMLEqual("Marshaller writes invalid DOMResult", expected, document);
79      }
80  
81      // see SWS-392
82      public void testMarshalDOMResultToExistentDocument() throws Exception {
83          DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
84          DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
85          Document existent = builder.newDocument();
86          Element rootElement = existent.createElement("root");
87          Element flightsElement = existent.createElement("flights");
88          rootElement.appendChild(flightsElement);
89          existent.appendChild(rootElement);
90  
91          // marshall into the existent document
92          DOMResult domResult = new DOMResult(flightsElement);
93          marshaller.marshal(flight, domResult);
94  
95          Document expected = builder.newDocument();
96          Element eRootElement = expected.createElement("root");
97          Element eFlightsElement = expected.createElement("flights");
98          Element eFlightElement = expected.createElement("flight");
99          eRootElement.appendChild(eFlightsElement);
100         eFlightsElement.appendChild(eFlightElement);
101         expected.appendChild(eRootElement);
102         Element eNumberElement = expected.createElement("flightNumber");
103         eFlightElement.appendChild(eNumberElement);
104         Text text = expected.createTextNode("42");
105         eNumberElement.appendChild(text);
106         assertXMLEqual("Marshaller writes invalid DOMResult", expected, existent);
107     }
108 
109     public void testMarshalStreamResultWriter() throws Exception {
110         StringWriter writer = new StringWriter();
111         StreamResult result = new StreamResult(writer);
112         marshaller.marshal(flight, result);
113         assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, writer.toString());
114     }
115 
116     public void testMarshalStreamResultOutputStream() throws Exception {
117         ByteArrayOutputStream os = new ByteArrayOutputStream();
118         StreamResult result = new StreamResult(os);
119         marshaller.marshal(flight, result);
120         String s = new String(os.toByteArray(), "UTF-8");
121         assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, s);
122     }
123 
124     public void testMarshalSaxResult() throws Exception {
125         MockControl handlerControl = MockControl.createStrictControl(ContentHandler.class);
126         handlerControl.setDefaultMatcher(MockControl.ALWAYS_MATCHER);
127         ContentHandler handlerMock = (ContentHandler) handlerControl.getMock();
128         handlerMock.startDocument();
129         handlerMock.startElement("", "flight", "flight", null);
130         handlerMock.startElement("", "number", "number", null);
131         handlerMock.characters(new char[]{'4', '2'}, 0, 2);
132         handlerMock.endElement("", "number", "number");
133         handlerMock.endElement("", "flight", "flight");
134         handlerMock.endDocument();
135 
136         handlerControl.replay();
137         SAXResult result = new SAXResult(handlerMock);
138         marshaller.marshal(flight, result);
139         handlerControl.verify();
140     }
141 
142     public void testMarshalStaxResultXMLStreamWriter() throws Exception {
143         XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
144         StringWriter writer = new StringWriter();
145         XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(writer);
146         StaxResult result = new StaxResult(streamWriter);
147         marshaller.marshal(flight, result);
148         assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, writer.toString());
149     }
150 
151     public void testMarshalStaxResultXMLEventWriter() throws Exception {
152         XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
153         StringWriter writer = new StringWriter();
154         XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(writer);
155         StaxResult result = new StaxResult(eventWriter);
156         marshaller.marshal(flight, result);
157         assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, writer.toString());
158     }
159 
160     public void testConverters() throws Exception {
161         marshaller.setConverters(new Converter[]{new EncodedByteArrayConverter()});
162         byte[] buf = new byte[]{0x1, 0x2};
163         StringResult result = new StringResult();
164         marshaller.marshal(buf, result);
165         assertXMLEqual("<byte-array>AQI=</byte-array>", result.toString());
166         StringSource source = new StringSource(result.toString());
167         byte[] bufResult = (byte[]) marshaller.unmarshal(source);
168         assertTrue("Invalid result", Arrays.equals(buf, bufResult));
169     }
170 
171     public void testUseAttributesFor() throws Exception {
172         marshaller.setUseAttributeForTypes(new Class[]{Long.TYPE});
173         StringResult result = new StringResult();
174         marshaller.marshal(flight, result);
175         String expected = "<flight flightNumber=\"42\" />";
176         assertXMLEqual("Marshaller does not use attributes", expected, result.toString());
177     }
178 
179     public void testUseAttributesForStringClassMap() throws Exception {
180         marshaller.setUseAttributeFor(Collections.singletonMap("flightNumber", Long.TYPE));
181         StringResult result = new StringResult();
182         marshaller.marshal(flight, result);
183         String expected = "<flight flightNumber=\"42\" />";
184         assertXMLEqual("Marshaller does not use attributes", expected, result.toString());
185     }
186 
187     public void testUseAttributesForClassStringMap() throws Exception {
188         marshaller.setUseAttributeFor(Collections.singletonMap(Flight.class, "flightNumber"));
189         StringResult result = new StringResult();
190         marshaller.marshal(flight, result);
191         String expected = "<flight flightNumber=\"42\" />";
192         assertXMLEqual("Marshaller does not use attributes", expected, result.toString());
193     }
194 
195     public void testOmitField() throws Exception {
196         marshaller.addOmittedField(Flight.class, "flightNumber");
197         StringResult result = new StringResult();
198         marshaller.marshal(flight, result);
199         assertXpathNotExists("/flight/flightNumber", result.toString());
200     }
201 
202     public void testOmitFields() throws Exception {
203         Map omittedFieldsMap = Collections.singletonMap(Flight.class, "flightNumber");
204         marshaller.setOmittedFields(omittedFieldsMap);
205         StringResult result = new StringResult();
206         marshaller.marshal(flight, result);
207         assertXpathNotExists("/flight/flightNumber", result.toString());
208     }
209 
210     public void testDriver() throws Exception {
211         marshaller.setStreamDriver(new JettisonMappedXmlDriver());
212         StringResult result = new StringResult();
213         marshaller.marshal(flight, result);
214         assertEquals("Invalid result", "{\"flight\":{\"flightNumber\":\"42\"}}", result.toString());
215         Object o = marshaller.unmarshal(new StringSource(result.toString()));
216         assertTrue("Unmarshalled object is not Flights", o instanceof Flight);
217         Flight unflight = (Flight) o;
218         assertNotNull("Flight is null", unflight);
219         assertEquals("Number is invalid", 42L, unflight.getFlightNumber());
220     }
221 
222 }