1   /**
2    * Copyright (c) 2000-2008 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.lar;
24  
25  import com.liferay.portal.PortalException;
26  import com.liferay.portal.SystemException;
27  import com.liferay.portal.kernel.lar.PortletDataContext;
28  import com.liferay.portal.kernel.lar.PortletDataException;
29  import com.liferay.portal.kernel.lar.PortletDataHandlerControl;
30  import com.liferay.portal.kernel.lar.PortletDataHandlerKeys;
31  import com.liferay.portal.kernel.lar.UserIdStrategy;
32  import com.liferay.portal.kernel.util.ObjectValuePair;
33  import com.liferay.portal.kernel.util.StringPool;
34  import com.liferay.portal.kernel.zip.ZipReader;
35  import com.liferay.portal.kernel.zip.ZipWriter;
36  import com.liferay.portlet.blogs.model.impl.BlogsEntryImpl;
37  import com.liferay.portlet.bookmarks.model.impl.BookmarksEntryImpl;
38  import com.liferay.portlet.bookmarks.model.impl.BookmarksFolderImpl;
39  import com.liferay.portlet.calendar.model.impl.CalEventImpl;
40  import com.liferay.portlet.documentlibrary.model.impl.DLFileEntryImpl;
41  import com.liferay.portlet.documentlibrary.model.impl.DLFileRankImpl;
42  import com.liferay.portlet.documentlibrary.model.impl.DLFileShortcutImpl;
43  import com.liferay.portlet.documentlibrary.model.impl.DLFolderImpl;
44  import com.liferay.portlet.imagegallery.model.impl.IGFolderImpl;
45  import com.liferay.portlet.imagegallery.model.impl.IGImageImpl;
46  import com.liferay.portlet.journal.model.impl.JournalArticleImpl;
47  import com.liferay.portlet.journal.model.impl.JournalFeedImpl;
48  import com.liferay.portlet.journal.model.impl.JournalStructureImpl;
49  import com.liferay.portlet.journal.model.impl.JournalTemplateImpl;
50  import com.liferay.portlet.messageboards.model.MBMessage;
51  import com.liferay.portlet.messageboards.model.impl.MBBanImpl;
52  import com.liferay.portlet.messageboards.model.impl.MBCategoryImpl;
53  import com.liferay.portlet.messageboards.model.impl.MBMessageFlagImpl;
54  import com.liferay.portlet.messageboards.model.impl.MBMessageImpl;
55  import com.liferay.portlet.messageboards.service.MBMessageLocalServiceUtil;
56  import com.liferay.portlet.polls.model.impl.PollsChoiceImpl;
57  import com.liferay.portlet.polls.model.impl.PollsQuestionImpl;
58  import com.liferay.portlet.polls.model.impl.PollsVoteImpl;
59  import com.liferay.portlet.ratings.model.RatingsEntry;
60  import com.liferay.portlet.ratings.model.impl.RatingsEntryImpl;
61  import com.liferay.portlet.ratings.service.RatingsEntryLocalServiceUtil;
62  import com.liferay.portlet.tags.NoSuchAssetException;
63  import com.liferay.portlet.tags.model.TagsAsset;
64  import com.liferay.portlet.tags.model.TagsEntry;
65  import com.liferay.portlet.tags.service.TagsAssetLocalServiceUtil;
66  import com.liferay.portlet.wiki.model.impl.WikiNodeImpl;
67  import com.liferay.portlet.wiki.model.impl.WikiPageImpl;
68  import com.liferay.util.MapUtil;
69  
70  import com.thoughtworks.xstream.XStream;
71  
72  import java.io.IOException;
73  
74  import java.util.Date;
75  import java.util.HashMap;
76  import java.util.Iterator;
77  import java.util.List;
78  import java.util.Map;
79  import java.util.Set;
80  
81  /**
82   * <a href="PortletDataContextImpl.java.html"><b><i>View Source</i></b></a>
83   *
84   * <p>
85   * Holds context information that is used during exporting and importing portlet
86   * data.
87   * </p>
88   *
89   * @author Brian Wing Shun Chan
90   * @author Raymond Augé
91   * @author Bruno Farache
92   * @author Alex Chow
93   *
94   */
95  public class PortletDataContextImpl implements PortletDataContext {
96  
97      public PortletDataContextImpl(
98          long companyId, long groupId, Map<String, String[]> parameterMap,
99          Set primaryKeys, UserIdStrategy userIdStrategy, ZipReader zipReader) {
100 
101         _companyId = companyId;
102         _groupId = groupId;
103         _parameterMap = parameterMap;
104         _primaryKeys = primaryKeys;
105         _dataStrategy =  MapUtil.getString(
106             parameterMap, PortletDataHandlerKeys.DATA_STRATEGY,
107             PortletDataHandlerKeys.DATA_STRATEGY_MIRROR);
108         _userIdStrategy = userIdStrategy;
109         _zipReader = zipReader;
110         _zipWriter = null;
111 
112         initXStream();
113     }
114 
115     public PortletDataContextImpl(
116             long companyId, long groupId, Map<String, String[]> parameterMap,
117             Set primaryKeys, Date startDate, Date endDate, ZipWriter zipWriter)
118         throws PortletDataException {
119 
120         validateDateRange(startDate, endDate);
121 
122         _companyId = companyId;
123         _groupId = groupId;
124         _parameterMap = parameterMap;
125         _primaryKeys = primaryKeys;
126         _dataStrategy =  null;
127         _userIdStrategy = null;
128         _startDate = startDate;
129         _endDate = endDate;
130         _zipReader = null;
131         _zipWriter = zipWriter;
132 
133         initXStream();
134     }
135 
136     public void addComments(Class<?> classObj, Object primaryKey)
137         throws PortalException, SystemException {
138 
139         List messages = MBMessageLocalServiceUtil.getMessages(
140             classObj.getName(), ((Long)primaryKey).longValue());
141 
142         if (messages.size() == 0) {
143             return;
144         }
145 
146         Iterator itr = messages.iterator();
147 
148         while (itr.hasNext()) {
149             MBMessage message = (MBMessage)itr.next();
150 
151             message.setUserUuid(message.getUserUuid());
152         }
153 
154         _commentsMap.put(getPrimaryKeyString(classObj, primaryKey), messages);
155     }
156 
157     public void addComments(String className, Object primaryKey, List messages)
158         throws PortalException, SystemException {
159 
160         _commentsMap.put(
161             getPrimaryKeyString(className, primaryKey), messages);
162     }
163 
164     public boolean addPrimaryKey(Class<?> classObj, Object primaryKey) {
165         boolean value = hasPrimaryKey(classObj, primaryKey);
166 
167         if (!value) {
168             _primaryKeys.add(getPrimaryKeyString(classObj, primaryKey));
169         }
170 
171         return value;
172     }
173 
174     public void addRatingsEntries(Class<?> classObj, Object primaryKey)
175         throws PortalException, SystemException {
176 
177         List entries = RatingsEntryLocalServiceUtil.getEntries(
178             classObj.getName(), ((Long)primaryKey).longValue());
179 
180         if (entries.size() == 0) {
181             return;
182         }
183 
184         Iterator itr = entries.iterator();
185 
186         while (itr.hasNext()) {
187             RatingsEntry entry = (RatingsEntry)itr.next();
188 
189             entry.setUserUuid(entry.getUserUuid());
190         }
191 
192         _ratingsEntriesMap.put(
193             getPrimaryKeyString(classObj, primaryKey), entries);
194     }
195 
196     public void addRatingsEntries(
197             String className, Object primaryKey, List entries)
198         throws PortalException, SystemException {
199 
200         _ratingsEntriesMap.put(
201             getPrimaryKeyString(className, primaryKey), entries);
202     }
203 
204     public void addTagsEntries(Class<?> classObj, Object classPK)
205         throws PortalException, SystemException {
206 
207         TagsAsset tagsAsset = null;
208 
209         try {
210             tagsAsset = TagsAssetLocalServiceUtil.getAsset(
211                 classObj.getName(), ((Long)classPK).longValue());
212         }
213         catch (NoSuchAssetException nsae) {
214 
215             // LEP-4979
216 
217             return;
218         }
219 
220         List tagsEntriesList = tagsAsset.getEntries();
221 
222         if (tagsEntriesList.size() == 0) {
223             return;
224         }
225 
226         String[] tagsEntries = new String[tagsEntriesList.size()];
227 
228         Iterator itr = tagsEntriesList.iterator();
229 
230         for (int i = 0; itr.hasNext(); i++) {
231             TagsEntry tagsEntry = (TagsEntry)itr.next();
232 
233             tagsEntries[i] = tagsEntry.getName();
234         }
235 
236         _tagsEntriesMap.put(
237             getPrimaryKeyString(classObj, classPK), tagsEntries);
238     }
239 
240     public void addTagsEntries(
241             String className, Object classPK, String[] values)
242         throws PortalException, SystemException {
243 
244         _tagsEntriesMap.put(getPrimaryKeyString(className, classPK), values);
245     }
246 
247     public void addZipEntry(String path, byte[] bytes) throws SystemException {
248         try {
249             getZipWriter().addEntry(path, bytes);
250         }
251         catch (IOException ioe) {
252             throw new SystemException(ioe);
253         }
254     }
255 
256     public void addZipEntry(String path, Object object) throws SystemException {
257         addZipEntry(path, toXML(object));
258     }
259 
260     public void addZipEntry(String path, String s) throws SystemException {
261         try {
262             getZipWriter().addEntry(path, s);
263         }
264         catch (IOException ioe) {
265             throw new SystemException(ioe);
266         }
267     }
268 
269     public void addZipEntry(String path, StringBuilder sb)
270         throws SystemException {
271 
272         try {
273             getZipWriter().addEntry(path, sb);
274         }
275         catch (IOException ioe) {
276             throw new SystemException(ioe);
277         }
278     }
279 
280     public Object fromXML(byte[] bytes) {
281         return _xStream.fromXML(new String(bytes));
282     }
283 
284     public Object fromXML(String xml) {
285         return _xStream.fromXML(xml);
286     }
287 
288     public boolean getBooleanParameter(String namespace, String name) {
289         boolean defaultValue = MapUtil.getBoolean(
290             getParameterMap(),
291             PortletDataHandlerKeys.PORTLET_DATA_CONTROL_DEFAULT, true);
292 
293         return MapUtil.getBoolean(
294             getParameterMap(),
295             PortletDataHandlerControl.getNamespacedControlName(namespace, name),
296             defaultValue);
297     }
298 
299     public Map getComments() {
300         return _commentsMap;
301     }
302 
303     public long getCompanyId() {
304         return _companyId;
305     }
306 
307     public String getDataStrategy() {
308          return _dataStrategy;
309     }
310 
311     public Date getEndDate() {
312         return _endDate;
313     }
314 
315     public long getGroupId() {
316         return _groupId;
317     }
318 
319     public long getImportGroupId() {
320         return _importGroupId;
321     }
322 
323     public String getImportLayoutPath(long layoutId) {
324         return getImportRootPath() + ROOT_PATH_LAYOUTS + layoutId;
325     }
326 
327     public String getImportPortletPath(String portletId) {
328         return getImportRootPath() + ROOT_PATH_PORTLETS + portletId;
329     }
330 
331     public String getImportRootPath() {
332         return ROOT_PATH_GROUPS + getImportGroupId();
333     }
334 
335     public String getLayoutPath(long layoutId) {
336         return getRootPath() + ROOT_PATH_LAYOUTS + layoutId;
337     }
338 
339     public Map getNewPrimaryKeysMap(Class<?> classObj) {
340         Map map = _newPrimaryKeysMaps.get(classObj.getName());
341 
342         if (map == null) {
343             map = new HashMap();
344 
345             _newPrimaryKeysMaps.put(classObj.getName(), map);
346         }
347 
348         return map;
349     }
350 
351     public long getOldPlid() {
352         return _oldPlid;
353     }
354 
355     public Map getParameterMap() {
356         return _parameterMap;
357     }
358 
359     public long getPlid() {
360         return _plid;
361     }
362 
363     public String getPortletPath(String portletId) {
364         return getRootPath() + ROOT_PATH_PORTLETS + portletId;
365     }
366 
367     public Set getPrimaryKeys() {
368         return _primaryKeys;
369     }
370 
371     public Map getRatingsEntries() {
372         return _ratingsEntriesMap;
373     }
374 
375     public String getRootPath() {
376         return ROOT_PATH_GROUPS + getGroupId();
377     }
378 
379     public Date getStartDate() {
380         return _startDate;
381     }
382 
383     public Map getTagsEntries() {
384         return _tagsEntriesMap;
385     }
386 
387     public String[] getTagsEntries(Class<?> classObj, Object primaryKey) {
388         return (String[])_tagsEntriesMap.get(
389             getPrimaryKeyString(classObj, primaryKey));
390     }
391 
392     public String[] getTagsEntries(String className, Object primaryKey) {
393         return (String[])_tagsEntriesMap.get(
394             getPrimaryKeyString(className, primaryKey));
395     }
396 
397     public long getUserId(String userUuid) throws SystemException {
398         return _userIdStrategy.getUserId(userUuid);
399     }
400 
401     public UserIdStrategy getUserIdStrategy() {
402         return _userIdStrategy;
403     }
404 
405     public Map<String, byte[]> getZipEntries() {
406         return getZipReader().getEntries();
407     }
408 
409     public byte[] getZipEntryAsByteArray(String path) {
410         return getZipReader().getEntryAsByteArray(path);
411     }
412 
413     public Object getZipEntryAsObject(String path) {
414         return fromXML(getZipEntryAsString(path));
415     }
416 
417     public String getZipEntryAsString(String path) {
418         return getZipReader().getEntryAsString(path);
419     }
420 
421     public Map<String, List<ObjectValuePair<String, byte[]>>>
422         getZipFolderEntries() {
423 
424         return getZipReader().getFolderEntries();
425     }
426 
427     public List<ObjectValuePair<String, byte[]>> getZipFolderEntries(
428         String path) {
429 
430         List<ObjectValuePair<String, byte[]>> folderEntries =
431             getZipReader().getFolderEntries(path);
432 
433         if ((folderEntries == null) && path.startsWith(StringPool.SLASH)) {
434             folderEntries = getZipReader().getFolderEntries(path.substring(1));
435         }
436 
437         return folderEntries;
438     }
439 
440     public ZipReader getZipReader() {
441         return _zipReader;
442     }
443 
444     public ZipWriter getZipWriter() {
445         return _zipWriter;
446     }
447 
448     public boolean hasDateRange() {
449         if (_startDate != null) {
450             return true;
451         }
452         else {
453             return false;
454         }
455     }
456 
457     public boolean hasPrimaryKey(Class<?> classObj, Object primaryKey) {
458         return _primaryKeys.contains(getPrimaryKeyString(classObj, primaryKey));
459     }
460 
461     public void importComments(
462             Class<?> classObj, Object primaryKey, Object newPrimaryKey,
463             long groupId)
464         throws PortalException, SystemException {
465 
466         Map<Long, Long> messagePKs = new HashMap<Long, Long>();
467         Map<Long, Long> threadPKs = new HashMap<Long, Long>();
468 
469         List<MBMessage> messages = (List<MBMessage>)_commentsMap.get(
470             getPrimaryKeyString(classObj, primaryKey));
471 
472         if (messages == null) {
473             return;
474         }
475 
476         for (MBMessage message : messages) {
477             long userId = getUserId(message.getUserUuid());
478             long parentMessageId = MapUtil.getLong(
479                 messagePKs, message.getParentMessageId(),
480                 message.getParentMessageId());
481             long threadId = MapUtil.getLong(
482                 threadPKs, message.getThreadId(), message.getThreadId());
483 
484             MBMessage newMessage =
485                 MBMessageLocalServiceUtil.addDiscussionMessage(
486                     userId, message.getUserName(), groupId, classObj.getName(),
487                     ((Long)newPrimaryKey).longValue(), threadId,
488                     parentMessageId, message.getSubject(), message.getBody());
489 
490             messagePKs.put(message.getMessageId(), newMessage.getMessageId());
491             threadPKs.put(message.getThreadId(), newMessage.getThreadId());
492         }
493     }
494 
495     public void importRatingsEntries(
496             Class<?> classObj, Object primaryKey, Object newPrimaryKey)
497         throws PortalException, SystemException {
498 
499         List<RatingsEntry> entries = (List<RatingsEntry>)_ratingsEntriesMap.get(
500             getPrimaryKeyString(classObj, primaryKey));
501 
502         if (entries == null) {
503             return;
504         }
505 
506         for (RatingsEntry entry : entries) {
507             long userId = getUserId(entry.getUserUuid());
508 
509             RatingsEntryLocalServiceUtil.updateEntry(
510                 userId, classObj.getName(), ((Long)newPrimaryKey).longValue(),
511                 entry.getScore());
512         }
513     }
514 
515     public boolean isPathNotProcessed(String path) {
516         return !addPrimaryKey(String.class, path);
517     }
518 
519     public boolean isWithinDateRange(Date modifiedDate) {
520         if (!hasDateRange()) {
521             return true;
522         }
523         else if ((_startDate.compareTo(modifiedDate) <= 0) &&
524                  (_endDate.after(modifiedDate))) {
525 
526             return true;
527         }
528         else {
529             return false;
530         }
531     }
532 
533     public void setImportGroupId(long importGroupId) {
534         _importGroupId = importGroupId;
535     }
536 
537     public void setOldPlid(long oldPlid) {
538         _oldPlid = oldPlid;
539     }
540 
541     public void setPlid(long plid) {
542         _plid = plid;
543     }
544 
545     public String toXML(Object object) {
546         return _xStream.toXML(object);
547     }
548 
549     protected String getPrimaryKeyString(Class<?> classObj, Object primaryKey) {
550         return getPrimaryKeyString(classObj.getName(), primaryKey);
551     }
552 
553     protected String getPrimaryKeyString(String className, Object primaryKey) {
554         StringBuilder sb = new StringBuilder();
555 
556         sb.append(className);
557         sb.append(StringPool.POUND);
558         sb.append(primaryKey);
559 
560         return sb.toString();
561     }
562 
563     protected void initXStream() {
564         _xStream = new XStream();
565 
566         _xStream.alias("BlogsEntry", BlogsEntryImpl.class);
567         _xStream.alias("BookmarksFolder", BookmarksFolderImpl.class);
568         _xStream.alias("BookmarksEntry", BookmarksEntryImpl.class);
569         _xStream.alias("CalEvent", CalEventImpl.class);
570         _xStream.alias("DLFolder", DLFolderImpl.class);
571         _xStream.alias("DLFileEntry", DLFileEntryImpl.class);
572         _xStream.alias("DLFileShortcut", DLFileShortcutImpl.class);
573         _xStream.alias("DLFileRank", DLFileRankImpl.class);
574         _xStream.alias("IGFolder", IGFolderImpl.class);
575         _xStream.alias("IGImage", IGImageImpl.class);
576         _xStream.alias("JournalArticle", JournalArticleImpl.class);
577         _xStream.alias("JournalFeed", JournalFeedImpl.class);
578         _xStream.alias("JournalStructure", JournalStructureImpl.class);
579         _xStream.alias("JournalTemplate", JournalTemplateImpl.class);
580         _xStream.alias("MBCategory", MBCategoryImpl.class);
581         _xStream.alias("MBMessage", MBMessageImpl.class);
582         _xStream.alias("MBMessageFlag", MBMessageFlagImpl.class);
583         _xStream.alias("MBBan", MBBanImpl.class);
584         _xStream.alias("PollsQuestion", PollsQuestionImpl.class);
585         _xStream.alias("PollsChoice", PollsChoiceImpl.class);
586         _xStream.alias("PollsVote", PollsVoteImpl.class);
587         _xStream.alias("RatingsEntry", RatingsEntryImpl.class);
588         _xStream.alias("WikiNode", WikiNodeImpl.class);
589         _xStream.alias("WikiPage", WikiPageImpl.class);
590     }
591 
592     protected void validateDateRange(Date startDate, Date endDate)
593         throws PortletDataException {
594 
595         if ((startDate == null) ^ (endDate == null)) {
596             throw new PortletDataException(
597                 "Both start and end dates must have valid values or be null");
598         }
599 
600         if (startDate != null) {
601             if (startDate.after(endDate) || startDate.equals(endDate)) {
602                 throw new PortletDataException(
603                     "The start date cannot be after the end date");
604             }
605 
606             Date now = new Date();
607 
608             if (startDate.after(now) || endDate.after(now)) {
609                 throw new PortletDataException(
610                     "Dates must not be in the future");
611             }
612         }
613     }
614 
615     private long _companyId;
616     private long _groupId;
617     private long _importGroupId;
618     private long _oldPlid;
619     private long _plid;
620     private Set _primaryKeys;
621     private Map<String, Map> _newPrimaryKeysMaps = new HashMap<String, Map>();
622     private String _dataStrategy;
623     private UserIdStrategy _userIdStrategy;
624     private Date _startDate;
625     private Date _endDate;
626     private ZipReader _zipReader;
627     private ZipWriter _zipWriter;
628     private XStream _xStream;
629     private Map _commentsMap = new HashMap();
630     private Map<String, String[]> _parameterMap;
631     private Map _ratingsEntriesMap = new HashMap();
632     private Map _tagsEntriesMap = new HashMap();
633 
634 }