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.jiangnan.es.orm.mybatis.util.MybatisMapperXmlGenerator.java

License:Apache License

/**
 * //w  w w  .ja va2  s. c o  m
 * @param document
 * @throws IOException
 */
private void write(Document document) throws IOException {
    XMLWriter xmlWriter = null;
    try {
        FileWriter writer = new FileWriter(new File(this.exportFileName));
        OutputFormat format = new OutputFormat();
        format.setEncoding("UTF-8");
        //? 
        format.setIndent(true);
        format.setIndent("    ");
        //? 
        format.setNewlines(true);
        xmlWriter = new XMLWriter(writer, format);
        xmlWriter.write(document);
    } finally {
        if (null != xmlWriter) {
            xmlWriter.close();
        }
    }
}

From source file:com.lafengmaker.tool.util.XMLDataUtil.java

License:Open Source License

/**
 * Save to xml file/*w  w w . ja  va2  s .  c  om*/
 * @param dom
 * @param sFilePathName
 * @param encode
 * @return
 * @throws CommonException
 */
public static boolean saveXML(Document dom, String sFilePathName, String encode) throws Exception {

    File file = new File(sFilePathName);

    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        FileOutputStream out = new FileOutputStream(file);
        // if(!encode.equals(ENCODE_UTF_8)){
        if (encode != null) {
            format.setEncoding(encode);
        }

        // format.setTrimText(true);
        XMLWriter xmlWriter = new XMLWriter(out, format);
        xmlWriter.write(dom);
        xmlWriter.flush();
        xmlWriter.close();
        return true;
    } catch (Exception e) {
        throw new RuntimeException("XMLDATAUTIL-SAVE_DOCUMENT-001", e);
    }

}

From source file:com.liferay.alloy.tools.transformer.AlloyDocsTransformer.java

License:Open Source License

private void _createXML() {
    ArrayList<Component> components = getComponents();

    Document doc = DocumentFactory.getInstance().createDocument();
    Element root = doc.addElement("components");

    root.addAttribute("short-name", _DEFAULT_TAGLIB_SHORT_NAME);
    root.addAttribute("uri", _DEFAULT_TAGLIB_URI);
    root.addAttribute("tlib-version", _DEFAULT_TAGLIB_VERSION);

    for (Component component : components) {
        Element componentNode = root.addElement("component");

        componentNode.addAttribute("name", component.getName());
        componentNode.addAttribute("module", component.getModule());
        componentNode.addAttribute("package", component.getPackage());
        componentNode.addAttribute("bodyContent", String.valueOf(component.isBodyContent()));
        componentNode.addAttribute("alloyComponent", String.valueOf(component.isAlloyComponent()));

        Element descriptionNode = componentNode.addElement("description");
        descriptionNode.addCDATA(component.getDescription());
        Element attributesNode = componentNode.addElement("attributes");
        Element eventsNode = componentNode.addElement("events");

        for (Attribute attribute : component.getAttributes()) {
            Element attributeNode = attributesNode.addElement("attribute");

            Element defaultValueNode = attributeNode.addElement("defaultValue");
            Element attributeDescriptionNode = attributeNode.addElement("description");
            Element javaScriptTypeNode = attributeNode.addElement("javaScriptType");
            Element nameNode = attributeNode.addElement("name");
            Element readOnlyNode = attributeNode.addElement("readOnly");

            defaultValueNode.setText(attribute.getDefaultValue());
            attributeDescriptionNode.addCDATA(_getAttributeDescription(attribute));
            javaScriptTypeNode.setText(attribute.getJavaScriptType());
            nameNode.setText(attribute.getName());
            readOnlyNode.setText(Boolean.toString(attribute.isReadOnly()));
        }//w  ww.java2 s .c om

        for (Attribute event : component.getEvents()) {
            Element eventNode = eventsNode.addElement("event");
            Element nameNode = eventNode.addElement("name");
            Element typeNode = eventNode.addElement("type");
            Element elementDescriptionNode = eventNode.addElement("description");

            nameNode.setText(event.getName());
            elementDescriptionNode.addCDATA(_getAttributeDescription(event));
            typeNode.setText(event.getType());
        }
    }

    try {
        File file = new File(_outputXML);

        file.getParentFile().mkdirs();

        FileOutputStream fos = new FileOutputStream(file);

        OutputFormat format = OutputFormat.createPrettyPrint();

        XMLWriter writer = new XMLWriter(fos, format);

        writer.write(doc);
        writer.flush();

        System.out.println("Writing " + _outputXML);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.liferay.alloy.tools.xmlbuilder.XMLBuilder.java

License:Open Source License

private void _createXML() {
    ArrayList<Component> components = getComponents();

    Document doc = DocumentFactory.getInstance().createDocument();
    Element root = doc.addElement("taglibs");

    root.addAttribute("short-name", _DEFAULT_TAGLIB_SHORT_NAME);
    root.addAttribute("uri", _DEFAULT_TAGLIB_URI);
    root.addAttribute("tlib-version", _DEFAULT_TAGLIB_VERSION);

    for (Component component : components) {
        Element componentNode = root.addElement("component");

        componentNode.addAttribute("name", component.getName());
        componentNode.addAttribute("module", component.getModule());
        componentNode.addAttribute("package", component.getPackage());
        componentNode.addAttribute("bodyContent", String.valueOf(component.isBodyContent()));

        componentNode.addAttribute("alloyComponent", String.valueOf(component.isAlloyComponent()));

        Element attributesNode = componentNode.addElement("attributes");
        Element eventsNode = componentNode.addElement("events");

        for (Attribute attribute : component.getAttributes()) {
            Element attributeNode = attributesNode.addElement("attribute");
            Element nameNode = attributeNode.addElement("name");
            Element inputTypeNode = attributeNode.addElement("inputType");
            Element outputTypeNode = attributeNode.addElement("outputType");
            Element defaultValueNode = attributeNode.addElement("defaultValue");

            Element descriptionNode = attributeNode.addElement("description");

            nameNode.setText(attribute.getName());
            inputTypeNode.setText(attribute.getInputType());
            outputTypeNode.setText(attribute.getOutputType());
            defaultValueNode.setText(attribute.getDefaultValue());
            descriptionNode.addCDATA(_getAttributeDescription(attribute));
        }/* w  ww .ja  v  a 2  s  .  c  om*/

        for (Attribute event : component.getEvents()) {
            Element eventNode = eventsNode.addElement("event");
            Element nameNode = eventNode.addElement("name");
            Element typeNode = eventNode.addElement("type");
            Element descriptionNode = eventNode.addElement("description");

            nameNode.setText(event.getName());
            typeNode.setText(event.getInputType());
            descriptionNode.addCDATA(_getAttributeDescription(event));
        }
    }

    try {
        FileOutputStream fos = new FileOutputStream(_componentXML);

        OutputFormat format = OutputFormat.createPrettyPrint();

        XMLWriter writer = new XMLWriter(fos, format);

        writer.write(doc);
        writer.flush();

        System.out.println("Writing " + _componentXML);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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.ja va2  s  .co 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  ww  w.j  a  v  a2 s .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 {//from   ww w.ja  v a 2 s .c om
        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 va 2 s  .  c om*/
    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);//from w  ww  . j  av  a 2s. co  m

    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 source file:com.lingxiang2014.util.SettingUtils.java

License:Open Source License

public static void set(Setting setting) {
    try {//ww w  .  ja v a 2 s  .  com
        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();
    }
}