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