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.BasePortletDataHandler;
34  import com.liferay.portal.lar.PortletDataContext;
35  import com.liferay.portal.lar.PortletDataException;
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.service.ServiceContext;
40  import com.liferay.portal.util.PortletKeys;
41  import com.liferay.portlet.bookmarks.NoSuchEntryException;
42  import com.liferay.portlet.bookmarks.NoSuchFolderException;
43  import com.liferay.portlet.bookmarks.model.BookmarksEntry;
44  import com.liferay.portlet.bookmarks.model.BookmarksFolder;
45  import com.liferay.portlet.bookmarks.model.impl.BookmarksFolderImpl;
46  import com.liferay.portlet.bookmarks.service.BookmarksEntryLocalServiceUtil;
47  import com.liferay.portlet.bookmarks.service.BookmarksFolderLocalServiceUtil;
48  import com.liferay.portlet.bookmarks.service.persistence.BookmarksEntryUtil;
49  import com.liferay.portlet.bookmarks.service.persistence.BookmarksFolderUtil;
50  
51  import java.util.List;
52  import java.util.Map;
53  
54  import javax.portlet.PortletPreferences;
55  
56  /**
57   * <a href="BookmarksPortletDataHandlerImpl.java.html"><b><i>View Source</i></b>
58   * </a>
59   *
60   * @author Jorge Ferrer
61   * @author Bruno Farache
62   * @author Raymond Augé
63   */
64  public class BookmarksPortletDataHandlerImpl extends BasePortletDataHandler {
65  
66      public PortletPreferences deleteData(
67              PortletDataContext context, String portletId,
68              PortletPreferences preferences)
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 preferences)
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 preferences, 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     protected void exportFolder(
176             PortletDataContext context, Element foldersEl, Element entriesEl,
177             BookmarksFolder folder)
178         throws PortalException, SystemException {
179 
180         if (context.isWithinDateRange(folder.getModifiedDate())) {
181             exportParentFolder(context, foldersEl, folder.getParentFolderId());
182 
183             String path = getFolderPath(context, folder);
184 
185             if (context.isPathNotProcessed(path)) {
186                 Element folderEl = foldersEl.addElement("folder");
187 
188                 folderEl.addAttribute("path", path);
189 
190                 folder.setUserUuid(folder.getUserUuid());
191 
192                 context.addZipEntry(path, folder);
193             }
194         }
195 
196         List<BookmarksEntry> entries = BookmarksEntryUtil.findByFolderId(
197             folder.getFolderId());
198 
199         for (BookmarksEntry entry : entries) {
200             exportEntry(context, foldersEl, entriesEl, entry);
201         }
202     }
203 
204     protected void exportEntry(
205             PortletDataContext context, Element foldersEl, Element entriesEl,
206             BookmarksEntry entry)
207         throws PortalException, SystemException {
208 
209         if (!context.isWithinDateRange(entry.getModifiedDate())) {
210             return;
211         }
212 
213         exportParentFolder(context, foldersEl, entry.getFolderId());
214 
215         String path = getEntryPath(context, entry);
216 
217         if (context.isPathNotProcessed(path)) {
218             Element entryEl = entriesEl.addElement("entry");
219 
220             entryEl.addAttribute("path", path);
221 
222             if (context.getBooleanParameter(_NAMESPACE, "tags")) {
223                 context.addTagsEntries(
224                     BookmarksEntry.class, entry.getEntryId());
225             }
226 
227             entry.setUserUuid(entry.getUserUuid());
228 
229             context.addZipEntry(path, entry);
230         }
231     }
232 
233     protected void exportParentFolder(
234             PortletDataContext context, Element foldersEl, long folderId)
235         throws PortalException, SystemException {
236 
237         if (folderId == BookmarksFolderImpl.DEFAULT_PARENT_FOLDER_ID) {
238             return;
239         }
240 
241         BookmarksFolder folder = BookmarksFolderUtil.findByPrimaryKey(folderId);
242 
243         exportParentFolder(context, foldersEl, folder.getParentFolderId());
244 
245         String path = getFolderPath(context, folder);
246 
247         if (context.isPathNotProcessed(path)) {
248             Element folderEl = foldersEl.addElement("folder");
249 
250             folderEl.addAttribute("path", path);
251 
252             folder.setUserUuid(folder.getUserUuid());
253 
254             context.addZipEntry(path, folder);
255         }
256     }
257 
258     protected String getEntryPath(
259         PortletDataContext context, BookmarksEntry entry) {
260 
261         StringBuilder sb = new StringBuilder();
262 
263         sb.append(context.getPortletPath(PortletKeys.BOOKMARKS));
264         sb.append("/entries/");
265         sb.append(entry.getEntryId());
266         sb.append(".xml");
267 
268         return sb.toString();
269     }
270 
271     protected String getFolderPath(
272         PortletDataContext context, BookmarksFolder folder) {
273 
274         StringBuilder sb = new StringBuilder();
275 
276         sb.append(context.getPortletPath(PortletKeys.BOOKMARKS));
277         sb.append("/folders/");
278         sb.append(folder.getFolderId());
279         sb.append(".xml");
280 
281         return sb.toString();
282     }
283 
284     protected String getImportFolderPath(
285         PortletDataContext context, long folderId) {
286 
287         StringBuilder sb = new StringBuilder();
288 
289         sb.append(context.getSourcePortletPath(PortletKeys.BOOKMARKS));
290         sb.append("/folders/");
291         sb.append(folderId);
292         sb.append(".xml");
293 
294         return sb.toString();
295     }
296 
297     protected void importEntry(
298             PortletDataContext context, Map<Long, Long> folderPKs,
299             BookmarksEntry entry)
300         throws Exception {
301 
302         long userId = context.getUserId(entry.getUserUuid());
303         long folderId = MapUtil.getLong(
304             folderPKs, entry.getFolderId(), entry.getFolderId());
305 
306         String[] tagsEntries = null;
307 
308         if (context.getBooleanParameter(_NAMESPACE, "tags")) {
309             tagsEntries = context.getTagsEntries(
310                 BookmarksEntry.class, entry.getEntryId());
311         }
312 
313         ServiceContext serviceContext = new ServiceContext();
314 
315         serviceContext.setAddCommunityPermissions(true);
316         serviceContext.setAddGuestPermissions(true);
317         serviceContext.setTagsEntries(tagsEntries);
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                         serviceContext);
349                 }
350                 catch (NoSuchEntryException nsee) {
351                     BookmarksEntryLocalServiceUtil.addEntry(
352                         entry.getUuid(), userId, folderId, entry.getName(),
353                         entry.getUrl(), entry.getComments(), serviceContext);
354                 }
355             }
356             else {
357                 BookmarksEntryLocalServiceUtil.addEntry(
358                     userId, folderId, entry.getName(), entry.getUrl(),
359                     entry.getComments(), serviceContext);
360             }
361         }
362         catch (NoSuchFolderException nsfe) {
363             _log.error(
364                 "Could not find the parent folder for entry " +
365                     entry.getEntryId());
366         }
367     }
368 
369     protected void importFolder(
370             PortletDataContext context, Map<Long, Long> folderPKs,
371             BookmarksFolder folder)
372         throws Exception {
373 
374         long userId = context.getUserId(folder.getUserUuid());
375         long parentFolderId = MapUtil.getLong(
376             folderPKs, folder.getParentFolderId(), folder.getParentFolderId());
377 
378         ServiceContext serviceContext = new ServiceContext();
379 
380         serviceContext.setAddCommunityPermissions(true);
381         serviceContext.setAddGuestPermissions(true);
382         serviceContext.setScopeGroupId(context.getScopeGroupId());
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, parentFolderId,
416                         folder.getName(), folder.getDescription(),
417                         serviceContext);
418                 }
419                 else {
420                     existingFolder =
421                         BookmarksFolderLocalServiceUtil.updateFolder(
422                             existingFolder.getFolderId(), parentFolderId,
423                             folder.getName(), folder.getDescription(), false,
424                             serviceContext);
425                 }
426             }
427             else {
428                 existingFolder = BookmarksFolderLocalServiceUtil.addFolder(
429                     userId, parentFolderId, folder.getName(),
430                     folder.getDescription(), serviceContext);
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 }