001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
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.getTitle(), vocabulary.getTitleMap(),
509                                    vocabulary.getDescriptionMap(), vocabulary.getSettings(),
510                                    serviceContext);
511                    }
512                    else {
513                            importedVocabulary =
514                                    AssetVocabularyLocalServiceUtil.updateVocabulary(
515                                            existingVocabulary.getVocabularyId(), vocabulary.getTitle(),
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                            _log.error(e, e);
648    
649                            throw new SystemException(e);
650                    }
651                    finally {
652                            context.setScopeGroupId(groupId);
653    
654                            SocialActivityThreadLocal.setEnabled(true);
655                            WorkflowThreadLocal.setEnabled(true);
656                    }
657    
658                    if (preferencesImpl == null) {
659                            return null;
660                    }
661    
662                    return PortletPreferencesSerializer.toXML(preferencesImpl);
663            }
664    
665            protected void importPortletPreferences(
666                            PortletDataContext context, long companyId, long groupId,
667                            Layout layout, String portletId, Element parentEl,
668                            boolean importPortletSetup, boolean importPortletArchivedSetups,
669                            boolean importUserPreferences, boolean preserveScopeLayoutId)
670                    throws PortalException, SystemException {
671    
672                    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId);
673                    long plid = 0;
674                    String scopeLayoutUuid = StringPool.BLANK;
675    
676                    if (layout != null) {
677                            plid = layout.getPlid();
678    
679                            if (preserveScopeLayoutId && (portletId != null)) {
680                                    javax.portlet.PortletPreferences jxPreferences =
681                                            PortletPreferencesFactoryUtil.getLayoutPortletSetup(
682                                                    layout, portletId);
683    
684                                    scopeLayoutUuid = GetterUtil.getString(
685                                            jxPreferences.getValue("lfr-scope-layout-uuid", null));
686    
687                                    context.setScopeLayoutUuid(scopeLayoutUuid);
688                            }
689                    }
690    
691                    List<Element> preferencesEls = parentEl.elements("portlet-preferences");
692    
693                    for (Element preferencesEl : preferencesEls) {
694                            String path = preferencesEl.attributeValue("path");
695    
696                            if (context.isPathNotProcessed(path)) {
697                                    Element el = null;
698                                    String xml = null;
699    
700                                    try {
701                                            xml = context.getZipEntryAsString(path);
702    
703                                            Document preferencesDoc = SAXReaderUtil.read(xml);
704    
705                                            el = preferencesDoc.getRootElement();
706                                    }
707                                    catch (DocumentException de) {
708                                            throw new SystemException(de);
709                                    }
710    
711                                    long ownerId = GetterUtil.getLong(
712                                            el.attributeValue("owner-id"));
713                                    int ownerType = GetterUtil.getInteger(
714                                            el.attributeValue("owner-type"));
715    
716                                    if (ownerType == PortletKeys.PREFS_OWNER_TYPE_COMPANY) {
717                                            continue;
718                                    }
719    
720                                    if (((ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP) ||
721                                            (ownerType == PortletKeys.PREFS_OWNER_TYPE_LAYOUT)) &&
722                                            !importPortletSetup) {
723    
724                                            continue;
725                                    }
726    
727                                    if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) &&
728                                            !importPortletArchivedSetups) {
729    
730                                            continue;
731                                    }
732    
733                                    if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_USER) &&
734                                            (ownerId != PortletKeys.PREFS_OWNER_ID_DEFAULT) &&
735                                            !importUserPreferences) {
736    
737                                            continue;
738                                    }
739    
740                                    if (ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP) {
741                                            plid = PortletKeys.PREFS_PLID_SHARED;
742                                            ownerId = context.getGroupId();
743                                    }
744    
745                                    boolean defaultUser = GetterUtil.getBoolean(
746                                            el.attributeValue("default-user"));
747    
748                                    if (portletId == null) {
749                                            portletId = el.attributeValue("portlet-id");
750                                    }
751    
752                                    if (ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) {
753                                            portletId = PortletConstants.getRootPortletId(portletId);
754    
755                                            String userUuid = el.attributeValue("archive-user-uuid");
756                                            String name = el.attributeValue("archive-name");
757    
758                                            long userId = context.getUserId(userUuid);
759    
760                                            PortletItem portletItem =
761                                                    PortletItemLocalServiceUtil.updatePortletItem(
762                                                            userId, groupId, name, portletId,
763                                                            PortletPreferences.class.getName());
764    
765                                            plid = 0;
766                                            ownerId = portletItem.getPortletItemId();
767                                    }
768    
769                                    if (defaultUser) {
770                                            ownerId = defaultUserId;
771                                    }
772    
773                                    PortletPreferencesLocalServiceUtil.updatePreferences(
774                                            ownerId, ownerType, plid, portletId, xml);
775                            }
776                    }
777    
778                    if (preserveScopeLayoutId && (layout != null)) {
779                            javax.portlet.PortletPreferences jxPreferences =
780                                    PortletPreferencesFactoryUtil.getLayoutPortletSetup(
781                                            layout, portletId);
782    
783                            try {
784                                    jxPreferences.setValue(
785                                            "lfr-scope-layout-uuid", scopeLayoutUuid);
786    
787                                    jxPreferences.store();
788                            }
789                            catch (Exception e) {
790                                    throw new PortalException(e);
791                            }
792                            finally {
793                                    context.setScopeLayoutUuid(scopeLayoutUuid);
794                            }
795                    }
796            }
797    
798            protected void readComments(PortletDataContext context, Element parentEl)
799                    throws SystemException {
800    
801                    try {
802                            String xml = context.getZipEntryAsString(
803                                    context.getSourceRootPath() + "/comments.xml");
804    
805                            if (xml == null) {
806                                    return;
807                            }
808    
809                            Document doc = SAXReaderUtil.read(xml);
810    
811                            Element root = doc.getRootElement();
812    
813                            List<Element> assets = root.elements("asset");
814    
815                            for (Element asset : assets) {
816                                    String path = asset.attributeValue("path");
817                                    String className = asset.attributeValue("class-name");
818                                    long classPK = GetterUtil.getLong(
819                                            asset.attributeValue("class-pk"));
820    
821                                    List<String> zipFolderEntries = context.getZipFolderEntries(
822                                            path);
823    
824                                    List<MBMessage> messages = new ArrayList<MBMessage>();
825    
826                                    for (String zipFolderEntry : zipFolderEntries) {
827                                            MBMessage message = (MBMessage)context.getZipEntryAsObject(
828                                                    zipFolderEntry);
829    
830                                            if (message != null) {
831                                                    messages.add(message);
832                                            }
833                                    }
834    
835                                    context.addComments(className, classPK, messages);
836                            }
837                    }
838                    catch (Exception e) {
839                            throw new SystemException(e);
840                    }
841            }
842    
843            protected void readLocks(PortletDataContext context, Element parentEl)
844                    throws SystemException {
845    
846                    try {
847                            String xml = context.getZipEntryAsString(
848                                    context.getSourceRootPath() + "/locks.xml");
849    
850                            if (xml == null) {
851                                    return;
852                            }
853    
854                            Document doc = SAXReaderUtil.read(xml);
855    
856                            Element root = doc.getRootElement();
857    
858                            List<Element> assets = root.elements("asset");
859    
860                            for (Element asset : assets) {
861                                    String className = asset.attributeValue("class-name");
862                                    String key = asset.attributeValue("key");
863                                    String path = asset.attributeValue("path");
864    
865                                    Lock lock = (Lock)context.getZipEntryAsObject(path);
866    
867                                    if (lock != null) {
868                                            context.addLocks(className, key, lock);
869                                    }
870                            }
871                    }
872                    catch (Exception e) {
873                            throw new SystemException(e);
874                    }
875            }
876    
877            protected void readRatings(PortletDataContext context, Element parentEl)
878                    throws SystemException {
879    
880                    try {
881                            String xml = context.getZipEntryAsString(
882                                    context.getSourceRootPath() + "/ratings.xml");
883    
884                            if (xml == null) {
885                                    return;
886                            }
887    
888                            Document doc = SAXReaderUtil.read(xml);
889    
890                            Element root = doc.getRootElement();
891    
892                            List<Element> assets = root.elements("asset");
893    
894                            for (Element asset : assets) {
895                                    String path = asset.attributeValue("path");
896                                    String className = asset.attributeValue("class-name");
897                                    long classPK = GetterUtil.getLong(
898                                            asset.attributeValue("class-pk"));
899    
900                                    List<String> zipFolderEntries = context.getZipFolderEntries(
901                                            path);
902    
903                                    List<RatingsEntry> ratingsEntries =
904                                            new ArrayList<RatingsEntry>();
905    
906                                    for (String zipFolderEntry : zipFolderEntries) {
907                                            RatingsEntry ratingsEntry =
908                                                    (RatingsEntry)context.getZipEntryAsObject(
909                                                            zipFolderEntry);
910    
911                                            if (ratingsEntry != null) {
912                                                    ratingsEntries.add(ratingsEntry);
913                                            }
914                                    }
915    
916                                    context.addRatingsEntries(className, classPK, ratingsEntries);
917                            }
918                    }
919                    catch (Exception e) {
920                            throw new SystemException(e);
921                    }
922            }
923    
924            protected void readCategories(PortletDataContext context)
925                    throws SystemException {
926    
927                    try {
928                            String xml = context.getZipEntryAsString(
929                                    context.getSourceRootPath() + "/categories-hierarchy.xml");
930    
931                            if (xml == null) {
932                                    return;
933                            }
934    
935                            Document doc = SAXReaderUtil.read(xml);
936    
937                            Element root = doc.getRootElement();
938    
939                            List<Element> vocabularyEls = root.element("vocabularies").elements(
940                                    "vocabulary");
941    
942                            Map<Long, Long> vocabularyPKs =
943                                    (Map<Long, Long>)context.getNewPrimaryKeysMap(
944                                            AssetVocabulary.class);
945    
946                            for (Element vocabularyEl : vocabularyEls) {
947                                    String path = vocabularyEl.attributeValue("path");
948    
949                                    if (!context.isPathNotProcessed(path)) {
950                                            continue;
951                                    }
952    
953                                    AssetVocabulary vocabulary =
954                                            (AssetVocabulary)context.getZipEntryAsObject(path);
955    
956                                    importVocabulary(
957                                            context, vocabularyPKs, vocabularyEl, vocabulary);
958                            }
959    
960                            List<Element> categoryEls = root.element("categories").elements(
961                                    "category");
962    
963                            Map<Long, Long> categoryPKs =
964                                    (Map<Long, Long>)context.getNewPrimaryKeysMap(
965                                            AssetCategory.class);
966    
967                            for (Element categoryEl : categoryEls) {
968                                    String path = categoryEl.attributeValue("path");
969    
970                                    if (!context.isPathNotProcessed(path)) {
971                                            continue;
972                                    }
973    
974                                    AssetCategory category =
975                                            (AssetCategory)context.getZipEntryAsObject(path);
976    
977                                    importCategory(
978                                            context, vocabularyPKs, categoryPKs, categoryEl, category);
979                            }
980    
981                            List<Element> assets = root.element("assets").elements("asset");
982    
983                            for (Element asset : assets) {
984                                    String className = GetterUtil.getString(
985                                            asset.attributeValue("class-name"));
986                                    long classPK = GetterUtil.getLong(
987                                            asset.attributeValue("class-pk"));
988                                    String[] assetCategoryUuids = StringUtil.split(
989                                            GetterUtil.getString(
990                                                    asset.attributeValue("category-uuids")));
991    
992                                    long[] assetCategoryIds = new long[0];
993    
994                                    for (String assetCategoryUuid : assetCategoryUuids) {
995                                            AssetCategory assetCategory =
996                                                    AssetCategoryUtil.fetchByUUID_G(
997                                                            assetCategoryUuid, context.getScopeGroupId());
998    
999                                            if (assetCategory != null) {
1000                                                    assetCategoryIds = ArrayUtil.append(
1001                                                            assetCategoryIds, assetCategory.getCategoryId());
1002                                            }
1003                                    }
1004    
1005                                    context.addAssetCategories(
1006                                            className, classPK, assetCategoryIds);
1007                            }
1008                    }
1009                    catch (Exception e) {
1010                            throw new SystemException(e);
1011                    }
1012            }
1013    
1014            protected void readTags(PortletDataContext context, Element parentEl)
1015                    throws SystemException {
1016    
1017                    try {
1018                            String xml = context.getZipEntryAsString(
1019                                    context.getSourceRootPath() + "/tags.xml");
1020    
1021                            if (xml == null) {
1022                                    return;
1023                            }
1024    
1025                            Document doc = SAXReaderUtil.read(xml);
1026    
1027                            Element root = doc.getRootElement();
1028    
1029                            List<Element> assets = root.elements("asset");
1030    
1031                            for (Element asset : assets) {
1032                                    String className = GetterUtil.getString(
1033                                            asset.attributeValue("class-name"));
1034                                    long classPK = GetterUtil.getLong(
1035                                            asset.attributeValue("class-pk"));
1036                                    String assetTagNames = GetterUtil.getString(
1037                                            asset.attributeValue("tags"));
1038    
1039                                    context.addAssetTags(className, classPK,
1040                                            StringUtil.split(assetTagNames));
1041                            }
1042                    }
1043                    catch (Exception e) {
1044                            throw new SystemException(e);
1045                    }
1046            }
1047    
1048            private static Log _log = LogFactoryUtil.getLog(PortletImporter.class);
1049    
1050            private PermissionImporter _permissionImporter = new PermissionImporter();
1051    
1052    }