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

The following examples show how to use javax.xml.stream.XMLOutputFactory#newFactory() . 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: XMLTransmitter.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
/**
 * @param output
 * @throws FactoryConfigurationError
 */
private void writeCopyright(OutputStream output) throws FactoryConfigurationError {
    try {
	    XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
	    XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(output);//;
	    try {
	        xmlStreamWriter.writeStartDocument(Charset.defaultCharset().name(), "1.0");
	        xmlStreamWriter.writeCharacters("\r\n");
	        xmlStreamWriter.writeComment("\r\n" + PROPRIETARY_COPYRIGHT);
	    } finally {
	        xmlStreamWriter.flush();
            xmlStreamWriter.close();
	    }
	} catch (XMLStreamException e) {
	    throw new EPSCommonException("A XML stream writer instance could not be created", e);
	}
}
 
Example 2
Source File: ConversionService.java    From validator with Apache License 2.0 6 votes vote down vote up
public <T> String writeXml(final T model, final Schema schema, final ValidationEventHandler handler) {
    if (model == null) {
        throw new ConversionExeption("Can not serialize null");
    }
    try ( final StringWriter w = new StringWriter() ) {
        final JAXBIntrospector introspector = getJaxbContext().createJAXBIntrospector();
        final Marshaller marshaller = getJaxbContext().createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setSchema(schema);
        marshaller.setEventHandler(handler);
        final XMLOutputFactory xof = XMLOutputFactory.newFactory();
        final XMLStreamWriter xmlStreamWriter = xof.createXMLStreamWriter(w);
        if (null == introspector.getElementName(model)) {
            final JAXBElement jaxbElement = new JAXBElement(createQName(model), model.getClass(), model);
            marshaller.marshal(jaxbElement, xmlStreamWriter);
        } else {
            marshaller.marshal(model, xmlStreamWriter);
        }
        xmlStreamWriter.flush();
        return w.toString();
    } catch (final JAXBException | IOException | XMLStreamException e) {
        throw new ConversionExeption(String.format("Error serializing Object %s", model.getClass().getName()), e);
    }
}
 
Example 3
Source File: XMLOutputFactoryNewInstanceTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test if newDefaultFactory() method returns an instance
 * of the expected factory.
 * @throws Exception If any errors occur.
 */
@Test
public void testDefaultInstance() throws Exception {
    XMLOutputFactory of1 = XMLOutputFactory.newDefaultFactory();
    XMLOutputFactory of2 = XMLOutputFactory.newFactory();
    assertNotSame(of1, of2, "same instance returned:");
    assertSame(of1.getClass(), of2.getClass(),
              "unexpected class mismatch for newDefaultFactory():");
    assertEquals(of1.getClass().getName(), DEFAULT_IMPL_CLASS);
}
 
Example 4
Source File: XMLOutputFactoryProvider.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Override
public XMLOutputFactory get() {
    System.setProperty("javax.xml.stream.XMLOutputFactory", FACTORY_CLASS);

    // NOTE: In case the newFactory(String, ClassLoader) is used, XMLOutputFactory treats the string as system
    //       property name. Also, the given class loader is ignored if the property is set!
    return XMLOutputFactory.newFactory();
}
 
Example 5
Source File: Marshalling.java    From proxymusic with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Marshal the provided <b>Opus</b> instance to an OutputStream.
 *
 * @param opus the root opus element
 * @param os   the output stream (not closed by this method)
 * @throws MarshallingException global exception (use getCause() for original exception)
 */
public static void marshal (final Opus opus,
                            final OutputStream os)
        throws MarshallingException
{
    try {
        Marshaller marshaller = getContext(Opus.class).createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        Writer out = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        out.write(XML_LINE);
        out.write("\n");
        out.write(OPUS_DOCTYPE_LINE);

        XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
        XMLStreamWriter writer = outputFactory.createXMLStreamWriter(out);

        // Our custom XmlStreamWriter for name-space, formatting and comment line
        writer = new MyStreamWriter(writer, 2);

        // Marshalling
        org.audiveris.proxymusic.opus.ObjectFactory opusFactory = new org.audiveris.proxymusic.opus.ObjectFactory();
        JAXBElement<Opus> elem = opusFactory.createOpus(opus);
        marshaller.marshal(elem, writer);
        writer.flush();
    } catch (Exception ex) {
        throw new MarshallingException(ex);
    }
}
 
Example 6
Source File: Marshalling.java    From proxymusic with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Marshal the provided <b>ScorePartwise</b> instance to an OutputStream.
 *
 * @param scorePartwise   the root scorePartwise element
 * @param os              the output stream (not closed by this method)
 * @param injectSignature false if ProxyMusic encoder must not be referenced
 * @param indentation     formatting indentation value, null for no formatting.
 *                        When formatting, a comment line is inserted before parts and measures
 * @throws MarshallingException global exception (use getCause() for original exception)
 */
public static void marshal (final ScorePartwise scorePartwise,
                            final OutputStream os,
                            final boolean injectSignature,
                            final Integer indentation)
        throws MarshallingException
{
    try {
        // Inject version & signature
        annotate(scorePartwise, injectSignature);

        Marshaller marshaller = getContext(ScorePartwise.class).createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

        Writer out = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        out.write(XML_LINE);
        out.write("\n");
        out.write(PARTWISE_DOCTYPE_LINE);

        XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
        XMLStreamWriter writer = outputFactory.createXMLStreamWriter(out);
        // Use our custom XmlStreamWriter for name-space, formatting and comment line
        writer = new MyStreamWriter(writer, indentation);

        // Marshalling
        marshaller.marshal(scorePartwise, writer);
        writer.flush();
    } catch (Exception ex) {
        throw new MarshallingException(ex);
    }
}
 
Example 7
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 8
Source File: StaxStreamHandlerTests.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();
	XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(result);
	return new StaxStreamHandler(streamWriter);
}
 
Example 9
Source File: XMLOutputFactoryNewInstanceTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "parameters")
public void testNewFactory(String factoryId, ClassLoader classLoader) {
    setSystemProperty(XMLOUTPUT_FACTORY_ID, XMLOUTPUT_FACTORY_CLASSNAME);
    try {
        XMLOutputFactory xif = XMLOutputFactory.newFactory(factoryId, classLoader);
        assertNotNull(xif);
    } finally {
        clearSystemProperty(XMLOUTPUT_FACTORY_ID);
    }
}
 
Example 10
Source File: SamlResponseHelper.java    From keycloak-protocol-cas with Apache License 2.0 5 votes vote down vote up
public static Document toDOM(SAML11ResponseType response) throws ParserConfigurationException, XMLStreamException, ProcessingException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);

    XMLOutputFactory factory = XMLOutputFactory.newFactory();

    Document doc = dbf.newDocumentBuilder().newDocument();
    DOMResult result = new DOMResult(doc);
    XMLStreamWriter xmlWriter = factory.createXMLStreamWriter(result);
    SAML11ResponseWriter writer = new SAML11ResponseWriter(xmlWriter);
    writer.write(response);
    return doc;
}
 
Example 11
Source File: StaxStreamHandlerTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
protected AbstractStaxHandler createStaxHandler(Result result) throws XMLStreamException {
	XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
	XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(result);
	return new StaxStreamHandler(streamWriter);
}
 
Example 12
Source File: StaxHelper.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Creates a new StAX XMLOutputFactory, with sensible defaults
 */
public static XMLOutputFactory newXMLOutputFactory() {
    XMLOutputFactory factory = XMLOutputFactory.newFactory();
    trySetProperty(factory, XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
    return factory;
}
 
Example 13
Source File: XMLOutputFactoryNewInstanceTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions = NullPointerException.class, dataProvider = "new-instance-neg", dataProviderClass = JAXPDataProvider.class)
public void testNewFactoryNeg(String factoryId, ClassLoader classLoader) {
    XMLOutputFactory.newFactory(factoryId, classLoader);
}
 
Example 14
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 15
Source File: SectDBSynchronizer.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
protected synchronized void initErrorFile() throws Exception {
  if (this.errorFile != null && this.errorWriter == null) {
    // first create the top-level XML file that sources the actual errors XML
    int dotIndex = this.errorFile.lastIndexOf('.');
    if (dotIndex <= 0
        || !"xml".equalsIgnoreCase(this.errorFile.substring(dotIndex + 1))) {
      this.errorFile = this.errorFile.concat(".xml");
    }
    String errorFileName = this.errorFile.substring(0,
        this.errorFile.length() - 4);
    String errorEntriesFile = errorFileName + ERROR_ENTRIES_SUFFIX + ".xml";
    String errorRootFile = this.errorFile;
    this.errorFile = errorEntriesFile;
    errorEntriesFile = rollFileIfRequired(errorEntriesFile, this.logger2);
    FileOutputStream xmlStream = new FileOutputStream(errorRootFile);
    final String encoding = "UTF-8";
    final XMLOutputFactory xmlFactory = XMLOutputFactory.newFactory();
    XMLStreamWriter xmlWriter = xmlFactory.createXMLStreamWriter(xmlStream,
        encoding);
    // write the XML header
    xmlWriter.writeStartDocument(encoding, "1.0");
    xmlWriter.writeCharacters("\n");
    xmlWriter.writeDTD("<!DOCTYPE staticinc [ <!ENTITY "
        + ERR_XML_ENTRIES_ENTITY + " SYSTEM \""
        + new File(errorEntriesFile).getName() + "\"> ]>");
    xmlWriter.writeCharacters("\n");
    xmlWriter.writeStartElement(ERR_XML_ROOT);
    xmlWriter.writeCharacters("\n");
    xmlWriter.writeEntityRef(ERR_XML_ENTRIES_ENTITY);
    xmlWriter.writeCharacters("\n");
    xmlWriter.writeEndElement();
    xmlWriter.writeCharacters("\n");
    xmlWriter.writeEndDocument();
    xmlWriter.flush();
    xmlWriter.close();
    xmlStream.flush();
    xmlStream.close();

    this.errorStream = new BufferedOutputStream(new FileOutputStream(
        this.errorFile));
    // disable basic output structure validation done by Woodstox since
    // this XML has multiple root elements by design
    if (xmlFactory
        .isPropertySupported("com.ctc.wstx.outputValidateStructure")) {
      xmlFactory.setProperty("com.ctc.wstx.outputValidateStructure",
          Boolean.FALSE);
    }
    this.errorWriter = xmlFactory.createXMLStreamWriter(this.errorStream,
        encoding);
  }
}
 
Example 16
Source File: EventErrorLogger.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
protected synchronized void initErrorFile() throws Exception {
  if (this.errorFile != null && this.errorWriter == null) {
    // first create the top-level XML file that sources the actual errors XML
    int dotIndex = this.errorFile.lastIndexOf('.');
    if (dotIndex <= 0
        || !"xml".equalsIgnoreCase(this.errorFile.substring(dotIndex + 1))) {
      this.errorFile = this.errorFile.concat(".xml");
    }
    String errorFileName = this.errorFile.substring(0,
        this.errorFile.length() - 4);
    String errorEntriesFile = errorFileName + ERROR_ENTRIES_SUFFIX + ".xml";
    
    String errorRootFile = this.errorFile;
    this.errorFile = errorEntriesFile;
    errorEntriesFile = rollFileIfRequired(errorEntriesFile, this.logger2);
    
    FileOutputStream xmlStream = new FileOutputStream(errorRootFile);
    
    final String encoding = "UTF-8";
    final XMLOutputFactory xmlFactory = XMLOutputFactory.newFactory();
    XMLStreamWriter xmlWriter = xmlFactory.createXMLStreamWriter(xmlStream,
        encoding);
    // write the XML header
    xmlWriter.writeStartDocument(encoding, "1.0");
    xmlWriter.writeCharacters("\n");
    xmlWriter.writeDTD("<!DOCTYPE staticinc [ <!ENTITY "
        + ERR_XML_ENTRIES_ENTITY + " SYSTEM \""
        + new File(errorEntriesFile).getName() + "\"> ]>");
    xmlWriter.writeCharacters("\n");
    xmlWriter.writeStartElement(ERR_XML_ROOT);
    xmlWriter.writeCharacters("\n");
    xmlWriter.writeEntityRef(ERR_XML_ENTRIES_ENTITY);
    xmlWriter.writeCharacters("\n");
    xmlWriter.writeEndElement();
    xmlWriter.writeCharacters("\n");
    xmlWriter.writeEndDocument();
    xmlWriter.flush();
    xmlWriter.close();
    xmlStream.flush();
    xmlStream.close();

    this.errorStream = new BufferedOutputStream(new FileOutputStream(
        this.errorFile));
    // disable basic output structure validation done by Woodstox since
    // this XML has multiple root elements by design
    if (xmlFactory
        .isPropertySupported("com.ctc.wstx.outputValidateStructure")) {
      xmlFactory.setProperty("com.ctc.wstx.outputValidateStructure",
          Boolean.FALSE);
    }
    this.errorWriter = xmlFactory.createXMLStreamWriter(this.errorStream,
        encoding);
  }
}
 
Example 17
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);
}
 
Example 18
Source File: StaxStreamHandlerTests.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();
	XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(result);
	return new StaxStreamHandler(streamWriter);
}
 
Example 19
Source File: StaxEventHandlerTests.java    From spring-analysis-note 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);
}
 
Example 20
Source File: XmlFactories.java    From arctic-sea with Apache License 2.0 3 votes vote down vote up
private XMLOutputFactory createOutputFactory() {
    XMLOutputFactory factory = XMLOutputFactory.newFactory();

    factory.setProperty("escapeCharacters", false);

    return factory;
}