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