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