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.BookmarksEntryFinderUtil;
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 implements PortletDataHandler {
66  
67      public PortletPreferences deleteData(
68              PortletDataContext context, String portletId,
69              PortletPreferences prefs)
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 prefs)
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 prefs, 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     public boolean isPublishToLiveByDefault() {
177         return false;
178     }
179 
180     protected void exportFolder(
181             PortletDataContext context, Element foldersEl, Element entriesEl,
182             BookmarksFolder folder)
183         throws PortalException, SystemException {
184 
185         if (context.isWithinDateRange(folder.getModifiedDate())) {
186             exportParentFolder(context, foldersEl, folder.getParentFolderId());
187 
188             String path = getFolderPath(context, folder);
189 
190             if (context.isPathNotProcessed(path)) {
191                 Element folderEl = foldersEl.addElement("folder");
192 
193                 folderEl.addAttribute("path", path);
194 
195                 folder.setUserUuid(folder.getUserUuid());
196 
197                 context.addZipEntry(path, folder);
198             }
199         }
200 
201         List<BookmarksEntry> entries = BookmarksEntryUtil.findByFolderId(
202             folder.getFolderId());
203 
204         for (BookmarksEntry entry : entries) {
205             exportEntry(context, foldersEl, entriesEl, entry);
206         }
207     }
208 
209     protected void exportEntry(
210             PortletDataContext context, Element foldersEl, Element entriesEl,
211             BookmarksEntry entry)
212         throws PortalException, SystemException {
213 
214         if (!context.isWithinDateRange(entry.getModifiedDate())) {
215             return;
216         }
217 
218         exportParentFolder(context, foldersEl, entry.getFolderId());
219 
220         String path = getEntryPath(context, entry);
221 
222         if (context.isPathNotProcessed(path)) {
223             Element entryEl = entriesEl.addElement("entry");
224 
225             entryEl.addAttribute("path", path);
226 
227             if (context.getBooleanParameter(_NAMESPACE, "tags")) {
228                 context.addTagsEntries(
229                     BookmarksEntry.class, entry.getEntryId());
230             }
231 
232             entry.setUserUuid(entry.getUserUuid());
233 
234             context.addZipEntry(path, entry);
235         }
236     }
237 
238     protected void exportParentFolder(
239             PortletDataContext context, Element foldersEl, long folderId)
240         throws PortalException, SystemException {
241 
242         if (folderId == BookmarksFolderImpl.DEFAULT_PARENT_FOLDER_ID) {
243             return;
244         }
245 
246         BookmarksFolder folder = BookmarksFolderUtil.findByPrimaryKey(folderId);
247 
248         exportParentFolder(context, foldersEl, folder.getParentFolderId());
249 
250         String path = getFolderPath(context, folder);
251 
252         if (context.isPathNotProcessed(path)) {
253             Element folderEl = foldersEl.addElement("folder");
254 
255             folderEl.addAttribute("path", path);
256 
257             folder.setUserUuid(folder.getUserUuid());
258 
259             context.addZipEntry(path, folder);
260         }
261     }
262 
263     protected String getEntryPath(
264         PortletDataContext context, BookmarksEntry entry) {
265 
266         StringBuilder sb = new StringBuilder();
267 
268         sb.append(context.getPortletPath(PortletKeys.BOOKMARKS));
269         sb.append("/entries/");
270         sb.append(entry.getEntryId());
271         sb.append(".xml");
272 
273         return sb.toString();
274     }
275 
276     protected String getFolderPath(
277         PortletDataContext context, BookmarksFolder folder) {
278 
279         StringBuilder sb = new StringBuilder();
280 
281         sb.append(context.getPortletPath(PortletKeys.BOOKMARKS));
282         sb.append("/folders/");
283         sb.append(folder.getFolderId());
284         sb.append(".xml");
285 
286         return sb.toString();
287     }
288 
289     protected String getImportFolderPath(
290         PortletDataContext context, long folderId) {
291 
292         StringBuilder sb = new StringBuilder();
293 
294         sb.append(context.getImportPortletPath(PortletKeys.BOOKMARKS));
295         sb.append("/folders/");
296         sb.append(folderId);
297         sb.append(".xml");
298 
299         return sb.toString();
300     }
301 
302     protected void importEntry(
303             PortletDataContext context, Map<Long, Long> folderPKs,
304             BookmarksEntry entry)
305         throws Exception {
306 
307         long userId = context.getUserId(entry.getUserUuid());
308         long folderId = MapUtil.getLong(
309             folderPKs, entry.getFolderId(), entry.getFolderId());
310 
311         String[] tagsEntries = null;
312 
313         if (context.getBooleanParameter(_NAMESPACE, "tags")) {
314             tagsEntries = context.getTagsEntries(
315                 BookmarksEntry.class, entry.getEntryId());
316         }
317 
318         boolean addCommunityPermissions = true;
319         boolean addGuestPermissions = true;
320 
321         if ((folderId != BookmarksFolderImpl.DEFAULT_PARENT_FOLDER_ID) &&
322             (folderId == entry.getFolderId())) {
323 
324             String path = getImportFolderPath(context, folderId);
325 
326             BookmarksFolder folder =
327                 (BookmarksFolder)context.getZipEntryAsObject(path);
328 
329             importFolder(context, folderPKs, folder);
330 
331             folderId = MapUtil.getLong(
332                 folderPKs, entry.getFolderId(), entry.getFolderId());
333         }
334 
335         BookmarksEntry existingEntry = null;
336 
337         try {
338             BookmarksFolderUtil.findByPrimaryKey(folderId);
339 
340             if (context.getDataStrategy().equals(
341                     PortletDataHandlerKeys.DATA_STRATEGY_MIRROR)) {
342 
343                 try {
344                     existingEntry = BookmarksEntryFinderUtil.findByUuid_G(
345                         entry.getUuid(), context.getGroupId());
346 
347                     BookmarksEntryLocalServiceUtil.updateEntry(
348                         userId, existingEntry.getEntryId(), folderId,
349                         entry.getName(), entry.getUrl(), entry.getComments(),
350                         tagsEntries);
351                 }
352                 catch (NoSuchEntryException nsee) {
353                     BookmarksEntryLocalServiceUtil.addEntry(
354                         entry.getUuid(), userId, folderId, entry.getName(),
355                         entry.getUrl(), entry.getComments(), tagsEntries,
356                         addCommunityPermissions, addGuestPermissions);
357                 }
358             }
359             else {
360                 BookmarksEntryLocalServiceUtil.addEntry(
361                     userId, folderId, entry.getName(), entry.getUrl(),
362                     entry.getComments(), tagsEntries, addCommunityPermissions,
363                     addGuestPermissions);
364             }
365         }
366         catch (NoSuchFolderException nsfe) {
367             _log.error(
368                 "Could not find the parent folder for entry " +
369                     entry.getEntryId());
370         }
371     }
372 
373     protected void importFolder(
374             PortletDataContext context, Map<Long, Long> folderPKs,
375             BookmarksFolder folder)
376         throws Exception {
377 
378         long userId = context.getUserId(folder.getUserUuid());
379         long plid = context.getPlid();
380         long parentFolderId = MapUtil.getLong(
381             folderPKs, folder.getParentFolderId(), folder.getParentFolderId());
382 
383         boolean addCommunityPermissions = true;
384         boolean addGuestPermissions = true;
385 
386         if ((parentFolderId != BookmarksFolderImpl.DEFAULT_PARENT_FOLDER_ID) &&
387             (parentFolderId == folder.getParentFolderId())) {
388 
389             String path = getImportFolderPath(context, parentFolderId);
390 
391             BookmarksFolder parentFolder =
392                 (BookmarksFolder)context.getZipEntryAsObject(path);
393 
394             importFolder(context, folderPKs, parentFolder);
395 
396             parentFolderId = MapUtil.getLong(
397                 folderPKs, folder.getParentFolderId(),
398                 folder.getParentFolderId());
399         }
400 
401         BookmarksFolder existingFolder = null;
402 
403         try {
404             if (parentFolderId !=
405                     BookmarksFolderImpl.DEFAULT_PARENT_FOLDER_ID) {
406 
407                 BookmarksFolderUtil.findByPrimaryKey(parentFolderId);
408             }
409 
410             if (context.getDataStrategy().equals(
411                     PortletDataHandlerKeys.DATA_STRATEGY_MIRROR)) {
412                 existingFolder = BookmarksFolderUtil.fetchByUUID_G(
413                     folder.getUuid(), context.getGroupId());
414 
415                 if (existingFolder == null) {
416                     existingFolder = BookmarksFolderLocalServiceUtil.addFolder(
417                         folder.getUuid(), userId, plid, parentFolderId,
418                         folder.getName(), folder.getDescription(),
419                         addCommunityPermissions, addGuestPermissions);
420                 }
421                 else {
422                     existingFolder =
423                         BookmarksFolderLocalServiceUtil.updateFolder(
424                             existingFolder.getFolderId(), parentFolderId,
425                             folder.getName(), folder.getDescription(), false);
426                 }
427             }
428             else {
429                 existingFolder = BookmarksFolderLocalServiceUtil.addFolder(
430                     userId, plid, parentFolderId, folder.getName(),
431                     folder.getDescription(), addCommunityPermissions,
432                     addGuestPermissions);
433             }
434 
435             folderPKs.put(folder.getFolderId(), existingFolder.getFolderId());
436         }
437         catch (NoSuchFolderException nsfe) {
438             _log.error(
439                 "Could not find the parent folder for folder " +
440                     folder.getFolderId());
441         }
442     }
443 
444     private static final String _NAMESPACE = "bookmarks";
445 
446     private static final PortletDataHandlerBoolean _foldersAndEntries =
447         new PortletDataHandlerBoolean(
448             _NAMESPACE, "folders-and-entries", true, true);
449 
450     private static final PortletDataHandlerBoolean _tags =
451         new PortletDataHandlerBoolean(_NAMESPACE, "tags");
452 
453     private static Log _log =
454         LogFactoryUtil.getLog(BookmarksPortletDataHandlerImpl.class);
455 
456 }