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