1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.springframework.oxm.xmlbeans;
17
18 import java.io.StringReader;
19 import javax.xml.namespace.QName;
20 import javax.xml.stream.XMLInputFactory;
21 import javax.xml.stream.XMLStreamReader;
22
23 import org.springframework.oxm.AbstractUnmarshallerTestCase;
24 import org.springframework.oxm.Unmarshaller;
25 import org.springframework.samples.flight.FlightDocument;
26 import org.springframework.samples.flight.FlightType;
27 import org.springframework.samples.flight.FlightsDocument;
28 import org.springframework.samples.flight.FlightsDocument.Flights;
29 import org.springframework.xml.transform.StaxSource;
30 import org.springframework.xml.transform.StringSource;
31
32 public class XmlBeansUnmarshallerTest extends AbstractUnmarshallerTestCase {
33
34 protected Unmarshaller createUnmarshaller() throws Exception {
35 return new XmlBeansMarshaller();
36 }
37
38 protected void testFlights(Object o) {
39 FlightsDocument flightsDocument = (FlightsDocument) o;
40 assertNotNull("FlightsDocument is null", flightsDocument);
41 Flights flights = flightsDocument.getFlights();
42 assertEquals("Invalid amount of flight elements", 1, flights.sizeOfFlightArray());
43 testFlight(flights.getFlightArray(0));
44 }
45
46 protected void testFlight(Object o) {
47 FlightType flight = null;
48 if (o instanceof FlightType) {
49 flight = (FlightType) o;
50 }
51 else if (o instanceof FlightDocument) {
52 FlightDocument flightDocument = (FlightDocument) o;
53 flight = flightDocument.getFlight();
54 }
55 assertNotNull("Flight is null", flight);
56 assertEquals("Number is invalid", 42L, flight.getNumber());
57 }
58
59 public void testUnmarshalPartialStaxSourceXmlStreamReader() throws Exception {
60 XMLInputFactory inputFactory = XMLInputFactory.newInstance();
61 XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(INPUT_STRING));
62 streamReader.nextTag();
63 assertEquals("Invalid element", new QName("http://samples.springframework.org/flight", "flights"),
64 streamReader.getName());
65 streamReader.nextTag();
66 assertEquals("Invalid element", new QName("http://samples.springframework.org/flight", "flight"),
67 streamReader.getName());
68 StaxSource source = new StaxSource(streamReader);
69 Object flight = unmarshaller.unmarshal(source);
70 testFlight(flight);
71 }
72
73 public void testValidate() throws Exception {
74 ((XmlBeansMarshaller) unmarshaller).setValidating(true);
75
76 try {
77 String invalidInput = "<tns:flights xmlns:tns=\"http://samples.springframework.org/flight\">" +
78 "<tns:flight><tns:number>abc</tns:number></tns:flight></tns:flights>";
79 unmarshaller.unmarshal(new StringSource(invalidInput));
80 fail("Expected a XmlBeansValidationFailureException");
81 }
82 catch (XmlBeansValidationFailureException ex) {
83
84 }
85
86
87 }
88
89 }