1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.portal.service.persistence;
16  
17  import com.liferay.portal.NoSuchRoleException;
18  import com.liferay.portal.kernel.dao.orm.QueryPos;
19  import com.liferay.portal.kernel.dao.orm.QueryUtil;
20  import com.liferay.portal.kernel.dao.orm.SQLQuery;
21  import com.liferay.portal.kernel.dao.orm.Session;
22  import com.liferay.portal.kernel.dao.orm.Type;
23  import com.liferay.portal.kernel.exception.SystemException;
24  import com.liferay.portal.kernel.util.OrderByComparator;
25  import com.liferay.portal.kernel.util.StringBundler;
26  import com.liferay.portal.kernel.util.StringPool;
27  import com.liferay.portal.kernel.util.StringUtil;
28  import com.liferay.portal.kernel.util.Validator;
29  import com.liferay.portal.model.Group;
30  import com.liferay.portal.model.Role;
31  import com.liferay.portal.model.impl.RoleImpl;
32  import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;
33  import com.liferay.util.dao.orm.CustomSQLUtil;
34  
35  import java.util.ArrayList;
36  import java.util.HashMap;
37  import java.util.Iterator;
38  import java.util.LinkedHashMap;
39  import java.util.List;
40  import java.util.Map;
41  
42  /**
43   * <a href="RoleFinderImpl.java.html"><b><i>View Source</i></b></a>
44   *
45   * @author Brian Wing Shun Chan
46   */
47  public class RoleFinderImpl
48      extends BasePersistenceImpl<Role> implements RoleFinder {
49  
50      public static String COUNT_BY_COMMUNITY =
51          RoleFinder.class.getName() + ".countByCommunity";
52  
53      public static String COUNT_BY_ORGANIZATION =
54          RoleFinder.class.getName() + ".countByOrganization";
55  
56      public static String COUNT_BY_ORGANIZATION_COMMUNITY =
57          RoleFinder.class.getName() + ".countByOrganizationCommunity";
58  
59      public static String COUNT_BY_USER =
60          RoleFinder.class.getName() + ".countByUser";
61  
62      public static String COUNT_BY_USER_GROUP =
63          RoleFinder.class.getName() + ".countByUserGroup";
64  
65      public static String COUNT_BY_USER_GROUP_COMMUNITY =
66          RoleFinder.class.getName() + ".countByUserGroupCommunity";
67  
68      public static String COUNT_BY_U_G_R =
69          RoleFinder.class.getName() + ".countByU_G_R";
70  
71      public static String COUNT_BY_C_N_D_T =
72          RoleFinder.class.getName() + ".countByC_N_D_T";
73  
74      public static String FIND_BY_SYSTEM =
75          RoleFinder.class.getName() + ".findBySystem";
76  
77      public static String FIND_BY_USER_GROUP_GROUP_ROLE =
78          RoleFinder.class.getName() + ".findByUserGroupGroupRole";
79  
80      public static String FIND_BY_USER_GROUP_ROLE =
81          RoleFinder.class.getName() + ".findByUserGroupRole";
82  
83      public static String FIND_BY_C_N =
84          RoleFinder.class.getName() + ".findByC_N";
85  
86      public static String FIND_BY_U_G =
87          RoleFinder.class.getName() + ".findByU_G";
88  
89      public static String FIND_BY_C_N_D_T =
90          RoleFinder.class.getName() + ".findByC_N_D_T";
91  
92      public static String FIND_BY_C_N_S_P =
93          RoleFinder.class.getName() + ".findByC_N_S_P";
94  
95      public static String JOIN_BY_ROLES_PERMISSIONS =
96          RoleFinder.class.getName() + ".joinByRolesPermissions";
97  
98      public static String JOIN_BY_USERS_ROLES =
99          RoleFinder.class.getName() + ".joinByUsersRoles";
100 
101     public int countByR_U(long roleId, long userId) throws SystemException {
102         Session session = null;
103 
104         try {
105             session = openSession();
106 
107             StringBundler sb = new StringBundler(13);
108 
109             sb.append("(");
110             sb.append(CustomSQLUtil.get(COUNT_BY_COMMUNITY));
111             sb.append(") UNION (");
112             sb.append(CustomSQLUtil.get(COUNT_BY_ORGANIZATION));
113             sb.append(") UNION (");
114             sb.append(CustomSQLUtil.get(COUNT_BY_ORGANIZATION_COMMUNITY));
115             sb.append(") UNION (");
116             sb.append(CustomSQLUtil.get(COUNT_BY_USER));
117             sb.append(") UNION (");
118             sb.append(CustomSQLUtil.get(COUNT_BY_USER_GROUP));
119             sb.append(") UNION (");
120             sb.append(CustomSQLUtil.get(COUNT_BY_USER_GROUP_COMMUNITY));
121             sb.append(")");
122 
123             SQLQuery q = session.createSQLQuery(sb.toString());
124 
125             q.addScalar(COUNT_COLUMN_NAME, Type.LONG);
126 
127             QueryPos qPos = QueryPos.getInstance(q);
128 
129             for (int i = 0; i < 6; i++) {
130                 qPos.add(roleId);
131                 qPos.add(userId);
132             }
133 
134             int count = 0;
135 
136             Iterator<Long> itr = q.list().iterator();
137 
138             while (itr.hasNext()) {
139                 Long l = itr.next();
140 
141                 if (l != null) {
142                     count += l.intValue();
143                 }
144             }
145 
146             return count;
147         }
148         catch (Exception e) {
149             throw new SystemException(e);
150         }
151         finally {
152             closeSession(session);
153         }
154     }
155 
156     public int countByU_G_R(long userId, long groupId, long roleId)
157         throws SystemException {
158 
159         Session session = null;
160 
161         try {
162             session = openSession();
163 
164             String sql = CustomSQLUtil.get(COUNT_BY_U_G_R);
165 
166             SQLQuery q = session.createSQLQuery(sql);
167 
168             q.addScalar(COUNT_COLUMN_NAME, Type.LONG);
169 
170             QueryPos qPos = QueryPos.getInstance(q);
171 
172             qPos.add(roleId);
173             qPos.add(groupId);
174             qPos.add(userId);
175 
176             Iterator<Long> itr = q.list().iterator();
177 
178             if (itr.hasNext()) {
179                 Long count = itr.next();
180 
181                 if (count != null) {
182                     return count.intValue();
183                 }
184             }
185 
186             return 0;
187         }
188         catch (Exception e) {
189             throw new SystemException(e);
190         }
191         finally {
192             closeSession(session);
193         }
194     }
195 
196     public int countByC_N_D_T(
197             long companyId, String name, String description, Integer type,
198             LinkedHashMap<String, Object> params)
199         throws SystemException {
200 
201         name = StringUtil.lowerCase(name);
202         description = StringUtil.lowerCase(description);
203 
204         Session session = null;
205 
206         try {
207             session = openSession();
208 
209             String sql = CustomSQLUtil.get(COUNT_BY_C_N_D_T);
210 
211             if (type == null) {
212                 sql = StringUtil.replace(sql, "AND (Role_.type_ = ?)", "");
213             }
214 
215             sql = StringUtil.replace(sql, "[$JOIN$]", getJoin(params));
216             sql = StringUtil.replace(sql, "[$WHERE$]", getWhere(params));
217 
218             SQLQuery q = session.createSQLQuery(sql);
219 
220             q.addScalar(COUNT_COLUMN_NAME, Type.LONG);
221 
222             QueryPos qPos = QueryPos.getInstance(q);
223 
224             setJoin(qPos, params);
225             qPos.add(companyId);
226             qPos.add(name);
227             qPos.add(name);
228             qPos.add(description);
229             qPos.add(description);
230 
231             if (type != null) {
232                 qPos.add(type);
233             }
234 
235             Iterator<Long> itr = q.list().iterator();
236 
237             if (itr.hasNext()) {
238                 Long count = itr.next();
239 
240                 if (count != null) {
241                     return count.intValue();
242                 }
243             }
244 
245             return 0;
246         }
247         catch (Exception e) {
248             throw new SystemException(e);
249         }
250         finally {
251             closeSession(session);
252         }
253     }
254 
255     public List<Role> findBySystem(long companyId) throws SystemException {
256         Session session = null;
257 
258         try {
259             session = openSession();
260 
261             String sql = CustomSQLUtil.get(FIND_BY_SYSTEM);
262 
263             SQLQuery q = session.createSQLQuery(sql);
264 
265             q.addEntity("Role_", RoleImpl.class);
266 
267             QueryPos qPos = QueryPos.getInstance(q);
268 
269             qPos.add(companyId);
270 
271             return q.list();
272         }
273         catch (Exception e) {
274             throw new SystemException(e);
275         }
276         finally {
277             closeSession(session);
278         }
279     }
280 
281     public List<Role> findByUserGroupGroupRole(long userId, long groupId)
282         throws SystemException {
283 
284         Session session = null;
285 
286         try {
287             session = openSession();
288 
289             String sql = CustomSQLUtil.get(FIND_BY_USER_GROUP_GROUP_ROLE);
290 
291             SQLQuery q = session.createSQLQuery(sql);
292 
293             q.addEntity("Role_", RoleImpl.class);
294 
295             QueryPos qPos = QueryPos.getInstance(q);
296 
297             qPos.add(userId);
298             qPos.add(groupId);
299 
300             return q.list();
301         }
302         catch (Exception e) {
303             throw new SystemException(e);
304         }
305         finally {
306             closeSession(session);
307         }
308     }
309 
310     public List<Role> findByUserGroupRole(long userId, long groupId)
311         throws SystemException {
312 
313         Session session = null;
314 
315         try {
316             session = openSession();
317 
318             String sql = CustomSQLUtil.get(FIND_BY_USER_GROUP_ROLE);
319 
320             SQLQuery q = session.createSQLQuery(sql);
321 
322             q.addEntity("Role_", RoleImpl.class);
323 
324             QueryPos qPos = QueryPos.getInstance(q);
325 
326             qPos.add(userId);
327             qPos.add(groupId);
328 
329             return q.list();
330         }
331         catch (Exception e) {
332             throw new SystemException(e);
333         }
334         finally {
335             closeSession(session);
336         }
337     }
338 
339     public Role findByC_N(long companyId, String name)
340         throws NoSuchRoleException, SystemException {
341 
342         name = StringUtil.lowerCase(name);
343 
344         Session session = null;
345 
346         try {
347             session = openSession();
348 
349             String sql = CustomSQLUtil.get(FIND_BY_C_N);
350 
351             SQLQuery q = session.createSQLQuery(sql);
352 
353             q.addEntity("Role_", RoleImpl.class);
354 
355             QueryPos qPos = QueryPos.getInstance(q);
356 
357             qPos.add(companyId);
358             qPos.add(name);
359 
360             List<Role> list = q.list();
361 
362             if (!list.isEmpty()) {
363                 return list.get(0);
364             }
365         }
366         catch (Exception e) {
367             throw new SystemException(e);
368         }
369         finally {
370             closeSession(session);
371         }
372 
373         StringBundler sb = new StringBundler(5);
374 
375         sb.append("No Role exists with the key {companyId=");
376         sb.append(companyId);
377         sb.append(", name=");
378         sb.append(name);
379         sb.append("}");
380 
381         throw new NoSuchRoleException(sb.toString());
382     }
383 
384     public List<Role> findByU_G(long userId, long groupId)
385         throws SystemException {
386 
387         return findByU_G(userId, new long[] {groupId});
388     }
389 
390     public List<Role> findByU_G(long userId, long[] groupIds)
391         throws SystemException {
392 
393         Session session = null;
394 
395         try {
396             session = openSession();
397 
398             String sql = CustomSQLUtil.get(FIND_BY_U_G);
399 
400             sql = StringUtil.replace(
401                 sql, "[$GROUP_IDS$]", getGroupIds(groupIds, "Groups_Roles"));
402 
403             SQLQuery q = session.createSQLQuery(sql);
404 
405             q.addEntity("Role_", RoleImpl.class);
406 
407             QueryPos qPos = QueryPos.getInstance(q);
408 
409             qPos.add(userId);
410             setGroupIds(qPos, groupIds);
411 
412             return q.list();
413         }
414         catch (Exception e) {
415             throw new SystemException(e);
416         }
417         finally {
418             closeSession(session);
419         }
420     }
421 
422     public List<Role> findByU_G(long userId, List<Group> groups)
423         throws SystemException {
424 
425         long[] groupIds = new long[groups.size()];
426 
427         for (int i = 0; i < groups.size(); i++) {
428             Group group = groups.get(i);
429 
430             groupIds[i] = group.getGroupId();
431         }
432 
433         return findByU_G(userId, groupIds);
434     }
435 
436     public List<Role> findByC_N_D_T(
437             long companyId, String name, String description, Integer type,
438             LinkedHashMap<String, Object> params, int start, int end,
439             OrderByComparator obc)
440         throws SystemException {
441 
442         name = StringUtil.lowerCase(name);
443         description = StringUtil.lowerCase(description);
444 
445         Session session = null;
446 
447         try {
448             session = openSession();
449 
450             String sql = CustomSQLUtil.get(FIND_BY_C_N_D_T);
451 
452             if (type == null) {
453                 sql = StringUtil.replace(sql, "AND (Role_.type_ = ?)", "");
454             }
455 
456             sql = StringUtil.replace(sql, "[$JOIN$]", getJoin(params));
457             sql = StringUtil.replace(sql, "[$WHERE$]", getWhere(params));
458             sql = CustomSQLUtil.replaceOrderBy(sql, obc);
459 
460             SQLQuery q = session.createSQLQuery(sql);
461 
462             q.addEntity("Role_", RoleImpl.class);
463 
464             QueryPos qPos = QueryPos.getInstance(q);
465 
466             setJoin(qPos, params);
467             qPos.add(companyId);
468             qPos.add(name);
469             qPos.add(name);
470             qPos.add(description);
471             qPos.add(description);
472 
473             if (type != null) {
474                 qPos.add(type);
475             }
476 
477             return (List<Role>)QueryUtil.list(q, getDialect(), start, end);
478         }
479         catch (Exception e) {
480             throw new SystemException(e);
481         }
482         finally {
483             closeSession(session);
484         }
485     }
486 
487     public Map<String, List<String>> findByC_N_S_P(
488             long companyId, String name, int scope, String primKey)
489         throws SystemException {
490 
491         Session session = null;
492 
493         try {
494             session = openSession();
495 
496             String sql = CustomSQLUtil.get(FIND_BY_C_N_S_P);
497 
498             SQLQuery q = session.createSQLQuery(sql);
499 
500             q.addScalar("roleName", Type.STRING);
501             q.addScalar("actionId", Type.STRING);
502 
503             QueryPos qPos = QueryPos.getInstance(q);
504 
505             qPos.add(companyId);
506             qPos.add(name);
507             qPos.add(scope);
508             qPos.add(primKey);
509 
510             Map<String, List<String>> roleMap =
511                 new HashMap<String, List<String>>();
512 
513             Iterator<Object[]> itr = q.list().iterator();
514 
515             while (itr.hasNext()) {
516                 Object[] array = itr.next();
517 
518                 String roleName = (String)array[0];
519                 String actionId = (String)array[1];
520 
521                 List<String> roleList = roleMap.get(roleName);
522 
523                 if (roleList == null) {
524                     roleList = new ArrayList<String>();
525                 }
526 
527                 roleList.add(actionId);
528 
529                 roleMap.put(roleName, roleList);
530             }
531 
532             return roleMap;
533         }
534         catch (Exception e) {
535             throw new SystemException(e);
536         }
537         finally {
538             closeSession(session);
539         }
540     }
541 
542     protected String getGroupIds(long[] groupIds, String table) {
543         if (groupIds.length == 0) {
544             return StringPool.BLANK;
545         }
546 
547         StringBundler sb = new StringBundler(groupIds.length * 3 - 1);
548 
549         for (int i = 0; i < groupIds.length; i++) {
550             sb.append(table);
551             sb.append(".groupId = ?");
552 
553             if ((i + 1) < groupIds.length) {
554                 sb.append(" OR ");
555             }
556         }
557 
558         return sb.toString();
559     }
560 
561     protected void setGroupIds(QueryPos qPos, long[] groupIds) {
562         for (int i = 0; i < groupIds.length; i++) {
563             qPos.add(groupIds[i]);
564         }
565     }
566 
567     protected String getJoin(LinkedHashMap<String, Object> params) {
568         if ((params == null) || params.isEmpty()) {
569             return StringPool.BLANK;
570         }
571 
572         StringBundler sb = new StringBundler(params.size());
573 
574         Iterator<Map.Entry<String, Object>> itr = params.entrySet().iterator();
575 
576         while (itr.hasNext()) {
577             Map.Entry<String, Object> entry = itr.next();
578 
579             String key = entry.getKey();
580             Object value = entry.getValue();
581 
582             if (Validator.isNotNull(value)) {
583                 sb.append(getJoin(key));
584             }
585         }
586 
587         return sb.toString();
588     }
589 
590     protected String getJoin(String key) {
591         String join = StringPool.BLANK;
592 
593         if (key.equals("permissionsResourceId")) {
594             join = CustomSQLUtil.get(JOIN_BY_ROLES_PERMISSIONS);
595         }
596         else if (key.equals("usersRoles")) {
597             join = CustomSQLUtil.get(JOIN_BY_USERS_ROLES);
598         }
599 
600         if (Validator.isNotNull(join)) {
601             int pos = join.indexOf("WHERE");
602 
603             if (pos != -1) {
604                 join = join.substring(0, pos);
605             }
606         }
607 
608         return join;
609     }
610 
611     protected String getWhere(LinkedHashMap<String, Object> params) {
612         if ((params == null) || params.isEmpty()) {
613             return StringPool.BLANK;
614         }
615 
616         StringBundler sb = new StringBundler(params.size());
617 
618         Iterator<Map.Entry<String, Object>> itr = params.entrySet().iterator();
619 
620         while (itr.hasNext()) {
621             Map.Entry<String, Object> entry = itr.next();
622 
623             String key = entry.getKey();
624             Object value = entry.getValue();
625 
626             if (Validator.isNotNull(value)) {
627                 sb.append(getWhere(key));
628             }
629         }
630 
631         return sb.toString();
632     }
633 
634     protected String getWhere(String key) {
635         String join = StringPool.BLANK;
636 
637         if (key.equals("permissionsResourceId")) {
638             join = CustomSQLUtil.get(JOIN_BY_ROLES_PERMISSIONS);
639         }
640         else if (key.equals("usersRoles")) {
641             join = CustomSQLUtil.get(JOIN_BY_USERS_ROLES);
642         }
643 
644         if (Validator.isNotNull(join)) {
645             int pos = join.indexOf("WHERE");
646 
647             if (pos != -1) {
648                 join = join.substring(pos + 5, join.length()).concat(" AND ");
649             }
650             else {
651                 join = StringPool.BLANK;
652             }
653         }
654 
655         return join;
656     }
657 
658     protected void setJoin(
659         QueryPos qPos, LinkedHashMap<String, Object> params) {
660 
661         if (params != null) {
662             Iterator<Map.Entry<String, Object>> itr =
663                 params.entrySet().iterator();
664 
665             while (itr.hasNext()) {
666                 Map.Entry<String, Object> entry = itr.next();
667 
668                 Object value = entry.getValue();
669 
670                 if (value instanceof Long) {
671                     Long valueLong = (Long)value;
672 
673                     if (Validator.isNotNull(valueLong)) {
674                         qPos.add(valueLong);
675                     }
676                 }
677                 else if (value instanceof String) {
678                     String valueString = (String)value;
679 
680                     if (Validator.isNotNull(valueString)) {
681                         qPos.add(valueString);
682                     }
683                 }
684             }
685         }
686     }
687 
688 }