001    /**
002     * Copyright (c) 2000-2010 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.NoSuchResourceException;
018    import com.liferay.portal.NoSuchRoleException;
019    import com.liferay.portal.kernel.exception.PortalException;
020    import com.liferay.portal.kernel.exception.SystemException;
021    import com.liferay.portal.kernel.lar.PortletDataContext;
022    import com.liferay.portal.kernel.lar.PortletDataContextListener;
023    import com.liferay.portal.kernel.lar.PortletDataException;
024    import com.liferay.portal.kernel.lar.PortletDataHandlerControl;
025    import com.liferay.portal.kernel.lar.PortletDataHandlerKeys;
026    import com.liferay.portal.kernel.lar.UserIdStrategy;
027    import com.liferay.portal.kernel.log.Log;
028    import com.liferay.portal.kernel.log.LogFactoryUtil;
029    import com.liferay.portal.kernel.util.KeyValuePair;
030    import com.liferay.portal.kernel.util.ListUtil;
031    import com.liferay.portal.kernel.util.MapUtil;
032    import com.liferay.portal.kernel.util.StringPool;
033    import com.liferay.portal.kernel.util.StringUtil;
034    import com.liferay.portal.kernel.workflow.WorkflowConstants;
035    import com.liferay.portal.kernel.zip.ZipReader;
036    import com.liferay.portal.kernel.zip.ZipWriter;
037    import com.liferay.portal.model.Group;
038    import com.liferay.portal.model.Lock;
039    import com.liferay.portal.model.Resource;
040    import com.liferay.portal.model.ResourceConstants;
041    import com.liferay.portal.model.Role;
042    import com.liferay.portal.model.RoleConstants;
043    import com.liferay.portal.model.impl.LockImpl;
044    import com.liferay.portal.security.permission.ResourceActionsUtil;
045    import com.liferay.portal.service.GroupLocalServiceUtil;
046    import com.liferay.portal.service.LockLocalServiceUtil;
047    import com.liferay.portal.service.PermissionLocalServiceUtil;
048    import com.liferay.portal.service.ResourceLocalServiceUtil;
049    import com.liferay.portal.service.ResourcePermissionLocalServiceUtil;
050    import com.liferay.portal.service.RoleLocalServiceUtil;
051    import com.liferay.portal.service.ServiceContext;
052    import com.liferay.portal.util.PortalUtil;
053    import com.liferay.portal.util.PropsValues;
054    import com.liferay.portlet.asset.model.AssetCategory;
055    import com.liferay.portlet.asset.service.AssetCategoryLocalServiceUtil;
056    import com.liferay.portlet.asset.service.AssetTagLocalServiceUtil;
057    import com.liferay.portlet.blogs.model.impl.BlogsEntryImpl;
058    import com.liferay.portlet.bookmarks.model.impl.BookmarksEntryImpl;
059    import com.liferay.portlet.bookmarks.model.impl.BookmarksFolderImpl;
060    import com.liferay.portlet.calendar.model.impl.CalEventImpl;
061    import com.liferay.portlet.documentlibrary.model.impl.DLFileEntryImpl;
062    import com.liferay.portlet.documentlibrary.model.impl.DLFileRankImpl;
063    import com.liferay.portlet.documentlibrary.model.impl.DLFileShortcutImpl;
064    import com.liferay.portlet.documentlibrary.model.impl.DLFolderImpl;
065    import com.liferay.portlet.imagegallery.model.impl.IGFolderImpl;
066    import com.liferay.portlet.imagegallery.model.impl.IGImageImpl;
067    import com.liferay.portlet.journal.model.impl.JournalArticleImpl;
068    import com.liferay.portlet.journal.model.impl.JournalFeedImpl;
069    import com.liferay.portlet.journal.model.impl.JournalStructureImpl;
070    import com.liferay.portlet.journal.model.impl.JournalTemplateImpl;
071    import com.liferay.portlet.messageboards.NoSuchDiscussionException;
072    import com.liferay.portlet.messageboards.model.MBDiscussion;
073    import com.liferay.portlet.messageboards.model.MBMessage;
074    import com.liferay.portlet.messageboards.model.MBMessageConstants;
075    import com.liferay.portlet.messageboards.model.MBThread;
076    import com.liferay.portlet.messageboards.model.impl.MBBanImpl;
077    import com.liferay.portlet.messageboards.model.impl.MBCategoryImpl;
078    import com.liferay.portlet.messageboards.model.impl.MBMessageFlagImpl;
079    import com.liferay.portlet.messageboards.model.impl.MBMessageImpl;
080    import com.liferay.portlet.messageboards.service.MBDiscussionLocalServiceUtil;
081    import com.liferay.portlet.messageboards.service.MBMessageLocalServiceUtil;
082    import com.liferay.portlet.messageboards.service.MBThreadLocalServiceUtil;
083    import com.liferay.portlet.messageboards.service.persistence.MBDiscussionUtil;
084    import com.liferay.portlet.messageboards.service.persistence.MBMessageUtil;
085    import com.liferay.portlet.polls.model.impl.PollsChoiceImpl;
086    import com.liferay.portlet.polls.model.impl.PollsQuestionImpl;
087    import com.liferay.portlet.polls.model.impl.PollsVoteImpl;
088    import com.liferay.portlet.ratings.model.RatingsEntry;
089    import com.liferay.portlet.ratings.model.impl.RatingsEntryImpl;
090    import com.liferay.portlet.ratings.service.RatingsEntryLocalServiceUtil;
091    import com.liferay.portlet.wiki.model.impl.WikiNodeImpl;
092    import com.liferay.portlet.wiki.model.impl.WikiPageImpl;
093    
094    import com.thoughtworks.xstream.XStream;
095    
096    import java.io.IOException;
097    import java.io.InputStream;
098    
099    import java.util.ArrayList;
100    import java.util.Date;
101    import java.util.HashMap;
102    import java.util.HashSet;
103    import java.util.Iterator;
104    import java.util.List;
105    import java.util.Map;
106    import java.util.Set;
107    
108    /**
109     * <p>
110     * Holds context information that is used during exporting and importing portlet
111     * data.
112     * </p>
113     *
114     * @author Brian Wing Shun Chan
115     * @author Raymond Augé
116     * @author Bruno Farache
117     * @author Alex Chow
118     */
119    public class PortletDataContextImpl implements PortletDataContext {
120    
121            public PortletDataContextImpl(
122                            long companyId, long groupId, Map<String, String[]> parameterMap,
123                            Set<String> primaryKeys, Date startDate, Date endDate,
124                            ZipWriter zipWriter)
125                    throws PortletDataException {
126    
127                    validateDateRange(startDate, endDate);
128    
129                    _companyId = companyId;
130                    _groupId = groupId;
131                    _scopeGroupId = groupId;
132                    _parameterMap = parameterMap;
133                    _primaryKeys = primaryKeys;
134                    _dataStrategy =  null;
135                    _userIdStrategy = null;
136                    _startDate = startDate;
137                    _endDate = endDate;
138                    _zipReader = null;
139                    _zipWriter = zipWriter;
140    
141                    initXStream();
142            }
143    
144            public PortletDataContextImpl(
145                    long companyId, long groupId, Map<String, String[]> parameterMap,
146                    Set<String> primaryKeys, UserIdStrategy userIdStrategy,
147                    ZipReader zipReader) {
148    
149                    _companyId = companyId;
150                    _groupId = groupId;
151                    _scopeGroupId = groupId;
152                    _parameterMap = parameterMap;
153                    _primaryKeys = primaryKeys;
154                    _dataStrategy =  MapUtil.getString(
155                            parameterMap, PortletDataHandlerKeys.DATA_STRATEGY,
156                            PortletDataHandlerKeys.DATA_STRATEGY_MIRROR);
157                    _userIdStrategy = userIdStrategy;
158                    _zipReader = zipReader;
159                    _zipWriter = null;
160    
161                    initXStream();
162            }
163    
164            public void addAssetCategories(Class<?> classObj, long classPK)
165                    throws SystemException {
166    
167                    List<AssetCategory> assetCategories =
168                            AssetCategoryLocalServiceUtil.getCategories(
169                                    classObj.getName(), classPK);
170    
171                    if (assetCategories.isEmpty()) {
172                            return;
173                    }
174    
175                    _assetCategoryUuidsMap.put(
176                            getPrimaryKeyString(classObj, classPK),
177                            StringUtil.split(ListUtil.toString(assetCategories, "uuid")));
178                    _assetCategoryIdsMap.put(
179                            getPrimaryKeyString(classObj, classPK),
180                            StringUtil.split(
181                                    ListUtil.toString(assetCategories, "categoryId"), 0L));
182            }
183    
184            public void addAssetCategories(
185                    String className, long classPK, long[] assetCategoryIds) {
186    
187                    _assetCategoryIdsMap.put(
188                            getPrimaryKeyString(className, classPK), assetCategoryIds);
189            }
190    
191            public void addAssetTags(Class<?> classObj, long classPK)
192                    throws SystemException {
193    
194                    String[] tagNames = AssetTagLocalServiceUtil.getTagNames(
195                            classObj.getName(), classPK);
196    
197                    if (tagNames.length == 0) {
198                            return;
199                    }
200    
201                    _assetTagNamesMap.put(
202                            getPrimaryKeyString(classObj, classPK), tagNames);
203            }
204    
205            public void addAssetTags(
206                    String className, long classPK, String[] assetTagNames) {
207    
208                    _assetTagNamesMap.put(
209                            getPrimaryKeyString(className, classPK), assetTagNames);
210            }
211    
212            public void addComments(Class<?> classObj, long classPK)
213                    throws SystemException {
214    
215                    long classNameId = PortalUtil.getClassNameId(classObj);
216    
217                    MBDiscussion discussion = MBDiscussionUtil.fetchByC_C(
218                            classNameId, classPK);
219    
220                    if (discussion == null) {
221                            return;
222                    }
223    
224                    List<MBMessage> messages = MBMessageLocalServiceUtil.getThreadMessages(
225                            discussion.getThreadId(), WorkflowConstants.STATUS_APPROVED);
226    
227                    if (messages.size() == 0) {
228                            return;
229                    }
230    
231                    Iterator<MBMessage> itr = messages.iterator();
232    
233                    while (itr.hasNext()) {
234                            MBMessage message = itr.next();
235    
236                            message.setUserUuid(message.getUserUuid());
237    
238                            addRatingsEntries(MBMessage.class, message.getPrimaryKey());
239                    }
240    
241                    _commentsMap.put(getPrimaryKeyString(classObj, classPK), messages);
242            }
243    
244            public void addComments(
245                    String className, long classPK, List<MBMessage> messages) {
246    
247                    _commentsMap.put(getPrimaryKeyString(className, classPK), messages);
248            }
249    
250            public void addLocks(Class<?> classObj, String key)
251                    throws PortalException, SystemException {
252    
253                    if (!_locksMap.containsKey(getPrimaryKeyString(classObj, key)) &&
254                            LockLocalServiceUtil.isLocked(classObj.getName(), key)) {
255    
256                            Lock lock = LockLocalServiceUtil.getLock(classObj.getName(), key);
257    
258                            addLocks(classObj.getName(), key, lock);
259                    }
260            }
261    
262            public void addLocks(String className, String key, Lock lock) {
263                    _locksMap.put(getPrimaryKeyString(className, key), lock);
264            }
265    
266            public void addPermissions(Class<?> classObj, long classPK)
267                    throws PortalException, SystemException {
268    
269                    addPermissions(classObj.getName(), classPK);
270            }
271    
272            public void addPermissions(String resourceName, long resourcePK)
273                    throws PortalException, SystemException {
274    
275                    if (((PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM != 5) &&
276                             (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM != 6)) ||
277                            (!MapUtil.getBoolean(
278                                    _parameterMap, PortletDataHandlerKeys.PERMISSIONS))) {
279    
280                            return;
281                    }
282    
283                    List<KeyValuePair> permissions = new ArrayList<KeyValuePair>();
284    
285                    Group group = GroupLocalServiceUtil.getGroup(_groupId);
286    
287                    List<Role> roles = RoleLocalServiceUtil.getRoles(_companyId);
288    
289                    for (Role role : roles) {
290                            int type = role.getType();
291    
292                            if ((type == RoleConstants.TYPE_REGULAR) ||
293                                    ((type == RoleConstants.TYPE_COMMUNITY) &&
294                                     (group.isCommunity())) ||
295                                    ((type == RoleConstants.TYPE_ORGANIZATION) &&
296                                     (group.isOrganization()))) {
297    
298                                    String name = role.getName();
299                                    String actionIds = getActionIds(
300                                            role, resourceName, String.valueOf(resourcePK));
301    
302                                    KeyValuePair permission = new KeyValuePair(name, actionIds);
303    
304                                    permissions.add(permission);
305                            }
306                    }
307    
308                    _permissionsMap.put(
309                            getPrimaryKeyString(resourceName, resourcePK), permissions);
310            }
311    
312            public void addPermissions(
313                    String resourceName, long resourcePK, List<KeyValuePair> permissions) {
314    
315                    if ((PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM != 5) &&
316                            (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM != 6)) {
317    
318                            return;
319                    }
320    
321                    _permissionsMap.put(
322                            getPrimaryKeyString(resourceName, resourcePK), permissions);
323            }
324    
325            public boolean addPrimaryKey(Class<?> classObj, String primaryKey) {
326                    boolean value = hasPrimaryKey(classObj, primaryKey);
327    
328                    if (!value) {
329                            _primaryKeys.add(getPrimaryKeyString(classObj, primaryKey));
330                    }
331    
332                    return value;
333            }
334    
335            public void addRatingsEntries(Class<?> classObj, long classPK)
336                    throws SystemException {
337    
338                    List<RatingsEntry> ratingsEntries =
339                            RatingsEntryLocalServiceUtil.getEntries(
340                                    classObj.getName(), classPK);
341    
342                    if (ratingsEntries.size() == 0) {
343                            return;
344                    }
345    
346                    Iterator<RatingsEntry> itr = ratingsEntries.iterator();
347    
348                    while (itr.hasNext()) {
349                            RatingsEntry entry = itr.next();
350    
351                            entry.setUserUuid(entry.getUserUuid());
352                    }
353    
354                    _ratingsEntriesMap.put(
355                            getPrimaryKeyString(classObj, classPK), ratingsEntries);
356            }
357    
358            public void addRatingsEntries(
359                    String className, long classPK, List<RatingsEntry> ratingsEntries) {
360    
361                    _ratingsEntriesMap.put(
362                            getPrimaryKeyString(className, classPK), ratingsEntries);
363            }
364    
365            public void addZipEntry(String path, byte[] bytes) throws SystemException {
366                    if (_portletDataContextListener != null) {
367                            _portletDataContextListener.onAddZipEntry(path);
368                    }
369    
370                    try {
371                            getZipWriter().addEntry(path, bytes);
372                    }
373                    catch (IOException ioe) {
374                            throw new SystemException(ioe);
375                    }
376            }
377    
378            public void addZipEntry(String path, InputStream is)
379                    throws SystemException {
380    
381                    if (_portletDataContextListener != null) {
382                            _portletDataContextListener.onAddZipEntry(path);
383                    }
384    
385                    try {
386                            getZipWriter().addEntry(path, is);
387                    }
388                    catch (IOException ioe) {
389                            throw new SystemException(ioe);
390                    }
391            }
392    
393            public void addZipEntry(String path, Object object) throws SystemException {
394                    addZipEntry(path, toXML(object));
395            }
396    
397            public void addZipEntry(String path, String s) throws SystemException {
398                    if (_portletDataContextListener != null) {
399                            _portletDataContextListener.onAddZipEntry(path);
400                    }
401    
402                    try {
403                            getZipWriter().addEntry(path, s);
404                    }
405                    catch (IOException ioe) {
406                            throw new SystemException(ioe);
407                    }
408            }
409    
410            public void addZipEntry(String path, StringBuilder sb)
411                    throws SystemException {
412    
413                    if (_portletDataContextListener != null) {
414                            _portletDataContextListener.onAddZipEntry(path);
415                    }
416    
417                    try {
418                            getZipWriter().addEntry(path, sb);
419                    }
420                    catch (IOException ioe) {
421                            throw new SystemException(ioe);
422                    }
423            }
424    
425            public Object fromXML(byte[] bytes) {
426                    return _xStream.fromXML(new String(bytes));
427            }
428    
429            public Object fromXML(String xml) {
430                    return _xStream.fromXML(xml);
431            }
432    
433            public long[] getAssetCategoryIds(Class<?> classObj, long classPK) {
434                    return _assetCategoryIdsMap.get(
435                            getPrimaryKeyString(classObj, classPK));
436            }
437    
438            public Map<String, long[]> getAssetCategoryIdsMap() {
439                    return _assetCategoryIdsMap;
440            }
441    
442            public Map<String, String[]> getAssetCategoryUuidsMap() {
443                    return _assetCategoryUuidsMap;
444            }
445    
446            public String[] getAssetTagNames(Class<?> classObj, long classPK) {
447                    return _assetTagNamesMap.get(getPrimaryKeyString(classObj, classPK));
448            }
449    
450            public String[] getAssetTagNames(String className, long classPK) {
451                    return _assetTagNamesMap.get(getPrimaryKeyString(className, classPK));
452            }
453    
454            public Map<String, String[]> getAssetTagNamesMap() {
455                    return _assetTagNamesMap;
456            }
457    
458            public boolean getBooleanParameter(String namespace, String name) {
459                    boolean defaultValue = MapUtil.getBoolean(
460                            getParameterMap(),
461                            PortletDataHandlerKeys.PORTLET_DATA_CONTROL_DEFAULT, true);
462    
463                    return MapUtil.getBoolean(
464                            getParameterMap(),
465                            PortletDataHandlerControl.getNamespacedControlName(namespace, name),
466                            defaultValue);
467            }
468    
469            public ClassLoader getClassLoader() {
470                    return _xStream.getClassLoader();
471            }
472    
473            public Map<String, List<MBMessage>> getComments() {
474                    return _commentsMap;
475            }
476    
477            public long getCompanyId() {
478                    return _companyId;
479            }
480    
481            public String getDataStrategy() {
482                    return _dataStrategy;
483            }
484    
485            public Date getEndDate() {
486                    return _endDate;
487            }
488    
489            public long getGroupId() {
490                    return _groupId;
491            }
492    
493            public String getLayoutPath(long layoutId) {
494                    return getRootPath() + ROOT_PATH_LAYOUTS + layoutId;
495            }
496    
497            public Map<String, Lock> getLocks() {
498                    return _locksMap;
499            }
500    
501            public Map<?, ?> getNewPrimaryKeysMap(Class<?> classObj) {
502                    return getNewPrimaryKeysMap(classObj.getName());
503            }
504    
505            public Map<?, ?> getNewPrimaryKeysMap(String className) {
506                    Map<?, ?> map = _newPrimaryKeysMaps.get(className);
507    
508                    if (map == null) {
509                            map = new HashMap<Object, Object>();
510    
511                            _newPrimaryKeysMaps.put(className, map);
512                    }
513    
514                    return map;
515            }
516    
517            public long getOldPlid() {
518                    return _oldPlid;
519            }
520    
521            public Map<String, String[]> getParameterMap() {
522                    return _parameterMap;
523            }
524    
525            public Map<String, List<KeyValuePair>> getPermissions() {
526                    return _permissionsMap;
527            }
528    
529            public long getPlid() {
530                    return _plid;
531            }
532    
533            public String getPortletPath(String portletId) {
534                    return getRootPath() + ROOT_PATH_PORTLETS + portletId;
535            }
536    
537            public Set<String> getPrimaryKeys() {
538                    return _primaryKeys;
539            }
540    
541            public Map<String, List<RatingsEntry>> getRatingsEntries() {
542                    return _ratingsEntriesMap;
543            }
544    
545            public String getRootPath() {
546                    return ROOT_PATH_GROUPS + getScopeGroupId();
547            }
548    
549            public long getScopeGroupId() {
550                    return _scopeGroupId;
551            }
552    
553            public String getScopeLayoutUuid() {
554                    return _scopeLayoutUuid;
555            }
556    
557            public long getSourceGroupId() {
558                    return _sourceGroupId;
559            }
560    
561            public String getSourceLayoutPath(long layoutId) {
562                    return getSourceRootPath() + ROOT_PATH_LAYOUTS + layoutId;
563            }
564    
565            public String getSourcePortletPath(String portletId) {
566                    return getSourceRootPath() + ROOT_PATH_PORTLETS + portletId;
567            }
568    
569            public String getSourceRootPath() {
570                    return ROOT_PATH_GROUPS + getSourceGroupId();
571            }
572    
573            public Date getStartDate() {
574                    return _startDate;
575            }
576    
577            public long getUserId(String userUuid) throws SystemException {
578                    return _userIdStrategy.getUserId(userUuid);
579            }
580    
581            public UserIdStrategy getUserIdStrategy() {
582                    return _userIdStrategy;
583            }
584    
585            public List<String> getZipEntries() {
586                    return getZipReader().getEntries();
587            }
588    
589            public byte[] getZipEntryAsByteArray(String path) {
590                    if (_portletDataContextListener != null) {
591                            _portletDataContextListener.onGetZipEntry(path);
592                    }
593    
594                    return getZipReader().getEntryAsByteArray(path);
595            }
596    
597            public InputStream getZipEntryAsInputStream(String path) {
598                    if (_portletDataContextListener != null) {
599                            _portletDataContextListener.onGetZipEntry(path);
600                    }
601    
602                    return getZipReader().getEntryAsInputStream(path);
603            }
604    
605            public Object getZipEntryAsObject(String path) {
606                    return fromXML(getZipEntryAsString(path));
607            }
608    
609            public String getZipEntryAsString(String path) {
610                    if (_portletDataContextListener != null) {
611                            _portletDataContextListener.onGetZipEntry(path);
612                    }
613    
614                    return getZipReader().getEntryAsString(path);
615            }
616    
617            public List<String> getZipFolderEntries() {
618                    return getZipFolderEntries(StringPool.SLASH);
619            }
620    
621            public List<String> getZipFolderEntries(String path) {
622                    return getZipReader().getFolderEntries(path);
623            }
624    
625            public ZipReader getZipReader() {
626                    return _zipReader;
627            }
628    
629            public ZipWriter getZipWriter() {
630                    return _zipWriter;
631            }
632    
633            public boolean hasDateRange() {
634                    if (_startDate != null) {
635                            return true;
636                    }
637                    else {
638                            return false;
639                    }
640            }
641    
642            public boolean hasNotUniquePerLayout(String dataKey) {
643                    return _notUniquePerLayout.contains(dataKey);
644            }
645    
646            public boolean hasPrimaryKey(Class<?> classObj, String primaryKey) {
647                    return _primaryKeys.contains(getPrimaryKeyString(classObj, primaryKey));
648            }
649    
650            public void importComments(
651                            Class<?> classObj, long classPK, long newClassPK, long groupId)
652                    throws PortalException, SystemException {
653    
654                    Map<Long, Long> messagePKs = new HashMap<Long, Long>();
655                    Map<Long, Long> threadPKs = new HashMap<Long, Long>();
656    
657                    List<MBMessage> messages = _commentsMap.get(
658                            getPrimaryKeyString(classObj, classPK));
659    
660                    if (messages == null) {
661                            return;
662                    }
663    
664                    MBDiscussion discussion = null;
665    
666                    try {
667                            discussion = MBDiscussionLocalServiceUtil.getDiscussion(
668                                    classObj.getName(), newClassPK);
669                    }
670                    catch (NoSuchDiscussionException nsde) {
671                    }
672    
673                    for (MBMessage message : messages) {
674                            long userId = getUserId(message.getUserUuid());
675                            long parentMessageId = MapUtil.getLong(
676                                    messagePKs, message.getParentMessageId(),
677                                    message.getParentMessageId());
678                            long threadId = MapUtil.getLong(
679                                    threadPKs, message.getThreadId(), message.getThreadId());
680    
681                            if ((message.getParentMessageId() ==
682                                            MBMessageConstants.DEFAULT_PARENT_MESSAGE_ID) &&
683                                    (discussion != null)) {
684    
685                                    MBThread thread = MBThreadLocalServiceUtil.getThread(
686                                            discussion.getThreadId());
687    
688                                    long rootMessageId = thread.getRootMessageId();
689    
690                                    messagePKs.put(message.getMessageId(), rootMessageId);
691                                    threadPKs.put(message.getThreadId(), thread.getThreadId());
692                            }
693                            else {
694                                    ServiceContext serviceContext = new ServiceContext();
695    
696                                    serviceContext.setScopeGroupId(groupId);
697    
698                                    MBMessage importedMessage = null;
699    
700                                    if (_dataStrategy.equals(
701                                                    PortletDataHandlerKeys.DATA_STRATEGY_MIRROR)) {
702    
703                                            MBMessage existingMessage = MBMessageUtil.fetchByUUID_G(
704                                                    message.getUuid(), groupId);
705    
706                                            if (existingMessage == null) {
707                                                    serviceContext.setUuid(message.getUuid());
708    
709                                                    importedMessage =
710                                                            MBMessageLocalServiceUtil.addDiscussionMessage(
711                                                                    userId, message.getUserName(), groupId,
712                                                                    classObj.getName(), newClassPK, threadId,
713                                                                    parentMessageId, message.getSubject(),
714                                                                    message.getBody(), serviceContext);
715                                            }
716                                            else {
717                                                    importedMessage =
718                                                            MBMessageLocalServiceUtil.updateDiscussionMessage(
719                                                                    userId, existingMessage.getMessageId(),
720                                                                    message.getSubject(), message.getBody(),
721                                                                    WorkflowConstants.ACTION_PUBLISH);
722                                            }
723                                    }
724                                    else {
725                                            importedMessage =
726                                                    MBMessageLocalServiceUtil.addDiscussionMessage(
727                                                            userId, message.getUserName(), groupId,
728                                                            classObj.getName(), newClassPK, threadId,
729                                                            parentMessageId, message.getSubject(),
730                                                            message.getBody(), serviceContext);
731                                    }
732    
733                                    messagePKs.put(
734                                            message.getMessageId(), importedMessage.getMessageId());
735                                    threadPKs.put(
736                                            message.getThreadId(), importedMessage.getThreadId());
737                            }
738    
739                            importRatingsEntries(
740                                    MBMessage.class, message.getPrimaryKey(),
741                                    messagePKs.get(message.getPrimaryKey()));
742                    }
743            }
744    
745            public void importLocks(Class<?> classObj, String key, String newKey)
746                    throws PortalException, SystemException {
747    
748                    Lock lock = _locksMap.get(getPrimaryKeyString(classObj, key));
749    
750                    if (lock == null) {
751                            return;
752                    }
753    
754                    long userId = getUserId(lock.getUserUuid());
755    
756                    long expirationTime = 0;
757    
758                    if (lock.getExpirationDate() != null) {
759                            Date expirationDate = lock.getExpirationDate();
760    
761                            expirationTime = expirationDate.getTime();
762                    }
763    
764                    LockLocalServiceUtil.lock(
765                            userId, classObj.getName(), newKey, lock.getOwner(),
766                            lock.getInheritable(), expirationTime);
767            }
768    
769            public void importPermissions(
770                            Class<?> classObj, long classPK, long newClassPK)
771                    throws PortalException, SystemException {
772    
773                    importPermissions(classObj.getName(), classPK, newClassPK);
774            }
775    
776            public void importPermissions(
777                            String resourceName, long resourcePK, long newResourcePK)
778                    throws PortalException, SystemException {
779    
780                    if (((PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM != 5) &&
781                             (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM != 6)) ||
782                            (!MapUtil.getBoolean(
783                                    _parameterMap, PortletDataHandlerKeys.PERMISSIONS))) {
784    
785                            return;
786                    }
787    
788                    List<KeyValuePair> permissions = _permissionsMap.get(
789                            getPrimaryKeyString(resourceName, resourcePK));
790    
791                    if (permissions == null) {
792                            return;
793                    }
794    
795                    for (KeyValuePair permission : permissions) {
796                            String roleName = permission.getKey();
797    
798                            Role role = null;
799    
800                            try {
801                                    role = RoleLocalServiceUtil.getRole(_companyId, roleName);
802                            }
803                            catch (NoSuchRoleException nsre) {
804                                    if (_log.isWarnEnabled()) {
805                                            _log.warn("Role " + roleName + " does not exist");
806                                    }
807    
808                                    continue;
809                            }
810    
811                            String[] actionIds = StringUtil.split(permission.getValue());
812    
813                            if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5) {
814                                    Resource resource = null;
815    
816                                    try {
817                                            resource = ResourceLocalServiceUtil.getResource(
818                                                    _companyId, resourceName,
819                                                    ResourceConstants.SCOPE_INDIVIDUAL,
820                                                    String.valueOf(newResourcePK));
821                                    }
822                                    catch (NoSuchResourceException nsre) {
823                                            resource = ResourceLocalServiceUtil.addResource(
824                                                    _companyId, resourceName,
825                                                    ResourceConstants.SCOPE_INDIVIDUAL,
826                                                    String.valueOf(newResourcePK));
827                                    }
828    
829                                    PermissionLocalServiceUtil.setRolePermissions(
830                                            role.getRoleId(), actionIds, resource.getResourceId());
831                            }
832                            else if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) {
833                                    ResourcePermissionLocalServiceUtil.setResourcePermissions(
834                                            _companyId, resourceName,
835                                            ResourceConstants.SCOPE_INDIVIDUAL,
836                                            String.valueOf(newResourcePK), role.getRoleId(), actionIds);
837                            }
838                    }
839            }
840    
841            public void importRatingsEntries(
842                            Class<?> classObj, long classPK, long newClassPK)
843                    throws PortalException, SystemException {
844    
845                    List<RatingsEntry> ratingsEntries = _ratingsEntriesMap.get(
846                            getPrimaryKeyString(classObj, classPK));
847    
848                    if (ratingsEntries == null) {
849                            return;
850                    }
851    
852                    ServiceContext serviceContext = new ServiceContext();
853    
854                    for (RatingsEntry ratingsEntry : ratingsEntries) {
855                            long userId = getUserId(ratingsEntry.getUserUuid());
856    
857                            serviceContext.setCreateDate(ratingsEntry.getCreateDate());
858                            serviceContext.setModifiedDate(ratingsEntry.getModifiedDate());
859    
860                            RatingsEntryLocalServiceUtil.updateEntry(
861                                    userId, classObj.getName(), ((Long)newClassPK).longValue(),
862                                    ratingsEntry.getScore(), serviceContext);
863                    }
864            }
865    
866            public boolean isDataStrategyMirror() {
867                    if (_dataStrategy.equals(PortletDataHandlerKeys.DATA_STRATEGY_MIRROR)) {
868                            return true;
869                    }
870                    else {
871                            return false;
872                    }
873            }
874    
875            public boolean isPathNotProcessed(String path) {
876                    return !addPrimaryKey(String.class, path);
877            }
878    
879            public boolean isPrivateLayout() {
880                    return _privateLayout;
881            }
882    
883            public boolean isWithinDateRange(Date modifiedDate) {
884                    if (!hasDateRange()) {
885                            return true;
886                    }
887                    else if ((_startDate.compareTo(modifiedDate) <= 0) &&
888                                     (_endDate.after(modifiedDate))) {
889    
890                            return true;
891                    }
892                    else {
893                            return false;
894                    }
895            }
896    
897            public void putNotUniquePerLayout(String dataKey) {
898                    _notUniquePerLayout.add(dataKey);
899            }
900    
901            public void setClassLoader(ClassLoader classLoader) {
902                    _xStream.setClassLoader(classLoader);
903            }
904    
905            public void setGroupId(long groupId) {
906                    _groupId = groupId;
907            }
908    
909            public void setOldPlid(long oldPlid) {
910                    _oldPlid = oldPlid;
911            }
912    
913            public void setPlid(long plid) {
914                    _plid = plid;
915            }
916    
917            public void setPortetDataContextListener(
918                    PortletDataContextListener portletDataContextListener) {
919    
920                    _portletDataContextListener = portletDataContextListener;
921            }
922    
923            public void setPrivateLayout(boolean privateLayout) {
924                    _privateLayout = privateLayout;
925            }
926    
927            public void setScopeGroupId(long scopeGroupId) {
928                    _scopeGroupId = scopeGroupId;
929            }
930    
931            public void setScopeLayoutUuid(String scopeLayoutUuid) {
932                    _scopeLayoutUuid = scopeLayoutUuid;
933            }
934    
935            public void setSourceGroupId(long sourceGroupId) {
936                    _sourceGroupId = sourceGroupId;
937            }
938    
939            public String toXML(Object object) {
940                    return _xStream.toXML(object);
941            }
942    
943            protected String getActionIds(
944                            Role role, String className, String primKey)
945                    throws PortalException, SystemException {
946    
947                    List<String> allActionIds = ResourceActionsUtil.getModelResourceActions(
948                            className);
949    
950                    List<String> actionIds = new ArrayList<String>(allActionIds.size());
951    
952                    for (String actionId : allActionIds) {
953                            if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5) {
954                                    if (PermissionLocalServiceUtil.hasRolePermission(
955                                                    role.getRoleId(), role.getCompanyId(), className,
956                                                    ResourceConstants.SCOPE_INDIVIDUAL, primKey,
957                                                    actionId)) {
958    
959                                            actionIds.add(actionId);
960                                    }
961                            }
962                            else if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) {
963                                    if (ResourcePermissionLocalServiceUtil.hasResourcePermission(
964                                                    role.getCompanyId(), className,
965                                                    ResourceConstants.SCOPE_INDIVIDUAL, primKey,
966                                                    role.getRoleId(), actionId)) {
967    
968                                            actionIds.add(actionId);
969                                    }
970                            }
971                    }
972    
973                    return StringUtil.merge(actionIds);
974            }
975    
976            protected String getPrimaryKeyString(Class<?> classObj, long classPK) {
977                    return getPrimaryKeyString(classObj.getName(), String.valueOf(classPK));
978            }
979    
980            protected String getPrimaryKeyString(Class<?> classObj, String primaryKey) {
981                    return getPrimaryKeyString(classObj.getName(), primaryKey);
982            }
983    
984            protected String getPrimaryKeyString(String className, long classPK) {
985                    return getPrimaryKeyString(className, String.valueOf(classPK));
986            }
987    
988            protected String getPrimaryKeyString(String className, String primaryKey) {
989                    return className.concat(StringPool.POUND).concat(primaryKey);
990            }
991    
992            protected void initXStream() {
993                    _xStream = new XStream();
994    
995                    _xStream.alias("BlogsEntry", BlogsEntryImpl.class);
996                    _xStream.alias("BookmarksFolder", BookmarksFolderImpl.class);
997                    _xStream.alias("BookmarksEntry", BookmarksEntryImpl.class);
998                    _xStream.alias("CalEvent", CalEventImpl.class);
999                    _xStream.alias("DLFolder", DLFolderImpl.class);
1000                    _xStream.alias("DLFileEntry", DLFileEntryImpl.class);
1001                    _xStream.alias("DLFileShortcut", DLFileShortcutImpl.class);
1002                    _xStream.alias("DLFileRank", DLFileRankImpl.class);
1003                    _xStream.alias("IGFolder", IGFolderImpl.class);
1004                    _xStream.alias("IGImage", IGImageImpl.class);
1005                    _xStream.alias("JournalArticle", JournalArticleImpl.class);
1006                    _xStream.alias("JournalFeed", JournalFeedImpl.class);
1007                    _xStream.alias("JournalStructure", JournalStructureImpl.class);
1008                    _xStream.alias("JournalTemplate", JournalTemplateImpl.class);
1009                    _xStream.alias("Lock", LockImpl.class);
1010                    _xStream.alias("MBCategory", MBCategoryImpl.class);
1011                    _xStream.alias("MBMessage", MBMessageImpl.class);
1012                    _xStream.alias("MBMessageFlag", MBMessageFlagImpl.class);
1013                    _xStream.alias("MBBan", MBBanImpl.class);
1014                    _xStream.alias("PollsQuestion", PollsQuestionImpl.class);
1015                    _xStream.alias("PollsChoice", PollsChoiceImpl.class);
1016                    _xStream.alias("PollsVote", PollsVoteImpl.class);
1017                    _xStream.alias("RatingsEntry", RatingsEntryImpl.class);
1018                    _xStream.alias("WikiNode", WikiNodeImpl.class);
1019                    _xStream.alias("WikiPage", WikiPageImpl.class);
1020            }
1021    
1022            protected void validateDateRange(Date startDate, Date endDate)
1023                    throws PortletDataException {
1024    
1025                    if ((startDate == null) ^ (endDate == null)) {
1026                            throw new PortletDataException(
1027                                    "Both start and end dates must have valid values or be null");
1028                    }
1029    
1030                    if (startDate != null) {
1031                            if (startDate.after(endDate) || startDate.equals(endDate)) {
1032                                    throw new PortletDataException(
1033                                            "The start date cannot be after the end date");
1034                            }
1035    
1036                            Date now = new Date();
1037    
1038                            if (startDate.after(now) || endDate.after(now)) {
1039                                    throw new PortletDataException(
1040                                            "Dates must not be in the future");
1041                            }
1042                    }
1043            }
1044    
1045            private static Log _log = LogFactoryUtil.getLog(
1046                    PortletDataContextImpl.class);
1047    
1048            private Map<String, long[]> _assetCategoryIdsMap =
1049                    new HashMap<String, long[]>();
1050            private Map<String, String[]> _assetCategoryUuidsMap =
1051                    new HashMap<String, String[]>();
1052            private Map<String, String[]> _assetTagNamesMap =
1053                    new HashMap<String, String[]>();
1054            private Map<String, List<MBMessage>> _commentsMap =
1055                    new HashMap<String, List<MBMessage>>();
1056            private long _companyId;
1057            private String _dataStrategy;
1058            private Date _endDate;
1059            private long _groupId;
1060            private Map<String, Lock> _locksMap = new HashMap<String, Lock>();
1061            private Map<String, Map<?, ?>> _newPrimaryKeysMaps =
1062                    new HashMap<String, Map<?, ?>>();
1063            private Set<String> _notUniquePerLayout = new HashSet<String>();
1064            private long _oldPlid;
1065            private Map<String, String[]> _parameterMap;
1066            private Map<String, List<KeyValuePair>> _permissionsMap =
1067                    new HashMap<String, List<KeyValuePair>>();
1068            private long _plid;
1069            private PortletDataContextListener _portletDataContextListener;
1070            private Set<String> _primaryKeys;
1071            private boolean _privateLayout;
1072            private Map<String, List<RatingsEntry>> _ratingsEntriesMap =
1073                    new HashMap<String, List<RatingsEntry>>();
1074            private long _scopeGroupId;
1075            private String _scopeLayoutUuid;
1076            private long _sourceGroupId;
1077            private Date _startDate;
1078            private UserIdStrategy _userIdStrategy;
1079            private XStream _xStream;
1080            private ZipReader _zipReader;
1081            private ZipWriter _zipWriter;
1082    
1083    }