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