You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by jo...@apache.org on 2024/06/05 11:33:58 UTC
(sling-org-apache-sling-jcr-repoinit) 01/02: SLING-12347 apply spotless formatting
This is an automated email from the ASF dual-hosted git repository.
joerghoh pushed a commit to branch SLING-12347
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-jcr-repoinit.git
commit 55d3aaca7c81ef971856ea38e00898c64ccb6926
Author: Joerg Hoh <jo...@apache.org>
AuthorDate: Wed Jun 5 13:31:15 2024 +0200
SLING-12347 apply spotless formatting
---
.../jcr/repoinit/JcrRepoInitOpsProcessor.java | 30 +-
.../apache/sling/jcr/repoinit/impl/AclUtil.java | 387 +++++++++------
.../apache/sling/jcr/repoinit/impl/AclVisitor.java | 52 +-
.../sling/jcr/repoinit/impl/DoNothingVisitor.java | 36 +-
.../jcr/repoinit/impl/GroupMembershipVisitor.java | 36 +-
.../repoinit/impl/JcrRepoInitOpsProcessorImpl.java | 110 +++--
.../sling/jcr/repoinit/impl/NamespacesVisitor.java | 32 +-
.../jcr/repoinit/impl/NodePropertiesVisitor.java | 104 ++--
.../sling/jcr/repoinit/impl/NodeVisitor.java | 60 +--
.../sling/jcr/repoinit/impl/NodetypesVisitor.java | 36 +-
.../sling/jcr/repoinit/impl/PrivilegeVisitor.java | 45 +-
.../sling/jcr/repoinit/impl/RepoInitException.java | 27 +-
.../jcr/repoinit/impl/RepoinitTextProvider.java | 61 +--
.../jcr/repoinit/impl/RepositoryInitializer.java | 61 +--
.../impl/RepositoryInitializerFactory.java | 192 ++++----
.../jcr/repoinit/impl/RetryableOperation.java | 35 +-
.../apache/sling/jcr/repoinit/impl/UserUtil.java | 64 +--
.../sling/jcr/repoinit/impl/UserVisitor.java | 64 ++-
.../apache/sling/jcr/repoinit/package-info.java | 2 -
.../sling/jcr/repoinit/CreateGroupsTest.java | 41 +-
.../apache/sling/jcr/repoinit/CreatePathsTest.java | 61 +--
.../sling/jcr/repoinit/CreateServiceUsersTest.java | 58 +--
.../apache/sling/jcr/repoinit/CreateUsersTest.java | 48 +-
.../apache/sling/jcr/repoinit/DeleteAclTest.java | 96 ++--
.../apache/sling/jcr/repoinit/EveryoneTest.java | 27 +-
.../sling/jcr/repoinit/ExecutionOrderTest.java | 54 ++-
.../apache/sling/jcr/repoinit/GeneralAclTest.java | 400 +++++++---------
.../sling/jcr/repoinit/GroupMembershipTest.java | 43 +-
.../org/apache/sling/jcr/repoinit/LogCapture.java | 14 +-
.../org/apache/sling/jcr/repoinit/MixinsTest.java | 81 ++--
.../sling/jcr/repoinit/NonExistentPathTest.java | 47 +-
.../sling/jcr/repoinit/PrincipalBasedAclTest.java | 526 ++++++++++-----------
.../sling/jcr/repoinit/RegisterNamespacesTest.java | 42 +-
.../sling/jcr/repoinit/RegisterNodetypesTest.java | 36 +-
.../sling/jcr/repoinit/RegisterPrivilegeTest.java | 70 ++-
.../org/apache/sling/jcr/repoinit/RemoveTest.java | 126 ++---
.../jcr/repoinit/RepositoryInitializerTest.java | 103 ++--
.../SetAclWithoutExistingAuthorizableTest.java | 90 ++--
.../sling/jcr/repoinit/SetPropertiesTest.java | 325 ++++++-------
.../sling/jcr/repoinit/impl/AclUtilTest.java | 466 ++++++++++++------
.../jcr/repoinit/impl/ManyServiceUsersTest.java | 74 +--
.../jcr/repoinit/impl/RepoinitReferenceTest.java | 80 ++--
.../impl/RepositoryInitializerFactoryTest.java | 56 ++-
.../jcr/repoinit/impl/RetryableOperationTest.java | 57 ++-
.../apache/sling/jcr/repoinit/impl/TestUtil.java | 141 +++---
.../sling/jcr/repoinit/it/MinimalRepoInitIT.java | 36 +-
.../sling/jcr/repoinit/it/RepoInitTestSupport.java | 95 ++--
.../sling/jcr/repoinit/it/RepoInitTextIT.java | 224 ++++++---
.../it/RepositoryInitializerFactoryIT.java | 95 ++--
.../jcr/repoinit/it/RepositoryInitializerIT.java | 43 +-
.../org/apache/sling/jcr/repoinit/it/Retry.java | 41 +-
.../java/org/apache/sling/jcr/repoinit/it/U.java | 91 ++--
52 files changed, 2784 insertions(+), 2437 deletions(-)
diff --git a/src/main/java/org/apache/sling/jcr/repoinit/JcrRepoInitOpsProcessor.java b/src/main/java/org/apache/sling/jcr/repoinit/JcrRepoInitOpsProcessor.java
index 79ee7b2..c2a5ff0 100644
--- a/src/main/java/org/apache/sling/jcr/repoinit/JcrRepoInitOpsProcessor.java
+++ b/src/main/java/org/apache/sling/jcr/repoinit/JcrRepoInitOpsProcessor.java
@@ -1,25 +1,27 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit;
-import java.util.List;
-
import javax.jcr.Session;
+import java.util.List;
+
import org.apache.sling.repoinit.parser.operations.Operation;
import org.osgi.annotation.versioning.ProviderType;
diff --git a/src/main/java/org/apache/sling/jcr/repoinit/impl/AclUtil.java b/src/main/java/org/apache/sling/jcr/repoinit/impl/AclUtil.java
index 008e581..e8a9e0b 100644
--- a/src/main/java/org/apache/sling/jcr/repoinit/impl/AclUtil.java
+++ b/src/main/java/org/apache/sling/jcr/repoinit/impl/AclUtil.java
@@ -1,38 +1,23 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
-import org.apache.jackrabbit.api.security.JackrabbitAccessControlEntry;
-import org.apache.jackrabbit.api.security.JackrabbitAccessControlList;
-import org.apache.jackrabbit.api.security.JackrabbitAccessControlManager;
-import org.apache.jackrabbit.api.security.JackrabbitAccessControlPolicy;
-import org.apache.jackrabbit.api.security.authorization.PrincipalAccessControlList;
-import org.apache.jackrabbit.api.security.principal.ItemBasedPrincipal;
-import org.apache.jackrabbit.api.security.user.Authorizable;
-import org.apache.jackrabbit.commons.jackrabbit.authorization.AccessControlUtils;
-import org.apache.jackrabbit.oak.spi.security.principal.PrincipalImpl;
-import org.apache.jackrabbit.util.Text;
-import org.apache.sling.repoinit.parser.operations.AclLine;
-import org.apache.sling.repoinit.parser.operations.RestrictionClause;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
@@ -43,6 +28,7 @@ import javax.jcr.security.AccessControlException;
import javax.jcr.security.AccessControlManager;
import javax.jcr.security.AccessControlPolicy;
import javax.jcr.security.Privilege;
+
import java.security.Principal;
import java.text.MessageFormat;
import java.util.ArrayList;
@@ -57,6 +43,23 @@ import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
+import org.apache.jackrabbit.api.security.JackrabbitAccessControlEntry;
+import org.apache.jackrabbit.api.security.JackrabbitAccessControlList;
+import org.apache.jackrabbit.api.security.JackrabbitAccessControlManager;
+import org.apache.jackrabbit.api.security.JackrabbitAccessControlPolicy;
+import org.apache.jackrabbit.api.security.authorization.PrincipalAccessControlList;
+import org.apache.jackrabbit.api.security.principal.ItemBasedPrincipal;
+import org.apache.jackrabbit.api.security.user.Authorizable;
+import org.apache.jackrabbit.commons.jackrabbit.authorization.AccessControlUtils;
+import org.apache.jackrabbit.oak.spi.security.principal.PrincipalImpl;
+import org.apache.jackrabbit.util.Text;
+import org.apache.sling.repoinit.parser.operations.AclLine;
+import org.apache.sling.repoinit.parser.operations.RestrictionClause;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import static org.apache.sling.repoinit.parser.operations.AclLine.ID_DELIMINATOR;
import static org.apache.sling.repoinit.parser.operations.AclLine.PATH_HOME;
import static org.apache.sling.repoinit.parser.operations.AclLine.PATH_REPOSITORY;
@@ -74,9 +77,13 @@ public class AclUtil {
}
private static final Logger LOG = LoggerFactory.getLogger(AclUtil.class);
+
public static JackrabbitAccessControlManager getJACM(Session s) throws RepositoryException {
final AccessControlManager acm = s.getAccessControlManager();
- checkState((acm instanceof JackrabbitAccessControlManager), "AccessControlManager is not a JackrabbitAccessControlManager: {0}", acm.getClass().getName());
+ checkState(
+ (acm instanceof JackrabbitAccessControlManager),
+ "AccessControlManager is not a JackrabbitAccessControlManager: {0}",
+ acm.getClass().getName());
return (JackrabbitAccessControlManager) acm;
}
@@ -89,44 +96,55 @@ public class AclUtil {
* @return
* @throws RepositoryException
*/
- private static LocalRestrictions createLocalRestrictions(List<RestrictionClause> list, JackrabbitAccessControlList jacl, Session s) throws RepositoryException {
- Map<String,Value> restrictions = new HashMap<>();
- Map<String,Value[]> mvrestrictions = new HashMap<>();
+ private static LocalRestrictions createLocalRestrictions(
+ List<RestrictionClause> list, JackrabbitAccessControlList jacl, Session s) throws RepositoryException {
+ Map<String, Value> restrictions = new HashMap<>();
+ Map<String, Value[]> mvrestrictions = new HashMap<>();
- if(list != null && !list.isEmpty()){
+ if (list != null && !list.isEmpty()) {
ValueFactory vf = s.getValueFactory();
- for(RestrictionClause rc : list){
- String restrictionName = rc.getName();
- int type = jacl.getRestrictionType(restrictionName);
- boolean isMvRestriction = jacl.isMultiValueRestriction(restrictionName);
- Value[] values = new Value[rc.getValues().size()];
- for(int i=0;i<values.length;i++) {
- values[i] = vf.createValue(rc.getValues().get(i),type);
- }
-
- if("rep:glob".equals(restrictionName) && values.length == 0) {
- // SLING-7280 - special case for rep:glob which supports an empty string
- // to mean "no values"
- restrictions.put(restrictionName, vf.createValue(""));
- } else if (isMvRestriction) {
- mvrestrictions.put(restrictionName, values);
- } else {
- checkState(values.length == 1, "Expected just one value for single valued restriction with name {0}", restrictionName);
- restrictions.put(restrictionName, values[0]);
- }
- }
- }
- return new LocalRestrictions(restrictions,mvrestrictions);
+ for (RestrictionClause rc : list) {
+ String restrictionName = rc.getName();
+ int type = jacl.getRestrictionType(restrictionName);
+ boolean isMvRestriction = jacl.isMultiValueRestriction(restrictionName);
+ Value[] values = new Value[rc.getValues().size()];
+ for (int i = 0; i < values.length; i++) {
+ values[i] = vf.createValue(rc.getValues().get(i), type);
+ }
+
+ if ("rep:glob".equals(restrictionName) && values.length == 0) {
+ // SLING-7280 - special case for rep:glob which supports an empty string
+ // to mean "no values"
+ restrictions.put(restrictionName, vf.createValue(""));
+ } else if (isMvRestriction) {
+ mvrestrictions.put(restrictionName, values);
+ } else {
+ checkState(
+ values.length == 1,
+ "Expected just one value for single valued restriction with name {0}",
+ restrictionName);
+ restrictions.put(restrictionName, values[0]);
+ }
+ }
+ }
+ return new LocalRestrictions(restrictions, mvrestrictions);
}
- public static void setAcl(Session session, List<String> principals, List<String> paths, List<String> privileges, boolean isAllow)
+ public static void setAcl(
+ Session session, List<String> principals, List<String> paths, List<String> privileges, boolean isAllow)
throws RepositoryException {
setAcl(session, principals, paths, privileges, isAllow, Collections.emptyList(), Collections.emptyList());
}
- public static void setAcl(Session session, List<String> principals, List<String> paths, List<String> privileges,
- boolean isAllow, List<RestrictionClause> restrictionClauses, List<String> options)
+ public static void setAcl(
+ Session session,
+ List<String> principals,
+ List<String> paths,
+ List<String> privileges,
+ boolean isAllow,
+ List<RestrictionClause> restrictionClauses,
+ List<String> options)
throws RepositoryException {
for (String jcrPath : getJcrPaths(session, paths)) {
@@ -137,13 +155,19 @@ public class AclUtil {
}
}
- private static void setAcl(Session session, List<String> principals, String jcrPath, List<String> privileges,
- boolean isAllow, List<RestrictionClause> restrictionClauses, List<String> options)
+ private static void setAcl(
+ Session session,
+ List<String> principals,
+ String jcrPath,
+ List<String> privileges,
+ boolean isAllow,
+ List<RestrictionClause> restrictionClauses,
+ List<String> options)
throws RepositoryException {
AccessControlManager acMgr = session.getAccessControlManager();
- final String [] privArray = privileges.toArray(new String[privileges.size()]);
+ final String[] privArray = privileges.toArray(new String[privileges.size()]);
final Privilege[] jcrPriv = AccessControlUtils.privilegesFromNames(acMgr, privArray);
JackrabbitAccessControlList acl = getAccessControlList(acMgr, jcrPath, true);
@@ -159,25 +183,35 @@ public class AclUtil {
.orElse(false);
for (String name : principals) {
final Principal principal = getPrincipal(session, name, ignoreMissingPrincipal);
- LocalAccessControlEntry newAce = new LocalAccessControlEntry(principal, jcrPriv, isAllow, localRestrictions);
+ LocalAccessControlEntry newAce =
+ new LocalAccessControlEntry(principal, jcrPriv, isAllow, localRestrictions);
if (contains(existingAces, newAce)) {
- LOG.info("Not adding {} to path {} since an equivalent access control entry already exists", newAce, jcrPath);
+ LOG.info(
+ "Not adding {} to path {} since an equivalent access control entry already exists",
+ newAce,
+ jcrPath);
continue;
}
- acl.addEntry(newAce.principal, newAce.privileges, newAce.isAllow,
- newAce.restrictions.getRestrictions(), newAce.restrictions.getMVRestrictions());
+ acl.addEntry(
+ newAce.principal,
+ newAce.privileges,
+ newAce.isAllow,
+ newAce.restrictions.getRestrictions(),
+ newAce.restrictions.getMVRestrictions());
changed = true;
}
- if ( changed ) {
+ if (changed) {
acMgr.setPolicy(jcrPath, acl);
}
}
@NotNull
- private static Principal getPrincipal(Session session, String name, boolean ignoreMissingPrincipal) throws RepositoryException {
+ private static Principal getPrincipal(Session session, String name, boolean ignoreMissingPrincipal)
+ throws RepositoryException {
Principal principal = AccessControlUtils.getPrincipal(session, name);
if (principal == null) {
- // backwards compatibility: fallback to original code treating principal name as authorizable ID (see SLING-8604)
+ // backwards compatibility: fallback to original code treating principal name as authorizable ID (see
+ // SLING-8604)
final Authorizable authorizable = UserUtil.getAuthorizable(session, name);
if (!ignoreMissingPrincipal) {
checkState(authorizable != null, "Authorizable not found: {0}", name);
@@ -202,7 +236,8 @@ public class AclUtil {
* @param principalName
* @throws RepositoryException
*/
- public static void removePolicy(@NotNull Session session, @NotNull final String principalName) throws RepositoryException {
+ public static void removePolicy(@NotNull Session session, @NotNull final String principalName)
+ throws RepositoryException {
Principal principal = AccessControlUtils.getPrincipal(session, principalName);
if (principal == null) {
LOG.info("Principal {} does not exist.", principalName);
@@ -228,7 +263,8 @@ public class AclUtil {
* @param paths
* @throws RepositoryException
*/
- public static void removePolicies(@NotNull Session session, @NotNull List<String> paths) throws RepositoryException {
+ public static void removePolicies(@NotNull Session session, @NotNull List<String> paths)
+ throws RepositoryException {
AccessControlManager acMgr = session.getAccessControlManager();
for (String jcrPath : getJcrPaths(session, paths)) {
if (!isValidPath(session, jcrPath)) {
@@ -245,7 +281,9 @@ public class AclUtil {
}
}
- public static void removeEntries(@NotNull Session session, @NotNull List<String> principals, @NotNull List<String> paths) throws RepositoryException {
+ public static void removeEntries(
+ @NotNull Session session, @NotNull List<String> principals, @NotNull List<String> paths)
+ throws RepositoryException {
Set<String> principalNames = new HashSet<>(principals);
AccessControlManager acMgr = session.getAccessControlManager();
for (String jcrPath : getJcrPaths(session, paths)) {
@@ -265,13 +303,23 @@ public class AclUtil {
acMgr.setPolicy(jcrPath, acl);
}
} else {
- LOG.info("Cannot remove access control entries for principal(s) {}. No ACL at {}", principalNames, jcrPath);
+ LOG.info(
+ "Cannot remove access control entries for principal(s) {}. No ACL at {}",
+ principalNames,
+ jcrPath);
}
}
}
}
- public static void removeEntries(@NotNull Session session, @NotNull List<String> principals, @NotNull List<String> paths, List<String> privileges, boolean isAllow, List<RestrictionClause> restrictionClauses) throws RepositoryException {
+ public static void removeEntries(
+ @NotNull Session session,
+ @NotNull List<String> principals,
+ @NotNull List<String> paths,
+ List<String> privileges,
+ boolean isAllow,
+ List<RestrictionClause> restrictionClauses)
+ throws RepositoryException {
Set<String> principalNames = new HashSet<>(principals);
AccessControlManager acMgr = session.getAccessControlManager();
for (String jcrPath : getJcrPaths(session, paths)) {
@@ -283,14 +331,16 @@ public class AclUtil {
boolean modified = false;
LocalRestrictions restr = createLocalRestrictions(restrictionClauses, acl, session);
- Privilege[] privs = AccessControlUtils.privilegesFromNames(acMgr, privileges.toArray(new String[0]));
+ Privilege[] privs =
+ AccessControlUtils.privilegesFromNames(acMgr, privileges.toArray(new String[0]));
for (AccessControlEntry ace : acl.getAccessControlEntries()) {
Principal principal = ace.getPrincipal();
if (!principalNames.contains(principal.getName())) {
continue;
}
- LocalAccessControlEntry entry = new LocalAccessControlEntry(ace.getPrincipal(), privs, isAllow, restr);
+ LocalAccessControlEntry entry =
+ new LocalAccessControlEntry(ace.getPrincipal(), privs, isAllow, restr);
if (entry.isEqual(ace)) {
acl.removeAccessControlEntry(ace);
modified = true;
@@ -299,16 +349,27 @@ public class AclUtil {
if (modified) {
acMgr.setPolicy(jcrPath, acl);
} else {
- LOG.info("No matching access control entry found to remove for principals {} at {}. Expected entry with isAllow={}, privileges={}, restrictions={}", principalNames, jcrPath, isAllow, privileges, restrictionClauses);
+ LOG.info(
+ "No matching access control entry found to remove for principals {} at {}. Expected entry with isAllow={}, privileges={}, restrictions={}",
+ principalNames,
+ jcrPath,
+ isAllow,
+ privileges,
+ restrictionClauses);
}
} else {
- LOG.info("Cannot remove access control entries for principal(s) {}. No ACL at {}", principalNames, jcrPath);
+ LOG.info(
+ "Cannot remove access control entries for principal(s) {}. No ACL at {}",
+ principalNames,
+ jcrPath);
}
}
}
}
- public static void setPrincipalAcl(Session session, String principalName, Collection<AclLine> lines, boolean isStrict) throws RepositoryException {
+ public static void setPrincipalAcl(
+ Session session, String principalName, Collection<AclLine> lines, boolean isStrict)
+ throws RepositoryException {
final JackrabbitAccessControlManager acMgr = getJACM(session);
Principal principal = AccessControlUtils.getPrincipal(session, principalName);
if (principal == null) {
@@ -326,7 +387,8 @@ public class AclUtil {
if (principal instanceof ItemBasedPrincipal) {
principalDescription += " (" + ((ItemBasedPrincipal) principal).getPath() + ")";
}
- throw new IllegalStateException("No PrincipalAccessControlList available for principal '" + principalDescription + "'.");
+ throw new IllegalStateException(
+ "No PrincipalAccessControlList available for principal '" + principalDescription + "'.");
}
boolean modified = false;
for (AclLine line : lines) {
@@ -335,27 +397,42 @@ public class AclUtil {
if (action == AclLine.Action.DENY) {
throw new AccessControlException("PrincipalAccessControlList doesn't support 'deny' entries.");
} else if (action == AclLine.Action.REMOVE) {
- throw new IllegalArgumentException(AclLine.Action.REMOVE + " is not supported. Use 'remove principal acl' instead.");
+ throw new IllegalArgumentException(
+ AclLine.Action.REMOVE + " is not supported. Use 'remove principal acl' instead.");
} else if (action == AclLine.Action.REMOVE_ALL) {
if (removePrincipalEntries(acl, principalName, entry -> jcrPaths.contains(entry.getEffectivePath()))) {
modified = true;
}
} else if (action == AclLine.Action.ALLOW) {
- final Privilege[] privileges = AccessControlUtils.privilegesFromNames(acMgr, line.getProperty(PROP_PRIVILEGES).toArray(new String[0]));
+ final Privilege[] privileges = AccessControlUtils.privilegesFromNames(
+ acMgr, line.getProperty(PROP_PRIVILEGES).toArray(new String[0]));
for (String effectivePath : jcrPaths) {
if (acl == null) {
- // no PrincipalAccessControlList available: don't fail if an equivalent path-based entry with the same definition exists
+ // no PrincipalAccessControlList available: don't fail if an equivalent path-based entry with
+ // the same definition exists
// or if there exists no node at the effective path (unable to evaluate path-based entries).
LOG.info("No PrincipalAccessControlList available for principal {}", principal);
- if (!containsEquivalentEntry(session, effectivePath, principal, privileges, true, line.getRestrictions())) {
- LOG.warn("No equivalent path-based entry exists for principal {} and effective path {} ", principal.getName(), effectivePath);
+ if (!containsEquivalentEntry(
+ session, effectivePath, principal, privileges, true, line.getRestrictions())) {
+ LOG.warn(
+ "No equivalent path-based entry exists for principal {} and effective path {} ",
+ principal.getName(),
+ effectivePath);
return;
}
} else {
- final LocalRestrictions restrictions = createLocalRestrictions(line.getRestrictions(), acl, session);
- final boolean added = acl.addEntry(effectivePath, privileges, restrictions.getRestrictions(), restrictions.getMVRestrictions());
+ final LocalRestrictions restrictions =
+ createLocalRestrictions(line.getRestrictions(), acl, session);
+ final boolean added = acl.addEntry(
+ effectivePath,
+ privileges,
+ restrictions.getRestrictions(),
+ restrictions.getMVRestrictions());
if (!added) {
- LOG.info("Equivalent principal-based entry already exists for principal {} and effective path {} ", principalName, effectivePath);
+ LOG.info(
+ "Equivalent principal-based entry already exists for principal {} and effective path {} ",
+ principalName,
+ effectivePath);
} else {
modified = true;
}
@@ -370,7 +447,8 @@ public class AclUtil {
}
}
- public static void removePrincipalEntries(Session session, String principalName, Collection<AclLine> lines) throws RepositoryException {
+ public static void removePrincipalEntries(Session session, String principalName, Collection<AclLine> lines)
+ throws RepositoryException {
final JackrabbitAccessControlManager acMgr = getJACM(session);
Principal principal = AccessControlUtils.getPrincipal(session, principalName);
if (principal == null) {
@@ -392,13 +470,20 @@ public class AclUtil {
if (!jcrPaths.contains(entry.getEffectivePath())) {
return false;
}
- LocalAccessControlEntry lace = new LocalAccessControlEntry(entry.getPrincipal(), privs, line.getAction()== AclLine.Action.ALLOW, restr);
+ LocalAccessControlEntry lace = new LocalAccessControlEntry(
+ entry.getPrincipal(), privs, line.getAction() == AclLine.Action.ALLOW, restr);
return lace.isEqual(entry);
};
if (removePrincipalEntries(acl, principalName, predicate)) {
modified = true;
} else {
- LOG.info("No matching access control entry found to remove for principal {} at {}. Expected entry with isAllow={}, privileges={}, restrictions={}", principalName, jcrPaths, line.getAction(), privNames, line.getRestrictions());
+ LOG.info(
+ "No matching access control entry found to remove for principal {} at {}. Expected entry with isAllow={}, privileges={}, restrictions={}",
+ principalName,
+ jcrPaths,
+ line.getAction(),
+ privNames,
+ line.getRestrictions());
}
}
if (modified) {
@@ -413,7 +498,8 @@ public class AclUtil {
* @param principalName
* @throws RepositoryException
*/
- public static void removePrincipalPolicy(@NotNull Session session, @NotNull String principalName) throws RepositoryException {
+ public static void removePrincipalPolicy(@NotNull Session session, @NotNull String principalName)
+ throws RepositoryException {
Principal principal = AccessControlUtils.getPrincipal(session, principalName);
if (principal == null) {
LOG.info("Cannot remove principal-based ACL. Principal {} does not exist.", principalName);
@@ -441,8 +527,9 @@ public class AclUtil {
* @throws RepositoryException
*/
@Nullable
- private static JackrabbitAccessControlList getAccessControlList(@NotNull AccessControlManager acMgr,
- @Nullable String path, boolean includeApplicable) throws RepositoryException {
+ private static JackrabbitAccessControlList getAccessControlList(
+ @NotNull AccessControlManager acMgr, @Nullable String path, boolean includeApplicable)
+ throws RepositoryException {
if (includeApplicable) {
return AccessControlUtils.getAccessControlList(acMgr, path);
} else {
@@ -456,8 +543,9 @@ public class AclUtil {
}
@Nullable
- private static PrincipalAccessControlList getPrincipalAccessControlList(@NotNull JackrabbitAccessControlManager acMgr,
- @NotNull Principal principal, boolean includeApplicable) throws RepositoryException {
+ private static PrincipalAccessControlList getPrincipalAccessControlList(
+ @NotNull JackrabbitAccessControlManager acMgr, @NotNull Principal principal, boolean includeApplicable)
+ throws RepositoryException {
PrincipalAccessControlList acl = null;
for (JackrabbitAccessControlPolicy policy : acMgr.getPolicies(principal)) {
if (policy instanceof PrincipalAccessControlList) {
@@ -476,7 +564,11 @@ public class AclUtil {
return acl;
}
- private static boolean removePrincipalEntries(@Nullable PrincipalAccessControlList acl, @NotNull String principalName, @NotNull Predicate<PrincipalAccessControlList.Entry> predicate) throws RepositoryException {
+ private static boolean removePrincipalEntries(
+ @Nullable PrincipalAccessControlList acl,
+ @NotNull String principalName,
+ @NotNull Predicate<PrincipalAccessControlList.Entry> predicate)
+ throws RepositoryException {
boolean modified = false;
if (acl == null) {
LOG.info("Cannot remove entries. No principal-based ACL for {}", principalName);
@@ -495,7 +587,8 @@ public class AclUtil {
}
@NotNull
- private static List<String> getJcrPaths(@NotNull Session session, @NotNull List<String> paths) throws RepositoryException {
+ private static List<String> getJcrPaths(@NotNull Session session, @NotNull List<String> paths)
+ throws RepositoryException {
List<String> jcrPaths = new ArrayList<>(paths.size());
for (String path : paths) {
if (PATH_REPOSITORY.equals(path) || path == null || path.isEmpty()) {
@@ -503,7 +596,7 @@ public class AclUtil {
} else if (path.startsWith(PATH_HOME)) {
int lastHashIndex = path.lastIndexOf(SUBTREE_DELIMINATOR);
checkState(lastHashIndex > -1, "Invalid format of home path: # deliminator expected.");
- String subTreePath = path.substring(lastHashIndex+1);
+ String subTreePath = path.substring(lastHashIndex + 1);
for (String aPath : getAuthorizablePaths(session, path.substring(PATH_HOME.length(), lastHashIndex))) {
jcrPaths.add(aPath + subTreePath);
}
@@ -515,7 +608,8 @@ public class AclUtil {
}
@NotNull
- private static Iterable<String> getAuthorizablePaths(@NotNull Session session, @NotNull String ids) throws RepositoryException {
+ private static Iterable<String> getAuthorizablePaths(@NotNull Session session, @NotNull String ids)
+ throws RepositoryException {
List<String> paths = new ArrayList<>();
for (String id : Text.explode(ids, ID_DELIMINATOR)) {
Authorizable a = UserUtil.getAuthorizable(session, id);
@@ -527,17 +621,31 @@ public class AclUtil {
return paths;
}
- private static boolean containsEquivalentEntry(Session session, String absPath, Principal principal, Privilege[] privileges, boolean isAllow, List<RestrictionClause> restrictionList) throws RepositoryException {
+ private static boolean containsEquivalentEntry(
+ Session session,
+ String absPath,
+ Principal principal,
+ Privilege[] privileges,
+ boolean isAllow,
+ List<RestrictionClause> restrictionList)
+ throws RepositoryException {
if (absPath != null && !session.nodeExists(absPath)) {
- LOG.info("Cannot determine existence of equivalent path-based entry for principal {}. No node at path {} ", principal.getName(), absPath);
+ LOG.info(
+ "Cannot determine existence of equivalent path-based entry for principal {}. No node at path {} ",
+ principal.getName(),
+ absPath);
return true;
}
for (AccessControlPolicy policy : session.getAccessControlManager().getPolicies(absPath)) {
if (policy instanceof JackrabbitAccessControlList) {
- LocalRestrictions lr = createLocalRestrictions(restrictionList, ((JackrabbitAccessControlList) policy), session);
+ LocalRestrictions lr =
+ createLocalRestrictions(restrictionList, ((JackrabbitAccessControlList) policy), session);
LocalAccessControlEntry newEntry = new LocalAccessControlEntry(principal, privileges, isAllow, lr);
if (contains(((JackrabbitAccessControlList) policy).getAccessControlEntries(), newEntry)) {
- LOG.info("Equivalent path-based entry exists for principal {} and effective path {} ", newEntry.principal.getName(), absPath);
+ LOG.info(
+ "Equivalent path-based entry exists for principal {} and effective path {} ",
+ newEntry.principal.getName(),
+ absPath);
return true;
}
}
@@ -546,8 +654,9 @@ public class AclUtil {
}
// visible for testing
- static boolean contains(AccessControlEntry[] existingAces, LocalAccessControlEntry newAce) throws RepositoryException {
- for (int i = 0 ; i < existingAces.length; i++) {
+ static boolean contains(AccessControlEntry[] existingAces, LocalAccessControlEntry newAce)
+ throws RepositoryException {
+ for (int i = 0; i < existingAces.length; i++) {
JackrabbitAccessControlEntry existingEntry = (JackrabbitAccessControlEntry) existingAces[i];
if (LOG.isDebugEnabled()) {
LOG.debug("Comparing {} with {}", newAce, toString(existingEntry));
@@ -561,8 +670,8 @@ public class AclUtil {
private static String toString(JackrabbitAccessControlEntry entry) throws RepositoryException {
return "[" + entry.getClass().getSimpleName() + "# principal: "
- + "" + entry.getPrincipal() + ", privileges: " + Arrays.toString(entry.getPrivileges()) +
- ", isAllow: " + entry.isAllow() + ", restrictionNames: " + entry.getRestrictionNames() + "]";
+ + "" + entry.getPrincipal() + ", privileges: " + Arrays.toString(entry.getPrivileges()) + ", isAllow: "
+ + entry.isAllow() + ", restrictionNames: " + entry.getRestrictionNames() + "]";
}
private static void checkState(boolean expression, String msgPattern, Object... args) {
@@ -585,7 +694,7 @@ public class AclUtil {
if (a == null || b == null) {
return false;
}
- if(a.length != b.length){
+ if (a.length != b.length) {
return false;
}
Set<Value> first = new HashSet<>(Arrays.asList(a));
@@ -602,12 +711,13 @@ public class AclUtil {
private final Privilege[] privileges;
private final boolean isAllow;
private final LocalRestrictions restrictions;
+
LocalAccessControlEntry(Principal principal, Privilege[] privileges, boolean isAllow) {
this(principal, privileges, isAllow, null);
}
- LocalAccessControlEntry(Principal principal, Privilege[] privileges,
- boolean isAllow, LocalRestrictions restrictions) {
+ LocalAccessControlEntry(
+ Principal principal, Privilege[] privileges, boolean isAllow, LocalRestrictions restrictions) {
this.principal = principal;
this.privileges = privileges;
this.isAllow = isAllow;
@@ -615,10 +725,10 @@ public class AclUtil {
}
public boolean isContainedIn(JackrabbitAccessControlEntry other) throws RepositoryException {
- return other.getPrincipal().equals(principal) &&
- contains(other.getPrivileges(), privileges) &&
- other.isAllow() == isAllow &&
- sameRestrictions(other);
+ return other.getPrincipal().equals(principal)
+ && contains(other.getPrivileges(), privileges)
+ && other.isAllow() == isAllow
+ && sameRestrictions(other);
}
public boolean isEqual(AccessControlEntry other) {
@@ -627,21 +737,21 @@ public class AclUtil {
}
try {
JackrabbitAccessControlEntry otherAce = (JackrabbitAccessControlEntry) other;
- return other.getPrincipal().equals(principal) &&
- equalPrivileges(other.getPrivileges(), privileges) &&
- otherAce.isAllow() == isAllow &&
- sameRestrictions(otherAce);
+ return other.getPrincipal().equals(principal)
+ && equalPrivileges(other.getPrivileges(), privileges)
+ && otherAce.isAllow() == isAllow
+ && sameRestrictions(otherAce);
} catch (RepositoryException e) {
throw new IllegalStateException("Cannot verify equivalence of access control entries", e);
}
}
- private Set<Privilege> expandPrivileges(Privilege[] privileges){
+ private Set<Privilege> expandPrivileges(Privilege[] privileges) {
Set<Privilege> expandedSet = new HashSet<>();
- if(privileges != null){
- for(Privilege privilege : privileges){
- if(privilege.isAggregate()){
+ if (privileges != null) {
+ for (Privilege privilege : privileges) {
+ if (privilege.isAggregate()) {
expandedSet.addAll(Arrays.asList(privilege.getAggregatePrivileges()));
} else {
expandedSet.add(privilege);
@@ -661,17 +771,17 @@ public class AclUtil {
*/
private boolean sameRestrictions(JackrabbitAccessControlEntry jace) throws RepositoryException {
// total (multivalue and simple) number of restrictions should be same
- if(jace.getRestrictionNames().length == (restrictions.size())){
- for(String rn : jace.getRestrictionNames()){
+ if (jace.getRestrictionNames().length == (restrictions.size())) {
+ for (String rn : jace.getRestrictionNames()) {
Value[] oldValues = jace.getRestrictions(rn);
Value[] newValues = restrictions.getRestrictions().get(rn) != null
- ? new Value[]{restrictions.getRestrictions().get(rn)}
- : restrictions.getMVRestrictions().get(rn);
- if((newValues == null || newValues.length == 0) && (oldValues == null || oldValues.length == 0)){
+ ? new Value[] {restrictions.getRestrictions().get(rn)}
+ : restrictions.getMVRestrictions().get(rn);
+ if ((newValues == null || newValues.length == 0) && (oldValues == null || oldValues.length == 0)) {
continue;
}
- if(!compareValues(newValues, oldValues)) {
+ if (!compareValues(newValues, oldValues)) {
return false;
}
}
@@ -697,7 +807,8 @@ public class AclUtil {
@Override
public String toString() {
- return "[" + getClass().getSimpleName() + "# principal " + principal+ ", privileges: " + Arrays.toString(privileges) + ", isAllow : " + isAllow + "]";
+ return "[" + getClass().getSimpleName() + "# principal " + principal + ", privileges: "
+ + Arrays.toString(privileges) + ", isAllow : " + isAllow + "]";
}
}
@@ -706,26 +817,28 @@ public class AclUtil {
* in ready to consume structure expected by jackrabbit
*/
private static class LocalRestrictions {
- private Map<String,Value> restrictions;
- private Map<String,Value[]> mvRestrictions;
- public LocalRestrictions(){
+ private Map<String, Value> restrictions;
+ private Map<String, Value[]> mvRestrictions;
+
+ public LocalRestrictions() {
restrictions = new HashMap<>();
mvRestrictions = new HashMap<>();
}
- public LocalRestrictions(Map<String,Value> restrictions,Map<String,Value[]> mvRestrictions){
+
+ public LocalRestrictions(Map<String, Value> restrictions, Map<String, Value[]> mvRestrictions) {
this.restrictions = restrictions != null ? restrictions : new HashMap<>();
this.mvRestrictions = mvRestrictions != null ? mvRestrictions : new HashMap<>();
}
- public Map<String,Value> getRestrictions(){
+ public Map<String, Value> getRestrictions() {
return this.restrictions;
}
- public Map<String,Value[]> getMVRestrictions(){
+ public Map<String, Value[]> getMVRestrictions() {
return this.mvRestrictions;
}
- public int size(){
+ public int size() {
return this.restrictions.size() + this.mvRestrictions.size();
}
}
diff --git a/src/main/java/org/apache/sling/jcr/repoinit/impl/AclVisitor.java b/src/main/java/org/apache/sling/jcr/repoinit/impl/AclVisitor.java
index 1680a83..f96f696 100644
--- a/src/main/java/org/apache/sling/jcr/repoinit/impl/AclVisitor.java
+++ b/src/main/java/org/apache/sling/jcr/repoinit/impl/AclVisitor.java
@@ -1,36 +1,34 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
-import static org.apache.sling.repoinit.parser.operations.AclLine.PROP_PATHS;
-import static org.apache.sling.repoinit.parser.operations.AclLine.PROP_PRINCIPALS;
-import static org.apache.sling.repoinit.parser.operations.AclLine.PROP_PRIVILEGES;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
import java.util.Collections;
import java.util.List;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
import org.apache.sling.repoinit.parser.operations.AclLine;
+import org.apache.sling.repoinit.parser.operations.DeleteAclPaths;
import org.apache.sling.repoinit.parser.operations.DeleteAclPrincipalBased;
import org.apache.sling.repoinit.parser.operations.DeleteAclPrincipals;
import org.apache.sling.repoinit.parser.operations.EnsureAclPrincipalBased;
-import org.apache.sling.repoinit.parser.operations.DeleteAclPaths;
import org.apache.sling.repoinit.parser.operations.RemoveAcePaths;
import org.apache.sling.repoinit.parser.operations.RemoveAcePrincipalBased;
import org.apache.sling.repoinit.parser.operations.RemoveAcePrincipals;
@@ -38,6 +36,10 @@ import org.apache.sling.repoinit.parser.operations.SetAclPaths;
import org.apache.sling.repoinit.parser.operations.SetAclPrincipalBased;
import org.apache.sling.repoinit.parser.operations.SetAclPrincipals;
+import static org.apache.sling.repoinit.parser.operations.AclLine.PROP_PATHS;
+import static org.apache.sling.repoinit.parser.operations.AclLine.PROP_PRINCIPALS;
+import static org.apache.sling.repoinit.parser.operations.AclLine.PROP_PRIVILEGES;
+
/**
* OperationVisitor which processes only operations related to ACLs.
* Having several such specialized visitors
@@ -54,7 +56,8 @@ class AclVisitor extends DoNothingVisitor {
public static final String OPTION_IGNORE_MISSING_PRINCIPAL = "ignoreMissingPrincipal";
private enum Instruction {
- SET, REMOVE
+ SET,
+ REMOVE
}
/**
@@ -67,7 +70,8 @@ class AclVisitor extends DoNothingVisitor {
super(s);
}
- private void handleAclLine(AclLine line, Instruction instruction, List<String> principals, List<String> paths, List<String> options)
+ private void handleAclLine(
+ AclLine line, Instruction instruction, List<String> principals, List<String> paths, List<String> options)
throws RepositoryException {
final AclLine.Action action = line.getAction();
if (action == AclLine.Action.REMOVE) {
@@ -81,7 +85,7 @@ class AclVisitor extends DoNothingVisitor {
if (instruction == Instruction.SET) {
log.info("Adding ACL '{}' entry '{}' for {} on {}", actionName, privileges, principals, paths);
AclUtil.setAcl(session, principals, paths, privileges, isAllow, line.getRestrictions(), options);
- } else if(instruction == Instruction.REMOVE) {
+ } else if (instruction == Instruction.REMOVE) {
log.info("Removing ACL '{}' entry '{}' for {} on {}", actionName, privileges, principals, paths);
AclUtil.removeEntries(session, principals, paths, privileges, isAllow, line.getRestrictions());
}
@@ -152,7 +156,7 @@ class AclVisitor extends DoNothingVisitor {
try {
handleAclLine(line, Instruction.REMOVE, principals, line.getProperty(PROP_PATHS), s.getOptions());
} catch (Exception e) {
- report(e,"Failed to remove access control entries (" + e.toString() + ") " + line);
+ report(e, "Failed to remove access control entries (" + e.toString() + ") " + line);
}
}
}
@@ -164,7 +168,7 @@ class AclVisitor extends DoNothingVisitor {
try {
handleAclLine(line, Instruction.REMOVE, line.getProperty(PROP_PRINCIPALS), paths, s.getOptions());
} catch (Exception e) {
- report(e,"Failed to remove access control entries (" + e.toString() + ") " + line);
+ report(e, "Failed to remove access control entries (" + e.toString() + ") " + line);
}
}
}
diff --git a/src/main/java/org/apache/sling/jcr/repoinit/impl/DoNothingVisitor.java b/src/main/java/org/apache/sling/jcr/repoinit/impl/DoNothingVisitor.java
index 8f313ec..13c1391 100644
--- a/src/main/java/org/apache/sling/jcr/repoinit/impl/DoNothingVisitor.java
+++ b/src/main/java/org/apache/sling/jcr/repoinit/impl/DoNothingVisitor.java
@@ -1,18 +1,20 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
@@ -24,6 +26,8 @@ import org.apache.sling.repoinit.parser.operations.CreateGroup;
import org.apache.sling.repoinit.parser.operations.CreatePath;
import org.apache.sling.repoinit.parser.operations.CreateServiceUser;
import org.apache.sling.repoinit.parser.operations.CreateUser;
+import org.apache.sling.repoinit.parser.operations.DeleteAclPaths;
+import org.apache.sling.repoinit.parser.operations.DeleteAclPrincipalBased;
import org.apache.sling.repoinit.parser.operations.DeleteAclPrincipals;
import org.apache.sling.repoinit.parser.operations.DeleteGroup;
import org.apache.sling.repoinit.parser.operations.DeleteServiceUser;
@@ -35,8 +39,6 @@ import org.apache.sling.repoinit.parser.operations.OperationVisitor;
import org.apache.sling.repoinit.parser.operations.RegisterNamespace;
import org.apache.sling.repoinit.parser.operations.RegisterNodetypes;
import org.apache.sling.repoinit.parser.operations.RegisterPrivilege;
-import org.apache.sling.repoinit.parser.operations.DeleteAclPaths;
-import org.apache.sling.repoinit.parser.operations.DeleteAclPrincipalBased;
import org.apache.sling.repoinit.parser.operations.RemoveAcePaths;
import org.apache.sling.repoinit.parser.operations.RemoveAcePrincipalBased;
import org.apache.sling.repoinit.parser.operations.RemoveAcePrincipals;
@@ -46,7 +48,6 @@ import org.apache.sling.repoinit.parser.operations.SetAclPaths;
import org.apache.sling.repoinit.parser.operations.SetAclPrincipalBased;
import org.apache.sling.repoinit.parser.operations.SetAclPrincipals;
import org.apache.sling.repoinit.parser.operations.SetProperties;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -75,10 +76,10 @@ class DoNothingVisitor implements OperationVisitor {
}
protected static String excerpt(String s, int maxLength) {
- if(s.length() < maxLength) {
+ if (s.length() < maxLength) {
return s;
} else {
- return s.substring(0, maxLength -1) + "...";
+ return s.substring(0, maxLength - 1) + "...";
}
}
@@ -216,5 +217,4 @@ class DoNothingVisitor implements OperationVisitor {
public void visitRemoveMixins(RemoveMixins s) {
// no-op
}
-
}
diff --git a/src/main/java/org/apache/sling/jcr/repoinit/impl/GroupMembershipVisitor.java b/src/main/java/org/apache/sling/jcr/repoinit/impl/GroupMembershipVisitor.java
index d93490a..e6f9915 100644
--- a/src/main/java/org/apache/sling/jcr/repoinit/impl/GroupMembershipVisitor.java
+++ b/src/main/java/org/apache/sling/jcr/repoinit/impl/GroupMembershipVisitor.java
@@ -1,30 +1,33 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
+import java.util.List;
+
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.sling.repoinit.parser.operations.AddGroupMembers;
import org.apache.sling.repoinit.parser.operations.RemoveGroupMembers;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import java.util.List;
-
/**
* OperationVisitor which processes only operations related to group memberships. Having several such specialized visitors makes it easy to control the
* execution order.
@@ -75,5 +78,4 @@ class GroupMembershipVisitor extends DoNothingVisitor {
report(e, "Unable to remove members from group [" + groupname + "]:" + e);
}
}
-
}
diff --git a/src/main/java/org/apache/sling/jcr/repoinit/impl/JcrRepoInitOpsProcessorImpl.java b/src/main/java/org/apache/sling/jcr/repoinit/impl/JcrRepoInitOpsProcessorImpl.java
index fdd3f21..29d7912 100644
--- a/src/main/java/org/apache/sling/jcr/repoinit/impl/JcrRepoInitOpsProcessorImpl.java
+++ b/src/main/java/org/apache/sling/jcr/repoinit/impl/JcrRepoInitOpsProcessorImpl.java
@@ -1,28 +1,30 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
+import javax.jcr.Session;
+
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
-import javax.jcr.Session;
-
import org.apache.sling.jcr.repoinit.JcrRepoInitOpsProcessor;
import org.apache.sling.repoinit.parser.operations.Operation;
import org.apache.sling.repoinit.parser.operations.OperationVisitor;
@@ -37,10 +39,9 @@ import static java.util.Collections.singleton;
/**
* Apply Operations produced by the repoinit parser to a JCR Repository
*/
-@Component(service = JcrRepoInitOpsProcessor.class,
- property = {
- Constants.SERVICE_VENDOR + "=The Apache Software Foundation"
- })
+@Component(
+ service = JcrRepoInitOpsProcessor.class,
+ property = {Constants.SERVICE_VENDOR + "=The Apache Software Foundation"})
public class JcrRepoInitOpsProcessorImpl implements JcrRepoInitOpsProcessor {
private static final Logger log = LoggerFactory.getLogger(JcrRepoInitOpsProcessorImpl.class);
@@ -54,44 +55,46 @@ public class JcrRepoInitOpsProcessorImpl implements JcrRepoInitOpsProcessor {
AtomicReference<Operation> lastAttemptedOperation = new AtomicReference<>();
try {
Stream.of(
- // register namespaces first
- singleton(new NamespacesVisitor(session)),
- // then create node types and privileges, both use namespaces
- asList(
- new NodetypesVisitor(session),
- new PrivilegeVisitor(session)),
- // finally apply everything else
- asList(
- new UserVisitor(session),
- new NodeVisitor(session),
- new AclVisitor(session),
- new GroupMembershipVisitor(session),
- new NodePropertiesVisitor(session))
- ).forEach(visitorGroup -> {
- ops.forEach(op -> {
- lastAttemptedOperation.set(op);
- visitorGroup.forEach(op::accept);
- });
- });
+ // register namespaces first
+ singleton(new NamespacesVisitor(session)),
+ // then create node types and privileges, both use namespaces
+ asList(new NodetypesVisitor(session), new PrivilegeVisitor(session)),
+ // finally apply everything else
+ asList(
+ new UserVisitor(session),
+ new NodeVisitor(session),
+ new AclVisitor(session),
+ new GroupMembershipVisitor(session),
+ new NodePropertiesVisitor(session)))
+ .forEach(visitorGroup -> {
+ ops.forEach(op -> {
+ lastAttemptedOperation.set(op);
+ visitorGroup.forEach(op::accept);
+ });
+ });
} catch (RepoInitException originalFailure) {
handleLegacyOrderingSupport(session, ops, originalFailure, lastAttemptedOperation);
}
}
// support legacy statement reordering for backwards compatibility
- private static void handleLegacyOrderingSupport(Session session, List<Operation> ops, RepoInitException originalFailure, AtomicReference<Operation> lastAttemptedOperation) {
+ private static void handleLegacyOrderingSupport(
+ Session session,
+ List<Operation> ops,
+ RepoInitException originalFailure,
+ AtomicReference<Operation> lastAttemptedOperation) {
try {
session.refresh(false); // drop transient changes
final OperationVisitor[] visitors = {
- new NamespacesVisitor(session),
- new NodetypesVisitor(session),
- new PrivilegeVisitor(session),
- new UserVisitor(session),
- new NodeVisitor(session),
- new AclVisitor(session),
- new GroupMembershipVisitor(session),
- new NodePropertiesVisitor(session)
+ new NamespacesVisitor(session),
+ new NodetypesVisitor(session),
+ new PrivilegeVisitor(session),
+ new UserVisitor(session),
+ new NodeVisitor(session),
+ new AclVisitor(session),
+ new GroupMembershipVisitor(session),
+ new NodePropertiesVisitor(session)
};
for (OperationVisitor v : visitors) {
@@ -100,12 +103,15 @@ public class JcrRepoInitOpsProcessorImpl implements JcrRepoInitOpsProcessor {
}
}
- log.warn("DEPRECATION - The repoinit script being executed relies on a bug causing repoinit statements " +
- "to be reordered (SLING-12107). For now your repoinit script was applied successfully in legacy " +
- "mode. Please review and fix the ordering of your repoinit statements to avoid future issues. " +
- "The code supporting the legacy order will be removed in a future release. The new code " +
- "failed on the statement \"{}\". The original exception message was: {}",
- Optional.ofNullable(lastAttemptedOperation.get()).map(Operation::asRepoInitString).orElse("unknown"),
+ log.warn(
+ "DEPRECATION - The repoinit script being executed relies on a bug causing repoinit statements "
+ + "to be reordered (SLING-12107). For now your repoinit script was applied successfully in legacy "
+ + "mode. Please review and fix the ordering of your repoinit statements to avoid future issues. "
+ + "The code supporting the legacy order will be removed in a future release. The new code "
+ + "failed on the statement \"{}\". The original exception message was: {}",
+ Optional.ofNullable(lastAttemptedOperation.get())
+ .map(Operation::asRepoInitString)
+ .orElse("unknown"),
originalFailure.getMessage());
} catch (Exception legacyFailure) {
// rethrow the originalFailure if the legacy code also failed
diff --git a/src/main/java/org/apache/sling/jcr/repoinit/impl/NamespacesVisitor.java b/src/main/java/org/apache/sling/jcr/repoinit/impl/NamespacesVisitor.java
index b4d0ebb..896b8e8 100644
--- a/src/main/java/org/apache/sling/jcr/repoinit/impl/NamespacesVisitor.java
+++ b/src/main/java/org/apache/sling/jcr/repoinit/impl/NamespacesVisitor.java
@@ -1,18 +1,20 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
@@ -22,7 +24,7 @@ import javax.jcr.Session;
import org.apache.sling.repoinit.parser.operations.RegisterNamespace;
/** OperationVisitor which processes only operations related to
- * namespaces and nodetypes. Having several such specialized visitors
+ * namespaces and nodetypes. Having several such specialized visitors
* makes it easy to control the execution order.
*/
class NamespacesVisitor extends DoNothingVisitor {
@@ -34,14 +36,14 @@ class NamespacesVisitor extends DoNothingVisitor {
public NamespacesVisitor(Session s) {
super(s);
}
-
+
@Override
public void visitRegisterNamespace(RegisterNamespace rn) {
try {
final NamespaceRegistry reg = session.getWorkspace().getNamespaceRegistry();
log.info("Registering namespace from {}", rn);
reg.registerNamespace(rn.getPrefix(), rn.getURI());
- } catch(Exception e) {
+ } catch (Exception e) {
report(e, "Unable to register namespace from " + rn);
}
}
diff --git a/src/main/java/org/apache/sling/jcr/repoinit/impl/NodePropertiesVisitor.java b/src/main/java/org/apache/sling/jcr/repoinit/impl/NodePropertiesVisitor.java
index 7dfce05..b311bb4 100644
--- a/src/main/java/org/apache/sling/jcr/repoinit/impl/NodePropertiesVisitor.java
+++ b/src/main/java/org/apache/sling/jcr/repoinit/impl/NodePropertiesVisitor.java
@@ -1,27 +1,23 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.List;
-import java.util.stream.Stream;
-
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
@@ -32,6 +28,12 @@ import javax.jcr.Value;
import javax.jcr.nodetype.NodeType;
import javax.jcr.nodetype.PropertyDefinition;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.List;
+import java.util.stream.Stream;
+
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.util.Text;
import org.apache.jackrabbit.value.BooleanValue;
@@ -44,7 +46,6 @@ import org.apache.sling.repoinit.parser.operations.SetProperties;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-
/**
* OperationVisitor which processes only operations related to setting node
* properties. Having several such specialized visitors makes it easy to control
@@ -54,12 +55,13 @@ import org.jetbrains.annotations.Nullable;
class NodePropertiesVisitor extends DoNothingVisitor {
/**
* The repoinit.parser transforms the authorizable(ids)[/relative_path] path
- * syntax from the original source into ":authorizable:ids#/relative_path" in the
+ * syntax from the original source into ":authorizable:ids#/relative_path" in the
* values provided from {@link SetProperties#getPaths()}
- *
+ *
* These constants are used to unwind those values into the parts for processing
*/
private static final String PATH_AUTHORIZABLE = ":authorizable:";
+
private static final char ID_DELIMINATOR = ',';
private static final char SUBTREE_DELIMINATOR = '#';
@@ -79,7 +81,8 @@ class NodePropertiesVisitor extends DoNothingVisitor {
* @param parentNode the parent node where the property will be set
* @return the property definition of the property or null if it could not be determined
*/
- private static @Nullable PropertyDefinition resolvePropertyDefinition(@NotNull String propName, @NotNull Node parentNode) throws RepositoryException {
+ private static @Nullable PropertyDefinition resolvePropertyDefinition(
+ @NotNull String propName, @NotNull Node parentNode) throws RepositoryException {
NodeType primaryNodeType = parentNode.getPrimaryNodeType();
// try the primary type
PropertyDefinition propDef = resolvePropertyDefinition(propName, primaryNodeType);
@@ -104,11 +107,12 @@ class NodePropertiesVisitor extends DoNothingVisitor {
* @param nodeType the node type to be searched for the property definition
* @return the required type of the property or {@link PropertyType#UNDEFINED} if it could not be determined
*/
- private static @Nullable PropertyDefinition resolvePropertyDefinition(@NotNull String propName, @NotNull NodeType nodeType) {
+ private static @Nullable PropertyDefinition resolvePropertyDefinition(
+ @NotNull String propName, @NotNull NodeType nodeType) {
return Stream.of(nodeType.getPropertyDefinitions())
- .filter(pd -> propName.equals(pd.getName()))
- .findFirst()
- .orElse(null);
+ .filter(pd -> propName.equals(pd.getName()))
+ .findFirst()
+ .orElse(null);
}
/**
@@ -130,8 +134,7 @@ class NodePropertiesVisitor extends DoNothingVisitor {
// then allow the value to be changed.
return Arrays.equals(
pd.getDefaultValues(),
- property.isMultiple() ? property.getValues() : new Value[] {property.getValue()}
- );
+ property.isMultiple() ? property.getValues() : new Value[] {property.getValue()});
}
}
return false;
@@ -170,7 +173,8 @@ class NodePropertiesVisitor extends DoNothingVisitor {
* @throws RepositoryException
* @throws PathNotFoundException
*/
- private static boolean needToSetProperty(Session session, Authorizable a, String pRelPath, PropertyLine line) throws RepositoryException {
+ private static boolean needToSetProperty(Session session, Authorizable a, String pRelPath, PropertyLine line)
+ throws RepositoryException {
if (!line.isDefault()) {
// It's a "set" line -> overwrite existing value if any
return true;
@@ -216,7 +220,8 @@ class NodePropertiesVisitor extends DoNothingVisitor {
* @return iterator over the found authorizables
*/
@NotNull
- private static Iterable<Authorizable> getAuthorizables(@NotNull Session session, @NotNull String ids) throws RepositoryException {
+ private static Iterable<Authorizable> getAuthorizables(@NotNull Session session, @NotNull String ids)
+ throws RepositoryException {
List<Authorizable> authorizables = new ArrayList<>();
for (String id : Text.explode(ids, ID_DELIMINATOR)) {
Authorizable a = UserUtil.getAuthorizable(session, id);
@@ -230,11 +235,12 @@ class NodePropertiesVisitor extends DoNothingVisitor {
/**
* Set properties on a user or group
- *
+ *
* @param nodePath the target path
* @param propertyLines the property lines to process to set the properties
*/
- private void setAuthorizableProperties(String nodePath, List<PropertyLine> propertyLines) throws RepositoryException {
+ private void setAuthorizableProperties(String nodePath, List<PropertyLine> propertyLines)
+ throws RepositoryException {
int lastHashIndex = nodePath.lastIndexOf(SUBTREE_DELIMINATOR);
if (lastHashIndex == -1) {
throw new IllegalStateException("Invalid format of authorizable path: # deliminator expected.");
@@ -256,8 +262,10 @@ class NodePropertiesVisitor extends DoNothingVisitor {
a.setProperty(pRelPath, pValue);
}
} else {
- log.info("Property '{}' already set on authorizable '{}', existing value will not be overwritten in 'default' mode",
- pRelPath, a.getID());
+ log.info(
+ "Property '{}' already set on authorizable '{}', existing value will not be overwritten in 'default' mode",
+ pRelPath,
+ a.getID());
}
}
}
@@ -265,7 +273,7 @@ class NodePropertiesVisitor extends DoNothingVisitor {
/**
* Set properties on a JCR node
- *
+ *
* @param nodePath the target path
* @param propertyLines the property lines to process to set the properties
*/
@@ -275,13 +283,14 @@ class NodePropertiesVisitor extends DoNothingVisitor {
for (PropertyLine pl : propertyLines) {
final String pName = pl.getPropertyName();
if (needToSetProperty(n, pl)) {
- final int newType = PropertyType.valueFromName(pl.getPropertyType().name());
+ final int newType =
+ PropertyType.valueFromName(pl.getPropertyType().name());
Value[] newValues = convertToValues(pl.getPropertyValues());
- Property oldProperty = n.hasProperty(pName) ? n.getProperty(pName) : null;
+ Property oldProperty = n.hasProperty(pName) ? n.getProperty(pName) : null;
// only set property if type and/or values change
// note: Node#setProperty() touches the node even if the property value is unchanged
// and thus needs to be explicitly avoided
- if(hasPropertyChange(oldProperty, newType, newValues)) {
+ if (hasPropertyChange(oldProperty, newType, newValues)) {
if (newValues.length == 1) {
n.setProperty(pName, newValues[0], newType);
} else {
@@ -289,18 +298,22 @@ class NodePropertiesVisitor extends DoNothingVisitor {
}
}
} else {
- log.info("Property '{}' already set on path '{}', existing value will not be overwritten in 'default' mode",
- pName, nodePath);
+ log.info(
+ "Property '{}' already set on path '{}', existing value will not be overwritten in 'default' mode",
+ pName,
+ nodePath);
}
}
}
- private boolean hasPropertyChange(Property oldProperty, int newType, Value... newValues) throws RepositoryException {
+ private boolean hasPropertyChange(Property oldProperty, int newType, Value... newValues)
+ throws RepositoryException {
if (oldProperty == null || oldProperty.getType() != newType) {
return true;
}
- final Value[] oldValues = oldProperty.isMultiple() ? oldProperty.getValues() : new Value[]{ oldProperty.getValue() };
+ final Value[] oldValues =
+ oldProperty.isMultiple() ? oldProperty.getValues() : new Value[] {oldProperty.getValue()};
if (oldValues.length != newValues.length) {
return true;
}
@@ -316,8 +329,7 @@ class NodePropertiesVisitor extends DoNothingVisitor {
}
private static boolean valueEquals(Value oldValue, Value newValue) throws RepositoryException {
- return oldValue.getType() == newValue.getType()
- && oldValue.getString().equals(newValue.getString());
+ return oldValue.getType() == newValue.getType() && oldValue.getString().equals(newValue.getString());
}
@Override
@@ -339,8 +351,8 @@ class NodePropertiesVisitor extends DoNothingVisitor {
private Value[] convertToValues(List<Object> values) {
int size = values.size();
Value[] valueArray = new Value[size];
- for(int i = 0; i < size; i++) {
- valueArray[i] = convertToValue(values.get(i));
+ for (int i = 0; i < size; i++) {
+ valueArray[i] = convertToValue(values.get(i));
}
return valueArray;
}
diff --git a/src/main/java/org/apache/sling/jcr/repoinit/impl/NodeVisitor.java b/src/main/java/org/apache/sling/jcr/repoinit/impl/NodeVisitor.java
index 33c98a9..9235eb8 100644
--- a/src/main/java/org/apache/sling/jcr/repoinit/impl/NodeVisitor.java
+++ b/src/main/java/org/apache/sling/jcr/repoinit/impl/NodeVisitor.java
@@ -1,31 +1,31 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.nodetype.ConstraintViolationException;
+import java.util.Collections;
+import java.util.List;
+
import org.apache.sling.repoinit.parser.operations.AddMixins;
import org.apache.sling.repoinit.parser.operations.CreatePath;
import org.apache.sling.repoinit.parser.operations.EnsureNodes;
@@ -63,7 +63,8 @@ public class NodeVisitor extends DoNothingVisitor {
createNodes(cp.getDefinitions(), cp.getPropertyLines(), false);
}
- private void createNodes(List<PathSegmentDefinition> pathSegmentDefinitions, List<PropertyLine> propertyLines, boolean strict) {
+ private void createNodes(
+ List<PathSegmentDefinition> pathSegmentDefinitions, List<PropertyLine> propertyLines, boolean strict) {
StringBuilder parentPathBuilder = new StringBuilder();
for (PathSegmentDefinition psd : pathSegmentDefinitions) {
String parentPath = parentPathBuilder.toString();
@@ -74,7 +75,8 @@ public class NodeVisitor extends DoNothingVisitor {
if (session.nodeExists(fullPath)) {
log.info("Node at {} already exists, checking/adjusting its types", fullPath);
node = session.getNode(fullPath);
- if (psd.getPrimaryType() != null && !node.getPrimaryNodeType().getName().equals(psd.getPrimaryType())) {
+ if (psd.getPrimaryType() != null
+ && !node.getPrimaryNodeType().getName().equals(psd.getPrimaryType())) {
log.info("Adjusting primary type of node {} to {}", fullPath, psd.getPrimaryType());
node.setPrimaryType(psd.getPrimaryType());
}
@@ -82,13 +84,17 @@ public class NodeVisitor extends DoNothingVisitor {
final Node parent = parentPath.equals("") ? session.getRootNode() : session.getNode(parentPath);
log.info("Creating node {} with primary type {}", fullPath, psd.getPrimaryType());
node = addChildNode(parent, psd);
-
+
} else {
- throw new RepoInitException("There is a property with the name of the to be created node already at " + fullPath + ", therefore bailing out here as potentially not supported by the underlying JCR");
+ throw new RepoInitException(
+ "There is a property with the name of the to be created node already at " + fullPath
+ + ", therefore bailing out here as potentially not supported by the underlying JCR");
}
} else {
if (session.itemExists(fullPath)) {
- log.info("Path already exists, nothing to do (and not checking its primary type for now): {}", fullPath);
+ log.info(
+ "Path already exists, nothing to do (and not checking its primary type for now): {}",
+ fullPath);
node = null;
} else {
final Node parent = parentPath.equals("") ? session.getRootNode() : session.getNode(parentPath);
@@ -96,7 +102,7 @@ public class NodeVisitor extends DoNothingVisitor {
node = addChildNode(parent, psd);
}
}
-
+
if (node != null) {
List<String> mixins = psd.getMixins();
if (mixins != null) {
@@ -113,7 +119,8 @@ public class NodeVisitor extends DoNothingVisitor {
}
if (!propertyLines.isEmpty()) {
// delegate to the NodePropertiesVisitor to set the properties
- SetProperties sp = new SetProperties(Collections.singletonList(parentPathBuilder.toString()), propertyLines);
+ SetProperties sp =
+ new SetProperties(Collections.singletonList(parentPathBuilder.toString()), propertyLines);
NodePropertiesVisitor npv = new NodePropertiesVisitor(session);
npv.visitSetProperties(sp);
}
@@ -177,7 +184,8 @@ public class NodeVisitor extends DoNothingVisitor {
}
@NotNull
- private static Node addChildNode(@NotNull Node parent, @NotNull PathSegmentDefinition psd) throws RepositoryException {
+ private static Node addChildNode(@NotNull Node parent, @NotNull PathSegmentDefinition psd)
+ throws RepositoryException {
String primaryType = psd.getPrimaryType();
if (primaryType == null) {
try {
@@ -191,6 +199,4 @@ public class NodeVisitor extends DoNothingVisitor {
return parent.addNode(psd.getSegment(), psd.getPrimaryType());
}
}
-
-
}
diff --git a/src/main/java/org/apache/sling/jcr/repoinit/impl/NodetypesVisitor.java b/src/main/java/org/apache/sling/jcr/repoinit/impl/NodetypesVisitor.java
index ea8bdfa..2065b0e 100644
--- a/src/main/java/org/apache/sling/jcr/repoinit/impl/NodetypesVisitor.java
+++ b/src/main/java/org/apache/sling/jcr/repoinit/impl/NodetypesVisitor.java
@@ -1,30 +1,32 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
-import java.io.StringReader;
-
import javax.jcr.Session;
+import java.io.StringReader;
+
import org.apache.jackrabbit.commons.cnd.CndImporter;
import org.apache.sling.repoinit.parser.operations.RegisterNodetypes;
/** OperationVisitor which processes only operations related to
- * namespaces and nodetypes. Having several such specialized visitors
+ * namespaces and nodetypes. Having several such specialized visitors
* makes it easy to control the execution order.
*/
class NodetypesVisitor extends DoNothingVisitor {
@@ -36,7 +38,7 @@ class NodetypesVisitor extends DoNothingVisitor {
public NodetypesVisitor(Session s) {
super(s);
}
-
+
@Override
public void visitRegisterNodetypes(RegisterNodetypes rn) {
try {
@@ -44,7 +46,7 @@ class NodetypesVisitor extends DoNothingVisitor {
log.info("Registering nodetypes from {}", excerpt(rn.getCndStatements(), 100));
}
CndImporter.registerNodeTypes(new StringReader(rn.getCndStatements()), session);
- } catch(Exception e) {
+ } catch (Exception e) {
report(e, "Unable to register nodetypes from " + rn);
}
}
diff --git a/src/main/java/org/apache/sling/jcr/repoinit/impl/PrivilegeVisitor.java b/src/main/java/org/apache/sling/jcr/repoinit/impl/PrivilegeVisitor.java
index 9dfb90b..7b7aa33 100644
--- a/src/main/java/org/apache/sling/jcr/repoinit/impl/PrivilegeVisitor.java
+++ b/src/main/java/org/apache/sling/jcr/repoinit/impl/PrivilegeVisitor.java
@@ -1,29 +1,30 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
-
-import org.apache.jackrabbit.api.JackrabbitWorkspace;
-import org.apache.sling.repoinit.parser.operations.RegisterPrivilege;
-
import javax.jcr.Session;
import javax.jcr.security.AccessControlException;
import javax.jcr.security.Privilege;
+import org.apache.jackrabbit.api.JackrabbitWorkspace;
+import org.apache.sling.repoinit.parser.operations.RegisterPrivilege;
+
public class PrivilegeVisitor extends DoNothingVisitor {
public PrivilegeVisitor(Session session) {
super(session);
@@ -32,12 +33,18 @@ public class PrivilegeVisitor extends DoNothingVisitor {
@Override
public void visitRegisterPrivilege(RegisterPrivilege rp) {
try {
- Privilege priv = ((JackrabbitWorkspace) session.getWorkspace()).getPrivilegeManager().getPrivilege(rp.getPrivilegeName());
+ Privilege priv = ((JackrabbitWorkspace) session.getWorkspace())
+ .getPrivilegeManager()
+ .getPrivilege(rp.getPrivilegeName());
log.info("Privilege {} already exists: {}, no changes made.", rp.getPrivilegeName(), priv);
} catch (AccessControlException ace) {
try {
- ((JackrabbitWorkspace) session.getWorkspace()).getPrivilegeManager()
- .registerPrivilege(rp.getPrivilegeName(), rp.isAbstract(), rp.getDeclaredAggregateNames().toArray(new String[0]));
+ ((JackrabbitWorkspace) session.getWorkspace())
+ .getPrivilegeManager()
+ .registerPrivilege(
+ rp.getPrivilegeName(),
+ rp.isAbstract(),
+ rp.getDeclaredAggregateNames().toArray(new String[0]));
} catch (Exception ex) {
report(ex, "Unable to register privilege from: " + rp);
}
diff --git a/src/main/java/org/apache/sling/jcr/repoinit/impl/RepoInitException.java b/src/main/java/org/apache/sling/jcr/repoinit/impl/RepoInitException.java
index 72223c1..d372423 100644
--- a/src/main/java/org/apache/sling/jcr/repoinit/impl/RepoInitException.java
+++ b/src/main/java/org/apache/sling/jcr/repoinit/impl/RepoInitException.java
@@ -1,18 +1,20 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
@@ -31,5 +33,4 @@ public class RepoInitException extends RuntimeException {
public RepoInitException(String msg) {
super(msg);
}
-
}
diff --git a/src/main/java/org/apache/sling/jcr/repoinit/impl/RepoinitTextProvider.java b/src/main/java/org/apache/sling/jcr/repoinit/impl/RepoinitTextProvider.java
index 5c72eee..f7aa517 100644
--- a/src/main/java/org/apache/sling/jcr/repoinit/impl/RepoinitTextProvider.java
+++ b/src/main/java/org/apache/sling/jcr/repoinit/impl/RepoinitTextProvider.java
@@ -1,18 +1,20 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
@@ -39,34 +41,34 @@ import org.slf4j.LoggerFactory;
/** Retrieves repoinit statements from URLs that return either
* raw repoinit text or Sling provisioning models that are parsed
* to extract the repoinit text.
- *
+ *
* Uses references like
- *
+ *
* <code>model@repoinit:context:/resources/provisioning/model</code>,
- *
- * meaning that the supplied context:/ URI returns a provisioning model
+ *
+ * meaning that the supplied context:/ URI returns a provisioning model
* containing repoinit statements in its "repoinit" additional section, or
- *
+ *
*
* <code>raw:classpath://com.example.sling.repoinit/repoinit.txt</code>
- *
+ *
* meaning that the supplied classpath: URI returns raw repoinit statements.
*/
public class RepoinitTextProvider {
- public enum TextFormat {
- RAW("raw"),
+ public enum TextFormat {
+ RAW("raw"),
MODEL("model");
private String type;
TextFormat(String type) {
this.type = type;
- }
+ }
public static TextFormat fromType(String v) {
Optional<TextFormat> findFirst = Stream.of(TextFormat.values())
- .filter(tf -> tf.type.equals(v))
- .findFirst();
+ .filter(tf -> tf.type.equals(v))
+ .findFirst();
if (!findFirst.isPresent()) {
throw new IllegalArgumentException("Value not found: " + v);
}
@@ -78,6 +80,7 @@ public class RepoinitTextProvider {
return type;
}
}
+
private static final String DEFAULT_MODEL_SECTION = "repoinit";
public static final Pattern REF_PATTERN = Pattern.compile("([a-z]+)(@([a-zA-Z0-9_-]+))?:(.*)");
@@ -100,7 +103,7 @@ public class RepoinitTextProvider {
format = TextFormat.fromType(m.group(1));
if (format.equals(TextFormat.RAW)) {
modelSection = null;
- } else if(format.equals(TextFormat.MODEL) && m.group(3) == null) {
+ } else if (format.equals(TextFormat.MODEL) && m.group(3) == null) {
modelSection = DEFAULT_MODEL_SECTION;
} else {
modelSection = m.group(3);
@@ -113,7 +116,7 @@ public class RepoinitTextProvider {
final StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName()).append(":");
sb.append("format=").append(format);
- if(modelSection != null) {
+ if (modelSection != null) {
sb.append(", model section=").append(modelSection);
}
sb.append(", URL=").append(url);
@@ -128,7 +131,7 @@ public class RepoinitTextProvider {
log.debug("Raw text from {}: \n{}", ref.url, rawText);
if (TextFormat.MODEL.equals(ref.format)) {
log.debug("Extracting provisioning model section {}", ref.modelSection);
- return extractFromModel(ref.url, rawText, ref.modelSection);
+ return extractFromModel(ref.url, rawText, ref.modelSection);
} else {
return rawText;
}
@@ -143,7 +146,11 @@ public class RepoinitTextProvider {
}
for (final Feature feature : model.getFeatures()) {
for (final Section section : feature.getAdditionalSections(modelSection)) {
- sb.append("# ").append(modelSection).append(" from ").append(feature.getName()).append("\n");
+ sb.append("# ")
+ .append(modelSection)
+ .append(" from ")
+ .append(feature.getName())
+ .append("\n");
sb.append("# ").append(section.getComment()).append("\n");
sb.append(section.getContents()).append("\n");
}
diff --git a/src/main/java/org/apache/sling/jcr/repoinit/impl/RepositoryInitializer.java b/src/main/java/org/apache/sling/jcr/repoinit/impl/RepositoryInitializer.java
index 8d822ba..aefc0d2 100644
--- a/src/main/java/org/apache/sling/jcr/repoinit/impl/RepositoryInitializer.java
+++ b/src/main/java/org/apache/sling/jcr/repoinit/impl/RepositoryInitializer.java
@@ -1,29 +1,31 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
import java.io.IOException;
import java.io.StringReader;
import java.util.Arrays;
import java.util.List;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
import org.apache.sling.jcr.api.SlingRepository;
import org.apache.sling.jcr.api.SlingRepositoryInitializer;
import org.apache.sling.jcr.repoinit.JcrRepoInitOpsProcessor;
@@ -45,30 +47,31 @@ import org.slf4j.LoggerFactory;
* from a configurable URL.
*/
@Designate(ocd = RepositoryInitializer.Config.class)
-@Component(service = SlingRepositoryInitializer.class,
- configurationPolicy=ConfigurationPolicy.REQUIRE,
- property = {
+@Component(
+ service = SlingRepositoryInitializer.class,
+ configurationPolicy = ConfigurationPolicy.REQUIRE,
+ property = {
Constants.SERVICE_VENDOR + "=The Apache Software Foundation",
// SlingRepositoryInitializers are executed in ascending
// order of their service ranking
Constants.SERVICE_RANKING + ":Integer=100"
- })
+ })
public class RepositoryInitializer implements SlingRepositoryInitializer {
- @ObjectClassDefinition(name = "Apache Sling Repository Initializer",
- description="Initializes the JCR content repository using repoinit statements")
+ @ObjectClassDefinition(
+ name = "Apache Sling Repository Initializer",
+ description = "Initializes the JCR content repository using repoinit statements")
public @interface Config {
- @AttributeDefinition(name="Repoinit references",
- description=
- "References to the source text that provides repoinit statements."
- + " format is either model@repoinit:<provisioning model URL> or raw:<raw URL>")
+ @AttributeDefinition(
+ name = "Repoinit references",
+ description = "References to the source text that provides repoinit statements."
+ + " format is either model@repoinit:<provisioning model URL> or raw:<raw URL>")
String[] references() default {};
}
private final Logger log = LoggerFactory.getLogger(getClass());
-
@Reference
private RepoInitParser parser;
@@ -90,13 +93,13 @@ public class RepositoryInitializer implements SlingRepositoryInitializer {
@Override
public void processRepository(SlingRepository repo) throws RepositoryException {
- if ( config.references() != null && config.references().length > 0 ) {
+ if (config.references() != null && config.references().length > 0) {
// loginAdministrative is ok here, definitely an admin operation
@SuppressWarnings("deprecation")
final Session s = repo.loginAdministrative(null);
try {
final RepoinitTextProvider p = new RepoinitTextProvider();
- for(String reference : config.references()) {
+ for (String reference : config.references()) {
try {
final String repoinitText = p.getRepoinitText(reference);
final List<Operation> ops;
@@ -108,7 +111,7 @@ public class RepositoryInitializer implements SlingRepositoryInitializer {
if (s.hasPendingChanges()) {
s.save();
}
- } catch (IOException|RuntimeException|RepositoryException|RepoInitParsingException e) {
+ } catch (IOException | RuntimeException | RepositoryException | RepoInitParsingException e) {
throw new RepoInitException("Error executing repoinit from " + reference, e);
}
}
diff --git a/src/main/java/org/apache/sling/jcr/repoinit/impl/RepositoryInitializerFactory.java b/src/main/java/org/apache/sling/jcr/repoinit/impl/RepositoryInitializerFactory.java
index a27477e..24f1344 100644
--- a/src/main/java/org/apache/sling/jcr/repoinit/impl/RepositoryInitializerFactory.java
+++ b/src/main/java/org/apache/sling/jcr/repoinit/impl/RepositoryInitializerFactory.java
@@ -1,31 +1,33 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
+import javax.jcr.InvalidItemStateException;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
import java.io.StringReader;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
-import javax.jcr.InvalidItemStateException;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
import org.apache.sling.commons.metrics.MetricsService;
import org.apache.sling.jcr.api.SlingRepository;
import org.apache.sling.jcr.api.SlingRepositoryInitializer;
@@ -50,32 +52,32 @@ import org.slf4j.LoggerFactory;
* through OSGi configurations. A configuration can contain URLs from which the
* statements are read or inlined statements.
*/
-@Designate(ocd = RepositoryInitializerFactory.Config.class, factory=true)
-@Component(service = SlingRepositoryInitializer.class,
- configurationPolicy=ConfigurationPolicy.REQUIRE,
- configurationPid = "org.apache.sling.jcr.repoinit.RepositoryInitializer",
- property = {
+@Designate(ocd = RepositoryInitializerFactory.Config.class, factory = true)
+@Component(
+ service = SlingRepositoryInitializer.class,
+ configurationPolicy = ConfigurationPolicy.REQUIRE,
+ configurationPid = "org.apache.sling.jcr.repoinit.RepositoryInitializer",
+ property = {
Constants.SERVICE_VENDOR + "=The Apache Software Foundation",
// SlingRepositoryInitializers are executed in ascending
// order of their service ranking
Constants.SERVICE_RANKING + ":Integer=100"
- })
+ })
public class RepositoryInitializerFactory implements SlingRepositoryInitializer {
- @ObjectClassDefinition(name = "Apache Sling Repository Initializer Factory",
- description="Initializes the JCR content repository using repoinit statements.")
- public @interface Config {
+ @ObjectClassDefinition(
+ name = "Apache Sling Repository Initializer Factory",
+ description = "Initializes the JCR content repository using repoinit statements.")
+ public @interface Config {
- @AttributeDefinition(name="References",
- description=
- "References to the source text that provides repoinit statements."
- + " format is a raw URL.")
- String[] references() default {};
+ @AttributeDefinition(
+ name = "References",
+ description =
+ "References to the source text that provides repoinit statements." + " format is a raw URL.")
+ String[] references() default {};
- @AttributeDefinition(name="Scripts",
- description=
- "Contents of a repo init script.")
- String[] scripts() default {};
+ @AttributeDefinition(name = "Scripts", description = "Contents of a repo init script.")
+ String[] scripts() default {};
}
private final Logger log = LoggerFactory.getLogger(getClass());
@@ -87,22 +89,22 @@ public class RepositoryInitializerFactory implements SlingRepositoryInitializer
@Reference
private JcrRepoInitOpsProcessor processor;
-
+
@Reference
MetricsService metrics;
private RepositoryInitializerFactory.Config config;
-
+
// assume that repoinit succeeds ... and just this to true if it fails
private AtomicBoolean aRepoInitStatementFailed = new AtomicBoolean(false);
-
private String componentId;
@Activate
public void activate(final RepositoryInitializerFactory.Config config, Map<String, Object> properties) {
this.config = config;
- this.componentId = properties.getOrDefault(ComponentConstants.COMPONENT_ID, "").toString();
+ this.componentId =
+ properties.getOrDefault(ComponentConstants.COMPONENT_ID, "").toString();
log.debug("Activated: {}", this);
metrics.gauge(METRIC_REPOINIT_FAILED, this::failureStateAsMetric);
}
@@ -116,17 +118,17 @@ public class RepositoryInitializerFactory implements SlingRepositoryInitializer
@Override
public void processRepository(final SlingRepository repo) throws Exception {
- if ( (config.references() != null && config.references().length > 0)
- || (config.scripts() != null && config.scripts().length > 0 )) {
+ if ((config.references() != null && config.references().length > 0)
+ || (config.scripts() != null && config.scripts().length > 0)) {
// loginAdministrative is ok here, definitely an admin operation
@SuppressWarnings("deprecation")
final Session s = repo.loginAdministrative(null);
try {
- if ( config.references() != null ) {
+ if (config.references() != null) {
final RepoinitTextProvider p = new RepoinitTextProvider();
- for(final String reference : config.references()) {
- if(reference == null || reference.trim().length() == 0) {
+ for (final String reference : config.references()) {
+ if (reference == null || reference.trim().length() == 0) {
continue;
}
final String repoinitText = p.getRepoinitText("raw:" + reference);
@@ -134,26 +136,30 @@ public class RepositoryInitializerFactory implements SlingRepositoryInitializer
try (StringReader sr = new StringReader(repoinitText)) {
ops = parser.parse(sr);
}
- String sourceReference = String.format("Configuration PID %s, reference URL %s", componentId, reference);
- String msg = String.format("Executing %s repoinit operations from \"%s\"", ops.size(), sourceReference);
+ String sourceReference =
+ String.format("Configuration PID %s, reference URL %s", componentId, reference);
+ String msg = String.format(
+ "Executing %s repoinit operations from \"%s\"", ops.size(), sourceReference);
log.info(msg);
- applyOperations(s,ops,msg, sourceReference);
+ applyOperations(s, ops, msg, sourceReference);
}
}
- if ( config.scripts() != null ) {
+ if (config.scripts() != null) {
int scriptIndex = 0;
- for(final String script : config.scripts()) {
- if(script == null || script.trim().length() == 0) {
+ for (final String script : config.scripts()) {
+ if (script == null || script.trim().length() == 0) {
continue;
}
final List<Operation> ops;
try (StringReader sr = new StringReader(script)) {
ops = parser.parse(sr);
}
- String sourceReference = String.format("Configuration PID %s, script[%d]", componentId, scriptIndex);
- String msg = String.format("Executing %s repoinit operations from \"%s\"", ops.size(), sourceReference);
+ String sourceReference =
+ String.format("Configuration PID %s, script[%d]", componentId, scriptIndex);
+ String msg = String.format(
+ "Executing %s repoinit operations from \"%s\"", ops.size(), sourceReference);
log.info(msg);
- applyOperations(s,ops,msg, sourceReference);
+ applyOperations(s, ops, msg, sourceReference);
scriptIndex++;
}
}
@@ -171,13 +177,20 @@ public class RepositoryInitializerFactory implements SlingRepositoryInitializer
* @param reference the reference identifying the source of the repoinit script
* @throws Exception if the application fails despite the retry
*/
- protected void applyOperations(Session session, List<Operation> ops, String logMessage, String reference) throws RepositoryException {
-
- RetryableOperation retry = new RetryableOperation.Builder().withBackoffBaseMsec(1000).withMaxRetries(3).build();
- RetryableOperation.RetryableOperationResult result = applyOperationInternal(session, ops, logMessage, reference, retry);
+ protected void applyOperations(Session session, List<Operation> ops, String logMessage, String reference)
+ throws RepositoryException {
+
+ RetryableOperation retry = new RetryableOperation.Builder()
+ .withBackoffBaseMsec(1000)
+ .withMaxRetries(3)
+ .build();
+ RetryableOperation.RetryableOperationResult result =
+ applyOperationInternal(session, ops, logMessage, reference, retry);
if (!result.isSuccessful()) {
- String msg = String.format("Applying repoinit operation failed despite retry; set loglevel to DEBUG to see all exceptions. "
- + "Last exception message from \"%s\" was: %s", result.getReference(), result.getFailureTrace().getMessage());
+ String msg = String.format(
+ "Applying repoinit operation failed despite retry; set loglevel to DEBUG to see all exceptions. "
+ + "Last exception message from \"%s\" was: %s",
+ result.getReference(), result.getFailureTrace().getMessage());
aRepoInitStatementFailed.set(true);
throw new RepositoryException(msg, result.getFailureTrace());
}
@@ -192,36 +205,38 @@ public class RepositoryInitializerFactory implements SlingRepositoryInitializer
* @param retry the retry object
* @return
*/
- protected RetryableOperationResult applyOperationInternal(Session session, List<Operation> ops, String logMessage,
- String reference, RetryableOperation retry) {
- return retry.apply(() -> {
- try {
- processor.apply(session, ops);
- if (session.hasPendingChanges()) {
- session.save();
- }
- return new RetryableOperation.RetryableOperationResult(true,false,reference,null);
- } catch (InvalidItemStateException|RepoInitException ex) {
- // a retry makes sense, because this exception might be caused by an concurrent operation
- log.debug("(temporarily) failed to apply repoinit operations",ex);
- try {
- session.refresh(false); // discard all pending changes
- } catch (RepositoryException e1) {
- // ignore
- }
- return new RetryableOperation.RetryableOperationResult(false,true,reference,ex);
- } catch (RepositoryException ex) {
- // a permanent error, retry is not useful
- try {
- session.refresh(false); // discard all pending changes
- } catch (RepositoryException e1) {
- // ignore
- }
- return new RetryableOperation.RetryableOperationResult(false,false,reference,ex);
- }
- }, logMessage);
+ protected RetryableOperationResult applyOperationInternal(
+ Session session, List<Operation> ops, String logMessage, String reference, RetryableOperation retry) {
+ return retry.apply(
+ () -> {
+ try {
+ processor.apply(session, ops);
+ if (session.hasPendingChanges()) {
+ session.save();
+ }
+ return new RetryableOperation.RetryableOperationResult(true, false, reference, null);
+ } catch (InvalidItemStateException | RepoInitException ex) {
+ // a retry makes sense, because this exception might be caused by an concurrent operation
+ log.debug("(temporarily) failed to apply repoinit operations", ex);
+ try {
+ session.refresh(false); // discard all pending changes
+ } catch (RepositoryException e1) {
+ // ignore
+ }
+ return new RetryableOperation.RetryableOperationResult(false, true, reference, ex);
+ } catch (RepositoryException ex) {
+ // a permanent error, retry is not useful
+ try {
+ session.refresh(false); // discard all pending changes
+ } catch (RepositoryException e1) {
+ // ignore
+ }
+ return new RetryableOperation.RetryableOperationResult(false, false, reference, ex);
+ }
+ },
+ logMessage);
}
-
+
/**
* return the state of the repoinit execution usable for a simple gauge metric
* @return 1 if repoinit did not finish successfully, 0 otherwise
@@ -229,7 +244,4 @@ public class RepositoryInitializerFactory implements SlingRepositoryInitializer
protected int failureStateAsMetric() {
return aRepoInitStatementFailed.get() ? 1 : 0;
}
-
-
-
}
diff --git a/src/main/java/org/apache/sling/jcr/repoinit/impl/RetryableOperation.java b/src/main/java/org/apache/sling/jcr/repoinit/impl/RetryableOperation.java
index 14601b6..d1f61da 100644
--- a/src/main/java/org/apache/sling/jcr/repoinit/impl/RetryableOperation.java
+++ b/src/main/java/org/apache/sling/jcr/repoinit/impl/RetryableOperation.java
@@ -1,18 +1,20 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
@@ -38,6 +40,7 @@ public class RetryableOperation {
@SuppressWarnings("java:S2245") // we don't do crypto stuff here
Random random = new Random();
+
int retryCount = 0;
RetryableOperation(int backoff, int maxRetries, int jitter) {
@@ -76,7 +79,6 @@ public class RetryableOperation {
}
}
-
/**
* A simple wrapper for the results
*/
@@ -95,7 +97,7 @@ public class RetryableOperation {
* @param reference the reference identifying the source of the repoinit script
* @param trace the exception trace (if any)
*/
- RetryableOperationResult (boolean successful, boolean shouldRetry, String reference, Exception trace) {
+ RetryableOperationResult(boolean successful, boolean shouldRetry, String reference, Exception trace) {
this.successful = successful;
this.shouldRetry = shouldRetry;
this.reference = reference;
@@ -141,7 +143,7 @@ public class RetryableOperation {
* @return the builder
*/
Builder withMaxRetries(int retries) {
- this.maxRetries= retries;
+ this.maxRetries = retries;
return this;
}
@@ -156,8 +158,7 @@ public class RetryableOperation {
}
RetryableOperation build() {
- return new RetryableOperation(exponentialBackoff,maxRetries, jitter);
+ return new RetryableOperation(exponentialBackoff, maxRetries, jitter);
}
}
-
}
diff --git a/src/main/java/org/apache/sling/jcr/repoinit/impl/UserUtil.java b/src/main/java/org/apache/sling/jcr/repoinit/impl/UserUtil.java
index 50e57c7..42643b9 100644
--- a/src/main/java/org/apache/sling/jcr/repoinit/impl/UserUtil.java
+++ b/src/main/java/org/apache/sling/jcr/repoinit/impl/UserUtil.java
@@ -1,21 +1,29 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.UnsupportedRepositoryOperationException;
+
+import java.security.Principal;
+
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.principal.PrincipalManager;
import org.apache.jackrabbit.api.security.user.Authorizable;
@@ -24,11 +32,6 @@ import org.apache.jackrabbit.api.security.user.UserManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.UnsupportedRepositoryOperationException;
-import java.security.Principal;
-
/** Utilities for User management */
public class UserUtil {
@@ -41,7 +44,7 @@ public class UserUtil {
private final String name;
SameNamePrincipal(String name) {
- if(name == null) {
+ if (name == null) {
throw new IllegalArgumentException("Name cannot be null");
}
this.name = name;
@@ -54,9 +57,7 @@ public class UserUtil {
@Override
public boolean equals(Object other) {
- return (
- other instanceof SameNamePrincipal)
- && (this.name.equals(((SameNamePrincipal)other).name));
+ return (other instanceof SameNamePrincipal) && (this.name.equals(((SameNamePrincipal) other).name));
}
@Override
@@ -66,17 +67,17 @@ public class UserUtil {
}
public static PrincipalManager getPrincipalManager(Session session) throws RepositoryException {
- if(!(session instanceof JackrabbitSession)) {
+ if (!(session instanceof JackrabbitSession)) {
throw new IllegalArgumentException("Session is not a JackrabbitSession");
}
- return ((JackrabbitSession)session).getPrincipalManager();
+ return ((JackrabbitSession) session).getPrincipalManager();
}
public static UserManager getUserManager(Session session) throws RepositoryException {
- if(!(session instanceof JackrabbitSession)) {
+ if (!(session instanceof JackrabbitSession)) {
throw new IllegalArgumentException("Session is not a JackrabbitSession");
}
- return ((JackrabbitSession)session).getUserManager();
+ return ((JackrabbitSession) session).getUserManager();
}
public static Authorizable getAuthorizable(Session session, String id) throws RepositoryException {
@@ -94,11 +95,10 @@ public class UserUtil {
public static boolean deleteAuthorizable(Session session, String id) throws RepositoryException {
final Authorizable authorizable = getUserManager(session).getAuthorizable(id);
- if(authorizable != null) {
+ if (authorizable != null) {
authorizable.remove();
return true;
- }
- else {
+ } else {
return false;
}
}
@@ -112,16 +112,16 @@ public class UserUtil {
if (authorizable.isGroup()) {
throw new IllegalStateException("Can't disable a group: " + id);
}
- ((User)authorizable).disable(reason);
+ ((User) authorizable).disable(reason);
return true;
- }
- else {
+ } else {
return false;
}
}
/** Create a user - fails if it already exists */
- public static void createUser(Session session, String username, String password, String path) throws RepositoryException {
+ public static void createUser(Session session, String username, String password, String path)
+ throws RepositoryException {
if (path == null) {
getUserManager(session).createUser(username, password);
} else {
diff --git a/src/main/java/org/apache/sling/jcr/repoinit/impl/UserVisitor.java b/src/main/java/org/apache/sling/jcr/repoinit/impl/UserVisitor.java
index 48a5e0f..9ccf331 100644
--- a/src/main/java/org/apache/sling/jcr/repoinit/impl/UserVisitor.java
+++ b/src/main/java/org/apache/sling/jcr/repoinit/impl/UserVisitor.java
@@ -1,21 +1,26 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.User;
@@ -30,9 +35,6 @@ import org.apache.sling.repoinit.parser.operations.DisableServiceUser;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
import static org.apache.sling.jcr.repoinit.impl.UserUtil.getPath;
import static org.apache.sling.jcr.repoinit.impl.UserUtil.getUserManager;
@@ -45,7 +47,7 @@ class UserVisitor extends DoNothingVisitor {
/**
* Create a visitor using the supplied JCR Session.
- *
+ *
* @param s must have sufficient rights to create users and set ACLs.
*/
public UserVisitor(Session s) {
@@ -125,7 +127,9 @@ class UserVisitor extends DoNothingVisitor {
// TODO we might revise this warning once we're able
// to create users by providing their encoded password
// using u.getPasswordEncoding - for now I think only cleartext works
- log.warn("Creating user {} with cleartext password - should NOT be used on production systems", username);
+ log.warn(
+ "Creating user {} with cleartext password - should NOT be used on production systems",
+ username);
} else {
log.info("Creating user {}", username);
}
@@ -153,7 +157,7 @@ class UserVisitor extends DoNothingVisitor {
public void visitDisableServiceUser(DisableServiceUser dsu) {
final String username = dsu.getUsername();
final String reason = dsu.getReason();
- log.info("Disabling service user {} reason {}", username, reason );
+ log.info("Disabling service user {} reason {}", username, reason);
try {
if (!UserUtil.disableUser(session, username, reason)) {
log.debug("Service user {} doesn't exist - assuming disable to be a noop.", username);
@@ -165,21 +169,37 @@ class UserVisitor extends DoNothingVisitor {
private void checkUserType(@NotNull String id, @Nullable User user, boolean expectedSystemUser) {
if (user != null && user.isSystemUser() != expectedSystemUser) {
- String msg = (expectedSystemUser) ? "Existing user %s is not a service user." : "Existing user %s is a service user.";
+ String msg = (expectedSystemUser)
+ ? "Existing user %s is not a service user."
+ : "Existing user %s is a service user.";
report(String.format(msg, id));
}
}
- private boolean needsRecreate(@NotNull String id, @NotNull Authorizable authorizable, @NotNull String intermediatePath, @NotNull String type) throws RepositoryException {
+ private boolean needsRecreate(
+ @NotNull String id,
+ @NotNull Authorizable authorizable,
+ @NotNull String intermediatePath,
+ @NotNull String type)
+ throws RepositoryException {
String path = getPath(authorizable);
if (path != null) {
String requiredIntermediate = intermediatePath + "/";
if (!path.contains(requiredIntermediate)) {
- log.info("Recreating {} '{}' with path '{}' to match required intermediate path '{}'", type, id, path, intermediatePath);
+ log.info(
+ "Recreating {} '{}' with path '{}' to match required intermediate path '{}'",
+ type,
+ id,
+ path,
+ intermediatePath);
authorizable.remove();
return true;
} else {
- log.info("{} '{}' already exists with required intermediate path '{}', no changes made.", type, id, intermediatePath);
+ log.info(
+ "{} '{}' already exists with required intermediate path '{}', no changes made.",
+ type,
+ id,
+ intermediatePath);
}
} else {
log.error("{} '{}' already exists but path cannot be determined, no changes made.", type, id);
diff --git a/src/main/java/org/apache/sling/jcr/repoinit/package-info.java b/src/main/java/org/apache/sling/jcr/repoinit/package-info.java
index 70246fb..ce24803 100644
--- a/src/main/java/org/apache/sling/jcr/repoinit/package-info.java
+++ b/src/main/java/org/apache/sling/jcr/repoinit/package-info.java
@@ -14,7 +14,5 @@
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
-
@org.osgi.annotation.versioning.Version("1.1.2")
package org.apache.sling.jcr.repoinit;
-
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/CreateGroupsTest.java b/src/test/java/org/apache/sling/jcr/repoinit/CreateGroupsTest.java
index beee1fe..898191e 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/CreateGroupsTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/CreateGroupsTest.java
@@ -1,26 +1,28 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit;
+import javax.jcr.RepositoryException;
+
import java.util.Collections;
import java.util.Random;
-import javax.jcr.RepositoryException;
-
import org.apache.jackrabbit.api.security.user.AuthorizableTypeException;
import org.apache.sling.jcr.repoinit.impl.TestUtil;
import org.apache.sling.jcr.repoinit.impl.UserUtil;
@@ -60,7 +62,7 @@ public class CreateGroupsTest {
U.parseAndExecute("create group " + groupId);
U.assertGroup("after creating group " + groupId, groupId, true);
}
-
+
@Test
public void createDeleteSingleTest() throws Exception {
U.assertGroup("at start of test", groupId, false);
@@ -97,7 +99,8 @@ public class CreateGroupsTest {
@Test
public void createGroupWithForcedAbsolutePathTest() throws Exception {
final String path = "/rep:security/rep:authorizables/rep:groups/testgroup/folder_for_" + groupId;
- final String forcedPath = "/rep:security/rep:authorizables/rep:groups/testgroup/folder_for_" + groupId + "_forced";
+ final String forcedPath =
+ "/rep:security/rep:authorizables/rep:groups/testgroup/folder_for_" + groupId + "_forced";
U.parseAndExecute("create group " + groupId + " with path " + path);
U.assertGroup("after creating group " + groupId, groupId, true, path);
U.parseAndExecute("create group " + groupId + " with forced path " + forcedPath);
@@ -106,7 +109,8 @@ public class CreateGroupsTest {
@Test
public void createGroupWithForcedPathNoClashTest() throws Exception {
- final String forcedPath = "/rep:security/rep:authorizables/rep:groups/testgroup/folder_for_" + groupId + "_forced";
+ final String forcedPath =
+ "/rep:security/rep:authorizables/rep:groups/testgroup/folder_for_" + groupId + "_forced";
U.parseAndExecute("create group " + groupId + " with forced path " + forcedPath);
U.assertGroup("after creating group " + groupId, groupId, true, forcedPath);
}
@@ -140,7 +144,8 @@ public class CreateGroupsTest {
U.adminSession.save();
// creating group with repoinit must fail
try {
- U.parseAndExecute("create group " + groupId + " with forced path /rep:security/rep:authorizables/rep:users/intermediate/path");
+ U.parseAndExecute("create group " + groupId
+ + " with forced path /rep:security/rep:authorizables/rep:users/intermediate/path");
fail("Group creation with conflicting user must fail.");
} catch (RuntimeException e) {
assertTrue(e.getCause() instanceof AuthorizableTypeException);
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/CreatePathsTest.java b/src/test/java/org/apache/sling/jcr/repoinit/CreatePathsTest.java
index 97b5eee..e23fa2d 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/CreatePathsTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/CreatePathsTest.java
@@ -1,34 +1,32 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import javax.jcr.Node;
+import javax.jcr.RepositoryException;
+import javax.jcr.ValueFactory;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.UUID;
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-import javax.jcr.ValueFactory;
-
import org.apache.sling.jcr.repoinit.impl.RepoInitException;
import org.apache.sling.jcr.repoinit.impl.TestUtil;
import org.apache.sling.repoinit.parser.RepoInitParsingException;
@@ -41,15 +39,17 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
/** Test the creation of paths with specific node types */
@RunWith(Parameterized.class)
public class CreatePathsTest {
@Parameters(name = "{1}")
public static Iterable<Object[]> data() {
- return Arrays.asList(new Object[][] {
- { Boolean.TRUE, "ensure nodes" }, { Boolean.FALSE, "create path" }
- });
+ return Arrays.asList(new Object[][] {{Boolean.TRUE, "ensure nodes"}, {Boolean.FALSE, "create path"}});
}
private final String baseCreateNodesStatement;
@@ -62,7 +62,7 @@ public class CreatePathsTest {
@Rule
public final SlingContext context = new SlingContext(ResourceResolverType.JCR_OAK);
-
+
private TestUtil U;
private static final String TEST_ID = UUID.randomUUID().toString();
@@ -148,18 +148,19 @@ public class CreatePathsTest {
@Test
public void createPathWithJcrTypeAndMixins() throws Exception {
- final String path = "/thirteen(nt:unstructured)/fourteen(nt:unstructured mixin mix:lockable)/fifteen(mixin mix:lockable)";
+ final String path =
+ "/thirteen(nt:unstructured)/fourteen(nt:unstructured mixin mix:lockable)/fifteen(mixin mix:lockable)";
U.parseAndExecute(baseCreateNodesStatement + path);
U.assertNodeExists("/thirteen", "nt:unstructured", Collections.<String>emptyList());
U.assertNodeExists("/thirteen/fourteen", "nt:unstructured", Collections.singletonList("mix:lockable"));
U.assertNodeExists("/thirteen/fourteen/fifteen", "nt:unstructured", Collections.singletonList("mix:lockable"));
}
-
+
@Test
public void createPathNoDefaultPrimaryType() throws Exception {
U.adminSession.getRootNode().addNode("folder", "nt:folder");
U.parseAndExecute(baseCreateNodesStatement + "/folder/subfolder/subfolder2");
-
+
Node subFolder = U.adminSession.getNode("/folder/subfolder");
assertEquals("sling:Folder", subFolder.getPrimaryNodeType().getName());
@@ -178,14 +179,15 @@ public class CreatePathsTest {
U.parseAndExecute(baseCreateNodesStatement + fullPath);
fail("Creating a node at a path where a property exists already should have thrown an exception");
} catch (RepoInitException e) {
- assertTrue(e.getMessage().contains("There is a property with the name of the to be created node already at"));
+ assertTrue(e.getMessage()
+ .contains("There is a property with the name of the to be created node already at"));
}
} else {
U.parseAndExecute("create path " + fullPath);
assertTrue(U.adminSession.propertyExists(fullPath));
}
}
-
+
/**
* SLING-11736 adjust existing node types
*/
@@ -226,10 +228,9 @@ public class CreatePathsTest {
+ "end\n";
U.parseAndExecute(createPathCndStatement);
- //verify it worked
+ // verify it worked
U.assertNodeExists("/one");
ValueFactory vf = U.adminSession.getValueFactory();
U.assertSVPropertyExists("/one", "displayName", vf.createValue("Hello"));
}
-
}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/CreateServiceUsersTest.java b/src/test/java/org/apache/sling/jcr/repoinit/CreateServiceUsersTest.java
index 812e75f..dd701c3 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/CreateServiceUsersTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/CreateServiceUsersTest.java
@@ -1,27 +1,29 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit;
+import javax.jcr.RepositoryException;
+
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
-import javax.jcr.RepositoryException;
-
import org.apache.jackrabbit.api.security.user.AuthorizableTypeException;
import org.apache.sling.jcr.repoinit.impl.TestUtil;
import org.apache.sling.jcr.repoinit.impl.UserUtil;
@@ -37,10 +39,10 @@ import static org.junit.Assert.fail;
/** Test the creation and delete of service users */
public class CreateServiceUsersTest {
-
+
@Rule
public final SlingContext context = new SlingContext(ResourceResolverType.JCR_OAK);
-
+
private static final Random random = new Random(42);
private String namePrefix;
@@ -48,7 +50,7 @@ public class CreateServiceUsersTest {
private TestUtil U;
private final List<String> toRemove = new ArrayList<>();
-
+
@Before
public void setup() throws RepositoryException {
U = new TestUtil(context);
@@ -134,45 +136,44 @@ public class CreateServiceUsersTest {
U.parseAndExecute("disable user " + userId + " : \"Test\"");
U.assertServiceUser("after disable regular user", userId, false);
}
-
+
private String user(int index) {
return namePrefix + "_" + index;
}
-
+
@Test
public void createUserMultipleTimes() throws Exception {
U.assertServiceUser("before test", userId, false);
final String input = "create service user " + userId;
- for(int i=0; i < 50; i++) {
+ for (int i = 0; i < 50; i++) {
U.parseAndExecute(input);
}
U.assertServiceUser("after creating it multiple times", userId, true);
}
-
+
@Test
public void createDeleteMultipleTest() throws Exception {
final int n = 50;
-
+
{
final StringBuilder input = new StringBuilder();
- for(int i=0; i < n; i++) {
+ for (int i = 0; i < n; i++) {
U.assertServiceUser("at start of test", user(i), false);
input.append("create service user ").append(user(i)).append("\n");
}
U.parseAndExecute(input.toString());
}
-
+
{
final StringBuilder input = new StringBuilder();
- for(int i=0; i < n; i++) {
+ for (int i = 0; i < n; i++) {
U.assertServiceUser("before deleting user", user(i), true);
input.append("delete service user ").append(user(i)).append("\n");
}
U.parseAndExecute(input.toString());
}
-
- for(int i=0; i < n; i++) {
+ for (int i = 0; i < n; i++) {
U.assertServiceUser("after deleting users", user(i), false);
}
}
@@ -245,7 +246,8 @@ public class CreateServiceUsersTest {
U.adminSession.save();
// creating service user with repoinit must fail
try {
- U.parseAndExecute("create service user " + userId + " with forced path /rep:security/rep:authorizables/rep:users/system");
+ U.parseAndExecute("create service user " + userId
+ + " with forced path /rep:security/rep:authorizables/rep:users/system");
fail("Service user creating with conflicting group must fail.");
} catch (RuntimeException e) {
assertTrue(e.getCause() instanceof AuthorizableTypeException);
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/CreateUsersTest.java b/src/test/java/org/apache/sling/jcr/repoinit/CreateUsersTest.java
index 1e1cfde..a52ebc8 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/CreateUsersTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/CreateUsersTest.java
@@ -1,26 +1,28 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit;
+import javax.jcr.RepositoryException;
+
import java.util.Collections;
import java.util.Random;
-import javax.jcr.RepositoryException;
-
import org.apache.jackrabbit.api.security.user.AuthorizableTypeException;
import org.apache.sling.jcr.repoinit.impl.TestUtil;
import org.apache.sling.jcr.repoinit.impl.UserUtil;
@@ -111,14 +113,16 @@ public class CreateUsersTest {
final String path = "/rep:security/rep:authorizables/rep:users/testusers/folder_for_" + userId;
U.parseAndExecute("create user " + userId + " with path " + path);
U.assertUser("after creating user " + userId, userId, true, path);
- final String forcedPath = "/rep:security/rep:authorizables/rep:users/testusers/folder_for_" + userId + "_forced";
+ final String forcedPath =
+ "/rep:security/rep:authorizables/rep:users/testusers/folder_for_" + userId + "_forced";
U.parseAndExecute("create user " + userId + " with forced path " + forcedPath);
U.assertUser("after creating user " + userId, userId, true, forcedPath);
}
@Test
public void createUserWithForcedPathNoClashTest() throws Exception {
- final String forcedPath = "/rep:security/rep:authorizables/rep:users/testusers/folder_for_" + userId + "_forced";
+ final String forcedPath =
+ "/rep:security/rep:authorizables/rep:users/testusers/folder_for_" + userId + "_forced";
U.parseAndExecute("create user " + userId + " with forced path " + forcedPath);
U.assertUser("after creating user " + userId, userId, true, forcedPath);
}
@@ -141,7 +145,7 @@ public class CreateUsersTest {
public void createUserMultipleTimes() throws Exception {
U.assertUser("before test", userId, false);
final String input = "create user " + userId;
- for(int i=0; i < 50; i++) {
+ for (int i = 0; i < 50; i++) {
U.parseAndExecute(input);
}
U.assertUser("after creating it multiple times", userId, true);
@@ -153,7 +157,7 @@ public class CreateUsersTest {
{
final StringBuilder input = new StringBuilder();
- for(int i=0; i < n; i++) {
+ for (int i = 0; i < n; i++) {
U.assertUser("at start of test", user(i), false);
input.append("create user ").append(user(i)).append("\n");
}
@@ -162,15 +166,14 @@ public class CreateUsersTest {
{
final StringBuilder input = new StringBuilder();
- for(int i=0; i < n; i++) {
+ for (int i = 0; i < n; i++) {
U.assertUser("before deleting user", user(i), true);
input.append("delete user ").append(user(i)).append("\n");
}
U.parseAndExecute(input.toString());
}
-
- for(int i=0; i < n; i++) {
+ for (int i = 0; i < n; i++) {
U.assertUser("after deleting users", user(i), false);
}
}
@@ -194,7 +197,8 @@ public class CreateUsersTest {
U.adminSession.save();
// creating service user with repoinit must fail
try {
- U.parseAndExecute("create user " + userId + " with forced path /rep:security/rep:authorizables/rep:users/intermediate/path");
+ U.parseAndExecute("create user " + userId
+ + " with forced path /rep:security/rep:authorizables/rep:users/intermediate/path");
fail("User creation with conflicting group must fail.");
} catch (RuntimeException e) {
assertTrue(e.getCause() instanceof AuthorizableTypeException);
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/DeleteAclTest.java b/src/test/java/org/apache/sling/jcr/repoinit/DeleteAclTest.java
index 9dccc6e..1fbce2c 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/DeleteAclTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/DeleteAclTest.java
@@ -1,21 +1,33 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit;
+import javax.jcr.Repository;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.SimpleCredentials;
+import javax.jcr.security.AccessControlPolicy;
+
+import java.security.Principal;
+import java.util.Arrays;
+import java.util.Collection;
+
import org.apache.jackrabbit.api.JackrabbitRepository;
import org.apache.jackrabbit.api.security.JackrabbitAccessControlList;
import org.apache.jackrabbit.api.security.JackrabbitAccessControlManager;
@@ -39,15 +51,6 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.SimpleCredentials;
-import javax.jcr.security.AccessControlPolicy;
-import java.security.Principal;
-import java.util.Arrays;
-import java.util.Collection;
-
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -56,39 +59,39 @@ import static org.junit.Assert.assertTrue;
@RunWith(Parameterized.class)
public class DeleteAclTest {
-
+
@Parameterized.Parameters(name = "ImportBehavior={0}")
public static Collection<Object[]> parameters() {
return Arrays.asList(
new Object[] {ImportBehavior.NAME_IGNORE},
new Object[] {ImportBehavior.NAME_BESTEFFORT},
- new Object[] {ImportBehavior.NAME_ABORT}
- );
+ new Object[] {ImportBehavior.NAME_ABORT});
}
private final String importBehaviorName;
-
+
private Repository repository;
private Session adminSession;
private JackrabbitAccessControlManager acMgr;
-
+
private TestUtil U;
private String userA;
public DeleteAclTest(String name) {
this.importBehaviorName = name;
}
-
+
@Before
public void setup() throws RepositoryException, RepoInitParsingException {
SecurityProvider sp = createSecurityProvider();
repository = new Jcr().with(sp).createRepository();
- String uid = sp.getParameters(UserConfiguration.NAME).getConfigValue(UserConstants.PARAM_ADMIN_ID, UserConstants.DEFAULT_ADMIN_ID);
+ String uid = sp.getParameters(UserConfiguration.NAME)
+ .getConfigValue(UserConstants.PARAM_ADMIN_ID, UserConstants.DEFAULT_ADMIN_ID);
adminSession = repository.login(new SimpleCredentials(uid, uid.toCharArray()), null);
acMgr = AclUtil.getJACM(adminSession);
U = new TestUtil(adminSession);
-
+
userA = "userA_" + U.id;
U.parseAndExecute("create service user " + U.username);
@@ -98,7 +101,7 @@ public class DeleteAclTest {
+ "create path (nt:unstructured) /var\n"
+ "create path (nt:unstructured) /no/policy\n"
+ "set ACL for " + U.username + "\n"
- + "allow jcr:read on /content, /var, home("+userA+")\n"
+ + "allow jcr:read on /content, /var, home(" + userA + ")\n"
+ "allow jcr:namespaceManagement on :repository\n"
+ "end\n"
+ "set ACL for " + userA + "\n"
@@ -106,8 +109,12 @@ public class DeleteAclTest {
+ "end\n");
}
- private SecurityProvider createSecurityProvider() {
- return SecurityProviderBuilder.newBuilder().with(ConfigurationParameters.of(AuthorizationConfiguration.NAME, ConfigurationParameters.of(ProtectedItemImporter.PARAM_IMPORT_BEHAVIOR, importBehaviorName))).build();
+ private SecurityProvider createSecurityProvider() {
+ return SecurityProviderBuilder.newBuilder()
+ .with(ConfigurationParameters.of(
+ AuthorizationConfiguration.NAME,
+ ConfigurationParameters.of(ProtectedItemImporter.PARAM_IMPORT_BEHAVIOR, importBehaviorName)))
+ .build();
}
@After
@@ -147,44 +154,45 @@ public class DeleteAclTest {
assertArrayEquals(new AccessControlPolicy[0], acMgr.getPolicies("/no/policy"));
U.parseAndExecute("delete ACL on /no/policy\n");
-
+
assertTrue(adminSession.nodeExists("/no/policy"));
assertArrayEquals(new AccessControlPolicy[0], acMgr.getPolicies("/no/policy"));
}
@Test
public void testDeleteAclByPrincipal() throws Exception {
- U.parseAndExecute("delete ACL for "+userA+"\n");
+ U.parseAndExecute("delete ACL for " + userA + "\n");
// removing resource-based ac setup by principal must leave entries for other principals intact
for (String path : new String[] {"/content", "/var"}) {
JackrabbitAccessControlList acl = AccessControlUtils.getAccessControlList(adminSession, path);
assertNotNull(acl);
assertEquals(1, acl.size()); // entry for U.username must not have been removed
- assertEquals(U.username, acl.getAccessControlEntries()[0].getPrincipal().getName());
+ assertEquals(
+ U.username, acl.getAccessControlEntries()[0].getPrincipal().getName());
}
}
-
+
@Test
public void testDeleteAclByNonExistingPrincipal() throws Exception {
Principal p = new PrincipalImpl("non-existing-service-user");
- assertEquals(0, acMgr.getPolicies(p).length);
-
+ assertEquals(0, acMgr.getPolicies(p).length);
+
// execution for non-existing principal must not fail
U.parseAndExecute("delete ACL for non-existing-service-user\n");
-
- assertEquals(0, acMgr.getPolicies(p).length);
+
+ assertEquals(0, acMgr.getPolicies(p).length);
}
@Test
public void testDeletesUserAndAcl() throws Exception {
Principal p = new PrincipalImpl(userA);
assertEquals(1, acMgr.getPolicies(p).length);
-
- U.parseAndExecute("delete service user "+userA+"\n");
+
+ U.parseAndExecute("delete service user " + userA + "\n");
assertEquals(1, acMgr.getPolicies(p).length);
- U.parseAndExecute("delete ACL for "+userA+"\n");
+ U.parseAndExecute("delete ACL for " + userA + "\n");
assertEquals(0, acMgr.getPolicies(p).length);
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/EveryoneTest.java b/src/test/java/org/apache/sling/jcr/repoinit/EveryoneTest.java
index a41fb0a..4d29331 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/EveryoneTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/EveryoneTest.java
@@ -1,18 +1,20 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit;
@@ -46,5 +48,4 @@ public class EveryoneTest {
final String statement = "set ACL for everyone\n allow jcr:read on /content\nend";
testUtil.parseAndExecute(statement);
}
-
}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/ExecutionOrderTest.java b/src/test/java/org/apache/sling/jcr/repoinit/ExecutionOrderTest.java
index c0f4646..6b46e3f 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/ExecutionOrderTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/ExecutionOrderTest.java
@@ -1,21 +1,28 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit;
+import javax.jcr.Node;
+import javax.jcr.RepositoryException;
+
+import java.util.UUID;
+
import ch.qos.logback.classic.Level;
import org.apache.sling.jcr.repoinit.impl.TestUtil;
import org.apache.sling.repoinit.parser.RepoInitParsingException;
@@ -25,10 +32,6 @@ import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import javax.jcr.Node;
-import javax.jcr.RepositoryException;
-import java.util.UUID;
-
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
@@ -60,9 +63,8 @@ public class ExecutionOrderTest {
"register nodetypes",
"<<===",
"[" + NS_PREFIX + ":foo] > nt:unstructured",
- "===>>"
- ,"register namespace (" + NS_PREFIX + ") " + NS_URI
- );
+ "===>>",
+ "register namespace (" + NS_PREFIX + ") " + NS_URI);
final Node n = U.getAdminSession().getNode(PATH);
assertEquals(NS_PREFIX + ":foo", n.getProperty("jcr:primaryType").getString());
}
@@ -76,8 +78,7 @@ public class ExecutionOrderTest {
" allow jcr:read on " + PATH,
" deny jcr:write on " + PATH,
"end",
- "delete group " + GROUP_NAME
- );
+ "delete group " + GROUP_NAME);
U.assertGroup("Group " + GROUP_NAME + " should have been deleted", GROUP_NAME, false);
@@ -88,15 +89,15 @@ public class ExecutionOrderTest {
@Test
public void legacySetAclBeforeCreatingGroupTest() throws Exception {
- try (LogCapture capture = new LogCapture("org.apache.sling.jcr.repoinit.impl.JcrRepoInitOpsProcessorImpl", true)) {
+ try (LogCapture capture =
+ new LogCapture("org.apache.sling.jcr.repoinit.impl.JcrRepoInitOpsProcessorImpl", true)) {
U.parseAndExecute(
"create path (nt:folder) " + PATH,
"set ACL for " + GROUP_NAME,
" allow jcr:read on " + PATH,
" deny jcr:write on " + PATH,
"end",
- "create group " + GROUP_NAME
- );
+ "create group " + GROUP_NAME);
capture.assertContains(Level.WARN, "DEPRECATION", "set ACL for " + GROUP_NAME);
} catch (RuntimeException e) {
@@ -106,12 +107,13 @@ public class ExecutionOrderTest {
@Test
public void legacyAddMemberBeforeCreatingGroupTest() throws Exception {
- try (LogCapture capture = new LogCapture("org.apache.sling.jcr.repoinit.impl.JcrRepoInitOpsProcessorImpl", true)) {
+ try (LogCapture capture =
+ new LogCapture("org.apache.sling.jcr.repoinit.impl.JcrRepoInitOpsProcessorImpl", true)) {
U.parseAndExecute(
"create group " + GROUP_NAME + "_1",
"add " + GROUP_NAME + "_1 to group " + GROUP_NAME,
"create group " + GROUP_NAME // reordered by legacy code
- );
+ );
capture.assertContains(Level.WARN, "DEPRECATION", "add " + GROUP_NAME + "_1 to group ");
} catch (RuntimeException e) {
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/GeneralAclTest.java b/src/test/java/org/apache/sling/jcr/repoinit/GeneralAclTest.java
index 6d405cf..d727964 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/GeneralAclTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/GeneralAclTest.java
@@ -1,26 +1,23 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
import javax.jcr.AccessDeniedException;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
@@ -43,6 +40,11 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.Test.None;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
/** Various ACL-related tests */
public class GeneralAclTest {
@@ -73,7 +75,7 @@ public class GeneralAclTest {
s.logout();
}
- @Test(expected=AccessDeniedException.class)
+ @Test(expected = AccessDeniedException.class)
public void getRootNodeIntiallyFails() throws Exception {
s.getRootNode();
}
@@ -87,14 +89,10 @@ public class GeneralAclTest {
try {
s.getNode(path);
fail("Expected read access to be initially denied:" + path);
- } catch(PathNotFoundException ignore) {
+ } catch (PathNotFoundException ignore) {
}
- final String allowRead =
- "set ACL for " + U.username + "\n"
- + "allow jcr:read on " + path + "\n"
- + "end"
- ;
+ final String allowRead = "set ACL for " + U.username + "\n" + "allow jcr:read on " + path + "\n" + "end";
U.parseAndExecute(allowRead);
final Node n = s.getNode(path);
@@ -102,29 +100,21 @@ public class GeneralAclTest {
n.setProperty("U.id", U.id);
s.save();
fail("Expected write access to be initially denied:" + path);
- } catch(AccessDeniedException ignore) {
+ } catch (AccessDeniedException ignore) {
}
s.refresh(false);
- final String allowWrite =
- "set ACL for " + U.username + "\n"
- + "allow jcr:write on " + path + "\n"
- + "end"
- ;
+ final String allowWrite = "set ACL for " + U.username + "\n" + "allow jcr:write on " + path + "\n" + "end";
U.parseAndExecute(allowWrite);
n.setProperty("U.id", U.id);
s.save();
- final String deny =
- "set ACL for " + U.username + "\n"
- + "deny jcr:all on " + path + "\n"
- + "end"
- ;
+ final String deny = "set ACL for " + U.username + "\n" + "deny jcr:all on " + path + "\n" + "end";
U.parseAndExecute(deny);
try {
s.getNode(path);
fail("Expected access to be denied again:" + path);
- } catch(PathNotFoundException ignore) {
+ } catch (PathNotFoundException ignore) {
}
}
@@ -133,11 +123,7 @@ public class GeneralAclTest {
final String nodename = "test_" + U.id;
final String path = "/" + nodename;
- final String aclSetup =
- "set ACL for " + U.username + "\n"
- + "allow jcr:all on /\n"
- + "end"
- ;
+ final String aclSetup = "set ACL for " + U.username + "\n" + "allow jcr:all on /\n" + "end";
U.parseAndExecute(aclSetup);
try {
assertFalse(s.itemExists(path));
@@ -155,15 +141,13 @@ public class GeneralAclTest {
@Test
public void addPathAclWithRepositoryPath() throws Exception {
final String aclSetup =
- "set ACL on :repository\n"
- + "allow jcr:namespaceManagement for "+U.username+"\n"
- + "end"
- ;
+ "set ACL on :repository\n" + "allow jcr:namespaceManagement for " + U.username + "\n" + "end";
U.parseAndExecute(aclSetup);
try {
s.refresh(false);
- assertTrue(s.getAccessControlManager().hasPrivileges(null, AccessControlUtils.privilegesFromNames(s, "jcr:namespaceManagement")));
+ assertTrue(s.getAccessControlManager()
+ .hasPrivileges(null, AccessControlUtils.privilegesFromNames(s, "jcr:namespaceManagement")));
} finally {
s.logout();
}
@@ -171,17 +155,15 @@ public class GeneralAclTest {
@Test
public void addPrincipalAclWithRepositoryPath() throws Exception {
- final String aclSetup =
- "set ACL for " + U.username + "\n"
- + "allow jcr:all on :repository,/\n"
- + "end"
- ;
+ final String aclSetup = "set ACL for " + U.username + "\n" + "allow jcr:all on :repository,/\n" + "end";
U.parseAndExecute(aclSetup);
try {
s.refresh(false);
- assertTrue(s.getAccessControlManager().hasPrivileges(null, AccessControlUtils.privilegesFromNames(s, Privilege.JCR_ALL)));
- assertTrue(s.getAccessControlManager().hasPrivileges("/", AccessControlUtils.privilegesFromNames(s, Privilege.JCR_ALL)));
+ assertTrue(s.getAccessControlManager()
+ .hasPrivileges(null, AccessControlUtils.privilegesFromNames(s, Privilege.JCR_ALL)));
+ assertTrue(s.getAccessControlManager()
+ .hasPrivileges("/", AccessControlUtils.privilegesFromNames(s, Privilege.JCR_ALL)));
} finally {
s.logout();
}
@@ -189,12 +171,10 @@ public class GeneralAclTest {
@Test
public void addRepositoryAcl() throws Exception {
- final String aclSetup =
- "set repository ACL for " + userA + "," + userB + "\n"
+ final String aclSetup = "set repository ACL for " + userA + "," + userB + "\n"
+ "allow jcr:namespaceManagement\n"
+ "allow jcr:nodeTypeDefinitionManagement\n"
- + "end"
- ;
+ + "end";
U.parseAndExecute(aclSetup);
verifyRegisterNamespace(userA, "a", "http://a", true);
@@ -207,14 +187,12 @@ public class GeneralAclTest {
@Test
public void addRepositoryAclInMultipleBlocks() throws Exception {
- final String aclSetup =
- "set repository ACL for " + userA + "\n"
- + "allow jcr:namespaceManagement,jcr:nodeTypeDefinitionManagement\n"
+ final String aclSetup = "set repository ACL for " + userA + "\n"
+ + "allow jcr:namespaceManagement,jcr:nodeTypeDefinitionManagement\n"
+ "end\n"
+ "set repository ACL for " + userB + "\n"
- + "allow jcr:namespaceManagement\n"
- + "end"
- ;
+ + "allow jcr:namespaceManagement\n"
+ + "end";
U.parseAndExecute(aclSetup);
verifyRegisterNamespace(userA, "a", "http://a", true);
@@ -225,15 +203,13 @@ public class GeneralAclTest {
@Test
public void addRepositoryAclInSequence() throws Exception {
- final String aclSetup =
- "set repository ACL for " + U.username + "\n"
- + "deny jcr:namespaceManagement,jcr:nodeTypeDefinitionManagement\n"
- + "allow jcr:namespaceManagement,jcr:nodeTypeDefinitionManagement\n"
+ final String aclSetup = "set repository ACL for " + U.username + "\n"
+ + "deny jcr:namespaceManagement,jcr:nodeTypeDefinitionManagement\n"
+ + "allow jcr:namespaceManagement,jcr:nodeTypeDefinitionManagement\n"
+ "end\n"
+ "set repository ACL for " + U.username + "\n"
- + "deny jcr:namespaceManagement\n"
- + "end"
- ;
+ + "deny jcr:namespaceManagement\n"
+ + "end";
U.parseAndExecute(aclSetup);
verifyRegisterNodeType(U.username, "typeC", true);
@@ -262,7 +238,6 @@ public class GeneralAclTest {
}
}
-
/**
* Verify the success/failure when registering a namespace.
* Registering a namespace successfully requires to be granted the jcr:namespaceManagement privilege.
@@ -289,34 +264,36 @@ public class GeneralAclTest {
* @param successExpected
* @throws RepositoryException
*/
- private void verifyAddChildNode(String username,String nodeName, boolean successExpected) throws RepositoryException {
- Session userSession = U.loginService(username);
- try {
- verifyAddChildNode(userSession,nodeName,successExpected);
- } finally {
- if(userSession != null) {
- userSession.logout();
- }
- }
- }
+ private void verifyAddChildNode(String username, String nodeName, boolean successExpected)
+ throws RepositoryException {
+ Session userSession = U.loginService(username);
+ try {
+ verifyAddChildNode(userSession, nodeName, successExpected);
+ } finally {
+ if (userSession != null) {
+ userSession.logout();
+ }
+ }
+ }
/**
* Verifies success/failure of adding a child
*/
- private void verifyAddChildNode(Session userSession, String nodeName, boolean successExpected) throws RepositoryException{
- Node rootNode = userSession.getRootNode();
+ private void verifyAddChildNode(Session userSession, String nodeName, boolean successExpected)
+ throws RepositoryException {
+ Node rootNode = userSession.getRootNode();
verifyAddChildNode(rootNode, nodeName, successExpected);
}
/**
* Verifies success/failure of adding a child
*/
- private void verifyAddChildNode(Node node, String nodeName, boolean successExpected) throws RepositoryException{
+ private void verifyAddChildNode(Node node, String nodeName, boolean successExpected) throws RepositoryException {
try {
node.addNode(nodeName);
node.getSession().save();
- assertTrue("Added child node succeeded "+nodeName,successExpected);
- } catch(Exception e) {
+ assertTrue("Added child node succeeded " + nodeName, successExpected);
+ } catch (Exception e) {
node.getSession().refresh(false);
assertTrue("Error adding " + nodeName + " to " + node + e.getMessage(), !successExpected);
}
@@ -330,12 +307,13 @@ public class GeneralAclTest {
* @param successExpected
* @throws RepositoryException
*/
- private void verifyAddProperty(String username,String nodeName,String propertyName, boolean successExpected) throws RepositoryException {
+ private void verifyAddProperty(String username, String nodeName, String propertyName, boolean successExpected)
+ throws RepositoryException {
Session userSession = U.loginService(username);
try {
verifyAddProperty(userSession, nodeName, propertyName, successExpected);
} finally {
- if(userSession != null) {
+ if (userSession != null) {
userSession.logout();
}
}
@@ -349,17 +327,20 @@ public class GeneralAclTest {
* @param successExpected
* @throws RepositoryException
*/
- private void verifyAddProperty(Session userSession,String relativePath,String propertyName,boolean successExpected) throws RepositoryException{
+ private void verifyAddProperty(
+ Session userSession, String relativePath, String propertyName, boolean successExpected)
+ throws RepositoryException {
try {
final Node n = userSession.getNode("/" + relativePath);
- n.setProperty(propertyName,"test");
+ n.setProperty(propertyName, "test");
userSession.save();
assertTrue("Expected setProperty " + propertyName + " to fail on " + relativePath, successExpected);
- } catch(RepositoryException e) {
+ } catch (RepositoryException e) {
userSession.refresh(false); // remove changes causing failure
assertFalse(
- "Expected setProperty " + propertyName + " to to succeed on " + relativePath + " but got " + e.getMessage(),
- successExpected);
+ "Expected setProperty " + propertyName + " to to succeed on " + relativePath + " but got "
+ + e.getMessage(),
+ successExpected);
}
}
@@ -371,44 +352,37 @@ public class GeneralAclTest {
try {
userSession.getNode(path);
assertTrue("Not expecting " + path + " to be readable but it was successfully read", successExpected);
- } catch(RepositoryException notReadable) {
+ } catch (RepositoryException notReadable) {
assertFalse("Expecting " + path + " to be readable but could not read it", successExpected);
}
}
- /**
- * Verifies that ACEs for existing principal are replaced
- */
- @Test
- @Ignore("SLING-6423 - ACLOptions processing is not implemented yet")
- public void mergeMode_ReplaceExistingPrincipalTest() throws Exception {
- final String initialAclSetup =
- " set ACL for " + userA + "\n"
- + "allow jcr:read,jcr:addChildNodes on / \n"
- + "end"
- ;
-
- final String aclsToBeMerged =
- " set ACL for " + userA + " (ACLOptions=merge)\n"
- + "allow jcr:read on / \n"
- + "allow jcr:modifyProperties on / \n"
- + "end"
- ;
-
- U.parseAndExecute(initialAclSetup);
- // verify that setup is correct
- verifyAddChildNode(userA, "A1_" + U.id, true); // add node should succeed
- verifyAddProperty(userA,"A1_"+U.id,"Prop1",false); // add property should fail
+ /**
+ * Verifies that ACEs for existing principal are replaced
+ */
+ @Test
+ @Ignore("SLING-6423 - ACLOptions processing is not implemented yet")
+ public void mergeMode_ReplaceExistingPrincipalTest() throws Exception {
+ final String initialAclSetup =
+ " set ACL for " + userA + "\n" + "allow jcr:read,jcr:addChildNodes on / \n" + "end";
- //now merge acls
- U.parseAndExecute(aclsToBeMerged);
+ final String aclsToBeMerged = " set ACL for " + userA + " (ACLOptions=merge)\n"
+ + "allow jcr:read on / \n"
+ + "allow jcr:modifyProperties on / \n"
+ + "end";
- //verify merged ACLs
- verifyAddChildNode(userA, "A2_" + U.id, false); // add node should fail
- verifyAddProperty(userA,"A1_"+U.id,"prop2",true);// add property should succeed
+ U.parseAndExecute(initialAclSetup);
+ // verify that setup is correct
+ verifyAddChildNode(userA, "A1_" + U.id, true); // add node should succeed
+ verifyAddProperty(userA, "A1_" + U.id, "Prop1", false); // add property should fail
- }
+ // now merge acls
+ U.parseAndExecute(aclsToBeMerged);
+ // verify merged ACLs
+ verifyAddChildNode(userA, "A2_" + U.id, false); // add node should fail
+ verifyAddProperty(userA, "A1_" + U.id, "prop2", true); // add property should succeed
+ }
/**
* Verify that ACLs for new principal are added
@@ -417,32 +391,25 @@ public class GeneralAclTest {
@Test
@Ignore("SLING-6423 - ACLOptions processing is not implemented yet")
public void mergeMode_AddAceTest() throws Exception {
- final String initialAclSetup =
- "set ACL for " + userA + "\n"
- + "allow jcr:read,jcr:write on /\n"
- + "end \n"
- ;
+ final String initialAclSetup = "set ACL for " + userA + "\n" + "allow jcr:read,jcr:write on /\n" + "end \n";
// userA,jcr:write ACE will be removed,
// userB ACE will be added
- final String aclsToBeMerged =
- "set ACL on / (ACLOptions=merge) \n"
- + "allow jcr:read for " + userA + "\n"
- + "allow jcr:read,jcr:write for " + userB + "\n"
- + "end \n"
- ;
+ final String aclsToBeMerged = "set ACL on / (ACLOptions=merge) \n"
+ + "allow jcr:read for " + userA + "\n"
+ + "allow jcr:read,jcr:write for " + userB + "\n"
+ + "end \n";
U.parseAndExecute(initialAclSetup);
// verify that setup is correct
verifyAddChildNode(userA, "A1_" + U.id, true);
verifyAddChildNode(userB, "B1_" + U.id, false);
- //now merge acls
+ // now merge acls
U.parseAndExecute(aclsToBeMerged);
- //verify merged ACLs
+ // verify merged ACLs
verifyAddChildNode(userA, "A2_" + U.id, false);
verifyAddChildNode(userB, "B2_" + U.id, true);
-
}
/**
@@ -452,68 +419,54 @@ public class GeneralAclTest {
@Test
@Ignore("SLING-6423 - ACLOptions processing is not implemented yet")
public void mergeMode_PreserveAceTest() throws Exception {
- final String initialAclSetup =
- "set ACL on / \n"
- + "allow jcr:read,jcr:write for " + userA + "\n"
- + "allow jcr:read,jcr:write for " + userB + "\n"
- + "end \n"
- ;
+ final String initialAclSetup = "set ACL on / \n"
+ + "allow jcr:read,jcr:write for " + userA + "\n"
+ + "allow jcr:read,jcr:write for " + userB + "\n"
+ + "end \n";
// userB ACE will be preserved
final String aclsToBeMerged =
- "set ACL on / (ACLOptions=merge) \n"
- + "allow jcr:read for " + userA + "\n"
- + "end \n"
- ;
+ "set ACL on / (ACLOptions=merge) \n" + "allow jcr:read for " + userA + "\n" + "end \n";
U.parseAndExecute(initialAclSetup);
// verify that setup is correct
verifyAddChildNode(userA, "A1_" + U.id, true);
verifyAddChildNode(userB, "B1_" + U.id, true);
- //now merge acls
+ // now merge acls
U.parseAndExecute(aclsToBeMerged);
- //verify merged ACLs
+ // verify merged ACLs
verifyAddChildNode(userA, "A2_" + U.id, false);
verifyAddChildNode(userB, "B2_" + U.id, true);
-
}
-
/**
* Verifiy that ACE for non-existing principal are added
* @throws Exception
*/
@Test
@Ignore("SLING-6423 - ACLOptions processing is not implemented yet")
- public void mergePreserveMode_AddAceTest() throws Exception{
- final String initialAclSetup =
- " set ACL for " + userB + "\n"
- + "allow jcr:read,jcr:write on /\n"
- + "end \n"
- ;
+ public void mergePreserveMode_AddAceTest() throws Exception {
+ final String initialAclSetup = " set ACL for " + userB + "\n" + "allow jcr:read,jcr:write on /\n" + "end \n";
- final String aclsToBeMerged =
- "set ACL for " + userA + " (ACLOptions=mergePreserve)\n"
+ final String aclsToBeMerged = "set ACL for " + userA + " (ACLOptions=mergePreserve)\n"
+ "allow jcr:read,jcr:write on / \n"
- + "end \n"
- ;
+ + "end \n";
U.parseAndExecute(initialAclSetup);
// verify that setup is correct
verifyAddChildNode(userA, "A1_" + U.id, false);
verifyAddChildNode(userB, "B1_" + U.id, true);
- //now merge acls
+ // now merge acls
U.parseAndExecute(aclsToBeMerged);
- //verify merged ACLs
+ // verify merged ACLs
verifyAddChildNode(userA, "A2_" + U.id, true);
verifyAddChildNode(userB, "B2_" + U.id, true);
}
-
/**
* Verify that ACE for existing principal are ignored
* @throws Exception
@@ -522,31 +475,25 @@ public class GeneralAclTest {
@Ignore("SLING-6423 - ACLOptions processing is not implemented yet")
public void mergePreserveMode_IgnoreAceTest() throws Exception {
final String initialAclSetup =
- "set ACL for " + userA + "\n"
- + "allow jcr:read,jcr:addChildNodes on /\n"
- + "end"
- ;
+ "set ACL for " + userA + "\n" + "allow jcr:read,jcr:addChildNodes on /\n" + "end";
- final String aclsToBeMerged =
- " set ACL for " + userA + " (ACLOptions=mergePreserve) \n"
+ final String aclsToBeMerged = " set ACL for " + userA + " (ACLOptions=mergePreserve) \n"
+ "allow jcr:read,jcr:modifyProperties on / \n"
- + "end \n"
- ;
+ + "end \n";
U.parseAndExecute(initialAclSetup);
// verify that setup is correct
verifyAddChildNode(userA, "A1_" + U.id, true); // add node should succeed
verifyAddProperty(userA, "A1_" + U.id, "Prop1", false); // add property should fail
- //now merge acls
+ // now merge acls
U.parseAndExecute(aclsToBeMerged);
- //verify merged ACLs
+ // verify merged ACLs
verifyAddChildNode(userA, "A2_" + U.id, true); // add node should succeed
verifyAddProperty(userA, "A2_" + U.id, "Prop1", false); // add property should fail
}
-
/**
* Verify that ACE for unspecified principal are preserved
* @throws Exception
@@ -555,27 +502,21 @@ public class GeneralAclTest {
@Ignore("SLING-6423 - ACLOptions processing is not implemented yet")
public void mergePreserveMode_PreserveAceTest() throws Exception {
final String initialAclSetup =
- " set ACL on /\n"
- + "allow jcr:read, jcr:write for " + userA + " , " + userB + "\n"
- + "end \n"
- ;
+ " set ACL on /\n" + "allow jcr:read, jcr:write for " + userA + " , " + userB + "\n" + "end \n";
// ACL for userA will be ignored but added for userB
final String aclsToBeMerged =
- " set ACL for " + userA + " (ACLOptions=mergePreserve) \n"
- + "allow jcr:read on / \n"
- + "end \n"
- ;
+ " set ACL for " + userA + " (ACLOptions=mergePreserve) \n" + "allow jcr:read on / \n" + "end \n";
U.parseAndExecute(initialAclSetup);
// verify that setup is correct
verifyAddChildNode(userA, "A1_" + U.id, true);
verifyAddChildNode(userB, "B1_" + U.id, true);
- //now merge acls
+ // now merge acls
U.parseAndExecute(aclsToBeMerged);
- //verify merged ACLs
+ // verify merged ACLs
verifyAddChildNode(userA, "A2_" + U.id, true);
verifyAddChildNode(userB, "B2_" + U.id, true);
}
@@ -594,15 +535,12 @@ public class GeneralAclTest {
U.adminSession.getRootNode().addNode(notAllowedNodeName);
U.adminSession.save();
-
final String nodeName = "test_" + U.id;
- final String aclSetup =
- "set ACL for " + U.username + "\n"
- + "allow jcr:all on / \n"
- + "deny jcr:addChildNodes on / restriction(rep:glob,*abc*)\n"
- + "end"
- ;
+ final String aclSetup = "set ACL for " + U.username + "\n"
+ + "allow jcr:all on / \n"
+ + "deny jcr:addChildNodes on / restriction(rep:glob,*abc*)\n"
+ + "end";
U.parseAndExecute(aclSetup);
@@ -615,7 +553,6 @@ public class GeneralAclTest {
}
}
-
/**
* Tests use of rep:itemNames restriction in set ACL
* @throws Exception
@@ -625,12 +562,10 @@ public class GeneralAclTest {
final String nodename = "test_" + U.id;
final String propName = "test2_" + U.id;
- final String aclSetup =
- "set ACL for " + U.username + "\n"
- + "allow jcr:all on / \n"
- + "deny jcr:modifyProperties on / restriction(rep:itemNames,"+propName+")\n"
- + "end"
- ;
+ final String aclSetup = "set ACL for " + U.username + "\n"
+ + "allow jcr:all on / \n"
+ + "deny jcr:modifyProperties on / restriction(rep:itemNames," + propName + ")\n"
+ + "end";
U.parseAndExecute(aclSetup);
@@ -654,37 +589,29 @@ public class GeneralAclTest {
final String nodeName = "test_" + U.id;
final String nodeName2 = "test2_" + U.id;
final String nodeName3 = "test3_" + U.id;
- final String propName = "propName" + U.id;
-
+ final String propName = "propName" + U.id;
U.adminSession.getRootNode().addNode(nodeName);
U.adminSession.getRootNode().addNode(nodeName2);
U.adminSession.getRootNode().addNode(nodeName3);
U.adminSession.save();
-
- final String aclSetup =
- "set ACL for " + U.username + "\n"
- + "allow jcr:all on / \n"
- + "deny jcr:addChildNodes on / restriction(rep:glob,"+nodeName2+")\n"
- + "end"
- ;
+ final String aclSetup = "set ACL for " + U.username + "\n"
+ + "allow jcr:all on / \n"
+ + "deny jcr:addChildNodes on / restriction(rep:glob," + nodeName2 + ")\n"
+ + "end";
U.parseAndExecute(aclSetup);
- final String aclSetup2 =
- "set ACL for " + U.username + "\n"
- + "deny jcr:addChildNodes on / restriction(rep:glob,"+nodeName3+")\n"
- + "end"
- ;
+ final String aclSetup2 = "set ACL for " + U.username + "\n"
+ + "deny jcr:addChildNodes on / restriction(rep:glob," + nodeName3 + ")\n"
+ + "end";
U.parseAndExecute(aclSetup2);
- final String aclSetup3 =
- "set ACL for " + U.username + "\n"
- + "deny jcr:modifyProperties on / restriction(rep:itemNames,"+propName+")\n"
- + "end"
- ;
+ final String aclSetup3 = "set ACL for " + U.username + "\n"
+ + "deny jcr:modifyProperties on / restriction(rep:itemNames," + propName + ")\n"
+ + "end";
U.parseAndExecute(aclSetup3);
@@ -706,15 +633,12 @@ public class GeneralAclTest {
}
}
-
@Test(expected = None.class)
public void emptyRestrictionTest() throws Exception {
- final String aclSetup =
- "set ACL for " + U.username + "\n"
- + "allow jcr:all on / \n"
- + "deny jcr:modifyProperties on / restriction(rep:itemNames)\n"
- + "end"
- ;
+ final String aclSetup = "set ACL for " + U.username + "\n"
+ + "allow jcr:all on / \n"
+ + "deny jcr:modifyProperties on / restriction(rep:itemNames)\n"
+ + "end";
U.parseAndExecute(aclSetup);
}
@@ -734,12 +658,10 @@ public class GeneralAclTest {
// Allow for reading the parent node but not its children with an empty glob restriction
// as per https://jackrabbit.apache.org/oak/docs/security/authorization/restriction.html
- final String aclSetup =
- "set ACL for " + U.username + "\n"
- + "deny jcr:read on /\n"
- + "allow jcr:read on /" + parentName + " restriction (rep:glob)\n"
- + "end"
- ;
+ final String aclSetup = "set ACL for " + U.username + "\n"
+ + "deny jcr:read on /\n"
+ + "allow jcr:read on /" + parentName + " restriction (rep:glob)\n"
+ + "end";
U.parseAndExecute(aclSetup);
@@ -755,20 +677,16 @@ public class GeneralAclTest {
@Test
public void failWhenSettingAclsForNonExistingPrincipal() throws RepositoryException {
U.assertPrivileges("nonExistingPrincipal", "/", false, "jcr:read");
- assertThrows(RepoInitException.class, () -> U.parseAndExecute(
- "set ACL on /",
- " allow jcr:read for nonExistingPrincipal",
- "end"
- ));
+ assertThrows(
+ RepoInitException.class,
+ () -> U.parseAndExecute("set ACL on /", " allow jcr:read for nonExistingPrincipal", "end"));
U.assertPrivileges("nonExistingPrincipal", "/", false, "jcr:read");
}
@Test
public void failWhenUsingInvalidSetAclRemoveSyntax() {
- assertThrows(RepoInitException.class, () -> U.parseAndExecute(
- "set ACL on /",
- " remove jcr:read for nonExistingPrincipal",
- "end"
- ));
+ assertThrows(
+ RepoInitException.class,
+ () -> U.parseAndExecute("set ACL on /", " remove jcr:read for nonExistingPrincipal", "end"));
}
}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/GroupMembershipTest.java b/src/test/java/org/apache/sling/jcr/repoinit/GroupMembershipTest.java
index a4e22e1..da9e976 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/GroupMembershipTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/GroupMembershipTest.java
@@ -1,21 +1,27 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit;
+import javax.jcr.RepositoryException;
+
+import java.util.Random;
+
import org.apache.sling.jcr.repoinit.impl.TestUtil;
import org.apache.sling.repoinit.parser.RepoInitParsingException;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
@@ -25,9 +31,6 @@ import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import javax.jcr.RepositoryException;
-import java.util.Random;
-
/** Test the group membership */
public class GroupMembershipTest {
@@ -60,6 +63,7 @@ public class GroupMembershipTest {
U.parseAndExecute("add " + userId + " to group " + groupId);
U.assertGroupMembership(userId, groupId, true);
}
+
@Test
public void removeMemberFromGroup() throws Exception {
U.parseAndExecute("add " + secondUserId + " to group " + groupId);
@@ -67,7 +71,7 @@ public class GroupMembershipTest {
U.parseAndExecute("remove " + secondUserId + " from group " + groupId);
U.assertGroupMembership(secondUserId, groupId, false);
}
-
+
@Test
public void addNonExistingMemberToGroup() throws Exception {
String nonExistingUserId = userNamePrefix + "_non";
@@ -90,20 +94,19 @@ public class GroupMembershipTest {
U.parseAndExecute("add " + userId + " to group " + otherUserId);
Assert.fail();
} catch (RuntimeException e) {
- Assert.assertEquals("expected runtime exception", otherUserId + " is not a group", e.getMessage());
+ Assert.assertEquals("expected runtime exception", otherUserId + " is not a group", e.getMessage());
}
}
@Test
public void addMemberToNonExistingGroup() throws Exception {
- String nonExistingGroupId = grpNamePrefix + "_non";
+ String nonExistingGroupId = grpNamePrefix + "_non";
U.assertGroup("Group should not exist", nonExistingGroupId, false);
try {
U.parseAndExecute("add " + userId + " to group " + nonExistingGroupId);
Assert.fail();
} catch (RuntimeException e) {
- Assert.assertEquals("expected runtime exception", nonExistingGroupId + " is not a group", e.getMessage());
+ Assert.assertEquals("expected runtime exception", nonExistingGroupId + " is not a group", e.getMessage());
}
}
-
}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/LogCapture.java b/src/test/java/org/apache/sling/jcr/repoinit/LogCapture.java
index 153664f..979d682 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/LogCapture.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/LogCapture.java
@@ -18,18 +18,17 @@
*/
package org.apache.sling.jcr.repoinit;
-import static org.junit.Assert.fail;
-
import java.util.function.Predicate;
import java.util.stream.Stream;
-import org.slf4j.LoggerFactory;
-
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
+import org.slf4j.LoggerFactory;
+
+import static org.junit.Assert.fail;
/**
* Capture logs for testing
@@ -60,10 +59,11 @@ class LogCapture extends ListAppender<ILoggingEvent> implements AutoCloseable {
return this.list.stream().anyMatch(p);
}
- public void assertContains(Level atLevel, String ... substrings) {
+ public void assertContains(Level atLevel, String... substrings) {
Stream.of(substrings).forEach(substring -> {
- if(!anyMatch(event -> event.getLevel() == atLevel && event.getFormattedMessage().contains(substring))) {
- if(verboseFailure) {
+ if (!anyMatch(event ->
+ event.getLevel() == atLevel && event.getFormattedMessage().contains(substring))) {
+ if (verboseFailure) {
fail(String.format("No log message contains [%s] in log\n%s", substring, this.list.toString()));
} else {
fail(String.format("No log message contains [%s]", substring));
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/MixinsTest.java b/src/test/java/org/apache/sling/jcr/repoinit/MixinsTest.java
index 735468e..dabdcdd 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/MixinsTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/MixinsTest.java
@@ -1,32 +1,32 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.nodetype.NoSuchNodeTypeException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.nodetype.NoSuchNodeTypeException;
-
+import ch.qos.logback.classic.Level;
import org.apache.sling.jcr.repoinit.impl.TestUtil;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.apache.sling.testing.mock.sling.junit.SlingContext;
@@ -34,14 +34,15 @@ import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import ch.qos.logback.classic.Level;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
/** Test the creation of paths with specific node types */
public class MixinsTest {
@Rule
public final SlingContext context = new SlingContext(ResourceResolverType.JCR_OAK);
-
+
private TestUtil U;
@Before
@@ -65,18 +66,23 @@ public class MixinsTest {
U.assertNodeExists("/addTwoMixinsOnOnePath1", "nt:unstructured", Collections.emptyList());
U.assertNodeExists("/addTwoMixinsOnOnePath1", "nt:unstructured", Collections.emptyList());
- U.parseAndExecute("add mixin mix:lockable,mix:referenceable to /addTwoMixinsOnOnePath1,/addTwoMixinsOnOnePath2");
- U.assertNodeExists("/addTwoMixinsOnOnePath1", "nt:unstructured", Arrays.asList("mix:lockable","mix:referenceable"));
- U.assertNodeExists("/addTwoMixinsOnOnePath1", "nt:unstructured", Arrays.asList("mix:lockable","mix:referenceable"));
+ U.parseAndExecute(
+ "add mixin mix:lockable,mix:referenceable to /addTwoMixinsOnOnePath1,/addTwoMixinsOnOnePath2");
+ U.assertNodeExists(
+ "/addTwoMixinsOnOnePath1", "nt:unstructured", Arrays.asList("mix:lockable", "mix:referenceable"));
+ U.assertNodeExists(
+ "/addTwoMixinsOnOnePath1", "nt:unstructured", Arrays.asList("mix:lockable", "mix:referenceable"));
}
@Test
public void removeOneMixinFromOnePath() throws Exception {
U.parseAndExecute("create path /removeOneMixinOnOnePath(nt:unstructured mixin mix:lockable,mix:referenceable)");
- U.assertNodeExists("/removeOneMixinOnOnePath", "nt:unstructured", Arrays.asList("mix:lockable","mix:referenceable"));
+ U.assertNodeExists(
+ "/removeOneMixinOnOnePath", "nt:unstructured", Arrays.asList("mix:lockable", "mix:referenceable"));
U.parseAndExecute("remove mixin mix:lockable from /removeOneMixinOnOnePath");
- U.assertNodeExists("/removeOneMixinOnOnePath", "nt:unstructured", Collections.singletonList("mix:referenceable"));
+ U.assertNodeExists(
+ "/removeOneMixinOnOnePath", "nt:unstructured", Collections.singletonList("mix:referenceable"));
U.parseAndExecute("remove mixin mix:referenceable from /removeOneMixinOnOnePath");
U.assertNodeExists("/removeOneMixinOnOnePath", "nt:unstructured", Collections.emptyList());
@@ -84,13 +90,20 @@ public class MixinsTest {
@Test
public void removeTwoMixinsFromTwoPaths() throws Exception {
- U.parseAndExecute("create path /removeTwoMixinsOnOnePath1(nt:unstructured mixin mix:lockable,mix:referenceable,mix:lastModified)\n"
- + "create path /removeTwoMixinsOnOnePath2(nt:unstructured mixin mix:lockable,mix:referenceable)");
- U.assertNodeExists("/removeTwoMixinsOnOnePath1", "nt:unstructured", Arrays.asList("mix:lockable","mix:referenceable", "mix:lastModified"));
- U.assertNodeExists("/removeTwoMixinsOnOnePath2", "nt:unstructured", Arrays.asList("mix:lockable","mix:referenceable"));
-
- U.parseAndExecute("remove mixin mix:lockable,mix:referenceable from /removeTwoMixinsOnOnePath1,/removeTwoMixinsOnOnePath2");
- U.assertNodeExists("/removeTwoMixinsOnOnePath1", "nt:unstructured", Collections.singletonList("mix:lastModified"));
+ U.parseAndExecute(
+ "create path /removeTwoMixinsOnOnePath1(nt:unstructured mixin mix:lockable,mix:referenceable,mix:lastModified)\n"
+ + "create path /removeTwoMixinsOnOnePath2(nt:unstructured mixin mix:lockable,mix:referenceable)");
+ U.assertNodeExists(
+ "/removeTwoMixinsOnOnePath1",
+ "nt:unstructured",
+ Arrays.asList("mix:lockable", "mix:referenceable", "mix:lastModified"));
+ U.assertNodeExists(
+ "/removeTwoMixinsOnOnePath2", "nt:unstructured", Arrays.asList("mix:lockable", "mix:referenceable"));
+
+ U.parseAndExecute(
+ "remove mixin mix:lockable,mix:referenceable from /removeTwoMixinsOnOnePath1,/removeTwoMixinsOnOnePath2");
+ U.assertNodeExists(
+ "/removeTwoMixinsOnOnePath1", "nt:unstructured", Collections.singletonList("mix:lastModified"));
U.assertNodeExists("/removeTwoMixinsOnOnePath2", "nt:unstructured", Collections.emptyList());
}
@@ -114,7 +127,8 @@ public class MixinsTest {
assertNodeNotExists("/removeMixinFromNotExistingPath");
// verify the warning was logged
- capture.assertContains(Level.WARN, "Path does not exist, not removing mixins: /removeMixinFromNotExistingPath");
+ capture.assertContains(
+ Level.WARN, "Path does not exist, not removing mixins: /removeMixinFromNotExistingPath");
}
}
@@ -142,5 +156,4 @@ public class MixinsTest {
Session adminSession = context.resourceResolver().adaptTo(Session.class);
assertFalse("Node should not exist", adminSession.nodeExists(path));
}
-
}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/NonExistentPathTest.java b/src/test/java/org/apache/sling/jcr/repoinit/NonExistentPathTest.java
index 2c34847..bb86744 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/NonExistentPathTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/NonExistentPathTest.java
@@ -1,24 +1,23 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
@@ -32,15 +31,18 @@ import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
/** Test setting ACLS on non-existent paths */
public class NonExistentPathTest {
@Rule
public final SlingContext context = new SlingContext(ResourceResolverType.JCR_OAK);
-
+
private TestUtil U;
private Session s;
-
+
@Before
public void setup() throws RepositoryException, RepoInitParsingException {
U = new TestUtil(context);
@@ -53,20 +55,15 @@ public class NonExistentPathTest {
U.cleanupUser();
s.logout();
}
-
+
@Test
public void setAclOnFoo() throws Exception {
- final String aclDef =
- "set ACL on /foo_" + U.id + "\n"
- + " allow jcr:all for " + U.username + "\n"
- + "end"
- ;
+ final String aclDef = "set ACL on /foo_" + U.id + "\n" + " allow jcr:all for " + U.username + "\n" + "end";
try {
U.parseAndExecute(aclDef);
fail("Expecting a wrapped PathNotFoundException");
- } catch(RuntimeException rux) {
+ } catch (RuntimeException rux) {
assertEquals(PathNotFoundException.class, rux.getCause().getClass());
}
}
-
}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/PrincipalBasedAclTest.java b/src/test/java/org/apache/sling/jcr/repoinit/PrincipalBasedAclTest.java
index 8083a35..282a3a8 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/PrincipalBasedAclTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/PrincipalBasedAclTest.java
@@ -1,21 +1,39 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit;
+import javax.jcr.Node;
+import javax.jcr.Property;
+import javax.jcr.Repository;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.SimpleCredentials;
+import javax.jcr.security.AccessControlManager;
+import javax.jcr.security.AccessControlPolicy;
+import javax.jcr.security.Privilege;
+import javax.security.auth.Subject;
+
+import java.security.Principal;
+import java.security.PrivilegedExceptionAction;
+import java.util.Collections;
+import java.util.UUID;
+
import org.apache.jackrabbit.api.JackrabbitRepository;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.JackrabbitAccessControlManager;
@@ -52,26 +70,11 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.Test.None;
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.SimpleCredentials;
-import javax.jcr.security.AccessControlManager;
-import javax.jcr.security.AccessControlPolicy;
-import javax.jcr.security.Privilege;
-import javax.security.auth.Subject;
-import java.security.Principal;
-import java.security.PrivilegedExceptionAction;
-import java.util.Collections;
-import java.util.UUID;
-
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@@ -101,7 +104,8 @@ public class PrincipalBasedAclTest {
SecurityProvider sp = createSecurityProvider();
repository = new Jcr().with(sp).createRepository();
- String uid = sp.getParameters(UserConfiguration.NAME).getConfigValue(UserConstants.PARAM_ADMIN_ID, UserConstants.DEFAULT_ADMIN_ID);
+ String uid = sp.getParameters(UserConfiguration.NAME)
+ .getConfigValue(UserConstants.PARAM_ADMIN_ID, UserConstants.DEFAULT_ADMIN_ID);
adminSession = (JackrabbitSession) repository.login(new SimpleCredentials(uid, uid.toCharArray()), null);
acMgr = AclUtil.getJACM(adminSession);
U = new TestUtil(adminSession);
@@ -112,14 +116,16 @@ public class PrincipalBasedAclTest {
propPath = prop.getPath();
adminSession.save();
- relPath = sp.getParameters(UserConfiguration.NAME).getConfigValue(UserConstants.PARAM_SYSTEM_RELATIVE_PATH, UserConstants.DEFAULT_SYSTEM_RELATIVE_PATH) + "/" + PRINCIPAL_BASED_SUBTREE;
+ relPath = sp.getParameters(UserConfiguration.NAME)
+ .getConfigValue(
+ UserConstants.PARAM_SYSTEM_RELATIVE_PATH, UserConstants.DEFAULT_SYSTEM_RELATIVE_PATH)
+ + "/" + PRINCIPAL_BASED_SUBTREE;
U.parseAndExecute("create service user " + U.username + " with path " + relPath);
testSession = loginSystemUserPrincipal(U.username);
assertPermission(testSession, PathUtils.ROOT_PATH, Session.ACTION_READ, false);
assertPermission(testSession, path, Session.ACTION_READ, false);
-
}
@After
@@ -145,14 +151,19 @@ public class PrincipalBasedAclTest {
*
* in an AND setup scenario one would need to inject the aggregation filter defined by oak-authorization-princialbased
*/
- SecurityProvider sp = SecurityProviderBuilder.newBuilder().with(ConfigurationParameters.of("authorizationCompositionType", "OR")).build();
+ SecurityProvider sp = SecurityProviderBuilder.newBuilder()
+ .with(ConfigurationParameters.of("authorizationCompositionType", "OR"))
+ .build();
ConfigurationParameters userParams = sp.getParameters(UserConfiguration.NAME);
String userRoot = userParams.getConfigValue(UserConstants.PARAM_USER_PATH, UserConstants.DEFAULT_USER_PATH);
- String systemRelPath = userParams.getConfigValue(UserConstants.PARAM_SYSTEM_RELATIVE_PATH, UserConstants.DEFAULT_SYSTEM_RELATIVE_PATH);
+ String systemRelPath = userParams.getConfigValue(
+ UserConstants.PARAM_SYSTEM_RELATIVE_PATH, UserConstants.DEFAULT_SYSTEM_RELATIVE_PATH);
FilterProviderImpl fp = new FilterProviderImpl();
- context.registerInjectActivateService(fp, Collections.singletonMap("path", PathUtils.concat(userRoot, systemRelPath, PRINCIPAL_BASED_SUBTREE)));
+ context.registerInjectActivateService(
+ fp,
+ Collections.singletonMap("path", PathUtils.concat(userRoot, systemRelPath, PRINCIPAL_BASED_SUBTREE)));
PrincipalBasedAuthorizationConfiguration authorizationConfig = new PrincipalBasedAuthorizationConfiguration();
authorizationConfig.bindMountInfoProvider(Mounts.defaultMountInfoProvider());
@@ -173,20 +184,28 @@ public class PrincipalBasedAclTest {
*/
private Session loginSystemUserPrincipal(final String systemUserPrincipalName) throws Exception {
SystemUserPrincipal principal = () -> systemUserPrincipalName;
- Subject subject = new Subject(true, Collections.singleton(principal), Collections.emptySet(), Collections.emptySet());
+ Subject subject =
+ new Subject(true, Collections.singleton(principal), Collections.emptySet(), Collections.emptySet());
return Subject.doAs(subject, (PrivilegedExceptionAction<Session>) () -> repository.login(null, null));
}
- private static void assertPermission(Session userSession, String absolutePath, String actions, boolean successExpected) throws RepositoryException {
- assertEquals("Expecting "+actions+" for path " + absolutePath + " to be " + (successExpected ? "granted" : "denied"), successExpected, userSession.hasPermission(absolutePath, actions));
+ private static void assertPermission(
+ Session userSession, String absolutePath, String actions, boolean successExpected)
+ throws RepositoryException {
+ assertEquals(
+ "Expecting " + actions + " for path " + absolutePath + " to be "
+ + (successExpected ? "granted" : "denied"),
+ successExpected,
+ userSession.hasPermission(absolutePath, actions));
}
private static void assertRegex(String regex, String shouldMatch) {
- assertTrue("Expecting '" + shouldMatch + "'' to match " + regex, shouldMatch.matches(regex));
+ assertTrue("Expecting '" + shouldMatch + "'' to match " + regex, shouldMatch.matches(regex));
}
-
+
@NotNull
- private static PrincipalAccessControlList assertPolicy(@NotNull Principal principal, @NotNull Session session, int expectedSize) throws RepositoryException {
+ private static PrincipalAccessControlList assertPolicy(
+ @NotNull Principal principal, @NotNull Session session, int expectedSize) throws RepositoryException {
PrincipalAccessControlList acl = getAcl(principal, session);
assertNotNull(acl);
assertEquals(expectedSize, acl.size());
@@ -202,17 +221,14 @@ public class PrincipalBasedAclTest {
throw new RepositoryException("Expected service user " + uid + " to exist.");
}
}
-
+
private Principal getPrincipal(@NotNull String serviceUserId) throws RepositoryException {
return getServiceUser(serviceUserId).getPrincipal();
}
@Test
public void readGranted() throws Exception {
- String setup =
- "set principal ACL for " + U.username + "\n"
- + "allow jcr:read on " + path + "\n"
- + "end";
+ String setup = "set principal ACL for " + U.username + "\n" + "allow jcr:read on " + path + "\n" + "end";
U.parseAndExecute(setup);
testSession.refresh(false);
@@ -223,11 +239,9 @@ public class PrincipalBasedAclTest {
@Test
public void grantedNonExistingPath() throws Exception {
- String nonExistingPath = path +"/nonExisting";
+ String nonExistingPath = path + "/nonExisting";
String setup =
- "set principal ACL for " + U.username + "\n"
- + "allow jcr:read on " + nonExistingPath + "\n"
- + "end";
+ "set principal ACL for " + U.username + "\n" + "allow jcr:read on " + nonExistingPath + "\n" + "end";
U.parseAndExecute(setup);
testSession.refresh(false);
@@ -236,28 +250,27 @@ public class PrincipalBasedAclTest {
@Test
public void grantAtRootPath() throws Exception {
- String setup =
- "set principal ACL for " + U.username + "\n"
- + "allow jcr:all on /\n"
- + "end"
- ;
+ String setup = "set principal ACL for " + U.username + "\n" + "allow jcr:all on /\n" + "end";
U.parseAndExecute(setup);
testSession.refresh(false);
- assertPermission(testSession, "/newChild", Session.ACTION_READ +","+ Session.ACTION_ADD_NODE +","+ Session.ACTION_REMOVE, true);
+ assertPermission(
+ testSession,
+ "/newChild",
+ Session.ACTION_READ + "," + Session.ACTION_ADD_NODE + "," + Session.ACTION_REMOVE,
+ true);
}
@Test
public void multiplePrivileges() throws Exception {
- String setup =
- "set principal ACL for " + U.username + "\n"
- + "allow jcr:read, jcr:versionManagement on " + path + "\n"
- + "end";
+ String setup = "set principal ACL for " + U.username + "\n"
+ + "allow jcr:read, jcr:versionManagement on " + path + "\n"
+ + "end";
U.parseAndExecute(setup);
testSession.refresh(false);
- String permissions = Permissions.getString(Permissions.READ|Permissions.VERSION_MANAGEMENT);
+ String permissions = Permissions.getString(Permissions.READ | Permissions.VERSION_MANAGEMENT);
assertPermission(testSession, path, permissions, true);
assertPermission(testSession, path + "/newchild", permissions, true);
}
@@ -265,39 +278,32 @@ public class PrincipalBasedAclTest {
@Test(expected = RepoInitException.class)
public void invalidPrivilege() throws Exception {
String setup =
- "set principal ACL for " + U.username + "\n"
- + "allow my:invalidPrivilege on " + path + "\n"
- + "end";
+ "set principal ACL for " + U.username + "\n" + "allow my:invalidPrivilege on " + path + "\n" + "end";
U.parseAndExecute(setup);
}
@Test(expected = RepoInitException.class)
- public void denyEntry() throws Exception {
- String setup =
- "set principal ACL for " + U.username + "\n"
- + "deny jcr:read on " + path + "\n"
- + "end";
+ public void denyEntry() throws Exception {
+ String setup = "set principal ACL for " + U.username + "\n" + "deny jcr:read on " + path + "\n" + "end";
U.parseAndExecute(setup);
}
@Test
public void repoLevelPermission() throws Exception {
String setup =
- "set principal ACL for " + U.username + "\n"
- + "allow jcr:namespaceManagement on :repository\n"
- + "end";
+ "set principal ACL for " + U.username + "\n" + "allow jcr:namespaceManagement on :repository\n" + "end";
U.parseAndExecute(setup);
testSession.refresh(false);
- assertTrue(testSession.getAccessControlManager().hasPrivileges(null, AccessControlUtils.privilegesFromNames(testSession, "jcr:namespaceManagement")));
+ assertTrue(testSession
+ .getAccessControlManager()
+ .hasPrivileges(null, AccessControlUtils.privilegesFromNames(testSession, "jcr:namespaceManagement")));
}
@Test
public void repoLevelAndPath() throws Exception {
String setup =
- "set principal ACL for " + U.username + "\n"
- + "allow jcr:all on :repository, "+path+"\n"
- + "end";
+ "set principal ACL for " + U.username + "\n" + "allow jcr:all on :repository, " + path + "\n" + "end";
U.parseAndExecute(setup);
testSession.refresh(false);
@@ -311,11 +317,9 @@ public class PrincipalBasedAclTest {
String notAllowed = "/testxyz_" + U.id;
String allowed = "/testabc_" + U.id;
- String setup =
- "set principal ACL for " + U.username + "\n"
- + "allow jcr:read on "+path+" restriction(rep:glob,*abc*)\n"
- + "end"
- ;
+ String setup = "set principal ACL for " + U.username + "\n"
+ + "allow jcr:read on " + path + " restriction(rep:glob,*abc*)\n"
+ + "end";
U.parseAndExecute(setup);
testSession.refresh(false);
@@ -326,10 +330,9 @@ public class PrincipalBasedAclTest {
@Test
public void emptyGlobRestriction() throws Exception {
- String setup =
- "set principal ACL for " + U.username + "\n"
- + "allow jcr:read on "+path+" restriction (rep:glob)\n"
- + "end";
+ String setup = "set principal ACL for " + U.username + "\n"
+ + "allow jcr:read on " + path + " restriction (rep:glob)\n"
+ + "end";
U.parseAndExecute(setup);
testSession.refresh(false);
@@ -342,11 +345,9 @@ public class PrincipalBasedAclTest {
@Test
public void mvItemNamesRestriction() throws Exception {
- String setup =
- "set principal ACL for " + U.username + "\n"
- + "allow jcr:modifyProperties on / restriction(rep:itemNames,propName,prop)\n"
- + "end"
- ;
+ String setup = "set principal ACL for " + U.username + "\n"
+ + "allow jcr:modifyProperties on / restriction(rep:itemNames,propName,prop)\n"
+ + "end";
U.parseAndExecute(setup);
testSession.refresh(false);
@@ -357,11 +358,9 @@ public class PrincipalBasedAclTest {
@Test
public void emptyMvRestrictionTest() throws Exception {
- String setup =
- "set principal ACL for " + U.username + "\n"
- + "allow jcr:read on "+path+" restriction(rep:ntNames)\n"
- + "end"
- ;
+ String setup = "set principal ACL for " + U.username + "\n"
+ + "allow jcr:read on " + path + " restriction(rep:ntNames)\n"
+ + "end";
U.parseAndExecute(setup);
testSession.refresh(false);
@@ -370,20 +369,16 @@ public class PrincipalBasedAclTest {
@Test(expected = RepoInitException.class)
public void unsupportedRestriction() throws Exception {
- String setup =
- "set principal ACL for " + U.username + "\n"
- + "allow jcr:read on "+path+" restriction(jcr:unsupported,value)\n"
- + "end"
- ;
+ String setup = "set principal ACL for " + U.username + "\n"
+ + "allow jcr:read on " + path + " restriction(jcr:unsupported,value)\n"
+ + "end";
U.parseAndExecute(setup);
}
@Test
public void multiplePaths() throws Exception {
String setup =
- "set principal ACL for " + U.username + "\n"
- + "allow jcr:read on "+path+", /content\n"
- + "end";
+ "set principal ACL for " + U.username + "\n" + "allow jcr:read on " + path + ", /content\n" + "end";
U.parseAndExecute(setup);
testSession.refresh(false);
@@ -395,10 +390,7 @@ public class PrincipalBasedAclTest {
@Test(expected = RepoInitParsingException.class)
public void missingPath() throws Exception {
- String setup =
- "set principal ACL for " + U.username + "\n"
- + "allow jcr:read on \n"
- + "end";
+ String setup = "set principal ACL for " + U.username + "\n" + "allow jcr:read on \n" + "end";
U.parseAndExecute(setup);
}
@@ -408,10 +400,9 @@ public class PrincipalBasedAclTest {
Session s = null;
try {
U.parseAndExecute("create service user otherSystemPrincipal with path " + relPath);
- String setup =
- "set principal ACL for " + U.username + ",otherSystemPrincipal \n"
- + "allow jcr:read on " + path + "\n"
- + "end";
+ String setup = "set principal ACL for " + U.username + ",otherSystemPrincipal \n"
+ + "allow jcr:read on " + path + "\n"
+ + "end";
U.parseAndExecute(setup);
testSession.refresh(false);
@@ -428,10 +419,7 @@ public class PrincipalBasedAclTest {
@Test(expected = RepoInitParsingException.class)
public void missingPrincipal() throws Exception {
- String setup =
- "set principal ACL for \n"
- + "allow jcr:read on "+path+"\n"
- + "end";
+ String setup = "set principal ACL for \n" + "allow jcr:read on " + path + "\n" + "end";
U.parseAndExecute(setup);
}
@@ -439,16 +427,17 @@ public class PrincipalBasedAclTest {
@Test
public void redundantEntry() throws Exception {
String setup = "set principal ACL for " + U.username + "\n"
- + "allow jcr:read on "+path+"\n"
- + "allow jcr:read on "+path+"\n"
- + "end";
+ + "allow jcr:read on " + path + "\n"
+ + "allow jcr:read on " + path + "\n"
+ + "end";
U.parseAndExecute(setup);
- Principal principal = adminSession.getUserManager().getAuthorizable(U.username).getPrincipal();
+ Principal principal =
+ adminSession.getUserManager().getAuthorizable(U.username).getPrincipal();
JackrabbitAccessControlManager acMgr = (JackrabbitAccessControlManager) adminSession.getAccessControlManager();
PrincipalAccessControlList pacl = null;
for (AccessControlPolicy policy : acMgr.getPolicies(principal)) {
- if (policy instanceof PrincipalAccessControlList) {
+ if (policy instanceof PrincipalAccessControlList) {
pacl = (PrincipalAccessControlList) policy;
break;
}
@@ -460,21 +449,18 @@ public class PrincipalBasedAclTest {
@Test
public void grantWithSecondSetup() throws Exception {
- String setup = "set principal ACL for " + U.username + "\n"
- + "allow jcr:read on "+path+"\n"
- + "end";
+ String setup = "set principal ACL for " + U.username + "\n" + "allow jcr:read on " + path + "\n" + "end";
U.parseAndExecute(setup);
- setup = "set principal ACL for " + U.username + "\n"
- + "allow jcr:write on "+path+"\n"
- + "end";
+ setup = "set principal ACL for " + U.username + "\n" + "allow jcr:write on " + path + "\n" + "end";
U.parseAndExecute(setup);
- Principal principal = adminSession.getUserManager().getAuthorizable(U.username).getPrincipal();
+ Principal principal =
+ adminSession.getUserManager().getAuthorizable(U.username).getPrincipal();
JackrabbitAccessControlManager acMgr = (JackrabbitAccessControlManager) adminSession.getAccessControlManager();
PrincipalAccessControlList pacl = null;
for (AccessControlPolicy policy : acMgr.getPolicies(principal)) {
- if (policy instanceof PrincipalAccessControlList) {
+ if (policy instanceof PrincipalAccessControlList) {
pacl = (PrincipalAccessControlList) policy;
break;
}
@@ -484,13 +470,11 @@ public class PrincipalBasedAclTest {
}
@Test(expected = None.class)
- public void principalAclNotAvailable() throws Exception {
+ public void principalAclNotAvailable() throws Exception {
try {
// create service user outside of supported tree for principal-based access control
U.parseAndExecute("create service user otherSystemPrincipal");
- String setup = "set principal ACL for otherSystemPrincipal \n"
- + "allow jcr:read on " + path + "\n"
- + "end";
+ String setup = "set principal ACL for otherSystemPrincipal \n" + "allow jcr:read on " + path + "\n" + "end";
U.parseAndExecute(setup);
} finally {
U.cleanupServiceUser("otherSystemPrincipal");
@@ -498,14 +482,13 @@ public class PrincipalBasedAclTest {
}
@Test(expected = None.class)
- public void principalAclNotAvailableStrict() throws Exception {
+ public void principalAclNotAvailableStrict() throws Exception {
try {
// create service user outside of supported tree for principal-based access control
U.parseAndExecute("create service user otherSystemPrincipal");
// principal-based ac-setup must fail as service user is not located below supported path
- String setup = "ensure principal ACL for otherSystemPrincipal \n"
- + "allow jcr:read on " + path + "\n"
- + "end";
+ String setup =
+ "ensure principal ACL for otherSystemPrincipal \n" + "allow jcr:read on " + path + "\n" + "end";
try {
U.parseAndExecute(setup);
fail("Setting a principal ACL outside a supported path must not succeed");
@@ -518,19 +501,23 @@ public class PrincipalBasedAclTest {
}
@Test
- public void principalAclNotAvailableRestrictionMismatch() throws Exception {
+ public void principalAclNotAvailableRestrictionMismatch() throws Exception {
JackrabbitAccessControlManager acMgr = (JackrabbitAccessControlManager) adminSession.getAccessControlManager();
try {
// create service user outside of supported tree for principal-based access control
U.parseAndExecute("create service user otherSystemPrincipal");
// setup path-based access control to establish effective permission setup
- String setup = "set ACL for otherSystemPrincipal \n"
- + "allow jcr:read on " + path + "\n"
- + "end";
+ String setup = "set ACL for otherSystemPrincipal \n" + "allow jcr:read on " + path + "\n" + "end";
U.parseAndExecute(setup);
- Principal principal = adminSession.getUserManager().getAuthorizable("otherSystemPrincipal").getPrincipal();
- assertTrue(acMgr.hasPrivileges(path, Collections.singleton(principal), AccessControlUtils.privilegesFromNames(adminSession, Privilege.JCR_READ)));
+ Principal principal = adminSession
+ .getUserManager()
+ .getAuthorizable("otherSystemPrincipal")
+ .getPrincipal();
+ assertTrue(acMgr.hasPrivileges(
+ path,
+ Collections.singleton(principal),
+ AccessControlUtils.privilegesFromNames(adminSession, Privilege.JCR_READ)));
setup = "set principal ACL for otherSystemPrincipal \n"
+ "allow jcr:read on " + path + " restriction(rep:glob,*mismatch)\n"
@@ -542,19 +529,23 @@ public class PrincipalBasedAclTest {
}
@Test
- public void principalAclNotAvailableRestrictionMismatchStrict() throws Exception {
+ public void principalAclNotAvailableRestrictionMismatchStrict() throws Exception {
JackrabbitAccessControlManager acMgr = (JackrabbitAccessControlManager) adminSession.getAccessControlManager();
try {
// create service user outside of supported tree for principal-based access control
U.parseAndExecute("create service user otherSystemPrincipal");
// setup path-based access control to establish effective permission setup
- String setup = "set ACL for otherSystemPrincipal \n"
- + "allow jcr:read on " + path + "\n"
- + "end";
+ String setup = "set ACL for otherSystemPrincipal \n" + "allow jcr:read on " + path + "\n" + "end";
U.parseAndExecute(setup);
- Principal principal = adminSession.getUserManager().getAuthorizable("otherSystemPrincipal").getPrincipal();
- assertTrue(acMgr.hasPrivileges(path, Collections.singleton(principal), AccessControlUtils.privilegesFromNames(adminSession, Privilege.JCR_READ)));
+ Principal principal = adminSession
+ .getUserManager()
+ .getAuthorizable("otherSystemPrincipal")
+ .getPrincipal();
+ assertTrue(acMgr.hasPrivileges(
+ path,
+ Collections.singleton(principal),
+ AccessControlUtils.privilegesFromNames(adminSession, Privilege.JCR_READ)));
// setting up principal-acl will not succeed (principal not located below supported path)
// since effective entry doesn't match the restriction -> setup must fail
@@ -573,25 +564,27 @@ public class PrincipalBasedAclTest {
}
@Test
- public void principalAclNotAvailableEntryPresent() throws Exception {
+ public void principalAclNotAvailableEntryPresent() throws Exception {
JackrabbitAccessControlManager acMgr = (JackrabbitAccessControlManager) adminSession.getAccessControlManager();
try {
// create service user outside of supported tree for principal-based access control
U.parseAndExecute("create service user otherSystemPrincipal");
// setup path-based access control to establish effective permission setup
- String setup = "set ACL for otherSystemPrincipal \n"
- + "allow jcr:read on " + path + "\n"
- + "end";
+ String setup = "set ACL for otherSystemPrincipal \n" + "allow jcr:read on " + path + "\n" + "end";
U.parseAndExecute(setup);
- Principal principal = adminSession.getUserManager().getAuthorizable("otherSystemPrincipal").getPrincipal();
- assertTrue(acMgr.hasPrivileges(path, Collections.singleton(principal), AccessControlUtils.privilegesFromNames(adminSession, Privilege.JCR_READ)));
+ Principal principal = adminSession
+ .getUserManager()
+ .getAuthorizable("otherSystemPrincipal")
+ .getPrincipal();
+ assertTrue(acMgr.hasPrivileges(
+ path,
+ Collections.singleton(principal),
+ AccessControlUtils.privilegesFromNames(adminSession, Privilege.JCR_READ)));
// setting up principal-acl will not succeed (principal not located below supported path)
// but there exists an effective entry with the same definition -> no exception
- setup = "set principal ACL for otherSystemPrincipal \n"
- + "allow jcr:read on " + path + "\n"
- + "end";
+ setup = "set principal ACL for otherSystemPrincipal \n" + "allow jcr:read on " + path + "\n" + "end";
U.parseAndExecute(setup);
for (AccessControlPolicy policy : acMgr.getPolicies(principal)) {
@@ -603,24 +596,26 @@ public class PrincipalBasedAclTest {
}
@Test
- public void principalAclNotAvailableEntryPresentStrict() throws Exception {
+ public void principalAclNotAvailableEntryPresentStrict() throws Exception {
JackrabbitAccessControlManager acMgr = (JackrabbitAccessControlManager) adminSession.getAccessControlManager();
try {
// create service user outside of supported tree for principal-based access control
U.parseAndExecute("create service user otherSystemPrincipal");
// setup path-based access control to establish effective permission setup
- String setup = "set ACL for otherSystemPrincipal \n"
- + "allow jcr:read on " + path + "\n"
- + "end";
+ String setup = "set ACL for otherSystemPrincipal \n" + "allow jcr:read on " + path + "\n" + "end";
U.parseAndExecute(setup);
- Principal principal = adminSession.getUserManager().getAuthorizable("otherSystemPrincipal").getPrincipal();
- assertTrue(acMgr.hasPrivileges(path, Collections.singleton(principal), AccessControlUtils.privilegesFromNames(adminSession, Privilege.JCR_READ)));
+ Principal principal = adminSession
+ .getUserManager()
+ .getAuthorizable("otherSystemPrincipal")
+ .getPrincipal();
+ assertTrue(acMgr.hasPrivileges(
+ path,
+ Collections.singleton(principal),
+ AccessControlUtils.privilegesFromNames(adminSession, Privilege.JCR_READ)));
// setting up principal-acl will not succeed (principal not located below supported path)
- setup = "ensure principal ACL for otherSystemPrincipal \n"
- + "allow jcr:read on " + path + "\n"
- + "end";
+ setup = "ensure principal ACL for otherSystemPrincipal \n" + "allow jcr:read on " + path + "\n" + "end";
try {
U.parseAndExecute(setup);
fail("Setting a principal ACL outside a supported path must not succeed");
@@ -633,7 +628,7 @@ public class PrincipalBasedAclTest {
}
@Test
- public void principalAclNotAvailableEntryWithRestrictionPresent() throws Exception {
+ public void principalAclNotAvailableEntryWithRestrictionPresent() throws Exception {
JackrabbitAccessControlManager acMgr = (JackrabbitAccessControlManager) adminSession.getAccessControlManager();
try {
// create service user outside of supported tree for principal-based access control
@@ -651,7 +646,10 @@ public class PrincipalBasedAclTest {
+ "end";
U.parseAndExecute(setup);
- Principal principal = adminSession.getUserManager().getAuthorizable("otherSystemPrincipal").getPrincipal();
+ Principal principal = adminSession
+ .getUserManager()
+ .getAuthorizable("otherSystemPrincipal")
+ .getPrincipal();
for (AccessControlPolicy policy : acMgr.getPolicies(principal)) {
assertFalse(policy instanceof PrincipalAccessControlList);
}
@@ -661,7 +659,7 @@ public class PrincipalBasedAclTest {
}
@Test
- public void principalAclNotAvailableEntryWithRestrictionPresentStrict() throws Exception {
+ public void principalAclNotAvailableEntryWithRestrictionPresentStrict() throws Exception {
JackrabbitAccessControlManager acMgr = (JackrabbitAccessControlManager) adminSession.getAccessControlManager();
try {
// create service user outside of supported tree for principal-based access control
@@ -688,15 +686,14 @@ public class PrincipalBasedAclTest {
}
@Test
- public void principalAclNotAvailableRepoLevelPermissions() throws Exception {
+ public void principalAclNotAvailableRepoLevelPermissions() throws Exception {
JackrabbitAccessControlManager acMgr = (JackrabbitAccessControlManager) adminSession.getAccessControlManager();
try {
// create service user outside of supported tree for principal-based access control
U.parseAndExecute("create service user otherSystemPrincipal");
// setup path-based access control to establish effective permission setup
- String setup = "set ACL for otherSystemPrincipal \n"
- + "allow jcr:namespaceManagement on :repository\n"
- + "end";
+ String setup =
+ "set ACL for otherSystemPrincipal \n" + "allow jcr:namespaceManagement on :repository\n" + "end";
U.parseAndExecute(setup);
// setting up principal-acl will not succeed (principal not located below supported path)
@@ -706,7 +703,10 @@ public class PrincipalBasedAclTest {
+ "end";
U.parseAndExecute(setup);
- Principal principal = adminSession.getUserManager().getAuthorizable("otherSystemPrincipal").getPrincipal();
+ Principal principal = adminSession
+ .getUserManager()
+ .getAuthorizable("otherSystemPrincipal")
+ .getPrincipal();
for (AccessControlPolicy policy : acMgr.getPolicies(principal)) {
assertFalse(policy instanceof PrincipalAccessControlList);
}
@@ -716,15 +716,14 @@ public class PrincipalBasedAclTest {
}
@Test
- public void principalAclNotAvailableRepoLevelPermissionsStrict() throws Exception {
+ public void principalAclNotAvailableRepoLevelPermissionsStrict() throws Exception {
JackrabbitAccessControlManager acMgr = (JackrabbitAccessControlManager) adminSession.getAccessControlManager();
try {
// create service user outside of supported tree for principal-based access control
U.parseAndExecute("create service user otherSystemPrincipal");
// setup path-based access control to establish effective permission setup
- String setup = "set ACL for otherSystemPrincipal \n"
- + "allow jcr:namespaceManagement on :repository\n"
- + "end";
+ String setup =
+ "set ACL for otherSystemPrincipal \n" + "allow jcr:namespaceManagement on :repository\n" + "end";
U.parseAndExecute(setup);
// setting up principal-acl will not succeed (principal not located below supported path)
@@ -744,7 +743,7 @@ public class PrincipalBasedAclTest {
}
@Test
- public void principalAclNotAvailableNonExistingNode() throws Exception {
+ public void principalAclNotAvailableNonExistingNode() throws Exception {
JackrabbitAccessControlManager acMgr = (JackrabbitAccessControlManager) adminSession.getAccessControlManager();
try {
// create service user outside of supported tree for principal-based access control
@@ -753,9 +752,8 @@ public class PrincipalBasedAclTest {
// setting up principal-acl will not succeed (principal not located below supported path)
// but since the target node does not exist we cannot verify if an equivalent resource-based ac-setup exists
// (AccessControlManager.getPolicies would fail with PathNotFoundException) => relaxed behavior (SLING-9412)
- String setup = "set principal ACL for otherSystemPrincipal \n"
- + "allow jcr:read on /non/existing/path\n"
- + "end";
+ String setup =
+ "set principal ACL for otherSystemPrincipal \n" + "allow jcr:read on /non/existing/path\n" + "end";
U.parseAndExecute(setup);
Principal principal = getPrincipal("otherSystemPrincipal");
@@ -768,7 +766,7 @@ public class PrincipalBasedAclTest {
}
@Test
- public void principalAclNotAvailableNonExistingNodeStrict() throws Exception {
+ public void principalAclNotAvailableNonExistingNodeStrict() throws Exception {
JackrabbitAccessControlManager acMgr = (JackrabbitAccessControlManager) adminSession.getAccessControlManager();
try {
// create service user outside of supported tree for principal-based access control
@@ -805,14 +803,16 @@ public class PrincipalBasedAclTest {
AclLine line = new AclLine(AclLine.Action.ALLOW);
line.setProperty(AclLine.PROP_PRINCIPALS, Collections.singletonList(principal.getName()));
line.setProperty(AclLine.PROP_PRIVILEGES, Collections.singletonList(Privilege.JCR_READ));
- line.setProperty(AclLine.PROP_PATHS, Collections.singletonList(":home:"+U.username+"#"));
+ line.setProperty(AclLine.PROP_PATHS, Collections.singletonList(":home:" + U.username + "#"));
AclUtil.setPrincipalAcl(U.adminSession, U.username, Collections.singletonList(line), false);
PrincipalAccessControlList acl = getAcl(principal, U.adminSession);
assertNotNull(acl);
assertEquals(1, acl.size());
PrincipalAccessControlList.Entry entry = (PrincipalAccessControlList.Entry) acl.getAccessControlEntries()[0];
- assertArrayEquals(AccessControlUtils.privilegesFromNames(AclUtil.getJACM(U.adminSession), Privilege.JCR_READ), entry.getPrivileges());
+ assertArrayEquals(
+ AccessControlUtils.privilegesFromNames(AclUtil.getJACM(U.adminSession), Privilege.JCR_READ),
+ entry.getPrivileges());
assertEquals(su.getPath(), entry.getEffectivePath());
}
@@ -822,7 +822,7 @@ public class PrincipalBasedAclTest {
String id = "systemUser_" + UUID.randomUUID().toString();
try {
User su = uMgr.createSystemUser(id, relPath);
- String setup = "set principal ACL for "+su.getPrincipal().getName()+" \n"
+ String setup = "set principal ACL for " + su.getPrincipal().getName() + " \n"
+ "allow jcr:read on " + path + "\n"
+ "end";
U.parseAndExecute(setup);
@@ -842,43 +842,33 @@ public class PrincipalBasedAclTest {
@Test
public void testRemoveAction() throws Exception {
- String setup = "set principal ACL for " + U.username + "\n"
- + "allow jcr:write on "+path+"\n"
- + "end";
+ String setup = "set principal ACL for " + U.username + "\n" + "allow jcr:write on " + path + "\n" + "end";
U.parseAndExecute(setup);
- setup = "set principal ACL for " + U.username + "\n"
- + "remove jcr:write on " + path + "\n"
- + "end";
+ setup = "set principal ACL for " + U.username + "\n" + "remove jcr:write on " + path + "\n" + "end";
try {
U.parseAndExecute(setup);
fail("Expecting REMOVE to fail");
- } catch(RuntimeException rex) {
+ } catch (RuntimeException rex) {
assertRegex(REMOVE_NOT_SUPPORTED_REGEX, rex.getMessage());
}
}
@Test(expected = None.class)
public void testRemoveNoExistingPolicy() throws Exception {
- String setup = "remove principal ACE for " + U.username + "\n"
- + "allow jcr:read on " + path + "\n"
- + "end";
+ String setup = "remove principal ACE for " + U.username + "\n" + "allow jcr:read on " + path + "\n" + "end";
U.parseAndExecute(setup);
}
@Test
public void testRemoveMatchingEntry() throws Exception {
Principal principal = getPrincipal(U.username);
- String setup = "set principal ACL for " + U.username + "\n"
- + "allow jcr:write on "+path+"\n"
- + "end";
+ String setup = "set principal ACL for " + U.username + "\n" + "allow jcr:write on " + path + "\n" + "end";
U.parseAndExecute(setup);
assertPolicy(principal, U.adminSession, 1);
- setup = "remove principal ACE for " + U.username + "\n"
- + "allow jcr:write on " + path + "\n"
- + "end";
+ setup = "remove principal ACE for " + U.username + "\n" + "allow jcr:write on " + path + "\n" + "end";
U.parseAndExecute(setup);
assertPolicy(principal, U.adminSession, 0);
}
@@ -886,30 +876,22 @@ public class PrincipalBasedAclTest {
@Test
public void testRemoveNoMatchingEntry() throws Exception {
Principal principal = getPrincipal(U.username);
- String setup = "set principal ACL for " + U.username + "\n"
- + "allow jcr:write on "+path+"\n"
- + "end";
+ String setup = "set principal ACL for " + U.username + "\n" + "allow jcr:write on " + path + "\n" + "end";
U.parseAndExecute(setup);
assertPolicy(principal, U.adminSession, 1);
// privilege mismatch
- setup = "remove principal ACE for " + U.username + "\n"
- + "allow jcr:read on " + path + "\n"
- + "end";
+ setup = "remove principal ACE for " + U.username + "\n" + "allow jcr:read on " + path + "\n" + "end";
U.parseAndExecute(setup);
assertPolicy(principal, U.adminSession, 1);
// privilege mismatch 2
- setup = "remove principal ACE for " + U.username + "\n"
- + "allow jcr:read,jcr:write on " + path + "\n"
- + "end";
+ setup = "remove principal ACE for " + U.username + "\n" + "allow jcr:read,jcr:write on " + path + "\n" + "end";
U.parseAndExecute(setup);
assertPolicy(principal, U.adminSession, 1);
// path mismatch
- setup = "remove principal ACE for " + U.username + "\n"
- + "allow jcr:write on " + path + "/mismatch\n"
- + "end";
+ setup = "remove principal ACE for " + U.username + "\n" + "allow jcr:write on " + path + "/mismatch\n" + "end";
U.parseAndExecute(setup);
assertPolicy(principal, U.adminSession, 1);
@@ -923,24 +905,18 @@ public class PrincipalBasedAclTest {
@Test(expected = RepoInitException.class)
public void testRemoveNonExistingPrincipal() throws Exception {
- String setup = "remove principal ACE for nonExistingPrincipal\n"
- + "deny jcr:write on " + path + "\n"
- + "end";
+ String setup = "remove principal ACE for nonExistingPrincipal\n" + "deny jcr:write on " + path + "\n" + "end";
U.parseAndExecute(setup);
}
@Test
public void testRemovePrincipalMismatch() throws Exception {
- String setup = "set principal ACL for " + U.username + "\n"
- + "allow jcr:write on "+path+"\n"
- + "end";
+ String setup = "set principal ACL for " + U.username + "\n" + "allow jcr:write on " + path + "\n" + "end";
U.parseAndExecute(setup);
U.parseAndExecute("create service user otherSystemPrincipal");
assertPolicy(getPrincipal(U.username), U.adminSession, 1);
- setup = "remove principal ACE for otherSystemPrincipal\n"
- + "allow jcr:write on " + path + "\n"
- + "end";
+ setup = "remove principal ACE for otherSystemPrincipal\n" + "allow jcr:write on " + path + "\n" + "end";
U.parseAndExecute(setup);
// ace must not have been removed
@@ -950,37 +926,29 @@ public class PrincipalBasedAclTest {
@Test
public void testRemovePrincipalMismatchStrict() throws Exception {
- String setup = "ensure principal ACL for " + U.username + "\n"
- + "allow jcr:write on "+path+"\n"
- + "end";
+ String setup = "ensure principal ACL for " + U.username + "\n" + "allow jcr:write on " + path + "\n" + "end";
U.parseAndExecute(setup);
U.parseAndExecute("create service user otherSystemPrincipal");
assertPolicy(getPrincipal(U.username), U.adminSession, 1);
- setup = "remove principal ACE for otherSystemPrincipal\n"
- + "allow jcr:write on " + path + "\n"
- + "end";
+ setup = "remove principal ACE for otherSystemPrincipal\n" + "allow jcr:write on " + path + "\n" + "end";
U.parseAndExecute(setup);
// ace must not have been removed
assertPolicy(getPrincipal(U.username), U.adminSession, 1);
assertNull(getAcl(getPrincipal("otherSystemPrincipal"), U.adminSession));
try {
- setup = "ensure principal ACL for otherSystemPrincipal\n"
- + "remove jcr:write on " + path + "\n"
- + "end";
+ setup = "ensure principal ACL for otherSystemPrincipal\n" + "remove jcr:write on " + path + "\n" + "end";
U.parseAndExecute(setup);
fail("Expecting REMOVE to fail");
- } catch(RuntimeException rex) {
+ } catch (RuntimeException rex) {
assertRegex(NO_PRINCIPAL_CONTROL_LIST_AVAILABLE, rex.getMessage());
}
}
@Test
public void testRemoveAllNoExistingPolicy() throws Exception {
- String setup = "set principal ACL for " + U.username + "\n"
- + "remove * on " + path + "\n"
- + "end";
+ String setup = "set principal ACL for " + U.username + "\n" + "remove * on " + path + "\n" + "end";
U.parseAndExecute(setup);
// removal must be ignored and no policy must be created
@@ -989,23 +957,19 @@ public class PrincipalBasedAclTest {
@Test(expected = RepoInitException.class)
public void testAllRemoveNonExistingPrincipal() throws Exception {
- String setup = "set principal ACL for nonExistingPrincipal\n"
- + "remove * on " + path + "\n"
- + "end";
+ String setup = "set principal ACL for nonExistingPrincipal\n" + "remove * on " + path + "\n" + "end";
U.parseAndExecute(setup);
}
@Test
public void testRemoveAll() throws Exception {
String setup = "set principal ACL for " + U.username + "\n"
- + "allow jcr:write on "+path+"\n"
- + "allow jcr:read on "+path+"\n"
+ + "allow jcr:write on " + path + "\n"
+ + "allow jcr:read on " + path + "\n"
+ "end";
U.parseAndExecute(setup);
- setup = "set principal ACL for " + U.username + "\n"
- + "remove * on " + path + "\n"
- + "end";
+ setup = "set principal ACL for " + U.username + "\n" + "remove * on " + path + "\n" + "end";
U.parseAndExecute(setup);
assertPolicy(getPrincipal(U.username), U.adminSession, 0);
@@ -1014,16 +978,14 @@ public class PrincipalBasedAclTest {
@Test
public void testRemoveAllRepositoryPath() throws Exception {
String setup = "set principal ACL for " + U.username + "\n"
- + "allow jcr:write on "+path+"\n"
+ + "allow jcr:write on " + path + "\n"
+ "allow jcr:namespaceManagement on :repository\n"
+ "end";
U.parseAndExecute(setup);
assertPolicy(getPrincipal(U.username), U.adminSession, 2);
- setup = "set principal ACL for " + U.username + "\n"
- + "remove * on :repository\n"
- + "end";
+ setup = "set principal ACL for " + U.username + "\n" + "remove * on :repository\n" + "end";
U.parseAndExecute(setup);
assertPolicy(getPrincipal(U.username), U.adminSession, 1);
@@ -1032,16 +994,14 @@ public class PrincipalBasedAclTest {
@Test
public void testRemoveAllPartialPathMatch() throws Exception {
String setup = "set principal ACL for " + U.username + "\n"
- + "allow jcr:write on "+path+"\n"
+ + "allow jcr:write on " + path + "\n"
+ "allow jcr:write on /another/path\n"
+ "end";
U.parseAndExecute(setup);
assertPolicy(getPrincipal(U.username), U.adminSession, 2);
- setup = "set principal ACL for " + U.username + "\n"
- + "remove * on " + path + "\n"
- + "end";
+ setup = "set principal ACL for " + U.username + "\n" + "remove * on " + path + "\n" + "end";
U.parseAndExecute(setup);
assertPolicy(getPrincipal(U.username), U.adminSession, 1);
@@ -1050,15 +1010,15 @@ public class PrincipalBasedAclTest {
@Test
public void testRemoveAllMultiplePaths() throws Exception {
String setup = "set principal ACL for " + U.username + "\n"
- + "allow jcr:write on "+path+"\n"
- + "allow jcr:write on home("+U.username+")\n"
+ + "allow jcr:write on " + path + "\n"
+ + "allow jcr:write on home(" + U.username + ")\n"
+ "end";
U.parseAndExecute(setup);
assertPolicy(getPrincipal(U.username), U.adminSession, 2);
setup = "set principal ACL for " + U.username + "\n"
- + "remove * on " + path + ", home("+U.username+")\n"
+ + "remove * on " + path + ", home(" + U.username + ")\n"
+ "end";
U.parseAndExecute(setup);
@@ -1068,14 +1028,12 @@ public class PrincipalBasedAclTest {
@Test
public void testRemoveAllPathMismatch() throws Exception {
String setup = "set principal ACL for " + U.username + "\n"
- + "allow jcr:write on "+path+"\n"
- + "allow jcr:read on "+path+"\n"
+ + "allow jcr:write on " + path + "\n"
+ + "allow jcr:read on " + path + "\n"
+ "end";
U.parseAndExecute(setup);
- setup = "set principal ACL for " + U.username + "\n"
- + "remove * on /another/path\n"
- + "end";
+ setup = "set principal ACL for " + U.username + "\n" + "remove * on /another/path\n" + "end";
U.parseAndExecute(setup);
assertPolicy(getPrincipal(U.username), U.adminSession, 2);
@@ -1083,29 +1041,21 @@ public class PrincipalBasedAclTest {
@Test(expected = None.class)
public void testRemoveAllPrincipalMismatch() throws Exception {
- String setup = "set principal ACL for " + U.username + "\n"
- + "allow jcr:write on "+path+"\n"
- + "end";
+ String setup = "set principal ACL for " + U.username + "\n" + "allow jcr:write on " + path + "\n" + "end";
U.parseAndExecute(setup);
U.parseAndExecute("create service user otherSystemPrincipal");
- setup = "set principal ACL for otherSystemPrincipal\n"
- + "remove * on " + path + "\n"
- + "end";
+ setup = "set principal ACL for otherSystemPrincipal\n" + "remove * on " + path + "\n" + "end";
U.parseAndExecute(setup);
}
@Test(expected = None.class)
public void testRemoveAllPrincipalMismatchStrict() throws Exception {
- String setup = "ensure principal ACL for " + U.username + "\n"
- + "allow jcr:write on "+path+"\n"
- + "end";
+ String setup = "ensure principal ACL for " + U.username + "\n" + "allow jcr:write on " + path + "\n" + "end";
U.parseAndExecute(setup);
U.parseAndExecute("create service user otherSystemPrincipal");
- setup = "ensure principal ACL for otherSystemPrincipal\n"
- + "remove * on " + path + "\n"
- + "end";
+ setup = "ensure principal ACL for otherSystemPrincipal\n" + "remove * on " + path + "\n" + "end";
try {
U.parseAndExecute(setup);
fail("Setting a principal ACL outside a supported path must not succeed");
@@ -1117,16 +1067,15 @@ public class PrincipalBasedAclTest {
@Test
public void testRemoveAllPrincipalDuplicated() throws Exception {
U.parseAndExecute(""
- + "set principal ACL for " + U.username + "\n"
- + "allow jcr:write on "+path+"\n"
- + "allow jcr:read on "+path+"\n"
- + "end\n"
- + "set principal ACL for " + U.username + "\n"
- // duplicating the remove statement exposes SLING-10145
- + "remove * on " + path + "\n"
- + "remove * on " + path + "\n"
- + "end\n"
- );
+ + "set principal ACL for " + U.username + "\n"
+ + "allow jcr:write on " + path + "\n"
+ + "allow jcr:read on " + path + "\n"
+ + "end\n"
+ + "set principal ACL for " + U.username + "\n"
+ // duplicating the remove statement exposes SLING-10145
+ + "remove * on " + path + "\n"
+ + "remove * on " + path + "\n"
+ + "end\n");
assertPolicy(getPrincipal(U.username), U.adminSession, 0);
}
@@ -1135,10 +1084,9 @@ public class PrincipalBasedAclTest {
public void testAddAndDeleteAcl() throws Exception {
U.parseAndExecute(""
+ "set principal ACL for " + U.username + "\n"
- + "allow jcr:write on "+path+"\n"
+ + "allow jcr:write on " + path + "\n"
+ "end\n"
- + "delete principal ACL for " + U.username + "\n"
- );
+ + "delete principal ACL for " + U.username + "\n");
assertNull(getAcl(getPrincipal(U.username), U.adminSession));
}
@@ -1184,7 +1132,7 @@ public class PrincipalBasedAclTest {
assertEquals(1, acMgr.getPolicies("/var").length);
- U.parseAndExecute("delete ACL for "+U.username+"\n");
+ U.parseAndExecute("delete ACL for " + U.username + "\n");
// resource-based acl at /var must be removed as it only contains a single entry for U.userName
assertEquals(0, acMgr.getPolicies("/var").length);
@@ -1196,7 +1144,8 @@ public class PrincipalBasedAclTest {
}
@Nullable
- private static PrincipalAccessControlList getApplicableAcl(@NotNull Principal principal, @NotNull Session session) throws RepositoryException {
+ private static PrincipalAccessControlList getApplicableAcl(@NotNull Principal principal, @NotNull Session session)
+ throws RepositoryException {
for (AccessControlPolicy policy : AclUtil.getJACM(session).getApplicablePolicies(principal)) {
if (policy instanceof PrincipalAccessControlList) {
return (PrincipalAccessControlList) policy;
@@ -1206,7 +1155,8 @@ public class PrincipalBasedAclTest {
}
@Nullable
- private static PrincipalAccessControlList getAcl(@NotNull Principal principal, @NotNull Session session) throws RepositoryException {
+ private static PrincipalAccessControlList getAcl(@NotNull Principal principal, @NotNull Session session)
+ throws RepositoryException {
for (AccessControlPolicy policy : AclUtil.getJACM(session).getPolicies(principal)) {
if (policy instanceof PrincipalAccessControlList) {
return (PrincipalAccessControlList) policy;
@@ -1214,4 +1164,4 @@ public class PrincipalBasedAclTest {
}
return null;
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/RegisterNamespacesTest.java b/src/test/java/org/apache/sling/jcr/repoinit/RegisterNamespacesTest.java
index 004af9b..21f2ea4 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/RegisterNamespacesTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/RegisterNamespacesTest.java
@@ -1,28 +1,28 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit;
-import static org.junit.Assert.assertEquals;
-
-import java.util.UUID;
-
import javax.jcr.NamespaceRegistry;
import javax.jcr.RepositoryException;
+import java.util.UUID;
+
import org.apache.sling.jcr.repoinit.impl.TestUtil;
import org.apache.sling.repoinit.parser.RepoInitParsingException;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
@@ -31,19 +31,21 @@ import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+
/** Test register namespace statements */
public class RegisterNamespacesTest {
@Rule
public final SlingContext context = new SlingContext(ResourceResolverType.JCR_OAK);
-
+
private TestUtil U;
private NamespaceRegistry ns;
-
+
private static final String TEST_ID = UUID.randomUUID().toString();
private static final String NS1 = "uri:ns:test1:" + TEST_ID;
private static final String NS2 = "http://example.com/ns/" + TEST_ID;
-
+
@Before
public void setup() throws RepositoryException, RepoInitParsingException {
U = new TestUtil(context);
@@ -56,7 +58,7 @@ public class RegisterNamespacesTest {
public void NS1registered() throws Exception {
assertEquals(NS1, ns.getURI("one"));
}
-
+
@Test
public void NS2registered() throws Exception {
assertEquals(NS2, ns.getURI("two"));
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/RegisterNodetypesTest.java b/src/test/java/org/apache/sling/jcr/repoinit/RegisterNodetypesTest.java
index 12fd524..5fe2b56 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/RegisterNodetypesTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/RegisterNodetypesTest.java
@@ -1,28 +1,28 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit;
-import static org.junit.Assert.assertEquals;
-
-import java.util.UUID;
-
import javax.jcr.NamespaceRegistry;
import javax.jcr.RepositoryException;
+import java.util.UUID;
+
import org.apache.sling.jcr.repoinit.impl.TestUtil;
import org.apache.sling.repoinit.parser.RepoInitParsingException;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
@@ -32,6 +32,8 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.Test.None;
+import static org.junit.Assert.assertEquals;
+
/** Test register nodetypes statements. Also registers a namespace */
public class RegisterNodetypesTest {
@@ -61,4 +63,4 @@ public class RegisterNodetypesTest {
public void fooNodetypeRegistered() throws Exception {
U.getAdminSession().getRootNode().addNode("test_" + TEST_ID, NS_PREFIX + ":foo");
}
- }
+}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/RegisterPrivilegeTest.java b/src/test/java/org/apache/sling/jcr/repoinit/RegisterPrivilegeTest.java
index 0c1ed38..7f0dbca 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/RegisterPrivilegeTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/RegisterPrivilegeTest.java
@@ -1,21 +1,29 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit;
+import javax.jcr.RepositoryException;
+import javax.jcr.security.Privilege;
+
+import java.util.HashSet;
+import java.util.Set;
+
import org.apache.jackrabbit.api.JackrabbitWorkspace;
import org.apache.sling.jcr.repoinit.impl.TestUtil;
import org.apache.sling.repoinit.parser.RepoInitParsingException;
@@ -25,11 +33,6 @@ import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import javax.jcr.RepositoryException;
-import javax.jcr.security.Privilege;
-import java.util.HashSet;
-import java.util.Set;
-
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -48,13 +51,17 @@ public class RegisterPrivilegeTest {
U.parseAndExecute("register privilege withoutabstract_withoutaggregates2");
U.parseAndExecute("register privilege withoutabstract_withoutaggregates3");
U.parseAndExecute("register abstract privilege withabstract_withoutaggregates");
- U.parseAndExecute("register privilege withoutabstract_withaggregates with withoutabstract_withoutaggregates1,withoutabstract_withoutaggregates2");
- U.parseAndExecute("register abstract privilege withabstract_withaggregates with withoutabstract_withoutaggregates1,withoutabstract_withoutaggregates3");
+ U.parseAndExecute(
+ "register privilege withoutabstract_withaggregates with withoutabstract_withoutaggregates1,withoutabstract_withoutaggregates2");
+ U.parseAndExecute(
+ "register abstract privilege withabstract_withaggregates with withoutabstract_withoutaggregates1,withoutabstract_withoutaggregates3");
}
@Test
public void testRegisterPrivilegeWithoutAbstractWithoutAggregates() throws Exception {
- Privilege privilege = ((JackrabbitWorkspace) U.getAdminSession().getWorkspace()).getPrivilegeManager().getPrivilege("withoutabstract_withoutaggregates1");
+ Privilege privilege = ((JackrabbitWorkspace) U.getAdminSession().getWorkspace())
+ .getPrivilegeManager()
+ .getPrivilege("withoutabstract_withoutaggregates1");
assertFalse(privilege.isAbstract());
assertEquals(0, privilege.getDeclaredAggregatePrivileges().length);
@@ -62,7 +69,9 @@ public class RegisterPrivilegeTest {
@Test
public void testRegisterPrivilegeWitAbstractWithoutAggregates() throws Exception {
- Privilege privilege = ((JackrabbitWorkspace) U.getAdminSession().getWorkspace()).getPrivilegeManager().getPrivilege("withabstract_withoutaggregates");
+ Privilege privilege = ((JackrabbitWorkspace) U.getAdminSession().getWorkspace())
+ .getPrivilegeManager()
+ .getPrivilege("withabstract_withoutaggregates");
assertTrue(privilege.isAbstract());
assertEquals(0, privilege.getDeclaredAggregatePrivileges().length);
@@ -70,7 +79,9 @@ public class RegisterPrivilegeTest {
@Test
public void testRegisterPrivilegeWithoutAbstractWithAggregates() throws Exception {
- Privilege privilege = ((JackrabbitWorkspace) U.getAdminSession().getWorkspace()).getPrivilegeManager().getPrivilege("withoutabstract_withaggregates");
+ Privilege privilege = ((JackrabbitWorkspace) U.getAdminSession().getWorkspace())
+ .getPrivilegeManager()
+ .getPrivilege("withoutabstract_withaggregates");
assertFalse(privilege.isAbstract());
assertEquals(2, privilege.getDeclaredAggregatePrivileges().length);
@@ -79,12 +90,17 @@ public class RegisterPrivilegeTest {
for (Privilege p : privilege.getDeclaredAggregatePrivileges()) {
names.add(p.getName());
}
- assertEquals(names, new HashSet<String>(asList("withoutabstract_withoutaggregates1","withoutabstract_withoutaggregates2")));
+ assertEquals(
+ names,
+ new HashSet<String>(
+ asList("withoutabstract_withoutaggregates1", "withoutabstract_withoutaggregates2")));
}
@Test
public void testRegisterPrivilegeWitAbstractWithAggregates() throws Exception {
- Privilege privilege = ((JackrabbitWorkspace) U.getAdminSession().getWorkspace()).getPrivilegeManager().getPrivilege("withabstract_withaggregates");
+ Privilege privilege = ((JackrabbitWorkspace) U.getAdminSession().getWorkspace())
+ .getPrivilegeManager()
+ .getPrivilege("withabstract_withaggregates");
assertTrue(privilege.isAbstract());
assertEquals(2, privilege.getDeclaredAggregatePrivileges().length);
@@ -93,7 +109,9 @@ public class RegisterPrivilegeTest {
for (Privilege p : privilege.getDeclaredAggregatePrivileges()) {
names.add(p.getName());
}
- assertEquals(names, new HashSet<String>(asList("withoutabstract_withoutaggregates1","withoutabstract_withoutaggregates3")));
+ assertEquals(
+ names,
+ new HashSet<String>(
+ asList("withoutabstract_withoutaggregates1", "withoutabstract_withoutaggregates3")));
}
-
}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/RemoveTest.java b/src/test/java/org/apache/sling/jcr/repoinit/RemoveTest.java
index d266d83..483d7dd 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/RemoveTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/RemoveTest.java
@@ -1,33 +1,31 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.fail;
-
-import java.util.UUID;
-
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.security.AccessControlList;
import javax.jcr.security.AccessControlPolicy;
+import java.util.UUID;
+
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.sling.jcr.repoinit.impl.TestUtil;
@@ -42,6 +40,10 @@ import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.fail;
+
public class RemoveTest {
@Rule
@@ -62,20 +64,20 @@ public class RemoveTest {
path = n.getPath();
UserManager uMgr = UserUtil.getUserManager(U.adminSession);
- Group gr = uMgr.createGroup("group_"+UUID.randomUUID().toString());
+ Group gr = uMgr.createGroup("group_" + UUID.randomUUID().toString());
groupId = gr.getID();
groupPrincipalName = gr.getPrincipal().getName();
U.adminSession.save();
String setup = "set ACL for " + U.username + "\n"
- + "deny jcr:read on "+path+"\n"
+ + "deny jcr:read on " + path + "\n"
+ "deny jcr:all on :repository\n"
+ "allow jcr:read on home(" + U.username + ")\n"
+ "end\n"
+ "\n"
+ "set ACL for " + groupPrincipalName + "\n"
- + "allow jcr:read on "+path+" restriction(rep:glob,/*/foo/*)\n"
+ + "allow jcr:read on " + path + " restriction(rep:glob,/*/foo/*)\n"
+ "allow jcr:namespaceManagement on :repository\n"
+ "allow jcr:read on home(" + U.username + ")\n"
+ "end";
@@ -85,7 +87,6 @@ public class RemoveTest {
assertPolicy(path, U.adminSession, 2);
assertPolicy(null, U.adminSession, 2);
assertPolicy(userHomePath, U.adminSession, 2);
-
}
@After
@@ -99,7 +100,8 @@ public class RemoveTest {
}
}
- private static void assertPolicy(@Nullable String path, @NotNull Session session, int expectedSize) throws RepositoryException {
+ private static void assertPolicy(@Nullable String path, @NotNull Session session, int expectedSize)
+ throws RepositoryException {
AccessControlPolicy[] policies = session.getAccessControlManager().getPolicies(path);
for (AccessControlPolicy policy : policies) {
if (policy instanceof AccessControlList) {
@@ -113,7 +115,7 @@ public class RemoveTest {
@Test
public void testRemoveAllByPath() throws RepoInitParsingException, RepositoryException {
String setup = "set ACL for " + U.username + "\n"
- + "remove * on "+path+",:repository, home("+U.username+")\n"
+ + "remove * on " + path + ",:repository, home(" + U.username + ")\n"
+ "end";
U.parseAndExecute(setup);
@@ -124,9 +126,8 @@ public class RemoveTest {
@Test
public void testRemoveAllByPrincipal() throws RepoInitParsingException, RepositoryException {
- String setup = "set ACL on "+path+", home("+U.username+"), :repository\n"
- + "remove * for "+U.username+"\n" +
- "end";
+ String setup = "set ACL on " + path + ", home(" + U.username + "), :repository\n" + "remove * for " + U.username
+ + "\n" + "end";
U.parseAndExecute(setup);
assertPolicy(path, U.adminSession, 1);
@@ -136,9 +137,8 @@ public class RemoveTest {
@Test
public void testRemoveAllByMultiplePrincipals() throws RepoInitParsingException, RepositoryException {
- String setup = "set ACL on "+path+"\n"
- + "remove * for "+U.username+", "+groupPrincipalName+"\n" +
- "end";
+ String setup =
+ "set ACL on " + path + "\n" + "remove * for " + U.username + ", " + groupPrincipalName + "\n" + "end";
U.parseAndExecute(setup);
assertPolicy(path, U.adminSession, 0);
@@ -148,46 +148,35 @@ public class RemoveTest {
@Test(expected = RuntimeException.class)
public void testRemoveActionByPath() throws RepoInitParsingException, RepositoryException {
- String setup = "set ACL for " + U.username + "\n"
- + "remove jcr:read on "+path+"\n"
- + "end";
+ String setup = "set ACL for " + U.username + "\n" + "remove jcr:read on " + path + "\n" + "end";
U.parseAndExecute(setup);
}
@Test(expected = RuntimeException.class)
public void testRemoveByPath2() throws RepoInitParsingException, RepositoryException {
- String setup = "set ACL for " + groupPrincipalName + "\n"
- + "remove jcr:versionManagement on :repository\n"
- + "end";
+ String setup =
+ "set ACL for " + groupPrincipalName + "\n" + "remove jcr:versionManagement on :repository\n" + "end";
U.parseAndExecute(setup);
}
@Test(expected = RuntimeException.class)
public void testRemoveActionByPrincipal() throws RepoInitParsingException, RepositoryException {
- String setup = "set ACL on home("+U.username+")\n"
- + "remove jcr:all for "+U.username+"\n" +
- "end";
+ String setup = "set ACL on home(" + U.username + ")\n" + "remove jcr:all for " + U.username + "\n" + "end";
U.parseAndExecute(setup);
}
-
+
@Test
public void testRemoveByNonExistingPath() throws Exception {
String path = "/non/existing";
- String setup = "remove ACE for " + U.username + "\n"
- + "deny jcr:read on "+path+"\n"
- + "end";
+ String setup = "remove ACE for " + U.username + "\n" + "deny jcr:read on " + path + "\n" + "end";
U.parseAndExecute(setup);
assertFalse(U.adminSession.nodeExists(path));
- setup = "remove ACE on "+path+"\n"
- + "deny jcr:read for " + U.username + "\n"
- + "end";
+ setup = "remove ACE on " + path + "\n" + "deny jcr:read for " + U.username + "\n" + "end";
U.parseAndExecute(setup);
assertFalse(U.adminSession.nodeExists(path));
- setup = "set ACL on "+path+"\n" +
- "remove * for "+U.username+"\n" +
- "end";
+ setup = "set ACL on " + path + "\n" + "remove * for " + U.username + "\n" + "end";
U.parseAndExecute(setup);
assertFalse(U.adminSession.nodeExists(path));
}
@@ -195,23 +184,17 @@ public class RemoveTest {
@Test
public void testRemoveByPath() throws RepoInitParsingException, RepositoryException {
// non-matching ACE (path-mismatch) -> not removed (and no exception)
- String setup = "remove ACE for " + U.username + "\n"
- + "deny jcr:read on /\n"
- + "end";
+ String setup = "remove ACE for " + U.username + "\n" + "deny jcr:read on /\n" + "end";
U.parseAndExecute(setup);
assertPolicy(path, U.adminSession, 2);
// non-matching ACE (privilege-mismatch) -> not removed (and no exception)
- setup = "remove ACE for " + U.username + "\n"
- + "deny jcr:read,jcr:write on "+path+"\n"
- + "end";
+ setup = "remove ACE for " + U.username + "\n" + "deny jcr:read,jcr:write on " + path + "\n" + "end";
U.parseAndExecute(setup);
assertPolicy(path, U.adminSession, 2);
// matching ACE -> removed
- setup = "remove ACE for " + U.username + "\n"
- + "deny jcr:read on "+path+"\n"
- + "end";
+ setup = "remove ACE for " + U.username + "\n" + "deny jcr:read on " + path + "\n" + "end";
U.parseAndExecute(setup);
assertPolicy(path, U.adminSession, 1);
}
@@ -219,9 +202,8 @@ public class RemoveTest {
@Test
public void testRemoveByRepository() throws RepoInitParsingException, RepositoryException {
// non-matching ACE (allow mismatch) -> not removed (and no exception)
- String setup = "remove ACE for " + groupPrincipalName + "\n"
- + "deny jcr:namespaceManagement on :repository\n"
- + "end";
+ String setup =
+ "remove ACE for " + groupPrincipalName + "\n" + "deny jcr:namespaceManagement on :repository\n" + "end";
U.parseAndExecute(setup);
assertPolicy(null, U.adminSession, 2);
@@ -236,9 +218,8 @@ public class RemoveTest {
@Test
public void testRemoveByPrincipalRepositoryPath() throws RepoInitParsingException, RepositoryException {
// non-matching ACE (privilege mismatch) -> not removed (and no exception)
- String setup = "remove ACE for " + groupPrincipalName + "\n"
- + "allow jcr:versionManagement on :repository\n"
- + "end";
+ String setup =
+ "remove ACE for " + groupPrincipalName + "\n" + "allow jcr:versionManagement on :repository\n" + "end";
U.parseAndExecute(setup);
assertPolicy(null, U.adminSession, 2);
@@ -253,25 +234,22 @@ public class RemoveTest {
@Test
public void testRemoveByHomePath() throws RepoInitParsingException, RepositoryException {
// no-matching ACE (restriction mismatch) -> not removed
- String setup = "remove ACE on home("+U.username+")\n"
- + "allow jcr:read for "+U.username+" restriction(rep:itemNames, prop1)\n" +
- "end";
+ String setup = "remove ACE on home(" + U.username + ")\n" + "allow jcr:read for " + U.username
+ + " restriction(rep:itemNames, prop1)\n" + "end";
U.parseAndExecute(setup);
assertPolicy(userHomePath, U.adminSession, 2);
-
- setup = "remove ACE on home("+U.username+")\n"
- + "allow jcr:read for "+U.username+"\n" +
- "end";
+
+ setup = "remove ACE on home(" + U.username + ")\n" + "allow jcr:read for " + U.username + "\n" + "end";
U.parseAndExecute(setup);
assertPolicy(userHomePath, U.adminSession, 1);
}
-
+
@Test
public void testRemoveEntryWithRestriction() throws Exception {
String setup = "remove ACE for " + groupPrincipalName + "\n"
- + "allow jcr:read on "+path+" restriction(rep:glob, /*/foo/*)\n"
+ + "allow jcr:read on " + path + " restriction(rep:glob, /*/foo/*)\n"
+ "end";
U.parseAndExecute(setup);
assertPolicy(path, U.adminSession, 1);
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/RepositoryInitializerTest.java b/src/test/java/org/apache/sling/jcr/repoinit/RepositoryInitializerTest.java
index 14a76b1..4561d83 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/RepositoryInitializerTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/RepositoryInitializerTest.java
@@ -1,25 +1,23 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
@@ -33,7 +31,6 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
-import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.sling.jcr.api.SlingRepository;
import org.apache.sling.jcr.repoinit.impl.JcrRepoInitOpsProcessorImpl;
import org.apache.sling.jcr.repoinit.impl.RepoinitTextProvider.TextFormat;
@@ -50,6 +47,9 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
/** Test the two ways in which our RepositoryInitializer
* can read repoinit statements: either from a provisioning
* model file or directly as raw repoinit statements.
@@ -71,35 +71,51 @@ public class RepositoryInitializerTest {
private final String serviceUser;
private final Class<?> expectedActivateException;
- @Parameters(name="{0}")
+ @Parameters(name = "{0}")
public static Collection<Object[]> data() {
- final List<Object []> result = new ArrayList<Object[]>();
+ final List<Object[]> result = new ArrayList<Object[]>();
// Realistic cases
- result.add(new Object[] { "Using provisioning model", "SECTION_" + UUID.randomUUID(), TextFormat.MODEL.toString(), true, true, null });
- result.add(new Object[] { "Default value of model section config", null, TextFormat.MODEL.toString(), true, true, null });
- result.add(new Object[] { "Raw repoinit/empty section", "", TextFormat.RAW.toString(), false, true, null });
- result.add(new Object[] { "Raw repoinit/ignored section name", "IGNORED_SectionName", TextFormat.RAW.toString(), false, true, null });
+ result.add(new Object[] {
+ "Using provisioning model", "SECTION_" + UUID.randomUUID(), TextFormat.MODEL.toString(), true, true, null
+ });
+ result.add(new Object[] {
+ "Default value of model section config", null, TextFormat.MODEL.toString(), true, true, null
+ });
+ result.add(new Object[] {"Raw repoinit/empty section", "", TextFormat.RAW.toString(), false, true, null});
+ result.add(new Object[] {
+ "Raw repoinit/ignored section name", "IGNORED_SectionName", TextFormat.RAW.toString(), false, true, null
+ });
// Edge and failure cases
- result.add(new Object[] { "All empty, just setup + parsing", "", TextFormat.RAW.toString(), false, false, null });
- result.add(new Object[] { "Raw repoinit/null format", null, null, true, false, RepoInitParsingException.class });
- result.add(new Object[] { "With model/null format", null, null, false, false, RuntimeException.class });
- result.add(new Object[] { "Invalid format", null, "invalidFormat", false, false, RuntimeException.class });
- result.add(new Object[] { "Empty model section", "", TextFormat.MODEL.toString(), false, false, IllegalArgumentException.class });
- result.add(new Object[] { "Null model section", null, TextFormat.MODEL.toString(), false, false, IOException.class });
+ result.add(new Object[] {"All empty, just setup + parsing", "", TextFormat.RAW.toString(), false, false, null});
+ result.add(new Object[] {"Raw repoinit/null format", null, null, true, false, RepoInitParsingException.class});
+ result.add(new Object[] {"With model/null format", null, null, false, false, RuntimeException.class});
+ result.add(new Object[] {"Invalid format", null, "invalidFormat", false, false, RuntimeException.class});
+ result.add(new Object[] {
+ "Empty model section", "", TextFormat.MODEL.toString(), false, false, IllegalArgumentException.class
+ });
+ result.add(
+ new Object[] {"Null model section", null, TextFormat.MODEL.toString(), false, false, IOException.class
+ });
return result;
}
- public RepositoryInitializerTest(String description, String modelSection, String textFormat,
- boolean useProvisioningModel, boolean testLogin, Class<?> expectedException) throws IOException {
+ public RepositoryInitializerTest(
+ String description,
+ String modelSection,
+ String textFormat,
+ boolean useProvisioningModel,
+ boolean testLogin,
+ Class<?> expectedException)
+ throws IOException {
serviceUser = getClass().getSimpleName() + "-" + UUID.randomUUID();
String txt = "create service user " + serviceUser;
- if(useProvisioningModel && modelSection == null) {
+ if (useProvisioningModel && modelSection == null) {
txt = "[feature name=foo]\n[:repoinit]\n" + txt;
- } else if(useProvisioningModel) {
+ } else if (useProvisioningModel) {
txt = "[feature name=bar]\n[:" + modelSection + "]\n" + txt;
}
this.repoInitText = txt + "\n";
@@ -115,8 +131,8 @@ public class RepositoryInitializerTest {
U = new TestUtil(context);
final String ref;
- if(TextFormat.MODEL.toString().equals(textFormat)) {
- if(modelSection != null) {
+ if (TextFormat.MODEL.toString().equals(textFormat)) {
+ if (modelSection != null) {
ref = "model@" + modelSection + ":" + url;
} else {
ref = "model:" + url;
@@ -127,7 +143,7 @@ public class RepositoryInitializerTest {
initializer = new RepositoryInitializer();
config = new HashMap<String, Object>();
- config.put("references", new String[] { ref });
+ config.put("references", new String[] {ref});
context.registerInjectActivateService(new RepoInitParserService());
context.registerInjectActivateService(new JcrRepoInitOpsProcessorImpl());
@@ -137,8 +153,8 @@ public class RepositoryInitializerTest {
// Mock environment doesn't cause this to be called
initializer.processRepository(context.getService(SlingRepository.class));
- } catch(Exception e) {
- if(expectedActivateException != null) {
+ } catch (Exception e) {
+ if (expectedActivateException != null) {
// check if the expected active exception is either the exception itself or in the root cause tree
Collection<Class<?>> actualExceptionClasses = new LinkedList<>();
actualExceptionClasses.add(e.getClass());
@@ -148,13 +164,12 @@ public class RepositoryInitializerTest {
t = t.getCause();
}
assertTrue(
- "Expecting a " + expectedActivateException.getName() + " but got " + withStackTrace(e),
- actualExceptionClasses.contains(expectedActivateException));
+ "Expecting a " + expectedActivateException.getName() + " but got " + withStackTrace(e),
+ actualExceptionClasses.contains(expectedActivateException));
} else {
fail("Unexpected Exception in activation: " + withStackTrace(e));
}
}
-
}
public static String withStackTrace(Throwable t) {
@@ -165,10 +180,10 @@ public class RepositoryInitializerTest {
@Test
public void testLogin() throws Exception {
- if(testLogin) {
+ if (testLogin) {
try {
U.loginService(serviceUser);
- } catch(Exception e) {
+ } catch (Exception e) {
fail("Login failed for " + serviceUser + " repoinit statements (" + repoInitText + ") not applied?");
}
}
@@ -184,4 +199,4 @@ public class RepositoryInitializerTest {
w.close();
return tmpFile.toURI().toURL().toString();
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/SetAclWithoutExistingAuthorizableTest.java b/src/test/java/org/apache/sling/jcr/repoinit/SetAclWithoutExistingAuthorizableTest.java
index 40532df..072e968 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/SetAclWithoutExistingAuthorizableTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/SetAclWithoutExistingAuthorizableTest.java
@@ -1,21 +1,30 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit;
+import javax.jcr.Repository;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.SimpleCredentials;
+
+import java.util.stream.Stream;
+
import org.apache.jackrabbit.oak.jcr.Jcr;
import org.apache.jackrabbit.oak.security.internal.SecurityProviderBuilder;
import org.apache.jackrabbit.oak.spi.security.ConfigurationParameters;
@@ -30,13 +39,6 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
-import javax.jcr.Repository;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.SimpleCredentials;
-
-import java.util.stream.Stream;
-
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.params.provider.Arguments.arguments;
@@ -44,31 +46,37 @@ class SetAclWithoutExistingAuthorizableTest {
static Stream<Arguments> nonExistingGroupStatements() {
return Stream.of(
- arguments(String.join("\n",
+ arguments(String.join(
+ "\n",
"set ACL on / (ACLOptions=ignoreMissingPrincipal)",
" allow jcr:read for nonExistingGroup",
"end")),
- arguments(String.join("\n",
+ arguments(String.join(
+ "\n",
"set ACL for nonExistingGroup (ACLOptions=ignoreMissingPrincipal)",
" allow jcr:read on /",
- "end"))
- );
+ "end")));
}
static Stream<Arguments> existingGroupStatements() {
return Stream.of(ImportBehavior.NAME_BESTEFFORT, ImportBehavior.NAME_IGNORE, ImportBehavior.NAME_ABORT)
.flatMap(importBehaviour -> Stream.of(
- arguments(importBehaviour, String.join("\n",
- "create group existingGroup",
- "set ACL on / (ACLOptions=ignoreMissingPrincipal)",
- " allow jcr:read for existingGroup",
- "end")),
- arguments(importBehaviour, String.join("\n",
- "create group existingGroup",
- "set ACL for existingGroup (ACLOptions=ignoreMissingPrincipal)",
- " allow jcr:read on /",
- "end"))
- ));
+ arguments(
+ importBehaviour,
+ String.join(
+ "\n",
+ "create group existingGroup",
+ "set ACL on / (ACLOptions=ignoreMissingPrincipal)",
+ " allow jcr:read for existingGroup",
+ "end")),
+ arguments(
+ importBehaviour,
+ String.join(
+ "\n",
+ "create group existingGroup",
+ "set ACL for existingGroup (ACLOptions=ignoreMissingPrincipal)",
+ " allow jcr:read on /",
+ "end"))));
}
@ParameterizedTest
@@ -107,15 +115,15 @@ class SetAclWithoutExistingAuthorizableTest {
assertReadOnRootPath(U, "existingGroup", true);
}
- private static void assertReadOnRootPath(TestUtil U, String principalName, boolean allowed) throws RepositoryException {
+ private static void assertReadOnRootPath(TestUtil U, String principalName, boolean allowed)
+ throws RepositoryException {
U.assertPrivileges(principalName, "/", allowed, "jcr:read");
}
@NotNull
private static TestUtil createTestUtil(String importBehaviour) throws RepositoryException {
- final Repository repository = new Jcr()
- .with(createSecurityProvider(importBehaviour))
- .createRepository();
+ final Repository repository =
+ new Jcr().with(createSecurityProvider(importBehaviour)).createRepository();
final Session adminSession = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
return new TestUtil(adminSession);
}
@@ -125,7 +133,7 @@ class SetAclWithoutExistingAuthorizableTest {
return SecurityProviderBuilder.newBuilder()
.with(ConfigurationParameters.of(
AuthorizationConfiguration.NAME,
- ConfigurationParameters.of(ProtectedItemImporter.PARAM_IMPORT_BEHAVIOR, importBehaviorName))
- ).build();
+ ConfigurationParameters.of(ProtectedItemImporter.PARAM_IMPORT_BEHAVIOR, importBehaviorName)))
+ .build();
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/SetPropertiesTest.java b/src/test/java/org/apache/sling/jcr/repoinit/SetPropertiesTest.java
index 7893109..c3cc47a 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/SetPropertiesTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/SetPropertiesTest.java
@@ -1,29 +1,23 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.io.IOException;
-import java.util.UUID;
-
import javax.jcr.Node;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
@@ -32,6 +26,9 @@ import javax.jcr.ValueFactory;
import javax.jcr.nodetype.NoSuchNodeTypeException;
import javax.jcr.nodetype.NodeType;
+import java.io.IOException;
+import java.util.UUID;
+
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.util.Text;
import org.apache.sling.jcr.repoinit.impl.TestUtil;
@@ -44,12 +41,17 @@ import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
/** Test the setting of properties on nodes */
public class SetPropertiesTest {
-
+
@Rule
public final SlingContext context = new SlingContext(ResourceResolverType.JCR_OAK);
-
+
private TestUtil U;
private ValueFactory vf;
private static final String pathPrefix = "/one/two/";
@@ -62,7 +64,7 @@ public class SetPropertiesTest {
public void setup() throws RepositoryException, IOException, RepoInitParsingException {
U = new TestUtil(context);
vf = U.adminSession.getValueFactory();
- for(String p : new String[] { path1, path2, path3, path4 }) {
+ for (String p : new String[] {path1, path2, path3, path4}) {
U.parseAndExecute("create path " + p);
U.assertNodeExists(p);
}
@@ -77,16 +79,14 @@ public class SetPropertiesTest {
@Test
public void setMultiplePropertiesTest() throws Exception {
- final String setProps =
- "set properties on " + path2 + "\n"
- + "set sling:ResourceType{String} to /x/y/z \n"
- + "set allowedTemplates to /d/e/f/*, m/n/* \n"
- + "set someInteger{Long} to 42 \n"
- + "set someFlag{Boolean} to true \n"
- + "set someDate{Date} to \"2020-03-19T11:39:33.437+05:30\" \n"
- + "set customSingleValueQuotedStringProp to \"hello, you!\" \n"
- + "end"
- ;
+ final String setProps = "set properties on " + path2 + "\n"
+ + "set sling:ResourceType{String} to /x/y/z \n"
+ + "set allowedTemplates to /d/e/f/*, m/n/* \n"
+ + "set someInteger{Long} to 42 \n"
+ + "set someFlag{Boolean} to true \n"
+ + "set someDate{Date} to \"2020-03-19T11:39:33.437+05:30\" \n"
+ + "set customSingleValueQuotedStringProp to \"hello, you!\" \n"
+ + "end";
U.parseAndExecute(setProps);
Value expectedValue1 = vf.createValue("/x/y/z");
U.assertSVPropertyExists(path2, "sling:ResourceType", expectedValue1);
@@ -106,33 +106,28 @@ public class SetPropertiesTest {
@Test
public void setPropertyOnNonExistentPathTest() throws Exception {
- String nonExistingPath = "/someNonExistingPath/A/B";
+ String nonExistingPath = "/someNonExistingPath/A/B";
try {
- U.parseAndExecute("set properties on " + nonExistingPath + " \n set sling:ResourceType{String} to /x/y/z \n end");
+ U.parseAndExecute(
+ "set properties on " + nonExistingPath + " \n set sling:ResourceType{String} to /x/y/z \n end");
Assert.fail();
} catch (RuntimeException e) {
- Assert.assertTrue("expected repository exception", e.getMessage().contains("Unable to set properties on path [" + nonExistingPath + "]:"));
+ Assert.assertTrue(
+ "expected repository exception",
+ e.getMessage().contains("Unable to set properties on path [" + nonExistingPath + "]:"));
}
}
@Test
public void setDefaultProperties() throws Exception {
final String setPropsA =
- "set properties on " + path3 + "\n"
- + "set one to oneA\n"
- + "default two to twoA\n"
- + "end"
- ;
+ "set properties on " + path3 + "\n" + "set one to oneA\n" + "default two to twoA\n" + "end";
U.parseAndExecute(setPropsA);
U.assertSVPropertyExists(path3, "one", vf.createValue("oneA"));
U.assertSVPropertyExists(path3, "two", vf.createValue("twoA"));
final String setPropsB =
- "set properties on " + path3 + "\n"
- + "set one to oneB\n"
- + "default two to twoB\n"
- + "end"
- ;
+ "set properties on " + path3 + "\n" + "set one to oneB\n" + "default two to twoB\n" + "end";
U.parseAndExecute(setPropsB);
U.assertSVPropertyExists(path3, "one", vf.createValue("oneB"));
@@ -189,15 +184,11 @@ public class SetPropertiesTest {
@Test
public void unknownAuthorizable() throws Exception {
- final String setProps =
- "set properties on authorizable(nonExistingUser)\n"
- + "set one to oneA\n"
- + "end"
- ;
+ final String setProps = "set properties on authorizable(nonExistingUser)\n" + "set one to oneA\n" + "end";
try {
U.parseAndExecute(setProps);
fail("Expecting execution to fail");
- } catch(RuntimeException asExpected) {
+ } catch (RuntimeException asExpected) {
// all good
}
}
@@ -209,30 +200,28 @@ public class SetPropertiesTest {
// The parser accepts any function name in paths,
// make sure we fail in the right way
- final String setProps =
- "set properties on UNauthorizable(" + userid + ")\n"
- + "set one to oneA\n"
- + "end"
- ;
+ final String setProps = "set properties on UNauthorizable(" + userid + ")\n" + "set one to oneA\n" + "end";
try {
U.parseAndExecute(setProps);
fail("Expecting execution to fail");
- } catch(RuntimeException asExpected) {
+ } catch (RuntimeException asExpected) {
// all good
}
}
-
+
@Test
public void noChangeOnSameProps() throws Exception {
String testRT = "/my/props/test";
- String repoinitStr = "set properties on " + path4 + " \n set sling:ResourceType{String} to "+testRT+" \n end";
+ String repoinitStr =
+ "set properties on " + path4 + " \n set sling:ResourceType{String} to " + testRT + " \n end";
boolean hasChanges = U.parseAndExecute(repoinitStr);
assertTrue("No changes first attempt - session should contain changes.", hasChanges);
hasChanges = U.parseAndExecute(repoinitStr);
- assertFalse("Returning changes on second execution with same values - session should NOT contain changes.", hasChanges);
+ assertFalse(
+ "Returning changes on second execution with same values - session should NOT contain changes.",
+ hasChanges);
Value expectedValue = vf.createValue(testRT);
U.assertSVPropertyExists(path4, "sling:ResourceType", expectedValue);
-
}
/**
@@ -271,37 +260,28 @@ public class SetPropertiesTest {
// verify the initial autocreated property values
U.assertSVPropertyExists(testPath, "slingtest:singleVal", vf.createValue("autocreated value"));
U.assertMVPropertyExists(testPath, "multiVal", new Value[] {
- vf.createValue("autocreated value1"),
- vf.createValue("autocreated value2")
+ vf.createValue("autocreated value1"), vf.createValue("autocreated value2")
});
// setting "default" the first time should change the value as the value is now
// the same as the autocreated default values
- final String setPropsA =
- "set properties on " + testPath + "\n" +
- "default slingtest:singleVal to sChanged1a\n" +
- "default multiVal to mChanged1a, mChanged2a\n" +
- "end";
+ final String setPropsA = "set properties on " + testPath + "\n" + "default slingtest:singleVal to sChanged1a\n"
+ + "default multiVal to mChanged1a, mChanged2a\n"
+ + "end";
U.parseAndExecute(setPropsA);
U.assertSVPropertyExists(testPath, "slingtest:singleVal", vf.createValue("sChanged1a"));
- U.assertMVPropertyExists(testPath, "multiVal", new Value[] {
- vf.createValue("mChanged1a"),
- vf.createValue("mChanged2a")
- });
+ U.assertMVPropertyExists(
+ testPath, "multiVal", new Value[] {vf.createValue("mChanged1a"), vf.createValue("mChanged2a")});
// setting again should do nothing as the value is now
// not the same as the autocreated default values
- final String setPropsB =
- "set properties on " + testPath + "\n" +
- "default slingtest:singleVal to sChanged1b\n" +
- "default multiVal to mChanged1b, mChanged2b\n" +
- "end";
+ final String setPropsB = "set properties on " + testPath + "\n" + "default slingtest:singleVal to sChanged1b\n"
+ + "default multiVal to mChanged1b, mChanged2b\n"
+ + "end";
U.parseAndExecute(setPropsB);
U.assertSVPropertyExists(testPath, "slingtest:singleVal", vf.createValue("sChanged1a"));
- U.assertMVPropertyExists(testPath, "multiVal", new Value[] {
- vf.createValue("mChanged1a"),
- vf.createValue("mChanged2a")
- });
+ U.assertMVPropertyExists(
+ testPath, "multiVal", new Value[] {vf.createValue("mChanged1a"), vf.createValue("mChanged2a")});
}
/**
@@ -322,69 +302,60 @@ public class SetPropertiesTest {
// create the test node
String name = UUID.randomUUID().toString();
- U.getAdminSession()
- .getNode(a.getPath())
- .addNode(name, "slingtest:sling11293");
+ U.getAdminSession().getNode(a.getPath()).addNode(name, "slingtest:sling11293");
String testPath = a.getPath() + "/" + name;
U.assertNodeExists(testPath);
// verify the initial autocreated property values
U.assertSVPropertyExists(testPath, "slingtest:singleVal", vf.createValue("autocreated value"));
U.assertMVPropertyExists(testPath, "multiVal", new Value[] {
- vf.createValue("autocreated value1"),
- vf.createValue("autocreated value2")
+ vf.createValue("autocreated value1"), vf.createValue("autocreated value2")
});
// setting "default" the first time should change the value as the value is now
// the same as the autocreated default values
- final String setPropsA =
- "set properties on authorizable(" + userid + ")/" + name + "\n" +
- "default slingtest:singleVal to sChanged1a\n" +
- "default multiVal to mChanged1a, mChanged2a\n" +
- "end";
+ final String setPropsA = "set properties on authorizable(" + userid + ")/" + name + "\n"
+ + "default slingtest:singleVal to sChanged1a\n"
+ + "default multiVal to mChanged1a, mChanged2a\n"
+ + "end";
U.parseAndExecute(setPropsA);
U.assertAuthorizableSVPropertyExists(userid, name + "/slingtest:singleVal", vf.createValue("sChanged1a"));
- U.assertAuthorizableMVPropertyExists(userid, name + "/multiVal", new Value[] {
- vf.createValue("mChanged1a"),
- vf.createValue("mChanged2a")
- });
+ U.assertAuthorizableMVPropertyExists(
+ userid, name + "/multiVal", new Value[] {vf.createValue("mChanged1a"), vf.createValue("mChanged2a")});
// setting again should do nothing as the value is now
// not the same as the autocreated default values
- final String setPropsB =
- "set properties on authorizable(" + userid + ")/" + name + "\n" +
- "default slingtest:singleVal to sChanged1b\n" +
- "default multiVal to mChanged1b, mChanged2b\n" +
- "end";
+ final String setPropsB = "set properties on authorizable(" + userid + ")/" + name + "\n"
+ + "default slingtest:singleVal to sChanged1b\n"
+ + "default multiVal to mChanged1b, mChanged2b\n"
+ + "end";
U.parseAndExecute(setPropsB);
U.assertAuthorizableSVPropertyExists(userid, name + "/slingtest:singleVal", vf.createValue("sChanged1a"));
- U.assertAuthorizableMVPropertyExists(userid, name + "/multiVal", new Value[] {
- vf.createValue("mChanged1a"),
- vf.createValue("mChanged2a")
- });
+ U.assertAuthorizableMVPropertyExists(
+ userid, name + "/multiVal", new Value[] {vf.createValue("mChanged1a"), vf.createValue("mChanged2a")});
}
protected void registerSling11293NodeType()
throws RepositoryException, RepoInitParsingException, NoSuchNodeTypeException {
- final String registerNodeTypes =
- "register nodetypes\n" +
- "<<===\n" +
- "<< <slingtest='http://sling.apache.org/ns/test/repoinit-it/v1.0'>\n" +
- "<< [slingtest:sling11293] > nt:unstructured\n" +
- "<< - slingtest:singleVal (String) = 'autocreated value'\n" +
- "<< autocreated\n" +
- "<< - multiVal (String) = 'autocreated value1', 'autocreated value2'\n" +
- "<< multiple autocreated\n" +
- "<< [slingtest:sling11293mixin]\n" +
- "<< mixin\n" +
- "<< - slingtest:singleVal (String) = 'autocreated value'\n" +
- "<< autocreated\n" +
- "<< - multiVal (String) = 'autocreated value1', 'autocreated value2'\n" +
- "<< multiple autocreated\n" +
- "===>>";
+ final String registerNodeTypes = "register nodetypes\n" + "<<===\n"
+ + "<< <slingtest='http://sling.apache.org/ns/test/repoinit-it/v1.0'>\n"
+ + "<< [slingtest:sling11293] > nt:unstructured\n"
+ + "<< - slingtest:singleVal (String) = 'autocreated value'\n"
+ + "<< autocreated\n"
+ + "<< - multiVal (String) = 'autocreated value1', 'autocreated value2'\n"
+ + "<< multiple autocreated\n"
+ + "<< [slingtest:sling11293mixin]\n"
+ + "<< mixin\n"
+ + "<< - slingtest:singleVal (String) = 'autocreated value'\n"
+ + "<< autocreated\n"
+ + "<< - multiVal (String) = 'autocreated value1', 'autocreated value2'\n"
+ + "<< multiple autocreated\n"
+ + "===>>";
U.parseAndExecute(registerNodeTypes);
- NodeType nodeType = U.getAdminSession().getWorkspace().getNodeTypeManager().getNodeType("slingtest:sling11293");
+ NodeType nodeType =
+ U.getAdminSession().getWorkspace().getNodeTypeManager().getNodeType("slingtest:sling11293");
assertNotNull(nodeType);
- NodeType mixinType = U.getAdminSession().getWorkspace().getNodeTypeManager().getNodeType("slingtest:sling11293mixin");
+ NodeType mixinType =
+ U.getAdminSession().getWorkspace().getNodeTypeManager().getNodeType("slingtest:sling11293mixin");
assertNotNull(mixinType);
}
@@ -392,17 +363,16 @@ public class SetPropertiesTest {
* Set properties on an authorizable and then verify that the values were set
*/
protected void assertAuthorizableProperties(String id) throws RepositoryException, RepoInitParsingException {
- final String setPropsA =
- "set properties on authorizable(" +id + ")\n"
- + "set one to oneA\n"
- + "set dbl{Double} to 3.14\n"
- + "default two to twoA\n"
- + "set nested/one to oneA\n"
- + "default nested/two to twoA\n"
- + "set three to threeA, \"threeB\", threeC\n"
- + "default four to fourA, \"fourB\"\n"
- + "set nested/three to threeA, \"threeB\", threeC\n"
- + "default nested/four to fourA, \"fourB\"\n"
+ final String setPropsA = "set properties on authorizable(" + id + ")\n"
+ + "set one to oneA\n"
+ + "set dbl{Double} to 3.14\n"
+ + "default two to twoA\n"
+ + "set nested/one to oneA\n"
+ + "default nested/two to twoA\n"
+ + "set three to threeA, \"threeB\", threeC\n"
+ + "default four to fourA, \"fourB\"\n"
+ + "set nested/three to threeA, \"threeB\", threeC\n"
+ + "default nested/four to fourA, \"fourB\"\n"
+ "end";
U.parseAndExecute(setPropsA);
@@ -412,24 +382,16 @@ public class SetPropertiesTest {
U.assertAuthorizableSVPropertyExists(id, "nested/one", vf.createValue("oneA"));
U.assertAuthorizableSVPropertyExists(id, "two", vf.createValue("twoA"));
U.assertAuthorizableSVPropertyExists(id, "nested/two", vf.createValue("twoA"));
- U.assertAuthorizableMVPropertyExists(id, "three", new Value[] {
- vf.createValue("threeA"),
- vf.createValue("threeB"),
- vf.createValue("threeC")
+ U.assertAuthorizableMVPropertyExists(
+ id, "three", new Value[] {vf.createValue("threeA"), vf.createValue("threeB"), vf.createValue("threeC")
});
U.assertAuthorizableMVPropertyExists(id, "nested/three", new Value[] {
- vf.createValue("threeA"),
- vf.createValue("threeB"),
- vf.createValue("threeC")
- });
- U.assertAuthorizableMVPropertyExists(id, "four", new Value[] {
- vf.createValue("fourA"),
- vf.createValue("fourB")
- });
- U.assertAuthorizableMVPropertyExists(id, "nested/four", new Value[] {
- vf.createValue("fourA"),
- vf.createValue("fourB")
- });
+ vf.createValue("threeA"), vf.createValue("threeB"), vf.createValue("threeC")
+ });
+ U.assertAuthorizableMVPropertyExists(
+ id, "four", new Value[] {vf.createValue("fourA"), vf.createValue("fourB")});
+ U.assertAuthorizableMVPropertyExists(
+ id, "nested/four", new Value[] {vf.createValue("fourA"), vf.createValue("fourB")});
}
/**
@@ -437,16 +399,15 @@ public class SetPropertiesTest {
* or not as appropriate
*/
protected void assertAuthorizablePropertiesAgain(String id) throws RepositoryException, RepoInitParsingException {
- final String setPropsA =
- "set properties on authorizable(" + id + ")\n"
- + "set one to changed_oneA\n"
- + "default two to changed_twoA\n"
- + "set nested/one to changed_oneA\n"
- + "default nested/two to changed_twoA\n"
- + "set three to changed_threeA, \"changed_threeB\", changed_threeC\n"
- + "default four to changed_fourA, \"changed_fourB\"\n"
- + "set nested/three to changed_threeA, \"changed_threeB\", changed_threeC\n"
- + "default nested/four to changed_fourA, \"changed_fourB\"\n"
+ final String setPropsA = "set properties on authorizable(" + id + ")\n"
+ + "set one to changed_oneA\n"
+ + "default two to changed_twoA\n"
+ + "set nested/one to changed_oneA\n"
+ + "default nested/two to changed_twoA\n"
+ + "set three to changed_threeA, \"changed_threeB\", changed_threeC\n"
+ + "default four to changed_fourA, \"changed_fourB\"\n"
+ + "set nested/three to changed_threeA, \"changed_threeB\", changed_threeC\n"
+ + "default nested/four to changed_fourA, \"changed_fourB\"\n"
+ "end";
U.parseAndExecute(setPropsA);
@@ -456,34 +417,24 @@ public class SetPropertiesTest {
U.assertAuthorizableSVPropertyExists(id, "two", vf.createValue("twoA"));
U.assertAuthorizableSVPropertyExists(id, "nested/two", vf.createValue("twoA"));
U.assertAuthorizableMVPropertyExists(id, "three", new Value[] {
- vf.createValue("changed_threeA"),
- vf.createValue("changed_threeB"),
- vf.createValue("changed_threeC")
- });
+ vf.createValue("changed_threeA"), vf.createValue("changed_threeB"), vf.createValue("changed_threeC")
+ });
U.assertAuthorizableMVPropertyExists(id, "nested/three", new Value[] {
- vf.createValue("changed_threeA"),
- vf.createValue("changed_threeB"),
- vf.createValue("changed_threeC")
- });
- U.assertAuthorizableMVPropertyExists(id, "four", new Value[] {
- vf.createValue("fourA"),
- vf.createValue("fourB")
- });
- U.assertAuthorizableMVPropertyExists(id, "nested/four", new Value[] {
- vf.createValue("fourA"),
- vf.createValue("fourB")
- });
+ vf.createValue("changed_threeA"), vf.createValue("changed_threeB"), vf.createValue("changed_threeC")
+ });
+ U.assertAuthorizableMVPropertyExists(
+ id, "four", new Value[] {vf.createValue("fourA"), vf.createValue("fourB")});
+ U.assertAuthorizableMVPropertyExists(
+ id, "nested/four", new Value[] {vf.createValue("fourA"), vf.createValue("fourB")});
}
/**
* Set properties on a subtree of an authorizable and then verify that the values were set
*/
- protected void assertAuthorizableSubTreeProperties(String id)
- throws RepositoryException, RepoInitParsingException {
- final String setPropsA =
- "set properties on authorizable(" + id + ")/nested\n"
- + "set one to oneA\n"
- + "default two to twoA\n"
+ protected void assertAuthorizableSubTreeProperties(String id) throws RepositoryException, RepoInitParsingException {
+ final String setPropsA = "set properties on authorizable(" + id + ")/nested\n"
+ + "set one to oneA\n"
+ + "default two to twoA\n"
+ "end";
U.parseAndExecute(setPropsA);
@@ -493,15 +444,14 @@ public class SetPropertiesTest {
}
/**
- * Change values for existing properties on a subtree of an authorizable and then verify
+ * Change values for existing properties on a subtree of an authorizable and then verify
* that the values were set or not as appropriate
*/
protected void assertAuthorizableSubTreePropertiesAgain(String id)
throws RepositoryException, RepoInitParsingException {
- final String setPropsA =
- "set properties on authorizable(" + id + ")/nested\n"
- + "set one to changed_oneA\n"
- + "default two to changed_twoA\n"
+ final String setPropsA = "set properties on authorizable(" + id + ")/nested\n"
+ + "set one to changed_oneA\n"
+ + "default two to changed_twoA\n"
+ "end";
U.parseAndExecute(setPropsA);
@@ -509,5 +459,4 @@ public class SetPropertiesTest {
U.assertAuthorizableSVPropertyExists(id, "nested/one", vf.createValue("changed_oneA"));
U.assertAuthorizableSVPropertyExists(id, "nested/two", vf.createValue("twoA"));
}
-
}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/impl/AclUtilTest.java b/src/test/java/org/apache/sling/jcr/repoinit/impl/AclUtilTest.java
index 2182547..ff04c18 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/impl/AclUtilTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/impl/AclUtilTest.java
@@ -1,32 +1,23 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
-
-import java.security.Principal;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
import javax.jcr.AccessDeniedException;
import javax.jcr.PathNotFoundException;
import javax.jcr.PropertyType;
@@ -37,6 +28,11 @@ import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.jcr.security.Privilege;
+import java.security.Principal;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.JackrabbitAccessControlList;
import org.apache.jackrabbit.api.security.user.AuthorizableExistsException;
@@ -47,7 +43,6 @@ import org.apache.jackrabbit.oak.commons.PathUtils;
import org.apache.jackrabbit.oak.spi.security.principal.EveryonePrincipal;
import org.apache.jackrabbit.oak.spi.security.principal.PrincipalImpl;
import org.apache.sling.repoinit.parser.RepoInitParsingException;
-import org.apache.sling.repoinit.parser.operations.RestrictionClause;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.apache.sling.testing.mock.sling.junit.SlingContext;
import org.junit.After;
@@ -58,27 +53,29 @@ import org.junit.Test;
import org.junit.function.ThrowingRunnable;
import org.junit.jupiter.api.Assertions;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
public class AclUtilTest {
@Rule
public final SlingContext context = new SlingContext(ResourceResolverType.JCR_OAK);
-
+
private TestUtil U;
private JackrabbitAccessControlList acl;
-
+
@Before
public void setup() throws RepositoryException, RepoInitParsingException {
U = new TestUtil(context);
U.parseAndExecute("create service user " + U.username);
-
- final String aclSetup =
- "set ACL for " + U.username + "\n"
- + "allow jcr:read on /\n"
- + "allow jcr:write on /\n"
- + "end"
- ;
-
+
+ final String aclSetup =
+ "set ACL for " + U.username + "\n" + "allow jcr:read on /\n" + "allow jcr:write on /\n" + "end";
+
U.parseAndExecute(aclSetup);
acl = AccessControlUtils.getAccessControlList(U.adminSession, "/");
}
@@ -93,59 +90,66 @@ public class AclUtilTest {
@Test
public void entryIsContained() throws Exception {
-
+
// validates that an exact match of the username, privilege list and isAllow is contained
-
- assertIsContained(acl, U.username, new String[]{ Privilege.JCR_READ, Privilege.JCR_WRITE }, true);
+
+ assertIsContained(acl, U.username, new String[] {Privilege.JCR_READ, Privilege.JCR_WRITE}, true);
}
@Test
public void testDeclaredAggregatePrivilegesAreContained() throws Exception {
- String [] privileges = new String[]{
- //JCR_READ
- "rep:readNodes","rep:readProperties",
- // JCR_WRITE
- Privilege.JCR_ADD_CHILD_NODES,Privilege.JCR_MODIFY_PROPERTIES,
- Privilege.JCR_REMOVE_CHILD_NODES, Privilege.JCR_REMOVE_NODE
+ String[] privileges = new String[] {
+ // JCR_READ
+ "rep:readNodes",
+ "rep:readProperties",
+ // JCR_WRITE
+ Privilege.JCR_ADD_CHILD_NODES,
+ Privilege.JCR_MODIFY_PROPERTIES,
+ Privilege.JCR_REMOVE_CHILD_NODES,
+ Privilege.JCR_REMOVE_NODE
};
assertIsContained(acl, U.username, privileges, true);
}
@Test
public void testAllAggregatePrivilegesAreContained() throws Exception {
- String [] privileges = new String[]{
- //JCR_READ
- "rep:readNodes","rep:readProperties",
- // JCR_WRITE
- Privilege.JCR_ADD_CHILD_NODES,"rep:addProperties",
- "rep:alterProperties","rep:removeProperties",
- Privilege.JCR_REMOVE_CHILD_NODES, Privilege.JCR_REMOVE_NODE
+ String[] privileges = new String[] {
+ // JCR_READ
+ "rep:readNodes",
+ "rep:readProperties",
+ // JCR_WRITE
+ Privilege.JCR_ADD_CHILD_NODES,
+ "rep:addProperties",
+ "rep:alterProperties",
+ "rep:removeProperties",
+ Privilege.JCR_REMOVE_CHILD_NODES,
+ Privilege.JCR_REMOVE_NODE
};
assertIsContained(acl, U.username, privileges, true);
}
-
@Test
public void entryWithFewerPrivilegesIsContained() throws Exception {
-
+
// validates that an exact match of the username and isAllow but with fewer privileges is contained
- assertIsContained(acl, U.username, new String[]{ Privilege.JCR_WRITE }, true);
+ assertIsContained(acl, U.username, new String[] {Privilege.JCR_WRITE}, true);
}
@Test
public void entryWithDifferentPrivilegeIsNotContained() throws Exception {
// validates that an exact match of the username and isAllow but with different privileges is contained
- assertIsNotContained(acl, U.username, new String[]{ Privilege.JCR_ALL }, true);
+ assertIsNotContained(acl, U.username, new String[] {Privilege.JCR_ALL}, true);
}
-
+
@Test
public void entryWithPartiallyMatchingPrivilegesIsContained() throws Exception {
- // validates that an exact match of the username and isAllow but with privileges partially overlapping is contained
- // existing: JCR_READ, JCR_WRITE
+ // validates that an exact match of the username and isAllow but with privileges partially overlapping is
+ // contained
+ // existing: JCR_READ, JCR_WRITE
// new: JCR_READ, JCR_MODIFY_PROPERTIES
- assertIsContained(acl, U.username, new String[]{Privilege.JCR_READ, Privilege.JCR_MODIFY_PROPERTIES }, true);
- }
-
+ assertIsContained(acl, U.username, new String[] {Privilege.JCR_READ, Privilege.JCR_MODIFY_PROPERTIES}, true);
+ }
+
@Test
public void entryWithDifferentUserIsNotContained() throws Exception {
@@ -153,18 +157,18 @@ public class AclUtilTest {
String otherPrincipalName = U.username + "_";
try {
U.parseAndExecute("create service user " + otherPrincipalName);
- assertIsNotContained(acl, otherPrincipalName, new String[]{ Privilege.JCR_READ, Privilege.JCR_WRITE }, true);
+ assertIsNotContained(acl, otherPrincipalName, new String[] {Privilege.JCR_READ, Privilege.JCR_WRITE}, true);
} finally {
U.cleanupServiceUser(otherPrincipalName);
}
}
-
+
@Test
public void entryWithDifferentIsAllowIsNotContained() throws Exception {
// validates that an exact match of the username and privileges but with different is allow is not contained
- assertIsNotContained(acl, U.username, new String[]{ Privilege.JCR_READ, Privilege.JCR_WRITE }, false);
+ assertIsNotContained(acl, U.username, new String[] {Privilege.JCR_READ, Privilege.JCR_WRITE}, false);
}
-
+
private void assertArrayCompare(Value[] a, Value[] b, boolean expected) {
final boolean actual = AclUtil.compareValues(a, b);
assertEquals("Expecting compareArrays to return " + expected, actual, expected);
@@ -172,18 +176,36 @@ public class AclUtilTest {
@Test
public void compareValuesTest() throws RepositoryException {
- ValueFactory vf = U.adminSession.getValueFactory();
- final Value[] a1 = new Value[] {vf.createValue("jcr:content", PropertyType.NAME), vf.createValue("jcr:data", PropertyType.NAME)};
- final Value[] a2 = new Value[] {vf.createValue("a", PropertyType.STRING), vf.createValue("b", PropertyType.STRING)};
- final Value[] a3 = new Value[] {vf.createValue("b", PropertyType.STRING), vf.createValue("c", PropertyType.STRING)};
-
- final Value[] a4 = new Value[] {vf.createValue("a", PropertyType.STRING), vf.createValue("b", PropertyType.STRING), vf.createValue("c", PropertyType.STRING)};
-
- final Value[] a5 = new Value[] {vf.createValue("b", PropertyType.STRING), vf.createValue("a", PropertyType.STRING)};
- final Value[] a6 = new Value[] {vf.createValue("b", PropertyType.STRING), vf.createValue("a", PropertyType.STRING), vf.createValue("c", PropertyType.STRING)};
- final Value[] a7 = new Value[] {vf.createValue("a", PropertyType.STRING), vf.createValue("b", PropertyType.STRING)};
- final Value[] a8 = new Value[] {vf.createValue("jcr:data", PropertyType.NAME), vf.createValue("jcr:content", PropertyType.NAME)};
- final Value[] a9 = new Value[] {vf.createValue("jcr:data", PropertyType.NAME), vf.createValue("jcr:content", PropertyType.STRING)};
+ ValueFactory vf = U.adminSession.getValueFactory();
+ final Value[] a1 = new Value[] {
+ vf.createValue("jcr:content", PropertyType.NAME), vf.createValue("jcr:data", PropertyType.NAME)
+ };
+ final Value[] a2 =
+ new Value[] {vf.createValue("a", PropertyType.STRING), vf.createValue("b", PropertyType.STRING)};
+ final Value[] a3 =
+ new Value[] {vf.createValue("b", PropertyType.STRING), vf.createValue("c", PropertyType.STRING)};
+
+ final Value[] a4 = new Value[] {
+ vf.createValue("a", PropertyType.STRING),
+ vf.createValue("b", PropertyType.STRING),
+ vf.createValue("c", PropertyType.STRING)
+ };
+
+ final Value[] a5 =
+ new Value[] {vf.createValue("b", PropertyType.STRING), vf.createValue("a", PropertyType.STRING)};
+ final Value[] a6 = new Value[] {
+ vf.createValue("b", PropertyType.STRING),
+ vf.createValue("a", PropertyType.STRING),
+ vf.createValue("c", PropertyType.STRING)
+ };
+ final Value[] a7 =
+ new Value[] {vf.createValue("a", PropertyType.STRING), vf.createValue("b", PropertyType.STRING)};
+ final Value[] a8 = new Value[] {
+ vf.createValue("jcr:data", PropertyType.NAME), vf.createValue("jcr:content", PropertyType.NAME)
+ };
+ final Value[] a9 = new Value[] {
+ vf.createValue("jcr:data", PropertyType.NAME), vf.createValue("jcr:content", PropertyType.STRING)
+ };
final Value[] emptyA = {};
final Value[] emptyB = {};
@@ -217,12 +239,21 @@ public class AclUtilTest {
public void testSetAclForEveryone() throws Exception {
Session session = U.adminSession;
try {
- assertTrue(session instanceof JackrabbitSession);
- assertNull(((JackrabbitSession) session).getUserManager().getAuthorizable(EveryonePrincipal.getInstance()));
+ assertTrue(session instanceof JackrabbitSession);
+ assertNull(((JackrabbitSession) session).getUserManager().getAuthorizable(EveryonePrincipal.getInstance()));
- AclUtil.setAcl(session, Collections.singletonList(EveryonePrincipal.NAME), Collections.singletonList(PathUtils.ROOT_PATH), Collections.singletonList(Privilege.JCR_READ), false);
+ AclUtil.setAcl(
+ session,
+ Collections.singletonList(EveryonePrincipal.NAME),
+ Collections.singletonList(PathUtils.ROOT_PATH),
+ Collections.singletonList(Privilege.JCR_READ),
+ false);
- assertIsContained(AccessControlUtils.getAccessControlList(session, PathUtils.ROOT_PATH), EveryonePrincipal.NAME, new String[] {Privilege.JCR_READ}, false);
+ assertIsContained(
+ AccessControlUtils.getAccessControlList(session, PathUtils.ROOT_PATH),
+ EveryonePrincipal.NAME,
+ new String[] {Privilege.JCR_READ},
+ false);
} finally {
session.refresh(false);
}
@@ -241,9 +272,18 @@ public class AclUtilTest {
uMgr.createUser(U.username, null, principal, null);
U.adminSession.save();
- AclUtil.setAcl(U.adminSession, Collections.singletonList(principal.getName()), Collections.singletonList(PathUtils.ROOT_PATH), Collections.singletonList(Privilege.JCR_READ), false);
+ AclUtil.setAcl(
+ U.adminSession,
+ Collections.singletonList(principal.getName()),
+ Collections.singletonList(PathUtils.ROOT_PATH),
+ Collections.singletonList(Privilege.JCR_READ),
+ false);
- assertIsContained(AccessControlUtils.getAccessControlList(U.adminSession, PathUtils.ROOT_PATH), principal.getName(), new String[] {Privilege.JCR_READ}, false);
+ assertIsContained(
+ AccessControlUtils.getAccessControlList(U.adminSession, PathUtils.ROOT_PATH),
+ principal.getName(),
+ new String[] {Privilege.JCR_READ},
+ false);
} finally {
U.adminSession.refresh(false);
}
@@ -266,12 +306,25 @@ public class AclUtilTest {
uMgr.createUser(U.username, null, principal, null);
U.adminSession.save();
- AclUtil.setAcl(U.adminSession, Collections.singletonList(U.username), Collections.singletonList(PathUtils.ROOT_PATH), Collections.singletonList(Privilege.JCR_READ), false);
+ AclUtil.setAcl(
+ U.adminSession,
+ Collections.singletonList(U.username),
+ Collections.singletonList(PathUtils.ROOT_PATH),
+ Collections.singletonList(Privilege.JCR_READ),
+ false);
// assert that the entries is created for the principal name (and not the identifier)
- assertIsContained(AccessControlUtils.getAccessControlList(U.adminSession, PathUtils.ROOT_PATH), principal.getName(), new String[] {Privilege.JCR_READ}, false);
+ assertIsContained(
+ AccessControlUtils.getAccessControlList(U.adminSession, PathUtils.ROOT_PATH),
+ principal.getName(),
+ new String[] {Privilege.JCR_READ},
+ false);
// assert no entry has been created for the identifier (which cannot be resolved to a principal)
- assertIsNotContained(AccessControlUtils.getAccessControlList(U.adminSession, PathUtils.ROOT_PATH), U.username, new String[] {Privilege.JCR_READ}, false);
+ assertIsNotContained(
+ AccessControlUtils.getAccessControlList(U.adminSession, PathUtils.ROOT_PATH),
+ U.username,
+ new String[] {Privilege.JCR_READ},
+ false);
} finally {
U.adminSession.refresh(false);
}
@@ -281,28 +334,62 @@ public class AclUtilTest {
public void testSetAclWithHomePath() throws Exception {
UserManager uMgr = ((JackrabbitSession) U.adminSession).getUserManager();
String userHomePath = uMgr.getAuthorizable(U.username).getPath();
- assertIsNotContained(AccessControlUtils.getAccessControlList(U.adminSession, userHomePath), U.username, new String[] {Privilege.JCR_READ}, true);
-
- List<String> paths = Collections.singletonList(":home:"+U.username+"#");
- AclUtil.setAcl(U.adminSession, Collections.singletonList(U.username), paths, Collections.singletonList(Privilege.JCR_READ), true);
- assertIsContained(AccessControlUtils.getAccessControlList(U.adminSession, userHomePath), U.username, new String[] {Privilege.JCR_READ}, true);
+ assertIsNotContained(
+ AccessControlUtils.getAccessControlList(U.adminSession, userHomePath),
+ U.username,
+ new String[] {Privilege.JCR_READ},
+ true);
+
+ List<String> paths = Collections.singletonList(":home:" + U.username + "#");
+ AclUtil.setAcl(
+ U.adminSession,
+ Collections.singletonList(U.username),
+ paths,
+ Collections.singletonList(Privilege.JCR_READ),
+ true);
+ assertIsContained(
+ AccessControlUtils.getAccessControlList(U.adminSession, userHomePath),
+ U.username,
+ new String[] {Privilege.JCR_READ},
+ true);
}
@Test
public void testSetAclWithHomePathMultipleIds() throws Exception {
UserManager uMgr = ((JackrabbitSession) U.adminSession).getUserManager();
String userHomePath = uMgr.getAuthorizable(U.username).getPath();
- assertIsNotContained(AccessControlUtils.getAccessControlList(U.adminSession, userHomePath), U.username, new String[] {Privilege.JCR_READ}, true);
+ assertIsNotContained(
+ AccessControlUtils.getAccessControlList(U.adminSession, userHomePath),
+ U.username,
+ new String[] {Privilege.JCR_READ},
+ true);
Group gr = uMgr.createGroup("groupId");
String groupHomePath = gr.getPath();
- assertIsNotContained(AccessControlUtils.getAccessControlList(U.adminSession, groupHomePath), U.username, new String[] {Privilege.JCR_READ}, true);
-
- List<String> paths = Collections.singletonList(":home:"+U.username+","+gr.getID()+"#");
- AclUtil.setAcl(U.adminSession, Collections.singletonList(U.username), paths, Collections.singletonList(Privilege.JCR_READ), true);
-
- assertIsContained(AccessControlUtils.getAccessControlList(U.adminSession, userHomePath), U.username, new String[] {Privilege.JCR_READ}, true);
- assertIsContained(AccessControlUtils.getAccessControlList(U.adminSession, groupHomePath), U.username, new String[] {Privilege.JCR_READ}, true);
+ assertIsNotContained(
+ AccessControlUtils.getAccessControlList(U.adminSession, groupHomePath),
+ U.username,
+ new String[] {Privilege.JCR_READ},
+ true);
+
+ List<String> paths = Collections.singletonList(":home:" + U.username + "," + gr.getID() + "#");
+ AclUtil.setAcl(
+ U.adminSession,
+ Collections.singletonList(U.username),
+ paths,
+ Collections.singletonList(Privilege.JCR_READ),
+ true);
+
+ assertIsContained(
+ AccessControlUtils.getAccessControlList(U.adminSession, userHomePath),
+ U.username,
+ new String[] {Privilege.JCR_READ},
+ true);
+ assertIsContained(
+ AccessControlUtils.getAccessControlList(U.adminSession, groupHomePath),
+ U.username,
+ new String[] {Privilege.JCR_READ},
+ true);
}
@Test
@@ -311,28 +398,74 @@ public class AclUtilTest {
String userHomePath = uMgr.getAuthorizable(U.username).getPath();
List<String> paths = Arrays.asList(":home:" + U.username + "#", ":repository", PathUtils.ROOT_PATH);
- AclUtil.setAcl(U.adminSession, Collections.singletonList(U.username), paths, Collections.singletonList(Privilege.JCR_ALL), true);
-
- assertIsContained(AccessControlUtils.getAccessControlList(U.adminSession, userHomePath), U.username, new String[] {Privilege.JCR_ALL}, true);
- assertIsContained(AccessControlUtils.getAccessControlList(U.adminSession, null), U.username, new String[] {Privilege.JCR_ALL}, true);
- assertIsContained(AccessControlUtils.getAccessControlList(U.adminSession, PathUtils.ROOT_PATH), U.username, new String[] {Privilege.JCR_ALL}, true);
+ AclUtil.setAcl(
+ U.adminSession,
+ Collections.singletonList(U.username),
+ paths,
+ Collections.singletonList(Privilege.JCR_ALL),
+ true);
+
+ assertIsContained(
+ AccessControlUtils.getAccessControlList(U.adminSession, userHomePath),
+ U.username,
+ new String[] {Privilege.JCR_ALL},
+ true);
+ assertIsContained(
+ AccessControlUtils.getAccessControlList(U.adminSession, null),
+ U.username,
+ new String[] {Privilege.JCR_ALL},
+ true);
+ assertIsContained(
+ AccessControlUtils.getAccessControlList(U.adminSession, PathUtils.ROOT_PATH),
+ U.username,
+ new String[] {Privilege.JCR_ALL},
+ true);
}
@Test
public void testSetAclWithHomePathAndSubtree() throws Exception {
UserManager uMgr = ((JackrabbitSession) U.adminSession).getUserManager();
- String userHomePath = U.adminSession.getNode(uMgr.getAuthorizable(U.username).getPath()).addNode("profiles").addNode("private").getPath();
- assertIsNotContained(AccessControlUtils.getAccessControlList(U.adminSession, userHomePath), U.username, new String[] {Privilege.JCR_READ}, true);
+ String userHomePath = U.adminSession
+ .getNode(uMgr.getAuthorizable(U.username).getPath())
+ .addNode("profiles")
+ .addNode("private")
+ .getPath();
+ assertIsNotContained(
+ AccessControlUtils.getAccessControlList(U.adminSession, userHomePath),
+ U.username,
+ new String[] {Privilege.JCR_READ},
+ true);
Group gr = uMgr.createGroup("groupId");
- String groupHomePath = U.adminSession.getNode(gr.getPath()).addNode("profiles").addNode("private").getPath();
- assertIsNotContained(AccessControlUtils.getAccessControlList(U.adminSession, groupHomePath), U.username, new String[] {Privilege.JCR_READ}, true);
-
- List<String> paths = Collections.singletonList(":home:"+U.username+","+gr.getID()+"#/profiles/private");
- AclUtil.setAcl(U.adminSession, Collections.singletonList(U.username), paths, Collections.singletonList(Privilege.JCR_READ), true);
-
- assertIsContained(AccessControlUtils.getAccessControlList(U.adminSession, userHomePath), U.username, new String[] {Privilege.JCR_READ}, true);
- assertIsContained(AccessControlUtils.getAccessControlList(U.adminSession, groupHomePath), U.username, new String[] {Privilege.JCR_READ}, true);
+ String groupHomePath = U.adminSession
+ .getNode(gr.getPath())
+ .addNode("profiles")
+ .addNode("private")
+ .getPath();
+ assertIsNotContained(
+ AccessControlUtils.getAccessControlList(U.adminSession, groupHomePath),
+ U.username,
+ new String[] {Privilege.JCR_READ},
+ true);
+
+ List<String> paths = Collections.singletonList(":home:" + U.username + "," + gr.getID() + "#/profiles/private");
+ AclUtil.setAcl(
+ U.adminSession,
+ Collections.singletonList(U.username),
+ paths,
+ Collections.singletonList(Privilege.JCR_READ),
+ true);
+
+ assertIsContained(
+ AccessControlUtils.getAccessControlList(U.adminSession, userHomePath),
+ U.username,
+ new String[] {Privilege.JCR_READ},
+ true);
+ assertIsContained(
+ AccessControlUtils.getAccessControlList(U.adminSession, groupHomePath),
+ U.username,
+ new String[] {Privilege.JCR_READ},
+ true);
}
@Test
@@ -340,30 +473,48 @@ public class AclUtilTest {
UserManager uMgr = ((JackrabbitSession) U.adminSession).getUserManager();
String userHomePath = uMgr.getAuthorizable(U.username).getPath() + "/profiles/private";
assertFalse(U.adminSession.nodeExists(userHomePath));
- assertThrows(PathNotFoundException.class, () -> AccessControlUtils.getAccessControlList(U.adminSession, userHomePath));
+ assertThrows(
+ PathNotFoundException.class,
+ () -> AccessControlUtils.getAccessControlList(U.adminSession, userHomePath));
Group gr = uMgr.createGroup("groupId");
String groupHomePath = U.adminSession.getNode(gr.getPath()).getPath() + "/profiles/private";
assertFalse(U.adminSession.nodeExists(groupHomePath));
- assertThrows(PathNotFoundException.class, () -> AccessControlUtils.getAccessControlList(U.adminSession, groupHomePath));
+ assertThrows(
+ PathNotFoundException.class,
+ () -> AccessControlUtils.getAccessControlList(U.adminSession, groupHomePath));
}
/**
* @param groupId the id of the group to create
*/
- protected void assertSetAclWithHomePath(String groupId) throws AccessDeniedException, UnsupportedRepositoryOperationException,
- RepositoryException, AuthorizableExistsException {
+ protected void assertSetAclWithHomePath(String groupId)
+ throws AccessDeniedException, UnsupportedRepositoryOperationException, RepositoryException,
+ AuthorizableExistsException {
UserManager uMgr = ((JackrabbitSession) U.adminSession).getUserManager();
Group gr = uMgr.createGroup(groupId);
String groupHomePath = gr.getPath();
- assertIsNotContained(AccessControlUtils.getAccessControlList(U.adminSession, groupHomePath), U.username, new String[] {Privilege.JCR_READ}, true);
-
- List<String> paths = Collections.singletonList(":home:"+gr.getID()+","+U.username+"#");
- AclUtil.setAcl(U.adminSession, Collections.singletonList(U.username), paths, Collections.singletonList(Privilege.JCR_READ), true);
+ assertIsNotContained(
+ AccessControlUtils.getAccessControlList(U.adminSession, groupHomePath),
+ U.username,
+ new String[] {Privilege.JCR_READ},
+ true);
+
+ List<String> paths = Collections.singletonList(":home:" + gr.getID() + "," + U.username + "#");
+ AclUtil.setAcl(
+ U.adminSession,
+ Collections.singletonList(U.username),
+ paths,
+ Collections.singletonList(Privilege.JCR_READ),
+ true);
- assertIsContained(AccessControlUtils.getAccessControlList(U.adminSession, groupHomePath), U.username, new String[] {Privilege.JCR_READ}, true);
+ assertIsContained(
+ AccessControlUtils.getAccessControlList(U.adminSession, groupHomePath),
+ U.username,
+ new String[] {Privilege.JCR_READ},
+ true);
}
@Test
@@ -384,14 +535,24 @@ public class AclUtilTest {
@Test(expected = IllegalStateException.class)
public void testSetAclWithHomePathMissingTrailingHash() throws Exception {
- List<String> paths = Collections.singletonList(":home:"+U.username);
- AclUtil.setAcl(U.adminSession, Collections.singletonList(U.username), paths, Collections.singletonList(Privilege.JCR_READ), true);
+ List<String> paths = Collections.singletonList(":home:" + U.username);
+ AclUtil.setAcl(
+ U.adminSession,
+ Collections.singletonList(U.username),
+ paths,
+ Collections.singletonList(Privilege.JCR_READ),
+ true);
}
@Test(expected = PathNotFoundException.class)
public void testSetAclWithHomePathUnknownUser() throws Exception {
List<String> paths = Collections.singletonList(":home:alice#");
- AclUtil.setAcl(U.adminSession, Collections.singletonList(U.username), paths, Collections.singletonList(Privilege.JCR_READ), true);
+ AclUtil.setAcl(
+ U.adminSession,
+ Collections.singletonList(U.username),
+ paths,
+ Collections.singletonList(Privilege.JCR_READ),
+ true);
}
@Test
@@ -402,8 +563,7 @@ public class AclUtilTest {
Collections.singletonList(U.username),
Arrays.asList(":home:" + U.username + "#", ":repository", PathUtils.ROOT_PATH),
Collections.singletonList(Privilege.JCR_ALL),
- true
- );
+ true);
setAcls.run();
Assertions.assertTrue(session.hasPendingChanges(), "Expected changes in the session");
@@ -418,33 +578,45 @@ public class AclUtilTest {
public void nullRestrictionClauseAndNullOptionsAreHandled() {
final Session session = U.adminSession;
Assertions.assertDoesNotThrow(() -> AclUtil.setAcl(
- session,
- Collections.singletonList(U.username),
- Collections.singletonList(PathUtils.ROOT_PATH),
- Collections.singletonList(Privilege.JCR_READ),
- true,
- null,
- null
- ));
+ session,
+ Collections.singletonList(U.username),
+ Collections.singletonList(PathUtils.ROOT_PATH),
+ Collections.singletonList(Privilege.JCR_READ),
+ true,
+ null,
+ null));
}
- private void assertIsContained(JackrabbitAccessControlList acl, String username, String[] privilegeNames, boolean isAllow) throws RepositoryException {
+ private void assertIsContained(
+ JackrabbitAccessControlList acl, String username, String[] privilegeNames, boolean isAllow)
+ throws RepositoryException {
assertIsContained0(acl, username, privilegeNames, isAllow, true);
}
-
- private void assertIsNotContained(JackrabbitAccessControlList acl, String username, String[] privilegeNames, boolean isAllow) throws RepositoryException {
+
+ private void assertIsNotContained(
+ JackrabbitAccessControlList acl, String username, String[] privilegeNames, boolean isAllow)
+ throws RepositoryException {
assertIsContained0(acl, username, privilegeNames, isAllow, false);
}
-
- private void assertIsContained0(JackrabbitAccessControlList acl, String username, String[] privilegeNames, boolean isAllow, boolean contained) throws RepositoryException {
- AclUtil.LocalAccessControlEntry localAce = new AclUtil.LocalAccessControlEntry(principal(username), privileges(privilegeNames), isAllow);
-
- if ( contained ) {
- assertTrue("ACL does not contain an entry for " + localAce, AclUtil.contains(acl.getAccessControlEntries(), localAce));
+
+ private void assertIsContained0(
+ JackrabbitAccessControlList acl,
+ String username,
+ String[] privilegeNames,
+ boolean isAllow,
+ boolean contained)
+ throws RepositoryException {
+ AclUtil.LocalAccessControlEntry localAce =
+ new AclUtil.LocalAccessControlEntry(principal(username), privileges(privilegeNames), isAllow);
+
+ if (contained) {
+ assertTrue(
+ "ACL does not contain an entry for " + localAce,
+ AclUtil.contains(acl.getAccessControlEntries(), localAce));
} else {
- assertFalse("ACL contains an entry for " + localAce, AclUtil.contains(acl.getAccessControlEntries(), localAce));
+ assertFalse(
+ "ACL contains an entry for " + localAce, AclUtil.contains(acl.getAccessControlEntries(), localAce));
}
-
}
private Principal principal(String principalName) throws RepositoryException {
@@ -454,4 +626,4 @@ public class AclUtilTest {
private Privilege[] privileges(String... privilegeNames) throws RepositoryException {
return AccessControlUtils.privilegesFromNames(U.adminSession, privilegeNames);
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/impl/ManyServiceUsersTest.java b/src/test/java/org/apache/sling/jcr/repoinit/impl/ManyServiceUsersTest.java
index 0e93d54..552689c 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/impl/ManyServiceUsersTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/impl/ManyServiceUsersTest.java
@@ -1,37 +1,42 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
-import java.util.Arrays;
-import java.util.UUID;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
+
+import java.util.Arrays;
+import java.util.UUID;
+
import org.apache.sling.repoinit.parser.RepoInitParsingException;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.apache.sling.testing.mock.sling.junit.SlingContext;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import static org.junit.Assert.fail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static org.junit.Assert.fail;
+
/** Created for SLING-6182 to verify that setAcl works right after
* creating a service user.
*/
@@ -39,53 +44,60 @@ public class ManyServiceUsersTest {
@Rule
public final SlingContext context = new SlingContext(ResourceResolverType.JCR_OAK);
-
+
private final Logger log = LoggerFactory.getLogger(getClass());
-
+
private static final String N_USERS_PROP = ManyServiceUsersTest.class.getSimpleName() + ".N_USERS";
-
+
private TestUtil U;
private static final int N_USERS = Integer.getInteger(N_USERS_PROP, 50);
private String uniqueId;
-
+
@Before
public void setup() throws RepositoryException, RepoInitParsingException {
U = new TestUtil(context);
uniqueId = UUID.randomUUID().toString();
}
-
+
@Test
public void testSyncServiceUserCreation() throws Exception {
-
- log.info("Creating {} service users (as set by the {} system property) and setting ACLs on them",
- N_USERS, N_USERS_PROP);
-
+
+ log.info(
+ "Creating {} service users (as set by the {} system property) and setting ACLs on them",
+ N_USERS,
+ N_USERS_PROP);
+
final Session s = U.getAdminSession();
final Node testRoot = s.getRootNode().addNode(getClass().getSimpleName() + "_" + uniqueId);
final String path = testRoot.getPath();
s.save();
-
+
Session otherSession = null;
try {
otherSession = s.getRepository().login(new SimpleCredentials("admin", "admin".toCharArray()));
- for(int i=1; i < N_USERS; i++) {
+ for (int i = 1; i < N_USERS; i++) {
final String username = getClass().getSimpleName() + "_" + uniqueId + "_" + i;
UserUtil.getUserManager(s).createSystemUser(username, null);
U.assertServiceUser("Right after creation at index " + i, username, true);
-
+
// Required for setAcl to work
s.save();
-
+
try {
- AclUtil.setAcl(otherSession, Arrays.asList(username), Arrays.asList(path), Arrays.asList("jcr:read"), true);
- } catch(Exception e) {
+ AclUtil.setAcl(
+ otherSession,
+ Arrays.asList(username),
+ Arrays.asList(path),
+ Arrays.asList("jcr:read"),
+ true);
+ } catch (Exception e) {
fail("SetAcl failed at index " + i + ": " + e);
}
}
} finally {
testRoot.remove();
s.save();
- if(otherSession != null) {
+ if (otherSession != null) {
otherSession.logout();
}
}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/impl/RepoinitReferenceTest.java b/src/test/java/org/apache/sling/jcr/repoinit/impl/RepoinitReferenceTest.java
index b1da973..fbf3b8c 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/impl/RepoinitReferenceTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/impl/RepoinitReferenceTest.java
@@ -1,23 +1,23 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
-import static org.junit.Assert.fail;
-import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -29,63 +29,67 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
/** Test the RepoinitTextProvider references parsing */
@RunWith(Parameterized.class)
public class RepoinitReferenceTest {
-
- @Parameters(name="{0}")
+
+ @Parameters(name = "{0}")
public static Collection<Object[]> data() {
- final List<Object []> result = new ArrayList<Object[]>();
-
+ final List<Object[]> result = new ArrayList<Object[]>();
+
// Valid references
- result.add(new Object[] { "model@foo:uri:1234", TextFormat.MODEL, "foo", "uri:1234", null });
- result.add(new Object[] { "model:uri:2345", TextFormat.MODEL, "repoinit", "uri:2345", null });
- result.add(new Object[] { "raw:uri:4567", TextFormat.RAW , null, "uri:4567", null });
- result.add(new Object[] { "raw:uri@5678", TextFormat.RAW, null, "uri@5678", null });
+ result.add(new Object[] {"model@foo:uri:1234", TextFormat.MODEL, "foo", "uri:1234", null});
+ result.add(new Object[] {"model:uri:2345", TextFormat.MODEL, "repoinit", "uri:2345", null});
+ result.add(new Object[] {"raw:uri:4567", TextFormat.RAW, null, "uri:4567", null});
+ result.add(new Object[] {"raw:uri@5678", TextFormat.RAW, null, "uri@5678", null});
// Invalid references
- result.add(new Object[] { "model@foo", null, null, null, IllegalArgumentException.class });
- result.add(new Object[] { "model#foo:url", TextFormat.MODEL, "repoinit", "url", IllegalArgumentException.class });
- result.add(new Object[] { "", null, null, null, IllegalArgumentException.class });
- result.add(new Object[] { null, null, null, null, IllegalArgumentException.class });
- result.add(new Object[] { "foo:url", null, null, null, IllegalArgumentException.class });
-
+ result.add(new Object[] {"model@foo", null, null, null, IllegalArgumentException.class});
+ result.add(new Object[] {"model#foo:url", TextFormat.MODEL, "repoinit", "url", IllegalArgumentException.class});
+ result.add(new Object[] {"", null, null, null, IllegalArgumentException.class});
+ result.add(new Object[] {null, null, null, null, IllegalArgumentException.class});
+ result.add(new Object[] {"foo:url", null, null, null, IllegalArgumentException.class});
+
// foo is ignored, by design
- result.add(new Object[] { "raw@foo:url", TextFormat.RAW, null, "url", null });
-
+ result.add(new Object[] {"raw@foo:url", TextFormat.RAW, null, "url", null});
+
return result;
}
-
+
private final String input;
private final RepoinitTextProvider.TextFormat format;
private final String modelSection;
private final String url;
private final Class<?> expectedException;
-
- public RepoinitReferenceTest(String input, TextFormat format, String modelSection, String url, Class<? >expectedException) {
+
+ public RepoinitReferenceTest(
+ String input, TextFormat format, String modelSection, String url, Class<?> expectedException) {
this.input = input;
this.format = format;
this.modelSection = modelSection;
this.url = url;
this.expectedException = expectedException;
}
-
+
@Test
public void testParsing() {
try {
final Reference ref = new Reference(input);
- if(expectedException != null) {
+ if (expectedException != null) {
fail("Expected a " + expectedException.getName());
}
assertEquals(format, ref.format);
assertEquals(modelSection, ref.modelSection);
assertEquals(url, ref.url);
- } catch(Exception e) {
- if(expectedException != null) {
+ } catch (Exception e) {
+ if (expectedException != null) {
assertEquals(expectedException, e.getClass());
} else {
fail("Unexpected " + e);
}
}
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/impl/RepositoryInitializerFactoryTest.java b/src/test/java/org/apache/sling/jcr/repoinit/impl/RepositoryInitializerFactoryTest.java
index da43299..213f2ab 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/impl/RepositoryInitializerFactoryTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/impl/RepositoryInitializerFactoryTest.java
@@ -1,21 +1,26 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
import org.apache.sling.commons.metrics.MetricsService;
import org.apache.sling.jcr.repoinit.JcrRepoInitOpsProcessor;
import org.apache.sling.jcr.repoinit.impl.RetryableOperation.RetryableOperationResult;
@@ -24,12 +29,8 @@ import org.apache.sling.testing.mock.sling.junit.SlingContext;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-
import org.mockito.ArgumentMatchers;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
@@ -52,42 +53,45 @@ public class RepositoryInitializerFactoryTest {
context.registerService(JcrRepoInitOpsProcessor.class, processor);
MetricsService metrics = mock(MetricsService.class);
context.registerService(MetricsService.class, metrics);
-
+
sut = new RepositoryInitializerFactory();
context.registerInjectActivateService(sut);
}
-
-
+
@Test
public void successfulRun() throws RepositoryException {
// doing nothing is also considered successful ...
sut.applyOperations(mock(Session.class), null, null, null);
- assertEquals(0,sut.failureStateAsMetric());
+ assertEquals(0, sut.failureStateAsMetric());
}
@Test
public void handleUncheckedErrorsInOperations() throws RepositoryException {
doThrow(new RepoInitException("some op failed", new Exception("root cause")))
- .when(processor).apply(ArgumentMatchers.any(), ArgumentMatchers.any());
+ .when(processor)
+ .apply(ArgumentMatchers.any(), ArgumentMatchers.any());
try {
- sut.applyOperations(mock(Session.class), null, null,null);
+ sut.applyOperations(mock(Session.class), null, null, null);
} catch (RepositoryException re) {
// expected
} catch (Exception e) {
fail();
}
- assertEquals(1,sut.failureStateAsMetric());
+ assertEquals(1, sut.failureStateAsMetric());
}
// https://issues.apache.org/jira/browse/SLING-11276
@Test
public void testRetriesWithExceptions() {
doThrow(new RepoInitException("some op failed", new Exception("root cause")))
- .when(processor).apply(ArgumentMatchers.any(), ArgumentMatchers.any());
- RetryableOperation retry = new RetryableOperation.Builder().withBackoffBaseMsec(1).withMaxRetries(3).build();
+ .when(processor)
+ .apply(ArgumentMatchers.any(), ArgumentMatchers.any());
+ RetryableOperation retry = new RetryableOperation.Builder()
+ .withBackoffBaseMsec(1)
+ .withMaxRetries(3)
+ .build();
RetryableOperationResult result = sut.applyOperationInternal(mock(Session.class), null, null, null, retry);
assertEquals(3, retry.retryCount);
assertFalse(result.isSuccessful());
}
-
}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/impl/RetryableOperationTest.java b/src/test/java/org/apache/sling/jcr/repoinit/impl/RetryableOperationTest.java
index 517a4f5..33c4dda 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/impl/RetryableOperationTest.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/impl/RetryableOperationTest.java
@@ -1,44 +1,44 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
public class RetryableOperationTest {
-
@Test
public void testWithoutRetry() {
RetryableOperation ro = new RetryableOperation.Builder().build();
Supplier<RetryableOperation.RetryableOperationResult> op = () -> {
- return new RetryableOperation.RetryableOperationResult(true,false,null,null);
+ return new RetryableOperation.RetryableOperationResult(true, false, null, null);
};
RetryableOperation.RetryableOperationResult result = ro.apply(op, "log");
- assertEquals(0,ro.retryCount);
+ assertEquals(0, ro.retryCount);
assertTrue(result.isSuccessful());
}
@@ -54,13 +54,13 @@ public class RetryableOperationTest {
Supplier<RetryableOperation.RetryableOperationResult> op = () -> {
// 1 regular execution + 2 retries
if (retries.getAndAdd(1) == 2) {
- return new RetryableOperation.RetryableOperationResult(true,false,null,null);
+ return new RetryableOperation.RetryableOperationResult(true, false, null, null);
} else {
- return new RetryableOperation.RetryableOperationResult(false,true,null,new RuntimeException());
+ return new RetryableOperation.RetryableOperationResult(false, true, null, new RuntimeException());
}
};
RetryableOperation.RetryableOperationResult result = ro.apply(op, "log");
- assertEquals(2,ro.retryCount);
+ assertEquals(2, ro.retryCount);
assertTrue(result.isSuccessful());
}
@@ -76,13 +76,13 @@ public class RetryableOperationTest {
Supplier<RetryableOperation.RetryableOperationResult> op = () -> {
// 1 regular execution + 4 retries
if (retries.getAndAdd(1) == 4) {
- return new RetryableOperation.RetryableOperationResult(true,false,null,null);
+ return new RetryableOperation.RetryableOperationResult(true, false, null, null);
} else {
- return new RetryableOperation.RetryableOperationResult(false,true,null,new RuntimeException());
+ return new RetryableOperation.RetryableOperationResult(false, true, null, new RuntimeException());
}
};
RetryableOperation.RetryableOperationResult result = ro.apply(op, "log");
- assertEquals(3,ro.retryCount); //only 3 retries and then stopped
+ assertEquals(3, ro.retryCount); // only 3 retries and then stopped
assertFalse(result.isSuccessful());
assertNotNull(result.getFailureTrace());
}
@@ -96,11 +96,10 @@ public class RetryableOperationTest {
.build();
Supplier<RetryableOperation.RetryableOperationResult> op = () -> {
// indicate a permanent failure, where it doesn't make sense to retry
- return new RetryableOperation.RetryableOperationResult(false,false,null,new RuntimeException());
+ return new RetryableOperation.RetryableOperationResult(false, false, null, new RuntimeException());
};
RetryableOperation.RetryableOperationResult result = ro.apply(op, "log");
- assertEquals(0,ro.retryCount); // no retry
+ assertEquals(0, ro.retryCount); // no retry
assertFalse(result.isSuccessful());
}
-
}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/impl/TestUtil.java b/src/test/java/org/apache/sling/jcr/repoinit/impl/TestUtil.java
index 54e87e7..f5b0904 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/impl/TestUtil.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/impl/TestUtil.java
@@ -1,35 +1,23 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.impl;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.io.StringReader;
-import java.util.Collections;
-import java.util.List;
-import java.util.Objects;
-import java.util.UUID;
-
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
@@ -39,6 +27,12 @@ import javax.jcr.Value;
import javax.jcr.nodetype.NodeType;
import javax.jcr.security.Privilege;
+import java.io.StringReader;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.UUID;
+
import org.apache.jackrabbit.api.security.JackrabbitAccessControlManager;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
@@ -51,6 +45,14 @@ import org.apache.sling.repoinit.parser.operations.Operation;
import org.apache.sling.testing.mock.sling.junit.SlingContext;
import org.jetbrains.annotations.NotNull;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
/** Test utilities */
public class TestUtil {
@@ -58,6 +60,7 @@ public class TestUtil {
@NotNull
public final Session adminSession;
+
public final String id;
public final String username;
@@ -80,28 +83,24 @@ public class TestUtil {
}
private void assertPathContains(Authorizable u, String pathShouldContain) throws RepositoryException {
- if(pathShouldContain != null) {
+ if (pathShouldContain != null) {
final String path = u.getPath();
- assertTrue(
- "Expecting path " + path + " to contain " + pathShouldContain,
- path.contains(pathShouldContain)
- );
+ assertTrue("Expecting path " + path + " to contain " + pathShouldContain, path.contains(pathShouldContain));
}
}
-
-
public void assertGroup(String info, String id, boolean expectToExist) throws RepositoryException {
assertGroup(info, id, expectToExist, null);
}
- public void assertGroup(String info, String id, boolean expectToExist, String pathShouldContain) throws RepositoryException {
+ public void assertGroup(String info, String id, boolean expectToExist, String pathShouldContain)
+ throws RepositoryException {
final Authorizable a = UserUtil.getUserManager(adminSession).getAuthorizable(id);
- if(!expectToExist) {
+ if (!expectToExist) {
assertNull(info + ", expecting Principal to be absent:" + id, a);
} else {
assertNotNull(info + ", expecting Principal to exist:" + id, a);
- final Group g = (Group)a;
+ final Group g = (Group) a;
assertPathContains(g, pathShouldContain);
}
}
@@ -110,13 +109,14 @@ public class TestUtil {
assertUser(info, id, expectToExist, null);
}
- public void assertUser(String info, String id, boolean expectToExist, String pathShouldContain) throws RepositoryException {
+ public void assertUser(String info, String id, boolean expectToExist, String pathShouldContain)
+ throws RepositoryException {
final Authorizable a = UserUtil.getUserManager(adminSession).getAuthorizable(id);
- if(!expectToExist) {
+ if (!expectToExist) {
assertNull(info + ", expecting Principal to be absent:" + id, a);
} else {
assertNotNull(info + ", expecting Principal to exist:" + id, a);
- final User u = (User)a;
+ final User u = (User) a;
assertFalse(info + ", expecting Principal to be a plain user:" + id, u.isSystemUser());
assertPathContains(u, pathShouldContain);
}
@@ -126,13 +126,14 @@ public class TestUtil {
assertServiceUser(info, id, expectToExist, null);
}
- public void assertServiceUser(String info, String id, boolean expectToExist, String pathShouldContain) throws RepositoryException {
+ public void assertServiceUser(String info, String id, boolean expectToExist, String pathShouldContain)
+ throws RepositoryException {
final Authorizable a = UserUtil.getUserManager(adminSession).getAuthorizable(id);
- if(!expectToExist) {
+ if (!expectToExist) {
assertNull(info + ", expecting Principal to be absent:" + id, a);
} else {
assertNotNull(info + ", expecting Principal to exist:" + id, a);
- final User u = (User)a;
+ final User u = (User) a;
assertTrue(info + ", expecting Principal to be a System user:" + id, u.isSystemUser());
assertPathContains(u, pathShouldContain);
}
@@ -145,7 +146,7 @@ public class TestUtil {
public void assertDisabledUser(String info, String id, String disabledReason) throws RepositoryException {
final Authorizable a = UserUtil.getUserManager(adminSession).getAuthorizable(id);
- final User user = (User)a;
+ final User user = (User) a;
assertTrue(info + ", expecting Principal to be disabled: " + id, user.isDisabled());
assertEquals("Expecting disabledReason==" + disabledReason, disabledReason, user.getDisabledReason());
}
@@ -163,16 +164,16 @@ public class TestUtil {
}
public void assertNodeExists(String path, String primaryType, List<String> mixins) throws RepositoryException {
- if(!adminSession.nodeExists(path)) {
+ if (!adminSession.nodeExists(path)) {
fail("Node does not exist:" + path);
}
- if(primaryType != null) {
+ if (primaryType != null) {
final Node n = adminSession.getNode(path);
- if(!n.hasProperty(JCR_PRIMARY_TYPE)) {
+ if (!n.hasProperty(JCR_PRIMARY_TYPE)) {
fail("No " + JCR_PRIMARY_TYPE + " property at " + path);
}
final String actual = n.getProperty(JCR_PRIMARY_TYPE).getString();
- if(!primaryType.equals(actual)) {
+ if (!primaryType.equals(actual)) {
fail("Primary type mismatch for " + path + ", expected " + primaryType + " but got " + actual);
}
}
@@ -180,17 +181,19 @@ public class TestUtil {
final Node n = adminSession.getNode(path);
NodeType[] mixinNodeTypes = n.getMixinNodeTypes();
if (mixinNodeTypes.length != mixins.size()) {
- fail("Number of mixin node types does not match, expected " + mixins.size() + " but got " + mixinNodeTypes.length);
+ fail("Number of mixin node types does not match, expected " + mixins.size() + " but got "
+ + mixinNodeTypes.length);
}
for (NodeType mixinNodeType : mixinNodeTypes) {
- if (! mixins.contains(mixinNodeType.getName())) {
+ if (!mixins.contains(mixinNodeType.getName())) {
fail("Node contains the unexpected mixin node type " + mixinNodeType.getName());
}
}
}
}
- public void assertGroupMembership(String userId, String groupId, boolean expectToBeMember) throws RepositoryException {
+ public void assertGroupMembership(String userId, String groupId, boolean expectToBeMember)
+ throws RepositoryException {
final Authorizable a = UserUtil.getUserManager(adminSession).getAuthorizable(groupId);
final Authorizable member = UserUtil.getUserManager(adminSession).getAuthorizable(userId);
boolean isMember = ((Group) a).isMember(member);
@@ -198,10 +201,11 @@ public class TestUtil {
if (!expectToBeMember) {
message += " not";
}
- assertEquals(message + " to be member of " + groupId, expectToBeMember, isMember);
+ assertEquals(message + " to be member of " + groupId, expectToBeMember, isMember);
}
- public void assertAuthorizableSVPropertyExists(String id, String propertyName, Value expectedValue) throws RepositoryException {
+ public void assertAuthorizableSVPropertyExists(String id, String propertyName, Value expectedValue)
+ throws RepositoryException {
final Authorizable a = UserUtil.getAuthorizable(adminSession, id);
assertNotNull("failed to get authorizable for " + id, a);
if (!a.hasProperty(propertyName)) {
@@ -215,7 +219,8 @@ public class TestUtil {
}
}
- public void assertAuthorizableMVPropertyExists(String id, String propertyName, Value[] expectedValues) throws RepositoryException {
+ public void assertAuthorizableMVPropertyExists(String id, String propertyName, Value[] expectedValues)
+ throws RepositoryException {
final Authorizable a = UserUtil.getAuthorizable(adminSession, id);
assertNotNull("failed to get authorizable for " + id, a);
if (!a.hasProperty(propertyName)) {
@@ -227,9 +232,10 @@ public class TestUtil {
}
}
- public void assertSVPropertyExists(String path, String propertyName, Value expectedValue) throws RepositoryException {
+ public void assertSVPropertyExists(String path, String propertyName, Value expectedValue)
+ throws RepositoryException {
final Node n = adminSession.getNode(path);
- if(!n.hasProperty(propertyName)) {
+ if (!n.hasProperty(propertyName)) {
fail("No " + propertyName + " property at " + path);
} else {
Property p = n.getProperty(propertyName);
@@ -238,9 +244,10 @@ public class TestUtil {
}
}
- public void assertMVPropertyExists(String path, String propertyName, Value[] expectedValues) throws RepositoryException {
+ public void assertMVPropertyExists(String path, String propertyName, Value[] expectedValues)
+ throws RepositoryException {
final Node n = adminSession.getNode(path);
- if(!n.hasProperty(propertyName)) {
+ if (!n.hasProperty(propertyName)) {
fail("No " + propertyName + " property at " + path);
} else {
Property p = n.getProperty(propertyName);
@@ -260,7 +267,7 @@ public class TestUtil {
public void cleanupUser() throws RepositoryException, RepoInitParsingException {
cleanupServiceUser(username);
}
-
+
public void cleanupServiceUser(String principalName) throws RepositoryException, RepoInitParsingException {
parseAndExecute("delete service user " + principalName);
assertServiceUser("in cleanupUser()", principalName, false);
@@ -275,17 +282,13 @@ public class TestUtil {
return adminSession;
}
- public String getTestCndStatement(String nsPrefix, String nsURI) throws RepositoryException, RepoInitParsingException {
- return "register nodetypes\n"
- + "<<===\n"
- + getTestCND(nsPrefix, nsURI)
- + "===>>\n"
- ;
+ public String getTestCndStatement(String nsPrefix, String nsURI)
+ throws RepositoryException, RepoInitParsingException {
+ return "register nodetypes\n" + "<<===\n" + getTestCND(nsPrefix, nsURI) + "===>>\n";
}
public String getTestCND(String nsPrefix, String nsURI) {
- return "<" + nsPrefix + "='" + nsURI + "'>\n"
- + "[" + nsPrefix + ":foo] > nt:unstructured\n";
+ return "<" + nsPrefix + "='" + nsURI + "'>\n" + "[" + nsPrefix + ":foo] > nt:unstructured\n";
}
public void cleanup(@NotNull List<String> idsToRemove) throws RepositoryException {
@@ -301,11 +304,13 @@ public class TestUtil {
}
}
- public void assertPrivileges(String principalName, String path, boolean allowed, String... privilegeNames) throws RepositoryException {
+ public void assertPrivileges(String principalName, String path, boolean allowed, String... privilegeNames)
+ throws RepositoryException {
final Privilege[] privileges = AccessControlUtils.privilegesFromNames(adminSession, privilegeNames);
final JackrabbitAccessControlManager acMgr = AclUtil.getJACM(adminSession);
assertEquals(
- String.format("Expected %s to have %s %s on %s",
+ String.format(
+ "Expected %s to have %s %s on %s",
principalName, String.join(", ", privilegeNames), allowed ? "allowed" : "denied", path),
allowed,
acMgr.hasPrivileges(path, Collections.singleton(() -> principalName), privileges));
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/it/MinimalRepoInitIT.java b/src/test/java/org/apache/sling/jcr/repoinit/it/MinimalRepoInitIT.java
index b721a75..5f75c44 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/it/MinimalRepoInitIT.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/it/MinimalRepoInitIT.java
@@ -1,30 +1,29 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.it;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import javax.inject.Inject;
import java.io.StringReader;
import java.util.List;
import java.util.UUID;
-import javax.inject.Inject;
-
import org.apache.sling.jcr.repoinit.JcrRepoInitOpsProcessor;
import org.apache.sling.repoinit.parser.RepoInitParser;
import org.apache.sling.repoinit.parser.operations.Operation;
@@ -34,6 +33,9 @@ import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerClass;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
/** Minimal integration test that demonstrates how to use
* the parser and operations executor to run repoinit
* statements at any time.
@@ -67,4 +69,4 @@ public class MinimalRepoInitIT extends RepoInitTestSupport {
session.save();
assertTrue("Expecting test nodes to be created", session.itemExists(path));
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/it/RepoInitTestSupport.java b/src/test/java/org/apache/sling/jcr/repoinit/it/RepoInitTestSupport.java
index 6c10e5e..17ade35 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/it/RepoInitTestSupport.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/it/RepoInitTestSupport.java
@@ -1,31 +1,23 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.it;
-import static org.apache.sling.testing.paxexam.SlingOptions.awaitility;
-import static org.apache.sling.testing.paxexam.SlingOptions.slingQuickstartOakTar;
-import static org.apache.sling.testing.paxexam.SlingOptions.versionResolver;
-import static org.ops4j.pax.exam.CoreOptions.composite;
-import static org.ops4j.pax.exam.CoreOptions.junitBundles;
-import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
-import static org.ops4j.pax.exam.CoreOptions.options;
-import static org.ops4j.pax.exam.CoreOptions.vmOption;
-import static org.ops4j.pax.exam.cm.ConfigurationAdminOptions.newConfiguration;
-
import javax.inject.Inject;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
@@ -40,6 +32,16 @@ import org.ops4j.pax.exam.Option;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static org.apache.sling.testing.paxexam.SlingOptions.awaitility;
+import static org.apache.sling.testing.paxexam.SlingOptions.slingQuickstartOakTar;
+import static org.apache.sling.testing.paxexam.SlingOptions.versionResolver;
+import static org.ops4j.pax.exam.CoreOptions.composite;
+import static org.ops4j.pax.exam.CoreOptions.junitBundles;
+import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
+import static org.ops4j.pax.exam.CoreOptions.options;
+import static org.ops4j.pax.exam.CoreOptions.vmOption;
+import static org.ops4j.pax.exam.cm.ConfigurationAdminOptions.newConfiguration;
+
public abstract class RepoInitTestSupport extends TestSupport {
protected Session session;
@@ -56,38 +58,38 @@ public abstract class RepoInitTestSupport extends TestSupport {
SlingOptions.versionResolver.setVersionFromProject("org.apache.jackrabbit", "jackrabbit-api");
SlingOptions.versionResolver.setVersionFromProject("org.apache.sling", "org.apache.sling.repoinit.parser");
SlingOptions.versionResolver.setVersionFromProject("org.apache.sling", "org.apache.sling.commons.metrics");
- SlingOptions.versionResolver.setVersionFromProject("org.apache.commons","commons-lang3"); // for the metrics
- return options(
- composite(
- super.baseConfiguration(),
- vmOption(System.getProperty("pax.vm.options")),
- slingQuickstart(),
- testBundle("bundle.filename"),
- mavenBundle().groupId("org.apache.sling").artifactId("org.apache.sling.repoinit.parser").versionAsInProject(),
- junitBundles(),
- awaitility(),
- newConfiguration("org.apache.sling.jcr.base.internal.LoginAdminWhitelist")
- .put("whitelist.bundles.regexp", "^PAXEXAM.*$")
- .asOption()
- ).add(
- additionalOptions()
- ).remove(
- // remove our bundle under test to avoid duplication
- mavenBundle().groupId("org.apache.sling").artifactId("org.apache.sling.jcr.repoinit").version(versionResolver)
- )
- );
+ SlingOptions.versionResolver.setVersionFromProject("org.apache.commons", "commons-lang3"); // for the metrics
+ return options(composite(
+ super.baseConfiguration(),
+ vmOption(System.getProperty("pax.vm.options")),
+ slingQuickstart(),
+ testBundle("bundle.filename"),
+ mavenBundle()
+ .groupId("org.apache.sling")
+ .artifactId("org.apache.sling.repoinit.parser")
+ .versionAsInProject(),
+ junitBundles(),
+ awaitility(),
+ newConfiguration("org.apache.sling.jcr.base.internal.LoginAdminWhitelist")
+ .put("whitelist.bundles.regexp", "^PAXEXAM.*$")
+ .asOption())
+ .add(additionalOptions())
+ .remove(
+ // remove our bundle under test to avoid duplication
+ mavenBundle()
+ .groupId("org.apache.sling")
+ .artifactId("org.apache.sling.jcr.repoinit")
+ .version(versionResolver)));
}
protected Option[] additionalOptions() {
- return new Option[]{};
+ return new Option[] {};
}
protected Option slingQuickstart() {
final String workingDirectory = workingDirectory();
final int httpPort = findFreePort();
- return composite(
- slingQuickstartOakTar(workingDirectory, httpPort)
- );
+ return composite(slingQuickstartOakTar(workingDirectory, httpPort));
}
public String getTestFileUrl(String path) {
@@ -107,5 +109,4 @@ public abstract class RepoInitTestSupport extends TestSupport {
session.logout();
}
}
-
}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/it/RepoInitTextIT.java b/src/test/java/org/apache/sling/jcr/repoinit/it/RepoInitTextIT.java
index 9f24f79..baac1c9 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/it/RepoInitTextIT.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/it/RepoInitTextIT.java
@@ -1,34 +1,32 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.it;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.UUID;
-
import javax.inject.Inject;
import javax.jcr.PropertyType;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.UUID;
+
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.UserManager;
@@ -42,6 +40,10 @@ import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerClass;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
/** Basic integration test of the repoinit parser and execution
* services, reading statements from a text file.
*/
@@ -67,7 +69,6 @@ public class RepoInitTextIT extends RepoInitTestSupport {
private static final String PROP_I = "quotedMix";
private static final String PROP_NODE_PATH = "/proptest/X/Y";
-
public static final String REPO_INIT_FILE = "/repoinit.txt";
@Inject
@@ -158,14 +159,26 @@ public class RepoInitTextIT extends RepoInitTestSupport {
new Retry() {
@Override
public Void call() throws Exception {
- assertTrue("Expecting user " + FRED_WILMA + "to be member of " + GROUP_A, U.isMember(session, FRED_WILMA, GROUP_A));
- assertTrue("Expecting user " + ALICE + "to be member of " + GROUP_A,U.isMember(session, ALICE, GROUP_A));
- assertTrue("Expecting user " + ANOTHER + "to be member of " + GROUP_B,U.isMember(session, ANOTHER, GROUP_B));
- assertFalse("Expecting user " + BOB + "not to be member of " + GROUP_B,U.isMember(session, BOB, GROUP_B));
- assertFalse("Expecting group " + GROUP_A + "not to be member of " + GROUP_B,U.isMember(session, GROUP_A, GROUP_B));
- assertTrue("Expecting group " + GROUP_A + "to be member of " + GROUP_C,U.isMember(session, GROUP_A, GROUP_C));
- assertTrue("Expecting user " + BOB + "to be member of " + GROUP_C,U.isMember(session, BOB, GROUP_C));
- assertTrue("Expecting group " + GROUP_B + "to be member of " + GROUP_C,U.isMember(session, GROUP_B, GROUP_C));
+ assertTrue(
+ "Expecting user " + FRED_WILMA + "to be member of " + GROUP_A,
+ U.isMember(session, FRED_WILMA, GROUP_A));
+ assertTrue(
+ "Expecting user " + ALICE + "to be member of " + GROUP_A, U.isMember(session, ALICE, GROUP_A));
+ assertTrue(
+ "Expecting user " + ANOTHER + "to be member of " + GROUP_B,
+ U.isMember(session, ANOTHER, GROUP_B));
+ assertFalse(
+ "Expecting user " + BOB + "not to be member of " + GROUP_B, U.isMember(session, BOB, GROUP_B));
+ assertFalse(
+ "Expecting group " + GROUP_A + "not to be member of " + GROUP_B,
+ U.isMember(session, GROUP_A, GROUP_B));
+ assertTrue(
+ "Expecting group " + GROUP_A + "to be member of " + GROUP_C,
+ U.isMember(session, GROUP_A, GROUP_C));
+ assertTrue("Expecting user " + BOB + "to be member of " + GROUP_C, U.isMember(session, BOB, GROUP_C));
+ assertTrue(
+ "Expecting group " + GROUP_B + "to be member of " + GROUP_C,
+ U.isMember(session, GROUP_B, GROUP_C));
return null;
}
};
@@ -180,36 +193,55 @@ public class RepoInitTextIT extends RepoInitTestSupport {
Value[] expectedValues1 = new Value[2];
expectedValues1[0] = vf.createValue("/d/e/f/*");
expectedValues1[1] = vf.createValue("m/n/*");
- assertTrue("Expecting array type property " + PROP_A + " to be present ", U.hasProperty(session, PROP_NODE_PATH, PROP_A, expectedValues1));
+ assertTrue(
+ "Expecting array type property " + PROP_A + " to be present ",
+ U.hasProperty(session, PROP_NODE_PATH, PROP_A, expectedValues1));
Value expectedValue2 = vf.createValue("42", PropertyType.valueFromName("Long"));
- assertTrue("Expecting Long type default property " + PROP_B + " to be present ", U.hasProperty(session, PROP_NODE_PATH, PROP_B, expectedValue2));
+ assertTrue(
+ "Expecting Long type default property " + PROP_B + " to be present ",
+ U.hasProperty(session, PROP_NODE_PATH, PROP_B, expectedValue2));
- Value expectedValue3 = vf.createValue("true", PropertyType.valueFromName("Boolean"));
- assertTrue("Expecting bool type property " + PROP_C + " to be present ", U.hasProperty(session, PROP_NODE_PATH, PROP_C, expectedValue3));
+ Value expectedValue3 = vf.createValue("true", PropertyType.valueFromName("Boolean"));
+ assertTrue(
+ "Expecting bool type property " + PROP_C + " to be present ",
+ U.hasProperty(session, PROP_NODE_PATH, PROP_C, expectedValue3));
- Value expectedValue4 = vf.createValue("2020-03-19T11:39:33.437+05:30", PropertyType.valueFromName("Date"));
- assertTrue("Expecting date type property " + PROP_D + " to be present " , U.hasProperty(session, PROP_NODE_PATH, PROP_D, expectedValue4));
+ Value expectedValue4 =
+ vf.createValue("2020-03-19T11:39:33.437+05:30", PropertyType.valueFromName("Date"));
+ assertTrue(
+ "Expecting date type property " + PROP_D + " to be present ",
+ U.hasProperty(session, PROP_NODE_PATH, PROP_D, expectedValue4));
Value expectedValue5 = vf.createValue("test");
- assertTrue("Expecting string type property " + PROP_E + " to be present " , U.hasProperty(session, PROP_NODE_PATH, PROP_E, expectedValue5));
+ assertTrue(
+ "Expecting string type property " + PROP_E + " to be present ",
+ U.hasProperty(session, PROP_NODE_PATH, PROP_E, expectedValue5));
Value expectedValue6 = vf.createValue("hello, you!");
- assertTrue("Expecting quoted string type property " + PROP_F + " to be present " , U.hasProperty(session, PROP_NODE_PATH, PROP_F, expectedValue6));
+ assertTrue(
+ "Expecting quoted string type property " + PROP_F + " to be present ",
+ U.hasProperty(session, PROP_NODE_PATH, PROP_F, expectedValue6));
Value[] expectedValues7 = new Value[2];
expectedValues7[0] = vf.createValue("test1");
expectedValues7[1] = vf.createValue("test2");
- assertTrue("Expecting string array type property " + PROP_G + " to be present " , U.hasProperty(session, PROP_NODE_PATH, PROP_G, expectedValues7));
+ assertTrue(
+ "Expecting string array type property " + PROP_G + " to be present ",
+ U.hasProperty(session, PROP_NODE_PATH, PROP_G, expectedValues7));
Value expectedValue8 = vf.createValue("Here's a \"double quoted string\" with suffix");
- assertTrue("Expecting quoted string type property " + PROP_H + " to be present " , U.hasProperty(session, PROP_NODE_PATH, PROP_H, expectedValue8));
+ assertTrue(
+ "Expecting quoted string type property " + PROP_H + " to be present ",
+ U.hasProperty(session, PROP_NODE_PATH, PROP_H, expectedValue8));
Value[] expectedValues9 = new Value[3];
expectedValues9[0] = vf.createValue("quoted");
expectedValues9[1] = vf.createValue("non-quoted");
expectedValues9[2] = vf.createValue("the last \" one");
- assertTrue("Expecting string array type property " + PROP_I + " to be present " , U.hasProperty(session, PROP_NODE_PATH, PROP_I, expectedValues9));
+ assertTrue(
+ "Expecting string array type property " + PROP_I + " to be present ",
+ U.hasProperty(session, PROP_NODE_PATH, PROP_I, expectedValues9));
return null;
}
@@ -221,15 +253,13 @@ public class RepoInitTextIT extends RepoInitTestSupport {
new Retry() {
@Override
public Void call() throws Exception {
- if(!(session instanceof JackrabbitSession)) {
+ if (!(session instanceof JackrabbitSession)) {
throw new IllegalArgumentException("Session is not a JackrabbitSession");
}
- UserManager um = ((JackrabbitSession)session).getUserManager();
+ UserManager um = ((JackrabbitSession) session).getUserManager();
- Authorizable [] authorizables = new Authorizable[] {
- um.getAuthorizable(ALICE),
- um.getAuthorizable(GROUP_A)
- };
+ Authorizable[] authorizables =
+ new Authorizable[] {um.getAuthorizable(ALICE), um.getAuthorizable(GROUP_A)};
for (Authorizable authorizable : authorizables) {
assertNotNull("Expected authorizable to not be null", authorizable);
@@ -237,39 +267,60 @@ public class RepoInitTextIT extends RepoInitTestSupport {
Value[] expectedValues1 = new Value[2];
expectedValues1[0] = vf.createValue("/d/e/f/*");
expectedValues1[1] = vf.createValue("m/n/*");
- assertTrue("Expecting array type property " + PROP_A + " to be present ", U.hasProperty(authorizable, PROP_A, expectedValues1));
+ assertTrue(
+ "Expecting array type property " + PROP_A + " to be present ",
+ U.hasProperty(authorizable, PROP_A, expectedValues1));
Value expectedValue2 = vf.createValue("42", PropertyType.valueFromName("Long"));
- assertTrue("Expecting Long type default property " + PROP_B + " to be present ", U.hasProperty(authorizable, PROP_B, expectedValue2));
+ assertTrue(
+ "Expecting Long type default property " + PROP_B + " to be present ",
+ U.hasProperty(authorizable, PROP_B, expectedValue2));
- Value expectedValue3 = vf.createValue("true", PropertyType.valueFromName("Boolean"));
- assertTrue("Expecting bool type property " + PROP_C + " to be present ", U.hasProperty(authorizable, PROP_C, expectedValue3));
+ Value expectedValue3 = vf.createValue("true", PropertyType.valueFromName("Boolean"));
+ assertTrue(
+ "Expecting bool type property " + PROP_C + " to be present ",
+ U.hasProperty(authorizable, PROP_C, expectedValue3));
- Value expectedValue4 = vf.createValue("2020-03-19T11:39:33.437+05:30", PropertyType.valueFromName("Date"));
- assertTrue("Expecting date type property " + PROP_D + " to be present " , U.hasProperty(authorizable, PROP_D, expectedValue4));
+ Value expectedValue4 =
+ vf.createValue("2020-03-19T11:39:33.437+05:30", PropertyType.valueFromName("Date"));
+ assertTrue(
+ "Expecting date type property " + PROP_D + " to be present ",
+ U.hasProperty(authorizable, PROP_D, expectedValue4));
Value expectedValue5 = vf.createValue("test");
- assertTrue("Expecting string type property " + PROP_E + " to be present " , U.hasProperty(authorizable, PROP_E, expectedValue5));
+ assertTrue(
+ "Expecting string type property " + PROP_E + " to be present ",
+ U.hasProperty(authorizable, PROP_E, expectedValue5));
Value expectedValue6 = vf.createValue("hello, you!");
- assertTrue("Expecting quoted string type property " + PROP_F + " to be present " , U.hasProperty(authorizable, PROP_F, expectedValue6));
+ assertTrue(
+ "Expecting quoted string type property " + PROP_F + " to be present ",
+ U.hasProperty(authorizable, PROP_F, expectedValue6));
Value[] expectedValues7 = new Value[2];
expectedValues7[0] = vf.createValue("test1");
expectedValues7[1] = vf.createValue("test2");
- assertTrue("Expecting string array type property " + PROP_G + " to be present " , U.hasProperty(authorizable, PROP_G, expectedValues7));
+ assertTrue(
+ "Expecting string array type property " + PROP_G + " to be present ",
+ U.hasProperty(authorizable, PROP_G, expectedValues7));
Value expectedValue8 = vf.createValue("Here's a \"double quoted string\" with suffix");
- assertTrue("Expecting quoted string type property " + PROP_H + " to be present " , U.hasProperty(authorizable, PROP_H, expectedValue8));
+ assertTrue(
+ "Expecting quoted string type property " + PROP_H + " to be present ",
+ U.hasProperty(authorizable, PROP_H, expectedValue8));
Value[] expectedValues9 = new Value[3];
expectedValues9[0] = vf.createValue("quoted");
expectedValues9[1] = vf.createValue("non-quoted");
expectedValues9[2] = vf.createValue("the last \" one");
- assertTrue("Expecting string array type property " + PROP_I + " to be present " , U.hasProperty(authorizable, PROP_I, expectedValues9));
+ assertTrue(
+ "Expecting string array type property " + PROP_I + " to be present ",
+ U.hasProperty(authorizable, PROP_I, expectedValues9));
Value nestedExpectedValue = vf.createValue("42", PropertyType.valueFromName("Long"));
- assertTrue("Expecting Long type default property nested/" + PROP_B + " to be present ", U.hasProperty(authorizable, "nested/" +PROP_B, nestedExpectedValue));
+ assertTrue(
+ "Expecting Long type default property nested/" + PROP_B + " to be present ",
+ U.hasProperty(authorizable, "nested/" + PROP_B, nestedExpectedValue));
}
return null;
@@ -282,15 +333,13 @@ public class RepoInitTextIT extends RepoInitTestSupport {
new Retry() {
@Override
public Void call() throws Exception {
- if(!(session instanceof JackrabbitSession)) {
+ if (!(session instanceof JackrabbitSession)) {
throw new IllegalArgumentException("Session is not a JackrabbitSession");
}
- UserManager um = ((JackrabbitSession)session).getUserManager();
+ UserManager um = ((JackrabbitSession) session).getUserManager();
- Authorizable [] authorizables = new Authorizable[] {
- um.getAuthorizable(BOB),
- um.getAuthorizable(GROUP_B)
- };
+ Authorizable[] authorizables =
+ new Authorizable[] {um.getAuthorizable(BOB), um.getAuthorizable(GROUP_B)};
for (Authorizable authorizable : authorizables) {
assertNotNull("Expected authorizable to not be null", authorizable);
@@ -298,43 +347,64 @@ public class RepoInitTextIT extends RepoInitTestSupport {
Value[] expectedValues1 = new Value[2];
expectedValues1[0] = vf.createValue("/d/e/f/*");
expectedValues1[1] = vf.createValue("m/n/*");
- assertTrue("Expecting array type property nested/" + PROP_A + " to be present ", U.hasProperty(authorizable, "nested/" + PROP_A, expectedValues1));
+ assertTrue(
+ "Expecting array type property nested/" + PROP_A + " to be present ",
+ U.hasProperty(authorizable, "nested/" + PROP_A, expectedValues1));
Value expectedValue2 = vf.createValue("42", PropertyType.valueFromName("Long"));
- assertTrue("Expecting Long type default property nested/" + PROP_B + " to be present ", U.hasProperty(authorizable, "nested/" + PROP_B, expectedValue2));
+ assertTrue(
+ "Expecting Long type default property nested/" + PROP_B + " to be present ",
+ U.hasProperty(authorizable, "nested/" + PROP_B, expectedValue2));
- Value expectedValue3 = vf.createValue("true", PropertyType.valueFromName("Boolean"));
- assertTrue("Expecting bool type property nested/" + PROP_C + " to be present ", U.hasProperty(authorizable, "nested/" + PROP_C, expectedValue3));
+ Value expectedValue3 = vf.createValue("true", PropertyType.valueFromName("Boolean"));
+ assertTrue(
+ "Expecting bool type property nested/" + PROP_C + " to be present ",
+ U.hasProperty(authorizable, "nested/" + PROP_C, expectedValue3));
- Value expectedValue4 = vf.createValue("2020-03-19T11:39:33.437+05:30", PropertyType.valueFromName("Date"));
- assertTrue("Expecting date type property nested/" + PROP_D + " to be present " , U.hasProperty(authorizable, "nested/" + PROP_D, expectedValue4));
+ Value expectedValue4 =
+ vf.createValue("2020-03-19T11:39:33.437+05:30", PropertyType.valueFromName("Date"));
+ assertTrue(
+ "Expecting date type property nested/" + PROP_D + " to be present ",
+ U.hasProperty(authorizable, "nested/" + PROP_D, expectedValue4));
Value expectedValue5 = vf.createValue("test");
- assertTrue("Expecting string type property nested/" + PROP_E + " to be present " , U.hasProperty(authorizable, "nested/" + PROP_E, expectedValue5));
+ assertTrue(
+ "Expecting string type property nested/" + PROP_E + " to be present ",
+ U.hasProperty(authorizable, "nested/" + PROP_E, expectedValue5));
Value expectedValue6 = vf.createValue("hello, you!");
- assertTrue("Expecting quoted string type property nested/" + PROP_F + " to be present " , U.hasProperty(authorizable, "nested/" + PROP_F, expectedValue6));
+ assertTrue(
+ "Expecting quoted string type property nested/" + PROP_F + " to be present ",
+ U.hasProperty(authorizable, "nested/" + PROP_F, expectedValue6));
Value[] expectedValues7 = new Value[2];
expectedValues7[0] = vf.createValue("test1");
expectedValues7[1] = vf.createValue("test2");
- assertTrue("Expecting string array type property nested/" + PROP_G + " to be present " , U.hasProperty(authorizable, "nested/" + PROP_G, expectedValues7));
+ assertTrue(
+ "Expecting string array type property nested/" + PROP_G + " to be present ",
+ U.hasProperty(authorizable, "nested/" + PROP_G, expectedValues7));
Value expectedValue8 = vf.createValue("Here's a \"double quoted string\" with suffix");
- assertTrue("Expecting quoted string type property nested/" + PROP_H + " to be present " , U.hasProperty(authorizable, "nested/" + PROP_H, expectedValue8));
+ assertTrue(
+ "Expecting quoted string type property nested/" + PROP_H + " to be present ",
+ U.hasProperty(authorizable, "nested/" + PROP_H, expectedValue8));
Value[] expectedValues9 = new Value[3];
expectedValues9[0] = vf.createValue("quoted");
expectedValues9[1] = vf.createValue("non-quoted");
expectedValues9[2] = vf.createValue("the last \" one");
- assertTrue("Expecting string array type property nested/" + PROP_I + " to be present " , U.hasProperty(authorizable, "nested/" + PROP_I, expectedValues9));
+ assertTrue(
+ "Expecting string array type property nested/" + PROP_I + " to be present ",
+ U.hasProperty(authorizable, "nested/" + PROP_I, expectedValues9));
Value nestedExpectedValue = vf.createValue("42", PropertyType.valueFromName("Long"));
- assertTrue("Expecting Long type default property nested/nested/" + PROP_B + " to be present ", U.hasProperty(authorizable, "nested/nested/" +PROP_B, nestedExpectedValue));
+ assertTrue(
+ "Expecting Long type default property nested/nested/" + PROP_B + " to be present ",
+ U.hasProperty(authorizable, "nested/nested/" + PROP_B, nestedExpectedValue));
}
return null;
}
};
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/it/RepositoryInitializerFactoryIT.java b/src/test/java/org/apache/sling/jcr/repoinit/it/RepositoryInitializerFactoryIT.java
index 60e53b9..0cda138 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/it/RepositoryInitializerFactoryIT.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/it/RepositoryInitializerFactoryIT.java
@@ -1,22 +1,24 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.it;
-import static org.junit.Assert.assertFalse;
+import javax.inject.Inject;
import java.time.Duration;
import java.util.ArrayList;
@@ -24,8 +26,6 @@ import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
-import javax.inject.Inject;
-
import org.awaitility.Awaitility;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -35,6 +35,8 @@ import org.ops4j.pax.exam.spi.reactors.PerClass;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
+import static org.junit.Assert.assertFalse;
+
/** Verify the RepositoryInitializerFactory functionality, to execute
* repoinit statements coming from OSGi configurations
*/
@@ -45,65 +47,54 @@ public class RepositoryInitializerFactoryIT extends RepoInitTestSupport {
@Inject
private ConfigurationAdmin configAdmin;
- private void assertConfigAndPaths(String references, String scripts, String ... expectedPaths) throws Exception {
- for(String path : expectedPaths) {
+ private void assertConfigAndPaths(String references, String scripts, String... expectedPaths) throws Exception {
+ for (String path : expectedPaths) {
assertFalse("Expecting path to be absent before test:" + path, session.itemExists(path));
}
final Dictionary<String, Object> props = new Hashtable<>();
- if(references != null) {
+ if (references != null) {
props.put("references", references);
}
- if(scripts != null) {
+ if (scripts != null) {
props.put("scripts", scripts);
}
- final Configuration cfg = configAdmin.createFactoryConfiguration("org.apache.sling.jcr.repoinit.RepositoryInitializer");
+ final Configuration cfg =
+ configAdmin.createFactoryConfiguration("org.apache.sling.jcr.repoinit.RepositoryInitializer");
cfg.setBundleLocation(null);
cfg.update(props);
// Configs are processed asynchronously, give them some time
List<String> missing = new ArrayList<>();
Awaitility.await("configAndPathsExist")
- .atMost(Duration.ofSeconds(5))
- .pollInterval(Duration.ofMillis(250))
- .until(() -> {
- session.refresh(false);
- missing.clear();
- for (String path : expectedPaths) {
- if (!session.itemExists(path)) {
- missing.add(path);
+ .atMost(Duration.ofSeconds(5))
+ .pollInterval(Duration.ofMillis(250))
+ .until(() -> {
+ session.refresh(false);
+ missing.clear();
+ for (String path : expectedPaths) {
+ if (!session.itemExists(path)) {
+ missing.add(path);
+ }
}
- }
- return missing.isEmpty();
- });
+ return missing.isEmpty();
+ });
}
@Test
public void testReferencesAndScripts() throws Exception {
- assertConfigAndPaths(
- null,
- "create path /repoinit-test/scripts/A",
- "/repoinit-test/scripts/A");
+ assertConfigAndPaths(null, "create path /repoinit-test/scripts/A", "/repoinit-test/scripts/A");
- assertConfigAndPaths(
- "",
- "create path /repoinit-test/scripts/B",
- "/repoinit-test/scripts/B");
+ assertConfigAndPaths("", "create path /repoinit-test/scripts/B", "/repoinit-test/scripts/B");
assertConfigAndPaths(
- getTestFileUrl("/repoinit-path-3.txt"),
- "create path /repoinit-test/scripts/C",
- "/repoinit-test/path-3",
- "/repoinit-test/scripts/C");
+ getTestFileUrl("/repoinit-path-3.txt"),
+ "create path /repoinit-test/scripts/C",
+ "/repoinit-test/path-3",
+ "/repoinit-test/scripts/C");
- assertConfigAndPaths(
- getTestFileUrl("/repoinit-path-4.txt"),
- null,
- "/repoinit-test/path-4");
+ assertConfigAndPaths(getTestFileUrl("/repoinit-path-4.txt"), null, "/repoinit-test/path-4");
- assertConfigAndPaths(
- getTestFileUrl("/repoinit-path-5.txt"),
- "",
- "/repoinit-test/path-5");
+ assertConfigAndPaths(getTestFileUrl("/repoinit-path-5.txt"), "", "/repoinit-test/path-5");
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/it/RepositoryInitializerIT.java b/src/test/java/org/apache/sling/jcr/repoinit/it/RepositoryInitializerIT.java
index beac5e7..7fc05aa 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/it/RepositoryInitializerIT.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/it/RepositoryInitializerIT.java
@@ -1,24 +1,23 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.it;
-import static org.junit.Assert.assertTrue;
-import static org.ops4j.pax.exam.cm.ConfigurationAdminOptions.newConfiguration;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Option;
@@ -26,6 +25,9 @@ import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerClass;
+import static org.junit.Assert.assertTrue;
+import static org.ops4j.pax.exam.cm.ConfigurationAdminOptions.newConfiguration;
+
/** Verify that statements provided as URLS to our RepositoryInitializer
* are executed.
*/
@@ -35,15 +37,14 @@ public class RepositoryInitializerIT extends RepoInitTestSupport {
@Override
protected Option[] additionalOptions() {
- final String [] srcUrls = {
- "raw:" + getTestFileUrl("/repoinit-path-1.txt"),
- "raw:" + getTestFileUrl("/repoinit-path-2.txt")
+ final String[] srcUrls = {
+ "raw:" + getTestFileUrl("/repoinit-path-1.txt"), "raw:" + getTestFileUrl("/repoinit-path-2.txt")
};
return new Option[] {
newConfiguration("org.apache.sling.jcr.repoinit.impl.RepositoryInitializer")
- .put("references", srcUrls)
- .asOption()
+ .put("references", srcUrls)
+ .asOption()
};
}
@@ -56,4 +57,4 @@ public class RepositoryInitializerIT extends RepoInitTestSupport {
public void path2Created() throws Exception {
assertTrue(session.itemExists("/repoinit-test/path-2"));
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/it/Retry.java b/src/test/java/org/apache/sling/jcr/repoinit/it/Retry.java
index d6eb79f..b6e48f0 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/it/Retry.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/it/Retry.java
@@ -1,19 +1,20 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
-
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.it;
@@ -33,12 +34,12 @@ public abstract class Retry implements Callable<Void> {
public Retry(int timeout, int interval) {
Awaitility.await()
- .atMost(Duration.ofMillis(timeout))
- .pollInterval(Duration.ofMillis(interval))
- .ignoreExceptions()
- .until(() -> {
- call();
- return true;
- });
+ .atMost(Duration.ofMillis(timeout))
+ .pollInterval(Duration.ofMillis(interval))
+ .ignoreExceptions()
+ .until(() -> {
+ call();
+ return true;
+ });
}
}
diff --git a/src/test/java/org/apache/sling/jcr/repoinit/it/U.java b/src/test/java/org/apache/sling/jcr/repoinit/it/U.java
index 381d2a9..0659c87 100644
--- a/src/test/java/org/apache/sling/jcr/repoinit/it/U.java
+++ b/src/test/java/org/apache/sling/jcr/repoinit/it/U.java
@@ -1,33 +1,35 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.jcr.repoinit.it;
-import java.util.UUID;
-import java.util.Arrays;
-
import javax.jcr.AccessDeniedException;
import javax.jcr.LoginException;
import javax.jcr.Node;
-import javax.jcr.Value;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.UnsupportedRepositoryOperationException;
+import javax.jcr.Value;
+
+import java.util.Arrays;
+import java.util.UUID;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
@@ -36,41 +38,44 @@ import org.apache.jackrabbit.api.security.user.User;
/** Test utilities */
public class U {
- public static boolean userExists(Session session, String id) throws LoginException, RepositoryException, InterruptedException {
- final Authorizable a = ((JackrabbitSession)session).getUserManager().getAuthorizable(id);
+ public static boolean userExists(Session session, String id)
+ throws LoginException, RepositoryException, InterruptedException {
+ final Authorizable a = ((JackrabbitSession) session).getUserManager().getAuthorizable(id);
return a != null;
}
public static boolean userIsDisabled(Session session, String id) throws RepositoryException {
- final Authorizable a = ((JackrabbitSession)session).getUserManager().getAuthorizable(id);
+ final Authorizable a = ((JackrabbitSession) session).getUserManager().getAuthorizable(id);
if (a == null) {
throw new IllegalStateException("Authorizable not found:" + id);
}
if (a.isGroup()) {
throw new IllegalStateException("Authorizable is a group:" + id);
}
- return ((User)a).isDisabled();
+ return ((User) a).isDisabled();
}
- public static Session getServiceSession(Session session, String serviceId) throws LoginException, RepositoryException {
+ public static Session getServiceSession(Session session, String serviceId)
+ throws LoginException, RepositoryException {
return session.impersonate(new SimpleCredentials(serviceId, new char[0]));
}
/** True if user can write to specified path.
* @throws PathNotFoundException if the path doesn't exist */
- public static boolean canWrite(Session session, String userId, String path) throws PathNotFoundException,RepositoryException {
- if(!session.itemExists(path)) {
+ public static boolean canWrite(Session session, String userId, String path)
+ throws PathNotFoundException, RepositoryException {
+ if (!session.itemExists(path)) {
throw new PathNotFoundException(path);
}
final Session serviceSession = getServiceSession(session, userId);
final String testNodeName = "test_" + UUID.randomUUID().toString();
try {
- ((Node)serviceSession.getItem(path)).addNode(testNodeName);
+ ((Node) serviceSession.getItem(path)).addNode(testNodeName);
serviceSession.save();
- } catch(AccessDeniedException ade) {
+ } catch (AccessDeniedException ade) {
return false;
- } catch(PathNotFoundException pnf) {
+ } catch (PathNotFoundException pnf) {
// Thrown when access is denied to a user's home node
return false;
} finally {
@@ -81,17 +86,18 @@ public class U {
/** True if user can read specified path.
* @throws PathNotFoundException if the path doesn't exist */
- public static boolean canRead(Session session, String userId, String path) throws PathNotFoundException,RepositoryException {
- if(!session.itemExists(path)) {
+ public static boolean canRead(Session session, String userId, String path)
+ throws PathNotFoundException, RepositoryException {
+ if (!session.itemExists(path)) {
throw new PathNotFoundException(path);
}
final Session serviceSession = getServiceSession(session, userId);
try {
serviceSession.getItem(path);
- } catch(AccessDeniedException ade) {
+ } catch (AccessDeniedException ade) {
return false;
- } catch(PathNotFoundException pnf) {
+ } catch (PathNotFoundException pnf) {
// Thrown when access is denied to a user's home node
return false;
} finally {
@@ -101,18 +107,20 @@ public class U {
}
public static String getHomePath(Session session, String userId)
- throws UnsupportedRepositoryOperationException, RepositoryException {
- final Authorizable a = ((JackrabbitSession)session).getUserManager().getAuthorizable(userId);
+ throws UnsupportedRepositoryOperationException, RepositoryException {
+ final Authorizable a = ((JackrabbitSession) session).getUserManager().getAuthorizable(userId);
return a.getPath();
}
- public static boolean isMember(Session session, String userId, String groupId) throws RepositoryException {
- final Authorizable a = ((JackrabbitSession)session).getUserManager().getAuthorizable(groupId);
- final Authorizable member = ((JackrabbitSession)session).getUserManager().getAuthorizable(userId);
+ public static boolean isMember(Session session, String userId, String groupId) throws RepositoryException {
+ final Authorizable a = ((JackrabbitSession) session).getUserManager().getAuthorizable(groupId);
+ final Authorizable member =
+ ((JackrabbitSession) session).getUserManager().getAuthorizable(userId);
return ((Group) a).isMember(member);
}
- public static boolean hasProperty(Session session, String nodePath, String propertyName, Value propertyValue) throws RepositoryException {
+ public static boolean hasProperty(Session session, String nodePath, String propertyName, Value propertyValue)
+ throws RepositoryException {
final Node n = session.getNode(nodePath);
if (n != null) {
boolean isPropertyPresent = n.hasProperty(propertyName);
@@ -124,7 +132,8 @@ public class U {
return false;
}
- public static boolean hasProperty(Session session, String nodePath, String propertyName, Value[] propertyValues) throws RepositoryException {
+ public static boolean hasProperty(Session session, String nodePath, String propertyName, Value[] propertyValues)
+ throws RepositoryException {
final Node n = session.getNode(nodePath);
if (n != null) {
boolean isPropertyPresent = n.hasProperty(propertyName);
@@ -136,7 +145,8 @@ public class U {
return false;
}
- public static boolean hasProperty(Authorizable a, String propertyName, Value propertyValue) throws RepositoryException {
+ public static boolean hasProperty(Authorizable a, String propertyName, Value propertyValue)
+ throws RepositoryException {
if (a != null) {
boolean isPropertyPresent = a.hasProperty(propertyName);
if (isPropertyPresent) {
@@ -150,7 +160,8 @@ public class U {
return false;
}
- public static boolean hasProperty(Authorizable a, String propertyName, Value[] propertyValues) throws RepositoryException {
+ public static boolean hasProperty(Authorizable a, String propertyName, Value[] propertyValues)
+ throws RepositoryException {
if (a != null) {
boolean isPropertyPresent = a.hasProperty(propertyName);
if (isPropertyPresent) {
@@ -160,4 +171,4 @@ public class U {
}
return false;
}
-}
\ No newline at end of file
+}