Example usage for com.liferay.portal.kernel.xml Element attributeValue

List of usage examples for com.liferay.portal.kernel.xml Element attributeValue

Introduction

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

Prototype

public String attributeValue(String name);

Source Link

Usage

From source file:com.liferay.portlet.dynamicdatamapping.model.impl.DDMStructureImpl.java

License:Open Source License

public String getDefaultLocale() {
    Document document = getDocument();

    if (document == null) {
        Locale locale = LocaleUtil.getDefault();

        return locale.toString();
    }//from  www. j  a v a  2s.c  o  m

    Element rootElement = document.getRootElement();

    return rootElement.attributeValue("default-locale");
}

From source file:com.liferay.portlet.dynamicdatamapping.model.impl.DDMStructureImpl.java

License:Open Source License

private Map<String, String> _getField(Element element, String locale) {
    Map<String, String> field = new HashMap<String, String>();

    List<String> availableLocales = getAvailableLocales();

    if ((locale != null) && !(availableLocales.contains(locale))) {
        locale = getDefaultLocale();/*from   w ww . j  a  va2s.co m*/
    }

    String xPathExpression = "meta-data[@locale=\"".concat(locale).concat("\"]");

    XPath xPathSelector = SAXReaderUtil.createXPath(xPathExpression);

    Node node = xPathSelector.selectSingleNode(element);

    Element metaDataElement = (Element) node.asXPathResult(node.getParent());

    if (metaDataElement != null) {
        List<Element> childMetaDataElements = metaDataElement.elements();

        for (Element childMetaDataElement : childMetaDataElements) {
            String name = childMetaDataElement.attributeValue("name");
            String value = childMetaDataElement.getText();

            field.put(name, value);
        }
    }

    for (Attribute attribute : element.attributes()) {
        field.put(attribute.getName(), attribute.getValue());
    }

    return field;
}

From source file:com.liferay.portlet.dynamicdatamapping.model.impl.DDMStructureImpl.java

License:Open Source License

private Map<String, Map<String, String>> _getFieldsMap(String locale) {
    if (_fieldsMap == null) {
        synchronized (this) {
            if (_fieldsMap == null) {
                _fieldsMap = new LinkedHashMap<String, Map<String, String>>();

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

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

                Iterator<Node> itr = nodes.iterator();

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

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

                    _fieldsMap.put(name, _getField(element, locale));
                }/*from   w  w w  . java  2 s  . com*/
            }
        }
    }

    return _fieldsMap;
}

From source file:com.liferay.portlet.dynamicdatamapping.service.impl.DDMStructureLocalServiceImpl.java

License:Open Source License

protected void appendNewStructureRequiredFields(DDMStructure structure, Document templateDocument) {

    String xsd = structure.getXsd();

    Document structureDocument = null;

    try {//from w  ww  .  jav a 2  s  .  co m
        structureDocument = SAXReaderUtil.read(xsd);
    } catch (DocumentException de) {
        if (_log.isWarnEnabled()) {
            _log.warn(de, de);
        }

        return;
    }

    Element templateElement = templateDocument.getRootElement();

    XPath structureXPath = SAXReaderUtil
            .createXPath("//dynamic-element[.//meta-data/entry[@name=\"required\"]=" + "\"true\"]");

    List<Node> nodes = structureXPath.selectNodes(structureDocument);

    Iterator<Node> itr = nodes.iterator();

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

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

        XPath templateXPath = SAXReaderUtil.createXPath("//dynamic-element[@name=\"" + name + "\"]");

        if (!templateXPath.booleanValueOf(templateDocument)) {
            templateElement.add(element.createCopy());
        }
    }
}

From source file:com.liferay.portlet.dynamicdatamapping.service.impl.DDMStructureLocalServiceImpl.java

License:Open Source License

protected void syncStructureTemplatesFields(DDMTemplate template, Element templateElement)
        throws PortalException, SystemException {

    DDMStructure structure = template.getStructure();

    List<Element> dynamicElementElements = templateElement.elements("dynamic-element");

    for (Element dynamicElementElement : dynamicElementElements) {
        String dataType = dynamicElementElement.attributeValue("dataType");
        String fieldName = dynamicElementElement.attributeValue("name");

        if (Validator.isNull(dataType)) {
            continue;
        }//  w  w w  .  ja  v  a2  s .  c  om

        if (!structure.hasField(fieldName)) {
            templateElement.remove(dynamicElementElement);

            continue;
        }

        String mode = template.getMode();

        if (mode.equals(DDMTemplateConstants.TEMPLATE_MODE_CREATE)) {
            boolean fieldRequired = structure.getFieldRequired(fieldName);

            List<Element> metadataElements = dynamicElementElement.elements("meta-data");

            for (Element metadataElement : metadataElements) {
                for (Element metadataEntryElement : metadataElement.elements()) {

                    String attributeName = metadataEntryElement.attributeValue("name");

                    if (fieldRequired && attributeName.equals("required")) {
                        metadataEntryElement.setText("true");
                    }
                }
            }
        }

        syncStructureTemplatesFields(template, dynamicElementElement);
    }
}

From source file:com.liferay.portlet.dynamicdatamapping.storage.XMLStorageAdapter.java

License:Open Source License

private List<Fields> _doQuery(long ddmStructureId, long[] classPKs, List<String> fieldNames,
        Condition condition, OrderByComparator orderByComparator) throws Exception {

    List<Fields> fieldsList = new ArrayList<Fields>();

    XPath conditionXPath = null;//  w ww.  ja v  a2s  .  co  m

    if (condition != null) {
        conditionXPath = _parseCondition(condition);
    }

    DDMStructure ddmStructure = DDMStructureLocalServiceUtil.getDDMStructure(ddmStructureId);

    for (long classPK : classPKs) {
        DDMContent ddmContent = DDMContentLocalServiceUtil.getContent(classPK);

        Document document = SAXReaderUtil.read(ddmContent.getXml());

        if ((conditionXPath != null) && !conditionXPath.booleanValueOf(document)) {

            continue;
        }

        Fields fields = new Fields();

        Element rootElement = document.getRootElement();

        List<Element> dynamicElementElements = rootElement.elements("dynamic-element");

        for (Element dynamicElementElement : dynamicElementElements) {
            String fieldName = dynamicElementElement.attributeValue("name");
            String fieldValue = dynamicElementElement.elementText("dynamic-content");

            if (!ddmStructure.hasField(fieldName)
                    || ((fieldNames != null) && !fieldNames.contains(fieldName))) {

                continue;
            }

            String fieldDataType = ddmStructure.getFieldDataType(fieldName);

            Serializable fieldValueSerializable = FieldConstants.getSerializable(fieldDataType, fieldValue);

            Field field = new Field(ddmStructureId, fieldName, fieldValueSerializable);

            fields.put(field);
        }

        fieldsList.add(fields);
    }

    if (orderByComparator != null) {
        Collections.sort(fieldsList, orderByComparator);
    }

    return fieldsList;
}

From source file:com.liferay.portlet.journal.action.RSSAction.java

License:Open Source License

protected String processContent(JournalFeed feed, JournalArticle article, String languageId,
        ThemeDisplay themeDisplay, SyndEntry syndEntry, SyndContent syndContent) throws Exception {

    String content = article.getDescription(languageId);

    String contentField = feed.getContentField();

    if (contentField.equals(JournalFeedConstants.RENDERED_WEB_CONTENT)) {
        String rendererTemplateId = article.getTemplateId();

        if (Validator.isNotNull(feed.getRendererTemplateId())) {
            rendererTemplateId = feed.getRendererTemplateId();
        }/*from w  w  w .j  a va  2s  .  c  o m*/

        JournalArticleDisplay articleDisplay = JournalContentUtil.getDisplay(feed.getGroupId(),
                article.getArticleId(), rendererTemplateId, null, languageId, themeDisplay, 1, _XML_REQUUEST);

        if (articleDisplay != null) {
            content = articleDisplay.getContent();
        }
    } else if (!contentField.equals(JournalFeedConstants.WEB_CONTENT_DESCRIPTION)) {

        Document document = SAXReaderUtil.read(article.getContentByLocale(languageId));

        XPath xPathSelector = SAXReaderUtil.createXPath("//dynamic-element[@name='" + contentField + "']");

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

        if (results.size() == 0) {
            return content;
        }

        Element element = (Element) results.get(0);

        String elType = element.attributeValue("type");

        if (elType.equals("document_library")) {
            String url = element.elementText("dynamic-content");

            url = processURL(feed, url, themeDisplay, syndEntry);
        } else if (elType.equals("image") || elType.equals("image_gallery")) {
            String url = element.elementText("dynamic-content");

            url = processURL(feed, url, themeDisplay, syndEntry);

            content = content + "<br /><br /><img alt='' src='" + themeDisplay.getURLPortal() + url + "' />";
        } else if (elType.equals("text_box")) {
            syndContent.setType("text");

            content = element.elementText("dynamic-content");
        } else {
            content = element.elementText("dynamic-content");
        }
    }

    return content;
}

From source file:com.liferay.portlet.journal.lar.JournalContentPortletDataHandlerImpl.java

License:Open Source License

@Override
protected PortletPreferences doImportData(PortletDataContext portletDataContext, String portletId,
        PortletPreferences portletPreferences, String data) throws Exception {

    portletDataContext.importPermissions("com.liferay.portlet.journal", portletDataContext.getSourceGroupId(),
            portletDataContext.getScopeGroupId());

    if (Validator.isNull(data)) {
        return null;
    }/*from  w  ww.  jav  a  2  s  . c  om*/

    long previousScopeGroupId = portletDataContext.getScopeGroupId();

    long importGroupId = GetterUtil.getLong(portletPreferences.getValue("groupId", null));

    if (importGroupId == portletDataContext.getSourceGroupId()) {
        portletDataContext.setScopeGroupId(portletDataContext.getGroupId());
    }

    Document document = SAXReaderUtil.read(data);

    Element rootElement = document.getRootElement();

    JournalPortletDataHandlerImpl.importReferencedData(portletDataContext, rootElement);

    Element structureElement = rootElement.element("structure");

    if (structureElement != null) {
        JournalPortletDataHandlerImpl.importStructure(portletDataContext, structureElement);
    }

    Element templateElement = rootElement.element("template");

    if (templateElement != null) {
        JournalPortletDataHandlerImpl.importTemplate(portletDataContext, templateElement);
    }

    Element articleElement = rootElement.element("article");

    if (articleElement != null) {
        JournalPortletDataHandlerImpl.importArticle(portletDataContext, articleElement);
    }

    String articleId = portletPreferences.getValue("articleId", null);

    if (Validator.isNotNull(articleId) && (articleElement != null)) {
        String importedArticleGroupId = articleElement.attributeValue("imported-article-group-id");

        if (Validator.isNull(importedArticleGroupId)) {
            importedArticleGroupId = String.valueOf(portletDataContext.getScopeGroupId());
        }

        portletPreferences.setValue("groupId", importedArticleGroupId);

        Map<String, String> articleIds = (Map<String, String>) portletDataContext
                .getNewPrimaryKeysMap(JournalArticle.class + ".articleId");

        articleId = MapUtil.getString(articleIds, articleId, articleId);

        portletPreferences.setValue("articleId", articleId);

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

        JournalContentSearchLocalServiceUtil.updateContentSearch(portletDataContext.getScopeGroupId(),
                layout.isPrivateLayout(), layout.getLayoutId(), portletId, articleId, true);
    } else {
        portletPreferences.setValue("groupId", StringPool.BLANK);
        portletPreferences.setValue("articleId", StringPool.BLANK);
    }

    String templateId = portletPreferences.getValue("templateId", null);

    if (Validator.isNotNull(templateId)) {
        Map<String, String> templateIds = (Map<String, String>) portletDataContext
                .getNewPrimaryKeysMap(JournalTemplate.class + ".templateId");

        templateId = MapUtil.getString(templateIds, templateId, templateId);

        portletPreferences.setValue("templateId", templateId);
    } else {
        portletPreferences.setValue("templateId", StringPool.BLANK);
    }

    portletDataContext.setScopeGroupId(previousScopeGroupId);

    return portletPreferences;
}

From source file:com.liferay.portlet.journal.lar.JournalPortletDataHandlerImpl.java

License:Open Source License

public static void importArticle(PortletDataContext portletDataContext, Element articleElement)
        throws Exception {

    String path = articleElement.attributeValue("path");

    if (!portletDataContext.isPathNotProcessed(path)) {
        return;// w w w  .j a v a2s  .co  m
    }

    JournalArticle article = (JournalArticle) portletDataContext.getZipEntryAsObject(path);

    prepareLanguagesForImport(article);

    long userId = portletDataContext.getUserId(article.getUserUuid());

    JournalCreationStrategy creationStrategy = JournalCreationStrategyFactory.getInstance();

    long authorId = creationStrategy.getAuthorUserId(portletDataContext, article);

    if (authorId != JournalCreationStrategy.USE_DEFAULT_USER_ID_STRATEGY) {
        userId = authorId;
    }

    User user = UserLocalServiceUtil.getUser(userId);

    String articleId = article.getArticleId();
    boolean autoArticleId = false;

    Map<String, String> articleIds = (Map<String, String>) portletDataContext
            .getNewPrimaryKeysMap(JournalArticle.class + ".articleId");

    String newArticleId = articleIds.get(articleId);

    // ======= Start of change ============
    if (Validator.isNotNull(newArticleId)) {

        // A sibling of a different version was already assigned a new
        // article id

        articleId = newArticleId;
    }
    // =======end of change================

    String content = article.getContent();

    content = importDLFileEntries(portletDataContext, articleElement, content);

    Group group = GroupLocalServiceUtil.getGroup(portletDataContext.getScopeGroupId());

    content = StringUtil.replace(content, "@data_handler_group_friendly_url@", group.getFriendlyURL());

    content = importLinksToLayout(portletDataContext, content);

    article.setContent(content);

    String newContent = creationStrategy.getTransformedContent(portletDataContext, article);

    if (!StringUtils.equals(JournalCreationStrategy.ARTICLE_CONTENT_UNCHANGED, newContent)) {
        article.setContent(newContent);
    }

    Map<String, String> structureIds = (Map<String, String>) portletDataContext
            .getNewPrimaryKeysMap(JournalStructure.class);

    String parentStructureId = MapUtil.getString(structureIds, article.getStructureId(),
            article.getStructureId());

    Map<String, String> templateIds = (Map<String, String>) portletDataContext
            .getNewPrimaryKeysMap(JournalTemplate.class);

    String parentTemplateId = MapUtil.getString(templateIds, article.getTemplateId(), article.getTemplateId());

    Date displayDate = article.getDisplayDate();

    int displayDateMonth = 0;
    int displayDateDay = 0;
    int displayDateYear = 0;
    int displayDateHour = 0;
    int displayDateMinute = 0;

    if (displayDate != null) {
        Calendar displayCal = CalendarFactoryUtil.getCalendar(user.getTimeZone());

        displayCal.setTime(displayDate);

        displayDateMonth = displayCal.get(Calendar.MONTH);
        displayDateDay = displayCal.get(Calendar.DATE);
        displayDateYear = displayCal.get(Calendar.YEAR);
        displayDateHour = displayCal.get(Calendar.HOUR);
        displayDateMinute = displayCal.get(Calendar.MINUTE);

        if (displayCal.get(Calendar.AM_PM) == Calendar.PM) {
            displayDateHour += 12;
        }
    }

    Date expirationDate = article.getExpirationDate();

    int expirationDateMonth = 0;
    int expirationDateDay = 0;
    int expirationDateYear = 0;
    int expirationDateHour = 0;
    int expirationDateMinute = 0;
    boolean neverExpire = true;

    if (expirationDate != null) {
        Calendar expirationCal = CalendarFactoryUtil.getCalendar(user.getTimeZone());

        expirationCal.setTime(expirationDate);

        expirationDateMonth = expirationCal.get(Calendar.MONTH);
        expirationDateDay = expirationCal.get(Calendar.DATE);
        expirationDateYear = expirationCal.get(Calendar.YEAR);
        expirationDateHour = expirationCal.get(Calendar.HOUR);
        expirationDateMinute = expirationCal.get(Calendar.MINUTE);
        neverExpire = false;

        if (expirationCal.get(Calendar.AM_PM) == Calendar.PM) {
            expirationDateHour += 12;
        }
    }

    Date reviewDate = article.getReviewDate();

    int reviewDateMonth = 0;
    int reviewDateDay = 0;
    int reviewDateYear = 0;
    int reviewDateHour = 0;
    int reviewDateMinute = 0;
    boolean neverReview = true;

    if (reviewDate != null) {
        Calendar reviewCal = CalendarFactoryUtil.getCalendar(user.getTimeZone());

        reviewCal.setTime(reviewDate);

        reviewDateMonth = reviewCal.get(Calendar.MONTH);
        reviewDateDay = reviewCal.get(Calendar.DATE);
        reviewDateYear = reviewCal.get(Calendar.YEAR);
        reviewDateHour = reviewCal.get(Calendar.HOUR);
        reviewDateMinute = reviewCal.get(Calendar.MINUTE);
        neverReview = false;

        if (reviewCal.get(Calendar.AM_PM) == Calendar.PM) {
            reviewDateHour += 12;
        }
    }

    long structurePrimaryKey = 0;

    if (Validator.isNotNull(article.getStructureId())) {
        String structureUuid = articleElement.attributeValue("structure-uuid");

        JournalStructure existingStructure = JournalStructureUtil.fetchByUUID_G(structureUuid,
                portletDataContext.getScopeGroupId());

        if (existingStructure == null) {
            Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(portletDataContext.getCompanyId());

            long companyGroupId = companyGroup.getGroupId();

            existingStructure = JournalStructureUtil.fetchByUUID_G(structureUuid, companyGroupId);
        }

        if (existingStructure == null) {
            String newStructureId = structureIds.get(article.getStructureId());

            if (Validator.isNotNull(newStructureId)) {
                existingStructure = JournalStructureUtil.fetchByG_S(portletDataContext.getScopeGroupId(),
                        String.valueOf(newStructureId));
            }

            if (existingStructure == null) {
                if (_log.isWarnEnabled()) {
                    StringBundler sb = new StringBundler();

                    sb.append("Structure ");
                    sb.append(article.getStructureId());
                    sb.append(" is missing for article ");
                    sb.append(article.getArticleId());
                    sb.append(", skipping this article.");

                    _log.warn(sb.toString());
                }

                return;
            }
        }

        structurePrimaryKey = existingStructure.getPrimaryKey();

        parentStructureId = existingStructure.getStructureId();
    }

    if (Validator.isNotNull(article.getTemplateId())) {
        String templateUuid = articleElement.attributeValue("template-uuid");

        JournalTemplate existingTemplate = JournalTemplateUtil.fetchByUUID_G(templateUuid,
                portletDataContext.getScopeGroupId());

        if (existingTemplate == null) {
            Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(portletDataContext.getCompanyId());

            long companyGroupId = companyGroup.getGroupId();

            existingTemplate = JournalTemplateUtil.fetchByUUID_G(templateUuid, companyGroupId);
        }

        if (existingTemplate == null) {
            String newTemplateId = templateIds.get(article.getTemplateId());

            if (Validator.isNotNull(newTemplateId)) {
                existingTemplate = JournalTemplateUtil.fetchByG_T(portletDataContext.getScopeGroupId(),
                        newTemplateId);
            }

            if (existingTemplate == null) {
                if (_log.isWarnEnabled()) {
                    StringBundler sb = new StringBundler();

                    sb.append("Template ");
                    sb.append(article.getTemplateId());
                    sb.append(" is missing for article ");
                    sb.append(article.getArticleId());
                    sb.append(", skipping this article.");

                    _log.warn(sb.toString());
                }

                return;
            }
        }

        parentTemplateId = existingTemplate.getTemplateId();
    }

    File smallFile = null;

    String smallImagePath = articleElement.attributeValue("small-image-path");

    if (article.isSmallImage() && Validator.isNotNull(smallImagePath)) {
        byte[] bytes = portletDataContext.getZipEntryAsByteArray(smallImagePath);

        smallFile = FileUtil.createTempFile(article.getSmallImageType());

        FileUtil.write(smallFile, bytes);
    }

    Map<String, byte[]> images = new HashMap<String, byte[]>();

    String imagePath = articleElement.attributeValue("image-path");

    if (portletDataContext.getBooleanParameter(_NAMESPACE, "images") && Validator.isNotNull(imagePath)) {

        List<String> imageFiles = portletDataContext.getZipFolderEntries(imagePath);

        for (String imageFile : imageFiles) {
            String fileName = imageFile;

            if (fileName.contains(StringPool.SLASH)) {
                fileName = fileName.substring(fileName.lastIndexOf(CharPool.SLASH) + 1);
            }

            if (fileName.endsWith(".xml")) {
                continue;
            }

            int pos = fileName.lastIndexOf(CharPool.PERIOD);

            if (pos != -1) {
                fileName = fileName.substring(0, pos);
            }

            images.put(fileName, portletDataContext.getZipEntryAsByteArray(imageFile));
        }
    }

    String articleURL = null;

    boolean addGroupPermissions = creationStrategy.addGroupPermissions(portletDataContext, article);
    boolean addGuestPermissions = creationStrategy.addGuestPermissions(portletDataContext, article);

    ServiceContext serviceContext = portletDataContext.createServiceContext(articleElement, article,
            _NAMESPACE);

    serviceContext.setAddGroupPermissions(addGroupPermissions);
    serviceContext.setAddGuestPermissions(addGuestPermissions);
    serviceContext.setAttribute("imported", Boolean.TRUE.toString());

    if (article.getStatus() != WorkflowConstants.STATUS_APPROVED) {
        serviceContext.setWorkflowAction(WorkflowConstants.ACTION_SAVE_DRAFT);
    }

    JournalArticle importedArticle = null;

    String articleResourceUuid = articleElement.attributeValue("article-resource-uuid");

    if (portletDataContext.isDataStrategyMirror()) {
        JournalArticleResource articleResource = JournalArticleResourceUtil.fetchByUUID_G(articleResourceUuid,
                portletDataContext.getScopeGroupId());

        if (articleResource == null) {
            Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(portletDataContext.getCompanyId());

            long companyGroupId = companyGroup.getGroupId();

            articleResource = JournalArticleResourceUtil.fetchByUUID_G(articleResourceUuid, companyGroupId);
        }
        //Modification start
        if (articleResource == null) {
            articleResource = JournalArticleResourceUtil.fetchByG_A(portletDataContext.getScopeGroupId(),
                    articleId);
        }
        //Modification end
        serviceContext.setUuid(articleResourceUuid);

        JournalArticle existingArticle = null;

        if (articleResource != null) {
            try {
                existingArticle = JournalArticleLocalServiceUtil.getLatestArticle(
                        articleResource.getResourcePrimKey(), WorkflowConstants.STATUS_ANY, false);
            } catch (NoSuchArticleException nsae) {
            }
        }

        if (existingArticle == null) {
            existingArticle = JournalArticleUtil.fetchByG_A_V(portletDataContext.getScopeGroupId(),
                    newArticleId, article.getVersion());
        }

        if (existingArticle == null) {
            importedArticle = JournalArticleLocalServiceUtil.addArticle(userId,
                    portletDataContext.getScopeGroupId(), article.getClassNameId(), structurePrimaryKey,
                    articleId, autoArticleId, article.getVersion(), article.getTitleMap(),
                    article.getDescriptionMap(), article.getContent(), article.getType(), parentStructureId,
                    parentTemplateId, article.getLayoutUuid(), displayDateMonth, displayDateDay,
                    displayDateYear, displayDateHour, displayDateMinute, expirationDateMonth, expirationDateDay,
                    expirationDateYear, expirationDateHour, expirationDateMinute, neverExpire, reviewDateMonth,
                    reviewDateDay, reviewDateYear, reviewDateHour, reviewDateMinute, neverReview,
                    article.isIndexable(), article.isSmallImage(), article.getSmallImageURL(), smallFile,
                    images, articleURL, serviceContext);
        } else {
            importedArticle = JournalArticleLocalServiceUtil.updateArticle(userId, existingArticle.getGroupId(),
                    existingArticle.getArticleId(), existingArticle.getVersion(), article.getTitleMap(),
                    article.getDescriptionMap(), article.getContent(), article.getType(), parentStructureId,
                    parentTemplateId, article.getLayoutUuid(), displayDateMonth, displayDateDay,
                    displayDateYear, displayDateHour, displayDateMinute, expirationDateMonth, expirationDateDay,
                    expirationDateYear, expirationDateHour, expirationDateMinute, neverExpire, reviewDateMonth,
                    reviewDateDay, reviewDateYear, reviewDateHour, reviewDateMinute, neverReview,
                    article.isIndexable(), article.isSmallImage(), article.getSmallImageURL(), smallFile,
                    images, articleURL, serviceContext);
        }
    } else {
        importedArticle = JournalArticleLocalServiceUtil.addArticle(userId,
                portletDataContext.getScopeGroupId(), article.getClassNameId(), structurePrimaryKey, articleId,
                autoArticleId, article.getVersion(), article.getTitleMap(), article.getDescriptionMap(),
                article.getContent(), article.getType(), parentStructureId, parentTemplateId,
                article.getLayoutUuid(), displayDateMonth, displayDateDay, displayDateYear, displayDateHour,
                displayDateMinute, expirationDateMonth, expirationDateDay, expirationDateYear,
                expirationDateHour, expirationDateMinute, neverExpire, reviewDateMonth, reviewDateDay,
                reviewDateYear, reviewDateHour, reviewDateMinute, neverReview, article.isIndexable(),
                article.isSmallImage(), article.getSmallImageURL(), smallFile, images, articleURL,
                serviceContext);
    }

    if (smallFile != null) {
        smallFile.delete();
    }

    portletDataContext.importClassedModel(article, importedArticle, _NAMESPACE);

    if (Validator.isNull(newArticleId)) {
        articleIds.put(article.getArticleId(), importedArticle.getArticleId());
    }

    Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(portletDataContext.getCompanyId());

    if (importedArticle.getGroupId() == companyGroup.getGroupId()) {
        portletDataContext.addCompanyReference(JournalArticle.class, articleId);
    }

    if (!articleId.equals(importedArticle.getArticleId())) {
        if (_log.isWarnEnabled()) {
            _log.warn("An article with the ID " + articleId + " already " + "exists. The new generated ID is "
                    + importedArticle.getArticleId());
        }
    }
}

From source file:com.liferay.portlet.journal.lar.JournalPortletDataHandlerImpl.java

License:Open Source License

public static void importFeed(PortletDataContext portletDataContext, Element feedElement) throws Exception {

    String path = feedElement.attributeValue("path");

    if (!portletDataContext.isPathNotProcessed(path)) {
        return;// w w w .j a  v a2  s  .  co  m
    }

    JournalFeed feed = (JournalFeed) portletDataContext.getZipEntryAsObject(path);

    long userId = portletDataContext.getUserId(feed.getUserUuid());

    JournalCreationStrategy creationStrategy = JournalCreationStrategyFactory.getInstance();

    long authorId = creationStrategy.getAuthorUserId(portletDataContext, feed);

    if (authorId != JournalCreationStrategy.USE_DEFAULT_USER_ID_STRATEGY) {
        userId = authorId;
    }

    Group group = GroupLocalServiceUtil.getGroup(portletDataContext.getScopeGroupId());

    String newGroupFriendlyURL = group.getFriendlyURL().substring(1);

    String[] friendlyUrlParts = StringUtil.split(feed.getTargetLayoutFriendlyUrl(), '/');

    String oldGroupFriendlyURL = friendlyUrlParts[2];

    if (oldGroupFriendlyURL.equals("@data_handler_group_friendly_url@")) {
        feed.setTargetLayoutFriendlyUrl(StringUtil.replace(feed.getTargetLayoutFriendlyUrl(),
                "@data_handler_group_friendly_url@", newGroupFriendlyURL));
    }

    String feedId = feed.getFeedId();
    boolean autoFeedId = false;

    if (Validator.isNumber(feedId)
            || (JournalFeedUtil.fetchByG_F(portletDataContext.getScopeGroupId(), feedId) != null)) {

        autoFeedId = true;
    }

    Map<String, String> structureIds = (Map<String, String>) portletDataContext
            .getNewPrimaryKeysMap(JournalStructure.class + ".structureId");

    String parentStructureId = MapUtil.getString(structureIds, feed.getStructureId(), feed.getStructureId());

    Map<String, String> templateIds = (Map<String, String>) portletDataContext
            .getNewPrimaryKeysMap(JournalTemplate.class + ".templateId");

    String parentTemplateId = MapUtil.getString(templateIds, feed.getTemplateId(), feed.getTemplateId());
    String parentRenderTemplateId = MapUtil.getString(templateIds, feed.getRendererTemplateId(),
            feed.getRendererTemplateId());

    boolean addGroupPermissions = creationStrategy.addGroupPermissions(portletDataContext, feed);
    boolean addGuestPermissions = creationStrategy.addGuestPermissions(portletDataContext, feed);

    ServiceContext serviceContext = portletDataContext.createServiceContext(feedElement, feed, _NAMESPACE);

    serviceContext.setAddGroupPermissions(addGroupPermissions);
    serviceContext.setAddGuestPermissions(addGuestPermissions);

    JournalFeed importedFeed = null;

    try {
        if (portletDataContext.isDataStrategyMirror()) {
            JournalFeed existingFeed = JournalFeedUtil.fetchByUUID_G(feed.getUuid(),
                    portletDataContext.getScopeGroupId());

            if (existingFeed == null) {
                serviceContext.setUuid(feed.getUuid());

                importedFeed = JournalFeedLocalServiceUtil.addFeed(userId, portletDataContext.getScopeGroupId(),
                        feedId, autoFeedId, feed.getName(), feed.getDescription(), feed.getType(),
                        parentStructureId, parentTemplateId, parentRenderTemplateId, feed.getDelta(),
                        feed.getOrderByCol(), feed.getOrderByType(), feed.getTargetLayoutFriendlyUrl(),
                        feed.getTargetPortletId(), feed.getContentField(), feed.getFeedType(),
                        feed.getFeedVersion(), serviceContext);
            } else {
                importedFeed = JournalFeedLocalServiceUtil.updateFeed(existingFeed.getGroupId(),
                        existingFeed.getFeedId(), feed.getName(), feed.getDescription(), feed.getType(),
                        parentStructureId, parentTemplateId, parentRenderTemplateId, feed.getDelta(),
                        feed.getOrderByCol(), feed.getOrderByType(), feed.getTargetLayoutFriendlyUrl(),
                        feed.getTargetPortletId(), feed.getContentField(), feed.getFeedType(),
                        feed.getFeedVersion(), serviceContext);
            }
        } else {
            importedFeed = JournalFeedLocalServiceUtil.addFeed(userId, portletDataContext.getScopeGroupId(),
                    feedId, autoFeedId, feed.getName(), feed.getDescription(), feed.getType(),
                    parentStructureId, parentTemplateId, parentRenderTemplateId, feed.getDelta(),
                    feed.getOrderByCol(), feed.getOrderByType(), feed.getTargetLayoutFriendlyUrl(),
                    feed.getTargetPortletId(), feed.getContentField(), feed.getFeedType(),
                    feed.getFeedVersion(), serviceContext);
        }

        portletDataContext.importClassedModel(feed, importedFeed, _NAMESPACE);

        if (!feedId.equals(importedFeed.getFeedId())) {
            if (_log.isWarnEnabled()) {
                StringBundler sb = new StringBundler(5);

                sb.append("A feed with the ID ");
                sb.append(feedId);
                sb.append(" already exists. The new generated ID is ");
                sb.append(importedFeed.getFeedId());
                sb.append(".");

                _log.warn(sb.toString());
            }
        }
    } catch (FeedTargetLayoutFriendlyUrlException ftlfurle) {
        if (_log.isWarnEnabled()) {
            StringBundler sb = new StringBundler(6);

            sb.append("A feed with the ID ");
            sb.append(feedId);
            sb.append(" cannot be imported because layout with friendly ");
            sb.append("URL ");
            sb.append(feed.getTargetLayoutFriendlyUrl());
            sb.append(" does not exist");

            _log.warn(sb.toString());
        }
    }
}