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