Example usage for javax.xml.stream XMLStreamWriter close

List of usage examples for javax.xml.stream XMLStreamWriter close

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamWriter close.

Prototype

public void close() throws XMLStreamException;

Source Link

Document

Close this writer and free any resources associated with the writer.

Usage

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 {//  w ww  .  ja v  a 2s  .c  o m
        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.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// ww  w .j a  v a 2 s  .co 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.xmlsh.commands.internal.json2xml.java

public int run(List<XValue> args) throws Exception {
    Options opts = new Options(SerializeOpts.getOptionDefs());
    opts.parse(args);//  ww w  . ja  v a2s  .  c o m

    args = opts.getRemainingArgs();

    OutputPort stdout = getStdout();

    mSerializeOpts = getSerializeOpts(opts);
    SerializeOpts inputOpts = mSerializeOpts.clone();
    // JSON is always UTF8
    inputOpts.setInputTextEncoding("UTF-8");

    InputPort in = args.isEmpty() ? this.getStdin() : this.getInput(args.get(0));
    Reader inr = new InputStreamReader(in.asInputStream(inputOpts), inputOpts.getInputTextEncoding());
    ;

    JSONTokener tokenizer = new JSONTokener(inr);

    /*
     * Assume JSON file is wrapped by an Object
     */
    JSONObject obj = new JSONObject(tokenizer);

    XMLStreamWriter sw = stdout.asXMLStreamWriter(mSerializeOpts);
    sw.writeStartDocument();

    write(obj, sw);
    sw.writeEndDocument();
    sw.flush();
    sw.close();

    inr.close();

    return 0;

}

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

public void getMeanWeights(String outputPath) {

    if (getModelsimWeights()) {
        XMLOutputFactory factory = XMLOutputFactory.newInstance();
        try {/*  w w  w .  j a v a2  s.  co  m*/
            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 ww . jav  a2  s .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   ww w.  j  a  va2  s.  c om

    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  ww .jav a 2s  .  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:solidbase.core.DBVersion.java

/**
 * Dumps the current log in XML format to the given output stream, with the given character set.
 *
 * @param out The outputstream to which the xml will be written.
 * @param charSet The requested character set.
 *///from   www .j  ava  2  s  .co  m
protected void logToXML(OutputStream out, Charset charSet) {
    // This method does not care about staleness

    boolean spec11 = SPEC11.equals(this.effectiveSpec);

    try {
        Connection connection = this.database.getDefaultConnection();
        Statement stat = connection.createStatement();
        try {
            ResultSet result = stat.executeQuery("SELECT " + (spec11 ? "TYPE, " : "")
                    + "SOURCE, TARGET, STATEMENT, STAMP, COMMAND, RESULT FROM " + this.logTableName
                    + " ORDER BY STAMP");

            XMLOutputFactory xof = XMLOutputFactory.newInstance();
            XMLStreamWriter xml = xof.createXMLStreamWriter(new OutputStreamWriter(out, charSet));
            xml.writeStartDocument("UTF-8", SPEC10);
            xml.writeStartElement("log");
            while (result.next()) {
                int i = 1;
                xml.writeStartElement("record");
                if (spec11)
                    xml.writeAttribute("type", result.getString(i++));
                xml.writeAttribute("source", StringUtils.defaultString(result.getString(i++)));
                xml.writeAttribute("target", result.getString(i++));
                xml.writeAttribute("statement", String.valueOf(result.getInt(i++)));
                xml.writeAttribute("stamp", String.valueOf(result.getTimestamp(i++)));
                String sql = result.getString(i++);
                if (sql != null) {
                    xml.writeStartElement("command");
                    xml.writeCharacters(sql);
                    xml.writeEndElement();
                }
                String res = result.getString(i++);
                if (res != null) {
                    xml.writeStartElement("result");
                    xml.writeCharacters(res);
                    xml.writeEndElement();
                }
                xml.writeEndElement();
            }
            xml.writeEndElement();
            xml.writeEndDocument();
            xml.close();
        } finally {
            stat.close();
            connection.commit();
        }
    } catch (XMLStreamException e) {
        throw new SystemException(e);
    } catch (SQLException e) {
        throw new SystemException(e);
    }
}

From source file:spypunk.tailthis.configuration.xml.ConfigurationXMLWriter.java

public void save(final Configuration configuration) throws Exception {

    FileUtils.forceMkdir(configurationFile.getParentFile());
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();
    XMLStreamWriter xtw = null;

    try {/*from w  w w . j  a  v a  2 s . c  o  m*/
        xtw = new IndentingXMLStreamWriter(xof.createXMLStreamWriter(new FileWriter(configurationFile)));

        xtw.writeStartElement(ConfigurationXMLConstants.TAILTHIS_ELEMENT_NAME);

        xtw.writeStartElement(ConfigurationXMLConstants.REMEMBER_LAST_OPENED_FILES_ELEMENT_NAME);
        xtw.writeCharacters(configuration.getRememberLastOpenedFiles().toString());
        xtw.writeEndElement();

        xtw.writeStartElement(ConfigurationXMLConstants.LAST_FOLDER_ELEMENT_NAME);
        xtw.writeCharacters(configuration.getLastFolder().getAbsolutePath());
        xtw.writeEndElement();

        xtw.writeStartElement(ConfigurationXMLConstants.LAST_OPENED_FILES_ELEMENT_NAME);

        for (final File lastOpenedFile : configuration.getLastOpenedFiles()) {
            xtw.writeStartElement(ConfigurationXMLConstants.LAST_OPENED_FILE_ELEMENT_NAME);
            xtw.writeCharacters(lastOpenedFile.getAbsolutePath());
            xtw.writeEndElement();
        }

        xtw.writeEndElement();

        xtw.writeStartElement(ConfigurationXMLConstants.UPDATE_PERIOD_ELEMENT_NAME);
        xtw.writeCharacters(configuration.getUpdatePeriod().toString());
        xtw.writeEndElement();

        xtw.writeStartElement(ConfigurationXMLConstants.ALWAYS_ON_TOP_ELEMENT_NAME);
        xtw.writeCharacters(configuration.getAlwaysOnTop().toString());
        xtw.writeEndElement();

        xtw.writeStartElement(ConfigurationXMLConstants.LOCALE_ELEMENT_NAME);
        xtw.writeCharacters(configuration.getLocale().getKey());
        xtw.writeEndElement();

        xtw.writeStartElement(ConfigurationXMLConstants.HIGHLIGHTINGS_ELEMENT_NAME);

        for (final Highlighting highlighting : configuration.getHighlightings()) {
            xtw.writeStartElement(ConfigurationXMLConstants.HIGHLIGHTING_ELEMENT_NAME);
            xtw.writeAttribute(ConfigurationXMLConstants.BACKGROUND_COLOR_ATTRIBUTE_NAME,
                    highlighting.getBackgroundColor().getKey());
            xtw.writeAttribute(ConfigurationXMLConstants.FOREGROUND_COLOR_ATTRIBUTE_NAME,
                    highlighting.getForegroundColor().getKey());
            xtw.writeCharacters(highlighting.getPattern().pattern());
            xtw.writeEndElement();
        }

        xtw.writeEndElement();

        xtw.writeEndElement();

        xtw.flush();
    } finally {
        if (xtw != null) {
            try {
                xtw.close();
            } catch (final XMLStreamException e) {
                LOGGER.warn(e.getMessage(), e);
            }
        }
    }
}

From source file:tds.itemscoringengine.ItemScoreRequest.java

@Override
public void writeXML(XMLStreamWriter out) throws XMLStreamException {

    out.writeStartDocument();/*from  w  w  w  . j  a  v a 2  s.  c o  m*/
    out.writeStartElement("ItemScoreRequest");

    String callBackUrl = getCallbackUrl();
    if (!StringUtils.isEmpty(callBackUrl))
        out.writeAttribute("callbackUrl", callBackUrl);

    out.writeStartElement("ResponseInfo");
    out.writeAttribute("itemIdentifier", _responseInfo.getItemIdentifier());
    out.writeAttribute("itemFormat", _responseInfo.getItemFormat());

    out.writeStartElement("StudentResponse");
    out.writeAttribute("encrypted", Boolean.toString(_responseInfo.isStudentResponseEncrypted()));
    out.writeCData(_responseInfo.getStudentResponse());
    out.writeEndElement(); // </StudentResponse>

    out.writeStartElement("Rubric");
    out.writeAttribute("type",
            _responseInfo.getContentType() == RubricContentType.ContentString ? "Data" : "Uri");
    out.writeAttribute("cancache", Boolean.toString(_responseInfo.isCanCacheRubric()));
    out.writeAttribute("encrypted", Boolean.toString(_responseInfo.isRubricEncrypted()));
    if (_responseInfo.getRubric() != null) {
        out.writeCData(_responseInfo.getRubric().toString());
    }
    out.writeEndElement(); // </Rubric>

    out.writeStartElement("ContextToken");
    out.writeCData(_responseInfo.getContextToken().toString());
    out.writeEndElement(); // </ContextToken>

    // <IncomingBindings>
    if (_responseInfo.getIncomingBindings() != null && _responseInfo.getIncomingBindings().size() > 0) {
        out.writeStartElement("IncomingBindings");
        for (VarBinding varBinding : _responseInfo.getIncomingBindings()) {
            out.writeStartElement("Binding");
            out.writeAttribute("name", varBinding.getName());
            out.writeAttribute("type", varBinding.getType());
            out.writeAttribute("value", varBinding.getValue());
            out.writeEndElement();
        }
        out.writeEndElement();
    }

    // <OutgoingBindings>
    if (_responseInfo.getOutgoingBindings() != null && _responseInfo.getOutgoingBindings().size() > 0) {
        out.writeStartElement("OutgoingBindings");
        for (VarBinding varBinding : _responseInfo.getOutgoingBindings()) {
            out.writeStartElement("Binding");
            out.writeAttribute("name", varBinding.getName());
            out.writeAttribute("type", varBinding.getType());
            out.writeAttribute("value", varBinding.getValue());
            out.writeEndElement();
        }
        out.writeEndElement();
    }

    out.writeEndElement(); // </ResponseInfo>
    out.writeEndElement(); // </ItemScoreRequest>
    out.writeEndDocument();
    out.close();
}