001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.lar;
016    
017    import com.liferay.portal.NoSuchRoleException;
018    import com.liferay.portal.NoSuchTeamException;
019    import com.liferay.portal.kernel.bean.BeanPropertiesUtil;
020    import com.liferay.portal.kernel.dao.orm.DynamicQuery;
021    import com.liferay.portal.kernel.dao.orm.Property;
022    import com.liferay.portal.kernel.dao.orm.PropertyFactoryUtil;
023    import com.liferay.portal.kernel.exception.PortalException;
024    import com.liferay.portal.kernel.exception.SystemException;
025    import com.liferay.portal.kernel.lar.ExportImportPathUtil;
026    import com.liferay.portal.kernel.lar.PortletDataContext;
027    import com.liferay.portal.kernel.lar.PortletDataContextListener;
028    import com.liferay.portal.kernel.lar.PortletDataException;
029    import com.liferay.portal.kernel.lar.PortletDataHandlerControl;
030    import com.liferay.portal.kernel.lar.PortletDataHandlerKeys;
031    import com.liferay.portal.kernel.lar.UserIdStrategy;
032    import com.liferay.portal.kernel.log.Log;
033    import com.liferay.portal.kernel.log.LogFactoryUtil;
034    import com.liferay.portal.kernel.util.GetterUtil;
035    import com.liferay.portal.kernel.util.KeyValuePair;
036    import com.liferay.portal.kernel.util.ListUtil;
037    import com.liferay.portal.kernel.util.MapUtil;
038    import com.liferay.portal.kernel.util.PrimitiveLongList;
039    import com.liferay.portal.kernel.util.StringBundler;
040    import com.liferay.portal.kernel.util.StringPool;
041    import com.liferay.portal.kernel.util.StringUtil;
042    import com.liferay.portal.kernel.util.Validator;
043    import com.liferay.portal.kernel.workflow.WorkflowConstants;
044    import com.liferay.portal.kernel.xml.Attribute;
045    import com.liferay.portal.kernel.xml.Element;
046    import com.liferay.portal.kernel.xml.Node;
047    import com.liferay.portal.kernel.xml.SAXReaderUtil;
048    import com.liferay.portal.kernel.xml.XPath;
049    import com.liferay.portal.kernel.zip.ZipReader;
050    import com.liferay.portal.kernel.zip.ZipWriter;
051    import com.liferay.portal.model.AttachedModel;
052    import com.liferay.portal.model.AuditedModel;
053    import com.liferay.portal.model.ClassedModel;
054    import com.liferay.portal.model.Group;
055    import com.liferay.portal.model.Layout;
056    import com.liferay.portal.model.Lock;
057    import com.liferay.portal.model.ResourceConstants;
058    import com.liferay.portal.model.ResourcedModel;
059    import com.liferay.portal.model.Role;
060    import com.liferay.portal.model.RoleConstants;
061    import com.liferay.portal.model.StagedModel;
062    import com.liferay.portal.model.Team;
063    import com.liferay.portal.model.impl.LockImpl;
064    import com.liferay.portal.security.permission.ResourceActionsUtil;
065    import com.liferay.portal.service.GroupLocalServiceUtil;
066    import com.liferay.portal.service.LockLocalServiceUtil;
067    import com.liferay.portal.service.ResourceBlockLocalServiceUtil;
068    import com.liferay.portal.service.ResourceBlockPermissionLocalServiceUtil;
069    import com.liferay.portal.service.ResourcePermissionLocalServiceUtil;
070    import com.liferay.portal.service.RoleLocalServiceUtil;
071    import com.liferay.portal.service.ServiceContext;
072    import com.liferay.portal.service.TeamLocalServiceUtil;
073    import com.liferay.portal.util.PortalUtil;
074    import com.liferay.portlet.asset.NoSuchEntryException;
075    import com.liferay.portlet.asset.model.AssetCategory;
076    import com.liferay.portlet.asset.model.AssetEntry;
077    import com.liferay.portlet.asset.model.AssetLink;
078    import com.liferay.portlet.asset.service.AssetCategoryLocalServiceUtil;
079    import com.liferay.portlet.asset.service.AssetEntryLocalServiceUtil;
080    import com.liferay.portlet.asset.service.AssetLinkLocalServiceUtil;
081    import com.liferay.portlet.asset.service.AssetTagLocalServiceUtil;
082    import com.liferay.portlet.blogs.model.impl.BlogsEntryImpl;
083    import com.liferay.portlet.bookmarks.model.impl.BookmarksEntryImpl;
084    import com.liferay.portlet.bookmarks.model.impl.BookmarksFolderImpl;
085    import com.liferay.portlet.calendar.model.impl.CalEventImpl;
086    import com.liferay.portlet.documentlibrary.model.impl.DLFileEntryImpl;
087    import com.liferay.portlet.documentlibrary.model.impl.DLFileRankImpl;
088    import com.liferay.portlet.documentlibrary.model.impl.DLFileShortcutImpl;
089    import com.liferay.portlet.documentlibrary.model.impl.DLFolderImpl;
090    import com.liferay.portlet.expando.model.ExpandoBridge;
091    import com.liferay.portlet.expando.model.ExpandoColumn;
092    import com.liferay.portlet.expando.service.ExpandoColumnLocalServiceUtil;
093    import com.liferay.portlet.journal.model.impl.JournalArticleImpl;
094    import com.liferay.portlet.journal.model.impl.JournalFeedImpl;
095    import com.liferay.portlet.journal.model.impl.JournalStructureImpl;
096    import com.liferay.portlet.journal.model.impl.JournalTemplateImpl;
097    import com.liferay.portlet.messageboards.model.MBDiscussion;
098    import com.liferay.portlet.messageboards.model.MBMessage;
099    import com.liferay.portlet.messageboards.model.MBThread;
100    import com.liferay.portlet.messageboards.model.impl.MBBanImpl;
101    import com.liferay.portlet.messageboards.model.impl.MBCategoryImpl;
102    import com.liferay.portlet.messageboards.model.impl.MBMessageImpl;
103    import com.liferay.portlet.messageboards.model.impl.MBThreadFlagImpl;
104    import com.liferay.portlet.messageboards.service.MBMessageLocalServiceUtil;
105    import com.liferay.portlet.messageboards.service.MBThreadLocalServiceUtil;
106    import com.liferay.portlet.messageboards.service.persistence.MBDiscussionUtil;
107    import com.liferay.portlet.messageboards.service.persistence.MBMessageUtil;
108    import com.liferay.portlet.polls.model.impl.PollsChoiceImpl;
109    import com.liferay.portlet.polls.model.impl.PollsQuestionImpl;
110    import com.liferay.portlet.polls.model.impl.PollsVoteImpl;
111    import com.liferay.portlet.ratings.model.RatingsEntry;
112    import com.liferay.portlet.ratings.model.impl.RatingsEntryImpl;
113    import com.liferay.portlet.ratings.service.RatingsEntryLocalServiceUtil;
114    import com.liferay.portlet.wiki.model.impl.WikiNodeImpl;
115    import com.liferay.portlet.wiki.model.impl.WikiPageImpl;
116    
117    import com.thoughtworks.xstream.XStream;
118    
119    import java.io.IOException;
120    import java.io.InputStream;
121    import java.io.Serializable;
122    
123    import java.util.ArrayList;
124    import java.util.Collections;
125    import java.util.Date;
126    import java.util.HashMap;
127    import java.util.HashSet;
128    import java.util.List;
129    import java.util.Map;
130    import java.util.Set;
131    
132    import jodd.bean.BeanUtil;
133    
134    /**
135     * <p>
136     * Holds context information that is used during exporting and importing portlet
137     * data.
138     * </p>
139     *
140     * @author Brian Wing Shun Chan
141     * @author Raymond Augé
142     * @author Bruno Farache
143     * @author Alexander Chow
144     */
145    public class PortletDataContextImpl implements PortletDataContext {
146    
147            public PortletDataContextImpl(
148                            long companyId, long groupId, Map<String, String[]> parameterMap,
149                            Set<String> primaryKeys, Date startDate, Date endDate,
150                            ZipWriter zipWriter)
151                    throws PortletDataException {
152    
153                    validateDateRange(startDate, endDate);
154    
155                    _companyId = companyId;
156    
157                    try {
158                            Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(
159                                    _companyId);
160    
161                            _companyGroupId = companyGroup.getGroupId();
162                    }
163                    catch (Exception e) {
164                            throw new IllegalStateException(e);
165                    }
166    
167                    _groupId = groupId;
168                    _scopeGroupId = groupId;
169                    _parameterMap = parameterMap;
170                    _primaryKeys = primaryKeys;
171                    _dataStrategy = null;
172                    _userIdStrategy = null;
173                    _startDate = startDate;
174                    _endDate = endDate;
175                    _zipReader = null;
176                    _zipWriter = zipWriter;
177    
178                    initXStream();
179            }
180    
181            public PortletDataContextImpl(
182                    long companyId, long groupId, Map<String, String[]> parameterMap,
183                    Set<String> primaryKeys, UserIdStrategy userIdStrategy,
184                    ZipReader zipReader) {
185    
186                    _companyId = companyId;
187    
188                    try {
189                            Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(
190                                    _companyId);
191    
192                            _companyGroupId = companyGroup.getGroupId();
193                    }
194                    catch (Exception e) {
195                            throw new IllegalStateException(e);
196                    }
197    
198                    _groupId = groupId;
199                    _scopeGroupId = groupId;
200                    _parameterMap = parameterMap;
201                    _primaryKeys = primaryKeys;
202                    _dataStrategy = MapUtil.getString(
203                            parameterMap, PortletDataHandlerKeys.DATA_STRATEGY,
204                            PortletDataHandlerKeys.DATA_STRATEGY_MIRROR);
205                    _userIdStrategy = userIdStrategy;
206                    _zipReader = zipReader;
207                    _zipWriter = null;
208    
209                    initXStream();
210            }
211    
212            public void addAssetCategories(Class<?> clazz, long classPK)
213                    throws SystemException {
214    
215                    List<AssetCategory> assetCategories =
216                            AssetCategoryLocalServiceUtil.getCategories(
217                                    clazz.getName(), classPK);
218    
219                    _assetCategoryUuidsMap.put(
220                            getPrimaryKeyString(clazz, classPK),
221                            StringUtil.split(
222                                    ListUtil.toString(
223                                            assetCategories, AssetCategory.UUID_ACCESSOR)));
224                    _assetCategoryIdsMap.put(
225                            getPrimaryKeyString(clazz, classPK),
226                            StringUtil.split(
227                                    ListUtil.toString(
228                                            assetCategories, AssetCategory.CATEGORY_ID_ACCESSOR), 0L));
229            }
230    
231            public void addAssetCategories(
232                    String className, long classPK, long[] assetCategoryIds) {
233    
234                    _assetCategoryIdsMap.put(
235                            getPrimaryKeyString(className, classPK), assetCategoryIds);
236            }
237    
238            public void addAssetLinks(Class<?> clazz, long classPK)
239                    throws PortalException, SystemException {
240    
241                    AssetEntry assetEntry = null;
242    
243                    try {
244                            assetEntry = AssetEntryLocalServiceUtil.getEntry(
245                                    clazz.getName(), classPK);
246                    }
247                    catch (NoSuchEntryException nsee) {
248                            return;
249                    }
250    
251                    List<AssetLink> directAssetLinks =
252                            AssetLinkLocalServiceUtil.getDirectLinks(assetEntry.getEntryId());
253    
254                    if (directAssetLinks.isEmpty()) {
255                            return;
256                    }
257    
258                    Map<Integer, List<AssetLink>> assetLinksMap =
259                            new HashMap<Integer, List<AssetLink>>();
260    
261                    for (AssetLink assetLink : directAssetLinks) {
262                            List<AssetLink> assetLinks = assetLinksMap.get(assetLink.getType());
263    
264                            if (assetLinks == null) {
265                                    assetLinks = new ArrayList<AssetLink>();
266    
267                                    assetLinksMap.put(assetLink.getType(), assetLinks);
268                            }
269    
270                            assetLinks.add(assetLink);
271                    }
272    
273                    for (Map.Entry<Integer, List<AssetLink>> entry :
274                                    assetLinksMap.entrySet()) {
275    
276                            int assetLinkType = entry.getKey();
277                            List<AssetLink> assetLinks = entry.getValue();
278    
279                            List<String> assetLinkUuids = new ArrayList<String>(
280                                    directAssetLinks.size());
281    
282                            for (AssetLink assetLink : assetLinks) {
283                                    try {
284                                            AssetEntry assetLinkEntry =
285                                                    AssetEntryLocalServiceUtil.getEntry(
286                                                            assetLink.getEntryId2());
287    
288                                            assetLinkUuids.add(assetLinkEntry.getClassUuid());
289                                    }
290                                    catch (NoSuchEntryException nsee) {
291                                    }
292                            }
293    
294                            _assetLinkUuidsMap.put(
295                                    getPrimaryKeyString(
296                                            assetEntry.getClassUuid(), String.valueOf(assetLinkType)),
297                                    assetLinkUuids.toArray(new String[assetLinkUuids.size()]));
298                    }
299            }
300    
301            public void addAssetTags(Class<?> clazz, long classPK)
302                    throws SystemException {
303    
304                    String[] tagNames = AssetTagLocalServiceUtil.getTagNames(
305                            clazz.getName(), classPK);
306    
307                    _assetTagNamesMap.put(getPrimaryKeyString(clazz, classPK), tagNames);
308            }
309    
310            public void addAssetTags(
311                    String className, long classPK, String[] assetTagNames) {
312    
313                    _assetTagNamesMap.put(
314                            getPrimaryKeyString(className, classPK), assetTagNames);
315            }
316    
317            public void addClassedModel(
318                            Element element, String path, ClassedModel classedModel,
319                            String namespace)
320                    throws PortalException, SystemException {
321    
322                    element.addAttribute("path", path);
323    
324                    if (classedModel instanceof AttachedModel) {
325                            AttachedModel attachedModel = (AttachedModel)classedModel;
326    
327                            element.addAttribute("class-name", attachedModel.getClassName());
328                    }
329                    else if (BeanUtil.hasProperty(classedModel, "className")) {
330                            String className = BeanPropertiesUtil.getStringSilent(
331                                    classedModel, "className");
332    
333                            if (className != null) {
334                                    element.addAttribute("class-name", className);
335                            }
336                    }
337    
338                    if (classedModel instanceof AuditedModel) {
339                            AuditedModel auditedModel = (AuditedModel)classedModel;
340    
341                            auditedModel.setUserUuid(auditedModel.getUserUuid());
342                    }
343    
344                    if (isResourceMain(classedModel)) {
345                            Class<?> clazz = classedModel.getModelClass();
346                            long classPK = getClassPK(classedModel);
347    
348                            addAssetLinks(clazz, classPK);
349                            addExpando(element, path, classedModel);
350                            addLocks(clazz, String.valueOf(classPK));
351                            addPermissions(clazz, classPK);
352    
353                            boolean portletMetadataAll = getBooleanParameter(
354                                    namespace, PortletDataHandlerKeys.PORTLET_METADATA_ALL);
355    
356                            if (portletMetadataAll ||
357                                    getBooleanParameter(namespace, "categories")) {
358    
359                                    addAssetCategories(clazz, classPK);
360                            }
361    
362                            if (portletMetadataAll ||
363                                    getBooleanParameter(namespace, "comments")) {
364    
365                                    addComments(clazz, classPK);
366                            }
367    
368                            if (portletMetadataAll ||
369                                    getBooleanParameter(namespace, "ratings")) {
370    
371                                    addRatingsEntries(clazz, classPK);
372                            }
373    
374                            if (portletMetadataAll || getBooleanParameter(namespace, "tags")) {
375                                    addAssetTags(clazz, classPK);
376                            }
377                    }
378    
379                    addZipEntry(path, classedModel);
380            }
381    
382            public void addComments(Class<?> clazz, long classPK)
383                    throws SystemException {
384    
385                    long classNameId = PortalUtil.getClassNameId(clazz);
386    
387                    MBDiscussion discussion = MBDiscussionUtil.fetchByC_C(
388                            classNameId, classPK);
389    
390                    if (discussion == null) {
391                            return;
392                    }
393    
394                    List<MBMessage> messages = MBMessageLocalServiceUtil.getThreadMessages(
395                            discussion.getThreadId(), WorkflowConstants.STATUS_APPROVED);
396    
397                    if (messages.isEmpty()) {
398                            return;
399                    }
400    
401                    MBMessage firstMessage = messages.get(0);
402    
403                    if ((messages.size() == 1) && firstMessage.isRoot()) {
404                            return;
405                    }
406    
407                    for (MBMessage message : messages) {
408                            message.setUserUuid(message.getUserUuid());
409    
410                            addRatingsEntries(MBDiscussion.class, message.getPrimaryKey());
411                    }
412    
413                    _commentsMap.put(getPrimaryKeyString(clazz, classPK), messages);
414            }
415    
416            public void addComments(
417                    String className, long classPK, List<MBMessage> messages) {
418    
419                    _commentsMap.put(getPrimaryKeyString(className, classPK), messages);
420            }
421    
422            /**
423             * @see #isWithinDateRange(Date)
424             */
425            public void addDateRangeCriteria(
426                    DynamicQuery dynamicQuery, String modifiedDatePropertyName) {
427    
428                    if (!hasDateRange()) {
429                            return;
430                    }
431    
432                    Property modifiedDateProperty = PropertyFactoryUtil.forName(
433                            modifiedDatePropertyName);
434    
435                    dynamicQuery.add(modifiedDateProperty.ge(_startDate));
436                    dynamicQuery.add(modifiedDateProperty.lt(_endDate));
437            }
438    
439            public void addExpando(
440                            Element element, String path, ClassedModel classedModel)
441                    throws PortalException, SystemException {
442    
443                    Class<?> clazz = classedModel.getModelClass();
444    
445                    String className = clazz.getName();
446    
447                    if (!_expandoColumnsMap.containsKey(className)) {
448                            List<ExpandoColumn> expandoColumns =
449                                    ExpandoColumnLocalServiceUtil.getDefaultTableColumns(
450                                            _companyId, className);
451    
452                            for (ExpandoColumn expandoColumn : expandoColumns) {
453                                    addPermissions(
454                                            ExpandoColumn.class, expandoColumn.getColumnId());
455                            }
456    
457                            _expandoColumnsMap.put(className, expandoColumns);
458                    }
459    
460                    ExpandoBridge expandoBridge = classedModel.getExpandoBridge();
461    
462                    Map<String, Serializable> expandoBridgeAttributes =
463                            expandoBridge.getAttributes();
464    
465                    if (!expandoBridgeAttributes.isEmpty()) {
466                            String expandoPath = ExportImportPathUtil.getExpandoPath(path);
467    
468                            element.addAttribute("expando-path", expandoPath);
469    
470                            addZipEntry(expandoPath, expandoBridgeAttributes);
471                    }
472            }
473    
474            public void addLocks(Class<?> clazz, String key)
475                    throws PortalException, SystemException {
476    
477                    if (!_locksMap.containsKey(getPrimaryKeyString(clazz, key)) &&
478                            LockLocalServiceUtil.isLocked(clazz.getName(), key)) {
479    
480                            Lock lock = LockLocalServiceUtil.getLock(clazz.getName(), key);
481    
482                            addLocks(clazz.getName(), key, lock);
483                    }
484            }
485    
486            public void addLocks(String className, String key, Lock lock) {
487                    _locksMap.put(getPrimaryKeyString(className, key), lock);
488            }
489    
490            public void addPermissions(Class<?> clazz, long classPK)
491                    throws PortalException, SystemException {
492    
493                    addPermissions(clazz.getName(), classPK);
494            }
495    
496            public void addPermissions(String resourceName, long resourcePK)
497                    throws PortalException, SystemException {
498    
499                    if (!MapUtil.getBoolean(
500                                    _parameterMap, PortletDataHandlerKeys.PERMISSIONS)) {
501    
502                            return;
503                    }
504    
505                    List<KeyValuePair> permissions = new ArrayList<KeyValuePair>();
506    
507                    Group group = GroupLocalServiceUtil.getGroup(_groupId);
508    
509                    List<Role> roles = RoleLocalServiceUtil.getRoles(_companyId);
510    
511                    PrimitiveLongList roleIds = new PrimitiveLongList(roles.size());
512                    Map<Long, String> roleIdsToNames = new HashMap<Long, String>();
513    
514                    for (Role role : roles) {
515                            int type = role.getType();
516    
517                            if ((type == RoleConstants.TYPE_REGULAR) ||
518                                    ((type == RoleConstants.TYPE_ORGANIZATION) &&
519                                     group.isOrganization()) ||
520                                    ((type == RoleConstants.TYPE_SITE) &&
521                                     (group.isLayoutSetPrototype() || group.isSite()))) {
522    
523                                    String name = role.getName();
524    
525                                    roleIds.add(role.getRoleId());
526                                    roleIdsToNames.put(role.getRoleId(), name);
527                            }
528                            else if ((type == RoleConstants.TYPE_PROVIDER) && role.isTeam()) {
529                                    Team team = TeamLocalServiceUtil.getTeam(role.getClassPK());
530    
531                                    if (team.getGroupId() == _groupId) {
532                                            String name =
533                                                    PermissionExporter.ROLE_TEAM_PREFIX + team.getName();
534    
535                                            roleIds.add(role.getRoleId());
536                                            roleIdsToNames.put(role.getRoleId(), name);
537                                    }
538                            }
539                    }
540    
541                    List<String> actionIds = ResourceActionsUtil.getModelResourceActions(
542                            resourceName);
543    
544                    Map<Long, Set<String>> roleIdsToActionIds = getActionIds(
545                            _companyId, roleIds.getArray(), resourceName, resourcePK,
546                            actionIds);
547    
548                    for (Map.Entry<Long, String> entry : roleIdsToNames.entrySet()) {
549                            long roleId = entry.getKey();
550                            String name = entry.getValue();
551    
552                            Set<String> availableActionIds = roleIdsToActionIds.get(roleId);
553    
554                            if (availableActionIds == null) {
555                                    availableActionIds = Collections.emptySet();
556                            }
557    
558                            KeyValuePair permission = new KeyValuePair(
559                                    name, StringUtil.merge(availableActionIds));
560    
561                            permissions.add(permission);
562                    }
563    
564                    _permissionsMap.put(
565                            getPrimaryKeyString(resourceName, resourcePK), permissions);
566            }
567    
568            public void addPermissions(
569                    String resourceName, long resourcePK, List<KeyValuePair> permissions) {
570    
571                    _permissionsMap.put(
572                            getPrimaryKeyString(resourceName, resourcePK), permissions);
573            }
574    
575            public boolean addPrimaryKey(Class<?> clazz, String primaryKey) {
576                    boolean value = hasPrimaryKey(clazz, primaryKey);
577    
578                    if (!value) {
579                            _primaryKeys.add(getPrimaryKeyString(clazz, primaryKey));
580                    }
581    
582                    return value;
583            }
584    
585            public void addRatingsEntries(Class<?> clazz, long classPK)
586                    throws SystemException {
587    
588                    List<RatingsEntry> ratingsEntries =
589                            RatingsEntryLocalServiceUtil.getEntries(clazz.getName(), classPK);
590    
591                    if (ratingsEntries.size() == 0) {
592                            return;
593                    }
594    
595                    for (RatingsEntry entry : ratingsEntries) {
596                            entry.setUserUuid(entry.getUserUuid());
597                    }
598    
599                    _ratingsEntriesMap.put(
600                            getPrimaryKeyString(clazz, classPK), ratingsEntries);
601            }
602    
603            public void addRatingsEntries(
604                    String className, long classPK, List<RatingsEntry> ratingsEntries) {
605    
606                    _ratingsEntriesMap.put(
607                            getPrimaryKeyString(className, classPK), ratingsEntries);
608            }
609    
610            public Element addReferenceElement(
611                    Element element, ClassedModel referencedClassedModel) {
612    
613                    Element referencesElement = element.element("references");
614    
615                    if (referencesElement == null) {
616                            referencesElement = element.addElement("references");
617                    }
618    
619                    Element referenceElement = referencesElement.addElement("reference");
620    
621                    referenceElement.addAttribute(
622                            "class-name", referencedClassedModel.getModelClassName());
623    
624                    Serializable primaryKeyObj = referencedClassedModel.getPrimaryKeyObj();
625    
626                    referenceElement.addAttribute(
627                            "class-pk", String.valueOf(primaryKeyObj));
628    
629                    return referenceElement;
630            }
631    
632            public void addZipEntry(String path, byte[] bytes) throws SystemException {
633                    if (_portletDataContextListener != null) {
634                            _portletDataContextListener.onAddZipEntry(path);
635                    }
636    
637                    try {
638                            ZipWriter zipWriter = getZipWriter();
639    
640                            zipWriter.addEntry(path, bytes);
641                    }
642                    catch (IOException ioe) {
643                            throw new SystemException(ioe);
644                    }
645            }
646    
647            public void addZipEntry(String path, InputStream is)
648                    throws SystemException {
649    
650                    if (_portletDataContextListener != null) {
651                            _portletDataContextListener.onAddZipEntry(path);
652                    }
653    
654                    try {
655                            ZipWriter zipWriter = getZipWriter();
656    
657                            zipWriter.addEntry(path, is);
658                    }
659                    catch (IOException ioe) {
660                            throw new SystemException(ioe);
661                    }
662            }
663    
664            public void addZipEntry(String path, Object object) throws SystemException {
665                    addZipEntry(path, toXML(object));
666            }
667    
668            public void addZipEntry(String path, String s) throws SystemException {
669                    if (_portletDataContextListener != null) {
670                            _portletDataContextListener.onAddZipEntry(path);
671                    }
672    
673                    try {
674                            ZipWriter zipWriter = getZipWriter();
675    
676                            zipWriter.addEntry(path, s);
677                    }
678                    catch (IOException ioe) {
679                            throw new SystemException(ioe);
680                    }
681            }
682    
683            public void addZipEntry(String path, StringBuilder sb)
684                    throws SystemException {
685    
686                    if (_portletDataContextListener != null) {
687                            _portletDataContextListener.onAddZipEntry(path);
688                    }
689    
690                    try {
691                            ZipWriter zipWriter = getZipWriter();
692    
693                            zipWriter.addEntry(path, sb);
694                    }
695                    catch (IOException ioe) {
696                            throw new SystemException(ioe);
697                    }
698            }
699    
700            public ServiceContext createServiceContext(
701                    Element element, ClassedModel classedModel, String namespace) {
702    
703                    return createServiceContext(element, null, classedModel, namespace);
704            }
705    
706            public ServiceContext createServiceContext(
707                    StagedModel stagedModel, String namespace) {
708    
709                    return createServiceContext(
710                            ExportImportPathUtil.getModelPath(stagedModel), stagedModel,
711                            namespace);
712            }
713    
714            public ServiceContext createServiceContext(
715                    String path, ClassedModel classedModel, String namespace) {
716    
717                    return createServiceContext(null, path, classedModel, namespace);
718            }
719    
720            public Object fromXML(byte[] bytes) {
721                    if ((bytes == null) || (bytes.length == 0)) {
722                            return null;
723                    }
724    
725                    return _xStream.fromXML(new String(bytes));
726            }
727    
728            public Object fromXML(String xml) {
729                    if (Validator.isNull(xml)) {
730                            return null;
731                    }
732    
733                    return _xStream.fromXML(xml);
734            }
735    
736            public long[] getAssetCategoryIds(Class<?> clazz, long classPK) {
737                    return _assetCategoryIdsMap.get(getPrimaryKeyString(clazz, classPK));
738            }
739    
740            public Map<String, long[]> getAssetCategoryIdsMap() {
741                    return _assetCategoryIdsMap;
742            }
743    
744            public Map<String, String[]> getAssetCategoryUuidsMap() {
745                    return _assetCategoryUuidsMap;
746            }
747    
748            public Map<String, String[]> getAssetLinkUuidsMap() {
749                    return _assetLinkUuidsMap;
750            }
751    
752            public String[] getAssetTagNames(Class<?> clazz, long classPK) {
753                    return _assetTagNamesMap.get(getPrimaryKeyString(clazz, classPK));
754            }
755    
756            public String[] getAssetTagNames(String className, long classPK) {
757                    return _assetTagNamesMap.get(getPrimaryKeyString(className, classPK));
758            }
759    
760            public Map<String, String[]> getAssetTagNamesMap() {
761                    return _assetTagNamesMap;
762            }
763    
764            public boolean getBooleanParameter(String namespace, String name) {
765                    boolean defaultValue = MapUtil.getBoolean(
766                            getParameterMap(),
767                            PortletDataHandlerKeys.PORTLET_DATA_CONTROL_DEFAULT, true);
768    
769                    return MapUtil.getBoolean(
770                            getParameterMap(),
771                            PortletDataHandlerControl.getNamespacedControlName(namespace, name),
772                            defaultValue);
773            }
774    
775            public ClassLoader getClassLoader() {
776                    return _xStream.getClassLoader();
777            }
778    
779            public Map<String, List<MBMessage>> getComments() {
780                    return _commentsMap;
781            }
782    
783            public long getCompanyGroupId() {
784                    return _companyGroupId;
785            }
786    
787            public long getCompanyId() {
788                    return _companyId;
789            }
790    
791            public String getDataStrategy() {
792                    return _dataStrategy;
793            }
794    
795            public Date getEndDate() {
796                    return _endDate;
797            }
798    
799            public Map<String, List<ExpandoColumn>> getExpandoColumns() {
800                    return _expandoColumnsMap;
801            }
802    
803            public Element getExportDataGroupElement(
804                    Class<? extends StagedModel> clazz) {
805    
806                    return getExportDataGroupElement(clazz.getSimpleName());
807            }
808    
809            public Element getExportDataRootElement() {
810                    return _exportDataRootElement;
811            }
812    
813            public Element getExportDataStagedModelElement(StagedModel stagedModel) {
814                    Class<?> clazz = stagedModel.getModelClass();
815    
816                    Element groupElement = getExportDataGroupElement(clazz.getSimpleName());
817    
818                    return groupElement.addElement("staged-model");
819            }
820    
821            public long getGroupId() {
822                    return _groupId;
823            }
824    
825            public Element getImportDataGroupElement(
826                    Class<? extends StagedModel> clazz) {
827    
828                    return getImportDataGroupElement(clazz.getSimpleName());
829            }
830    
831            public Element getImportDataRootElement() {
832                    return _importDataRootElement;
833            }
834    
835            public Element getImportDataStagedModelElement(StagedModel stagedModel) {
836                    String path = ExportImportPathUtil.getModelPath(stagedModel);
837    
838                    Class<?> clazz = stagedModel.getModelClass();
839    
840                    return getImportDataStagedModelElement(
841                            clazz.getSimpleName(), "path", path);
842            }
843    
844            public Element getImportDataStagedModelElement(
845                    String name, String attribute, String value) {
846    
847                    Element groupElement = getImportDataGroupElement(name);
848    
849                    if (groupElement == null) {
850                            return null;
851                    }
852    
853                    StringBundler sb = new StringBundler(4);
854    
855                    sb.append("staged-model");
856                    sb.append("[@" + attribute + "='");
857                    sb.append(value);
858                    sb.append("']");
859    
860                    XPath xPath = SAXReaderUtil.createXPath(sb.toString());
861    
862                    return (Element)xPath.selectSingleNode(groupElement);
863            }
864    
865            public String getLayoutPath(long layoutId) {
866                    return ExportImportPathUtil.getLayoutPath(this, layoutId);
867            }
868    
869            public Map<String, Lock> getLocks() {
870                    return _locksMap;
871            }
872    
873            public Map<?, ?> getNewPrimaryKeysMap(Class<?> clazz) {
874                    return getNewPrimaryKeysMap(clazz.getName());
875            }
876    
877            public Map<?, ?> getNewPrimaryKeysMap(String className) {
878                    Map<?, ?> map = _newPrimaryKeysMaps.get(className);
879    
880                    if (map == null) {
881                            map = new HashMap<Object, Object>();
882    
883                            _newPrimaryKeysMaps.put(className, map);
884                    }
885    
886                    return map;
887            }
888    
889            public long getOldPlid() {
890                    return _oldPlid;
891            }
892    
893            public Map<String, String[]> getParameterMap() {
894                    return _parameterMap;
895            }
896    
897            public Map<String, List<KeyValuePair>> getPermissions() {
898                    return _permissionsMap;
899            }
900    
901            public long getPlid() {
902                    return _plid;
903            }
904    
905            public String getPortletPath(String portletId) {
906                    return ExportImportPathUtil.getPortletPath(this, portletId);
907            }
908    
909            public Set<String> getPrimaryKeys() {
910                    return _primaryKeys;
911            }
912    
913            public Map<String, List<RatingsEntry>> getRatingsEntries() {
914                    return _ratingsEntriesMap;
915            }
916    
917            public List<Element> getReferencedDataElements(
918                    StagedModel parentStagedModel, Class<? extends StagedModel> clazz) {
919    
920                    List<Element> referencedElements = new ArrayList<Element>();
921    
922                    List<Element> referenceElements = getReferenceElements(
923                            parentStagedModel, clazz);
924    
925                    for (Element referenceElement : referenceElements) {
926                            long classPK = GetterUtil.getLong(
927                                    referenceElement.attributeValue("class-pk"));
928    
929                            StringBuilder sb = new StringBuilder(6);
930    
931                            sb.append("staged-model[contains(@path, '/");
932                            sb.append(clazz.getName());
933                            sb.append(StringPool.FORWARD_SLASH);
934                            sb.append(classPK);
935                            sb.append(".xml");
936                            sb.append("')]");
937    
938                            XPath xPath = SAXReaderUtil.createXPath(sb.toString());
939    
940                            Element groupElement = getImportDataGroupElement(clazz);
941    
942                            Element referencedElement = (Element)xPath.selectSingleNode(
943                                    groupElement);
944    
945                            referencedElements.add(referencedElement);
946                    }
947    
948                    return referencedElements;
949            }
950    
951            public String getRootPath() {
952                    return ExportImportPathUtil.getRootPath(this);
953            }
954    
955            public long getScopeGroupId() {
956                    return _scopeGroupId;
957            }
958    
959            public String getScopeLayoutUuid() {
960                    return _scopeLayoutUuid;
961            }
962    
963            public String getScopeType() {
964                    return _scopeType;
965            }
966    
967            public long getSourceCompanyGroupId() {
968                    return _sourceCompanyGroupId;
969            }
970    
971            public long getSourceGroupId() {
972                    return _sourceGroupId;
973            }
974    
975            public String getSourceLayoutPath(long layoutId) {
976                    return ExportImportPathUtil.getSourceLayoutPath(this, layoutId);
977            }
978    
979            public String getSourcePortletPath(String portletId) {
980                    return ExportImportPathUtil.getSourcePortletPath(this, portletId);
981            }
982    
983            public String getSourceRootPath() {
984                    return ExportImportPathUtil.getSourceRootPath(this);
985            }
986    
987            public Date getStartDate() {
988                    return _startDate;
989            }
990    
991            public long getUserId(String userUuid) {
992                    return _userIdStrategy.getUserId(userUuid);
993            }
994    
995            public UserIdStrategy getUserIdStrategy() {
996                    return _userIdStrategy;
997            }
998    
999            public List<String> getZipEntries() {
1000                    return getZipReader().getEntries();
1001            }
1002    
1003            public byte[] getZipEntryAsByteArray(String path) {
1004                    if (!Validator.isFilePath(path, false)) {
1005                            return null;
1006                    }
1007    
1008                    if (_portletDataContextListener != null) {
1009                            _portletDataContextListener.onGetZipEntry(path);
1010                    }
1011    
1012                    return getZipReader().getEntryAsByteArray(path);
1013            }
1014    
1015            public InputStream getZipEntryAsInputStream(String path) {
1016                    if (!Validator.isFilePath(path, false)) {
1017                            return null;
1018                    }
1019    
1020                    if (_portletDataContextListener != null) {
1021                            _portletDataContextListener.onGetZipEntry(path);
1022                    }
1023    
1024                    return getZipReader().getEntryAsInputStream(path);
1025            }
1026    
1027            public Object getZipEntryAsObject(Element element, String path) {
1028                    Object object = fromXML(getZipEntryAsString(path));
1029    
1030                    Attribute classNameAttribute = element.attribute("class-name");
1031    
1032                    if (classNameAttribute != null) {
1033                            BeanPropertiesUtil.setProperty(
1034                                    object, "className", classNameAttribute.getText());
1035                    }
1036    
1037                    return object;
1038            }
1039    
1040            public Object getZipEntryAsObject(String path) {
1041                    return fromXML(getZipEntryAsString(path));
1042            }
1043    
1044            public String getZipEntryAsString(String path) {
1045                    if (!Validator.isFilePath(path, false)) {
1046                            return null;
1047                    }
1048    
1049                    if (_portletDataContextListener != null) {
1050                            _portletDataContextListener.onGetZipEntry(path);
1051                    }
1052    
1053                    return getZipReader().getEntryAsString(path);
1054            }
1055    
1056            public List<String> getZipFolderEntries() {
1057                    return getZipFolderEntries(StringPool.SLASH);
1058            }
1059    
1060            public List<String> getZipFolderEntries(String path) {
1061                    if (!Validator.isFilePath(path, false)) {
1062                            return null;
1063                    }
1064    
1065                    return getZipReader().getFolderEntries(path);
1066            }
1067    
1068            public ZipReader getZipReader() {
1069                    return _zipReader;
1070            }
1071    
1072            public ZipWriter getZipWriter() {
1073                    return _zipWriter;
1074            }
1075    
1076            public boolean hasDateRange() {
1077                    if (_startDate != null) {
1078                            return true;
1079                    }
1080                    else {
1081                            return false;
1082                    }
1083            }
1084    
1085            public boolean hasNotUniquePerLayout(String dataKey) {
1086                    return _notUniquePerLayout.contains(dataKey);
1087            }
1088    
1089            public boolean hasPrimaryKey(Class<?> clazz, String primaryKey) {
1090                    return _primaryKeys.contains(getPrimaryKeyString(clazz, primaryKey));
1091            }
1092    
1093            public void importClassedModel(
1094                            ClassedModel classedModel, ClassedModel newClassedModel,
1095                            String namespace)
1096                    throws PortalException, SystemException {
1097    
1098                    if (!isResourceMain(classedModel)) {
1099                            return;
1100                    }
1101    
1102                    Class<?> clazz = classedModel.getModelClass();
1103                    long classPK = getClassPK(classedModel);
1104    
1105                    long newClassPK = getClassPK(newClassedModel);
1106    
1107                    Map<Long, Long> newPrimaryKeysMap =
1108                            (Map<Long, Long>)getNewPrimaryKeysMap(clazz);
1109    
1110                    newPrimaryKeysMap.put(classPK, newClassPK);
1111    
1112                    importLocks(clazz, String.valueOf(classPK), String.valueOf(newClassPK));
1113                    importPermissions(clazz, classPK, newClassPK);
1114    
1115                    boolean portletMetadataAll = getBooleanParameter(
1116                            namespace, PortletDataHandlerKeys.PORTLET_METADATA_ALL);
1117    
1118                    if (portletMetadataAll || getBooleanParameter(namespace, "comments")) {
1119                            importComments(clazz, classPK, newClassPK, getScopeGroupId());
1120                    }
1121    
1122                    if (portletMetadataAll || getBooleanParameter(namespace, "ratings")) {
1123                            importRatingsEntries(clazz, classPK, newClassPK);
1124                    }
1125            }
1126    
1127            public void importComments(
1128                            Class<?> clazz, long classPK, long newClassPK, long groupId)
1129                    throws PortalException, SystemException {
1130    
1131                    Map<Long, Long> messagePKs = new HashMap<Long, Long>();
1132                    Map<Long, Long> threadPKs = new HashMap<Long, Long>();
1133    
1134                    List<MBMessage> messages = _commentsMap.get(
1135                            getPrimaryKeyString(clazz, classPK));
1136    
1137                    if (messages == null) {
1138                            return;
1139                    }
1140    
1141                    MBMessage firstMessage = messages.get(0);
1142    
1143                    if ((messages.size() == 1) && firstMessage.isRoot()) {
1144                            return;
1145                    }
1146    
1147                    long classNameId = PortalUtil.getClassNameId(clazz);
1148    
1149                    MBDiscussion discussion = MBDiscussionUtil.fetchByC_C(
1150                            classNameId, newClassPK);
1151    
1152                    for (MBMessage message : messages) {
1153                            long userId = getUserId(message.getUserUuid());
1154                            long parentMessageId = MapUtil.getLong(
1155                                    messagePKs, message.getParentMessageId(),
1156                                    message.getParentMessageId());
1157                            long threadId = MapUtil.getLong(
1158                                    threadPKs, message.getThreadId(), message.getThreadId());
1159    
1160                            if (message.isRoot()) {
1161                                    if (discussion != null) {
1162                                            MBThread thread = MBThreadLocalServiceUtil.getThread(
1163                                                    discussion.getThreadId());
1164    
1165                                            long rootMessageId = thread.getRootMessageId();
1166    
1167                                            messagePKs.put(message.getMessageId(), rootMessageId);
1168                                            threadPKs.put(message.getThreadId(), thread.getThreadId());
1169                                    }
1170                                    else if (clazz == Layout.class) {
1171                                            MBMessage importedMessage =
1172                                                    MBMessageLocalServiceUtil.addDiscussionMessage(
1173                                                            userId, message.getUserName(), groupId,
1174                                                            clazz.getName(), newClassPK,
1175                                                            WorkflowConstants.ACTION_PUBLISH);
1176    
1177                                            messagePKs.put(
1178                                                    message.getMessageId(), importedMessage.getMessageId());
1179                                            threadPKs.put(
1180                                                    message.getThreadId(), importedMessage.getThreadId());
1181                                    }
1182                            }
1183                            else {
1184                                    ServiceContext serviceContext = new ServiceContext();
1185    
1186                                    serviceContext.setCreateDate(message.getCreateDate());
1187                                    serviceContext.setModifiedDate(message.getModifiedDate());
1188                                    serviceContext.setScopeGroupId(groupId);
1189    
1190                                    MBMessage importedMessage = null;
1191    
1192                                    if (_dataStrategy.equals(
1193                                                    PortletDataHandlerKeys.DATA_STRATEGY_MIRROR) ||
1194                                            _dataStrategy.equals(
1195                                                    PortletDataHandlerKeys.
1196                                                            DATA_STRATEGY_MIRROR_OVERWRITE)) {
1197    
1198                                            MBMessage existingMessage = MBMessageUtil.fetchByUUID_G(
1199                                                    message.getUuid(), groupId);
1200    
1201                                            if (existingMessage == null) {
1202                                                    serviceContext.setUuid(message.getUuid());
1203    
1204                                                    importedMessage =
1205                                                            MBMessageLocalServiceUtil.addDiscussionMessage(
1206                                                                    userId, message.getUserName(), groupId,
1207                                                                    clazz.getName(), newClassPK, threadId,
1208                                                                    parentMessageId, message.getSubject(),
1209                                                                    message.getBody(), serviceContext);
1210                                            }
1211                                            else {
1212                                                    serviceContext.setWorkflowAction(
1213                                                            WorkflowConstants.ACTION_PUBLISH);
1214    
1215                                                    importedMessage =
1216                                                            MBMessageLocalServiceUtil.updateDiscussionMessage(
1217                                                                    userId, existingMessage.getMessageId(),
1218                                                                    clazz.getName(), newClassPK,
1219                                                                    message.getSubject(), message.getBody(),
1220                                                                    serviceContext);
1221                                            }
1222                                    }
1223                                    else {
1224                                            importedMessage =
1225                                                    MBMessageLocalServiceUtil.addDiscussionMessage(
1226                                                            userId, message.getUserName(), groupId,
1227                                                            clazz.getName(), newClassPK, threadId,
1228                                                            parentMessageId, message.getSubject(),
1229                                                            message.getBody(), serviceContext);
1230                                    }
1231    
1232                                    messagePKs.put(
1233                                            message.getMessageId(), importedMessage.getMessageId());
1234                                    threadPKs.put(
1235                                            message.getThreadId(), importedMessage.getThreadId());
1236                            }
1237    
1238                            importRatingsEntries(
1239                                    MBDiscussion.class, message.getPrimaryKey(),
1240                                    messagePKs.get(message.getPrimaryKey()));
1241                    }
1242            }
1243    
1244            public void importLocks(Class<?> clazz, String key, String newKey)
1245                    throws PortalException, SystemException {
1246    
1247                    Lock lock = _locksMap.get(getPrimaryKeyString(clazz, key));
1248    
1249                    if (lock == null) {
1250                            return;
1251                    }
1252    
1253                    long userId = getUserId(lock.getUserUuid());
1254    
1255                    long expirationTime = 0;
1256    
1257                    if (lock.getExpirationDate() != null) {
1258                            Date expirationDate = lock.getExpirationDate();
1259    
1260                            expirationTime = expirationDate.getTime();
1261                    }
1262    
1263                    LockLocalServiceUtil.lock(
1264                            userId, clazz.getName(), newKey, lock.getOwner(),
1265                            lock.isInheritable(), expirationTime);
1266            }
1267    
1268            public void importPermissions(Class<?> clazz, long classPK, long newClassPK)
1269                    throws PortalException, SystemException {
1270    
1271                    importPermissions(clazz.getName(), classPK, newClassPK);
1272            }
1273    
1274            public void importPermissions(
1275                            String resourceName, long resourcePK, long newResourcePK)
1276                    throws PortalException, SystemException {
1277    
1278                    if (!MapUtil.getBoolean(
1279                                    _parameterMap, PortletDataHandlerKeys.PERMISSIONS)) {
1280    
1281                            return;
1282                    }
1283    
1284                    List<KeyValuePair> permissions = _permissionsMap.get(
1285                            getPrimaryKeyString(resourceName, resourcePK));
1286    
1287                    if (permissions == null) {
1288                            return;
1289                    }
1290    
1291                    Map<Long, String[]> roleIdsToActionIds = new HashMap<Long, String[]>();
1292    
1293                    for (KeyValuePair permission : permissions) {
1294                            String roleName = permission.getKey();
1295    
1296                            Role role = null;
1297    
1298                            Team team = null;
1299    
1300                            if (roleName.startsWith(PermissionExporter.ROLE_TEAM_PREFIX)) {
1301                                    roleName = roleName.substring(
1302                                            PermissionExporter.ROLE_TEAM_PREFIX.length());
1303    
1304                                    try {
1305                                            team = TeamLocalServiceUtil.getTeam(_groupId, roleName);
1306                                    }
1307                                    catch (NoSuchTeamException nste) {
1308                                            if (_log.isWarnEnabled()) {
1309                                                    _log.warn("Team " + roleName + " does not exist");
1310                                            }
1311    
1312                                            continue;
1313                                    }
1314                            }
1315    
1316                            try {
1317                                    if (team != null) {
1318                                            role = RoleLocalServiceUtil.getTeamRole(
1319                                                    _companyId, team.getTeamId());
1320                                    }
1321                                    else {
1322                                            role = RoleLocalServiceUtil.getRole(_companyId, roleName);
1323                                    }
1324                            }
1325                            catch (NoSuchRoleException nsre) {
1326                                    if (_log.isWarnEnabled()) {
1327                                            _log.warn("Role " + roleName + " does not exist");
1328                                    }
1329    
1330                                    continue;
1331                            }
1332    
1333                            String[] actionIds = StringUtil.split(permission.getValue());
1334    
1335                            roleIdsToActionIds.put(role.getRoleId(), actionIds);
1336                    }
1337    
1338                    if (roleIdsToActionIds.isEmpty()) {
1339                            return;
1340                    }
1341    
1342                    if (ResourceBlockLocalServiceUtil.isSupported(resourceName)) {
1343                            ResourceBlockLocalServiceUtil.setIndividualScopePermissions(
1344                                    _companyId, _groupId, resourceName, newResourcePK,
1345                                    roleIdsToActionIds);
1346                    }
1347                    else {
1348                            ResourcePermissionLocalServiceUtil.setResourcePermissions(
1349                                    _companyId, resourceName, ResourceConstants.SCOPE_INDIVIDUAL,
1350                                    String.valueOf(newResourcePK), roleIdsToActionIds);
1351                    }
1352            }
1353    
1354            public void importRatingsEntries(
1355                            Class<?> clazz, long classPK, long newClassPK)
1356                    throws PortalException, SystemException {
1357    
1358                    List<RatingsEntry> ratingsEntries = _ratingsEntriesMap.get(
1359                            getPrimaryKeyString(clazz, classPK));
1360    
1361                    if (ratingsEntries == null) {
1362                            return;
1363                    }
1364    
1365                    ServiceContext serviceContext = new ServiceContext();
1366    
1367                    for (RatingsEntry ratingsEntry : ratingsEntries) {
1368                            long userId = getUserId(ratingsEntry.getUserUuid());
1369    
1370                            serviceContext.setCreateDate(ratingsEntry.getCreateDate());
1371                            serviceContext.setModifiedDate(ratingsEntry.getModifiedDate());
1372    
1373                            RatingsEntryLocalServiceUtil.updateEntry(
1374                                    userId, clazz.getName(), newClassPK, ratingsEntry.getScore(),
1375                                    serviceContext);
1376                    }
1377            }
1378    
1379            public boolean isDataStrategyMirror() {
1380                    if (_dataStrategy.equals(PortletDataHandlerKeys.DATA_STRATEGY_MIRROR) ||
1381                            _dataStrategy.equals(
1382                                    PortletDataHandlerKeys.DATA_STRATEGY_MIRROR_OVERWRITE)) {
1383    
1384                            return true;
1385                    }
1386                    else {
1387                            return false;
1388                    }
1389            }
1390    
1391            public boolean isDataStrategyMirrorWithOverwriting() {
1392                    if (_dataStrategy.equals(
1393                                    PortletDataHandlerKeys.DATA_STRATEGY_MIRROR_OVERWRITE)) {
1394    
1395                            return true;
1396                    }
1397                    else {
1398                            return false;
1399                    }
1400            }
1401    
1402            public boolean isPathNotProcessed(String path) {
1403                    return !isPathProcessed(path);
1404            }
1405    
1406            public boolean isPathProcessed(String path) {
1407                    return addPrimaryKey(String.class, path);
1408            }
1409    
1410            public boolean isPerformDirectBinaryImport() {
1411                    return MapUtil.getBoolean(
1412                            _parameterMap, PortletDataHandlerKeys.PERFORM_DIRECT_BINARY_IMPORT);
1413            }
1414    
1415            public boolean isPrivateLayout() {
1416                    return _privateLayout;
1417            }
1418    
1419            /**
1420             * @see #addDateRangeCriteria(DynamicQuery, String)
1421             */
1422            public boolean isWithinDateRange(Date modifiedDate) {
1423                    if (!hasDateRange()) {
1424                            return true;
1425                    }
1426                    else if ((_startDate.compareTo(modifiedDate) <= 0) &&
1427                                     _endDate.after(modifiedDate)) {
1428    
1429                            return true;
1430                    }
1431                    else {
1432                            return false;
1433                    }
1434            }
1435    
1436            public void putNotUniquePerLayout(String dataKey) {
1437                    _notUniquePerLayout.add(dataKey);
1438            }
1439    
1440            public void setClassLoader(ClassLoader classLoader) {
1441                    _xStream.setClassLoader(classLoader);
1442            }
1443    
1444            public void setExportDataRootElement(Element exportDataRootElement) {
1445                    _exportDataRootElement = exportDataRootElement;
1446            }
1447    
1448            public void setGroupId(long groupId) {
1449                    _groupId = groupId;
1450            }
1451    
1452            public void setImportDataRootElement(Element importDataRootElement) {
1453                    _importDataRootElement = importDataRootElement;
1454            }
1455    
1456            public void setOldPlid(long oldPlid) {
1457                    _oldPlid = oldPlid;
1458            }
1459    
1460            public void setPlid(long plid) {
1461                    _plid = plid;
1462            }
1463    
1464            public void setPortetDataContextListener(
1465                    PortletDataContextListener portletDataContextListener) {
1466    
1467                    _portletDataContextListener = portletDataContextListener;
1468            }
1469    
1470            public void setPrivateLayout(boolean privateLayout) {
1471                    _privateLayout = privateLayout;
1472            }
1473    
1474            public void setScopeGroupId(long scopeGroupId) {
1475                    _scopeGroupId = scopeGroupId;
1476            }
1477    
1478            public void setScopeLayoutUuid(String scopeLayoutUuid) {
1479                    _scopeLayoutUuid = scopeLayoutUuid;
1480            }
1481    
1482            public void setScopeType(String scopeType) {
1483                    _scopeType = scopeType;
1484            }
1485    
1486            public void setSourceCompanyGroupId(long sourceCompanyGroupId) {
1487                    _sourceCompanyGroupId = sourceCompanyGroupId;
1488            }
1489    
1490            public void setSourceGroupId(long sourceGroupId) {
1491                    _sourceGroupId = sourceGroupId;
1492            }
1493    
1494            public void setStartDate(Date startDate) {
1495                    _startDate = startDate;
1496            }
1497    
1498            public String toXML(Object object) {
1499                    return _xStream.toXML(object);
1500            }
1501    
1502            protected ServiceContext createServiceContext(
1503                    Element element, String path, ClassedModel classedModel,
1504                    String namespace) {
1505    
1506                    Class<?> clazz = classedModel.getModelClass();
1507                    long classPK = getClassPK(classedModel);
1508    
1509                    ServiceContext serviceContext = new ServiceContext();
1510    
1511                    // Theme display
1512    
1513                    serviceContext.setCompanyId(getCompanyId());
1514                    serviceContext.setScopeGroupId(getScopeGroupId());
1515    
1516                    // Dates
1517    
1518                    if (classedModel instanceof AuditedModel) {
1519                            AuditedModel auditedModel = (AuditedModel)classedModel;
1520    
1521                            serviceContext.setUserId(getUserId(auditedModel));
1522                            serviceContext.setCreateDate(auditedModel.getCreateDate());
1523                            serviceContext.setModifiedDate(auditedModel.getModifiedDate());
1524                    }
1525    
1526                    // Permissions
1527    
1528                    if (!MapUtil.getBoolean(
1529                                    _parameterMap, PortletDataHandlerKeys.PERMISSIONS)) {
1530    
1531                            serviceContext.setAddGroupPermissions(true);
1532                            serviceContext.setAddGuestPermissions(true);
1533                    }
1534    
1535                    // Asset
1536    
1537                    boolean portletMetadataAll = getBooleanParameter(
1538                            namespace, PortletDataHandlerKeys.PORTLET_METADATA_ALL);
1539    
1540                    if (isResourceMain(classedModel)) {
1541                            if (portletMetadataAll ||
1542                                    getBooleanParameter(namespace, "categories")) {
1543    
1544                                    long[] assetCategoryIds = getAssetCategoryIds(clazz, classPK);
1545    
1546                                    serviceContext.setAssetCategoryIds(assetCategoryIds);
1547                            }
1548    
1549                            if (portletMetadataAll || getBooleanParameter(namespace, "tags")) {
1550                                    String[] assetTagNames = getAssetTagNames(clazz, classPK);
1551    
1552                                    serviceContext.setAssetTagNames(assetTagNames);
1553                            }
1554                    }
1555    
1556                    // Expando
1557    
1558                    String expandoPath = null;
1559    
1560                    if (element != null) {
1561                            expandoPath = element.attributeValue("expando-path");
1562                    }
1563                    else {
1564                            expandoPath = ExportImportPathUtil.getExpandoPath(path);
1565                    }
1566    
1567                    if (Validator.isNotNull(expandoPath)) {
1568                            try {
1569                                    Map<String, Serializable> expandoBridgeAttributes =
1570                                            (Map<String, Serializable>)getZipEntryAsObject(expandoPath);
1571    
1572                                    serviceContext.setExpandoBridgeAttributes(
1573                                            expandoBridgeAttributes);
1574                            }
1575                            catch (Exception e) {
1576                                    if (_log.isDebugEnabled()) {
1577                                            _log.debug(e, e);
1578                                    }
1579                            }
1580                    }
1581    
1582                    return serviceContext;
1583            }
1584    
1585            protected Map<Long, Set<String>> getActionIds(
1586                            long companyId, long[] roleIds, String className, long primKey,
1587                            List<String> actionIds)
1588                    throws PortalException, SystemException {
1589    
1590                    if (ResourceBlockLocalServiceUtil.isSupported(className)) {
1591                            return ResourceBlockPermissionLocalServiceUtil.
1592                                    getAvailableResourceBlockPermissionActionIds(
1593                                            roleIds, className, primKey, actionIds);
1594                    }
1595                    else {
1596                            return ResourcePermissionLocalServiceUtil.
1597                                    getAvailableResourcePermissionActionIds(
1598                                            companyId, className, ResourceConstants.SCOPE_INDIVIDUAL,
1599                                            String.valueOf(primKey), roleIds, actionIds);
1600                    }
1601            }
1602    
1603            protected long getClassPK(ClassedModel classedModel) {
1604                    if (classedModel instanceof ResourcedModel) {
1605                            ResourcedModel resourcedModel = (ResourcedModel)classedModel;
1606    
1607                            return resourcedModel.getResourcePrimKey();
1608                    }
1609                    else {
1610                            return (Long)classedModel.getPrimaryKeyObj();
1611                    }
1612            }
1613    
1614            protected String getExpandoPath(String path) {
1615                    return ExportImportPathUtil.getExpandoPath(path);
1616            }
1617    
1618            protected Element getExportDataGroupElement(String name) {
1619                    if (_exportDataRootElement == null) {
1620                            throw new IllegalStateException(
1621                                    "Root data element not initialized");
1622                    }
1623    
1624                    Element groupElement = _exportDataRootElement.element(name);
1625    
1626                    if (groupElement == null) {
1627                            groupElement = _exportDataRootElement.addElement(name);
1628                    }
1629    
1630                    return groupElement;
1631            }
1632    
1633            protected Element getImportDataGroupElement(String name) {
1634                    if (_importDataRootElement == null) {
1635                            throw new IllegalStateException(
1636                                    "Root data element not initialized");
1637                    }
1638    
1639                    if (Validator.isNull(name)) {
1640                            return SAXReaderUtil.createElement("EMPTY-ELEMENT");
1641                    }
1642    
1643                    Element groupElement = _importDataRootElement.element(name);
1644    
1645                    if (groupElement == null) {
1646                            return SAXReaderUtil.createElement("EMPTY-ELEMENT");
1647                    }
1648    
1649                    return groupElement;
1650            }
1651    
1652            protected String getPrimaryKeyString(Class<?> clazz, long classPK) {
1653                    return getPrimaryKeyString(clazz.getName(), String.valueOf(classPK));
1654            }
1655    
1656            protected String getPrimaryKeyString(Class<?> clazz, String primaryKey) {
1657                    return getPrimaryKeyString(clazz.getName(), primaryKey);
1658            }
1659    
1660            protected String getPrimaryKeyString(String className, long classPK) {
1661                    return getPrimaryKeyString(className, String.valueOf(classPK));
1662            }
1663    
1664            protected String getPrimaryKeyString(String className, String primaryKey) {
1665                    return className.concat(StringPool.POUND).concat(primaryKey);
1666            }
1667    
1668            protected List<Element> getReferenceElements(
1669                    StagedModel parentStagedModel, Class<? extends StagedModel> clazz) {
1670    
1671                    Element stagedModelElement = getImportDataStagedModelElement(
1672                            parentStagedModel);
1673    
1674                    if (stagedModelElement == null) {
1675                            return Collections.emptyList();
1676                    }
1677    
1678                    Element referencesElement = stagedModelElement.element("references");
1679    
1680                    if (referencesElement == null) {
1681                            return Collections.emptyList();
1682                    }
1683    
1684                    XPath xPath = SAXReaderUtil.createXPath(
1685                            "reference[@class-name='"+ clazz.getName() + "']");
1686    
1687                    List<Node> nodes = xPath.selectNodes(referencesElement);
1688    
1689                    return ListUtil.fromArray(nodes.toArray(new Element[nodes.size()]));
1690            }
1691    
1692            protected long getUserId(AuditedModel auditedModel) {
1693                    try {
1694                            String userUuid = auditedModel.getUserUuid();
1695    
1696                            return getUserId(userUuid);
1697                    }
1698                    catch (SystemException se) {
1699                            if (_log.isErrorEnabled()) {
1700                                    _log.error(se, se);
1701                            }
1702                    }
1703    
1704                    return 0;
1705            }
1706    
1707            protected void initXStream() {
1708                    _xStream = new XStream();
1709    
1710                    _xStream.alias("BlogsEntry", BlogsEntryImpl.class);
1711                    _xStream.alias("BookmarksFolder", BookmarksFolderImpl.class);
1712                    _xStream.alias("BookmarksEntry", BookmarksEntryImpl.class);
1713                    _xStream.alias("CalEvent", CalEventImpl.class);
1714                    _xStream.alias("DLFolder", DLFolderImpl.class);
1715                    _xStream.alias("DLFileEntry", DLFileEntryImpl.class);
1716                    _xStream.alias("DLFileShortcut", DLFileShortcutImpl.class);
1717                    _xStream.alias("DLFileRank", DLFileRankImpl.class);
1718                    _xStream.alias("JournalArticle", JournalArticleImpl.class);
1719                    _xStream.alias("JournalFeed", JournalFeedImpl.class);
1720                    _xStream.alias("JournalStructure", JournalStructureImpl.class);
1721                    _xStream.alias("JournalTemplate", JournalTemplateImpl.class);
1722                    _xStream.alias("Lock", LockImpl.class);
1723                    _xStream.alias("MBBan", MBBanImpl.class);
1724                    _xStream.alias("MBCategory", MBCategoryImpl.class);
1725                    _xStream.alias("MBMessage", MBMessageImpl.class);
1726                    _xStream.alias("MBThreadFlag", MBThreadFlagImpl.class);
1727                    _xStream.alias("PollsQuestion", PollsQuestionImpl.class);
1728                    _xStream.alias("PollsChoice", PollsChoiceImpl.class);
1729                    _xStream.alias("PollsVote", PollsVoteImpl.class);
1730                    _xStream.alias("RatingsEntry", RatingsEntryImpl.class);
1731                    _xStream.alias("WikiNode", WikiNodeImpl.class);
1732                    _xStream.alias("WikiPage", WikiPageImpl.class);
1733    
1734                    _xStream.omitField(HashMap.class, "cache_bitmask");
1735            }
1736    
1737            protected boolean isResourceMain(ClassedModel classedModel) {
1738                    if (classedModel instanceof ResourcedModel) {
1739                            ResourcedModel resourcedModel = (ResourcedModel)classedModel;
1740    
1741                            return resourcedModel.isResourceMain();
1742                    }
1743    
1744                    return true;
1745            }
1746    
1747            protected void validateDateRange(Date startDate, Date endDate)
1748                    throws PortletDataException {
1749    
1750                    if ((startDate == null) && (endDate != null)) {
1751                            throw new PortletDataException(
1752                                    PortletDataException.END_DATE_IS_MISSING_START_DATE);
1753                    }
1754                    else if ((startDate != null) && (endDate == null)) {
1755                            throw new PortletDataException(
1756                                    PortletDataException.START_DATE_IS_MISSING_END_DATE);
1757                    }
1758    
1759                    if (startDate != null) {
1760                            if (startDate.after(endDate) || startDate.equals(endDate)) {
1761                                    throw new PortletDataException(
1762                                            PortletDataException.START_DATE_AFTER_END_DATE);
1763                            }
1764    
1765                            Date now = new Date();
1766    
1767                            if (startDate.after(now)) {
1768                                    throw new PortletDataException(
1769                                            PortletDataException.FUTURE_START_DATE);
1770                            }
1771    
1772                            if (endDate.after(now)) {
1773                                    throw new PortletDataException(
1774                                            PortletDataException.FUTURE_END_DATE);
1775                            }
1776                    }
1777            }
1778    
1779            private static Log _log = LogFactoryUtil.getLog(
1780                    PortletDataContextImpl.class);
1781    
1782            private Map<String, long[]> _assetCategoryIdsMap =
1783                    new HashMap<String, long[]>();
1784            private Map<String, String[]> _assetCategoryUuidsMap =
1785                    new HashMap<String, String[]>();
1786            private Map<String, String[]> _assetLinkUuidsMap =
1787                    new HashMap<String, String[]>();
1788            private Map<String, String[]> _assetTagNamesMap =
1789                    new HashMap<String, String[]>();
1790            private Map<String, List<MBMessage>> _commentsMap =
1791                    new HashMap<String, List<MBMessage>>();
1792            private long _companyGroupId;
1793            private long _companyId;
1794            private String _dataStrategy;
1795            private Date _endDate;
1796            private Map<String, List<ExpandoColumn>> _expandoColumnsMap =
1797                    new HashMap<String, List<ExpandoColumn>>();
1798            private Element _exportDataRootElement;
1799            private long _groupId;
1800            private Element _importDataRootElement;
1801            private Map<String, Lock> _locksMap = new HashMap<String, Lock>();
1802            private Map<String, Map<?, ?>> _newPrimaryKeysMaps =
1803                    new HashMap<String, Map<?, ?>>();
1804            private Set<String> _notUniquePerLayout = new HashSet<String>();
1805            private long _oldPlid;
1806            private Map<String, String[]> _parameterMap;
1807            private Map<String, List<KeyValuePair>> _permissionsMap =
1808                    new HashMap<String, List<KeyValuePair>>();
1809            private long _plid;
1810            private PortletDataContextListener _portletDataContextListener;
1811            private Set<String> _primaryKeys;
1812            private boolean _privateLayout;
1813            private Map<String, List<RatingsEntry>> _ratingsEntriesMap =
1814                    new HashMap<String, List<RatingsEntry>>();
1815            private long _scopeGroupId;
1816            private String _scopeLayoutUuid;
1817            private String _scopeType;
1818            private long _sourceCompanyGroupId;
1819            private long _sourceGroupId;
1820            private Date _startDate;
1821            private UserIdStrategy _userIdStrategy;
1822            private XStream _xStream;
1823            private ZipReader _zipReader;
1824            private ZipWriter _zipWriter;
1825    
1826    }