JcrGraphNode.java 17 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.security.user.UserProperties
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.Workspace
 *  javax.jcr.query.Query
 *  javax.jcr.query.QueryManager
 *  javax.jcr.query.QueryResult
 *  org.apache.jackrabbit.api.JackrabbitSession
 *  org.apache.jackrabbit.api.security.user.Authorizable
 *  org.apache.jackrabbit.api.security.user.UserManager
 *  org.apache.jackrabbit.commons.jackrabbit.authorization.AccessControlUtils
 *  org.apache.jackrabbit.util.ISO9075
 *  org.apache.jackrabbit.util.Text
 *  org.apache.sling.api.resource.Resource
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.granite.socialgraph.impl;

import com.adobe.granite.security.user.UserProperties;
import com.adobe.granite.socialgraph.Direction;
import com.adobe.granite.socialgraph.GraphNode;
import com.adobe.granite.socialgraph.Relationship;
import com.adobe.granite.socialgraph.SocialGraphException;
import com.adobe.granite.socialgraph.impl.AbstractPropertyMap;
import com.adobe.granite.socialgraph.impl.JcrRelationship;
import com.adobe.granite.socialgraph.impl.JcrSocialGraph;
import java.security.Principal;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Workspace;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.jackrabbit.commons.jackrabbit.authorization.AccessControlUtils;
import org.apache.jackrabbit.util.ISO9075;
import org.apache.jackrabbit.util.Text;
import org.apache.sling.api.resource.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/*
 * This class specifies class file version 49.0 but uses Java 6 signatures.  Assumed Java 6.
 */
public class JcrGraphNode
extends AbstractPropertyMap
implements GraphNode {
    private static final Logger log = LoggerFactory.getLogger(JcrGraphNode.class);
    public static String SOCIAL_NODE_NAME = "social";
    public static String RELATIONSHIPS_NODE_NAME = "relationships";
    public static String SOCIAL_NODE_TYPE = "sling:Folder";
    public static String RELATIONSHIPS_NODE_TYPE = "sling:Folder";
    public static String RELATIONSHIP_NODE_TYPE = "nt:unstructured";
    public static String ID_PROPERTY_NAME = "id";
    private final JcrSocialGraph graph;
    private final String authId;
    private final boolean isGroupNode;

    public JcrGraphNode(JcrSocialGraph graph, String path, String authId, boolean isGroupNode) {
        super(path);
        this.graph = graph;
        this.authId = authId;
        this.isGroupNode = isGroupNode;
    }

    @Override
    public String getId() {
        return this.authId == null ? this.path : this.authId;
    }

    @Override
    public Resource getResource() {
        return this.graph.getResource(this.path);
    }

    @Override
    public boolean isVirtual() {
        return false;
    }

    public boolean isGroupNode() {
        return this.isGroupNode;
    }

    @Override
    protected Node getNode(boolean create) {
        if (this.authId == null) {
            log.debug("GraphNodes on non users not supported");
            return null;
        }
        Session session = this.graph.getSession();
        try {
            if (!session.nodeExists(this.path)) {
                return null;
            }
            Node node = session.getNode(this.path);
            Node ret = null;
            if (node.hasNode(SOCIAL_NODE_NAME)) {
                ret = node.getNode(SOCIAL_NODE_NAME);
            } else if (create) {
                try {
                    ret = node.addNode(SOCIAL_NODE_NAME, SOCIAL_NODE_TYPE);
                }
                catch (RepositoryException e) {
                    String msg = String.format("Error while creating social node %s/%s", this.path, SOCIAL_NODE_NAME);
                    log.error(msg);
                    throw new SocialGraphException(msg, (Throwable)e);
                }
            }
            return ret;
        }
        catch (RepositoryException e) {
            log.warn("Unable to read social node", (Throwable)e);
            return null;
        }
    }

    protected Node getRelationshipsNode(boolean create) {
        Node socialNode = this.getNode(create);
        if (socialNode == null) {
            return null;
        }
        try {
            if (socialNode.hasNode(RELATIONSHIPS_NODE_NAME)) {
                return socialNode.getNode(RELATIONSHIPS_NODE_NAME);
            }
            if (create) {
                try {
                    return socialNode.addNode(RELATIONSHIPS_NODE_NAME, RELATIONSHIPS_NODE_TYPE);
                }
                catch (RepositoryException e) {
                    String msg = String.format("Error while creating relationships node %s/%s/%s", this.path, SOCIAL_NODE_NAME, RELATIONSHIPS_NODE_NAME);
                    log.error(msg);
                    throw new SocialGraphException(msg, (Throwable)e);
                }
            }
        }
        catch (RepositoryException e) {
            log.warn("Unable to read relationships node", (Throwable)e);
        }
        return null;
    }

    @Override
    public void delete() {
        Node node = this.getNode(false);
        if (node != null) {
            try {
                node.remove();
            }
            catch (RepositoryException e) {
                log.warn("Error while removing graph node", (Throwable)e);
            }
        }
    }

    @Override
    public /* varargs */ Iterable<Relationship> getRelationships(Direction dir, String ... types) {
        HashMap<String, Relationship> relations = new HashMap<String, Relationship>();
        try {
            switch (dir) {
                case BOTH: {
                    this.fillOutgoingRelationships(relations, types);
                    this.fillIncomingRelationships(relations, types);
                    if (this.authId == null) break;
                    this.graph.fillOutgoingVirtualRelationships(this.authId, relations, types);
                    this.graph.fillIncomingVirtualRelationships(this.authId, relations, types);
                    break;
                }
                case INCOMING: {
                    this.fillIncomingRelationships(relations, types);
                    if (this.authId == null) break;
                    this.graph.fillIncomingVirtualRelationships(this.authId, relations, types);
                    break;
                }
                case OUTGOING: {
                    this.fillOutgoingRelationships(relations, types);
                    if (this.authId == null) break;
                    this.graph.fillOutgoingVirtualRelationships(this.authId, relations, types);
                }
            }
        }
        catch (RepositoryException e) {
            log.error("Error while reading relationships", (Throwable)e);
        }
        return relations.values();
    }

    private void fillIncomingRelationships(Map<String, Relationship> relations, String[] types) throws RepositoryException {
        String escapedId = this.getId().replaceAll("'", "''");
        if (types == null || types.length == 0) {
            StringBuilder queryString = new StringBuilder("/jcr:root/home//").append(SOCIAL_NODE_NAME).append('/').append(RELATIONSHIPS_NODE_NAME).append("//*[@id='").append(escapedId).append("']");
            Query q = this.graph.getSession().getWorkspace().getQueryManager().createQuery(queryString.toString(), "xpath");
            QueryResult res = q.execute();
            NodeIterator iter = res.getNodes();
            while (iter.hasNext()) {
                Node relNode = iter.nextNode();
                String relPath = relNode.getPath();
                String type = Text.getName((String)Text.getRelativeParent((String)relPath, (int)1));
                UserProperties up = this.graph.getUserPropertiesByPath(relPath);
                if (up == null) continue;
                JcrRelationship rel = new JcrRelationship(this.graph, relPath, type, up.getAuthorizableID(), this.getId());
                relations.put(rel.signature(), rel);
            }
        } else {
            for (String type : types) {
                StringBuilder queryString = new StringBuilder("/jcr:root/home//").append(SOCIAL_NODE_NAME).append('/').append(RELATIONSHIPS_NODE_NAME).append('/').append(ISO9075.encode((String)type)).append("//*[@id='").append(escapedId).append("']");
                Query q = this.graph.getSession().getWorkspace().getQueryManager().createQuery(queryString.toString(), "xpath");
                QueryResult res = q.execute();
                NodeIterator iter = res.getNodes();
                while (iter.hasNext()) {
                    Node relNode = iter.nextNode();
                    String relPath = relNode.getPath();
                    UserProperties up = this.graph.getUserPropertiesByPath(relPath);
                    if (up == null) continue;
                    JcrRelationship rel = new JcrRelationship(this.graph, relPath, type, up.getAuthorizableID(), this.getId());
                    relations.put(rel.signature(), rel);
                }
            }
        }
    }

    private /* varargs */ void fillOutgoingRelationships(Map<String, Relationship> relations, String ... types) throws RepositoryException {
        Node rNode = this.getRelationshipsNode(false);
        if (rNode == null) {
            return;
        }
        if (types == null || types.length == 0) {
            NodeIterator iter = rNode.getNodes();
            while (iter.hasNext()) {
                Node typeNode = iter.nextNode();
                String type = typeNode.getName();
                this.fillRelationships(relations, typeNode, type);
            }
        } else {
            for (String type : types) {
                if (!rNode.hasNode(type)) continue;
                Node typeNode = rNode.getNode(type);
                this.fillRelationships(relations, typeNode, type);
            }
        }
    }

    private void fillRelationships(Map<String, Relationship> relations, Node typeNode, String type) throws RepositoryException {
        NodeIterator iter = typeNode.getNodes();
        while (iter.hasNext()) {
            Node relNode = iter.nextNode();
            try {
                String otherId = relNode.getProperty("id").getString();
                JcrRelationship rel = new JcrRelationship(this.graph, relNode.getPath(), type, this.authId, otherId);
                relations.put(rel.signature(), rel);
            }
            catch (RepositoryException e) {
                log.warn("Relationship node has no 'id' property {}", (Object)relNode.getPath());
            }
        }
    }

    @Override
    public Relationship getRelationship(Direction dir, GraphNode node, String type) {
        if (type == null || type.length() == 0) {
            throw new IllegalArgumentException("Type must not be null or empty.");
        }
        switch (dir) {
            case BOTH: {
                throw new IllegalArgumentException("Only incoming or outgoing allowed.");
            }
            case INCOMING: {
                return node.getRelationship(Direction.OUTGOING, this, type);
            }
            case OUTGOING: {
                String typePath = this.path + '/' + SOCIAL_NODE_NAME + '/' + RELATIONSHIPS_NODE_NAME + '/' + type;
                try {
                    if (this.graph.getSession().nodeExists(typePath)) {
                        String otherId = node.getId();
                        Node typeNode = this.graph.getSession().getNode(typePath);
                        NodeIterator iter = typeNode.getNodes();
                        while (iter.hasNext()) {
                            String id;
                            Node relNode = iter.nextNode();
                            if (!relNode.hasProperty(ID_PROPERTY_NAME) || !(id = relNode.getProperty(ID_PROPERTY_NAME).getString()).equals(otherId)) continue;
                            return new JcrRelationship(this.graph, relNode.getPath(), type, this.authId, otherId);
                        }
                    }
                }
                catch (RepositoryException e) {
                    log.warn("Error while reading relationship node", (Throwable)e);
                }
                if (!this.isGroupNode && (!(node instanceof JcrGraphNode) || !((JcrGraphNode)node).isGroupNode())) break;
                return this.graph.getVirtualRelationship(this.authId, node.getId(), type);
            }
        }
        return null;
    }

    @Override
    public Relationship createRelationshipTo(GraphNode other, String type) {
        if (other == null) {
            throw new IllegalArgumentException("Unable to creation relationship. 'other' must not be null.");
        }
        if (type == null) {
            throw new IllegalArgumentException("Unable to creation relationship. 'type' must not be null.");
        }
        if (this.equals(other)) {
            throw new IllegalArgumentException("Unable to creation relationship. self relationships not allowed.");
        }
        Relationship r = this.getRelationship(Direction.OUTGOING, other, type);
        if (r != null && !r.isVirtual()) {
            String msg = String.format("Unable to create relationship of type '%s' from '%s' to '%s'. Already exists.", type, this.authId, other.getId());
            log.error(msg);
            throw new IllegalArgumentException(msg);
        }
        try {
            Node relationshipsNode = this.getRelationshipsNode(true);
            Node relationshipTypesNode = relationshipsNode.hasNode(type) ? relationshipsNode.getNode(type) : relationshipsNode.addNode(type, RELATIONSHIPS_NODE_TYPE);
            String otherId = other.getId();
            NodeIterator iter = relationshipTypesNode.getNodes();
            while (iter.hasNext()) {
                String id;
                Node relNode = iter.nextNode();
                if (!relNode.hasProperty(ID_PROPERTY_NAME) || !(id = relNode.getProperty(ID_PROPERTY_NAME).getString()).equals(otherId)) continue;
                String msg = String.format("Unable to create relationship of type '%s' from '%s' to '%s'. Already exists.", type, this.authId, otherId);
                log.error(msg);
                throw new IllegalArgumentException(msg);
            }
            String nameHint = Text.getName((String)otherId);
            int cnt = 0;
            while (relationshipTypesNode.hasNode(nameHint)) {
                nameHint = Text.getName((String)otherId) + cnt++;
            }
            Node rNode = relationshipTypesNode.addNode(nameHint, RELATIONSHIP_NODE_TYPE);
            JcrRelationship rel = new JcrRelationship(this.graph, rNode.getPath(), type, this.authId, otherId);
            rel.put("jcr:created", (Object)Calendar.getInstance());
            rel.put("jcr:createdBy", (Object)this.graph.getSession().getUserID());
            rel.put(ID_PROPERTY_NAME, (Object)otherId);
            if (otherId.charAt(0) != '/') {
                this.allowRead(rNode, otherId);
            }
            return rel;
        }
        catch (RepositoryException e) {
            log.error("Error while creating relationship", (Throwable)e);
            throw new SocialGraphException("Error while creation relationship", (Throwable)e);
        }
    }

    private void allowRead(Node node, String authId) {
        try {
            Session s = node.getSession();
            if (!(s instanceof JackrabbitSession)) {
                log.warn("Unable to apply ACLs. No Jackrabbit session: " + (Object)s);
                return;
            }
            Authorizable authorizable = ((JackrabbitSession)s).getUserManager().getAuthorizable(authId);
            if (authorizable != null) {
                AccessControlUtils.addAccessControlEntry((Session)s, (String)node.getPath(), (Principal)authorizable.getPrincipal(), (String[])new String[]{"{http://www.jcp.org/jcr/1.0}read"}, (boolean)true);
            }
        }
        catch (Exception e) {
            log.error("Error while applying ACLs", (Throwable)e);
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof GraphNode)) {
            return false;
        }
        GraphNode that = (GraphNode)o;
        if (!this.getId().equals(that.getId())) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        return this.getId().hashCode();
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("JcrGraphNode");
        sb.append("{authId='").append(this.authId).append('\'');
        sb.append(", path='").append(this.path).append('\'');
        sb.append('}');
        return sb.toString();
    }

}