javax.xml.stream.XMLOutputFactory Java Examples

The following examples show how to use javax.xml.stream.XMLOutputFactory. 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: CfgApi.java    From aion with MIT License 8 votes vote down vote up
public String toXML() {
    final XMLOutputFactory output = XMLOutputFactory.newInstance();
    output.setProperty("escapeCharacters", false);
    XMLStreamWriter xmlWriter;
    String xml;
    try {
        Writer strWriter = new StringWriter();
        xmlWriter = output.createXMLStreamWriter(strWriter);
        xmlWriter.writeCharacters("\r\n\t");
        xmlWriter.writeStartElement("api");

        xmlWriter.writeCharacters(this.rpc.toXML());
        xmlWriter.writeCharacters(this.zmq.toXML());
        xmlWriter.writeCharacters(this.nrg.toXML());

        xmlWriter.writeCharacters("\r\n\t");
        xmlWriter.writeEndElement();
        xml = strWriter.toString();
        strWriter.flush();
        strWriter.close();
        xmlWriter.flush();
        xmlWriter.close();
        return xml;
    } catch (IOException | XMLStreamException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example #2
Source File: PolicyUtil.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
public static OMElement getPolicyAsOMElement(Policy policy) {

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(baos);
            policy.serialize(writer);
            writer.flush();
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            XMLStreamReader xmlStreamReader =
                    XMLInputFactory.newInstance().createXMLStreamReader(bais);
            StAXOMBuilder staxOMBuilder =
                    (StAXOMBuilder) OMXMLBuilderFactory.createStAXOMBuilder(
                            OMAbstractFactory.getOMFactory(), xmlStreamReader);
            return staxOMBuilder.getDocumentElement();

        } catch (Exception ex) {
            throw new RuntimeException("can't convert the policy to an OMElement", ex);
        }
    }
 
Example #3
Source File: PolicyUtil.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
public static String getPolicyAsString(Policy policy) {
    ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
    try {
        XMLStreamWriter writer =
                XMLOutputFactory.newInstance().createXMLStreamWriter(outBuffer);
        policy.serialize(writer);
        writer.flush();
        ByteArrayInputStream bais = new ByteArrayInputStream(outBuffer.toByteArray());
        XMLPrettyPrinter xmlPrettyPrinter = new XMLPrettyPrinter(bais);
        return xmlPrettyPrinter.xmlFormat();

    } catch (XMLStreamException e) {
        throw new RuntimeException("Serialization of Policy object failed " + e);
    }

}
 
Example #4
Source File: Bufr2Xml.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public Bufr2Xml(Message message, NetcdfFile ncfile, OutputStream os, boolean skipMissing) throws IOException {
  indent = new Indent(2);
  indent.setIndentLevel(0);

  try {
    XMLOutputFactory fac = XMLOutputFactory.newInstance();
    staxWriter = fac.createXMLStreamWriter(os, CDM.UTF8);

    staxWriter.writeStartDocument(CDM.UTF8, "1.0");
    // staxWriter.writeCharacters("\n");
    // staxWriter.writeStartElement("bufrMessage");

    writeMessage(message, ncfile);

    staxWriter.writeCharacters("\n");
    staxWriter.writeEndDocument();
    staxWriter.flush();

  } catch (XMLStreamException e) {
    throw new IOException(e.getMessage());
  }
}
 
Example #5
Source File: TemplateSerializer.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * This method when called assumes the Framework Nar ClassLoader is in the
 * classloader hierarchy of the current context class loader.
 * @param dto the template dto to serialize
 * @return serialized representation of the DTO
 */
public static byte[] serialize(final TemplateDTO dto) {
    try {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final BufferedOutputStream bos = new BufferedOutputStream(baos);

        JAXBContext context = JAXBContext.newInstance(TemplateDTO.class);
        Marshaller marshaller = context.createMarshaller();
        XMLOutputFactory xmlof = XMLOutputFactory.newInstance();
        XMLStreamWriter writer = new IndentingXMLStreamWriter(xmlof.createXMLStreamWriter(bos));
        marshaller.marshal(dto, writer);

        bos.flush();
        return baos.toByteArray(); //Note: For really large templates this could use a lot of heap space
    } catch (final IOException | JAXBException | XMLStreamException e) {
        throw new FlowSerializationException(e);
    }
}
 
Example #6
Source File: XMLStreamWriterImpl.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize an instance of this XMLStreamWriter. Allocate new instances
 * for all the data structures. Set internal flags based on property values.
 */
private void init() {
    fReuse = false;
    fNamespaceDecls = new ArrayList<>();
    fPrefixGen = new Random();
    fAttributeCache = new ArrayList<>();
    fInternalNamespaceContext = new NamespaceSupport();
    fInternalNamespaceContext.reset();
    fNamespaceContext = new NamespaceContextImpl();
    fNamespaceContext.internalContext = fInternalNamespaceContext;

    // Set internal state based on property values
    Boolean ob = (Boolean) fPropertyManager.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
    fIsRepairingNamespace = ob;
    ob = (Boolean) fPropertyManager.getProperty(Constants.ESCAPE_CHARACTERS);
    setEscapeCharacters(ob);
}
 
Example #7
Source File: XMLStreamWriterImpl.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initialize an instance of this XMLStreamWriter. Allocate new instances
 * for all the data structures. Set internal flags based on property values.
 */
private void init() {
    fReuse = false;
    fNamespaceDecls = new ArrayList();
    fPrefixGen = new Random();
    fAttributeCache = new ArrayList();
    fInternalNamespaceContext = new NamespaceSupport();
    fInternalNamespaceContext.reset();
    fNamespaceContext = new NamespaceContextImpl();
    fNamespaceContext.internalContext = fInternalNamespaceContext;

    // Set internal state based on property values
    Boolean ob = (Boolean) fPropertyManager.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
    fIsRepairingNamespace = ob.booleanValue();
    ob = (Boolean) fPropertyManager.getProperty(Constants.ESCAPE_CHARACTERS);
    setEscapeCharacters(ob.booleanValue());
}
 
Example #8
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 #9
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 #10
Source File: XMLStreamWriterImpl.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Reset this instance so that it can be re-used. Clears but does not
 * re-allocate internal data structures.
 *
 * @param resetProperties Indicates if properties should be read again
 */
void reset(boolean resetProperties) {
    if (!fReuse) {
        throw new java.lang.IllegalStateException(
            "close() Must be called before calling reset()");
    }

    fReuse = false;
    fNamespaceDecls.clear();
    fAttributeCache.clear();

    // reset Element/NamespaceContext stacks
    fElementStack.clear();
    fInternalNamespaceContext.reset();

    fStartTagOpened = false;
    fNamespaceContext.userContext = null;

    if (resetProperties) {
        Boolean ob = (Boolean) fPropertyManager.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
        fIsRepairingNamespace = ob.booleanValue();
        ob = (Boolean) fPropertyManager.getProperty(Constants.ESCAPE_CHARACTERS);
        setEscapeCharacters(ob.booleanValue());
    }
}
 
Example #11
Source File: XMLStreamWriterImpl.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initialize an instance of this XMLStreamWriter. Allocate new instances
 * for all the data structures. Set internal flags based on property values.
 */
private void init() {
    fReuse = false;
    fNamespaceDecls = new ArrayList();
    fPrefixGen = new Random();
    fAttributeCache = new ArrayList();
    fInternalNamespaceContext = new NamespaceSupport();
    fInternalNamespaceContext.reset();
    fNamespaceContext = new NamespaceContextImpl();
    fNamespaceContext.internalContext = fInternalNamespaceContext;

    // Set internal state based on property values
    Boolean ob = (Boolean) fPropertyManager.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
    fIsRepairingNamespace = ob.booleanValue();
    ob = (Boolean) fPropertyManager.getProperty(Constants.ESCAPE_CHARACTERS);
    setEscapeCharacters(ob.booleanValue());
}
 
Example #12
Source File: XMLStreamWriterImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Reset this instance so that it can be re-used. Clears but does not
 * re-allocate internal data structures.
 *
 * @param resetProperties Indicates if properties should be read again
 */
void reset(boolean resetProperties) {
    if (!fReuse) {
        throw new java.lang.IllegalStateException(
            "close() Must be called before calling reset()");
    }

    fReuse = false;
    fNamespaceDecls.clear();
    fAttributeCache.clear();

    // reset Element/NamespaceContext stacks
    fElementStack.clear();
    fInternalNamespaceContext.reset();

    fStartTagOpened = false;
    fNamespaceContext.userContext = null;

    if (resetProperties) {
        Boolean ob = (Boolean) fPropertyManager.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
        fIsRepairingNamespace = ob;
        ob = (Boolean) fPropertyManager.getProperty(Constants.ESCAPE_CHARACTERS);
        setEscapeCharacters(ob);
    }
}
 
Example #13
Source File: EPRHeader.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public void writeTo(SOAPMessage saaj) throws SOAPException {
        try {
            // TODO what about in-scope namespaces
            // Not very efficient consider implementing a stream buffer
            // processor that produces a DOM node from the buffer.
            Transformer t = XmlUtil.newTransformer();
            SOAPHeader header = saaj.getSOAPHeader();
            if (header == null)
                header = saaj.getSOAPPart().getEnvelope().addHeader();
// TODO workaround for oracle xdk bug 16555545, when this bug is fixed the line below can be
// uncommented and all lines below, except the catch block, can be removed.
//            t.transform(epr.asSource(localName), new DOMResult(header));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XMLStreamWriter w = XMLOutputFactory.newFactory().createXMLStreamWriter(baos);
            epr.writeTo(localName, w);
            w.flush();
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
            fac.setNamespaceAware(true);
            Node eprNode = fac.newDocumentBuilder().parse(bais).getDocumentElement();
            Node eprNodeToAdd = header.getOwnerDocument().importNode(eprNode, true);
            header.appendChild(eprNodeToAdd);
        } catch (Exception e) {
            throw new SOAPException(e);
        }
    }
 
Example #14
Source File: XMLStreamWriterImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initialize an instance of this XMLStreamWriter. Allocate new instances
 * for all the data structures. Set internal flags based on property values.
 */
private void init() {
    fReuse = false;
    fNamespaceDecls = new ArrayList();
    fPrefixGen = new Random();
    fAttributeCache = new ArrayList();
    fInternalNamespaceContext = new NamespaceSupport();
    fInternalNamespaceContext.reset();
    fNamespaceContext = new NamespaceContextImpl();
    fNamespaceContext.internalContext = fInternalNamespaceContext;

    // Set internal state based on property values
    Boolean ob = (Boolean) fPropertyManager.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
    fIsRepairingNamespace = ob.booleanValue();
    ob = (Boolean) fPropertyManager.getProperty(Constants.ESCAPE_CHARACTERS);
    setEscapeCharacters(ob.booleanValue());
}
 
Example #15
Source File: XMLStreamWriterImpl.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initialize an instance of this XMLStreamWriter. Allocate new instances
 * for all the data structures. Set internal flags based on property values.
 */
private void init() {
    fReuse = false;
    fNamespaceDecls = new ArrayList();
    fPrefixGen = new Random();
    fAttributeCache = new ArrayList();
    fInternalNamespaceContext = new NamespaceSupport();
    fInternalNamespaceContext.reset();
    fNamespaceContext = new NamespaceContextImpl();
    fNamespaceContext.internalContext = fInternalNamespaceContext;

    // Set internal state based on property values
    Boolean ob = (Boolean) fPropertyManager.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
    fIsRepairingNamespace = ob.booleanValue();
    ob = (Boolean) fPropertyManager.getProperty(Constants.ESCAPE_CHARACTERS);
    setEscapeCharacters(ob.booleanValue());
}
 
Example #16
Source File: XMLStreamWriterImpl.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Reset this instance so that it can be re-used. Clears but does not
 * re-allocate internal data structures.
 *
 * @param resetProperties Indicates if properties should be read again
 */
void reset(boolean resetProperties) {
    if (!fReuse) {
        throw new java.lang.IllegalStateException(
            "close() Must be called before calling reset()");
    }

    fReuse = false;
    fNamespaceDecls.clear();
    fAttributeCache.clear();

    // reset Element/NamespaceContext stacks
    fElementStack.clear();
    fInternalNamespaceContext.reset();

    fStartTagOpened = false;
    fNamespaceContext.userContext = null;

    if (resetProperties) {
        Boolean ob = (Boolean) fPropertyManager.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
        fIsRepairingNamespace = ob.booleanValue();
        ob = (Boolean) fPropertyManager.getProperty(Constants.ESCAPE_CHARACTERS);
        setEscapeCharacters(ob.booleanValue());
    }
}
 
Example #17
Source File: Configuration.java    From galleon with Apache License 2.0 6 votes vote down vote up
public void needRewrite() throws XMLStreamException, IOException {
    Path configFile = getConfigFile();
    Files.deleteIfExists(configFile);
    try (BufferedWriter bw = Files.newBufferedWriter(configFile,
            StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
        try (FormattingXmlStreamWriter writer = new FormattingXmlStreamWriter(XMLOutputFactory.newInstance()
                .createXMLStreamWriter(bw))) {
            writer.writeStartDocument();
            writer.writeStartElement(ConfigXmlParser10.ROOT_1_0.getLocalPart());
            writer.writeDefaultNamespace(ConfigXmlParser10.NAMESPACE_1_0);
            maven.write(writer);
            writer.writeEndElement();
            writer.writeEndDocument();
        }
    }
}
 
Example #18
Source File: XMLStreamWriterImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Reset this instance so that it can be re-used. Clears but does not
 * re-allocate internal data structures.
 *
 * @param resetProperties Indicates if properties should be read again
 */
void reset(boolean resetProperties) {
    if (!fReuse) {
        throw new java.lang.IllegalStateException(
            "close() Must be called before calling reset()");
    }

    fReuse = false;
    fNamespaceDecls.clear();
    fAttributeCache.clear();

    // reset Element/NamespaceContext stacks
    fElementStack.clear();
    fInternalNamespaceContext.reset();

    fStartTagOpened = false;
    fNamespaceContext.userContext = null;

    if (resetProperties) {
        Boolean ob = (Boolean) fPropertyManager.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
        fIsRepairingNamespace = ob.booleanValue();
        ob = (Boolean) fPropertyManager.getProperty(Constants.ESCAPE_CHARACTERS);
        setEscapeCharacters(ob.booleanValue());
    }
}
 
Example #19
Source File: XMLStreamWriterImpl.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Reset this instance so that it can be re-used. Clears but does not
 * re-allocate internal data structures.
 *
 * @param resetProperties Indicates if properties should be read again
 */
void reset(boolean resetProperties) {
    if (!fReuse) {
        throw new java.lang.IllegalStateException(
            "close() Must be called before calling reset()");
    }

    fReuse = false;
    fNamespaceDecls.clear();
    fAttributeCache.clear();

    // reset Element/NamespaceContext stacks
    fElementStack.clear();
    fInternalNamespaceContext.reset();

    fStartTagOpened = false;
    fNamespaceContext.userContext = null;

    if (resetProperties) {
        Boolean ob = (Boolean) fPropertyManager.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
        fIsRepairingNamespace = ob.booleanValue();
        ob = (Boolean) fPropertyManager.getProperty(Constants.ESCAPE_CHARACTERS);
        setEscapeCharacters(ob.booleanValue());
    }
}
 
Example #20
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 #21
Source File: XMLStreamWriterImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Reset this instance so that it can be re-used. Clears but does not
 * re-allocate internal data structures.
 *
 * @param resetProperties Indicates if properties should be read again
 */
void reset(boolean resetProperties) {
    if (!fReuse) {
        throw new java.lang.IllegalStateException(
            "close() Must be called before calling reset()");
    }

    fReuse = false;
    fNamespaceDecls.clear();
    fAttributeCache.clear();

    // reset Element/NamespaceContext stacks
    fElementStack.clear();
    fInternalNamespaceContext.reset();

    fStartTagOpened = false;
    fNamespaceContext.userContext = null;

    if (resetProperties) {
        Boolean ob = (Boolean) fPropertyManager.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
        fIsRepairingNamespace = ob.booleanValue();
        ob = (Boolean) fPropertyManager.getProperty(Constants.ESCAPE_CHARACTERS);
        setEscapeCharacters(ob.booleanValue());
    }
}
 
Example #22
Source File: SurrogatesTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void generateAndReadXml(String content) throws Exception {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    OutputStreamWriter streamWriter = new OutputStreamWriter(stream);
    XMLStreamWriter writer = factory.createXMLStreamWriter(streamWriter);

    // Generate xml with selected stream writer type
    generateXML(writer, content);
    String output = stream.toString();
    System.out.println("Generated xml: " + output);
    // Read generated xml with StAX parser
    readXML(output.getBytes(), content);
}
 
Example #23
Source File: Bug6600882Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test() {
    try {
        XMLOutputFactory of = XMLOutputFactory.newInstance();
        XMLStreamWriter w = of.createXMLStreamWriter(new ByteArrayOutputStream());
        XMLStreamWriter w1 = of.createXMLStreamWriter(new ByteArrayOutputStream());
        System.out.println(w);
        Assert.assertTrue(w.equals(w) && w.hashCode() == w.hashCode());
        Assert.assertFalse(w1.equals(w));
    } catch (Throwable ex) {
        Assert.fail(ex.toString());
    }
}
 
Example #24
Source File: StaxUtilsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void isStaxResult() throws Exception {
	XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
	XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(new StringWriter());
	Result result = StaxUtils.createCustomStaxResult(streamWriter);

	assertTrue("Not a StAX Result", StaxUtils.isStaxResult(result));
}
 
Example #25
Source File: XStreamMarshallerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void marshalStaxResultXMLStreamWriter() throws Exception {
	XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
	StringWriter writer = new StringWriter();
	XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(writer);
	Result result = StaxUtils.createStaxResult(streamWriter);
	marshaller.marshal(flight, result);
	assertThat("Marshaller writes invalid StreamResult", writer.toString(), isSimilarTo(EXPECTED_STRING));
}
 
Example #26
Source File: XMLStreamTestBase.java    From jpx with Apache License 2.0 5 votes vote down vote up
private static <T> byte[] toBytes(final T value, final XMLWriter<T> writer)
	throws XMLStreamException
{
	final ByteArrayOutputStream out = new ByteArrayOutputStream();
	final XMLOutputFactory factory = XMLProvider.provider().xmlOutputFactory();
	final XMLStreamWriter streamWriter = new IndentingXMLStreamWriter(
		factory.createXMLStreamWriter(out, "UTF-8"), "    ");

	writer.write(streamWriter, value);
	return out.toByteArray();
}
 
Example #27
Source File: AbstractMarshallerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void marshalJaxp14StaxResultStreamWriter() throws Exception {
	XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
	StringWriter writer = new StringWriter();
	XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(writer);
	StAXResult result = new StAXResult(streamWriter);
	marshaller.marshal(flights, result);
	assertThat("Marshaller writes invalid StreamResult", writer.toString(), isSimilarTo(EXPECTED_STRING));
}
 
Example #28
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 #29
Source File: StationSubsetWriterXML.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public StationSubsetWriterXML(FeatureDatasetPoint fdPoint, SubsetParams ncssParams, OutputStream out)
    throws XMLStreamException, NcssException, IOException {
  super(fdPoint, ncssParams);

  XMLOutputFactory factory = XMLOutputFactory.newInstance();
  staxWriter = factory.createXMLStreamWriter(out, "UTF-8");
}
 
Example #30
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);
    }
}