Example usage for org.dom4j.io XMLWriter write

List of usage examples for org.dom4j.io XMLWriter write

Introduction

In this page you can find the example usage for org.dom4j.io XMLWriter write.

Prototype

public void write(Object object) throws IOException 

Source Link

Document

Writes the given object which should be a String, a Node or a List of Nodes.

Usage

From source file:com.pureinfo.srm.reports.table.data.institute.InstituteQueryAction.java

License:Open Source License

private void writeResponse(Document sInsJson) throws PureException {
    try {/*from  ww  w  .jav  a  2 s  .c o m*/
        response.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
        response.setHeader("Pragma", "no-cache"); //HTTP 1.0
        response.setDateHeader("Expires", -1);
        response.setDateHeader("max-age", 0);
        response.setContentType("text/xml");
        response.setCharacterEncoding("utf-8");
        XMLWriter writer = new XMLWriter(response.getWriter());
        writer.write(sInsJson);
        writer.close();
    } catch (IOException e) {
        throw new PureException(PureException.FILE_WRITE_FAILED, "failed to write response", e);
    }
}

From source file:com.qagen.osfe.programData.readerWriter.ReaderWriter.java

License:Apache License

protected void saveDocument() {
    try {/*from   www.j a v  a  2  s .co  m*/
        final OutputFormat format = OutputFormat.createPrettyPrint();
        final FileWriter writer = new FileWriter(fileName);
        final XMLWriter xmlWriter = new XMLWriter(writer, format);

        xmlWriter.write(document);
        xmlWriter.close();
    } catch (IOException e) {
        throw new ProgramDataException(e);
    }
}

From source file:com.rockagen.commons.util.XmlUtil.java

License:Apache License

/**
 * Format xml//from w  ww .  j ava 2  s . co m
 *
 * @param xmlStr   xml String
 * @param formater {@link OutputFormat}
 * @return format String
 */
public static String format(String xmlStr, OutputFormat formater) {
    if (CommUtil.isBlank(xmlStr))
        return xmlStr;

    SAXReader reader = new SAXReader();
    StringReader sr = new StringReader(xmlStr);

    Document doc;
    XMLWriter writer = null;
    StringWriter sw = new StringWriter();
    try {
        doc = reader.read(sr);
        writer = new XMLWriter(sw, formater);
        writer.write(doc);
        return sw.toString();
    } catch (DocumentException e) {
        log.error("{}", e.getMessage(), e);
    } catch (IOException e) {
        log.error("{}", e.getMessage(), e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException ignored) {
            }
        }

    }

    return xmlStr;
}

From source file:com.rowtheboat.gui.OptionsSingleton.java

License:Open Source License

/**
 * This method saves the options to the options.xml file
 *//*www .  ja  va2 s. c o  m*/
public void saveOptions() throws SAXException, IOException {

    /* Start the document */
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new FileWriter(optionsFile), format);
    writer.startDocument();

    /* Add the main options section */
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("Options");

    /* Standard options */
    DefaultElement standardElement = new DefaultElement("Standard");
    standardElement.addElement("FullStrokeData").addText(getFullStrokeData() + "");
    standardElement.addElement("BoatSmoothing").addText(getBoatSmoothing() + "");
    root.add(standardElement);

    /* Input options */
    DefaultElement inputElement = new DefaultElement("Input");
    inputElement.addElement("SerialPort").addText(getSerialPort());
    root.add(inputElement);

    /* Race options */
    DefaultElement raceElement = new DefaultElement("Race");
    raceElement.addElement("Countdown").addText(getDelay() + "");
    root.add(raceElement);

    /* End the document */
    writer.write(root);
    writer.endDocument();
    writer.close();
}

From source file:com.safi.workshop.sqlexplorer.history.SQLHistory.java

License:Open Source License

/**
 * Save all the used queries into a file, so that we can reuse them next time.
 *//* w w w  .  j  a v  a 2 s .c  o  m*/
public void save() {

    try {
        File file = new File(ApplicationFiles.SQLHISTORY_FILE_NAME_V350);
        Element root = new DefaultElement(HISTORY);
        for (SQLHistoryElement elem : _history)
            root.add(elem.describeAsXml());
        XMLWriter xmlWriter = new XMLWriter(new FileWriter(file), OutputFormat.createPrettyPrint());
        xmlWriter.write(root);
        xmlWriter.flush();
        xmlWriter.close();

        // Get rid of old versions
        new File(ApplicationFiles.SQLHISTORY_FILE_NAME_V300).delete();

    } catch (IOException e) {
        SQLExplorerPlugin.error("Couldn't save sql history.", e);
    }

}

From source file:com.sammyun.util.SettingUtils.java

License:Open Source License

/**
 * /* www . j  a  va2 s. com*/
 * 
 * @param setting 
 */
public static void set(Setting setting) {
    try {
        File preschoolEduXmlFile = new ClassPathResource(CommonAttributes.PRESCHOOLEDU_XML_PATH).getFile();
        Document document = new SAXReader().read(preschoolEduXmlFile);
        List<Element> elements = document.selectNodes("/preschoolEdu/setting");
        for (Element element : elements) {
            try {
                String name = element.attributeValue("name");
                String value = beanUtils.getProperty(setting, name);
                Attribute attribute = element.attribute("value");
                attribute.setValue(value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                logger.error(e.getMessage());
            } catch (InvocationTargetException e) {
                e.printStackTrace();
                logger.error(e.getMessage());
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
                logger.error(e.getMessage());
            }
        }

        FileOutputStream fileOutputStream = null;
        XMLWriter xmlWriter = null;
        try {
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            outputFormat.setIndent(true);
            outputFormat.setIndent("   ");
            outputFormat.setNewlines(true);
            fileOutputStream = new FileOutputStream(preschoolEduXmlFile);
            xmlWriter = new XMLWriter(fileOutputStream, outputFormat);
            xmlWriter.write(document);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (xmlWriter != null) {
                try {
                    xmlWriter.close();
                } catch (IOException e) {
                }
            }
            IOUtils.closeQuietly(fileOutputStream);
        }

        Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME);
        cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting));
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
    }
}

From source file:com.sap.data.db.dao.StructureUtil.java

private void save(Document document, String filepath) throws IOException {
    document.addDocType(this.HIBERNATE_MAPPING, this.HIBERNATE_MAPPING_EN, this.HIBERNATE_MAPPING_DTD);
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");

    XMLWriter writer = new XMLWriter(new FileWriter(new File(filepath)), format);
    writer.write(document);
    writer.close();//w w w .ja v  a2s  .co m
}

From source file:com.servoy.extension.install.LibActivationHandler.java

License:Open Source License

protected void writeBackXML(Document doc, File f, String encoding)
        throws IOException, TransformerFactoryConfigurationError, TransformerException, DocumentException {
    BufferedOutputStream os = null;
    try {/*w ww. j av a 2 s.co  m*/
        os = new BufferedOutputStream(new FileOutputStream(f));
        doc.normalize();
        StringWriter sw = new StringWriter(1024);
        DOMSource source = new DOMSource(doc);
        Transformer newTransformer = TransformerFactory.newInstance().newTransformer();
        newTransformer.setOutputProperty(OutputKeys.ENCODING, encoding);
        newTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
        newTransformer.transform(source, new StreamResult(sw));

        // normally the transformer code above should have been enough for producing pretty formatted XML (needed so that repeated remove/restore of tags
        // doesn't produce endless newlines or other bad looking XML); but it seems that with some versions of the JDK that doesn't do it's job so we use dom4j
        final OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(encoding);
        final XMLWriter writer = new XMLWriter(os, format);
        writer.write(DocumentHelper.parseText(sw.toString()));
    } finally {
        Utils.closeOutputStream(os);
    }

}

From source file:com.smartwork.im.StreamError.java

License:Open Source License

public String toString() {
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
    try {//from  w ww. j  a  v a2s  . c o m
        writer.write(element);
    } catch (Exception e) {
    }
    return out.toString();
}

From source file:com.smartwork.im.utils.XMLProperties.java

License:Open Source License

/**
 * Saves the properties to disk as an XML document. A temporary file is
 * used during the writing process for maximum safety.
 *///from   w w  w  . j av  a 2  s  .  co m
private synchronized void saveProperties() {
    boolean error = false;
    // Write data out to a temporary file first.
    File tempFile = null;
    Writer writer = null;
    try {
        tempFile = new File(file.getParentFile(), file.getName() + ".tmp");
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile)));
        OutputFormat prettyPrinter = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(writer, prettyPrinter);
        xmlWriter.write(document);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        // There were errors so abort replacing the old property file.
        error = true;
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e1) {
                logger.error(e1.getMessage(), e1);
                error = true;
            }
        }
    }

    // No errors occured, so delete the main file.
    if (!error) {
        // Delete the old file so we can replace it.
        if (!file.delete()) {
            logger.error("Error deleting property file: " + file.getAbsolutePath());
            return;
        }
        // Copy new contents to the file.
        try {
            copy(tempFile, file);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            // There were errors so abort replacing the old property file.
            error = true;
        }
        // If no errors, delete the temp file.
        if (!error) {
            tempFile.delete();
        }
    }
}