001    /**
002     * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portlet.dynamicdatamapping.service.impl;
016    
017    import com.liferay.portal.kernel.exception.PortalException;
018    import com.liferay.portal.kernel.exception.SystemException;
019    import com.liferay.portal.kernel.log.Log;
020    import com.liferay.portal.kernel.log.LogFactoryUtil;
021    import com.liferay.portal.kernel.util.FileUtil;
022    import com.liferay.portal.kernel.util.LocaleUtil;
023    import com.liferay.portal.kernel.util.OrderByComparator;
024    import com.liferay.portal.kernel.util.PropsKeys;
025    import com.liferay.portal.kernel.util.StringPool;
026    import com.liferay.portal.kernel.util.StringUtil;
027    import com.liferay.portal.kernel.util.Validator;
028    import com.liferay.portal.model.Group;
029    import com.liferay.portal.model.Image;
030    import com.liferay.portal.model.ResourceConstants;
031    import com.liferay.portal.model.User;
032    import com.liferay.portal.service.ServiceContext;
033    import com.liferay.portal.service.persistence.ImageUtil;
034    import com.liferay.portal.util.PrefsPropsUtil;
035    import com.liferay.portlet.dynamicdatamapping.NoSuchTemplateException;
036    import com.liferay.portlet.dynamicdatamapping.TemplateDuplicateTemplateKeyException;
037    import com.liferay.portlet.dynamicdatamapping.TemplateNameException;
038    import com.liferay.portlet.dynamicdatamapping.TemplateScriptException;
039    import com.liferay.portlet.dynamicdatamapping.TemplateSmallImageNameException;
040    import com.liferay.portlet.dynamicdatamapping.TemplateSmallImageSizeException;
041    import com.liferay.portlet.dynamicdatamapping.model.DDMTemplate;
042    import com.liferay.portlet.dynamicdatamapping.service.base.DDMTemplateLocalServiceBaseImpl;
043    
044    import java.io.File;
045    import java.io.IOException;
046    
047    import java.util.ArrayList;
048    import java.util.Date;
049    import java.util.List;
050    import java.util.Locale;
051    import java.util.Map;
052    
053    /**
054     * @author Brian Wing Shun Chan
055     * @author Eduardo Lundgren
056     * @author Marcellus Tavares
057     */
058    public class DDMTemplateLocalServiceImpl
059            extends DDMTemplateLocalServiceBaseImpl {
060    
061            public DDMTemplate addTemplate(
062                            long userId, long groupId, long classNameId, long classPK,
063                            Map<Locale, String> nameMap, Map<Locale, String> descriptionMap,
064                            String type, String mode, String language, String script,
065                            ServiceContext serviceContext)
066                    throws PortalException, SystemException {
067    
068                    return addTemplate(
069                            userId, groupId, classNameId, classPK, null, nameMap,
070                            descriptionMap, type, mode, language, script, false, false, null,
071                            null, serviceContext);
072            }
073    
074            public DDMTemplate addTemplate(
075                            long userId, long groupId, long classNameId, long classPK,
076                            String templateKey, Map<Locale, String> nameMap,
077                            Map<Locale, String> descriptionMap, String type, String mode,
078                            String language, String script, boolean cacheable,
079                            boolean smallImage, String smallImageURL, File smallImageFile,
080                            ServiceContext serviceContext)
081                    throws PortalException, SystemException {
082    
083                    // Template
084    
085                    User user = userPersistence.findByPrimaryKey(userId);
086                    Date now = new Date();
087    
088                    if (Validator.isNull(templateKey)) {
089                            templateKey = String.valueOf(counterLocalService.increment());
090                    }
091                    else {
092                            templateKey = templateKey.trim().toUpperCase();
093                    }
094    
095                    byte[] smallImageBytes = null;
096    
097                    if (smallImage) {
098                            try {
099                                    smallImageBytes = FileUtil.getBytes(smallImageFile);
100                            }
101                            catch (IOException ioe) {
102                            }
103    
104                            if ((smallImageBytes == null) || Validator.isUrl(smallImageURL)) {
105                                    smallImage = false;
106                            }
107                    }
108    
109                    validate(
110                            groupId, templateKey, nameMap, script, smallImage, smallImageURL,
111                            smallImageFile, smallImageBytes);
112    
113                    long templateId = counterLocalService.increment();
114    
115                    DDMTemplate template = ddmTemplatePersistence.create(templateId);
116    
117                    template.setUuid(serviceContext.getUuid());
118                    template.setGroupId(groupId);
119                    template.setCompanyId(user.getCompanyId());
120                    template.setUserId(user.getUserId());
121                    template.setUserName(user.getFullName());
122                    template.setCreateDate(serviceContext.getCreateDate(now));
123                    template.setModifiedDate(serviceContext.getModifiedDate(now));
124                    template.setClassNameId(classNameId);
125                    template.setClassPK(classPK);
126                    template.setTemplateKey(templateKey);
127                    template.setNameMap(nameMap);
128                    template.setDescriptionMap(descriptionMap);
129                    template.setType(type);
130                    template.setMode(mode);
131                    template.setLanguage(language);
132                    template.setScript(script);
133                    template.setCacheable(cacheable);
134                    template.setSmallImage(smallImage);
135                    template.setSmallImageId(counterLocalService.increment());
136                    template.setSmallImageURL(smallImageURL);
137    
138                    ddmTemplatePersistence.update(template);
139    
140                    // Resources
141    
142                    if (serviceContext.isAddGroupPermissions() ||
143                            serviceContext.isAddGuestPermissions()) {
144    
145                            addTemplateResources(
146                                    template, serviceContext.isAddGroupPermissions(),
147                                    serviceContext.isAddGuestPermissions());
148                    }
149                    else {
150                            addTemplateResources(
151                                    template, serviceContext.getGroupPermissions(),
152                                    serviceContext.getGuestPermissions());
153                    }
154    
155                    // Small image
156    
157                    saveImages(
158                            smallImage, template.getSmallImageId(), smallImageFile,
159                            smallImageBytes);
160    
161                    return template;
162            }
163    
164            public void addTemplateResources(
165                            DDMTemplate template, boolean addGroupPermissions,
166                            boolean addGuestPermissions)
167                    throws PortalException, SystemException {
168    
169                    resourceLocalService.addResources(
170                            template.getCompanyId(), template.getGroupId(),
171                            template.getUserId(), DDMTemplate.class.getName(),
172                            template.getTemplateId(), false, addGroupPermissions,
173                            addGuestPermissions);
174            }
175    
176            public void addTemplateResources(
177                            DDMTemplate template, String[] groupPermissions,
178                            String[] guestPermissions)
179                    throws PortalException, SystemException {
180    
181                    resourceLocalService.addModelResources(
182                            template.getCompanyId(), template.getGroupId(),
183                            template.getUserId(), DDMTemplate.class.getName(),
184                            template.getTemplateId(), groupPermissions, guestPermissions);
185            }
186    
187            public DDMTemplate copyTemplate(
188                            long userId, long templateId, Map<Locale, String> nameMap,
189                            Map<Locale, String> descriptionMap, ServiceContext serviceContext)
190                    throws PortalException, SystemException {
191    
192                    DDMTemplate template = ddmTemplatePersistence.findByPrimaryKey(
193                            templateId);
194    
195                    File smallImageFile = null;
196    
197                    if (template.isSmallImage() &&
198                                    Validator.isNull(template.getSmallImageURL())) {
199    
200                            Image smallImage = ImageUtil.fetchByPrimaryKey(
201                                    template.getSmallImageId());
202    
203                            if (smallImage != null) {
204                                    smallImageFile = FileUtil.createTempFile(smallImage.getType());
205    
206                                    try {
207                                            FileUtil.write(smallImageFile, smallImage.getTextObj());
208                                    }
209                                    catch (IOException ioe) {
210                                            _log.error(ioe);
211                                    }
212                            }
213                    }
214    
215                    return addTemplate(
216                            userId, template.getGroupId(), template.getClassNameId(),
217                            template.getClassPK(), null, nameMap, descriptionMap,
218                            template.getType(), template.getMode(), template.getLanguage(),
219                            template.getScript(), template.isCacheable(),
220                            template.isSmallImage(), template.getSmallImageURL(),
221                            smallImageFile, serviceContext);
222            }
223    
224            public List<DDMTemplate> copyTemplates(
225                            long userId, long classNameId, long oldClassPK, long newClassPK,
226                            String type, ServiceContext serviceContext)
227                    throws PortalException, SystemException {
228    
229                    List<DDMTemplate> newTemplates = new ArrayList<DDMTemplate>();
230    
231                    List<DDMTemplate> oldTemplates = ddmTemplatePersistence.findByC_C_T(
232                            classNameId, oldClassPK, type);
233    
234                    for (DDMTemplate oldTemplate : oldTemplates) {
235                            DDMTemplate newTemplate = copyTemplate(
236                                    userId, oldTemplate.getTemplateId(), oldTemplate.getNameMap(),
237                                    oldTemplate.getDescriptionMap(), serviceContext);
238    
239                            newTemplates.add(newTemplate);
240                    }
241    
242                    return newTemplates;
243            }
244    
245            public void deleteTemplate(DDMTemplate template)
246                    throws PortalException, SystemException {
247    
248                    // Template
249    
250                    ddmTemplatePersistence.remove(template);
251    
252                    // Resources
253    
254                    resourceLocalService.deleteResource(
255                            template.getCompanyId(), DDMTemplate.class.getName(),
256                            ResourceConstants.SCOPE_INDIVIDUAL, template.getTemplateId());
257            }
258    
259            public void deleteTemplate(long templateId)
260                    throws PortalException, SystemException {
261    
262                    DDMTemplate template = ddmTemplatePersistence.findByPrimaryKey(
263                            templateId);
264    
265                    deleteTemplate(template);
266            }
267    
268            public void deleteTemplates(long groupId)
269                    throws PortalException, SystemException {
270    
271                    List<DDMTemplate> templates = ddmTemplatePersistence.findByGroupId(
272                            groupId);
273    
274                    for (DDMTemplate template : templates) {
275                            deleteTemplate(template);
276                    }
277            }
278    
279            public DDMTemplate fetchTemplate(long groupId, String templateKey)
280                    throws SystemException {
281    
282                    templateKey = templateKey.trim().toUpperCase();
283    
284                    return ddmTemplatePersistence.fetchByG_T(groupId, templateKey);
285            }
286    
287            public DDMTemplate getTemplate(long templateId)
288                    throws PortalException, SystemException {
289    
290                    return ddmTemplatePersistence.findByPrimaryKey(templateId);
291            }
292    
293            public DDMTemplate getTemplate(long groupId, String templateKey)
294                    throws PortalException, SystemException {
295    
296                    templateKey = templateKey.trim().toUpperCase();
297    
298                    return ddmTemplatePersistence.findByG_T(groupId, templateKey);
299            }
300    
301            public DDMTemplate getTemplate(
302                            long groupId, String templateKey, boolean includeGlobalTemplates)
303                    throws PortalException, SystemException {
304    
305                    templateKey = templateKey.trim().toUpperCase();
306    
307                    DDMTemplate template = ddmTemplatePersistence.fetchByG_T(
308                            groupId, templateKey);
309    
310                    if (template != null) {
311                            return template;
312                    }
313    
314                    if (!includeGlobalTemplates) {
315                            throw new NoSuchTemplateException(
316                                    "No DDMTemplate exists with the template key " + templateKey);
317                    }
318    
319                    Group group = groupPersistence.findByPrimaryKey(groupId);
320    
321                    Group companyGroup = groupLocalService.getCompanyGroup(
322                            group.getCompanyId());
323    
324                    return ddmTemplatePersistence.findByG_T(
325                            companyGroup.getGroupId(), templateKey);
326            }
327    
328            public List<DDMTemplate> getTemplates(long classPK) throws SystemException {
329                    return ddmTemplatePersistence.findByClassPK(classPK);
330            }
331    
332            public List<DDMTemplate> getTemplates(long groupId, long classNameId)
333                    throws SystemException {
334    
335                    return ddmTemplatePersistence.findByG_C(groupId, classNameId);
336            }
337    
338            public List<DDMTemplate> getTemplates(
339                            long groupId, long classNameId, long classPK)
340                    throws SystemException {
341    
342                    return ddmTemplatePersistence.findByG_C_C(
343                            groupId, classNameId, classPK);
344            }
345    
346            public List<DDMTemplate> getTemplates(
347                            long classNameId, long classPK, String type)
348                    throws SystemException {
349    
350                    return ddmTemplatePersistence.findByC_C_T(classNameId, classPK, type);
351            }
352    
353            public List<DDMTemplate> getTemplates(
354                            long classNameId, long classPK, String type, String mode)
355                    throws SystemException {
356    
357                    return ddmTemplatePersistence.findByC_C_T_M(
358                            classNameId, classPK, type, mode);
359            }
360    
361            public List<DDMTemplate> search(
362                            long companyId, long groupId, long classNameId, long classPK,
363                            String keywords, String type, String mode, int start, int end,
364                            OrderByComparator orderByComparator)
365                    throws SystemException {
366    
367                    return ddmTemplateFinder.findByKeywords(
368                            companyId, groupId, classNameId, classPK, keywords, type, mode,
369                            start, end, orderByComparator);
370            }
371    
372            public List<DDMTemplate> search(
373                            long companyId, long groupId, long classNameId, long classPK,
374                            String name, String description, String type, String mode,
375                            String language, boolean andOperator, int start, int end,
376                            OrderByComparator orderByComparator)
377                    throws SystemException {
378    
379                    return ddmTemplateFinder.findByC_G_C_C_N_D_T_M_L(
380                            companyId, groupId, classNameId, classPK, name, description, type,
381                            mode, language, andOperator, start, end, orderByComparator);
382            }
383    
384            public List<DDMTemplate> search(
385                            long companyId, long[] groupIds, long[] classNameIds, long classPK,
386                            String keywords, String type, String mode, int start, int end,
387                            OrderByComparator orderByComparator)
388                    throws SystemException {
389    
390                    return ddmTemplateFinder.findByKeywords(
391                            companyId, groupIds, classNameIds, classPK, keywords, type, mode,
392                            start, end, orderByComparator);
393            }
394    
395            public List<DDMTemplate> search(
396                            long companyId, long[] groupIds, long[] classNameIds, long classPK,
397                            String name, String description, String type, String mode,
398                            String language, boolean andOperator, int start, int end,
399                            OrderByComparator orderByComparator)
400                    throws SystemException {
401    
402                    return ddmTemplateFinder.findByC_G_C_C_N_D_T_M_L(
403                            companyId, groupIds, classNameIds, classPK, name, description, type,
404                            mode, language, andOperator, start, end, orderByComparator);
405            }
406    
407            public int searchCount(
408                            long companyId, long groupId, long classNameId, long classPK,
409                            String keywords, String type, String mode)
410                    throws SystemException {
411    
412                    return ddmTemplateFinder.countByKeywords(
413                            companyId, groupId, classNameId, classPK, keywords, type, mode);
414            }
415    
416            public int searchCount(
417                            long companyId, long groupId, long classNameId, long classPK,
418                            String name, String description, String type, String mode,
419                            String language, boolean andOperator)
420                    throws SystemException {
421    
422                    return ddmTemplateFinder.countByC_G_C_C_N_D_T_M_L(
423                            companyId, groupId, classNameId, classPK, name, description, type,
424                            mode, language, andOperator);
425            }
426    
427            public int searchCount(
428                            long companyId, long[] groupIds, long[] classNameIds, long classPK,
429                            String keywords, String type, String mode)
430                    throws SystemException {
431    
432                    return ddmTemplateFinder.countByKeywords(
433                            companyId, groupIds, classNameIds, classPK, keywords, type, mode);
434            }
435    
436            public int searchCount(
437                            long companyId, long[] groupIds, long[] classNameIds, long classPK,
438                            String name, String description, String type, String mode,
439                            String language, boolean andOperator)
440                    throws SystemException {
441    
442                    return ddmTemplateFinder.countByC_G_C_C_N_D_T_M_L(
443                            companyId, groupIds, classNameIds, classPK, name, description, type,
444                            mode, language, andOperator);
445            }
446    
447            public DDMTemplate updateTemplate(
448                            long templateId, Map<Locale, String> nameMap,
449                            Map<Locale, String> descriptionMap, String type, String mode,
450                            String language, String script, boolean cacheable,
451                            boolean smallImage, String smallImageURL, File smallImageFile,
452                            ServiceContext serviceContext)
453                    throws PortalException, SystemException {
454    
455                    byte[] smallImageBytes = null;
456    
457                    try {
458                            smallImageBytes = FileUtil.getBytes(smallImageFile);
459                    }
460                    catch (IOException ioe) {
461                    }
462    
463                    validate(
464                            nameMap, script, smallImage, smallImageURL, smallImageFile,
465                            smallImageBytes);
466    
467                    DDMTemplate template = ddmTemplateLocalService.getDDMTemplate(
468                            templateId);
469    
470                    template.setModifiedDate(serviceContext.getModifiedDate(null));
471                    template.setNameMap(nameMap);
472                    template.setDescriptionMap(descriptionMap);
473                    template.setType(type);
474                    template.setMode(mode);
475                    template.setLanguage(language);
476                    template.setScript(script);
477                    template.setCacheable(cacheable);
478                    template.setSmallImage(smallImage);
479                    template.setSmallImageURL(smallImageURL);
480    
481                    ddmTemplatePersistence.update(template);
482    
483                    // Small image
484    
485                    saveImages(
486                            smallImage, template.getSmallImageId(), smallImageFile,
487                            smallImageBytes);
488    
489                    return template;
490            }
491    
492            protected void saveImages(
493                            boolean smallImage, long smallImageId, File smallImageFile,
494                            byte[] smallImageBytes)
495                    throws PortalException, SystemException {
496    
497                    if (smallImage) {
498                            if ((smallImageFile != null) && (smallImageBytes != null)) {
499                                    imageLocalService.updateImage(smallImageId, smallImageBytes);
500                            }
501                    }
502                    else {
503                            imageLocalService.deleteImage(smallImageId);
504                    }
505            }
506    
507            protected void validate(
508                            long groupId, String templateKey, Map<Locale, String> nameMap,
509                            String script, boolean smallImage, String smallImageURL,
510                            File smallImageFile, byte[] smallImageBytes)
511                    throws PortalException, SystemException {
512    
513                    templateKey = templateKey.trim().toUpperCase();
514    
515                    DDMTemplate template = ddmTemplatePersistence.fetchByG_T(
516                            groupId, templateKey);
517    
518                    if (template != null) {
519                            throw new TemplateDuplicateTemplateKeyException();
520                    }
521    
522                    validate(
523                            nameMap, script, smallImage, smallImageURL, smallImageFile,
524                            smallImageBytes);
525            }
526    
527            protected void validate(
528                            Map<Locale, String> nameMap, String script, boolean smallImage,
529                            String smallImageURL, File smallImageFile, byte[] smallImageBytes)
530                    throws PortalException, SystemException {
531    
532                    validateName(nameMap);
533    
534                    if (Validator.isNull(script)) {
535                            throw new TemplateScriptException();
536                    }
537    
538                    String[] imageExtensions = PrefsPropsUtil.getStringArray(
539                            PropsKeys.DYNAMIC_DATA_MAPPING_IMAGE_EXTENSIONS, StringPool.COMMA);
540    
541                    if (smallImage && Validator.isNull(smallImageURL) &&
542                            (smallImageFile != null) && (smallImageBytes != null)) {
543    
544                            String smallImageName = smallImageFile.getName();
545    
546                            if (smallImageName != null) {
547                                    boolean validSmallImageExtension = false;
548    
549                                    for (int i = 0; i < imageExtensions.length; i++) {
550                                            if (StringPool.STAR.equals(imageExtensions[i]) ||
551                                                    StringUtil.endsWith(
552                                                            smallImageName, imageExtensions[i])) {
553    
554                                                    validSmallImageExtension = true;
555    
556                                                    break;
557                                            }
558                                    }
559    
560                                    if (!validSmallImageExtension) {
561                                            throw new TemplateSmallImageNameException(smallImageName);
562                                    }
563                            }
564    
565                            long smallImageMaxSize = PrefsPropsUtil.getLong(
566                                    PropsKeys.DYNAMIC_DATA_MAPPING_IMAGE_SMALL_MAX_SIZE);
567    
568                            if ((smallImageMaxSize > 0) &&
569                                    ((smallImageBytes == null) ||
570                                     (smallImageBytes.length > smallImageMaxSize))) {
571    
572                                    throw new TemplateSmallImageSizeException();
573                            }
574                    }
575            }
576    
577            protected void validateName(Map<Locale, String> nameMap)
578                    throws PortalException {
579    
580                    String name = nameMap.get(LocaleUtil.getDefault());
581    
582                    if (Validator.isNull(name)) {
583                            throw new TemplateNameException();
584                    }
585            }
586    
587            private static Log _log = LogFactoryUtil.getLog(
588                    DDMTemplateLocalServiceImpl.class);
589    
590    }