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