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