TeamManagerImpl.java 31.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.cq.projects.api.Project
 *  com.adobe.cq.projects.api.ProjectException
 *  com.adobe.cq.projects.api.ProjectMember
 *  com.adobe.cq.projects.api.ProjectMemberRole
 *  com.adobe.granite.security.user.UserManagementService
 *  com.day.cq.commons.jcr.JcrUtil
 *  javax.jcr.Node
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.Value
 *  javax.jcr.ValueFactory
 *  javax.jcr.security.AccessControlManager
 *  javax.jcr.security.AccessControlPolicy
 *  javax.jcr.security.Privilege
 *  org.apache.commons.lang3.StringUtils
 *  org.apache.jackrabbit.api.JackrabbitSession
 *  org.apache.jackrabbit.api.security.JackrabbitAccessControlList
 *  org.apache.jackrabbit.api.security.user.Authorizable
 *  org.apache.jackrabbit.api.security.user.Group
 *  org.apache.jackrabbit.api.security.user.UserManager
 *  org.apache.jackrabbit.commons.jackrabbit.authorization.AccessControlUtils
 *  org.apache.jackrabbit.util.Text
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ValueMap
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.projects.impl.team;

import com.adobe.cq.projects.api.Project;
import com.adobe.cq.projects.api.ProjectException;
import com.adobe.cq.projects.api.ProjectMember;
import com.adobe.cq.projects.api.ProjectMemberRole;
import com.adobe.cq.projects.impl.ProjectImpl;
import com.adobe.cq.projects.impl.ProjectMemberImpl;
import com.adobe.cq.projects.impl.team.DefaultProjectsRoleProvider;
import com.adobe.cq.projects.impl.team.GenericRole;
import com.adobe.cq.projects.impl.team.RoleClass;
import com.adobe.cq.projects.impl.team.Team;
import com.adobe.cq.projects.impl.team.TeamException;
import com.adobe.cq.projects.impl.team.TeamImpl;
import com.adobe.cq.projects.impl.team.TeamManager;
import com.adobe.granite.security.user.UserManagementService;
import com.day.cq.commons.jcr.JcrUtil;
import java.security.Principal;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.jcr.security.AccessControlManager;
import javax.jcr.security.AccessControlPolicy;
import javax.jcr.security.Privilege;
import org.apache.commons.lang3.StringUtils;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.JackrabbitAccessControlList;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.jackrabbit.commons.jackrabbit.authorization.AccessControlUtils;
import org.apache.jackrabbit.util.Text;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TeamManagerImpl
implements TeamManager {
    private static final Logger LOGGER = LoggerFactory.getLogger(TeamManagerImpl.class);
    private static final Object LOCK = new Object();
    private final Map<String, ProjectMemberRole> roles;
    private final UserManager userManager;
    private final UserManagementService userManagementService;
    private final Session session;
    private JackrabbitAccessControlList teamLocationAccessControlList;
    private JackrabbitAccessControlList projectPathAccessControlList;
    private JackrabbitAccessControlList damPathAccessControlList;
    private String groupLocationPath;
    private String projectPath;
    private String projectDAMFolderPath;
    private static final String[] EDITOR_PERMISSIONS = new String[]{"{http://www.jcp.org/jcr/1.0}write", "{http://www.jcp.org/jcr/1.0}nodeTypeManagement"};
    private static final String[] EDITOR_DAM_FOLDER_PERMISSIONS = new String[]{"{http://www.jcp.org/jcr/1.0}removeChildNodes", "{http://www.jcp.org/jcr/1.0}addChildNodes", "{http://www.jcp.org/jcr/1.0}modifyProperties", "crx:replicate"};

    public TeamManagerImpl(Map<String, ProjectMemberRole> roles, Session session, UserManagementService userManagementService) throws RepositoryException {
        this.roles = roles;
        this.userManager = ((JackrabbitSession)session).getUserManager();
        this.session = session;
        this.userManagementService = userManagementService;
    }

    public Collection<ProjectMember> createTeamMemberList(List<String> userIds, List<String> roleIds) throws TeamException {
        return this.createTeamMemberList(userIds.toArray(new String[userIds.size()]), roleIds.toArray(new String[roleIds.size()]));
    }

    protected Collection<ProjectMember> createTeamMemberList(String[] userIds, String[] roleIds) throws TeamException {
        List<ProjectMember> teamMembers = Collections.emptyList();
        boolean containsOwner = false;
        if (userIds != null && roleIds != null) {
            if (userIds.length != roleIds.length) {
                throw new IllegalArgumentException("userIds and roleIds must have the same size.");
            }
            teamMembers = new ArrayList<ProjectMember>(userIds.length);
            for (int i = 0; i < userIds.length; ++i) {
                String userId = userIds[i];
                String roleId = roleIds[i];
                ProjectMemberRole r = this.getRole(roleId);
                if (r == null) {
                    String msg = MessageFormat.format("The role {0} is not available for {1}.", roleId, userId);
                    throw new TeamException(msg);
                }
                if (r.getId().equals(DefaultProjectsRoleProvider.ROLE_OWNER.getId())) {
                    containsOwner = true;
                }
                boolean found = false;
                for (ProjectMember member : teamMembers) {
                    if (!member.getId().equals(userId)) continue;
                    found = true;
                    HashSet<ProjectMemberRole> roles = new HashSet<ProjectMemberRole>();
                    roles.addAll(member.getRoles());
                    roles.add(r);
                    teamMembers.add(new ProjectMemberImpl(userId, roles));
                    teamMembers.remove((Object)member);
                    break;
                }
                if (found) continue;
                teamMembers.add(new ProjectMemberImpl(userId, r));
            }
        }
        if (!containsOwner) {
            throw new TeamException("The team does not contain an owner");
        }
        return teamMembers;
    }

    @Override
    public String getUserId() {
        return this.session.getUserID();
    }

    @Override
    public boolean canApplyTeam(String path) {
        try {
            AccessControlManager accessControlManager = this.session.getAccessControlManager();
            Privilege[] privs = new Privilege[]{accessControlManager.privilegeFromName("{http://www.jcp.org/jcr/1.0}modifyAccessControl")};
            return accessControlManager.hasPrivileges(path, privs);
        }
        catch (RepositoryException e) {
            LOGGER.info("unable to determine if user can apply access to team: {}", (Object)e.getMessage());
            return false;
        }
    }

    public ProjectMemberRole getRole(String id) {
        return this.roles.get(id);
    }

    @Override
    public Map<String, ProjectMemberRole> getRoles() throws TeamException {
        return this.roles;
    }

    public Team getTeam(String id) {
        String groupId = String.format("projects-%s", id);
        try {
            Authorizable auth = this.userManager.getAuthorizable(groupId);
            if (auth == null || !auth.isGroup()) {
                LOGGER.info("Unable to get team {}. No such group {}", new Object[]{id, groupId});
                return null;
            }
            return new TeamImpl(this, id, Text.getRelativeParent((String)auth.getPath(), (int)1));
        }
        catch (RepositoryException e) {
            LOGGER.error("Error while retrieving group {}.", (Object)groupId, (Object)e);
            return null;
        }
    }

    private Set<ProjectMemberRole> getRoles(String teamId, Authorizable auth) throws RepositoryException {
        HashSet<ProjectMemberRole> roles = new HashSet<ProjectMemberRole>();
        String prefix = String.format("projects-%s-", teamId);
        Iterator iter = auth.declaredMemberOf();
        while (iter.hasNext()) {
            ProjectMemberRole r;
            Group grp = (Group)iter.next();
            String grpName = grp.getID();
            if (!grpName.startsWith(prefix) || (r = this.getRole(grpName.substring(prefix.length()))) == null) continue;
            roles.add(r);
        }
        if (roles.isEmpty()) {
            roles.add(this.getRole("observer"));
        }
        return roles;
    }

    protected Group getRoleGroup(UserManager uMgr, TeamImpl team, ProjectMemberRole role) throws RepositoryException {
        if (uMgr == null) {
            uMgr = this.userManager;
        }
        String groupId = null;
        groupId = role == null || role.equals((Object)DefaultProjectsRoleProvider.ROLE_VIEWER) ? String.format("projects-%s", team.getId()) : String.format("projects-%s-%s", team.getId(), role.getId());
        Authorizable auth = uMgr.getAuthorizable(groupId);
        if (auth != null && auth instanceof Group) {
            return (Group)auth;
        }
        return null;
    }

    protected Map<String, ProjectMember> getMembers(TeamImpl team) throws TeamException, RepositoryException {
        return this.getMembers(this.userManager, team);
    }

    private Map<String, ProjectMember> getMembers(UserManager uMgr, TeamImpl team) throws TeamException, RepositoryException {
        TreeMap<String, ProjectMember> members = new TreeMap<String, ProjectMember>();
        Group primaryGroup = this.getRoleGroup(uMgr, team, null);
        if (primaryGroup == null) {
            throw new TeamException("Primary group must exist for team: " + team.getId());
        }
        Iterator iter = primaryGroup.getDeclaredMembers();
        while (iter.hasNext()) {
            Authorizable auth = (Authorizable)iter.next();
            if (auth == null) continue;
            Set<ProjectMemberRole> roles = this.getRoles(team.getId(), auth);
            members.put(auth.getID(), new ProjectMemberImpl(auth.getID(), roles));
        }
        return members;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Override
    public Map<String, String> createProjectGroups(ProjectImpl project, String[] teamMemberUserIds, String[] teamMemberRoleIds) throws TeamException {
        HashMap<String, String> result = new HashMap<String, String>();
        String projectPath = project.getPath();
        if (!this.canApplyTeam(projectPath)) {
            LOGGER.warn("User {} does not have permission to update the team members for project {}", (Object)this.getUserId(), (Object)projectPath);
            throw new ProjectException("Unable to update team members for project " + projectPath);
        }
        LOGGER.debug("Entering synchronized block");
        Object object = LOCK;
        synchronized (object) {
            block19 : {
                try {
                    this.session.refresh(true);
                    UserManager userSessionUserManager = ((JackrabbitSession)this.session).getUserManager();
                    String creatorId = this.session.getUserID();
                    Authorizable creator = userSessionUserManager.getAuthorizable(creatorId);
                    if (creator == null || creator.isGroup()) {
                        throw new TeamException("Unable to create team. no such creator: " + creatorId);
                    }
                    String creatorPath = String.format(this.userManagementService.getGroupRootPath() + "/projects/%s", creatorId);
                    if (!this.session.nodeExists(creatorPath)) {
                        JcrUtil.createPath((String)creatorPath, (String)"rep:AuthorizableFolder", (String)"rep:AuthorizableFolder", (Session)this.session, (boolean)true);
                        AccessControlUtils.addAccessControlEntry((Session)this.session, (String)creatorPath, (Principal)creator.getPrincipal(), (String[])new String[]{"{http://www.jcp.org/jcr/1.0}all"}, (boolean)true);
                    }
                    String teamId = project.getName();
                    String teamName = project.getTitle();
                    String escapedTeamId = StringUtils.replaceChars((String)teamId, (String)"- %/:[]*|\t\r\n", (String)"___________");
                    Group projectAdminsGroup = (Group)userSessionUserManager.getAuthorizable("projects-administrators");
                    Group projectUsersGroup = (Group)userSessionUserManager.getAuthorizable("projects-users");
                    String generatedTeamId = this.generateUniqueTeamId(userSessionUserManager, escapedTeamId);
                    final String groupId = String.format("projects-%s", generatedTeamId);
                    this.groupLocationPath = String.format(this.userManagementService.getGroupRootPath() + "/projects/%s/%s", creatorId, generatedTeamId);
                    Principal p = new Principal(){

                        @Override
                        public String getName() {
                            return groupId;
                        }
                    };
                    Group observerGroup = userSessionUserManager.createGroup(p, this.groupLocationPath);
                    result.put("observer", observerGroup.getID());
                    String displayName = String.format("%s %s", teamName, this.roles.get("observer").getDisplayName());
                    ValueFactory vf = this.session.getValueFactory();
                    Value displayNameValue = vf.createValue(displayName);
                    observerGroup.setProperty("./profile/givenName", displayNameValue);
                    observerGroup.setProperty("./profile/alternateTitle", vf.createValue(DefaultProjectsRoleProvider.ROLE_VIEWER.getDisplayName()));
                    observerGroup.setProperty("jcr:title", vf.createValue(teamName));
                    if (!observerGroup.isMember((Authorizable)projectUsersGroup)) {
                        projectUsersGroup.addMember((Authorizable)observerGroup);
                    }
                    HashMap<String, ArrayList<Authorizable>> roleToAuthorizable = new HashMap<String, ArrayList<Authorizable>>();
                    if (teamMemberUserIds != null) {
                        for (int count = 0; count < teamMemberUserIds.length; ++count) {
                            Authorizable newMember = userSessionUserManager.getAuthorizable(teamMemberUserIds[count]);
                            if (newMember != null) {
                                observerGroup.addMember(newMember);
                                ArrayList<Authorizable> authForRoles = (ArrayList<Authorizable>)roleToAuthorizable.get(teamMemberRoleIds[count]);
                                if (authForRoles == null) {
                                    authForRoles = new ArrayList<Authorizable>();
                                    roleToAuthorizable.put(teamMemberRoleIds[count], authForRoles);
                                }
                                authForRoles.add(newMember);
                                continue;
                            }
                            LOGGER.warn("Unable to lookup user with ID {}.  Skipping adding this user to the project.", (Object)teamMemberUserIds[count]);
                        }
                    }
                    AccessControlManager accessControlManager = this.session.getAccessControlManager();
                    this.teamLocationAccessControlList = AccessControlUtils.getAccessControlList((AccessControlManager)accessControlManager, (String)this.groupLocationPath);
                    this.projectPath = project.getPath();
                    this.projectPathAccessControlList = AccessControlUtils.getAccessControlList((AccessControlManager)accessControlManager, (String)this.projectPath);
                    this.projectDAMFolderPath = project.getAssetFolder().getPath();
                    this.damPathAccessControlList = AccessControlUtils.getAccessControlList((AccessControlManager)accessControlManager, (String)this.projectDAMFolderPath);
                    Privilege[] privileges = TeamManagerImpl.privilegesFromNames(accessControlManager, "{http://www.jcp.org/jcr/1.0}all");
                    this.projectPathAccessControlList.addEntry(projectAdminsGroup.getPrincipal(), privileges, false);
                    this.projectPathAccessControlList.addEntry(projectUsersGroup.getPrincipal(), privileges, false);
                    this.damPathAccessControlList.addEntry(projectAdminsGroup.getPrincipal(), privileges, false);
                    this.damPathAccessControlList.addEntry(projectUsersGroup.getPrincipal(), privileges, false);
                    this.applyObserverAcls(accessControlManager, observerGroup, this.teamLocationAccessControlList, this.projectPathAccessControlList, this.damPathAccessControlList);
                    for (ProjectMemberRole projectMemberRole : this.roles.values()) {
                        if ("observer".equals(projectMemberRole.getId())) continue;
                        if (projectMemberRole instanceof GenericRole) {
                            Group createdGroup = this.createRoleGroupAndAcls(this.session, accessControlManager, userSessionUserManager, (GenericRole)projectMemberRole, generatedTeamId, teamName, this.groupLocationPath, project, this.teamLocationAccessControlList, this.projectPathAccessControlList, this.damPathAccessControlList, (List)roleToAuthorizable.get(projectMemberRole.getId()));
                            result.put(projectMemberRole.getId(), createdGroup.getID());
                            continue;
                        }
                        throw new TeamException("Unpexected role class '" + projectMemberRole.getClass() + "'");
                    }
                    if (creator.isGroup() || !this.session.nodeExists(creator.getPath())) break block19;
                    Node userNode = this.session.getNode(creator.getPath());
                    if (userNode.hasNode("rep:cache")) {
                        LOGGER.debug("Cache found, invalidating!");
                        userNode.getNode("rep:cache").remove();
                        break block19;
                    }
                    LOGGER.debug("No cache found!");
                }
                catch (RepositoryException e) {
                    LOGGER.error("Error while creating team group.", (Throwable)e);
                    throw new TeamException("Error while creating team group", e);
                }
                finally {
                    LOGGER.debug("Exiting synchronized block");
                }
            }
        }
        return result;
    }

    @Override
    public void applyACLs() throws RepositoryException {
        this.session.getAccessControlManager().setPolicy(this.groupLocationPath, (AccessControlPolicy)this.teamLocationAccessControlList);
        this.session.getAccessControlManager().setPolicy(this.projectPath, (AccessControlPolicy)this.projectPathAccessControlList);
        this.session.getAccessControlManager().setPolicy(this.projectDAMFolderPath, (AccessControlPolicy)this.damPathAccessControlList);
    }

    private Group createRoleGroupAndAcls(Session session, AccessControlManager accessControlManager, UserManager userManager, GenericRole projectMemberRole, String teamId, String teamName, String teamGroupPath, ProjectImpl project, JackrabbitAccessControlList teamPathAccessControlList, JackrabbitAccessControlList projectPathAccessControlList, JackrabbitAccessControlList damPathAccessControlList, List<Authorizable> defaultMembers) throws RepositoryException {
        final String groupId = String.format("projects-%s-%s", teamId, projectMemberRole.getId());
        Principal principal = new Principal(){

            @Override
            public String getName() {
                return groupId;
            }
        };
        Group createdGroup = userManager.createGroup(principal, teamGroupPath);
        ValueFactory vf = session.getValueFactory();
        String displayName = String.format("%s %s", teamName, projectMemberRole.getDisplayName());
        Value displayNameValue = vf.createValue(displayName);
        createdGroup.setProperty("./profile/givenName", displayNameValue);
        createdGroup.setProperty("./profile/alternateTitle", vf.createValue(projectMemberRole.getDisplayName()));
        switch (projectMemberRole.getRoleClass()) {
            case editor: {
                this.applyEditorAcls(session, accessControlManager, createdGroup, teamGroupPath, project, projectPathAccessControlList, damPathAccessControlList);
                break;
            }
            case observer: {
                this.applyObserverAcls(accessControlManager, createdGroup, teamPathAccessControlList, projectPathAccessControlList, damPathAccessControlList);
                break;
            }
            case owner: {
                this.applyOwnerAcls(accessControlManager, createdGroup, teamGroupPath, teamPathAccessControlList, projectPathAccessControlList, damPathAccessControlList);
            }
        }
        if (defaultMembers != null) {
            for (Authorizable newMember : defaultMembers) {
                createdGroup.addMember(newMember);
            }
        }
        return createdGroup;
    }

    private boolean applyOwnerAcls(AccessControlManager accessControlManager, Group group, String teamGroupPath, JackrabbitAccessControlList teamPathAccessControlList, JackrabbitAccessControlList projectPathAccessControlList, JackrabbitAccessControlList damPathAccessControlList) throws RepositoryException {
        boolean entryAdded = false;
        String[] OWNER_PERMISSIONS = new String[]{"{http://www.jcp.org/jcr/1.0}all"};
        if (teamPathAccessControlList != null) {
            entryAdded = teamPathAccessControlList.addEntry(group.getPrincipal(), TeamManagerImpl.privilegesFromNames(accessControlManager, OWNER_PERMISSIONS), true) || entryAdded;
        }
        entryAdded = this.applyTeamACLs(accessControlManager, group, OWNER_PERMISSIONS, null, projectPathAccessControlList, damPathAccessControlList) || entryAdded;
        return entryAdded;
    }

    private boolean applyObserverAcls(AccessControlManager accessControlManager, Group group, JackrabbitAccessControlList teamPathAccessControlList, JackrabbitAccessControlList projectPathAccessControlList, JackrabbitAccessControlList damPathAccessControlList) throws RepositoryException {
        boolean entryAdded = false;
        String[] OBSERVER_PERMISSIONS = new String[]{"{http://www.jcp.org/jcr/1.0}read", "{http://www.jcp.org/jcr/1.0}readAccessControl"};
        if (teamPathAccessControlList != null) {
            entryAdded = teamPathAccessControlList.addEntry(group.getPrincipal(), TeamManagerImpl.privilegesFromNames(accessControlManager, "{http://www.jcp.org/jcr/1.0}read"), true) || entryAdded;
        }
        entryAdded = this.applyTeamACLs(accessControlManager, group, OBSERVER_PERMISSIONS, null, projectPathAccessControlList, damPathAccessControlList) || entryAdded;
        return entryAdded;
    }

    private void applyEditorAcls(Session adminSession, AccessControlManager accessControlManager, Group group, String teamPath, ProjectImpl project, JackrabbitAccessControlList projectPathAccessControlList, JackrabbitAccessControlList damPathAccessControlList) throws RepositoryException {
        HashMap<String, Value> globs = new HashMap<String, Value>(1);
        ValueFactory vf = this.session.getValueFactory();
        Value value = vf.createValue("/*");
        globs.put("rep:glob", value);
        this.applyTeamACLs(accessControlManager, group, EDITOR_PERMISSIONS, globs, projectPathAccessControlList, damPathAccessControlList);
    }

    private boolean applyTeamACLs(AccessControlManager accessControlManager, Group group, String[] permissions, Map<String, Value> globs, JackrabbitAccessControlList projectPathAccessControlList, JackrabbitAccessControlList damPathAccessControlList) throws RepositoryException {
        boolean entryAdded = false;
        entryAdded = projectPathAccessControlList.addEntry(group.getPrincipal(), TeamManagerImpl.privilegesFromNames(accessControlManager, permissions), true, globs) || entryAdded;
        entryAdded = damPathAccessControlList.addEntry(group.getPrincipal(), TeamManagerImpl.privilegesFromNames(accessControlManager, permissions), true, null) || entryAdded;
        return entryAdded;
    }

    private String generateUniqueTeamId(UserManager userManager, String escapedTeamId) throws RepositoryException {
        int c = -1;
        do {
            Object[] arrobject = new Object[2];
            arrobject[0] = escapedTeamId;
            arrobject[1] = c < 0 ? "" : String.valueOf(c);
            String generatedTeamId = String.format("%s%s", arrobject);
            String groupId = String.format("projects-%s", generatedTeamId);
            Authorizable authorizable = userManager.getAuthorizable(groupId);
            if (authorizable == null) {
                return generatedTeamId;
            }
            ++c;
        } while (true);
    }

    @Override
    public Collection<ProjectMember> updateRoleGroups(Project project, List<String> userIds, List<String> roleIds) throws TeamException {
        Map<String, String> roleToGroupIdMap = this.getRoleGroupIDs(project);
        Collection<ProjectMember> result = this.createTeamMemberList(userIds, roleIds);
        try {
            UserManager sessionUserManager = ((JackrabbitSession)this.session).getUserManager();
            String observerRoleId = "observer";
            this.adjustMasterProjectGroup(sessionUserManager, roleToGroupIdMap.get(observerRoleId), userIds);
            roleToGroupIdMap.remove(observerRoleId);
            Map<String, Set<String>> projectMembers = this.createRoleToAuthIdMap(userIds, roleIds);
            for (String roleId : roleToGroupIdMap.keySet()) {
                this.adjustGroupMembers(sessionUserManager, roleToGroupIdMap.get(roleId), projectMembers.get(roleId));
            }
        }
        catch (RepositoryException e) {
            throw new TeamException("Failed to update project groups", e);
        }
        return result;
    }

    private Map<String, Set<String>> createRoleToAuthIdMap(List<String> userIds, List<String> roleIds) {
        HashMap<String, Set<String>> result = new HashMap<String, Set<String>>();
        Iterator<String> userIterator = userIds.iterator();
        Iterator<String> roleIterator = roleIds.iterator();
        while (userIterator.hasNext()) {
            String userId = userIterator.next();
            String roleId = roleIterator.next();
            if (!result.containsKey(roleId)) {
                HashSet setOfUserIds = new HashSet();
                result.put(roleId, setOfUserIds);
            }
            result.get(roleId).add(userId);
        }
        return result;
    }

    private void adjustGroupMembers(UserManager userManager, String groupId, Set<String> projectMembers) throws RepositoryException, TeamException {
        if (projectMembers != null) {
            HashSet<String> uniqueUserIds = new HashSet<String>(projectMembers);
            this.adjustGroupMembers(userManager, uniqueUserIds, groupId);
        } else {
            Authorizable observerAuth = userManager.getAuthorizable(groupId);
            if (observerAuth != null && observerAuth.isGroup()) {
                Group group = (Group)observerAuth;
                Iterator declaredMembers = group.getDeclaredMembers();
                while (declaredMembers.hasNext()) {
                    Authorizable member = (Authorizable)declaredMembers.next();
                    group.removeMember(member);
                }
            } else {
                LOGGER.warn("Authorizable {} does not exist", (Object)groupId);
            }
        }
    }

    private void adjustMasterProjectGroup(UserManager userManager, String groupId, List<String> userIds) throws TeamException, RepositoryException {
        if (userIds != null) {
            HashSet<String> uniqueUserIds = new HashSet<String>(userIds);
            this.adjustGroupMembers(userManager, uniqueUserIds, groupId);
        }
    }

    private void adjustGroupMembers(UserManager userManager, Set<String> uniqueUserIds, String groupId) throws RepositoryException, TeamException {
        Authorizable observerAuth = userManager.getAuthorizable(groupId);
        if (observerAuth == null || !observerAuth.isGroup()) {
            throw new TeamException("Authorizable '" + groupId + "' is not a group");
        }
        Group projectGroup = (Group)observerAuth;
        Iterator currentMembers = projectGroup.getDeclaredMembers();
        if (currentMembers != null) {
            while (currentMembers.hasNext()) {
                Authorizable next = (Authorizable)currentMembers.next();
                if (!uniqueUserIds.contains(next.getID())) {
                    LOGGER.debug("----- adding {} to {}", (Object)next.getID(), (Object)groupId);
                    projectGroup.removeMember(next);
                    continue;
                }
                uniqueUserIds.remove(next.getID());
            }
        }
        for (String userIdToAdd : uniqueUserIds) {
            Authorizable auth = userManager.getAuthorizable(userIdToAdd);
            if (auth == null) continue;
            LOGGER.debug("----- adding {} to {}", (Object)userIdToAdd, (Object)groupId);
            projectGroup.addMember(auth);
        }
    }

    private Map<String, String> getRoleGroupIDs(Project project) throws TeamException {
        HashMap<String, String> result = new HashMap<String, String>();
        ValueMap vm = (ValueMap)project.adaptTo(ValueMap.class);
        Map<String, ProjectMemberRole> allRoles = this.getRoles();
        if (allRoles != null && allRoles.values() != null) {
            for (ProjectMemberRole role : allRoles.values()) {
                String roleId = role.getId();
                String groupId = (String)vm.get("role_" + roleId, String.class);
                if (StringUtils.isNotBlank((CharSequence)groupId)) {
                    result.put(roleId, groupId);
                    continue;
                }
                throw new TeamException("Can't find group id for role '" + roleId + "'");
            }
        } else {
            throw new TeamException("No roles found for project '" + project.getTitle() + "'");
        }
        return result;
    }

    @Override
    public Team getTeam(Project project) throws TeamException {
        ValueMap map = (ValueMap)project.adaptTo(ValueMap.class);
        String projectTeamId = (String)map.get("role_observer", String.class);
        if (projectTeamId == null) {
            throw new TeamException("Failed to load team for project " + ((Resource)project.adaptTo(Resource.class)).getPath());
        }
        String teamId = projectTeamId.substring("projects-".length());
        return this.getTeam(teamId);
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public static /* varargs */ Privilege[] privilegesFromNames(AccessControlManager accessControlManager, String ... privilegeNames) throws RepositoryException {
        long start = System.currentTimeMillis();
        try {
            HashSet<Privilege> privileges = new HashSet<Privilege>(privilegeNames.length);
            for (String privName : privilegeNames) {
                privileges.add(accessControlManager.privilegeFromName(privName));
            }
            String[] arr$ = privileges.toArray((T[])new Privilege[privileges.size()]);
            return arr$;
        }
        finally {
            long end = System.currentTimeMillis();
            LOGGER.info("==== Timing for privilegesFromNames: {} for {} number of privileges", (Object)(end - start), (Object)privilegeNames.length);
        }
    }

}