ProjectStorageProvider.java 33.6 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 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
/*
 * 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.ProjectFilter
 *  com.adobe.cq.projects.api.ProjectMemberRole
 *  com.adobe.granite.workflow.WorkflowException
 *  com.adobe.granite.workflow.WorkflowSession
 *  com.adobe.granite.workflow.exec.Workflow
 *  com.day.cq.commons.jcr.JcrUtil
 *  com.day.cq.wcm.api.PageManager
 *  com.day.cq.wcm.api.PageManagerFactory
 *  com.day.cq.wcm.api.Template
 *  javax.jcr.Binary
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.Property
 *  javax.jcr.PropertyIterator
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.Value
 *  javax.jcr.ValueFactory
 *  javax.jcr.Workspace
 *  javax.jcr.query.QueryManager
 *  javax.jcr.query.QueryResult
 *  javax.jcr.query.qom.And
 *  javax.jcr.query.qom.Column
 *  javax.jcr.query.qom.Comparison
 *  javax.jcr.query.qom.Constraint
 *  javax.jcr.query.qom.DescendantNode
 *  javax.jcr.query.qom.DynamicOperand
 *  javax.jcr.query.qom.Literal
 *  javax.jcr.query.qom.Or
 *  javax.jcr.query.qom.Ordering
 *  javax.jcr.query.qom.PropertyValue
 *  javax.jcr.query.qom.QueryObjectModel
 *  javax.jcr.query.qom.QueryObjectModelFactory
 *  javax.jcr.query.qom.Selector
 *  javax.jcr.query.qom.Source
 *  javax.jcr.query.qom.StaticOperand
 *  org.apache.commons.lang3.StringUtils
 *  org.apache.felix.scr.annotations.Activate
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.jackrabbit.api.security.user.Group
 *  org.apache.jackrabbit.commons.JcrUtils
 *  org.apache.sling.api.adapter.AdapterManager
 *  org.apache.sling.api.resource.LoginException
 *  org.apache.sling.api.resource.ModifiableValueMap
 *  org.apache.sling.api.resource.PersistenceException
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceResolverFactory
 *  org.apache.sling.api.resource.ResourceUtil
 *  org.apache.sling.jcr.api.SlingRepository
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.projects.impl;

import com.adobe.cq.projects.api.Project;
import com.adobe.cq.projects.api.ProjectException;
import com.adobe.cq.projects.api.ProjectFilter;
import com.adobe.cq.projects.api.ProjectMemberRole;
import com.adobe.cq.projects.impl.ProjectImpl;
import com.adobe.cq.projects.impl.team.Team;
import com.adobe.cq.projects.impl.team.TeamException;
import com.adobe.cq.projects.impl.team.TeamManager;
import com.adobe.cq.projects.impl.team.TeamManagerFactory;
import com.adobe.cq.projects.impl.util.ProjectUtils;
import com.adobe.granite.workflow.WorkflowException;
import com.adobe.granite.workflow.WorkflowSession;
import com.adobe.granite.workflow.exec.Workflow;
import com.day.cq.commons.jcr.JcrUtil;
import com.day.cq.wcm.api.PageManager;
import com.day.cq.wcm.api.PageManagerFactory;
import com.day.cq.wcm.api.Template;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.jcr.Binary;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.jcr.Workspace;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import javax.jcr.query.qom.And;
import javax.jcr.query.qom.Column;
import javax.jcr.query.qom.Comparison;
import javax.jcr.query.qom.Constraint;
import javax.jcr.query.qom.DescendantNode;
import javax.jcr.query.qom.DynamicOperand;
import javax.jcr.query.qom.Literal;
import javax.jcr.query.qom.Or;
import javax.jcr.query.qom.Ordering;
import javax.jcr.query.qom.PropertyValue;
import javax.jcr.query.qom.QueryObjectModel;
import javax.jcr.query.qom.QueryObjectModelFactory;
import javax.jcr.query.qom.Selector;
import javax.jcr.query.qom.Source;
import javax.jcr.query.qom.StaticOperand;
import org.apache.commons.lang3.StringUtils;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.sling.api.adapter.AdapterManager;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ModifiableValueMap;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.jcr.api.SlingRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(metatype=0, immediate=1, label="Project Management Storage Implementation", description="Stores project data")
@Service(value={ProjectStorageProvider.class})
public class ProjectStorageProvider {
    public static final Logger LOGGER = LoggerFactory.getLogger(ProjectStorageProvider.class);
    public static final String DEFAULT_DAM_PATH = "/content/dam/projects";
    public static final String DEFAULT_ROOT_PATH = "/content/projects";
    @org.apache.felix.scr.annotations.Property(value={"/content/projects"}, label="Project Storage Root Path", description="Indicates where in the repository project data will be stored", propertyPrivate=1)
    public static final String OSGI_PROPERTY_ROOTPATH = "projectstorage.rootpath";
    public static final long MAX_CHILD_NODES = 1000;
    public static final String SLING_FOLDER_TYPE = "sling:OrderedFolder";
    public static final String NODE_NAME_LINKS = "links";
    private static final String CQ_PROJECT_MIXIN = "cq:Project";
    private static final String PROJECT_NODE_TYPE = "nt:unstructured";
    private static final Object LOCK = new Object();
    @Reference
    protected SlingRepository repository;
    @Reference
    protected TeamManagerFactory teamManagerFactory;
    @Reference
    protected ResourceResolverFactory resourceResolverFactory;
    @Reference
    protected AdapterManager adapterManager;
    @Reference
    protected PageManagerFactory pageManagerFactory = null;
    private String projectHomePath;

    @Activate
    public void activate(Map<String, Object> properties) {
        this.projectHomePath = (String)properties.get("projectstorage.rootpath");
    }

    public void deleteProject(Project project, boolean deleteProjectGroups, boolean deleteAssetFolder, boolean terminateProjectWorkflows) {
        Session jcrSession = null;
        if (project == null) {
            throw new ProjectException("No project specified to delete");
        }
        String projectTitle = project.getTitle();
        try {
            Resource assetFolder;
            Node assetFolderNode;
            Node projectNode = (Node)project.adaptTo(Node.class);
            jcrSession = projectNode.getSession();
            if (deleteAssetFolder && (assetFolder = project.getAssetFolder()) != null && !ResourceUtil.isNonExistingResource((Resource)assetFolder) && (assetFolderNode = (Node)assetFolder.adaptTo(Node.class)) != null) {
                assetFolderNode.remove();
            }
            if (terminateProjectWorkflows) {
                this.terminateRunningWorkflows(projectNode);
            }
            if (deleteProjectGroups) {
                this.deleteProjectGroups(jcrSession, project);
            }
            projectNode.remove();
            jcrSession.save();
        }
        catch (RepositoryException e) {
            if (jcrSession != null) {
                try {
                    jcrSession.refresh(false);
                }
                catch (RepositoryException e1) {
                    LOGGER.debug("Unable to refresh session", (Throwable)e1);
                }
            }
            throw new ProjectException("Unable to delete project " + projectTitle + " for user " + jcrSession.getUserID(), (Throwable)e);
        }
    }

    private void terminateRunningWorkflows(Node projectNode) throws RepositoryException {
        Node workFolderNode;
        String workFolder = null;
        Property workFolderProperty = null;
        Node jcrContentNode = projectNode.getNode("jcr:content");
        try {
            if (jcrContentNode != null) {
                workFolderProperty = jcrContentNode.getProperty("work.folder");
            }
        }
        catch (RepositoryException re) {
            LOGGER.debug("jcr:content/work.folder property not found for project {}", (Object)projectNode.getPath());
        }
        if (workFolderProperty != null) {
            workFolder = workFolderProperty.getString();
        }
        if (StringUtils.isBlank((CharSequence)workFolder)) {
            workFolder = "work";
        }
        if (jcrContentNode.hasNode(workFolder) && (workFolderNode = jcrContentNode.getNode(workFolder)) != null) {
            WorkflowSession wfSession = (WorkflowSession)this.adapterManager.getAdapter((Object)projectNode.getSession(), WorkflowSession.class);
            NodeIterator allWork = workFolderNode.getNodes();
            while (allWork.hasNext()) {
                Node workRef = allWork.nextNode();
                String workflowId = ProjectUtils.getStringProperty(workRef, "workflow.id");
                if (workflowId == null) continue;
                try {
                    Workflow workflow = wfSession.getWorkflow(workflowId);
                    if (workflow != null) {
                        if (!workflow.isActive()) continue;
                        wfSession.terminateWorkflow(workflow);
                        continue;
                    }
                    LOGGER.debug("workflow instance not found for id {}", (Object)workflowId);
                }
                catch (WorkflowException e) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Unable to terminate the workflow instance {}", (Object)workflowId, (Object)e);
                        continue;
                    }
                    LOGGER.warn("Unable to terminate the workflow instance {} cause: {}", new Object[]{workflowId, e.getMessage()});
                }
            }
        }
    }

    private void deleteProjectGroups(Session session, Project project) {
        Template template = (Template)project.adaptTo(Template.class);
        Resource projectResource = (Resource)project.adaptTo(Resource.class);
        String projectPath = projectResource.getPath();
        try {
            TeamManager teamManager = this.teamManagerFactory.createTeamManager(session, template);
            if (projectPath != null) {
                Team projectTeam = teamManager.getTeam(project);
                if (projectTeam == null) {
                    throw new ProjectException("Failed to load team for project " + projectPath + ". No groups deleted");
                }
                String teamPath = projectTeam.getTeamPath();
                Map<String, ProjectMemberRole> teamRoles = teamManager.getRoles();
                for (ProjectMemberRole role : teamRoles.values()) {
                    Group roleGroup = projectTeam.getGroup(role);
                    if (roleGroup != null) {
                        LOGGER.debug("removing group {}", (Object)roleGroup.getID());
                        roleGroup.remove();
                        continue;
                    }
                    LOGGER.debug("no group found for role {} {}", (Object)role.getDisplayName(), (Object)role.getId());
                }
                Node teamNode = session.getNode(teamPath);
                NodeIterator childNodes = teamNode.getNodes();
                boolean canRemove = true;
                while (childNodes.hasNext()) {
                    Node childNode = childNodes.nextNode();
                    if ("rep:policy".equals(childNode.getName())) continue;
                    canRemove = false;
                    break;
                }
                if (canRemove) {
                    teamNode.remove();
                }
            } else {
                LOGGER.info("Failed to load team for project {}. No groups deleted", (Object)projectPath);
            }
        }
        catch (RepositoryException e) {
            LOGGER.error("Failed to delete Project groups for project {}", (Object)projectResource.getParent(), (Object)e);
        }
        catch (TeamException e) {
            LOGGER.error("Failed to delete Project groups for project {}", (Object)projectResource.getParent(), (Object)e);
        }
    }

    public Iterator<Project> getProjects(ResourceResolver resourceResolver, ProjectFilter filter, int startIndex, int limit) {
        ArrayList<Project> projects = new ArrayList<Project>();
        try {
            Session userSession = (Session)resourceResolver.adaptTo(Session.class);
            ValueFactory valueFactory = userSession.getValueFactory();
            String rootPath = this.getProjectHome();
            QueryManager qm = userSession.getWorkspace().getQueryManager();
            QueryObjectModelFactory qf = qm.getQOMFactory();
            Selector selectorSource = qf.selector("cq:Project", "projects");
            DescendantNode queryConstraint = qf.descendantNode(selectorSource.getSelectorName(), this.getProjectHome());
            if (filter != null) {
                if (filter.getActive() != null) {
                    queryConstraint = qf.and((Constraint)queryConstraint, (Constraint)qf.comparison((DynamicOperand)qf.propertyValue(selectorSource.getSelectorName(), "jcr:content/active"), "jcr.operator.equal.to", (StaticOperand)qf.literal(valueFactory.createValue(filter.getActive().booleanValue()))));
                }
                if (filter.getProjectTemplates() != null) {
                    Comparison templatesConstraint = null;
                    for (String templatePath : filter.getProjectTemplates()) {
                        Comparison c = qf.comparison((DynamicOperand)qf.propertyValue(selectorSource.getSelectorName(), "jcr:content/cq:template"), "jcr.operator.equal.to", (StaticOperand)qf.literal(valueFactory.createValue(templatePath)));
                        if (templatesConstraint == null) {
                            templatesConstraint = c;
                            continue;
                        }
                        templatesConstraint = qf.or((Constraint)templatesConstraint, (Constraint)c);
                    }
                    queryConstraint = qf.and((Constraint)queryConstraint, (Constraint)templatesConstraint);
                }
            }
            QueryObjectModel query = qf.createQuery((Source)selectorSource, (Constraint)queryConstraint, null, null);
            if (startIndex > 0) {
                query.setOffset((long)startIndex);
            }
            if (limit > 0) {
                query.setLimit((long)limit);
            }
            QueryResult queryResult = query.execute();
            NodeIterator nodeIterator = queryResult.getNodes();
            while (nodeIterator.hasNext()) {
                Node projectNode = nodeIterator.nextNode();
                Project project = this.getProject(userSession, resourceResolver, projectNode);
                if (project == null) continue;
                projects.add(project);
            }
        }
        catch (RepositoryException e) {
            throw new ProjectException("Unable to retrieve projects", (Throwable)e);
        }
        return projects.iterator();
    }

    public Project resolveProject(Resource resource) {
        while (resource != null && !ResourceUtil.isNonExistingResource((Resource)resource)) {
            if (resource.isResourceType("cq/gui/components/projects/admin/card/projectcard")) {
                return this.getProject(resource);
            }
            resource = resource.getParent();
        }
        return null;
    }

    public Project getProject(Resource resource) {
        if (resource != null) {
            ResourceResolver resourceResolver = resource.getResourceResolver();
            Session userSession = (Session)resourceResolver.adaptTo(Session.class);
            Node projectNode = (Node)resource.adaptTo(Node.class);
            return this.getProject(userSession, resourceResolver, projectNode);
        }
        return null;
    }

    private Project getProject(Session userSession, ResourceResolver resourceResolver, Node projectNode) {
        ProjectImpl project = null;
        try {
            Resource resource = resourceResolver.resolve(projectNode.getPath());
            if (resource == null || ResourceUtil.isNonExistingResource((Resource)resource) || !resource.isResourceType("cq/gui/components/projects/admin/card/projectcard")) {
                return null;
            }
            project = new ProjectImpl(resource, null);
            Template projectTemplate = (Template)project.adaptTo(Template.class);
            if (projectTemplate == null) {
                LOGGER.warn("Unable to resolve the template for the project {}", (Object)projectNode.getPath());
                return null;
            }
            TeamManager teamManager = this.teamManagerFactory.createTeamManager(userSession, projectTemplate);
            project.setTeamManager(teamManager);
            PropertyIterator propertyIterator = projectNode.getProperties();
            while (propertyIterator.hasNext()) {
                Property property = propertyIterator.nextProperty();
                String name = property.getName();
                if (name.startsWith("jcr")) continue;
                if (name.startsWith("jcr:title")) {
                    project.setTitle(property.getString());
                    continue;
                }
                if (!name.startsWith("jcr:description")) continue;
                project.setDescription(property.getString());
            }
        }
        catch (RepositoryException e) {
            LOGGER.error("Unable to resolve project node", (Throwable)e);
        }
        return project;
    }

    private Template getTemplate(String templatePath, ResourceResolver resourceResolver) {
        PageManager pm = this.pageManagerFactory.getPageManager(resourceResolver);
        return pm.getTemplate(templatePath);
    }

    public Project createProject(String parentPath, String nodeName, String title, String templatePath, ResourceResolver resourceResolver) {
        return this.createProject(parentPath, nodeName, title, templatePath, resourceResolver, null, null, null);
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public Project createProject(String parentPath, String nodeName, String title, String templatePath, ResourceResolver resourceResolver, String description, String[] teamMemberUserIds, String[] teamMemberRoleIds) {
        ProjectImpl project;
        LOGGER.debug("Entering synchronized block");
        Object object = LOCK;
        synchronized (object) {
            Session userSession = (Session)resourceResolver.adaptTo(Session.class);
            try {
                Resource content;
                userSession.refresh(true);
                String name = null;
                if (StringUtils.isBlank((CharSequence)nodeName) && StringUtils.isBlank((CharSequence)title)) {
                    throw new IllegalArgumentException("The project title and name can't be both null.");
                }
                name = StringUtils.isBlank((CharSequence)nodeName) ? title : nodeName;
                name = JcrUtil.createValidName((String)name, (String[])JcrUtil.STANDARD_LABEL_CHAR_MAPPING, (String)"");
                Node projectNode = this.createProjectNode(name, parentPath, resourceResolver);
                Template projectTemplate = this.getTemplate(templatePath, resourceResolver);
                if (projectTemplate == null) {
                    throw new ProjectException("Unable to create a project with no template");
                }
                Resource template = (Resource)projectTemplate.adaptTo(Resource.class);
                Node tNode = (Node)projectTemplate.adaptTo(Node.class);
                try {
                    Node contentNode;
                    if (template != null && template.getChild("jcr:content") != null) {
                        contentNode = JcrUtil.copy((Node)tNode.getNode("jcr:content"), (Node)projectNode, (String)null);
                        if (tNode.hasProperty("coverUrl")) {
                            contentNode.setProperty("coverUrl", tNode.getProperty("coverUrl").getString());
                        }
                    } else {
                        contentNode = projectNode.addNode("jcr:content", "nt:unstructured");
                    }
                    content = resourceResolver.resolve(contentNode.getPath());
                }
                catch (RepositoryException e) {
                    throw new ProjectException("Unable to copy project template structure", (Throwable)e);
                }
                ModifiableValueMap contentProperties = (ModifiableValueMap)content.adaptTo(ModifiableValueMap.class);
                if (title != null && !title.equals("")) {
                    contentProperties.put((Object)"jcr:title", (Object)title);
                }
                if (StringUtils.isNotBlank((CharSequence)description)) {
                    contentProperties.put((Object)"jcr:description", (Object)description);
                }
                contentProperties.put((Object)"cq:template", (Object)projectTemplate.getPath());
                contentProperties.put((Object)"sling:resourceType", (Object)"cq/gui/components/projects/admin/card/projectcontent");
                String uniqueProjectName = projectNode.getName();
                Resource damFolder = this.createProjectDamFolder(projectNode, uniqueProjectName, title, resourceResolver);
                contentProperties.put((Object)"damFolderPath", (Object)damFolder.getPath());
                if (tNode.hasNode("damfolders")) {
                    Node damFolderNode = (Node)damFolder.adaptTo(Node.class);
                    Node damfolders = tNode.getNode("damfolders");
                    NodeIterator childNodes = damfolders.getNodes();
                    while (childNodes.hasNext()) {
                        Node damfolder = (Node)childNodes.next();
                        String jcrTitle = "";
                        jcrTitle = damfolder.hasProperty("jcr:title") ? damfolder.getProperty("jcr:title").getString() : damfolder.getName();
                        Resource damFolderResource = this.createDamFolder(damFolderNode, jcrTitle, resourceResolver);
                        ModifiableValueMap props = (ModifiableValueMap)damFolderResource.adaptTo(ModifiableValueMap.class);
                        props.put((Object)"projectPath", (Object)projectNode.getPath());
                    }
                }
                Resource linksNode = this.createLinksNode(content);
                Resource resource = resourceResolver.getResource(projectNode.getPath());
                project = new ProjectImpl(resource, null);
                TeamManager teamManager = this.teamManagerFactory.createTeamManager(userSession, project.adaptTo(Template.class));
                project.setTeamManager(teamManager);
                this.setupProjectTeam(project, teamMemberUserIds, teamMemberRoleIds);
                project.setTitle(title);
                project.setActive(true);
                this.createGadgetsFromTemplate(tNode, project);
                resourceResolver.commit();
                this.setProjectCover(project, userSession, projectTemplate);
                teamManager.applyACLs();
            }
            catch (RepositoryException e) {
                throw new ProjectException("Unable to create the project", (Throwable)e);
            }
            catch (LoginException e) {
                throw new ProjectException("Unable to create resource resolver as user " + userSession.getUserID(), (Throwable)e);
            }
            catch (PersistenceException e) {
                throw new ProjectException("Unable to create the project", (Throwable)e);
            }
            LOGGER.debug("Exiting synchronized block.");
        }
        return project;
    }

    private void setupProjectTeam(ProjectImpl project, String[] teamMemberUserIds, String[] teamMemberRoleIds) {
        try {
            Map<String, String> roleIdToGroups = project.getTeamManager().createProjectGroups(project, teamMemberUserIds, teamMemberRoleIds);
            ModifiableValueMap values = project.adaptTo(ModifiableValueMap.class);
            for (String roleId : roleIdToGroups.keySet()) {
                String groupId = roleIdToGroups.get(roleId);
                values.put((Object)("role_" + roleId), (Object)groupId);
            }
        }
        catch (TeamException e) {
            throw new ProjectException("Failed to update team", (Throwable)e);
        }
    }

    private void setProjectCover(ProjectImpl project, Session userSession, Template projectTemplate) {
        String thumbnailPath = projectTemplate.getThumbnailPath();
        if (StringUtils.isNotEmpty((CharSequence)thumbnailPath)) {
            try {
                Property property;
                String mimeTypeProperty = thumbnailPath + "/" + "jcr:content" + "/" + "jcr:mimeType";
                String dataProperty = thumbnailPath + "/" + "jcr:content" + "/" + "jcr:data";
                Binary thumbnail = null;
                String mimeTypeValue = "image/png";
                if (userSession.propertyExists(dataProperty) && (property = userSession.getProperty(dataProperty)).getType() == 2) {
                    thumbnail = property.getBinary();
                }
                if (userSession.propertyExists(mimeTypeProperty) && (property = userSession.getProperty(mimeTypeProperty)).getType() == 1) {
                    mimeTypeValue = property.getString();
                }
                if (thumbnail != null) {
                    project.setProjectCover(mimeTypeValue, thumbnail.getStream());
                }
            }
            catch (RepositoryException e) {
                LOGGER.error("Could not read file contents: " + projectTemplate.getThumbnailPath(), (Throwable)e);
            }
        }
    }

    private String createUniqueNodeName(ResourceResolver resourceResolver, String projectHome, String name) throws RepositoryException {
        Resource projectHomeResource = resourceResolver.getResource(projectHome);
        Iterator dateFolders = projectHomeResource.listChildren();
        while (dateFolders.hasNext()) {
            Resource dateFolder = (Resource)dateFolders.next();
            Resource childWithSameName = dateFolder.getChild(name);
            if (childWithSameName == null || ResourceUtil.isNonExistingResource((Resource)childWithSameName)) continue;
            return name + System.currentTimeMillis();
        }
        return name;
    }

    private Resource createLinksNode(Resource content) throws PersistenceException {
        HashMap<String, String> props = new HashMap<String, String>();
        props.put("jcr:primaryType", "nt:unstructured");
        return content.getResourceResolver().create(content, "links", props);
    }

    private void createGadgetsFromTemplate(Node template, Project project) {
        try {
            if (template != null && template.hasNode("gadgets")) {
                Resource projectResource = (Resource)project.adaptTo(Resource.class);
                Resource gadgetResource = ProjectUtils.getOrCreateGadgetFolder(projectResource);
                Node gadgetNode = (Node)gadgetResource.adaptTo(Node.class);
                Node templateGadgets = template.getNode("gadgets");
                NodeIterator childNodes = templateGadgets.getNodes();
                while (childNodes.hasNext()) {
                    Node link = (Node)childNodes.next();
                    JcrUtil.copy((Node)link, (Node)gadgetNode, (String)null);
                }
            }
        }
        catch (RepositoryException e) {
            throw new ProjectException("Unable to copy project links from template", (Throwable)e);
        }
        catch (PersistenceException e) {
            throw new ProjectException("Failed to update project gadgets", (Throwable)e);
        }
    }

    private Resource createProjectDamFolder(Node projectNode, String uniqueProjectName, String projectTitle, ResourceResolver resourceResolver) {
        Session session = (Session)resourceResolver.adaptTo(Session.class);
        Resource damFolder = this.getDamFolder(uniqueProjectName, resourceResolver);
        if (damFolder == null) {
            try {
                Node projectDamRoot = session.getNode(this.getDamPath());
                String damFolderPath = projectNode.getPath().substring("/content/projects/".length());
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Creating DAM folder: {}", (Object)uniqueProjectName);
                }
                Node damFolderNode = JcrUtils.getOrCreateByPath((Node)projectDamRoot, (String)damFolderPath, (boolean)false, (String)"sling:OrderedFolder", (String)"sling:OrderedFolder", (boolean)false);
                damFolder = resourceResolver.getResource(damFolderNode.getPath());
                ModifiableValueMap folderProperties = (ModifiableValueMap)damFolder.adaptTo(ModifiableValueMap.class);
                folderProperties.put((Object)"jcr:title", (Object)projectTitle);
                String[] paths = new String[]{projectNode.getPath()};
                folderProperties.put((Object)"projectPath", (Object)paths);
            }
            catch (Exception e) {
                throw new ProjectException("Could not create DAM folder: " + this.getDamPath() + "/" + uniqueProjectName, (Throwable)e);
            }
        }
        return damFolder;
    }

    private Resource createDamFolder(Node parentDamFolder, String title, ResourceResolver resourceResolver) {
        Resource damFolder = null;
        String folderPath = "";
        try {
            String uniqueTitle = JcrUtil.createValidName((String)title);
            folderPath = parentDamFolder.getPath() + "/" + uniqueTitle;
            if (LOGGER.isDebugEnabled()) {
                LOGGER.info("Create DAM folder: " + folderPath);
            }
            Node damFolderNode = JcrUtils.getOrCreateByPath((Node)parentDamFolder, (String)uniqueTitle, (boolean)false, (String)"sling:OrderedFolder", (String)"sling:OrderedFolder", (boolean)false);
            damFolder = resourceResolver.getResource(damFolderNode.getPath());
            ModifiableValueMap folderProperties = (ModifiableValueMap)damFolder.adaptTo(ModifiableValueMap.class);
            folderProperties.put((Object)"jcr:title", (Object)title);
        }
        catch (Exception e) {
            throw new ProjectException("Could not create DAM folder: " + folderPath, (Throwable)e);
        }
        return damFolder;
    }

    private Resource getDamFolder(String title, ResourceResolver resourceResolver) {
        String projectDamPath = this.getDamPath() + "/" + title;
        return resourceResolver.getResource(projectDamPath);
    }

    private Node createProjectNode(String title, String parentPath, ResourceResolver resourceResolver) throws RepositoryException, LoginException {
        Session userSession = (Session)resourceResolver.adaptTo(Session.class);
        Node parentNode = userSession.getNode(parentPath);
        String nodeName = this.createUniqueNodeName(resourceResolver, parentPath, title);
        Node projectNode = JcrUtils.getOrCreateUniqueByPath((Node)parentNode, (String)nodeName, (String)"nt:unstructured");
        projectNode.setProperty("sling:resourceType", "cq/gui/components/projects/admin/card/projectcard");
        projectNode.addMixin("{http://www.jcp.org/jcr/mix/1.0}created");
        projectNode.addMixin("{http://www.jcp.org/jcr/mix/1.0}lastModified");
        projectNode.addMixin("cq:Project");
        return projectNode;
    }

    public String getProjectHome() {
        return this.projectHomePath;
    }

    public String getDamPath() {
        return "/content/dam/projects";
    }

    protected void bindRepository(SlingRepository slingRepository) {
        this.repository = slingRepository;
    }

    protected void unbindRepository(SlingRepository slingRepository) {
        if (this.repository == slingRepository) {
            this.repository = null;
        }
    }

    protected void bindTeamManagerFactory(TeamManagerFactory teamManagerFactory) {
        this.teamManagerFactory = teamManagerFactory;
    }

    protected void unbindTeamManagerFactory(TeamManagerFactory teamManagerFactory) {
        if (this.teamManagerFactory == teamManagerFactory) {
            this.teamManagerFactory = null;
        }
    }

    protected void bindResourceResolverFactory(ResourceResolverFactory resourceResolverFactory) {
        this.resourceResolverFactory = resourceResolverFactory;
    }

    protected void unbindResourceResolverFactory(ResourceResolverFactory resourceResolverFactory) {
        if (this.resourceResolverFactory == resourceResolverFactory) {
            this.resourceResolverFactory = null;
        }
    }

    protected void bindAdapterManager(AdapterManager adapterManager) {
        this.adapterManager = adapterManager;
    }

    protected void unbindAdapterManager(AdapterManager adapterManager) {
        if (this.adapterManager == adapterManager) {
            this.adapterManager = null;
        }
    }

    protected void bindPageManagerFactory(PageManagerFactory pageManagerFactory) {
        this.pageManagerFactory = pageManagerFactory;
    }

    protected void unbindPageManagerFactory(PageManagerFactory pageManagerFactory) {
        if (this.pageManagerFactory == pageManagerFactory) {
            this.pageManagerFactory = null;
        }
    }
}