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   */
65  public class BookmarksPortletDataHandlerImpl extends BasePortletDataHandler {
66  
67      public PortletPreferences deleteData(
68              PortletDataContext context, String portletId,
69              PortletPreferences preferences)
70          throws PortletDataException {
71  
72          try {
73              if (!context.addPrimaryKey(
74                      BookmarksPortletDataHandlerImpl.class, "deleteData")) {
75  
76                  BookmarksFolderLocalServiceUtil.deleteFolders(
77                      context.getGroupId());
78              }
79  
80              return null;
81          }
82          catch (Exception e) {
83              throw new PortletDataException(e);
84          }
85      }
86  
87      public String exportData(
88              PortletDataContext context, String portletId,
89              PortletPreferences preferences)
90          throws PortletDataException {
91  
92          try {
93              Document doc = SAXReaderUtil.createDocument();
94  
95              Element root = doc.addElement("bookmarks-data");
96  
97              root.addAttribute("group-id", String.valueOf(context.getGroupId()));
98  
99              Element foldersEl = root.addElement("folders");
100             Element entriesEl = root.addElement("entries");
101 
102             List<BookmarksFolder> folders = BookmarksFolderUtil.findByGroupId(
103                 context.getGroupId());
104 
105             for (BookmarksFolder folder : folders) {
106                 exportFolder(context, foldersEl, entriesEl, folder);
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.findByFolderId(
198             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         exportParentFolder(context, foldersEl, entry.getFolderId());
215 
216         String path = getEntryPath(context, entry);
217 
218         if (context.isPathNotProcessed(path)) {
219             Element entryEl = entriesEl.addElement("entry");
220 
221             entryEl.addAttribute("path", path);
222 
223             if (context.getBooleanParameter(_NAMESPACE, "tags")) {
224                 context.addTagsEntries(
225                     BookmarksEntry.class, entry.getEntryId());
226             }
227 
228             entry.setUserUuid(entry.getUserUuid());
229 
230             context.addZipEntry(path, entry);
231         }
232     }
233 
234     protected void exportParentFolder(
235             PortletDataContext context, Element foldersEl, long folderId)
236         throws PortalException, SystemException {
237 
238         if (folderId == BookmarksFolderImpl.DEFAULT_PARENT_FOLDER_ID) {
239             return;
240         }
241 
242         BookmarksFolder folder = BookmarksFolderUtil.findByPrimaryKey(folderId);
243 
244         exportParentFolder(context, foldersEl, folder.getParentFolderId());
245 
246         String path = getFolderPath(context, folder);
247 
248         if (context.isPathNotProcessed(path)) {
249             Element folderEl = foldersEl.addElement("folder");
250 
251             folderEl.addAttribute("path", path);
252 
253             folder.setUserUuid(folder.getUserUuid());
254 
255             context.addZipEntry(path, folder);
256         }
257     }
258 
259     protected String getEntryPath(
260         PortletDataContext context, BookmarksEntry entry) {
261 
262         StringBuilder sb = new StringBuilder();
263 
264         sb.append(context.getPortletPath(PortletKeys.BOOKMARKS));
265         sb.append("/entries/");
266         sb.append(entry.getEntryId());
267         sb.append(".xml");
268 
269         return sb.toString();
270     }
271 
272     protected String getFolderPath(
273         PortletDataContext context, BookmarksFolder folder) {
274 
275         StringBuilder sb = new StringBuilder();
276 
277         sb.append(context.getPortletPath(PortletKeys.BOOKMARKS));
278         sb.append("/folders/");
279         sb.append(folder.getFolderId());
280         sb.append(".xml");
281 
282         return sb.toString();
283     }
284 
285     protected String getImportFolderPath(
286         PortletDataContext context, long folderId) {
287 
288         StringBuilder sb = new StringBuilder();
289 
290         sb.append(context.getSourcePortletPath(PortletKeys.BOOKMARKS));
291         sb.append("/folders/");
292         sb.append(folderId);
293         sb.append(".xml");
294 
295         return sb.toString();
296     }
297 
298     protected void importEntry(
299             PortletDataContext context, Map<Long, Long> folderPKs,
300             BookmarksEntry entry)
301         throws Exception {
302 
303         long userId = context.getUserId(entry.getUserUuid());
304         long folderId = MapUtil.getLong(
305             folderPKs, entry.getFolderId(), entry.getFolderId());
306 
307         String[] tagsEntries = null;
308 
309         if (context.getBooleanParameter(_NAMESPACE, "tags")) {
310             tagsEntries = context.getTagsEntries(
311                 BookmarksEntry.class, entry.getEntryId());
312         }
313 
314         ServiceContext serviceContext = new ServiceContext();
315 
316         serviceContext.setAddCommunityPermissions(true);
317         serviceContext.setAddGuestPermissions(true);
318         serviceContext.setTagsEntries(tagsEntries);
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                         serviceContext);
350                 }
351                 catch (NoSuchEntryException nsee) {
352                     BookmarksEntryLocalServiceUtil.addEntry(
353                         entry.getUuid(), userId, folderId, entry.getName(),
354                         entry.getUrl(), entry.getComments(), serviceContext);
355                 }
356             }
357             else {
358                 BookmarksEntryLocalServiceUtil.addEntry(
359                     userId, folderId, entry.getName(), entry.getUrl(),
360                     entry.getComments(), serviceContext);
361             }
362         }
363         catch (NoSuchFolderException nsfe) {
364             _log.error(
365                 "Could not find the parent folder for entry " +
366                     entry.getEntryId());
367         }
368     }
369 
370     protected void importFolder(
371             PortletDataContext context, Map<Long, Long> folderPKs,
372             BookmarksFolder folder)
373         throws Exception {
374 
375         long userId = context.getUserId(folder.getUserUuid());
376         long parentFolderId = MapUtil.getLong(
377             folderPKs, folder.getParentFolderId(), folder.getParentFolderId());
378 
379         ServiceContext serviceContext = new ServiceContext();
380 
381         serviceContext.setAddCommunityPermissions(true);
382         serviceContext.setAddGuestPermissions(true);
383         serviceContext.setScopeGroupId(context.getScopeGroupId());
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, parentFolderId,
417                         folder.getName(), folder.getDescription(),
418                         serviceContext);
419                 }
420                 else {
421                     existingFolder =
422                         BookmarksFolderLocalServiceUtil.updateFolder(
423                             existingFolder.getFolderId(), parentFolderId,
424                             folder.getName(), folder.getDescription(), false,
425                             serviceContext);
426                 }
427             }
428             else {
429                 existingFolder = BookmarksFolderLocalServiceUtil.addFolder(
430                     userId, parentFolderId, folder.getName(),
431                     folder.getDescription(), serviceContext);
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 }