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

The following examples show how to use javax.xml.stream.XMLStreamWriter#writeEndDocument() . 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: 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 2
Source File: TsoOvervoltageSecurityIndex.java    From powsybl-core with Mozilla Public License 2.0 6 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("computation-succeed");
    xmlWriter.writeCharacters(Boolean.toString(computationSucceed));
    xmlWriter.writeEndElement();

    xmlWriter.writeStartElement("overvoltage-count");
    xmlWriter.writeCharacters(Integer.toString(overvoltageCount));
    xmlWriter.writeEndElement();

    xmlWriter.writeEndElement();
    xmlWriter.writeEndDocument();
}
 
Example 3
Source File: UnprefixedNameTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testUnboundPrefix() throws Exception {

    try {
        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        XMLStreamWriter w = xof.createXMLStreamWriter(System.out);
        // here I'm trying to write
        // <bar xmlns="foo" />
        w.writeStartDocument();
        w.writeStartElement("foo", "bar");
        w.writeDefaultNamespace("foo");
        w.writeCharacters("---");
        w.writeEndElement();
        w.writeEndDocument();
        w.close();

        // Unexpected success
        String FAIL_MSG = "Unexpected success.  Expected: " + "XMLStreamException - " + "if the namespace URI has not been bound to a prefix "
                + "and javax.xml.stream.isPrefixDefaulting has not been " + "set to true";
        System.err.println(FAIL_MSG);
        Assert.fail(FAIL_MSG);
    } catch (XMLStreamException xmlStreamException) {
        // Expected Exception
        System.out.println("Expected XMLStreamException: " + xmlStreamException.toString());
    }
}
 
Example 4
Source File: XmlSecOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message mc) throws Fault {
    try {
        XMLStreamWriter xtw = mc.getContent(XMLStreamWriter.class);
        if (xtw != null) {
            xtw.writeEndDocument();
            xtw.flush();
            xtw.close();
        }

        OutputStream os = (OutputStream) mc.get(OUTPUT_STREAM_HOLDER);
        if (os != null) {
            mc.setContent(OutputStream.class, os);
        }
        mc.removeContent(XMLStreamWriter.class);
    } catch (XMLStreamException e) {
        throw new Fault(e);
    }
}
 
Example 5
Source File: FastInfosetCodec.java    From openjdk-8-source 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: WSS4JStaxOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void handleMessageInternal(Message mc) throws Fault {
    try {
        XMLStreamWriter xtw = mc.getContent(XMLStreamWriter.class);
        if (xtw != null) {
            xtw.writeEndDocument();
            xtw.flush();
            xtw.close();
        }

        OutputStream os = (OutputStream) mc.get(OUTPUT_STREAM_HOLDER);
        if (os != null) {
            mc.setContent(OutputStream.class, os);
        }
        mc.removeContent(XMLStreamWriter.class);
    } catch (XMLStreamException e) {
        throw new Fault(e);
    }
}
 
Example 7
Source File: FastInfosetCodec.java    From jdk8u60 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 8
Source File: TsoOverloadSecurityIndex.java    From powsybl-core with Mozilla Public License 2.0 6 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("computation-succeed");
    xmlWriter.writeCharacters(Boolean.toString(computationSucceed));
    xmlWriter.writeEndElement();

    xmlWriter.writeStartElement("overload-count");
    xmlWriter.writeCharacters(Integer.toString(overloadCount));
    xmlWriter.writeEndElement();

    for (String overloadedBranch : overloadedBranches) {
        xmlWriter.writeStartElement("overloaded-branch");
        xmlWriter.writeCharacters(overloadedBranch);
        xmlWriter.writeEndElement();
    }

    xmlWriter.writeEndElement();
    xmlWriter.writeEndDocument();
}
 
Example 9
Source File: FastInfosetCodec.java    From openjdk-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 10
Source File: SurrogatesTest.java    From openjdk-jdk8u 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 11
Source File: MapFileGenerator.java    From mpxj with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Generate an IKVM map file.
 *
 * @param mapFileName map file name
 * @param jarFile jar file containing code to be mapped
 * @param mapClassMethods true if we want to produce .Net style class method names
 * @throws IOException
 * @throws XMLStreamException
 * @throws ClassNotFoundException
 * @throws IntrospectionException
 */
private void writeMapFile(String mapFileName, File jarFile, boolean mapClassMethods) throws IOException, XMLStreamException, ClassNotFoundException, IntrospectionException
{
   FileWriter fw = new FileWriter(mapFileName);
   XMLOutputFactory xof = XMLOutputFactory.newInstance();
   XMLStreamWriter writer = xof.createXMLStreamWriter(fw);
   //XMLStreamWriter writer = new IndentingXMLStreamWriter(xof.createXMLStreamWriter(fw));

   writer.writeStartDocument();
   writer.writeStartElement("root");
   writer.writeStartElement("assembly");

   addClasses(writer, jarFile, mapClassMethods);

   writer.writeEndElement();
   writer.writeEndElement();
   writer.writeEndDocument();
   writer.flush();
   writer.close();

   fw.flush();
   fw.close();
}
 
Example 12
Source File: XMLConfig.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
/** @param model {@link EngineModel}
 *  @param file File to write with information from model
 *  @throws Exception on error
 */
public void write(final EngineModel model, final File file) throws Exception
{
    final XMLStreamWriter base =
            XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream(file), XMLUtil.ENCODING);
    final XMLStreamWriter writer = new IndentingXMLStreamWriter(base);
    writer.writeStartDocument(XMLUtil.ENCODING, "1.0");
    writer.writeStartElement(ENGINECONFIG);
    {
        for (int g=0; g<model.getGroupCount(); ++g)
            write(model, writer, model.getGroup(g));
    }
    writer.writeEndElement();
    writer.writeEndDocument();
    writer.flush();
    writer.close();
}
 
Example 13
Source File: TsoFrequencySecurityIndex.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("freq-out-count");
    xmlWriter.writeCharacters(Integer.toString(freqOutCount));
    xmlWriter.writeEndElement();
    xmlWriter.writeEndElement();
    xmlWriter.writeEndDocument();
}
 
Example 14
Source File: OverloadSecurityIndex.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("fx");
    xmlWriter.writeCharacters(Double.toString(indexValue));
    xmlWriter.writeEndElement();
    xmlWriter.writeEndElement();
    xmlWriter.writeEndDocument();
}
 
Example 15
Source File: EncodingTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testWriteStartDocumentUTF8Fail() {

    XMLStreamWriter writer = null;
    ByteArrayOutputStream byteArrayOutputStream = null;

    // pick a different encoding to use v. default encoding
    String defaultCharset = java.nio.charset.Charset.defaultCharset().name();
    String useCharset = "UTF-8";
    if (useCharset.equals(defaultCharset)) {
        useCharset = "US-ASCII";
    }

    System.out.println("defaultCharset = " + defaultCharset + ", useCharset = " + useCharset);

    try {
        byteArrayOutputStream = new ByteArrayOutputStream();
        writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(byteArrayOutputStream);

        writer.writeStartDocument(useCharset, "1.0");
        writer.writeStartElement("root");
        writer.writeEndElement();
        writer.writeEndDocument();
        writer.flush();

        Assert.fail("Expected XMLStreamException as default underlying stream encoding of " + defaultCharset
                + " differs from explicitly specified encoding of " + useCharset);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 16
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 17
Source File: AbstractFaultSoapPayloadConverter.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public void process(Exchange exchange) {
    final Exception exception = (Exception) exchange.getProperty(Exchange.EXCEPTION_CAUGHT);
    if (exception instanceof SoapFault) {

        SoapFault soapFault = (SoapFault) exception;
        final Message in = exchange.getIn();

        // get SOAP QNames from CxfPayload headers
        final SoapMessage soapMessage = in.getHeader("CamelCxfMessage", SoapMessage.class);
        final SoapVersion soapVersion = soapMessage.getVersion();

        try {

            // get CxfPayload body
            final CxfPayload<?> cxfPayload = in.getMandatoryBody(CxfPayload.class);

            final OutputStream outputStream = newOutputStream(in, cxfPayload);
            final XMLStreamWriter writer = newXmlStreamWriter(outputStream);

            handleFault(writer, soapFault, soapVersion);
            writer.writeEndDocument();

            final InputStream inputStream = getInputStream(outputStream, writer);

            // set the input stream as the Camel message body
            in.setBody(inputStream);

        } catch (InvalidPayloadException | XMLStreamException | IOException e) {
            throw new RuntimeCamelException("Error parsing CXF Payload: " + e.getMessage(), e);
        }
    }
}
 
Example 18
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 19
Source File: SoapFaultSerializerTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testSoap12Out() throws Exception {
    String faultString = "Hadrian caused this Fault!";
    SoapFault fault = new SoapFault(faultString, Soap12.getInstance().getSender());

    QName qname = new QName("http://cxf.apache.org/soap/fault", "invalidsoap", "cxffaultcode");
    fault.setSubCode(qname);

    SoapMessage m = new SoapMessage(new MessageImpl());
    m.setVersion(Soap12.getInstance());

    m.setContent(Exception.class, fault);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(out);
    writer.writeStartDocument();
    writer.writeStartElement("Body");

    m.setContent(XMLStreamWriter.class, writer);

    Soap12FaultOutInterceptorInternal.INSTANCE.handleMessage(m);

    writer.writeEndElement();
    writer.writeEndDocument();
    writer.close();

    Document faultDoc = StaxUtils.read(new ByteArrayInputStream(out.toByteArray()));

    assertValid("//soap12env:Fault/soap12env:Code/soap12env:Value[text()='ns1:Sender']",
                faultDoc);
    assertValid("//soap12env:Fault/soap12env:Code/soap12env:Subcode/"
                + "soap12env:Value[text()='cxffaultcode:invalidsoap']",
                faultDoc);
    assertValid("//soap12env:Fault/soap12env:Reason/soap12env:Text[@xml:lang='en']",
                faultDoc);
    assertValid("//soap12env:Fault/soap12env:Reason/soap12env:Text[text()='" + faultString + "']",
                faultDoc);

    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(out.toByteArray()));
    m.setContent(XMLStreamReader.class, reader);

    reader.nextTag();

    Soap12FaultInInterceptor inInterceptor = new Soap12FaultInInterceptor();
    inInterceptor.handleMessage(m);

    SoapFault fault2 = (SoapFault)m.getContent(Exception.class);
    assertNotNull(fault2);
    assertEquals(Soap12.getInstance().getSender(), fault2.getFaultCode());
    assertEquals(fault.getMessage(), fault2.getMessage());
    assertEquals(fault.getSubCode(), fault2.getSubCode());
}
 
Example 20
Source File: StaxUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static void writeEvent(XMLEvent event, XMLStreamWriter writer)
    throws XMLStreamException {

    switch (event.getEventType()) {
    case XMLStreamConstants.START_ELEMENT:
        writeStartElementEvent(event, writer);
        break;
    case XMLStreamConstants.END_ELEMENT:
        writer.writeEndElement();
        break;
    case XMLStreamConstants.ATTRIBUTE:
        writeAttributeEvent(event, writer);
        break;
    case XMLStreamConstants.ENTITY_REFERENCE:
        writer.writeEntityRef(((javax.xml.stream.events.EntityReference)event).getName());
        break;
    case XMLStreamConstants.DTD:
        writer.writeDTD(((DTD)event).getDocumentTypeDeclaration());
        break;
    case XMLStreamConstants.PROCESSING_INSTRUCTION:
        if (((javax.xml.stream.events.ProcessingInstruction)event).getData() != null) {
            writer.writeProcessingInstruction(
                ((javax.xml.stream.events.ProcessingInstruction)event).getTarget(),
                ((javax.xml.stream.events.ProcessingInstruction)event).getData());
        } else {
            writer.writeProcessingInstruction(
                ((javax.xml.stream.events.ProcessingInstruction)event).getTarget());
        }
        break;
    case XMLStreamConstants.NAMESPACE:
        if (((Namespace)event).isDefaultNamespaceDeclaration()) {
            writer.writeDefaultNamespace(((Namespace)event).getNamespaceURI());
            writer.setDefaultNamespace(((Namespace)event).getNamespaceURI());
        } else {
            writer.writeNamespace(((Namespace)event).getPrefix(),
                                  ((Namespace)event).getNamespaceURI());
            writer.setPrefix(((Namespace)event).getPrefix(),
                             ((Namespace)event).getNamespaceURI());
        }
        break;
    case XMLStreamConstants.COMMENT:
        writer.writeComment(((javax.xml.stream.events.Comment)event).getText());
        break;
    case XMLStreamConstants.CHARACTERS:
    case XMLStreamConstants.SPACE:
        writer.writeCharacters(event.asCharacters().getData());
        break;
    case XMLStreamConstants.CDATA:
        writer.writeCData(event.asCharacters().getData());
        break;
    case XMLStreamConstants.START_DOCUMENT:
        if (((StartDocument)event).encodingSet()) {
            writer.writeStartDocument(((StartDocument)event).getCharacterEncodingScheme(),
                                      ((StartDocument)event).getVersion());

        } else {
            writer.writeStartDocument(((StartDocument)event).getVersion());
        }
        break;
    case XMLStreamConstants.END_DOCUMENT:
        writer.writeEndDocument();
        break;
    default:
        //shouldn't get here
    }
}