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.taobao.android.builder.tasks.library.publish.UpdatePomTask.java

License:Apache License

private void updatePomXml(File xml) throws IOException, DocumentException {

    Map<String, DependencyExtraInfo> extraInfoMap = getExtraMap();

    File backupFile = new File(xml.getParentFile(), "pom-backup.xml");
    FileUtils.deleteQuietly(backupFile);

    FileUtils.moveFile(xml, backupFile);

    XMLWriter writer = null;// XML
    SAXReader reader = new SAXReader();
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");// XML??
    FileOutputStream fos = new FileOutputStream(xml);

    try {// ww  w .j  av  a  2  s  .com
        Document document = reader.read(backupFile);// ?XML

        Element dependencies = document.getRootElement().element("dependencies");

        if ((null != dependencies) && null != dependencies.elements()) {
            List<Element> list = dependencies.elements();

            for (Element element : list) {

                List<Element> itemList = element.elements();

                String group = "";
                String name = "";
                String type;
                String scope;

                Element scopeEl = null;
                Element typeEl = null;

                for (Element element1 : itemList) {
                    if ("groupId".equals(element1.getQName().getName())) {
                        group = element1.getStringValue();
                    } else if ("artifactId".equals(element1.getQName().getName())) {
                        name = element1.getStringValue();
                    } else if ("scope".equals(element1.getQName().getName())) {
                        scope = element1.getStringValue();
                        scopeEl = element1;
                    } else if ("type".equals(element1.getQName().getName())) {
                        type = element1.getStringValue();
                        typeEl = element1;
                    }
                }

                DependencyExtraInfo dependencyExtraInfo = extraInfoMap.get(group + ":" + name);
                if (null == dependencyExtraInfo) {
                    continue;
                }

                //update scope
                if (StringUtils.isNotEmpty(dependencyExtraInfo.scope)) {
                    if (null != scopeEl) {
                        scopeEl.setText(dependencyExtraInfo.scope);
                    } else {
                        Element newEl = element.addElement("scope");
                        newEl.setText(dependencyExtraInfo.scope);
                    }
                }

                if (StringUtils.isNotEmpty(dependencyExtraInfo.type)) {
                    if (null != typeEl) {
                        typeEl.setText(dependencyExtraInfo.type);
                    } else {
                        Element newEl = element.addElement("type");
                        newEl.setText(dependencyExtraInfo.type);
                    }
                }

            }
        }

        writer = new XMLWriter(fos, format);
        writer.write(document);

    } finally {
        if (null != writer) {
            writer.close();
        }
        IOUtils.closeQuietly(fos);
    }

}

From source file:com.taobao.android.builder.tools.manifest.ManifestFileUtils.java

License:Apache License

/**
 * manifest???/*from w  w  w  . j a va  2s. co  m*/
 *
 * @param mainManifest
 * @param libManifestMap
 * @param baseBunfleInfoFile
 * @param manifestOptions
 */
public static void postProcessManifests(File mainManifest, Map<String, File> libManifestMap,
        Multimap<String, File> libDependenciesMaps, File baseBunfleInfoFile, ManifestOptions manifestOptions,
        boolean addMultiDex, Set<String> remoteBundles) throws IOException, DocumentException {
    File backupFile = new File(mainManifest.getParentFile(), "AndroidManifest-backup.xml");
    FileUtils.deleteQuietly(backupFile);
    FileUtils.moveFile(mainManifest, backupFile);

    XMLWriter writer = null;// XML
    SAXReader reader = new SAXReader();
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");// XML??
    FileOutputStream fos = new FileOutputStream(mainManifest);
    if (mainManifest.exists()) {
        try {
            Document document = reader.read(backupFile);// ?XML
            if (null != baseBunfleInfoFile && baseBunfleInfoFile.exists()) {
                addApplicationMetaData(document, libManifestMap, baseBunfleInfoFile, manifestOptions,
                        remoteBundles);
            }
            if (null != manifestOptions && manifestOptions.isAddBundleLocation()) {
                addBundleLocationToDestManifest(document, libManifestMap, libDependenciesMaps, manifestOptions);
            }
            if (null != manifestOptions && manifestOptions.isReplaceApplication()) {
                replaceManifestApplicationName(document);
            }
            if ((null != manifestOptions && manifestOptions.isAddMultiDexMetaData()) || addMultiDex) {
                addMultiDexMetaData(document);
            }
            if (null != manifestOptions && manifestOptions.isRemoveProvider()) {
                removeProvider(document);
            }
            removeCustomLaunches(document, manifestOptions);
            updatePermission(document, manifestOptions);
            removeComments(document);

            writer = new XMLWriter(fos, format);
            writer.write(document);
        } finally {
            if (null != writer) {
                writer.close();
            }
            IOUtils.closeQuietly(fos);
        }
    }
}

From source file:com.taobao.android.builder.tools.manifest.ManifestFileUtils.java

License:Apache License

private static void saveFile(Document document, OutputFormat format, File file) throws IOException {

    XMLWriter writer = null;// XML
    FileOutputStream fos = null;/* w ww .ja v a2  s .com*/
    try {
        fos = new FileOutputStream(file);
        writer = new XMLWriter(fos, format);
        writer.write(document);
    } finally {
        if (null != writer) {
            writer.close();
        }
        IOUtils.closeQuietly(fos);
    }
}

From source file:com.taobao.android.builder.tools.manifest.ManifestFileUtils.java

License:Apache License

public static void minifyManifest(File mainManifest, File destManifest) throws IOException, DocumentException {

    XMLWriter writer = null;// XML
    SAXReader reader = new SAXReader();
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");// XML??
    FileOutputStream fos = new FileOutputStream(destManifest);
    if (mainManifest.exists()) {
        try {//from   www  . j  a v  a  2  s .c om
            Document document = reader.read(mainManifest);// ?XML

            //                removeComments(document);

            Element element = document.getRootElement();

            element.clearContent();

            writer = new XMLWriter(fos, format);
            writer.write(document);
        } finally {
            if (null != writer) {
                writer.close();
            }
            IOUtils.closeQuietly(fos);
        }
    }
}

From source file:com.taobao.android.builder.tools.manifest.ManifestFileUtils.java

License:Apache License

public static void removeProvider(File androidManifestFile) throws IOException, DocumentException {
    File backupFile = new File(androidManifestFile.getParentFile(), "AndroidManifest-backup.xml");
    FileUtils.deleteQuietly(backupFile);
    FileUtils.moveFile(androidManifestFile, backupFile);

    XMLWriter writer = null;// XML
    SAXReader reader = new SAXReader();
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");// XML??
    FileOutputStream fos = new FileOutputStream(androidManifestFile);

    if (androidManifestFile.exists()) {
        try {/*from  w ww  . j  a  va2  s .  com*/
            Document document = reader.read(backupFile);// ?XML
            Element root = document.getRootElement();// 
            List<? extends Node> nodes = root.selectNodes("//provider");
            for (Node node : nodes) {
                Element element = (Element) node;
                String name = element.attributeValue("name");
                logger.info("[Remove Provider]" + name);
                element.getParent().remove(element);
            }
            writer = new XMLWriter(fos, format);
            writer.write(document);
        } finally {
            if (null != writer) {
                writer.close();
            }
            IOUtils.closeQuietly(fos);
        }
    }
}

From source file:com.taobao.android.builder.tools.xml.XmlHelper.java

License:Apache License

public static void saveFile(Document document, OutputFormat format, File file) throws IOException {

    XMLWriter writer = null;// XML
    FileOutputStream fos = null;//from   w w w. j  a va2  s  . com
    try {
        fos = new FileOutputStream(file);
        writer = new XMLWriter(fos, format);
        writer.write(document);
    } finally {
        if (null != writer) {
            writer.close();
        }
        IOUtils.closeQuietly(fos);
    }
}

From source file:com.taobao.datax.engine.tools.JobConfGenDriver.java

License:Open Source License

private static int genXmlFile(String filename, ClassNode reader, ClassNode writer) throws IOException {

    Document document = DocumentHelper.createDocument();
    Element jobsElement = document.addElement("jobs");
    Element jobElement = jobsElement.addElement("job");
    String id = reader.getName() + "_to_" + writer.getName() + "_job";
    jobElement.addAttribute("id", id);

    /**/*from  ww  w  .  jav  a  2s  .c  om*/
     * ?readerxml
     */
    Element readerElement = jobElement.addElement("reader");
    Element plugin_Element = readerElement.addElement("plugin");
    plugin_Element.setText(reader.getName());

    ClassNode readerNode = reader;
    Element tempElement = null;

    List<ClassMember> members = readerNode.getAllMembers();
    for (ClassMember member : members) {
        StringBuilder command = new StringBuilder("\n");

        Set<String> set = member.getAllKeys();
        String value = "";
        for (String key : set) {
            value = member.getAttr("default");
            command.append(key).append(":").append(member.getAttr(key)).append("\n");
        }
        readerElement.addComment(command.toString());

        String keyName = member.getName();
        keyName = keyName.substring(1, keyName.length() - 1);
        tempElement = readerElement.addElement("param");
        tempElement.addAttribute("key", keyName);

        if (value == null || "".equals(value)) {
            value = "?";
        }
        tempElement.addAttribute("value", value);
    }

    /**
     * ?writerxml
     */
    Element writerElement = jobElement.addElement("writer");
    plugin_Element = writerElement.addElement("plugin");
    plugin_Element.setText(writer.getName());

    members = writer.getAllMembers();
    for (ClassMember member : members) {
        StringBuilder command = new StringBuilder("\n");
        Set<String> set = member.getAllKeys();

        String value = "";
        for (String key : set) {
            value = member.getAttr("default");
            command.append(key).append(":").append(member.getAttr(key)).append("\n");
        }
        writerElement.addComment(command.toString());

        String keyName = member.getName();
        keyName = keyName.substring(1, keyName.length() - 1);
        tempElement = writerElement.addElement("param");
        tempElement.addAttribute("key", keyName);

        if (value == null || "".equals(value)) {
            value = "?";
        }
        tempElement.addAttribute("value", value);
    }

    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        XMLWriter writerOfXML = new XMLWriter(new FileWriter(new File(filename)), format);
        writerOfXML.write(document);
        writerOfXML.close();
    } catch (Exception ex) {
        throw new IOException(ex.getCause());
    }

    return 0;
}

From source file:com.taobao.osceola.demo.acount.persist.service.impl.AccountPersistServiceImpl.java

License:Open Source License

/**
 * @param doc//from   www .j a va  2  s. c om
 */
private void writeDocment(Document doc) throws AccountPersistException {
    Writer out = null;
    try {
        out = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
        XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
        writer.write(doc);
    } catch (Exception e) {
        throw new AccountPersistException("", e);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            throw new AccountPersistException("", e);
        }
    }
}

From source file:com.tedi.engine.XMLOutput.java

License:Open Source License

/**
 * Handles functionality of formatting and writing document.
 * //w  ww.ja  va2 s  . c o m
 * @param doc
 *            The document
 * @return the cleaned document.
 * @throws Exception
 */
private String cleanDocument(Document doc) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("Cleaning the document object.");
    }
    String docStr = "";
    // --COMMENTED OUT 10-10-2005
    // JBG----------------------------------------------------------------------------------
    // if (dtd != null && dtd.length()>0) {
    // xmlUtils.setDocument(doc);
    // try {
    // AbstractSchemaDescriptor schema =
    // AbstractSchemaDescriptor.createDescriptor(absoluteDTD_URL.toString());
    // schema.processSchema(doc.getRootElement().getName());
    // xmlUtils.setSchema(schema);
    // xmlUtils.cleanDocument();
    // }
    // catch (Exception e) {
    // execResults.addMessage(ExecutionResults.M_WARNING,
    // ExecutionResults.J2EE_TARGET_ERR,
    // "Error removing optional attributes/elements: " + e.getMessage());
    // }
    // }
    // ----------------------------------------------------------------------------------------------------------------
    cleanElement(doc.getRootElement());
    StringWriter sw = new StringWriter();
    OutputFormat format = isCompact ? OutputFormat.createCompactFormat() : OutputFormat.createPrettyPrint();
    format.setExpandEmptyElements(false);
    XMLWriter writer = new XMLWriter(sw, format);
    writer.setMaximumAllowedCharacter(127);
    writer.write(doc);
    writer.close();
    docStr = sw.toString();
    if (isSuppressDocType && doc.getDocType() != null) {
        int ndx = docStr.indexOf("<" + doc.getRootElement().getName());
        docStr = docStr.substring(ndx);
    }
    return docStr;
}

From source file:com.test.android.push.xmpp.net.Connection.java

License:Open Source License

/**
 * Delivers the packet to this connection (without checking the recipient).
 * /*from  w  w w.  j a v  a2 s .  c om*/
 * @param packet the packet to deliver
 */
public void deliver(Packet packet) {
    log.debug("SENT: " + packet.toXML());
    if (!isClosed()) {
        IoBuffer buffer = IoBuffer.allocate(4096);
        buffer.setAutoExpand(true);

        boolean errorDelivering = false;
        try {
            XMLWriter xmlSerializer = new XMLWriter(new IoBufferWriter(buffer, (CharsetEncoder) encoder.get()),
                    new OutputFormat());
            xmlSerializer.write(packet.getElement());
            xmlSerializer.flush();
            buffer.flip();
            ioSession.write(buffer);
        } catch (Exception e) {
            log.debug("Connection: Error delivering packet" + "\n" + this.toString(), e);
            errorDelivering = true;
        }
        if (errorDelivering) {
            close();
        } else {
            session.incrementServerPacketCount();
        }
    }
    log.debug("deliver() end...");
}