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:net.sf.jvifm.model.MimeManager.java

License:Open Source License

@SuppressWarnings("unchecked")
public void store() {

    try {/*from  ww  w.  ja  va 2 s  .  c  o  m*/
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("mimes");
        for (Iterator it = mimeInfo.keySet().iterator(); it.hasNext();) {
            String postfix = (String) it.next();
            Element filetypeEle = root.addElement("filetype");
            filetypeEle.addAttribute("postfix", postfix);
            List<String> appPathList = mimeInfo.get(postfix);
            for (String appPath : appPathList) {
                filetypeEle.addElement("appPath").addText(appPath);
            }
        }

        FileOutputStream fos = new FileOutputStream(storePath);
        OutputFormat outformat = OutputFormat.createPrettyPrint();

        outformat.setEncoding("UTF-8");
        BufferedOutputStream out = new BufferedOutputStream(fos);
        XMLWriter writer = new XMLWriter(out, outformat);

        writer.write(document);
        writer.flush();
        writer.close();
        fos.close();

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

}

From source file:net.sf.jvifm.model.ShortcutsManager.java

License:Open Source License

public void store() {

    try {// w  w  w . j a  v a2  s .  com

        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("commands");

        for (Shortcut shortcut : shortcutsList) {

            Element shortcutElement = root.addElement("command");

            shortcutElement.addElement("name").addText(shortcut.getName());
            shortcutElement.addElement("text").addText(shortcut.getText());

        }

        FileOutputStream fos = new FileOutputStream(storePath);
        OutputFormat outformat = OutputFormat.createPrettyPrint();

        outformat.setEncoding("UTF-8");
        BufferedOutputStream out = new BufferedOutputStream(fos);
        XMLWriter writer = new XMLWriter(out, outformat);

        writer.write(document);
        writer.flush();
        writer.close();
        fos.close();

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

}

From source file:net.shopxx.action.admin.InstallAction.java

public String save() throws URISyntaxException, IOException, DocumentException {
    if (isInstalled()) {
        return ajaxJsonErrorMessage("SHOP++?????");
    }/*  www  .  jav a2s  .  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("[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 (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("SHOP++?????");
}

From source file:net.sourceforge.sqlexplorer.dbproduct.AliasManager.java

License:Open Source License

/**
 * Saves all the Aliases to the users preferences
 * //from   w  w  w.  ja  va2  s .  c o m
 */
public void saveAliases() throws ExplorerException {
    DefaultElement root = new DefaultElement(Alias.ALIASES);
    for (Alias alias : aliases.values()) {
        root.add(alias.describeAsXml());
    }
    try {
        FileWriter writer = new FileWriter(new File(ApplicationFiles.USER_ALIAS_FILE_NAME));
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(writer, format);
        xmlWriter.write(root);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new ExplorerException(e);
    }
}

From source file:net.sourceforge.sqlexplorer.dbproduct.DriverManager.java

License:Open Source License

/**
 * Saves the drivers back to disk// w w  w . j a v  a 2s  . com
 * @throws ExplorerException
 */
public void saveDrivers() throws ExplorerException {
    Element root = new DefaultElement(DRIVERS);
    for (ManagedDriver driver : drivers.values())
        root.add(driver.describeAsXml());

    try {
        FileWriter writer = new FileWriter(new File(ApplicationFiles.USER_DRIVER_FILE_NAME));
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(writer, format);
        xmlWriter.write(root);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new ExplorerException(e);
    }
}

From source file:net.sourceforge.sqlexplorer.XMLUtils.java

License:Open Source License

public static void save(Element pRoot, File pFile) {
    try {//from  w ww.  j  ava  2 s  .  com
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(pFile), OutputFormat.createPrettyPrint());
        xmlWriter.startDocument();
        xmlWriter.write(pRoot);
        xmlWriter.endDocument();
        xmlWriter.flush();
        xmlWriter.close();
    } catch (Exception e) {
        SQLExplorerPlugin.error("Couldn't save: " + pFile.getAbsolutePath(), e);
    }

}

From source file:net.unicon.toro.installer.tools.MergeConfiguration.java

License:Open Source License

private void mergeWebChanges(Element el, File path) throws Exception {
    System.out.println("Merging web.xml changes to " + path.getAbsolutePath());
    Utils.instance().backupFile(path, true);

    OutputFormat format = OutputFormat.createPrettyPrint();

    SAXReader reader = new SAXReader();
    reader.setIncludeInternalDTDDeclarations(true);
    Document document = reader.read(new URL("file:" + path.getAbsolutePath()));
    SAXSource source = new DocumentSource(document);

    List<Element> filters = (List<Element>) el.selectNodes("add-filter/filter");
    List<Element> filterMappings = (List<Element>) el.selectNodes("add-filter-mapping/filter-mapping");
    List<Element> servlets = (List<Element>) el.selectNodes("add-servlet/servlet");
    List<Element> servletMappings = (List<Element>) el.selectNodes("add-servlet-mapping/servlet-mapping");
    List<Element> errorPages = (List<Element>) el.selectNodes("add-error-page/error-page");

    // remove previous changes
    StringWriter cleansedDocumentWriter = new StringWriter();
    WebXmlCleanserFilter cleaner = new WebXmlCleanserFilter(new XMLWriter(cleansedDocumentWriter));
    cleaner.parse(source.getInputSource());

    // add new changes
    try {/*from  w ww  . jav a  2 s . c  om*/
        Document cleansedDocument = reader.read(new StringReader(cleansedDocumentWriter.toString()));
        source = new DocumentSource(cleansedDocument);
        SAXWriter saxWriter = new WebXmlAdditionsWriter(new XMLWriter(new FileOutputStream(path), format),
                filters, filterMappings, servlets, servletMappings, errorPages);
        saxWriter.parse(source.getInputSource());
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:net.yrom.builder.util.ManifestParser.java

License:Apache License

public void write(File file) throws IOException {
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new FileWriter(file), format);
    writer.write(doc);/* w w  w  .  ja va  2 s  . c om*/
    writer.close();
}

From source file:news.Confirmation.java

public static void validateXMLByXSD() {
    String xmlFileName = "C:\\Users\\Andy\\Documents\\NetBeansProjects\\WebService\\build\\web\\XML\\HomeNews.xml";
    String xsdFileName = "C:\\Users\\Andy\\Documents\\NetBeansProjects\\WebService\\web\\Schmea.xsd";
    try {//from   w  w  w .  ja  v a 2 s.c  om
        //XML? 
        XMLErrorHandler errorHandler = new XMLErrorHandler();
        //? SAX ? 
        SAXParserFactory factory = SAXParserFactory.newInstance();
        //??? XML  
        factory.setValidating(true);
        //????? XML ??? 
        factory.setNamespaceAware(true);
        //??? SAXParser  
        SAXParser parser = factory.newSAXParser();
        //? 
        SAXReader xmlReader = new SAXReader();
        //??xml 
        Document xmlDocument = (Document) xmlReader.read(new File(xmlFileName));
        // XMLReader ? [url]http://sax.sourceforge.net/?selected=get-set[/url]  
        parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                "http://www.w3.org/2001/XMLSchema");
        parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "file:" + xsdFileName);
        //SAXValidator 
        SAXValidator validator = new SAXValidator(parser.getXMLReader());
        //????? 
        validator.setErrorHandler(errorHandler);
        // 
        validator.validate(xmlDocument);

        XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
        //???? 
        if (errorHandler.getErrors().hasContent()) {
            System.out.println("XMLXSD?");
            writer.write(errorHandler.getErrors());
        } else {
            System.out.println("Good! XMLXSD??");
        }
    } catch (Exception ex) {
        System.out.println("XML: " + xmlFileName + " XSD:" + xsdFileName
                + "\n " + ex.getMessage());
        ex.printStackTrace();
    }
}

From source file:nidonuevo.model.Engine.java

public void saveToXML() {

    //        try {
    //            Thread.sleep(3000);//Para esperar a q se cargue todo, despues lo borraremos
    //        } catch (InterruptedException ex) {
    //            Logger.getLogger(Engine.class.getName()).log(Level.SEVERE, null, ex);
    //        }// w  ww. ja v a  2 s .co m
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("GameData");
    //PLAYER
    Element player = root.addElement("Player");
    player.addElement("name").addText(LMS.getPlayer().getName());
    player.addElement("happiness").addText("" + LMS.getPlayer().getHappiness());
    player.addElement("numberOfFriends").addText("" + LMS.getPlayer().getNumberOfFriends());
    player.addElement("level").addText("" + LMS.getPlayer().getLevel());
    player.addElement("numerOfTrophies").addText("" + LMS.getPlayer().getNumberOfTrophies());
    ////FRIENDS
    Element friends = player.addElement("Friends");
    for (int i = 0; i < LMS.getPlayer().getFriends().size(); i++) {
        Element friend = friends.addElement("Friend").addAttribute("id",
                "" + LMS.getPlayer().getFriends().get(i).getId());
    }
    ////INVENTORY
    Element inventory = player.addElement("Inventory");
    inventory.addElement("Capacity").addText("" + LMS.getPlayer().getInventory().getCapacity());
    inventory.addElement("Quantity").addText("" + LMS.getPlayer().getInventory().getQuantity());
    //////ITEMS
    Element items = inventory.addElement("Items");
    for (int i = 0; i < LMS.getPlayer().getInventory().getItems().size(); i++) {
        Element item = items.addElement("Item").addAttribute("id",
                "" + LMS.getPlayer().getInventory().getItems().get(i).getId());
        item.addElement("stock").addText("" + LMS.getPlayer().getInventory().getItems().get(i).getStock());
    }
    //Mapa Actual
    Element cMap = root.addElement("CurrentMap");
    cMap.addElement("Map").addText("" + getCurrentMap());

    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setIndent(true);
        XMLWriter writer = new XMLWriter(new FileWriter("GameData.xml"), format);
        writer.write(document);
        writer.setIndentLevel(2);
        writer.close();
    } catch (IOException ex) {
        Logger.getLogger(Engine.class.getName()).log(Level.SEVERE, null, ex);
    }

}