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