001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.service.persistence;
016    
017    import com.liferay.portal.NoSuchGroupException;
018    import com.liferay.portal.kernel.dao.orm.QueryPos;
019    import com.liferay.portal.kernel.dao.orm.QueryUtil;
020    import com.liferay.portal.kernel.dao.orm.SQLQuery;
021    import com.liferay.portal.kernel.dao.orm.Session;
022    import com.liferay.portal.kernel.dao.orm.Type;
023    import com.liferay.portal.kernel.exception.SystemException;
024    import com.liferay.portal.kernel.util.GetterUtil;
025    import com.liferay.portal.kernel.util.OrderByComparator;
026    import com.liferay.portal.kernel.util.StringBundler;
027    import com.liferay.portal.kernel.util.StringPool;
028    import com.liferay.portal.kernel.util.StringUtil;
029    import com.liferay.portal.kernel.util.Validator;
030    import com.liferay.portal.model.Group;
031    import com.liferay.portal.model.Organization;
032    import com.liferay.portal.model.ResourceAction;
033    import com.liferay.portal.model.impl.GroupImpl;
034    import com.liferay.portal.service.ClassNameLocalServiceUtil;
035    import com.liferay.portal.service.ResourceActionLocalServiceUtil;
036    import com.liferay.portal.service.ResourceBlockLocalServiceUtil;
037    import com.liferay.portal.service.impl.GroupLocalServiceImpl;
038    import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;
039    import com.liferay.portal.util.PropsValues;
040    import com.liferay.portal.util.comparator.GroupNameComparator;
041    import com.liferay.util.dao.orm.CustomSQLUtil;
042    
043    import java.util.ArrayList;
044    import java.util.HashMap;
045    import java.util.HashSet;
046    import java.util.Iterator;
047    import java.util.LinkedHashMap;
048    import java.util.List;
049    import java.util.Map;
050    import java.util.Set;
051    import java.util.concurrent.ConcurrentHashMap;
052    
053    /**
054     * @author Brian Wing Shun Chan
055     * @author Shuyang Zhou
056     */
057    public class GroupFinderImpl
058            extends BasePersistenceImpl<Group> implements GroupFinder {
059    
060            public static final String COUNT_BY_GROUP_ID =
061                    GroupFinder.class.getName() + ".countByGroupId";
062    
063            public static final String COUNT_BY_C_N_D =
064                    GroupFinder.class.getName() + ".countByC_N_D";
065    
066            public static final String FIND_BY_LIVE_GROUPS =
067                    GroupFinder.class.getName() + ".findByLiveGroups";
068    
069            public static final String FIND_BY_NO_LAYOUTS =
070                    GroupFinder.class.getName() + ".findByNoLayouts";
071    
072            public static final String FIND_BY_NULL_FRIENDLY_URL =
073                    GroupFinder.class.getName() + ".findByNullFriendlyURL";
074    
075            public static final String FIND_BY_SYSTEM =
076                    GroupFinder.class.getName() + ".findBySystem";
077    
078            public static final String FIND_BY_C_C =
079                    GroupFinder.class.getName() + ".findByC_C";
080    
081            public static final String FIND_BY_C_N =
082                    GroupFinder.class.getName() + ".findByC_N";
083    
084            public static final String FIND_BY_C_N_D =
085                    GroupFinder.class.getName() + ".findByC_N_D";
086    
087            public static final String JOIN_BY_ACTIVE =
088                    GroupFinder.class.getName() + ".joinByActive";
089    
090            public static final String JOIN_BY_CREATOR_USER_ID =
091                    GroupFinder.class.getName() + ".joinByCreatorUserId";
092    
093            public static final String JOIN_BY_GROUP_ORG =
094                    GroupFinder.class.getName() + ".joinByGroupOrg";
095    
096            public static final String JOIN_BY_GROUPS_ORGS =
097                    GroupFinder.class.getName() + ".joinByGroupsOrgs";
098    
099            public static final String JOIN_BY_GROUPS_ROLES =
100                    GroupFinder.class.getName() + ".joinByGroupsRoles";
101    
102            public static final String JOIN_BY_GROUPS_USER_GROUPS =
103                    GroupFinder.class.getName() + ".joinByGroupsUserGroups";
104    
105            public static final String JOIN_BY_LAYOUT_SET =
106                    GroupFinder.class.getName() + ".joinByLayoutSet";
107    
108            public static final String JOIN_BY_PAGE_COUNT =
109                    GroupFinder.class.getName() + ".joinByPageCount";
110    
111            public static final String JOIN_BY_ROLE_PERMISSIONS =
112                    GroupFinder.class.getName() + ".joinByRolePermissions";
113    
114            public static final String JOIN_BY_ROLE_RESOURCE_PERMISSIONS =
115                    GroupFinder.class.getName() + ".joinByRoleResourcePermissions";
116    
117            public static final String JOIN_BY_ROLE_RESOURCE_TYPE_PERMISSIONS =
118                    GroupFinder.class.getName() + ".joinByRoleResourceTypePermissions";
119    
120            public static final String JOIN_BY_SITE =
121                    GroupFinder.class.getName() + ".joinBySite";
122    
123            public static final String JOIN_BY_TYPE =
124                    GroupFinder.class.getName() + ".joinByType";
125    
126            public static final String JOIN_BY_USER_GROUP_ROLE =
127                    GroupFinder.class.getName() + ".joinByUserGroupRole";
128    
129            public static final String JOIN_BY_USERS_GROUPS =
130                    GroupFinder.class.getName() + ".joinByUsersGroups";
131    
132            @Override
133            public int countByG_U(long groupId, long userId, boolean inherit)
134                    throws SystemException {
135    
136                    LinkedHashMap<String, Object> params1 =
137                            new LinkedHashMap<String, Object>();
138    
139                    params1.put("usersGroups", userId);
140    
141                    LinkedHashMap<String, Object> params2 =
142                            new LinkedHashMap<String, Object>();
143    
144                    params2.put("groupOrg", userId);
145    
146                    LinkedHashMap<String, Object> params3 =
147                            new LinkedHashMap<String, Object>();
148    
149                    params3.put("groupsOrgs", userId);
150    
151                    LinkedHashMap<String, Object> params4 =
152                            new LinkedHashMap<String, Object>();
153    
154                    params4.put("groupsUserGroups", userId);
155    
156                    Session session = null;
157    
158                    try {
159                            session = openSession();
160    
161                            int count = countByGroupId(session, groupId, params1);
162    
163                            if (inherit) {
164                                    count += countByGroupId(session, groupId, params2);
165                                    count += countByGroupId(session, groupId, params3);
166                                    count += countByGroupId(session, groupId, params4);
167                            }
168    
169                            return count;
170                    }
171                    catch (Exception e) {
172                            throw new SystemException(e);
173                    }
174                    finally {
175                            closeSession(session);
176                    }
177            }
178    
179            @Override
180            public int countByC_N_D(
181                            long companyId, String name, String realName, String description,
182                            LinkedHashMap<String, Object> params)
183                    throws SystemException {
184    
185                    return countByC_C_N_D(
186                            companyId, _getGroupOrganizationClassNameIds(), name, realName,
187                            description, params);
188            }
189    
190            @Override
191            public int countByC_C_N_D(
192                            long companyId, long[] classNameIds, String name, String realName,
193                            String description, LinkedHashMap<String, Object> params)
194                    throws SystemException {
195    
196                    name = StringUtil.lowerCase(name);
197                    description = StringUtil.lowerCase(description);
198    
199                    if (params == null) {
200                            params = _emptyLinkedHashMap;
201                    }
202    
203                    LinkedHashMap<String, Object> params1 = params;
204    
205                    LinkedHashMap<String, Object> params2 = null;
206    
207                    LinkedHashMap<String, Object> params3 = null;
208    
209                    LinkedHashMap<String, Object> params4 = null;
210    
211                    Long userId = (Long)params.get("usersGroups");
212    
213                    boolean doUnion = Validator.isNotNull(userId);
214    
215                    if (doUnion) {
216                            params2 = new LinkedHashMap<String, Object>(params1);
217    
218                            params2.remove("usersGroups");
219                            params2.put("groupOrg", userId);
220    
221                            params3 = new LinkedHashMap<String, Object>(params1);
222    
223                            params3.remove("usersGroups");
224                            params3.put("groupsOrgs", userId);
225    
226                            params4 = new LinkedHashMap<String, Object>(params1);
227    
228                            params4.remove("usersGroups");
229                            params4.put("groupsUserGroups", userId);
230                    }
231    
232                    Session session = null;
233    
234                    try {
235                            session = openSession();
236    
237                            Set<Long> groupIds = new HashSet<Long>();
238    
239                            groupIds.addAll(
240                                    countByC_C_N_D(
241                                            session, companyId, classNameIds, name, realName,
242                                            description, params1));
243    
244                            if (doUnion) {
245                                    groupIds.addAll(
246                                            countByC_C_N_D(
247                                                    session, companyId, classNameIds, name, realName,
248                                                    description, params2));
249    
250                                    groupIds.addAll(
251                                            countByC_C_N_D(
252                                                    session, companyId, classNameIds, name, realName,
253                                                    description, params3));
254    
255                                    groupIds.addAll(
256                                            countByC_C_N_D(
257                                                    session, companyId, classNameIds, name, realName,
258                                                    description, params4));
259                            }
260    
261                            return groupIds.size();
262                    }
263                    catch (Exception e) {
264                            throw new SystemException(e);
265                    }
266                    finally {
267                            closeSession(session);
268                    }
269            }
270    
271            @Override
272            public List<Group> findByLiveGroups() throws SystemException {
273                    Session session = null;
274    
275                    try {
276                            session = openSession();
277    
278                            String sql = CustomSQLUtil.get(FIND_BY_LIVE_GROUPS);
279    
280                            SQLQuery q = session.createSQLQuery(sql);
281    
282                            q.addEntity("Group_", GroupImpl.class);
283    
284                            return q.list(true);
285                    }
286                    catch (Exception e) {
287                            throw new SystemException(e);
288                    }
289                    finally {
290                            closeSession(session);
291                    }
292            }
293    
294            @Override
295            public List<Group> findByNoLayouts(
296                            long classNameId, boolean privateLayout, int start, int end)
297                    throws SystemException {
298    
299                    Session session = null;
300    
301                    try {
302                            session = openSession();
303    
304                            String sql = CustomSQLUtil.get(FIND_BY_NO_LAYOUTS);
305    
306                            SQLQuery q = session.createSQLQuery(sql);
307    
308                            q.addEntity("Group_", GroupImpl.class);
309    
310                            QueryPos qPos = QueryPos.getInstance(q);
311    
312                            qPos.add(classNameId);
313                            qPos.add(privateLayout);
314    
315                            return q.list(true);
316                    }
317                    catch (Exception e) {
318                            throw new SystemException(e);
319                    }
320                    finally {
321                            closeSession(session);
322                    }
323            }
324    
325            @Override
326            public List<Group> findByNullFriendlyURL() throws SystemException {
327                    Session session = null;
328    
329                    try {
330                            session = openSession();
331    
332                            String sql = CustomSQLUtil.get(FIND_BY_NULL_FRIENDLY_URL);
333    
334                            SQLQuery q = session.createSQLQuery(sql);
335    
336                            q.addEntity("Group_", GroupImpl.class);
337    
338                            return q.list(true);
339                    }
340                    catch (Exception e) {
341                            throw new SystemException(e);
342                    }
343                    finally {
344                            closeSession(session);
345                    }
346            }
347    
348            @Override
349            public List<Group> findBySystem(long companyId) throws SystemException {
350                    Session session = null;
351    
352                    try {
353                            session = openSession();
354    
355                            String sql = CustomSQLUtil.get(FIND_BY_SYSTEM);
356    
357                            SQLQuery q = session.createSQLQuery(sql);
358    
359                            q.addEntity("Group_", GroupImpl.class);
360    
361                            QueryPos qPos = QueryPos.getInstance(q);
362    
363                            qPos.add(companyId);
364    
365                            return q.list(true);
366                    }
367                    catch (Exception e) {
368                            throw new SystemException(e);
369                    }
370                    finally {
371                            closeSession(session);
372                    }
373            }
374    
375            @Override
376            public List<Group> findByCompanyId(
377                            long companyId, LinkedHashMap<String, Object> params, int start,
378                            int end, OrderByComparator obc)
379                    throws SystemException {
380    
381                    if (params == null) {
382                            params = _emptyLinkedHashMap;
383                    }
384    
385                    LinkedHashMap<String, Object> params1 = params;
386    
387                    LinkedHashMap<String, Object> params2 = null;
388    
389                    LinkedHashMap<String, Object> params3 = null;
390    
391                    LinkedHashMap<String, Object> params4 = null;
392    
393                    Long userId = (Long)params.get("usersGroups");
394                    boolean inherit = GetterUtil.getBoolean(params.get("inherit"), true);
395    
396                    boolean doUnion = Validator.isNotNull(userId) && inherit;
397    
398                    if (doUnion) {
399                            params2 = new LinkedHashMap<String, Object>(params1);
400    
401                            params2.remove("usersGroups");
402                            params2.put("groupOrg", userId);
403    
404                            params3 = new LinkedHashMap<String, Object>(params1);
405    
406                            params3.remove("usersGroups");
407                            params3.put("groupsOrgs", userId);
408    
409                            params4 = new LinkedHashMap<String, Object>(params1);
410    
411                            params4.remove("usersGroups");
412                            params4.put("groupsUserGroups", userId);
413                    }
414    
415                    String sql = null;
416    
417                    String sqlKey = _buildSQLKey(
418                            params1, params2, params3, params4, obc, doUnion);
419    
420                    sql = _findByCompanyIdSQLCache.get(sqlKey);
421    
422                    if (sql == null) {
423                            String findByC_C_SQL = CustomSQLUtil.get(FIND_BY_C_C);
424    
425                            if (params.get("active") == Boolean.TRUE) {
426                                    findByC_C_SQL = StringUtil.replace(
427                                            findByC_C_SQL, "(Group_.liveGroupId = 0) AND",
428                                            StringPool.BLANK);
429                            }
430    
431                            findByC_C_SQL = StringUtil.replace(
432                                    findByC_C_SQL, "Group_.classNameId = ?",
433                                    "Group_.classNameId = ".concat(
434                                            StringUtil.merge(
435                                                    _getGroupOrganizationClassNameIds(),
436                                                    " OR Group_.classNameId = ")));
437                            findByC_C_SQL = replaceOrderBy(findByC_C_SQL, obc);
438    
439                            StringBundler sb = new StringBundler();
440    
441                            sb.append("(");
442                            sb.append(replaceJoinAndWhere(findByC_C_SQL, params1));
443                            sb.append(")");
444    
445                            if (doUnion) {
446                                    sb.append(" UNION (");
447                                    sb.append(replaceJoinAndWhere(findByC_C_SQL, params2));
448                                    sb.append(") UNION (");
449                                    sb.append(replaceJoinAndWhere(findByC_C_SQL, params3));
450                                    sb.append(") UNION (");
451                                    sb.append(replaceJoinAndWhere(findByC_C_SQL, params4));
452                                    sb.append(")");
453                            }
454    
455                            if (obc != null) {
456                                    sb.append(" ORDER BY ");
457                                    sb.append(obc.toString());
458                            }
459    
460                            sql = sb.toString();
461    
462                            _findByCompanyIdSQLCache.put(sqlKey, sql);
463                    }
464    
465                    Session session = null;
466    
467                    try {
468                            session = openSession();
469    
470                            SQLQuery q = session.createSQLQuery(sql);
471    
472                            q.addScalar("groupId", Type.LONG);
473    
474                            QueryPos qPos = QueryPos.getInstance(q);
475    
476                            setJoin(qPos, params1);
477    
478                            qPos.add(companyId);
479    
480                            if (doUnion) {
481                                    setJoin(qPos, params2);
482    
483                                    qPos.add(companyId);
484    
485                                    setJoin(qPos, params3);
486    
487                                    qPos.add(companyId);
488    
489                                    setJoin(qPos, params4);
490    
491                                    qPos.add(companyId);
492                            }
493    
494                            List<Long> groupIds = (List<Long>)QueryUtil.list(
495                                    q, getDialect(), start, end);
496    
497                            List<Group> groups = new ArrayList<Group>(groupIds.size());
498    
499                            for (Long groupId : groupIds) {
500                                    Group group = GroupUtil.findByPrimaryKey(groupId);
501    
502                                    groups.add(group);
503                            }
504    
505                            return groups;
506                    }
507                    catch (Exception e) {
508                            throw new SystemException(e);
509                    }
510                    finally {
511                            closeSession(session);
512                    }
513            }
514    
515            @Override
516            public Group findByC_N(long companyId, String name)
517                    throws NoSuchGroupException, SystemException {
518    
519                    name = StringUtil.lowerCase(name);
520    
521                    Session session = null;
522    
523                    try {
524                            session = openSession();
525    
526                            String sql = CustomSQLUtil.get(FIND_BY_C_N);
527    
528                            SQLQuery q = session.createSQLQuery(sql);
529    
530                            q.addEntity("Group_", GroupImpl.class);
531    
532                            QueryPos qPos = QueryPos.getInstance(q);
533    
534                            qPos.add(companyId);
535                            qPos.add(name);
536    
537                            List<Group> groups = q.list();
538    
539                            if (!groups.isEmpty()) {
540                                    return groups.get(0);
541                            }
542                    }
543                    catch (Exception e) {
544                            throw new SystemException(e);
545                    }
546                    finally {
547                            closeSession(session);
548                    }
549    
550                    StringBundler sb = new StringBundler(5);
551    
552                    sb.append("No Group exists with the key {companyId=");
553                    sb.append(companyId);
554                    sb.append(", name=");
555                    sb.append(name);
556                    sb.append("}");
557    
558                    throw new NoSuchGroupException(sb.toString());
559            }
560    
561            @Override
562            public List<Group> findByC_N_D(
563                            long companyId, String name, String realName, String description,
564                            LinkedHashMap<String, Object> params, int start, int end,
565                            OrderByComparator obc)
566                    throws SystemException {
567    
568                    return findByC_C_N_D(
569                            companyId, _getGroupOrganizationClassNameIds(), name, realName,
570                            description, params, start, end, obc);
571            }
572    
573            @Override
574            public List<Group> findByC_C_N_D(
575                            long companyId, long[] classNameIds, String name, String realName,
576                            String description, LinkedHashMap<String, Object> params, int start,
577                            int end, OrderByComparator obc)
578                    throws SystemException {
579    
580                    name = StringUtil.lowerCase(name);
581                    description = StringUtil.lowerCase(description);
582    
583                    if (params == null) {
584                            params = _emptyLinkedHashMap;
585                    }
586    
587                    LinkedHashMap<String, Object> params1 = params;
588    
589                    LinkedHashMap<String, Object> params2 = null;
590    
591                    LinkedHashMap<String, Object> params3 = null;
592    
593                    LinkedHashMap<String, Object> params4 = null;
594    
595                    Long userId = (Long)params.get("usersGroups");
596                    boolean inherit = GetterUtil.getBoolean(params.get("inherit"), true);
597    
598                    boolean doUnion = Validator.isNotNull(userId) && inherit;
599    
600                    if (doUnion) {
601                            params2 = new LinkedHashMap<String, Object>(params1);
602    
603                            params2.remove("usersGroups");
604                            params2.put("groupOrg", userId);
605    
606                            params3 = new LinkedHashMap<String, Object>(params1);
607    
608                            params3.remove("usersGroups");
609                            params3.put("groupsOrgs", userId);
610    
611                            params4 = new LinkedHashMap<String, Object>(params1);
612    
613                            params4.remove("usersGroups");
614                            params4.put("groupsUserGroups", userId);
615                    }
616    
617                    String sql = null;
618    
619                    if (classNameIds == _getGroupOrganizationClassNameIds()) {
620                            String sqlKey = _buildSQLKey(
621                                    params1, params2, params3, params4, obc, doUnion);
622    
623                            sql = _findByC_C_N_DSQLCache.get(sqlKey);
624                    }
625    
626                    if (sql == null) {
627                            String findByC_N_D_SQL = CustomSQLUtil.get(FIND_BY_C_N_D);
628    
629                            if (classNameIds == null) {
630                                    findByC_N_D_SQL = StringUtil.replace(
631                                            findByC_N_D_SQL, "AND (Group_.classNameId = ?)",
632                                            StringPool.BLANK);
633                            }
634                            else {
635                                    findByC_N_D_SQL = StringUtil.replace(
636                                            findByC_N_D_SQL, "Group_.classNameId = ?",
637                                            "Group_.classNameId = ".concat(
638                                                    StringUtil.merge(
639                                                            classNameIds, " OR Group_.classNameId = ")));
640                            }
641    
642                            findByC_N_D_SQL = replaceOrderBy(findByC_N_D_SQL, obc);
643    
644                            StringBundler sb = new StringBundler();
645    
646                            sb.append("(");
647                            sb.append(replaceJoinAndWhere(findByC_N_D_SQL, params1));
648                            sb.append(")");
649    
650                            if (doUnion) {
651                                    sb.append(" UNION (");
652                                    sb.append(replaceJoinAndWhere(findByC_N_D_SQL, params2));
653                                    sb.append(") UNION (");
654                                    sb.append(replaceJoinAndWhere(findByC_N_D_SQL, params3));
655                                    sb.append(") UNION (");
656                                    sb.append(replaceJoinAndWhere(findByC_N_D_SQL, params4));
657                                    sb.append(")");
658                            }
659    
660                            if (obc != null) {
661                                    sb.append(" ORDER BY ");
662                                    sb.append(obc.toString());
663                            }
664    
665                            sql = sb.toString();
666    
667                            if (classNameIds == _getGroupOrganizationClassNameIds()) {
668                                    String sqlKey = _buildSQLKey(
669                                            params1, params2, params3, params4, obc, doUnion);
670    
671                                    _findByC_C_N_DSQLCache.put(sqlKey, sql);
672                            }
673                    }
674    
675                    Session session = null;
676    
677                    try {
678                            session = openSession();
679    
680                            SQLQuery q = session.createSQLQuery(sql);
681    
682                            q.addScalar("groupId", Type.LONG);
683    
684                            QueryPos qPos = QueryPos.getInstance(q);
685    
686                            setJoin(qPos, params1);
687    
688                            qPos.add(companyId);
689                            qPos.add(name);
690                            qPos.add(realName);
691                            qPos.add(name);
692                            qPos.add(description);
693                            qPos.add(description);
694    
695                            if (doUnion) {
696                                    setJoin(qPos, params2);
697    
698                                    qPos.add(companyId);
699                                    qPos.add(name);
700                                    qPos.add(realName);
701                                    qPos.add(name);
702                                    qPos.add(description);
703                                    qPos.add(description);
704    
705                                    setJoin(qPos, params3);
706    
707                                    qPos.add(companyId);
708                                    qPos.add(name);
709                                    qPos.add(realName);
710                                    qPos.add(name);
711                                    qPos.add(description);
712                                    qPos.add(description);
713    
714                                    setJoin(qPos, params4);
715    
716                                    qPos.add(companyId);
717                                    qPos.add(name);
718                                    qPos.add(realName);
719                                    qPos.add(name);
720                                    qPos.add(description);
721                                    qPos.add(description);
722                            }
723    
724                            List<Long> groupIds = (List<Long>)QueryUtil.list(
725                                    q, getDialect(), start, end);
726    
727                            List<Group> groups = new ArrayList<Group>(groupIds.size());
728    
729                            for (Long groupId : groupIds) {
730                                    Group group = GroupUtil.findByPrimaryKey(groupId);
731    
732                                    groups.add(group);
733                            }
734    
735                            return groups;
736                    }
737                    catch (Exception e) {
738                            throw new SystemException(e);
739                    }
740                    finally {
741                            closeSession(session);
742                    }
743            }
744    
745            protected int countByGroupId(
746                            Session session, long groupId, LinkedHashMap<String, Object> params)
747                    throws Exception {
748    
749                    String sql = CustomSQLUtil.get(COUNT_BY_GROUP_ID);
750    
751                    sql = replaceJoinAndWhere(sql, params);
752    
753                    SQLQuery q = session.createSQLQuery(sql);
754    
755                    q.addScalar(COUNT_COLUMN_NAME, Type.LONG);
756    
757                    QueryPos qPos = QueryPos.getInstance(q);
758    
759                    setJoin(qPos, params);
760    
761                    qPos.add(groupId);
762    
763                    Iterator<Long> itr = q.iterate();
764    
765                    if (itr.hasNext()) {
766                            Long count = itr.next();
767    
768                            if (count != null) {
769                                    return count.intValue();
770                            }
771                    }
772    
773                    return 0;
774            }
775    
776            protected List<Long> countByC_C_N_D(
777                            Session session, long companyId, long[] classNameIds, String name,
778                            String realName, String description,
779                            LinkedHashMap<String, Object> params)
780                    throws Exception {
781    
782                    String sql = CustomSQLUtil.get(COUNT_BY_C_N_D);
783    
784                    if (classNameIds == null) {
785                            sql = StringUtil.replace(
786                                    sql, "AND (Group_.classNameId = ?)", StringPool.BLANK);
787                    }
788                    else {
789                            sql = StringUtil.replace(
790                                    sql, "Group_.classNameId = ?",
791                                    "Group_.classNameId = ".concat(
792                                            StringUtil.merge(
793                                                    classNameIds, " OR Group_.classNameId = ")));
794                    }
795    
796                    sql = replaceJoinAndWhere(sql, params);
797    
798                    SQLQuery q = session.createSQLQuery(sql);
799    
800                    q.addScalar("groupId", Type.LONG);
801    
802                    QueryPos qPos = QueryPos.getInstance(q);
803    
804                    setJoin(qPos, params);
805    
806                    qPos.add(companyId);
807                    qPos.add(name);
808                    qPos.add(realName);
809                    qPos.add(name);
810                    qPos.add(description);
811                    qPos.add(description);
812    
813                    return q.list(true);
814            }
815    
816            protected String getJoin(LinkedHashMap<String, Object> params) {
817                    if ((params == null) || params.isEmpty()) {
818                            return StringPool.BLANK;
819                    }
820    
821                    StringBundler sb = new StringBundler(params.size());
822    
823                    for (Map.Entry<String, Object> entry : params.entrySet()) {
824                            String key = entry.getKey();
825                            Object value = entry.getValue();
826    
827                            if (Validator.isNull(value)) {
828                                    continue;
829                            }
830    
831                            if (key.equals("rolePermissions") &&
832                                    (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6)) {
833    
834                                    List<Object> values = (List<Object>)value;
835    
836                                    String name = (String)values.get(0);
837    
838                                    if (ResourceBlockLocalServiceUtil.isSupported(name)) {
839                                            key = "rolePermissions_6_block";
840                                    }
841                                    else {
842                                            key = "rolePermissions_6";
843                                    }
844                            }
845    
846                            Map<String, String> joinMap = _getJoinMap();
847    
848                            String joinValue = joinMap.get(key);
849    
850                            if (Validator.isNotNull(joinValue)) {
851                                    sb.append(joinValue);
852                            }
853                    }
854    
855                    return sb.toString();
856            }
857    
858            protected String getWhere(LinkedHashMap<String, Object> params) {
859                    if ((params == null) || params.isEmpty()) {
860                            return StringPool.BLANK;
861                    }
862    
863                    StringBundler sb = new StringBundler(params.size());
864    
865                    for (Map.Entry<String, Object> entry : params.entrySet()) {
866                            String key = entry.getKey();
867    
868                            if (key.equals("types")) {
869                                    List<Integer> types = (List<Integer>)entry.getValue();
870    
871                                    if (!types.isEmpty()) {
872                                            sb.append("(");
873    
874                                            for (int i = 0; i < types.size(); i++) {
875                                                    sb.append("(Group_.type_ = ?) ");
876    
877                                                    if ((i + 1) < types.size()) {
878                                                            sb.append("OR ");
879                                                    }
880                                            }
881    
882                                            sb.append(") AND ");
883                                    }
884                            }
885                            else {
886                                    if (key.equals("rolePermissions") &&
887                                            (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6)) {
888    
889                                            List<Object> values = (List<Object>)entry.getValue();
890    
891                                            String name = (String)values.get(0);
892    
893                                            if (ResourceBlockLocalServiceUtil.isSupported(name)) {
894                                                    key = "rolePermissions_6_block";
895                                            }
896                                            else {
897                                                    key = "rolePermissions_6";
898                                            }
899                                    }
900    
901                                    Map<String, String> whereMap = _getWhereMap();
902    
903                                    String whereValue = whereMap.get(key);
904    
905                                    if (Validator.isNotNull(whereValue)) {
906                                            sb.append(whereValue);
907                                    }
908                            }
909                    }
910    
911                    return sb.toString();
912            }
913    
914            protected String replaceJoinAndWhere(
915                    String sql, LinkedHashMap<String, Object> params) {
916    
917                    if (params.isEmpty()) {
918                            return StringUtil.replace(
919                                    sql,
920                                    new String[] {
921                                            "[$JOIN$]", "[$WHERE$]"
922                                    },
923                                    new String[] {
924                                            StringPool.BLANK, StringPool.BLANK
925                                    });
926                    }
927    
928                    String cacheKey = _getCacheKey(sql, params);
929    
930                    String resultSQL = _replaceJoinAndWhereSQLCache.get(cacheKey);
931    
932                    if (resultSQL == null) {
933                            sql = StringUtil.replace(sql, "[$JOIN$]", getJoin(params));
934    
935                            resultSQL = StringUtil.replace(sql, "[$WHERE$]", getWhere(params));
936    
937                            _replaceJoinAndWhereSQLCache.put(cacheKey, resultSQL);
938                    }
939    
940                    return resultSQL;
941            }
942    
943            protected String replaceOrderBy(String sql, OrderByComparator obc) {
944                    if (obc instanceof GroupNameComparator) {
945                            sql = StringUtil.replace(
946                                    sql, "Group_.name AS groupName",
947                                    "REPLACE(Group_.name, '" +
948                                            GroupLocalServiceImpl.ORGANIZATION_NAME_SUFFIX +
949                                                    "', '') AS groupName");
950                    }
951    
952                    return sql;
953            }
954    
955            protected void setJoin(QueryPos qPos, LinkedHashMap<String, Object> params)
956                    throws Exception {
957    
958                    if (params == null) {
959                            return;
960                    }
961    
962                    for (Map.Entry<String, Object> entry : params.entrySet()) {
963                            String key = entry.getKey();
964    
965                            if (key.equals("active") || key.equals("layoutSet") ||
966                                    key.equals("site")) {
967    
968                                    Boolean value = (Boolean)entry.getValue();
969    
970                                    qPos.add(value);
971                            }
972                            else if (key.equals("pageCount")) {
973                            }
974                            else if (key.equals("rolePermissions")) {
975                                    List<Object> values = (List<Object>)entry.getValue();
976    
977                                    String name = (String)values.get(0);
978                                    Integer scope = (Integer)values.get(1);
979                                    String actionId = (String)values.get(2);
980                                    Long roleId = (Long)values.get(3);
981    
982                                    ResourceAction resourceAction =
983                                            ResourceActionLocalServiceUtil.getResourceAction(
984                                                    name, actionId);
985    
986                                    if ((PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) &&
987                                            ResourceBlockLocalServiceUtil.isSupported(name)) {
988    
989                                            // Scope is assumed to always be group
990    
991                                            qPos.add(name);
992                                            qPos.add(roleId);
993                                            qPos.add(resourceAction.getBitwiseValue());
994                                    }
995                                    else {
996                                            qPos.add(name);
997                                            qPos.add(scope);
998                                            qPos.add(roleId);
999                                            qPos.add(resourceAction.getBitwiseValue());
1000                                    }
1001                            }
1002                            else if (key.equals("types")) {
1003                                    List<Integer> values = (List<Integer>)entry.getValue();
1004    
1005                                    for (int i = 0; i < values.size(); i++) {
1006                                            Integer value = values.get(i);
1007    
1008                                            qPos.add(value);
1009                                    }
1010                            }
1011                            else if (key.equals("userGroupRole")) {
1012                                    List<Long> values = (List<Long>)entry.getValue();
1013    
1014                                    Long userId = values.get(0);
1015                                    Long roleId = values.get(1);
1016    
1017                                    qPos.add(userId);
1018                                    qPos.add(roleId);
1019                            }
1020                            else {
1021                                    Object value = entry.getValue();
1022    
1023                                    if (value instanceof Integer) {
1024                                            Integer valueInteger = (Integer)value;
1025    
1026                                            if (Validator.isNotNull(valueInteger)) {
1027                                                    qPos.add(valueInteger);
1028                                            }
1029                                    }
1030                                    else if (value instanceof Long) {
1031                                            Long valueLong = (Long)value;
1032    
1033                                            if (Validator.isNotNull(valueLong)) {
1034                                                    qPos.add(valueLong);
1035                                            }
1036                                    }
1037                                    else if (value instanceof String) {
1038                                            String valueString = (String)value;
1039    
1040                                            if (Validator.isNotNull(valueString)) {
1041                                                    qPos.add(valueString);
1042                                            }
1043                                    }
1044                            }
1045                    }
1046            }
1047    
1048            private String _buildSQLKey(
1049                    LinkedHashMap<String, Object> param1,
1050                    LinkedHashMap<String, Object> param2,
1051                    LinkedHashMap<String, Object> param3,
1052                    LinkedHashMap<String, Object> param4, OrderByComparator obc,
1053                    boolean doUnion) {
1054    
1055                    StringBundler sb = null;
1056    
1057                    if (doUnion) {
1058                            sb = new StringBundler(
1059                                    param1.size() + param2.size() + param3.size() + param4.size() +
1060                                            1);
1061    
1062                            for (String key : param1.keySet()) {
1063                                    sb.append(key);
1064                            }
1065    
1066                            for (String key : param2.keySet()) {
1067                                    sb.append(key);
1068                            }
1069    
1070                            for (String key : param3.keySet()) {
1071                                    sb.append(key);
1072                            }
1073    
1074                            for (String key : param4.keySet()) {
1075                                    sb.append(key);
1076                            }
1077                    }
1078                    else {
1079                            sb = new StringBundler(param1.size() + 1);
1080    
1081                            for (String key : param1.keySet()) {
1082                                    sb.append(key);
1083                            }
1084                    }
1085    
1086                    sb.append(obc.getOrderBy());
1087    
1088                    return sb.toString();
1089            }
1090    
1091            private String _getCacheKey(
1092                    String sql, LinkedHashMap<String, Object> params) {
1093    
1094                    StringBundler sb = new StringBundler(params.size() + 1);
1095    
1096                    sb.append(sql);
1097    
1098                    for (Map.Entry<String, Object> entry : params.entrySet()) {
1099                            String key = entry.getKey();
1100    
1101                            if (key.equals("rolePermissions") &&
1102                                    (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6)) {
1103    
1104                                    List<Object> values = (List<Object>)entry.getValue();
1105    
1106                                    String name = (String)values.get(0);
1107    
1108                                    if (ResourceBlockLocalServiceUtil.isSupported(name)) {
1109                                            key = "rolePermissions_6_block";
1110                                    }
1111                                    else {
1112                                            key = "rolePermissions_6";
1113                                    }
1114                            }
1115    
1116                            sb.append(key);
1117                    }
1118    
1119                    return sb.toString();
1120            }
1121    
1122            private String _getCondition(String join) {
1123                    if (Validator.isNotNull(join)) {
1124                            int pos = join.indexOf("WHERE");
1125    
1126                            if (pos != -1) {
1127                                    join = join.substring(pos + 5, join.length()).concat(" AND ");
1128                            }
1129                            else {
1130                                    join = StringPool.BLANK;
1131                            }
1132                    }
1133    
1134                    return join;
1135            }
1136    
1137            private long[] _getGroupOrganizationClassNameIds() {
1138                    if (_groupOrganizationClassNameIds == null) {
1139                            _groupOrganizationClassNameIds = new long[] {
1140                                    ClassNameLocalServiceUtil.getClassNameId(Group.class),
1141                                    ClassNameLocalServiceUtil.getClassNameId(Organization.class)
1142                            };
1143                    }
1144    
1145                    return _groupOrganizationClassNameIds;
1146            }
1147    
1148            private Map<String, String> _getJoinMap() {
1149                    if (_joinMap != null) {
1150                            return _joinMap;
1151                    }
1152    
1153                    Map<String, String> joinMap = new HashMap<String, String>();
1154    
1155                    joinMap.put("active", _removeWhere(CustomSQLUtil.get(JOIN_BY_ACTIVE)));
1156                    joinMap.put(
1157                            "groupOrg", _removeWhere(CustomSQLUtil.get(JOIN_BY_GROUP_ORG)));
1158                    joinMap.put(
1159                            "groupsOrgs", _removeWhere(CustomSQLUtil.get(JOIN_BY_GROUPS_ORGS)));
1160                    joinMap.put(
1161                            "groupsRoles",
1162                            _removeWhere(CustomSQLUtil.get(JOIN_BY_GROUPS_ROLES)));
1163                    joinMap.put(
1164                            "groupsUserGroups",
1165                            _removeWhere(CustomSQLUtil.get(JOIN_BY_GROUPS_USER_GROUPS)));
1166                    joinMap.put(
1167                            "layoutSet", _removeWhere(CustomSQLUtil.get(JOIN_BY_LAYOUT_SET)));
1168                    joinMap.put(
1169                            "pageCount", _removeWhere(CustomSQLUtil.get(JOIN_BY_PAGE_COUNT)));
1170                    joinMap.put(
1171                            "rolePermissions",
1172                            _removeWhere(CustomSQLUtil.get(JOIN_BY_ROLE_PERMISSIONS)));
1173                    joinMap.put(
1174                            "rolePermissions_6",
1175                            _removeWhere(CustomSQLUtil.get(JOIN_BY_ROLE_RESOURCE_PERMISSIONS)));
1176                    joinMap.put(
1177                            "rolePermissions_6_block",
1178                            _removeWhere(
1179                                    CustomSQLUtil.get(JOIN_BY_ROLE_RESOURCE_TYPE_PERMISSIONS)));
1180                    joinMap.put("site", _removeWhere(CustomSQLUtil.get(JOIN_BY_SITE)));
1181                    joinMap.put("type", _removeWhere(CustomSQLUtil.get(JOIN_BY_TYPE)));
1182                    joinMap.put(
1183                            "userGroupRole",
1184                            _removeWhere(CustomSQLUtil.get(JOIN_BY_USER_GROUP_ROLE)));
1185                    joinMap.put(
1186                            "usersGroups",
1187                            _removeWhere(CustomSQLUtil.get(JOIN_BY_USERS_GROUPS)));
1188    
1189                    _joinMap = joinMap;
1190    
1191                    return _joinMap;
1192            }
1193    
1194            private Map<String, String> _getWhereMap() {
1195                    if (_whereMap != null) {
1196                            return _whereMap;
1197                    }
1198    
1199                    Map<String, String> whereMap = new HashMap<String, String>();
1200    
1201                    whereMap.put(
1202                            "active", _getCondition(CustomSQLUtil.get(JOIN_BY_ACTIVE)));
1203                    whereMap.put(
1204                            "creatorUserId",
1205                            _getCondition(CustomSQLUtil.get(JOIN_BY_CREATOR_USER_ID)));
1206                    whereMap.put(
1207                            "groupOrg", _getCondition(CustomSQLUtil.get(JOIN_BY_GROUP_ORG)));
1208                    whereMap.put(
1209                            "groupsOrgs",
1210                            _getCondition(CustomSQLUtil.get(JOIN_BY_GROUPS_ORGS)));
1211                    whereMap.put(
1212                            "groupsRoles",
1213                            _getCondition(CustomSQLUtil.get(JOIN_BY_GROUPS_ROLES)));
1214                    whereMap.put(
1215                            "groupsUserGroups",
1216                            _getCondition(CustomSQLUtil.get(JOIN_BY_GROUPS_USER_GROUPS)));
1217                    whereMap.put(
1218                            "layoutSet", _getCondition(CustomSQLUtil.get(JOIN_BY_LAYOUT_SET)));
1219                    whereMap.put(
1220                            "pageCount", _getCondition(CustomSQLUtil.get(JOIN_BY_PAGE_COUNT)));
1221                    whereMap.put(
1222                            "rolePermissions",
1223                            _getCondition(CustomSQLUtil.get(JOIN_BY_ROLE_PERMISSIONS)));
1224                    whereMap.put(
1225                            "rolePermissions_6",
1226                            _getCondition(
1227                                    CustomSQLUtil.get(JOIN_BY_ROLE_RESOURCE_PERMISSIONS)));
1228                    whereMap.put(
1229                            "rolePermissions_6_block",
1230                            _getCondition(
1231                                    CustomSQLUtil.get(JOIN_BY_ROLE_RESOURCE_TYPE_PERMISSIONS)));
1232                    whereMap.put("site", _getCondition(CustomSQLUtil.get(JOIN_BY_SITE)));
1233                    whereMap.put("type", _getCondition(CustomSQLUtil.get(JOIN_BY_TYPE)));
1234                    whereMap.put(
1235                            "userGroupRole",
1236                            _getCondition(CustomSQLUtil.get(JOIN_BY_USER_GROUP_ROLE)));
1237                    whereMap.put(
1238                            "usersGroups",
1239                            _getCondition(CustomSQLUtil.get(JOIN_BY_USERS_GROUPS)));
1240    
1241                    _whereMap = whereMap;
1242    
1243                    return _whereMap;
1244            }
1245    
1246            private String _removeWhere(String join) {
1247                    if (Validator.isNotNull(join)) {
1248                            int pos = join.indexOf("WHERE");
1249    
1250                            if (pos != -1) {
1251                                    join = join.substring(0, pos);
1252                            }
1253                    }
1254    
1255                    return join;
1256            }
1257    
1258            private LinkedHashMap<String, Object> _emptyLinkedHashMap =
1259                    new LinkedHashMap<String, Object>(0);
1260            private Map<String, String> _findByC_C_N_DSQLCache =
1261                    new ConcurrentHashMap<String, String>();
1262            private Map<String, String> _findByCompanyIdSQLCache =
1263                    new ConcurrentHashMap<String, String>();
1264            private volatile long[] _groupOrganizationClassNameIds;
1265            private volatile Map<String, String> _joinMap;
1266            private Map<String, String> _replaceJoinAndWhereSQLCache =
1267                    new ConcurrentHashMap<String, String>();
1268            private volatile Map<String, String> _whereMap;
1269    
1270    }