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             String path = getFolderPath(context, folder);
188 
189             if (context.isPathNotProcessed(path)) {
190                 Element folderEl = foldersEl.addElement("folder");
191 
192                 folderEl.addAttribute("path", path);
193 
194                 folder.setUserUuid(folder.getUserUuid());
195 
196                 context.addZipEntry(path, folder);
197             }
198 
199             exportParentFolder(context, foldersEl, folder.getParentFolderId());
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         String path = getEntryPath(context, entry);
220 
221         if (context.isPathNotProcessed(path)) {
222             Element entryEl = entriesEl.addElement("entry");
223 
224             entryEl.addAttribute("path", path);
225 
226             if (context.getBooleanParameter(_NAMESPACE, "tags")) {
227                 context.addTagsEntries(
228                     BookmarksEntry.class, entry.getEntryId());
229             }
230 
231             entry.setUserUuid(entry.getUserUuid());
232 
233             context.addZipEntry(path, entry);
234         }
235 
236         exportParentFolder(context, foldersEl, entry.getFolderId());
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         String path = getFolderPath(context, folder);
250 
251         if (context.isPathNotProcessed(path)) {
252             Element folderEl = foldersEl.addElement("folder");
253 
254             folderEl.addAttribute("path", path);
255 
256             folder.setUserUuid(folder.getUserUuid());
257 
258             context.addZipEntry(path, folder);
259         }
260 
261         exportParentFolder(context, foldersEl, folder.getParentFolderId());
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 void importEntry(
291             PortletDataContext context, Map<Long, Long> folderPKs,
292             BookmarksEntry entry)
293         throws Exception {
294 
295         long userId = context.getUserId(entry.getUserUuid());
296         long folderId = MapUtil.getLong(
297             folderPKs, entry.getFolderId(), entry.getFolderId());
298 
299         String[] tagsEntries = null;
300 
301         if (context.getBooleanParameter(_NAMESPACE, "tags")) {
302             tagsEntries = context.getTagsEntries(
303                 BookmarksEntry.class, entry.getEntryId());
304         }
305 
306         boolean addCommunityPermissions = true;
307         boolean addGuestPermissions = true;
308 
309         BookmarksEntry existingEntry = null;
310 
311         try {
312             BookmarksFolderUtil.findByPrimaryKey(folderId);
313 
314             if (context.getDataStrategy().equals(
315                     PortletDataHandlerKeys.DATA_STRATEGY_MIRROR)) {
316 
317                 try {
318                     existingEntry = BookmarksEntryFinderUtil.findByUuid_G(
319                         entry.getUuid(), context.getGroupId());
320 
321                     BookmarksEntryLocalServiceUtil.updateEntry(
322                         userId, existingEntry.getEntryId(), folderId,
323                         entry.getName(), entry.getUrl(), entry.getComments(),
324                         tagsEntries);
325                 }
326                 catch (NoSuchEntryException nsee) {
327                     BookmarksEntryLocalServiceUtil.addEntry(
328                         entry.getUuid(), userId, folderId, entry.getName(),
329                         entry.getUrl(), entry.getComments(), tagsEntries,
330                         addCommunityPermissions, addGuestPermissions);
331                 }
332             }
333             else {
334                 BookmarksEntryLocalServiceUtil.addEntry(
335                     userId, folderId, entry.getName(), entry.getUrl(),
336                     entry.getComments(), tagsEntries, addCommunityPermissions,
337                     addGuestPermissions);
338             }
339         }
340         catch (NoSuchFolderException nsfe) {
341             _log.error(
342                 "Could not find the parent folder for entry " +
343                     entry.getEntryId());
344         }
345     }
346 
347     protected void importFolder(
348             PortletDataContext context, Map<Long, Long> folderPKs,
349             BookmarksFolder folder)
350         throws Exception {
351 
352         long userId = context.getUserId(folder.getUserUuid());
353         long plid = context.getPlid();
354         long parentFolderId = MapUtil.getLong(
355             folderPKs, folder.getParentFolderId(), folder.getParentFolderId());
356 
357         boolean addCommunityPermissions = true;
358         boolean addGuestPermissions = true;
359 
360         BookmarksFolder existingFolder = null;
361 
362         try {
363             if (parentFolderId !=
364                     BookmarksFolderImpl.DEFAULT_PARENT_FOLDER_ID) {
365 
366                 BookmarksFolderUtil.findByPrimaryKey(parentFolderId);
367             }
368 
369             if (context.getDataStrategy().equals(
370                     PortletDataHandlerKeys.DATA_STRATEGY_MIRROR)) {
371                 existingFolder = BookmarksFolderUtil.fetchByUUID_G(
372                     folder.getUuid(), context.getGroupId());
373 
374                 if (existingFolder == null) {
375                     existingFolder = BookmarksFolderLocalServiceUtil.addFolder(
376                         folder.getUuid(), userId, plid, parentFolderId,
377                         folder.getName(), folder.getDescription(),
378                         addCommunityPermissions, addGuestPermissions);
379                 }
380                 else {
381                     existingFolder =
382                         BookmarksFolderLocalServiceUtil.updateFolder(
383                             existingFolder.getFolderId(), parentFolderId,
384                             folder.getName(), folder.getDescription(), false);
385                 }
386             }
387             else {
388                 existingFolder = BookmarksFolderLocalServiceUtil.addFolder(
389                     userId, plid, parentFolderId, folder.getName(),
390                     folder.getDescription(), addCommunityPermissions,
391                     addGuestPermissions);
392             }
393 
394             folderPKs.put(folder.getFolderId(), existingFolder.getFolderId());
395         }
396         catch (NoSuchFolderException nsfe) {
397             _log.error(
398                 "Could not find the parent folder for folder " +
399                     folder.getFolderId());
400         }
401     }
402 
403     private static final String _NAMESPACE = "bookmarks";
404 
405     private static final PortletDataHandlerBoolean _foldersAndEntries =
406         new PortletDataHandlerBoolean(
407             _NAMESPACE, "folders-and-entries", true, true);
408 
409     private static final PortletDataHandlerBoolean _tags =
410         new PortletDataHandlerBoolean(_NAMESPACE, "tags");
411 
412     private static Log _log =
413         LogFactory.getLog(BookmarksPortletDataHandlerImpl.class);
414 
415 }