Java Code Examples for javax.xml.stream.XMLOutputFactory#createXMLEventWriter()

The following examples show how to use javax.xml.stream.XMLOutputFactory#createXMLEventWriter() . 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: XMLStreamWriterTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @bug 8139584
 * Verifies that the resulting XML contains the standalone setting.
 */
@Test
public void testCreateStartDocument_DOMWriter()
        throws ParserConfigurationException, XMLStreamException {

    XMLOutputFactory xof = XMLOutputFactory.newInstance();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();
    XMLEventWriter eventWriter = xof.createXMLEventWriter(new DOMResult(doc));
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent event = eventFactory.createStartDocument("iso-8859-15", "1.0", true);
    eventWriter.add(event);
    eventWriter.flush();
    Assert.assertEquals(doc.getXmlEncoding(), "iso-8859-15");
    Assert.assertEquals(doc.getXmlVersion(), "1.0");
    Assert.assertTrue(doc.getXmlStandalone());
}
 
Example 2
Source File: XMLStreamWriterTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @bug 8139584
 * Verifies that the resulting XML contains the standalone setting.
 */
@Test
public void testCreateStartDocument() throws XMLStreamException {

    StringWriter stringWriter = new StringWriter();
    XMLOutputFactory out = XMLOutputFactory.newInstance();
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();

    XMLEventWriter eventWriter = out.createXMLEventWriter(stringWriter);

    XMLEvent event = eventFactory.createStartDocument("iso-8859-15", "1.0", true);
    eventWriter.add(event);
    eventWriter.flush();
    Assert.assertTrue(stringWriter.toString().contains("encoding=\"iso-8859-15\""));
    Assert.assertTrue(stringWriter.toString().contains("version=\"1.0\""));
    Assert.assertTrue(stringWriter.toString().contains("standalone=\"yes\""));
}
 
Example 3
Source File: XMLEventWriterTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test XMLStreamWriter parsing a file with an external entity reference.
 */
@Test
public void testXMLStreamWriter() {

    try {
        XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
        XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(System.out);
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        String file = getClass().getResource("XMLEventWriterTest.xml").getPath();
        XMLEventReader eventReader = inputFactory.createXMLEventReader(new StreamSource(new File(file)));

        // adds the event to the consumer.
        eventWriter.add(eventReader);
        eventWriter.flush();
        eventWriter.close();

        // expected success
    } catch (Exception exception) {
        exception.printStackTrace();
        Assert.fail(exception.toString());
    }
}
 
Example 4
Source File: AbstractMarshallerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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));
}
 
Example 5
Source File: StreamResultTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testEventWriterWithStAXResultNStreamWriter() {
    String encoding = "";
    if (getSystemProperty("file.encoding").equals("UTF-8")) {
        encoding = " encoding=\"UTF-8\"";
    }
    final String EXPECTED_OUTPUT = "<?xml version=\"1.0\"" + encoding + "?><root></root>";

    try {
        XMLOutputFactory ofac = XMLOutputFactory.newInstance();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        XMLStreamWriter swriter = ofac.createXMLStreamWriter(buffer);
        StAXResult res = new StAXResult(swriter);
        XMLEventWriter writer = ofac.createXMLEventWriter(res);

        XMLEventFactory efac = XMLEventFactory.newInstance();
        writer.add(efac.createStartDocument(null, "1.0"));
        writer.add(efac.createStartElement("", "", "root"));
        writer.add(efac.createEndElement("", "", "root"));
        writer.add(efac.createEndDocument());
        writer.close();

        Assert.assertEquals(buffer.toString(), EXPECTED_OUTPUT);
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail(e.toString());
    }
}
 
Example 6
Source File: XStreamMarshallerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void marshalStaxResultXMLEventWriter() throws Exception {
	XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
	StringWriter writer = new StringWriter();
	XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(writer);
	Result result = StaxUtils.createStaxResult(eventWriter);
	marshaller.marshal(flight, result);
	assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, writer.toString());
}
 
Example 7
Source File: StreamResultTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testEventWriterWithStAXResultNEventWriter() {
    String encoding = "";
    if (getSystemProperty("file.encoding").equals("UTF-8")) {
        encoding = " encoding=\"UTF-8\"";
    }
    final String EXPECTED_OUTPUT = "<?xml version=\"1.0\"" + encoding + "?><root></root>";

    try {
        XMLOutputFactory ofac = XMLOutputFactory.newInstance();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        XMLEventWriter writer = ofac.createXMLEventWriter(buffer);
        StAXResult res = new StAXResult(writer);
        writer = ofac.createXMLEventWriter(res);

        XMLEventFactory efac = XMLEventFactory.newInstance();
        writer.add(efac.createStartDocument(null, "1.0"));
        writer.add(efac.createStartElement("", "", "root"));
        writer.add(efac.createEndElement("", "", "root"));
        writer.add(efac.createEndDocument());
        writer.close();

        Assert.assertEquals(buffer.toString(), EXPECTED_OUTPUT);
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail(e.toString());
    }
}
 
Example 8
Source File: StreamResultTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testStreamWriterWithStAXResultNEventWriter() throws Exception {
    try {
        XMLOutputFactory ofac = XMLOutputFactory.newInstance();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        XMLEventWriter writer = ofac.createXMLEventWriter(buffer);
        StAXResult res = new StAXResult(writer);
        XMLStreamWriter swriter = ofac.createXMLStreamWriter(res);
        Assert.fail("Expected an Exception as XMLStreamWriter can't be created " + "with a StAXResult which has EventWriter.");
    } catch (Exception e) {
        System.out.println(e.toString());
    }
}
 
Example 9
Source File: AbstractMarshallerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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));
}
 
Example 10
Source File: StaxEventHandlerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected AbstractStaxHandler createStaxHandler(Result result)
		throws XMLStreamException {
	XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
	XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(result);
	return new StaxEventHandler(eventWriter);
}
 
Example 11
Source File: XMLEventStreamWriterTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Before
public void createStreamReader() throws Exception {
	stringWriter = new StringWriter();
	XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
	XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(stringWriter);
	streamWriter = new XMLEventStreamWriter(eventWriter, XMLEventFactory.newInstance());
}
 
Example 12
Source File: StaxXMLWriter.java    From journaldev with MIT License 5 votes vote down vote up
public void writeXML(String fileName, String rootElement, Map<String, String> elementsMap){
        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
        try {
//            XMLEventWriter xmlEventWriter = xmlOutputFactory
//                    .createXMLEventWriter(new FileOutputStream(fileName), "UTF-8");
            //For Debugging - below code to print XML to Console
            XMLEventWriter xmlEventWriter = xmlOutputFactory.createXMLEventWriter(System.out);
            XMLEventFactory eventFactory = XMLEventFactory.newInstance();
            XMLEvent end = eventFactory.createDTD("\n");
            StartDocument startDocument = eventFactory.createStartDocument();
            xmlEventWriter.add(startDocument);
            xmlEventWriter.add(end);
            StartElement configStartElement = eventFactory.createStartElement("",
                "", rootElement);
            xmlEventWriter.add(configStartElement);
            xmlEventWriter.add(end);
            // Write the element nodes
            Set<String> elementNodes = elementsMap.keySet();
            for(String key : elementNodes){
                createNode(xmlEventWriter, key, elementsMap.get(key));
            }
            
            xmlEventWriter.add(eventFactory.createEndElement("", "", rootElement));
            xmlEventWriter.add(end);
            xmlEventWriter.add(eventFactory.createEndDocument());
            xmlEventWriter.close();

        } catch ( XMLStreamException e) {
            e.printStackTrace();
        }
    }
 
Example 13
Source File: AbstractMarshallerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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));
}
 
Example 14
Source File: AbstractMarshallerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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));
}
 
Example 15
Source File: AbstractMarshallerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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);
	assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, writer.toString());
}
 
Example 16
Source File: XMLEventStreamWriterTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void createStreamReader() throws Exception {
	stringWriter = new StringWriter();
	XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
	XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(stringWriter);
	streamWriter = new XMLEventStreamWriter(eventWriter, XMLEventFactory.newInstance());
}
 
Example 17
Source File: Bug6551616.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void test() throws Exception {
    final String XML = "" + "<?xml version='1.0'?>" + "<doc xmlns:foo='http://example.com/foo/' xml:lang='us-en'><p>Test</p></doc>";

    javax.xml.parsers.SAXParserFactory saxFactory = javax.xml.parsers.SAXParserFactory.newInstance();

    javax.xml.parsers.SAXParser parser = saxFactory.newSAXParser();

    XMLOutputFactory outFactory = XMLOutputFactory.newInstance();
    XMLEventWriter writer = outFactory.createXMLEventWriter(System.out);

    SAX2StAXEventWriter handler = new SAX2StAXEventWriter(writer);

    InputStream is = new StringBufferInputStream(XML);

    parser.parse(is, handler);

    // if it doesn't blow up, it succeeded.
}
 
Example 18
Source File: XMLEventWriterTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Inspired by CR 6245284 Sun Stax /sjsxp.jar does not behave properly
 * during merge of xml files.
 */
@Test
public void testMerge() {

    try {
        // Create the XML input factory
        XMLInputFactory factory = XMLInputFactory.newInstance();

        // Create XML event reader 1
        InputStream inputStream1 = new FileInputStream(new File(XMLEventWriterTest.class.getResource("merge-1.xml").toURI()));
        XMLEventReader r1 = factory.createXMLEventReader(inputStream1);

        // Create XML event reader 2
        InputStream inputStream2 = new FileInputStream(new File(XMLEventWriterTest.class.getResource("merge-2.xml").toURI()));
        XMLEventReader r2 = factory.createXMLEventReader(inputStream2);

        // Create the output factory
        XMLOutputFactory xmlof = XMLOutputFactory.newInstance();

        // Create XML event writer
        XMLEventWriter xmlw = xmlof.createXMLEventWriter(System.out);

        // Read to first <product> element in document 1
        // and output to result document
        QName bName = new QName("b");

        while (r1.hasNext()) {
            // Read event to be written to result document
            XMLEvent event = r1.nextEvent();

            if (event.getEventType() == XMLEvent.END_ELEMENT) {

                // Start element - stop at <product> element
                QName name = event.asEndElement().getName();
                if (name.equals(bName)) {

                    QName zName = new QName("z");

                    boolean isZr = false;

                    while (r2.hasNext()) {
                        // Read event to be written to result document
                        XMLEvent event2 = r2.nextEvent();
                        // Output event
                        if (event2.getEventType() == XMLEvent.START_ELEMENT && event2.asStartElement().getName().equals(zName)) {
                            isZr = true;
                        }

                        if (xmlw != null && isZr) {
                            xmlw.add(event2);
                        }

                        // stop adding events after </z>
                        // i.e. do not write END_DOCUMENT :)
                        if (isZr && event2.getEventType() == XMLEvent.END_ELEMENT && event2.asEndElement().getName().equals(zName)) {
                            isZr = false;
                        }
                    }
                    xmlw.flush();
                }
            }

            // Output event
            if (xmlw != null) {
                xmlw.add(event);
            }
        }

        // Read to first <product> element in document 1
        // without writing to result document
        xmlw.close();

        // expected success
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail(ex.toString());
    }
}
 
Example 19
Source File: ArtifactsXmlAbsoluteUrlRemover.java    From nexus-repository-p2 with Eclipse Public License 1.0 4 votes vote down vote up
private TempBlob transformXmlMetadata(final TempBlob artifact,
                                      final Repository repository,
                                      final String file,
                                      final String extension,
                                      final XmlStreamTransformer transformer) throws IOException {

  Path tempFile = createTempFile("", ".xml");
  // This is required in the case that the input stream is a jar to allow us to extract a single file
  Path artifactsTempFile = createTempFile("", ".xml");
  try {
    try (InputStream xmlIn = xmlInputStream(artifact, file + "." + "xml", extension, artifactsTempFile);
         OutputStream xmlOut = xmlOutputStream(file + "." + "xml", extension, tempFile)) {
      XMLInputFactory inputFactory = XMLInputFactory.newInstance();
      inputFactory.setProperty(SUPPORT_DTD, false);
      inputFactory.setProperty(IS_SUPPORTING_EXTERNAL_ENTITIES, false);

      XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
      XMLEventReader reader = null;
      XMLEventWriter writer = null;
      //try-with-resources will be better here, but XMLEventReader and XMLEventWriter are not AutoCloseable
      try {
        reader = inputFactory.createXMLEventReader(xmlIn);
        writer = outputFactory.createXMLEventWriter(xmlOut);
        transformer.transform(reader, writer);
        writer.flush();
      }
      finally {
        if (reader != null) {
          reader.close();
        }
        if (writer != null) {
          writer.close();
        }
      }
    }
    catch (XMLStreamException ex) {
      log.error("Failed to rewrite metadata for file with extension {} and blob {} with reason: {} ",
          ex, artifact.getBlob().getId(), ex);
      return artifact;
    }
    return convertFileToTempBlob(tempFile, repository);
  }
  finally {
    delete(tempFile);
    delete(artifactsTempFile);
  }
}
 
Example 20
Source File: StaxEventHandlerTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
protected AbstractStaxHandler createStaxHandler(Result result) throws XMLStreamException {
	XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
	XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(result);
	return new StaxEventHandler(eventWriter);
}