@Override protected void writeToResult(Object o, HttpHeaders headers, Result result) throws Exception { Assert.notNull(this.marshaller, "Property 'marshaller' is required"); this.marshaller.marshal(o, result); }
/** * Marshal the given object to a {@link TextMessage}. * @param object the object to be marshalled * @param session current JMS session * @param marshaller the marshaller to use * @return the resulting message * @throws JMSException if thrown by JMS methods * @throws IOException in case of I/O errors * @throws XmlMappingException in case of OXM mapping errors * @see Session#createTextMessage * @see Marshaller#marshal(Object, Result) */ protected TextMessage marshalToTextMessage(Object object, Session session, Marshaller marshaller) throws JMSException, IOException, XmlMappingException { StringWriter writer = new StringWriter(); Result result = new StreamResult(writer); marshaller.marshal(object, result); return session.createTextMessage(writer.toString()); }
@Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { Object toBeMarshalled = locateToBeMarshalled(model); if (toBeMarshalled == null) { throw new IllegalStateException("Unable to locate object to be marshalled in model: " + model); } Assert.state(this.marshaller != null, "No Marshaller set"); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); this.marshaller.marshal(toBeMarshalled, new StreamResult(baos)); setResponseContentType(request, response); response.setContentLength(baos.size()); baos.writeTo(response.getOutputStream()); }
/** * Marshal the given object to a {@link BytesMessage}. * @param object the object to be marshalled * @param session current JMS session * @param marshaller the marshaller to use * @return the resulting message * @throws JMSException if thrown by JMS methods * @throws IOException in case of I/O errors * @throws XmlMappingException in case of OXM mapping errors * @see Session#createBytesMessage * @see Marshaller#marshal(Object, Result) */ protected BytesMessage marshalToBytesMessage(Object object, Session session, Marshaller marshaller) throws JMSException, IOException, XmlMappingException { ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); StreamResult streamResult = new StreamResult(bos); marshaller.marshal(object, streamResult); BytesMessage message = session.createBytesMessage(); message.writeBytes(bos.toByteArray()); return message; }
private void parse() throws SAXException { SAXResult result = new SAXResult(getContentHandler()); result.setLexicalHandler(getLexicalHandler()); try { this.marshaller.marshal(this.content, result); } catch (IOException ex) { SAXParseException saxException = new SAXParseException(ex.getMessage(), null, null, -1, -1, ex); ErrorHandler errorHandler = getErrorHandler(); if (errorHandler != null) { errorHandler.fatalError(saxException); } else { throw saxException; } } } }
@Test public void marshalStreamResultOutputStream() throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); StreamResult result = new StreamResult(os); marshaller.marshal(flights, result); assertThat("Marshaller writes invalid StreamResult", new String(os.toByteArray(), "UTF-8"), isSimilarTo(EXPECTED_STRING)); }
@Test public void marshalStreamResultWriter() throws Exception { StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); marshaller.marshal(flights, result); assertThat("Marshaller writes invalid StreamResult", writer.toString(), isSimilarTo(EXPECTED_STRING)); }
@Test public void marshalStaxResultStreamWriter() throws Exception { XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); StringWriter writer = new StringWriter(); XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(writer); Result result = StaxUtils.createStaxResult(streamWriter); marshaller.marshal(flights, result); assertThat("Marshaller writes invalid StreamResult", writer.toString(), isSimilarTo(EXPECTED_STRING)); }
@Test public void marshalJaxp14StaxResultStreamWriter() throws Exception { XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); StringWriter writer = new StringWriter(); XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(writer); StAXResult result = new StAXResult(streamWriter); marshaller.marshal(flights, result); assertThat("Marshaller writes invalid StreamResult", writer.toString(), isSimilarTo(EXPECTED_STRING)); }
@Test public void marshalDOMResult() throws Exception { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder(); Document result = builder.newDocument(); DOMResult domResult = new DOMResult(result); marshaller.marshal(flights, domResult); Document expected = builder.newDocument(); Element flightsElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flights"); Attr namespace = expected.createAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:tns"); namespace.setNodeValue("http://samples.springframework.org/flight"); flightsElement.setAttributeNode(namespace); expected.appendChild(flightsElement); Element flightElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flight"); flightsElement.appendChild(flightElement); Element numberElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:number"); flightElement.appendChild(numberElement); Text text = expected.createTextNode("42"); numberElement.appendChild(text); assertThat("Marshaller writes invalid DOMResult", result, isSimilarTo(expected)); }
@Test public void marshalStaxResultEventWriter() throws Exception { XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); StringWriter writer = new StringWriter(); XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(writer); Result result = StaxUtils.createStaxResult(eventWriter); marshaller.marshal(flights, result); assertThat("Marshaller writes invalid StreamResult", writer.toString(), isSimilarTo(EXPECTED_STRING)); }
@Test public void marshalJaxp14StaxResultEventWriter() throws Exception { XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); StringWriter writer = new StringWriter(); XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(writer); StAXResult result = new StAXResult(eventWriter); marshaller.marshal(flights, result); assertThat("Marshaller writes invalid StreamResult", writer.toString(), isSimilarTo(EXPECTED_STRING)); }
@Test public void toTextMessage() throws Exception { converter.setTargetType(MessageType.TEXT); TextMessage textMessageMock = mock(TextMessage.class); Object toBeMarshalled = new Object(); given(sessionMock.createTextMessage(isA(String.class))).willReturn(textMessageMock); converter.toMessage(toBeMarshalled, sessionMock); verify(marshallerMock).marshal(eq(toBeMarshalled), isA(Result.class)); }
@Test public void renderModelKeyWithJaxbElement() throws Exception { String toBeMarshalled = "value"; String modelKey = "key"; view.setModelKey(modelKey); Map<String, Object> model = new HashMap<>(); model.put(modelKey, new JAXBElement<>(new QName("model"), String.class, toBeMarshalled)); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); given(marshallerMock.supports(String.class)).willReturn(true); marshallerMock.marshal(eq(toBeMarshalled), isA(StreamResult.class)); view.render(model, request, response); assertEquals("Invalid content type", "application/xml", response.getContentType()); assertEquals("Invalid content length", 0, response.getContentLength()); }
@Test public void renderNoModelKey() throws Exception { Object toBeMarshalled = new Object(); String modelKey = "key"; Map<String, Object> model = new HashMap<>(); model.put(modelKey, toBeMarshalled); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); given(marshallerMock.supports(Object.class)).willReturn(true); view.render(model, request, response); assertEquals("Invalid content type", "application/xml", response.getContentType()); assertEquals("Invalid content length", 0, response.getContentLength()); verify(marshallerMock).marshal(eq(toBeMarshalled), isA(StreamResult.class)); }
@Test public void renderModelKey() throws Exception { Object toBeMarshalled = new Object(); String modelKey = "key"; view.setModelKey(modelKey); Map<String, Object> model = new HashMap<>(); model.put(modelKey, toBeMarshalled); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); given(marshallerMock.supports(Object.class)).willReturn(true); marshallerMock.marshal(eq(toBeMarshalled), isA(StreamResult.class)); view.render(model, request, response); assertEquals("Invalid content type", "application/xml", response.getContentType()); assertEquals("Invalid content length", 0, response.getContentLength()); }
@Test public void renderNoModelKeyAndBindingResultFirst() throws Exception { Object toBeMarshalled = new Object(); String modelKey = "key"; Map<String, Object> model = new LinkedHashMap<>(); model.put(BindingResult.MODEL_KEY_PREFIX + modelKey, new BeanPropertyBindingResult(toBeMarshalled, modelKey)); model.put(modelKey, toBeMarshalled); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); given(marshallerMock.supports(BeanPropertyBindingResult.class)).willReturn(true); given(marshallerMock.supports(Object.class)).willReturn(true); view.render(model, request, response); assertEquals("Invalid content type", "application/xml", response.getContentType()); assertEquals("Invalid content length", 0, response.getContentLength()); verify(marshallerMock).marshal(eq(toBeMarshalled), isA(StreamResult.class)); }
@Test public void toBytesMessage() throws Exception { BytesMessage bytesMessageMock = mock(BytesMessage.class); Object toBeMarshalled = new Object(); given(sessionMock.createBytesMessage()).willReturn(bytesMessageMock); converter.toMessage(toBeMarshalled, sessionMock); verify(marshallerMock).marshal(eq(toBeMarshalled), isA(Result.class)); verify(bytesMessageMock).writeBytes(isA(byte[].class)); }
@Test public void write() throws Exception { String body = "<root>Hello World</root>"; MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); Marshaller marshaller = mock(Marshaller.class); willDoNothing().given(marshaller).marshal(eq(body), isA(Result.class)); MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(marshaller); converter.write(body, null, outputMessage); assertEquals("Invalid content-type", new MediaType("application", "xml"), outputMessage.getHeaders().getContentType()); }
@Test public void writeWithMarshallingFailureException() throws Exception { String body = "<root>Hello World</root>"; MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); MarshallingFailureException ex = new MarshallingFailureException("forced"); Marshaller marshaller = mock(Marshaller.class); willThrow(ex).given(marshaller).marshal(eq(body), isA(Result.class)); try { MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(marshaller); converter.write(body, null, outputMessage); fail("HttpMessageNotWritableException should be thrown"); } catch (HttpMessageNotWritableException e) { assertTrue("Invalid exception hierarchy", e.getCause() == ex); } }