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.NoSuchGroupException;
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.impl.GroupImpl;
38  import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;
39  import com.liferay.util.dao.orm.CustomSQLUtil;
40  
41  import java.util.ArrayList;
42  import java.util.Iterator;
43  import java.util.LinkedHashMap;
44  import java.util.List;
45  import java.util.Map;
46  
47  /**
48   * <a href="GroupFinderImpl.java.html"><b><i>View Source</i></b></a>
49   *
50   * @author Brian Wing Shun Chan
51   */
52  public class GroupFinderImpl
53      extends BasePersistenceImpl implements GroupFinder {
54  
55      public static String COUNT_BY_GROUP_ID =
56          GroupFinder.class.getName() + ".countByGroupId";
57  
58      public static String COUNT_BY_C_N_D =
59          GroupFinder.class.getName() + ".countByC_N_D";
60  
61      public static String FIND_BY_NO_LAYOUTS =
62          GroupFinder.class.getName() + ".findByNoLayouts";
63  
64      public static String FIND_BY_NULL_FRIENDLY_URL =
65          GroupFinder.class.getName() + ".findByNullFriendlyURL";
66  
67      public static String FIND_BY_SYSTEM =
68          GroupFinder.class.getName() + ".findBySystem";
69  
70      public static String FIND_BY_C_N =
71          GroupFinder.class.getName() + ".findByC_N";
72  
73      public static String FIND_BY_C_N_D =
74          GroupFinder.class.getName() + ".findByC_N_D";
75  
76      public static String JOIN_BY_ACTIVE =
77          GroupFinder.class.getName() + ".joinByActive";
78  
79      public static String JOIN_BY_CREATOR_USER_ID =
80          GroupFinder.class.getName() + ".joinByCreatorUserId";
81  
82      public static String JOIN_BY_GROUPS_ORGS =
83          GroupFinder.class.getName() + ".joinByGroupsOrgs";
84  
85      public static String JOIN_BY_GROUPS_ROLES =
86          GroupFinder.class.getName() + ".joinByGroupsRoles";
87  
88      public static String JOIN_BY_GROUPS_USER_GROUPS =
89          GroupFinder.class.getName() + ".joinByGroupsUserGroups";
90  
91      public static String JOIN_BY_LAYOUT_SET =
92          GroupFinder.class.getName() + ".joinByLayoutSet";
93  
94      public static String JOIN_BY_PAGE_COUNT =
95          GroupFinder.class.getName() + ".joinByPageCount";
96  
97      public static String JOIN_BY_ROLE_PERMISSIONS =
98          GroupFinder.class.getName() + ".joinByRolePermissions";
99  
100     public static String JOIN_BY_TYPE =
101         GroupFinder.class.getName() + ".joinByType";
102 
103     public static String JOIN_BY_USER_GROUP_ROLE =
104         GroupFinder.class.getName() + ".joinByUserGroupRole";
105 
106     public static String JOIN_BY_USERS_GROUPS =
107         GroupFinder.class.getName() + ".joinByUsersGroups";
108 
109     public int countByG_U(long groupId, long userId) throws SystemException {
110         LinkedHashMap<String, Object> params1 =
111             new LinkedHashMap<String, Object>();
112 
113         params1.put("usersGroups", userId);
114 
115         LinkedHashMap<String, Object> params2 =
116             new LinkedHashMap<String, Object>();
117 
118         params2.put("groupsOrgs", userId);
119 
120         LinkedHashMap<String, Object> params3 =
121             new LinkedHashMap<String, Object>();
122 
123         params3.put("groupsUserGroups", userId);
124 
125         Session session = null;
126 
127         try {
128             session = openSession();
129 
130             int count = countByGroupId(session, groupId, params1);
131             count += countByGroupId(session, groupId, params2);
132             count += countByGroupId(session, groupId, params3);
133 
134             return count;
135         }
136         catch (Exception e) {
137             throw new SystemException(e);
138         }
139         finally {
140             closeSession(session);
141         }
142     }
143 
144     public int countByC_N_D(
145             long companyId, String name, String description,
146             LinkedHashMap<String, Object> params)
147         throws SystemException {
148 
149         name = StringUtil.lowerCase(name);
150         description = StringUtil.lowerCase(description);
151 
152         if (params == null) {
153             params = new LinkedHashMap<String, Object>();
154         }
155 
156         Long userId = (Long)params.get("usersGroups");
157 
158         LinkedHashMap<String, Object> params1 = params;
159 
160         LinkedHashMap<String, Object> params2 =
161             new LinkedHashMap<String, Object>();
162 
163         params2.putAll(params1);
164 
165         if (userId != null) {
166             params2.remove("usersGroups");
167             params2.put("groupsOrgs", userId);
168         }
169 
170         LinkedHashMap<String, Object> params3 =
171             new LinkedHashMap<String, Object>();
172 
173         params3.putAll(params1);
174 
175         if (userId != null) {
176             params3.remove("usersGroups");
177             params3.put("groupsUserGroups", userId);
178         }
179 
180         Session session = null;
181 
182         try {
183             session = openSession();
184 
185             int count = countByC_N_D(
186                 session, companyId, name, description, params1);
187 
188             if (Validator.isNotNull(userId)) {
189                 count += countByC_N_D(
190                     session, companyId, name, description, params2);
191 
192                 count += countByC_N_D(
193                     session, companyId, name, description, params3);
194             }
195 
196             return count;
197         }
198         catch (Exception e) {
199             throw new SystemException(e);
200         }
201         finally {
202             closeSession(session);
203         }
204     }
205 
206     public List<Group> findByNoLayouts(
207             long classNameId, boolean privateLayout, int start, int end)
208         throws SystemException {
209 
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("Group_", GroupImpl.class);
220 
221             QueryPos qPos = QueryPos.getInstance(q);
222 
223             qPos.add(classNameId);
224             qPos.add(privateLayout);
225 
226             return q.list();
227         }
228         catch (Exception e) {
229             throw new SystemException(e);
230         }
231         finally {
232             closeSession(session);
233         }
234     }
235 
236     public List<Group> findByNullFriendlyURL() throws SystemException {
237         Session session = null;
238 
239         try {
240             session = openSession();
241 
242             String sql = CustomSQLUtil.get(FIND_BY_NULL_FRIENDLY_URL);
243 
244             SQLQuery q = session.createSQLQuery(sql);
245 
246             q.addEntity("Group_", GroupImpl.class);
247 
248             return q.list();
249         }
250         catch (Exception e) {
251             throw new SystemException(e);
252         }
253         finally {
254             closeSession(session);
255         }
256     }
257 
258     public List<Group> findBySystem(long companyId) throws SystemException {
259         Session session = null;
260 
261         try {
262             session = openSession();
263 
264             String sql = CustomSQLUtil.get(FIND_BY_SYSTEM);
265 
266             SQLQuery q = session.createSQLQuery(sql);
267 
268             q.addEntity("Group_", GroupImpl.class);
269 
270             QueryPos qPos = QueryPos.getInstance(q);
271 
272             qPos.add(companyId);
273 
274             return q.list();
275         }
276         catch (Exception e) {
277             throw new SystemException(e);
278         }
279         finally {
280             closeSession(session);
281         }
282     }
283 
284     public Group findByC_N(long companyId, String name)
285         throws NoSuchGroupException, SystemException {
286 
287         name = StringUtil.lowerCase(name);
288 
289         Session session = null;
290 
291         try {
292             session = openSession();
293 
294             String sql = CustomSQLUtil.get(FIND_BY_C_N);
295 
296             SQLQuery q = session.createSQLQuery(sql);
297 
298             q.addEntity("Group_", GroupImpl.class);
299 
300             QueryPos qPos = QueryPos.getInstance(q);
301 
302             qPos.add(companyId);
303             qPos.add(name);
304 
305             List<Group> list = q.list();
306 
307             if (!list.isEmpty()) {
308                 return list.get(0);
309             }
310         }
311         catch (Exception e) {
312             throw new SystemException(e);
313         }
314         finally {
315             closeSession(session);
316         }
317 
318         StringBuilder sb = new StringBuilder();
319 
320         sb.append("No Group exists with the key {companyId=");
321         sb.append(companyId);
322         sb.append(", name=");
323         sb.append(name);
324         sb.append("}");
325 
326         throw new NoSuchGroupException(sb.toString());
327     }
328 
329     public List<Group> findByC_N_D(
330             long companyId, String name, String description,
331             LinkedHashMap<String, Object> params, int start, int end,
332             OrderByComparator obc)
333         throws SystemException {
334 
335         name = StringUtil.lowerCase(name);
336         description = StringUtil.lowerCase(description);
337 
338         if (params == null) {
339             params = new LinkedHashMap<String, Object>();
340         }
341 
342         Long userId = (Long)params.get("usersGroups");
343 
344         LinkedHashMap<String, Object> params1 = params;
345 
346         LinkedHashMap<String, Object> params2 =
347             new LinkedHashMap<String, Object>();
348 
349         params2.putAll(params1);
350 
351         if (userId != null) {
352             params2.remove("usersGroups");
353             params2.put("groupsOrgs", userId);
354         }
355 
356         LinkedHashMap<String, Object> params3 =
357             new LinkedHashMap<String, Object>();
358 
359         params3.putAll(params1);
360 
361         if (userId != null) {
362             params3.remove("usersGroups");
363             params3.put("groupsUserGroups", userId);
364         }
365 
366         StringBuilder sb = new StringBuilder();
367 
368         sb.append("(");
369 
370         sb.append(CustomSQLUtil.get(FIND_BY_C_N_D));
371 
372         String sql = sb.toString();
373 
374         sql = StringUtil.replace(sql, "[$JOIN$]", getJoin(params1));
375         sql = StringUtil.replace(sql, "[$WHERE$]", getWhere(params1));
376 
377         sb = new StringBuilder();
378 
379         sb.append(sql);
380 
381         sb.append(")");
382 
383         if (Validator.isNotNull(userId)) {
384             sb.append(" UNION (");
385 
386             sb.append(CustomSQLUtil.get(FIND_BY_C_N_D));
387 
388             sql = sb.toString();
389 
390             sql = StringUtil.replace(sql, "[$JOIN$]", getJoin(params2));
391             sql = StringUtil.replace(sql, "[$WHERE$]", getWhere(params2));
392 
393             sb = new StringBuilder();
394 
395             sb.append(sql);
396 
397             sb.append(") UNION (");
398 
399             sb.append(CustomSQLUtil.get(FIND_BY_C_N_D));
400 
401             sql = sb.toString();
402 
403             sql = StringUtil.replace(sql, "[$JOIN$]", getJoin(params3));
404             sql = StringUtil.replace(sql, "[$WHERE$]", getWhere(params3));
405 
406             sb = new StringBuilder();
407 
408             sb.append(sql);
409 
410             sb.append(")");
411         }
412 
413         sql = sb.toString();
414         sql = CustomSQLUtil.replaceOrderBy(sql, obc);
415 
416         Session session = null;
417 
418         try {
419             session = openSession();
420 
421             SQLQuery q = session.createSQLQuery(sql);
422 
423             q.addScalar("groupId", Type.LONG);
424 
425             QueryPos qPos = QueryPos.getInstance(q);
426 
427             setJoin(qPos, params1);
428             qPos.add(companyId);
429             qPos.add(name);
430             qPos.add(name);
431             qPos.add(description);
432             qPos.add(description);
433 
434             if (Validator.isNotNull(userId)) {
435                 setJoin(qPos, params2);
436                 qPos.add(companyId);
437                 qPos.add(name);
438                 qPos.add(name);
439                 qPos.add(description);
440                 qPos.add(description);
441 
442                 setJoin(qPos, params3);
443                 qPos.add(companyId);
444                 qPos.add(name);
445                 qPos.add(name);
446                 qPos.add(description);
447                 qPos.add(description);
448             }
449 
450             List<Group> groups = new ArrayList<Group>();
451 
452             Iterator<Long> itr = (Iterator<Long>)QueryUtil.iterate(
453                 q, getDialect(), start, end);
454 
455             while (itr.hasNext()) {
456                 long groupId = itr.next();
457 
458                 Group group = GroupUtil.findByPrimaryKey(groupId);
459 
460                 groups.add(group);
461             }
462 
463             return groups;
464         }
465         catch (Exception e) {
466             throw new SystemException(e);
467         }
468         finally {
469             closeSession(session);
470         }
471     }
472 
473     protected int countByGroupId(
474         Session session, long groupId, LinkedHashMap<String, Object> params) {
475 
476         String sql = CustomSQLUtil.get(COUNT_BY_GROUP_ID);
477 
478         sql = StringUtil.replace(sql, "[$JOIN$]", getJoin(params));
479         sql = StringUtil.replace(sql, "[$WHERE$]", getWhere(params));
480 
481         SQLQuery q = session.createSQLQuery(sql);
482 
483         q.addScalar(COUNT_COLUMN_NAME, Type.LONG);
484 
485         QueryPos qPos = QueryPos.getInstance(q);
486 
487         setJoin(qPos, params);
488         qPos.add(groupId);
489 
490         Iterator<Long> itr = q.list().iterator();
491 
492         if (itr.hasNext()) {
493             Long count = itr.next();
494 
495             if (count != null) {
496                 return count.intValue();
497             }
498         }
499 
500         return 0;
501     }
502 
503     protected int countByC_N_D(
504         Session session, long companyId, String name, String description,
505         LinkedHashMap<String, Object> params) {
506 
507         String sql = CustomSQLUtil.get(COUNT_BY_C_N_D);
508 
509         sql = StringUtil.replace(sql, "[$JOIN$]", getJoin(params));
510         sql = StringUtil.replace(sql, "[$WHERE$]", getWhere(params));
511 
512         SQLQuery q = session.createSQLQuery(sql);
513 
514         q.addScalar(COUNT_COLUMN_NAME, Type.LONG);
515 
516         QueryPos qPos = QueryPos.getInstance(q);
517 
518         setJoin(qPos, params);
519         qPos.add(companyId);
520         qPos.add(name);
521         qPos.add(name);
522         qPos.add(description);
523         qPos.add(description);
524 
525         Iterator<Long> itr = q.list().iterator();
526 
527         if (itr.hasNext()) {
528             Long count = itr.next();
529 
530             if (count != null) {
531                 return count.intValue();
532             }
533         }
534 
535         return 0;
536     }
537 
538     protected String getJoin(LinkedHashMap<String, Object> params) {
539         if (params == null) {
540             return StringPool.BLANK;
541         }
542 
543         StringBuilder sb = new StringBuilder();
544 
545         Iterator<Map.Entry<String, Object>> itr = params.entrySet().iterator();
546 
547         while (itr.hasNext()) {
548             Map.Entry<String, Object> entry = itr.next();
549 
550             String key = entry.getKey();
551             Object value = entry.getValue();
552 
553             if (Validator.isNotNull(value)) {
554                 sb.append(getJoin(key));
555             }
556         }
557 
558         return sb.toString();
559     }
560 
561     protected String getJoin(String key) {
562         String join = StringPool.BLANK;
563 
564         if (key.equals("groupsOrgs")) {
565             join = CustomSQLUtil.get(JOIN_BY_GROUPS_ORGS);
566         }
567         else if (key.equals("groupsRoles")) {
568             join = CustomSQLUtil.get(JOIN_BY_GROUPS_ROLES);
569         }
570         else if (key.equals("groupsUserGroups")) {
571             join = CustomSQLUtil.get(JOIN_BY_GROUPS_USER_GROUPS);
572         }
573         else if (key.equals("layoutSet")) {
574             join = CustomSQLUtil.get(JOIN_BY_LAYOUT_SET);
575         }
576         else if (key.equals("pageCount")) {
577             join = CustomSQLUtil.get(JOIN_BY_PAGE_COUNT);
578         }
579         else if (key.equals("rolePermissions")) {
580             join = CustomSQLUtil.get(JOIN_BY_ROLE_PERMISSIONS);
581         }
582         else if (key.equals("userGroupRole")) {
583             join = CustomSQLUtil.get(JOIN_BY_USER_GROUP_ROLE);
584         }
585         else if (key.equals("usersGroups")) {
586             join = CustomSQLUtil.get(JOIN_BY_USERS_GROUPS);
587         }
588 
589         if (Validator.isNotNull(join)) {
590             int pos = join.indexOf("WHERE");
591 
592             if (pos != -1) {
593                 join = join.substring(0, pos);
594             }
595         }
596 
597         return join;
598     }
599 
600     protected String getWhere(LinkedHashMap<String, Object> params) {
601         if (params == null) {
602             return StringPool.BLANK;
603         }
604 
605         StringBuilder sb = new StringBuilder();
606 
607         Iterator<Map.Entry<String, Object>> itr = params.entrySet().iterator();
608 
609         while (itr.hasNext()) {
610             Map.Entry<String, Object> entry = itr.next();
611 
612             String key = entry.getKey();
613             Object value = entry.getValue();
614 
615             if (Validator.isNotNull(value)) {
616                 sb.append(getWhere(key, value));
617             }
618         }
619 
620         return sb.toString();
621     }
622 
623     protected String getWhere(String key, Object value) {
624         String join = StringPool.BLANK;
625 
626         if (key.equals("active")) {
627             join = CustomSQLUtil.get(JOIN_BY_ACTIVE);
628         }
629         else if (key.equals("creatorUserId")) {
630             join = CustomSQLUtil.get(JOIN_BY_CREATOR_USER_ID);
631         }
632         else if (key.equals("groupsOrgs")) {
633             join = CustomSQLUtil.get(JOIN_BY_GROUPS_ORGS);
634         }
635         else if (key.equals("groupsRoles")) {
636             join = CustomSQLUtil.get(JOIN_BY_GROUPS_ROLES);
637         }
638         else if (key.equals("groupsUserGroups")) {
639             join = CustomSQLUtil.get(JOIN_BY_GROUPS_USER_GROUPS);
640         }
641         else if (key.equals("layoutSet")) {
642             join = CustomSQLUtil.get(JOIN_BY_LAYOUT_SET);
643         }
644         else if (key.equals("pageCount")) {
645             join = CustomSQLUtil.get(JOIN_BY_PAGE_COUNT);
646         }
647         else if (key.equals("rolePermissions")) {
648             join = CustomSQLUtil.get(JOIN_BY_ROLE_PERMISSIONS);
649         }
650         else if (key.equals("type")) {
651             join = CustomSQLUtil.get(JOIN_BY_TYPE);
652         }
653         else if (key.equals("types")) {
654             List<Integer> types = (List<Integer>)value;
655 
656             if (!types.isEmpty()) {
657                 StringBuilder sb = new StringBuilder();
658 
659                 sb.append("WHERE (");
660 
661                 for (int i = 0; i < types.size(); i++) {
662                     sb.append("(Group_.type_ = ?) ");
663 
664                     if ((i + 1) < types.size()) {
665                         sb.append("OR ");
666                     }
667                 }
668 
669                 sb.append(")");
670 
671                 join = sb.toString();
672             }
673         }
674         else if (key.equals("userGroupRole")) {
675             join = CustomSQLUtil.get(JOIN_BY_USER_GROUP_ROLE);
676         }
677         else if (key.equals("usersGroups")) {
678             join = CustomSQLUtil.get(JOIN_BY_USERS_GROUPS);
679         }
680 
681         if (Validator.isNotNull(join)) {
682             int pos = join.indexOf("WHERE");
683 
684             if (pos != -1) {
685                 StringBuilder sb = new StringBuilder();
686 
687                 sb.append(join.substring(pos + 5, join.length()));
688                 sb.append(" AND ");
689 
690                 join = sb.toString();
691             }
692             else {
693                 join = StringPool.BLANK;
694             }
695         }
696 
697         return join;
698     }
699 
700     protected void setJoin(
701         QueryPos qPos, LinkedHashMap<String, Object> params) {
702 
703         if (params != null) {
704             Iterator<Map.Entry<String, Object>> itr =
705                 params.entrySet().iterator();
706 
707             while (itr.hasNext()) {
708                 Map.Entry<String, Object> entry = itr.next();
709 
710                 String key = entry.getKey();
711 
712                 if (key.equals("active") || key.equals("layoutSet")) {
713                     Boolean value = (Boolean)entry.getValue();
714 
715                     qPos.add(value);
716                 }
717                 else if (key.equals("pageCount")) {
718                 }
719                 else if (key.equals("rolePermissions")) {
720                     List<Object> values = (List<Object>)entry.getValue();
721 
722                     for (int i = 0; i < values.size(); i++) {
723                         Object value = values.get(i);
724 
725                         if (value instanceof Integer) {
726                             Integer valueInteger = (Integer)value;
727 
728                             qPos.add(valueInteger);
729                         }
730                         else if (value instanceof Long) {
731                             Long valueLong = (Long)value;
732 
733                             qPos.add(valueLong);
734                         }
735                         else if (value instanceof String) {
736                             String valueString = (String)value;
737 
738                             qPos.add(valueString);
739                         }
740                     }
741                 }
742                 else if (key.equals("types")) {
743                     List<Integer> values = (List<Integer>)entry.getValue();
744 
745                     for (int i = 0; i < values.size(); i++) {
746                         Integer value = values.get(i);
747 
748                         qPos.add(value);
749                     }
750                 }
751                 else if (key.equals("userGroupRole")) {
752                     List<Long> values = (List<Long>)entry.getValue();
753 
754                     Long userId = values.get(0);
755                     Long roleId = values.get(1);
756 
757                     qPos.add(userId);
758                     qPos.add(roleId);
759                 }
760                 else {
761                     Object value = entry.getValue();
762 
763                     if (value instanceof Long) {
764                         Long valueLong = (Long)value;
765 
766                         if (Validator.isNotNull(valueLong)) {
767                             qPos.add(valueLong);
768                         }
769                     }
770                     else if (value instanceof String) {
771                         String valueString = (String)value;
772 
773                         if (Validator.isNotNull(valueString)) {
774                             qPos.add(valueString);
775                         }
776                     }
777                 }
778             }
779         }
780     }
781 
782 }