Example usage for org.dom4j Document getRootElement

List of usage examples for org.dom4j Document getRootElement

Introduction

In this page you can find the example usage for org.dom4j Document getRootElement.

Prototype

Element getRootElement();

Source Link

Document

Returns the root Element for this document.

Usage

From source file:com.liferay.alloy.tools.builder.taglib.TagBuilder.java

License:Open Source License

private void _createTld() throws Exception {
    Map<String, Object> context = getDefaultTemplateContext();

    for (Document doc : getComponentDefinitionDocs()) {
        Element root = doc.getRootElement();

        String shortName = Convert.toString(root.attributeValue("short-name"), _DEFAULT_TAGLIB_SHORT_NAME);
        String version = Convert.toString(root.attributeValue("tlib-version"), _DEFAULT_TAGLIB_VERSION);
        String uri = Convert.toString(root.attributeValue("uri"), _DEFAULT_TAGLIB_URI);

        boolean isAlloyComponent = shortName.equals(_DEFAULT_ATTRIBUTE_NAMESPACE);

        context.put("alloyComponent", isAlloyComponent);
        context.put("components", getComponents(doc));
        context.put("shortName", shortName);
        context.put("uri", uri);
        context.put("version", version);

        String tldFilePath = _tldDir.concat(shortName).concat(_TLD_EXTENSION);

        File tldFile = new File(tldFilePath);

        String content = processTemplate(_tplTld, context);

        Document source = SAXReaderUtil.read(new ByteArrayInputStream(content.getBytes()));

        if (tldFile.exists()) {
            Document target = SAXReaderUtil.read(new ByteArrayInputStream(FileUtil.readBytes(tldFile)));

            source = mergeTlds(source, target);
        }//from  w  ww . j ava  2s  . c  o m

        writeFile(tldFile, content, true);
    }
}

From source file:com.liferay.maven.plugins.ThemeMergeMojo.java

License:Open Source License

protected void doExecute() throws Exception {
    workDir = new File(workDir, "liferay-theme");

    if (!workDir.exists()) {
        workDir.mkdirs();/*from   w ww.j a  va  2  s . c o  m*/
    }

    if (Validator.isNotNull(parentTheme)) {
        if (parentTheme.indexOf(":") > 0) {
            String[] parentThemeArray = parentTheme.split(":");

            parentThemeArtifactGroupId = parentThemeArray[0];
            parentThemeArtifactId = parentThemeArray[1];
            parentThemeArtifactVersion = parentThemeArray[2];
            parentThemeId = null;
        } else {
            parentThemeId = parentTheme;
        }
    }

    getLog().info("Parent theme group ID " + parentThemeArtifactGroupId);
    getLog().info("Parent theme artifact ID " + parentThemeArtifactId);
    getLog().info("Parent theme version " + parentThemeArtifactVersion);
    getLog().info("Parent theme ID " + parentThemeId);

    String[] excludes = null;
    String[] includes = null;

    boolean portalTheme = false;

    if (parentThemeArtifactGroupId.equals("com.liferay.portal") && parentThemeArtifactId.equals("portal-web")) {

        portalTheme = true;
    }

    if (!portalTheme) {
        Dependency dependency = createDependency(parentThemeArtifactGroupId, parentThemeArtifactId,
                parentThemeArtifactVersion, "", "war");

        Artifact artifact = resolveArtifact(dependency);

        UnArchiver unArchiver = archiverManager.getUnArchiver(artifact.getFile());

        unArchiver.setDestDirectory(workDir);
        unArchiver.setSourceFile(artifact.getFile());

        IncludeExcludeFileSelector includeExcludeFileSelector = new IncludeExcludeFileSelector();

        includeExcludeFileSelector.setExcludes(excludes);
        includeExcludeFileSelector.setIncludes(includes);

        unArchiver.setFileSelectors(new FileSelector[] { includeExcludeFileSelector });

        unArchiver.extract();
    }

    File liferayLookAndFeelXml = new File(webappSourceDir, "WEB-INF/liferay-look-and-feel.xml");

    if (liferayLookAndFeelXml.exists()) {
        Document document = SAXReaderUtil.read(liferayLookAndFeelXml, false);

        Element rootElement = document.getRootElement();

        List<Element> themeElements = rootElement.elements("theme");

        for (Element themeElement : themeElements) {
            String id = themeElement.attributeValue("id");

            if (Validator.isNotNull(themeId) && !themeId.equals(id)) {
                continue;
            }

            Theme targetTheme = readTheme(themeElement);

            if (portalTheme) {
                mergePortalTheme(targetTheme);
            } else {
                File sourceLiferayLookAndFeelXml = new File(workDir, "WEB-INF/liferay-look-and-feel.xml");

                Theme sourceTheme = readTheme(parentThemeId, sourceLiferayLookAndFeelXml);

                mergeTheme(sourceTheme, targetTheme);
            }
        }
    } else {
        String id = PortalUtil.getJsSafePortletId(project.getArtifactId());

        Theme targetTheme = readTheme(id, null);

        if (portalTheme) {
            mergePortalTheme(targetTheme);
        } else {
            File sourceLiferayLookAndFeelXml = new File(workDir, "WEB-INF/liferay-look-and-feel.xml");

            Theme sourceTheme = readTheme(parentThemeId, sourceLiferayLookAndFeelXml);

            mergeTheme(sourceTheme, targetTheme);
        }
    }
}

From source file:com.liferay.maven.plugins.ThemeMergeMojo.java

License:Open Source License

protected Theme readTheme(String themeId, File liferayLookAndFeelXml) throws Exception {

    if ((liferayLookAndFeelXml != null) && liferayLookAndFeelXml.exists()) {
        Document document = SAXReaderUtil.read(liferayLookAndFeelXml, false);

        Element rootElement = document.getRootElement();

        List<Element> themeElements = rootElement.elements("theme");

        for (Element themeElement : themeElements) {
            String id = themeElement.attributeValue("id");

            if (Validator.isNotNull(themeId) && !themeId.equals(id)) {
                continue;
            }/* w ww .  j a v a2 s.  co m*/

            return readTheme(themeElement);
        }
    }

    Theme theme = new Theme(themeId);

    theme.setCssPath("/css");
    theme.setImagesPath("/images");
    theme.setJavaScriptPath("/js");
    theme.setRootPath("/");
    theme.setTemplateExtension(themeType);
    theme.setTemplatesPath("/templates");

    return theme;
}

From source file:com.liferay.petra.log4j.Log4JUtil.java

License:Open Source License

public static void configureLog4J(URL url) {
    if (url == null) {
        return;/*  w  w w.j ava2 s .com*/
    }

    String urlContent = _getURLContent(url);

    if (urlContent == null) {
        return;
    }

    // See LPS-6029, LPS-8865, and LPS-24280

    DOMConfigurator domConfigurator = new DOMConfigurator();

    domConfigurator.doConfigure(new UnsyncStringReader(urlContent), LogManager.getLoggerRepository());

    try {
        SAXReader saxReader = new SAXReader();

        saxReader.setEntityResolver(new EntityResolver() {

            @Override
            public InputSource resolveEntity(String publicId, String systemId) {

                if (systemId.endsWith("log4j.dtd")) {
                    return new InputSource(DOMConfigurator.class.getResourceAsStream("log4j.dtd"));
                }

                return null;
            }

        });

        Document document = saxReader.read(new UnsyncStringReader(urlContent), url.toExternalForm());

        Element rootElement = document.getRootElement();

        List<Element> categoryElements = rootElement.elements("category");

        for (Element categoryElement : categoryElements) {
            String name = categoryElement.attributeValue("name");

            Element priorityElement = categoryElement.element("priority");

            String priority = priorityElement.attributeValue("value");

            java.util.logging.Logger jdkLogger = java.util.logging.Logger.getLogger(name);

            jdkLogger.setLevel(_getJdkLevel(priority));
        }
    } catch (Exception e) {
        _logger.error(e, e);
    }
}

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 ww.ja va 2  s.  c om*/

    /*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.portal.ejb.PortletManagerImpl.java

License:Open Source License

private Map _readLiferayDisplayXML(String servletContextName, String xml)
        throws DocumentException, IOException {

    Map categories = new LinkedHashMap();

    if (xml == null) {
        return categories;
    }/*from  w ww.j  av  a 2  s  . co  m*/

    SAXReader reader = new SAXReader();
    reader.setEntityResolver(null);

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

    Set portletIds = new HashSet();

    Iterator itr1 = doc.getRootElement().elements("category").iterator();

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

        String name = category.attributeValue("name");

        List portlets = new ArrayList();

        Iterator itr2 = category.elements("portlet").iterator();

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

            String portletId = portlet.attributeValue("id");
            if (servletContextName != null) {
                portletId = servletContextName + PortletConfigImpl.WAR_SEPARATOR + portletId;
            }

            portletIds.add(portletId);

            String status = portlet.attributeValue("status");

            portlets.add(new KeyValuePair(portletId, status));
        }

        if (portlets.size() > 0) {
            categories.put(name, portlets);
        }
    }

    // Portlets that do not belong to any categories should default to the
    // Undefined category

    List undefinedPortlets = new ArrayList();

    itr1 = _getPortletsPool().values().iterator();

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

        String portletId = portlet.getPortletId();

        if ((servletContextName != null) && (portlet.isWARFile())
                && (portletId.startsWith(servletContextName) && (!portletIds.contains(portletId)))) {

            undefinedPortlets.add(new KeyValuePair(portletId, null));
        } else if ((servletContextName == null) && (!portlet.isWARFile())
                && (!portletIds.contains(portletId))) {

            undefinedPortlets.add(new KeyValuePair(portletId, null));
        }
    }

    if (undefinedPortlets.size() > 0) {
        categories.put("category.undefined", undefinedPortlets);
    }

    return categories;
}

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

License:Open Source License

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

    Set liferayPortletIds = new HashSet();

    if (xml == null) {
        return liferayPortletIds;
    }/*from w w w .j ava  2  s  .  c om*/

    SAXReader reader = new SAXReader();
    reader.setEntityResolver(null);

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

    Element root = doc.getRootElement();

    Map customUserAttributes = new HashMap();

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

    while (itr.hasNext()) {
        Element customUserAttribute = (Element) itr.next();

        String name = customUserAttribute.attributeValue("name");
        String customClass = customUserAttribute.attributeValue("custom-class");

        customUserAttributes.put(name, customClass);
    }

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

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

        String portletId = portlet.attributeValue("id");
        if (servletContextName != null) {
            portletId = servletContextName + PortletConfigImpl.WAR_SEPARATOR + portletId;
        }

        liferayPortletIds.add(portletId);

        Portlet portletModel = (Portlet) portletsPool.get(portletId);

        if (portletModel != null) {
            portletModel.setStrutsPath(
                    GetterUtil.get(portlet.attributeValue("struts-path"), portletModel.getStrutsPath()));
            portletModel.setIndexerClass(
                    GetterUtil.get(portlet.attributeValue("indexer-class"), portletModel.getIndexerClass()));
            portletModel.setSchedulerClass(GetterUtil.get(portlet.attributeValue("scheduler-class"),
                    portletModel.getSchedulerClass()));
            portletModel.setPreferencesSharingType(
                    GetterUtil.get(portlet.attributeValue("preferences-sharing-type"),
                            portletModel.getPreferencesSharingType()));
            portletModel.setUseDefaultTemplate(GetterUtil.get(portlet.attributeValue("use-default-template"),
                    portletModel.isUseDefaultTemplate()));
            portletModel.setShowPortletAccessDenied(
                    GetterUtil.get(portlet.attributeValue("show-portlet-access-denied"),
                            portletModel.isShowPortletAccessDenied()));
            portletModel.setShowPortletInactive(GetterUtil.get(portlet.attributeValue("show-portlet-inactive"),
                    portletModel.isShowPortletInactive()));
            portletModel.setRestoreCurrentView(GetterUtil.get(portlet.attributeValue("restore-current-view"),
                    portletModel.isRestoreCurrentView()));
            portletModel.setNs4Compatible(
                    GetterUtil.get(portlet.attributeValue("ns-4-compatible"), portletModel.isNs4Compatible()));
            portletModel.setNarrow(GetterUtil.get(portlet.attributeValue("narrow"), portletModel.isNarrow()));
            portletModel.setActive(GetterUtil.get(portlet.attributeValue("active"), portletModel.isActive()));
            portletModel
                    .setInclude(GetterUtil.get(portlet.attributeValue("include"), portletModel.isInclude()));

            portletModel.getCustomUserAttributes().putAll(customUserAttributes);
        }
    }

    return liferayPortletIds;
}

From source file:com.liferay.portal.events.InitAction.java

License:Open Source License

public void run(String[] ids) throws ActionException {

    // Set default locale

    String userLanguage = SystemProperties.get("user.language");
    String userCountry = SystemProperties.get("user.country");
    String userVariant = SystemProperties.get("user.variant");

    if (Validator.isNull(userVariant)) {
        Locale.setDefault(new Locale(userLanguage, userCountry));
    } else {/*from  w  ww  .j  a v  a2s .com*/
        Locale.setDefault(new Locale(userLanguage, userCountry, userVariant));
    }

    // Log4J

    if (GetterUtil.get(PropsUtil.get(PropsUtil.LOG_CONFIGURE_LOG4J), true) && !ServerDetector.isSun()) {

        URL portalLog4jUrl = getClass().getClassLoader().getResource("META-INF/portal-log4j.xml");

        if (Logger.getRootLogger().getAllAppenders() instanceof NullEnumeration) {

            DOMConfigurator.configure(portalLog4jUrl);
        } else {
            Set currentLoggerNames = new HashSet();

            Enumeration enu = LogManager.getCurrentLoggers();

            while (enu.hasMoreElements()) {
                Logger logger = (Logger) enu.nextElement();

                currentLoggerNames.add(logger.getName());
            }

            try {
                SAXReader reader = new SAXReader();

                Document doc = reader.read(portalLog4jUrl);

                Element root = doc.getRootElement();

                Iterator itr = root.elements("category").iterator();

                while (itr.hasNext()) {
                    Element category = (Element) itr.next();

                    String name = category.attributeValue("name");
                    String priority = category.element("priority").attributeValue("value");

                    Logger logger = Logger.getLogger(name);

                    logger.setLevel(Level.toLevel(priority));
                }
            } catch (Exception e) {
                com.dotmarketing.util.Logger.error(this, e.getMessage(), e);
            }
        }
    }
}

From source file:com.liferay.portal.servlet.MainServlet.java

License:Open Source License

private void _checkWebSettings(String xml) throws DocumentException {
    SAXReader reader = new SAXReader();
    reader.setEntityResolver(null);//from   w  w w  .j  av a 2  s  .  c o m

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

    Element root = doc.getRootElement();

    int timeout = GetterUtil.getInteger(PropsUtil.get(PropsUtil.SESSION_TIMEOUT));

    Element sessionConfig = root.element("session-config");

    if (sessionConfig != null) {
        String sessionTimeout = sessionConfig.elementText("session-timeout");

        timeout = GetterUtil.get(sessionConfig.elementText("session-timeout"), timeout);
    }

    PropsUtil.set(PropsUtil.SESSION_TIMEOUT, Integer.toString(timeout));
}

From source file:com.liferay.portal.tools.EARXMLBuilder.java

License:Open Source License

private String _buildPramatiXMLWebModule(String path) throws DocumentException, IOException {

    String contextRoot = path.substring(2, path.length() - 4);
    String filePath = path + "/docroot/WEB-INF/web.xml";

    if (path.endsWith("-complete")) {
        contextRoot = "/";
        filePath = path.substring(0, path.length() - 9) + "/docroot/WEB-INF/web.xml";
    }/*from  ww  w.j av  a2  s.c o  m*/

    StringBuffer sb = new StringBuffer();

    sb.append("\t<web-module>\n");
    sb.append("\t\t<name>").append(contextRoot).append("</name>\n");
    sb.append("\t\t<module-name>").append(path.substring(3, path.length())).append(".war</module-name>\n");

    SAXReader reader = new SAXReader();
    reader.setEntityResolver(new EntityResolver());

    Document doc = reader.read(new File(filePath));

    Iterator itr = doc.getRootElement().elements("ejb-local-ref").iterator();

    while (itr.hasNext()) {
        Element ejbLocalRef = (Element) itr.next();

        sb.append("\t\t<ejb-local-ref>\n");
        sb.append("\t\t\t<ejb-ref-name>").append(ejbLocalRef.elementText("ejb-ref-name"))
                .append("</ejb-ref-name>\n");
        sb.append("\t\t\t<ejb-link>").append(ejbLocalRef.elementText("ejb-link")).append("</ejb-link>\n");
        sb.append("\t\t</ejb-local-ref>\n");
    }

    itr = doc.getRootElement().elements("resource-ref").iterator();

    while (itr.hasNext()) {
        Element resourceRef = (Element) itr.next();

        sb.append("\t\t<resource-mapping>\n");
        sb.append("\t\t\t<resource-name>").append(resourceRef.elementText("res-ref-name"))
                .append("</resource-name>\n");
        sb.append("\t\t\t<resource-type>").append(resourceRef.elementText("res-type"))
                .append("</resource-type>\n");
        sb.append("\t\t\t<resource-link>").append(resourceRef.elementText("res-ref-name"))
                .append("</resource-link>\n");
        sb.append("\t\t</resource-mapping>\n");
    }

    sb.append("\t</web-module>\n");

    return sb.toString();
}