Example usage for com.liferay.portal.kernel.xml SAXReaderUtil read

List of usage examples for com.liferay.portal.kernel.xml SAXReaderUtil read

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.xml SAXReaderUtil read.

Prototype

public static Document read(URL url) throws DocumentException 

Source Link

Usage

From source file:com.liferay.exportimport.controller.PortletImportController.java

License:Open Source License

public void importPortletPreferences(PortletDataContext portletDataContext, long companyId, long groupId,
        Layout layout, Element parentElement, boolean preserveScopeLayoutId,
        boolean importPortletArchivedSetups, boolean importPortletData, boolean importPortletSetup,
        boolean importPortletUserPreferences) throws Exception {

    long plid = LayoutConstants.DEFAULT_PLID;
    String scopeType = StringPool.BLANK;
    String scopeLayoutUuid = StringPool.BLANK;

    if (layout != null) {
        plid = layout.getPlid();/*from  ww w  .jav a2  s.  com*/

        if (preserveScopeLayoutId) {
            javax.portlet.PortletPreferences jxPortletPreferences = PortletPreferencesFactoryUtil
                    .getLayoutPortletSetup(layout, portletDataContext.getPortletId());

            scopeType = GetterUtil.getString(jxPortletPreferences.getValue("lfrScopeType", null));
            scopeLayoutUuid = GetterUtil.getString(jxPortletPreferences.getValue("lfrScopeLayoutUuid", null));

            portletDataContext.setScopeType(scopeType);
            portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);
        }
    }

    List<Element> portletPreferencesElements = parentElement.elements("portlet-preferences");

    for (Element portletPreferencesElement : portletPreferencesElements) {
        String path = portletPreferencesElement.attributeValue("path");

        if (portletDataContext.isPathNotProcessed(path)) {
            String xml = null;

            Element element = null;

            try {
                xml = portletDataContext.getZipEntryAsString(path);

                Document preferencesDocument = SAXReaderUtil.read(xml);

                element = preferencesDocument.getRootElement();
            } catch (DocumentException de) {
                throw new SystemException(
                        "Unable to parse XML portlet preferences for portlet "
                                + portletDataContext.getPortletId() + " while importing portlet preferences",
                        de);
            }

            long ownerId = GetterUtil.getLong(element.attributeValue("owner-id"));
            int ownerType = GetterUtil.getInteger(element.attributeValue("owner-type"));

            if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_COMPANY) || !importPortletSetup) {

                continue;
            }

            if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) && !importPortletArchivedSetups) {

                continue;
            }

            if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_USER)
                    && (ownerId != PortletKeys.PREFS_OWNER_ID_DEFAULT) && !importPortletUserPreferences) {

                continue;
            }

            long curPlid = plid;
            String curPortletId = portletDataContext.getPortletId();

            if (ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP) {
                curPlid = PortletKeys.PREFS_PLID_SHARED;
                curPortletId = portletDataContext.getRootPortletId();
                ownerId = portletDataContext.getScopeGroupId();
            }

            long elementPlid = GetterUtil.getLong(element.attributeValue("plid"));

            if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_LAYOUT)
                    && (ownerId != PortletKeys.PREFS_OWNER_ID_DEFAULT)
                    && (elementPlid == PortletKeys.PREFS_PLID_SHARED)) {

                curPlid = PortletKeys.PREFS_PLID_SHARED;
                ownerId = portletDataContext.getScopeGroupId();
            }

            if (ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) {
                String userUuid = element.attributeValue("archive-user-uuid");

                long userId = portletDataContext.getUserId(userUuid);

                String name = element.attributeValue("archive-name");

                curPortletId = portletDataContext.getRootPortletId();

                PortletItem portletItem = _portletItemLocalService.updatePortletItem(userId, groupId, name,
                        curPortletId, PortletPreferences.class.getName());

                curPlid = LayoutConstants.DEFAULT_PLID;
                ownerId = portletItem.getPortletItemId();
            }

            if (ownerType == PortletKeys.PREFS_OWNER_TYPE_USER) {
                String userUuid = element.attributeValue("user-uuid");

                ownerId = portletDataContext.getUserId(userUuid);
            }

            boolean defaultUser = GetterUtil.getBoolean(element.attributeValue("default-user"));

            if (defaultUser) {
                ownerId = _userLocalService.getDefaultUserId(companyId);
            }

            javax.portlet.PortletPreferences jxPortletPreferences = PortletPreferencesFactoryUtil
                    .fromXML(companyId, ownerId, ownerType, curPlid, curPortletId, xml);

            Element importDataRootElement = portletDataContext.getImportDataRootElement();

            try {
                Element preferenceDataElement = portletPreferencesElement.element("preference-data");

                if (preferenceDataElement != null) {
                    portletDataContext.setImportDataRootElement(preferenceDataElement);
                }

                ExportImportPortletPreferencesProcessor exportImportPortletPreferencesProcessor = ExportImportPortletPreferencesProcessorRegistryUtil
                        .getExportImportPortletPreferencesProcessor(
                                PortletIdCodec.decodePortletName(curPortletId));

                if (exportImportPortletPreferencesProcessor != null) {
                    List<Capability> importCapabilities = exportImportPortletPreferencesProcessor
                            .getImportCapabilities();

                    if (ListUtil.isNotEmpty(importCapabilities)) {
                        for (Capability importCapability : importCapabilities) {

                            importCapability.process(portletDataContext, jxPortletPreferences);
                        }
                    }

                    exportImportPortletPreferencesProcessor.processImportPortletPreferences(portletDataContext,
                            jxPortletPreferences);
                } else {
                    PortletDataHandler portletDataHandler = _portletDataHandlerProvider
                            .provide(portletDataContext.getCompanyId(), curPortletId);

                    if (portletDataHandler != null) {
                        jxPortletPreferences = portletDataHandler.processImportPortletPreferences(
                                portletDataContext, curPortletId, jxPortletPreferences);
                    }
                }
            } finally {
                portletDataContext.setImportDataRootElement(importDataRootElement);
            }

            updatePortletPreferences(portletDataContext, ownerId, ownerType, curPlid, curPortletId,
                    PortletPreferencesFactoryUtil.toXML(jxPortletPreferences), importPortletData);
        }
    }

    if (preserveScopeLayoutId && (layout != null)) {
        javax.portlet.PortletPreferences jxPortletPreferences = PortletPreferencesFactoryUtil
                .getLayoutPortletSetup(layout, portletDataContext.getPortletId());

        try {
            jxPortletPreferences.setValue("lfrScopeType", scopeType);
            jxPortletPreferences.setValue("lfrScopeLayoutUuid", scopeLayoutUuid);

            jxPortletPreferences.store();
        } finally {
            portletDataContext.setScopeType(scopeType);
            portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);
        }
    }
}

From source file:com.liferay.exportimport.controller.PortletImportController.java

License:Open Source License

protected void doImportPortletInfo(PortletDataContext portletDataContext, long userId) throws Exception {

    Map<String, String[]> parameterMap = portletDataContext.getParameterMap();

    boolean importPermissions = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();/*from   w  w  w . j ava  2  s .c  om*/

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    if (serviceContext == null) {
        serviceContext = new ServiceContext();

        serviceContext.setCompanyId(portletDataContext.getCompanyId());
        serviceContext.setSignedIn(false);
        serviceContext.setUserId(userId);

        ServiceContextThreadLocal.pushServiceContext(serviceContext);
    }

    // LAR validation

    validateFile(portletDataContext.getCompanyId(), portletDataContext.getGroupId(),
            portletDataContext.getPortletId(), portletDataContext.getZipReader());

    // Source and target group id

    Map<Long, Long> groupIds = (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(Group.class);

    groupIds.put(portletDataContext.getSourceGroupId(), portletDataContext.getGroupId());

    // Manifest

    ManifestSummary manifestSummary = _exportImportHelper.getManifestSummary(portletDataContext);

    if (BackgroundTaskThreadLocal.hasBackgroundTask()) {
        _portletDataHandlerStatusMessageSender.sendStatusMessage("portlet", portletDataContext.getPortletId(),
                manifestSummary);
    }

    portletDataContext.setManifestSummary(manifestSummary);

    // Read expando tables, locks and permissions to make them
    // available to the data handlers through the portlet data context

    Element rootElement = portletDataContext.getImportDataRootElement();

    Element portletElement = null;

    try {
        portletElement = rootElement.element("portlet");

        Document portletDocument = SAXReaderUtil
                .read(portletDataContext.getZipEntryAsString(portletElement.attributeValue("path")));

        portletElement = portletDocument.getRootElement();
    } catch (DocumentException de) {
        throw new SystemException("Unable to parse XML document for portlet "
                + portletDataContext.getPortletId() + " during import", de);
    }

    LayoutCache layoutCache = new LayoutCache();

    if (importPermissions) {
        _permissionImporter.checkRoles(layoutCache, portletDataContext.getCompanyId(),
                portletDataContext.getGroupId(), userId, portletElement);

        _permissionImporter.readPortletDataPermissions(portletDataContext);
    }

    String layoutsImportMode = MapUtil.getString(parameterMap, PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE);

    if (!layoutsImportMode.equals(PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_CREATED_FROM_PROTOTYPE)) {

        readExpandoTables(portletDataContext);
    }

    readLocks(portletDataContext);

    Element portletDataElement = portletElement.element("portlet-data");

    Map<String, Boolean> importPortletControlsMap = _exportImportHelper.getImportPortletControlsMap(
            portletDataContext.getCompanyId(), portletDataContext.getPortletId(), parameterMap,
            portletDataElement, manifestSummary);

    Layout layout = _layoutLocalService.getLayout(portletDataContext.getPlid());

    try {

        // Portlet preferences

        importPortletPreferences(portletDataContext, layout.getCompanyId(), portletDataContext.getGroupId(),
                layout, portletElement, true,
                importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS),
                importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_DATA),
                importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP),
                importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_USER_PREFERENCES));

        // Portlet data

        if (importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_DATA)) {

            if (_log.isDebugEnabled()) {
                _log.debug("Importing portlet data");
            }

            importPortletData(portletDataContext, portletDataElement);
        }
    } finally {
        resetPortletScope(portletDataContext, portletDataContext.getGroupId());
    }

    // Portlet permissions

    if (importPermissions) {
        if (_log.isDebugEnabled()) {
            _log.debug("Importing portlet permissions");
        }

        _permissionImporter.importPortletPermissions(layoutCache, portletDataContext.getCompanyId(),
                portletDataContext.getGroupId(), userId, layout, portletElement,
                portletDataContext.getPortletId());

        if (userId > 0) {
            Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);

            User user = _userLocalService.fetchUser(userId);

            indexer.reindex(user);
        }
    }

    // Asset links

    if (_log.isDebugEnabled()) {
        _log.debug("Importing asset links");
    }

    importAssetLinks(portletDataContext);

    // Deletion system events

    _deletionSystemEventImporter.importDeletionSystemEvents(portletDataContext);

    if (_log.isInfoEnabled()) {
        _log.info("Importing portlet takes " + stopWatch.getTime() + " ms");
    }

    // Service portlet preferences

    boolean importPortletSetup = importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP);

    if (importPortletSetup) {
        try {
            List<Element> serviceElements = rootElement.elements("service");

            for (Element serviceElement : serviceElements) {
                Document serviceDocument = SAXReaderUtil
                        .read(portletDataContext.getZipEntryAsString(serviceElement.attributeValue("path")));

                importServicePortletPreferences(portletDataContext, serviceDocument.getRootElement());
            }
        } catch (DocumentException de) {
            throw new SystemException("Unable to parse XML service information for portlet "
                    + portletDataContext.getPortletId() + " during import", de);
        } catch (PortalException pe) {
            throw new PortletDataException(
                    "Unable to import service preferences for portlet " + portletDataContext.getPortletId(),
                    pe);
        }
    }

    ZipReader zipReader = portletDataContext.getZipReader();

    zipReader.close();
}

From source file:com.liferay.exportimport.controller.PortletImportController.java

License:Open Source License

protected void importAssetLinks(PortletDataContext portletDataContext) throws Exception {

    String xml = portletDataContext
            .getZipEntryAsString(ExportImportPathUtil.getSourceRootPath(portletDataContext) + "/links.xml");

    if (xml == null) {
        return;/*from  ww w  .ja v  a 2s .com*/
    }

    Element importDataRootElement = portletDataContext.getImportDataRootElement();

    try {
        Document document = SAXReaderUtil.read(xml);

        Element rootElement = document.getRootElement();

        portletDataContext.setImportDataRootElement(rootElement);

        Element linksElement = portletDataContext.getImportDataGroupElement(StagedAssetLink.class);

        List<Element> linkElements = linksElement.elements();

        for (Element linkElement : linkElements) {
            StagedModelDataHandlerUtil.importStagedModel(portletDataContext, linkElement);
        }
    } finally {
        portletDataContext.setImportDataRootElement(importDataRootElement);
    }
}

From source file:com.liferay.exportimport.controller.PortletImportController.java

License:Open Source License

protected void readExpandoTables(PortletDataContext portletDataContext) throws Exception {

    String xml = portletDataContext.getZipEntryAsString(
            ExportImportPathUtil.getSourceRootPath(portletDataContext) + "/expando-tables.xml");

    if (xml == null) {
        return;/* www .jav a 2  s.c o m*/
    }

    Document document = SAXReaderUtil.read(xml);

    Element rootElement = document.getRootElement();

    List<Element> expandoTableElements = rootElement.elements("expando-table");

    for (Element expandoTableElement : expandoTableElements) {
        String className = expandoTableElement.attributeValue("class-name");

        ExpandoTable expandoTable = null;

        try {
            expandoTable = _expandoTableLocalService.getDefaultTable(portletDataContext.getCompanyId(),
                    className);
        } catch (NoSuchTableException nste) {

            // LPS-52675

            if (_log.isDebugEnabled()) {
                _log.debug(nste, nste);
            }

            expandoTable = _expandoTableLocalService.addDefaultTable(portletDataContext.getCompanyId(),
                    className);
        }

        List<Element> expandoColumnElements = expandoTableElement.elements("expando-column");

        for (Element expandoColumnElement : expandoColumnElements) {
            long columnId = GetterUtil.getLong(expandoColumnElement.attributeValue("column-id"));
            String name = expandoColumnElement.attributeValue("name");
            int type = GetterUtil.getInteger(expandoColumnElement.attributeValue("type"));
            String defaultData = expandoColumnElement.elementText("default-data");
            String typeSettings = expandoColumnElement.elementText("type-settings");

            Serializable defaultDataObject = ExpandoConverterUtil.getAttributeFromString(type, defaultData);

            ExpandoColumn expandoColumn = _expandoColumnLocalService.getColumn(expandoTable.getTableId(), name);

            if (expandoColumn != null) {
                _expandoColumnLocalService.updateColumn(expandoColumn.getColumnId(), name, type,
                        defaultDataObject);
            } else {
                expandoColumn = _expandoColumnLocalService.addColumn(expandoTable.getTableId(), name, type,
                        defaultDataObject);
            }

            _expandoColumnLocalService.updateTypeSettings(expandoColumn.getColumnId(), typeSettings);

            portletDataContext.importPermissions(ExpandoColumn.class, columnId, expandoColumn.getColumnId());
        }
    }
}

From source file:com.liferay.exportimport.controller.PortletImportController.java

License:Open Source License

protected void readLocks(PortletDataContext portletDataContext) throws Exception {

    String xml = portletDataContext
            .getZipEntryAsString(ExportImportPathUtil.getSourceRootPath(portletDataContext) + "/locks.xml");

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

    Document document = SAXReaderUtil.read(xml);

    Element rootElement = document.getRootElement();

    List<Element> assetElements = rootElement.elements("asset");

    for (Element assetElement : assetElements) {
        String path = assetElement.attributeValue("path");
        String className = assetElement.attributeValue("class-name");
        String key = assetElement.attributeValue("key");

        Lock lock = (Lock) portletDataContext.getZipEntryAsObject(path);

        if (lock != null) {
            portletDataContext.addLocks(className, key, lock);
        }
    }
}

From source file:com.liferay.exportimport.controller.PortletImportController.java

License:Open Source License

protected void validateFile(long companyId, long groupId, String portletId, ZipReader zipReader)
        throws Exception {

    // XML/* w ww . j a v a  2 s .  co m*/

    String xml = zipReader.getEntryAsString("/manifest.xml");

    if (xml == null) {
        throw new LARFileException(LARFileException.TYPE_MISSING_MANIFEST);
    }

    Element rootElement = null;

    try {
        Document document = SAXReaderUtil.read(xml);

        rootElement = document.getRootElement();
    } catch (Exception e) {
        throw new LARFileException(LARFileException.TYPE_INVALID_MANIFEST, e);
    }

    // Build compatibility

    Element headerElement = rootElement.element("header");
    Element portletElement = rootElement.element("portlet");

    int importBuildNumber = GetterUtil.getInteger(headerElement.attributeValue("build-number"));

    if (importBuildNumber < ReleaseInfo.RELEASE_7_0_0_BUILD_NUMBER) {
        int buildNumber = ReleaseInfo.getBuildNumber();

        throw new LayoutImportException(LayoutImportException.TYPE_WRONG_BUILD_NUMBER,
                new Object[] { importBuildNumber, buildNumber });
    } else {
        BiPredicate<Version, Version> majorVersionBiPredicate = (currentVersion, importVersion) -> Objects
                .equals(currentVersion.getMajor(), importVersion.getMajor());

        BiPredicate<Version, Version> minorVersionBiPredicate = (currentVersion, importVersion) -> {
            int currentMinorVersion = GetterUtil.getInteger(currentVersion.getMinor(), -1);
            int importedMinorVersion = GetterUtil.getInteger(importVersion.getMinor(), -1);

            if (((currentMinorVersion == -1) && (importedMinorVersion == -1))
                    || (currentMinorVersion < importedMinorVersion)) {

                return false;
            }

            return true;
        };

        BiPredicate<Version, Version> manifestVersionBiPredicate = (currentVersion, importVersion) -> {
            BiPredicate<Version, Version> versionBiPredicate = majorVersionBiPredicate
                    .and(minorVersionBiPredicate);

            return versionBiPredicate.test(currentVersion, importVersion);
        };

        String importSchemaVersion = GetterUtil.getString(headerElement.attributeValue("schema-version"),
                "1.0.0");

        if (!manifestVersionBiPredicate.test(
                Version.getInstance(ExportImportConstants.EXPORT_IMPORT_SCHEMA_VERSION),
                Version.getInstance(importSchemaVersion))) {

            throw new LayoutImportException(LayoutImportException.TYPE_WRONG_LAR_SCHEMA_VERSION,
                    new Object[] { importSchemaVersion, ExportImportConstants.EXPORT_IMPORT_SCHEMA_VERSION });
        }
    }

    // Type

    String larType = headerElement.attributeValue("type");

    if (!larType.equals("portlet")) {
        throw new LARTypeException(larType, new String[] { "portlet" });
    }

    // Portlet compatibility

    String rootPortletId = headerElement.attributeValue("root-portlet-id");

    String expectedRootPortletId = PortletIdCodec.decodePortletName(portletId);

    if (!expectedRootPortletId.equals(rootPortletId)) {
        throw new PortletIdException(expectedRootPortletId);
    }

    String schemaVersion = GetterUtil.getString(portletElement.attributeValue("schema-version"), "1.0.0");

    PortletDataHandler portletDataHandler = _portletDataHandlerProvider.provide(companyId, portletId);

    if (!portletDataHandler.validateSchemaVersion(schemaVersion)) {
        throw new LayoutImportException(LayoutImportException.TYPE_WRONG_PORTLET_SCHEMA_VERSION,
                new Object[] { schemaVersion, portletId, portletDataHandler.getSchemaVersion() });
    }

    // Available locales

    if (portletDataHandler.isDataLocalized()) {
        List<Locale> sourceAvailableLocales = Arrays.asList(LocaleUtil
                .fromLanguageIds(StringUtil.split(headerElement.attributeValue("available-locales"))));

        for (Locale sourceAvailableLocale : sourceAvailableLocales) {
            if (!LanguageUtil.isAvailableLocale(_portal.getSiteGroupId(groupId), sourceAvailableLocale)) {

                LocaleException le = new LocaleException(LocaleException.TYPE_EXPORT_IMPORT);

                le.setSourceAvailableLocales(sourceAvailableLocales);
                le.setTargetAvailableLocales(LanguageUtil.getAvailableLocales(_portal.getSiteGroupId(groupId)));

                throw le;
            }
        }
    }
}

From source file:com.liferay.exportimport.lar.PermissionImporter.java

License:Open Source License

public void readPortletDataPermissions(PortletDataContext portletDataContext) throws Exception {

    String xml = portletDataContext.getZipEntryAsString(
            ExportImportPathUtil.getSourceRootPath(portletDataContext) + "/portlet-data-permissions.xml");

    if (xml == null) {
        return;//from w  w  w.j av a  2  s  .  c o m
    }

    Document document = SAXReaderUtil.read(xml);

    Element rootElement = document.getRootElement();

    List<Element> portletDataElements = rootElement.elements("portlet-data");

    for (Element portletDataElement : portletDataElements) {
        String resourceName = portletDataElement.attributeValue("resource-name");
        long resourcePK = GetterUtil.getLong(portletDataElement.attributeValue("resource-pk"));

        List<KeyValuePair> permissions = new ArrayList<>();

        List<Element> permissionsElements = portletDataElement.elements("permissions");

        for (Element permissionsElement : permissionsElements) {
            String roleName = permissionsElement.attributeValue("role-name");
            String actions = permissionsElement.attributeValue("actions");

            KeyValuePair permission = new KeyValuePair(roleName, actions);

            permissions.add(permission);
        }

        portletDataContext.addPermissions(resourceName, resourcePK, permissions);
    }
}

From source file:com.liferay.exportimport.lar.PortletDataContextFactoryImpl.java

License:Open Source License

protected void readXML(PortletDataContext portletDataContext) throws PortletDataException {

    String xml = portletDataContext.getZipEntryAsString("/manifest.xml");

    Element rootElement = null;//from w  w  w. j a va2 s.  c o m

    try {
        Document document = SAXReaderUtil.read(xml);

        rootElement = document.getRootElement();
    } catch (Exception e) {
        throw new PortletDataException("Unable to create portlet data context for the import "
                + "process because of an invalid LAR manifest", e);
    }

    portletDataContext.setImportDataRootElement(rootElement);

    Element headerElement = rootElement.element("header");

    long sourceCompanyId = GetterUtil.getLong(headerElement.attributeValue("company-id"));

    portletDataContext.setSourceCompanyId(sourceCompanyId);

    long sourceCompanyGroupId = GetterUtil.getLong(headerElement.attributeValue("company-group-id"));

    portletDataContext.setSourceCompanyGroupId(sourceCompanyGroupId);

    long sourceGroupId = GetterUtil.getLong(headerElement.attributeValue("group-id"));

    portletDataContext.setSourceGroupId(sourceGroupId);

    long sourceUserPersonalSiteGroupId = GetterUtil
            .getLong(headerElement.attributeValue("user-personal-site-group-id"));

    portletDataContext.setSourceUserPersonalSiteGroupId(sourceUserPersonalSiteGroupId);

    Element missingReferencesElement = rootElement.element("missing-references");

    if (missingReferencesElement != null) {
        portletDataContext.setMissingReferencesElement(missingReferencesElement);
    }
}

From source file:com.liferay.faces.portal.component.inputsearch.internal.InputSearchRenderer.java

License:Open Source License

@Override
protected StringBuilder getMarkup(UIComponent uiComponent, StringBuilder markup) throws Exception {

    //J-/* w  w  w.java2 s .c  o  m*/
    // NOTE: The specified markup looks like the following (HTML comments added for clarity):
    //
    // <!-- Opening <div> rendered by html/taglib/ui/input_search/page.jsp -->
    // <div class="input-append">
    //
    //    <!-- Input text field rendered by html/taglib/ui/input_search/page.jsp -->
    //    <input class="search-query span9" id="...:jid42" name="..." placeholder="" type="text" value="" />
    //
    //    <!-- Search button rendered by html/taglib/ui/input_search/page.jsp -->
    //    <button class="btn" type="submit">Search</button>
    //
    //    <!-- HtmlInputText (dynamically added JSF child component) -->
    //    <input type="text" name="...:htmlInputText" />
    //
    //    <!-- HtmlCommandButton (dynamically added JSF child component) -->
    //    <input type="submit" name="...:htmlCommandButton" value="" />
    //
    // <!-- Closing </div> rendered by html/taglib/ui/input_search/page.jsp -->
    // </div>
    //J+

    // Parse the generated markup as an XML document.
    InputSearch inputSearch = cast(uiComponent);
    Document document = SAXReaderUtil.read(markup.toString());
    Element rootElement = document.getRootElement();

    // Locate the first/main input element in the XML document. This is the one that will contain contain the value
    // that will be submitted in the postback and received by the decode(FacesContext, UIComponent) method).
    String xpathInput = "//input[contains(@id, '" + uiComponent.getClientId() + "')]";
    Element mainInputElement = (Element) rootElement.selectSingleNode(xpathInput);

    if (mainInputElement != null) {

        // Copy the value attribute of the InputSearch component to the first input element in the XML document.
        mainInputElement.attribute("value").setValue((String) inputSearch.getValue());

        // Locate the dynamically added HtmlInputText and HtmlCommandButton child components.
        String xpathInputs = "//input[@type='text']";
        List<Node> inputElements = rootElement.selectNodes(xpathInputs);

        if ((inputElements != null) && (inputElements.size() == 2)) {

            // Copy each "on" attribute name/value pairs from the HtmlInputText to the first input element in
            // the XML document. This will enable all of the AjaxBehavior events like keyup/keydown to work.
            Element htmlInputTextElement = (Element) inputElements.get(1);
            Iterator<Attribute> attributeIterator = htmlInputTextElement.attributeIterator();

            while (attributeIterator.hasNext()) {
                Attribute attribute = attributeIterator.next();
                String attributeName = attribute.getName();

                if (attributeName.startsWith("on")) {
                    mainInputElement.addAttribute(attributeName, attribute.getValue());
                }
            }

            // Remove the HtmlInputText <input> from the XML document so that only one text field is rendered.
            htmlInputTextElement.getParent().remove(htmlInputTextElement);
        }
    }

    // Locate the HtmlCommandButton in the XML document.
    List<UIComponent> children = uiComponent.getChildren();
    HtmlCommandButton htmlCommandButton = (HtmlCommandButton) children.get(1);
    String htmlCommandButtonClientId = htmlCommandButton.getClientId();

    // Note that if there is an AjaxBehavior, then the rendered HtmlCommandButton can be located in the XML document
    // via the name attribute. Otherwise it can be located in the XML document via the id attribute.
    String htmlCommandButtonXPath = "//input[contains(@name,'" + htmlCommandButtonClientId
            + "') and @type='submit']";
    Element htmlCommandButtonElement = (Element) rootElement.selectSingleNode(htmlCommandButtonXPath);

    if (htmlCommandButtonElement == null) {
        htmlCommandButtonXPath = "//input[contains(@id,'" + htmlCommandButtonClientId
                + "') and @type='submit']";
        htmlCommandButtonElement = (Element) rootElement.selectSingleNode(htmlCommandButtonXPath);
    }

    if (htmlCommandButtonElement != null) {

        // Locate the <button> element in the XML document that was rendered by page.jsp
        Element buttonElement = (Element) rootElement.selectSingleNode("//button[@type='submit']");

        if (buttonElement != null) {

            // Copy attributes found on the HtmlCommandButton <input> element to the <button> element that was
            // rendered by page.jsp
            Attribute onClickAttr = htmlCommandButtonElement.attribute("onclick");

            if (onClickAttr != null) {
                buttonElement.addAttribute("onclick", onClickAttr.getValue());
            }

            Attribute nameAttr = htmlCommandButtonElement.attribute("name");

            if (nameAttr != null) {
                buttonElement.addAttribute("name", nameAttr.getValue());
            }

            Attribute idAttr = htmlCommandButtonElement.attribute("id");

            if (idAttr != null) {
                buttonElement.addAttribute("id", idAttr.getValue());
            }

            // Remove the HtmlCommandButton <input> from the XML document so that only one button is rendered.
            htmlCommandButtonElement.getParent().remove(htmlCommandButtonElement);
        }
    }

    // Returned the modified verson of the specified markup.
    return new StringBuilder(rootElement.asXML());
}

From source file:com.liferay.faces.test.hooks.TestSetupAction.java

License:Open Source License

protected void setupBridgeTCKSite(long companyId, long userId) throws Exception, DocumentException {
    Group site = getSiteForSetup(companyId, userId, "Bridge TCK");
    long groupId = site.getGroupId();
    addAllUsersToSite(companyId, groupId);

    URL configFileURL = getClass().getClassLoader().getResource("pluto-portal-driver-config.xml");
    Document document = SAXReaderUtil.read(configFileURL);
    Element rootElement = document.getRootElement();
    Element renderConfigElement = rootElement.element("render-config");
    Iterator<Element> pageElementIterator = renderConfigElement.elementIterator("page");

    while (pageElementIterator.hasNext()) {
        Element pageElement = pageElementIterator.next();
        Attribute nameAttribute = pageElement.attribute("name");
        String pageName = nameAttribute.getValue();
        Element portletElement = pageElement.element("portlet");
        nameAttribute = portletElement.attribute("name");

        String portletName = nameAttribute.getValue();
        String liferayPortletName = portletName.replaceAll("-", "");
        String liferayPortletId = liferayPortletName + "_WAR_bridgetckmainportlet";
        PortalPage portalPage = new PortalPage(pageName, liferayPortletId);
        setupPrivatePage(companyId, userId, groupId, portalPage);
    }/* w  ww. j  a v a  2 s  . c o m*/

    setupPrivatePage(companyId, userId, groupId, new PortalPage("Lifecycle Set",
            "chapter3TestslifecycleTestportlet_WAR_bridgetcklifecyclesetportlet"));
    setupPrivatePage(companyId, userId, groupId, new PortalPage("Render Policy Always Delegate",
            "chapter3TestsrenderPolicyTestportlet_WAR_bridgetckrenderpolicy1portlet"));
    setupPrivatePage(companyId, userId, groupId, new PortalPage("Render Policy Default",
            "chapter3TestsrenderPolicyTestportlet_WAR_bridgetckrenderpolicy2portlet"));
    setupPrivatePage(companyId, userId, groupId, new PortalPage("Render Policy Never Delegate",
            "chapter3TestsrenderPolicyTestportlet_WAR_bridgetckrenderpolicy3portlet"));
    setupPrivatePage(companyId, userId, groupId, new PortalPage("Render Response Wrapper",
            "chapter6_2_1TestsusesConfiguredRenderResponseWrapperTestportlet_WAR_bridgetckresponsewrapperportlet"));
    setupPrivatePage(companyId, userId, groupId, new PortalPage("Resource Response Wrapper",
            "chapter6_2_1TestsusesConfiguredResourceResponseWrapperTestportlet_WAR_bridgetckresponsewrapperportlet"));
}