1   /**
2    * Copyright (c) 2000-2007 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portlet.imagegallery.service.impl;
24  
25  import com.liferay.counter.service.CounterLocalServiceUtil;
26  import com.liferay.portal.PortalException;
27  import com.liferay.portal.SystemException;
28  import com.liferay.portal.kernel.util.ByteArrayMaker;
29  import com.liferay.portal.kernel.util.GetterUtil;
30  import com.liferay.portal.kernel.util.OrderByComparator;
31  import com.liferay.portal.kernel.util.StringPool;
32  import com.liferay.portal.kernel.util.StringUtil;
33  import com.liferay.portal.model.Image;
34  import com.liferay.portal.model.User;
35  import com.liferay.portal.model.impl.ResourceImpl;
36  import com.liferay.portal.service.ResourceLocalServiceUtil;
37  import com.liferay.portal.service.impl.ImageLocalUtil;
38  import com.liferay.portal.service.persistence.UserUtil;
39  import com.liferay.portal.util.PropsUtil;
40  import com.liferay.portlet.imagegallery.ImageNameException;
41  import com.liferay.portlet.imagegallery.ImageSizeException;
42  import com.liferay.portlet.imagegallery.model.IGFolder;
43  import com.liferay.portlet.imagegallery.model.IGImage;
44  import com.liferay.portlet.imagegallery.service.base.IGImageLocalServiceBaseImpl;
45  import com.liferay.portlet.imagegallery.service.persistence.IGFolderUtil;
46  import com.liferay.portlet.imagegallery.service.persistence.IGImageFinder;
47  import com.liferay.portlet.imagegallery.service.persistence.IGImageUtil;
48  import com.liferay.portlet.tags.service.TagsAssetLocalServiceUtil;
49  import com.liferay.util.FileUtil;
50  import com.liferay.util.ImageUtil;
51  
52  import com.sun.media.jai.codec.ImageCodec;
53  import com.sun.media.jai.codec.ImageEncoder;
54  
55  import java.awt.image.RenderedImage;
56  
57  import java.io.File;
58  import java.io.IOException;
59  
60  import java.util.Date;
61  import java.util.Iterator;
62  import java.util.List;
63  
64  import javax.imageio.ImageIO;
65  
66  /**
67   * <a href="IGImageLocalServiceImpl.java.html"><b><i>View Source</i></b></a>
68   *
69   * @author Brian Wing Shun Chan
70   *
71   */
72  public class IGImageLocalServiceImpl extends IGImageLocalServiceBaseImpl {
73  
74      public IGImage addImage(
75              long userId, long folderId, String description, File file,
76              String contentType, String[] tagsEntries,
77              boolean addCommunityPermissions, boolean addGuestPermissions)
78          throws PortalException, SystemException {
79  
80          return addImage(
81              userId, folderId, description, file, contentType, tagsEntries,
82              Boolean.valueOf(addCommunityPermissions),
83              Boolean.valueOf(addGuestPermissions), null, null);
84      }
85  
86      public IGImage addImage(
87              long userId, long folderId, String description, File file,
88              String contentType, String[] tagsEntries,
89              String[] communityPermissions, String[] guestPermissions)
90          throws PortalException, SystemException {
91  
92          return addImage(
93              userId, folderId, description, file, contentType, tagsEntries,
94              null, null, communityPermissions, guestPermissions);
95      }
96  
97      public IGImage addImage(
98              long userId, long folderId, String description, File file,
99              String contentType, String[] tagsEntries,
100             Boolean addCommunityPermissions, Boolean addGuestPermissions,
101             String[] communityPermissions, String[] guestPermissions)
102         throws PortalException, SystemException {
103 
104         try {
105 
106             // Image
107 
108             User user = UserUtil.findByPrimaryKey(userId);
109             IGFolder folder = IGFolderUtil.findByPrimaryKey(folderId);
110             RenderedImage renderedImage = ImageUtil.read(
111                 file).getRenderedImage();
112             byte[] bytes = FileUtil.getBytes(file);
113             Date now = new Date();
114 
115             validate(file, bytes);
116 
117             long imageId = CounterLocalServiceUtil.increment();
118 
119             IGImage image = IGImageUtil.create(imageId);
120 
121             image.setCompanyId(user.getCompanyId());
122             image.setUserId(user.getUserId());
123             image.setCreateDate(now);
124             image.setModifiedDate(now);
125             image.setFolderId(folderId);
126             image.setDescription(description);
127             image.setSmallImageId(CounterLocalServiceUtil.increment());
128             image.setLargeImageId(CounterLocalServiceUtil.increment());
129 
130             IGImageUtil.update(image);
131 
132             // Images
133 
134             saveImages(
135                 image.getLargeImageId(), renderedImage, image.getSmallImageId(),
136                 file, bytes, contentType);
137 
138             // Resources
139 
140             if ((addCommunityPermissions != null) &&
141                 (addGuestPermissions != null)) {
142 
143                 addImageResources(
144                     folder, image, addCommunityPermissions.booleanValue(),
145                     addGuestPermissions.booleanValue());
146             }
147             else {
148                 addImageResources(
149                     folder, image, communityPermissions, guestPermissions);
150             }
151 
152             // Tags
153 
154             updateTagsAsset(userId, image, tagsEntries);
155 
156             return image;
157         }
158         catch (IOException ioe) {
159             throw new ImageSizeException(ioe);
160         }
161     }
162 
163     public void addImageResources(
164             long folderId, long imageId, boolean addCommunityPermissions,
165             boolean addGuestPermissions)
166         throws PortalException, SystemException {
167 
168         IGFolder folder = IGFolderUtil.findByPrimaryKey(folderId);
169         IGImage image = IGImageUtil.findByPrimaryKey(imageId);
170 
171         addImageResources(
172             folder, image, addCommunityPermissions, addGuestPermissions);
173     }
174 
175     public void addImageResources(
176             IGFolder folder, IGImage image, boolean addCommunityPermissions,
177             boolean addGuestPermissions)
178         throws PortalException, SystemException {
179 
180         ResourceLocalServiceUtil.addResources(
181             image.getCompanyId(), folder.getGroupId(), image.getUserId(),
182             IGImage.class.getName(), image.getImageId(), false,
183             addCommunityPermissions, addGuestPermissions);
184     }
185 
186     public void addImageResources(
187             long folderId, long imageId, String[] communityPermissions,
188             String[] guestPermissions)
189         throws PortalException, SystemException {
190 
191         IGFolder folder = IGFolderUtil.findByPrimaryKey(folderId);
192         IGImage image = IGImageUtil.findByPrimaryKey(imageId);
193 
194         addImageResources(
195             folder, image, communityPermissions, guestPermissions);
196     }
197 
198     public void addImageResources(
199             IGFolder folder, IGImage image, String[] communityPermissions,
200             String[] guestPermissions)
201         throws PortalException, SystemException {
202 
203         ResourceLocalServiceUtil.addModelResources(
204             image.getCompanyId(), folder.getGroupId(), image.getUserId(),
205             IGImage.class.getName(), image.getImageId(), communityPermissions,
206             guestPermissions);
207     }
208 
209     public void deleteImage(long imageId)
210         throws PortalException, SystemException {
211 
212         IGImage image = IGImageUtil.findByPrimaryKey(imageId);
213 
214         deleteImage(image);
215     }
216 
217     public void deleteImage(IGImage image)
218         throws PortalException, SystemException {
219 
220         // Tags
221 
222         TagsAssetLocalServiceUtil.deleteAsset(
223             IGImage.class.getName(), image.getImageId());
224 
225         // Resources
226 
227         ResourceLocalServiceUtil.deleteResource(
228             image.getCompanyId(), IGImage.class.getName(),
229             ResourceImpl.SCOPE_INDIVIDUAL, image.getImageId());
230 
231         // Images
232 
233         ImageLocalUtil.deleteImage(image.getSmallImageId());
234         ImageLocalUtil.deleteImage(image.getLargeImageId());
235 
236         // Image
237 
238         IGImageUtil.remove(image.getPrimaryKey());
239     }
240 
241     public void deleteImages(long folderId)
242         throws PortalException, SystemException {
243 
244         Iterator itr = IGImageUtil.findByFolderId(folderId).iterator();
245 
246         while (itr.hasNext()) {
247             IGImage image = (IGImage)itr.next();
248 
249             deleteImage(image);
250         }
251     }
252 
253     public int getFoldersImagesCount(List folderIds)
254         throws SystemException {
255 
256         return IGImageFinder.countByFolderIds(folderIds);
257     }
258 
259     public List getGroupImages(long groupId, int begin, int end)
260         throws SystemException {
261 
262         return IGImageFinder.findByGroupId(groupId, begin, end);
263     }
264 
265     public List getGroupImages(long groupId, long userId, int begin, int end)
266         throws SystemException {
267 
268         if (userId <= 0) {
269             return IGImageFinder.findByGroupId(groupId, begin, end);
270         }
271         else {
272             return IGImageFinder.findByG_U(groupId, userId, begin, end);
273         }
274     }
275 
276     public int getGroupImagesCount(long groupId) throws SystemException {
277         return IGImageFinder.countByGroupId(groupId);
278     }
279 
280     public int getGroupImagesCount(long groupId, long userId)
281         throws SystemException {
282 
283         if (userId <= 0) {
284             return IGImageFinder.countByGroupId(groupId);
285         }
286         else {
287             return IGImageFinder.countByG_U(groupId, userId);
288         }
289     }
290 
291     public IGImage getImage(long imageId)
292         throws PortalException, SystemException {
293 
294         return IGImageUtil.findByPrimaryKey(imageId);
295     }
296 
297     public List getImages(long folderId) throws SystemException {
298         return IGImageUtil.findByFolderId(folderId);
299     }
300 
301     public List getImages(long folderId, int begin, int end)
302         throws SystemException {
303 
304         return IGImageUtil.findByFolderId(folderId, begin, end);
305     }
306 
307     public List getImages(
308             long folderId, int begin, int end, OrderByComparator obc)
309         throws SystemException {
310 
311         return IGImageUtil.findByFolderId(folderId, begin, end, obc);
312     }
313 
314     public int getImagesCount(long folderId) throws SystemException {
315         return IGImageUtil.countByFolderId(folderId);
316     }
317 
318     public List getNoAssetImages() throws SystemException {
319         return IGImageFinder.findByNoAssets();
320     }
321 
322     public IGImage updateImage(
323             long userId, long imageId, long folderId, String description,
324             File file, String contentType, String[] tagsEntries)
325         throws PortalException, SystemException {
326 
327         try {
328 
329             // Image
330 
331             IGImage image = IGImageUtil.findByPrimaryKey(imageId);
332 
333             IGFolder folder = getFolder(image, folderId);
334 
335             RenderedImage renderedImage = null;
336             byte[] bytes = null;
337 
338             if (file != null) {
339                 if (file.exists()) {
340                     renderedImage = ImageUtil.read(file).getRenderedImage();
341                     bytes = FileUtil.getBytes(file);
342                 }
343 
344                 validate(file, bytes);
345             }
346 
347             image.setModifiedDate(new Date());
348             image.setFolderId(folder.getFolderId());
349             image.setDescription(description);
350 
351             IGImageUtil.update(image);
352 
353             // Images
354 
355             if (renderedImage != null) {
356                 saveImages(
357                     image.getLargeImageId(), renderedImage,
358                     image.getSmallImageId(), file, bytes, contentType);
359             }
360 
361             // Tags
362 
363             updateTagsAsset(userId, image, tagsEntries);
364 
365             return image;
366         }
367         catch (IOException ioe) {
368             throw new ImageSizeException(ioe);
369         }
370     }
371 
372     public void updateTagsAsset(
373             long userId, IGImage image, String[] tagsEntries)
374         throws PortalException, SystemException {
375 
376         Image largeImage = ImageLocalUtil.getImage(image.getLargeImageId());
377 
378         if (largeImage == null) {
379             return;
380         }
381 
382         TagsAssetLocalServiceUtil.updateAsset(
383             userId, IGImage.class.getName(), image.getImageId(), tagsEntries,
384             null, null, null, null, largeImage.getType(),
385             image.getDescription(), image.getDescription(),
386             image.getDescription(), null, largeImage.getHeight(),
387             largeImage.getWidth());
388     }
389 
390     protected IGFolder getFolder(IGImage image, long folderId)
391         throws PortalException, SystemException {
392 
393         if (image.getFolderId() != folderId) {
394             IGFolder oldFolder = IGFolderUtil.findByPrimaryKey(
395                 image.getFolderId());
396 
397             IGFolder newFolder = IGFolderUtil.fetchByPrimaryKey(folderId);
398 
399             if ((newFolder == null) ||
400                 (oldFolder.getGroupId() != newFolder.getGroupId())) {
401 
402                 folderId = image.getFolderId();
403             }
404         }
405 
406         return IGFolderUtil.findByPrimaryKey(folderId);
407     }
408 
409     protected void saveImages(
410             long largeImageId, RenderedImage renderedImage, long smallImageId,
411             File file, byte[] bytes, String contentType)
412         throws SystemException {
413 
414         try {
415 
416             // Image
417 
418             ImageLocalUtil.updateImage(largeImageId, bytes);
419 
420             // Thumbnail
421 
422             int thumbnailMaxHeight = GetterUtil.getInteger(
423                 PropsUtil.get(PropsUtil.IG_IMAGE_THUMBNAIL_MAX_HEIGHT));
424 
425             int thumbnailMaxWidth = GetterUtil.getInteger(
426                 PropsUtil.get(PropsUtil.IG_IMAGE_THUMBNAIL_MAX_WIDTH));
427 
428             RenderedImage thumbnail = ImageUtil.scale(
429                 renderedImage, thumbnailMaxHeight, thumbnailMaxWidth);
430 
431             ByteArrayMaker bam = new ByteArrayMaker();
432 
433             if (contentType.indexOf("bmp") != -1) {
434                 ImageEncoder encoder = ImageCodec.createImageEncoder(
435                     "BMP", bam, null);
436 
437                 encoder.encode(thumbnail);
438             }
439             else if (contentType.indexOf("gif") != -1) {
440                 ImageUtil.encodeGIF(thumbnail, bam);
441             }
442             else if (contentType.indexOf("jpg") != -1 ||
443                      contentType.indexOf("jpeg") != -1) {
444 
445                 ImageIO.write(thumbnail, "jpeg", bam);
446             }
447             else if (contentType.indexOf("png") != -1) {
448                 ImageIO.write(thumbnail, "png", bam);
449             }
450             else if (contentType.indexOf("tif") != -1) {
451                 ImageEncoder encoder = ImageCodec.createImageEncoder(
452                     "TIFF", bam, null);
453 
454                 encoder.encode(thumbnail);
455             }
456 
457             ImageLocalUtil.updateImage(smallImageId, bam.toByteArray());
458         }
459         catch (IOException ioe) {
460             throw new SystemException(ioe);
461         }
462     }
463 
464     protected void validate(File file, byte[] bytes)
465         throws PortalException, SystemException {
466 
467         String imageName = StringPool.BLANK;
468 
469         if (file != null) {
470             imageName = file.getName();
471         }
472 
473         boolean validImageExtension = false;
474 
475         String[] imageExtensions =
476             PropsUtil.getArray(PropsUtil.IG_IMAGE_EXTENSIONS);
477 
478         for (int i = 0; i < imageExtensions.length; i++) {
479             if (StringPool.STAR.equals(imageExtensions[i]) ||
480                 StringUtil.endsWith(imageName, imageExtensions[i])) {
481 
482                 validImageExtension = true;
483 
484                 break;
485             }
486         }
487 
488         if (!validImageExtension) {
489             throw new ImageNameException(imageName);
490         }
491 
492         long imageMaxSize = GetterUtil.getLong(
493             PropsUtil.get(PropsUtil.IG_IMAGE_MAX_SIZE));
494 
495         if ((imageMaxSize > 0) &&
496             ((bytes == null) || (bytes.length > imageMaxSize))) {
497 
498             throw new ImageSizeException();
499         }
500     }
501 
502 }