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