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