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.NoSuchClassNameException;
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.ClassName;
40  import com.liferay.portal.model.ModelListener;
41  import com.liferay.portal.model.impl.ClassNameImpl;
42  import com.liferay.portal.model.impl.ClassNameModelImpl;
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="ClassNamePersistenceImpl.java.html"><b><i>View Source</i></b></a>
55   *
56   * @author Brian Wing Shun Chan
57   *
58   */
59  public class ClassNamePersistenceImpl extends BasePersistenceImpl
60      implements ClassNamePersistence, InitializingBean {
61      public ClassName create(long classNameId) {
62          ClassName className = new ClassNameImpl();
63  
64          className.setNew(true);
65          className.setPrimaryKey(classNameId);
66  
67          return className;
68      }
69  
70      public ClassName remove(long classNameId)
71          throws NoSuchClassNameException, SystemException {
72          Session session = null;
73  
74          try {
75              session = openSession();
76  
77              ClassName className = (ClassName)session.get(ClassNameImpl.class,
78                      new Long(classNameId));
79  
80              if (className == null) {
81                  if (_log.isWarnEnabled()) {
82                      _log.warn("No ClassName exists with the primary key " +
83                          classNameId);
84                  }
85  
86                  throw new NoSuchClassNameException(
87                      "No ClassName exists with the primary key " + classNameId);
88              }
89  
90              return remove(className);
91          }
92          catch (NoSuchClassNameException nsee) {
93              throw nsee;
94          }
95          catch (Exception e) {
96              throw processException(e);
97          }
98          finally {
99              closeSession(session);
100         }
101     }
102 
103     public ClassName remove(ClassName className) throws SystemException {
104         if (_listeners.length > 0) {
105             for (ModelListener listener : _listeners) {
106                 listener.onBeforeRemove(className);
107             }
108         }
109 
110         className = removeImpl(className);
111 
112         if (_listeners.length > 0) {
113             for (ModelListener listener : _listeners) {
114                 listener.onAfterRemove(className);
115             }
116         }
117 
118         return className;
119     }
120 
121     protected ClassName removeImpl(ClassName className)
122         throws SystemException {
123         Session session = null;
124 
125         try {
126             session = openSession();
127 
128             session.delete(className);
129 
130             session.flush();
131 
132             return className;
133         }
134         catch (Exception e) {
135             throw processException(e);
136         }
137         finally {
138             closeSession(session);
139 
140             FinderCacheUtil.clearCache(ClassName.class.getName());
141         }
142     }
143 
144     /**
145      * @deprecated Use <code>update(ClassName className, boolean merge)</code>.
146      */
147     public ClassName update(ClassName className) throws SystemException {
148         if (_log.isWarnEnabled()) {
149             _log.warn(
150                 "Using the deprecated update(ClassName className) method. Use update(ClassName className, boolean merge) instead.");
151         }
152 
153         return update(className, 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        className 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 className 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 ClassName update(ClassName className, boolean merge)
170         throws SystemException {
171         boolean isNew = className.isNew();
172 
173         if (_listeners.length > 0) {
174             for (ModelListener listener : _listeners) {
175                 if (isNew) {
176                     listener.onBeforeCreate(className);
177                 }
178                 else {
179                     listener.onBeforeUpdate(className);
180                 }
181             }
182         }
183 
184         className = updateImpl(className, merge);
185 
186         if (_listeners.length > 0) {
187             for (ModelListener listener : _listeners) {
188                 if (isNew) {
189                     listener.onAfterCreate(className);
190                 }
191                 else {
192                     listener.onAfterUpdate(className);
193                 }
194             }
195         }
196 
197         return className;
198     }
199 
200     public ClassName updateImpl(com.liferay.portal.model.ClassName className,
201         boolean merge) throws SystemException {
202         Session session = null;
203 
204         try {
205             session = openSession();
206 
207             if (merge) {
208                 session.merge(className);
209             }
210             else {
211                 if (className.isNew()) {
212                     session.save(className);
213                 }
214             }
215 
216             session.flush();
217 
218             className.setNew(false);
219 
220             return className;
221         }
222         catch (Exception e) {
223             throw processException(e);
224         }
225         finally {
226             closeSession(session);
227 
228             FinderCacheUtil.clearCache(ClassName.class.getName());
229         }
230     }
231 
232     public ClassName findByPrimaryKey(long classNameId)
233         throws NoSuchClassNameException, SystemException {
234         ClassName className = fetchByPrimaryKey(classNameId);
235 
236         if (className == null) {
237             if (_log.isWarnEnabled()) {
238                 _log.warn("No ClassName exists with the primary key " +
239                     classNameId);
240             }
241 
242             throw new NoSuchClassNameException(
243                 "No ClassName exists with the primary key " + classNameId);
244         }
245 
246         return className;
247     }
248 
249     public ClassName fetchByPrimaryKey(long classNameId)
250         throws SystemException {
251         Session session = null;
252 
253         try {
254             session = openSession();
255 
256             return (ClassName)session.get(ClassNameImpl.class,
257                 new Long(classNameId));
258         }
259         catch (Exception e) {
260             throw processException(e);
261         }
262         finally {
263             closeSession(session);
264         }
265     }
266 
267     public ClassName findByValue(String value)
268         throws NoSuchClassNameException, SystemException {
269         ClassName className = fetchByValue(value);
270 
271         if (className == null) {
272             StringBuilder msg = new StringBuilder();
273 
274             msg.append("No ClassName exists with the key {");
275 
276             msg.append("value=" + value);
277 
278             msg.append(StringPool.CLOSE_CURLY_BRACE);
279 
280             if (_log.isWarnEnabled()) {
281                 _log.warn(msg.toString());
282             }
283 
284             throw new NoSuchClassNameException(msg.toString());
285         }
286 
287         return className;
288     }
289 
290     public ClassName fetchByValue(String value) throws SystemException {
291         boolean finderClassNameCacheEnabled = ClassNameModelImpl.CACHE_ENABLED;
292         String finderClassName = ClassName.class.getName();
293         String finderMethodName = "fetchByValue";
294         String[] finderParams = new String[] { String.class.getName() };
295         Object[] finderArgs = new Object[] { value };
296 
297         Object result = null;
298 
299         if (finderClassNameCacheEnabled) {
300             result = FinderCacheUtil.getResult(finderClassName,
301                     finderMethodName, finderParams, finderArgs, this);
302         }
303 
304         if (result == null) {
305             Session session = null;
306 
307             try {
308                 session = openSession();
309 
310                 StringBuilder query = new StringBuilder();
311 
312                 query.append("FROM com.liferay.portal.model.ClassName WHERE ");
313 
314                 if (value == null) {
315                     query.append("value IS NULL");
316                 }
317                 else {
318                     query.append("value = ?");
319                 }
320 
321                 query.append(" ");
322 
323                 Query q = session.createQuery(query.toString());
324 
325                 QueryPos qPos = QueryPos.getInstance(q);
326 
327                 if (value != null) {
328                     qPos.add(value);
329                 }
330 
331                 List<ClassName> list = q.list();
332 
333                 FinderCacheUtil.putResult(finderClassNameCacheEnabled,
334                     finderClassName, finderMethodName, finderParams,
335                     finderArgs, list);
336 
337                 if (list.size() == 0) {
338                     return null;
339                 }
340                 else {
341                     return list.get(0);
342                 }
343             }
344             catch (Exception e) {
345                 throw processException(e);
346             }
347             finally {
348                 closeSession(session);
349             }
350         }
351         else {
352             List<ClassName> list = (List<ClassName>)result;
353 
354             if (list.size() == 0) {
355                 return null;
356             }
357             else {
358                 return list.get(0);
359             }
360         }
361     }
362 
363     public List<Object> findWithDynamicQuery(DynamicQuery dynamicQuery)
364         throws SystemException {
365         Session session = null;
366 
367         try {
368             session = openSession();
369 
370             dynamicQuery.compile(session);
371 
372             return dynamicQuery.list();
373         }
374         catch (Exception e) {
375             throw processException(e);
376         }
377         finally {
378             closeSession(session);
379         }
380     }
381 
382     public List<Object> findWithDynamicQuery(DynamicQuery dynamicQuery,
383         int start, int end) throws SystemException {
384         Session session = null;
385 
386         try {
387             session = openSession();
388 
389             dynamicQuery.setLimit(start, end);
390 
391             dynamicQuery.compile(session);
392 
393             return dynamicQuery.list();
394         }
395         catch (Exception e) {
396             throw processException(e);
397         }
398         finally {
399             closeSession(session);
400         }
401     }
402 
403     public List<ClassName> findAll() throws SystemException {
404         return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
405     }
406 
407     public List<ClassName> findAll(int start, int end)
408         throws SystemException {
409         return findAll(start, end, null);
410     }
411 
412     public List<ClassName> findAll(int start, int end, OrderByComparator obc)
413         throws SystemException {
414         boolean finderClassNameCacheEnabled = ClassNameModelImpl.CACHE_ENABLED;
415         String finderClassName = ClassName.class.getName();
416         String finderMethodName = "findAll";
417         String[] finderParams = new String[] {
418                 "java.lang.Integer", "java.lang.Integer",
419                 "com.liferay.portal.kernel.util.OrderByComparator"
420             };
421         Object[] finderArgs = new Object[] {
422                 String.valueOf(start), String.valueOf(end), String.valueOf(obc)
423             };
424 
425         Object result = null;
426 
427         if (finderClassNameCacheEnabled) {
428             result = FinderCacheUtil.getResult(finderClassName,
429                     finderMethodName, finderParams, finderArgs, this);
430         }
431 
432         if (result == null) {
433             Session session = null;
434 
435             try {
436                 session = openSession();
437 
438                 StringBuilder query = new StringBuilder();
439 
440                 query.append("FROM com.liferay.portal.model.ClassName ");
441 
442                 if (obc != null) {
443                     query.append("ORDER BY ");
444                     query.append(obc.getOrderBy());
445                 }
446 
447                 Query q = session.createQuery(query.toString());
448 
449                 List<ClassName> list = (List<ClassName>)QueryUtil.list(q,
450                         getDialect(), start, end);
451 
452                 if (obc == null) {
453                     Collections.sort(list);
454                 }
455 
456                 FinderCacheUtil.putResult(finderClassNameCacheEnabled,
457                     finderClassName, finderMethodName, finderParams,
458                     finderArgs, list);
459 
460                 return list;
461             }
462             catch (Exception e) {
463                 throw processException(e);
464             }
465             finally {
466                 closeSession(session);
467             }
468         }
469         else {
470             return (List<ClassName>)result;
471         }
472     }
473 
474     public void removeByValue(String value)
475         throws NoSuchClassNameException, SystemException {
476         ClassName className = findByValue(value);
477 
478         remove(className);
479     }
480 
481     public void removeAll() throws SystemException {
482         for (ClassName className : findAll()) {
483             remove(className);
484         }
485     }
486 
487     public int countByValue(String value) throws SystemException {
488         boolean finderClassNameCacheEnabled = ClassNameModelImpl.CACHE_ENABLED;
489         String finderClassName = ClassName.class.getName();
490         String finderMethodName = "countByValue";
491         String[] finderParams = new String[] { String.class.getName() };
492         Object[] finderArgs = new Object[] { value };
493 
494         Object result = null;
495 
496         if (finderClassNameCacheEnabled) {
497             result = FinderCacheUtil.getResult(finderClassName,
498                     finderMethodName, finderParams, finderArgs, this);
499         }
500 
501         if (result == null) {
502             Session session = null;
503 
504             try {
505                 session = openSession();
506 
507                 StringBuilder query = new StringBuilder();
508 
509                 query.append("SELECT COUNT(*) ");
510                 query.append("FROM com.liferay.portal.model.ClassName WHERE ");
511 
512                 if (value == null) {
513                     query.append("value IS NULL");
514                 }
515                 else {
516                     query.append("value = ?");
517                 }
518 
519                 query.append(" ");
520 
521                 Query q = session.createQuery(query.toString());
522 
523                 QueryPos qPos = QueryPos.getInstance(q);
524 
525                 if (value != null) {
526                     qPos.add(value);
527                 }
528 
529                 Long count = null;
530 
531                 Iterator<Long> itr = q.list().iterator();
532 
533                 if (itr.hasNext()) {
534                     count = itr.next();
535                 }
536 
537                 if (count == null) {
538                     count = new Long(0);
539                 }
540 
541                 FinderCacheUtil.putResult(finderClassNameCacheEnabled,
542                     finderClassName, finderMethodName, finderParams,
543                     finderArgs, count);
544 
545                 return count.intValue();
546             }
547             catch (Exception e) {
548                 throw processException(e);
549             }
550             finally {
551                 closeSession(session);
552             }
553         }
554         else {
555             return ((Long)result).intValue();
556         }
557     }
558 
559     public int countAll() throws SystemException {
560         boolean finderClassNameCacheEnabled = ClassNameModelImpl.CACHE_ENABLED;
561         String finderClassName = ClassName.class.getName();
562         String finderMethodName = "countAll";
563         String[] finderParams = new String[] {  };
564         Object[] finderArgs = new Object[] {  };
565 
566         Object result = null;
567 
568         if (finderClassNameCacheEnabled) {
569             result = FinderCacheUtil.getResult(finderClassName,
570                     finderMethodName, finderParams, finderArgs, this);
571         }
572 
573         if (result == null) {
574             Session session = null;
575 
576             try {
577                 session = openSession();
578 
579                 Query q = session.createQuery(
580                         "SELECT COUNT(*) FROM com.liferay.portal.model.ClassName");
581 
582                 Long count = null;
583 
584                 Iterator<Long> itr = q.list().iterator();
585 
586                 if (itr.hasNext()) {
587                     count = itr.next();
588                 }
589 
590                 if (count == null) {
591                     count = new Long(0);
592                 }
593 
594                 FinderCacheUtil.putResult(finderClassNameCacheEnabled,
595                     finderClassName, finderMethodName, finderParams,
596                     finderArgs, count);
597 
598                 return count.intValue();
599             }
600             catch (Exception e) {
601                 throw processException(e);
602             }
603             finally {
604                 closeSession(session);
605             }
606         }
607         else {
608             return ((Long)result).intValue();
609         }
610     }
611 
612     public void registerListener(ModelListener listener) {
613         List<ModelListener> listeners = ListUtil.fromArray(_listeners);
614 
615         listeners.add(listener);
616 
617         _listeners = listeners.toArray(new ModelListener[listeners.size()]);
618     }
619 
620     public void unregisterListener(ModelListener listener) {
621         List<ModelListener> listeners = ListUtil.fromArray(_listeners);
622 
623         listeners.remove(listener);
624 
625         _listeners = listeners.toArray(new ModelListener[listeners.size()]);
626     }
627 
628     public void afterPropertiesSet() {
629         String[] listenerClassNames = StringUtil.split(GetterUtil.getString(
630                     com.liferay.portal.util.PropsUtil.get(
631                         "value.object.listener.com.liferay.portal.model.ClassName")));
632 
633         if (listenerClassNames.length > 0) {
634             try {
635                 List<ModelListener> listeners = new ArrayList<ModelListener>();
636 
637                 for (String listenerClassName : listenerClassNames) {
638                     listeners.add((ModelListener)Class.forName(
639                             listenerClassName).newInstance());
640                 }
641 
642                 _listeners = listeners.toArray(new ModelListener[listeners.size()]);
643             }
644             catch (Exception e) {
645                 _log.error(e);
646             }
647         }
648     }
649 
650     private static Log _log = LogFactory.getLog(ClassNamePersistenceImpl.class);
651     private ModelListener[] _listeners = new ModelListener[0];
652 }