Java Code Examples for javax.xml.stream.XMLEventWriter#flush()

The following examples show how to use javax.xml.stream.XMLEventWriter#flush() . 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: XmlTransformer.java    From recheck with GNU Affero General Public License v3.0 6 votes vote down vote up
private void convertAndWriteToFile( final InputStream inputStream, final File tmpFile ) throws IOException {
	try ( final LZ4BlockOutputStream out = new LZ4BlockOutputStream( new FileOutputStream( tmpFile ) ) ) {
		reset();

		final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
		inputFactory.setProperty( XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE );
		final XMLEventReader eventReader =
				inputFactory.createXMLEventReader( inputStream, StandardCharsets.UTF_8.name() );
		final XMLEventWriter eventWriter =
				XMLOutputFactory.newInstance().createXMLEventWriter( out, StandardCharsets.UTF_8.name() );

		while ( eventReader.hasNext() ) {
			final XMLEvent nextEvent = eventReader.nextEvent();
			convert( nextEvent, eventWriter );
		}
		eventReader.close();
		eventWriter.flush();
		eventWriter.close();

	} catch ( final XMLStreamException | FactoryConfigurationError e ) {
		throw new RuntimeException( e );
	}
}
 
Example 2
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 3
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 4
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 5
Source File: XMLUtilities.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public InputStream deleteProperty(final InputStream src, final List<String> path) throws Exception {
  final XMLEventReader reader = getEventReader(src);

  final ByteArrayOutputStream bos = new ByteArrayOutputStream();
  final XMLEventWriter writer = getEventWriter(bos);

  final XMLEventReader changesReader =
      new XMLEventReaderWrapper(IOUtils.toInputStream(
          String.format("<%s m:null=\"true\" />", path.get(path.size() - 1)), Constants.ENCODING));

  writer.add(changesReader);
  changesReader.close();

  writer.add(reader);

  reader.close();
  IOUtils.closeQuietly(src);

  writer.flush();
  writer.close();

  return new ByteArrayInputStream(bos.toByteArray());
}
 
Example 6
Source File: Utilities.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
public static boolean writeEvents(List<XMLEvent> events, OutputStream out) {
  if (events == null || events.size() == 0) {
    return false;
  }

  try {
    XMLOutputFactory factory = XmlFactories.getOutputFactory();

    XMLEventWriter eventWriter = factory.createXMLEventWriter(out, "UTF-8");

    for (XMLEvent event: events) {
      eventWriter.add(event);
    }

    eventWriter.flush();
    eventWriter.close();

    return true;
  } catch (XMLStreamException e) {
    throw new MarkLogicIOException(e);
  }
}
 
Example 7
Source File: XMLStreamReaderHandle.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
@Override
public void write(OutputStream out) throws IOException {
  try {
    XMLInputFactory inputFactory = getFactory();
    if (inputFactory == null) {
      throw new MarkLogicInternalException("Failed to make StAX input factory");
    }

    // TODO: rework to copy straight from stream reader to stream writer
    XMLEventReader reader = inputFactory.createXMLEventReader(content);

    XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
    XMLEventWriter   writer        =
      outputFactory.createXMLEventWriter(out, "UTF-8");

    writer.add(reader);
    writer.flush();
    writer.close();

    content.close();
  } catch (XMLStreamException e) {
    logger.error("Failed to parse StAX events from input stream",e);
    throw new MarkLogicInternalException(e);
  }
}
 
Example 8
Source File: JAXBEncoderDecoderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testMarshallWithFormQualifiedElement() throws Exception {
    ObjectWithQualifiedElementElement testObject = new ObjectWithQualifiedElementElement();
    testObject.setString1("twine");
    testObject.setString2("cord");

    QName elName = new QName(wrapperAnnotation.targetNamespace(),
                             wrapperAnnotation.localName());
    MessagePartInfo part = new MessagePartInfo(elName, null);
    part.setElement(true);
    part.setElementQName(elName);

    StringWriter stringWriter = new StringWriter();
    XMLOutputFactory opFactory = XMLOutputFactory.newInstance();
    opFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
    XMLEventWriter writer = opFactory.createXMLEventWriter(stringWriter);
    JAXBEncoderDecoder.marshall(context.createMarshaller(), testObject, part, writer);
    writer.flush();
    writer.close();
    String xmlResult = stringWriter.toString();
    // the following is a bit of a crock, but, to tell the truth, this test case most exists
    // so that it could be examined inside the debugger to see how JAXB works.
    assertTrue(xmlResult.contains(":string2>cord</ns"));
}
 
Example 9
Source File: XmlOutputStreamFilter.java    From KeePassJava2 with Apache License 2.0 5 votes vote down vote up
public XmlOutputStreamFilter(final OutputStream outputStream, final XmlEventTransformer eventTransformer) throws IOException {

        super();
        pipedInputStream = new PipedInputStream(this);

        Callable<Boolean> output = new Callable<Boolean>() {
            public Boolean call() {
                try {
                    XMLEventReader eventReader = new com.fasterxml.aalto.stax.InputFactoryImpl()
                            .createXMLEventReader(pipedInputStream);
                    XMLEventWriter eventWriter = new com.fasterxml.aalto.stax.OutputFactoryImpl()
                            .createXMLEventWriter(outputStream);

                    XMLEvent event = null;
                    while (eventReader.hasNext()) {
                        event = eventReader.nextEvent();
                        event = eventTransformer.transform(event);
                        eventWriter.add(event);
                        eventWriter.flush();
                    }

                    eventReader.close();
                    eventWriter.flush();
                    eventWriter.close();
                    outputStream.flush();
                    outputStream.close();
                } catch (XMLStreamException | IOException e) {
                    throw new IllegalStateException(e);
                }
                return true;
            }
        };
        future = Executors.newSingleThreadExecutor().submit(output);
    }
 
Example 10
Source File: JAXBEncoderDecoderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testMarshallWithoutQNameInfo() throws Exception {
    GreetMe obj = new GreetMe();
    obj.setRequestType("Hello");

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLOutputFactory opFactory = XMLOutputFactory.newInstance();
    opFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
    XMLEventWriter writer = opFactory.createXMLEventWriter(baos);

    //STARTDOCUMENT/ENDDOCUMENT is not required
    //writer.add(eFactory.createStartDocument("utf-8", "1.0"));
    JAXBEncoderDecoder.marshall(context.createMarshaller(), obj, null, writer);
    //writer.add(eFactory.createEndDocument());
    writer.flush();
    writer.close();

    //System.out.println(baos.toString());

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    XMLInputFactory ipFactory = XMLInputFactory.newInstance();
    XMLEventReader reader = ipFactory.createXMLEventReader(bais);

    Unmarshaller um = context.createUnmarshaller();
    Object val = um.unmarshal(reader, GreetMe.class);
    assertTrue(val instanceof JAXBElement);
    val = ((JAXBElement<?>)val).getValue();
    assertTrue(val instanceof GreetMe);
    assertEquals(obj.getRequestType(),
                 ((GreetMe)val).getRequestType());
}
 
Example 11
Source File: XMLUtilities.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public InputStream addAtomInlinecount(final InputStream feed, final int count) throws Exception {
  final XMLEventReader reader = getEventReader(feed);

  final ByteArrayOutputStream bos = new ByteArrayOutputStream();
  final XMLEventWriter writer = getEventWriter(bos);

  try {

    final XMLElement feedElement =
        extractElement(reader, writer, Collections.<String> singletonList("feed"), 0, 1, 1).getValue();

    writer.add(feedElement.getStart());
    addAtomElement(IOUtils.toInputStream(String.format("<m:count>%d</m:count>", count), Constants.ENCODING), writer);
    writer.add(feedElement.getContentReader());
    writer.add(feedElement.getEnd());

    while (reader.hasNext()) {
      writer.add(reader.nextEvent());
    }

  } finally {
    writer.flush();
    writer.close();
    reader.close();
    IOUtils.closeQuietly(feed);
  }

  return new ByteArrayInputStream(bos.toByteArray());
}
 
Example 12
Source File: AndroidManifestProcessor.java    From bazel with Apache License 2.0 4 votes vote down vote up
/**
 * Overwrite the package attribute of {@code <manifest>} in an AndroidManifest.xml file.
 *
 * @param manifest The input manifest.
 * @param customPackage The package to write to the manifest.
 * @param output The output manifest to generate.
 * @return The output manifest if generated or the input manifest if no overwriting is required.
 */
/* TODO(apell): switch from custom xml parsing to Gradle merger with NO_PLACEHOLDER_REPLACEMENT
 * set when android common is updated to version 2.5.0.
 */
public Path writeManifestPackage(Path manifest, String customPackage, Path output) {
  if (Strings.isNullOrEmpty(customPackage)) {
    return manifest;
  }
  try {
    Files.createDirectories(output.getParent());
    XMLEventReader reader =
        XMLInputFactory.newInstance()
            .createXMLEventReader(Files.newInputStream(manifest), UTF_8.name());
    XMLEventWriter writer =
        XMLOutputFactory.newInstance()
            .createXMLEventWriter(Files.newOutputStream(output), UTF_8.name());
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    while (reader.hasNext()) {
      XMLEvent event = reader.nextEvent();
      if (event.isStartElement()
          && event.asStartElement().getName().toString().equalsIgnoreCase("manifest")) {
        StartElement element = event.asStartElement();
        @SuppressWarnings("unchecked")
        Iterator<Attribute> attributes = element.getAttributes();
        ImmutableList.Builder<Attribute> newAttributes = ImmutableList.builder();
        while (attributes.hasNext()) {
          Attribute attr = attributes.next();
          if (attr.getName().toString().equalsIgnoreCase("package")) {
            newAttributes.add(eventFactory.createAttribute("package", customPackage));
          } else {
            newAttributes.add(attr);
          }
        }
        writer.add(
            eventFactory.createStartElement(
                element.getName(), newAttributes.build().iterator(), element.getNamespaces()));
      } else {
        writer.add(event);
      }
    }
    writer.flush();
  } catch (XMLStreamException | FactoryConfigurationError | IOException e) {
    throw new ManifestProcessingException(e);
  }

  return output;
}
 
Example 13
Source File: AssignmentConversionServiceImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private String adjustXmlForGroups(String xml) {
    if (StringUtils.isBlank(xml)) return null;
    // special processing for assignments in order to deserialize groups correctly
    // see https://stackoverflow.com/questions/47199799/jackson-xml-tag-and-attribute-with-the-same-name
    // see https://github.com/FasterXML/jackson-dataformat-xml/issues/65
    try (InputStream in = new ByteArrayInputStream(xml.getBytes());
         OutputStream out = new ByteArrayOutputStream()) {

        XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(in);
        XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(out);
        XMLEventFactory eventFactory = XMLEventFactory.newInstance();
        List<XMLEvent> groupEvents = new ArrayList<>();

        while (reader.hasNext()) {
            XMLEvent event = reader.nextEvent();
            if (event.isStartElement() && "group".equals(event.asStartElement().getName().getLocalPart())) {
                for (; !event.isEndElement(); event = reader.nextEvent()) {
                    groupEvents.add(event);
                }
                groupEvents.add(event);
            } else if (event.isEndElement() && "assignment".equals(event.asEndElement().getName().getLocalPart())) {
                writer.add(eventFactory.createStartElement("", "", "groups"));
                for (XMLEvent e : groupEvents) {
                    writer.add(e);
                }
                writer.add(eventFactory.createEndElement("", "", "groups"));
                writer.add(event);
            } else {
                writer.add(event);
            }
        }
        writer.flush();
        String adjustedXml = out.toString();
        log.debug("adjusted groups in xml: {}", adjustedXml);
        return adjustedXml;
    } catch (XMLStreamException xse) {
        log.warn("xml parsing error while adjusting for groups, {}\n{}", xse.getMessage(), xml);
    } catch (IOException ioe) {
        log.warn("could not adjust xml for groups, {}\n{}", ioe.getMessage(), xml);
    }
    return null;
}
 
Example 14
Source File: XMLUtilities.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Override
protected InputStream replaceLink(
    final InputStream toBeChanged, final String linkName, final InputStream replacement)
    throws Exception {
  final XMLEventReader reader = getEventReader(toBeChanged);

  final ByteArrayOutputStream bos = new ByteArrayOutputStream();
  final XMLEventWriter writer = getEventWriter(bos);

  final XMLEventFactory eventFactory = XMLEventFactory.newInstance();
  XMLEvent newLine = eventFactory.createSpace("\n");

  try {
    final XMLElement linkElement =
        extractElement(reader, writer,
            Collections.<String> singletonList(Constants.get(ConstantKey.LINK)),
            Collections.<Map.Entry<String, String>> singletonList(
                new SimpleEntry<String, String>("title", linkName)), false, 0, -1, -1).getValue();
    writer.add(linkElement.getStart());

    // ------------------------------------------
    // write inline ...
    // ------------------------------------------
    writer.add(newLine);
    writer.add(eventFactory.createStartElement("m", null, "inline"));

    addAtomElement(replacement, writer);

    writer.add(eventFactory.createEndElement("m", null, "inline"));
    writer.add(newLine);
    // ------------------------------------------

    writer.add(linkElement.getEnd());

    writer.add(reader);
    writer.flush();
    writer.close();
  } finally {
    reader.close();
    IOUtils.closeQuietly(toBeChanged);
  }

  return new ByteArrayInputStream(bos.toByteArray());
}
 
Example 15
Source File: XMLUtilities.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Override
public InputStream addEditLink(
    final InputStream content, final String title, final String href)
    throws Exception {

  final ByteArrayOutputStream copy = new ByteArrayOutputStream();
  IOUtils.copy(content, copy);
  IOUtils.closeQuietly(content);

  XMLEventReader reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  XMLEventWriter writer = getEventWriter(bos);

  final String editLinkElement = String.format("<link rel=\"edit\" title=\"%s\" href=\"%s\" />", title, href);

  try {
    // check edit link existence
    extractElement(reader, writer, Collections.<String> singletonList(Constants.get(ConstantKey.LINK)),
        Collections.<Map.Entry<String, String>> singletonList(
            new AbstractMap.SimpleEntry<String, String>("rel", "edit")), false, 0, -1, -1);

    addAtomElement(IOUtils.toInputStream(editLinkElement, Constants.ENCODING), writer);
    writer.add(reader);

  } catch (Exception e) {
    reader.close();
    reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

    bos = new ByteArrayOutputStream();
    writer = getEventWriter(bos);

    final XMLElement entryElement =
        extractElement(reader, writer, Collections.<String> singletonList("entry"), 0, 1, 1).getValue();

    writer.add(entryElement.getStart());

    addAtomElement(IOUtils.toInputStream(editLinkElement, Constants.ENCODING), writer);

    writer.add(entryElement.getContentReader());
    writer.add(entryElement.getEnd());

    writer.add(reader);

    writer.flush();
    writer.close();
  } finally {
    reader.close();
  }

  return new ByteArrayInputStream(bos.toByteArray());
}
 
Example 16
Source File: XMLUtilities.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc }
 */
@Override
protected InputStream addLinks(
    final String entitySetName, final String entitykey, final InputStream is, final Set<String> links)
    throws Exception {

  // -----------------------------------------
  // 0. Build reader and writer
  // -----------------------------------------
  final XMLEventReader reader = getEventReader(is);
  final XMLEventFactory eventFactory = XMLEventFactory.newInstance();

  final ByteArrayOutputStream bos = new ByteArrayOutputStream();
  final XMLEventWriter writer = getEventWriter(bos);
  // -----------------------------------------
  final Map.Entry<Integer, XMLElement> entry =
      extractElement(reader, writer, Collections.singletonList("entry"), 0, 1, 1);

  writer.add(entry.getValue().getStart());

  final Map<String, NavigationProperty> navigationProperties = metadata.getNavigationProperties(entitySetName);

  // add for links
  for (String link : links) {
    final Set<Attribute> attributes = new HashSet<Attribute>();
    attributes.add(eventFactory.createAttribute(new QName("title"), link));
    attributes.add(eventFactory.createAttribute(new QName("href"),
        Commons.getLinksURI(entitySetName, entitykey, link)));
    attributes.add(eventFactory.createAttribute(new QName("rel"),
        Constants.get(ConstantKey.ATOM_LINK_REL) + link));
    attributes.add(eventFactory.createAttribute(new QName("type"),
        navigationProperties.get(link).isEntitySet()
            ? Constants.get(ConstantKey.ATOM_LINK_FEED)
            : Constants.get(ConstantKey.ATOM_LINK_ENTRY)));

    writer.add(eventFactory.createStartElement(
        new QName(Constants.get(ConstantKey.LINK)), attributes.iterator(), null));
    writer.add(eventFactory.createEndElement(new QName(Constants.get(ConstantKey.LINK)), null));
  }

  writer.add(entry.getValue().getContentReader());
  writer.add(entry.getValue().getEnd());
  writer.add(reader);
  IOUtils.closeQuietly(is);

  writer.flush();
  writer.close();
  reader.close();

  return new ByteArrayInputStream(bos.toByteArray());
}
 
Example 17
Source File: AssignmentConversionServiceImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private String adjustXmlForGroups(String xml) {
    if (StringUtils.isBlank(xml)) return null;
    // special processing for assignments in order to deserialize groups correctly
    // see https://stackoverflow.com/questions/47199799/jackson-xml-tag-and-attribute-with-the-same-name
    // see https://github.com/FasterXML/jackson-dataformat-xml/issues/65
    try (InputStream in = new ByteArrayInputStream(xml.getBytes());
         OutputStream out = new ByteArrayOutputStream()) {

        XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(in);
        XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(out);
        XMLEventFactory eventFactory = XMLEventFactory.newInstance();
        List<XMLEvent> groupEvents = new ArrayList<>();

        while (reader.hasNext()) {
            XMLEvent event = reader.nextEvent();
            if (event.isStartElement() && "group".equals(event.asStartElement().getName().getLocalPart())) {
                for (; !event.isEndElement(); event = reader.nextEvent()) {
                    groupEvents.add(event);
                }
                groupEvents.add(event);
            } else if (event.isEndElement() && "assignment".equals(event.asEndElement().getName().getLocalPart())) {
                writer.add(eventFactory.createStartElement("", "", "groups"));
                for (XMLEvent e : groupEvents) {
                    writer.add(e);
                }
                writer.add(eventFactory.createEndElement("", "", "groups"));
                writer.add(event);
            } else {
                writer.add(event);
            }
        }
        writer.flush();
        String adjustedXml = out.toString();
        log.debug("adjusted groups in xml: {}", adjustedXml);
        return adjustedXml;
    } catch (XMLStreamException xse) {
        log.warn("xml parsing error while adjusting for groups, {}\n{}", xse.getMessage(), xml);
    } catch (IOException ioe) {
        log.warn("could not adjust xml for groups, {}\n{}", ioe.getMessage(), xml);
    }
    return null;
}
 
Example 18
Source File: EppXmlSanitizer.java    From nomulus with Apache License 2.0 4 votes vote down vote up
private static String sanitizeAndEncode(byte[] inputXmlBytes)
    throws XMLStreamException, UnsupportedEncodingException {
  XMLEventReader xmlEventReader =
      XML_INPUT_FACTORY.createXMLEventReader(new ByteArrayInputStream(inputXmlBytes));

  if (!xmlEventReader.hasNext()) {
    return "";
  }

  XMLEvent firstEvent = xmlEventReader.nextEvent();
  checkState(firstEvent.isStartDocument(), "Missing StartDocument");
  // Get input encoding for use in XMLEventWriter creation, so that sanitized XML preserves the
  // encoding declaration. According to XML spec, UTF-8 is to be used unless input declares
  // otherwise. Epp officially allows UTF-8 and UTF-16.
  String inputEncoding =
      Optional.ofNullable(((StartDocument) firstEvent).getCharacterEncodingScheme())
          .orElse(StandardCharsets.UTF_8.name());

  ByteArrayOutputStream outputXmlBytes = new ByteArrayOutputStream();
  XMLEventWriter xmlEventWriter =
      XML_OUTPUT_FACTORY.createXMLEventWriter(outputXmlBytes, inputEncoding);
  xmlEventWriter.add(firstEvent);

  while (xmlEventReader.hasNext()) {
    XMLEvent xmlEvent = xmlEventReader.nextEvent();
    xmlEventWriter.add(xmlEvent);
    if (isStartEventForSensitiveData(xmlEvent)) {
      QName startEventName = xmlEvent.asStartElement().getName();
      while (xmlEventReader.hasNext()) {
        XMLEvent event = xmlEventReader.nextEvent();
        if (event.isCharacters()) {
          Characters characters = event.asCharacters();
          event = XML_EVENT_FACTORY.createCharacters(maskSensitiveData(characters.getData()));
        }
        xmlEventWriter.add(event);
        if (isMatchingEndEvent(event, startEventName)) {
          // The inner while-loop is guaranteed to break here for any valid XML.
          // If matching event is missing, xmlEventReader will throw XMLStreamException.
          break;
        }
      }
    }
  }
  xmlEventWriter.flush();
  return outputXmlBytes.toString(inputEncoding);
}
 
Example 19
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 20
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);
  }
}