org.apache.jackrabbit.oak.api.Tree - java examples

Here are the examples of the java api org.apache.jackrabbit.oak.api.Tree taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

155 Examples 7

19 View Complete Implementation : CugImporter.java
Copyright Apache License 2.0
Author : apache
// ------------------------------------------< ProtectedPropertyImporter >---
@Override
public boolean handlePropInfo(@NotNull Tree parent, @NotNull PropInfo protectedPropInfo, @NotNull PropertyDefinition def) {
    if (CugUtil.definesCug(parent) && isValid(protectedPropInfo, def) && CugUtil.isSupportedPath(parent.getPath(), supportedPaths)) {
        Set<String> principalNames = new HashSet<>();
        for (TextValue txtValue : protectedPropInfo.getTextValues()) {
            String principalName = txtValue.getString();
            Principal principal = principalManager.getPrincipal(principalName);
            if (principal == null) {
                switch(importBehavior) {
                    case ImportBehavior.IGNORE:
                        log.debug("Ignoring unknown principal with name '{}'.", principalName);
                        break;
                    case ImportBehavior.BESTEFFORT:
                        log.debug("Importing unknown principal '{}'", principalName);
                        principalNames.add(principalName);
                        break;
                    default:
                        // ImportBehavior.ABORT
                        throw new AccessControlException("Unknown principal '" + principalName + "'.");
                }
            } else {
                principalNames.add(principalName);
            }
        }
        parent.setProperty(REP_PRINCIPAL_NAMES, principalNames, Type.STRINGS);
        return true;
    } else {
        return false;
    }
}

19 View Complete Implementation : VersionTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testVersionableWithUnsupportedType() throws Exception {
    Tree versionable = root.getTree("/content");
    Tree vh = checkNotNull(versionManager.getVersionHistory(versionable));
    Tree frozen = vh.getChild("1.0").getChild(JCR_FROZENNODE).getChild("a").getChild("b").getChild("c");
    Tree invalidFrozen = frozen.addChild(REP_CUG_POLICY);
    invalidFrozen.setProperty(JCR_PRIMARYTYPE, NT_REP_CUG_POLICY);
    CugPermissionProvider pp = createCugPermissionProvider(ImmutableSet.of(SUPPORTED_PATH, SUPPORTED_PATH2));
    TreePermission tp = getTreePermission(root, PathUtils.concat(vh.getPath(), "1.0", JCR_FROZENNODE, "a/b/c"), pp);
    TreePermission tpForUnsupportedType = pp.getTreePermission(invalidFrozen, TreeType.VERSION, tp);
    replacedertEquals(TreePermission.NO_RECOURSE, tpForUnsupportedType);
}

19 View Complete Implementation : PrincipalPolicyImporterTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testEndWithInvalidTree() throws Exception {
    init(true, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
    User user = getTestSystemUser();
    Tree policyTree = createPolicyTree(user);
    importer.handlePropInfo(policyTree, mockPropInfo(user.getPrincipal()), mockPropertyDefinition(getJcrName(NT_REP_PRINCIPAL_POLICY)));
    importer.propertiesCompleted(policyTree);
    importer.end(mockTree("/another/path", true));
    // end-call must have removed the policy due to the mismatch
    replacedertFalse(root.getTree(policyTree.getPath()).exists());
}

19 View Complete Implementation : AccessControlManagerLimitedUserTest.java
Copyright Apache License 2.0
Author : apache
@Test(expected = CommitFailedException.clreplaced)
public void testAddEntryTree() throws Exception {
    // grant read-ac access on principal policy
    grant(testPrincipal, systemPrincipalPath, JCR_READ_ACCESS_CONTROL);
    root.commit();
    testRoot.refresh();
    try {
        Tree policyTree = testRoot.getTree(getPolicyPath());
        Tree entry = TreeUtil.addChild(policyTree, "entry", NT_REP_PRINCIPAL_ENTRY);
        entry.setProperty(REP_EFFECTIVE_PATH, TEST_OAK_PATH, Type.PATH);
        entry.setProperty(Constants.REP_PRIVILEGES, ImmutableList.of(JCR_ADD_CHILD_NODES), Type.NAMES);
        testRoot.commit();
    } catch (CommitFailedException e) {
        replacedertEquals(CommitFailedException.ACCESS, e.getType());
        replacedertEquals(3, e.getCode());
        throw e;
    }
}

19 View Complete Implementation : PermissionProviderVersionTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testIsGrantedWithProperty() throws Exception {
    Tree t = getVersionTree(contentPath, true);
    replacedertFalse(permissionProvider.isGranted(t, t.getProperty(JCR_PRIMARYTYPE), Permissions.READ_PROPERTY));
    t = getVersionTree(grandchildPath, false);
    replacedertFalse(permissionProvider.isGranted(t, t.getProperty(JCR_PRIMARYTYPE), Permissions.READ_PROPERTY | Permissions.VERSION_MANAGEMENT));
    t = getVersionTree(TEST_OAK_PATH, true);
    replacedertFalse(permissionProvider.isGranted(t, t.getProperty(JCR_PRIMARYTYPE), Permissions.READ_PROPERTY | Permissions.WRITE));
    t = getVersionTree(grandchildPath, true);
    replacedertTrue(permissionProvider.isGranted(t, t.getProperty(JCR_PRIMARYTYPE), Permissions.READ_PROPERTY));
    t = getVersionTree(TEST_OAK_PATH, false);
    replacedertTrue(permissionProvider.isGranted(t, t.getProperty(JCR_PRIMARYTYPE), Permissions.READ_PROPERTY | Permissions.VERSION_MANAGEMENT));
}

19 View Complete Implementation : PrincipalBasedPermissionProviderTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testGetTreePermission() {
    Tree tree = root.getTree(PathUtils.ROOT_PATH);
    TreePermission tp = permissionProvider.getTreePermission(tree, TreePermission.EMPTY);
    for (String elem : PathUtils.elements(TEST_OAK_PATH)) {
        tree = tree.getChild(elem);
        tp = permissionProvider.getTreePermission(tree, tp);
        replacedertTrue(tp instanceof AbstractTreePermission);
        replacedertSame(TreeType.DEFAULT, ((AbstractTreePermission) tp).getType());
    }
}

19 View Complete Implementation : RestrictionProviderImpl.java
Copyright Apache License 2.0
Author : apache
// ------------------------------------------------< RestrictionProvider >---
@NotNull
@Override
public RestrictionPattern getPattern(String oakPath, @NotNull Tree tree) {
    if (oakPath == null) {
        return RestrictionPattern.EMPTY;
    } else {
        List<RestrictionPattern> patterns = new ArrayList<>(NUMBER_OF_DEFINITIONS);
        PropertyState glob = tree.getProperty(REP_GLOB);
        if (glob != null) {
            patterns.add(GlobPattern.create(oakPath, glob.getValue(Type.STRING)));
        }
        PropertyState ntNames = tree.getProperty(REP_NT_NAMES);
        if (ntNames != null) {
            patterns.add(new NodeTypePattern(ntNames.getValue(Type.NAMES)));
        }
        PropertyState prefixes = tree.getProperty(REP_PREFIXES);
        if (prefixes != null) {
            patterns.add(new PrefixPattern(prefixes.getValue(Type.STRINGS)));
        }
        PropertyState itemNames = tree.getProperty(REP_ITEM_NAMES);
        if (itemNames != null) {
            patterns.add(new ItemNamePattern(itemNames.getValue(Type.NAMES)));
        }
        return CompositePattern.create(patterns);
    }
}

19 View Complete Implementation : CugPermissionProvider.java
Copyright Apache License 2.0
Author : apache
@NotNull
@Override
public TreePermission getTreePermission(@NotNull Tree tree, @NotNull TreePermission parentPermission) {
    if (TreePermission.NO_RECOURSE == parentPermission) {
        throw new IllegalStateException("Attempt to create tree permission for path '" + tree.getPath() + "', which is either not supported or doesn't contain any CUGs.");
    }
    Tree immutableTree = getImmutableTree(tree);
    TreeType type = typeProvider.getType(immutableTree);
    return getTreePermission(immutableTree, type, parentPermission);
}

19 View Complete Implementation : PolicyValidatorLimitedUserTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testAddRestrictionMissingModAcPermission() throws Exception {
    Tree entry = createPolicyEntryTree(root, TEST_OAK_PATH, JCR_READ);
    root.commit();
    testRoot.refresh();
    entry = testRoot.getTree(entry.getPath());
    Tree restrictions = TreeUtil.addChild(entry, REP_RESTRICTIONS, NT_REP_RESTRICTIONS);
    restrictions.setProperty(REP_GLOB, "*/glob/*");
    try {
        testRoot.commit();
        fail("CommitFailedException expected; type ACCESS; code 3");
    } catch (CommitFailedException e) {
        replacedertEquals(CommitFailedException.ACCESS, e.getType());
        replacedertEquals(3, e.getCode());
    }
}

19 View Complete Implementation : PermissionValidator.java
Copyright Apache License 2.0
Author : apache
private void checkPermissions(@NotNull Tree parent, @NotNull PropertyState property, long defaultPermission) throws CommitFailedException {
    if (NodeStateUtils.isHidden(property.getName())) {
        // ignore any hidden properties (except for OAK_CHILD_ORDER which has
        // been covered in "propertyChanged"
        return;
    }
    long toTest = getPermission(parent, property, defaultPermission);
    if (toTest != Permissions.NO_PERMISSION) {
        boolean isGranted;
        if (Permissions.isRepositoryPermission(toTest)) {
            isGranted = permissionProvider.getRepositoryPermission().isGranted(toTest);
        } else {
            isGranted = parentPermission.isGranted(toTest, property);
        }
        if (!isGranted) {
            throw new CommitFailedException(ACCESS, 0, "Access denied");
        }
    }
}

19 View Complete Implementation : CugPermissionProvider.java
Copyright Apache License 2.0
Author : apache
@Override
public boolean isGranted(@NotNull TreeLocation location, long permissions) {
    if (isRead(permissions)) {
        Tree tree = getTreeFromLocation(location);
        if (tree != null) {
            return isGranted(tree, location.getProperty(), permissions);
        }
    }
    return false;
}

19 View Complete Implementation : CugTreePermissionTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testIsInCugSupportedPathWithoutCug() throws Exception {
    Tree node = root.getTree(SUPPORTED_PATH2);
    Tree c1 = TreeUtil.addChild(node, "c1", NT_OAK_UNSTRUCTURED);
    Tree c2 = TreeUtil.addChild(node, "c2", NT_OAK_UNSTRUCTURED);
    String cugPath = c2.getPath();
    createCug(cugPath, getTestGroupPrincipal());
    root.commit();
    replacedertTrue(getCugTreePermission(cugPath).isInCug());
    replacedertFalse(getCugTreePermission(c1.getPath()).isInCug());
}

19 View Complete Implementation : IdentifierManager.java
Copyright Apache License 2.0
Author : apache
/**
 * Return the identifier of a tree.
 *
 * @param tree  a tree
 * @return  identifier of {@code tree}
 */
@NotNull
public static String getIdentifier(Tree tree) {
    PropertyState property = tree.getProperty(JcrConstants.JCR_UUID);
    if (property != null) {
        return property.getValue(Type.STRING);
    } else if (tree.isRoot()) {
        return "/";
    } else {
        String parentId = getIdentifier(tree.getParent());
        return PathUtils.concat(parentId, tree.getName());
    }
}

19 View Complete Implementation : EntryPredicateTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testCreateParentTree() {
    when(pe.appliesTo(PARENT_PATH)).thenReturn(true);
    Tree parentTree = mockTree(PARENT_PATH, true);
    when(tree.exists()).thenReturn(true);
    when(tree.getParent()).thenReturn(parentTree);
    Predicate<PermissionEntry> predicate = EntryPredicate.createParent(tree, Permissions.REMOVE_NODE | Permissions.READ_PROPERTY | Permissions.LOCK_MANAGEMENT);
    predicate.apply(pe);
    verify(pe, never()).matches();
    verify(pe, never()).matches(TREE_PATH);
    verify(pe, never()).matches(PARENT_PATH);
    verify(pe, times(1)).appliesTo(PARENT_PATH);
    verify(pe, times(1)).matches(parentTree, null);
    verify(pe, never()).matches(tree, null);
    verify(pe, never()).getPrivilegeBits();
}

19 View Complete Implementation : LdapLoginTestBase.java
Copyright Apache License 2.0
Author : apache
@Test
public void testSyncCreateUser() throws Exception {
    ContentSession cs = null;
    try {
        cs = login(new SimpleCredentials(USER_ID, USER_PWD.toCharArray()));
        root.refresh();
        Authorizable user = userManager.getAuthorizable(USER_ID);
        replacedertNotNull(user);
        replacedertTrue(user.hasProperty(USER_PROP));
        Tree userTree = cs.getLatestRoot().getTree(user.getPath());
        replacedertFalse(userTree.hasProperty(UserConstants.REP_PreplacedWORD));
        replacedertNull(userManager.getAuthorizable(GROUP_DN));
    } finally {
        if (cs != null) {
            cs.close();
        }
        options.clear();
    }
}

19 View Complete Implementation : NodeTypeImpl.java
Copyright Apache License 2.0
Author : apache
/**
 * Returns the declared child node definitions in their original order.
 *
 * @return declared child node definitions
 */
@Override
@NotNull
public NodeDefinition[] getDeclaredChildNodeDefinitions() {
    Map<Integer, NodeDefinition> definitions = newTreeMap();
    for (Tree child : Iterables.filter(definition.getChildren(), PrimaryTypePredicate.CHILDNODE_DEF_PREDICATE)) {
        definitions.put(getIndex(child), new NodeDefinitionImpl(child, this, mapper));
    }
    return definitions.values().toArray(NO_NODE_DEFINITIONS);
}

19 View Complete Implementation : MockUtility.java
Copyright Apache License 2.0
Author : apache
static Tree mockTree(@NotNull String name, @NotNull String ntName, @NotNull String path, @NotNull String... propertyNames) {
    Tree t = mock(Tree.clreplaced);
    when(t.exists()).thenReturn(true);
    when(t.getName()).thenReturn(name);
    if (ntName != null) {
        when(t.getProperty(JcrConstants.JCR_PRIMARYTYPE)).thenReturn(createPrimaryTypeProperty(ntName));
    }
    when(t.getPath()).thenReturn(path);
    when(t.isRoot()).thenReturn(PathUtils.denotesRoot(path));
    for (String propertyName : propertyNames) {
        when(t.hasProperty(propertyName)).thenReturn(true);
        when(t.getProperty(propertyName)).thenReturn(PropertyStates.createProperty(propertyName, "anyValue"));
    }
    return t;
}

19 View Complete Implementation : CugValidatorTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testMissingMixin() throws Exception {
    Tree cug = TreeUtil.addChild(node, REP_CUG_POLICY, NT_REP_CUG_POLICY);
    cug.setProperty(REP_PRINCIPAL_NAMES, ImmutableList.of(EveryonePrincipal.NAME), Type.STRINGS);
    try {
        root.commit();
        fail();
    } catch (CommitFailedException e) {
        replacedertTrue(e.isAccessControlViolation());
        replacedertEquals(22, e.getCode());
    } finally {
        root.refresh();
    }
}

19 View Complete Implementation : PrincipalPolicyImporterTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testStartChildInfoRepNodeRestriction() throws Exception {
    init(true, ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW);
    User user = getTestSystemUser();
    Tree policyTree = createPolicyTree(user);
    importer.handlePropInfo(policyTree, mockPropInfo(user.getPrincipal()), mockPropertyDefinition(getJcrName(NT_REP_PRINCIPAL_POLICY)));
    importer.start(policyTree);
    importer.startChildInfo(mockNodeInfo("entry", getJcrName(NT_REP_PRINCIPAL_ENTRY)), mockPropInfos(null, PrivilegeConstants.REP_READ_PROPERTIES));
    importer.startChildInfo(mockNodeInfo(getJcrName(REP_RESTRICTIONS), getJcrName(NT_REP_RESTRICTIONS)), mockPropInfos(ImmutableMap.of(getJcrName(REP_NODE_PATH), "/effective/path"), PropertyType.STRING));
    importer.endChildInfo();
    importer.endChildInfo();
    importer.end(policyTree);
    PrincipalPolicyImpl.EntryImpl entry = replacedertPolicy(getAccessControlManager(root).getPolicies(user.getPrincipal()), 1);
    replacedertEquals("/effective/path", entry.getEffectivePath());
}

19 View Complete Implementation : DynamicSyncContextTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testSyncUserIdExistingGroups() throws Exception {
    ExternalUser externalUser = idp.getUser(USER_ID);
    DefaultSyncContext ctx = new DefaultSyncContext(syncConfig, idp, userManager, valueFactory);
    ctx.sync(externalUser);
    ctx.close();
    Authorizable user = userManager.getAuthorizable(externalUser.getId());
    for (ExternalIdenreplacedyRef ref : externalUser.getDeclaredGroups()) {
        Group gr = userManager.getAuthorizable(ref.getId(), Group.clreplaced);
        replacedertTrue(gr.isMember(user));
    }
    syncContext.setForceUserSync(true);
    syncContext.sync(externalUser.getId());
    Authorizable a = userManager.getAuthorizable(USER_ID);
    Tree t = r.getTree(a.getPath());
    replacedertFalse(t.hasProperty(REP_EXTERNAL_PRINCIPAL_NAMES));
    replacedertSyncedMembership(userManager, a, externalUser);
}

19 View Complete Implementation : PrincipalPolicyImporter.java
Copyright Apache License 2.0
Author : apache
@Override
public void end(@NotNull Tree protectedParent) throws RepositoryException {
    checkState(policy != null);
    if (isValidProtectedParent(protectedParent, policy)) {
        getAccessControlManager().setPolicy(policy.getPath(), policy);
    } else {
        log.warn("Protected parent {} does not match path of PrincipalAccessControlList {}.", protectedParent.getPath(), policy.getOakPath());
        getAccessControlManager().removePolicy(policy.getPath(), policy);
    }
    policy = null;
}

19 View Complete Implementation : NodeTypeTemplateImpl.java
Copyright Apache License 2.0
Author : apache
private static void writeItemDefinitions(@NotNull Tree nodeTypeTree, @Nullable List<? extends ItemDefinitionTemplate> itemDefTemplates, @NotNull String nodeName, @NotNull String primaryTypeName) throws RepositoryException {
    // first remove existing
    for (Tree t : filter(nodeTypeTree.getChildren(), new SameNamePredicate(nodeName))) {
        t.remove();
    }
    // now write definitions
    int index = 1;
    if (itemDefTemplates != null) {
        for (ItemDefinitionTemplate template : itemDefTemplates) {
            String name = nodeName(nodeName, index);
            Tree tree = nodeTypeTree.getChild(name);
            if (!tree.exists()) {
                tree = nodeTypeTree.addChild(name);
                tree.setProperty(JCR_PRIMARYTYPE, primaryTypeName, NAME);
            }
            template.writeTo(tree);
            index++;
        }
    }
}

19 View Complete Implementation : NodeTypeImpl.java
Copyright Apache License 2.0
Author : apache
private void addSubtypes(String typeName, Map<String, NodeType> subtypes, Tree root, Map<String, Set<String>> inheritance) {
    Set<String> subnames = inheritance.get(typeName);
    if (subnames != null) {
        for (String subname : subnames) {
            if (!subtypes.containsKey(subname)) {
                Tree tree = root.getChild(subname);
                subtypes.put(subname, new NodeTypeImpl(tree, mapper));
            }
        }
    }
}

19 View Complete Implementation : DynamicSyncContextTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testSyncUserByIdUpdate() throws Exception {
    ExternalIdenreplacedy externalId = idp.listUsers().next();
    Authorizable a = userManager.createUser(externalId.getId(), null);
    a.setProperty(DefaultSyncContext.REP_EXTERNAL_ID, valueFactory.createValue(externalId.getExternalId().getString()));
    syncContext.setForceUserSync(true);
    SyncResult result = syncContext.sync(externalId.getId());
    replacedertEquals(SyncResult.Status.UPDATE, result.getStatus());
    Tree t = r.getTree(a.getPath());
    replacedertTrue(t.hasProperty(REP_EXTERNAL_PRINCIPAL_NAMES));
}

19 View Complete Implementation : AccessControlValidator.java
Copyright Apache License 2.0
Author : apache
private void checkValidRestrictions(@NotNull Tree aceTree) throws CommitFailedException {
    String path;
    Tree aclTree = checkNotNull(aceTree.getParent());
    String aclPath = aclTree.getPath();
    if (REP_REPO_POLICY.equals(Text.getName(aclPath))) {
        path = null;
    } else {
        path = Text.getRelativeParent(aclPath, 1);
    }
    try {
        restrictionProvider.validateRestrictions(path, aceTree);
    } catch (AccessControlException e) {
        throw new CommitFailedException(ACCESS_CONTROL, 1, "Access control violation", e);
    } catch (RepositoryException e) {
        throw new CommitFailedException(OAK, 13, "Internal error", e);
    }
}

19 View Complete Implementation : PermissionValidator.java
Copyright Apache License 2.0
Author : apache
private boolean isImmutableProperty(@NotNull String name, @NotNull Tree parent) {
    // NOTE: we cannot rely on autocreated/protected definition as this
    // doesn't reveal if a given property is expected to be never modified
    // after creation.
    NodeState parentNs = provider.getTreeProvider().asNodeState(parent);
    if (JcrConstants.JCR_UUID.equals(name) && isReferenceable.apply(parentNs)) {
        return true;
    } else {
        return (JCR_CREATED.equals(name) || JCR_CREATEDBY.equals(name)) && isCreated.apply(parentNs);
    }
}

19 View Complete Implementation : PermissionUtil.java
Copyright Apache License 2.0
Author : apache
@Nullable
public static String getPath(@Nullable Tree parentBefore, @Nullable Tree parentAfter) {
    String path = null;
    if (parentBefore != null) {
        path = parentBefore.getPath();
    } else if (parentAfter != null) {
        path = parentAfter.getPath();
    }
    return path;
}

19 View Complete Implementation : ExternalIdentityImporter.java
Copyright Apache License 2.0
Author : apache
/**
 * Prevent 'rep:externalPrincipalNames' properties from being imported with a
 * non-system session.
 * Note: in order to make sure those properties are synchronized again upon
 * the next login, 'rep:lastSynced' property gets removed as well.
 *
 * @param protectedParent The protected parent tree.
 */
@Override
public void propertiesCompleted(@NotNull Tree protectedParent) {
    if (!isSystemSession) {
        if (protectedParent.hasProperty(REP_EXTERNAL_PRINCIPAL_NAMES)) {
            log.debug("Found reserved property {} managed by the system => Removed from imported scope.", REP_EXTERNAL_PRINCIPAL_NAMES);
            protectedParent.removeProperty(REP_EXTERNAL_PRINCIPAL_NAMES);
            // force creation of rep:externalPrincipalNames by removing the
            // rep:lastSynced property as well.
            protectedParent.removeProperty(REP_LAST_SYNCED);
        }
    }
}

19 View Complete Implementation : CugContextTest.java
Copyright Apache License 2.0
Author : apache
@Before
@Override
public void before() throws Exception {
    super.before();
    // add more child nodes
    Tree n = root.getTree(SUPPORTED_PATH);
    createTrees(n, NT_OAK_UNSTRUCTURED, "a", "b", "c");
    createTrees(n, NT_OAK_UNSTRUCTURED, "aa", "bb", "cc");
    // create cugs
    createCug("/content/a", getTestUser().getPrincipal());
    // setup regular acl at /content
    AccessControlManager acMgr = getAccessControlManager(root);
    AccessControlList acl = AccessControlUtils.getAccessControlList(acMgr, "/content");
    acl.addAccessControlEntry(getTestUser().getPrincipal(), privilegesFromNames(PrivilegeConstants.JCR_READ));
    acMgr.setPolicy("/content", acl);
    root.commit();
}

19 View Complete Implementation : SelectorImpl.java
Copyright Apache License 2.0
Author : apache
private boolean evaluateTypeMatch() {
    CachedTree ct = getCachedTree(currentRow.getPath());
    if (!ct.exists()) {
        return false;
    }
    Tree t = ct.getTree();
    LazyValue<Tree> readOnly = ct.getReadOnlyTree();
    String primaryTypeName = TreeUtil.getPrimaryTypeName(t, readOnly);
    if (primaryTypeName != null && primaryTypes.contains(primaryTypeName)) {
        return true;
    }
    for (String mixinName : TreeUtil.getMixinTypeNames(t, readOnly)) {
        if (mixinTypes.contains(mixinName)) {
            return true;
        }
    }
    // no matches found
    return false;
}

19 View Complete Implementation : PermissionProviderVersionTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testIsGrantedVersionHistoryRemoved() throws Exception {
    String vhPath = getVersionPath(contentPath, true);
    root.getTree(contentPath).remove();
    root.commit();
    permissionProvider.refresh();
    Tree vhTree = root.getTree(vhPath);
    replacedertFalse(vhTree.exists());
    // permissions affected because unable to resolve versionable tree
    replacedertFalse(permissionProvider.isGranted(vhTree, null, Permissions.READ | Permissions.VERSION_MANAGEMENT));
}

19 View Complete Implementation : CugContextTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testDefinesProperty() {
    Tree cugTree = root.getTree(CUG_PATH);
    PropertyState repPrincipalNames = cugTree.getProperty(CugConstants.REP_PRINCIPAL_NAMES);
    replacedertTrue(CugContext.INSTANCE.definesProperty(cugTree, repPrincipalNames));
    replacedertFalse(CugContext.INSTANCE.definesProperty(cugTree, cugTree.getProperty(JcrConstants.JCR_PRIMARYTYPE)));
    for (String path : NO_CUG_PATH) {
        replacedertFalse(path, CugContext.INSTANCE.definesProperty(root.getTree(path), repPrincipalNames));
    }
}

19 View Complete Implementation : CugPermissionProvider.java
Copyright Apache License 2.0
Author : apache
private boolean includesCug(@Nullable Tree tree) {
    if (tree != null) {
        Tree immutableTree = getImmutableTree(tree);
        TreeType type = typeProvider.getType(immutableTree);
        if (isSupportedType(type) && topPaths.hasAny()) {
            return getCugRoot(immutableTree, type) != null;
        }
    }
    return false;
}

19 View Complete Implementation : MembershipWriter.java
Copyright Apache License 2.0
Author : apache
/**
 * Removes the member from the given group.
 *
 * @param groupTree group to remove the member from
 * @param memberContentId member to remove
 * @return {@code true} if the member was removed.
 */
boolean removeMember(@NotNull Tree groupTree, @NotNull String memberContentId) {
    Map<String, String> m = Maps.newHashMapWithExpectedSize(1);
    m.put(memberContentId, "-");
    return removeMembers(groupTree, m).isEmpty();
}

19 View Complete Implementation : PrincipalPolicyImporterTest.java
Copyright Apache License 2.0
Author : apache
@Test(expected = ConstraintViolationException.clreplaced)
public void testStartChildInfoWrongEffectivePathPropertyType() throws Exception {
    init(true, ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING);
    User user = getTestSystemUser();
    Tree policyTree = createPolicyTree(user);
    importer.handlePropInfo(policyTree, mockPropInfo(user.getPrincipal()), mockPropertyDefinition(getJcrName(NT_REP_PRINCIPAL_POLICY)));
    List<PropInfo> propInfos = mockPropInfos(null, PrivilegeConstants.JCR_REMOVE_CHILD_NODES);
    // effective path with wrong type
    TextValue tx = when(mock(TextValue.clreplaced).getString()).thenReturn("/effective/path").getMock();
    PropInfo propInfo = mockPropInfo(getJcrName(REP_EFFECTIVE_PATH));
    when(propInfo.getTextValue()).thenReturn(tx);
    when(propInfo.getType()).thenReturn(PropertyType.STRING);
    propInfos.add(propInfo);
    importer.startChildInfo(mockNodeInfo("entry", getJcrName(NT_REP_PRINCIPAL_ENTRY)), propInfos);
}

19 View Complete Implementation : TokenExternalLoginModuleTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testTokenCreation() throws Exception {
    Credentials creds = createTestCredentials();
    replacedertTrue(credentialsSupport.setAttributes(creds, ImmutableMap.<String, Object>of(".token", "")));
    String expectedUserId = credentialsSupport.getUserId(creds);
    ContentSession cs = login(creds);
    try {
        replacedertEquals(expectedUserId, cs.getAuthInfo().getUserID());
        Map<String, ?> attributes = credentialsSupport.getAttributes(creds);
        String token = attributes.get(".token").toString();
        replacedertFalse(token.isEmpty());
        root.refresh();
        User user = getUserManager(root).getAuthorizable(expectedUserId, User.clreplaced);
        Tree tokenParent = root.getTree(user.getPath()).getChild(".tokens");
        replacedertTrue(tokenParent.exists());
        replacedertEquals(1, tokenParent.getChildrenCount(100));
    } finally {
        cs.close();
    }
}

19 View Complete Implementation : PermissionProviderVersionTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testGetTreePermissionVersionableNodeRemoved() throws Exception {
    String versionPath = getVersionPath(TEST_OAK_PATH, false);
    root.getTree(TEST_OAK_PATH).remove();
    root.commit();
    permissionProvider.refresh();
    Tree tree = getRootProvider().createReadOnlyRoot(root).getTree(PathUtils.ROOT_PATH);
    TreePermission tp = permissionProvider.getTreePermission(tree, TreePermission.EMPTY);
    for (String elem : PathUtils.elements(versionPath)) {
        tree = tree.getChild(elem);
        tp = permissionProvider.getTreePermission(tree, tp);
    }
    replacedertTrue(tp instanceof AbstractTreePermission);
    AbstractTreePermission atp = (AbstractTreePermission) tp;
    replacedertSame(TreeType.VERSION, atp.getType());
    // tree must point to non-existing versionable node and NOT to the version tree
    replacedertNotSame(tree, atp.getTree());
    replacedertFalse(atp.getTree().exists());
    replacedertEquals(TEST_OAK_PATH, atp.getTree().getPath());
}

19 View Complete Implementation : PermissionValidator.java
Copyright Apache License 2.0
Author : apache
@Nullable
private Tree getVersionHistoryTree(@NotNull Tree versionstorageTree) throws CommitFailedException {
    Tree versionHistory = null;
    for (Tree child : versionstorageTree.getChildren()) {
        if (VersionConstants.NT_VERSIONHISTORY.equals(TreeUtil.getPrimaryTypeName(child))) {
            versionHistory = child;
        } else if (isVersionstorageTree(child)) {
            versionHistory = getVersionHistoryTree(child);
        } else {
            throw new CommitFailedException("Misc", 0, "unexpected node");
        }
    }
    return versionHistory;
}

19 View Complete Implementation : NodeDefinitionImpl.java
Copyright Apache License 2.0
Author : apache
@Override
public NodeType[] getRequiredPrimaryTypes() {
    String[] oakNames = getNames(JcrConstants.JCR_REQUIREDPRIMARYTYPES);
    if (oakNames == null) {
        oakNames = new String[] { JcrConstants.NT_BASE };
    }
    NodeType[] types = new NodeType[oakNames.length];
    Tree root = definition.getParent();
    while (!JCR_NODE_TYPES.equals(root.getName())) {
        root = root.getParent();
    }
    for (int i = 0; i < oakNames.length; i++) {
        Tree type = root.getChild(oakNames[i]);
        checkState(type.exists());
        types[i] = new NodeTypeImpl(type, mapper);
    }
    return types;
}

19 View Complete Implementation : ReadablePathsPermissionTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testIsGrantedTree() throws Exception {
    replacedertTrue(permissionProvider.isGranted(getTree(readablePaths.next()), null, Permissions.READ));
    replacedertTrue(permissionProvider.isGranted(getTree(readablePaths.next()), null, Permissions.READ_NODE));
    Tree t = getTree(readablePaths.next());
    replacedertTrue(permissionProvider.isGranted(t, t.getProperty(JCR_PRIMARYTYPE), Permissions.READ_PROPERTY));
    replacedertTrue(permissionProvider.isGranted(getTree(readableChildPaths.next()), null, Permissions.READ));
    replacedertTrue(permissionProvider.isGranted(getTree(readableChildPaths.next()), null, Permissions.READ_NODE));
    t = getTree(readableChildPaths.next());
    replacedertTrue(permissionProvider.isGranted(t, t.getProperty(JCR_PRIMARYTYPE), Permissions.READ_PROPERTY));
}

19 View Complete Implementation : PrincipalBasedAccessControlManager.java
Copyright Apache License 2.0
Author : apache
@Nullable
private AbstractEntry createEffectiveEntry(@NotNull Tree entryTree) throws AccessControlException {
    String principalName = TreeUtil.getString(entryTree.getParent(), AccessControlConstants.REP_PRINCIPAL_NAME);
    Principal principal = principalManager.getPrincipal(principalName);
    if (principal == null || !filter.canHandle(Collections.singleton(principal))) {
        return null;
    }
    String oakPath = Strings.emptyToNull(TreeUtil.getString(entryTree, REP_EFFECTIVE_PATH));
    PrivilegeBits bits = privilegeBitsProvider.getBits(entryTree.getProperty(Constants.REP_PRIVILEGES).getValue(Type.NAMES));
    Set<Restriction> restrictions = mgrProvider.getRestrictionProvider().readRestrictions(oakPath, entryTree);
    NamePathMapper npMapper = getNamePathMapper();
    return new AbstractEntry(oakPath, principal, bits, restrictions, npMapper) {

        @Override
        @NotNull
        NamePathMapper getNamePathMapper() {
            return npMapper;
        }

        @Override
        public Privilege[] getPrivileges() {
            Set<String> names = privilegeBitsProvider.getPrivilegeNames(getPrivilegeBits());
            return Utils.privilegesFromOakNames(names, mgrProvider.getPrivilegeManager(), getNamePathMapper());
        }
    };
}

19 View Complete Implementation : ExternalIdentityValidatorTest.java
Copyright Apache License 2.0
Author : apache
@Test(expected = CommitFailedException.clreplaced)
public void testRemoveExternalPrincipalNames() throws Exception {
    Tree userTree = root.getTree(externalUserPath);
    try {
        userTree.removeProperty(ExternalIdenreplacedyConstants.REP_EXTERNAL_PRINCIPAL_NAMES);
        root.commit();
        fail("Removing rep:externalPrincipalNames must be detected.");
    } catch (CommitFailedException e) {
        // success
        replacedertException(e, CONSTRAINT, 70);
    } finally {
        root.refresh();
    }
}

19 View Complete Implementation : CompositePermissionProviderAnd.java
Copyright Apache License 2.0
Author : apache
@Override
public boolean isGranted(@NotNull Tree parent, @Nullable PropertyState property, long permissions) {
    Tree immParent = PermissionUtil.getReadOnlyTree(parent, getImmutableRoot());
    boolean isGranted = false;
    long coveredPermissions = Permissions.NO_PERMISSION;
    for (AggregatedPermissionProvider aggregatedPermissionProvider : getPermissionProviders()) {
        long supportedPermissions = aggregatedPermissionProvider.supportedPermissions(immParent, property, permissions);
        if (Util.doEvaluate(supportedPermissions)) {
            isGranted = aggregatedPermissionProvider.isGranted(immParent, property, supportedPermissions);
            if (!isGranted) {
                return false;
            }
            coveredPermissions |= supportedPermissions;
        }
    }
    return isGranted && coveredPermissions == permissions;
}

19 View Complete Implementation : AuthorizablePropertiesImpl.java
Copyright Apache License 2.0
Author : apache
/**
 * Retrieves the node at {@code relPath} relative to node replacedociated with
 * this authorizable. If no such node exist it and any missing intermediate
 * nodes are created.
 *
 * @param relPath A relative path.
 * @return The corresponding node.
 * @throws RepositoryException If an error occurs or if {@code relPath} refers
 *                             to a node that is outside of the scope of this authorizable.
 */
@NotNull
private Tree getOrCreateTargetTree(@Nullable String relPath) throws RepositoryException {
    Tree targetTree;
    Tree userTree = getTree();
    if (relPath != null) {
        String userPath = userTree.getPath();
        targetTree = getLocation(userTree, relPath).getTree();
        if (targetTree != null) {
            checkScope(userPath, targetTree.getPath(), relPath);
        } else {
            targetTree = Utils.getOrAddTree(userTree, relPath, JcrConstants.NT_UNSTRUCTURED);
            checkScope(userPath, targetTree.getPath(), relPath);
        }
    } else {
        targetTree = userTree;
    }
    return targetTree;
}

19 View Complete Implementation : TokenProviderImpl.java
Copyright Apache License 2.0
Author : apache
/**
 * Retrieves the token information replacedociated with the specified login
 * token. If no accessible {@code Tree} exists for the given token or if
 * the token is not replacedociated with a valid user this method returns {@code null}.
 *
 * @param token A valid login token.
 * @return The {@code TokenInfo} replacedociated with the specified token or
 *         {@code null} of the corresponding information does not exist or is not
 *         replacedociated with a valid user.
 */
@Nullable
@Override
public TokenInfo getTokenInfo(@NotNull String token) {
    int pos = token.indexOf(DELIM);
    String nodeId = (pos == -1) ? token : token.substring(0, pos);
    Tree tokenTree = identifierManager.getTree(nodeId);
    if (isValidTokenTree(tokenTree)) {
        try {
            User user = getUser(tokenTree);
            if (user != null) {
                return new TokenInfoImpl(tokenTree, token, user.getID(), user.getPrincipal());
            }
        } catch (RepositoryException e) {
            log.debug("Cannot determine userID/principal from token: {}", e.getMessage());
        }
    }
    // invalid token tree or failed to extract user or it's id/principal
    return null;
}

19 View Complete Implementation : PermissionStoreImpl.java
Copyright Apache License 2.0
Author : apache
private void loadPermissionEntries(@NotNull Tree tree, @NotNull PrincipalPermissionEntries principalPermissionEntries) {
    String path = TreeUtil.getString(tree, PermissionConstants.REP_ACCESS_CONTROLLED_PATH);
    if (path != null) {
        Collection<PermissionEntry> entries = principalPermissionEntries.getEntriesByPath(path);
        if (entries == null) {
            entries = new TreeSet<>();
            principalPermissionEntries.putEntriesByPath(path, entries);
        }
        for (Tree child : tree.getChildren()) {
            if (child.getName().charAt(0) == 'c') {
                loadPermissionEntries(child, principalPermissionEntries);
            } else {
                entries.add(createPermissionEntry(path, child));
            }
        }
    } else {
        log.error("Permission entry at '{}' without rep:accessControlledPath property.", tree.getPath());
    }
}

19 View Complete Implementation : CugEvaluationTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testWriteAcl() throws Exception {
    ContentSession cs = createTestSession2();
    Root r = cs.getLatestRoot();
    try {
        Tree tree = r.getTree("/content/a/b/c");
        tree.setProperty(JCR_MIXINTYPES, ImmutableList.of(MIX_REP_CUG_MIXIN, AccessControlConstants.MIX_REP_ACCESS_CONTROLLABLE), Type.NAMES);
        tree.addChild(AccessControlConstants.REP_POLICY).setProperty(JCR_PRIMARYTYPE, AccessControlConstants.NT_REP_ACL, Type.NAME);
        r.commit();
        fail();
    } catch (CommitFailedException e) {
        replacedertTrue(e.isAccessViolation());
    } finally {
        r.refresh();
    }
}

19 View Complete Implementation : PermissionProviderInternalTypeTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testGetChildTreePermission() {
    Tree readOnly = getRootProvider().createReadOnlyRoot(root).getTree(PathUtils.ROOT_PATH);
    TreePermission tp = (AbstractTreePermission) permissionProvider.getTreePermission(readOnly, TreePermission.EMPTY);
    NodeState ns = getTreeProvider().asNodeState(readOnly);
    for (String elem : PathUtils.elements(PermissionConstants.PERMISSIONS_STORE_PATH)) {
        ns = ns.getChildNode(elem);
        tp = permissionProvider.getTreePermission(elem, ns, (AbstractTreePermission) tp);
    }
    replacedertSame(TreePermission.EMPTY, tp);
}

19 View Complete Implementation : NestedCugHookTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testMoveToSupportedPath() throws Exception {
    createCug(root, SUPPORTED_PATH3, EveryonePrincipal.NAME);
    Tree newTree = TreeUtil.addChild(root.getTree(SUPPORTED_PATH3), "child", NT_OAK_UNSTRUCTURED);
    String path = newTree.getPath();
    createCug(path, getTestGroupPrincipal());
    root.commit();
    String destPath = PathUtils.concat(SUPPORTED_PATH, "moved");
    root.move(path, destPath);
    root.commit();
    replacedertNestedCugs(root, getRootProvider(), SUPPORTED_PATH3, true);
    replacedertNestedCugs(root, getRootProvider(), ROOT_PATH, false, SUPPORTED_PATH3, destPath);
}

19 View Complete Implementation : VersionTreePermissionTest.java
Copyright Apache License 2.0
Author : apache
@Before
public void before() throws Exception {
    super.before();
    testPrincipal = getTestSystemUser().getPrincipal();
    setupContentTrees(TEST_OAK_PATH);
    contentPath = PathUtils.getAncestorPath(TEST_OAK_PATH, 3);
    childPath = PathUtils.getAncestorPath(TEST_OAK_PATH, 2);
    grandchildPath = PathUtils.getAncestorPath(TEST_OAK_PATH, 1);
    // setup permissions on childPath + TEST_OAK_PATH
    PrincipalPolicyImpl policy = setupPrincipalBasedAccessControl(testPrincipal, getNamePathMapper().getJcrPath(childPath), JCR_READ);
    addPrincipalBasedEntry(policy, getNamePathMapper().getJcrPath(TEST_OAK_PATH), PrivilegeConstants.JCR_VERSION_MANAGEMENT);
    // versionabel nodes: contentPath + grandChildPath + TEST_OAK_PATH
    // -> TEST_OAK_PATH versionable node holds policy, grandchildPath get permissions inherited, and contentPath has no permissions granted
    Tree typeRoot = root.getTree(NodeTypeConstants.NODE_TYPES_PATH);
    for (String path : new String[] { contentPath, grandchildPath, TEST_OAK_PATH }) {
        Tree versionable = root.getTree(path);
        TreeUtil.addMixin(root.getTree(path), NodeTypeConstants.MIX_VERSIONABLE, typeRoot, "uid");
    }
    root.commit();
    // force creation of a new versions (except for TEST_OAK_PATH)
    for (String path : new String[] { contentPath, grandchildPath }) {
        root.getTree(path).setProperty(JCR_ISCHECKEDOUT, false);
        root.commit();
        root.getTree(path).setProperty(JCR_ISCHECKEDOUT, true);
        root.commit();
    }
    permissionProvider = createPermissionProvider(root, testPrincipal);
}