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