Example usage for org.dom4j.io XMLWriter write

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

Introduction

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

Prototype

public void write(Object object) throws IOException 

Source Link

Document

Writes the given object which should be a String, a Node or a List of Nodes.

Usage

From source file:com.liferay.petra.xml.Dom4jUtil.java

License:Open Source License

public static String toString(Node node, String indent, boolean expandEmptyElements, boolean trimText)
        throws IOException {

    UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();

    OutputFormat outputFormat = OutputFormat.createPrettyPrint();

    outputFormat.setExpandEmptyElements(expandEmptyElements);
    outputFormat.setIndent(indent);//from   w ww  .  j  a v  a  2s . c  o  m
    outputFormat.setLineSeparator(StringPool.NEW_LINE);
    outputFormat.setTrimText(trimText);

    XMLWriter xmlWriter = new XMLWriter(unsyncByteArrayOutputStream, outputFormat);

    xmlWriter.write(node);

    String content = unsyncByteArrayOutputStream.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.contains(" \n")) {
        content = StringUtil.replace(content, " \n", "\n");
    }

    if (content.startsWith("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")) {
        content = StringUtil.replaceFirst(content, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
                "<?xml version=\"1.0\"?>");
    }

    return content;
}

From source file:com.liferay.portal.ejb.PortletManagerImpl.java

License:Open Source License

private Set _readPortletXML(String servletContextName, String xml, Map portletsPool)
        throws DocumentException, IOException {

    Set portletIds = new HashSet();

    if (xml == null) {
        return portletIds;
    }/*from   w w w  . java2s.  co  m*/

    /*EntityResolver resolver = new EntityResolver() {
       public InputSource resolveEntity(String publicId, String systemId) {
    InputStream is =
       getClass().getClassLoader().getResourceAsStream(
          "com/liferay/portal/resources/portlet-app_1_0.xsd");
            
    return new InputSource(is);
       }
    };*/

    SAXReader reader = new SAXReader();
    //reader.setEntityResolver(resolver);

    Document doc = reader.read(new StringReader(xml));

    Element root = doc.getRootElement();

    Set userAttributes = new HashSet();

    Iterator itr1 = root.elements("user-attribute").iterator();

    while (itr1.hasNext()) {
        Element userAttribute = (Element) itr1.next();

        String name = userAttribute.elementText("name");

        userAttributes.add(name);
    }

    itr1 = root.elements("portlet").iterator();

    while (itr1.hasNext()) {
        Element portlet = (Element) itr1.next();

        String portletId = portlet.elementText("portlet-name");
        if (servletContextName != null) {
            portletId = servletContextName + PortletConfigImpl.WAR_SEPARATOR + portletId;
        }

        portletIds.add(portletId);

        Portlet portletModel = (Portlet) portletsPool.get(portletId);
        if (portletModel == null) {
            portletModel = new Portlet(new PortletPK(portletId, _SHARED_KEY, _SHARED_KEY));

            portletsPool.put(portletId, portletModel);
        }

        if (servletContextName != null) {
            portletModel.setWARFile(true);
        }

        portletModel.setPortletClass(portlet.elementText("portlet-class"));

        Iterator itr2 = portlet.elements("init-param").iterator();

        while (itr2.hasNext()) {
            Element initParam = (Element) itr2.next();

            portletModel.getInitParams().put(initParam.elementText("name"), initParam.elementText("value"));
        }

        Element expirationCache = portlet.element("expiration-cache");
        if (expirationCache != null) {
            portletModel.setExpCache(new Integer(GetterUtil.getInteger(expirationCache.getText())));
        }

        itr2 = portlet.elements("supports").iterator();

        while (itr2.hasNext()) {
            Element supports = (Element) itr2.next();

            String mimeType = supports.elementText("mime-type");

            Iterator itr3 = supports.elements("portlet-mode").iterator();

            while (itr3.hasNext()) {
                Element portletMode = (Element) itr3.next();

                Set mimeTypeModes = (Set) portletModel.getPortletModes().get(mimeType);

                if (mimeTypeModes == null) {
                    mimeTypeModes = new HashSet();

                    portletModel.getPortletModes().put(mimeType, mimeTypeModes);
                }

                mimeTypeModes.add(portletMode.getTextTrim().toLowerCase());
            }
        }

        Set supportedLocales = portletModel.getSupportedLocales();

        supportedLocales.add(Locale.getDefault().getLanguage());

        itr2 = portlet.elements("supported-locale").iterator();

        while (itr2.hasNext()) {
            Element supportedLocaleEl = (Element) itr2.next();

            String supportedLocale = supportedLocaleEl.getText();

            supportedLocales.add(supportedLocale);
        }

        portletModel.setResourceBundle(portlet.elementText("resource-bundle"));

        Element portletInfo = portlet.element("portlet-info");

        String portletInfoTitle = null;
        String portletInfoShortTitle = null;
        String portletInfoKeyWords = null;

        if (portletInfo != null) {
            portletInfoTitle = portletInfo.elementText("title");
            portletInfoShortTitle = portletInfo.elementText("short-title");
            portletInfoKeyWords = portletInfo.elementText("keywords");
        }

        portletModel
                .setPortletInfo(new PortletInfo(portletInfoTitle, portletInfoShortTitle, portletInfoKeyWords));

        Element portletPreferences = portlet.element("portlet-preferences");

        String defaultPreferences = null;
        String prefsValidator = null;

        if (portletPreferences != null) {
            Element prefsValidatorEl = portletPreferences.element("preferences-validator");

            String prefsValidatorName = null;

            if (prefsValidatorEl != null) {
                prefsValidator = prefsValidatorEl.getText();

                portletPreferences.remove(prefsValidatorEl);
            }

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            XMLWriter writer = new XMLWriter(baos, OutputFormat.createCompactFormat());

            writer.write(portletPreferences);

            defaultPreferences = baos.toString();
        }

        portletModel.setDefaultPreferences(defaultPreferences);
        portletModel.setPreferencesValidator(prefsValidator);

        if (!portletModel.isWARFile() && Validator.isNotNull(prefsValidator)
                && GetterUtil.getBoolean(PropsUtil.get(PropsUtil.PREFERENCE_VALIDATE_ON_STARTUP))) {

            try {
                PreferencesValidator prefsValidatorObj = PortalUtil.getPreferencesValidator(portletModel);

                prefsValidatorObj.validate(PortletPreferencesSerializer.fromDefaultXML(defaultPreferences));
            } catch (Exception e) {
                _log.warn("Portlet with the name " + portletId + " does not have valid default preferences");
            }
        }

        List roles = new ArrayList();

        itr2 = portlet.elements("security-role-ref").iterator();

        while (itr2.hasNext()) {
            Element role = (Element) itr2.next();

            roles.add(role.elementText("role-name"));
        }

        portletModel.setRolesArray((String[]) roles.toArray(new String[0]));

        portletModel.getUserAttributes().addAll(userAttributes);
    }

    return portletIds;
}

From source file:com.liferay.portlet.PortletPreferencesSerializer.java

License:Open Source License

public static String toXML(PortletPreferencesImpl prefs) throws SystemException {

    try {/*  w  w w.  java2s.  c o  m*/
        Map preferences = prefs.getPreferences();

        DocumentFactory docFactory = DocumentFactory.getInstance();

        Element portletPreferences = docFactory.createElement("portlet-preferences");

        Iterator itr = preferences.entrySet().iterator();

        while (itr.hasNext()) {
            Map.Entry entry = (Map.Entry) itr.next();

            Preference preference = (Preference) entry.getValue();

            Element prefEl = docFactory.createElement("preference");

            Element nameEl = docFactory.createElement("name");
            nameEl.addText(preference.getName());

            prefEl.add(nameEl);

            String[] values = preference.getValues();

            for (int i = 0; i < values.length; i++) {
                Element valueEl = docFactory.createElement("value");
                valueEl.addText(values[i]);

                prefEl.add(valueEl);
            }

            if (preference.isReadOnly()) {
                Element valueEl = docFactory.createElement("read-only");
                valueEl.addText("true");
            }

            portletPreferences.add(prefEl);
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        XMLWriter writer = new XMLWriter(baos, OutputFormat.createCompactFormat());

        writer.write(portletPreferences);

        return baos.toString();
    } catch (IOException ioe) {
        throw new SystemException(ioe);
    }
}

From source file:com.liferay.util.xml.XMLFormatter.java

License:Open Source License

public static String toString(Document doc, String indent) throws IOException {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    OutputFormat format = OutputFormat.createPrettyPrint();

    format.setIndent(indent);/*from w  w  w.j a v  a 2 s.  co m*/
    format.setLineSeparator("\n");

    XMLWriter writer = new XMLWriter(baos, format);

    writer.write(doc);

    String content = baos.toString();

    content = StringUtil.replace(content, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
            "<?xml version=\"1.0\"?>");

    int x = content.indexOf("<!DOCTYPE");
    if (x != -1) {
        x = content.indexOf(">", x) + 1;
        content = content.substring(0, x) + "\n" + content.substring(x, content.length());
    }

    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);
    }

    return content;
}

From source file:com.liferay.util.xml.XMLMergerRunner.java

License:Open Source License

private String _documentToString(Document doc, String docType) throws IOException {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    OutputFormat format = OutputFormat.createPrettyPrint();

    format.setIndent("\t");
    format.setLineSeparator("\n");

    XMLWriter writer = new XMLWriter(baos, format);

    writer.write(doc);

    String xml = baos.toString();

    int pos = xml.indexOf("<?");

    String header = xml.substring(pos, xml.indexOf("?>", pos) + 2);

    xml = StringUtil.replace(xml, header, "");
    xml = header + "\n" + docType + "\n" + xml;

    return xml;//from   w  ww.  ja va  2  s.  co  m
}

From source file:com.lingxiang2014.util.SettingUtils.java

License:Open Source License

public static void set(Setting setting) {
    try {/* ww w. j  a v  a2s. c  om*/
        File shopxxXmlFile = new ClassPathResource(CommonAttributes.SHOPXX_XML_PATH).getFile();
        Document document = new SAXReader().read(shopxxXmlFile);
        List<Element> elements = document.selectNodes("/shopxx/setting");
        for (Element element : elements) {
            try {
                String name = element.attributeValue("name");
                String value = beanUtils.getProperty(setting, name);
                Attribute attribute = element.attribute("value");
                attribute.setValue(value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }

        FileOutputStream fileOutputStream = null;
        XMLWriter xmlWriter = null;
        try {
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            outputFormat.setIndent(true);
            outputFormat.setIndent("   ");
            outputFormat.setNewlines(true);
            fileOutputStream = new FileOutputStream(shopxxXmlFile);
            xmlWriter = new XMLWriter(fileOutputStream, outputFormat);
            xmlWriter.write(document);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (xmlWriter != null) {
                try {
                    xmlWriter.close();
                } catch (IOException e) {
                }
            }
            IOUtils.closeQuietly(fileOutputStream);
        }

        Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME);
        cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.liveneo.plat.web.action.MakeLicfile.java

public static void createXmlFile(String fileName, Document doc) {
    try {/*from   w  w w  .  j  a v  a2 s . co m*/
        File testfile = new File("fileName");
        if (testfile.exists()) {
            testfile.delete();
        }
        FileWriter fileWriter = new FileWriter(fileName);
        OutputFormat xmlFormat = OutputFormat.createPrettyPrint();
        xmlFormat.setEncoding("UTF-8");
        xmlFormat.setSuppressDeclaration(false);
        xmlFormat.setExpandEmptyElements(false);
        XMLWriter xmlWriter = new XMLWriter(fileWriter, xmlFormat);
        xmlWriter.write(doc);
        xmlWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.love320.templateparser.label.impl.LabelBeanDaoImpl.java

License:Apache License

private boolean XMLWriter() {
    try {/*from  w w  w  . ja  v a2s.c om*/
        OutputFormat format = OutputFormat.createPrettyPrint();//?
        format.setEncoding("UTF-8");//?
        XMLWriter output = new XMLWriter(new FileWriter(new File(configPath)), format);//?
        output.write(DOCROOT.getDocument());//
        output.close();//

        return true;
    } catch (IOException e) {
        logger.error("IOException", e);
    }
    return false;
}

From source file:com.magicpwd._util.Jxml.java

License:Open Source License

public static void save(Document document, File file) throws IOException {
    // ?//from  ww  w. ja  v  a 2  s  .c om
    OutputFormat format = OutputFormat.createPrettyPrint();
    // ??
    // OutputFormat format = OutputFormat.createCompactFormat();
    // XML?
    // format.setEncoding("GBK");
    XMLWriter writer = new XMLWriter(new FileWriter(file), format);
    writer.write(document);
    writer.close();
}

From source file:com.maomao.framework.utils.XmlUtils.java

License:Apache License

public String Dom2String(Document doc) {

    XMLWriter writer = null;
    try {/*from w w  w  . j  a v  a2  s  .c o  m*/
        StringWriter sw = new StringWriter();
        writer = new XMLWriter(sw);
        writer.write(doc);
        return sw.toString();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (null != writer)
            try {
                writer.close();
            } catch (Exception ie) {
            }
    }
    return null;
}