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.journal.model.impl.JournalArticleImpl.java

License:Open Source License

@Override
public Document getDocument() {
    if (_document == null) {
        try {/*from   www  . j a  v  a 2 s.com*/
            _document = SAXReaderUtil.read(getContent());
        } catch (DocumentException de) {
            if (_log.isWarnEnabled()) {
                _log.warn(de, de);
            }
        }
    }

    return _document;
}

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

License:Open Source License

protected Map<String, LocalizedValue> createFieldsValuesMap(String content) {

    try {//from   w  w w .  ja v  a 2 s . c  o  m
        Document document = SAXReaderUtil.read(content);

        Element rootElement = document.getRootElement();

        Locale defaultLocale = LocaleUtil.fromLanguageId(rootElement.attributeValue("default-locale"));

        return createFieldsValuesMap(rootElement, defaultLocale);
    } catch (DocumentException de) {
        throw new SystemException(de);
    }
}

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

License:Open Source License

protected String format(User user, long groupId, JournalArticle article, String content)
        throws PortalException {

    Document document = null;/*ww  w. ja  va2 s  .  com*/

    try {
        document = SAXReaderUtil.read(content);

        Element rootElement = document.getRootElement();

        format(user, groupId, article, rootElement);

        content = XMLUtil.formatXML(document);
    } catch (DocumentException de) {
        _log.error(de, de);
    }

    return content;
}

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

License:Open Source License

protected void validateContent(String content) throws PortalException {
    if (Validator.isNull(content)) {
        throw new ArticleContentException("Content is null");
    }//  w ww . j a v a 2 s .  c  o  m

    try {
        SAXReaderUtil.read(content);
    } catch (DocumentException de) {
        if (_log.isDebugEnabled()) {
            _log.debug("Invalid content:\n" + content);
        }

        throw new ArticleContentException("Unable to read content with an XML parser", de);
    }
}

From source file:com.liferay.journal.transformer.ContentTransformerListener.java

License:Open Source License

/**
 * Fill one article with content from another approved article. See the
 * article DOCUMENTATION-INSTALLATION-BORLAND for a sample use case.
 *
 * @return the processed string/*from www  . j a v  a  2  s .c  om*/
 */
protected String replace(String xml, Map<String, String> tokens) {
    try {
        Document document = SAXReaderUtil.read(xml);

        replace(document, tokens);

        xml = XMLUtil.formatXML(document);
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(e.getMessage());
        }
    }

    return xml;
}

From source file:com.liferay.journal.transformer.JournalTransformer.java

License:Open Source License

protected String doTransform(ThemeDisplay themeDisplay, Map<String, Object> contextObjects,
        Map<String, String> tokens, String viewMode, String languageId, Document document,
        PortletRequestModel portletRequestModel, String script, String langType, boolean propagateException)
        throws Exception {

    // Setup listeners

    if (_log.isDebugEnabled()) {
        _log.debug("Language " + languageId);
    }//from w w w  .  j a va2  s .  c om

    if (Validator.isNull(viewMode)) {
        viewMode = Constants.VIEW;
    }

    if (_logTokens.isDebugEnabled()) {
        String tokensString = PropertiesUtil.list(tokens);

        _logTokens.debug(tokensString);
    }

    if (_logTransformBefore.isDebugEnabled()) {
        _logTransformBefore.debug(document);
    }

    List<TransformerListener> transformerListeners = JournalTransformerListenerRegistryUtil
            .getTransformerListeners();

    for (TransformerListener transformerListener : transformerListeners) {

        // Modify XML

        if (_logXmlBeforeListener.isDebugEnabled()) {
            _logXmlBeforeListener.debug(document);
        }

        if (transformerListener != null) {
            document = transformerListener.onXml(document, languageId, tokens);

            if (_logXmlAfterListener.isDebugEnabled()) {
                _logXmlAfterListener.debug(document);
            }
        }

        // Modify script

        if (_logScriptBeforeListener.isDebugEnabled()) {
            _logScriptBeforeListener.debug(script);
        }

        if (transformerListener != null) {
            script = transformerListener.onScript(script, document, languageId, tokens);

            if (_logScriptAfterListener.isDebugEnabled()) {
                _logScriptAfterListener.debug(script);
            }
        }
    }

    // Transform

    String output = null;

    if (Validator.isNull(langType)) {
        output = LocalizationUtil.getLocalization(document.asXML(), languageId);
    } else {
        long companyId = 0;
        long companyGroupId = 0;
        long articleGroupId = 0;
        long classNameId = 0;

        if (tokens != null) {
            companyId = GetterUtil.getLong(tokens.get("company_id"));
            companyGroupId = GetterUtil.getLong(tokens.get("company_group_id"));
            articleGroupId = GetterUtil.getLong(tokens.get("article_group_id"));
            classNameId = GetterUtil.getLong(tokens.get(TemplateConstants.CLASS_NAME_ID));
        }

        long scopeGroupId = 0;
        long siteGroupId = 0;

        if (themeDisplay != null) {
            companyId = themeDisplay.getCompanyId();
            companyGroupId = themeDisplay.getCompanyGroupId();
            scopeGroupId = themeDisplay.getScopeGroupId();
            siteGroupId = themeDisplay.getSiteGroupId();
        }

        String templateId = tokens.get("template_id");

        templateId = getTemplateId(templateId, companyId, companyGroupId, articleGroupId);

        Template template = getTemplate(templateId, tokens, languageId, document, script, langType);

        if (contextObjects != null) {
            template.putAll(contextObjects);
        }

        UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();

        try {
            if (document != null) {
                Element rootElement = document.getRootElement();

                List<TemplateNode> templateNodes = getTemplateNodes(themeDisplay, rootElement,
                        Long.valueOf(tokens.get("ddm_structure_id")));

                if (templateNodes != null) {
                    for (TemplateNode templateNode : templateNodes) {
                        template.put(templateNode.getName(), templateNode);
                    }
                }

                if (portletRequestModel != null) {
                    template.put("request", portletRequestModel.toMap());

                    if (langType.equals(TemplateConstants.LANG_TYPE_XSL)) {
                        Document requestDocument = SAXReaderUtil.read(portletRequestModel.toXML());

                        Element requestElement = requestDocument.getRootElement();

                        template.put("xmlRequest", requestElement.asXML());
                    }
                } else {
                    Element requestElement = rootElement.element("request");

                    template.put("request", insertRequestVariables(requestElement));

                    if (langType.equals(TemplateConstants.LANG_TYPE_XSL)) {
                        template.put("xmlRequest", requestElement.asXML());
                    }
                }
            }

            template.put("articleGroupId", articleGroupId);
            template.put("company", getCompany(themeDisplay, companyId));
            template.put("companyId", companyId);
            template.put("device", getDevice(themeDisplay));

            String templatesPath = getTemplatesPath(companyId, articleGroupId, classNameId);

            Locale locale = LocaleUtil.fromLanguageId(languageId);

            template.put("locale", locale);

            template.put("permissionChecker", PermissionThreadLocal.getPermissionChecker());
            template.put("randomNamespace", StringUtil.randomId() + StringPool.UNDERLINE);
            template.put("scopeGroupId", scopeGroupId);
            template.put("siteGroupId", siteGroupId);
            template.put("templatesPath", templatesPath);
            template.put("viewMode", viewMode);

            if (themeDisplay != null) {
                TemplateManager templateManager = TemplateManagerUtil.getTemplateManager(langType);

                HttpServletRequest request = themeDisplay.getRequest();

                templateManager.addTaglibSupport(template, request, themeDisplay.getResponse());
                templateManager.addTaglibTheme(template, "taglibLiferay", request,
                        new PipingServletResponse(themeDisplay.getResponse(), unsyncStringWriter));
            }

            // Deprecated variables

            template.put("groupId", articleGroupId);
            template.put("journalTemplatesPath", templatesPath);

            mergeTemplate(template, unsyncStringWriter, propagateException);
        } catch (Exception e) {
            if (e instanceof DocumentException) {
                throw new TransformException("Unable to read XML document", e);
            } else if (e instanceof IOException) {
                throw new TransformException("Error reading template", e);
            } else if (e instanceof TransformException) {
                throw (TransformException) e;
            } else {
                throw new TransformException("Unhandled exception", e);
            }
        }

        output = unsyncStringWriter.toString();
    }

    // Postprocess output

    for (TransformerListener transformerListener : transformerListeners) {

        // Modify output

        if (_logOutputBeforeListener.isDebugEnabled()) {
            _logOutputBeforeListener.debug(output);
        }

        output = transformerListener.onOutput(output, languageId, tokens);

        if (_logOutputAfterListener.isDebugEnabled()) {
            _logOutputAfterListener.debug(output);
        }
    }

    if (_logTransfromAfter.isDebugEnabled()) {
        _logTransfromAfter.debug(output);
    }

    return output;
}

From source file:com.liferay.journal.trash.test.JournalArticleTrashHandlerTest.java

License:Open Source License

@Test
public void testArticleImages() throws Exception {
    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(group.getGroupId());

    Class<?> clazz = getClass();

    ClassLoader classLoader = clazz.getClassLoader();

    String definition = StringUtil.read(classLoader,
            "com/liferay/journal/dependencies" + "/test-ddm-structure-image-field.xml");

    DDMForm ddmForm = _ddmFormXSDDeserializer.deserialize(definition);

    DDMStructure ddmStructure = DDMStructureTestUtil.addStructure(serviceContext.getScopeGroupId(),
            JournalArticle.class.getName(), ddmForm);

    DDMTemplate ddmTemplate = DDMTemplateTestUtil.addTemplate(serviceContext.getScopeGroupId(),
            ddmStructure.getStructureId(), PortalUtil.getClassNameId(JournalArticle.class));

    InputStream inputStream = classLoader.getResourceAsStream("/com/liferay/journal/dependencies/liferay.png");

    FileEntry tempFileEntry = TempFileEntryUtil.addTempFileEntry(group.getGroupId(),
            TestPropsValues.getUserId(), JournalArticle.class.getName(), "liferay.png", inputStream,
            ContentTypes.IMAGE_PNG);/*from  w  w w  . j a  v  a2  s .  co  m*/

    String content = StringUtil.read(classLoader,
            "com/liferay/journal/dependencies/test-journal-content-image-" + "field.xml");

    Document document = SAXReaderUtil.read(content);

    Element dynamicContent = (Element) document.selectSingleNode("//dynamic-content");

    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

    jsonObject.put("groupId", group.getGroupId());
    jsonObject.put("name", "liferay.png");
    jsonObject.put("tempFile", Boolean.TRUE.toString());
    jsonObject.put("title", "liferay.png");
    jsonObject.put("type", "journal");
    jsonObject.put("uuid", tempFileEntry.getUuid());

    dynamicContent.setText(jsonObject.toString());

    baseModel = JournalTestUtil.addArticleWithXMLContent(JournalFolderConstants.DEFAULT_PARENT_FOLDER_ID,
            document.asXML(), ddmStructure.getStructureKey(), ddmTemplate.getTemplateKey(), serviceContext);

    JournalArticle article = (JournalArticle) baseModel;

    long folderId = article.getImagesFolderId();

    Assert.assertEquals(1, PortletFileRepositoryUtil.getPortletFileEntriesCount(group.getGroupId(), folderId));

    moveBaseModelToTrash((Long) baseModel.getPrimaryKeyObj());

    Assert.assertEquals(0, PortletFileRepositoryUtil.getPortletFileEntriesCount(group.getGroupId(), folderId,
            WorkflowConstants.STATUS_APPROVED));
    Assert.assertEquals(1, PortletFileRepositoryUtil.getPortletFileEntriesCount(group.getGroupId(), folderId,
            WorkflowConstants.STATUS_IN_TRASH));

    TrashHandler trashHandler = TrashHandlerRegistryUtil.getTrashHandler(getBaseModelClassName());

    trashHandler.deleteTrashEntry(getTrashEntryClassPK(baseModel));

    Assert.assertEquals(0, PortletFileRepositoryUtil.getPortletFileEntriesCount(group.getGroupId(), folderId));
}

From source file:com.liferay.journal.util.impl.JournalUtil.java

License:Open Source License

public static String mergeArticleContent(String curContent, String newContent, boolean removeNullElements) {

    try {/*from   w  w w.ja v  a 2s.  c  om*/
        Document curDocument = SAXReaderUtil.read(curContent);
        Document newDocument = SAXReaderUtil.read(newContent);

        Element curRootElement = curDocument.getRootElement();
        Element newRootElement = newDocument.getRootElement();

        curRootElement.addAttribute("default-locale", newRootElement.attributeValue("default-locale"));
        curRootElement.addAttribute("available-locales", newRootElement.attributeValue("available-locales"));

        _mergeArticleContentUpdate(curDocument, newRootElement,
                LocaleUtil.toLanguageId(LocaleUtil.getSiteDefault()));

        if (removeNullElements) {
            _mergeArticleContentDelete(curRootElement, newDocument);
        }

        curContent = XMLUtil.formatXML(curDocument);
    } catch (Exception e) {
        _log.error(e, e);
    }

    return curContent;
}

From source file:com.liferay.journal.util.impl.JournalUtil.java

License:Open Source License

public static String prepareLocalizedContentForImport(String content, Locale defaultImportLocale)
        throws LocaleException {

    try {/*from www. j av a2 s .  co m*/
        Document oldDocument = SAXReaderUtil.read(content);

        Document newDocument = SAXReaderUtil.read(content);

        Element newRootElement = newDocument.getRootElement();

        Attribute availableLocalesAttribute = newRootElement.attribute("available-locales");

        if (availableLocalesAttribute == null) {
            newRootElement = newRootElement.addAttribute("available-locales", StringPool.BLANK);

            availableLocalesAttribute = newRootElement.attribute("available-locales");
        }

        String defaultImportLanguageId = LocaleUtil.toLanguageId(defaultImportLocale);

        if (!StringUtil.contains(availableLocalesAttribute.getValue(), defaultImportLanguageId)) {

            if (Validator.isNull(availableLocalesAttribute.getValue())) {
                availableLocalesAttribute.setValue(defaultImportLanguageId);
            } else {
                availableLocalesAttribute.setValue(
                        availableLocalesAttribute.getValue() + StringPool.COMMA + defaultImportLanguageId);
            }

            _mergeArticleContentUpdate(oldDocument, newRootElement,
                    LocaleUtil.toLanguageId(defaultImportLocale));

            content = XMLUtil.formatXML(newDocument);
        }

        Attribute defaultLocaleAttribute = newRootElement.attribute("default-locale");

        if (defaultLocaleAttribute == null) {
            newRootElement = newRootElement.addAttribute("default-locale", StringPool.BLANK);

            defaultLocaleAttribute = newRootElement.attribute("default-locale");
        }

        Locale defaultContentLocale = LocaleUtil.fromLanguageId(defaultLocaleAttribute.getValue());

        if (!LocaleUtil.equals(defaultContentLocale, defaultImportLocale)) {
            defaultLocaleAttribute.setValue(defaultImportLanguageId);

            content = XMLUtil.formatXML(newDocument);
        }
    } catch (Exception e) {
        throw new LocaleException(LocaleException.TYPE_CONTENT,
                "The locale " + defaultImportLocale + " is not available");
    }

    return content;
}

From source file:com.liferay.journal.util.impl.JournalUtil.java

License:Open Source License

public static String removeOldContent(String content, String xsd) {
    try {//from w  ww.j  a v  a2s.  c o m
        Document contentDoc = SAXReaderUtil.read(content);
        Document xsdDoc = SAXReaderUtil.read(xsd);

        Element contentRoot = contentDoc.getRootElement();

        Stack<String> path = new Stack<>();

        path.push(contentRoot.getName());

        _removeOldContent(path, contentRoot, xsdDoc);

        content = XMLUtil.formatXML(contentDoc);
    } catch (Exception e) {
        _log.error(e, e);
    }

    return content;
}