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