Example usage for org.dom4j.io OutputFormat createPrettyPrint

List of usage examples for org.dom4j.io OutputFormat createPrettyPrint

Introduction

In this page you can find the example usage for org.dom4j.io OutputFormat createPrettyPrint.

Prototype

public static OutputFormat createPrettyPrint() 

Source Link

Document

A static helper method to create the default pretty printing format.

Usage

From source file:cn.com.iscs.base.util.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.
 *//*  w  w w.j  ava 2s.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), "UTF-8"));
        OutputFormat prettyPrinter = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(writer, prettyPrinter);
        xmlWriter.write(document);
    } catch (Exception e) {
        e.printStackTrace();
        // There were errors so abort replacing the old property file.
        error = true;
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e1) {
                //          Log.error(e1);
                e1.printStackTrace();
                error = true;
            }
        }
    }

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

From source file:cn.com.xdays.xshop.action.admin.InstallAction.java

public String save() throws URISyntaxException, IOException, DocumentException {
    if (isInstalled()) {
        return ajaxJsonErrorMessage("SHOP++?????");
    }// ww w.j ava2  s .  com
    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 {
        Class.forName("com.mysql.jdbc.Driver");
        // ?
        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("[SHOP++?]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 (Exception 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("SHOP++?????");
}

From source file:cn.feng.web.ssm.excel.controller.StringUtils.java

License:Apache License

/**
 * /* ww  w. jav a  2 s .  c  o m*/
 * dom4j 
 * @param document
 * @return
 */
public static String document2str(Document document, String chartset) {
    String result = "";
    OutputFormat format;
    ByteArrayOutputStream out;
    try {
        format = OutputFormat.createPrettyPrint();
        format.setEncoding(chartset);
        out = new ByteArrayOutputStream();
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(document);
        writer.flush();
        writer.close();
        result = out.toString(format.getEncoding());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:cn.ict.zyq.bestConf.util.ParseXMLToYaml.java

License:Open Source License

public static void appendXMLByDOM4J(HashMap target, String source, String destination) throws IOException {

    SAXReader reader = new SAXReader();
    try {//ww w.ja va  2s.co m

        Document document = reader.read(new File(source));
        Element configStore = document.getRootElement();
        Iterator iter = target.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = entry.getKey().toString();
            String val = entry.getValue().toString();
            Element property = configStore.addElement("property");
            Element name = property.addElement("name");
            name.setText(key);
            Element value = property.addElement("value");
            value.setText(val);
        }
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(new FileOutputStream(destination), format);
        writer.write(document);
        writer.close();

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

From source file:cn.itcreator.android.reader.util.XMLUtil.java

License:Open Source License

/**
 * save the list to a xml file/*from ww  w .j  a va 2  s .c  o  m*/
 * @param list the list u wanna save
 * @return
 */
public boolean saveToFile(List<BookMark> list) {
    boolean result = true;
    Element root = null;
    root = mDocument.getRootElement();
    if (null == root) {
        root = mDocument.addElement("bookmark");
    }
    for (BookMark bookMark : list) {
        Element mark = root.addElement("mark");
        mark.addAttribute("markName", bookMark.getMarkName());
        mark.addAttribute("currentOffset", "" + bookMark.getCurrentOffset());
    }
    OutputFormat format = OutputFormat.createPrettyPrint();
    /** Give the xml file encode */
    format.setEncoding(Constant.UTF8);
    try {
        XMLWriter writer = new XMLWriter(new FileOutputStream(mFilePath), format);
        writer.write(mDocument);
        writer.close();
    } catch (IOException e) {
        result = false;
    }
    return result;
}

From source file:cn.mario256.blog.util.SystemUtils.java

License:Open Source License

/**
 * //w ww  .  j  av a 2s  .  co m
 * 
 * @param setting
 *            
 */
@SuppressWarnings("unchecked")
public static void setSetting(Setting setting) {
    Assert.notNull(setting);

    try {
        File turingXmlFile = new ClassPathResource(CommonAttributes.TURING_XML_PATH).getFile();
        Document document = new SAXReader().read(turingXmlFile);
        List<org.dom4j.Element> elements = document.selectNodes("/turing/setting");
        for (org.dom4j.Element element : elements) {
            try {
                String name = element.attributeValue("name");
                String value = BEAN_UTILS.getProperty(setting, name);
                Attribute attribute = element.attribute("value");
                attribute.setValue(value);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }

        XMLWriter xmlWriter = null;
        try {
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            outputFormat.setIndent(true);
            outputFormat.setIndent("   ");
            outputFormat.setNewlines(true);
            xmlWriter = new XMLWriter(new FileOutputStream(turingXmlFile), outputFormat);
            xmlWriter.write(document);
            xmlWriter.flush();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage(), e);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            try {
                if (xmlWriter != null) {
                    xmlWriter.close();
                }
            } catch (IOException e) {
            }
        }
        Ehcache cache = CACHE_MANAGER.getEhcache(Setting.CACHE_NAME);
        String cacheKey = "setting";
        cache.put(new Element(cacheKey, setting));
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.adobe.ac.pmd.metrics.engine.AbstractMetrics.java

License:Apache License

public void execute(final File outputFile) throws DocumentException, IOException {
    final String builtReport = buildReport(loadMetrics());
    final Document document = DocumentHelper.parseText(builtReport);
    final OutputFormat format = OutputFormat.createPrettyPrint();

    if (!outputFile.exists()) {
        if (outputFile.createNewFile() == false) {
            LOGGER.warning("Could not create a new output file");
        }/*w  w  w .  j  a v a 2  s .  c  o  m*/
    }

    final XMLWriter writer = new XMLWriter(new FileOutputStream(outputFile), format);
    writer.write(document);
    writer.close();
}

From source file:com.ai.tools.generator.util.XMLFormatter.java

License:Open Source License

public static String toString(Branch branch, String indent, boolean expandEmptyElements) throws IOException {
    ByteArrayMaker bam = new ByteArrayMaker();

    OutputFormat format = OutputFormat.createPrettyPrint();

    format.setExpandEmptyElements(expandEmptyElements);
    format.setIndent(indent);/*from   w  w  w  .  ja va  2  s.c o m*/
    format.setLineSeparator("\n");

    XMLWriter writer = new XMLWriter(bam, format);

    writer.write(branch);

    String content = bam.toString(StringPool.UTF8);

    // LEP-4257

    //content = StringUtil.replace(content, "\n\n\n", "\n\n");
    if (content.endsWith("\n\n")) {
        content = content.substring(0, content.length() - 2);
    }

    if (content.endsWith("\n")) {
        content = content.substring(0, content.length() - 1);
    }

    while (content.indexOf(" \n") != -1) {
        content = StringUtil.replace(content, " \n", "\n");
    }

    return content;
}

From source file:com.alibaba.antx.util.SimpleXMLWriter.java

License:Open Source License

/**
 * XML writer//w  w w  . j ava 2  s .c o  m
 *
 * @param file XML
 * @throws IOException 
 */
public SimpleXMLWriter(File file) throws IOException {
    super(new FileOutputStream(file), OutputFormat.createPrettyPrint());
}

From source file:com.alibaba.citrus.springext.support.SchemaUtil.java

License:Open Source License

/** DOM */
public static void writeDocument(Document doc, Writer writer, String charset) throws IOException {
    charset = defaultIfEmpty(trimToNull(charset), "UTF-8");

    OutputFormat format = OutputFormat.createPrettyPrint();

    format.setEncoding(charset);//from  w w  w.  j  a  va  2 s. com
    format.setIndent(true);
    format.setIndentSize(4);

    XMLWriter xmlWriter = new XMLWriter(writer, format);
    xmlWriter.write(doc);
    xmlWriter.flush();
}