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.journal.lar;
24  
25  import com.liferay.portal.NoSuchImageException;
26  import com.liferay.portal.PortalException;
27  import com.liferay.portal.SystemException;
28  import com.liferay.portal.kernel.lar.PortletDataContext;
29  import com.liferay.portal.kernel.lar.PortletDataException;
30  import com.liferay.portal.kernel.lar.PortletDataHandler;
31  import com.liferay.portal.kernel.lar.PortletDataHandlerBoolean;
32  import com.liferay.portal.kernel.lar.PortletDataHandlerControl;
33  import com.liferay.portal.kernel.lar.PortletDataHandlerKeys;
34  import com.liferay.portal.kernel.util.CalendarFactoryUtil;
35  import com.liferay.portal.kernel.util.ObjectValuePair;
36  import com.liferay.portal.kernel.util.StringPool;
37  import com.liferay.portal.kernel.util.Validator;
38  import com.liferay.portal.model.Image;
39  import com.liferay.portal.service.persistence.ImageUtil;
40  import com.liferay.portal.util.PortalUtil;
41  import com.liferay.portlet.journal.model.JournalArticle;
42  import com.liferay.portlet.journal.model.JournalArticleImage;
43  import com.liferay.portlet.journal.model.JournalStructure;
44  import com.liferay.portlet.journal.model.JournalTemplate;
45  import com.liferay.portlet.journal.model.impl.JournalArticleImpl;
46  import com.liferay.portlet.journal.service.JournalArticleLocalServiceUtil;
47  import com.liferay.portlet.journal.service.JournalStructureLocalServiceUtil;
48  import com.liferay.portlet.journal.service.JournalTemplateLocalServiceUtil;
49  import com.liferay.portlet.journal.service.persistence.JournalArticleImageUtil;
50  import com.liferay.portlet.journal.service.persistence.JournalArticleUtil;
51  import com.liferay.portlet.journal.service.persistence.JournalStructureUtil;
52  import com.liferay.portlet.journal.service.persistence.JournalTemplateUtil;
53  import com.liferay.util.CollectionFactory;
54  import com.liferay.util.FileUtil;
55  import com.liferay.util.MapUtil;
56  
57  import com.thoughtworks.xstream.XStream;
58  
59  import java.io.File;
60  import java.io.IOException;
61  
62  import java.util.Calendar;
63  import java.util.Date;
64  import java.util.Iterator;
65  import java.util.List;
66  import java.util.Map;
67  
68  import javax.portlet.PortletPreferences;
69  
70  import org.apache.commons.logging.Log;
71  import org.apache.commons.logging.LogFactory;
72  
73  import org.dom4j.Document;
74  import org.dom4j.DocumentHelper;
75  import org.dom4j.Element;
76  
77  /**
78   * <a href="JournalPortletDataHandlerImpl.java.html"><b><i>View Source</i></b>
79   * </a>
80   *
81   * <p>
82   * Provides the Journal portlet export and import functionality, which is to
83   * clone all articles, structures, and templates associated with the layout's
84   * group. Upon import, new instances of the corresponding articles, structures,
85   * and templates are created or updated according to the DATA_MIRROW strategy
86   * The author of the newly created objects are determined by the
87   * JournalCreationStrategy class defined in <i>portal.properties</i>. That
88   * strategy also allows the text of the journal article to be modified prior
89   * to import.
90   * </p>
91   *
92   * <p>
93   * This <code>PortletDataHandler</code> differs from
94   * <code>JournalContentPortletDataHandlerImpl</code> in that it exports all
95   * articles owned by the group whether or not they are actually displayed in a
96   * portlet in the layout set.
97   * </p>
98   *
99   * @author Raymond Aug?
100  * @author Joel Kozikowski
101  * @author Brian Wing Shun Chan
102  * @author Bruno Farache
103  *
104  * @see com.liferay.portal.kernel.lar.PortletDataHandler
105  * @see com.liferay.portlet.journal.lar.JournalContentPortletDataHandlerImpl
106  * @see com.liferay.portlet.journal.lar.JournalCreationStrategy
107  *
108  */
109 public class JournalPortletDataHandlerImpl implements PortletDataHandler {
110 
111     public PortletPreferences deleteData(
112             PortletDataContext context, String portletId,
113             PortletPreferences prefs)
114         throws PortletDataException {
115 
116         try {
117             if (!context.addPrimaryKey(
118                     JournalPortletDataHandlerImpl.class, "deleteData")) {
119 
120                 List articles = JournalArticleUtil.findByGroupId(
121                     context.getGroupId());
122 
123                 Iterator itr = articles.iterator();
124 
125                 while (itr.hasNext()) {
126                     JournalArticle article = (JournalArticle)itr.next();
127 
128                     // Templates
129 
130                     JournalTemplateLocalServiceUtil.deleteTemplate(
131                         context.getGroupId(), article.getTemplateId());
132 
133                     // Structures
134 
135                     JournalStructureLocalServiceUtil.deleteStructure(
136                         context.getGroupId(), article.getStructureId());
137                 }
138 
139                 // Articles
140 
141                 JournalArticleLocalServiceUtil.deleteArticles(
142                     context.getGroupId());
143             }
144 
145             return null;
146         }
147         catch (Exception e) {
148             throw new PortletDataException(e);
149         }
150     }
151 
152     public String exportData(
153             PortletDataContext context, String portletId,
154             PortletPreferences prefs)
155         throws PortletDataException {
156 
157         try {
158             XStream xStream = new XStream();
159 
160             Document doc = DocumentHelper.createDocument();
161 
162             Element root = doc.addElement("journal-data");
163 
164             root.addAttribute("group-id", String.valueOf(context.getGroupId()));
165 
166             // Structures
167 
168             List obj = JournalStructureUtil.findByGroupId(context.getGroupId());
169 
170             Iterator itr = obj.iterator();
171 
172             while (itr.hasNext()) {
173                 JournalStructure structure = (JournalStructure)itr.next();
174 
175                 if (context.addPrimaryKey(
176                         JournalStructure.class, structure.getPrimaryKeyObj())) {
177 
178                     itr.remove();
179                 }
180                 else {
181                     exportStructure(structure);
182                 }
183             }
184 
185             String xml = xStream.toXML(obj);
186 
187             Document tempDoc = PortalUtil.readDocumentFromXML(xml);
188 
189             Element el = root.addElement("journal-structures");
190 
191             el.content().add(tempDoc.getRootElement().createCopy());
192 
193             // Templates
194 
195             obj = JournalTemplateUtil.findByGroupId(context.getGroupId());
196 
197             itr = obj.iterator();
198 
199             while (itr.hasNext()) {
200                 JournalTemplate template = (JournalTemplate)itr.next();
201 
202                 if (context.addPrimaryKey(
203                         JournalTemplate.class, template.getPrimaryKeyObj())) {
204 
205                     itr.remove();
206                 }
207                 else {
208                     exportTemplate(context, template);
209                 }
210             }
211 
212             xml = xStream.toXML(obj);
213 
214             el = root.addElement("journal-templates");
215 
216             tempDoc = PortalUtil.readDocumentFromXML(xml);
217 
218             el.content().add(tempDoc.getRootElement().createCopy());
219 
220             // Articles
221 
222             obj = JournalArticleUtil.findByGroupId(context.getGroupId());
223 
224             itr = obj.iterator();
225 
226             while (itr.hasNext()) {
227                 JournalArticle article = (JournalArticle)itr.next();
228 
229                 if (context.addPrimaryKey(
230                         JournalArticle.class, article.getPrimaryKeyObj())) {
231 
232                     itr.remove();
233                 }
234                 else {
235                     exportArticle(context, article);
236                 }
237             }
238 
239             xml = xStream.toXML(obj);
240 
241             el = root.addElement("journal-articles");
242 
243             tempDoc = PortalUtil.readDocumentFromXML(xml);
244 
245             el.content().add(tempDoc.getRootElement().createCopy());
246 
247             return doc.asXML();
248         }
249         catch (Exception e) {
250             throw new PortletDataException(e);
251         }
252     }
253 
254     public PortletDataHandlerControl[] getExportControls()
255         throws PortletDataException {
256 
257         return new PortletDataHandlerControl[] {
258             _articlesStructuresAndTemplates, _images, _comments, _ratings, _tags
259         };
260     }
261 
262     public PortletDataHandlerControl[] getImportControls()
263         throws PortletDataException {
264 
265         return new PortletDataHandlerControl[] {
266             _articlesStructuresAndTemplates, _images, _comments, _ratings, _tags
267         };
268     }
269 
270     public PortletPreferences importData(
271             PortletDataContext context, String portletId,
272             PortletPreferences prefs, String data)
273         throws PortletDataException {
274 
275         try {
276             XStream xStream = new XStream();
277 
278             Document doc = PortalUtil.readDocumentFromXML(data);
279 
280             Element root = doc.getRootElement();
281 
282             // Structures
283 
284             Element el = root.element("journal-structures").element("list");
285 
286             Document tempDoc = DocumentHelper.createDocument();
287 
288             tempDoc.content().add(el.createCopy());
289 
290             Map structurePKs = CollectionFactory.getHashMap();
291 
292             List structures = (List)xStream.fromXML(tempDoc.asXML());
293 
294             Iterator itr = structures.iterator();
295 
296             while (itr.hasNext()) {
297                 JournalStructure structure = (JournalStructure)itr.next();
298 
299                 importStructure(context, structurePKs, structure);
300             }
301 
302             // Templates
303 
304             el = root.element("journal-templates").element("list");
305 
306             tempDoc = DocumentHelper.createDocument();
307 
308             tempDoc.content().add(el.createCopy());
309 
310             Map templatePKs = CollectionFactory.getHashMap();
311 
312             List templates = (List)xStream.fromXML(tempDoc.asXML());
313 
314             itr = templates.iterator();
315 
316             while (itr.hasNext()) {
317                 JournalTemplate template = (JournalTemplate)itr.next();
318 
319                 importTemplate(context, structurePKs, templatePKs, template);
320             }
321 
322             // Articles
323 
324             el = root.element("journal-articles").element("list");
325 
326             tempDoc = DocumentHelper.createDocument();
327 
328             tempDoc.content().add(el.createCopy());
329 
330             List articles = (List)xStream.fromXML(tempDoc.asXML());
331 
332             itr = articles.iterator();
333 
334             while (itr.hasNext()) {
335                 JournalArticle article = (JournalArticle)itr.next();
336 
337                 importArticle(context, structurePKs, templatePKs, article);
338             }
339 
340             return null;
341         }
342         catch (Exception e) {
343             throw new PortletDataException(e);
344         }
345     }
346 
347     protected static void exportArticle(
348             PortletDataContext context, JournalArticle article)
349         throws IOException, PortalException, SystemException {
350 
351         article.setUserUuid(article.getUserUuid());
352         article.setApprovedByUserUuid(article.getApprovedByUserUuid());
353 
354         if (article.isSmallImage()) {
355             Image smallImage = ImageUtil.fetchByPrimaryKey(
356                 article.getSmallImageId());
357 
358             article.setSmallImageType(smallImage.getType());
359 
360             context.getZipWriter().addEntry(
361                 getSmallImageDir(article), smallImage.getTextObj());
362         }
363 
364         if (context.getBooleanParameter(_NAMESPACE, "images")) {
365             List articleImages = JournalArticleImageUtil.findByG_A_V(
366                 context.getGroupId(), article.getArticleId(),
367                 article.getVersion());
368 
369             Iterator itr = articleImages.iterator();
370 
371             while (itr.hasNext()) {
372                 JournalArticleImage articleImage =
373                     (JournalArticleImage)itr.next();
374 
375                 try {
376                     Image image = ImageUtil.findByPrimaryKey(
377                         articleImage.getArticleImageId());
378 
379                     String fileName =
380                         articleImage.getElName() +
381                             articleImage.getLanguageId() + "." +
382                                 image.getType();
383 
384                     context.getZipWriter().addEntry(
385                         getArticleImageDir(article) + fileName,
386                         image.getTextObj());
387                 }
388                 catch (NoSuchImageException nsie) {
389                 }
390             }
391         }
392 
393         if (context.getBooleanParameter(_NAMESPACE, "comments")) {
394             context.addComments(
395                 JournalArticle.class, new Long(article.getResourcePrimKey()));
396         }
397 
398         if (context.getBooleanParameter(_NAMESPACE, "ratings")) {
399             context.addRatingsEntries(
400                 JournalArticle.class, new Long(article.getResourcePrimKey()));
401         }
402 
403         if (context.getBooleanParameter(_NAMESPACE, "tags")) {
404             context.addTagsEntries(
405                 JournalArticle.class, new Long(article.getResourcePrimKey()));
406         }
407     }
408 
409     protected static void exportStructure(JournalStructure structure)
410         throws SystemException {
411 
412         structure.setUserUuid(structure.getUserUuid());
413     }
414 
415     protected static void exportTemplate(
416             PortletDataContext context, JournalTemplate template)
417         throws IOException, PortalException, SystemException {
418 
419         template.setUserUuid(template.getUserUuid());
420 
421         if (template.isSmallImage()) {
422             Image smallImage = ImageUtil.fetchByPrimaryKey(
423                 template.getSmallImageId());
424 
425             template.setSmallImageType(smallImage.getType());
426 
427             context.getZipWriter().addEntry(
428                 getSmallImageDir(template), smallImage.getTextObj());
429         }
430     }
431 
432     protected static String getArticleImageDir(JournalArticle article) {
433         return _ARTICLE_IMAGES_FOLDER + article.getArticleId() + "/" +
434             article.getVersion() + "/";
435     }
436 
437     protected static String getSmallImageDir(JournalArticle article)
438         throws PortalException, SystemException {
439 
440         return _ARTICLE_SMALL_IMAGES_FOLDER + article.getSmallImageId() + "." +
441             article.getSmallImageType();
442     }
443 
444     protected static String getSmallImageDir(JournalTemplate template)
445         throws PortalException, SystemException {
446 
447         return _TEMPLATE_SMALL_IMAGES_FOLDER + template.getSmallImageId() +
448             "." + template.getSmallImageType();
449     }
450 
451     protected static JournalArticle importArticle(
452             PortletDataContext context, Map structurePKs, Map templatePKs,
453             JournalArticle article)
454         throws Exception {
455 
456         long userId = context.getUserId(article.getUserUuid());
457         long plid = context.getPlid();
458 
459         String articleId = article.getArticleId();
460         boolean autoArticleId = false;
461 
462         if ((Validator.isNumber(articleId)) ||
463             (JournalArticleUtil.fetchByG_A_V(
464                 context.getGroupId(), articleId,
465                     JournalArticleImpl.DEFAULT_VERSION) != null)) {
466 
467             autoArticleId = true;
468         }
469 
470         boolean incrementVersion = false;
471 
472         String parentStructureId = MapUtil.getString(
473             structurePKs, article.getStructureId(), article.getStructureId());
474         String parentTemplateId = MapUtil.getString(
475             templatePKs, article.getTemplateId(), article.getTemplateId());
476 
477         Date displayDate = article.getDisplayDate();
478 
479         int displayDateMonth = 0;
480         int displayDateDay = 0;
481         int displayDateYear = 0;
482         int displayDateHour = 0;
483         int displayDateMinute = 0;
484 
485         if (displayDate != null) {
486             Calendar displayCal = CalendarFactoryUtil.getCalendar();
487 
488             displayCal.setTime(displayDate);
489 
490             displayDateMonth = displayCal.get(Calendar.MONTH);
491             displayDateDay = displayCal.get(Calendar.DATE);
492             displayDateYear = displayCal.get(Calendar.YEAR);
493             displayDateHour = displayCal.get(Calendar.HOUR);
494             displayDateMinute = displayCal.get(Calendar.MINUTE);
495         }
496 
497         Date expirationDate = article.getExpirationDate();
498 
499         int expirationDateMonth = 0;
500         int expirationDateDay = 0;
501         int expirationDateYear = 0;
502         int expirationDateHour = 0;
503         int expirationDateMinute = 0;
504         boolean neverExpire = true;
505 
506         if (expirationDate != null) {
507             Calendar expirationCal = CalendarFactoryUtil.getCalendar();
508 
509             expirationCal.setTime(expirationDate);
510 
511             expirationDateMonth = expirationCal.get(Calendar.MONTH);
512             expirationDateDay = expirationCal.get(Calendar.DATE);
513             expirationDateYear = expirationCal.get(Calendar.YEAR);
514             expirationDateHour = expirationCal.get(Calendar.HOUR);
515             expirationDateMinute = expirationCal.get(Calendar.MINUTE);
516             neverExpire = false;
517         }
518 
519         Date reviewDate = article.getReviewDate();
520 
521         int reviewDateMonth = 0;
522         int reviewDateDay = 0;
523         int reviewDateYear = 0;
524         int reviewDateHour = 0;
525         int reviewDateMinute = 0;
526         boolean neverReview = true;
527 
528         if (reviewDate != null) {
529             Calendar reviewCal = CalendarFactoryUtil.getCalendar();
530 
531             reviewCal.setTime(reviewDate);
532 
533             reviewDateMonth = reviewCal.get(Calendar.MONTH);
534             reviewDateDay = reviewCal.get(Calendar.DATE);
535             reviewDateYear = reviewCal.get(Calendar.YEAR);
536             reviewDateHour = reviewCal.get(Calendar.HOUR);
537             reviewDateMinute = reviewCal.get(Calendar.MINUTE);
538             neverReview = false;
539         }
540 
541         File smallFile = null;
542 
543         if (article.isSmallImage()) {
544             byte[] byteArray = context.getZipReader().getEntryAsByteArray(
545                 getSmallImageDir(article));
546 
547             smallFile = File.createTempFile(
548                 String.valueOf(article.getSmallImageId()),
549                 StringPool.PERIOD + article.getSmallImageType());
550 
551             FileUtil.write(smallFile, byteArray);
552         }
553 
554         Map images = CollectionFactory.getHashMap();
555 
556         if (context.getBooleanParameter(_NAMESPACE, "images")) {
557             List imageFiles =
558                 (List)context.getZipReader().getFolderEntries().get(
559                     getArticleImageDir(article));
560 
561             if (imageFiles != null && imageFiles.size() > 0) {
562                 Iterator itr = imageFiles.iterator();
563 
564                 while (itr.hasNext()) {
565                     ObjectValuePair imageFile = (ObjectValuePair)itr.next();
566 
567                     String fileName = (String)imageFile.getKey();
568 
569                     int pos = fileName.lastIndexOf(".");
570 
571                     if (pos != -1) {
572                         fileName = fileName.substring(0, pos);
573                     }
574 
575                     images.put(fileName, imageFile.getValue());
576                 }
577             }
578         }
579 
580         String articleURL = null;
581 
582         PortletPreferences prefs = null;
583 
584         String[] tagsEntries = null;
585 
586         if (context.getBooleanParameter(_NAMESPACE, "tags")) {
587             tagsEntries = context.getTagsEntries(
588                 JournalArticle.class, new Long(article.getResourcePrimKey()));
589         }
590 
591         JournalCreationStrategy creationStrategy =
592             JournalCreationStrategyFactory.getInstance();
593 
594         long authorId = creationStrategy.getAuthorUserId(
595             context.getCompanyId(), context.getGroupId(), article);
596 
597         if (authorId != JournalCreationStrategy.USE_DEFAULT_USER_ID_STRATEGY) {
598             userId = authorId;
599         }
600 
601         String newContent = creationStrategy.getTransformedContent(
602             context.getCompanyId(), context.getGroupId(), article);
603 
604         if (newContent != JournalCreationStrategy.ARTICLE_CONTENT_UNCHANGED) {
605             article.setContent(newContent);
606         }
607 
608         boolean addCommunityPermissions =
609             creationStrategy.addCommunityPermissions(
610                 context.getCompanyId(), context.getGroupId(), article);
611         boolean addGuestPermissions = creationStrategy.addGuestPermissions(
612             context.getCompanyId(), context.getGroupId(), article);
613 
614         JournalArticle existingArticle = null;
615 
616         if (context.getDataStrategy().equals(
617                 PortletDataHandlerKeys.DATA_STRATEGY_MIRROR)) {
618 
619             existingArticle = JournalArticleUtil.fetchByUUID_G(
620                 article.getUuid(), context.getGroupId());
621 
622             if (existingArticle == null) {
623                 existingArticle =  JournalArticleLocalServiceUtil.addArticle(
624                     article.getUuid(), userId, articleId, autoArticleId, plid,
625                     article.getTitle(), article.getDescription(),
626                     article.getContent(), article.getType(), parentStructureId,
627                     parentTemplateId, displayDateMonth, displayDateDay,
628                     displayDateYear, displayDateHour, displayDateMinute,
629                     expirationDateMonth, expirationDateDay, expirationDateYear,
630                     expirationDateHour, expirationDateMinute, neverExpire,
631                     reviewDateMonth, reviewDateDay, reviewDateYear,
632                     reviewDateHour, reviewDateMinute, neverReview,
633                     article.getIndexable(), article.getSmallImage(),
634                     article.getSmallImageURL(), smallFile, images, articleURL,
635                     prefs, tagsEntries, addCommunityPermissions,
636                     addGuestPermissions);
637             }
638             else {
639                 existingArticle =  JournalArticleLocalServiceUtil.updateArticle(
640                     userId, existingArticle.getGroupId(),
641                     existingArticle.getArticleId(),
642                     existingArticle.getVersion(), incrementVersion,
643                     article.getTitle(), article.getDescription(),
644                     article.getContent(), article.getType(),
645                     existingArticle.getStructureId(),
646                     existingArticle.getTemplateId(), displayDateMonth,
647                     displayDateDay, displayDateYear, displayDateHour,
648                     displayDateMinute, expirationDateMonth,
649                     expirationDateDay, expirationDateYear, expirationDateHour,
650                     expirationDateMinute, neverExpire, reviewDateMonth,
651                     reviewDateDay, reviewDateYear, reviewDateHour,
652                     reviewDateMinute, neverReview, article.getIndexable(),
653                     article.getSmallImage(), article.getSmallImageURL(),
654                     smallFile, images, articleURL, prefs, tagsEntries);
655             }
656         }
657         else {
658             existingArticle = JournalArticleLocalServiceUtil.addArticle(
659                 userId, articleId, autoArticleId, plid, article.getTitle(),
660                 article.getDescription(), article.getContent(),
661                 article.getType(), parentStructureId, parentTemplateId,
662                 displayDateMonth, displayDateDay, displayDateYear,
663                 displayDateHour, displayDateMinute, expirationDateMonth,
664                 expirationDateDay, expirationDateYear, expirationDateHour,
665                 expirationDateMinute, neverExpire, reviewDateMonth,
666                 reviewDateDay, reviewDateYear, reviewDateHour, reviewDateMinute,
667                 neverReview, article.getIndexable(), article.getSmallImage(),
668                 article.getSmallImageURL(), smallFile, images, articleURL,
669                 prefs, tagsEntries, addCommunityPermissions,
670                 addGuestPermissions);
671         }
672 
673         long strategyApprovalUserId = creationStrategy.getApprovalUserId(
674             context.getCompanyId(), context.getGroupId(), article);
675 
676         if ((strategyApprovalUserId !=
677                 JournalCreationStrategy.USE_DEFAULT_USER_ID_STRATEGY) ||
678             (article.isApproved() && !existingArticle.isApproved())) {
679 
680             long approvedByUserId = strategyApprovalUserId;
681 
682             if (approvedByUserId == 0) {
683                 approvedByUserId = context.getUserId(
684                     article.getApprovedByUserUuid());
685             }
686 
687             JournalArticleLocalServiceUtil.approveArticle(
688                 approvedByUserId, context.getGroupId(),
689                 existingArticle.getArticleId(), existingArticle.getVersion(),
690                 articleURL, prefs);
691         }
692 
693         if (context.getBooleanParameter(_NAMESPACE, "comments")) {
694             context.importComments(
695                 JournalArticle.class, new Long(article.getResourcePrimKey()),
696                 new Long(existingArticle.getResourcePrimKey()),
697                 context.getGroupId());
698         }
699 
700         if (context.getBooleanParameter(_NAMESPACE, "ratings")) {
701             context.importRatingsEntries(
702                 JournalArticle.class, new Long(article.getResourcePrimKey()),
703                 new Long(existingArticle.getResourcePrimKey()));
704         }
705 
706         if (!articleId.equals(existingArticle.getArticleId())) {
707             if (_log.isWarnEnabled()) {
708                 _log.warn(
709                     "An article with the ID " + articleId + " already " +
710                         "exists. The new generated ID is " +
711                             existingArticle.getArticleId());
712             }
713         }
714 
715         return existingArticle;
716     }
717 
718     protected static void importStructure(
719             PortletDataContext context, Map structurePKs,
720             JournalStructure structure)
721         throws Exception {
722 
723         long userId = context.getUserId(structure.getUserUuid());
724         long plid = context.getPlid();
725 
726         String structureId = structure.getStructureId();
727         boolean autoStructureId = false;
728 
729         if ((Validator.isNumber(structureId)) ||
730             (JournalStructureUtil.fetchByG_S(
731                 context.getGroupId(), structureId) != null)) {
732 
733             autoStructureId = true;
734         }
735 
736         JournalCreationStrategy creationStrategy =
737             JournalCreationStrategyFactory.getInstance();
738 
739         long authorId = creationStrategy.getAuthorUserId(
740             context.getCompanyId(), context.getGroupId(), structure);
741 
742         if (authorId != JournalCreationStrategy.USE_DEFAULT_USER_ID_STRATEGY) {
743             userId = authorId;
744         }
745 
746         boolean addCommunityPermissions =
747             creationStrategy.addCommunityPermissions(
748                 context.getCompanyId(), context.getGroupId(), structure);
749         boolean addGuestPermissions = creationStrategy.addGuestPermissions(
750             context.getCompanyId(), context.getGroupId(), structure);
751 
752         JournalStructure existingStructure = null;
753 
754         if (context.getDataStrategy().equals(
755                 PortletDataHandlerKeys.DATA_STRATEGY_MIRROR)) {
756 
757             existingStructure = JournalStructureUtil.fetchByUUID_G(
758                 structure.getUuid(), context.getGroupId());
759 
760             if (existingStructure == null) {
761                 existingStructure =
762                     JournalStructureLocalServiceUtil.addStructure(
763                         structure.getUuid(), userId, structureId,
764                         autoStructureId, plid, structure.getName(),
765                         structure.getDescription(), structure.getXsd(),
766                         addCommunityPermissions, addGuestPermissions);
767             }
768             else {
769                 existingStructure =
770                     JournalStructureLocalServiceUtil.updateStructure(
771                         existingStructure.getGroupId(),
772                         existingStructure.getStructureId(), structure.getName(),
773                         structure.getDescription(), structure.getXsd());
774             }
775         }
776         else {
777             existingStructure =
778                 JournalStructureLocalServiceUtil.addStructure(
779                     userId, structureId, autoStructureId, plid,
780                     structure.getName(), structure.getDescription(),
781                     structure.getXsd(), addCommunityPermissions,
782                     addGuestPermissions);
783         }
784 
785         structurePKs.put(
786             structure.getStructureId(), existingStructure.getStructureId());
787 
788         if (!structureId.equals(existingStructure.getStructureId())) {
789             if (_log.isWarnEnabled()) {
790                 _log.warn(
791                     "A structure with the ID " + structureId + " already " +
792                         "exists. The new generated ID is " +
793                             existingStructure.getStructureId());
794             }
795         }
796     }
797 
798     protected static void importTemplate(
799             PortletDataContext context, Map structurePKs, Map templatePKs,
800             JournalTemplate template)
801         throws Exception {
802 
803         long userId = context.getUserId(template.getUserUuid());
804         long plid = context.getPlid();
805 
806         String templateId = template.getTemplateId();
807         boolean autoTemplateId = false;
808 
809         if ((Validator.isNumber(templateId)) ||
810             (JournalTemplateUtil.fetchByG_T(
811                 context.getGroupId(), templateId) != null)) {
812 
813             autoTemplateId = true;
814         }
815 
816         String parentStructureId = MapUtil.getString(
817             structurePKs, template.getStructureId(), template.getStructureId());
818 
819         boolean formatXsl = false;
820 
821         JournalCreationStrategy creationStrategy =
822             JournalCreationStrategyFactory.getInstance();
823 
824         long authorId = creationStrategy.getAuthorUserId(
825             context.getCompanyId(), context.getGroupId(), template);
826 
827         if (authorId != JournalCreationStrategy.USE_DEFAULT_USER_ID_STRATEGY) {
828             userId = authorId;
829         }
830 
831         boolean addCommunityPermissions =
832             creationStrategy.addCommunityPermissions(
833                 context.getCompanyId(), context.getGroupId(), template);
834         boolean addGuestPermissions = creationStrategy.addGuestPermissions(
835             context.getCompanyId(), context.getGroupId(), template);
836 
837         File smallFile = null;
838 
839         if (template.isSmallImage()) {
840             byte[] byteArray = context.getZipReader().getEntryAsByteArray(
841                 getSmallImageDir(template));
842 
843             smallFile = File.createTempFile(
844                 String.valueOf(template.getSmallImageId()),
845                 StringPool.PERIOD + template.getSmallImageType());
846 
847             FileUtil.write(smallFile, byteArray);
848         }
849 
850         JournalTemplate existingTemplate = null;
851 
852         if (context.getDataStrategy().equals(
853                 PortletDataHandlerKeys.DATA_STRATEGY_MIRROR)) {
854 
855             existingTemplate = JournalTemplateUtil.fetchByUUID_G(
856                 template.getUuid(), context.getGroupId());
857 
858             if (existingTemplate == null) {
859                 existingTemplate =
860                     JournalTemplateLocalServiceUtil.addTemplate(
861                         template.getUuid(), userId, templateId, autoTemplateId,
862                         plid, parentStructureId, template.getName(),
863                         template.getDescription(), template.getXsl(), formatXsl,
864                         template.getLangType(), template.getCacheable(),
865                         template.isSmallImage(), template.getSmallImageURL(),
866                         smallFile, addCommunityPermissions,
867                         addGuestPermissions);
868             }
869             else {
870                 existingTemplate =
871                     JournalTemplateLocalServiceUtil.updateTemplate(
872                         existingTemplate.getGroupId(),
873                         existingTemplate.getTemplateId(),
874                         existingTemplate.getStructureId(), template.getName(),
875                         template.getDescription(), template.getXsl(), formatXsl,
876                         template.getLangType(), template.getCacheable(),
877                         template.isSmallImage(), template.getSmallImageURL(),
878                         smallFile);
879             }
880         }
881         else {
882             existingTemplate =
883                 JournalTemplateLocalServiceUtil.addTemplate(
884                     userId, templateId, autoTemplateId, plid, parentStructureId,
885                     template.getName(), template.getDescription(),
886                     template.getXsl(), formatXsl, template.getLangType(),
887                     template.getCacheable(), template.isSmallImage(),
888                     template.getSmallImageURL(), smallFile,
889                     addCommunityPermissions, addGuestPermissions);
890         }
891 
892         templatePKs.put(
893             template.getTemplateId(), existingTemplate.getTemplateId());
894 
895         if (!templateId.equals(existingTemplate.getTemplateId())) {
896             if (_log.isWarnEnabled()) {
897                 _log.warn(
898                     "A template with the ID " + templateId + " already " +
899                         "exists. The new generated ID is " +
900                             existingTemplate.getTemplateId());
901             }
902         }
903     }
904 
905     private static final String _NAMESPACE = "journal";
906 
907     private static final String _ARTICLE_IMAGES_FOLDER =
908         "article-images/";
909 
910     private static final String _ARTICLE_SMALL_IMAGES_FOLDER =
911         "article-thumbnails/";
912 
913     private static final String _TEMPLATE_SMALL_IMAGES_FOLDER =
914         "template-thumbnails/";
915 
916     private static final PortletDataHandlerBoolean
917         _articlesStructuresAndTemplates = new PortletDataHandlerBoolean(
918             _NAMESPACE, "articles-structures-and-templates", true, true);
919 
920     private static final PortletDataHandlerBoolean _images =
921         new PortletDataHandlerBoolean(_NAMESPACE, "images");
922 
923     private static final PortletDataHandlerBoolean _comments =
924         new PortletDataHandlerBoolean(_NAMESPACE, "comments");
925 
926     private static final PortletDataHandlerBoolean _ratings =
927         new PortletDataHandlerBoolean(_NAMESPACE, "ratings");
928 
929     private static final PortletDataHandlerBoolean _tags =
930         new PortletDataHandlerBoolean(_NAMESPACE, "tags");
931 
932     private static Log _log =
933         LogFactory.getLog(JournalPortletDataHandlerImpl.class);
934 
935 }