Example usage for org.dom4j.io XMLWriter close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the underlying Writer

Usage

From source file:com.iterzp.momo.utils.SettingUtils.java

License:Open Source License

/**
 * /*from   w  w w .  j a va2 s.c om*/
 * 
 * @param setting
 *            
 */
public static void set(Setting setting) {
    try {
        File shopxxXmlFile = new ClassPathResource(CommonAttributes.MOMO_XML_PATH).getFile();
        Document document = new SAXReader().read(shopxxXmlFile);
        List<Element> elements = document.selectNodes("/momo/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();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }

        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(shopxxXmlFile);
            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();
    }
}

From source file:com.jboss.transaction.txinterop.test.XMLResultsServlet.java

License:LGPL

public void doStatus(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/xml");
    response.setHeader("Cache-Control", "no-cache");

    HttpSession session = request.getSession();
    final FullTestResult testResult = (FullTestResult) session
            .getAttribute(TestConstants.ATTRIBUTE_TEST_RESULT);

    DOMDocument report = new DOMDocument();
    DOMElement testsuite = new DOMElement("testsuite");
    report.setRootElement(testsuite);//ww  w.j a va2 s .  c  o m

    if (testResult == null) {
        // No JUnit test results generated.
    } else {
        List passedTests = testResult.getPassedTests();
        List failedTests = testResult.getFailedTests();
        List errorTests = testResult.getErrorTests();

        final int runCount = testResult.runCount();
        final int errorCount = testResult.errorCount();
        final int failureCount = testResult.failureCount();

        testsuite.addAttribute("name", "com.jboss.transaction.txinterop.interop.InteropTestSuite");
        testsuite.addAttribute("errors", Integer.toString(errorCount));
        testsuite.addAttribute("failures", Integer.toString(failureCount));
        testsuite.addAttribute("hostname", request.getServerName());
        testsuite.addAttribute("tests", Integer.toString(runCount));
        testsuite.addAttribute("timestamp", new Date().toString());

        DOMElement properties = new DOMElement("properties");
        testsuite.add(properties);
        DOMElement status = newPropertyDOMElement("status");
        properties.add(status);
        status.addAttribute("value", "finished");

        long totalDuration = 0;

        if (!passedTests.isEmpty()) {
            Iterator passedTestsIterator = passedTests.iterator();
            while (passedTestsIterator.hasNext()) {
                FullTestResult.PassedTest passedTest = (FullTestResult.PassedTest) passedTestsIterator.next();
                totalDuration += passedTest.duration;

                final String name = passedTest.test.toString();
                final String description = (String) TestConstants.DESCRIPTIONS.get(name);

                testsuite.add(newTestcase(passedTest.test.getClass().getName(), name + ": " + description,
                        passedTest.duration));
            }
        }

        if (!failedTests.isEmpty()) {
            Iterator failedTestsIterator = failedTests.iterator();
            while (failedTestsIterator.hasNext()) {
                FullTestResult.FailedTest failedTest = (FullTestResult.FailedTest) failedTestsIterator.next();
                totalDuration += failedTest.duration;

                final String name = failedTest.test.toString();
                final String description = (String) TestConstants.DESCRIPTIONS.get(name);
                CharArrayWriter charArrayWriter = new CharArrayWriter();
                PrintWriter printWriter = new PrintWriter(charArrayWriter, true);
                failedTest.assertionFailedError.printStackTrace(printWriter);
                printWriter.close();
                charArrayWriter.close();

                testsuite.add(newFailedTestcase(failedTest.test.getClass().getName(), name + ": " + description,
                        failedTest.duration, failedTest.assertionFailedError.getMessage(),
                        charArrayWriter.toString()));
            }
        }

        if (!errorTests.isEmpty()) {
            Iterator errorTestsIterator = errorTests.iterator();
            while (errorTestsIterator.hasNext()) {
                FullTestResult.ErrorTest errorTest = (FullTestResult.ErrorTest) errorTestsIterator.next();
                totalDuration += errorTest.duration;

                final String name = errorTest.test.toString();
                final String description = (String) TestConstants.DESCRIPTIONS.get(name);
                CharArrayWriter charArrayWriter = new CharArrayWriter();
                PrintWriter printWriter = new PrintWriter(charArrayWriter, true);
                errorTest.throwable.printStackTrace(printWriter);
                printWriter.close();
                charArrayWriter.close();

                System.out.println("charArrayWriter.toString()=" + charArrayWriter.toString());
                testsuite.add(newErrorTestcase(errorTest.test.getClass().getName(), name + ": " + description,
                        errorTest.duration, errorTest.throwable.getMessage(), charArrayWriter.toString()));
            }
        }

        // total time of all tests
        testsuite.addAttribute("time", Float.toString(totalDuration / 1000f));
    }

    String logContent = null;
    final String logName = (String) session.getAttribute(TestConstants.ATTRIBUTE_LOG_NAME);
    if (logName != null) {
        try {
            logContent = TestLogController.readLog(logName);
        } catch (final Throwable th) {
            log("Error reading log file", th);
        }
    }

    testsuite.add(new DOMElement("system-out").addCDATA((logContent != null) ? logContent : ""));
    testsuite.add(new DOMElement("system-err").addCDATA(""));

    XMLWriter outputter = new XMLWriter(response.getWriter(), OutputFormat.createPrettyPrint());
    try {
        outputter.write(testsuite);
        outputter.close();
    } catch (IOException e) {
        throw new ServletException(e);
    }
}

From source file:com.jboss.transaction.wstf.test.XMLResultsServlet.java

License:LGPL

public void doStatus(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/xml");
    response.setHeader("Cache-Control", "no-cache");

    HttpSession session = request.getSession();
    final FullTestResult testResult = (FullTestResult) session
            .getAttribute(TestConstants.ATTRIBUTE_TEST_RESULT);

    DOMDocument report = new DOMDocument();
    DOMElement testsuite = new DOMElement("testsuite");
    report.setRootElement(testsuite);/*  ww  w . j a  v  a  2  s .c  o m*/

    if (testResult == null) {
        // No JUnit test results generated.
    } else {
        List passedTests = testResult.getPassedTests();
        List failedTests = testResult.getFailedTests();
        List errorTests = testResult.getErrorTests();

        final int runCount = testResult.runCount();
        final int errorCount = testResult.errorCount();
        final int failureCount = testResult.failureCount();

        testsuite.addAttribute("name", "com.jboss.transaction.wstf.interop.InteropTestSuite");
        testsuite.addAttribute("errors", Integer.toString(errorCount));
        testsuite.addAttribute("failures", Integer.toString(failureCount));
        testsuite.addAttribute("hostname", request.getServerName());
        testsuite.addAttribute("tests", Integer.toString(runCount));
        testsuite.addAttribute("timestamp", new Date().toString());

        DOMElement properties = new DOMElement("properties");
        testsuite.add(properties);
        DOMElement status = newPropertyDOMElement("status");
        properties.add(status);
        status.addAttribute("value", "finished");

        long totalDuration = 0;

        if (!passedTests.isEmpty()) {
            Iterator passedTestsIterator = passedTests.iterator();
            while (passedTestsIterator.hasNext()) {
                FullTestResult.PassedTest passedTest = (FullTestResult.PassedTest) passedTestsIterator.next();
                totalDuration += passedTest.duration;

                final String name = passedTest.test.toString();
                final String description = (String) TestConstants.DESCRIPTIONS.get(name);

                testsuite.add(newTestcase(passedTest.test.getClass().getName(), name + ": " + description,
                        passedTest.duration));
            }
        }

        if (!failedTests.isEmpty()) {
            Iterator failedTestsIterator = failedTests.iterator();
            while (failedTestsIterator.hasNext()) {
                FullTestResult.FailedTest failedTest = (FullTestResult.FailedTest) failedTestsIterator.next();
                totalDuration += failedTest.duration;

                final String name = failedTest.test.toString();
                final String description = (String) TestConstants.DESCRIPTIONS.get(name);
                CharArrayWriter charArrayWriter = new CharArrayWriter();
                PrintWriter printWriter = new PrintWriter(charArrayWriter, true);
                failedTest.assertionFailedError.printStackTrace(printWriter);
                printWriter.close();
                charArrayWriter.close();

                testsuite.add(newFailedTestcase(failedTest.test.getClass().getName(), name + ": " + description,
                        failedTest.duration, failedTest.assertionFailedError.getMessage(),
                        charArrayWriter.toString()));
            }
        }

        if (!errorTests.isEmpty()) {
            Iterator errorTestsIterator = errorTests.iterator();
            while (errorTestsIterator.hasNext()) {
                FullTestResult.ErrorTest errorTest = (FullTestResult.ErrorTest) errorTestsIterator.next();
                totalDuration += errorTest.duration;

                final String name = errorTest.test.toString();
                final String description = (String) TestConstants.DESCRIPTIONS.get(name);
                CharArrayWriter charArrayWriter = new CharArrayWriter();
                PrintWriter printWriter = new PrintWriter(charArrayWriter, true);
                errorTest.throwable.printStackTrace(printWriter);
                printWriter.close();
                charArrayWriter.close();

                System.out.println("charArrayWriter.toString()=" + charArrayWriter.toString());
                testsuite.add(newErrorTestcase(errorTest.test.getClass().getName(), name + ": " + description,
                        errorTest.duration, errorTest.throwable.getMessage(), charArrayWriter.toString()));
            }
        }

        // total time of all tests
        testsuite.addAttribute("time", Float.toString(totalDuration / 1000f));
    }

    String logContent = null;
    final String logName = (String) session.getAttribute(TestConstants.ATTRIBUTE_LOG_NAME);
    if (logName != null) {
        try {
            logContent = TestLogController.readLog(logName);
        } catch (final Throwable th) {
            log("Error reading log file", th);
        }
    }

    testsuite.add(new DOMElement("system-out").addCDATA((logContent != null) ? logContent : ""));
    testsuite.add(new DOMElement("system-err").addCDATA(""));

    XMLWriter outputter = new XMLWriter(response.getWriter(), OutputFormat.createPrettyPrint());
    try {
        outputter.write(testsuite);
        outputter.close();
    } catch (IOException e) {
        throw new ServletException(e);
    }
}

From source file:com.jiangnan.es.orm.mybatis.util.MybatisMapperXmlGenerator.java

License:Apache License

/**
 * /*from   w w  w  .  ja v  a  2 s . c o m*/
 * @param document
 * @throws IOException
 */
private void write(Document document) throws IOException {
    XMLWriter xmlWriter = null;
    try {
        FileWriter writer = new FileWriter(new File(this.exportFileName));
        OutputFormat format = new OutputFormat();
        format.setEncoding("UTF-8");
        //? 
        format.setIndent(true);
        format.setIndent("    ");
        //? 
        format.setNewlines(true);
        xmlWriter = new XMLWriter(writer, format);
        xmlWriter.write(document);
    } finally {
        if (null != xmlWriter) {
            xmlWriter.close();
        }
    }
}

From source file:com.lafengmaker.tool.util.XMLDataUtil.java

License:Open Source License

/**
 * Save to xml file//from   www  .  ja v a  2s. c  o m
 * @param dom
 * @param sFilePathName
 * @param encode
 * @return
 * @throws CommonException
 */
public static boolean saveXML(Document dom, String sFilePathName, String encode) throws Exception {

    File file = new File(sFilePathName);

    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        FileOutputStream out = new FileOutputStream(file);
        // if(!encode.equals(ENCODE_UTF_8)){
        if (encode != null) {
            format.setEncoding(encode);
        }

        // format.setTrimText(true);
        XMLWriter xmlWriter = new XMLWriter(out, format);
        xmlWriter.write(dom);
        xmlWriter.flush();
        xmlWriter.close();
        return true;
    } catch (Exception e) {
        throw new RuntimeException("XMLDATAUTIL-SAVE_DOCUMENT-001", e);
    }

}

From source file:com.laudandjolynn.mytv.MyTvData.java

License:Apache License

public void writeData(String parent, String tag, String value) {
    logger.debug("write data to my tv data file: " + Constant.MY_TV_DATA_FILE_PATH);
    File file = new File(Constant.MY_TV_DATA_FILE_PATH);
    if (!file.exists()) {
        Document doc = DocumentHelper.createDocument();
        doc.addElement(Constant.APP_NAME);
        try {/*from  ww w  . j ava 2s  .co  m*/
            FileUtils.writeWithNIO(doc.asXML().getBytes(), Constant.MY_TV_DATA_FILE_PATH);
        } catch (IOException e) {
            throw new MyTvException(
                    "error occur while write data to file. -- " + Constant.MY_TV_DATA_FILE_PATH);
        }
    }
    SAXReader reader = new SAXReader();
    try {
        Document xmlDoc = reader.read(file);
        Element parentElement = xmlDoc.getRootElement();
        if (parent != null) {
            List<?> nodes = xmlDoc.selectNodes("//" + parent);
            if (nodes != null && nodes.size() > 0) {
                parentElement = (Element) nodes.get(0);
            }
        }
        parentElement.addElement(tag).setText(value);
        try {
            XMLWriter writer = new XMLWriter(new FileWriter(file));
            writer.write(xmlDoc);
            writer.close();
        } catch (IOException e) {
            throw new MyTvException(
                    "error occur while write data to file. -- " + Constant.MY_TV_DATA_FILE_PATH);
        }
    } catch (DocumentException e) {
        String msg = "can't parse xml file. -- " + Constant.MY_TV_DATA_FILE_PATH;
        throw new MyTvException(msg);
    }
}

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

License:Open Source License

public static void set(Setting setting) {
    try {// w  ww .  j  a v a2  s.c om
        File shopxxXmlFile = new ClassPathResource(CommonAttributes.SHOPXX_XML_PATH).getFile();
        Document document = new SAXReader().read(shopxxXmlFile);
        List<Element> elements = document.selectNodes("/shopxx/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();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }

        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(shopxxXmlFile);
            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();
    }
}

From source file:com.liveneo.plat.web.action.MakeLicfile.java

public static void createXmlFile(String fileName, Document doc) {
    try {/* w  w  w  .  j a  va2s.  c  o m*/
        File testfile = new File("fileName");
        if (testfile.exists()) {
            testfile.delete();
        }
        FileWriter fileWriter = new FileWriter(fileName);
        OutputFormat xmlFormat = OutputFormat.createPrettyPrint();
        xmlFormat.setEncoding("UTF-8");
        xmlFormat.setSuppressDeclaration(false);
        xmlFormat.setExpandEmptyElements(false);
        XMLWriter xmlWriter = new XMLWriter(fileWriter, xmlFormat);
        xmlWriter.write(doc);
        xmlWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.love320.templateparser.label.impl.LabelBeanDaoImpl.java

License:Apache License

private boolean XMLWriter() {
    try {//  w w w. j  av a2 s  .co m
        OutputFormat format = OutputFormat.createPrettyPrint();//?
        format.setEncoding("UTF-8");//?
        XMLWriter output = new XMLWriter(new FileWriter(new File(configPath)), format);//?
        output.write(DOCROOT.getDocument());//
        output.close();//

        return true;
    } catch (IOException e) {
        logger.error("IOException", e);
    }
    return false;
}

From source file:com.magicpwd._util.Jxml.java

License:Open Source License

public static void save(Document document, File file) throws IOException {
    // ?//from www.ja v a 2 s . c  o m
    OutputFormat format = OutputFormat.createPrettyPrint();
    // ??
    // OutputFormat format = OutputFormat.createCompactFormat();
    // XML?
    // format.setEncoding("GBK");
    XMLWriter writer = new XMLWriter(new FileWriter(file), format);
    writer.write(document);
    writer.close();
}