1   /**
2    * Copyright (c) 2000-2008 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.portal.service.persistence;
24  
25  import com.liferay.portal.NoSuchImageException;
26  import com.liferay.portal.SystemException;
27  import com.liferay.portal.kernel.dao.DynamicQuery;
28  import com.liferay.portal.kernel.dao.DynamicQueryInitializer;
29  import com.liferay.portal.kernel.util.GetterUtil;
30  import com.liferay.portal.kernel.util.OrderByComparator;
31  import com.liferay.portal.kernel.util.StringMaker;
32  import com.liferay.portal.kernel.util.StringPool;
33  import com.liferay.portal.kernel.util.StringUtil;
34  import com.liferay.portal.model.Image;
35  import com.liferay.portal.model.ModelListener;
36  import com.liferay.portal.model.impl.ImageImpl;
37  import com.liferay.portal.model.impl.ImageModelImpl;
38  import com.liferay.portal.spring.hibernate.FinderCache;
39  import com.liferay.portal.spring.hibernate.HibernateUtil;
40  import com.liferay.portal.util.PropsUtil;
41  
42  import com.liferay.util.dao.hibernate.QueryUtil;
43  
44  import org.apache.commons.logging.Log;
45  import org.apache.commons.logging.LogFactory;
46  
47  import org.hibernate.Query;
48  import org.hibernate.Session;
49  
50  import java.util.ArrayList;
51  import java.util.Collections;
52  import java.util.Iterator;
53  import java.util.List;
54  
55  /**
56   * <a href="ImagePersistenceImpl.java.html"><b><i>View Source</i></b></a>
57   *
58   * @author Brian Wing Shun Chan
59   *
60   */
61  public class ImagePersistenceImpl extends BasePersistence
62      implements ImagePersistence {
63      public Image create(long imageId) {
64          Image image = new ImageImpl();
65  
66          image.setNew(true);
67          image.setPrimaryKey(imageId);
68  
69          return image;
70      }
71  
72      public Image remove(long imageId)
73          throws NoSuchImageException, SystemException {
74          Session session = null;
75  
76          try {
77              session = openSession();
78  
79              Image image = (Image)session.get(ImageImpl.class, new Long(imageId));
80  
81              if (image == null) {
82                  if (_log.isWarnEnabled()) {
83                      _log.warn("No Image exists with the primary key " +
84                          imageId);
85                  }
86  
87                  throw new NoSuchImageException(
88                      "No Image exists with the primary key " + imageId);
89              }
90  
91              return remove(image);
92          }
93          catch (NoSuchImageException nsee) {
94              throw nsee;
95          }
96          catch (Exception e) {
97              throw HibernateUtil.processException(e);
98          }
99          finally {
100             closeSession(session);
101         }
102     }
103 
104     public Image remove(Image image) throws SystemException {
105         if (_listeners != null) {
106             for (ModelListener listener : _listeners) {
107                 listener.onBeforeRemove(image);
108             }
109         }
110 
111         image = removeImpl(image);
112 
113         if (_listeners != null) {
114             for (ModelListener listener : _listeners) {
115                 listener.onAfterRemove(image);
116             }
117         }
118 
119         return image;
120     }
121 
122     protected Image removeImpl(Image image) throws SystemException {
123         Session session = null;
124 
125         try {
126             session = openSession();
127 
128             session.delete(image);
129 
130             session.flush();
131 
132             return image;
133         }
134         catch (Exception e) {
135             throw HibernateUtil.processException(e);
136         }
137         finally {
138             closeSession(session);
139 
140             FinderCache.clearCache(Image.class.getName());
141         }
142     }
143 
144     /**
145      * @deprecated Use <code>update(Image image, boolean merge)</code>.
146      */
147     public Image update(Image image) throws SystemException {
148         if (_log.isWarnEnabled()) {
149             _log.warn(
150                 "Using the deprecated update(Image image) method. Use update(Image image, boolean merge) instead.");
151         }
152 
153         return update(image, false);
154     }
155 
156     /**
157      * Add, update, or merge, the entity. This method also calls the model
158      * listeners to trigger the proper events associated with adding, deleting,
159      * or updating an entity.
160      *
161      * @param        image the entity to add, update, or merge
162      * @param        merge boolean value for whether to merge the entity. The
163      *                default value is false. Setting merge to true is more
164      *                expensive and should only be true when image is
165      *                transient. See LEP-5473 for a detailed discussion of this
166      *                method.
167      * @return        true if the portlet can be displayed via Ajax
168      */
169     public Image update(Image image, boolean merge) throws SystemException {
170         boolean isNew = image.isNew();
171 
172         if (_listeners != null) {
173             for (ModelListener listener : _listeners) {
174                 if (isNew) {
175                     listener.onBeforeCreate(image);
176                 }
177                 else {
178                     listener.onBeforeUpdate(image);
179                 }
180             }
181         }
182 
183         image = updateImpl(image, merge);
184 
185         if (_listeners != null) {
186             for (ModelListener listener : _listeners) {
187                 if (isNew) {
188                     listener.onAfterCreate(image);
189                 }
190                 else {
191                     listener.onAfterUpdate(image);
192                 }
193             }
194         }
195 
196         return image;
197     }
198 
199     public Image updateImpl(com.liferay.portal.model.Image image, boolean merge)
200         throws SystemException {
201         Session session = null;
202 
203         try {
204             session = openSession();
205 
206             if (merge) {
207                 session.merge(image);
208             }
209             else {
210                 if (image.isNew()) {
211                     session.save(image);
212                 }
213             }
214 
215             session.flush();
216 
217             image.setNew(false);
218 
219             return image;
220         }
221         catch (Exception e) {
222             throw HibernateUtil.processException(e);
223         }
224         finally {
225             closeSession(session);
226 
227             FinderCache.clearCache(Image.class.getName());
228         }
229     }
230 
231     public Image findByPrimaryKey(long imageId)
232         throws NoSuchImageException, SystemException {
233         Image image = fetchByPrimaryKey(imageId);
234 
235         if (image == null) {
236             if (_log.isWarnEnabled()) {
237                 _log.warn("No Image exists with the primary key " + imageId);
238             }
239 
240             throw new NoSuchImageException(
241                 "No Image exists with the primary key " + imageId);
242         }
243 
244         return image;
245     }
246 
247     public Image fetchByPrimaryKey(long imageId) throws SystemException {
248         Session session = null;
249 
250         try {
251             session = openSession();
252 
253             return (Image)session.get(ImageImpl.class, new Long(imageId));
254         }
255         catch (Exception e) {
256             throw HibernateUtil.processException(e);
257         }
258         finally {
259             closeSession(session);
260         }
261     }
262 
263     public List<Image> findBySize(int size) throws SystemException {
264         boolean finderClassNameCacheEnabled = ImageModelImpl.CACHE_ENABLED;
265         String finderClassName = Image.class.getName();
266         String finderMethodName = "findBySize";
267         String[] finderParams = new String[] { Integer.class.getName() };
268         Object[] finderArgs = new Object[] { new Integer(size) };
269 
270         Object result = null;
271 
272         if (finderClassNameCacheEnabled) {
273             result = FinderCache.getResult(finderClassName, finderMethodName,
274                     finderParams, finderArgs, getSessionFactory());
275         }
276 
277         if (result == null) {
278             Session session = null;
279 
280             try {
281                 session = openSession();
282 
283                 StringMaker query = new StringMaker();
284 
285                 query.append("FROM com.liferay.portal.model.Image WHERE ");
286 
287                 query.append("size_ < ?");
288 
289                 query.append(" ");
290 
291                 query.append("ORDER BY ");
292 
293                 query.append("imageId ASC");
294 
295                 Query q = session.createQuery(query.toString());
296 
297                 int queryPos = 0;
298 
299                 q.setInteger(queryPos++, size);
300 
301                 List<Image> list = q.list();
302 
303                 FinderCache.putResult(finderClassNameCacheEnabled,
304                     finderClassName, finderMethodName, finderParams,
305                     finderArgs, list);
306 
307                 return list;
308             }
309             catch (Exception e) {
310                 throw HibernateUtil.processException(e);
311             }
312             finally {
313                 closeSession(session);
314             }
315         }
316         else {
317             return (List<Image>)result;
318         }
319     }
320 
321     public List<Image> findBySize(int size, int begin, int end)
322         throws SystemException {
323         return findBySize(size, begin, end, null);
324     }
325 
326     public List<Image> findBySize(int size, int begin, int end,
327         OrderByComparator obc) throws SystemException {
328         boolean finderClassNameCacheEnabled = ImageModelImpl.CACHE_ENABLED;
329         String finderClassName = Image.class.getName();
330         String finderMethodName = "findBySize";
331         String[] finderParams = new String[] {
332                 Integer.class.getName(),
333                 
334                 "java.lang.Integer", "java.lang.Integer",
335                 "com.liferay.portal.kernel.util.OrderByComparator"
336             };
337         Object[] finderArgs = new Object[] {
338                 new Integer(size),
339                 
340                 String.valueOf(begin), String.valueOf(end), String.valueOf(obc)
341             };
342 
343         Object result = null;
344 
345         if (finderClassNameCacheEnabled) {
346             result = FinderCache.getResult(finderClassName, finderMethodName,
347                     finderParams, finderArgs, getSessionFactory());
348         }
349 
350         if (result == null) {
351             Session session = null;
352 
353             try {
354                 session = openSession();
355 
356                 StringMaker query = new StringMaker();
357 
358                 query.append("FROM com.liferay.portal.model.Image WHERE ");
359 
360                 query.append("size_ < ?");
361 
362                 query.append(" ");
363 
364                 if (obc != null) {
365                     query.append("ORDER BY ");
366                     query.append(obc.getOrderBy());
367                 }
368 
369                 else {
370                     query.append("ORDER BY ");
371 
372                     query.append("imageId ASC");
373                 }
374 
375                 Query q = session.createQuery(query.toString());
376 
377                 int queryPos = 0;
378 
379                 q.setInteger(queryPos++, size);
380 
381                 List<Image> list = (List<Image>)QueryUtil.list(q, getDialect(),
382                         begin, end);
383 
384                 FinderCache.putResult(finderClassNameCacheEnabled,
385                     finderClassName, finderMethodName, finderParams,
386                     finderArgs, list);
387 
388                 return list;
389             }
390             catch (Exception e) {
391                 throw HibernateUtil.processException(e);
392             }
393             finally {
394                 closeSession(session);
395             }
396         }
397         else {
398             return (List<Image>)result;
399         }
400     }
401 
402     public Image findBySize_First(int size, OrderByComparator obc)
403         throws NoSuchImageException, SystemException {
404         List<Image> list = findBySize(size, 0, 1, obc);
405 
406         if (list.size() == 0) {
407             StringMaker msg = new StringMaker();
408 
409             msg.append("No Image exists with the key {");
410 
411             msg.append("size=" + size);
412 
413             msg.append(StringPool.CLOSE_CURLY_BRACE);
414 
415             throw new NoSuchImageException(msg.toString());
416         }
417         else {
418             return list.get(0);
419         }
420     }
421 
422     public Image findBySize_Last(int size, OrderByComparator obc)
423         throws NoSuchImageException, SystemException {
424         int count = countBySize(size);
425 
426         List<Image> list = findBySize(size, count - 1, count, obc);
427 
428         if (list.size() == 0) {
429             StringMaker msg = new StringMaker();
430 
431             msg.append("No Image exists with the key {");
432 
433             msg.append("size=" + size);
434 
435             msg.append(StringPool.CLOSE_CURLY_BRACE);
436 
437             throw new NoSuchImageException(msg.toString());
438         }
439         else {
440             return list.get(0);
441         }
442     }
443 
444     public Image[] findBySize_PrevAndNext(long imageId, int size,
445         OrderByComparator obc) throws NoSuchImageException, SystemException {
446         Image image = findByPrimaryKey(imageId);
447 
448         int count = countBySize(size);
449 
450         Session session = null;
451 
452         try {
453             session = openSession();
454 
455             StringMaker query = new StringMaker();
456 
457             query.append("FROM com.liferay.portal.model.Image WHERE ");
458 
459             query.append("size_ < ?");
460 
461             query.append(" ");
462 
463             if (obc != null) {
464                 query.append("ORDER BY ");
465                 query.append(obc.getOrderBy());
466             }
467 
468             else {
469                 query.append("ORDER BY ");
470 
471                 query.append("imageId ASC");
472             }
473 
474             Query q = session.createQuery(query.toString());
475 
476             int queryPos = 0;
477 
478             q.setInteger(queryPos++, size);
479 
480             Object[] objArray = QueryUtil.getPrevAndNext(q, count, obc, image);
481 
482             Image[] array = new ImageImpl[3];
483 
484             array[0] = (Image)objArray[0];
485             array[1] = (Image)objArray[1];
486             array[2] = (Image)objArray[2];
487 
488             return array;
489         }
490         catch (Exception e) {
491             throw HibernateUtil.processException(e);
492         }
493         finally {
494             closeSession(session);
495         }
496     }
497 
498     public List<Image> findWithDynamicQuery(
499         DynamicQueryInitializer queryInitializer) throws SystemException {
500         Session session = null;
501 
502         try {
503             session = openSession();
504 
505             DynamicQuery query = queryInitializer.initialize(session);
506 
507             return query.list();
508         }
509         catch (Exception e) {
510             throw HibernateUtil.processException(e);
511         }
512         finally {
513             closeSession(session);
514         }
515     }
516 
517     public List<Image> findWithDynamicQuery(
518         DynamicQueryInitializer queryInitializer, int begin, int end)
519         throws SystemException {
520         Session session = null;
521 
522         try {
523             session = openSession();
524 
525             DynamicQuery query = queryInitializer.initialize(session);
526 
527             query.setLimit(begin, end);
528 
529             return query.list();
530         }
531         catch (Exception e) {
532             throw HibernateUtil.processException(e);
533         }
534         finally {
535             closeSession(session);
536         }
537     }
538 
539     public List<Image> findAll() throws SystemException {
540         return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
541     }
542 
543     public List<Image> findAll(int begin, int end) throws SystemException {
544         return findAll(begin, end, null);
545     }
546 
547     public List<Image> findAll(int begin, int end, OrderByComparator obc)
548         throws SystemException {
549         boolean finderClassNameCacheEnabled = ImageModelImpl.CACHE_ENABLED;
550         String finderClassName = Image.class.getName();
551         String finderMethodName = "findAll";
552         String[] finderParams = new String[] {
553                 "java.lang.Integer", "java.lang.Integer",
554                 "com.liferay.portal.kernel.util.OrderByComparator"
555             };
556         Object[] finderArgs = new Object[] {
557                 String.valueOf(begin), String.valueOf(end), String.valueOf(obc)
558             };
559 
560         Object result = null;
561 
562         if (finderClassNameCacheEnabled) {
563             result = FinderCache.getResult(finderClassName, finderMethodName,
564                     finderParams, finderArgs, getSessionFactory());
565         }
566 
567         if (result == null) {
568             Session session = null;
569 
570             try {
571                 session = openSession();
572 
573                 StringMaker query = new StringMaker();
574 
575                 query.append("FROM com.liferay.portal.model.Image ");
576 
577                 if (obc != null) {
578                     query.append("ORDER BY ");
579                     query.append(obc.getOrderBy());
580                 }
581 
582                 else {
583                     query.append("ORDER BY ");
584 
585                     query.append("imageId ASC");
586                 }
587 
588                 Query q = session.createQuery(query.toString());
589 
590                 List<Image> list = (List<Image>)QueryUtil.list(q, getDialect(),
591                         begin, end);
592 
593                 if (obc == null) {
594                     Collections.sort(list);
595                 }
596 
597                 FinderCache.putResult(finderClassNameCacheEnabled,
598                     finderClassName, finderMethodName, finderParams,
599                     finderArgs, list);
600 
601                 return list;
602             }
603             catch (Exception e) {
604                 throw HibernateUtil.processException(e);
605             }
606             finally {
607                 closeSession(session);
608             }
609         }
610         else {
611             return (List<Image>)result;
612         }
613     }
614 
615     public void removeBySize(int size) throws SystemException {
616         for (Image image : findBySize(size)) {
617             remove(image);
618         }
619     }
620 
621     public void removeAll() throws SystemException {
622         for (Image image : findAll()) {
623             remove(image);
624         }
625     }
626 
627     public int countBySize(int size) throws SystemException {
628         boolean finderClassNameCacheEnabled = ImageModelImpl.CACHE_ENABLED;
629         String finderClassName = Image.class.getName();
630         String finderMethodName = "countBySize";
631         String[] finderParams = new String[] { Integer.class.getName() };
632         Object[] finderArgs = new Object[] { new Integer(size) };
633 
634         Object result = null;
635 
636         if (finderClassNameCacheEnabled) {
637             result = FinderCache.getResult(finderClassName, finderMethodName,
638                     finderParams, finderArgs, getSessionFactory());
639         }
640 
641         if (result == null) {
642             Session session = null;
643 
644             try {
645                 session = openSession();
646 
647                 StringMaker query = new StringMaker();
648 
649                 query.append("SELECT COUNT(*) ");
650                 query.append("FROM com.liferay.portal.model.Image WHERE ");
651 
652                 query.append("size_ < ?");
653 
654                 query.append(" ");
655 
656                 Query q = session.createQuery(query.toString());
657 
658                 int queryPos = 0;
659 
660                 q.setInteger(queryPos++, size);
661 
662                 Long count = null;
663 
664                 Iterator<Long> itr = q.list().iterator();
665 
666                 if (itr.hasNext()) {
667                     count = itr.next();
668                 }
669 
670                 if (count == null) {
671                     count = new Long(0);
672                 }
673 
674                 FinderCache.putResult(finderClassNameCacheEnabled,
675                     finderClassName, finderMethodName, finderParams,
676                     finderArgs, count);
677 
678                 return count.intValue();
679             }
680             catch (Exception e) {
681                 throw HibernateUtil.processException(e);
682             }
683             finally {
684                 closeSession(session);
685             }
686         }
687         else {
688             return ((Long)result).intValue();
689         }
690     }
691 
692     public int countAll() throws SystemException {
693         boolean finderClassNameCacheEnabled = ImageModelImpl.CACHE_ENABLED;
694         String finderClassName = Image.class.getName();
695         String finderMethodName = "countAll";
696         String[] finderParams = new String[] {  };
697         Object[] finderArgs = new Object[] {  };
698 
699         Object result = null;
700 
701         if (finderClassNameCacheEnabled) {
702             result = FinderCache.getResult(finderClassName, finderMethodName,
703                     finderParams, finderArgs, getSessionFactory());
704         }
705 
706         if (result == null) {
707             Session session = null;
708 
709             try {
710                 session = openSession();
711 
712                 Query q = session.createQuery(
713                         "SELECT COUNT(*) FROM com.liferay.portal.model.Image");
714 
715                 Long count = null;
716 
717                 Iterator<Long> itr = q.list().iterator();
718 
719                 if (itr.hasNext()) {
720                     count = itr.next();
721                 }
722 
723                 if (count == null) {
724                     count = new Long(0);
725                 }
726 
727                 FinderCache.putResult(finderClassNameCacheEnabled,
728                     finderClassName, finderMethodName, finderParams,
729                     finderArgs, count);
730 
731                 return count.intValue();
732             }
733             catch (Exception e) {
734                 throw HibernateUtil.processException(e);
735             }
736             finally {
737                 closeSession(session);
738             }
739         }
740         else {
741             return ((Long)result).intValue();
742         }
743     }
744 
745     protected void initDao() {
746         String[] listenerClassNames = StringUtil.split(GetterUtil.getString(
747                     PropsUtil.get(
748                         "value.object.listener.com.liferay.portal.model.Image")));
749 
750         if (listenerClassNames.length > 0) {
751             try {
752                 List<ModelListener> listeners = new ArrayList<ModelListener>();
753 
754                 for (String listenerClassName : listenerClassNames) {
755                     listeners.add((ModelListener)Class.forName(
756                             listenerClassName).newInstance());
757                 }
758 
759                 _listeners = listeners.toArray(new ModelListener[listeners.size()]);
760             }
761             catch (Exception e) {
762                 _log.error(e);
763             }
764         }
765     }
766 
767     private static Log _log = LogFactory.getLog(ImagePersistenceImpl.class);
768     private ModelListener[] _listeners;
769 }