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

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

Introduction

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

Prototype

public static XPath createXPath(String xPathExpression) 

Source Link

Usage

From source file:com.liferay.journal.internal.exportimport.content.processor.JournalArticleExportImportContentProcessor.java

License:Open Source License

protected String replaceExportJournalArticleReferences(PortletDataContext portletDataContext,
        StagedModel stagedModel, String content, boolean exportReferencedContent) throws Exception {

    Group group = _groupLocalService.fetchGroup(portletDataContext.getGroupId());

    if (group.isStagingGroup()) {
        group = group.getLiveGroup();//  w  w  w  .  j a  v  a  2  s.c o  m
    }

    if (group.isStaged() && !group.isStagedRemotely() && !group.isStagedPortlet(JournalPortletKeys.JOURNAL)) {

        return content;
    }

    Document document = SAXReaderUtil.read(content);

    XPath xPath = SAXReaderUtil.createXPath("//dynamic-element[@type='ddm-journal-article']");

    List<Node> ddmJournalArticleNodes = xPath.selectNodes(document);

    for (Node ddmJournalArticleNode : ddmJournalArticleNodes) {
        Element ddmJournalArticleElement = (Element) ddmJournalArticleNode;

        List<Element> dynamicContentElements = ddmJournalArticleElement.elements("dynamic-content");

        for (Element dynamicContentElement : dynamicContentElements) {
            String jsonData = dynamicContentElement.getStringValue();

            JSONObject jsonObject = _jsonFactory.createJSONObject(jsonData);

            long classPK = GetterUtil.getLong(jsonObject.get("classPK"));

            JournalArticle journalArticle = _journalArticleLocalService.fetchLatestArticle(classPK);

            if (journalArticle == null) {
                if (_log.isInfoEnabled()) {
                    StringBundler messageSB = new StringBundler();

                    messageSB.append("Staged model with class name ");
                    messageSB.append(stagedModel.getModelClassName());
                    messageSB.append(" and primary key ");
                    messageSB.append(stagedModel.getPrimaryKeyObj());
                    messageSB.append(" references missing journal ");
                    messageSB.append("article with class primary key ");
                    messageSB.append(classPK);

                    _log.info(messageSB.toString());
                }

                continue;
            }

            String journalArticleReference = "[$journal-article-reference=" + journalArticle.getPrimaryKey()
                    + "$]";

            if (_log.isDebugEnabled()) {
                _log.debug("Replacing " + jsonData + " with " + journalArticleReference);
            }

            dynamicContentElement.clearContent();

            dynamicContentElement.addCDATA(journalArticleReference);

            if (exportReferencedContent) {
                StagedModelDataHandlerUtil.exportReferenceStagedModel(portletDataContext, stagedModel,
                        journalArticle, PortletDataContext.REFERENCE_TYPE_DEPENDENCY);
            } else {
                Element entityElement = portletDataContext.getExportDataElement(stagedModel);

                portletDataContext.addReferenceElement(stagedModel, entityElement, journalArticle,
                        PortletDataContext.REFERENCE_TYPE_DEPENDENCY, true);
            }
        }
    }

    return document.asXML();
}

From source file:com.liferay.journal.internal.exportimport.content.processor.JournalArticleExportImportContentProcessor.java

License:Open Source License

protected void validateJournalArticleReferences(String content) throws PortalException {

    List<Throwable> throwables = new ArrayList<>();

    try {/*from   www . j  a v  a2 s.c o m*/
        Document document = SAXReaderUtil.read(content);

        XPath xPath = SAXReaderUtil.createXPath("//dynamic-element[@type='ddm-journal-article']");

        List<Node> ddmJournalArticleNodes = xPath.selectNodes(document);

        for (Node ddmJournalArticleNode : ddmJournalArticleNodes) {
            Element ddmJournalArticleElement = (Element) ddmJournalArticleNode;

            List<Element> dynamicContentElements = ddmJournalArticleElement.elements("dynamic-content");

            for (Element dynamicContentElement : dynamicContentElements) {
                String json = dynamicContentElement.getStringValue();

                if (Validator.isNull(json)) {
                    if (_log.isDebugEnabled()) {
                        _log.debug("No journal article reference is specified");
                    }

                    continue;
                }

                JSONObject jsonObject = _jsonFactory.createJSONObject(json);

                long classPK = GetterUtil.getLong(jsonObject.get("classPK"));

                JournalArticle journalArticle = _journalArticleLocalService.fetchLatestArticle(classPK);

                if (journalArticle == null) {
                    Throwable throwable = new NoSuchArticleException(
                            "No JournalArticle exists with the key " + "{resourcePrimKey=" + classPK + "}");

                    throwables.add(throwable);
                }
            }
        }
    } catch (DocumentException de) {
        if (_log.isDebugEnabled()) {
            _log.debug("Invalid content:\n" + content);
        }
    }

    if (!throwables.isEmpty()) {
        throw new PortalException(
                new BulkException("Unable to validate journal article references", throwables));
    }
}

From source file:com.liferay.journal.internal.upgrade.v0_0_6.UpgradeImageTypeContentAttributes.java

License:Open Source License

protected String addImageContentAttributes(String content) throws Exception {

    Document contentDocument = SAXReaderUtil.read(content);

    contentDocument = contentDocument.clone();

    XPath xPath = SAXReaderUtil.createXPath("//dynamic-element[@type='image']");

    List<Node> imageNodes = xPath.selectNodes(contentDocument);

    for (Node imageNode : imageNodes) {
        Element imageEl = (Element) imageNode;

        List<Element> dynamicContentEls = imageEl.elements("dynamic-content");

        String id = null;/*from ww w  .ja v a  2  s.  c  om*/

        for (Element dynamicContentEl : dynamicContentEls) {
            id = dynamicContentEl.attributeValue("id");

            dynamicContentEl.addAttribute("alt", StringPool.BLANK);
            dynamicContentEl.addAttribute("name", id);
            dynamicContentEl.addAttribute("title", id);
            dynamicContentEl.addAttribute("type", "journal");
        }

        if (Validator.isNotNull(id)) {
            imageEl.addAttribute("instance-id", getImageInstanceId(id));
        }
    }

    return contentDocument.formattedString();
}

From source file:com.liferay.journal.internal.upgrade.v1_0_0.UpgradeImageTypeContentAttributes.java

License:Open Source License

protected String addImageContentAttributes(String content) throws Exception {

    Document contentDocument = SAXReaderUtil.read(content);

    contentDocument = contentDocument.clone();

    XPath xPath = SAXReaderUtil.createXPath("//dynamic-element[@type='image']");

    List<Node> imageNodes = xPath.selectNodes(contentDocument);

    for (Node imageNode : imageNodes) {
        Element imageEl = (Element) imageNode;

        List<Element> dynamicContentEls = imageEl.elements("dynamic-content");

        for (Element dynamicContentEl : dynamicContentEls) {
            String id = dynamicContentEl.attributeValue("id");

            dynamicContentEl.addAttribute("alt", StringPool.BLANK);
            dynamicContentEl.addAttribute("name", id);
            dynamicContentEl.addAttribute("title", id);
            dynamicContentEl.addAttribute("type", "journal");
        }//from   w  w w  . j  a va  2  s  .c o  m
    }

    return contentDocument.formattedString();
}

From source file:com.liferay.journal.internal.upgrade.v1_1_0.UpgradeDocumentLibraryTypeContent.java

License:Open Source License

protected String convertContent(String content) throws Exception {
    Document contentDocument = SAXReaderUtil.read(content);

    contentDocument = contentDocument.clone();

    XPath xPath = SAXReaderUtil.createXPath("//dynamic-element[@type='document_library']");

    List<Node> imageNodes = xPath.selectNodes(contentDocument);

    for (Node imageNode : imageNodes) {
        Element imageEl = (Element) imageNode;

        List<Element> dynamicContentEls = imageEl.elements("dynamic-content");

        for (Element dynamicContentEl : dynamicContentEls) {
            String data = getDocumentLibraryValue(dynamicContentEl.getText());

            dynamicContentEl.clearContent();

            dynamicContentEl.addCDATA(data);
        }/*from  w  ww. j a v a  2 s  .  c  o  m*/
    }

    return contentDocument.formattedString();
}

From source file:com.liferay.journal.internal.upgrade.v1_1_0.UpgradeImageTypeContent.java

License:Open Source License

protected String convertTypeImageElements(long userId, long groupId, String content, long resourcePrimKey)
        throws Exception {

    Document contentDocument = SAXReaderUtil.read(content);

    contentDocument = contentDocument.clone();

    XPath xPath = SAXReaderUtil.createXPath("//dynamic-element[@type='image']");

    List<Node> imageNodes = xPath.selectNodes(contentDocument);

    for (Node imageNode : imageNodes) {
        Element imageEl = (Element) imageNode;

        List<Element> dynamicContentEls = imageEl.elements("dynamic-content");

        for (Element dynamicContentEl : dynamicContentEls) {
            String id = dynamicContentEl.attributeValue("id");

            if (Validator.isNull(id)) {
                continue;
            }//from w  ww .  j  a  va 2 s.  c  o m

            long folderId = getFolderId(userId, groupId, resourcePrimKey);

            FileEntry fileEntry = getFileEntry(groupId, folderId, id);

            if (fileEntry == null) {
                continue;
            }

            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

            jsonObject.put("alt", StringPool.BLANK);
            jsonObject.put("groupId", fileEntry.getGroupId());
            jsonObject.put("name", fileEntry.getFileName());
            jsonObject.put("resourcePrimKey", resourcePrimKey);
            jsonObject.put("title", fileEntry.getTitle());
            jsonObject.put("type", "journal");
            jsonObject.put("uuid", fileEntry.getUuid());

            dynamicContentEl.clearContent();

            dynamicContentEl.addCDATA(jsonObject.toString());
        }
    }

    return contentDocument.formattedString();
}

From source file:com.liferay.journal.internal.util.impl.JournalConverterImpl.java

License:Open Source License

protected Element fetchMetadataEntry(Element parentElement, String attributeName, String attributeValue) {

    StringBundler sb = new StringBundler(5);

    sb.append("entry[@");
    sb.append(attributeName);/*www. j  a va  2  s.  c  om*/
    sb.append(StringPool.EQUAL);
    sb.append(HtmlUtil.escapeXPathAttribute(attributeValue));
    sb.append(StringPool.CLOSE_BRACKET);

    XPath xPathSelector = SAXReaderUtil.createXPath(sb.toString());

    return (Element) xPathSelector.selectSingleNode(parentElement);
}

From source file:com.liferay.journal.service.impl.JournalArticleLocalServiceImpl.java

License:Open Source License

protected void copyArticleImages(JournalArticle oldArticle, JournalArticle newArticle) throws Exception {

    Folder folder = newArticle.addImagesFolder();

    for (FileEntry fileEntry : oldArticle.getImagesFileEntries()) {
        PortletFileRepositoryUtil.addPortletFileEntry(oldArticle.getGroupId(), newArticle.getUserId(),
                JournalArticle.class.getName(), newArticle.getResourcePrimKey(), JournalConstants.SERVICE_NAME,
                folder.getFolderId(), fileEntry.getContentStream(), fileEntry.getFileName(),
                fileEntry.getMimeType(), false);
    }//from   w w w  . j  a  v  a 2  s. c om

    Document contentDocument = oldArticle.getDocument();

    contentDocument = contentDocument.clone();

    XPath xPathSelector = SAXReaderUtil.createXPath("//dynamic-element[@type='image']");

    List<Node> imageNodes = xPathSelector.selectNodes(contentDocument);

    for (Node imageNode : imageNodes) {
        Element imageEl = (Element) imageNode;

        List<Element> dynamicContentEls = imageEl.elements("dynamic-content");

        for (Element dynamicContentEl : dynamicContentEls) {
            String fileName = dynamicContentEl.attributeValue("name");

            FileEntry fileEntry = PortletFileRepositoryUtil.getPortletFileEntry(newArticle.getGroupId(),
                    folder.getFolderId(), fileName);

            String previewURL = DLUtil.getPreviewURL(fileEntry, fileEntry.getFileVersion(), null,
                    StringPool.BLANK, false, true);

            dynamicContentEl.addAttribute("resourcePrimKey", String.valueOf(newArticle.getResourcePrimKey()));

            dynamicContentEl.clearContent();

            dynamicContentEl.addCDATA(previewURL);
        }
    }

    newArticle.setContent(contentDocument.formattedString());
}

From source file:com.liferay.journal.service.impl.JournalArticleLocalServiceImpl.java

License:Open Source License

protected JournalArticleDisplay getArticleDisplay(JournalArticle article, String ddmTemplateKey,
        String viewMode, String languageId, int page, PortletRequestModel portletRequestModel,
        ThemeDisplay themeDisplay, boolean propagateException) throws PortalException {

    String content = null;/*from w w  w  .  jav  a2s  .  c o m*/

    if (page < 1) {
        page = 1;
    }

    int numberOfPages = 1;
    boolean paginate = false;
    boolean pageFlow = false;

    boolean cacheable = true;

    Map<String, String> tokens = JournalUtil.getTokens(article.getGroupId(), portletRequestModel, themeDisplay);

    if ((themeDisplay == null) && (portletRequestModel == null)) {
        tokens.put("company_id", String.valueOf(article.getCompanyId()));

        Group companyGroup = groupLocalService.getCompanyGroup(article.getCompanyId());

        tokens.put("article_group_id", String.valueOf(article.getGroupId()));
        tokens.put("company_group_id", String.valueOf(companyGroup.getGroupId()));

        // Deprecated tokens

        tokens.put("group_id", String.valueOf(article.getGroupId()));
    }

    tokens.put(TemplateConstants.CLASS_NAME_ID,
            String.valueOf(classNameLocalService.getClassNameId(DDMStructure.class)));
    tokens.put("article_resource_pk", String.valueOf(article.getResourcePrimKey()));

    DDMStructure ddmStructure = article.getDDMStructure();

    tokens.put("ddm_structure_key", String.valueOf(ddmStructure.getStructureKey()));
    tokens.put("ddm_structure_id", String.valueOf(ddmStructure.getStructureId()));

    // Deprecated token

    tokens.put("structure_id", article.getDDMStructureKey());

    String defaultDDMTemplateKey = article.getDDMTemplateKey();

    if (Validator.isNull(ddmTemplateKey)) {
        ddmTemplateKey = defaultDDMTemplateKey;
    }

    Document document = article.getDocument();

    document = document.clone();

    Element rootElement = document.getRootElement();

    List<Element> pages = rootElement.elements("page");

    if (!pages.isEmpty()) {
        pageFlow = true;

        String targetPage = null;

        Map<String, String[]> parameters = portletRequestModel.getParameters();

        if (parameters != null) {
            String[] values = parameters.get("targetPage");

            if ((values != null) && (values.length > 0)) {
                targetPage = values[0];
            }
        }

        Element pageElement = null;

        if (Validator.isNotNull(targetPage)) {
            targetPage = HtmlUtil.escapeXPathAttribute(targetPage);

            XPath xPathSelector = SAXReaderUtil.createXPath("/root/page[@id = " + targetPage + "]");

            pageElement = (Element) xPathSelector.selectSingleNode(document);
        }

        if (pageElement != null) {
            document = SAXReaderUtil.createDocument(pageElement);

            rootElement = document.getRootElement();

            numberOfPages = pages.size();
        } else {
            if (page > pages.size()) {
                page = 1;
            }

            pageElement = pages.get(page - 1);

            document = SAXReaderUtil.createDocument(pageElement);

            rootElement = document.getRootElement();

            numberOfPages = pages.size();
            paginate = true;
        }
    }

    JournalUtil.addAllReservedEls(rootElement, tokens, article, languageId, themeDisplay);

    try {
        if (_log.isDebugEnabled()) {
            _log.debug(
                    "Transforming " + article.getArticleId() + " " + article.getVersion() + " " + languageId);
        }

        // Try with specified template first (in the current group and the
        // global group). If a template is not specified, use the default
        // one. If the specified template does not exist, use the default
        // one. If the default one does not exist, throw an exception.

        DDMTemplate ddmTemplate = null;

        try {
            ddmTemplate = ddmTemplateLocalService.getTemplate(PortalUtil.getSiteGroupId(article.getGroupId()),
                    classNameLocalService.getClassNameId(DDMStructure.class), ddmTemplateKey, true);

            Group companyGroup = groupLocalService.getCompanyGroup(article.getCompanyId());

            if (companyGroup.getGroupId() == ddmTemplate.getGroupId()) {
                tokens.put("company_group_id", String.valueOf(companyGroup.getGroupId()));
            }
        } catch (NoSuchTemplateException nste) {
            if (!defaultDDMTemplateKey.equals(ddmTemplateKey)) {
                ddmTemplate = ddmTemplateLocalService.getTemplate(
                        PortalUtil.getSiteGroupId(article.getGroupId()),
                        classNameLocalService.getClassNameId(DDMStructure.class), defaultDDMTemplateKey);
            } else {
                throw nste;
            }
        }

        tokens.put("ddm_template_key", String.valueOf(ddmTemplate.getTemplateKey()));
        tokens.put("ddm_template_id", String.valueOf(ddmTemplate.getTemplateId()));

        // Deprecated token

        tokens.put("template_id", ddmTemplateKey);

        String script = ddmTemplate.getScript();
        String langType = ddmTemplate.getLanguage();
        cacheable = ddmTemplate.isCacheable();

        content = JournalUtil.transform(themeDisplay, tokens, viewMode, languageId, document,
                portletRequestModel, script, langType, propagateException);

        if (!pageFlow) {
            JournalServiceConfiguration journalServiceConfiguration = configurationProvider
                    .getCompanyConfiguration(JournalServiceConfiguration.class, article.getCompanyId());

            String[] pieces = StringUtil.split(content,
                    journalServiceConfiguration.journalArticlePageBreakToken());

            if (pieces.length > 1) {
                if (page > pieces.length) {
                    page = 1;
                }

                content = pieces[page - 1];
                numberOfPages = pieces.length;
                paginate = true;
            }
        }
    } catch (Exception e) {
        throw new SystemException(e);
    }

    return new JournalArticleDisplayImpl(article.getCompanyId(), article.getId(), article.getResourcePrimKey(),
            article.getGroupId(), article.getUserId(), article.getArticleId(), article.getVersion(),
            article.getTitle(languageId), article.getUrlTitle(), article.getDescription(languageId),
            article.getAvailableLanguageIds(), content, article.getDDMStructureKey(), ddmTemplateKey,
            article.isSmallImage(), article.getSmallImageId(), article.getSmallImageURL(), numberOfPages, page,
            paginate, cacheable);
}

From source file:com.liferay.journal.test.util.JournalTestUtil.java

License:Open Source License

public static Map<String, Map<String, String>> getXsdMap(String xsd) throws Exception {

    Map<String, Map<String, String>> map = new HashMap<>();

    Document document = UnsecureSAXReaderUtil.read(xsd);

    XPath xPathSelector = SAXReaderUtil.createXPath("//dynamic-element");

    List<Node> nodes = xPathSelector.selectNodes(document);

    for (Node node : nodes) {
        Element dynamicElementElement = (Element) node;

        String type = dynamicElementElement.attributeValue("type");

        if (Objects.equals(type, "selection_break")) {
            continue;
        }/* www . j a v  a 2s  .  co m*/

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

        map.put(name, _getMap(dynamicElementElement));
    }

    return map;
}