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         return getZipReader().getFolderEntries(path);
431     }
432 
433     public ZipReader getZipReader() {
434         return _zipReader;
435     }
436 
437     public ZipWriter getZipWriter() {
438         return _zipWriter;
439     }
440 
441     public boolean hasDateRange() {
442         if (_startDate != null) {
443             return true;
444         }
445         else {
446             return false;
447         }
448     }
449 
450     public boolean hasPrimaryKey(Class<?> classObj, Object primaryKey) {
451         return _primaryKeys.contains(getPrimaryKeyString(classObj, primaryKey));
452     }
453 
454     public void importComments(
455             Class<?> classObj, Object primaryKey, Object newPrimaryKey,
456             long groupId)
457         throws PortalException, SystemException {
458 
459         Map<Long, Long> messagePKs = new HashMap<Long, Long>();
460         Map<Long, Long> threadPKs = new HashMap<Long, Long>();
461 
462         List<MBMessage> messages = (List<MBMessage>)_commentsMap.get(
463             getPrimaryKeyString(classObj, primaryKey));
464 
465         if (messages == null) {
466             return;
467         }
468 
469         for (MBMessage message : messages) {
470             long userId = getUserId(message.getUserUuid());
471             long parentMessageId = MapUtil.getLong(
472                 messagePKs, message.getParentMessageId(),
473                 message.getParentMessageId());
474             long threadId = MapUtil.getLong(
475                 threadPKs, message.getThreadId(), message.getThreadId());
476 
477             MBMessage newMessage =
478                 MBMessageLocalServiceUtil.addDiscussionMessage(
479                     userId, message.getUserName(), groupId, classObj.getName(),
480                     ((Long)newPrimaryKey).longValue(), threadId,
481                     parentMessageId, message.getSubject(), message.getBody());
482 
483             messagePKs.put(message.getMessageId(), newMessage.getMessageId());
484             threadPKs.put(message.getThreadId(), newMessage.getThreadId());
485         }
486     }
487 
488     public void importRatingsEntries(
489             Class<?> classObj, Object primaryKey, Object newPrimaryKey)
490         throws PortalException, SystemException {
491 
492         List<RatingsEntry> entries = (List<RatingsEntry>)_ratingsEntriesMap.get(
493             getPrimaryKeyString(classObj, primaryKey));
494 
495         if (entries == null) {
496             return;
497         }
498 
499         for (RatingsEntry entry : entries) {
500             long userId = getUserId(entry.getUserUuid());
501 
502             RatingsEntryLocalServiceUtil.updateEntry(
503                 userId, classObj.getName(), ((Long)newPrimaryKey).longValue(),
504                 entry.getScore());
505         }
506     }
507 
508     public boolean isPathNotProcessed(String path) {
509         return !addPrimaryKey(String.class, path);
510     }
511 
512     public boolean isWithinDateRange(Date modifiedDate) {
513         if (!hasDateRange()) {
514             return true;
515         }
516         else if ((_startDate.compareTo(modifiedDate) <= 0) &&
517                  (_endDate.after(modifiedDate))) {
518 
519             return true;
520         }
521         else {
522             return false;
523         }
524     }
525 
526     public void setImportGroupId(long importGroupId) {
527         _importGroupId = importGroupId;
528     }
529 
530     public void setOldPlid(long oldPlid) {
531         _oldPlid = oldPlid;
532     }
533 
534     public void setPlid(long plid) {
535         _plid = plid;
536     }
537 
538     public String toXML(Object object) {
539         return _xStream.toXML(object);
540     }
541 
542     protected String getPrimaryKeyString(Class<?> classObj, Object primaryKey) {
543         return getPrimaryKeyString(classObj.getName(), primaryKey);
544     }
545 
546     protected String getPrimaryKeyString(String className, Object primaryKey) {
547         StringBuilder sb = new StringBuilder();
548 
549         sb.append(className);
550         sb.append(StringPool.POUND);
551         sb.append(primaryKey);
552 
553         return sb.toString();
554     }
555 
556     protected void initXStream() {
557         _xStream = new XStream();
558 
559         _xStream.alias("BlogsEntry", BlogsEntryImpl.class);
560         _xStream.alias("BookmarksFolder", BookmarksFolderImpl.class);
561         _xStream.alias("BookmarksEntry", BookmarksEntryImpl.class);
562         _xStream.alias("CalEvent", CalEventImpl.class);
563         _xStream.alias("DLFolder", DLFolderImpl.class);
564         _xStream.alias("DLFileEntry", DLFileEntryImpl.class);
565         _xStream.alias("DLFileShortcut", DLFileShortcutImpl.class);
566         _xStream.alias("DLFileRank", DLFileRankImpl.class);
567         _xStream.alias("IGFolder", IGFolderImpl.class);
568         _xStream.alias("IGImage", IGImageImpl.class);
569         _xStream.alias("JournalArticle", JournalArticleImpl.class);
570         _xStream.alias("JournalFeed", JournalFeedImpl.class);
571         _xStream.alias("JournalStructure", JournalStructureImpl.class);
572         _xStream.alias("JournalTemplate", JournalTemplateImpl.class);
573         _xStream.alias("MBCategory", MBCategoryImpl.class);
574         _xStream.alias("MBMessage", MBMessageImpl.class);
575         _xStream.alias("MBMessageFlag", MBMessageFlagImpl.class);
576         _xStream.alias("MBBan", MBBanImpl.class);
577         _xStream.alias("PollsQuestion", PollsQuestionImpl.class);
578         _xStream.alias("PollsChoice", PollsChoiceImpl.class);
579         _xStream.alias("PollsVote", PollsVoteImpl.class);
580         _xStream.alias("RatingsEntry", RatingsEntryImpl.class);
581         _xStream.alias("WikiNode", WikiNodeImpl.class);
582         _xStream.alias("WikiPage", WikiPageImpl.class);
583     }
584 
585     protected void validateDateRange(Date startDate, Date endDate)
586         throws PortletDataException {
587 
588         if ((startDate == null) ^ (endDate == null)) {
589             throw new PortletDataException(
590                 "Both start and end dates must have valid values or be null");
591         }
592 
593         if (startDate != null) {
594             if (startDate.after(endDate) || startDate.equals(endDate)) {
595                 throw new PortletDataException(
596                     "The start date cannot be after the end date");
597             }
598 
599             Date now = new Date();
600 
601             if (startDate.after(now) || endDate.after(now)) {
602                 throw new PortletDataException(
603                     "Dates must not be in the future");
604             }
605         }
606     }
607 
608     private long _companyId;
609     private long _groupId;
610     private long _importGroupId;
611     private long _oldPlid;
612     private long _plid;
613     private Set _primaryKeys;
614     private Map<String, Map> _newPrimaryKeysMaps = new HashMap<String, Map>();
615     private String _dataStrategy;
616     private UserIdStrategy _userIdStrategy;
617     private Date _startDate;
618     private Date _endDate;
619     private ZipReader _zipReader;
620     private ZipWriter _zipWriter;
621     private XStream _xStream;
622     private Map _commentsMap = new HashMap();
623     private Map<String, String[]> _parameterMap;
624     private Map _ratingsEntriesMap = new HashMap();
625     private Map _tagsEntriesMap = new HashMap();
626 
627 }