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

The following examples show how to use javax.xml.stream.XMLStreamWriter#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: 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 2
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 3
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 4
Source File: EPRHeader.java    From openjdk-8-source 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 5
Source File: SoapOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(SoapMessage message) throws Fault {
    try {
        XMLStreamWriter xtw = message.getContent(XMLStreamWriter.class);
        if (xtw != null) {
            // Write body end
            xtw.writeEndElement();
            // Write Envelope end element
            xtw.writeEndElement();
            xtw.writeEndDocument();

            xtw.flush();
        }
    } catch (XMLStreamException e) {
        if (e.getCause() instanceof EOFException) {
            //Nothing we can do about this, some clients will close the connection early if
            //they fully parse everything they need
        } else {
            SoapVersion soapVersion = message.getVersion();
            throw new SoapFault(new org.apache.cxf.common.i18n.Message("XML_WRITE_EXC", BUNDLE), e,
                                soapVersion.getSender());
        }
    }
}
 
Example 6
Source File: SurrogatesTest.java    From openjdk-jdk8u-backup 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 7
Source File: EPRHeader.java    From openjdk-8 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 8
Source File: SignatureConfirmationTest.java    From steady with Apache License 2.0 5 votes vote down vote up
private byte[] getMessageBytes(Document doc) throws Exception {
    // XMLOutputFactory factory = XMLOutputFactory.newInstance();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    // XMLStreamWriter byteArrayWriter =
    // factory.createXMLStreamWriter(outputStream);
    XMLStreamWriter byteArrayWriter = StaxUtils.createXMLStreamWriter(outputStream);

    StaxUtils.writeDocument(doc, byteArrayWriter, false);

    byteArrayWriter.flush();
    return outputStream.toByteArray();
}
 
Example 9
Source File: SAAJMessage.java    From openjdk-8-source 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 10
Source File: ExpressionStoreTestCase.java    From ironjacamar with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Test stored values changed by environment variables
 *  
 */
@Test
public void testStoreEnvVariables()
{
   System.setProperty("Property2", "Value2");
   System.setProperty("driver-class1", "org1");
   System.setProperty("driver-class2", "sqldb");
   System.setProperty("driver-class3", "jdbcDriver2");
   System.setProperty("reauth-plugin-prop2b", "Value2");
   System.setProperty("ConfigProp123", "Value123");
   System.setProperty("enabled", "false");
   System.setProperty("initial-pool-size", "3");
   
   try (InputStream is = ExpressionStoreTestCase.class.getClassLoader().
         getResourceAsStream("../../resources/test/ds/expression.xml");
         ByteArrayOutputStream os = new ByteArrayOutputStream())
   {
      assertNotNull(is);

      XMLStreamReader xsr = XMLInputFactory.newInstance().createXMLStreamReader(is);

      DsParser parser = new DsParser();
      DataSources ds =  parser.parse(xsr);
      assertNotNull(ds);
      
      XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(os);
      
      assertNotNull(ds.getDataSource());
      
      DataSource datasource = ds.getDataSource().get(0);
      assertNotNull(datasource);
      parser.store(ds, writer);
      
      writer.flush();
      writer.close();
   
      Document document =  DocumentBuilderFactory.newInstance().newDocumentBuilder()
            .parse(new ByteArrayInputStream(os.toByteArray()));
      
      XPath xPath =  XPathFactory.newInstance().newXPath();
      
      //Test simple expression without default value 
      test(document, xPath, "/datasources/xa-datasource[1]/url-delimiter",
            "${url-delimiter}");
      
      //Test simple expression with an empty default value 
      test(document, xPath, "/datasources/xa-datasource[1]/url-property",
            "${url-property:}");

      //Test simple expression with default value, default value was not changed 
      test(document, xPath, "/datasources/datasource[1]/connection-property[@name='name1']",
            "${Property1:Property1}");

      //Test with no expression
      test(document, xPath, "/datasources/datasource[1]/security/reauth-plugin/config-property[@name='name1']",
            "ConfigProp123");

      //Test simple expression with default value, value is changed
      test(document, xPath, "/datasources/datasource[1]/connection-property[@name='name2']",
            "${Property2:Value2}");
  
         // complex expression, values are set
      test(document, xPath, "/datasources/datasource[1]/driver-class",
            "${driver-class1:org1}.${driver-class2:sqldb}.${driver-class3:jdbcDriver2}");

      // nested expression, value is set
      test(document, xPath, "/datasources/datasource[1]/security/reauth-plugin/config-property[@name='name2']",
            "${reauth-plugin-prop2a:${reauth-plugin-prop2b:Value2}}");

      //Test simple expression with boolean default value, value is changed
      test(document, xPath, "/datasources/xa-datasource[1]/@enabled",
            "${enabled:false}");
      
      //Test simple expression with integer default value, value is not changed
      test(document, xPath, "/datasources/xa-datasource[1]/xa-pool/min-pool-size",
            "${min-pool-size:1}");
      
      //Test simple expression with integer default value, value is changed
      test(document, xPath, "/datasources/xa-datasource[1]/xa-pool/initial-pool-size",
            "${initial-pool-size:3}");

   }
   catch (Exception e)
   {
      fail("Exception thrown: " + e.getMessage());
   }
   finally
   {
      System.clearProperty("Property2");
      System.clearProperty("driver-class1");
      System.clearProperty("driver-class2");
      System.clearProperty("driver-class3");
      System.clearProperty("reauth-plugin-prop2b");
      System.clearProperty("ConfigProp123");
      System.clearProperty("enabled");
      System.clearProperty("initial-pool-size");
   }      
}
 
Example 11
Source File: DataBindingProvider.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void writeToWriter(XMLStreamWriter writer, Object o) throws Exception {
    DataWriter<XMLStreamWriter> dataWriter = binding.createWriter(XMLStreamWriter.class);
    dataWriter.write(o, writer);
    writer.flush();
}
 
Example 12
Source File: JkPomTemplateGenerator.java    From jeka with Apache License 2.0 4 votes vote down vote up
private static String extraXml(JkPomMetadata publicationInfo)
        throws XMLStreamException, FactoryConfigurationError {
    final StringWriter stringWriter = new StringWriter();
    final XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(
            stringWriter);
    final JkProjectInfo projectInfo = publicationInfo.getProjectInfo();
    if (projectInfo != null) {
        writeElement("  ", writer, "name", projectInfo.getName());
        writeElement("  ", writer, "description", projectInfo.getDescription());
        writeElement("  ", writer, "url", projectInfo.getUrl());
    }
    final List<JkLicenseInfo> licenses = publicationInfo.getLicenses();
    if (!licenses.isEmpty()) {
        writer.writeCharacters("\n");
        writer.writeCharacters("  ");
        writer.writeStartElement("licenses");
        for (final JkLicenseInfo license : licenses) {
            writer.writeCharacters("\n    ");
            writer.writeStartElement("license");
            writer.writeCharacters("\n");
            writeElement("      ", writer, "name", license.getName());
            writeElement("      ", writer, "url", license.getUrl());
            writer.writeCharacters("    ");
            writer.writeEndElement();
        }
        writer.writeCharacters("\n  ");
        writer.writeEndElement();
    }
    final List<JkDeveloperInfo> developers = publicationInfo.getDevelopers();
    if (!developers.isEmpty()) {
        writer.writeCharacters("\n\n");
        writer.writeCharacters("  ");
        writer.writeStartElement("developers");
        for (final JkDeveloperInfo developer : developers) {
            writer.writeCharacters("\n    ");
            writer.writeStartElement("developer");
            writer.writeCharacters("\n");
            writeElement("      ", writer, "name", developer.getName());
            writeElement("      ", writer, "email", developer.getEmail());
            writeElement("      ", writer, "organization", developer.getOrganisation());
            writeElement("      ", writer, "organizationUrl", developer.getOrganisationUrl());
            writer.writeCharacters("    ");
            writer.writeEndElement();
        }
        writer.writeCharacters("\n  ");
        writer.writeEndElement();
    }
    final JkScmInfo scm = publicationInfo.getScm();
    if (scm != null) {
        writer.writeCharacters("\n\n  ");
        writer.writeStartElement("scm");
        writer.writeCharacters("\n");
        writeElement("    ", writer, "connection", scm.getConnection());
        writeElement("    ", writer, "developerConnection", scm.getDeveloperConnection());
        writeElement("    ", writer, "url", scm.getUrl());
        writer.writeCharacters("  ");
        writer.writeEndElement();
    }

    writer.flush();
    writer.close();
    return stringWriter.toString();
}
 
Example 13
Source File: JavaToProcessorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testTransientMessage() throws Exception {
    //CXF-5744
    env.put(ToolConstants.CFG_OUTPUTFILE, output.getPath() + "/transient_message.wsdl");
    env.put(ToolConstants.CFG_CLASSNAME, "org.apache.cxf.tools.fortest.exception.Echo4");
    env.put(ToolConstants.CFG_VERBOSE, ToolConstants.CFG_VERBOSE);
    try {
        processor.setEnvironment(env);
        processor.process();
    } catch (Exception e) {
        e.printStackTrace();
    }

    File wsdlFile = new File(output, "transient_message.wsdl");
    assertTrue(wsdlFile.exists());

    Document doc = StaxUtils.read(wsdlFile);
    //StaxUtils.print(doc);
    Map<String, String> map = new HashMap<>();
    map.put("xsd", "http://www.w3.org/2001/XMLSchema");
    map.put("wsdl", "http://schemas.xmlsoap.org/wsdl/");
    map.put("soap", "http://schemas.xmlsoap.org/wsdl/soap/");
    map.put("tns", "http://cxf.apache.org/test/HelloService");
    XPathUtils util = new XPathUtils(map);

    String path = "//xsd:complexType[@name='TransientMessageException']//xsd:sequence/xsd:element[@name='message']";
    Element nd = (Element)util.getValueNode(path, doc);
    assertNull(nd);

    //ok, we didn't map it into the schema.  Make sure the runtime won't write it out.
    List<ServiceInfo> sl = CastUtils.cast((List<?>)env.get("serviceList"));
    FaultInfo mi = sl.get(0).getInterface().getOperation(new QName("http://cxf.apache.org/test/HelloService",
                                                                   "echo"))
        .getFault(new QName("http://cxf.apache.org/test/HelloService",
                            "TransientMessageException"));
    MessagePartInfo mpi = mi.getMessagePart(0);
    JAXBContext ctx = JAXBContext.newInstance(String.class, Integer.TYPE);
    StringWriter sw = new StringWriter();
    XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(sw);
    TransientMessageException tme = new TransientMessageException(12, "Exception Message");
    Marshaller ms = ctx.createMarshaller();
    ms.setProperty(Marshaller.JAXB_FRAGMENT, true);
    JAXBEncoderDecoder.marshallException(ms, tme, mpi, writer);
    writer.flush();
    writer.close();
    assertEquals(-1, sw.getBuffer().indexOf("Exception Message"));
}
 
Example 14
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 15
Source File: XMLMessageOutInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    BindingOperationInfo boi = message.getExchange().getBindingOperationInfo();
    MessageInfo mi;
    BindingMessageInfo bmi;
    if (isRequestor(message)) {
        mi = boi.getOperationInfo().getInput();
        bmi = boi.getInput();
    } else {
        mi = boi.getOperationInfo().getOutput();
        bmi = boi.getOutput();
    }
    XMLBindingMessageFormat xmf = bmi.getExtensor(XMLBindingMessageFormat.class);
    QName rootInModel = null;
    if (xmf != null) {
        rootInModel = xmf.getRootNode();
    }
    final int mpn = mi.getMessagePartsNumber();
    if (boi.isUnwrapped()
        || mpn == 1) {
        // wrapper out interceptor created the wrapper
        // or if bare-one-param
        new BareOutInterceptor().handleMessage(message);
    } else {
        if (rootInModel == null) {
            rootInModel = boi.getName();
        }
        if (mpn == 0 && !boi.isUnwrapped()) {
            // write empty operation qname
            writeMessage(message, rootInModel, false);
        } else {
            // multi param, bare mode, needs write root node
            writeMessage(message, rootInModel, true);
        }
    }
    // in the end we do flush ;)
    XMLStreamWriter writer = message.getContent(XMLStreamWriter.class);
    try {
        writer.flush();
    } catch (XMLStreamException e) {
        throw new Fault(new org.apache.cxf.common.i18n.Message("STAX_WRITE_EXC", BUNDLE, e));
    }
}
 
Example 16
Source File: JAXRSDefaultFaultOutInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    if (PropertyUtils.isTrue(message.getExchange().get(JAXRSUtils.SECOND_JAXRS_EXCEPTION))) {
        return;
    }
    final Fault f = (Fault) message.getContent(Exception.class);

    Response r = JAXRSUtils.convertFaultToResponse(f.getCause(), message);
    if (r != null) {
        JAXRSUtils.setMessageContentType(message, r);
        message.setContent(List.class, new MessageContentsList(r));
        if (message.getExchange().getOutMessage() == null && message.getExchange().getOutFaultMessage() != null) {
            message.getExchange().setOutMessage(message.getExchange().getOutFaultMessage());
        }
        new JAXRSOutInterceptor().handleMessage(message);
        return;
    }

    ServerProviderFactory.releaseRequestState(message);
    if (mustPropogateException(message)) {
        throw f;
    }

    new StaxOutInterceptor().handleMessage(message);
    message.put(org.apache.cxf.message.Message.RESPONSE_CODE, f.getStatusCode());
    NSStack nsStack = new NSStack();
    nsStack.push();

    XMLStreamWriter writer = message.getContent(XMLStreamWriter.class);
    try {
        nsStack.add("http://cxf.apache.org/bindings/xformat");
        String prefix = nsStack.getPrefix("http://cxf.apache.org/bindings/xformat");
        StaxUtils.writeStartElement(writer, prefix, "XMLFault",
                                    "http://cxf.apache.org/bindings/xformat");
        StaxUtils.writeStartElement(writer, prefix, "faultstring",
                                    "http://cxf.apache.org/bindings/xformat");
        Throwable t = f.getCause();
        writer.writeCharacters(t == null ? f.getMessage() : t.toString());
        // fault string
        writer.writeEndElement();
        // call StaxUtils to write Fault detail.

        if (f.getDetail() != null) {
            StaxUtils.writeStartElement(writer, prefix, "detail", "http://cxf.apache.org/bindings/xformat");
            StaxUtils.writeNode(DOMUtils.getChild(f.getDetail(), Node.ELEMENT_NODE),
                                writer, false);
            writer.writeEndElement();
        }
        // fault root
        writer.writeEndElement();
        writer.flush();
    } catch (XMLStreamException xe) {
        throw new Fault(new org.apache.cxf.common.i18n.Message("XML_WRITE_EXC", BUNDLE), xe);
    }
}
 
Example 17
Source File: JAXBExtensionHelper.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void marshall(@SuppressWarnings("rawtypes") Class parent, QName qname,
                     ExtensibilityElement obj, PrintWriter pw,
                     final Definition wsdl, ExtensionRegistry registry) throws WSDLException {
    try {
        Marshaller u = createMarshaller();
        u.setProperty("jaxb.encoding", StandardCharsets.UTF_8.name());
        u.setProperty("jaxb.fragment", Boolean.TRUE);
        u.setProperty("jaxb.formatted.output", Boolean.TRUE);

        Object mObj = obj;

        Class<?> objectFactory = Class.forName(PackageUtils.getPackageName(typeClass) + ".ObjectFactory",
                                               true,
                                               obj.getClass().getClassLoader());
        Method[] methods = objectFactory.getDeclaredMethods();
        for (Method method : methods) {
            if (method.getParameterTypes().length == 1
                && method.getParameterTypes()[0].equals(typeClass)) {

                mObj = method.invoke(objectFactory.newInstance(), new Object[] {obj});
            }
        }

        javax.xml.stream.XMLOutputFactory fact = javax.xml.stream.XMLOutputFactory.newInstance();
        XMLStreamWriter writer =
            new PrettyPrintXMLStreamWriter(fact.createXMLStreamWriter(pw), 2, getIndentLevel(parent));

        if (namespace != null && !namespace.equals(jaxbNamespace)) {
            Map<String, String> outMap = new HashMap<>();
            outMap.put("{" + jaxbNamespace + "}*", "{" + namespace + "}*");
            writer = new OutTransformWriter(writer,
                                            outMap,
                                            Collections.<String, String>emptyMap(),
                                            Collections.<String>emptyList(),
                                            false,
                                            "");
        }
        Map<String, String> nspref = new HashMap<>();
        for (Object ent : wsdl.getNamespaces().entrySet()) {
            Map.Entry<?, ?> entry = (Map.Entry<?, ?>)ent;
            nspref.put((String)entry.getValue(), (String)entry.getKey());
        }
        JAXBUtils.setNamespaceMapper(nspref, u);
        u.marshal(mObj, writer);
        writer.flush();
    } catch (Exception ex) {
        throw new WSDLException(WSDLException.PARSER_ERROR,
                                "",
                                ex);
    }

}
 
Example 18
Source File: CfgNet.java    From aion with MIT License 4 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);

        // start element net
        xmlWriter.writeCharacters("\r\n\t");
        xmlWriter.writeStartElement("net");

        // sub-element id
        xmlWriter.writeCharacters("\r\n\t\t");
        xmlWriter.writeStartElement("id");
        xmlWriter.writeCharacters(this.id + "");
        xmlWriter.writeEndElement();

        // sub-element nodes
        xmlWriter.writeCharacters("\r\n\t\t");
        xmlWriter.writeStartElement("nodes");
        for (String node : nodes) {
            xmlWriter.writeCharacters("\r\n\t\t\t");
            xmlWriter.writeStartElement("node");
            xmlWriter.writeCharacters(node);
            xmlWriter.writeEndElement();
        }
        xmlWriter.writeCharacters("\r\n\t\t");
        xmlWriter.writeEndElement();

        // sub-element p2p
        xmlWriter.writeCharacters(this.p2p.toXML());

        // close element net
        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 19
Source File: AbstractBeanDefinitionParser.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void mapElementToJaxbProperty(Element data,
                                        BeanDefinitionBuilder bean,
                                        String propertyName,
                                        Class<?> c) {
    try {
        XMLStreamWriter xmlWriter = null;
        Unmarshaller u = null;
        try {
            StringWriter writer = new StringWriter();
            xmlWriter = StaxUtils.createXMLStreamWriter(writer);
            StaxUtils.copy(data, xmlWriter);
            xmlWriter.flush();

            BeanDefinitionBuilder jaxbbean
                = BeanDefinitionBuilder.rootBeanDefinition(JAXBBeanFactory.class);
            jaxbbean.getRawBeanDefinition().setFactoryMethodName("createJAXBBean");
            jaxbbean.addConstructorArgValue(getContext(c));
            jaxbbean.addConstructorArgValue(writer.toString());
            jaxbbean.addConstructorArgValue(c);
            bean.addPropertyValue(propertyName, jaxbbean.getBeanDefinition());
        } catch (Exception ex) {
            u = getContext(c).createUnmarshaller();
            u.setEventHandler(null);
            Object obj;
            if (c != null) {
                obj = u.unmarshal(data, c);
            } else {
                obj = u.unmarshal(data);
            }
            if (obj instanceof JAXBElement<?>) {
                JAXBElement<?> el = (JAXBElement<?>)obj;
                obj = el.getValue();
            }
            if (obj != null) {
                bean.addPropertyValue(propertyName, obj);
            }
        } finally {
            StaxUtils.close(xmlWriter);
            JAXBUtils.closeUnmarshaller(u);
        }
    } catch (JAXBException e) {
        throw new RuntimeException("Could not parse configuration.", e);
    }
}
 
Example 20
Source File: XmlFormatter.java    From jboss-logmanager-ext with Apache License 2.0 4 votes vote down vote up
private void safeFlush(final XMLStreamWriter flushable) {
    if (flushable != null) try {
        flushable.flush();
    } catch (Throwable ignore) {
    }
}