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.wiki.lar;
24  
25  import com.liferay.documentlibrary.service.DLServiceUtil;
26  import com.liferay.portal.PortalException;
27  import com.liferay.portal.SystemException;
28  import com.liferay.portal.kernel.log.Log;
29  import com.liferay.portal.kernel.log.LogFactoryUtil;
30  import com.liferay.portal.kernel.util.ObjectValuePair;
31  import com.liferay.portal.kernel.util.StringPool;
32  import com.liferay.portal.kernel.xml.Document;
33  import com.liferay.portal.kernel.xml.Element;
34  import com.liferay.portal.kernel.xml.SAXReaderUtil;
35  import com.liferay.portal.lar.BasePortletDataHandler;
36  import com.liferay.portal.lar.PortletDataContext;
37  import com.liferay.portal.lar.PortletDataException;
38  import com.liferay.portal.lar.PortletDataHandlerBoolean;
39  import com.liferay.portal.lar.PortletDataHandlerControl;
40  import com.liferay.portal.lar.PortletDataHandlerKeys;
41  import com.liferay.portal.model.CompanyConstants;
42  import com.liferay.portal.service.ServiceContext;
43  import com.liferay.portal.util.PortletKeys;
44  import com.liferay.portal.util.PropsKeys;
45  import com.liferay.portal.util.PropsUtil;
46  import com.liferay.portlet.wiki.NoSuchNodeException;
47  import com.liferay.portlet.wiki.NoSuchPageException;
48  import com.liferay.portlet.wiki.model.WikiNode;
49  import com.liferay.portlet.wiki.model.WikiPage;
50  import com.liferay.portlet.wiki.service.WikiNodeLocalServiceUtil;
51  import com.liferay.portlet.wiki.service.WikiPageLocalServiceUtil;
52  import com.liferay.portlet.wiki.service.persistence.WikiNodeUtil;
53  import com.liferay.portlet.wiki.service.persistence.WikiPageFinderUtil;
54  import com.liferay.portlet.wiki.service.persistence.WikiPageUtil;
55  import com.liferay.util.MapUtil;
56  
57  import java.util.ArrayList;
58  import java.util.List;
59  import java.util.Map;
60  
61  import javax.portlet.PortletPreferences;
62  
63  /**
64   * <a href="WikiPortletDataHandlerImpl.java.html"><b><i>View Source</i></b></a>
65   *
66   * @author Bruno Farache
67   * @author Jorge Ferrer
68   *
69   */
70  public class WikiPortletDataHandlerImpl extends BasePortletDataHandler {
71  
72      public PortletPreferences deleteData(
73              PortletDataContext context, String portletId,
74              PortletPreferences preferences)
75          throws PortletDataException {
76  
77          try {
78              if (!context.addPrimaryKey(
79                      WikiPortletDataHandlerImpl.class, "deleteData")) {
80  
81                  WikiNodeLocalServiceUtil.deleteNodes(context.getGroupId());
82              }
83              return null;
84          }
85          catch (Exception e) {
86              throw new PortletDataException(e);
87          }
88      }
89  
90      public String exportData(
91              PortletDataContext context, String portletId,
92              PortletPreferences preferences)
93          throws PortletDataException {
94  
95          try {
96              Document doc = SAXReaderUtil.createDocument();
97  
98              Element root = doc.addElement("wiki-data");
99  
100             root.addAttribute("group-id", String.valueOf(context.getGroupId()));
101 
102             Element nodesEl = root.addElement("nodes");
103             Element pagesEl = root.addElement("pages");
104 
105             List<WikiNode> nodes = WikiNodeUtil.findByGroupId(
106                 context.getGroupId());
107 
108             for (WikiNode node : nodes) {
109                 exportNode(context, nodesEl, pagesEl, node);
110             }
111 
112             return doc.formattedString();
113         }
114         catch (Exception e) {
115             throw new PortletDataException(e);
116         }
117     }
118 
119     public PortletDataHandlerControl[] getExportControls() {
120         return new PortletDataHandlerControl[] {
121             _nodesAndPages, _attachments, _categories, _comments, _tags
122         };
123     }
124 
125     public PortletDataHandlerControl[] getImportControls() {
126         return new PortletDataHandlerControl[] {
127             _nodesAndPages, _attachments, _categories, _comments, _tags
128         };
129     }
130 
131     public PortletPreferences importData(
132             PortletDataContext context, String portletId,
133             PortletPreferences preferences, String data)
134         throws PortletDataException {
135 
136         try {
137             Document doc = SAXReaderUtil.read(data);
138 
139             Element root = doc.getRootElement();
140 
141             List<Element> nodeEls = root.element("nodes").elements("node");
142 
143             Map<Long, Long> nodePKs =
144                 (Map<Long, Long>)context.getNewPrimaryKeysMap(WikiNode.class);
145 
146             for (Element nodeEl : nodeEls) {
147                 String path = nodeEl.attributeValue("path");
148 
149                 if (!context.isPathNotProcessed(path)) {
150                     continue;
151                 }
152 
153                 WikiNode node = (WikiNode)context.getZipEntryAsObject(path);
154 
155                 importNode(context, nodePKs, node);
156             }
157 
158             List<Element> pageEls = root.element("pages").elements("page");
159 
160             for (Element pageEl : pageEls) {
161                 String path = pageEl.attributeValue("path");
162 
163                 if (!context.isPathNotProcessed(path)) {
164                     continue;
165                 }
166 
167                 WikiPage page = (WikiPage)context.getZipEntryAsObject(path);
168 
169                 importPage(context, nodePKs, pageEl, page);
170             }
171 
172             return null;
173         }
174         catch (Exception e) {
175             throw new PortletDataException(e);
176         }
177     }
178 
179     protected void exportNode(
180             PortletDataContext context, Element nodesEl, Element pagesEl,
181             WikiNode node)
182         throws PortalException, SystemException {
183 
184         if (context.isWithinDateRange(node.getModifiedDate())) {
185             String path = getNodePath(context, node);
186 
187             if (context.isPathNotProcessed(path)) {
188                 Element nodeEl = nodesEl.addElement("node");
189 
190                 nodeEl.addAttribute("path", path);
191 
192                 node.setUserUuid(node.getUserUuid());
193 
194                 context.addZipEntry(path, node);
195             }
196         }
197 
198         List<WikiPage> nodePages = WikiPageUtil.findByNodeId(node.getNodeId());
199 
200         for (WikiPage page : nodePages) {
201             exportPage(context, nodesEl, pagesEl, page);
202         }
203     }
204 
205     protected void exportNode(
206             PortletDataContext context, Element nodesEl, long nodeId)
207         throws PortalException, SystemException {
208 
209         if (!context.hasDateRange()) {
210             return;
211         }
212 
213         WikiNode node = WikiNodeUtil.findByPrimaryKey(nodeId);
214 
215         String path = getNodePath(context, node);
216 
217         if (!context.isPathNotProcessed(path)) {
218             return;
219         }
220 
221         Element nodeEl = nodesEl.addElement("node");
222 
223         nodeEl.addAttribute("path", path);
224 
225         node.setUserUuid(node.getUserUuid());
226 
227         context.addZipEntry(path, node);
228     }
229 
230     protected void exportPage(
231             PortletDataContext context, Element nodesEl, Element pagesEl,
232             WikiPage page)
233         throws PortalException, SystemException {
234 
235         if (!context.isWithinDateRange(page.getModifiedDate())) {
236             return;
237         }
238 
239         String path = getPagePath(context, page);
240 
241         if (context.isPathNotProcessed(path)) {
242             Element pageEl = pagesEl.addElement("page");
243 
244             pageEl.addAttribute("path", path);
245 
246             page.setUserUuid(page.getUserUuid());
247 
248             if (context.getBooleanParameter(_NAMESPACE, "categories")) {
249                 context.addTagsCategories(
250                     WikiPage.class, page.getResourcePrimKey());
251             }
252 
253             if (context.getBooleanParameter(_NAMESPACE, "comments")) {
254                 context.addComments(WikiPage.class, page.getResourcePrimKey());
255             }
256 
257             if (context.getBooleanParameter(_NAMESPACE, "tags")) {
258                 context.addTagsEntries(
259                     WikiPage.class, page.getResourcePrimKey());
260             }
261 
262             if (context.getBooleanParameter(_NAMESPACE, "attachments") &&
263                 page.isHead()) {
264 
265                 for (String attachment : page.getAttachmentsFiles()) {
266                     int pos = attachment.lastIndexOf(StringPool.SLASH);
267 
268                     String name = attachment.substring(pos + 1);
269                     String binPath = getPageAttachementBinPath(
270                         context, page, name);
271 
272                     Element attachmentEl = pageEl.addElement("attachment");
273 
274                     attachmentEl.addAttribute("name", name);
275                     attachmentEl.addAttribute("bin-path", binPath);
276 
277                     byte[] bytes = DLServiceUtil.getFile(
278                         context.getCompanyId(), CompanyConstants.SYSTEM,
279                         attachment);
280 
281                     context.addZipEntry(binPath, bytes);
282                 }
283 
284                 page.setAttachmentsDir(page.getAttachmentsDir());
285             }
286 
287             context.addZipEntry(path, page);
288         }
289 
290         exportNode(context, nodesEl, page.getNodeId());
291     }
292 
293     protected void importNode(
294             PortletDataContext context, Map<Long, Long> nodePKs, WikiNode node)
295         throws Exception {
296 
297         long userId = context.getUserId(node.getUserUuid());
298 
299         ServiceContext serviceContext = new ServiceContext();
300 
301         serviceContext.setAddCommunityPermissions(true);
302         serviceContext.setAddGuestPermissions(true);
303         serviceContext.setScopeGroupId(context.getGroupId());
304 
305         WikiNode existingNode = null;
306 
307         if (context.getDataStrategy().equals(
308                 PortletDataHandlerKeys.DATA_STRATEGY_MIRROR)) {
309 
310             existingNode = WikiNodeUtil.fetchByUUID_G(
311                 node.getUuid(), context.getGroupId());
312 
313             String nodeName = PropsUtil.get(PropsKeys.WIKI_INITIAL_NODE_NAME);
314 
315             if (existingNode == null && node.getName().equals(nodeName)) {
316                 try {
317                     WikiNodeUtil.removeByG_N(
318                         context.getGroupId(), node.getName());
319                 }
320                 catch (NoSuchNodeException nsne) {
321                 }
322             }
323 
324             if (existingNode == null) {
325                 existingNode = WikiNodeLocalServiceUtil.addNode(
326                     node.getUuid(), userId, node.getName(),
327                     node.getDescription(), serviceContext);
328             }
329             else {
330                 existingNode = WikiNodeLocalServiceUtil.updateNode(
331                     existingNode.getNodeId(), node.getName(),
332                     node.getDescription());
333             }
334         }
335         else {
336             String nodeName = PropsUtil.get(PropsKeys.WIKI_INITIAL_NODE_NAME);
337 
338             if (node.getName().equals(nodeName)) {
339                 try {
340                     WikiNodeUtil.removeByG_N(
341                         context.getGroupId(), node.getName());
342                 }
343                 catch (NoSuchNodeException nsne) {
344                 }
345             }
346 
347             existingNode = WikiNodeLocalServiceUtil.addNode(
348                 userId, node.getName(), node.getDescription(), serviceContext);
349         }
350 
351         nodePKs.put(node.getNodeId(), existingNode.getNodeId());
352     }
353 
354     protected void importPage(
355             PortletDataContext context, Map<Long, Long> nodePKs, Element pageEl,
356             WikiPage page)
357         throws Exception {
358 
359         long userId = context.getUserId(page.getUserUuid());
360         long nodeId = MapUtil.getLong(
361             nodePKs, page.getNodeId(), page.getNodeId());
362 
363         String[] tagsCategories = null;
364         String[] tagsEntries = null;
365 
366         if (context.getBooleanParameter(_NAMESPACE, "categories")) {
367             tagsCategories = context.getTagsCategories(
368                 WikiPage.class, page.getResourcePrimKey());
369         }
370 
371         if (context.getBooleanParameter(_NAMESPACE, "tags")) {
372             tagsEntries = context.getTagsEntries(
373                 WikiPage.class, page.getResourcePrimKey());
374         }
375 
376         ServiceContext serviceContext = new ServiceContext();
377 
378         serviceContext.setTagsCategories(tagsCategories);
379         serviceContext.setTagsEntries(tagsEntries);
380 
381         WikiPage existingPage = null;
382 
383         try {
384             WikiNodeUtil.findByPrimaryKey(nodeId);
385 
386             if (context.getDataStrategy().equals(
387                     PortletDataHandlerKeys.DATA_STRATEGY_MIRROR)) {
388 
389                 try {
390                     existingPage = WikiPageFinderUtil.findByUuid_G(
391                         page.getUuid(), context.getGroupId());
392 
393                     existingPage = WikiPageLocalServiceUtil.updatePage(
394                         userId, nodeId, existingPage.getTitle(), 0,
395                         page.getContent(), page.getSummary(), true,
396                         page.getFormat(), page.getParentTitle(),
397                         page.getRedirectTitle(), serviceContext);
398                 }
399                 catch (NoSuchPageException nspe) {
400                     existingPage = WikiPageLocalServiceUtil.addPage(
401                         page.getUuid(), userId, nodeId, page.getTitle(),
402                         page.getVersion(), page.getContent(), page.getSummary(),
403                         true, page.getFormat(), page.getHead(),
404                         page.getParentTitle(), page.getRedirectTitle(),
405                         serviceContext);
406                 }
407             }
408             else {
409                 existingPage = WikiPageLocalServiceUtil.addPage(
410                     null, userId, nodeId, page.getTitle(), page.getVersion(),
411                     page.getContent(), page.getSummary(), true,
412                     page.getFormat(), page.getHead(), page.getParentTitle(),
413                     page.getRedirectTitle(), serviceContext);
414             }
415 
416             if (context.getBooleanParameter(_NAMESPACE, "attachments") &&
417                 page.isHead()) {
418 
419                 List<Element> attachmentEls = pageEl.elements("attachment");
420 
421                 List<ObjectValuePair<String, byte[]>> files =
422                     new ArrayList<ObjectValuePair<String, byte[]>>();
423 
424                 for (Element attachmentEl : attachmentEls) {
425                     String name = attachmentEl.attributeValue("name");
426                     String binPath = attachmentEl.attributeValue("bin-path");
427 
428                     byte[] bytes = context.getZipEntryAsByteArray(binPath);
429 
430                     files.add(new ObjectValuePair<String, byte[]>(name, bytes));
431                 }
432 
433                 if (files.size() > 0) {
434                     WikiPageLocalServiceUtil.addPageAttachments(
435                         nodeId, page.getTitle(), files);
436                 }
437             }
438 
439             if (context.getBooleanParameter(_NAMESPACE, "comments")) {
440                 context.importComments(
441                     WikiPage.class, page.getResourcePrimKey(),
442                     existingPage.getResourcePrimKey(), context.getGroupId());
443             }
444 
445             if (context.getBooleanParameter(_NAMESPACE, "ratings")) {
446                 context.importRatingsEntries(
447                     WikiPage.class, page.getResourcePrimKey(),
448                     existingPage.getResourcePrimKey());
449             }
450         }
451         catch (NoSuchNodeException nsne) {
452             _log.error("Could not find the node for page " + page.getPageId());
453         }
454     }
455 
456     protected String getNodePath(PortletDataContext context, WikiNode node) {
457         StringBuilder sb = new StringBuilder();
458 
459         sb.append(context.getPortletPath(PortletKeys.WIKI));
460         sb.append("/nodes/");
461         sb.append(node.getNodeId());
462         sb.append(".xml");
463 
464         return sb.toString();
465     }
466 
467     protected String getPageAttachementBinPath(
468         PortletDataContext context, WikiPage page, String attachment) {
469 
470         StringBuilder sb = new StringBuilder();
471 
472         sb.append(context.getPortletPath(PortletKeys.WIKI));
473         sb.append("/bin/");
474         sb.append(page.getPageId());
475         sb.append(StringPool.SLASH);
476         sb.append(attachment);
477 
478         return sb.toString();
479     }
480 
481     protected String getPagePath(PortletDataContext context, WikiPage page) {
482         StringBuilder sb = new StringBuilder();
483 
484         sb.append(context.getPortletPath(PortletKeys.WIKI));
485         sb.append("/pages/");
486         sb.append(page.getPageId());
487         sb.append(".xml");
488 
489         return sb.toString();
490     }
491 
492     private static final String _NAMESPACE = "wiki";
493 
494     private static final PortletDataHandlerBoolean _nodesAndPages =
495         new PortletDataHandlerBoolean(
496             _NAMESPACE, "wikis-and-pages", true, true);
497 
498     private static final PortletDataHandlerBoolean _attachments =
499         new PortletDataHandlerBoolean(_NAMESPACE, "attachments");
500 
501     private static final PortletDataHandlerBoolean _categories =
502         new PortletDataHandlerBoolean(_NAMESPACE, "categories");
503 
504     private static final PortletDataHandlerBoolean _comments =
505         new PortletDataHandlerBoolean(_NAMESPACE, "comments");
506 
507     private static final PortletDataHandlerBoolean _tags =
508         new PortletDataHandlerBoolean(_NAMESPACE, "tags");
509 
510     private static Log _log =
511         LogFactoryUtil.getLog(WikiPortletDataHandlerImpl.class);
512 
513 }