001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.lar;
016    
017    import com.liferay.portal.LARFileException;
018    import com.liferay.portal.LARTypeException;
019    import com.liferay.portal.LayoutImportException;
020    import com.liferay.portal.PortletIdException;
021    import com.liferay.portal.kernel.exception.PortalException;
022    import com.liferay.portal.kernel.exception.SystemException;
023    import com.liferay.portal.kernel.lar.PortletDataContext;
024    import com.liferay.portal.kernel.lar.PortletDataHandler;
025    import com.liferay.portal.kernel.lar.PortletDataHandlerKeys;
026    import com.liferay.portal.kernel.lar.UserIdStrategy;
027    import com.liferay.portal.kernel.log.Log;
028    import com.liferay.portal.kernel.log.LogFactoryUtil;
029    import com.liferay.portal.kernel.util.ArrayUtil;
030    import com.liferay.portal.kernel.util.GetterUtil;
031    import com.liferay.portal.kernel.util.MapUtil;
032    import com.liferay.portal.kernel.util.ReleaseInfo;
033    import com.liferay.portal.kernel.util.StringBundler;
034    import com.liferay.portal.kernel.util.StringPool;
035    import com.liferay.portal.kernel.util.StringUtil;
036    import com.liferay.portal.kernel.util.Validator;
037    import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
038    import com.liferay.portal.kernel.xml.Document;
039    import com.liferay.portal.kernel.xml.DocumentException;
040    import com.liferay.portal.kernel.xml.Element;
041    import com.liferay.portal.kernel.xml.Node;
042    import com.liferay.portal.kernel.xml.SAXReaderUtil;
043    import com.liferay.portal.kernel.zip.ZipReader;
044    import com.liferay.portal.kernel.zip.ZipReaderFactoryUtil;
045    import com.liferay.portal.model.Group;
046    import com.liferay.portal.model.Layout;
047    import com.liferay.portal.model.Lock;
048    import com.liferay.portal.model.Portlet;
049    import com.liferay.portal.model.PortletConstants;
050    import com.liferay.portal.model.PortletItem;
051    import com.liferay.portal.model.PortletPreferences;
052    import com.liferay.portal.model.User;
053    import com.liferay.portal.service.GroupLocalServiceUtil;
054    import com.liferay.portal.service.LayoutLocalServiceUtil;
055    import com.liferay.portal.service.PortletItemLocalServiceUtil;
056    import com.liferay.portal.service.PortletLocalServiceUtil;
057    import com.liferay.portal.service.PortletPreferencesLocalServiceUtil;
058    import com.liferay.portal.service.ServiceContext;
059    import com.liferay.portal.service.UserLocalServiceUtil;
060    import com.liferay.portal.service.persistence.PortletPreferencesUtil;
061    import com.liferay.portal.service.persistence.UserUtil;
062    import com.liferay.portal.util.PortletKeys;
063    import com.liferay.portlet.PortletPreferencesFactoryUtil;
064    import com.liferay.portlet.PortletPreferencesImpl;
065    import com.liferay.portlet.PortletPreferencesSerializer;
066    import com.liferay.portlet.asset.NoSuchCategoryException;
067    import com.liferay.portlet.asset.model.AssetCategory;
068    import com.liferay.portlet.asset.model.AssetCategoryConstants;
069    import com.liferay.portlet.asset.model.AssetVocabulary;
070    import com.liferay.portlet.asset.service.AssetCategoryLocalServiceUtil;
071    import com.liferay.portlet.asset.service.AssetVocabularyLocalServiceUtil;
072    import com.liferay.portlet.asset.service.persistence.AssetCategoryUtil;
073    import com.liferay.portlet.asset.service.persistence.AssetVocabularyUtil;
074    import com.liferay.portlet.messageboards.model.MBMessage;
075    import com.liferay.portlet.ratings.model.RatingsEntry;
076    import com.liferay.portlet.social.util.SocialActivityThreadLocal;
077    
078    import java.io.File;
079    
080    import java.util.ArrayList;
081    import java.util.HashSet;
082    import java.util.List;
083    import java.util.Map;
084    
085    import org.apache.commons.lang.time.StopWatch;
086    
087    /**
088     * @author Brian Wing Shun Chan
089     * @author Joel Kozikowski
090     * @author Charles May
091     * @author Raymond Augé
092     * @author Jorge Ferrer
093     * @author Bruno Farache
094     * @author Zsigmond Rab
095     * @author Douglas Wong
096     */
097    public class PortletImporter {
098    
099            public void importPortletInfo(
100                            long userId, long plid, long groupId, String portletId,
101                            Map<String, String[]> parameterMap, File file)
102                    throws PortalException, SystemException {
103    
104                    boolean deletePortletData = MapUtil.getBoolean(
105                            parameterMap, PortletDataHandlerKeys.DELETE_PORTLET_DATA);
106                    boolean importPermissions = MapUtil.getBoolean(
107                            parameterMap, PortletDataHandlerKeys.PERMISSIONS);
108                    boolean importPortletData = MapUtil.getBoolean(
109                            parameterMap, PortletDataHandlerKeys.PORTLET_DATA);
110                    boolean importPortletArchivedSetups = MapUtil.getBoolean(
111                            parameterMap, PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS);
112                    boolean importPortletSetup = MapUtil.getBoolean(
113                            parameterMap, PortletDataHandlerKeys.PORTLET_SETUP);
114                    boolean importUserPreferences = MapUtil.getBoolean(
115                            parameterMap, PortletDataHandlerKeys.PORTLET_USER_PREFERENCES);
116                    String userIdStrategy = MapUtil.getString(
117                            parameterMap, PortletDataHandlerKeys.USER_ID_STRATEGY);
118    
119                    StopWatch stopWatch = null;
120    
121                    if (_log.isInfoEnabled()) {
122                            stopWatch = new StopWatch();
123    
124                            stopWatch.start();
125                    }
126    
127                    Layout layout = LayoutLocalServiceUtil.getLayout(plid);
128    
129                    long companyId = layout.getCompanyId();
130    
131                    User user = UserUtil.findByPrimaryKey(userId);
132    
133                    UserIdStrategy strategy = getUserIdStrategy(user, userIdStrategy);
134    
135                    ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(file);
136    
137                    PortletDataContext context = new PortletDataContextImpl(
138                            companyId, groupId, parameterMap, new HashSet<String>(),
139                            strategy, zipReader);
140    
141                    context.setPortetDataContextListener(
142                            new PortletDataContextListenerImpl(context));
143    
144                    context.setPlid(plid);
145                    context.setPrivateLayout(layout.isPrivateLayout());
146    
147                    // Zip
148    
149                    Element root = null;
150    
151                    // Manifest
152    
153                    String xml = context.getZipEntryAsString("/manifest.xml");
154    
155                    try {
156                            Document doc = SAXReaderUtil.read(xml);
157    
158                            root = doc.getRootElement();
159                    }
160                    catch (Exception e) {
161                            throw new LARFileException(
162                                    "Cannot locate a manifest in this LAR file.");
163                    }
164    
165                    // Build compatibility
166    
167                    Element header = root.element("header");
168    
169                    int buildNumber = ReleaseInfo.getBuildNumber();
170    
171                    int importBuildNumber = GetterUtil.getInteger(
172                            header.attributeValue("build-number"));
173    
174                    if (buildNumber != importBuildNumber) {
175                            throw new LayoutImportException(
176                                    "LAR build number " + importBuildNumber + " does not match " +
177                                            "portal build number " + buildNumber);
178                    }
179    
180                    // Type compatibility
181    
182                    String type = header.attributeValue("type");
183    
184                    if (!type.equals("portlet")) {
185                            throw new LARTypeException(
186                                    "Invalid type of LAR file (" + type + ")");
187                    }
188    
189                    // Portlet compatibility
190    
191                    String rootPortletId = header.attributeValue("root-portlet-id");
192    
193                    if (!PortletConstants.getRootPortletId(portletId).equals(
194                                    rootPortletId)) {
195    
196                            throw new PortletIdException("Invalid portlet id " + rootPortletId);
197                    }
198    
199                    // Import group id
200    
201                    long sourceGroupId = GetterUtil.getLong(
202                            header.attributeValue("group-id"));
203    
204                    context.setSourceGroupId(sourceGroupId);
205    
206                    // Read categories, comments, locks, ratings, and tags to make them
207                    // available to the data handlers through the context
208    
209                    if (importPermissions) {
210                            _permissionImporter.readPortletDataPermissions(context);
211                    }
212    
213                    readCategories(context);
214                    readComments(context, root);
215                    readLocks(context, root);
216                    readRatings(context, root);
217                    readTags(context, root);
218    
219                    // Delete portlet data
220    
221                    if (_log.isDebugEnabled()) {
222                            _log.debug("Deleting portlet data");
223                    }
224    
225                    if (deletePortletData) {
226                            deletePortletData(context, portletId, plid);
227                    }
228    
229                    Element portletRefEl = root.element("portlet");
230                    Element portletEl = null;
231    
232                    try {
233                            Document portletDoc = SAXReaderUtil.read(
234                                    context.getZipEntryAsString(
235                                            portletRefEl.attributeValue("path")));
236    
237                            portletEl = portletDoc.getRootElement();
238                    }
239                    catch (DocumentException de) {
240                            throw new SystemException(de);
241                    }
242    
243                    // Portlet preferences
244    
245                    importPortletPreferences(
246                            context, layout.getCompanyId(), groupId, layout, portletId,
247                            portletEl, importPortletSetup, importPortletArchivedSetups,
248                            importUserPreferences, true);
249    
250                    // Portlet data
251    
252                    if (_log.isDebugEnabled()) {
253                            _log.debug("Importing portlet data");
254                    }
255    
256                    if (importPortletData) {
257                            Element portletDataRefEl = portletEl.element("portlet-data");
258    
259                            if (portletDataRefEl != null) {
260                                    importPortletData(context, portletId, plid, portletDataRefEl);
261                            }
262                            else {
263                                    if (_log.isWarnEnabled()) {
264                                            _log.warn(
265                                                    "Could not import portlet data because it cannot be " +
266                                                            "found in the input");
267                                    }
268                            }
269                    }
270    
271                    if (_log.isInfoEnabled()) {
272                            _log.info(
273                                    "Importing portlet data takes " + stopWatch.getTime() + " ms");
274                    }
275    
276                    zipReader.close();
277            }
278    
279            protected void deletePortletData(
280                            PortletDataContext context, String portletId, long plid)
281                    throws SystemException {
282    
283                    long ownerId = PortletKeys.PREFS_OWNER_ID_DEFAULT;
284                    int ownerType = PortletKeys.PREFS_OWNER_TYPE_LAYOUT;
285    
286                    PortletPreferences portletPreferences =
287                            PortletPreferencesUtil.fetchByO_O_P_P(
288                                    ownerId, ownerType, plid, portletId);
289    
290                    if (portletPreferences == null) {
291                            portletPreferences =
292                                    new com.liferay.portal.model.impl.PortletPreferencesImpl();
293                    }
294    
295                    String xml = deletePortletData(
296                            context, portletId, portletPreferences);
297    
298                    if (xml != null) {
299                            PortletPreferencesLocalServiceUtil.updatePreferences(
300                                    ownerId, ownerType, plid, portletId, xml);
301                    }
302            }
303    
304            protected String deletePortletData(
305                            PortletDataContext context, String portletId,
306                            PortletPreferences portletPreferences)
307                    throws SystemException {
308    
309                    Portlet portlet = PortletLocalServiceUtil.getPortletById(
310                            context.getCompanyId(), portletId);
311    
312                    if (portlet == null) {
313                            if (_log.isDebugEnabled()) {
314                                    _log.debug(
315                                            "Do not delete portlet data for " + portletId +
316                                                    " because the portlet does not exist");
317                            }
318    
319                            return null;
320                    }
321    
322                    PortletDataHandler portletDataHandler =
323                            portlet.getPortletDataHandlerInstance();
324    
325                    if (portletDataHandler == null) {
326                            if (_log.isDebugEnabled()) {
327                                    _log.debug(
328                                            "Do not delete portlet data for " + portletId +
329                                                    " because the portlet does not have a " +
330                                                            "PortletDataHandler");
331                            }
332    
333                            return null;
334                    }
335    
336                    if (_log.isDebugEnabled()) {
337                            _log.debug("Deleting data for " + portletId);
338                    }
339    
340                    PortletPreferencesImpl preferencesImpl =
341                            (PortletPreferencesImpl)PortletPreferencesSerializer.fromDefaultXML(
342                                    portletPreferences.getPreferences());
343    
344                    try {
345                            preferencesImpl =
346                                    (PortletPreferencesImpl)portletDataHandler.deleteData(
347                                            context, portletId, preferencesImpl);
348                    }
349                    catch (Exception e) {
350                            throw new SystemException(e);
351                    }
352                    finally {
353                            context.setGroupId(context.getScopeGroupId());
354                    }
355    
356                    if (preferencesImpl == null) {
357                            return null;
358                    }
359    
360                    return PortletPreferencesSerializer.toXML(preferencesImpl);
361            }
362    
363            protected String getCategoryPath(
364                    PortletDataContext context, long categoryId) {
365    
366                    StringBundler sb = new StringBundler(6);
367    
368                    sb.append(context.getSourceRootPath());
369                    sb.append("/categories/");
370                    sb.append(categoryId);
371                    sb.append(".xml");
372    
373                    return sb.toString();
374            }
375    
376            protected UserIdStrategy getUserIdStrategy(
377                    User user, String userIdStrategy) {
378    
379                    if (UserIdStrategy.ALWAYS_CURRENT_USER_ID.equals(userIdStrategy)) {
380                            return new AlwaysCurrentUserIdStrategy(user);
381                    }
382    
383                    return new CurrentUserIdStrategy(user);
384            }
385    
386            protected void importCategory(
387                            PortletDataContext context, Map<Long, Long> vocabularyPKs,
388                            Map<Long, Long> categoryPKs, Element categoryEl,
389                            AssetCategory category)
390                    throws Exception {
391    
392                    long userId = context.getUserId(category.getUserUuid());
393                    long vocabularyId = MapUtil.getLong(
394                            vocabularyPKs, category.getVocabularyId(),
395                            category.getVocabularyId());
396                    long parentCategoryId = MapUtil.getLong(
397                            categoryPKs, category.getParentCategoryId(),
398                            category.getParentCategoryId());
399    
400                    if ((parentCategoryId !=
401                                    AssetCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) &&
402                            (parentCategoryId == category.getParentCategoryId())) {
403    
404                            String path = getCategoryPath(context, parentCategoryId);
405    
406                            AssetCategory parentCategory =
407                                    (AssetCategory)context.getZipEntryAsObject(path);
408    
409                            Node parentCategoryNode = categoryEl.getParent().selectSingleNode(
410                                    "./category[@path='" + path + "']");
411    
412                            if (parentCategoryNode != null) {
413                                    importCategory(
414                                            context, vocabularyPKs, categoryPKs,
415                                            (Element)parentCategoryNode, parentCategory);
416    
417                                    parentCategoryId = MapUtil.getLong(
418                                            categoryPKs, category.getParentCategoryId(),
419                                            category.getParentCategoryId());
420                            }
421                    }
422    
423                    ServiceContext serviceContext = new ServiceContext();
424    
425                    serviceContext.setAddCommunityPermissions(true);
426                    serviceContext.setAddGuestPermissions(true);
427                    serviceContext.setCreateDate(category.getCreateDate());
428                    serviceContext.setModifiedDate(category.getModifiedDate());
429                    serviceContext.setScopeGroupId(context.getScopeGroupId());
430    
431                    AssetCategory importedCategory = null;
432    
433                    try {
434                            if (parentCategoryId !=
435                                            AssetCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) {
436    
437                                    AssetCategoryUtil.findByPrimaryKey(parentCategoryId);
438                            }
439    
440                            List<Element> propertyEls = categoryEl.elements("property");
441    
442                            String[] properties = new String[propertyEls.size()];
443    
444                            for (int i = 0; i < properties.length; i++) {
445                                    Element propertyEl = propertyEls.get(i);
446                                    String key = propertyEl.attributeValue("key");
447                                    String value = propertyEl.attributeValue("value");
448    
449                                    properties[i] = key.concat(StringPool.COLON).concat(value);
450                            }
451    
452                            AssetCategory existingCategory = AssetCategoryUtil.fetchByP_N_V(
453                                    parentCategoryId, category.getName(), vocabularyId);
454    
455                            if (existingCategory == null) {
456                                    serviceContext.setUuid(category.getUuid());
457    
458                                    importedCategory = AssetCategoryLocalServiceUtil.addCategory(
459                                            userId, parentCategoryId, category.getTitleMap(),
460                                            vocabularyId, properties, serviceContext);
461                            }
462                            else {
463                                    importedCategory = AssetCategoryLocalServiceUtil.updateCategory(
464                                            userId, existingCategory.getCategoryId(), parentCategoryId,
465                                            category.getTitleMap(), vocabularyId, properties,
466                                            serviceContext);
467                            }
468    
469                            categoryPKs.put(
470                                    category.getCategoryId(), importedCategory.getCategoryId());
471    
472                            context.importPermissions(
473                                    AssetCategory.class, category.getCategoryId(),
474                                    importedCategory.getCategoryId());
475                    }
476                    catch (NoSuchCategoryException nsce) {
477                            _log.error(
478                                    "Could not find the parent category for category " +
479                                            category.getCategoryId());
480                    }
481            }
482    
483            protected void importVocabulary(
484                            PortletDataContext context, Map<Long, Long> vocabularyPKs,
485                            Element vocabularyEl, AssetVocabulary vocabulary)
486                    throws Exception {
487    
488                    long userId = context.getUserId(vocabulary.getUserUuid());
489                    long groupId = context.getScopeGroupId();
490    
491                    ServiceContext serviceContext = new ServiceContext();
492    
493                    serviceContext.setAddCommunityPermissions(true);
494                    serviceContext.setAddGuestPermissions(true);
495                    serviceContext.setCreateDate(vocabulary.getCreateDate());
496                    serviceContext.setModifiedDate(vocabulary.getModifiedDate());
497                    serviceContext.setScopeGroupId(context.getScopeGroupId());
498    
499                    AssetVocabulary importedVocabulary = null;
500    
501                    AssetVocabulary existingVocabulary = AssetVocabularyUtil.fetchByG_N(
502                            groupId, vocabulary.getName());
503    
504                    if (existingVocabulary == null) {
505                            serviceContext.setUuid(vocabulary.getUuid());
506    
507                            importedVocabulary = AssetVocabularyLocalServiceUtil.addVocabulary(
508                                    userId, vocabulary.getTitleMap(),
509                                    vocabulary.getDescriptionMap(), vocabulary.getSettings(),
510                                    serviceContext);
511                    }
512                    else {
513                            importedVocabulary =
514                                    AssetVocabularyLocalServiceUtil.updateVocabulary(
515                                            existingVocabulary.getVocabularyId(),
516                                            vocabulary.getTitleMap(), vocabulary.getDescriptionMap(),
517                                            vocabulary.getSettings(),serviceContext);
518                    }
519    
520                    vocabularyPKs.put(
521                            vocabulary.getVocabularyId(), importedVocabulary.getVocabularyId());
522    
523                    context.importPermissions(
524                            AssetVocabulary.class, vocabulary.getVocabularyId(),
525                            importedVocabulary.getVocabularyId());
526            }
527    
528            protected void importPortletData(
529                            PortletDataContext context, String portletId, long plid,
530                            Element portletDataRefEl)
531                    throws SystemException {
532    
533                    long ownerId = PortletKeys.PREFS_OWNER_ID_DEFAULT;
534                    int ownerType = PortletKeys.PREFS_OWNER_TYPE_LAYOUT;
535    
536                    PortletPreferences portletPreferences =
537                            PortletPreferencesUtil.fetchByO_O_P_P(
538                                    ownerId, ownerType, plid, portletId);
539    
540                    if (portletPreferences == null) {
541                            portletPreferences =
542                                    new com.liferay.portal.model.impl.PortletPreferencesImpl();
543                    }
544    
545                    String xml = importPortletData(
546                            context, portletId, portletPreferences, portletDataRefEl);
547    
548                    if (xml != null) {
549                            PortletPreferencesLocalServiceUtil.updatePreferences(
550                                    ownerId, ownerType, plid, portletId, xml);
551                    }
552            }
553    
554            protected String importPortletData(
555                            PortletDataContext context, String portletId,
556                            PortletPreferences portletPreferences, Element portletDataRefEl)
557                    throws SystemException {
558    
559                    Portlet portlet = PortletLocalServiceUtil.getPortletById(
560                            context.getCompanyId(), portletId);
561    
562                    if (portlet == null) {
563                            if (_log.isDebugEnabled()) {
564                                    _log.debug(
565                                            "Do not import portlet data for " + portletId +
566                                                    " because the portlet does not exist");
567                            }
568    
569                            return null;
570                    }
571    
572                    PortletDataHandler portletDataHandler =
573                            portlet.getPortletDataHandlerInstance();
574    
575                    if (portletDataHandler == null) {
576                            if (_log.isDebugEnabled()) {
577                                    _log.debug(
578                                            "Do not import portlet data for " + portletId +
579                                                    " because the portlet does not have a " +
580                                                            "PortletDataHandler");
581                            }
582    
583                            return null;
584                    }
585    
586                    if (_log.isDebugEnabled()) {
587                            _log.debug("Importing data for " + portletId);
588                    }
589    
590                    // Layout scope
591    
592                    long groupId = context.getGroupId();
593    
594                    String scopeLayoutUuid = context.getScopeLayoutUuid();
595    
596                    if (Validator.isNull(scopeLayoutUuid)) {
597                            scopeLayoutUuid = GetterUtil.getString(
598                                    portletDataRefEl.getParent().attributeValue(
599                                            "scope-layout-uuid"));
600                    }
601    
602                    if (Validator.isNotNull(scopeLayoutUuid)) {
603                            try {
604                                    Layout scopeLayout =
605                                            LayoutLocalServiceUtil.getLayoutByUuidAndGroupId(
606                                                    scopeLayoutUuid, groupId);
607    
608                                    Group scopeGroup = null;
609    
610                                    if (scopeLayout.hasScopeGroup()) {
611                                            scopeGroup = scopeLayout.getScopeGroup();
612                                    }
613                                    else {
614                                            String name = String.valueOf(scopeLayout.getPlid());
615    
616                                            scopeGroup = GroupLocalServiceUtil.addGroup(
617                                                    context.getUserId(null), Layout.class.getName(),
618                                                    scopeLayout.getPlid(), name, null, 0, null, true, null);
619                                    }
620    
621                                    context.setScopeGroupId(scopeGroup.getGroupId());
622                            }
623                            catch (PortalException pe) {
624                            }
625                    }
626    
627                    PortletPreferencesImpl preferencesImpl = null;
628    
629                    if (portletPreferences != null) {
630                            preferencesImpl = (PortletPreferencesImpl)
631                                    PortletPreferencesSerializer.fromDefaultXML(
632                                            portletPreferences.getPreferences());
633                    }
634    
635                    String portletData = context.getZipEntryAsString(
636                            portletDataRefEl.attributeValue("path"));
637    
638                    try {
639                            SocialActivityThreadLocal.setEnabled(false);
640                            WorkflowThreadLocal.setEnabled(false);
641    
642                            preferencesImpl =
643                                    (PortletPreferencesImpl)portletDataHandler.importData(
644                                            context, portletId, preferencesImpl, portletData);
645                    }
646                    catch (Exception e) {
647                            throw new SystemException(e);
648                    }
649                    finally {
650                            context.setScopeGroupId(groupId);
651    
652                            SocialActivityThreadLocal.setEnabled(true);
653                            WorkflowThreadLocal.setEnabled(true);
654                    }
655    
656                    if (preferencesImpl == null) {
657                            return null;
658                    }
659    
660                    return PortletPreferencesSerializer.toXML(preferencesImpl);
661            }
662    
663            protected void importPortletPreferences(
664                            PortletDataContext context, long companyId, long groupId,
665                            Layout layout, String portletId, Element parentEl,
666                            boolean importPortletSetup, boolean importPortletArchivedSetups,
667                            boolean importUserPreferences, boolean preserveScopeLayoutId)
668                    throws PortalException, SystemException {
669    
670                    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId);
671                    long plid = 0;
672                    String scopeLayoutUuid = StringPool.BLANK;
673    
674                    if (layout != null) {
675                            plid = layout.getPlid();
676    
677                            if (preserveScopeLayoutId && (portletId != null)) {
678                                    javax.portlet.PortletPreferences jxPreferences =
679                                            PortletPreferencesFactoryUtil.getLayoutPortletSetup(
680                                                    layout, portletId);
681    
682                                    scopeLayoutUuid = GetterUtil.getString(
683                                            jxPreferences.getValue("lfr-scope-layout-uuid", null));
684    
685                                    context.setScopeLayoutUuid(scopeLayoutUuid);
686                            }
687                    }
688    
689                    List<Element> preferencesEls = parentEl.elements("portlet-preferences");
690    
691                    for (Element preferencesEl : preferencesEls) {
692                            String path = preferencesEl.attributeValue("path");
693    
694                            if (context.isPathNotProcessed(path)) {
695                                    Element el = null;
696                                    String xml = null;
697    
698                                    try {
699                                            xml = context.getZipEntryAsString(path);
700    
701                                            Document preferencesDoc = SAXReaderUtil.read(xml);
702    
703                                            el = preferencesDoc.getRootElement();
704                                    }
705                                    catch (DocumentException de) {
706                                            throw new SystemException(de);
707                                    }
708    
709                                    long ownerId = GetterUtil.getLong(
710                                            el.attributeValue("owner-id"));
711                                    int ownerType = GetterUtil.getInteger(
712                                            el.attributeValue("owner-type"));
713    
714                                    if (ownerType == PortletKeys.PREFS_OWNER_TYPE_COMPANY) {
715                                            continue;
716                                    }
717    
718                                    if (((ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP) ||
719                                            (ownerType == PortletKeys.PREFS_OWNER_TYPE_LAYOUT)) &&
720                                            !importPortletSetup) {
721    
722                                            continue;
723                                    }
724    
725                                    if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) &&
726                                            !importPortletArchivedSetups) {
727    
728                                            continue;
729                                    }
730    
731                                    if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_USER) &&
732                                            (ownerId != PortletKeys.PREFS_OWNER_ID_DEFAULT) &&
733                                            !importUserPreferences) {
734    
735                                            continue;
736                                    }
737    
738                                    if (ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP) {
739                                            plid = PortletKeys.PREFS_PLID_SHARED;
740                                            ownerId = context.getGroupId();
741                                    }
742    
743                                    boolean defaultUser = GetterUtil.getBoolean(
744                                            el.attributeValue("default-user"));
745    
746                                    if (portletId == null) {
747                                            portletId = el.attributeValue("portlet-id");
748                                    }
749    
750                                    if (ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) {
751                                            portletId = PortletConstants.getRootPortletId(portletId);
752    
753                                            String userUuid = el.attributeValue("archive-user-uuid");
754                                            String name = el.attributeValue("archive-name");
755    
756                                            long userId = context.getUserId(userUuid);
757    
758                                            PortletItem portletItem =
759                                                    PortletItemLocalServiceUtil.updatePortletItem(
760                                                            userId, groupId, name, portletId,
761                                                            PortletPreferences.class.getName());
762    
763                                            plid = 0;
764                                            ownerId = portletItem.getPortletItemId();
765                                    }
766    
767                                    if (defaultUser) {
768                                            ownerId = defaultUserId;
769                                    }
770    
771                                    PortletPreferencesLocalServiceUtil.updatePreferences(
772                                            ownerId, ownerType, plid, portletId, xml);
773                            }
774                    }
775    
776                    if (preserveScopeLayoutId && (layout != null)) {
777                            javax.portlet.PortletPreferences jxPreferences =
778                                    PortletPreferencesFactoryUtil.getLayoutPortletSetup(
779                                            layout, portletId);
780    
781                            try {
782                                    jxPreferences.setValue(
783                                            "lfr-scope-layout-uuid", scopeLayoutUuid);
784    
785                                    jxPreferences.store();
786                            }
787                            catch (Exception e) {
788                                    throw new PortalException(e);
789                            }
790                            finally {
791                                    context.setScopeLayoutUuid(scopeLayoutUuid);
792                            }
793                    }
794            }
795    
796            protected void readComments(PortletDataContext context, Element parentEl)
797                    throws SystemException {
798    
799                    try {
800                            String xml = context.getZipEntryAsString(
801                                    context.getSourceRootPath() + "/comments.xml");
802    
803                            if (xml == null) {
804                                    return;
805                            }
806    
807                            Document doc = SAXReaderUtil.read(xml);
808    
809                            Element root = doc.getRootElement();
810    
811                            List<Element> assets = root.elements("asset");
812    
813                            for (Element asset : assets) {
814                                    String path = asset.attributeValue("path");
815                                    String className = asset.attributeValue("class-name");
816                                    long classPK = GetterUtil.getLong(
817                                            asset.attributeValue("class-pk"));
818    
819                                    List<String> zipFolderEntries = context.getZipFolderEntries(
820                                            path);
821    
822                                    List<MBMessage> messages = new ArrayList<MBMessage>();
823    
824                                    for (String zipFolderEntry : zipFolderEntries) {
825                                            MBMessage message = (MBMessage)context.getZipEntryAsObject(
826                                                    zipFolderEntry);
827    
828                                            if (message != null) {
829                                                    messages.add(message);
830                                            }
831                                    }
832    
833                                    context.addComments(className, classPK, messages);
834                            }
835                    }
836                    catch (Exception e) {
837                            throw new SystemException(e);
838                    }
839            }
840    
841            protected void readLocks(PortletDataContext context, Element parentEl)
842                    throws SystemException {
843    
844                    try {
845                            String xml = context.getZipEntryAsString(
846                                    context.getSourceRootPath() + "/locks.xml");
847    
848                            if (xml == null) {
849                                    return;
850                            }
851    
852                            Document doc = SAXReaderUtil.read(xml);
853    
854                            Element root = doc.getRootElement();
855    
856                            List<Element> assets = root.elements("asset");
857    
858                            for (Element asset : assets) {
859                                    String className = asset.attributeValue("class-name");
860                                    String key = asset.attributeValue("key");
861                                    String path = asset.attributeValue("path");
862    
863                                    Lock lock = (Lock)context.getZipEntryAsObject(path);
864    
865                                    if (lock != null) {
866                                            context.addLocks(className, key, lock);
867                                    }
868                            }
869                    }
870                    catch (Exception e) {
871                            throw new SystemException(e);
872                    }
873            }
874    
875            protected void readRatings(PortletDataContext context, Element parentEl)
876                    throws SystemException {
877    
878                    try {
879                            String xml = context.getZipEntryAsString(
880                                    context.getSourceRootPath() + "/ratings.xml");
881    
882                            if (xml == null) {
883                                    return;
884                            }
885    
886                            Document doc = SAXReaderUtil.read(xml);
887    
888                            Element root = doc.getRootElement();
889    
890                            List<Element> assets = root.elements("asset");
891    
892                            for (Element asset : assets) {
893                                    String path = asset.attributeValue("path");
894                                    String className = asset.attributeValue("class-name");
895                                    long classPK = GetterUtil.getLong(
896                                            asset.attributeValue("class-pk"));
897    
898                                    List<String> zipFolderEntries = context.getZipFolderEntries(
899                                            path);
900    
901                                    List<RatingsEntry> ratingsEntries =
902                                            new ArrayList<RatingsEntry>();
903    
904                                    for (String zipFolderEntry : zipFolderEntries) {
905                                            RatingsEntry ratingsEntry =
906                                                    (RatingsEntry)context.getZipEntryAsObject(
907                                                            zipFolderEntry);
908    
909                                            if (ratingsEntry != null) {
910                                                    ratingsEntries.add(ratingsEntry);
911                                            }
912                                    }
913    
914                                    context.addRatingsEntries(className, classPK, ratingsEntries);
915                            }
916                    }
917                    catch (Exception e) {
918                            throw new SystemException(e);
919                    }
920            }
921    
922            protected void readCategories(PortletDataContext context)
923                    throws SystemException {
924    
925                    try {
926                            String xml = context.getZipEntryAsString(
927                                    context.getSourceRootPath() + "/categories-hierarchy.xml");
928    
929                            if (xml == null) {
930                                    return;
931                            }
932    
933                            Document doc = SAXReaderUtil.read(xml);
934    
935                            Element root = doc.getRootElement();
936    
937                            List<Element> vocabularyEls = root.element("vocabularies").elements(
938                                    "vocabulary");
939    
940                            Map<Long, Long> vocabularyPKs =
941                                    (Map<Long, Long>)context.getNewPrimaryKeysMap(
942                                            AssetVocabulary.class);
943    
944                            for (Element vocabularyEl : vocabularyEls) {
945                                    String path = vocabularyEl.attributeValue("path");
946    
947                                    if (!context.isPathNotProcessed(path)) {
948                                            continue;
949                                    }
950    
951                                    AssetVocabulary vocabulary =
952                                            (AssetVocabulary)context.getZipEntryAsObject(path);
953    
954                                    importVocabulary(
955                                            context, vocabularyPKs, vocabularyEl, vocabulary);
956                            }
957    
958                            List<Element> categoryEls = root.element("categories").elements(
959                                    "category");
960    
961                            Map<Long, Long> categoryPKs =
962                                    (Map<Long, Long>)context.getNewPrimaryKeysMap(
963                                            AssetCategory.class);
964    
965                            for (Element categoryEl : categoryEls) {
966                                    String path = categoryEl.attributeValue("path");
967    
968                                    if (!context.isPathNotProcessed(path)) {
969                                            continue;
970                                    }
971    
972                                    AssetCategory category =
973                                            (AssetCategory)context.getZipEntryAsObject(path);
974    
975                                    importCategory(
976                                            context, vocabularyPKs, categoryPKs, categoryEl, category);
977                            }
978    
979                            List<Element> assets = root.element("assets").elements("asset");
980    
981                            for (Element asset : assets) {
982                                    String className = GetterUtil.getString(
983                                            asset.attributeValue("class-name"));
984                                    long classPK = GetterUtil.getLong(
985                                            asset.attributeValue("class-pk"));
986                                    String[] assetCategoryUuids = StringUtil.split(
987                                            GetterUtil.getString(
988                                                    asset.attributeValue("category-uuids")));
989    
990                                    long[] assetCategoryIds = new long[0];
991    
992                                    for (String assetCategoryUuid : assetCategoryUuids) {
993                                            AssetCategory assetCategory =
994                                                    AssetCategoryUtil.fetchByUUID_G(
995                                                            assetCategoryUuid, context.getScopeGroupId());
996    
997                                            if (assetCategory != null) {
998                                                    assetCategoryIds = ArrayUtil.append(
999                                                            assetCategoryIds, assetCategory.getCategoryId());
1000                                            }
1001                                    }
1002    
1003                                    context.addAssetCategories(
1004                                            className, classPK, assetCategoryIds);
1005                            }
1006                    }
1007                    catch (Exception e) {
1008                            throw new SystemException(e);
1009                    }
1010            }
1011    
1012            protected void readTags(PortletDataContext context, Element parentEl)
1013                    throws SystemException {
1014    
1015                    try {
1016                            String xml = context.getZipEntryAsString(
1017                                    context.getSourceRootPath() + "/tags.xml");
1018    
1019                            if (xml == null) {
1020                                    return;
1021                            }
1022    
1023                            Document doc = SAXReaderUtil.read(xml);
1024    
1025                            Element root = doc.getRootElement();
1026    
1027                            List<Element> assets = root.elements("asset");
1028    
1029                            for (Element asset : assets) {
1030                                    String className = GetterUtil.getString(
1031                                            asset.attributeValue("class-name"));
1032                                    long classPK = GetterUtil.getLong(
1033                                            asset.attributeValue("class-pk"));
1034                                    String assetTagNames = GetterUtil.getString(
1035                                            asset.attributeValue("tags"));
1036    
1037                                    context.addAssetTags(className, classPK,
1038                                            StringUtil.split(assetTagNames));
1039                            }
1040                    }
1041                    catch (Exception e) {
1042                            throw new SystemException(e);
1043                    }
1044            }
1045    
1046            private static Log _log = LogFactoryUtil.getLog(PortletImporter.class);
1047    
1048            private PermissionImporter _permissionImporter = new PermissionImporter();
1049    
1050    }