1   /**
2    * Copyright (c) 2000-2009 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   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
13   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
14   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
15   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
16   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
17   * SOFTWARE.
18   */
19  
20  package com.liferay.portal.service.persistence;
21  
22  import com.liferay.portal.NoSuchRoleException;
23  import com.liferay.portal.SystemException;
24  import com.liferay.portal.kernel.dao.orm.QueryPos;
25  import com.liferay.portal.kernel.dao.orm.QueryUtil;
26  import com.liferay.portal.kernel.dao.orm.SQLQuery;
27  import com.liferay.portal.kernel.dao.orm.Session;
28  import com.liferay.portal.kernel.dao.orm.Type;
29  import com.liferay.portal.kernel.util.OrderByComparator;
30  import com.liferay.portal.kernel.util.StringPool;
31  import com.liferay.portal.kernel.util.StringUtil;
32  import com.liferay.portal.kernel.util.Validator;
33  import com.liferay.portal.model.Group;
34  import com.liferay.portal.model.Role;
35  import com.liferay.portal.model.impl.RoleImpl;
36  import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;
37  import com.liferay.util.dao.orm.CustomSQLUtil;
38  
39  import java.util.ArrayList;
40  import java.util.HashMap;
41  import java.util.Iterator;
42  import java.util.LinkedHashMap;
43  import java.util.List;
44  import java.util.Map;
45  
46  /**
47   * <a href="RoleFinderImpl.java.html"><b><i>View Source</i></b></a>
48   *
49   * @author Brian Wing Shun Chan
50   *
51   */
52  public class RoleFinderImpl extends BasePersistenceImpl implements RoleFinder {
53  
54      public static String COUNT_BY_C_N_D_T =
55          RoleFinder.class.getName() + ".countByC_N_D_T";
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 FIND_BY_SYSTEM =
76          RoleFinder.class.getName() + ".findBySystem";
77  
78      public static String FIND_BY_USER_GROUP_ROLE =
79          RoleFinder.class.getName() + ".findByUserGroupRole";
80  
81      public static String FIND_BY_C_N =
82          RoleFinder.class.getName() + ".findByC_N";
83  
84      public static String FIND_BY_U_G =
85          RoleFinder.class.getName() + ".findByU_G";
86  
87      public static String FIND_BY_C_N_D_T =
88          RoleFinder.class.getName() + ".findByC_N_D_T";
89  
90      public static String FIND_BY_C_N_S_P =
91          RoleFinder.class.getName() + ".findByC_N_S_P";
92  
93      public static String JOIN_BY_ROLES_PERMISSIONS =
94          RoleFinder.class.getName() + ".joinByRolesPermissions";
95  
96      public static String JOIN_BY_USERS_ROLES =
97          RoleFinder.class.getName() + ".joinByUsersRoles";
98  
99      public int countByR_U(long roleId, long userId) throws SystemException {
100         Session session = null;
101 
102         try {
103             session = openSession();
104 
105             StringBuilder sb = new StringBuilder();
106 
107             sb.append("(");
108             sb.append(CustomSQLUtil.get(COUNT_BY_COMMUNITY));
109             sb.append(") UNION (");
110             sb.append(CustomSQLUtil.get(COUNT_BY_ORGANIZATION));
111             sb.append(") UNION (");
112             sb.append(CustomSQLUtil.get(COUNT_BY_ORGANIZATION_COMMUNITY));
113             sb.append(") UNION (");
114             sb.append(CustomSQLUtil.get(COUNT_BY_USER));
115             sb.append(") UNION (");
116             sb.append(CustomSQLUtil.get(COUNT_BY_USER_GROUP));
117             sb.append(") UNION (");
118             sb.append(CustomSQLUtil.get(COUNT_BY_USER_GROUP_COMMUNITY));
119             sb.append(")");
120 
121             SQLQuery q = session.createSQLQuery(sb.toString());
122 
123             q.addScalar(COUNT_COLUMN_NAME, Type.LONG);
124 
125             QueryPos qPos = QueryPos.getInstance(q);
126 
127             for (int i = 0; i < 6; i++) {
128                 qPos.add(roleId);
129                 qPos.add(userId);
130             }
131 
132             int count = 0;
133 
134             Iterator<Long> itr = q.list().iterator();
135 
136             while (itr.hasNext()) {
137                 Long l = itr.next();
138 
139                 if (l != null) {
140                     count += l.intValue();
141                 }
142             }
143 
144             return count;
145         }
146         catch (Exception e) {
147             throw new SystemException(e);
148         }
149         finally {
150             closeSession(session);
151         }
152     }
153 
154     public int countByC_N_D_T(
155             long companyId, String name, String description, Integer type,
156             LinkedHashMap<String, Object> params)
157         throws SystemException {
158 
159         name = StringUtil.lowerCase(name);
160         description = StringUtil.lowerCase(description);
161 
162         Session session = null;
163 
164         try {
165             session = openSession();
166 
167             String sql = CustomSQLUtil.get(COUNT_BY_C_N_D_T);
168 
169             if (type == null) {
170                 sql = StringUtil.replace(sql, "AND (Role_.type_ = ?)", "");
171             }
172 
173             sql = StringUtil.replace(sql, "[$JOIN$]", getJoin(params));
174             sql = StringUtil.replace(sql, "[$WHERE$]", getWhere(params));
175 
176             SQLQuery q = session.createSQLQuery(sql);
177 
178             q.addScalar(COUNT_COLUMN_NAME, Type.LONG);
179 
180             QueryPos qPos = QueryPos.getInstance(q);
181 
182             setJoin(qPos, params);
183             qPos.add(companyId);
184             qPos.add(name);
185             qPos.add(name);
186             qPos.add(description);
187             qPos.add(description);
188 
189             if (type != null) {
190                 qPos.add(type);
191             }
192 
193             Iterator<Long> itr = q.list().iterator();
194 
195             if (itr.hasNext()) {
196                 Long count = itr.next();
197 
198                 if (count != null) {
199                     return count.intValue();
200                 }
201             }
202 
203             return 0;
204         }
205         catch (Exception e) {
206             throw new SystemException(e);
207         }
208         finally {
209             closeSession(session);
210         }
211     }
212 
213     public List<Role> findBySystem(long companyId) throws SystemException {
214         Session session = null;
215 
216         try {
217             session = openSession();
218 
219             String sql = CustomSQLUtil.get(FIND_BY_SYSTEM);
220 
221             SQLQuery q = session.createSQLQuery(sql);
222 
223             q.addEntity("Role_", RoleImpl.class);
224 
225             QueryPos qPos = QueryPos.getInstance(q);
226 
227             qPos.add(companyId);
228 
229             return q.list();
230         }
231         catch (Exception e) {
232             throw new SystemException(e);
233         }
234         finally {
235             closeSession(session);
236         }
237     }
238 
239     public List<Role> findByUserGroupRole(long userId, long groupId)
240         throws SystemException {
241 
242         Session session = null;
243 
244         try {
245             session = openSession();
246 
247             String sql = CustomSQLUtil.get(FIND_BY_USER_GROUP_ROLE);
248 
249             SQLQuery q = session.createSQLQuery(sql);
250 
251             q.addEntity("Role_", RoleImpl.class);
252 
253             QueryPos qPos = QueryPos.getInstance(q);
254 
255             qPos.add(userId);
256             qPos.add(groupId);
257 
258             return q.list();
259         }
260         catch (Exception e) {
261             throw new SystemException(e);
262         }
263         finally {
264             closeSession(session);
265         }
266     }
267 
268     public Role findByC_N(long companyId, String name)
269         throws NoSuchRoleException, SystemException {
270 
271         name = StringUtil.lowerCase(name);
272 
273         Session session = null;
274 
275         try {
276             session = openSession();
277 
278             String sql = CustomSQLUtil.get(FIND_BY_C_N);
279 
280             SQLQuery q = session.createSQLQuery(sql);
281 
282             q.addEntity("Role_", RoleImpl.class);
283 
284             QueryPos qPos = QueryPos.getInstance(q);
285 
286             qPos.add(companyId);
287             qPos.add(name);
288 
289             List<Role> list = q.list();
290 
291             if (!list.isEmpty()) {
292                 return list.get(0);
293             }
294         }
295         catch (Exception e) {
296             throw new SystemException(e);
297         }
298         finally {
299             closeSession(session);
300         }
301 
302         StringBuilder sb = new StringBuilder();
303 
304         sb.append("No Role exists with the key {companyId=");
305         sb.append(companyId);
306         sb.append(", name=");
307         sb.append(name);
308         sb.append("}");
309 
310         throw new NoSuchRoleException(sb.toString());
311     }
312 
313     public List<Role> findByU_G(long userId, long groupId)
314         throws SystemException {
315 
316         return findByU_G(userId, new long[] {groupId});
317     }
318 
319     public List<Role> findByU_G(long userId, long[] groupIds)
320         throws SystemException {
321 
322         Session session = null;
323 
324         try {
325             session = openSession();
326 
327             String sql = CustomSQLUtil.get(FIND_BY_U_G);
328 
329             sql = StringUtil.replace(
330                 sql, "[$GROUP_IDS$]", getGroupIds(groupIds, "Groups_Roles"));
331 
332             SQLQuery q = session.createSQLQuery(sql);
333 
334             q.addEntity("Role_", RoleImpl.class);
335 
336             QueryPos qPos = QueryPos.getInstance(q);
337 
338             qPos.add(userId);
339             setGroupIds(qPos, groupIds);
340 
341             return q.list();
342         }
343         catch (Exception e) {
344             throw new SystemException(e);
345         }
346         finally {
347             closeSession(session);
348         }
349     }
350 
351     public List<Role> findByU_G(long userId, List<Group> groups)
352         throws SystemException {
353 
354         long[] groupIds = new long[groups.size()];
355 
356         for (int i = 0; i < groups.size(); i++) {
357             Group group = groups.get(i);
358 
359             groupIds[i] = group.getGroupId();
360         }
361 
362         return findByU_G(userId, groupIds);
363     }
364 
365     public List<Role> findByC_N_D_T(
366             long companyId, String name, String description, Integer type,
367             LinkedHashMap<String, Object> params, int start, int end,
368             OrderByComparator obc)
369         throws SystemException {
370 
371         name = StringUtil.lowerCase(name);
372         description = StringUtil.lowerCase(description);
373 
374         Session session = null;
375 
376         try {
377             session = openSession();
378 
379             String sql = CustomSQLUtil.get(FIND_BY_C_N_D_T);
380 
381             if (type == null) {
382                 sql = StringUtil.replace(sql, "AND (Role_.type_ = ?)", "");
383             }
384 
385             sql = StringUtil.replace(sql, "[$JOIN$]", getJoin(params));
386             sql = StringUtil.replace(sql, "[$WHERE$]", getWhere(params));
387             sql = CustomSQLUtil.replaceOrderBy(sql, obc);
388 
389             SQLQuery q = session.createSQLQuery(sql);
390 
391             q.addEntity("Role_", RoleImpl.class);
392 
393             QueryPos qPos = QueryPos.getInstance(q);
394 
395             setJoin(qPos, params);
396             qPos.add(companyId);
397             qPos.add(name);
398             qPos.add(name);
399             qPos.add(description);
400             qPos.add(description);
401 
402             if (type != null) {
403                 qPos.add(type);
404             }
405 
406             return (List<Role>)QueryUtil.list(q, getDialect(), start, end);
407         }
408         catch (Exception e) {
409             throw new SystemException(e);
410         }
411         finally {
412             closeSession(session);
413         }
414     }
415 
416     public Map<String, List<String>> findByC_N_S_P(
417             long companyId, String name, int scope, String primKey)
418         throws SystemException {
419 
420         Session session = null;
421 
422         try {
423             session = openSession();
424 
425             String sql = CustomSQLUtil.get(FIND_BY_C_N_S_P);
426 
427             SQLQuery q = session.createSQLQuery(sql);
428 
429             q.addScalar("roleName", Type.STRING);
430             q.addScalar("actionId", Type.STRING);
431 
432             QueryPos qPos = QueryPos.getInstance(q);
433 
434             qPos.add(companyId);
435             qPos.add(name);
436             qPos.add(scope);
437             qPos.add(primKey);
438 
439             Map<String, List<String>> roleMap =
440                 new HashMap<String, List<String>>();
441 
442             Iterator<Object[]> itr = q.list().iterator();
443 
444             while (itr.hasNext()) {
445                 Object[] array = itr.next();
446 
447                 String roleName = (String)array[0];
448                 String actionId = (String)array[1];
449 
450                 List<String> roleList = roleMap.get(roleName);
451 
452                 if (roleList == null) {
453                     roleList = new ArrayList<String>();
454                 }
455 
456                 roleList.add(actionId);
457 
458                 roleMap.put(roleName, roleList);
459             }
460 
461             return roleMap;
462         }
463         catch (Exception e) {
464             throw new SystemException(e);
465         }
466         finally {
467             closeSession(session);
468         }
469     }
470 
471     protected String getGroupIds(long[] groupIds, String table) {
472         StringBuilder sb = new StringBuilder();
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) {
494             return StringPool.BLANK;
495         }
496 
497         StringBuilder sb = new StringBuilder();
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) {
538             return StringPool.BLANK;
539         }
540 
541         StringBuilder sb = new StringBuilder();
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                 StringBuilder sb = new StringBuilder();
574 
575                 sb.append(join.substring(pos + 5, join.length()));
576                 sb.append(" AND ");
577 
578                 join = sb.toString();
579             }
580             else {
581                 join = StringPool.BLANK;
582             }
583         }
584 
585         return join;
586     }
587 
588     protected void setJoin(
589         QueryPos qPos, LinkedHashMap<String, Object> params) {
590 
591         if (params != null) {
592             Iterator<Map.Entry<String, Object>> itr =
593                 params.entrySet().iterator();
594 
595             while (itr.hasNext()) {
596                 Map.Entry<String, Object> entry = itr.next();
597 
598                 Object value = entry.getValue();
599 
600                 if (value instanceof Long) {
601                     Long valueLong = (Long)value;
602 
603                     if (Validator.isNotNull(valueLong)) {
604                         qPos.add(valueLong);
605                     }
606                 }
607                 else if (value instanceof String) {
608                     String valueString = (String)value;
609 
610                     if (Validator.isNotNull(valueString)) {
611                         qPos.add(valueString);
612                     }
613                 }
614             }
615         }
616     }
617 
618 }