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