Java Code Examples for javax.xml.stream.XMLStreamWriter#writeStartDocument()

The following examples show how to use javax.xml.stream.XMLStreamWriter#writeStartDocument() . 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: XMLCodec.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public ContentType encode(Packet packet, OutputStream out) {
            String encoding = (String) packet.invocationProperties
            .get(XMLConstants.OUTPUT_XML_CHARACTER_ENCODING);

    XMLStreamWriter writer = null;

            if (encoding != null && encoding.length() > 0) {
        writer = XMLStreamWriterFactory.create(out, encoding);
    } else {
        writer = XMLStreamWriterFactory.create(out);
    }

    try {
        if (packet.getMessage().hasPayload()){
            writer.writeStartDocument();
            packet.getMessage().writePayloadTo(writer);
            writer.flush();
        }
    } catch (XMLStreamException e) {
        throw new WebServiceException(e);
    }
    return contentType;
}
 
Example 2
Source File: SurrogatesTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private void generateXML(XMLStreamWriter writer, String sequence)
        throws XMLStreamException {
    char[] seqArr = sequence.toCharArray();
    writer.writeStartDocument();
    writer.writeStartElement("root");

    // Use writeCharacters( String ) to write characters
    writer.writeStartElement("writeCharactersWithString");
    writer.writeCharacters(sequence);
    writer.writeEndElement();

    // Use writeCharacters( char [], int , int ) to write characters
    writer.writeStartElement("writeCharactersWithArray");
    writer.writeCharacters(seqArr, 0, seqArr.length);
    writer.writeEndElement();

    // Close root element and document
    writer.writeEndElement();
    writer.writeEndDocument();
    writer.flush();
    writer.close();
}
 
Example 3
Source File: WadlWriter.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
public static final void writeDocument(final Application app, final Map<String, String> prefixMappings,
        final OutputStream outstream) {
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();
    try {
        final XMLStreamWriter xsw = new IndentingXMLStreamWriter(xof.createXMLStreamWriter(outstream, "UTF-8"));
        xsw.writeStartDocument("UTF-8", "1.0");
        try {
            writeApplication(app, prefixMappings, xsw);
        } finally {
            xsw.writeEndDocument();
        }
        xsw.flush();
    } catch (final XMLStreamException e) {
        throw new WadlRuntimeException(e);
    }
}
 
Example 4
Source File: Bug6846132Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testSAXResult() {
    DefaultHandler handler = new DefaultHandler();

    final String EXPECTED_OUTPUT = "<?xml version=\"1.0\"?><root></root>";
    try {
        SAXResult saxResult = new SAXResult(handler);
        // saxResult.setSystemId("jaxp-ri/unit-test/javax/xml/stream/XMLOutputFactoryTest/cr6846132.xml");
        XMLOutputFactory ofac = XMLOutputFactory.newInstance();
        XMLStreamWriter writer = ofac.createXMLStreamWriter(saxResult);
        writer.writeStartDocument("1.0");
        writer.writeStartElement("root");
        writer.writeEndElement();
        writer.writeEndDocument();
        writer.flush();
        writer.close();
    } catch (Exception e) {
        if (e instanceof UnsupportedOperationException) {
            // expected
        } else {
            e.printStackTrace();
            Assert.fail(e.toString());
        }
    }
}
 
Example 5
Source File: FastInfosetCodec.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public ContentType encode(Packet packet, OutputStream out) {
    Message message = packet.getMessage();
    if (message != null && message.hasPayload()) {
        final XMLStreamWriter writer = getXMLStreamWriter(out);
        try {
            writer.writeStartDocument();
            packet.getMessage().writePayloadTo(writer);
            writer.writeEndDocument();
            writer.flush();
        } catch (XMLStreamException e) {
            throw new WebServiceException(e);
        }
    }

    return _contentType;
}
 
Example 6
Source File: AbstractMessageImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void writeToBodyStart(XMLStreamWriter w) throws XMLStreamException {
    String soapNsUri = soapVersion.nsUri;
    w.writeStartDocument();
    w.writeStartElement("S","Envelope",soapNsUri);
    w.writeNamespace("S",soapNsUri);
    if(hasHeaders()) {
        w.writeStartElement("S","Header",soapNsUri);
        MessageHeaders headers = getHeaders();
        for (Header h : headers.asList()) {
            h.writeTo(w);
        }
        w.writeEndElement();
    }
    // write the body
    w.writeStartElement("S","Body",soapNsUri);
}
 
Example 7
Source File: AbstractMessageImpl.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Default implementation that relies on {@link #writePayloadTo(XMLStreamWriter)}
 */
@Override
public void writeTo(XMLStreamWriter w) throws XMLStreamException {
    String soapNsUri = soapVersion.nsUri;
    w.writeStartDocument();
    w.writeStartElement("S","Envelope",soapNsUri);
    w.writeNamespace("S",soapNsUri);
    if(hasHeaders()) {
        w.writeStartElement("S","Header",soapNsUri);
        MessageHeaders headers = getHeaders();
        for (Header h : headers.asList()) {
            h.writeTo(w);
        }
        w.writeEndElement();
    }
    // write the body
    w.writeStartElement("S","Body",soapNsUri);

    writePayloadTo(w);

    w.writeEndElement();
    w.writeEndElement();
    w.writeEndDocument();
}
 
Example 8
Source File: FastInfosetCodec.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public ContentType encode(Packet packet, OutputStream out) {
    Message message = packet.getMessage();
    if (message != null && message.hasPayload()) {
        final XMLStreamWriter writer = getXMLStreamWriter(out);
        try {
            writer.writeStartDocument();
            packet.getMessage().writePayloadTo(writer);
            writer.writeEndDocument();
            writer.flush();
        } catch (XMLStreamException e) {
            throw new WebServiceException(e);
        }
    }

    return _contentType;
}
 
Example 9
Source File: PseudoRdfXmlWriter.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Write a pseudo RDF XML for the given ontology and gene annotations.
 * 
 * @param stream
 * @param graph the ontology
 * @param gafs (optional) list of gaf documents or null
 * @throws IOException
 */
public void write(OutputStream stream, OWLGraphWrapper graph, List<GafDocument> gafs) throws IOException {
	try {
		XMLStreamWriter writer = createWriter(stream);
		writer.writeStartDocument();
		writer.writeDTD("\n<!DOCTYPE go:go PUBLIC \"-//Gene Ontology//Custom XML/RDF Version 2.0//EN\" \""+GO_RDF_XML_DTD+"\">\n");
		
		writer.writeStartElement("go:go");
		writer.writeNamespace("go", GO_NAMESPACE_URI);
		writer.writeNamespace("rdf", RDF_NAMESPACE_URI);
		
		writer.writeStartElement(RDF_NAMESPACE_URI, "RDF");
		
		writeTerms(writer, graph, gafs);
		
		writer.writeEndElement(); // RDF
		writer.writeEndElement(); // go:go
		
		writer.writeEndDocument();
		writer.flush();
	} catch (XMLStreamException e) {
		throw new IOException(e);
	}
}
 
Example 10
Source File: FastInfosetCodec.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public ContentType encode(Packet packet, OutputStream out) {
    Message message = packet.getMessage();
    if (message != null && message.hasPayload()) {
        final XMLStreamWriter writer = getXMLStreamWriter(out);
        try {
            writer.writeStartDocument();
            packet.getMessage().writePayloadTo(writer);
            writer.writeEndDocument();
            writer.flush();
        } catch (XMLStreamException e) {
            throw new WebServiceException(e);
        }
    }

    return _contentType;
}
 
Example 11
Source File: SurrogatesTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private void generateXML(XMLStreamWriter writer, String sequence)
        throws XMLStreamException {
    char[] seqArr = sequence.toCharArray();
    writer.writeStartDocument();
    writer.writeStartElement("root");

    // Use writeCharacters( String ) to write characters
    writer.writeStartElement("writeCharactersWithString");
    writer.writeCharacters(sequence);
    writer.writeEndElement();

    // Use writeCharacters( char [], int , int ) to write characters
    writer.writeStartElement("writeCharactersWithArray");
    writer.writeCharacters(seqArr, 0, seqArr.length);
    writer.writeEndElement();

    // Close root element and document
    writer.writeEndElement();
    writer.writeEndDocument();
    writer.flush();
    writer.close();
}
 
Example 12
Source File: OdsWritter.java    From SODS with Apache License 2.0 5 votes vote down vote up
private void writeSpreadsheet() throws UnsupportedEncodingException, XMLStreamException {
    ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
    XMLStreamWriter out = XMLOutputFactory.newInstance().createXMLStreamWriter(
            new OutputStreamWriter(output, "utf-8"));

    out.writeStartDocument("UTF-8", "1.0");
    out.writeStartElement( "office:document-content");
    out.writeAttribute("xmlns:office", office);
    out.writeAttribute("xmlns:table", table_namespace);
    out.writeAttribute("xmlns:text",text_namespace);
    out.writeAttribute("xmlns:fo",font_namespace);
    out.writeAttribute("xmlns:style", style_namespace);
    out.writeAttribute("xmlns:dc", metadata_namespace);

    out.writeAttribute("office:version", "1.2");

    writeStyles(out);
    writeContent(out);

    out.writeEndElement();
    out.writeEndDocument();
    out.close();

    try {
        this.out.addEntry(output.toByteArray(),"content.xml");
    } catch (IOException e) {
        throw new GenerateOdsException(e);
    }
}
 
Example 13
Source File: PropertiesModuleConfigRepository.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
public static void writeXml(Path configDir, Path xmlFile) throws IOException, XMLStreamException {
    XMLOutputFactory output = XMLOutputFactory.newInstance();
    try (Writer writer = Files.newBufferedWriter(xmlFile, StandardCharsets.UTF_8)) {
        XMLStreamWriter xmlWriter = output.createXMLStreamWriter(writer);
        try {
            xmlWriter.writeStartDocument(StandardCharsets.UTF_8.toString(), "1.0");
            xmlWriter.writeStartElement("config");
            try (DirectoryStream<Path> ds = Files.newDirectoryStream(configDir, entry -> Files.isRegularFile(entry) && entry.getFileName().toString().endsWith(".properties"))) {
                for (Path file : ds) {
                    String fileName = file.getFileName().toString();
                    String fileNameWithoutExtension = fileName.substring(0, fileName.length() - 11);
                    xmlWriter.writeStartElement(fileNameWithoutExtension);
                    Properties properties = new Properties();
                    try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
                        properties.load(reader);
                    }
                    for (String name : properties.stringPropertyNames()) {
                        String value = properties.getProperty(name);
                        xmlWriter.writeStartElement(name);
                        xmlWriter.writeCharacters(value);
                        xmlWriter.writeEndElement();
                    }
                    xmlWriter.writeEndElement();
                }
            }
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();
        } finally {
            xmlWriter.close();
        }
    }
}
 
Example 14
Source File: XmlErrorDocumentProducer.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
public void writeErrorDocument(final XMLStreamWriter writer, final String errorCode, final String message,
    final Locale locale, final String innerError) throws XMLStreamException {
  writer.writeStartDocument();
  writer.writeStartElement(FormatXml.M_ERROR);
  writer.writeDefaultNamespace(Edm.NAMESPACE_M_2007_08);
  writer.writeStartElement(FormatXml.M_CODE);
  if (errorCode != null) {
    writer.writeCharacters(errorCode);
  }
  writer.writeEndElement();
  writer.writeStartElement(FormatXml.M_MESSAGE);
  if (locale != null) {
    writer.writeAttribute(Edm.PREFIX_XML, Edm.NAMESPACE_XML_1998, FormatXml.XML_LANG, getLocale(locale));
  } else {
    writer.writeAttribute(Edm.PREFIX_XML, Edm.NAMESPACE_XML_1998, FormatXml.XML_LANG, "");
  }
  if (message != null) {
    writer.writeCharacters(message);
  }
  writer.writeEndElement();

  if (innerError != null) {
    writer.writeStartElement(FormatXml.M_INNER_ERROR);
    writer.writeCharacters(innerError);
    writer.writeEndElement();
  }

  writer.writeEndDocument();
}
 
Example 15
Source File: TransientSecurityIndex.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void toXml(XMLStreamWriter xmlWriter) throws XMLStreamException {
    xmlWriter.writeStartDocument();
    xmlWriter.writeStartElement("index");
    xmlWriter.writeAttribute("name", XML_NAME);
    xmlWriter.writeStartElement("j");
    xmlWriter.writeCharacters(Double.toString(j));
    xmlWriter.writeEndElement();
    xmlWriter.writeEndElement();
    xmlWriter.writeEndDocument();
}
 
Example 16
Source File: SAAJMessage.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public void writeTo(XMLStreamWriter writer) throws XMLStreamException {
    try {
        writer.writeStartDocument();
        if (!parsedMessage) {
            DOMUtil.serializeNode(sm.getSOAPPart().getEnvelope(), writer);
        } else {
            SOAPEnvelope env = sm.getSOAPPart().getEnvelope();
            DOMUtil.writeTagWithAttributes(env, writer);
            if (hasHeaders()) {
                if(env.getHeader() != null) {
                    DOMUtil.writeTagWithAttributes(env.getHeader(), writer);
                } else {
                    writer.writeStartElement(env.getPrefix(), "Header", env.getNamespaceURI());
                }
                for (Header h : headers.asList()) {
                    h.writeTo(writer);
                }
                writer.writeEndElement();
            }

            DOMUtil.serializeNode(sm.getSOAPBody(), writer);
            writer.writeEndElement();
        }
        writer.writeEndDocument();
        writer.flush();
    } catch (SOAPException ex) {
        throw new XMLStreamException2(ex);
        //for now. ask jaxws team what to do.
    }
}
 
Example 17
Source File: NamespaceTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private void startDocument(XMLStreamWriter xmlStreamWriter) throws XMLStreamException {
    xmlStreamWriter.writeStartDocument();
    xmlStreamWriter.writeStartElement("root");
}
 
Example 18
Source File: XgmmlWriter.java    From owltools with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Write a pseudo RDF XML for the given ontology and gene annotations.
 * 
 * @param stream
 * @param graph the ontology
 * @param gafs (optional) list of gaf documents or null
 * @throws IOException
 */
public void write(OutputStream stream, OWLGraphWrapper graph, List<GafDocument> gafs) throws IOException {
	try {
		XMLStreamWriter writer = createWriter(stream);
		writer.writeStartDocument();

		writer.writeStartElement("graph");
		writer.writeAttribute("id","1");
		writer.writeAttribute("label","test");


		//xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		//xmlns:ns1="http://www.w3.org/1999/xlink" 
		//xmlns:dc="http://purl.org/dc/elements/1.1/" 
		//xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" 
		//xmlns="http://www.cs.rpi.edu/XGMML"

		writer.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
		writer.writeNamespace("ns1", "http://www.w3.org/1999/xlink");
		writer.writeNamespace("dc", DC);
		writer.writeNamespace("rdf", RDF_NAMESPACE_URI);
		writer.writeNamespace("", "http://www.cs.rpi.edu/XGMML");

		/*
		writer.writeStartElement("att");
		writer.writeAttribute("name","networkMetadata");


		writer.writeStartElement(RDF_NAMESPACE_URI, "RDF");
		writer.writeStartElement(RDF_NAMESPACE_URI, "Description");
		writer.writeAttribute(RDF_NAMESPACE_URI,"about",graph.getSourceOntology().getOntologyID().getOntologyIRI().get().toString());
		writeTag(writer, DC, "type", "ontology");
		writeTag(writer, DC, "format", "Cytoscape-XGMML");
		writer.writeEndElement(); // Description		

		writer.writeEndElement(); // RDF
		writer.writeEndElement(); // att
		 */
		// TODO <att value="#eeffcc" name="backgroundColor"/>
		writeNodes(writer, graph, gafs);
		writeEdges(writer, graph, gafs);
		//			writeEdges();

		writer.writeEndElement(); // graph

		writer.writeEndDocument();
		writer.flush();
	} catch (XMLStreamException e) {
		throw new IOException(e);
	}
}
 
Example 19
Source File: StaxOutInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("resource")
public void handleMessage(Message message) {
    OutputStream os = message.getContent(OutputStream.class);
    XMLStreamWriter xwriter = message.getContent(XMLStreamWriter.class);
    Writer writer = null;
    if (os == null) {
        writer = message.getContent(Writer.class);
    }
    if ((os == null && writer == null) || xwriter != null) {
        return;
    }

    String encoding = getEncoding(message);

    try {
        XMLOutputFactory factory = getXMLOutputFactory(message);
        if (factory == null) {
            if (writer == null) {
                os = setupOutputStream(os);
                xwriter = StaxUtils.createXMLStreamWriter(os, encoding);
            } else {
                xwriter = StaxUtils.createXMLStreamWriter(writer);
            }
        } else {
            if (PropertyUtils.isTrue(message.getContextualProperty(Message.THREAD_SAFE_STAX_FACTORIES))) {
                if (writer == null) {
                    os = setupOutputStream(os);
                    xwriter = factory.createXMLStreamWriter(os, encoding);
                } else {
                    xwriter = factory.createXMLStreamWriter(writer);
                }
            } else {
                synchronized (factory) {
                    if (writer == null) {
                        os = setupOutputStream(os);
                        xwriter = factory.createXMLStreamWriter(os, encoding);
                    } else {
                        xwriter = factory.createXMLStreamWriter(writer);
                    }
                }
            }
        }
        if (MessageUtils.getContextualBoolean(message, FORCE_START_DOCUMENT, false)) {
            xwriter.writeStartDocument(encoding, "1.0");
            message.removeContent(OutputStream.class);
            message.put(OUTPUT_STREAM_HOLDER, os);
            message.removeContent(Writer.class);
            message.put(WRITER_HOLDER, writer);
        }
    } catch (XMLStreamException e) {
        throw new Fault(new org.apache.cxf.common.i18n.Message("STREAM_CREATE_EXC", BUNDLE), e);
    }
    message.setContent(XMLStreamWriter.class, xwriter);

    // Add a final interceptor to write end elements
    message.getInterceptorChain().add(ENDING);
}
 
Example 20
Source File: ExpressionTestCase.java    From ironjacamar with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Write
 * @throws Exception In case of an error
 */
@Ignore
public void testWrite() throws Exception
{
   IronJacamarParser parser = new IronJacamarParser();

   InputStream is = ExpressionTestCase.class.getClassLoader().
      getResourceAsStream("../../resources/test/ironjacamar/expression.xml");
   assertNotNull(is);

   StringBuilder sb = new StringBuilder();
   BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
   String line = br.readLine();
   while (line != null)
   {
      String data = line.trim();
      sb.append(data);
      if (!data.equals("") && !data.endsWith(">"))
         sb.append(" ");
      line = br.readLine();
   }

   is.close();

   is = ExpressionTestCase.class.getClassLoader().
      getResourceAsStream("../../resources/test/ironjacamar/expression.xml");
   assertNotNull(is);
   
   XMLStreamReader xsr = XMLInputFactory.newInstance().createXMLStreamReader(is);

   Activation a = parser.parse(xsr);
   assertNotNull(a);

   is.close();

   StringWriter sw = new StringWriter();
   XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(sw);
   xsw.setDefaultNamespace("");

   xsw.writeStartDocument("UTF-8", "1.0");
   parser.store(a, xsw);
   xsw.writeEndDocument();

   xsw.flush();
   xsw.close();

   assertEquals(sb.toString(), sw.toString());
}