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