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