001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portlet.dynamicdatamapping.lar;
016    
017    import com.liferay.portal.kernel.exception.PortalException;
018    import com.liferay.portal.kernel.exception.SystemException;
019    import com.liferay.portal.kernel.lar.BaseStagedModelDataHandler;
020    import com.liferay.portal.kernel.lar.ExportImportHelperUtil;
021    import com.liferay.portal.kernel.lar.ExportImportPathUtil;
022    import com.liferay.portal.kernel.lar.PortletDataContext;
023    import com.liferay.portal.kernel.lar.PortletDataException;
024    import com.liferay.portal.kernel.lar.StagedModelDataHandlerUtil;
025    import com.liferay.portal.kernel.util.FileUtil;
026    import com.liferay.portal.kernel.util.GetterUtil;
027    import com.liferay.portal.kernel.util.LocaleUtil;
028    import com.liferay.portal.kernel.util.LocalizationUtil;
029    import com.liferay.portal.kernel.util.MapUtil;
030    import com.liferay.portal.kernel.util.StringPool;
031    import com.liferay.portal.kernel.util.Validator;
032    import com.liferay.portal.kernel.xml.Element;
033    import com.liferay.portal.model.Image;
034    import com.liferay.portal.service.ImageLocalServiceUtil;
035    import com.liferay.portal.service.ServiceContext;
036    import com.liferay.portal.service.UserLocalServiceUtil;
037    import com.liferay.portal.util.PortalUtil;
038    import com.liferay.portlet.dynamicdatamapping.model.DDMStructure;
039    import com.liferay.portlet.dynamicdatamapping.model.DDMTemplate;
040    import com.liferay.portlet.dynamicdatamapping.service.DDMStructureLocalServiceUtil;
041    import com.liferay.portlet.dynamicdatamapping.service.DDMTemplateLocalServiceUtil;
042    
043    import java.io.File;
044    
045    import java.util.HashMap;
046    import java.util.Locale;
047    import java.util.Map;
048    
049    /**
050     * @author Mate Thurzo
051     * @author Daniel Kocsis
052     */
053    public class DDMTemplateStagedModelDataHandler
054            extends BaseStagedModelDataHandler<DDMTemplate> {
055    
056            public static final String[] CLASS_NAMES = {DDMTemplate.class.getName()};
057    
058            @Override
059            public void deleteStagedModel(
060                            String uuid, long groupId, String className, String extraData)
061                    throws PortalException, SystemException {
062    
063                    DDMTemplate ddmTemplate =
064                            DDMTemplateLocalServiceUtil.fetchDDMTemplateByUuidAndGroupId(
065                                    uuid, groupId);
066    
067                    if (ddmTemplate != null) {
068                            DDMTemplateLocalServiceUtil.deleteTemplate(ddmTemplate);
069                    }
070            }
071    
072            @Override
073            public String[] getClassNames() {
074                    return CLASS_NAMES;
075            }
076    
077            @Override
078            public String getDisplayName(DDMTemplate template) {
079                    return template.getNameCurrentValue();
080            }
081    
082            @Override
083            public Map<String, String> getReferenceAttributes(
084                    PortletDataContext portletDataContext, DDMTemplate template) {
085    
086                    Map<String, String> referenceAttributes = new HashMap<String, String>();
087    
088                    referenceAttributes.put(
089                            "referenced-class-name", template.getClassName());
090                    referenceAttributes.put("template-key", template.getTemplateKey());
091    
092                    long defaultUserId = 0;
093    
094                    try {
095                            defaultUserId = UserLocalServiceUtil.getDefaultUserId(
096                                    template.getCompanyId());
097                    }
098                    catch (Exception e) {
099                            return referenceAttributes;
100                    }
101    
102                    boolean preloaded = false;
103    
104                    if (defaultUserId == template.getUserId()) {
105                            preloaded = true;
106                    }
107    
108                    referenceAttributes.put("preloaded", String.valueOf(preloaded));
109    
110                    return referenceAttributes;
111            }
112    
113            @Override
114            public void importCompanyStagedModel(
115                            PortletDataContext portletDataContext, Element element)
116                    throws PortletDataException {
117    
118                    String uuid = element.attributeValue("uuid");
119                    long classNameId = PortalUtil.getClassNameId(
120                            element.attributeValue("referenced-class-name"));
121                    String templateKey = element.attributeValue("template-key");
122                    boolean preloaded = GetterUtil.getBoolean(
123                            element.attributeValue("preloaded"));
124    
125                    DDMTemplate existingTemplate = null;
126    
127                    try {
128                            existingTemplate = getExistingTemplate(
129                                    uuid, portletDataContext.getCompanyGroupId(), classNameId,
130                                    templateKey, preloaded);
131                    }
132                    catch (Exception e) {
133                            throw new PortletDataException(e);
134                    }
135    
136                    Map<Long, Long> templateIds =
137                            (Map<Long, Long>)portletDataContext.getNewPrimaryKeysMap(
138                                    DDMTemplate.class);
139    
140                    long templateId = GetterUtil.getLong(
141                            element.attributeValue("class-pk"));
142    
143                    templateIds.put(templateId, existingTemplate.getTemplateId());
144    
145                    Map<String, String> templateKeys =
146                            (Map<String, String>)portletDataContext.getNewPrimaryKeysMap(
147                                    DDMTemplate.class + ".ddmTemplateKey");
148    
149                    templateKeys.put(templateKey, existingTemplate.getTemplateKey());
150            }
151    
152            @Override
153            protected void doImportGroupStagedModel(
154                            PortletDataContext portletDataContext, Element referenceElement,
155                            long groupId)
156                    throws Exception {
157    
158                    String uuid = referenceElement.attributeValue("uuid");
159                    long classNameId = PortalUtil.getClassNameId(
160                            referenceElement.attributeValue("referenced-class-name"));
161                    String templateKey = referenceElement.attributeValue("template-key");
162                    boolean preloaded = GetterUtil.getBoolean(
163                            referenceElement.attributeValue("preloaded"));
164    
165                    DDMTemplate existingTemplate = null;
166    
167                    try {
168                            existingTemplate = getExistingTemplate(
169                                    uuid, groupId, classNameId, templateKey, preloaded);
170                    }
171                    catch (Exception e) {
172                            throw new PortletDataException(e);
173                    }
174    
175                    if (existingTemplate == null) {
176                            return;
177                    }
178    
179                    Map<Long, Long> templateIds =
180                            (Map<Long, Long>)portletDataContext.getNewPrimaryKeysMap(
181                                    DDMTemplate.class);
182    
183                    long templateId = GetterUtil.getLong(
184                            referenceElement.attributeValue("class-pk"));
185    
186                    templateIds.put(templateId, existingTemplate.getTemplateId());
187    
188                    Map<String, String> templateKeys =
189                            (Map<String, String>)portletDataContext.getNewPrimaryKeysMap(
190                                    DDMTemplate.class + ".ddmTemplateKey");
191    
192                    templateKeys.put(templateKey, existingTemplate.getTemplateKey());
193            }
194    
195            @Override
196            public boolean validateReference(
197                    PortletDataContext portletDataContext, Element referenceElement) {
198    
199                    String uuid = referenceElement.attributeValue("uuid");
200                    long classNameId = PortalUtil.getClassNameId(
201                            referenceElement.attributeValue("referenced-class-name"));
202                    String templateKey = referenceElement.attributeValue("template-key");
203                    boolean preloaded = GetterUtil.getBoolean(
204                            referenceElement.attributeValue("preloaded"));
205    
206                    try {
207                            DDMTemplate existingTemplate = getExistingTemplate(
208                                    uuid, portletDataContext.getScopeGroupId(), classNameId,
209                                    templateKey, preloaded);
210    
211                            if (existingTemplate == null) {
212                                    existingTemplate = getExistingTemplate(
213                                            uuid, portletDataContext.getCompanyGroupId(), classNameId,
214                                            templateKey, preloaded);
215                            }
216    
217                            if (existingTemplate == null) {
218                                    return false;
219                            }
220    
221                            return true;
222                    }
223                    catch (Exception e) {
224                            return false;
225                    }
226            }
227    
228            @Override
229            protected void doExportStagedModel(
230                            PortletDataContext portletDataContext, DDMTemplate template)
231                    throws Exception {
232    
233                    Element templateElement = portletDataContext.getExportDataElement(
234                            template);
235    
236                    DDMStructure structure = DDMStructureLocalServiceUtil.fetchStructure(
237                            template.getClassPK());
238    
239                    if (structure != null) {
240                            StagedModelDataHandlerUtil.exportReferenceStagedModel(
241                                    portletDataContext, template, structure,
242                                    PortletDataContext.REFERENCE_TYPE_STRONG);
243                    }
244    
245                    if (template.isSmallImage()) {
246                            Image smallImage = ImageLocalServiceUtil.fetchImage(
247                                    template.getSmallImageId());
248    
249                            if (Validator.isNotNull(template.getSmallImageURL())) {
250                                    String smallImageURL =
251                                            ExportImportHelperUtil.replaceExportContentReferences(
252                                                    portletDataContext, template, templateElement,
253                                                    template.getSmallImageURL().concat(StringPool.SPACE),
254                                                    true);
255    
256                                    template.setSmallImageURL(smallImageURL);
257                            }
258                            else if (smallImage != null) {
259                                    String smallImagePath = ExportImportPathUtil.getModelPath(
260                                            template,
261                                            smallImage.getImageId() + StringPool.PERIOD +
262                                                    template.getSmallImageType());
263    
264                                    templateElement.addAttribute(
265                                            "small-image-path", smallImagePath);
266    
267                                    template.setSmallImageType(smallImage.getType());
268    
269                                    portletDataContext.addZipEntry(
270                                            smallImagePath, smallImage.getTextObj());
271                            }
272                    }
273    
274                    String script = ExportImportHelperUtil.replaceExportContentReferences(
275                            portletDataContext, template, templateElement, template.getScript(),
276                            portletDataContext.getBooleanParameter(
277                                    DDMPortletDataHandler.NAMESPACE, "referenced-content"));
278    
279                    template.setScript(script);
280    
281                    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(
282                            template.getCompanyId());
283    
284                    if (defaultUserId == template.getUserId()) {
285                            templateElement.addAttribute("preloaded", "true");
286                    }
287    
288                    portletDataContext.addClassedModel(
289                            templateElement, ExportImportPathUtil.getModelPath(template),
290                            template);
291            }
292    
293            @Override
294            protected void doImportStagedModel(
295                            PortletDataContext portletDataContext, DDMTemplate template)
296                    throws Exception {
297    
298                    prepareLanguagesForImport(template);
299    
300                    long userId = portletDataContext.getUserId(template.getUserUuid());
301    
302                    long classPK = template.getClassPK();
303    
304                    if (classPK > 0) {
305                            StagedModelDataHandlerUtil.importReferenceStagedModel(
306                                    portletDataContext, template, DDMStructure.class, classPK);
307    
308                            Map<Long, Long> structureIds =
309                                    (Map<Long, Long>)portletDataContext.getNewPrimaryKeysMap(
310                                            DDMStructure.class);
311    
312                            classPK = MapUtil.getLong(structureIds, classPK, classPK);
313                    }
314    
315                    File smallFile = null;
316    
317                    try {
318                            Element templateElement =
319                                    portletDataContext.getImportDataStagedModelElement(template);
320    
321                            if (template.isSmallImage()) {
322                                    String smallImagePath = templateElement.attributeValue(
323                                            "small-image-path");
324    
325                                    if (Validator.isNotNull(template.getSmallImageURL())) {
326                                            String smallImageURL =
327                                                    ExportImportHelperUtil.replaceImportContentReferences(
328                                                            portletDataContext, templateElement,
329                                                            template.getSmallImageURL(), true);
330    
331                                            template.setSmallImageURL(smallImageURL);
332                                    }
333                                    else if (Validator.isNotNull(smallImagePath)) {
334                                            byte[] bytes = portletDataContext.getZipEntryAsByteArray(
335                                                    smallImagePath);
336    
337                                            if (bytes != null) {
338                                                    smallFile = FileUtil.createTempFile(
339                                                            template.getSmallImageType());
340    
341                                                    FileUtil.write(smallFile, bytes);
342                                            }
343                                    }
344                            }
345    
346                            String script =
347                                    ExportImportHelperUtil.replaceImportContentReferences(
348                                            portletDataContext, templateElement, template.getScript(),
349                                            true);
350    
351                            template.setScript(script);
352    
353                            ServiceContext serviceContext =
354                                    portletDataContext.createServiceContext(template);
355    
356                            DDMTemplate importedTemplate = null;
357    
358                            if (portletDataContext.isDataStrategyMirror()) {
359                                    boolean preloaded = GetterUtil.getBoolean(
360                                            templateElement.attributeValue("preloaded"));
361    
362                                    DDMTemplate existingTemplate = getExistingTemplate(
363                                            template.getUuid(), portletDataContext.getScopeGroupId(),
364                                            template.getClassNameId(), template.getTemplateKey(),
365                                            preloaded);
366    
367                                    if (existingTemplate == null) {
368                                            serviceContext.setUuid(template.getUuid());
369    
370                                            // Force a new template key if a template with the same key
371                                            // already exists
372    
373                                            existingTemplate =
374                                                    DDMTemplateLocalServiceUtil.fetchTemplate(
375                                                            portletDataContext.getScopeGroupId(),
376                                                            template.getClassNameId(),
377                                                            template.getTemplateKey());
378    
379                                            if (existingTemplate != null) {
380                                                    template.setTemplateKey(null);
381                                            }
382    
383                                            importedTemplate = DDMTemplateLocalServiceUtil.addTemplate(
384                                                    userId, portletDataContext.getScopeGroupId(),
385                                                    template.getClassNameId(), classPK,
386                                                    template.getTemplateKey(), template.getNameMap(),
387                                                    template.getDescriptionMap(), template.getType(),
388                                                    template.getMode(), template.getLanguage(),
389                                                    template.getScript(), template.isCacheable(),
390                                                    template.isSmallImage(), template.getSmallImageURL(),
391                                                    smallFile, serviceContext);
392                                    }
393                                    else {
394                                            importedTemplate =
395                                                    DDMTemplateLocalServiceUtil.updateTemplate(
396                                                            existingTemplate.getTemplateId(), classPK,
397                                                            template.getNameMap(), template.getDescriptionMap(),
398                                                            template.getType(), template.getMode(),
399                                                            template.getLanguage(), template.getScript(),
400                                                            template.isCacheable(), template.isSmallImage(),
401                                                            template.getSmallImageURL(), smallFile,
402                                                            serviceContext);
403                                    }
404                            }
405                            else {
406                                    importedTemplate = DDMTemplateLocalServiceUtil.addTemplate(
407                                            userId, portletDataContext.getScopeGroupId(),
408                                            template.getClassNameId(), classPK, null,
409                                            template.getNameMap(), template.getDescriptionMap(),
410                                            template.getType(), template.getMode(),
411                                            template.getLanguage(), template.getScript(),
412                                            template.isCacheable(), template.isSmallImage(),
413                                            template.getSmallImageURL(), smallFile, serviceContext);
414                            }
415    
416                            portletDataContext.importClassedModel(template, importedTemplate);
417    
418                            Map<String, String> ddmTemplateKeys =
419                                    (Map<String, String>)portletDataContext.getNewPrimaryKeysMap(
420                                            DDMTemplate.class + ".ddmTemplateKey");
421    
422                            ddmTemplateKeys.put(
423                                    template.getTemplateKey(), importedTemplate.getTemplateKey());
424                    }
425                    finally {
426                            if (smallFile != null) {
427                                    smallFile.delete();
428                            }
429                    }
430            }
431    
432            protected DDMTemplate getExistingTemplate(
433                            String uuid, long groupId, long classNameId, String templateKey,
434                            boolean preloaded)
435                    throws Exception {
436    
437                    DDMTemplate existingTemplate = null;
438    
439                    if (!preloaded) {
440                            existingTemplate =
441                                    DDMTemplateLocalServiceUtil.fetchDDMTemplateByUuidAndGroupId(
442                                            uuid, groupId);
443                    }
444                    else {
445                            existingTemplate = DDMTemplateLocalServiceUtil.fetchTemplate(
446                                    groupId, classNameId, templateKey);
447                    }
448    
449                    return existingTemplate;
450            }
451    
452            protected void prepareLanguagesForImport(DDMTemplate template)
453                    throws PortalException {
454    
455                    Locale defaultLocale = LocaleUtil.fromLanguageId(
456                            template.getDefaultLanguageId());
457    
458                    Locale[] availableLocales = LocaleUtil.fromLanguageIds(
459                            template.getAvailableLanguageIds());
460    
461                    Locale defaultImportLocale = LocalizationUtil.getDefaultImportLocale(
462                            DDMTemplate.class.getName(), template.getPrimaryKey(),
463                            defaultLocale, availableLocales);
464    
465                    template.prepareLocalizedFieldsForImport(defaultImportLocale);
466            }
467    
468    }