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.LocaleException;
021    import com.liferay.portal.NoSuchGroupException;
022    import com.liferay.portal.NoSuchLayoutException;
023    import com.liferay.portal.PortletIdException;
024    import com.liferay.portal.kernel.exception.PortalException;
025    import com.liferay.portal.kernel.exception.SystemException;
026    import com.liferay.portal.kernel.language.LanguageUtil;
027    import com.liferay.portal.kernel.lar.ExportImportThreadLocal;
028    import com.liferay.portal.kernel.lar.PortletDataContext;
029    import com.liferay.portal.kernel.lar.PortletDataHandler;
030    import com.liferay.portal.kernel.lar.PortletDataHandlerKeys;
031    import com.liferay.portal.kernel.lar.UserIdStrategy;
032    import com.liferay.portal.kernel.log.Log;
033    import com.liferay.portal.kernel.log.LogFactoryUtil;
034    import com.liferay.portal.kernel.search.Indexer;
035    import com.liferay.portal.kernel.search.IndexerRegistryUtil;
036    import com.liferay.portal.kernel.util.ArrayUtil;
037    import com.liferay.portal.kernel.util.GetterUtil;
038    import com.liferay.portal.kernel.util.LocaleUtil;
039    import com.liferay.portal.kernel.util.MapUtil;
040    import com.liferay.portal.kernel.util.ReleaseInfo;
041    import com.liferay.portal.kernel.util.StringBundler;
042    import com.liferay.portal.kernel.util.StringPool;
043    import com.liferay.portal.kernel.util.StringUtil;
044    import com.liferay.portal.kernel.util.Validator;
045    import com.liferay.portal.kernel.xml.Document;
046    import com.liferay.portal.kernel.xml.DocumentException;
047    import com.liferay.portal.kernel.xml.Element;
048    import com.liferay.portal.kernel.xml.Node;
049    import com.liferay.portal.kernel.xml.SAXReaderUtil;
050    import com.liferay.portal.kernel.zip.ZipReader;
051    import com.liferay.portal.kernel.zip.ZipReaderFactoryUtil;
052    import com.liferay.portal.model.Company;
053    import com.liferay.portal.model.Group;
054    import com.liferay.portal.model.GroupConstants;
055    import com.liferay.portal.model.Layout;
056    import com.liferay.portal.model.Lock;
057    import com.liferay.portal.model.Portlet;
058    import com.liferay.portal.model.PortletConstants;
059    import com.liferay.portal.model.PortletItem;
060    import com.liferay.portal.model.PortletPreferences;
061    import com.liferay.portal.model.User;
062    import com.liferay.portal.security.permission.ActionKeys;
063    import com.liferay.portal.security.permission.PermissionCacheUtil;
064    import com.liferay.portal.security.permission.PermissionChecker;
065    import com.liferay.portal.security.permission.PermissionThreadLocal;
066    import com.liferay.portal.service.CompanyLocalServiceUtil;
067    import com.liferay.portal.service.GroupLocalServiceUtil;
068    import com.liferay.portal.service.LayoutLocalServiceUtil;
069    import com.liferay.portal.service.PortletItemLocalServiceUtil;
070    import com.liferay.portal.service.PortletLocalServiceUtil;
071    import com.liferay.portal.service.PortletPreferencesLocalServiceUtil;
072    import com.liferay.portal.service.ServiceContext;
073    import com.liferay.portal.service.UserLocalServiceUtil;
074    import com.liferay.portal.service.persistence.PortletPreferencesUtil;
075    import com.liferay.portal.service.persistence.UserUtil;
076    import com.liferay.portal.servlet.filters.cache.CacheUtil;
077    import com.liferay.portal.util.PortalUtil;
078    import com.liferay.portal.util.PortletKeys;
079    import com.liferay.portlet.PortletPreferencesFactoryUtil;
080    import com.liferay.portlet.PortletPreferencesImpl;
081    import com.liferay.portlet.asset.NoSuchCategoryException;
082    import com.liferay.portlet.asset.NoSuchEntryException;
083    import com.liferay.portlet.asset.NoSuchTagException;
084    import com.liferay.portlet.asset.model.AssetCategory;
085    import com.liferay.portlet.asset.model.AssetCategoryConstants;
086    import com.liferay.portlet.asset.model.AssetEntry;
087    import com.liferay.portlet.asset.model.AssetTag;
088    import com.liferay.portlet.asset.model.AssetVocabulary;
089    import com.liferay.portlet.asset.service.AssetCategoryLocalServiceUtil;
090    import com.liferay.portlet.asset.service.AssetEntryLocalServiceUtil;
091    import com.liferay.portlet.asset.service.AssetLinkLocalServiceUtil;
092    import com.liferay.portlet.asset.service.AssetTagLocalServiceUtil;
093    import com.liferay.portlet.asset.service.AssetVocabularyLocalServiceUtil;
094    import com.liferay.portlet.asset.service.permission.AssetPermission;
095    import com.liferay.portlet.asset.service.persistence.AssetCategoryUtil;
096    import com.liferay.portlet.asset.service.persistence.AssetTagUtil;
097    import com.liferay.portlet.asset.service.persistence.AssetVocabularyUtil;
098    import com.liferay.portlet.assetpublisher.util.AssetPublisherUtil;
099    import com.liferay.portlet.dynamicdatamapping.model.DDMStructure;
100    import com.liferay.portlet.dynamicdatamapping.service.persistence.DDMStructureUtil;
101    import com.liferay.portlet.expando.NoSuchTableException;
102    import com.liferay.portlet.expando.model.ExpandoColumn;
103    import com.liferay.portlet.expando.model.ExpandoTable;
104    import com.liferay.portlet.expando.service.ExpandoColumnLocalServiceUtil;
105    import com.liferay.portlet.expando.service.ExpandoTableLocalServiceUtil;
106    import com.liferay.portlet.expando.util.ExpandoConverterUtil;
107    import com.liferay.portlet.journalcontent.util.JournalContentUtil;
108    import com.liferay.portlet.messageboards.model.MBMessage;
109    import com.liferay.portlet.ratings.model.RatingsEntry;
110    
111    import java.io.File;
112    import java.io.Serializable;
113    
114    import java.util.ArrayList;
115    import java.util.Enumeration;
116    import java.util.HashMap;
117    import java.util.HashSet;
118    import java.util.List;
119    import java.util.Locale;
120    import java.util.Map;
121    
122    import org.apache.commons.lang.time.StopWatch;
123    
124    /**
125     * @author Brian Wing Shun Chan
126     * @author Joel Kozikowski
127     * @author Charles May
128     * @author Raymond Augé
129     * @author Jorge Ferrer
130     * @author Bruno Farache
131     * @author Zsigmond Rab
132     * @author Douglas Wong
133     * @author Mate Thurzo
134     */
135    public class PortletImporter {
136    
137            public void importPortletInfo(
138                            long userId, long plid, long groupId, String portletId,
139                            Map<String, String[]> parameterMap, File file)
140                    throws Exception {
141    
142                    try {
143                            ExportImportThreadLocal.setPortletImportInProcess(true);
144    
145                            doImportPortletInfo(
146                                    userId, plid, groupId, portletId, parameterMap, file);
147                    }
148                    finally {
149                            ExportImportThreadLocal.setPortletImportInProcess(false);
150    
151                            CacheUtil.clearCache();
152                            JournalContentUtil.clearCache();
153                            PermissionCacheUtil.clearCache();
154                    }
155            }
156    
157            protected void deletePortletData(
158                            PortletDataContext portletDataContext, String portletId, long plid)
159                    throws Exception {
160    
161                    long ownerId = PortletKeys.PREFS_OWNER_ID_DEFAULT;
162                    int ownerType = PortletKeys.PREFS_OWNER_TYPE_LAYOUT;
163    
164                    PortletPreferences portletPreferences =
165                            PortletPreferencesUtil.fetchByO_O_P_P(
166                                    ownerId, ownerType, plid, portletId);
167    
168                    if (portletPreferences == null) {
169                            portletPreferences =
170                                    new com.liferay.portal.model.impl.PortletPreferencesImpl();
171                    }
172    
173                    String xml = deletePortletData(
174                            portletDataContext, portletId, portletPreferences);
175    
176                    if (xml != null) {
177                            PortletPreferencesLocalServiceUtil.updatePreferences(
178                                    ownerId, ownerType, plid, portletId, xml);
179                    }
180            }
181    
182            protected String deletePortletData(
183                            PortletDataContext portletDataContext, String portletId,
184                            PortletPreferences portletPreferences)
185                    throws Exception {
186    
187                    Portlet portlet = PortletLocalServiceUtil.getPortletById(
188                            portletDataContext.getCompanyId(), portletId);
189    
190                    if (portlet == null) {
191                            if (_log.isDebugEnabled()) {
192                                    _log.debug(
193                                            "Do not delete portlet data for " + portletId +
194                                                    " because the portlet does not exist");
195                            }
196    
197                            return null;
198                    }
199    
200                    PortletDataHandler portletDataHandler =
201                            portlet.getPortletDataHandlerInstance();
202    
203                    if (portletDataHandler == null) {
204                            if (_log.isDebugEnabled()) {
205                                    _log.debug(
206                                            "Do not delete portlet data for " + portletId +
207                                                    " because the portlet does not have a " +
208                                                            "PortletDataHandler");
209                            }
210    
211                            return null;
212                    }
213    
214                    if (_log.isDebugEnabled()) {
215                            _log.debug("Deleting data for " + portletId);
216                    }
217    
218                    PortletPreferencesImpl portletPreferencesImpl =
219                            (PortletPreferencesImpl)
220                                    PortletPreferencesFactoryUtil.fromDefaultXML(
221                                            portletPreferences.getPreferences());
222    
223                    try {
224                            portletPreferencesImpl =
225                                    (PortletPreferencesImpl)portletDataHandler.deleteData(
226                                            portletDataContext, portletId, portletPreferencesImpl);
227                    }
228                    finally {
229                            portletDataContext.setGroupId(portletDataContext.getScopeGroupId());
230                    }
231    
232                    if (portletPreferencesImpl == null) {
233                            return null;
234                    }
235    
236                    return PortletPreferencesFactoryUtil.toXML(portletPreferencesImpl);
237            }
238    
239            protected void doImportPortletInfo(
240                            long userId, long plid, long groupId, String portletId,
241                            Map<String, String[]> parameterMap, File file)
242                    throws Exception {
243    
244                    boolean deletePortletData = MapUtil.getBoolean(
245                            parameterMap, PortletDataHandlerKeys.DELETE_PORTLET_DATA);
246                    boolean importCategories = MapUtil.getBoolean(
247                            parameterMap, PortletDataHandlerKeys.CATEGORIES);
248                    boolean importPermissions = MapUtil.getBoolean(
249                            parameterMap, PortletDataHandlerKeys.PERMISSIONS);
250                    boolean importPortletData = MapUtil.getBoolean(
251                            parameterMap, PortletDataHandlerKeys.PORTLET_DATA);
252                    boolean importPortletArchivedSetups = MapUtil.getBoolean(
253                            parameterMap, PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS);
254                    boolean importPortletSetup = MapUtil.getBoolean(
255                            parameterMap, PortletDataHandlerKeys.PORTLET_SETUP);
256                    boolean importPortletUserPreferences = MapUtil.getBoolean(
257                            parameterMap, PortletDataHandlerKeys.PORTLET_USER_PREFERENCES);
258                    String userIdStrategyString = MapUtil.getString(
259                            parameterMap, PortletDataHandlerKeys.USER_ID_STRATEGY);
260    
261                    StopWatch stopWatch = null;
262    
263                    if (_log.isInfoEnabled()) {
264                            stopWatch = new StopWatch();
265    
266                            stopWatch.start();
267                    }
268    
269                    Layout layout = LayoutLocalServiceUtil.getLayout(plid);
270    
271                    User user = UserUtil.findByPrimaryKey(userId);
272    
273                    UserIdStrategy userIdStrategy = getUserIdStrategy(
274                            user, userIdStrategyString);
275    
276                    ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(file);
277    
278                    PortletDataContext portletDataContext = new PortletDataContextImpl(
279                            layout.getCompanyId(), groupId, parameterMap, new HashSet<String>(),
280                            userIdStrategy, zipReader);
281    
282                    portletDataContext.setPortetDataContextListener(
283                            new PortletDataContextListenerImpl(portletDataContext));
284    
285                    portletDataContext.setPlid(plid);
286                    portletDataContext.setPrivateLayout(layout.isPrivateLayout());
287    
288                    // Manifest
289    
290                    String xml = portletDataContext.getZipEntryAsString("/manifest.xml");
291    
292                    Element rootElement = null;
293    
294                    try {
295                            Document document = SAXReaderUtil.read(xml);
296    
297                            rootElement = document.getRootElement();
298                    }
299                    catch (Exception e) {
300                            throw new LARFileException("Unable to read /manifest.xml");
301                    }
302    
303                    // Build compatibility
304    
305                    Element headerElement = rootElement.element("header");
306    
307                    int buildNumber = ReleaseInfo.getBuildNumber();
308    
309                    int importBuildNumber = GetterUtil.getInteger(
310                            headerElement.attributeValue("build-number"));
311    
312                    if (buildNumber != importBuildNumber) {
313                            throw new LayoutImportException(
314                                    "LAR build number " + importBuildNumber + " does not match " +
315                                            "portal build number " + buildNumber);
316                    }
317    
318                    // Type compatibility
319    
320                    String type = headerElement.attributeValue("type");
321    
322                    if (!type.equals("portlet")) {
323                            throw new LARTypeException(
324                                    "Invalid type of LAR file (" + type + ")");
325                    }
326    
327                    // Portlet compatibility
328    
329                    String rootPortletId = headerElement.attributeValue("root-portlet-id");
330    
331                    if (!PortletConstants.getRootPortletId(portletId).equals(
332                                    rootPortletId)) {
333    
334                            throw new PortletIdException("Invalid portlet id " + rootPortletId);
335                    }
336    
337                    // Available locales
338    
339                    Portlet portlet = PortletLocalServiceUtil.getPortletById(
340                            portletDataContext.getCompanyId(), portletId);
341    
342                    PortletDataHandler portletDataHandler =
343                            portlet.getPortletDataHandlerInstance();
344    
345                    if ((portletDataHandler != null) &&
346                            portletDataHandler.isDataLocalized()) {
347    
348                            Locale[] sourceAvailableLocales = LocaleUtil.fromLanguageIds(
349                                    StringUtil.split(
350                                            headerElement.attributeValue("available-locales")));
351    
352                            Locale[] targetAvailableLocales =
353                                    LanguageUtil.getAvailableLocales();
354    
355                            for (Locale sourceAvailableLocale : sourceAvailableLocales) {
356                                    if (!ArrayUtil.contains(
357                                                    targetAvailableLocales, sourceAvailableLocale)) {
358    
359                                            LocaleException le = new LocaleException(
360                                                    "Locale " + sourceAvailableLocale + " is not " +
361                                                            "available in company " + layout.getCompanyId());
362    
363                                            le.setSourceAvailableLocales(sourceAvailableLocales);
364                                            le.setTargetAvailableLocales(targetAvailableLocales);
365    
366                                            throw le;
367                                    }
368                            }
369                    }
370    
371                    // Import group id
372    
373                    long sourceGroupId = GetterUtil.getLong(
374                            headerElement.attributeValue("group-id"));
375    
376                    portletDataContext.setSourceGroupId(sourceGroupId);
377    
378                    // Read asset categories, asset tags, comments, locks, and ratings
379                    // entries to make them available to the data handlers through the
380                    // context
381    
382                    if (importPermissions) {
383                            _permissionImporter.readPortletDataPermissions(portletDataContext);
384                    }
385    
386                    if (importCategories) {
387                            readAssetCategories(portletDataContext);
388                    }
389    
390                    readAssetTags(portletDataContext);
391                    readComments(portletDataContext);
392                    readExpandoTables(portletDataContext);
393                    readLocks(portletDataContext);
394                    readRatingsEntries(portletDataContext);
395    
396                    // Delete portlet data
397    
398                    if (_log.isDebugEnabled()) {
399                            _log.debug("Deleting portlet data");
400                    }
401    
402                    if (deletePortletData) {
403                            deletePortletData(portletDataContext, portletId, plid);
404                    }
405    
406                    Element portletElement = null;
407    
408                    try {
409                            portletElement = rootElement.element("portlet");
410    
411                            Document portletDocument = SAXReaderUtil.read(
412                                    portletDataContext.getZipEntryAsString(
413                                            portletElement.attributeValue("path")));
414    
415                            portletElement = portletDocument.getRootElement();
416                    }
417                    catch (DocumentException de) {
418                            throw new SystemException(de);
419                    }
420    
421                    setPortletScope(portletDataContext, portletElement);
422    
423                    Element portletDataElement = portletElement.element("portlet-data");
424    
425                    boolean importData = importPortletData && (portletDataElement != null);
426    
427                    try {
428    
429                            // Portlet preferences
430    
431                            importPortletPreferences(
432                                    portletDataContext, layout.getCompanyId(), groupId, layout,
433                                    portletId, portletElement, importPortletSetup,
434                                    importPortletArchivedSetups, importPortletUserPreferences, true,
435                                    importData);
436    
437                            // Portlet data
438    
439                            if (importData) {
440                                    if (_log.isDebugEnabled()) {
441                                            _log.debug("Importing portlet data");
442                                    }
443    
444                                    importPortletData(
445                                            portletDataContext, portletId, plid, portletDataElement);
446                            }
447                    }
448                    finally {
449                            resetPortletScope(portletDataContext, groupId);
450                    }
451    
452                    // Portlet permissions
453    
454                    if (importPermissions) {
455                            if (_log.isDebugEnabled()) {
456                                    _log.debug("Importing portlet permissions");
457                            }
458    
459                            LayoutCache layoutCache = new LayoutCache();
460    
461                            _permissionImporter.importPortletPermissions(
462                                    layoutCache, layout.getCompanyId(), groupId, userId, layout,
463                                    portletElement, portletId);
464    
465                            if (userId > 0) {
466                                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
467                                            User.class);
468    
469                                    indexer.reindex(userId);
470                            }
471                    }
472    
473                    // Asset links
474    
475                    if (_log.isDebugEnabled()) {
476                            _log.debug("Importing asset links");
477                    }
478    
479                    readAssetLinks(portletDataContext);
480    
481                    if (_log.isInfoEnabled()) {
482                            _log.info("Importing portlet takes " + stopWatch.getTime() + " ms");
483                    }
484    
485                    zipReader.close();
486            }
487    
488            /**
489             * @see com.liferay.portlet.documentlibrary.lar.DLPortletDataHandler#getFileEntryTypeName(
490             *      String, long, String, int)
491             * @see com.liferay.portlet.documentlibrary.lar.DLPortletDataHandler#getFolderName(
492             *      String, long, long, String, int)
493             */
494            protected String getAssetCategoryName(
495                            String uuid, long groupId, long parentCategoryId, String name,
496                            long vocabularyId, int count)
497                    throws Exception {
498    
499                    AssetCategory assetCategory = null;
500    
501                    try {
502                            assetCategory = AssetCategoryUtil.findByG_P_N_V_First(
503                                    groupId, parentCategoryId, name, vocabularyId, null);
504                    }
505                    catch (NoSuchCategoryException nsce) {
506                            return name;
507                    }
508    
509                    if (Validator.isNotNull(uuid) && uuid.equals(assetCategory.getUuid())) {
510                            return name;
511                    }
512    
513                    name = StringUtil.appendParentheticalSuffix(name, count);
514    
515                    return getAssetCategoryName(
516                            uuid, groupId, parentCategoryId, name, vocabularyId, ++count);
517            }
518    
519            protected String getAssetCategoryPath(
520                    PortletDataContext portletDataContext, long assetCategoryId) {
521    
522                    StringBundler sb = new StringBundler(6);
523    
524                    sb.append(portletDataContext.getSourceRootPath());
525                    sb.append("/categories/");
526                    sb.append(assetCategoryId);
527                    sb.append(".xml");
528    
529                    return sb.toString();
530            }
531    
532            protected Map<Locale, String> getAssetCategoryTitleMap(
533                    AssetCategory assetCategory, String name) {
534    
535                    Map<Locale, String> titleMap = assetCategory.getTitleMap();
536    
537                    if (titleMap == null) {
538                            titleMap = new HashMap<Locale, String>();
539                    }
540    
541                    Locale locale = LocaleUtil.getDefault();
542    
543                    titleMap.put(locale, name);
544    
545                    return titleMap;
546            }
547    
548            /**
549             * @see com.liferay.portlet.documentlibrary.lar.DLPortletDataHandler#getFileEntryTypeName(
550             *      String, long, String, int)
551             * @see com.liferay.portlet.documentlibrary.lar.DLPortletDataHandler#getFolderName(
552             *      String, long, long, String, int)
553             */
554            protected String getAssetVocabularyName(
555                            String uuid, long groupId, String name, int count)
556                    throws Exception {
557    
558                    AssetVocabulary assetVocabulary = AssetVocabularyUtil.fetchByG_N(
559                            groupId, name);
560    
561                    if (assetVocabulary == null) {
562                            return name;
563                    }
564    
565                    if (Validator.isNotNull(uuid) &&
566                            uuid.equals(assetVocabulary.getUuid())) {
567    
568                            return name;
569                    }
570    
571                    name = StringUtil.appendParentheticalSuffix(name, count);
572    
573                    return getAssetVocabularyName(uuid, groupId, name, ++count);
574            }
575    
576            protected Map<Locale, String> getAssetVocabularyTitleMap(
577                    AssetVocabulary assetVocabulary, String name) {
578    
579                    Map<Locale, String> titleMap = assetVocabulary.getTitleMap();
580    
581                    if (titleMap == null) {
582                            titleMap = new HashMap<Locale, String>();
583                    }
584    
585                    Locale locale = LocaleUtil.getDefault();
586    
587                    titleMap.put(locale, name);
588    
589                    return titleMap;
590            }
591    
592            protected UserIdStrategy getUserIdStrategy(
593                    User user, String userIdStrategy) {
594    
595                    if (UserIdStrategy.ALWAYS_CURRENT_USER_ID.equals(userIdStrategy)) {
596                            return new AlwaysCurrentUserIdStrategy(user);
597                    }
598    
599                    return new CurrentUserIdStrategy(user);
600            }
601    
602            protected void importAssetCategory(
603                            PortletDataContext portletDataContext,
604                            Map<Long, Long> assetVocabularyPKs,
605                            Map<Long, Long> assetCategoryPKs,
606                            Map<String, String> assetCategoryUuids,
607                            Element assetCategoryElement, AssetCategory assetCategory)
608                    throws Exception {
609    
610                    long userId = portletDataContext.getUserId(assetCategory.getUserUuid());
611                    long groupId = portletDataContext.getGroupId();
612                    long assetVocabularyId = MapUtil.getLong(
613                            assetVocabularyPKs, assetCategory.getVocabularyId(),
614                            assetCategory.getVocabularyId());
615                    long parentAssetCategoryId = MapUtil.getLong(
616                            assetCategoryPKs, assetCategory.getParentCategoryId(),
617                            assetCategory.getParentCategoryId());
618    
619                    if ((parentAssetCategoryId !=
620                                    AssetCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) &&
621                            (parentAssetCategoryId == assetCategory.getParentCategoryId())) {
622    
623                            String path = getAssetCategoryPath(
624                                    portletDataContext, parentAssetCategoryId);
625    
626                            AssetCategory parentAssetCategory =
627                                    (AssetCategory)portletDataContext.getZipEntryAsObject(path);
628    
629                            Node parentCategoryNode =
630                                    assetCategoryElement.getParent().selectSingleNode(
631                                            "./category[@path='" + path + "']");
632    
633                            if (parentCategoryNode != null) {
634                                    importAssetCategory(
635                                            portletDataContext, assetVocabularyPKs, assetCategoryPKs,
636                                            assetCategoryUuids, (Element)parentCategoryNode,
637                                            parentAssetCategory);
638    
639                                    parentAssetCategoryId = MapUtil.getLong(
640                                            assetCategoryPKs, assetCategory.getParentCategoryId(),
641                                            assetCategory.getParentCategoryId());
642                            }
643                    }
644    
645                    ServiceContext serviceContext = new ServiceContext();
646    
647                    serviceContext.setAddGroupPermissions(true);
648                    serviceContext.setAddGuestPermissions(true);
649                    serviceContext.setCreateDate(assetCategory.getCreateDate());
650                    serviceContext.setModifiedDate(assetCategory.getModifiedDate());
651                    serviceContext.setScopeGroupId(portletDataContext.getScopeGroupId());
652    
653                    boolean global = GetterUtil.getBoolean(
654                            assetCategoryElement.attributeValue("global"));
655    
656                    if (global) {
657                            Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(
658                                    portletDataContext.getCompanyId());
659    
660                            groupId = companyGroup.getGroupId();
661                    }
662    
663                    AssetCategory importedAssetCategory = null;
664    
665                    try {
666                            if (parentAssetCategoryId !=
667                                            AssetCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) {
668    
669                                    AssetCategoryUtil.findByPrimaryKey(parentAssetCategoryId);
670                            }
671    
672                            List<Element> propertyElements = assetCategoryElement.elements(
673                                    "property");
674    
675                            String[] properties = new String[propertyElements.size()];
676    
677                            for (int i = 0; i < propertyElements.size(); i++) {
678                                    Element propertyElement = propertyElements.get(i);
679    
680                                    String key = propertyElement.attributeValue("key");
681                                    String value = propertyElement.attributeValue("value");
682    
683                                    properties[i] = key.concat(StringPool.COLON).concat(value);
684                            }
685    
686                            AssetCategory existingAssetCategory =
687                                    AssetCategoryUtil.fetchByUUID_G(
688                                            assetCategory.getUuid(), groupId);
689    
690                            if (existingAssetCategory == null) {
691                                    String name = getAssetCategoryName(
692                                            null, portletDataContext.getGroupId(),
693                                            parentAssetCategoryId, assetCategory.getName(),
694                                            assetCategory.getVocabularyId(), 2);
695    
696                                    serviceContext.setUuid(assetCategory.getUuid());
697    
698                                    if (global) {
699                                            if (AssetPermission.contains(
700                                                            PermissionThreadLocal.getPermissionChecker(),
701                                                            groupId, ActionKeys.ADD_CATEGORY)) {
702    
703                                                    serviceContext.setScopeGroupId(groupId);
704                                            }
705                                            else {
706                                                    StringBundler sb = new StringBundler(6);
707    
708                                                    sb.append("Category ");
709                                                    sb.append(assetCategory.getName());
710                                                    sb.append(" could not be imported to the Global ");
711                                                    sb.append("scope because the user does not have ");
712                                                    sb.append("permissions. It will be imported into the ");
713                                                    sb.append("current scope.");
714    
715                                                    _log.error(sb.toString());
716                                            }
717                                    }
718    
719                                    importedAssetCategory =
720                                            AssetCategoryLocalServiceUtil.addCategory(
721                                                    userId, parentAssetCategoryId,
722                                                    getAssetCategoryTitleMap(assetCategory, name),
723                                                    assetCategory.getDescriptionMap(), assetVocabularyId,
724                                                    properties, serviceContext);
725                            }
726                            else {
727                                    String name = getAssetCategoryName(
728                                            assetCategory.getUuid(), assetCategory.getGroupId(),
729                                            parentAssetCategoryId, assetCategory.getName(),
730                                            assetCategory.getVocabularyId(), 2);
731    
732                                    boolean updateAssetCategory = true;
733    
734                                    if (global) {
735                                            PermissionChecker permissionChecker =
736                                                    PermissionThreadLocal.getPermissionChecker();
737    
738                                            if (permissionChecker.hasPermission(
739                                                            groupId, AssetCategory.class.getName(),
740                                                            existingAssetCategory.getCategoryId(),
741                                                            ActionKeys.UPDATE)) {
742    
743                                                    serviceContext.setScopeGroupId(groupId);
744                                            }
745                                            else {
746                                                    updateAssetCategory = false;
747                                            }
748                                    }
749    
750                                    if (updateAssetCategory) {
751                                            importedAssetCategory =
752                                                    AssetCategoryLocalServiceUtil.updateCategory(
753                                                            userId, existingAssetCategory.getCategoryId(),
754                                                            parentAssetCategoryId,
755                                                            getAssetCategoryTitleMap(assetCategory, name),
756                                                            assetCategory.getDescriptionMap(),
757                                                            assetVocabularyId, properties, serviceContext);
758                                    }
759                                    else {
760                                            StringBundler sb = new StringBundler(4);
761    
762                                            sb.append("Category ");
763                                            sb.append(existingAssetCategory.getName());
764                                            sb.append(" could not be updated in the Global scope ");
765                                            sb.append("because the user does not have permissions.");
766    
767                                            _log.error(sb.toString());
768    
769                                            return;
770                                    }
771                            }
772    
773                            assetCategoryPKs.put(
774                                    assetCategory.getCategoryId(),
775                                    importedAssetCategory.getCategoryId());
776    
777                            assetCategoryUuids.put(
778                                    assetCategory.getUuid(), importedAssetCategory.getUuid());
779    
780                            portletDataContext.importPermissions(
781                                    AssetCategory.class, assetCategory.getCategoryId(),
782                                    importedAssetCategory.getCategoryId());
783                    }
784                    catch (NoSuchCategoryException nsce) {
785                            _log.error(
786                                    "Could not find the parent category for category " +
787                                            assetCategory.getCategoryId());
788                    }
789            }
790    
791            protected void importAssetTag(
792                            PortletDataContext portletDataContext, Map<Long, Long> assetTagPKs,
793                            Element assetTagElement, AssetTag assetTag)
794                    throws PortalException, SystemException {
795    
796                    long userId = portletDataContext.getUserId(assetTag.getUserUuid());
797    
798                    ServiceContext serviceContext = new ServiceContext();
799    
800                    serviceContext.setAddGroupPermissions(true);
801                    serviceContext.setAddGuestPermissions(true);
802                    serviceContext.setCreateDate(assetTag.getCreateDate());
803                    serviceContext.setModifiedDate(assetTag.getModifiedDate());
804                    serviceContext.setScopeGroupId(portletDataContext.getScopeGroupId());
805    
806                    AssetTag importedAssetTag = null;
807    
808                    List<Element> propertyElements = assetTagElement.elements("property");
809    
810                    String[] properties = new String[propertyElements.size()];
811    
812                    for (int i = 0; i < propertyElements.size(); i++) {
813                            Element propertyElement = propertyElements.get(i);
814    
815                            String key = propertyElement.attributeValue("key");
816                            String value = propertyElement.attributeValue("value");
817    
818                            properties[i] = key.concat(StringPool.COLON).concat(value);
819                    }
820    
821                    AssetTag existingAssetTag = null;
822    
823                    try {
824                            existingAssetTag = AssetTagUtil.findByG_N(
825                                    portletDataContext.getScopeGroupId(), assetTag.getName());
826                    }
827                    catch (NoSuchTagException nste) {
828                            if (_log.isDebugEnabled()) {
829                                    StringBundler sb = new StringBundler(5);
830    
831                                    sb.append("No AssetTag exists with the key {groupId=");
832                                    sb.append(portletDataContext.getScopeGroupId());
833                                    sb.append(", name=");
834                                    sb.append(assetTag.getName());
835                                    sb.append("}");
836    
837                                    _log.debug(sb.toString());
838                            }
839                    }
840    
841                    try {
842                            if (existingAssetTag == null) {
843                                    importedAssetTag = AssetTagLocalServiceUtil.addTag(
844                                            userId, assetTag.getName(), properties, serviceContext);
845                            }
846                            else {
847                                    importedAssetTag = AssetTagLocalServiceUtil.updateTag(
848                                            userId, existingAssetTag.getTagId(), assetTag.getName(),
849                                            properties, serviceContext);
850                            }
851    
852                            assetTagPKs.put(assetTag.getTagId(), importedAssetTag.getTagId());
853    
854                            portletDataContext.importPermissions(
855                                    AssetTag.class, assetTag.getTagId(),
856                                    importedAssetTag.getTagId());
857                    }
858                    catch (NoSuchTagException nste) {
859                            _log.error(
860                                    "Could not find the parent category for category " +
861                                            assetTag.getTagId());
862                    }
863            }
864    
865            protected void importAssetVocabulary(
866                            PortletDataContext portletDataContext,
867                            Map<Long, Long> assetVocabularyPKs, Element assetVocabularyElement,
868                            AssetVocabulary assetVocabulary)
869                    throws Exception {
870    
871                    long userId = portletDataContext.getUserId(
872                            assetVocabulary.getUserUuid());
873                    long groupId = portletDataContext.getScopeGroupId();
874    
875                    ServiceContext serviceContext = new ServiceContext();
876    
877                    serviceContext.setAddGroupPermissions(true);
878                    serviceContext.setAddGuestPermissions(true);
879                    serviceContext.setCreateDate(assetVocabulary.getCreateDate());
880                    serviceContext.setModifiedDate(assetVocabulary.getModifiedDate());
881                    serviceContext.setScopeGroupId(portletDataContext.getScopeGroupId());
882    
883                    boolean global = GetterUtil.getBoolean(
884                            assetVocabularyElement.attributeValue("global"));
885    
886                    if (global) {
887                            Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(
888                                    portletDataContext.getCompanyId());
889    
890                            groupId = companyGroup.getGroupId();
891                    }
892    
893                    AssetVocabulary importedAssetVocabulary = null;
894    
895                    AssetVocabulary existingAssetVocabulary =
896                            AssetVocabularyUtil.fetchByUUID_G(
897                                    assetVocabulary.getUuid(), groupId);
898    
899                    if (existingAssetVocabulary == null) {
900                            String name = getAssetVocabularyName(
901                                    null, groupId, assetVocabulary.getName(), 2);
902    
903                            serviceContext.setUuid(assetVocabulary.getUuid());
904    
905                            if (global) {
906                                    if (AssetPermission.contains(
907                                                    PermissionThreadLocal.getPermissionChecker(), groupId,
908                                                    ActionKeys.ADD_VOCABULARY)) {
909    
910                                            serviceContext.setScopeGroupId(groupId);
911                                    }
912                                    else {
913                                            StringBundler sb = new StringBundler(5);
914    
915                                            sb.append("Vocabulary ");
916                                            sb.append(assetVocabulary.getName());
917                                            sb.append(" could not be imported to the Global scope ");
918                                            sb.append("because the user does not have permissions. ");
919                                            sb.append("It will be imported into the current scope.");
920    
921                                            _log.error(sb.toString());
922                                    }
923                            }
924    
925                            importedAssetVocabulary =
926                                    AssetVocabularyLocalServiceUtil.addVocabulary(
927                                            userId, StringPool.BLANK,
928                                            getAssetVocabularyTitleMap(assetVocabulary, name),
929                                            assetVocabulary.getDescriptionMap(),
930                                            assetVocabulary.getSettings(), serviceContext);
931                    }
932                    else {
933                            String name = getAssetVocabularyName(
934                                    assetVocabulary.getUuid(), groupId, assetVocabulary.getName(),
935                                    2);
936    
937                            boolean updateVocabulary = true;
938    
939                            if (global) {
940                                    PermissionChecker permissionChecker =
941                                            PermissionThreadLocal.getPermissionChecker();
942    
943                                    if (permissionChecker.hasPermission(
944                                                    groupId, AssetVocabulary.class.getName(),
945                                                    existingAssetVocabulary.getVocabularyId(),
946                                                    ActionKeys.UPDATE)) {
947    
948                                            serviceContext.setScopeGroupId(groupId);
949                                    }
950                                    else {
951                                            updateVocabulary = false;
952                                    }
953                            }
954    
955                            if (updateVocabulary) {
956                                    importedAssetVocabulary =
957                                            AssetVocabularyLocalServiceUtil.updateVocabulary(
958                                                    existingAssetVocabulary.getVocabularyId(),
959                                                    StringPool.BLANK,
960                                                    getAssetVocabularyTitleMap(assetVocabulary, name),
961                                                    assetVocabulary.getDescriptionMap(),
962                                                    assetVocabulary.getSettings(), serviceContext);
963                            }
964                            else {
965                                    StringBundler sb = new StringBundler(4);
966    
967                                    sb.append("Vocabulary ");
968                                    sb.append(existingAssetVocabulary.getName());
969                                    sb.append(" could not be updated in the Global scope because ");
970                                    sb.append("the user does not have permissions.");
971    
972                                    _log.error(sb.toString());
973    
974                                    return;
975                            }
976                    }
977    
978                    assetVocabularyPKs.put(
979                            assetVocabulary.getVocabularyId(),
980                            importedAssetVocabulary.getVocabularyId());
981    
982                    portletDataContext.importPermissions(
983                            AssetVocabulary.class, assetVocabulary.getVocabularyId(),
984                            importedAssetVocabulary.getVocabularyId());
985            }
986    
987            protected void importPortletData(
988                            PortletDataContext portletDataContext, String portletId, long plid,
989                            Element portletDataElement)
990                    throws Exception {
991    
992                    long ownerId = PortletKeys.PREFS_OWNER_ID_DEFAULT;
993                    int ownerType = PortletKeys.PREFS_OWNER_TYPE_LAYOUT;
994    
995                    PortletPreferences portletPreferences =
996                            PortletPreferencesUtil.fetchByO_O_P_P(
997                                    ownerId, ownerType, plid, portletId);
998    
999                    if (portletPreferences == null) {
1000                            portletPreferences =
1001                                    new com.liferay.portal.model.impl.PortletPreferencesImpl();
1002                    }
1003    
1004                    String xml = importPortletData(
1005                            portletDataContext, portletId, portletPreferences,
1006                            portletDataElement);
1007    
1008                    if (Validator.isNotNull(xml)) {
1009                            PortletPreferencesLocalServiceUtil.updatePreferences(
1010                                    ownerId, ownerType, plid, portletId, xml);
1011                    }
1012            }
1013    
1014            protected String importPortletData(
1015                            PortletDataContext portletDataContext, String portletId,
1016                            PortletPreferences portletPreferences, Element portletDataElement)
1017                    throws Exception {
1018    
1019                    Portlet portlet = PortletLocalServiceUtil.getPortletById(
1020                            portletDataContext.getCompanyId(), portletId);
1021    
1022                    if (portlet == null) {
1023                            if (_log.isDebugEnabled()) {
1024                                    _log.debug(
1025                                            "Do not import portlet data for " + portletId +
1026                                                    " because the portlet does not exist");
1027                            }
1028    
1029                            return null;
1030                    }
1031    
1032                    PortletDataHandler portletDataHandler =
1033                            portlet.getPortletDataHandlerInstance();
1034    
1035                    if (portletDataHandler == null) {
1036                            if (_log.isDebugEnabled()) {
1037                                    _log.debug(
1038                                            "Do not import portlet data for " + portletId +
1039                                                    " because the portlet does not have a " +
1040                                                            "PortletDataHandler");
1041                            }
1042    
1043                            return null;
1044                    }
1045    
1046                    if (_log.isDebugEnabled()) {
1047                            _log.debug("Importing data for " + portletId);
1048                    }
1049    
1050                    PortletPreferencesImpl portletPreferencesImpl = null;
1051    
1052                    if (portletPreferences != null) {
1053                            portletPreferencesImpl =
1054                                    (PortletPreferencesImpl)
1055                                            PortletPreferencesFactoryUtil.fromDefaultXML(
1056                                                    portletPreferences.getPreferences());
1057                    }
1058    
1059                    String portletData = portletDataContext.getZipEntryAsString(
1060                            portletDataElement.attributeValue("path"));
1061    
1062                    portletPreferencesImpl =
1063                            (PortletPreferencesImpl)portletDataHandler.importData(
1064                                    portletDataContext, portletId, portletPreferencesImpl,
1065                                    portletData);
1066    
1067                    if (portletPreferencesImpl == null) {
1068                            return null;
1069                    }
1070    
1071                    return PortletPreferencesFactoryUtil.toXML(portletPreferencesImpl);
1072            }
1073    
1074            protected void importPortletPreferences(
1075                            PortletDataContext portletDataContext, long companyId, long groupId,
1076                            Layout layout, String portletId, Element parentElement,
1077                            boolean importPortletSetup, boolean importPortletArchivedSetups,
1078                            boolean importPortletUserPreferences, boolean preserveScopeLayoutId,
1079                            boolean importPortletData)
1080                    throws Exception {
1081    
1082                    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId);
1083                    long plid = 0;
1084                    String scopeType = StringPool.BLANK;
1085                    String scopeLayoutUuid = StringPool.BLANK;
1086    
1087                    if (layout != null) {
1088                            plid = layout.getPlid();
1089    
1090                            if (preserveScopeLayoutId && (portletId != null)) {
1091                                    javax.portlet.PortletPreferences jxPreferences =
1092                                            PortletPreferencesFactoryUtil.getLayoutPortletSetup(
1093                                                    layout, portletId);
1094    
1095                                    scopeType = GetterUtil.getString(
1096                                            jxPreferences.getValue("lfrScopeType", null));
1097                                    scopeLayoutUuid = GetterUtil.getString(
1098                                            jxPreferences.getValue("lfrScopeLayoutUuid", null));
1099    
1100                                    portletDataContext.setScopeType(scopeType);
1101                                    portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);
1102                            }
1103                    }
1104    
1105                    List<Element> portletPreferencesElements = parentElement.elements(
1106                            "portlet-preferences");
1107    
1108                    for (Element portletPreferencesElement : portletPreferencesElements) {
1109                            String path = portletPreferencesElement.attributeValue("path");
1110    
1111                            if (portletDataContext.isPathNotProcessed(path)) {
1112                                    String xml = null;
1113    
1114                                    Element element = null;
1115    
1116                                    try {
1117                                            xml = portletDataContext.getZipEntryAsString(path);
1118    
1119                                            Document preferencesDocument = SAXReaderUtil.read(xml);
1120    
1121                                            element = preferencesDocument.getRootElement();
1122                                    }
1123                                    catch (DocumentException de) {
1124                                            throw new SystemException(de);
1125                                    }
1126    
1127                                    long ownerId = GetterUtil.getLong(
1128                                            element.attributeValue("owner-id"));
1129                                    int ownerType = GetterUtil.getInteger(
1130                                            element.attributeValue("owner-type"));
1131    
1132                                    if (ownerType == PortletKeys.PREFS_OWNER_TYPE_COMPANY) {
1133                                            continue;
1134                                    }
1135    
1136                                    if (((ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP) ||
1137                                             (ownerType == PortletKeys.PREFS_OWNER_TYPE_LAYOUT)) &&
1138                                            !importPortletSetup) {
1139    
1140                                            continue;
1141                                    }
1142    
1143                                    if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) &&
1144                                            !importPortletArchivedSetups) {
1145    
1146                                            continue;
1147                                    }
1148    
1149                                    if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_USER) &&
1150                                            (ownerId != PortletKeys.PREFS_OWNER_ID_DEFAULT) &&
1151                                            !importPortletUserPreferences) {
1152    
1153                                            continue;
1154                                    }
1155    
1156                                    if (ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP) {
1157                                            plid = PortletKeys.PREFS_PLID_SHARED;
1158                                            ownerId = portletDataContext.getScopeGroupId();
1159                                    }
1160    
1161                                    boolean defaultUser = GetterUtil.getBoolean(
1162                                            element.attributeValue("default-user"));
1163    
1164                                    if (portletId == null) {
1165                                            portletId = element.attributeValue("portlet-id");
1166                                    }
1167    
1168                                    if (ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) {
1169                                            portletId = PortletConstants.getRootPortletId(portletId);
1170    
1171                                            String userUuid = element.attributeValue(
1172                                                    "archive-user-uuid");
1173                                            String name = element.attributeValue("archive-name");
1174    
1175                                            long userId = portletDataContext.getUserId(userUuid);
1176    
1177                                            PortletItem portletItem =
1178                                                    PortletItemLocalServiceUtil.updatePortletItem(
1179                                                            userId, groupId, name, portletId,
1180                                                            PortletPreferences.class.getName());
1181    
1182                                            plid = 0;
1183                                            ownerId = portletItem.getPortletItemId();
1184                                    }
1185                                    else if (ownerType == PortletKeys.PREFS_OWNER_TYPE_USER) {
1186                                            String userUuid = element.attributeValue("user-uuid");
1187    
1188                                            ownerId = portletDataContext.getUserId(userUuid);
1189                                    }
1190    
1191                                    if (defaultUser) {
1192                                            ownerId = defaultUserId;
1193                                    }
1194    
1195                                    String rootPotletId = PortletConstants.getRootPortletId(
1196                                            portletId);
1197    
1198                                    if (rootPotletId.equals(PortletKeys.ASSET_PUBLISHER)) {
1199                                            xml = updateAssetPublisherPortletPreferences(
1200                                                    portletDataContext, companyId, ownerId, ownerType, plid,
1201                                                    portletId, xml, layout);
1202                                    }
1203                                    else if (rootPotletId.equals(
1204                                                            PortletKeys.TAGS_CATEGORIES_NAVIGATION)) {
1205    
1206                                            xml = updateAssetCategoriesNavigationPortletPreferences(
1207                                                    portletDataContext, companyId, ownerId, ownerType, plid,
1208                                                    portletId, xml);
1209                                    }
1210    
1211                                    updatePortletPreferences(
1212                                            portletDataContext, ownerId, ownerType, plid, portletId,
1213                                            xml, importPortletData);
1214                            }
1215                    }
1216    
1217                    if (preserveScopeLayoutId && (layout != null)) {
1218                            javax.portlet.PortletPreferences jxPreferences =
1219                                    PortletPreferencesFactoryUtil.getLayoutPortletSetup(
1220                                            layout, portletId);
1221    
1222                            try {
1223                                    jxPreferences.setValue("lfrScopeType", scopeType);
1224                                    jxPreferences.setValue("lfrScopeLayoutUuid", scopeLayoutUuid);
1225    
1226                                    jxPreferences.store();
1227                            }
1228                            finally {
1229                                    portletDataContext.setScopeType(scopeType);
1230                                    portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);
1231                            }
1232                    }
1233            }
1234    
1235            protected void readAssetCategories(PortletDataContext portletDataContext)
1236                    throws Exception {
1237    
1238                    String xml = portletDataContext.getZipEntryAsString(
1239                            portletDataContext.getSourceRootPath() +
1240                                    "/categories-hierarchy.xml");
1241    
1242                    if (xml == null) {
1243                            return;
1244                    }
1245    
1246                    Document document = SAXReaderUtil.read(xml);
1247    
1248                    Element rootElement = document.getRootElement();
1249    
1250                    Element assetVocabulariesElement = rootElement.element("vocabularies");
1251    
1252                    List<Element> assetVocabularyElements =
1253                            assetVocabulariesElement.elements("vocabulary");
1254    
1255                    Map<Long, Long> assetVocabularyPKs =
1256                            (Map<Long, Long>)portletDataContext.getNewPrimaryKeysMap(
1257                                    AssetVocabulary.class);
1258    
1259                    for (Element assetVocabularyElement : assetVocabularyElements) {
1260                            String path = assetVocabularyElement.attributeValue("path");
1261    
1262                            if (!portletDataContext.isPathNotProcessed(path)) {
1263                                    continue;
1264                            }
1265    
1266                            AssetVocabulary assetVocabulary =
1267                                    (AssetVocabulary)portletDataContext.getZipEntryAsObject(path);
1268    
1269                            importAssetVocabulary(
1270                                    portletDataContext, assetVocabularyPKs, assetVocabularyElement,
1271                                    assetVocabulary);
1272                    }
1273    
1274                    Element assetCategoriesElement = rootElement.element("categories");
1275    
1276                    List<Element> assetCategoryElements = assetCategoriesElement.elements(
1277                            "category");
1278    
1279                    Map<Long, Long> assetCategoryPKs =
1280                            (Map<Long, Long>)portletDataContext.getNewPrimaryKeysMap(
1281                                    AssetCategory.class);
1282    
1283                    Map<String, String> assetCategoryUuids =
1284                            (Map<String, String>)portletDataContext.getNewPrimaryKeysMap(
1285                                    AssetCategory.class.getName() + "uuid");
1286    
1287                    for (Element assetCategoryElement : assetCategoryElements) {
1288                            String path = assetCategoryElement.attributeValue("path");
1289    
1290                            if (!portletDataContext.isPathNotProcessed(path)) {
1291                                    continue;
1292                            }
1293    
1294                            AssetCategory assetCategory =
1295                                    (AssetCategory)portletDataContext.getZipEntryAsObject(path);
1296    
1297                            importAssetCategory(
1298                                    portletDataContext, assetVocabularyPKs, assetCategoryPKs,
1299                                    assetCategoryUuids, assetCategoryElement, assetCategory);
1300                    }
1301    
1302                    Element assetsElement = rootElement.element("assets");
1303    
1304                    List<Element> assetElements = assetsElement.elements("asset");
1305    
1306                    for (Element assetElement : assetElements) {
1307                            String className = GetterUtil.getString(
1308                                    assetElement.attributeValue("class-name"));
1309                            long classPK = GetterUtil.getLong(
1310                                    assetElement.attributeValue("class-pk"));
1311                            String[] assetCategoryUuidArray = StringUtil.split(
1312                                    GetterUtil.getString(
1313                                            assetElement.attributeValue("category-uuids")));
1314    
1315                            long[] assetCategoryIds = new long[0];
1316    
1317                            for (String assetCategoryUuid : assetCategoryUuidArray) {
1318                                    assetCategoryUuid = MapUtil.getString(
1319                                            assetCategoryUuids, assetCategoryUuid, assetCategoryUuid);
1320    
1321                                    AssetCategory assetCategory = AssetCategoryUtil.fetchByUUID_G(
1322                                            assetCategoryUuid, portletDataContext.getScopeGroupId());
1323    
1324                                    if (assetCategory == null) {
1325                                            Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(
1326                                                    portletDataContext.getCompanyId());
1327    
1328                                            assetCategory = AssetCategoryUtil.fetchByUUID_G(
1329                                                    assetCategoryUuid, companyGroup.getGroupId());
1330                                    }
1331    
1332                                    if (assetCategory != null) {
1333                                            assetCategoryIds = ArrayUtil.append(
1334                                                    assetCategoryIds, assetCategory.getCategoryId());
1335                                    }
1336                            }
1337    
1338                            portletDataContext.addAssetCategories(
1339                                    className, classPK, assetCategoryIds);
1340                    }
1341            }
1342    
1343            protected void readAssetLinks(PortletDataContext portletDataContext)
1344                    throws Exception {
1345    
1346                    String xml = portletDataContext.getZipEntryAsString(
1347                            portletDataContext.getSourceRootPath() + "/links.xml");
1348    
1349                    if (xml == null) {
1350                            return;
1351                    }
1352    
1353                    Document document = SAXReaderUtil.read(xml);
1354    
1355                    Element rootElement = document.getRootElement();
1356    
1357                    List<Element> assetLinkElements = rootElement.elements("asset-link");
1358    
1359                    for (Element assetLinkElement : assetLinkElements) {
1360                            String sourceUuid = GetterUtil.getString(
1361                                    assetLinkElement.attributeValue("source-uuid"));
1362                            String[] assetEntryUuidArray = StringUtil.split(
1363                                    GetterUtil.getString(
1364                                            assetLinkElement.attributeValue("target-uuids")));
1365                            int assetLinkType = GetterUtil.getInteger(
1366                                    assetLinkElement.attributeValue("type"));
1367    
1368                            List<Long> assetEntryIds = new ArrayList<Long>();
1369    
1370                            for (String assetEntryUuid : assetEntryUuidArray) {
1371                                    try {
1372                                            AssetEntry assetEntry = AssetEntryLocalServiceUtil.getEntry(
1373                                                    portletDataContext.getScopeGroupId(), assetEntryUuid);
1374    
1375                                            assetEntryIds.add(assetEntry.getEntryId());
1376                                    }
1377                                    catch (NoSuchEntryException nsee) {
1378                                    }
1379                            }
1380    
1381                            if (assetEntryIds.isEmpty()) {
1382                                    continue;
1383                            }
1384    
1385                            long[] assetEntryIdsArray = ArrayUtil.toArray(
1386                                    assetEntryIds.toArray(new Long[assetEntryIds.size()]));
1387    
1388                            try {
1389                                    AssetEntry assetEntry = AssetEntryLocalServiceUtil.getEntry(
1390                                            portletDataContext.getScopeGroupId(), sourceUuid);
1391    
1392                                    AssetLinkLocalServiceUtil.updateLinks(
1393                                            assetEntry.getUserId(), assetEntry.getEntryId(),
1394                                            assetEntryIdsArray, assetLinkType);
1395                            }
1396                            catch (NoSuchEntryException nsee) {
1397                            }
1398                    }
1399            }
1400    
1401            protected void readAssetTags(PortletDataContext portletDataContext)
1402                    throws Exception {
1403    
1404                    String xml = portletDataContext.getZipEntryAsString(
1405                            portletDataContext.getSourceRootPath() + "/tags.xml");
1406    
1407                    if (xml == null) {
1408                            return;
1409                    }
1410    
1411                    Document document = SAXReaderUtil.read(xml);
1412    
1413                    Element rootElement = document.getRootElement();
1414    
1415                    List<Element> assetTagElements = rootElement.elements("tag");
1416    
1417                    for (Element assetTagElement : assetTagElements) {
1418                            String path = assetTagElement.attributeValue("path");
1419    
1420                            if (!portletDataContext.isPathNotProcessed(path)) {
1421                                    continue;
1422                            }
1423    
1424                            AssetTag assetTag =
1425                                    (AssetTag)portletDataContext.getZipEntryAsObject(path);
1426    
1427                            Map<Long, Long> assetTagPKs =
1428                                    (Map<Long, Long>)portletDataContext.getNewPrimaryKeysMap(
1429                                            AssetTag.class);
1430    
1431                            importAssetTag(
1432                                    portletDataContext, assetTagPKs, assetTagElement, assetTag);
1433                    }
1434    
1435                    List<Element> assetElements = rootElement.elements("asset");
1436    
1437                    for (Element assetElement : assetElements) {
1438                            String className = GetterUtil.getString(
1439                                    assetElement.attributeValue("class-name"));
1440                            long classPK = GetterUtil.getLong(
1441                                    assetElement.attributeValue("class-pk"));
1442                            String assetTagNames = GetterUtil.getString(
1443                                    assetElement.attributeValue("tags"));
1444    
1445                            portletDataContext.addAssetTags(
1446                                    className, classPK, StringUtil.split(assetTagNames));
1447                    }
1448            }
1449    
1450            protected void readComments(PortletDataContext portletDataContext)
1451                    throws Exception {
1452    
1453                    String xml = portletDataContext.getZipEntryAsString(
1454                            portletDataContext.getSourceRootPath() + "/comments.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                            long classPK = GetterUtil.getLong(
1470                                    assetElement.attributeValue("class-pk"));
1471    
1472                            List<String> zipFolderEntries =
1473                                    portletDataContext.getZipFolderEntries(path);
1474    
1475                            List<MBMessage> mbMessages = new ArrayList<MBMessage>();
1476    
1477                            for (String zipFolderEntry : zipFolderEntries) {
1478                                    MBMessage mbMessage =
1479                                            (MBMessage)portletDataContext.getZipEntryAsObject(
1480                                                    zipFolderEntry);
1481    
1482                                    if (mbMessage != null) {
1483                                            mbMessages.add(mbMessage);
1484                                    }
1485                            }
1486    
1487                            portletDataContext.addComments(className, classPK, mbMessages);
1488                    }
1489            }
1490    
1491            protected void readExpandoTables(PortletDataContext portletDataContext)
1492                    throws Exception {
1493    
1494                    String xml = portletDataContext.getZipEntryAsString(
1495                            portletDataContext.getSourceRootPath() + "/expando-tables.xml");
1496    
1497                    if (xml == null) {
1498                            return;
1499                    }
1500    
1501                    Document document = SAXReaderUtil.read(xml);
1502    
1503                    Element rootElement = document.getRootElement();
1504    
1505                    List<Element> expandoTableElements = rootElement.elements(
1506                            "expando-table");
1507    
1508                    for (Element expandoTableElement : expandoTableElements) {
1509                            String className = expandoTableElement.attributeValue("class-name");
1510    
1511                            ExpandoTable expandoTable = null;
1512    
1513                            try {
1514                                    expandoTable = ExpandoTableLocalServiceUtil.getDefaultTable(
1515                                            portletDataContext.getCompanyId(), className);
1516                            }
1517                            catch (NoSuchTableException nste) {
1518                                    expandoTable = ExpandoTableLocalServiceUtil.addDefaultTable(
1519                                            portletDataContext.getCompanyId(), className);
1520                            }
1521    
1522                            List<Element> expandoColumnElements = expandoTableElement.elements(
1523                                    "expando-column");
1524    
1525                            for (Element expandoColumnElement : expandoColumnElements) {
1526                                    long columnId = GetterUtil.getLong(
1527                                            expandoColumnElement.attributeValue("column-id"));
1528                                    String name = expandoColumnElement.attributeValue("name");
1529                                    int type = GetterUtil.getInteger(
1530                                            expandoColumnElement.attributeValue("type"));
1531                                    String defaultData = expandoColumnElement.elementText(
1532                                            "default-data");
1533                                    String typeSettings = expandoColumnElement.elementText(
1534                                            "type-settings");
1535    
1536                                    Serializable defaultDataObject =
1537                                            ExpandoConverterUtil.getAttributeFromString(
1538                                                    type, defaultData);
1539    
1540                                    ExpandoColumn expandoColumn =
1541                                            ExpandoColumnLocalServiceUtil.getColumn(
1542                                                    expandoTable.getTableId(), name);
1543    
1544                                    if (expandoColumn != null) {
1545                                            ExpandoColumnLocalServiceUtil.updateColumn(
1546                                                    expandoColumn.getColumnId(), name, type,
1547                                                    defaultDataObject);
1548                                    }
1549                                    else {
1550                                            expandoColumn = ExpandoColumnLocalServiceUtil.addColumn(
1551                                                    expandoTable.getTableId(), name, type,
1552                                                    defaultDataObject);
1553                                    }
1554    
1555                                    ExpandoColumnLocalServiceUtil.updateTypeSettings(
1556                                            expandoColumn.getColumnId(), typeSettings);
1557    
1558                                    portletDataContext.importPermissions(
1559                                            ExpandoColumn.class, columnId, expandoColumn.getColumnId());
1560                            }
1561                    }
1562            }
1563    
1564            protected void readLocks(PortletDataContext portletDataContext)
1565                    throws Exception {
1566    
1567                    String xml = portletDataContext.getZipEntryAsString(
1568                            portletDataContext.getSourceRootPath() + "/locks.xml");
1569    
1570                    if (xml == null) {
1571                            return;
1572                    }
1573    
1574                    Document document = SAXReaderUtil.read(xml);
1575    
1576                    Element rootElement = document.getRootElement();
1577    
1578                    List<Element> assetElements = rootElement.elements("asset");
1579    
1580                    for (Element assetElement : assetElements) {
1581                            String path = assetElement.attributeValue("path");
1582                            String className = assetElement.attributeValue("class-name");
1583                            String key = assetElement.attributeValue("key");
1584    
1585                            Lock lock = (Lock)portletDataContext.getZipEntryAsObject(path);
1586    
1587                            if (lock != null) {
1588                                    portletDataContext.addLocks(className, key, lock);
1589                            }
1590                    }
1591            }
1592    
1593            protected void readRatingsEntries(PortletDataContext portletDataContext)
1594                    throws Exception {
1595    
1596                    String xml = portletDataContext.getZipEntryAsString(
1597                            portletDataContext.getSourceRootPath() + "/ratings.xml");
1598    
1599                    if (xml == null) {
1600                            return;
1601                    }
1602    
1603                    Document document = SAXReaderUtil.read(xml);
1604    
1605                    Element rootElement = document.getRootElement();
1606    
1607                    List<Element> assetElements = rootElement.elements("asset");
1608    
1609                    for (Element assetElement : assetElements) {
1610                            String path = assetElement.attributeValue("path");
1611                            String className = assetElement.attributeValue("class-name");
1612                            long classPK = GetterUtil.getLong(
1613                                    assetElement.attributeValue("class-pk"));
1614    
1615                            List<String> zipFolderEntries =
1616                                    portletDataContext.getZipFolderEntries(path);
1617    
1618                            List<RatingsEntry> ratingsEntries = new ArrayList<RatingsEntry>();
1619    
1620                            for (String zipFolderEntry : zipFolderEntries) {
1621                                    RatingsEntry ratingsEntry =
1622                                            (RatingsEntry)portletDataContext.getZipEntryAsObject(
1623                                                    zipFolderEntry);
1624    
1625                                    if (ratingsEntry != null) {
1626                                            ratingsEntries.add(ratingsEntry);
1627                                    }
1628                            }
1629    
1630                            portletDataContext.addRatingsEntries(
1631                                    className, classPK, ratingsEntries);
1632                    }
1633            }
1634    
1635            protected void resetPortletScope(
1636                    PortletDataContext portletDataContext, long groupId) {
1637    
1638                    portletDataContext.setScopeGroupId(groupId);
1639                    portletDataContext.setScopeLayoutUuid(StringPool.BLANK);
1640                    portletDataContext.setScopeType(StringPool.BLANK);
1641            }
1642    
1643            protected void setPortletScope(
1644                    PortletDataContext portletDataContext, Element portletElement) {
1645    
1646                    // Portlet data scope
1647    
1648                    String scopeLayoutUuid = GetterUtil.getString(
1649                            portletElement.attributeValue("scope-layout-uuid"));
1650                    String scopeLayoutType = GetterUtil.getString(
1651                            portletElement.attributeValue("scope-layout-type"));
1652    
1653                    portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);
1654                    portletDataContext.setScopeType(scopeLayoutType);
1655    
1656                    // Layout scope
1657    
1658                    try {
1659                            Group scopeGroup = null;
1660    
1661                            if (scopeLayoutType.equals("company")) {
1662                                    scopeGroup = GroupLocalServiceUtil.getCompanyGroup(
1663                                            portletDataContext.getCompanyId());
1664                            }
1665                            else if (Validator.isNotNull(scopeLayoutUuid)) {
1666                                    boolean privateLayout = GetterUtil.getBoolean(
1667                                            portletElement.attributeValue("private-layout"));
1668    
1669                                    Layout scopeLayout =
1670                                            LayoutLocalServiceUtil.getLayoutByUuidAndGroupId(
1671                                                    scopeLayoutUuid, portletDataContext.getGroupId(),
1672                                                    privateLayout);
1673    
1674                                    if (scopeLayout.hasScopeGroup()) {
1675                                            scopeGroup = scopeLayout.getScopeGroup();
1676                                    }
1677                                    else {
1678                                            String name = String.valueOf(scopeLayout.getPlid());
1679    
1680                                            scopeGroup = GroupLocalServiceUtil.addGroup(
1681                                                    portletDataContext.getUserId(null),
1682                                                    GroupConstants.DEFAULT_PARENT_GROUP_ID,
1683                                                    Layout.class.getName(), scopeLayout.getPlid(),
1684                                                    GroupConstants.DEFAULT_LIVE_GROUP_ID, name, null, 0,
1685                                                    null, false, true, null);
1686                                    }
1687    
1688                                    Group group = scopeLayout.getGroup();
1689    
1690                                    if (group.isStaged() && !group.isStagedRemotely()) {
1691                                            try {
1692                                                    Layout oldLayout =
1693                                                            LayoutLocalServiceUtil.getLayoutByUuidAndGroupId(
1694                                                                    scopeLayoutUuid,
1695                                                                    portletDataContext.getSourceGroupId(),
1696                                                                    privateLayout);
1697    
1698                                                    Group oldScopeGroup = oldLayout.getScopeGroup();
1699    
1700                                                    oldScopeGroup.setLiveGroupId(scopeGroup.getGroupId());
1701    
1702                                                    GroupLocalServiceUtil.updateGroup(oldScopeGroup);
1703                                            }
1704                                            catch (NoSuchLayoutException nsle) {
1705                                                    if (_log.isWarnEnabled()) {
1706                                                            _log.warn(nsle);
1707                                                    }
1708                                            }
1709                                    }
1710                            }
1711    
1712                            if (scopeGroup != null) {
1713                                    portletDataContext.setScopeGroupId(scopeGroup.getGroupId());
1714                            }
1715                    }
1716                    catch (PortalException pe) {
1717                    }
1718                    catch (Exception e) {
1719                            _log.error(e, e);
1720                    }
1721            }
1722    
1723            protected String updateAssetCategoriesNavigationPortletPreferences(
1724                            PortletDataContext portletDataContext, long companyId, long ownerId,
1725                            int ownerType, long plid, String portletId, String xml)
1726                    throws Exception {
1727    
1728                    Company company = CompanyLocalServiceUtil.getCompanyById(companyId);
1729    
1730                    Group companyGroup = company.getGroup();
1731    
1732                    javax.portlet.PortletPreferences jxPreferences =
1733                            PortletPreferencesFactoryUtil.fromXML(
1734                                    companyId, ownerId, ownerType, plid, portletId, xml);
1735    
1736                    Enumeration<String> enu = jxPreferences.getNames();
1737    
1738                    while (enu.hasMoreElements()) {
1739                            String name = enu.nextElement();
1740    
1741                            if (name.equals("assetVocabularyIds")) {
1742                                    updatePreferencesClassPKs(
1743                                            portletDataContext, jxPreferences, name,
1744                                            AssetVocabulary.class, companyGroup.getGroupId());
1745                            }
1746                    }
1747    
1748                    return PortletPreferencesFactoryUtil.toXML(jxPreferences);
1749            }
1750    
1751            protected void updateAssetPublisherClassNameIds(
1752                            javax.portlet.PortletPreferences jxPreferences, String key)
1753                    throws Exception {
1754    
1755                    String[] oldValues = jxPreferences.getValues(key, null);
1756    
1757                    if (oldValues == null) {
1758                            return;
1759                    }
1760    
1761                    String[] newValues = new String[oldValues.length];
1762    
1763                    int i = 0;
1764    
1765                    for (String oldValue : oldValues) {
1766                            if (key.equals("anyAssetType") &&
1767                                    (oldValue.equals("false") || oldValue.equals("true"))) {
1768    
1769                                    newValues[i++] = oldValue;
1770    
1771                                    continue;
1772                            }
1773    
1774                            try {
1775                                    long classNameId = PortalUtil.getClassNameId(oldValue);
1776    
1777                                    newValues[i++] = String.valueOf(classNameId);
1778                            }
1779                            catch (Exception e) {
1780                                    if (_log.isWarnEnabled()) {
1781                                            _log.warn(
1782                                                    "Unable to find class name ID for class name " +
1783                                                            oldValue);
1784                                    }
1785                            }
1786                    }
1787    
1788                    jxPreferences.setValues(key, newValues);
1789            }
1790    
1791            protected String updateAssetPublisherPortletPreferences(
1792                            PortletDataContext portletDataContext, long companyId, long ownerId,
1793                            int ownerType, long plid, String portletId, String xml,
1794                            Layout layout)
1795                    throws Exception {
1796    
1797                    Company company = CompanyLocalServiceUtil.getCompanyById(companyId);
1798    
1799                    Group companyGroup = company.getGroup();
1800    
1801                    javax.portlet.PortletPreferences jxPreferences =
1802                            PortletPreferencesFactoryUtil.fromXML(
1803                                    companyId, ownerId, ownerType, plid, portletId, xml);
1804    
1805                    Enumeration<String> enu = jxPreferences.getNames();
1806    
1807                    while (enu.hasMoreElements()) {
1808                            String name = enu.nextElement();
1809    
1810                            String value = GetterUtil.getString(
1811                                    jxPreferences.getValue(name, null));
1812    
1813                            if (name.equals(
1814                                            "anyClassTypeJournalArticleAssetRendererFactory") ||
1815                                    name.equals(
1816                                            "classTypeIdsJournalArticleAssetRendererFactory") ||
1817                                    name.equals("classTypeIds")) {
1818    
1819                                    updatePreferencesClassPKs(
1820                                            portletDataContext, jxPreferences, name, DDMStructure.class,
1821                                            companyGroup.getGroupId());
1822                            }
1823                            else if (name.equals("anyAssetType") ||
1824                                             name.equals("classNameIds")) {
1825    
1826                                    updateAssetPublisherClassNameIds(jxPreferences, name);
1827                            }
1828                            else if (name.startsWith("queryName") &&
1829                                             value.equalsIgnoreCase("assetCategories")) {
1830    
1831                                    String index = name.substring(9, name.length());
1832    
1833                                    updatePreferencesClassPKs(
1834                                            portletDataContext, jxPreferences, "queryValues" + index,
1835                                            AssetCategory.class, companyGroup.getGroupId());
1836                            }
1837                            else if (name.equals("scopeIds")) {
1838                                    updateAssetPublisherScopeIds(
1839                                            jxPreferences, name, companyGroup.getGroupId(),
1840                                            layout.getPlid());
1841                            }
1842                    }
1843    
1844                    return PortletPreferencesFactoryUtil.toXML(jxPreferences);
1845            }
1846    
1847            protected void updateAssetPublisherScopeIds(
1848                            javax.portlet.PortletPreferences jxPreferences, String key,
1849                            long companyGroupId, long plid)
1850                    throws Exception {
1851    
1852                    String[] oldValues = jxPreferences.getValues(key, null);
1853    
1854                    if (oldValues == null) {
1855                            return;
1856                    }
1857    
1858                    Layout layout = LayoutLocalServiceUtil.getLayout(plid);
1859    
1860                    String companyGroupScopeId =
1861                            AssetPublisherUtil.SCOPE_ID_GROUP_PREFIX + companyGroupId;
1862    
1863                    List<String> newValues = new ArrayList<String>(oldValues.length);
1864    
1865                    for (int i = 0; i < oldValues.length; i++) {
1866                            String oldValue = oldValues[i];
1867    
1868                            String newValue = StringUtil.replace(
1869                                    oldValue, "[$COMPANY_GROUP_SCOPE_ID$]", companyGroupScopeId);
1870    
1871                            try {
1872                                    if (!AssetPublisherUtil.isScopeIdSelectable(
1873                                                    PermissionThreadLocal.getPermissionChecker(), newValue,
1874                                                    companyGroupId, layout)) {
1875    
1876                                            continue;
1877                                    }
1878    
1879                                    newValues.add(newValue);
1880                            }
1881                            catch (NoSuchGroupException nsge) {
1882                                    if (_log.isInfoEnabled()) {
1883                                            _log.info(
1884                                                    "Ignoring scope " + newValue + "because the " +
1885                                                            "referenced group was not found");
1886                                    }
1887                            }
1888                    }
1889    
1890                    jxPreferences.setValues(
1891                            key, newValues.toArray(new String[newValues.size()]));
1892            }
1893    
1894            protected void updatePortletPreferences(
1895                            PortletDataContext portletDataContext, long ownerId, int ownerType,
1896                            long plid, String portletId, String xml, boolean importData)
1897                    throws Exception {
1898    
1899                    if (importData) {
1900                            PortletPreferencesLocalServiceUtil.updatePreferences(
1901                                    ownerId, ownerType, plid, portletId, xml);
1902                    }
1903                    else {
1904                            Portlet portlet = PortletLocalServiceUtil.getPortletById(
1905                                    portletDataContext.getCompanyId(), portletId);
1906    
1907                            if (portlet == null) {
1908                                    if (_log.isDebugEnabled()) {
1909                                            _log.debug(
1910                                                    "Do not update portlet preferences for " + portletId +
1911                                                            " because the portlet does not exist");
1912                                    }
1913    
1914                                    return;
1915                            }
1916    
1917                            PortletDataHandler portletDataHandler =
1918                                    portlet.getPortletDataHandlerInstance();
1919    
1920                            if (portletDataHandler == null) {
1921                                    PortletPreferencesLocalServiceUtil.updatePreferences(
1922                                            ownerId, ownerType, plid, portletId, xml);
1923    
1924                                    return;
1925                            }
1926    
1927                            // Portlet preferences to be updated only when importing data
1928    
1929                            String[] dataPortletPreferences =
1930                                    portletDataHandler.getDataPortletPreferences();
1931    
1932                            // Current portlet preferences
1933    
1934                            javax.portlet.PortletPreferences portletPreferences =
1935                                    PortletPreferencesLocalServiceUtil.getPreferences(
1936                                            portletDataContext.getCompanyId(), ownerId, ownerType, plid,
1937                                            portletId);
1938    
1939                            // New portlet preferences
1940    
1941                            javax.portlet.PortletPreferences jxPreferences =
1942                                    PortletPreferencesFactoryUtil.fromXML(
1943                                            portletDataContext.getCompanyId(), ownerId, ownerType, plid,
1944                                            portletId, xml);
1945    
1946                            Enumeration<String> enu = jxPreferences.getNames();
1947    
1948                            while (enu.hasMoreElements()) {
1949                                    String name = enu.nextElement();
1950    
1951                                    String scopeLayoutUuid =
1952                                            portletDataContext.getScopeLayoutUuid();
1953                                    String scopeType = portletDataContext.getScopeType();
1954    
1955                                    if (!ArrayUtil.contains(dataPortletPreferences, name) ||
1956                                            (Validator.isNull(scopeLayoutUuid) &&
1957                                             scopeType.equals("company"))) {
1958    
1959                                            String[] values = jxPreferences.getValues(name, null);
1960    
1961                                            portletPreferences.setValues(name, values);
1962                                    }
1963                            }
1964    
1965                            PortletPreferencesLocalServiceUtil.updatePreferences(
1966                                    ownerId, ownerType, plid, portletId, portletPreferences);
1967                    }
1968            }
1969    
1970            protected void updatePreferencesClassPKs(
1971                            PortletDataContext portletDataContext,
1972                            javax.portlet.PortletPreferences jxPreferences, String key,
1973                            Class<?> clazz, long companyGroupId)
1974                    throws Exception {
1975    
1976                    String[] oldValues = jxPreferences.getValues(key, null);
1977    
1978                    if (oldValues == null) {
1979                            return;
1980                    }
1981    
1982                    Map<Long, Long> primaryKeysMap =
1983                            (Map<Long, Long>)portletDataContext.getNewPrimaryKeysMap(clazz);
1984    
1985                    String[] newValues = new String[oldValues.length];
1986    
1987                    for (int i = 0; i < oldValues.length; i++) {
1988                            String oldValue = oldValues[i];
1989    
1990                            String newValue = oldValue;
1991    
1992                            String[] uuids = StringUtil.split(oldValue);
1993    
1994                            for (String uuid : uuids) {
1995                                    Long newPrimaryKey = null;
1996    
1997                                    if (Validator.isNumber(uuid)) {
1998                                            long oldPrimaryKey = GetterUtil.getLong(uuid);
1999    
2000                                            newPrimaryKey = MapUtil.getLong(
2001                                                    primaryKeysMap, oldPrimaryKey, oldPrimaryKey);
2002                                    }
2003                                    else {
2004                                            String className = clazz.getName();
2005    
2006                                            if (className.equals(AssetCategory.class.getName())) {
2007                                                    AssetCategory assetCategory =
2008                                                            AssetCategoryUtil.fetchByUUID_G(
2009                                                                    uuid, portletDataContext.getScopeGroupId());
2010    
2011                                                    if (assetCategory == null) {
2012                                                            assetCategory = AssetCategoryUtil.fetchByUUID_G(
2013                                                                    uuid, companyGroupId);
2014                                                    }
2015    
2016                                                    if (assetCategory != null) {
2017                                                            newPrimaryKey = assetCategory.getCategoryId();
2018                                                    }
2019                                            }
2020                                            else if (className.equals(
2021                                                            AssetVocabulary.class.getName())) {
2022    
2023                                                    AssetVocabulary assetVocabulary =
2024                                                            AssetVocabularyUtil.fetchByUUID_G(
2025                                                                    uuid, portletDataContext.getScopeGroupId());
2026    
2027                                                    if (assetVocabulary == null) {
2028                                                            assetVocabulary = AssetVocabularyUtil.fetchByUUID_G(
2029                                                                    uuid, companyGroupId);
2030                                                    }
2031    
2032                                                    if (assetVocabulary != null) {
2033                                                            newPrimaryKey = assetVocabulary.getVocabularyId();
2034                                                    }
2035                                            }
2036                                            else if (className.equals(DDMStructure.class.getName())) {
2037                                                    DDMStructure ddmStructure =
2038                                                            DDMStructureUtil.fetchByUUID_G(
2039                                                                    uuid, portletDataContext.getScopeGroupId());
2040    
2041                                                    if (ddmStructure == null) {
2042                                                            ddmStructure = DDMStructureUtil.fetchByUUID_G(
2043                                                                    uuid, companyGroupId);
2044                                                    }
2045    
2046                                                    if (ddmStructure != null) {
2047                                                            newPrimaryKey = ddmStructure.getStructureId();
2048                                                    }
2049                                            }
2050                                    }
2051    
2052                                    if (Validator.isNull(newPrimaryKey)) {
2053                                            if (_log.isWarnEnabled()) {
2054                                                    StringBundler sb = new StringBundler(8);
2055    
2056                                                    sb.append("Unable to get primary key for ");
2057                                                    sb.append(clazz);
2058                                                    sb.append(" with UUID ");
2059                                                    sb.append(uuid);
2060                                                    sb.append(" in company group ");
2061                                                    sb.append(companyGroupId);
2062                                                    sb.append(" or in group ");
2063                                                    sb.append(portletDataContext.getScopeGroupId());
2064    
2065                                                    _log.warn(sb.toString());
2066                                            }
2067                                    }
2068                                    else {
2069                                            newValue = StringUtil.replace(
2070                                                    newValue, uuid, newPrimaryKey.toString());
2071                                    }
2072                            }
2073    
2074                            newValues[i] = newValue;
2075                    }
2076    
2077                    jxPreferences.setValues(key, newValues);
2078            }
2079    
2080            private static Log _log = LogFactoryUtil.getLog(PortletImporter.class);
2081    
2082            private PermissionImporter _permissionImporter = new PermissionImporter();
2083    
2084    }