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