Example usage for javax.xml.stream XMLOutputFactory newInstance

List of usage examples for javax.xml.stream XMLOutputFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.stream XMLOutputFactory newInstance.

Prototype

public static XMLOutputFactory newInstance() throws FactoryConfigurationError 

Source Link

Document

Creates a new instance of the factory in exactly the same manner as the #newFactory() method.

Usage

From source file:org.wso2.carbon.repository.core.ResourceStorer.java

/**
 * Method to do a dump.//from   w w w.  j a va2s  .c o  m
 *
 * @param _path   the path to obtain the dump from.
 * @param writer the writer used.
 *
 * @throws RepositoryException if the operation failed.
 */
public void dump(String _path, Writer writer) throws RepositoryException {
    String path = _path;

    if (!path.equals("/") && path.endsWith("/")) {
        path = path.substring(0, path.length() - 1);
    }

    XMLStreamWriter xmlWriter = null;
    try {
        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        xmlWriter = xof.createXMLStreamWriter(writer);

        // we are not using xmlWriter.writeStartDocument and writeEndDocument to get rid of the
        // xml descriptor it put in every child node
        dumpRecursively(path, xmlWriter, writer);
    } catch (XMLStreamException e) {
        String msg = "Failed to serialize the dumped element at " + path + ".";
        log.error(msg);
        throw new RepositoryException(msg, e);
    } finally {
        if (xmlWriter != null) {
            try {
                xmlWriter.close();
            } catch (XMLStreamException e) {
            }
        }
    }
}

From source file:org.wso2.carbon.security.config.SecurityConfigAdmin.java

private OMElement buildRampartConfigXML(String privateStore, String[] trustedStores,
        KerberosConfigData kerberosConfig) throws SecurityConfigException {

    ByteArrayOutputStream out = null;
    XMLStreamWriter writer = null;
    OMElement rampartConfigElement = null;
    try {/*www  .j  a v a2 s.com*/
        Properties props = getServerCryptoProperties(privateStore, trustedStores);
        RampartConfig rampartConfig = new RampartConfig();
        populateRampartConfig(rampartConfig, props, kerberosConfig);
        if (rampartConfig != null) {
            //addRampartConfigs(policyElement, rampartConfig);
            out = new ByteArrayOutputStream();
            writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out);
            rampartConfig.serialize(writer);
            writer.flush();
            writer.close();
            out.close();
            out.flush();
            rampartConfigElement = AXIOMUtil.stringToOM(out.toString());
        }
    } catch (Exception e) {
        throw new SecurityConfigException("Error while building rampart configs", e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                log.error("Error while closing output stream", e);
            }
            if (writer != null) {
                try {
                    writer.close();
                } catch (XMLStreamException e) {
                    log.error("Error while closing xml stream writer", e);
                }
            }
        }
    }
    return rampartConfigElement;
}

From source file:org.wso2.dss.integration.test.samples.EventingSampleTestCase.java

private void updateAxis2_ClientXML() throws Exception {
    String axis2_client_path = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator
            + "conf" + File.separator + "axis2" + File.separator + "axis2_client.xml";

    String mail_transport_config = getResourceLocation() + File.separator + "resources" + File.separator
            + "mailTransport.xml";

    FileOutputStream fileOutputStream = null;
    XMLStreamWriter writer = null;

    try {/*  w  ww. ja v a  2s  .co  m*/
        OMElement axis2_client_xml = AXIOMUtil.stringToOM(FileManager.readFile(axis2_client_path));

        axis2_client_xml.addChild(AXIOMUtil.stringToOM(FileManager.readFile(mail_transport_config)));
        axis2_client_xml.build();
        fileOutputStream = new FileOutputStream(axis2_client_path);
        writer = XMLOutputFactory.newInstance().createXMLStreamWriter(fileOutputStream);
        axis2_client_xml.serialize(writer);

    } catch (Exception e) {
        throw new Exception("axis2_client.xml update fails");
    } finally {
        if (fileOutputStream != null) {
            fileOutputStream.close();
        }
        if (writer != null) {
            writer.flush();
        }
    }
}

From source file:org.wso2.ei.dataservice.integration.test.samples.EventingSampleTestCase.java

private void updateAxis2_ClientXML() throws Exception {
    String axis2_client_path = CarbonUtils.getCarbonHome() + File.separator + "conf" + File.separator + "axis2"
            + File.separator + "axis2_client.xml";

    String mail_transport_config = getResourceLocation() + File.separator + "resources" + File.separator
            + "mailTransport.xml";

    FileOutputStream fileOutputStream = null;
    XMLStreamWriter writer = null;

    try {/*from w  w w .j  av a 2 s .co  m*/
        OMElement axis2_client_xml = AXIOMUtil.stringToOM(FileManager.readFile(axis2_client_path));

        axis2_client_xml.addChild(AXIOMUtil.stringToOM(FileManager.readFile(mail_transport_config)));
        axis2_client_xml.build();
        fileOutputStream = new FileOutputStream(axis2_client_path);
        writer = XMLOutputFactory.newInstance().createXMLStreamWriter(fileOutputStream);
        axis2_client_xml.serialize(writer);

    } catch (Exception e) {
        throw new Exception("axis2_client.xml update fails");
    } finally {
        if (fileOutputStream != null) {
            fileOutputStream.close();
        }
        if (writer != null) {
            writer.flush();
        }
    }
}

From source file:org.wso2.maven.AbstractMavenReleaseMojo.java

/**
 * Update versions in the given artifact.xml file of a ESB/DSS project.
 *
 * @param artifactXml artifact.xml file of a ESB/DSS project.
 * @param newVersion  new version to which, the artifacts should be updated.
 * @throws Exception// w  w  w. jav  a  2  s . c o m
 */
protected void updateArtifactVersions(File artifactXml, String newVersion) throws Exception {
    InputStream inputStream = new FileInputStream(artifactXml);
    XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
    StAXOMBuilder builder = new StAXOMBuilder(xmlStreamReader);
    OMElement documentElement = builder.getDocumentElement();
    Iterator artifacts = documentElement.getChildrenWithName(new QName(ARTIFACT));
    while (artifacts.hasNext()) {
        OMElement artifact = (OMElement) artifacts.next();
        OMAttribute version = artifact.getAttribute(new QName(VERSION));
        if (version != null) {
            version.setAttributeValue(newVersion);
        }
    }
    if (isInDryRunMode()) {
        artifactXml = new File(artifactXml.getPath() + getDryRunFilePrefix());
    }
    FileOutputStream outputStream = new FileOutputStream(artifactXml);
    XMLStreamWriter xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(outputStream);
    builder.getDocument().serialize(xmlStreamWriter);
    inputStream.close();
    xmlStreamReader.close();
    outputStream.close();
    xmlStreamWriter.close();
}

From source file:org.xronos.orcc.analysis.XronosDynamicWeights.java

public void getMeanWeights(String outputPath) {

    if (getModelsimWeights()) {
        XMLOutputFactory factory = XMLOutputFactory.newInstance();
        try {/*from w  w w. j  ava  2 s. c  om*/
            XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(
                    outputPath + File.separator + network.getSimpleName() + "_dynamicWeights.xml"));
            writer.writeStartDocument();
            writer.writeStartElement("actors");
            for (Actor actor : statistics.keySet()) {
                writer.writeStartElement("actor");
                writer.writeAttribute("name", actor.getSimpleName().toLowerCase());
                Map<Action, SummaryStatistics> actionWeight = statistics.get(actor);
                writer.writeStartElement("actions");
                for (Action action : actionWeight.keySet()) {
                    writer.writeStartElement("action");
                    writer.writeAttribute("name", action.getName().toLowerCase());

                    double min = Double.isNaN(actionWeight.get(action).getMin()) ? 0
                            : actionWeight.get(action).getMin();
                    double mean = Double.isNaN(actionWeight.get(action).getMean()) ? 0
                            : actionWeight.get(action).getMean();
                    double max = Double.isNaN(actionWeight.get(action).getMax()) ? 0
                            : actionWeight.get(action).getMax();
                    double variance = Double.isNaN(actionWeight.get(action).getVariance()) ? 0
                            : actionWeight.get(action).getVariance();

                    writer.writeAttribute("min", Double.toString(min));
                    writer.writeAttribute("mean", Double.toString(mean));
                    writer.writeAttribute("max", Double.toString(max));
                    writer.writeAttribute("variance", Double.toString(variance));

                    writer.writeEndElement();
                }
                writer.writeEndElement();
                writer.writeEndElement();
            }
            writer.writeEndElement();
            writer.writeEndDocument();

            writer.flush();
            writer.close();
        } catch (XMLStreamException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:org.xwiki.xar.XarPackage.java

/**
 * Write the package descriptor to the passed stream as XML.
 * //from w  w w .jav  a 2s .c  o  m
 * @param stream the stream to the resulting XML file
 * @param encoding the encoding to use to write the descriptor
 * @throws XarException when failing to parse the descriptor
 * @throws IOException when failing to read the file
 */
public void write(OutputStream stream, String encoding) throws XarException, IOException {
    XMLStreamWriter writer;
    try {
        writer = XMLOutputFactory.newInstance().createXMLStreamWriter(stream, encoding);
    } catch (Exception e) {
        throw new XarException("Failed to create an instance of XML stream writer", e);
    }

    writer = new IndentingXMLStreamWriter(writer);

    try {
        writer.writeStartDocument(encoding, "1.0");
        write(writer);
        writer.writeEndDocument();

        writer.flush();
    } catch (Exception e) {
        throw new XarException("Failed to write XML", e);
    } finally {
        try {
            writer.close();
        } catch (XMLStreamException e) {
            throw new XarException("Failed to close XML writer", e);
        }
    }
}

From source file:ro.kuberam.libs.java.ftclient.FTP.FTP.java

public StreamResult listResources(Object abstractConnection, String remoteResourcePath) throws Exception {
    long startTime = new Date().getTime();

    boolean isDirectory = checkIsDirectory(remoteResourcePath);

    if (!isDirectory) {
        throw new Exception(ErrorMessages.err_FTC008);
    }//from w w w.  java2s .  c o m

    FTPClient connection = (FTPClient) abstractConnection;
    if (!connection.isConnected()) {
        throw new Exception(ErrorMessages.err_FTC002);
    }

    List<Object> connectionObject = _checkResourcePath(connection, remoteResourcePath, "list-resources",
            isDirectory);

    System.out.println("resources: " + connectionObject.size());

    FTPFile[] resources = (FTPFile[]) connectionObject.get(1);
    StringWriter writer = new StringWriter();
    XMLStreamWriter xmlWriter = null;

    try {
        xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer);
        xmlWriter.setPrefix(modulePrefix, moduleNsUri);
        xmlWriter.writeStartDocument();
        xmlWriter.writeStartElement(modulePrefix + ":resources-list");
        xmlWriter.writeNamespace(modulePrefix, moduleNsUri);
        xmlWriter.writeAttribute("absolute-path", remoteResourcePath);
        for (FTPFile resource : resources) {
            _generateResourceElement(xmlWriter, resource, null, remoteResourcePath + resource.getName());
        }
        xmlWriter.writeEndElement();
        xmlWriter.writeEndDocument();
        xmlWriter.close();
    } catch (Exception ex) {
        throw new Exception(ex.getMessage());
    }

    // FTPconnection.completePendingCommand();
    StreamResult resultAsStreamResult = new StreamResult(writer);
    log.info("The FTP sub-module retrieved the list of resources in " + (new Date().getTime() - startTime)
            + " ms.");

    return resultAsStreamResult;
}

From source file:ro.kuberam.libs.java.ftclient.FTP.FTP.java

public StreamResult getResourceMetadata(Object abstractConnection, String remoteResourcePath) throws Exception {
    long startTime = new Date().getTime();
    FTPClient FTPconnection = (FTPClient) abstractConnection;

    if (!FTPconnection.isConnected()) {
        throw new Exception(ErrorMessages.err_FTC002);
    }/*from  w  w  w. j a  v a2s.c  o m*/

    List<Object> FTPconnectionObject = _checkResourcePath(FTPconnection, remoteResourcePath,
            "get-resource-metadata", checkIsDirectory(remoteResourcePath));

    FTPFile[] resources = (FTPFile[]) FTPconnectionObject.get(1);

    StringWriter writer = new StringWriter();
    XMLStreamWriter xmlWriter = null;

    try {
        xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer);
        xmlWriter.setPrefix(modulePrefix, moduleNsUri);
        xmlWriter.writeStartDocument();
        for (FTPFile resource : resources) {
            _generateResourceElement(xmlWriter, resource, null, remoteResourcePath);
        }
        xmlWriter.writeEndDocument();
        xmlWriter.close();
    } catch (Exception ex) {
        throw new Exception(ex.getMessage());
    }

    // FTPconnection.completePendingCommand();
    StreamResult resultAsStreamResult = new StreamResult(writer);

    log.info("The FTP sub-module retrieved the metadata for resource '" + remoteResourcePath + "' in "
            + (new Date().getTime() - startTime) + " ms.");

    return resultAsStreamResult;
}

From source file:ru.codeinside.gws.crypto.cryptopro.CryptoProvider.java

private String saxFilter(Node node) {
    try {//from w  w w  .  ja  v a 2s. com
        final Transformer transformer = TransformerFactory.newInstance().newTransformer();
        final StringWriter w1 = new StringWriter();
        transformer.transform(new DOMSource(node), new StreamResult(w1));
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLEventReader eventReader = xif
                .createXMLEventReader(new StreamSource(new StringReader(w1.toString())));
        XMLEventReader filteredReader = xif.createFilteredReader(eventReader, new EventFilter() {
            @Override
            public boolean accept(XMLEvent event) {
                int type = event.getEventType();
                if (type == XMLStreamConstants.START_DOCUMENT || type == XMLStreamConstants.END_DOCUMENT) {
                    return false;
                }
                if (event.isStartElement()) {
                    StartElement startElement = (StartElement) event;
                    QName name = startElement.getName();
                    if ("".equals(name.getNamespaceURI()) && "root".equals(name.getLocalPart())) {
                        return false;
                    }
                }
                if (event.isEndElement()) {
                    EndElement endElement = (EndElement) event;
                    QName name = endElement.getName();
                    if ("".equals(name.getNamespaceURI()) && "root".equals(name.getLocalPart())) {
                        return false;
                    }
                }
                return true;
            }
        });
        StringWriter sw = new StringWriter();
        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        XMLEventWriter writer = xof.createXMLEventWriter(sw);
        while (filteredReader.hasNext()) {
            writer.add(filteredReader.nextEvent());
        }
        return sw.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}