1   /**
2    * Copyright (c) 2000-2009 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.NoSuchGroupException;
26  import com.liferay.portal.SystemException;
27  import com.liferay.portal.kernel.dao.orm.FinderCacheUtil;
28  import com.liferay.portal.kernel.dao.orm.QueryPos;
29  import com.liferay.portal.kernel.dao.orm.QueryUtil;
30  import com.liferay.portal.kernel.dao.orm.SQLQuery;
31  import com.liferay.portal.kernel.dao.orm.Session;
32  import com.liferay.portal.kernel.dao.orm.Type;
33  import com.liferay.portal.kernel.util.GetterUtil;
34  import com.liferay.portal.kernel.util.OrderByComparator;
35  import com.liferay.portal.kernel.util.StringPool;
36  import com.liferay.portal.kernel.util.StringUtil;
37  import com.liferay.portal.kernel.util.Validator;
38  import com.liferay.portal.model.Group;
39  import com.liferay.portal.model.impl.GroupImpl;
40  import com.liferay.portal.model.impl.GroupModelImpl;
41  import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;
42  import com.liferay.util.dao.orm.CustomSQLUtil;
43  
44  import java.util.ArrayList;
45  import java.util.Iterator;
46  import java.util.LinkedHashMap;
47  import java.util.List;
48  import java.util.Map;
49  
50  /**
51   * <a href="GroupFinderImpl.java.html"><b><i>View Source</i></b></a>
52   *
53   * @author Brian Wing Shun Chan
54   *
55   */
56  public class GroupFinderImpl
57      extends BasePersistenceImpl implements GroupFinder {
58  
59      public static String COUNT_BY_GROUP_ID =
60          GroupFinder.class.getName() + ".countByGroupId";
61  
62      public static String COUNT_BY_C_N_D =
63          GroupFinder.class.getName() + ".countByC_N_D";
64  
65      public static String FIND_BY_NULL_FRIENDLY_URL =
66          GroupFinder.class.getName() + ".findByNullFriendlyURL";
67  
68      public static String FIND_BY_C_N =
69          GroupFinder.class.getName() + ".findByC_N";
70  
71      public static String FIND_BY_C_N_D =
72          GroupFinder.class.getName() + ".findByC_N_D";
73  
74      public static String JOIN_BY_ACTIVE =
75          GroupFinder.class.getName() + ".joinByActive";
76  
77      public static String JOIN_BY_CREATOR_USER_ID =
78          GroupFinder.class.getName() + ".joinByCreatorUserId";
79  
80      public static String JOIN_BY_GROUPS_ORGS =
81          GroupFinder.class.getName() + ".joinByGroupsOrgs";
82  
83      public static String JOIN_BY_GROUPS_ROLES =
84          GroupFinder.class.getName() + ".joinByGroupsRoles";
85  
86      public static String JOIN_BY_GROUPS_USER_GROUPS =
87          GroupFinder.class.getName() + ".joinByGroupsUserGroups";
88  
89      public static String JOIN_BY_LAYOUT_SET =
90          GroupFinder.class.getName() + ".joinByLayoutSet";
91  
92      public static String JOIN_BY_PAGE_COUNT =
93          GroupFinder.class.getName() + ".joinByPageCount";
94  
95      public static String JOIN_BY_ROLE_PERMISSIONS =
96          GroupFinder.class.getName() + ".joinByRolePermissions";
97  
98      public static String JOIN_BY_TYPE =
99          GroupFinder.class.getName() + ".joinByType";
100 
101     public static String JOIN_BY_USER_GROUP_ROLE =
102         GroupFinder.class.getName() + ".joinByUserGroupRole";
103 
104     public static String JOIN_BY_USERS_GROUPS =
105         GroupFinder.class.getName() + ".joinByUsersGroups";
106 
107     public int countByG_U(long groupId, long userId) throws SystemException {
108         LinkedHashMap<String, Object> params1 =
109             new LinkedHashMap<String, Object>();
110 
111         params1.put("usersGroups", userId);
112 
113         LinkedHashMap<String, Object> params2 =
114             new LinkedHashMap<String, Object>();
115 
116         params2.put("groupsOrgs", userId);
117 
118         LinkedHashMap<String, Object> params3 =
119             new LinkedHashMap<String, Object>();
120 
121         params3.put("groupsUserGroups", userId);
122 
123         Session session = null;
124 
125         try {
126             session = openSession();
127 
128             int count = countByGroupId(session, groupId, params1);
129             count += countByGroupId(session, groupId, params2);
130             count += countByGroupId(session, groupId, params3);
131 
132             return count;
133         }
134         catch (Exception e) {
135             throw new SystemException(e);
136         }
137         finally {
138             closeSession(session);
139         }
140     }
141 
142     public int countByC_N_D(
143             long companyId, String name, String description,
144             LinkedHashMap<String, Object> params)
145         throws SystemException {
146 
147         name = StringUtil.lowerCase(name);
148         description = StringUtil.lowerCase(description);
149 
150         if (params == null) {
151             params = new LinkedHashMap<String, Object>();
152         }
153 
154         Long userId = (Long)params.get("usersGroups");
155 
156         LinkedHashMap<String, Object> params1 = params;
157 
158         LinkedHashMap<String, Object> params2 =
159             new LinkedHashMap<String, Object>();
160 
161         params2.putAll(params1);
162 
163         if (userId != null) {
164             params2.remove("usersGroups");
165             params2.put("groupsOrgs", userId);
166         }
167 
168         LinkedHashMap<String, Object> params3 =
169             new LinkedHashMap<String, Object>();
170 
171         params3.putAll(params1);
172 
173         if (userId != null) {
174             params3.remove("usersGroups");
175             params3.put("groupsUserGroups", userId);
176         }
177 
178         Session session = null;
179 
180         try {
181             session = openSession();
182 
183             int count = countByC_N_D(
184                 session, companyId, name, description, params1);
185 
186             if (Validator.isNotNull(userId)) {
187                 count += countByC_N_D(
188                     session, companyId, name, description, params2);
189 
190                 count += countByC_N_D(
191                     session, companyId, name, description, params3);
192             }
193 
194             return count;
195         }
196         catch (Exception e) {
197             throw new SystemException(e);
198         }
199         finally {
200             closeSession(session);
201         }
202     }
203 
204     public List<Group> findByNullFriendlyURL() throws SystemException {
205         Session session = null;
206 
207         try {
208             session = openSession();
209 
210             String sql = CustomSQLUtil.get(FIND_BY_NULL_FRIENDLY_URL);
211 
212             SQLQuery q = session.createSQLQuery(sql);
213 
214             q.addEntity("Group_", GroupImpl.class);
215 
216             return q.list();
217         }
218         catch (Exception e) {
219             throw new SystemException(e);
220         }
221         finally {
222             closeSession(session);
223         }
224     }
225 
226     public Group findByC_N(long companyId, String name)
227         throws NoSuchGroupException, SystemException {
228 
229         name = StringUtil.lowerCase(name);
230 
231         boolean finderClassNameCacheEnabled = GroupModelImpl.CACHE_ENABLED;
232         String finderClassName = Group.class.getName();
233         String finderMethodName = "customFindByC_N";
234         String finderParams[] = new String[] {
235             Long.class.getName(), String.class.getName()
236         };
237         Object finderArgs[] = new Object[] {companyId, name};
238 
239         Object result = FinderCacheUtil.getResult(
240             finderClassName, finderMethodName, finderParams, finderArgs, this);
241 
242         if (result == null) {
243             Session session = null;
244 
245             try {
246                 session = openSession();
247 
248                 String sql = CustomSQLUtil.get(FIND_BY_C_N);
249 
250                 SQLQuery q = session.createSQLQuery(sql);
251 
252                 q.addEntity("Group_", GroupImpl.class);
253 
254                 QueryPos qPos = QueryPos.getInstance(q);
255 
256                 qPos.add(companyId);
257                 qPos.add(name);
258 
259                 Iterator<Group> itr = q.list().iterator();
260 
261                 if (itr.hasNext()) {
262                     Group group = itr.next();
263 
264                     FinderCacheUtil.putResult(
265                         finderClassNameCacheEnabled, finderClassName,
266                         finderMethodName, finderParams, finderArgs, group);
267 
268                     return group;
269                 }
270             }
271             catch (Exception e) {
272                 throw new SystemException(e);
273             }
274             finally {
275                 closeSession(session);
276             }
277 
278             StringBuilder sb = new StringBuilder();
279 
280             sb.append("No Group exists with the key {companyId=");
281             sb.append(companyId);
282             sb.append(", name=");
283             sb.append(name);
284             sb.append("}");
285 
286             throw new NoSuchGroupException(sb.toString());
287         }
288         else {
289             return (Group)result;
290         }
291     }
292 
293     public List<Group> findByC_N_D(
294             long companyId, String name, String description,
295             LinkedHashMap<String, Object> params, int start, int end,
296             OrderByComparator obc)
297         throws SystemException {
298 
299         name = StringUtil.lowerCase(name);
300         description = StringUtil.lowerCase(description);
301 
302         if (params == null) {
303             params = new LinkedHashMap<String, Object>();
304         }
305 
306         Long userId = (Long)params.get("usersGroups");
307 
308         LinkedHashMap<String, Object> params1 = params;
309 
310         LinkedHashMap<String, Object> params2 =
311             new LinkedHashMap<String, Object>();
312 
313         params2.putAll(params1);
314 
315         if (userId != null) {
316             params2.remove("usersGroups");
317             params2.put("groupsOrgs", userId);
318         }
319 
320         LinkedHashMap<String, Object> params3 =
321             new LinkedHashMap<String, Object>();
322 
323         params3.putAll(params1);
324 
325         if (userId != null) {
326             params3.remove("usersGroups");
327             params3.put("groupsUserGroups", userId);
328         }
329 
330         StringBuilder sb = new StringBuilder();
331 
332         sb.append("(");
333 
334         sb.append(CustomSQLUtil.get(FIND_BY_C_N_D));
335 
336         String sql = sb.toString();
337 
338         sql = StringUtil.replace(sql, "[$JOIN$]", getJoin(params1));
339         sql = StringUtil.replace(sql, "[$WHERE$]", getWhere(params1));
340 
341         sb = new StringBuilder();
342 
343         sb.append(sql);
344 
345         sb.append(")");
346 
347         if (Validator.isNotNull(userId)) {
348             sb.append(" UNION (");
349 
350             sb.append(CustomSQLUtil.get(FIND_BY_C_N_D));
351 
352             sql = sb.toString();
353 
354             sql = StringUtil.replace(sql, "[$JOIN$]", getJoin(params2));
355             sql = StringUtil.replace(sql, "[$WHERE$]", getWhere(params2));
356 
357             sb = new StringBuilder();
358 
359             sb.append(sql);
360 
361             sb.append(") UNION (");
362 
363             sb.append(CustomSQLUtil.get(FIND_BY_C_N_D));
364 
365             sql = sb.toString();
366 
367             sql = StringUtil.replace(sql, "[$JOIN$]", getJoin(params3));
368             sql = StringUtil.replace(sql, "[$WHERE$]", getWhere(params3));
369 
370             sb = new StringBuilder();
371 
372             sb.append(sql);
373 
374             sb.append(")");
375         }
376 
377         sql = sb.toString();
378         sql = CustomSQLUtil.replaceOrderBy(sql, obc);
379 
380         Session session = null;
381 
382         try {
383             session = openSession();
384 
385             SQLQuery q = session.createSQLQuery(sql);
386 
387             q.addScalar("groupId", Type.STRING);
388 
389             QueryPos qPos = QueryPos.getInstance(q);
390 
391             setJoin(qPos, params1);
392             qPos.add(companyId);
393             qPos.add(name);
394             qPos.add(name);
395             qPos.add(description);
396             qPos.add(description);
397 
398             if (Validator.isNotNull(userId)) {
399                 setJoin(qPos, params2);
400                 qPos.add(companyId);
401                 qPos.add(name);
402                 qPos.add(name);
403                 qPos.add(description);
404                 qPos.add(description);
405 
406                 setJoin(qPos, params3);
407                 qPos.add(companyId);
408                 qPos.add(name);
409                 qPos.add(name);
410                 qPos.add(description);
411                 qPos.add(description);
412             }
413 
414             List<Group> groups = new ArrayList<Group>();
415 
416             Iterator<String> itr = (Iterator<String>)QueryUtil.iterate(
417                 q, getDialect(), start, end);
418 
419             while (itr.hasNext()) {
420                 long groupId = GetterUtil.getLong(itr.next());
421 
422                 Group group = GroupUtil.findByPrimaryKey(groupId);
423 
424                 groups.add(group);
425             }
426 
427             return groups;
428         }
429         catch (Exception e) {
430             throw new SystemException(e);
431         }
432         finally {
433             closeSession(session);
434         }
435     }
436 
437     protected int countByGroupId(
438         Session session, long groupId, LinkedHashMap<String, Object> params) {
439 
440         String sql = CustomSQLUtil.get(COUNT_BY_GROUP_ID);
441 
442         sql = StringUtil.replace(sql, "[$JOIN$]", getJoin(params));
443         sql = StringUtil.replace(sql, "[$WHERE$]", getWhere(params));
444 
445         SQLQuery q = session.createSQLQuery(sql);
446 
447         q.addScalar(COUNT_COLUMN_NAME, Type.LONG);
448 
449         QueryPos qPos = QueryPos.getInstance(q);
450 
451         setJoin(qPos, params);
452         qPos.add(groupId);
453 
454         Iterator<Long> itr = q.list().iterator();
455 
456         if (itr.hasNext()) {
457             Long count = itr.next();
458 
459             if (count != null) {
460                 return count.intValue();
461             }
462         }
463 
464         return 0;
465     }
466 
467     protected int countByC_N_D(
468         Session session, long companyId, String name, String description,
469         LinkedHashMap<String, Object> params) {
470 
471         String sql = CustomSQLUtil.get(COUNT_BY_C_N_D);
472 
473         sql = StringUtil.replace(sql, "[$JOIN$]", getJoin(params));
474         sql = StringUtil.replace(sql, "[$WHERE$]", getWhere(params));
475 
476         SQLQuery q = session.createSQLQuery(sql);
477 
478         q.addScalar(COUNT_COLUMN_NAME, Type.LONG);
479 
480         QueryPos qPos = QueryPos.getInstance(q);
481 
482         setJoin(qPos, params);
483         qPos.add(companyId);
484         qPos.add(name);
485         qPos.add(name);
486         qPos.add(description);
487         qPos.add(description);
488 
489         Iterator<Long> itr = q.list().iterator();
490 
491         if (itr.hasNext()) {
492             Long count = itr.next();
493 
494             if (count != null) {
495                 return count.intValue();
496             }
497         }
498 
499         return 0;
500     }
501 
502     protected String getJoin(LinkedHashMap<String, Object> params) {
503         if (params == null) {
504             return StringPool.BLANK;
505         }
506 
507         StringBuilder sb = new StringBuilder();
508 
509         Iterator<Map.Entry<String, Object>> itr = params.entrySet().iterator();
510 
511         while (itr.hasNext()) {
512             Map.Entry<String, Object> entry = itr.next();
513 
514             String key = entry.getKey();
515             Object value = entry.getValue();
516 
517             if (Validator.isNotNull(value)) {
518                 sb.append(getJoin(key));
519             }
520         }
521 
522         return sb.toString();
523     }
524 
525     protected String getJoin(String key) {
526         String join = StringPool.BLANK;
527 
528         if (key.equals("groupsOrgs")) {
529             join = CustomSQLUtil.get(JOIN_BY_GROUPS_ORGS);
530         }
531         else if (key.equals("groupsRoles")) {
532             join = CustomSQLUtil.get(JOIN_BY_GROUPS_ROLES);
533         }
534         else if (key.equals("groupsUserGroups")) {
535             join = CustomSQLUtil.get(JOIN_BY_GROUPS_USER_GROUPS);
536         }
537         else if (key.equals("layoutSet")) {
538             join = CustomSQLUtil.get(JOIN_BY_LAYOUT_SET);
539         }
540         else if (key.equals("pageCount")) {
541             join = CustomSQLUtil.get(JOIN_BY_PAGE_COUNT);
542         }
543         else if (key.equals("rolePermissions")) {
544             join = CustomSQLUtil.get(JOIN_BY_ROLE_PERMISSIONS);
545         }
546         else if (key.equals("userGroupRole")) {
547             join = CustomSQLUtil.get(JOIN_BY_USER_GROUP_ROLE);
548         }
549         else if (key.equals("usersGroups")) {
550             join = CustomSQLUtil.get(JOIN_BY_USERS_GROUPS);
551         }
552 
553         if (Validator.isNotNull(join)) {
554             int pos = join.indexOf("WHERE");
555 
556             if (pos != -1) {
557                 join = join.substring(0, pos);
558             }
559         }
560 
561         return join;
562     }
563 
564     protected String getWhere(LinkedHashMap<String, Object> params) {
565         if (params == null) {
566             return StringPool.BLANK;
567         }
568 
569         StringBuilder sb = new StringBuilder();
570 
571         Iterator<Map.Entry<String, Object>> itr = params.entrySet().iterator();
572 
573         while (itr.hasNext()) {
574             Map.Entry<String, Object> entry = itr.next();
575 
576             String key = entry.getKey();
577             Object value = entry.getValue();
578 
579             if (Validator.isNotNull(value)) {
580                 sb.append(getWhere(key, value));
581             }
582         }
583 
584         return sb.toString();
585     }
586 
587     protected String getWhere(String key, Object value) {
588         String join = StringPool.BLANK;
589 
590         if (key.equals("active")) {
591             join = CustomSQLUtil.get(JOIN_BY_ACTIVE);
592         }
593         else if (key.equals("creatorUserId")) {
594             join = CustomSQLUtil.get(JOIN_BY_CREATOR_USER_ID);
595         }
596         else if (key.equals("groupsOrgs")) {
597             join = CustomSQLUtil.get(JOIN_BY_GROUPS_ORGS);
598         }
599         else if (key.equals("groupsRoles")) {
600             join = CustomSQLUtil.get(JOIN_BY_GROUPS_ROLES);
601         }
602         else if (key.equals("groupsUserGroups")) {
603             join = CustomSQLUtil.get(JOIN_BY_GROUPS_USER_GROUPS);
604         }
605         else if (key.equals("layoutSet")) {
606             join = CustomSQLUtil.get(JOIN_BY_LAYOUT_SET);
607         }
608         else if (key.equals("pageCount")) {
609             join = CustomSQLUtil.get(JOIN_BY_PAGE_COUNT);
610         }
611         else if (key.equals("rolePermissions")) {
612             join = CustomSQLUtil.get(JOIN_BY_ROLE_PERMISSIONS);
613         }
614         else if (key.equals("type")) {
615             join = CustomSQLUtil.get(JOIN_BY_TYPE);
616         }
617         else if (key.equals("types")) {
618             List<Integer> types = (List<Integer>)value;
619 
620             StringBuilder sb = new StringBuilder();
621 
622             sb.append("WHERE (");
623 
624             for (int i = 0; i < types.size(); i++) {
625                 sb.append("(Group_.type_ = ?) ");
626 
627                 if ((i + 1) < types.size()) {
628                     sb.append("OR ");
629                 }
630             }
631 
632             sb.append(")");
633 
634             join = sb.toString();
635         }
636         else if (key.equals("userGroupRole")) {
637             join = CustomSQLUtil.get(JOIN_BY_USER_GROUP_ROLE);
638         }
639         else if (key.equals("usersGroups")) {
640             join = CustomSQLUtil.get(JOIN_BY_USERS_GROUPS);
641         }
642 
643         if (Validator.isNotNull(join)) {
644             int pos = join.indexOf("WHERE");
645 
646             if (pos != -1) {
647                 StringBuilder sb = new StringBuilder();
648 
649                 sb.append(join.substring(pos + 5, join.length()));
650                 sb.append(" AND ");
651 
652                 join = sb.toString();
653             }
654             else {
655                 join = StringPool.BLANK;
656             }
657         }
658 
659         return join;
660     }
661 
662     protected void setJoin(
663         QueryPos qPos, LinkedHashMap<String, Object> params) {
664 
665         if (params != null) {
666             Iterator<Map.Entry<String, Object>> itr =
667                 params.entrySet().iterator();
668 
669             while (itr.hasNext()) {
670                 Map.Entry<String, Object> entry = itr.next();
671 
672                 String key = entry.getKey();
673 
674                 if (key.equals("active") || key.equals("layoutSet")) {
675                     Boolean value = (Boolean)entry.getValue();
676 
677                     qPos.add(value);
678                 }
679                 else if (key.equals("pageCount")) {
680                 }
681                 else if (key.equals("rolePermissions")) {
682                     List<Object> values = (List<Object>)entry.getValue();
683 
684                     for (int i = 0; i < values.size(); i++) {
685                         Object value = values.get(i);
686 
687                         if (value instanceof Integer) {
688                             Integer valueInteger = (Integer)value;
689 
690                             qPos.add(valueInteger);
691                         }
692                         else if (value instanceof Long) {
693                             Long valueLong = (Long)value;
694 
695                             qPos.add(valueLong);
696                         }
697                         else if (value instanceof String) {
698                             String valueString = (String)value;
699 
700                             qPos.add(valueString);
701                         }
702                     }
703                 }
704                 else if (key.equals("types")) {
705                     List<Integer> values = (List<Integer>)entry.getValue();
706 
707                     for (int i = 0; i < values.size(); i++) {
708                         Integer value = values.get(i);
709 
710                         qPos.add(value);
711                     }
712                 }
713                 else if (key.equals("userGroupRole")) {
714                     List<Long> values = (List<Long>)entry.getValue();
715 
716                     Long userId = values.get(0);
717                     Long roleId = values.get(1);
718 
719                     qPos.add(userId);
720                     qPos.add(roleId);
721                 }
722                 else {
723                     Object value = entry.getValue();
724 
725                     if (value instanceof Long) {
726                         Long valueLong = (Long)value;
727 
728                         if (Validator.isNotNull(valueLong)) {
729                             qPos.add(valueLong);
730                         }
731                     }
732                     else if (value instanceof String) {
733                         String valueString = (String)value;
734 
735                         if (Validator.isNotNull(valueString)) {
736                             qPos.add(valueString);
737                         }
738                     }
739                 }
740             }
741         }
742     }
743 
744 }