001    /**
002     * Copyright (c) 2000-2012 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.NoSuchLayoutException;
021    import com.liferay.portal.PortletIdException;
022    import com.liferay.portal.kernel.exception.PortalException;
023    import com.liferay.portal.kernel.exception.SystemException;
024    import com.liferay.portal.kernel.lar.ImportExportThreadLocal;
025    import com.liferay.portal.kernel.lar.PortletDataContext;
026    import com.liferay.portal.kernel.lar.PortletDataHandler;
027    import com.liferay.portal.kernel.lar.PortletDataHandlerKeys;
028    import com.liferay.portal.kernel.lar.UserIdStrategy;
029    import com.liferay.portal.kernel.log.Log;
030    import com.liferay.portal.kernel.log.LogFactoryUtil;
031    import com.liferay.portal.kernel.search.Indexer;
032    import com.liferay.portal.kernel.search.IndexerRegistryUtil;
033    import com.liferay.portal.kernel.util.ArrayUtil;
034    import com.liferay.portal.kernel.util.GetterUtil;
035    import com.liferay.portal.kernel.util.LocaleUtil;
036    import com.liferay.portal.kernel.util.MapUtil;
037    import com.liferay.portal.kernel.util.ReleaseInfo;
038    import com.liferay.portal.kernel.util.StringBundler;
039    import com.liferay.portal.kernel.util.StringPool;
040    import com.liferay.portal.kernel.util.StringUtil;
041    import com.liferay.portal.kernel.util.Validator;
042    import com.liferay.portal.kernel.xml.Document;
043    import com.liferay.portal.kernel.xml.DocumentException;
044    import com.liferay.portal.kernel.xml.Element;
045    import com.liferay.portal.kernel.xml.Node;
046    import com.liferay.portal.kernel.xml.SAXReaderUtil;
047    import com.liferay.portal.kernel.zip.ZipReader;
048    import com.liferay.portal.kernel.zip.ZipReaderFactoryUtil;
049    import com.liferay.portal.model.Group;
050    import com.liferay.portal.model.Layout;
051    import com.liferay.portal.model.Lock;
052    import com.liferay.portal.model.Portlet;
053    import com.liferay.portal.model.PortletConstants;
054    import com.liferay.portal.model.PortletItem;
055    import com.liferay.portal.model.PortletPreferences;
056    import com.liferay.portal.model.User;
057    import com.liferay.portal.security.permission.PermissionCacheUtil;
058    import com.liferay.portal.service.GroupLocalServiceUtil;
059    import com.liferay.portal.service.LayoutLocalServiceUtil;
060    import com.liferay.portal.service.PortletItemLocalServiceUtil;
061    import com.liferay.portal.service.PortletLocalServiceUtil;
062    import com.liferay.portal.service.PortletPreferencesLocalServiceUtil;
063    import com.liferay.portal.service.ServiceContext;
064    import com.liferay.portal.service.UserLocalServiceUtil;
065    import com.liferay.portal.service.persistence.PortletPreferencesUtil;
066    import com.liferay.portal.service.persistence.UserUtil;
067    import com.liferay.portal.servlet.filters.cache.CacheUtil;
068    import com.liferay.portal.util.PortletKeys;
069    import com.liferay.portal.util.PropsValues;
070    import com.liferay.portlet.PortletPreferencesFactoryUtil;
071    import com.liferay.portlet.PortletPreferencesImpl;
072    import com.liferay.portlet.asset.NoSuchCategoryException;
073    import com.liferay.portlet.asset.NoSuchEntryException;
074    import com.liferay.portlet.asset.NoSuchTagException;
075    import com.liferay.portlet.asset.model.AssetCategory;
076    import com.liferay.portlet.asset.model.AssetCategoryConstants;
077    import com.liferay.portlet.asset.model.AssetEntry;
078    import com.liferay.portlet.asset.model.AssetTag;
079    import com.liferay.portlet.asset.model.AssetVocabulary;
080    import com.liferay.portlet.asset.service.AssetCategoryLocalServiceUtil;
081    import com.liferay.portlet.asset.service.AssetEntryLocalServiceUtil;
082    import com.liferay.portlet.asset.service.AssetLinkLocalServiceUtil;
083    import com.liferay.portlet.asset.service.AssetTagLocalServiceUtil;
084    import com.liferay.portlet.asset.service.AssetVocabularyLocalServiceUtil;
085    import com.liferay.portlet.asset.service.persistence.AssetCategoryUtil;
086    import com.liferay.portlet.asset.service.persistence.AssetTagUtil;
087    import com.liferay.portlet.asset.service.persistence.AssetVocabularyUtil;
088    import com.liferay.portlet.expando.NoSuchTableException;
089    import com.liferay.portlet.expando.model.ExpandoColumn;
090    import com.liferay.portlet.expando.model.ExpandoTable;
091    import com.liferay.portlet.expando.service.ExpandoColumnLocalServiceUtil;
092    import com.liferay.portlet.expando.service.ExpandoTableLocalServiceUtil;
093    import com.liferay.portlet.expando.util.ExpandoConverterUtil;
094    import com.liferay.portlet.journalcontent.util.JournalContentUtil;
095    import com.liferay.portlet.messageboards.model.MBMessage;
096    import com.liferay.portlet.ratings.model.RatingsEntry;
097    
098    import java.io.File;
099    import java.io.Serializable;
100    
101    import java.util.ArrayList;
102    import java.util.Enumeration;
103    import java.util.HashMap;
104    import java.util.HashSet;
105    import java.util.List;
106    import java.util.Locale;
107    import java.util.Map;
108    
109    import org.apache.commons.lang.time.StopWatch;
110    
111    /**
112     * @author Brian Wing Shun Chan
113     * @author Joel Kozikowski
114     * @author Charles May
115     * @author Raymond Augé
116     * @author Jorge Ferrer
117     * @author Bruno Farache
118     * @author Zsigmond Rab
119     * @author Douglas Wong
120     */
121    public class PortletImporter {
122    
123            public void importPortletInfo(
124                            long userId, long plid, long groupId, String portletId,
125                            Map<String, String[]> parameterMap, File file)
126                    throws Exception {
127    
128                    try {
129                            ImportExportThreadLocal.setPortletImportInProcess(true);
130    
131                            doImportPortletInfo(
132                                    userId, plid, groupId, portletId, parameterMap, file);
133                    }
134                    finally {
135                            ImportExportThreadLocal.setPortletImportInProcess(false);
136    
137                            CacheUtil.clearCache();
138                            JournalContentUtil.clearCache();
139                            PermissionCacheUtil.clearCache();
140                    }
141            }
142    
143            protected String checkPortletPreferences(
144                            PortletDataContext portletDataContext, long companyId, long ownerId,
145                            int ownerType, long plid, String portletId, String xml)
146                    throws Exception {
147    
148                    String rootPotletId = PortletConstants.getRootPortletId(portletId);
149    
150                    if (!rootPotletId.equals(PortletKeys.ASSET_PUBLISHER)) {
151                            return xml;
152                    }
153    
154                    PortletPreferencesImpl portletPreferences =
155                            (PortletPreferencesImpl)PortletPreferencesFactoryUtil.
156                                    fromXML(companyId, ownerId, ownerType, plid, portletId, xml);
157    
158                     Enumeration<String> enu = portletPreferences.getNames();
159    
160                     while (enu.hasMoreElements()) {
161                            String name = enu.nextElement();
162    
163                            String value = GetterUtil.getString(
164                                    portletPreferences.getValue(name, StringPool.BLANK));
165    
166                            String prefix = "queryName";
167    
168                            if (value.equalsIgnoreCase("assetCategories") &&
169                                    name.startsWith(prefix)) {
170    
171                                    String index = name.substring(prefix.length(), name.length());
172    
173                                    String queryValuesName = "queryValues" + index;
174    
175                                    String[] importedAssetCategoryPKs =
176                                            portletPreferences.getValues(queryValuesName, null);
177    
178                                    Map<Long, Long> assetCategoryPKs =
179                                            (Map<Long, Long>)portletDataContext.getNewPrimaryKeysMap(
180                                                    AssetCategory.class);
181    
182                                    String[] newAssetCategoryPKs = new String[
183                                            importedAssetCategoryPKs.length];
184    
185                                    int i = 0;
186    
187                                    for (String importedAssetCategoryPK :
188                                                    importedAssetCategoryPKs) {
189    
190                                            String newAssetCategoryPK = StringUtil.valueOf(
191                                                    assetCategoryPKs.get(
192                                                            new Long(importedAssetCategoryPK)));
193    
194                                            if (Validator.isNull(newAssetCategoryPK)) {
195                                                    newAssetCategoryPK = importedAssetCategoryPK;
196                                            }
197    
198                                            newAssetCategoryPKs[i++] = newAssetCategoryPK;
199                                    }
200    
201                                    portletPreferences.setValues(
202                                            queryValuesName, newAssetCategoryPKs);
203                            }
204                    }
205    
206                    return PortletPreferencesFactoryUtil.toXML(portletPreferences);
207            }
208    
209            protected void deletePortletData(
210                            PortletDataContext portletDataContext, String portletId, long plid)
211                    throws Exception {
212    
213                    long ownerId = PortletKeys.PREFS_OWNER_ID_DEFAULT;
214                    int ownerType = PortletKeys.PREFS_OWNER_TYPE_LAYOUT;
215    
216                    PortletPreferences portletPreferences =
217                            PortletPreferencesUtil.fetchByO_O_P_P(
218                                    ownerId, ownerType, plid, portletId);
219    
220                    if (portletPreferences == null) {
221                            portletPreferences =
222                                    new com.liferay.portal.model.impl.PortletPreferencesImpl();
223                    }
224    
225                    String xml = deletePortletData(
226                            portletDataContext, portletId, portletPreferences);
227    
228                    if (xml != null) {
229                            PortletPreferencesLocalServiceUtil.updatePreferences(
230                                    ownerId, ownerType, plid, portletId, xml);
231                    }
232            }
233    
234            protected String deletePortletData(
235                            PortletDataContext portletDataContext, String portletId,
236                            PortletPreferences portletPreferences)
237                    throws Exception {
238    
239                    Portlet portlet = PortletLocalServiceUtil.getPortletById(
240                            portletDataContext.getCompanyId(), portletId);
241    
242                    if (portlet == null) {
243                            if (_log.isDebugEnabled()) {
244                                    _log.debug(
245                                            "Do not delete portlet data for " + portletId +
246                                                    " because the portlet does not exist");
247                            }
248    
249                            return null;
250                    }
251    
252                    PortletDataHandler portletDataHandler =
253                            portlet.getPortletDataHandlerInstance();
254    
255                    if (portletDataHandler == null) {
256                            if (_log.isDebugEnabled()) {
257                                    _log.debug(
258                                            "Do not delete portlet data for " + portletId +
259                                                    " because the portlet does not have a " +
260                                                            "PortletDataHandler");
261                            }
262    
263                            return null;
264                    }
265    
266                    if (_log.isDebugEnabled()) {
267                            _log.debug("Deleting data for " + portletId);
268                    }
269    
270                    PortletPreferencesImpl portletPreferencesImpl =
271                            (PortletPreferencesImpl)
272                                    PortletPreferencesFactoryUtil.fromDefaultXML(
273                                            portletPreferences.getPreferences());
274    
275                    try {
276                            portletPreferencesImpl =
277                                    (PortletPreferencesImpl)portletDataHandler.deleteData(
278                                            portletDataContext, portletId, portletPreferencesImpl);
279                    }
280                    finally {
281                            portletDataContext.setGroupId(portletDataContext.getScopeGroupId());
282                    }
283    
284                    if (portletPreferencesImpl == null) {
285                            return null;
286                    }
287    
288                    return PortletPreferencesFactoryUtil.toXML(portletPreferencesImpl);
289            }
290    
291            protected void doImportPortletInfo(
292                            long userId, long plid, long groupId, String portletId,
293                            Map<String, String[]> parameterMap, File file)
294                    throws Exception {
295    
296                    boolean deletePortletData = MapUtil.getBoolean(
297                            parameterMap, PortletDataHandlerKeys.DELETE_PORTLET_DATA);
298                    boolean importPermissions = MapUtil.getBoolean(
299                            parameterMap, PortletDataHandlerKeys.PERMISSIONS);
300                    boolean importUserPermissions = MapUtil.getBoolean(
301                            parameterMap, PortletDataHandlerKeys.PERMISSIONS);
302                    boolean importPortletData = MapUtil.getBoolean(
303                            parameterMap, PortletDataHandlerKeys.PORTLET_DATA);
304                    boolean importPortletArchivedSetups = MapUtil.getBoolean(
305                            parameterMap, PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS);
306                    boolean importPortletSetup = MapUtil.getBoolean(
307                            parameterMap, PortletDataHandlerKeys.PORTLET_SETUP);
308                    boolean importPortletUserPreferences = MapUtil.getBoolean(
309                            parameterMap, PortletDataHandlerKeys.PORTLET_USER_PREFERENCES);
310                    String userIdStrategyString = MapUtil.getString(
311                            parameterMap, PortletDataHandlerKeys.USER_ID_STRATEGY);
312    
313                    StopWatch stopWatch = null;
314    
315                    if (_log.isInfoEnabled()) {
316                            stopWatch = new StopWatch();
317    
318                            stopWatch.start();
319                    }
320    
321                    Layout layout = LayoutLocalServiceUtil.getLayout(plid);
322    
323                    User user = UserUtil.findByPrimaryKey(userId);
324    
325                    UserIdStrategy userIdStrategy = getUserIdStrategy(
326                            user, userIdStrategyString);
327    
328                    ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(file);
329    
330                    PortletDataContext portletDataContext = new PortletDataContextImpl(
331                            layout.getCompanyId(), groupId, parameterMap, new HashSet<String>(),
332                            userIdStrategy, zipReader);
333    
334                    portletDataContext.setPortetDataContextListener(
335                            new PortletDataContextListenerImpl(portletDataContext));
336    
337                    portletDataContext.setPlid(plid);
338                    portletDataContext.setPrivateLayout(layout.isPrivateLayout());
339    
340                    // Manifest
341    
342                    String xml = portletDataContext.getZipEntryAsString("/manifest.xml");
343    
344                    Element rootElement = null;
345    
346                    try {
347                            Document document = SAXReaderUtil.read(xml);
348    
349                            rootElement = document.getRootElement();
350                    }
351                    catch (Exception e) {
352                            throw new LARFileException("Unable to read /manifest.xml");
353                    }
354    
355                    // Build compatibility
356    
357                    Element headerElement = rootElement.element("header");
358    
359                    int buildNumber = ReleaseInfo.getBuildNumber();
360    
361                    int importBuildNumber = GetterUtil.getInteger(
362                            headerElement.attributeValue("build-number"));
363    
364                    if (buildNumber != importBuildNumber) {
365                            throw new LayoutImportException(
366                                    "LAR build number " + importBuildNumber + " does not match " +
367                                            "portal build number " + buildNumber);
368                    }
369    
370                    // Type compatibility
371    
372                    String type = headerElement.attributeValue("type");
373    
374                    if (!type.equals("portlet")) {
375                            throw new LARTypeException(
376                                    "Invalid type of LAR file (" + type + ")");
377                    }
378    
379                    // Portlet compatibility
380    
381                    String rootPortletId = headerElement.attributeValue("root-portlet-id");
382    
383                    if (!PortletConstants.getRootPortletId(portletId).equals(
384                                    rootPortletId)) {
385    
386                            throw new PortletIdException("Invalid portlet id " + rootPortletId);
387                    }
388    
389                    // Import group id
390    
391                    long sourceGroupId = GetterUtil.getLong(
392                            headerElement.attributeValue("group-id"));
393    
394                    portletDataContext.setSourceGroupId(sourceGroupId);
395    
396                    // Read asset categories, asset tags, comments, locks, and ratings
397                    // entries to make them available to the data handlers through the
398                    // context
399    
400                    if (importPermissions) {
401                            _permissionImporter.readPortletDataPermissions(portletDataContext);
402                    }
403    
404                    readAssetCategories(portletDataContext);
405                    readAssetTags(portletDataContext);
406                    readComments(portletDataContext);
407                    readExpandoTables(portletDataContext);
408                    readLocks(portletDataContext);
409                    readRatingsEntries(portletDataContext);
410    
411                    // Delete portlet data
412    
413                    if (_log.isDebugEnabled()) {
414                            _log.debug("Deleting portlet data");
415                    }
416    
417                    if (deletePortletData) {
418                            deletePortletData(portletDataContext, portletId, plid);
419                    }
420    
421                    Element portletElement = null;
422    
423                    try {
424                            portletElement = rootElement.element("portlet");
425    
426                            Document portletDocument = SAXReaderUtil.read(
427                                    portletDataContext.getZipEntryAsString(
428                                            portletElement.attributeValue("path")));
429    
430                            portletElement = portletDocument.getRootElement();
431                    }
432                    catch (DocumentException de) {
433                            throw new SystemException(de);
434                    }
435    
436                    setPortletScope(portletDataContext, portletElement);
437    
438                    try {
439    
440                            // Portlet preferences
441    
442                            importPortletPreferences(
443                                    portletDataContext, layout.getCompanyId(), groupId, layout,
444                                    portletId, portletElement, importPortletSetup,
445                                    importPortletArchivedSetups, importPortletUserPreferences,
446                                    true);
447    
448                            // Portlet data
449    
450                            Element portletDataElement = portletElement.element("portlet-data");
451    
452                            if (importPortletData && (portletDataElement != null)) {
453                                    if (_log.isDebugEnabled()) {
454                                            _log.debug("Importing portlet data");
455                                    }
456    
457                                    importPortletData(
458                                            portletDataContext, portletId, plid, portletDataElement);
459                            }
460                    }
461                    finally {
462                            resetPortletScope(portletDataContext, groupId);
463                    }
464    
465                    // Portlet permissions
466    
467                    if (importPermissions) {
468                            if (_log.isDebugEnabled()) {
469                                    _log.debug("Importing portlet permissions");
470                            }
471    
472                            LayoutCache layoutCache = new LayoutCache();
473    
474                            _permissionImporter.importPortletPermissions(
475                                    layoutCache, layout.getCompanyId(), groupId, userId, layout,
476                                    portletElement, portletId, importUserPermissions);
477    
478                            if ((userId > 0) &&
479                                    ((PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5) ||
480                                     (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6))) {
481    
482                                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
483    
484                                    indexer.reindex(userId);
485                            }
486                    }
487    
488                    // Asset links
489    
490                    if (_log.isDebugEnabled()) {
491                            _log.debug("Importing asset links");
492                    }
493    
494                    readAssetLinks(portletDataContext);
495    
496                    if (_log.isInfoEnabled()) {
497                            _log.info("Importing portlet takes " + stopWatch.getTime() + " ms");
498                    }
499    
500                    zipReader.close();
501            }
502    
503            /**
504             * @see {@link DLPortletDataHandlerImpl#getFileEntryTypeName(String, long,
505             *      long, String, int)}
506             * @see {@link DLPortletDataHandlerImpl#getFolderName(String, long, long,
507             *      String, int)}
508             */
509            protected String getAssetCategoryName(
510                            String uuid, long parentCategoryId, String name, int count)
511                    throws Exception {
512    
513                    AssetCategory assetCategory = null;
514    
515                    try {
516                            assetCategory = AssetCategoryUtil.findByP_N_First(
517                                    parentCategoryId, name, null);
518                    }
519                    catch (NoSuchCategoryException nsce) {
520                            return name;
521                    }
522    
523                    if (Validator.isNotNull(uuid) && uuid.equals(assetCategory.getUuid())) {
524                            return name;
525                    }
526    
527                    name = StringUtil.appendParentheticalSuffix(name, count);
528    
529                    return getAssetCategoryName(uuid, parentCategoryId, name, ++count);
530            }
531    
532            protected String getAssetCategoryPath(
533                    PortletDataContext portletDataContext, long assetCategoryId) {
534    
535                    StringBundler sb = new StringBundler(6);
536    
537                    sb.append(portletDataContext.getSourceRootPath());
538                    sb.append("/categories/");
539                    sb.append(assetCategoryId);
540                    sb.append(".xml");
541    
542                    return sb.toString();
543            }
544    
545            protected Map<Locale, String> getAssetCategoryTitleMap(
546                    AssetCategory assetCategory, String name) {
547    
548                    Map<Locale, String> titleMap = assetCategory.getTitleMap();
549    
550                    if (titleMap == null) {
551                            titleMap = new HashMap<Locale, String>();
552                    }
553    
554                    Locale locale = LocaleUtil.getDefault();
555    
556                    titleMap.put(locale, name);
557    
558                    return titleMap;
559            }
560    
561            /**
562             * @see {@link DLPortletDataHandlerImpl#getFileEntryTypeName(String, long,
563             *      long, String, int)}
564             * @see {@link DLPortletDataHandlerImpl#getFolderName(String, long, long,
565             *      String, int)}
566             */
567            protected String getAssetVocabularyName(
568                            String uuid, long groupId, String name, int count)
569                    throws Exception {
570    
571                    AssetVocabulary assetVocabulary = AssetVocabularyUtil.fetchByG_N(
572                            groupId, name);
573    
574                    if (assetVocabulary == null) {
575                            return name;
576                    }
577    
578                    if (Validator.isNotNull(uuid) &&
579                            uuid.equals(assetVocabulary.getUuid())) {
580    
581                            return name;
582                    }
583    
584                    name = StringUtil.appendParentheticalSuffix(name, count);
585    
586                    return getAssetVocabularyName(uuid, groupId, name, ++count);
587            }
588    
589            protected Map<Locale, String> getAssetVocabularyTitleMap(
590                    AssetVocabulary assetVocabulary, String name) {
591    
592                    Map<Locale, String> titleMap = assetVocabulary.getTitleMap();
593    
594                    if (titleMap == null) {
595                            titleMap = new HashMap<Locale, String>();
596                    }
597    
598                    Locale locale = LocaleUtil.getDefault();
599    
600                    titleMap.put(locale, name);
601    
602                    return titleMap;
603            }
604    
605            protected UserIdStrategy getUserIdStrategy(
606                    User user, String userIdStrategy) {
607    
608                    if (UserIdStrategy.ALWAYS_CURRENT_USER_ID.equals(userIdStrategy)) {
609                            return new AlwaysCurrentUserIdStrategy(user);
610                    }
611    
612                    return new CurrentUserIdStrategy(user);
613            }
614    
615            protected void importAssetCategory(
616                            PortletDataContext portletDataContext,
617                            Map<Long, Long> assetVocabularyPKs,
618                            Map<Long, Long> assetCategoryPKs,
619                            Map<String, String> assetCategoryUuids,
620                            Element assetCategoryElement, AssetCategory assetCategory)
621                    throws Exception {
622    
623                    long userId = portletDataContext.getUserId(assetCategory.getUserUuid());
624                    long assetVocabularyId = MapUtil.getLong(
625                            assetVocabularyPKs, assetCategory.getVocabularyId(),
626                            assetCategory.getVocabularyId());
627                    long parentAssetCategoryId = MapUtil.getLong(
628                            assetCategoryPKs, assetCategory.getParentCategoryId(),
629                            assetCategory.getParentCategoryId());
630    
631                    if ((parentAssetCategoryId !=
632                                    AssetCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) &&
633                            (parentAssetCategoryId == assetCategory.getParentCategoryId())) {
634    
635                            String path = getAssetCategoryPath(
636                                    portletDataContext, parentAssetCategoryId);
637    
638                            AssetCategory parentAssetCategory =
639                                    (AssetCategory)portletDataContext.getZipEntryAsObject(path);
640    
641                            Node parentCategoryNode =
642                                    assetCategoryElement.getParent().selectSingleNode(
643                                            "./category[@path='" + path + "']");
644    
645                            if (parentCategoryNode != null) {
646                                    importAssetCategory(
647                                            portletDataContext, assetVocabularyPKs, assetCategoryPKs,
648                                            assetCategoryUuids, (Element)parentCategoryNode,
649                                            parentAssetCategory);
650    
651                                    parentAssetCategoryId = MapUtil.getLong(
652                                            assetCategoryPKs, assetCategory.getParentCategoryId(),
653                                            assetCategory.getParentCategoryId());
654                            }
655                    }
656    
657                    ServiceContext serviceContext = new ServiceContext();
658    
659                    serviceContext.setAddGroupPermissions(true);
660                    serviceContext.setAddGuestPermissions(true);
661                    serviceContext.setCreateDate(assetCategory.getCreateDate());
662                    serviceContext.setModifiedDate(assetCategory.getModifiedDate());
663                    serviceContext.setScopeGroupId(portletDataContext.getScopeGroupId());
664    
665                    AssetCategory importedAssetCategory = null;
666    
667                    try {
668                            if (parentAssetCategoryId !=
669                                            AssetCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) {
670    
671                                    AssetCategoryUtil.findByPrimaryKey(parentAssetCategoryId);
672                            }
673    
674                            List<Element> propertyElements = assetCategoryElement.elements(
675                                    "property");
676    
677                            String[] properties = new String[propertyElements.size()];
678    
679                            for (int i = 0; i < propertyElements.size(); i++) {
680                                    Element propertyElement = propertyElements.get(i);
681    
682                                    String key = propertyElement.attributeValue("key");
683                                    String value = propertyElement.attributeValue("value");
684    
685                                    properties[i] = key.concat(StringPool.COLON).concat(value);
686                            }
687    
688                            AssetCategory existingAssetCategory =
689                                    AssetCategoryUtil.fetchByUUID_G(
690                                            assetCategory.getUuid(),
691                                            portletDataContext.getScopeGroupId());
692    
693                            if (existingAssetCategory == null) {
694                                    String name = getAssetCategoryName(
695                                            null, parentAssetCategoryId, assetCategory.getName(), 2);
696    
697                                    serviceContext.setUuid(assetCategory.getUuid());
698    
699                                    importedAssetCategory =
700                                            AssetCategoryLocalServiceUtil.addCategory(
701                                                    userId, parentAssetCategoryId,
702                                                    getAssetCategoryTitleMap(assetCategory, name),
703                                                    assetCategory.getDescriptionMap(), assetVocabularyId,
704                                                    properties, serviceContext);
705                            }
706                            else {
707                                    String name = getAssetCategoryName(
708                                            assetCategory.getUuid(), parentAssetCategoryId,
709                                            assetCategory.getName(), 2);
710    
711                                    importedAssetCategory =
712                                            AssetCategoryLocalServiceUtil.updateCategory(
713                                                    userId, existingAssetCategory.getCategoryId(),
714                                                    parentAssetCategoryId,
715                                                    getAssetCategoryTitleMap(assetCategory, name),
716                                                    assetCategory.getDescriptionMap(), assetVocabularyId,
717                                                    properties, serviceContext);
718                            }
719    
720                            assetCategoryPKs.put(
721                                    assetCategory.getCategoryId(),
722                                    importedAssetCategory.getCategoryId());
723    
724                            assetCategoryUuids.put(
725                                    assetCategory.getUuid(), importedAssetCategory.getUuid());
726    
727                            portletDataContext.importPermissions(
728                                    AssetCategory.class, assetCategory.getCategoryId(),
729                                    importedAssetCategory.getCategoryId());
730                    }
731                    catch (NoSuchCategoryException nsce) {
732                            _log.error(
733                                    "Could not find the parent category for category " +
734                                            assetCategory.getCategoryId());
735                    }
736            }
737    
738            protected void importAssetTag(
739                            PortletDataContext portletDataContext, Map<Long, Long> assetTagPKs,
740                            Element assetTagElement, AssetTag assetTag)
741                    throws SystemException, PortalException {
742    
743                    long userId = portletDataContext.getUserId(assetTag.getUserUuid());
744    
745                    ServiceContext serviceContext = new ServiceContext();
746    
747                    serviceContext.setAddGroupPermissions(true);
748                    serviceContext.setAddGuestPermissions(true);
749                    serviceContext.setCreateDate(assetTag.getCreateDate());
750                    serviceContext.setModifiedDate(assetTag.getModifiedDate());
751                    serviceContext.setScopeGroupId(portletDataContext.getScopeGroupId());
752    
753                    AssetTag importedAssetTag = null;
754    
755                    List<Element> propertyElements = assetTagElement.elements("property");
756    
757                    String[] properties = new String[propertyElements.size()];
758    
759                    for (int i = 0; i < propertyElements.size(); i++) {
760                            Element propertyElement = propertyElements.get(i);
761    
762                            String key = propertyElement.attributeValue("key");
763                            String value = propertyElement.attributeValue("value");
764    
765                            properties[i] = key.concat(StringPool.COLON).concat(value);
766                    }
767    
768                    AssetTag existingAssetTag = null;
769    
770                    try {
771                            existingAssetTag = AssetTagUtil.findByG_N(
772                                    portletDataContext.getScopeGroupId(), assetTag.getName());
773                    }
774                    catch (NoSuchTagException nste) {
775                            if (_log.isDebugEnabled()) {
776                                    StringBundler sb = new StringBundler(5);
777    
778                                    sb.append("No AssetTag exists with the key {groupId=");
779                                    sb.append(portletDataContext.getScopeGroupId());
780                                    sb.append(", name=");
781                                    sb.append(assetTag.getName());
782                                    sb.append("}");
783    
784                                    _log.debug(sb.toString());
785                            }
786                    }
787    
788                    try {
789                            if (existingAssetTag == null) {
790                                    importedAssetTag = AssetTagLocalServiceUtil.addTag(
791                                            userId, assetTag.getName(), properties, serviceContext);
792                            }
793                            else {
794                                    importedAssetTag = AssetTagLocalServiceUtil.updateTag(
795                                            userId, existingAssetTag.getTagId(), assetTag.getName(),
796                                            properties, serviceContext);
797                            }
798    
799                            assetTagPKs.put(assetTag.getTagId(), importedAssetTag.getTagId());
800    
801                            portletDataContext.importPermissions(
802                                    AssetTag.class, assetTag.getTagId(),
803                                    importedAssetTag.getTagId());
804                    }
805                    catch (NoSuchTagException nste) {
806                            _log.error(
807                                    "Could not find the parent category for category " +
808                                            assetTag.getTagId());
809                    }
810            }
811    
812            protected void importAssetVocabulary(
813                            PortletDataContext portletDataContext,
814                            Map<Long, Long> assetVocabularyPKs, Element assetVocabularyElement,
815                            AssetVocabulary assetVocabulary)
816                    throws Exception {
817    
818                    long userId = portletDataContext.getUserId(
819                            assetVocabulary.getUserUuid());
820                    long groupId = portletDataContext.getScopeGroupId();
821    
822                    ServiceContext serviceContext = new ServiceContext();
823    
824                    serviceContext.setAddGroupPermissions(true);
825                    serviceContext.setAddGuestPermissions(true);
826                    serviceContext.setCreateDate(assetVocabulary.getCreateDate());
827                    serviceContext.setModifiedDate(assetVocabulary.getModifiedDate());
828                    serviceContext.setScopeGroupId(portletDataContext.getScopeGroupId());
829    
830                    AssetVocabulary importedAssetVocabulary = null;
831    
832                    AssetVocabulary existingAssetVocabulary =
833                            AssetVocabularyUtil.fetchByUUID_G(
834                                    assetVocabulary.getUuid(), groupId);
835    
836                    if (existingAssetVocabulary == null) {
837                            Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(
838                                    portletDataContext.getCompanyId());
839    
840                            existingAssetVocabulary = AssetVocabularyUtil.fetchByUUID_G(
841                                    assetVocabulary.getUuid(), companyGroup.getGroupId());
842                    }
843    
844                    if (existingAssetVocabulary == null) {
845                            String name = getAssetVocabularyName(
846                                    null, groupId, assetVocabulary.getName(), 2);
847    
848                            serviceContext.setUuid(assetVocabulary.getUuid());
849    
850                            importedAssetVocabulary =
851                                    AssetVocabularyLocalServiceUtil.addVocabulary(
852                                            userId, StringPool.BLANK,
853                                            getAssetVocabularyTitleMap(assetVocabulary, name),
854                                            assetVocabulary.getDescriptionMap(),
855                                            assetVocabulary.getSettings(), serviceContext);
856                    }
857                    else {
858                            String name = getAssetVocabularyName(
859                                    assetVocabulary.getUuid(), groupId, assetVocabulary.getName(),
860                                    2);
861    
862                            importedAssetVocabulary =
863                                    AssetVocabularyLocalServiceUtil.updateVocabulary(
864                                            existingAssetVocabulary.getVocabularyId(), StringPool.BLANK,
865                                            getAssetVocabularyTitleMap(assetVocabulary, name),
866                                            assetVocabulary.getDescriptionMap(),
867                                            assetVocabulary.getSettings(), serviceContext);
868                    }
869    
870                    assetVocabularyPKs.put(
871                            assetVocabulary.getVocabularyId(),
872                            importedAssetVocabulary.getVocabularyId());
873    
874                    portletDataContext.importPermissions(
875                            AssetVocabulary.class, assetVocabulary.getVocabularyId(),
876                            importedAssetVocabulary.getVocabularyId());
877            }
878    
879            protected void importPortletData(
880                            PortletDataContext portletDataContext, String portletId, long plid,
881                            Element portletDataElement)
882                    throws Exception {
883    
884                    long ownerId = PortletKeys.PREFS_OWNER_ID_DEFAULT;
885                    int ownerType = PortletKeys.PREFS_OWNER_TYPE_LAYOUT;
886    
887                    PortletPreferences portletPreferences =
888                            PortletPreferencesUtil.fetchByO_O_P_P(
889                                    ownerId, ownerType, plid, portletId);
890    
891                    if (portletPreferences == null) {
892                            portletPreferences =
893                                    new com.liferay.portal.model.impl.PortletPreferencesImpl();
894                    }
895    
896                    String xml = importPortletData(
897                            portletDataContext, portletId, portletPreferences,
898                            portletDataElement);
899    
900                    if (xml != null) {
901                            PortletPreferencesLocalServiceUtil.updatePreferences(
902                                    ownerId, ownerType, plid, portletId, xml);
903                    }
904            }
905    
906            protected String importPortletData(
907                            PortletDataContext portletDataContext, String portletId,
908                            PortletPreferences portletPreferences, Element portletDataElement)
909                    throws Exception {
910    
911                    Portlet portlet = PortletLocalServiceUtil.getPortletById(
912                            portletDataContext.getCompanyId(), portletId);
913    
914                    if (portlet == null) {
915                            if (_log.isDebugEnabled()) {
916                                    _log.debug(
917                                            "Do not import portlet data for " + portletId +
918                                                    " because the portlet does not exist");
919                            }
920    
921                            return null;
922                    }
923    
924                    PortletDataHandler portletDataHandler =
925                            portlet.getPortletDataHandlerInstance();
926    
927                    if (portletDataHandler == null) {
928                            if (_log.isDebugEnabled()) {
929                                    _log.debug(
930                                            "Do not import portlet data for " + portletId +
931                                                    " because the portlet does not have a " +
932                                                            "PortletDataHandler");
933                            }
934    
935                            return null;
936                    }
937    
938                    if (_log.isDebugEnabled()) {
939                            _log.debug("Importing data for " + portletId);
940                    }
941    
942                    PortletPreferencesImpl portletPreferencesImpl = null;
943    
944                    if (portletPreferences != null) {
945                            portletPreferencesImpl =
946                                    (PortletPreferencesImpl)
947                                            PortletPreferencesFactoryUtil.fromDefaultXML(
948                                                    portletPreferences.getPreferences());
949                    }
950    
951                    String portletData = portletDataContext.getZipEntryAsString(
952                            portletDataElement.attributeValue("path"));
953    
954                    try {
955                            portletPreferencesImpl =
956                                    (PortletPreferencesImpl)portletDataHandler.importData(
957                                            portletDataContext, portletId, portletPreferencesImpl,
958                                            portletData);
959                    }
960                    catch (Exception e) {
961                            throw e;
962                    }
963    
964                    if (portletPreferencesImpl == null) {
965                            return null;
966                    }
967    
968                    return PortletPreferencesFactoryUtil.toXML(portletPreferencesImpl);
969            }
970    
971            protected void importPortletPreferences(
972                            PortletDataContext portletDataContext, long companyId, long groupId,
973                            Layout layout, String portletId, Element parentElement,
974                            boolean importPortletSetup, boolean importPortletArchivedSetups,
975                            boolean importPortletUserPreferences, boolean preserveScopeLayoutId)
976                    throws Exception {
977    
978                    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId);
979                    long plid = 0;
980                    String scopeType = StringPool.BLANK;
981                    String scopeLayoutUuid = StringPool.BLANK;
982    
983                    if (layout != null) {
984                            plid = layout.getPlid();
985    
986                            if (preserveScopeLayoutId && (portletId != null)) {
987                                    javax.portlet.PortletPreferences jxPreferences =
988                                            PortletPreferencesFactoryUtil.getLayoutPortletSetup(
989                                                    layout, portletId);
990    
991                                    scopeType = GetterUtil.getString(
992                                            jxPreferences.getValue("lfrScopeType", null));
993                                    scopeLayoutUuid = GetterUtil.getString(
994                                            jxPreferences.getValue("lfrScopeLayoutUuid", null));
995    
996                                    portletDataContext.setScopeType(scopeType);
997                                    portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);
998                            }
999                    }
1000    
1001                    List<Element> portletPreferencesElements = parentElement.elements(
1002                            "portlet-preferences");
1003    
1004                    for (Element portletPreferencesElement : portletPreferencesElements) {
1005                            String path = portletPreferencesElement.attributeValue("path");
1006    
1007                            if (portletDataContext.isPathNotProcessed(path)) {
1008                                    String xml = null;
1009    
1010                                    Element element = null;
1011    
1012                                    try {
1013                                            xml = portletDataContext.getZipEntryAsString(path);
1014    
1015                                            Document preferencesDocument = SAXReaderUtil.read(xml);
1016    
1017                                            element = preferencesDocument.getRootElement();
1018                                    }
1019                                    catch (DocumentException de) {
1020                                            throw new SystemException(de);
1021                                    }
1022    
1023                                    long ownerId = GetterUtil.getLong(
1024                                            element.attributeValue("owner-id"));
1025                                    int ownerType = GetterUtil.getInteger(
1026                                            element.attributeValue("owner-type"));
1027    
1028                                    if (ownerType == PortletKeys.PREFS_OWNER_TYPE_COMPANY) {
1029                                            continue;
1030                                    }
1031    
1032                                    if (((ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP) ||
1033                                             (ownerType == PortletKeys.PREFS_OWNER_TYPE_LAYOUT)) &&
1034                                            !importPortletSetup) {
1035    
1036                                            continue;
1037                                    }
1038    
1039                                    if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) &&
1040                                            !importPortletArchivedSetups) {
1041    
1042                                            continue;
1043                                    }
1044    
1045                                    if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_USER) &&
1046                                            (ownerId != PortletKeys.PREFS_OWNER_ID_DEFAULT) &&
1047                                            !importPortletUserPreferences) {
1048    
1049                                            continue;
1050                                    }
1051    
1052                                    if (ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP) {
1053                                            plid = PortletKeys.PREFS_PLID_SHARED;
1054                                            ownerId = portletDataContext.getScopeGroupId();
1055                                    }
1056    
1057                                    boolean defaultUser = GetterUtil.getBoolean(
1058                                            element.attributeValue("default-user"));
1059    
1060                                    if (portletId == null) {
1061                                            portletId = element.attributeValue("portlet-id");
1062                                    }
1063    
1064                                    if (ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) {
1065                                            portletId = PortletConstants.getRootPortletId(portletId);
1066    
1067                                            String userUuid = element.attributeValue(
1068                                                    "archive-user-uuid");
1069                                            String name = element.attributeValue("archive-name");
1070    
1071                                            long userId = portletDataContext.getUserId(userUuid);
1072    
1073                                            PortletItem portletItem =
1074                                                    PortletItemLocalServiceUtil.updatePortletItem(
1075                                                            userId, groupId, name, portletId,
1076                                                            PortletPreferences.class.getName());
1077    
1078                                            plid = 0;
1079                                            ownerId = portletItem.getPortletItemId();
1080                                    }
1081                                    else if (ownerType == PortletKeys.PREFS_OWNER_TYPE_USER) {
1082                                            String userUuid = element.attributeValue("user-uuid");
1083    
1084                                            ownerId = portletDataContext.getUserId(userUuid);
1085                                    }
1086    
1087                                    if (defaultUser) {
1088                                            ownerId = defaultUserId;
1089                                    }
1090    
1091                                    xml = checkPortletPreferences(
1092                                            portletDataContext, companyId, ownerId, ownerType, plid,
1093                                            portletId, xml);
1094    
1095                                    PortletPreferencesLocalServiceUtil.updatePreferences(
1096                                            ownerId, ownerType, plid, portletId, xml);
1097                            }
1098                    }
1099    
1100                    if (preserveScopeLayoutId && (layout != null)) {
1101                            javax.portlet.PortletPreferences jxPreferences =
1102                                    PortletPreferencesFactoryUtil.getLayoutPortletSetup(
1103                                            layout, portletId);
1104    
1105                            try {
1106                                    jxPreferences.setValue("lfrScopeType", scopeType);
1107                                    jxPreferences.setValue("lfrScopeLayoutUuid", scopeLayoutUuid);
1108    
1109                                    jxPreferences.store();
1110                            }
1111                            finally {
1112                                    portletDataContext.setScopeType(scopeType);
1113                                    portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);
1114                            }
1115                    }
1116            }
1117    
1118            protected void readAssetCategories(PortletDataContext portletDataContext)
1119                    throws Exception {
1120    
1121                    String xml = portletDataContext.getZipEntryAsString(
1122                            portletDataContext.getSourceRootPath() +
1123                                    "/categories-hierarchy.xml");
1124    
1125                    if (xml == null) {
1126                            return;
1127                    }
1128    
1129                    Document document = SAXReaderUtil.read(xml);
1130    
1131                    Element rootElement = document.getRootElement();
1132    
1133                    Element assetVocabulariesElement = rootElement.element("vocabularies");
1134    
1135                    List<Element> assetVocabularyElements =
1136                            assetVocabulariesElement.elements("vocabulary");
1137    
1138                    Map<Long, Long> assetVocabularyPKs =
1139                            (Map<Long, Long>)portletDataContext.getNewPrimaryKeysMap(
1140                                    AssetVocabulary.class);
1141    
1142                    for (Element assetVocabularyElement : assetVocabularyElements) {
1143                            String path = assetVocabularyElement.attributeValue("path");
1144    
1145                            if (!portletDataContext.isPathNotProcessed(path)) {
1146                                    continue;
1147                            }
1148    
1149                            AssetVocabulary assetVocabulary =
1150                                    (AssetVocabulary)portletDataContext.getZipEntryAsObject(path);
1151    
1152                            importAssetVocabulary(
1153                                    portletDataContext, assetVocabularyPKs, assetVocabularyElement,
1154                                    assetVocabulary);
1155                    }
1156    
1157                    Element assetCategoriesElement = rootElement.element("categories");
1158    
1159                    List<Element> assetCategoryElements = assetCategoriesElement.elements(
1160                            "category");
1161    
1162                    Map<Long, Long> assetCategoryPKs =
1163                            (Map<Long, Long>)portletDataContext.getNewPrimaryKeysMap(
1164                                    AssetCategory.class);
1165    
1166                    Map<String, String> assetCategoryUuids =
1167                            (Map<String, String>)portletDataContext.getNewPrimaryKeysMap(
1168                                    AssetCategory.class.getName() + "uuid");
1169    
1170                    for (Element assetCategoryElement : assetCategoryElements) {
1171                            String path = assetCategoryElement.attributeValue("path");
1172    
1173                            if (!portletDataContext.isPathNotProcessed(path)) {
1174                                    continue;
1175                            }
1176    
1177                            AssetCategory assetCategory =
1178                                    (AssetCategory)portletDataContext.getZipEntryAsObject(path);
1179    
1180                            importAssetCategory(
1181                                    portletDataContext, assetVocabularyPKs, assetCategoryPKs,
1182                                    assetCategoryUuids, assetCategoryElement, assetCategory);
1183                    }
1184    
1185                    Element assetsElement = rootElement.element("assets");
1186    
1187                    List<Element> assetElements = assetsElement.elements("asset");
1188    
1189                    for (Element assetElement : assetElements) {
1190                            String className = GetterUtil.getString(
1191                                    assetElement.attributeValue("class-name"));
1192                            long classPK = GetterUtil.getLong(
1193                                    assetElement.attributeValue("class-pk"));
1194                            String[] assetCategoryUuidArray = StringUtil.split(
1195                                    GetterUtil.getString(
1196                                            assetElement.attributeValue("category-uuids")));
1197    
1198                            long[] assetCategoryIds = new long[0];
1199    
1200                            for (String assetCategoryUuid : assetCategoryUuidArray) {
1201                                    assetCategoryUuid = MapUtil.getString(
1202                                            assetCategoryUuids, assetCategoryUuid, assetCategoryUuid);
1203    
1204                                    AssetCategory assetCategory = AssetCategoryUtil.fetchByUUID_G(
1205                                            assetCategoryUuid, portletDataContext.getScopeGroupId());
1206    
1207                                    if (assetCategory == null) {
1208                                            Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(
1209                                                    portletDataContext.getCompanyId());
1210    
1211                                            assetCategory = AssetCategoryUtil.fetchByUUID_G(
1212                                                    assetCategoryUuid, companyGroup.getGroupId());
1213                                    }
1214    
1215                                    if (assetCategory != null) {
1216                                            assetCategoryIds = ArrayUtil.append(
1217                                                    assetCategoryIds, assetCategory.getCategoryId());
1218                                    }
1219                            }
1220    
1221                            portletDataContext.addAssetCategories(
1222                                    className, classPK, assetCategoryIds);
1223                    }
1224            }
1225    
1226            protected void readAssetLinks(PortletDataContext portletDataContext)
1227                    throws Exception {
1228    
1229                    String xml = portletDataContext.getZipEntryAsString(
1230                            portletDataContext.getSourceRootPath() + "/links.xml");
1231    
1232                    if (xml == null) {
1233                            return;
1234                    }
1235    
1236                    Document document = SAXReaderUtil.read(xml);
1237    
1238                    Element rootElement = document.getRootElement();
1239    
1240                    List<Element> assetLinkElements = rootElement.elements("asset-link");
1241    
1242                    for (Element assetLinkElement : assetLinkElements) {
1243                            String sourceUuid = GetterUtil.getString(
1244                                    assetLinkElement.attributeValue("source-uuid"));
1245                            String[] assetEntryUuidArray = StringUtil.split(
1246                                    GetterUtil.getString(
1247                                            assetLinkElement.attributeValue("target-uuids")));
1248                            int assetLinkType = GetterUtil.getInteger(
1249                                    assetLinkElement.attributeValue("type"));
1250    
1251                            List<Long> assetEntryIds = new ArrayList<Long>();
1252    
1253                            for (String assetEntryUuid : assetEntryUuidArray) {
1254                                    try {
1255                                            AssetEntry assetEntry = AssetEntryLocalServiceUtil.getEntry(
1256                                                    portletDataContext.getScopeGroupId(), assetEntryUuid);
1257    
1258                                            assetEntryIds.add(assetEntry.getEntryId());
1259                                    }
1260                                    catch (NoSuchEntryException nsee) {
1261                                    }
1262                            }
1263    
1264                            if (assetEntryIds.isEmpty()) {
1265                                    continue;
1266                            }
1267    
1268                            long[] assetEntryIdsArray = ArrayUtil.toArray(
1269                                    assetEntryIds.toArray(new Long[assetEntryIds.size()]));
1270    
1271                            try {
1272                                    AssetEntry assetEntry = AssetEntryLocalServiceUtil.getEntry(
1273                                            portletDataContext.getScopeGroupId(), sourceUuid);
1274    
1275                                    AssetLinkLocalServiceUtil.updateLinks(
1276                                            assetEntry.getUserId(), assetEntry.getEntryId(),
1277                                            assetEntryIdsArray, assetLinkType);
1278                            }
1279                            catch (NoSuchEntryException nsee) {
1280                            }
1281                    }
1282            }
1283    
1284            protected void readAssetTags(PortletDataContext portletDataContext)
1285                    throws Exception {
1286    
1287                    String xml = portletDataContext.getZipEntryAsString(
1288                            portletDataContext.getSourceRootPath() + "/tags.xml");
1289    
1290                    if (xml == null) {
1291                            return;
1292                    }
1293    
1294                    Document document = SAXReaderUtil.read(xml);
1295    
1296                    Element rootElement = document.getRootElement();
1297    
1298                    List<Element> assetTagElements = rootElement.elements("tag");
1299    
1300                    for (Element assetTagElement : assetTagElements) {
1301                            String path = assetTagElement.attributeValue("path");
1302    
1303                            if (!portletDataContext.isPathNotProcessed(path)) {
1304                                    continue;
1305                            }
1306    
1307                            AssetTag assetTag =
1308                                    (AssetTag)portletDataContext.getZipEntryAsObject(path);
1309    
1310                            Map<Long, Long> assetTagPKs =
1311                                    (Map<Long, Long>)portletDataContext.getNewPrimaryKeysMap(
1312                                            AssetTag.class);
1313    
1314                            importAssetTag(
1315                                    portletDataContext, assetTagPKs, assetTagElement, assetTag);
1316                    }
1317    
1318                    List<Element> assetElements = rootElement.elements("asset");
1319    
1320                    for (Element assetElement : assetElements) {
1321                            String className = GetterUtil.getString(
1322                                    assetElement.attributeValue("class-name"));
1323                            long classPK = GetterUtil.getLong(
1324                                    assetElement.attributeValue("class-pk"));
1325                            String assetTagNames = GetterUtil.getString(
1326                                    assetElement.attributeValue("tags"));
1327    
1328                            portletDataContext.addAssetTags(
1329                                    className, classPK, StringUtil.split(assetTagNames));
1330                    }
1331            }
1332    
1333            protected void readComments(PortletDataContext portletDataContext)
1334                    throws Exception {
1335    
1336                    String xml = portletDataContext.getZipEntryAsString(
1337                            portletDataContext.getSourceRootPath() + "/comments.xml");
1338    
1339                    if (xml == null) {
1340                            return;
1341                    }
1342    
1343                    Document document = SAXReaderUtil.read(xml);
1344    
1345                    Element rootElement = document.getRootElement();
1346    
1347                    List<Element> assetElements = rootElement.elements("asset");
1348    
1349                    for (Element assetElement : assetElements) {
1350                            String path = assetElement.attributeValue("path");
1351                            String className = assetElement.attributeValue("class-name");
1352                            long classPK = GetterUtil.getLong(
1353                                    assetElement.attributeValue("class-pk"));
1354    
1355                            List<String> zipFolderEntries =
1356                                    portletDataContext.getZipFolderEntries(path);
1357    
1358                            List<MBMessage> mbMessages = new ArrayList<MBMessage>();
1359    
1360                            for (String zipFolderEntry : zipFolderEntries) {
1361                                    MBMessage mbMessage =
1362                                            (MBMessage)portletDataContext.getZipEntryAsObject(
1363                                                    zipFolderEntry);
1364    
1365                                    if (mbMessage != null) {
1366                                            mbMessages.add(mbMessage);
1367                                    }
1368                            }
1369    
1370                            portletDataContext.addComments(className, classPK, mbMessages);
1371                    }
1372            }
1373    
1374            protected void readExpandoTables(PortletDataContext portletDataContext)
1375                    throws Exception {
1376    
1377                    String xml = portletDataContext.getZipEntryAsString(
1378                            portletDataContext.getSourceRootPath() + "/expando-tables.xml");
1379    
1380                    if (xml == null) {
1381                            return;
1382                    }
1383    
1384                    Document document = SAXReaderUtil.read(xml);
1385    
1386                    Element rootElement = document.getRootElement();
1387    
1388                    List<Element> expandoTableElements = rootElement.elements(
1389                            "expando-table");
1390    
1391                    for (Element expandoTableElement : expandoTableElements) {
1392                            String className = expandoTableElement.attributeValue("class-name");
1393    
1394                            ExpandoTable expandoTable = null;
1395    
1396                            try {
1397                                    expandoTable = ExpandoTableLocalServiceUtil.getDefaultTable(
1398                                            portletDataContext.getCompanyId(), className);
1399                            }
1400                            catch (NoSuchTableException nste) {
1401                                    expandoTable = ExpandoTableLocalServiceUtil.addDefaultTable(
1402                                            portletDataContext.getCompanyId(), className);
1403                            }
1404    
1405                            List<Element> expandoColumnElements = expandoTableElement.elements(
1406                                    "expando-column");
1407    
1408                            for (Element expandoColumnElement : expandoColumnElements) {
1409                                    long columnId = GetterUtil.getLong(
1410                                            expandoColumnElement.attributeValue("column-id"));
1411                                    String name = expandoColumnElement.attributeValue("name");
1412                                    int type = GetterUtil.getInteger(
1413                                            expandoColumnElement.attributeValue("type"));
1414                                    String defaultData = expandoColumnElement.elementText(
1415                                            "default-data");
1416                                    String typeSettings = expandoColumnElement.elementText(
1417                                            "type-settings");
1418    
1419                                    Serializable defaultDataObject =
1420                                            ExpandoConverterUtil.getAttributeFromString(
1421                                                    type, defaultData);
1422    
1423                                    ExpandoColumn expandoColumn =
1424                                            ExpandoColumnLocalServiceUtil.getColumn(
1425                                                    expandoTable.getTableId(), name);
1426    
1427                                    if (expandoColumn != null) {
1428                                            ExpandoColumnLocalServiceUtil.updateColumn(
1429                                                    expandoColumn.getColumnId(), name, type,
1430                                                    defaultDataObject);
1431                                    }
1432                                    else {
1433                                            expandoColumn = ExpandoColumnLocalServiceUtil.addColumn(
1434                                                    expandoTable.getTableId(), name, type,
1435                                                    defaultDataObject);
1436                                    }
1437    
1438                                    ExpandoColumnLocalServiceUtil.updateTypeSettings(
1439                                            expandoColumn.getColumnId(), typeSettings);
1440    
1441                                    portletDataContext.importPermissions(
1442                                            ExpandoColumn.class, columnId, expandoColumn.getColumnId());
1443                            }
1444                    }
1445            }
1446    
1447            protected void readLocks(PortletDataContext portletDataContext)
1448                    throws Exception {
1449    
1450                    String xml = portletDataContext.getZipEntryAsString(
1451                            portletDataContext.getSourceRootPath() + "/locks.xml");
1452    
1453                    if (xml == null) {
1454                            return;
1455                    }
1456    
1457                    Document document = SAXReaderUtil.read(xml);
1458    
1459                    Element rootElement = document.getRootElement();
1460    
1461                    List<Element> assetElements = rootElement.elements("asset");
1462    
1463                    for (Element assetElement : assetElements) {
1464                            String path = assetElement.attributeValue("path");
1465                            String className = assetElement.attributeValue("class-name");
1466                            String key = assetElement.attributeValue("key");
1467    
1468                            Lock lock = (Lock)portletDataContext.getZipEntryAsObject(path);
1469    
1470                            if (lock != null) {
1471                                    portletDataContext.addLocks(className, key, lock);
1472                            }
1473                    }
1474            }
1475    
1476            protected void readRatingsEntries(PortletDataContext portletDataContext)
1477                    throws Exception {
1478    
1479                    String xml = portletDataContext.getZipEntryAsString(
1480                            portletDataContext.getSourceRootPath() + "/ratings.xml");
1481    
1482                    if (xml == null) {
1483                            return;
1484                    }
1485    
1486                    Document document = SAXReaderUtil.read(xml);
1487    
1488                    Element rootElement = document.getRootElement();
1489    
1490                    List<Element> assetElements = rootElement.elements("asset");
1491    
1492                    for (Element assetElement : assetElements) {
1493                            String path = assetElement.attributeValue("path");
1494                            String className = assetElement.attributeValue("class-name");
1495                            long classPK = GetterUtil.getLong(
1496                                    assetElement.attributeValue("class-pk"));
1497    
1498                            List<String> zipFolderEntries =
1499                                    portletDataContext.getZipFolderEntries(path);
1500    
1501                            List<RatingsEntry> ratingsEntries = new ArrayList<RatingsEntry>();
1502    
1503                            for (String zipFolderEntry : zipFolderEntries) {
1504                                    RatingsEntry ratingsEntry =
1505                                            (RatingsEntry)portletDataContext.getZipEntryAsObject(
1506                                                    zipFolderEntry);
1507    
1508                                    if (ratingsEntry != null) {
1509                                            ratingsEntries.add(ratingsEntry);
1510                                    }
1511                            }
1512    
1513                            portletDataContext.addRatingsEntries(
1514                                    className, classPK, ratingsEntries);
1515                    }
1516            }
1517    
1518            protected void resetPortletScope(
1519                    PortletDataContext portletDataContext, long groupId) {
1520    
1521                    portletDataContext.setScopeGroupId(groupId);
1522                    portletDataContext.setScopeLayoutUuid(StringPool.BLANK);
1523                    portletDataContext.setScopeType(StringPool.BLANK);
1524            }
1525    
1526            protected void setPortletScope(
1527                    PortletDataContext portletDataContext, Element portletElement) {
1528    
1529                    // Portlet data scope
1530    
1531                    String scopeLayoutUuid = GetterUtil.getString(
1532                            portletElement.attributeValue("scope-layout-uuid"));
1533                    String scopeLayoutType = GetterUtil.getString(
1534                            portletElement.attributeValue("scope-layout-type"));
1535    
1536                    portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);
1537                    portletDataContext.setScopeType(scopeLayoutType);
1538    
1539                    // Layout scope
1540    
1541                    try {
1542                            Group scopeGroup = null;
1543    
1544                            if (scopeLayoutType.equals("company")) {
1545                                    scopeGroup = GroupLocalServiceUtil.getCompanyGroup(
1546                                            portletDataContext.getCompanyId());
1547                            }
1548                            else if (Validator.isNotNull(scopeLayoutUuid)) {
1549                                    Layout scopeLayout =
1550                                            LayoutLocalServiceUtil.getLayoutByUuidAndGroupId(
1551                                                    scopeLayoutUuid, portletDataContext.getGroupId());
1552    
1553                                    if (scopeLayout.hasScopeGroup()) {
1554                                            scopeGroup = scopeLayout.getScopeGroup();
1555                                    }
1556                                    else {
1557                                            String name = String.valueOf(scopeLayout.getPlid());
1558    
1559                                            scopeGroup = GroupLocalServiceUtil.addGroup(
1560                                                    portletDataContext.getUserId(null),
1561                                                    Layout.class.getName(), scopeLayout.getPlid(), name,
1562                                                    null, 0, null, false, true, null);
1563                                    }
1564    
1565                                    Group group = scopeLayout.getGroup();
1566    
1567                                    if (group.isStaged() && !group.isStagedRemotely()) {
1568                                            try {
1569                                                    Layout oldLayout =
1570                                                            LayoutLocalServiceUtil.getLayoutByUuidAndGroupId(
1571                                                                    scopeLayoutUuid,
1572                                                                    portletDataContext.getSourceGroupId());
1573    
1574                                                    Group oldScopeGroup = oldLayout.getScopeGroup();
1575    
1576                                                    oldScopeGroup.setLiveGroupId(scopeGroup.getGroupId());
1577    
1578                                                    GroupLocalServiceUtil.updateGroup(oldScopeGroup, true);
1579                                            }
1580                                            catch (NoSuchLayoutException nsle) {
1581                                                    if (_log.isWarnEnabled()) {
1582                                                            _log.warn(nsle);
1583                                                    }
1584                                            }
1585                                    }
1586    
1587                                    portletDataContext.setScopeGroupId(scopeGroup.getGroupId());
1588                            }
1589                    }
1590                    catch (PortalException pe) {
1591                    }
1592                    catch (Exception e) {
1593                            _log.error(e, e);
1594                    }
1595            }
1596    
1597            private static Log _log = LogFactoryUtil.getLog(PortletImporter.class);
1598    
1599            private PermissionImporter _permissionImporter = new PermissionImporter();
1600    
1601    }