javax.xml.transform.stax.StAXSource Java Examples

The following examples show how to use javax.xml.transform.stax.StAXSource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StaEDIXMLStreamReaderTest.java    From staedi with Apache License 2.0 10 votes vote down vote up
@Test
void testReadXml() throws Exception {
    XMLStreamReader xmlReader = getXmlReader("/x12/extraDelimiter997.edi");
    xmlReader.next(); // Per StAXSource JavaDoc, put in START_DOCUMENT state
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    StringWriter result = new StringWriter();
    transformer.transform(new StAXSource(xmlReader), new StreamResult(result));
    String resultString = result.toString();
    Diff d = DiffBuilder.compare(Input.fromFile("src/test/resources/x12/extraDelimiter997.xml"))
                        .withTest(resultString).build();
    assertTrue(!d.hasDifferences(), () -> "XML unexpectedly different:\n" + d.toString(new DefaultComparisonFormatter()));
}
 
Example #2
Source File: SourceHttpMessageConverterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void readStAXSourceExternal() throws Exception {
	MockHttpInputMessage inputMessage = new MockHttpInputMessage(bodyExternal.getBytes("UTF-8"));
	inputMessage.getHeaders().setContentType(new MediaType("application", "xml"));
	converter.setSupportDtd(true);
	StAXSource result = (StAXSource) converter.read(StAXSource.class, inputMessage);
	XMLStreamReader streamReader = result.getXMLStreamReader();
	assertTrue(streamReader.hasNext());
	streamReader.next();
	streamReader.next();
	String s = streamReader.getLocalName();
	assertEquals("root", s);
	try {
		s = streamReader.getElementText();
		assertNotEquals("Foo Bar", s);
	}
	catch (XMLStreamException ex) {
		// Some parsers raise a parse exception
	}
	streamReader.close();
}
 
Example #3
Source File: JDBCSQLXML.java    From evosql with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a Source for reading the XML value designated by this SQLXML
 * instance. <p>
 *
 * @param sourceClass The class of the source, or null.  If null, then a
 *      DOMSource is returned.
 * @return a Source for reading the XML value.
 * @throws SQLException if there is an error processing the XML value
 *   or if the given <tt>sourceClass</tt> is not supported.
 */
protected <T extends Source>T getSourceImpl(
        Class<T> sourceClass) throws SQLException {

    if (JAXBSource.class.isAssignableFrom(sourceClass)) {

        // Must go first presently, since JAXBSource extends SAXSource
        // (purely as an implementation detail) and it's not possible
        // to instantiate a valid JAXBSource with a Zero-Args
        // constructor(or any subclass thereof, due to the finality of
        // its private marshaller and context object attributes)
        // FALL THROUGH... will throw an exception
    } else if (StreamSource.class.isAssignableFrom(sourceClass)) {
        return createStreamSource(sourceClass);
    } else if ((sourceClass == null)
               || DOMSource.class.isAssignableFrom(sourceClass)) {
        return createDOMSource(sourceClass);
    } else if (SAXSource.class.isAssignableFrom(sourceClass)) {
        return createSAXSource(sourceClass);
    } else if (StAXSource.class.isAssignableFrom(sourceClass)) {
        return createStAXSource(sourceClass);
    }

    throw JDBCUtil.invalidArgument("sourceClass: " + sourceClass);
}
 
Example #4
Source File: CatalogSupport4.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@DataProvider(name = "data_ValidatorA")
public Object[][] getDataValidator() {
    DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);

    SAXSource ss = new SAXSource(new InputSource(xml_val_test));
    ss.setSystemId(xml_val_test_id);

    StAXSource stax = getStaxSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);
    StAXSource stax1 = getStaxSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);

    StreamSource source = new StreamSource(new File(xml_val_test));

    return new Object[][]{
        // use catalog
        {true, false, true, ds, null, null, xml_catalog, null},
        {false, true, true, ds, null, null, null, xml_catalog},
        {true, false, true, ss, null, null, xml_catalog, null},
        {false, true, true, ss, null, null, null, xml_catalog},
        {true, false, true, stax, null, null, xml_catalog, xml_catalog},
        {false, true, true, stax1, null, null, xml_catalog, xml_catalog},
        {true, false, true, source, null, null, xml_catalog, null},
        {false, true, true, source, null, null, null, xml_catalog},
    };
}
 
Example #5
Source File: CatalogSupport5.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@DataProvider(name = "data_ValidatorC")
public Object[][] getDataValidator() {
    DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);

    SAXSource ss = new SAXSource(new InputSource(xml_val_test));
    ss.setSystemId(xml_val_test_id);

    StAXSource stax = getStaxSource(xml_val_test, xml_val_test_id, false, true, xml_catalog);
    StAXSource stax1 = getStaxSource(xml_val_test, xml_val_test_id, false, true, xml_catalog);

    StreamSource source = new StreamSource(new File(xml_val_test));

    return new Object[][]{
        // use catalog
        {false, false, true, ds, null, null, xml_bogus_catalog, null},
        {false, false, true, ds, null, null, null, xml_bogus_catalog},
        {false, false, true, ss, null, null, xml_bogus_catalog, null},
        {false, false, true, ss, null, null, null, xml_bogus_catalog},
        {false, false, true, stax, null, null, xml_bogus_catalog, null},
        {false, false, true, stax1, null, null, null, xml_bogus_catalog},
        {false, false, true, source, null, null, xml_bogus_catalog, null},
        {false, false, true, source, null, null, null, xml_bogus_catalog},
    };
}
 
Example #6
Source File: XML.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Unmarshal an object from the given stream, DOM or other sources.
 * Together with the {@linkplain #unmarshal(Source, Map) Unmarshal Global Root Element} variant,
 * this is the most flexible unmarshalling method provided in this {@code XML} class.
 * The source is specified by the {@code input} argument implementation, for example
 * {@link javax.xml.transform.stream.StreamSource} for reading from a file or input stream.
 * The optional {@code properties} map can contain any key documented in this {@code XML} class,
 * together with the keys documented in the <cite>supported properties</cite> section of the the
 * {@link Unmarshaller} class.
 *
 * @param  <T>           compile-time value of the {@code declaredType} argument.
 * @param  input         the file from which to read a XML representation.
 * @param  declaredType  the JAXB mapped class of the object to unmarshal.
 * @param  properties    an optional map of properties to give to the unmarshaller, or {@code null} if none.
 * @return the object unmarshalled from the given input, wrapped in a JAXB element.
 * @throws JAXBException if a property has an illegal value, or if an error occurred during the unmarshalling.
 *
 * @since 0.8
 */
public static <T> JAXBElement<T> unmarshal(final Source input, final Class<T> declaredType, final Map<String,?> properties)
        throws JAXBException
{
    ensureNonNull("input", input);
    ensureNonNull("declaredType", declaredType);
    final MarshallerPool pool = getPool();
    final Unmarshaller unmarshaller = pool.acquireUnmarshaller(properties);
    final JAXBElement<T> element;
    if (input instanceof StAXSource) {                  // Same workaround than the one documented in above method.
        @Workaround(library = "JDK", version = "1.8")
        final XMLStreamReader reader = ((StAXSource) input).getXMLStreamReader();
        if (reader != null) {
            element = unmarshaller.unmarshal(reader, declaredType);
        } else {
            element = unmarshaller.unmarshal(((StAXSource) input).getXMLEventReader(), declaredType);
        }
    } else {
        element = unmarshaller.unmarshal(input, declaredType);
    }
    pool.recycle(unmarshaller);
    return element;
}
 
Example #7
Source File: SourceHttpMessageConverter.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected T readInternal(Class<? extends T> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	InputStream body = inputMessage.getBody();
	if (DOMSource.class == clazz) {
		return (T) readDOMSource(body, inputMessage);
	}
	else if (SAXSource.class == clazz) {
		return (T) readSAXSource(body, inputMessage);
	}
	else if (StAXSource.class == clazz) {
		return (T) readStAXSource(body, inputMessage);
	}
	else if (StreamSource.class == clazz || Source.class == clazz) {
		return (T) readStreamSource(body);
	}
	else {
		throw new HttpMessageNotReadableException("Could not read class [" + clazz +
				"]. Only DOMSource, SAXSource, StAXSource, and StreamSource are supported.", inputMessage);
	}
}
 
Example #8
Source File: StaEDIXMLStreamReaderTest.java    From staedi with Apache License 2.0 6 votes vote down vote up
@Test
void testTransactionElementWithXmlns() throws Exception {
    EDIInputFactory ediFactory = EDIInputFactory.newFactory();
    ediFactory.setProperty(EDIInputFactory.XML_DECLARE_TRANSACTION_XMLNS, Boolean.TRUE);
    InputStream stream = getClass().getResourceAsStream("/x12/extraDelimiter997.edi");
    ediReader = ediFactory.createEDIStreamReader(stream);
    XMLStreamReader xmlReader = ediFactory.createXMLStreamReader(ediReader);

    xmlReader.next(); // Per StAXSource JavaDoc, put in START_DOCUMENT state
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    StringWriter result = new StringWriter();
    transformer.transform(new StAXSource(xmlReader), new StreamResult(result));
    String resultString = result.toString();
    Diff d = DiffBuilder.compare(Input.fromFile("src/test/resources/x12/extraDelimiter997-transaction-xmlns.xml"))
                        .withTest(resultString).build();
    assertTrue(!d.hasDifferences(), () -> "XML unexpectedly different:\n" + d.toString(new DefaultComparisonFormatter()));
}
 
Example #9
Source File: SourceHttpMessageConverter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected T readInternal(Class<? extends T> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	InputStream body = inputMessage.getBody();
	if (DOMSource.class == clazz) {
		return (T) readDOMSource(body, inputMessage);
	}
	else if (SAXSource.class == clazz) {
		return (T) readSAXSource(body, inputMessage);
	}
	else if (StAXSource.class == clazz) {
		return (T) readStAXSource(body, inputMessage);
	}
	else if (StreamSource.class == clazz || Source.class == clazz) {
		return (T) readStreamSource(body);
	}
	else {
		throw new HttpMessageNotReadableException("Could not read class [" + clazz +
				"]. Only DOMSource, SAXSource, StAXSource, and StreamSource are supported.", inputMessage);
	}
}
 
Example #10
Source File: StaEDIXMLStreamReaderTest.java    From staedi with Apache License 2.0 6 votes vote down vote up
@Test
void testXmlIOEquivalence() throws Exception {
    XMLStreamReader xmlReader = getXmlReader("/x12/extraDelimiter997.edi");
    xmlReader.next(); // Per StAXSource JavaDoc, put in START_DOCUMENT state
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    StringWriter result = new StringWriter();
    transformer.transform(new StAXSource(xmlReader), new StreamResult(result));
    String resultString = result.toString();

    EDIOutputFactory ediOutFactory = EDIOutputFactory.newFactory();
    ediOutFactory.setProperty(EDIOutputFactory.PRETTY_PRINT, "true");
    ByteArrayOutputStream resultEDI = new ByteArrayOutputStream();
    EDIStreamWriter ediWriter = ediOutFactory.createEDIStreamWriter(resultEDI);
    XMLStreamWriter xmlWriter = new StaEDIXMLStreamWriter(ediWriter);
    transformer.transform(new StreamSource(new StringReader(resultString)), new StAXResult(xmlWriter));
    String expectedEDI = String.join("\n", Files.readAllLines(Paths.get("src/test/resources/x12/extraDelimiter997.edi")));
    assertEquals(expectedEDI, new String(resultEDI.toByteArray()).trim());
}
 
Example #11
Source File: SourceHttpMessageConverterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void readStAXSourceExternal() throws Exception {
	MockHttpInputMessage inputMessage = new MockHttpInputMessage(bodyExternal.getBytes("UTF-8"));
	inputMessage.getHeaders().setContentType(new MediaType("application", "xml"));
	converter.setSupportDtd(true);
	StAXSource result = (StAXSource) converter.read(StAXSource.class, inputMessage);
	XMLStreamReader streamReader = result.getXMLStreamReader();
	assertTrue(streamReader.hasNext());
	streamReader.next();
	streamReader.next();
	String s = streamReader.getLocalName();
	assertEquals("root", s);
	try {
		s = streamReader.getElementText();
		assertNotEquals("Foo Bar", s);
	}
	catch (XMLStreamException ex) {
		// Some parsers raise a parse exception
	}
	streamReader.close();
}
 
Example #12
Source File: SourceHttpMessageConverter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected T readInternal(Class<? extends T> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	InputStream body = inputMessage.getBody();
	if (DOMSource.class == clazz) {
		return (T) readDOMSource(body);
	}
	else if (SAXSource.class == clazz) {
		return (T) readSAXSource(body);
	}
	else if (StAXSource.class == clazz) {
		return (T) readStAXSource(body);
	}
	else if (StreamSource.class == clazz || Source.class == clazz) {
		return (T) readStreamSource(body);
	}
	else {
		throw new HttpMessageConversionException("Could not read class [" + clazz +
				"]. Only DOMSource, SAXSource, StAXSource, and StreamSource are supported.");
	}
}
 
Example #13
Source File: CatalogSupport2.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@DataProvider(name = "data_ValidatorC")
public Object[][] getDataValidator() {
    DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);

    SAXSource ss = new SAXSource(new InputSource(xml_val_test));
    ss.setSystemId(xml_val_test_id);

    StAXSource stax = getStaxSource(xml_val_test, xml_val_test_id, false, true, xml_catalog);
    StAXSource stax1 = getStaxSource(xml_val_test, xml_val_test_id, false, true, xml_catalog);

    StreamSource source = new StreamSource(new File(xml_val_test));

    return new Object[][]{
        // use catalog
        {false, false, true, ds, null, null, xml_catalog, null},
        {false, false, true, ds, null, null, null, xml_catalog},
        {false, false, true, ss, null, null, xml_catalog, null},
        {false, false, true, ss, null, null, null, xml_catalog},
        {false, false, true, stax, null, null, xml_catalog, null},
        {false, false, true, stax1, null, null, null, xml_catalog},
        {false, false, true, source, null, null, xml_catalog, null},
        {false, false, true, source, null, null, null, xml_catalog},
    };
}
 
Example #14
Source File: MetaMapConceptProvider.java    From bioasq with Apache License 2.0 5 votes vote down vote up
private List<String> splitResponseByMMO(String response)
        throws XMLStreamException, TransformerException {
  XMLStreamReader reader = xmlInputFactory.createXMLStreamReader(new StringReader(response));
  while (!reader.hasName() || !"MMOs".equals(reader.getLocalName())) {
    reader.next();
  }
  List<String> mmoStrings = new ArrayList<>();
  while (reader.nextTag() == XMLStreamConstants.START_ELEMENT) {
    StringWriter buffer = new StringWriter();
    transformer.transform(new StAXSource(reader), new StreamResult(buffer));
    mmoStrings.add(buffer.toString());
  }
  return mmoStrings;
}
 
Example #15
Source File: DispatchClientServerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testStAXSourcePAYLOAD() throws Exception {

    URL wsdl = getClass().getResource("/wsdl/hello_world.wsdl");
    assertNotNull(wsdl);

    Service service = Service.create(wsdl, SERVICE_NAME);
    assertNotNull(service);

    Dispatch<StAXSource> disp = service.createDispatch(PORT_NAME, StAXSource.class, Service.Mode.PAYLOAD);
    disp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
                                 "http://localhost:"
                                 + greeterPort
                                 + "/SOAPDispatchService/SoapDispatchPort");
    QName opQName = new QName("http://apache.org/hello_world_soap_http", "greetMe");
    disp.getRequestContext().put(MessageContext.WSDL_OPERATION, opQName);

    // Test request-response
    InputStream is = getClass().getResourceAsStream("resources/GreetMeDocLiteralSOAPBodyReq.xml");
    StAXSource staxSourceReq = new StAXSource(StaxUtils.createXMLStreamReader(is));
    assertNotNull(staxSourceReq);
    Source resp = disp.invoke(staxSourceReq);
    assertNotNull(resp);
    assertTrue(resp instanceof StAXSource);
    String expected = "Hello TestSOAPInputMessage";
    String actual = StaxUtils.toString(StaxUtils.read(resp));
    assertTrue("Expected: " + expected, actual.contains(expected));
}
 
Example #16
Source File: AbstractUnmarshallerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void unmarshalJaxp14StaxSourceXmlStreamReader() throws Exception {
	XMLInputFactory inputFactory = XMLInputFactory.newInstance();
	XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(INPUT_STRING));
	StAXSource source = new StAXSource(streamReader);
	Object flights = unmarshaller.unmarshal(source);
	testFlights(flights);
}
 
Example #17
Source File: SourceHttpMessageConverterTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void readStAXSourceWithXmlBomb() throws Exception {
	// https://en.wikipedia.org/wiki/Billion_laughs
	// https://msdn.microsoft.com/en-us/magazine/ee335713.aspx
	String content = "<?xml version=\"1.0\"?>\n" +
			"<!DOCTYPE lolz [\n" +
			" <!ENTITY lol \"lol\">\n" +
			" <!ELEMENT lolz (#PCDATA)>\n" +
			" <!ENTITY lol1 \"&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;\">\n" +
			" <!ENTITY lol2 \"&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;\">\n" +
			" <!ENTITY lol3 \"&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;\">\n" +
			" <!ENTITY lol4 \"&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;\">\n" +
			" <!ENTITY lol5 \"&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;\">\n" +
			" <!ENTITY lol6 \"&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;\">\n" +
			" <!ENTITY lol7 \"&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;\">\n" +
			" <!ENTITY lol8 \"&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;\">\n" +
			" <!ENTITY lol9 \"&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;\">\n" +
			"]>\n" +
			"<root>&lol9;</root>";
	MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes("UTF-8"));
	StAXSource result = (StAXSource) this.converter.read(StAXSource.class, inputMessage);

	XMLStreamReader streamReader = result.getXMLStreamReader();
	assertTrue(streamReader.hasNext());
	streamReader.next();
	streamReader.next();
	String s = streamReader.getLocalName();
	assertEquals("root", s);
	assertThatExceptionOfType(XMLStreamException.class).isThrownBy(() ->
			streamReader.getElementText())
		.withMessageContaining("\"lol9\"");
}
 
Example #18
Source File: AbstractUnmarshallerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void unmarshalJaxp14StaxSourceXmlEventReader() throws Exception {
	XMLInputFactory inputFactory = XMLInputFactory.newInstance();
	XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(INPUT_STRING));
	StAXSource source = new StAXSource(eventReader);
	Object flights = unmarshaller.unmarshal(source);
	testFlights(flights);
}
 
Example #19
Source File: DmnXMLConverter.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public void validateModel(XMLStreamReader xmlStreamReader) throws Exception {
    Schema schema;
    if (isDMN12(xmlStreamReader)) {
        schema = createSchema(DMN_XSD);
    } else {
        schema = createSchema(DMN_11_XSD);
    }
    Validator validator = schema.newValidator();
    validator.validate(new StAXSource(xmlStreamReader));
}
 
Example #20
Source File: StaxUtilsTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void isStaxSourceJaxp14() throws Exception {
	XMLInputFactory inputFactory = XMLInputFactory.newInstance();
	String expected = "<element/>";
	XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(expected));
	StAXSource source = new StAXSource(streamReader);

	assertTrue("Not a StAX Source", StaxUtils.isStaxSource(source));
}
 
Example #21
Source File: CR6708840Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * workaround before the fix: provide a result
 */
@Test
public final void testStAXWResult() {
    try {
        XMLInputFactory xmlif = XMLInputFactory.newInstance();

        // XMLStreamReader staxReader =
        // xmlif.createXMLStreamReader((Source)new
        // StreamSource(getClass().getResource("Forum31576.xml").getFile()));
        XMLStreamReader staxReader = xmlif.createXMLStreamReader(this.getClass().getResourceAsStream("gMonths.xml"));

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schemaGrammar = schemaFactory.newSchema(new File(getClass().getResource("gMonths.xsd").getFile()));

        Validator schemaValidator = schemaGrammar.newValidator();

        Source staxSrc = new StAXSource(staxReader);
        File resultFile = new File(USER_DIR + "gMonths.result.xml");
        if (resultFile.exists()) {
            resultFile.delete();
        }

        Result xmlResult = new javax.xml.transform.stax.StAXResult(XMLOutputFactory.newInstance().createXMLStreamWriter(new FileWriter(resultFile)));
        schemaValidator.validate(staxSrc, xmlResult);

        while (staxReader.hasNext()) {
            int eventType = staxReader.next();
            System.out.println("Event of type: " + eventType);
        }
    } catch (Exception e) {
        Assert.fail(e.getMessage());
        e.printStackTrace();
    }
}
 
Example #22
Source File: AbstractUnmarshallerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void unmarshalJaxp14StaxSourceXmlEventReader() throws Exception {
	XMLInputFactory inputFactory = XMLInputFactory.newInstance();
	XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(INPUT_STRING));
	StAXSource source = new StAXSource(eventReader);
	Object flights = unmarshaller.unmarshal(source);
	testFlights(flights);
}
 
Example #23
Source File: StaxUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the {@link XMLStreamReader} for the given StAX Source.
 * @param source a JAXP 1.4 {@link StAXSource}
 * @return the {@link XMLStreamReader}
 * @throws IllegalArgumentException if {@code source} isn't a JAXP 1.4 {@link StAXSource}
 * or custom StAX Source
 */
public static XMLStreamReader getXMLStreamReader(Source source) {
	if (source instanceof StAXSource) {
		return ((StAXSource) source).getXMLStreamReader();
	}
	else if (source instanceof StaxSource) {
		return ((StaxSource) source).getXMLStreamReader();
	}
	else {
		throw new IllegalArgumentException("Source '" + source + "' is neither StaxSource nor StAXSource");
	}
}
 
Example #24
Source File: AvvisaturaUtils.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
public static  CtEsitoAvvisoDigitale leggiProssimoEsitoAvvisoDigitale(XMLStreamReader xsr, Transformer t) throws JAXBException, IOException, XMLStreamException, TransformerException {

		if(trovaProssimoEsitoAvvisoDigitale(xsr)) {

			DOMResult result = new DOMResult();
			t.transform(new StAXSource(xsr), result);
			Node domNode = result.getNode();
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			JAXBElement<CtEsitoAvvisoDigitale> root = jaxbUnmarshaller.unmarshal(domNode, CtEsitoAvvisoDigitale.class);
			return root.getValue();
		} else {
			return null;
		}

	}
 
Example #25
Source File: StaxUtilsTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void isStaxSourceJaxp14() throws Exception {
	XMLInputFactory inputFactory = XMLInputFactory.newInstance();
	String expected = "<element/>";
	XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(expected));
	StAXSource source = new StAXSource(streamReader);

	assertTrue("Not a StAX Source", StaxUtils.isStaxSource(source));
}
 
Example #26
Source File: RequestPayloadConverter.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
void convertAsXml(final Message in) {
    final String body = bodyAsString(in);
    if (body == null) {
        return;
    }

    try {
        final XMLStreamReader bodyReader = XML_INPUT_FACTORY.createXMLStreamReader(new StringReader(body));

        final XMLStreamReader eventReader = XML_INPUT_FACTORY.createFilteredReader(bodyReader, new XmlPayloadProcessor(in.getHeaders()));

        final Source source = new StAXSource(eventReader);
        final ByteArrayOutputStream out = new ByteArrayOutputStream(body.length());
        final Result result = new StreamResult(out);

        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(source, result);

        in.setBody(new String(out.toByteArray(), StandardCharsets.UTF_8));
    } catch (XMLStreamException | TransformerFactoryConfigurationError | TransformerException e) {
        LOG.warn("Unable to parse payload, continuing without conversion", e);

        return;
    }

}
 
Example #27
Source File: StaEDIXMLStreamReaderTest.java    From staedi with Apache License 2.0 5 votes vote down vote up
@Test
void testReadXml_WithOptionalInterchangeServiceRequests_TransactionOnly() throws Exception {
    EDIInputFactory ediFactory = EDIInputFactory.newFactory();
    XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
    InputStream stream = getClass().getResourceAsStream("/x12/optionalInterchangeServices.edi");
    ediFactory.setProperty(EDIInputFactory.XML_DECLARE_TRANSACTION_XMLNS, Boolean.TRUE);
    EDIStreamReader reader = ediFactory.createEDIStreamReader(stream);
    EDIStreamReader filtered = ediFactory.createFilteredReader(reader, r -> true);
    XMLStreamReader xmlReader = ediFactory.createXMLStreamReader(filtered);
    xmlReader.next(); // Per StAXSource JavaDoc, put in START_DOCUMENT state
    XMLStreamReader xmlCursor = xmlFactory.createFilteredReader(xmlReader, r -> {
        boolean startTx = (r.getEventType() == XMLStreamConstants.START_ELEMENT && r.getName().getLocalPart().equals("TRANSACTION"));

        if (!startTx) {
            Logger.getGlobal().info("Skipping event: " + r.getEventType() + "; "
                    + (r.getEventType() == XMLStreamConstants.START_ELEMENT || r.getEventType() == XMLStreamConstants.END_ELEMENT
                            ? r.getName()
                            : ""));
        }

        return startTx;
    });

    xmlCursor.hasNext();

    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    StringWriter result = new StringWriter();
    transformer.transform(new StAXSource(xmlReader), new StreamResult(result));
    String resultString = result.toString();
    System.out.println(resultString);
    Diff d = DiffBuilder.compare(Input.fromFile("src/test/resources/x12/optionalInterchangeServices_transactionOnly.xml"))
                        .withTest(resultString).build();
    assertTrue(!d.hasDifferences(), () -> "XML unexpectedly different:\n" + d.toString(new DefaultComparisonFormatter()));
}
 
Example #28
Source File: StaEDIXMLStreamReaderTest.java    From staedi with Apache License 2.0 5 votes vote down vote up
@Test
void testEDIReporterUnset() throws Exception {
    EDIInputFactory ediFactory = EDIInputFactory.newFactory();
    InputStream stream = getClass().getResourceAsStream("/x12/invalid999.edi");
    SchemaFactory schemaFactory = SchemaFactory.newFactory();
    Schema schema = schemaFactory.createSchema(getClass().getResource("/x12/EDISchema999.xml"));

    EDIStreamReader ediReader = ediFactory.createEDIStreamReader(stream);
    ediReader = ediFactory.createFilteredReader(ediReader, (reader) -> {
        if (reader.getEventType() == EDIStreamEvent.START_TRANSACTION) {
            reader.setTransactionSchema(schema);
        }
        return true;
    });

    XMLStreamReader xmlReader = new StaEDIXMLStreamReader(ediReader);

    xmlReader.next(); // Per StAXSource JavaDoc, put in START_DOCUMENT state
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    StringWriter result = new StringWriter();
    TransformerException thrown = assertThrows(TransformerException.class,
                                               () -> transformer.transform(new StAXSource(xmlReader), new StreamResult(result)));
    Throwable cause = thrown.getCause();
    assertTrue(cause instanceof XMLStreamException);
    javax.xml.stream.Location l = ((XMLStreamException) cause).getLocation();
    assertEquals("ParseError at [row,col]:[" + l.getLineNumber() + "," +
            l.getColumnNumber() + "]\n" +
            "Message: " + "Segment IK5 has error UNEXPECTED_SEGMENT", cause.getMessage());
}
 
Example #29
Source File: SourceHttpMessageConverter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Source readStAXSource(InputStream body) {
	try {
		XMLInputFactory inputFactory = XMLInputFactory.newInstance();
		inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, isSupportDtd());
		inputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, isProcessExternalEntities());
		if (!isProcessExternalEntities()) {
			inputFactory.setXMLResolver(NO_OP_XML_RESOLVER);
		}
		XMLStreamReader streamReader = inputFactory.createXMLStreamReader(body);
		return new StAXSource(streamReader);
	}
	catch (XMLStreamException ex) {
		throw new HttpMessageNotReadableException("Could not parse document: " + ex.getMessage(), ex);
	}
}
 
Example #30
Source File: StaxUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Return the {@link XMLStreamReader} for the given StAX Source.
 * @param source a JAXP 1.4 {@link StAXSource}
 * @return the {@link XMLStreamReader}
 * @throws IllegalArgumentException if {@code source} isn't a JAXP 1.4 {@link StAXSource}
 * or custom StAX Source
 */
public static XMLStreamReader getXMLStreamReader(Source source) {
	if (source instanceof StAXSource) {
		return ((StAXSource) source).getXMLStreamReader();
	}
	else if (source instanceof StaxSource) {
		return ((StaxSource) source).getXMLStreamReader();
	}
	else {
		throw new IllegalArgumentException("Source '" + source + "' is neither StaxSource nor StAXSource");
	}
}