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