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