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.portlet.bookmarks.lar;
16  
17  import com.liferay.portal.kernel.exception.PortalException;
18  import com.liferay.portal.kernel.exception.SystemException;
19  import com.liferay.portal.kernel.log.Log;
20  import com.liferay.portal.kernel.log.LogFactoryUtil;
21  import com.liferay.portal.kernel.util.MapUtil;
22  import com.liferay.portal.kernel.util.StringBundler;
23  import com.liferay.portal.kernel.xml.Document;
24  import com.liferay.portal.kernel.xml.Element;
25  import com.liferay.portal.kernel.xml.SAXReaderUtil;
26  import com.liferay.portal.lar.BasePortletDataHandler;
27  import com.liferay.portal.lar.PortletDataContext;
28  import com.liferay.portal.lar.PortletDataException;
29  import com.liferay.portal.lar.PortletDataHandlerBoolean;
30  import com.liferay.portal.lar.PortletDataHandlerControl;
31  import com.liferay.portal.lar.PortletDataHandlerKeys;
32  import com.liferay.portal.service.ServiceContext;
33  import com.liferay.portal.util.PortletKeys;
34  import com.liferay.portlet.bookmarks.NoSuchEntryException;
35  import com.liferay.portlet.bookmarks.NoSuchFolderException;
36  import com.liferay.portlet.bookmarks.model.BookmarksEntry;
37  import com.liferay.portlet.bookmarks.model.BookmarksFolder;
38  import com.liferay.portlet.bookmarks.model.BookmarksFolderConstants;
39  import com.liferay.portlet.bookmarks.service.BookmarksEntryLocalServiceUtil;
40  import com.liferay.portlet.bookmarks.service.BookmarksFolderLocalServiceUtil;
41  import com.liferay.portlet.bookmarks.service.persistence.BookmarksEntryUtil;
42  import com.liferay.portlet.bookmarks.service.persistence.BookmarksFolderUtil;
43  
44  import java.util.List;
45  import java.util.Map;
46  
47  import javax.portlet.PortletPreferences;
48  
49  /**
50   * <a href="BookmarksPortletDataHandlerImpl.java.html"><b><i>View Source</i></b>
51   * </a>
52   *
53   * @author Jorge Ferrer
54   * @author Bruno Farache
55   * @author Raymond Augé
56   */
57  public class BookmarksPortletDataHandlerImpl extends BasePortletDataHandler {
58  
59      public PortletPreferences deleteData(
60              PortletDataContext context, String portletId,
61              PortletPreferences preferences)
62          throws PortletDataException {
63  
64          try {
65              if (!context.addPrimaryKey(
66                      BookmarksPortletDataHandlerImpl.class, "deleteData")) {
67  
68                  BookmarksFolderLocalServiceUtil.deleteFolders(
69                      context.getGroupId());
70              }
71  
72              return null;
73          }
74          catch (Exception e) {
75              throw new PortletDataException(e);
76          }
77      }
78  
79      public String exportData(
80              PortletDataContext context, String portletId,
81              PortletPreferences preferences)
82          throws PortletDataException {
83  
84          try {
85              Document doc = SAXReaderUtil.createDocument();
86  
87              Element root = doc.addElement("bookmarks-data");
88  
89              root.addAttribute("group-id", String.valueOf(context.getGroupId()));
90  
91              Element foldersEl = root.addElement("folders");
92              Element entriesEl = root.addElement("entries");
93  
94              List<BookmarksFolder> folders = BookmarksFolderUtil.findByGroupId(
95                  context.getGroupId());
96  
97              for (BookmarksFolder folder : folders) {
98                  exportFolder(context, foldersEl, entriesEl, folder);
99              }
100 
101             List<BookmarksEntry> entries = BookmarksEntryUtil.findByG_F(
102                 context.getGroupId(),
103                 BookmarksFolderConstants.DEFAULT_PARENT_FOLDER_ID);
104 
105             for (BookmarksEntry entry : entries) {
106                 exportEntry(context, null, entriesEl, entry);
107             }
108 
109             return doc.formattedString();
110         }
111         catch (Exception e) {
112             throw new PortletDataException(e);
113         }
114     }
115 
116     public PortletDataHandlerControl[] getExportControls() {
117         return new PortletDataHandlerControl[] {_foldersAndEntries, _tags};
118     }
119 
120     public PortletDataHandlerControl[] getImportControls() {
121         return new PortletDataHandlerControl[] {_foldersAndEntries, _tags};
122     }
123 
124     public PortletPreferences importData(
125             PortletDataContext context, String portletId,
126             PortletPreferences preferences, String data)
127         throws PortletDataException {
128 
129         try {
130             Document doc = SAXReaderUtil.read(data);
131 
132             Element root = doc.getRootElement();
133 
134             List<Element> folderEls = root.element("folders").elements(
135                 "folder");
136 
137             Map<Long, Long> folderPKs =
138                 (Map<Long, Long>)context.getNewPrimaryKeysMap(
139                     BookmarksFolder.class);
140 
141             for (Element folderEl : folderEls) {
142                 String path = folderEl.attributeValue("path");
143 
144                 if (!context.isPathNotProcessed(path)) {
145                     continue;
146                 }
147 
148                 BookmarksFolder folder =
149                     (BookmarksFolder)context.getZipEntryAsObject(path);
150 
151                 importFolder(context, folderPKs, folder);
152             }
153 
154             List<Element> entryEls = root.element("entries").elements("entry");
155 
156             for (Element entryEl : entryEls) {
157                 String path = entryEl.attributeValue("path");
158 
159                 if (!context.isPathNotProcessed(path)) {
160                     continue;
161                 }
162 
163                 BookmarksEntry entry =
164                     (BookmarksEntry)context.getZipEntryAsObject(path);
165 
166                 importEntry(context, folderPKs, entry);
167             }
168 
169             return null;
170         }
171         catch (Exception e) {
172             throw new PortletDataException(e);
173         }
174     }
175 
176     protected void exportFolder(
177             PortletDataContext context, Element foldersEl, Element entriesEl,
178             BookmarksFolder folder)
179         throws PortalException, SystemException {
180 
181         if (context.isWithinDateRange(folder.getModifiedDate())) {
182             exportParentFolder(context, foldersEl, folder.getParentFolderId());
183 
184             String path = getFolderPath(context, folder);
185 
186             if (context.isPathNotProcessed(path)) {
187                 Element folderEl = foldersEl.addElement("folder");
188 
189                 folderEl.addAttribute("path", path);
190 
191                 folder.setUserUuid(folder.getUserUuid());
192 
193                 context.addZipEntry(path, folder);
194             }
195         }
196 
197         List<BookmarksEntry> entries = BookmarksEntryUtil.findByG_F(
198             folder.getGroupId(), folder.getFolderId());
199 
200         for (BookmarksEntry entry : entries) {
201             exportEntry(context, foldersEl, entriesEl, entry);
202         }
203     }
204 
205     protected void exportEntry(
206             PortletDataContext context, Element foldersEl, Element entriesEl,
207             BookmarksEntry entry)
208         throws PortalException, SystemException {
209 
210         if (!context.isWithinDateRange(entry.getModifiedDate())) {
211             return;
212         }
213 
214         if (foldersEl != null) {
215             exportParentFolder(context, foldersEl, entry.getFolderId());
216         }
217 
218         String path = getEntryPath(context, entry);
219 
220         if (context.isPathNotProcessed(path)) {
221             Element entryEl = entriesEl.addElement("entry");
222 
223             entryEl.addAttribute("path", path);
224 
225             if (context.getBooleanParameter(_NAMESPACE, "tags")) {
226                 context.addAssetTags(BookmarksEntry.class, entry.getEntryId());
227             }
228 
229             entry.setUserUuid(entry.getUserUuid());
230 
231             context.addZipEntry(path, entry);
232         }
233     }
234 
235     protected void exportParentFolder(
236             PortletDataContext context, Element foldersEl, long folderId)
237         throws PortalException, SystemException {
238 
239         if (folderId == BookmarksFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
240             return;
241         }
242 
243         BookmarksFolder folder = BookmarksFolderUtil.findByPrimaryKey(folderId);
244 
245         exportParentFolder(context, foldersEl, folder.getParentFolderId());
246 
247         String path = getFolderPath(context, folder);
248 
249         if (context.isPathNotProcessed(path)) {
250             Element folderEl = foldersEl.addElement("folder");
251 
252             folderEl.addAttribute("path", path);
253 
254             folder.setUserUuid(folder.getUserUuid());
255 
256             context.addZipEntry(path, folder);
257         }
258     }
259 
260     protected String getEntryPath(
261         PortletDataContext context, BookmarksEntry entry) {
262 
263         StringBundler sb = new StringBundler(4);
264 
265         sb.append(context.getPortletPath(PortletKeys.BOOKMARKS));
266         sb.append("/entries/");
267         sb.append(entry.getEntryId());
268         sb.append(".xml");
269 
270         return sb.toString();
271     }
272 
273     protected String getFolderPath(
274         PortletDataContext context, BookmarksFolder folder) {
275 
276         StringBundler sb = new StringBundler(4);
277 
278         sb.append(context.getPortletPath(PortletKeys.BOOKMARKS));
279         sb.append("/folders/");
280         sb.append(folder.getFolderId());
281         sb.append(".xml");
282 
283         return sb.toString();
284     }
285 
286     protected String getImportFolderPath(
287         PortletDataContext context, long folderId) {
288 
289         StringBundler sb = new StringBundler(4);
290 
291         sb.append(context.getSourcePortletPath(PortletKeys.BOOKMARKS));
292         sb.append("/folders/");
293         sb.append(folderId);
294         sb.append(".xml");
295 
296         return sb.toString();
297     }
298 
299     protected void importEntry(
300             PortletDataContext context, Map<Long, Long> folderPKs,
301             BookmarksEntry entry)
302         throws Exception {
303 
304         long userId = context.getUserId(entry.getUserUuid());
305         long groupId = context.getGroupId();
306         long folderId = MapUtil.getLong(
307             folderPKs, entry.getFolderId(), entry.getFolderId());
308 
309         String[] assetTagNames = null;
310 
311         if (context.getBooleanParameter(_NAMESPACE, "tags")) {
312             assetTagNames = context.getAssetTagNames(
313                 BookmarksEntry.class, entry.getEntryId());
314         }
315 
316         ServiceContext serviceContext = new ServiceContext();
317 
318         serviceContext.setAddCommunityPermissions(true);
319         serviceContext.setAddGuestPermissions(true);
320         serviceContext.setAssetTagNames(assetTagNames);
321 
322         if ((folderId != BookmarksFolderConstants.DEFAULT_PARENT_FOLDER_ID) &&
323             (folderId == entry.getFolderId())) {
324 
325             String path = getImportFolderPath(context, folderId);
326 
327             BookmarksFolder folder =
328                 (BookmarksFolder)context.getZipEntryAsObject(path);
329 
330             importFolder(context, folderPKs, folder);
331 
332             folderId = MapUtil.getLong(
333                 folderPKs, entry.getFolderId(), entry.getFolderId());
334         }
335 
336         BookmarksEntry existingEntry = null;
337 
338         try {
339             if (context.getDataStrategy().equals(
340                     PortletDataHandlerKeys.DATA_STRATEGY_MIRROR)) {
341 
342                 try {
343                     existingEntry = BookmarksEntryUtil.findByUUID_G(
344                         entry.getUuid(), groupId);
345 
346                     BookmarksEntryLocalServiceUtil.updateEntry(
347                         userId, existingEntry.getEntryId(), groupId, folderId,
348                         entry.getName(), entry.getUrl(), entry.getComments(),
349                         serviceContext);
350                 }
351                 catch (NoSuchEntryException nsee) {
352                     BookmarksEntryLocalServiceUtil.addEntry(
353                         entry.getUuid(), userId, groupId, folderId,
354                         entry.getName(), entry.getUrl(), entry.getComments(),
355                         serviceContext);
356                 }
357             }
358             else {
359                 BookmarksEntryLocalServiceUtil.addEntry(
360                     null, userId, groupId, folderId, entry.getName(),
361                     entry.getUrl(), entry.getComments(), serviceContext);
362             }
363         }
364         catch (NoSuchFolderException nsfe) {
365             _log.error(
366                 "Could not find the parent folder for entry " +
367                     entry.getEntryId());
368         }
369     }
370 
371     protected void importFolder(
372             PortletDataContext context, Map<Long, Long> folderPKs,
373             BookmarksFolder folder)
374         throws Exception {
375 
376         long userId = context.getUserId(folder.getUserUuid());
377         long parentFolderId = MapUtil.getLong(
378             folderPKs, folder.getParentFolderId(), folder.getParentFolderId());
379 
380         ServiceContext serviceContext = new ServiceContext();
381 
382         serviceContext.setAddCommunityPermissions(true);
383         serviceContext.setAddGuestPermissions(true);
384         serviceContext.setScopeGroupId(context.getScopeGroupId());
385 
386         if ((parentFolderId !=
387                 BookmarksFolderConstants.DEFAULT_PARENT_FOLDER_ID) &&
388             (parentFolderId == folder.getParentFolderId())) {
389 
390             String path = getImportFolderPath(context, parentFolderId);
391 
392             BookmarksFolder parentFolder =
393                 (BookmarksFolder)context.getZipEntryAsObject(path);
394 
395             importFolder(context, folderPKs, parentFolder);
396 
397             parentFolderId = MapUtil.getLong(
398                 folderPKs, folder.getParentFolderId(),
399                 folder.getParentFolderId());
400         }
401 
402         BookmarksFolder existingFolder = null;
403 
404         try {
405             if (parentFolderId !=
406                 BookmarksFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
407 
408                 BookmarksFolderUtil.findByPrimaryKey(parentFolderId);
409             }
410 
411             if (context.getDataStrategy().equals(
412                     PortletDataHandlerKeys.DATA_STRATEGY_MIRROR)) {
413                 existingFolder = BookmarksFolderUtil.fetchByUUID_G(
414                     folder.getUuid(), context.getGroupId());
415 
416                 if (existingFolder == null) {
417                     existingFolder = BookmarksFolderLocalServiceUtil.addFolder(
418                         folder.getUuid(), userId, parentFolderId,
419                         folder.getName(), folder.getDescription(),
420                         serviceContext);
421                 }
422                 else {
423                     existingFolder =
424                         BookmarksFolderLocalServiceUtil.updateFolder(
425                             existingFolder.getFolderId(), parentFolderId,
426                             folder.getName(), folder.getDescription(), false,
427                             serviceContext);
428                 }
429             }
430             else {
431                 existingFolder = BookmarksFolderLocalServiceUtil.addFolder(
432                     null, userId, parentFolderId, folder.getName(),
433                     folder.getDescription(), serviceContext);
434             }
435 
436             folderPKs.put(folder.getFolderId(), existingFolder.getFolderId());
437         }
438         catch (NoSuchFolderException nsfe) {
439             _log.error(
440                 "Could not find the parent folder for folder " +
441                     folder.getFolderId());
442         }
443     }
444 
445     private static final String _NAMESPACE = "bookmarks";
446 
447     private static final PortletDataHandlerBoolean _foldersAndEntries =
448         new PortletDataHandlerBoolean(
449             _NAMESPACE, "folders-and-entries", true, true);
450 
451     private static final PortletDataHandlerBoolean _tags =
452         new PortletDataHandlerBoolean(_NAMESPACE, "tags");
453 
454     private static Log _log = LogFactoryUtil.getLog(
455         BookmarksPortletDataHandlerImpl.class);
456 
457 }