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