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.eurelis.opencms.workflows.workflows.A_OSWorkflowManager.java

License:Open Source License

/**
 * Get the OpenCMS RFS OSWorkflow configuration file and update it with the given filepath.
 * // w  w w.  ja  va 2  s  .  c  o m
 * @param listOfWorkflowsFilepath
 *            the path of the file containing the list of available workflow descriptions
 * @return the path in RFS of the updated file
 * @throws DocumentException
 *             this exception is thrown if an error occurs during the parsing of the document
 * @throws IOException
 *             this exception is thrown if a problem occurs during overwriting of the config file
 */
private String updateOSWorkflowConfigFile(String listOfWorkflowsFilepath)
        throws CmsException, DocumentException, IOException {

    // get file path
    String configFilePath = this.getWebINFPath() + ModuleSharedVariables.SYSTEM_FILE_SEPARATOR
            + OSWORKFLOWCONFIGFILE_RFSFILEPATH;

    File listOfWorkflowsFile = new File(listOfWorkflowsFilepath);
    // Load Jdom parser
    SAXReader reader = new SAXReader();
    Document document = reader.read(configFilePath);
    Node propertyNode = document.selectSingleNode(OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_XPATH);
    if (propertyNode != null) {
        if (propertyNode.getNodeType() == Node.ELEMENT_NODE) {
            // convert Node into element
            Element propertyElement = (Element) propertyNode;

            // update the Attribute
            Attribute valueAttribute = propertyElement
                    .attribute(OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_ATTRIBUTNAME);

            valueAttribute.setValue(listOfWorkflowsFile.toURI().toString());

        } else {
            LOGGER.debug("the node with Xpath " + OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_XPATH + " in the file "
                    + configFilePath + " doesn't correspond to an element");
        }

    } else {
        Node parentNode = document.selectSingleNode(OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_PARENT_XPATH);
        if (parentNode != null) {

            if (parentNode.getNodeType() == Node.ELEMENT_NODE) {
                // convert Node into element
                Element parentElement = (Element) parentNode;

                // add new property
                Element propertyElement = parentElement.addElement("property");

                // add attributs
                propertyElement.addAttribute("key", "resource");
                propertyElement.addAttribute("value", listOfWorkflowsFile.toURI().toString());

            } else {
                LOGGER.debug("the node with Xpath " + OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_XPATH
                        + " in the file " + configFilePath + " doesn't correspond to an element");
            }

        } else {
            LOGGER.debug("the node with Xpath " + OSWORKFLOWCONFIGFILE_PROPERTYTOUPDATE_PARENT_XPATH
                    + " in the file " + configFilePath + " has not been found.");
        }
    }

    /*
     * Get a string of the resulting file
     */

    // creating of a buffer that will collect result
    ByteArrayOutputStream xmlContent = new ByteArrayOutputStream();

    // Pretty print the document to xmlContent
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(xmlContent, format);
    writer.write(document);
    writer.flush();
    writer.close();

    // get the config file content as a String
    String documentContent = new String(xmlContent.toByteArray());

    /*
     * Overwrite the config file
     */
    FileWriter.writeFile(configFilePath, documentContent);

    return configFilePath;
}

From source file:com.eurelis.tools.xml.transformation.local.LocalDocumentSource.java

License:Open Source License

/**
 * Write a dom4j document to the location specified by a File object
 *
 * @param file the location where to write the document
 * @param document the dom4j document to write
 *//* w ww.ja v a 2 s . c om*/
public static void writeDocument(File file, Document document) {
    XMLWriter xmlWriter = null;

    OutputStream os = null;
    OutputStreamWriter osw = null;

    try {

        os = new FileOutputStream(file);
        osw = new OutputStreamWriter(os, "UTF-8");

        xmlWriter = new XMLWriter(osw, new OutputFormat("  ", true, "UTF-8"));
        xmlWriter.write(document);

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (xmlWriter != null) {
            try {
                xmlWriter.flush();
                xmlWriter.close();

                osw.close();
                os.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

From source file:com.ewcms.content.particular.web.ProjectBasicAction.java

License:Open Source License

public void exportXML() {
    if (getSelections() != null && getSelections().size() > 0) {
        ServletOutputStream out = null;//ww w. j a  v  a  2s .c om
        try {
            Document document = particularFac.exportXml(getSelections());

            StringWriter stringWriter = new StringWriter();

            OutputFormat xmlFormat = new OutputFormat();
            xmlFormat.setEncoding("UTF-8");
            XMLWriter xmlWriter = new XMLWriter(stringWriter, xmlFormat);
            xmlWriter.write(document);
            xmlWriter.flush();
            xmlWriter.close();

            HttpServletResponse resp = Struts2Util.getResponse();
            out = resp.getOutputStream();
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/xml; charset=UTF-8");
            resp.addHeader("Content-Disposition", "attachment; filename=xmjbxx.xml");
            out.write(stringWriter.toString().getBytes("UTF-8"));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
                out = null;
            }
        }
    }
}

From source file:com.example.sample.pMainActivity.java

License:Apache License

/**
 * XML/*  w w  w . j  av  a 2 s  .  c om*/
 * @param doc
 * @throws IOException
 */
public void saveDocument(Document doc) {
    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(
                new FileOutputStream(
                        Environment.getDataDirectory() + "/data/com.example.sample/shared_prefs/tatans2.xml"),
                format);
        writer.write(doc);
        writer.close();
    } catch (IOException e) {
        Log.d(TAG, "IOException: " + e.toString());
    }

}

From source file:com.faithbj.shop.action.admin.InstallAction.java

public String save() throws URISyntaxException, IOException, DocumentException {
    if (isInstalled()) {
        return ajaxJsonErrorMessage("CAIJINGLING?????");
    }/*from w  w w .ja v a  2 s  .  c o  m*/
    if (StringUtils.isEmpty(databaseHost)) {
        return ajaxJsonErrorMessage("?!");
    }
    if (StringUtils.isEmpty(databasePort)) {
        return ajaxJsonErrorMessage("??!");
    }
    if (StringUtils.isEmpty(databaseUsername)) {
        return ajaxJsonErrorMessage("???!");
    }
    if (StringUtils.isEmpty(databasePassword)) {
        return ajaxJsonErrorMessage("??!");
    }
    if (StringUtils.isEmpty(databaseName)) {
        return ajaxJsonErrorMessage("???!");
    }
    if (StringUtils.isEmpty(adminUsername)) {
        return ajaxJsonErrorMessage("???!");
    }
    if (StringUtils.isEmpty(adminPassword)) {
        return ajaxJsonErrorMessage("??!");
    }
    if (StringUtils.isEmpty(installStatus)) {
        Map<String, String> jsonMap = new HashMap<String, String>();
        jsonMap.put(STATUS, "requiredCheckFinish");
        return ajaxJson(jsonMap);
    }

    String jdbcUrl = "jdbc:mysql://" + databaseHost + ":" + databasePort + "/" + databaseName
            + "?useUnicode=true&characterEncoding=UTF-8";
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    try {
        // ?
        connection = DriverManager.getConnection(jdbcUrl, databaseUsername, databasePassword);
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        String[] types = { "TABLE" };
        resultSet = databaseMetaData.getTables(null, databaseName, "%", types);
        if (StringUtils.equalsIgnoreCase(installStatus, "databaseCheck")) {
            Map<String, String> jsonMap = new HashMap<String, String>();
            jsonMap.put(STATUS, "databaseCheckFinish");
            return ajaxJson(jsonMap);
        }

        // ?
        if (StringUtils.equalsIgnoreCase(installStatus, "databaseCreate")) {
            StringBuffer stringBuffer = new StringBuffer();
            BufferedReader bufferedReader = null;
            String sqlFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI()
                    .getPath() + SQL_INSTALL_FILE_NAME;
            bufferedReader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(sqlFilePath), "UTF-8"));
            String line = "";
            while (null != line) {
                line = bufferedReader.readLine();
                stringBuffer.append(line);
                if (null != line && line.endsWith(";")) {
                    System.out.println("[CAIJINGLING?]SQL: " + line);
                    preparedStatement = connection.prepareStatement(stringBuffer.toString());
                    preparedStatement.executeUpdate();
                    stringBuffer = new StringBuffer();
                }
            }
            String insertAdminSql = "INSERT INTO `admin` VALUES ('402881862bec2a21012bec2bd8de0003','2010-10-10 0:0:0','2010-10-10 0:0:0','','admin@shopxx.net',b'1',b'0',b'0',b'0',NULL,NULL,0,NULL,'?','"
                    + DigestUtils.md5Hex(adminPassword) + "','" + adminUsername + "');";
            String insertAdminRoleSql = "INSERT INTO `admin_role` VALUES ('402881862bec2a21012bec2bd8de0003','402881862bec2a21012bec2b70510002');";
            preparedStatement = connection.prepareStatement(insertAdminSql);
            preparedStatement.executeUpdate();
            preparedStatement = connection.prepareStatement(insertAdminRoleSql);
            preparedStatement.executeUpdate();
        }
    } catch (SQLException e) {
        e.printStackTrace();
        return ajaxJsonErrorMessage("???!");
    } finally {
        try {
            if (resultSet != null) {
                resultSet.close();
                resultSet = null;
            }
            if (preparedStatement != null) {
                preparedStatement.close();
                preparedStatement = null;
            }
            if (connection != null) {
                connection.close();
                connection = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // ???
    String configFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()
            + JDBC_CONFIG_FILE_NAME;
    Properties properties = new Properties();
    properties.put("jdbc.driver", "com.mysql.jdbc.Driver");
    properties.put("jdbc.url", jdbcUrl);
    properties.put("jdbc.username", databaseUsername);
    properties.put("jdbc.password", databasePassword);
    properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
    properties.put("hibernate.show_sql", "false");
    properties.put("hibernate.format_sql", "false");
    OutputStream outputStream = new FileOutputStream(configFilePath);
    properties.store(outputStream, JDBC_CONFIG_FILE_DESCRIPTION);
    outputStream.close();

    // ??
    String backupWebConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI()
            .getPath() + BACKUP_WEB_CONFIG_FILE_NAME;
    String backupApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + BACKUP_APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String backupCompassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + BACKUP_COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String backupSecurityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + BACKUP_SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME;

    String webConfigFilePath = new File(
            Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()).getParent() + "/"
            + WEB_CONFIG_FILE_NAME;
    String applicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("")
            .toURI().getPath() + APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String compassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String securityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME;

    FileUtils.copyFile(new File(backupWebConfigFilePath), new File(webConfigFilePath));
    FileUtils.copyFile(new File(backupApplicationContextConfigFilePath),
            new File(applicationContextConfigFilePath));
    FileUtils.copyFile(new File(backupCompassApplicationContextConfigFilePath),
            new File(compassApplicationContextConfigFilePath));
    FileUtils.copyFile(new File(backupSecurityApplicationContextConfigFilePath),
            new File(securityApplicationContextConfigFilePath));

    // ??
    String systemConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI()
            .getPath() + SystemConfigUtil.CONFIG_FILE_NAME;
    File systemConfigFile = new File(systemConfigFilePath);
    SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(systemConfigFile);
    Element rootElement = document.getRootElement();
    Element systemConfigElement = rootElement.element("systemConfig");
    Node isInstalledNode = document.selectSingleNode("/shopxx/systemConfig/isInstalled");
    if (isInstalledNode == null) {
        isInstalledNode = systemConfigElement.addElement("isInstalled");
    }
    isInstalledNode.setText("true");
    try {
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();// XML?
        outputFormat.setEncoding("UTF-8");// XML?
        outputFormat.setIndent(true);// ?
        outputFormat.setIndent("   ");// TAB?
        outputFormat.setNewlines(true);// ??
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(systemConfigFile), outputFormat);
        xmlWriter.write(document);
        xmlWriter.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ajaxJsonSuccessMessage("CAIJINGLING?????");
}

From source file:com.feilong.tools.dom4j.Dom4jUtil.java

License:Apache License

/**
 * ? xml.<br>/* www .jav a 2 s  . co m*/
 * 
 * <pre>
 * {@code
 * <wddxPacket version='1.0'><header/><data><struct><var name='TRANSACTIONID'><string></string></var><var name='ACQUIRERRESPONSECODE'><string></string></var><var name='SCRUBMESSAGE'><string>Invalid siteID</string></var><var name='AMOUNT'><string></string></var><var name='SERVICEVERSION'><string>2.0</string></var><var name='TRANSACTIONSCRUBCODE'><string></string></var><var name='MERCHANTTRANSACTIONID'><string>010003170001</string></var><var name='CURRENCY'><string></string></var><var name='TRANSACTIONSTATUS'><string></string></var><var name='SITEID'><string>Blanja2</string></var><var name='TRANSACTIONDATE'><string></string></var><var name='ACQUIRERCODE'><string></string></var><var name='SCRUBCODE'><string>50007</string></var><var name='TRANSACTIONSCRUBMESSAGE'><string></string></var><var name='ACQUIRERAPPROVALCODE'><string></string></var><var name='TRANSACTIONTYPE'><string>AUTHORIZATION</string></var></struct></data></wddxPacket>
 * }
 * </pre>
 * 
 * ?
 * 
 * <pre>
 * {@code
 * <wddxPacket version="1.0">
 *    <header/>
 *    <data>
 *       <struct>
 *          <var name="TRANSACTIONID">
 *             <string/>
 *          </var>
 *          <var name="ACQUIRERRESPONSECODE">
 *             <string/>
 *          </var>
 *          <var name="SCRUBMESSAGE">
 *             <string>Invalid siteID</string>
 *          </var>
 *          <var name="AMOUNT">
 *             <string/>
 *          </var>
 *          <var name="SERVICEVERSION">
 *             <string>2.0</string>
 *          </var>
 *          <var name="TRANSACTIONSCRUBCODE">
 *             <string/>
 *          </var>
 *          <var name="MERCHANTTRANSACTIONID">
 *             <string>010003170001</string>
 *          </var>
 *          <var name="CURRENCY">
 *             <string/>
 *          </var>
 *          <var name="TRANSACTIONSTATUS">
 *             <string/>
 *          </var>
 *          <var name="SITEID">
 *             <string>Blanja2</string>
 *          </var>
 *          <var name="TRANSACTIONDATE">
 *             <string/>
 *          </var>
 *          <var name="ACQUIRERCODE">
 *             <string/>
 *          </var>
 *          <var name="SCRUBCODE">
 *             <string>50007</string>
 *          </var>
 *          <var name="TRANSACTIONSCRUBMESSAGE">
 *             <string/>
 *          </var>
 *          <var name="ACQUIRERAPPROVALCODE">
 *             <string/>
 *          </var>
 *          <var name="TRANSACTIONTYPE">
 *             <string>AUTHORIZATION</string>
 *          </var>
 *       </struct>
 *    </data>
 * </wddxPacket>
 * 
 * }
 * </pre>
 *
 * @param xmlString
 *            the xml string
 * @param encoding
 *            the encoding
 * @param writer
 *            the writer
 * @return the string
 * @throws Dom4jException
 *             the dom4j exception
 * @since 1.0.8
 */
public static String format(String xmlString, String encoding, Writer writer) throws Dom4jException {

    OutputFormat outputFormat = OutputFormat.createPrettyPrint(); // XML?
    outputFormat.setEncoding(encoding); // XML?
    outputFormat.setSuppressDeclaration(true);
    outputFormat.setIndent(true); // ?
    outputFormat.setIndent("   "); // tab?
    outputFormat.setNewlines(true); // ??

    XMLWriter xmlWriter = new XMLWriter(writer, outputFormat);
    xmlWriter.setEscapeText(false);

    Document document = string2Document(xmlString);
    try {
        xmlWriter.write(document);
        xmlWriter.close();

        return writer.toString();
    } catch (IOException e) {
        throw new Dom4jException(e);
    }
}

From source file:com.founder.fix.fixflow.core.impl.util.XmlUtil.java

License:Apache License

public static void save(Document document, String fileName, String encoding) throws Exception {
    XMLWriter writer = null;
    try {//  www .  j  a  v a2s  .c  om
        OutputFormat format = OutputFormat.createPrettyPrint();

        if (!"".equals(encoding))
            format.setEncoding(encoding);
        else
            format.setEncoding("UTF-8");

        writer = new XMLWriter(new FileWriter(fileName), format);
        writer.write(document);
        writer.close();
    } catch (Exception e) {
        throw e;
    } finally {
        if (writer != null)
            writer.close();

    }

}

From source file:com.glaf.core.util.Dom4jUtils.java

License:Apache License

public static void createDoument(Document doc, String filename, OutputFormat format) {
    FileWriter out = null;//  ww w  .  j  av  a2  s  . c  o  m
    XMLWriter writer = null;
    try {
        out = new FileWriter(filename);
        writer = new XMLWriter(out, format);
        writer.write(doc);
        out.close();
    } catch (IOException ex) {
        writer = null;
        out = null;
        throw new RuntimeException(ex.getMessage());
    } finally {
        try {
            if (writer != null) {
                writer.close();
                writer = null;
            }
            if (out != null) {
                out.close();
                out = null;
            }
        } catch (IOException ioe) {
        }
    }
}

From source file:com.glaf.core.util.Dom4jUtils.java

License:Apache License

/**
 * ??//from   ww  w.  j av a 2  s  .  c o  m
 * 
 * @param doc
 *            Document
 * @param format
 *            OutputFormat
 * @return byte[]
 * @throws Exception
 */
public static byte[] getBytesFromDocument(Document doc, OutputFormat format) {
    ByteArrayOutputStream baos = null;
    BufferedOutputStream bos = null;
    XMLWriter writer = null;
    byte[] data = null;
    try {
        baos = new ByteArrayOutputStream();
        bos = new BufferedOutputStream(baos);
        writer = new XMLWriter(bos, format);
        writer.write(doc);
        if (baos != null) {
            data = baos.toByteArray();
        }
        bos.close();
        baos.close();
        baos = null;
        return data;
    } catch (IOException ex) {
        bos = null;
        writer = null;
        throw new RuntimeException(ex);
    } finally {
        try {
            if (writer != null) {
                writer.close();
                writer = null;
            }
            if (bos != null) {
                bos.close();
                bos = null;
            }
            if (baos != null) {
                baos.close();
                baos = null;
            }
        } catch (IOException ioe) {
        }
    }
}

From source file:com.globalsight.cxe.adapter.msoffice.ExcelRepairer.java

License:Apache License

private void repairWt() throws Exception {
    List<File> fs = getExcelRepairFiles();

    for (File f : fs) {
        String content = FileUtil.readFile(f, "utf-8");

        XmlParser parser = new XmlParser();
        org.dom4j.Document document = parser.parseXml(content);
        Element element = document.getRootElement();

        @SuppressWarnings("unchecked")
        List<Element> wts = element.selectNodes("//t");

        for (Element wt : wts) {
            if (wt == null)
                continue;

            @SuppressWarnings("unchecked")
            List<Element> es = wt.elements();
            if (!wt.isTextOnly()) {
                String text = wt.getStringValue();
                for (Element e : es) {
                    wt.remove(e);//from  w w  w. j a va  2 s .c o m
                }

                wt.setText(text);
            }
        }

        Writer fileWriter = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
        XMLWriter xmlWriter = new XMLWriter(fileWriter);
        xmlWriter.write(document);
        xmlWriter.close();
    }
}