Example usage for org.dom4j.io XMLWriter XMLWriter

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

Introduction

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

Prototype

public XMLWriter(OutputStream out, OutputFormat format) throws UnsupportedEncodingException 

Source Link

Usage

From source file:com.xpn.xwiki.objects.BaseCollection.java

License:Open Source License

public String toXMLString() {
    Document doc = new DOMDocument();
    doc.setRootElement(toXML(null));//from  w w  w  .j  av a2  s.c om
    OutputFormat outputFormat = new OutputFormat("", true);
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out, outputFormat);
    try {
        writer.write(doc);
        return out.toString();
    } catch (IOException e) {
        e.printStackTrace();

        return "";
    }
}

From source file:com.xpn.xwiki.objects.BaseProperty.java

License:Open Source License

public String toXMLString() {
    Document doc = new DOMDocument();
    doc.setRootElement(toXML());/*from  w ww  .j a v a2s  .  c  o  m*/
    OutputFormat outputFormat = new OutputFormat("", true);
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out, outputFormat);
    try {
        writer.write(doc);

        return out.toString();
    } catch (IOException e) {
        e.printStackTrace();

        return "";
    }
}

From source file:com.xpn.xwiki.pdf.impl.PdfExportImpl.java

License:Open Source License

/**
 * Apply a CSS style sheet to an XHTML document and return the document with the resulting style properties inlined
 * in <tt>style</tt> attributes.
 * /*w  ww .j a  v a  2s . com*/
 * @param html the valid XHTML document to style
 * @param css the style sheet to apply
 * @param context the current request context
 * @return the document with inlined style
 */
private String applyCSS(String html, String css, XWikiContext context) {
    try {
        // Prepare the input
        Reader re = new StringReader(html);
        InputSource source = new InputSource(re);
        SAXReader reader = new SAXReader(XHTMLDocumentFactory.getInstance());
        reader.setEntityResolver(new DefaultEntityResolver());
        XHTMLDocument document = (XHTMLDocument) reader.read(source);

        // Apply the style sheet
        document.setDefaultStyleSheet(new DOM4JCSSStyleSheet(null, null, null));
        document.addStyleSheet(new org.w3c.css.sac.InputSource(new StringReader(css)));
        applyInlineStyle(document.getRootElement());
        OutputFormat outputFormat = new OutputFormat("", false);
        if ((context == null) || (context.getWiki() == null)) {
            outputFormat.setEncoding("UTF-8");
        } else {
            outputFormat.setEncoding(context.getWiki().getEncoding());
        }
        StringWriter out = new StringWriter();
        XMLWriter writer = new XMLWriter(out, outputFormat);
        writer.write(document);
        String result = out.toString();
        // Debug output
        if (LOG.isDebugEnabled()) {
            LOG.debug("HTML with CSS applied: " + result);
        }
        return result;
    } catch (Exception ex) {
        LOG.warn("Failed to apply CSS: " + ex.getMessage(), ex);
        return html;
    }
}

From source file:com.xpn.xwiki.tool.xar.XarMojo.java

License:Open Source License

/**
 * Create and add package configuration file to the package.
 * //from  w w w .  j a  v a 2 s  . com
 * @param packageFile the package when to add configuration file.
 * @param files the files in the package.
 * @throws Exception error when writing the configuration file.
 */
private void generatePackageXml(File packageFile, Collection<ArchiveEntry> files) throws Exception {
    getLog().info("Generating package.xml descriptor at [" + packageFile.getPath() + "]");

    OutputFormat outputFormat = new OutputFormat("", true);
    outputFormat.setEncoding(this.encoding);
    OutputStream out = new FileOutputStream(packageFile);
    XMLWriter writer = new XMLWriter(out, outputFormat);
    writer.write(toXML(files));
    writer.close();
    out.close();
}

From source file:com.yahoo.validatar.report.junit.JUnitFormatter.java

License:Apache License

/**
 * {@inheritDoc}/*w w  w .j a va  2 s  . co  m*/
 * Writes out the report for the given testSuites in the JUnit XML format.
 */
@Override
public void writeReport(List<TestSuite> testSuites) throws IOException {
    Document document = DocumentHelper.createDocument();

    Element testSuitesRoot = document.addElement("testsuites");

    // Output for each test suite
    for (TestSuite testSuite : testSuites) {
        Element testSuiteRoot = testSuitesRoot.addElement("testsuite")
                .addAttribute("tests", Integer.toString(testSuite.queries.size() + testSuite.tests.size()))
                .addAttribute("name", testSuite.name);

        for (Query query : testSuite.queries) {
            Element queryNode = testSuiteRoot.addElement("testcase").addAttribute("name", query.name);
            if (query.failed()) {
                String failureMessage = StringUtils.join(query.getMessages(), ", ");
                queryNode.addElement("failed").addText(failureMessage);
            }
        }
        for (Test test : testSuite.tests) {
            Element testNode = testSuiteRoot.addElement("testcase").addAttribute("name", test.name);
            if (test.failed()) {
                String failedAsserts = StringUtils.join(test.getMessages(), ", ");
                String failureMessage = "Description: " + test.description + ";\n" + "Failed asserts: "
                        + failedAsserts + "\n";
                testNode.addElement("failed").addText(failureMessage);
            }
        }
    }

    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new FileWriter(outputFile), format);
    writer.write(document);
    writer.close();
}

From source file:com.yeliu.Main.java

License:Open Source License

/**
 * ??manifest//from   ww  w.  j  av a 2 s. co m
 * @param channel
 * @return
 */
private File saveChannelManifest(String channel) {
    OutputFormat format = OutputFormat.createPrettyPrint();
    //      format.setEncoding("GBK");
    // ???XML  
    File out = new File(
            processDirPath + File.separator + "manifesttemp" + File.separator + "AndroidManifest.xml");
    File outDir = out.getParentFile();
    if (!outDir.exists()) {
        outDir.mkdirs();
    }
    XMLWriter writer = null;
    try {
        writer = new XMLWriter(new FileWriter(out), format);
        writer.write(xmlDoc); //  
        return out;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

From source file:com.zg.action.admin.InstallAction.java

public String save() throws URISyntaxException, IOException, DocumentException {
    if (isInstalled()) {
        return ajaxJsonErrorMessage("SHOP++?????");
    }//from w ww  .j av  a 2 s  . co 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() + SystemConfigUtils.CONFIG_FILE_NAME;
    File systemConfigFile = new File(
            ConfigurationManager.getConfigProperties(SystemConfigUtils.CONFIG_FILE_PATH_NAME));
    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:com.zimbra.common.soap.DomUtil.java

License:Open Source License

/** Convert an Element to a String. */
public static String toString(Element env, boolean prettyPrint) {
    if (prettyPrint) {
        StringWriter buff = new StringWriter();
        try {//w  w  w. j a va 2 s . c o m
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter writer = new XMLWriter(buff, format);
            writer.write(env);
            writer.close();
        } catch (IOException e) {
            // ignore, since StringWriter doesn't throw IOExceptions
        }
        return buff.toString();
    } else {
        return env.asXML();
    }
}

From source file:com.zimbra.cs.account.accesscontrol.RightManager.java

License:Open Source License

private void writeXML(String fileName, Document document) throws IOException {
    // Pretty print the document to output file
    OutputFormat format = OutputFormat.createPrettyPrint();

    BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
    XMLWriter xmlWriter = new XMLWriter(writer, format);
    xmlWriter.write(document);//from   w  w  w . ja v  a 2 s.  com
    writer.close();
}

From source file:com.zimbra.cs.dav.client.DavRequest.java

License:Open Source License

public String getRequestMessageString() throws IOException {
    if (mDoc != null) {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setTrimText(false);/*  ww w .  j a  v  a 2 s.  c o  m*/
        format.setOmitEncoding(false);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(mDoc);
        return new String(out.toByteArray(), "UTF-8");
    }
    return "";
}