You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by en...@apache.org on 2025/08/20 18:11:38 UTC
(sling-org-apache-sling-jcr-jackrabbit-usermanager) branch master updated: SLING-12898 Update to Parent 62 and apply spotless formatting (#27)
This is an automated email from the ASF dual-hosted git repository.
enorman pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-jcr-jackrabbit-usermanager.git
The following commit(s) were added to refs/heads/master by this push:
new ebf672e SLING-12898 Update to Parent 62 and apply spotless formatting (#27)
ebf672e is described below
commit ebf672e8760f856485a81597b988b43f965356f6
Author: Eric Norman <en...@apache.org>
AuthorDate: Wed Aug 20 11:11:33 2025 -0700
SLING-12898 Update to Parent 62 and apply spotless formatting (#27)
---
pom.xml | 195 +++---
.../usermanager/AuthorizablePrivilegesInfo.java | 81 ++-
.../jackrabbit/usermanager/ChangeUserPassword.java | 24 +-
.../sling/jackrabbit/usermanager/CreateGroup.java | 28 +-
.../sling/jackrabbit/usermanager/CreateUser.java | 42 +-
.../usermanager/DeleteAuthorizables.java | 17 +-
.../sling/jackrabbit/usermanager/DeleteGroup.java | 14 +-
.../sling/jackrabbit/usermanager/DeleteUser.java | 14 +-
.../usermanager/PrincipalNameFilter.java | 27 +-
.../usermanager/PrincipalNameGenerator.java | 33 +-
.../sling/jackrabbit/usermanager/UpdateGroup.java | 18 +-
.../sling/jackrabbit/usermanager/UpdateUser.java | 20 +-
.../impl/AuthorizableAdapterFactory.java | 39 +-
.../impl/AuthorizablePrivilegesInfoImpl.java | 263 +++----
.../impl/post/AbstractAuthorizablePostServlet.java | 280 ++++----
.../impl/post/AbstractGroupPostServlet.java | 70 +-
.../usermanager/impl/post/AbstractPostServlet.java | 153 ++---
.../impl/post/ChangeUserPasswordServlet.java | 158 ++---
.../usermanager/impl/post/CreateGroupServlet.java | 141 ++--
.../usermanager/impl/post/CreateUserServlet.java | 188 ++---
.../impl/post/DeleteAuthorizableServlet.java | 127 ++--
.../impl/post/PrincipalNameGeneratorImpl.java | 77 ++-
.../usermanager/impl/post/UpdateGroupServlet.java | 119 ++--
.../usermanager/impl/post/UpdateUserServlet.java | 114 ++--
.../impl/resource/AuthorizableResource.java | 59 +-
.../resource/AuthorizableResourceProvider.java | 196 +++---
.../impl/resource/AuthorizableValueMap.java | 37 +-
.../impl/resource/BaseAuthorizableValueMap.java | 67 +-
.../usermanager/impl/resource/BaseResource.java | 27 +-
.../impl/resource/NestedAuthorizableResource.java | 49 +-
.../impl/resource/NestedAuthorizableValueMap.java | 35 +-
.../impl/resource/PrincipalResource.java | 45 +-
.../sling/jackrabbit/usermanager/package-info.java | 2 -
.../resource/SystemUserManagerPaths.java | 31 +-
.../usermanager/resource/package-info.java | 2 -
.../AuthorizablePrivilegesInfoTest.java | 57 +-
.../impl/AuthorizableAdapterFactoryTest.java | 40 +-
.../post/AbstractAuthorizablePostServletTest.java | 178 ++---
.../impl/post/AbstractPostServletTest.java | 92 +--
.../impl/post/PrincipalNameGeneratorImplTest.java | 96 +--
.../impl/resource/LazyInputStreamTest.java | 45 +-
.../jcr/jackrabbit/usermanager/it/AceTools.java | 69 +-
.../it/AuthorizablePrivilegesInfoIT.java | 755 ++++++++++++++-------
.../sling/jcr/jackrabbit/usermanager/it/Retry.java | 4 +-
.../usermanager/it/UserManagerTestSupport.java | 164 +++--
.../it/post/AnonymousSelfRegistrationIT.java | 39 +-
.../usermanager/it/post/ChangeUserPasswordIT.java | 326 +++++----
.../usermanager/it/post/CreateGroupIT.java | 163 +++--
.../CreatePrincipalWithCustomNameGeneratorIT.java | 108 +--
.../usermanager/it/post/CreateUserIT.java | 179 ++---
.../it/post/CustomPostResponseCreatorImpl.java | 31 +-
.../it/post/CustomPrincipalNameFilterImpl.java | 34 +-
.../it/post/CustomPrincipalNameGeneratorImpl.java | 41 +-
.../usermanager/it/post/RemoveAuthorizablesIT.java | 137 ++--
.../post/SLING11259AuthorizablePropertiesIT.java | 127 ++--
.../usermanager/it/post/UpdateGroupIT.java | 90 +--
.../usermanager/it/post/UpdateUserIT.java | 140 ++--
.../it/post/UserManagerClientTestSupport.java | 200 +++---
.../usermanager/it/post/UserPrivilegesInfoIT.java | 79 +--
.../resource/AuthorizableResourceProviderIT.java | 208 +++---
.../it/resource/AuthorizableValueMapIT.java | 52 +-
.../it/resource/BaseAuthorizableResourcesIT.java | 22 +-
.../it/resource/BaseAuthorizableValueMapIT.java | 375 +++++++---
.../it/resource/NestedAuthorizableResourcesIT.java | 266 ++++----
.../it/resource/NestedAuthorizableValueMapIT.java | 22 +-
.../resource/NoNestedAuthorizableResourcesIT.java | 68 +-
.../it/resource/PrincipalResourcesIT.java | 74 +-
67 files changed, 3892 insertions(+), 3181 deletions(-)
diff --git a/pom.xml b/pom.xml
index cefefd4..ec64388 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
+<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
@@ -23,17 +23,22 @@
<parent>
<groupId>org.apache.sling</groupId>
<artifactId>sling-bundle-parent</artifactId>
- <version>52</version>
+ <version>62</version>
<relativePath />
</parent>
<artifactId>org.apache.sling.jcr.jackrabbit.usermanager</artifactId>
<version>3.0.0-SNAPSHOT</version>
<name>Apache Sling JCR Jackrabbit User Manager</name>
- <description>
- Provides ResourceProvider and POST operations for the Jackrabbit
- User Manager.
- </description>
+ <description>Provides ResourceProvider and POST operations for the Jackrabbit
+ User Manager.</description>
+
+ <scm>
+ <connection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-jcr-jackrabbit-usermanager.git</connection>
+ <developerConnection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-jcr-jackrabbit-usermanager.git</developerConnection>
+ <tag>HEAD</tag>
+ <url>https://github.com/apache/sling-org-apache-sling-jcr-jackrabbit-usermanager/tree/${project.scm.tag}</url>
+ </scm>
<properties>
<sling.java.version>17</sling.java.version>
@@ -42,59 +47,6 @@
<slf4j.version>2.0.17</slf4j.version>
</properties>
- <scm>
- <connection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-jcr-jackrabbit-usermanager.git</connection>
- <developerConnection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-jcr-jackrabbit-usermanager.git</developerConnection>
- <url>https://github.com/apache/sling-org-apache-sling-jcr-jackrabbit-usermanager.git</url>
- <tag>HEAD</tag>
- </scm>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.sling</groupId>
- <artifactId>sling-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>generate-adapter-metadata</id>
- <phase>process-classes</phase>
- <goals>
- <goal>generate-adapter-metadata</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
-
- <plugin>
- <groupId>biz.aQute.bnd</groupId>
- <artifactId>bnd-maven-plugin</artifactId>
- </plugin>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-failsafe-plugin</artifactId>
- <executions>
- <execution>
- <goals>
- <goal>integration-test</goal>
- <goal>verify</goal>
- </goals>
- </execution>
- </executions>
- <configuration>
- <redirectTestOutputToFile>true</redirectTestOutputToFile>
- <systemPropertyVariables>
- <bundle.filename>${basedir}/target/${project.build.finalName}.jar</bundle.filename>
- </systemPropertyVariables>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.servicemix.tooling</groupId>
- <artifactId>depends-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
-
<dependencies>
<dependency>
<groupId>org.osgi</groupId>
@@ -200,13 +152,12 @@
<optional>true</optional>
</dependency>
-
<!-- Sling Testing PaxExam -->
<dependency>
- <groupId>org.apache.sling</groupId>
- <artifactId>org.apache.sling.testing.paxexam</artifactId>
- <version>4.1.2</version>
- <scope>test</scope>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.testing.paxexam</artifactId>
+ <version>4.1.2</version>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.sling</groupId>
@@ -217,17 +168,17 @@
<!-- an OSGi framework -->
<dependency>
- <groupId>org.apache.felix</groupId>
- <artifactId>org.apache.felix.framework</artifactId>
- <version>7.0.5</version>
- <scope>test</scope>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>org.apache.felix.framework</artifactId>
+ <version>7.0.5</version>
+ <scope>test</scope>
</dependency>
<!-- JUnit -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
@@ -238,39 +189,39 @@
<!-- Pax Exam -->
<dependency>
- <groupId>org.ops4j.pax.exam</groupId>
- <artifactId>pax-exam</artifactId>
- <version>${org.ops4j.pax.exam.version}</version>
- <scope>test</scope>
+ <groupId>org.ops4j.pax.exam</groupId>
+ <artifactId>pax-exam</artifactId>
+ <version>${org.ops4j.pax.exam.version}</version>
+ <scope>test</scope>
</dependency>
<dependency>
- <groupId>org.ops4j.pax.exam</groupId>
- <artifactId>pax-exam-cm</artifactId>
- <version>${org.ops4j.pax.exam.version}</version>
- <scope>test</scope>
+ <groupId>org.ops4j.pax.exam</groupId>
+ <artifactId>pax-exam-cm</artifactId>
+ <version>${org.ops4j.pax.exam.version}</version>
+ <scope>test</scope>
</dependency>
<dependency>
- <groupId>org.ops4j.pax.exam</groupId>
- <artifactId>pax-exam-container-forked</artifactId>
- <version>${org.ops4j.pax.exam.version}</version>
- <scope>test</scope>
+ <groupId>org.ops4j.pax.exam</groupId>
+ <artifactId>pax-exam-container-forked</artifactId>
+ <version>${org.ops4j.pax.exam.version}</version>
+ <scope>test</scope>
</dependency>
<dependency>
- <groupId>org.ops4j.pax.exam</groupId>
- <artifactId>pax-exam-junit4</artifactId>
- <version>${org.ops4j.pax.exam.version}</version>
- <scope>test</scope>
+ <groupId>org.ops4j.pax.exam</groupId>
+ <artifactId>pax-exam-junit4</artifactId>
+ <version>${org.ops4j.pax.exam.version}</version>
+ <scope>test</scope>
</dependency>
<dependency>
- <groupId>org.ops4j.pax.exam</groupId>
- <artifactId>pax-exam-link-mvn</artifactId>
- <version>${org.ops4j.pax.exam.version}</version>
- <scope>test</scope>
+ <groupId>org.ops4j.pax.exam</groupId>
+ <artifactId>pax-exam-link-mvn</artifactId>
+ <version>${org.ops4j.pax.exam.version}</version>
+ <scope>test</scope>
</dependency>
<dependency>
- <groupId>javax.inject</groupId>
- <artifactId>javax.inject</artifactId>
- <scope>test</scope>
+ <groupId>javax.inject</groupId>
+ <artifactId>javax.inject</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
@@ -278,10 +229,10 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
- <version>${slf4j.version}</version>
- <scope>test</scope>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
+ <version>${slf4j.version}</version>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.felix</groupId>
@@ -296,7 +247,7 @@
</exclusion>
</exclusions>
</dependency>
- <dependency>
+ <dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>4.3.0</version>
@@ -328,6 +279,52 @@
<scope>test</scope>
</dependency>
</dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>sling-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>generate-adapter-metadata</id>
+ <goals>
+ <goal>generate-adapter-metadata</goal>
+ </goals>
+ <phase>process-classes</phase>
+ </execution>
+ </executions>
+ </plugin>
+
+ <plugin>
+ <groupId>biz.aQute.bnd</groupId>
+ <artifactId>bnd-maven-plugin</artifactId>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-failsafe-plugin</artifactId>
+ <configuration>
+ <redirectTestOutputToFile>true</redirectTestOutputToFile>
+ <systemPropertyVariables>
+ <bundle.filename>${basedir}/target/${project.build.finalName}.jar</bundle.filename>
+ </systemPropertyVariables>
+ </configuration>
+ <executions>
+ <execution>
+ <goals>
+ <goal>integration-test</goal>
+ <goal>verify</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.servicemix.tooling</groupId>
+ <artifactId>depends-maven-plugin</artifactId>
+ </plugin>
+ </plugins>
+ </build>
<profiles>
<profile>
<id>jacoco-report</id>
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/AuthorizablePrivilegesInfo.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/AuthorizablePrivilegesInfo.java
index ff03cf8..5ebf165 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/AuthorizablePrivilegesInfo.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/AuthorizablePrivilegesInfo.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.jackrabbit.usermanager;
@@ -31,22 +33,22 @@ public interface AuthorizablePrivilegesInfo {
* @deprecated use {@link #ADD_PROPERTY} instead
*/
@Deprecated
- addProperty, //NOSONAR
+ addProperty, // NOSONAR
/**
* @deprecated use {@link #ADD_NESTED_PROPERTY} instead
*/
@Deprecated
- addNestedProperty, //NOSONAR
+ addNestedProperty, // NOSONAR
/**
* @deprecated use {@link #ALTER_PROPERTY} instead
*/
@Deprecated
- alterProperty, //NOSONAR
+ alterProperty, // NOSONAR
/**
* @deprecated use {@link #REMOVE_PROPERTY} instead
*/
@Deprecated
- removeProperty, //NOSONAR
+ removeProperty, // NOSONAR
ADD_PROPERTY,
ADD_NESTED_PROPERTY,
@@ -62,13 +64,13 @@ public interface AuthorizablePrivilegesInfo {
*/
public static PropertyUpdateTypes convertDeprecated(PropertyUpdateTypes updateType) {
PropertyUpdateTypes converted = null;
- if (addProperty.equals(updateType)) { //NOSONAR
+ if (addProperty.equals(updateType)) { // NOSONAR
converted = ADD_PROPERTY;
- } else if (addNestedProperty.equals(updateType)) { //NOSONAR
+ } else if (addNestedProperty.equals(updateType)) { // NOSONAR
converted = ADD_NESTED_PROPERTY;
- } else if (alterProperty.equals(updateType)) { //NOSONAR
+ } else if (alterProperty.equals(updateType)) { // NOSONAR
converted = ALTER_PROPERTY;
- } else if (removeProperty.equals(updateType)) { //NOSONAR
+ } else if (removeProperty.equals(updateType)) { // NOSONAR
converted = REMOVE_PROPERTY;
}
@@ -84,7 +86,7 @@ public interface AuthorizablePrivilegesInfo {
/**
* Checks whether the current user has been granted privileges
* to add a new user.
- *
+ *
* @param jcrSession the JCR session of the current user
* @return true if the current user has the privileges, false otherwise
*/
@@ -93,23 +95,22 @@ public interface AuthorizablePrivilegesInfo {
/**
* Checks whether the current user has been granted privileges
* to add a new group.
- *
+ *
* @param jcrSession the JCR session of the current user
* @return true if the current user has the privileges, false otherwise
*/
boolean canAddGroup(Session jcrSession);
-
+
/**
* Checks whether the current user has been granted privileges
* to update the properties of the specified user or group.
* Equivalent of: #canUpdateProperties(Session, String, PropertyUpdateTypes.addProperty, PropertyUpdateTypes.addNestedProperty, PropertyUpdateTypes.alterProperty, PropertyUpdateTypes.removeProperty)
- *
+ *
* @param jcrSession the JCR session of the current user
* @param principalId the user or group id to check
* @return true if the current user has the privileges, false otherwise
*/
- boolean canUpdateProperties(Session jcrSession,
- String principalId);
+ boolean canUpdateProperties(Session jcrSession, String principalId);
/**
* Checks whether the current user has been granted privileges
@@ -120,32 +121,30 @@ public interface AuthorizablePrivilegesInfo {
* @param propertyUpdateTypes specify the types of property updates that may be supplied. See: {@link PropertyUpdateTypes}
* @return true if the current user has the privileges, false otherwise
*/
- default boolean canUpdateProperties(Session jcrSession,
- String principalId, PropertyUpdateTypes ... propertyUpdateTypes) {
+ default boolean canUpdateProperties(
+ Session jcrSession, String principalId, PropertyUpdateTypes... propertyUpdateTypes) {
throw new UnsupportedOperationException();
}
/**
* Checks whether the current user has been granted privileges
* to remove the specified user or group.
- *
+ *
* @param jcrSession the JCR session of the current user
* @param principalId the user or group id to check
* @return true if the current user has the privileges, false otherwise
*/
- boolean canRemove(Session jcrSession,
- String principalId);
-
+ boolean canRemove(Session jcrSession, String principalId);
+
/**
* Checks whether the current user has been granted privileges
* to update the membership of the specified group.
- *
+ *
* @param jcrSession the JCR session of the current user
* @param groupId the group id to check
* @return true if the current user has the privileges, false otherwise
*/
- boolean canUpdateGroupMembers(Session jcrSession,
- String groupId);
+ boolean canUpdateGroupMembers(Session jcrSession, String groupId);
/**
* Checks whether the current user has been granted privileges
@@ -155,8 +154,7 @@ public interface AuthorizablePrivilegesInfo {
* @param userId the user id to check
* @return true if the current user has the privileges, false otherwise
*/
- default boolean canDisable(Session jcrSession,
- String userId) {
+ default boolean canDisable(Session jcrSession, String userId) {
throw new UnsupportedOperationException();
}
@@ -168,8 +166,7 @@ public interface AuthorizablePrivilegesInfo {
* @param userId the user id to check
* @return true if the current user has the privileges, false otherwise
*/
- default boolean canChangePassword(Session jcrSession,
- String userId) {
+ default boolean canChangePassword(Session jcrSession, String userId) {
throw new UnsupportedOperationException();
}
@@ -182,9 +179,7 @@ public interface AuthorizablePrivilegesInfo {
* @param userId the user id to check
* @return true if the current user has the privileges, false otherwise
*/
- default boolean canChangePasswordWithoutOldPassword(@NotNull Session jcrSession,
- @NotNull String userId) {
+ default boolean canChangePasswordWithoutOldPassword(@NotNull Session jcrSession, @NotNull String userId) {
throw new UnsupportedOperationException();
}
-
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/ChangeUserPassword.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/ChangeUserPassword.java
index 4c8dce5..c681aa2 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/ChangeUserPassword.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/ChangeUserPassword.java
@@ -18,11 +18,11 @@
*/
package org.apache.sling.jackrabbit.usermanager;
-import java.util.List;
-
import javax.jcr.RepositoryException;
import javax.jcr.Session;
+import java.util.List;
+
import org.apache.jackrabbit.api.security.user.User;
import org.apache.sling.servlets.post.Modification;
@@ -32,14 +32,14 @@ import org.apache.sling.servlets.post.Modification;
* This interface is not intended to be implemented by bundles. It is
* implemented by this bundle and may be used by client bundles.
* </p>
- *
+ *
* @since 2.2.0
*/
public interface ChangeUserPassword {
/**
* Update the password of a user in the repository
- *
+ *
* @param jcrSession the JCR session of the user updating the user
* @param name The name of the user to update (required)
* @param oldPassword The current password of the user (required for non-admin users)
@@ -49,12 +49,12 @@ public interface ChangeUserPassword {
* @return the user whose password was changed
* @throws RepositoryException if password can't be changed for some reason
*/
- public User changePassword(Session jcrSession,
- String name,
- String oldPassword,
- String newPassword,
- String newPasswordConfirm,
- List<Modification> changes
- ) throws RepositoryException;
-
+ public User changePassword(
+ Session jcrSession,
+ String name,
+ String oldPassword,
+ String newPassword,
+ String newPasswordConfirm,
+ List<Modification> changes)
+ throws RepositoryException;
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/CreateGroup.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/CreateGroup.java
index bf16611..3c7db5e 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/CreateGroup.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/CreateGroup.java
@@ -18,12 +18,12 @@
*/
package org.apache.sling.jackrabbit.usermanager;
-import java.util.List;
-import java.util.Map;
-
import javax.jcr.RepositoryException;
import javax.jcr.Session;
+import java.util.List;
+import java.util.Map;
+
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.sling.servlets.post.Modification;
@@ -33,14 +33,14 @@ import org.apache.sling.servlets.post.Modification;
* This interface is not intended to be implemented by bundles. It is
* implemented by this bundle and may be used by client bundles.
* </p>
- *
+ *
* @since 2.2.0
*/
public interface CreateGroup {
/**
* Create a new group for the repository
- *
+ *
* @param jcrSession the JCR session of the user creating the group
* @param name The name of the new group. If null or empty, the name is calculated from the supplied properties (per SLING-10902).
* @param properties Extra properties to update on the group. The entry values should be either a String or String[] (optional)
@@ -48,27 +48,21 @@ public interface CreateGroup {
* @return the group that was created
* @throws RepositoryException if group can't be created
*/
- public Group createGroup(Session jcrSession,
- String name,
- Map<String, ?> properties,
- List<Modification> changes
- ) throws RepositoryException;
+ public Group createGroup(Session jcrSession, String name, Map<String, ?> properties, List<Modification> changes)
+ throws RepositoryException;
/**
- * Create a new group for the repository. The name is calculated from the
+ * Create a new group for the repository. The name is calculated from the
* supplied properties (per SLING-10902).
- *
+ *
* @param jcrSession the JCR session of the user creating the group
* @param properties Extra properties to update on the group. The entry values should be either a String or String[] (optional)
* @param changes The list of changes for this operation (optional)
* @return the group that was created
* @throws RepositoryException if group can't be created
*/
- public default Group createGroup(Session jcrSession,
- Map<String, ?> properties,
- List<Modification> changes
- ) throws RepositoryException {
+ public default Group createGroup(Session jcrSession, Map<String, ?> properties, List<Modification> changes)
+ throws RepositoryException {
return createGroup(jcrSession, null, properties, changes);
}
-
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/CreateUser.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/CreateUser.java
index 28e1118..c7513b3 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/CreateUser.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/CreateUser.java
@@ -18,12 +18,12 @@
*/
package org.apache.sling.jackrabbit.usermanager;
-import java.util.List;
-import java.util.Map;
-
import javax.jcr.RepositoryException;
import javax.jcr.Session;
+import java.util.List;
+import java.util.Map;
+
import org.apache.jackrabbit.api.security.user.User;
import org.apache.sling.servlets.post.Modification;
@@ -33,14 +33,14 @@ import org.apache.sling.servlets.post.Modification;
* This interface is not intended to be implemented by bundles. It is
* implemented by this bundle and may be used by client bundles.
* </p>
- *
+ *
* @since 2.2.0
*/
public interface CreateUser {
/**
* Create a new user for the repository
- *
+ *
* @param jcrSession the JCR session of the user creating the user
* @param name The name of the new user. If null or empty, the name is calculated from the supplied properties (per SLING-10902).
* @param password The password of the new user (required)
@@ -50,18 +50,19 @@ public interface CreateUser {
* @return the user that was created
* @throws RepositoryException if user can't be created
*/
- public User createUser(Session jcrSession,
- String name,
- String password,
- String passwordConfirm,
- Map<String, ?> properties,
- List<Modification> changes
- ) throws RepositoryException;
+ public User createUser(
+ Session jcrSession,
+ String name,
+ String password,
+ String passwordConfirm,
+ Map<String, ?> properties,
+ List<Modification> changes)
+ throws RepositoryException;
/**
- * Create a new user for the repository. The name is calculated from the
+ * Create a new user for the repository. The name is calculated from the
* supplied properties (per SLING-10902).
- *
+ *
* @param jcrSession the JCR session of the user creating the user
* @param password The password of the new user (required)
* @param passwordConfirm The password of the new user again (required)
@@ -70,12 +71,13 @@ public interface CreateUser {
* @return the user that was created
* @throws RepositoryException if user can't be created
*/
- public default User createUser(Session jcrSession,
- String password,
- String passwordConfirm,
- Map<String, ?> properties,
- List<Modification> changes
- ) throws RepositoryException {
+ public default User createUser(
+ Session jcrSession,
+ String password,
+ String passwordConfirm,
+ Map<String, ?> properties,
+ List<Modification> changes)
+ throws RepositoryException {
return createUser(jcrSession, null, password, passwordConfirm, properties, changes);
}
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/DeleteAuthorizables.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/DeleteAuthorizables.java
index 27923e3..f50c80f 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/DeleteAuthorizables.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/DeleteAuthorizables.java
@@ -18,11 +18,11 @@
*/
package org.apache.sling.jackrabbit.usermanager;
-import java.util.List;
-
import javax.jcr.RepositoryException;
import javax.jcr.Session;
+import java.util.List;
+
import org.apache.sling.api.resource.Resource;
import org.apache.sling.servlets.post.Modification;
@@ -32,24 +32,21 @@ import org.apache.sling.servlets.post.Modification;
* This interface is not intended to be implemented by bundles. It is
* implemented by this bundle and may be used by client bundles.
* </p>
- *
+ *
* @since 2.2.0
*/
public interface DeleteAuthorizables {
/**
* Deletes one or more users or groups from the repository
- *
+ *
* @param jcrSession the JCR session of the user creating the user
* @param baseResource the base resource to calculate the relative paths from (required)
* @param paths An array of relative resource paths to Authorizables to be deleted (required)
* @param changes The list of changes for this operation (optional)
* @throws RepositoryException if authorizable (user or group) can't be deleted
*/
- public void deleteAuthorizables(Session jcrSession,
- Resource baseResource,
- String [] paths,
- List<Modification> changes
- ) throws RepositoryException;
-
+ public void deleteAuthorizables(
+ Session jcrSession, Resource baseResource, String[] paths, List<Modification> changes)
+ throws RepositoryException;
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/DeleteGroup.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/DeleteGroup.java
index 297d66b..223c505 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/DeleteGroup.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/DeleteGroup.java
@@ -18,11 +18,11 @@
*/
package org.apache.sling.jackrabbit.usermanager;
-import java.util.List;
-
import javax.jcr.RepositoryException;
import javax.jcr.Session;
+import java.util.List;
+
import org.apache.sling.servlets.post.Modification;
/**
@@ -31,22 +31,18 @@ import org.apache.sling.servlets.post.Modification;
* This interface is not intended to be implemented by bundles. It is
* implemented by this bundle and may be used by client bundles.
* </p>
- *
+ *
* @since 2.2.0
*/
public interface DeleteGroup {
/**
* Deletes a group from the repository
- *
+ *
* @param jcrSession the JCR session of the user creating the user
* @param name The name of the group to delete (required)
* @param changes The list of changes for this operation (optional)
* @throws RepositoryException if group can't be deleted
*/
- public void deleteGroup(Session jcrSession,
- String name,
- List<Modification> changes
- ) throws RepositoryException;
-
+ public void deleteGroup(Session jcrSession, String name, List<Modification> changes) throws RepositoryException;
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/DeleteUser.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/DeleteUser.java
index 2d60690..a22c5ce 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/DeleteUser.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/DeleteUser.java
@@ -18,11 +18,11 @@
*/
package org.apache.sling.jackrabbit.usermanager;
-import java.util.List;
-
import javax.jcr.RepositoryException;
import javax.jcr.Session;
+import java.util.List;
+
import org.apache.sling.servlets.post.Modification;
/**
@@ -31,22 +31,18 @@ import org.apache.sling.servlets.post.Modification;
* This interface is not intended to be implemented by bundles. It is
* implemented by this bundle and may be used by client bundles.
* </p>
- *
+ *
* @since 2.2.0
*/
public interface DeleteUser {
/**
* Deletes a user from the repository
- *
+ *
* @param jcrSession the JCR session of the user creating the user
* @param name The name of the user to delete (required)
* @param changes The list of changes for this operation (optional)
* @throws RepositoryException if user can't be deleted
*/
- public void deleteUser(Session jcrSession,
- String name,
- List<Modification> changes
- ) throws RepositoryException;
-
+ public void deleteUser(Session jcrSession, String name, List<Modification> changes) throws RepositoryException;
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/PrincipalNameFilter.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/PrincipalNameFilter.java
index 6437f7d..a7e4084 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/PrincipalNameFilter.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/PrincipalNameFilter.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.jackrabbit.usermanager;
@@ -28,5 +30,4 @@ public interface PrincipalNameFilter {
* @return the filtered value
*/
String filter(String principalName);
-
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/PrincipalNameGenerator.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/PrincipalNameGenerator.java
index 6453d2b..ae7de2c 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/PrincipalNameGenerator.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/PrincipalNameGenerator.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.jackrabbit.usermanager;
@@ -47,13 +49,14 @@ public interface PrincipalNameGenerator {
*
* @param parameters the current request parameters map
* @param type the type of principal
- * @param principalNameFilter for filtering what characters are allowed in a name
+ * @param principalNameFilter for filtering what characters are allowed in a name
* @param defaultPrincipalNameGenerator the default principal name generator
*
* @return the info about the principal name to be created or null if unable to do so
*/
- public NameInfo getPrincipalName(Map<String, ?> parameters, AuthorizableType type,
+ public NameInfo getPrincipalName(
+ Map<String, ?> parameters,
+ AuthorizableType type,
PrincipalNameFilter principalNameFilter,
PrincipalNameGenerator defaultPrincipalNameGenerator);
-
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/UpdateGroup.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/UpdateGroup.java
index faa30ae..a8bcb8b 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/UpdateGroup.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/UpdateGroup.java
@@ -18,12 +18,12 @@
*/
package org.apache.sling.jackrabbit.usermanager;
-import java.util.List;
-import java.util.Map;
-
import javax.jcr.RepositoryException;
import javax.jcr.Session;
+import java.util.List;
+import java.util.Map;
+
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.sling.servlets.post.Modification;
@@ -33,14 +33,14 @@ import org.apache.sling.servlets.post.Modification;
* This interface is not intended to be implemented by bundles. It is
* implemented by this bundle and may be used by client bundles.
* </p>
- *
+ *
* @since 2.2.0
*/
public interface UpdateGroup {
/**
* Update a group in the repository
- *
+ *
* @param jcrSession the JCR session of the user creating the group
* @param name The name of the group to update (required)
* @param properties Extra properties to update on the group. The entry values should be either a String or String[] (optional)
@@ -48,10 +48,6 @@ public interface UpdateGroup {
* @return the group that was updated or null if not found
* @throws RepositoryException if group can't be updated
*/
- public Group updateGroup(Session jcrSession,
- String name,
- Map<String, ?> properties,
- List<Modification> changes
- ) throws RepositoryException;
-
+ public Group updateGroup(Session jcrSession, String name, Map<String, ?> properties, List<Modification> changes)
+ throws RepositoryException;
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/UpdateUser.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/UpdateUser.java
index 65a6032..7d8f7a7 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/UpdateUser.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/UpdateUser.java
@@ -18,12 +18,12 @@
*/
package org.apache.sling.jackrabbit.usermanager;
-import java.util.List;
-import java.util.Map;
-
import javax.jcr.RepositoryException;
import javax.jcr.Session;
+import java.util.List;
+import java.util.Map;
+
import org.apache.jackrabbit.api.security.user.User;
import org.apache.sling.servlets.post.Modification;
@@ -33,25 +33,21 @@ import org.apache.sling.servlets.post.Modification;
* This interface is not intended to be implemented by bundles. It is
* implemented by this bundle and may be used by client bundles.
* </p>
- *
+ *
* @since 2.2.0
*/
public interface UpdateUser {
/**
* Update a user in the repository
- *
+ *
* @param jcrSession the JCR session of the user updating the user
* @param name The name of the user to update (required)
* @param properties Extra properties to update on the user. The entry values should be either a String or String[] (optional)
* @param changes The list of changes for this operation (optional)
- * @return the user that was updated or null if not found
+ * @return the user that was updated or null if not found
* @throws RepositoryException if user can't be updated
*/
- public User updateUser(Session jcrSession,
- String name,
- Map<String, ?> properties,
- List<Modification> changes
- ) throws RepositoryException;
-
+ public User updateUser(Session jcrSession, String name, Map<String, ?> properties, List<Modification> changes)
+ throws RepositoryException;
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/AuthorizableAdapterFactory.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/AuthorizableAdapterFactory.java
index 00b0d99..90a771a 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/AuthorizableAdapterFactory.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/AuthorizableAdapterFactory.java
@@ -1,20 +1,21 @@
/*
- * 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.jackrabbit.usermanager.impl;
import javax.jcr.RepositoryException;
@@ -29,10 +30,13 @@ import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@Component(service = AdapterFactory.class, property = {
- AdapterFactory.ADAPTER_CLASSES + "=org.apache.jackrabbit.api.security.user.User",
- AdapterFactory.ADAPTER_CLASSES + "=org.apache.jackrabbit.api.security.user.Authorizable",
- AdapterFactory.ADAPTABLE_CLASSES + "=org.apache.sling.api.resource.ResourceResolver" })
+@Component(
+ service = AdapterFactory.class,
+ property = {
+ AdapterFactory.ADAPTER_CLASSES + "=org.apache.jackrabbit.api.security.user.User",
+ AdapterFactory.ADAPTER_CLASSES + "=org.apache.jackrabbit.api.security.user.Authorizable",
+ AdapterFactory.ADAPTABLE_CLASSES + "=org.apache.sling.api.resource.ResourceResolver"
+ })
public class AuthorizableAdapterFactory implements AdapterFactory {
/**
@@ -54,5 +58,4 @@ public class AuthorizableAdapterFactory implements AdapterFactory {
}
return null;
}
-
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/AuthorizablePrivilegesInfoImpl.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/AuthorizablePrivilegesInfoImpl.java
index acd1295..a8c79b8 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/AuthorizablePrivilegesInfoImpl.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/AuthorizablePrivilegesInfoImpl.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.jackrabbit.usermanager.impl;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.security.AccessControlManager;
import javax.jcr.security.Privilege;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
@@ -49,7 +51,7 @@ import org.slf4j.LoggerFactory;
/**
* Helper class to assist in the usage of access control of users/groups from scripts.
- *
+ *
* The default access control policy defined by this provider has the following
* characteristics:
* <ul>
@@ -59,11 +61,14 @@ import org.slf4j.LoggerFactory;
* her/his group membership,</li>
* </ul>
*/
-@Component(service=AuthorizablePrivilegesInfo.class,
- property={
- AuthorizablePrivilegesInfoImpl.PAR_USER_ADMIN_GROUP_NAME + "=" + AuthorizablePrivilegesInfoImpl.DEFAULT_USER_ADMIN_GROUP_NAME,
- AuthorizablePrivilegesInfoImpl.PAR_GROUP_ADMIN_GROUP_NAME + "=" + AuthorizablePrivilegesInfoImpl.DEFAULT_GROUP_ADMIN_GROUP_NAME
- })
+@Component(
+ service = AuthorizablePrivilegesInfo.class,
+ property = {
+ AuthorizablePrivilegesInfoImpl.PAR_USER_ADMIN_GROUP_NAME + "="
+ + AuthorizablePrivilegesInfoImpl.DEFAULT_USER_ADMIN_GROUP_NAME,
+ AuthorizablePrivilegesInfoImpl.PAR_GROUP_ADMIN_GROUP_NAME + "="
+ + AuthorizablePrivilegesInfoImpl.DEFAULT_GROUP_ADMIN_GROUP_NAME
+ })
public class AuthorizablePrivilegesInfoImpl implements AuthorizablePrivilegesInfo {
/** default log */
@@ -75,9 +80,9 @@ public class AuthorizablePrivilegesInfoImpl implements AuthorizablePrivilegesInf
* @see #PAR_USER_ADMIN_GROUP_NAME
*/
static final String DEFAULT_USER_ADMIN_GROUP_NAME = "UserAdmin";
-
+
/**
- * The name of the configuration parameter providing the
+ * The name of the configuration parameter providing the
* 'User administrator' group name.
*/
static final String PAR_USER_ADMIN_GROUP_NAME = "user.admin.group.name";
@@ -88,9 +93,9 @@ public class AuthorizablePrivilegesInfoImpl implements AuthorizablePrivilegesInf
* @see #PAR_GROUP_ADMIN_GROUP_NAME
*/
static final String DEFAULT_GROUP_ADMIN_GROUP_NAME = "GroupAdmin";
-
+
/**
- * The name of the configuration parameter providing the
+ * The name of the configuration parameter providing the
* 'Group administrator' group name.
*/
static final String PAR_GROUP_ADMIN_GROUP_NAME = "group.admin.group.name";
@@ -101,38 +106,43 @@ public class AuthorizablePrivilegesInfoImpl implements AuthorizablePrivilegesInf
private boolean allowSelfChangePassword = false;
private String userAdminGroupName;
- @Reference(cardinality=ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC)
+ @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC)
private void bindChangeUserPassword(ChangeUserPassword changeUserPassword, Map<String, Object> properties) {
if (properties.containsKey("alwaysAllowSelfChangePassword")) {
// log warning about the wrong property name
- log.warn("Obsolete 'alwaysAllowSelfChangePassword' configuration key was detected for the bound ChangeUserPassword component. Please change that key in your configuration to 'allowSelfChangePassword'.");
+ log.warn(
+ "Obsolete 'alwaysAllowSelfChangePassword' configuration key was detected for the bound ChangeUserPassword component. Please change that key in your configuration to 'allowSelfChangePassword'.");
allowSelfChangePassword = OsgiUtil.toBoolean(properties.get("alwaysAllowSelfChangePassword"), false);
} else {
allowSelfChangePassword = OsgiUtil.toBoolean(properties.get("allowSelfChangePassword"), false);
}
- userAdminGroupName = OsgiUtil.toString(properties.get(PAR_USER_ADMIN_GROUP_NAME), DEFAULT_USER_ADMIN_GROUP_NAME);
+ userAdminGroupName =
+ OsgiUtil.toString(properties.get(PAR_USER_ADMIN_GROUP_NAME), DEFAULT_USER_ADMIN_GROUP_NAME);
}
+
@SuppressWarnings("unused")
private void unbindChangeUserPassword(ChangeUserPassword changeUserPassword, Map<String, Object> properties) {
allowSelfChangePassword = false;
}
-
- @Reference(cardinality=ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC)
+
+ @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC)
private void bindUserConfiguration(UserConfiguration userConfig, Map<String, Object> properties) {
- usersPath = (String)properties.get(UserConstants.PARAM_USER_PATH);
- groupsPath = (String)properties.get(UserConstants.PARAM_GROUP_PATH);
+ usersPath = (String) properties.get(UserConstants.PARAM_USER_PATH);
+ groupsPath = (String) properties.get(UserConstants.PARAM_GROUP_PATH);
}
+
@SuppressWarnings("unused")
private void unbindUserConfiguration(UserConfiguration userConfig, Map<String, Object> properties) {
usersPath = null;
groupsPath = null;
}
- @Reference(cardinality=ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC)
+ @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC)
private void bindCreateUser(CreateUser createUser, Map<String, Object> properties) {
selfRegistrationEnabled = Boolean.TRUE.equals(properties.get("self.registration.enabled"));
}
+
@SuppressWarnings("unused")
private void unbindCreateUser(CreateUser createUser, Map<String, Object> properties) {
selfRegistrationEnabled = false;
@@ -144,22 +154,22 @@ public class AuthorizablePrivilegesInfoImpl implements AuthorizablePrivilegesInf
public boolean canAddGroup(Session jcrSession) {
boolean hasRights = false;
try {
- UserManager userManager = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager userManager = ((JackrabbitSession) jcrSession).getUserManager();
Authorizable currentUserAuthorizable = userManager.getAuthorizable(jcrSession.getUserID());
if (currentUserAuthorizable instanceof User currentUser && currentUser.isAdmin()) {
- hasRights = true; //admin user has full control
+ hasRights = true; // admin user has full control
} else {
if (groupsPath != null) {
- //check if the non-admin user has sufficient rights on the home folder
+ // check if the non-admin user has sufficient rights on the home folder
AccessControlManager acm = jcrSession.getAccessControlManager();
hasRights = acm.hasPrivileges(groupsPath, new Privilege[] {
- acm.privilegeFromName(Privilege.JCR_READ),
- acm.privilegeFromName(Privilege.JCR_READ_ACCESS_CONTROL),
- acm.privilegeFromName(Privilege.JCR_MODIFY_ACCESS_CONTROL),
- acm.privilegeFromName(PrivilegeConstants.REP_WRITE),
- acm.privilegeFromName(PrivilegeConstants.REP_USER_MANAGEMENT)
- });
+ acm.privilegeFromName(Privilege.JCR_READ),
+ acm.privilegeFromName(Privilege.JCR_READ_ACCESS_CONTROL),
+ acm.privilegeFromName(Privilege.JCR_MODIFY_ACCESS_CONTROL),
+ acm.privilegeFromName(PrivilegeConstants.REP_WRITE),
+ acm.privilegeFromName(PrivilegeConstants.REP_USER_MANAGEMENT)
+ });
}
}
} catch (RepositoryException e) {
@@ -174,25 +184,25 @@ public class AuthorizablePrivilegesInfoImpl implements AuthorizablePrivilegesInf
public boolean canAddUser(Session jcrSession) {
boolean hasRights = false;
try {
- //if self-registration is enabled, then anyone can create a user
+ // if self-registration is enabled, then anyone can create a user
if (selfRegistrationEnabled) {
hasRights = true;
} else {
- UserManager userManager = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager userManager = ((JackrabbitSession) jcrSession).getUserManager();
Authorizable currentUserAuthorizable = userManager.getAuthorizable(jcrSession.getUserID());
if (currentUserAuthorizable instanceof User currentUser && currentUser.isAdmin()) {
- hasRights = true; //admin user has full control
+ hasRights = true; // admin user has full control
} else {
if (usersPath != null) {
- //check if the non-admin user has sufficient rights on the home folder
+ // check if the non-admin user has sufficient rights on the home folder
AccessControlManager acm = jcrSession.getAccessControlManager();
hasRights = acm.hasPrivileges(usersPath, new Privilege[] {
- acm.privilegeFromName(Privilege.JCR_READ),
- acm.privilegeFromName(Privilege.JCR_READ_ACCESS_CONTROL),
- acm.privilegeFromName(Privilege.JCR_MODIFY_ACCESS_CONTROL),
- acm.privilegeFromName(PrivilegeConstants.REP_WRITE),
- acm.privilegeFromName(PrivilegeConstants.REP_USER_MANAGEMENT)
- });
+ acm.privilegeFromName(Privilege.JCR_READ),
+ acm.privilegeFromName(Privilege.JCR_READ_ACCESS_CONTROL),
+ acm.privilegeFromName(Privilege.JCR_MODIFY_ACCESS_CONTROL),
+ acm.privilegeFromName(PrivilegeConstants.REP_WRITE),
+ acm.privilegeFromName(PrivilegeConstants.REP_USER_MANAGEMENT)
+ });
}
}
}
@@ -202,10 +212,14 @@ public class AuthorizablePrivilegesInfoImpl implements AuthorizablePrivilegesInf
return hasRights;
}
- protected boolean checkAuthorizablePath(Session jcrSession, String principalId,
- AuthorizableChecker authorizableChecker, AccessChecker accessChecker) throws RepositoryException {
+ protected boolean checkAuthorizablePath(
+ Session jcrSession,
+ String principalId,
+ AuthorizableChecker authorizableChecker,
+ AccessChecker accessChecker)
+ throws RepositoryException {
boolean hasRights = false;
- UserManager userManager = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager userManager = ((JackrabbitSession) jcrSession).getUserManager();
Authorizable currentUser = userManager.getAuthorizable(jcrSession.getUserID());
Authorizable authorizable = userManager.getAuthorizable(principalId);
@@ -217,8 +231,8 @@ public class AuthorizablePrivilegesInfoImpl implements AuthorizablePrivilegesInf
if (authorizableChecker != null && !authorizableChecker.isValid(authorizable)) {
// no rights, so skip the rest
} else {
- if (currentUser instanceof User u && u.isAdmin()){
- hasRights = true; //admin user has full control
+ if (currentUser instanceof User u && u.isAdmin()) {
+ hasRights = true; // admin user has full control
} else {
String path = authorizable.getPath();
if (accessChecker != null) {
@@ -237,15 +251,14 @@ public class AuthorizablePrivilegesInfoImpl implements AuthorizablePrivilegesInf
public boolean canRemove(Session jcrSession, String principalId) {
boolean hasRights = false;
try {
- hasRights = checkAuthorizablePath(jcrSession, principalId, null,
- path -> {
- //check if the non-admin user has sufficient rights on the home folder
- AccessControlManager acm = jcrSession.getAccessControlManager();
- return acm.hasPrivileges(path, new Privilege[] {
- acm.privilegeFromName(Privilege.JCR_READ),
- acm.privilegeFromName(PrivilegeConstants.REP_USER_MANAGEMENT)
- });
+ hasRights = checkAuthorizablePath(jcrSession, principalId, null, path -> {
+ // check if the non-admin user has sufficient rights on the home folder
+ AccessControlManager acm = jcrSession.getAccessControlManager();
+ return acm.hasPrivileges(path, new Privilege[] {
+ acm.privilegeFromName(Privilege.JCR_READ),
+ acm.privilegeFromName(PrivilegeConstants.REP_USER_MANAGEMENT)
});
+ });
} catch (RepositoryException e) {
log.warn("Failed to determine if {} can remove authorizable {}", jcrSession.getUserID(), principalId);
}
@@ -258,16 +271,14 @@ public class AuthorizablePrivilegesInfoImpl implements AuthorizablePrivilegesInf
public boolean canUpdateGroupMembers(Session jcrSession, String groupId) {
boolean hasRights = false;
try {
- hasRights = checkAuthorizablePath(jcrSession, groupId,
- Group.class::isInstance,
- path -> {
- //check if the non-admin user has sufficient rights on the home folder
- AccessControlManager acm = jcrSession.getAccessControlManager();
- return acm.hasPrivileges(path, new Privilege[] {
- acm.privilegeFromName(Privilege.JCR_READ),
- acm.privilegeFromName(PrivilegeConstants.REP_USER_MANAGEMENT)
- });
+ hasRights = checkAuthorizablePath(jcrSession, groupId, Group.class::isInstance, path -> {
+ // check if the non-admin user has sufficient rights on the home folder
+ AccessControlManager acm = jcrSession.getAccessControlManager();
+ return acm.hasPrivileges(path, new Privilege[] {
+ acm.privilegeFromName(Privilege.JCR_READ),
+ acm.privilegeFromName(PrivilegeConstants.REP_USER_MANAGEMENT)
});
+ });
} catch (RepositoryException e) {
log.warn("Failed to determine if {} can remove authorizable {}", jcrSession.getUserID(), groupId);
}
@@ -278,29 +289,32 @@ public class AuthorizablePrivilegesInfoImpl implements AuthorizablePrivilegesInf
* @see org.apache.sling.jackrabbit.usermanager.AuthorizablePrivilegesInfo#canUpdateProperties(javax.jcr.Session, java.lang.String)
*/
public boolean canUpdateProperties(Session jcrSession, String principalId) {
- return canUpdateProperties(jcrSession, principalId,
- PropertyUpdateTypes.ADD_PROPERTY, PropertyUpdateTypes.ADD_NESTED_PROPERTY,
- PropertyUpdateTypes.ALTER_PROPERTY, PropertyUpdateTypes.REMOVE_PROPERTY);
+ return canUpdateProperties(
+ jcrSession,
+ principalId,
+ PropertyUpdateTypes.ADD_PROPERTY,
+ PropertyUpdateTypes.ADD_NESTED_PROPERTY,
+ PropertyUpdateTypes.ALTER_PROPERTY,
+ PropertyUpdateTypes.REMOVE_PROPERTY);
}
/* (non-Javadoc)
* @see org.apache.sling.jackrabbit.usermanager.AuthorizablePrivilegesInfo#canUpdateProperties(javax.jcr.Session, java.lang.String, org.apache.sling.jackrabbit.usermanager.AuthorizablePrivilegesInfo.PropertyUpdateTypes[])
*/
@Override
- public boolean canUpdateProperties(Session jcrSession, String principalId,
- PropertyUpdateTypes... propertyUpdateTypes) {
+ public boolean canUpdateProperties(
+ Session jcrSession, String principalId, PropertyUpdateTypes... propertyUpdateTypes) {
boolean hasRights = false;
try {
- hasRights = checkAuthorizablePath(jcrSession, principalId, null,
- path -> {
- //check if the non-admin user has sufficient rights on the home folder
- AccessControlManager acm = jcrSession.getAccessControlManager();
- Set<Privilege> requiredPrivileges = new HashSet<>();
- requiredPrivileges.add(acm.privilegeFromName(Privilege.JCR_READ));
- if (propertyUpdateTypes != null) {
- for (PropertyUpdateTypes updateType : propertyUpdateTypes) {
- updateType = PropertyUpdateTypes.convertDeprecated(updateType);
- switch (updateType) {
+ hasRights = checkAuthorizablePath(jcrSession, principalId, null, path -> {
+ // check if the non-admin user has sufficient rights on the home folder
+ AccessControlManager acm = jcrSession.getAccessControlManager();
+ Set<Privilege> requiredPrivileges = new HashSet<>();
+ requiredPrivileges.add(acm.privilegeFromName(Privilege.JCR_READ));
+ if (propertyUpdateTypes != null) {
+ for (PropertyUpdateTypes updateType : propertyUpdateTypes) {
+ updateType = PropertyUpdateTypes.convertDeprecated(updateType);
+ switch (updateType) {
case ADD_NESTED_PROPERTY:
requiredPrivileges.add(acm.privilegeFromName(PrivilegeConstants.REP_ADD_PROPERTIES));
requiredPrivileges.add(acm.privilegeFromName(Privilege.JCR_ADD_CHILD_NODES));
@@ -317,14 +331,17 @@ public class AuthorizablePrivilegesInfoImpl implements AuthorizablePrivilegesInf
default:
log.warn("Unexpected property update type: {}", updateType);
break;
- }
}
}
+ }
- return acm.hasPrivileges(path, requiredPrivileges.toArray(new Privilege[requiredPrivileges.size()]));
- });
+ return acm.hasPrivileges(path, requiredPrivileges.toArray(new Privilege[requiredPrivileges.size()]));
+ });
} catch (RepositoryException e) {
- log.warn("Failed to determine if {} can update properties of authorizable {}", jcrSession.getUserID(), principalId);
+ log.warn(
+ "Failed to determine if {} can update properties of authorizable {}",
+ jcrSession.getUserID(),
+ principalId);
}
return hasRights;
}
@@ -336,16 +353,14 @@ public class AuthorizablePrivilegesInfoImpl implements AuthorizablePrivilegesInf
public boolean canDisable(Session jcrSession, String userId) {
boolean hasRights = false;
try {
- hasRights = checkAuthorizablePath(jcrSession, userId,
- User.class::isInstance,
- path -> {
- //check if the non-admin user has sufficient rights on the home folder
- AccessControlManager acm = jcrSession.getAccessControlManager();
- Set<Privilege> requiredPrivileges = new HashSet<>();
- requiredPrivileges.add(acm.privilegeFromName(Privilege.JCR_READ));
- requiredPrivileges.add(acm.privilegeFromName(PrivilegeConstants.REP_USER_MANAGEMENT));
- return acm.hasPrivileges(path, requiredPrivileges.toArray(new Privilege[requiredPrivileges.size()]));
- });
+ hasRights = checkAuthorizablePath(jcrSession, userId, User.class::isInstance, path -> {
+ // check if the non-admin user has sufficient rights on the home folder
+ AccessControlManager acm = jcrSession.getAccessControlManager();
+ Set<Privilege> requiredPrivileges = new HashSet<>();
+ requiredPrivileges.add(acm.privilegeFromName(Privilege.JCR_READ));
+ requiredPrivileges.add(acm.privilegeFromName(PrivilegeConstants.REP_USER_MANAGEMENT));
+ return acm.hasPrivileges(path, requiredPrivileges.toArray(new Privilege[requiredPrivileges.size()]));
+ });
} catch (RepositoryException e) {
log.warn("Failed to determine if {} can disable user {}", jcrSession.getUserID(), userId);
}
@@ -359,18 +374,22 @@ public class AuthorizablePrivilegesInfoImpl implements AuthorizablePrivilegesInf
public boolean canChangePassword(Session jcrSession, String userId) {
boolean hasRights = false;
try {
- hasRights = checkAuthorizablePath(jcrSession, userId,
- //system users and anonymous have no passwords
- authorizable -> authorizable instanceof User u &&
- !u.isSystemUser() && !"anonymous".equals(authorizable.getID()),
+ hasRights = checkAuthorizablePath(
+ jcrSession,
+ userId,
+ // system users and anonymous have no passwords
+ authorizable -> authorizable instanceof User u
+ && !u.isSystemUser()
+ && !"anonymous".equals(authorizable.getID()),
path -> {
boolean allowed = false;
- //check if the non-admin user has sufficient rights on the home folder
+ // check if the non-admin user has sufficient rights on the home folder
AccessControlManager acm = jcrSession.getAccessControlManager();
Set<Privilege> requiredPrivileges = new HashSet<>();
requiredPrivileges.add(acm.privilegeFromName(Privilege.JCR_READ));
requiredPrivileges.add(acm.privilegeFromName(PrivilegeConstants.REP_USER_MANAGEMENT));
- allowed = acm.hasPrivileges(path, requiredPrivileges.toArray(new Privilege[requiredPrivileges.size()]));
+ allowed = acm.hasPrivileges(
+ path, requiredPrivileges.toArray(new Privilege[requiredPrivileges.size()]));
if (!allowed && jcrSession.getUserID().equals(userId)) {
// check if the ChangeUserPassword service is configured to always allow
@@ -394,12 +413,14 @@ public class AuthorizablePrivilegesInfoImpl implements AuthorizablePrivilegesInf
try {
// can't change your own password without the old password
if (!jcrSession.getUserID().equals(userId)) {
- UserManager um = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager um = ((JackrabbitSession) jcrSession).getUserManager();
Authorizable currentAuthorizable = um.getAuthorizable(jcrSession.getUserID());
if (currentAuthorizable instanceof User currentUser) {
Authorizable targetAuthorizable = um.getAuthorizable(userId);
- //system users and anonymous have no passwords
- if (targetAuthorizable instanceof User targetUser && !targetUser.isSystemUser() && !"anonymous".equals(targetUser.getID())) {
+ // system users and anonymous have no passwords
+ if (targetAuthorizable instanceof User targetUser
+ && !targetUser.isSystemUser()
+ && !"anonymous".equals(targetUser.getID())) {
if (currentUser.isAdmin()) {
can = true;
} else if (userAdminGroupName != null) {
@@ -417,25 +438,31 @@ public class AuthorizablePrivilegesInfoImpl implements AuthorizablePrivilegesInf
return can;
}
-
// ---------- SCR Integration ----------------------------------------------
@Activate
protected void activate(BundleContext bundleContext, Map<String, Object> properties) {
String deprecatedUserAdminGroupName = OsgiUtil.toString(properties.get(PAR_USER_ADMIN_GROUP_NAME), null);
- if ( deprecatedUserAdminGroupName != null && ! DEFAULT_USER_ADMIN_GROUP_NAME.equals(deprecatedUserAdminGroupName)) {
- log.warn("Configuration setting for {} is deprecated and will not have any effect", PAR_USER_ADMIN_GROUP_NAME);
+ if (deprecatedUserAdminGroupName != null
+ && !DEFAULT_USER_ADMIN_GROUP_NAME.equals(deprecatedUserAdminGroupName)) {
+ log.warn(
+ "Configuration setting for {} is deprecated and will not have any effect",
+ PAR_USER_ADMIN_GROUP_NAME);
}
String deprecatedGroupAdminGroupName = OsgiUtil.toString(properties.get(PAR_GROUP_ADMIN_GROUP_NAME), null);
- if ( deprecatedGroupAdminGroupName != null && ! DEFAULT_GROUP_ADMIN_GROUP_NAME.equals(deprecatedUserAdminGroupName)) {
- log.warn("Configuration setting for {} is deprecated and will not have any effect", PAR_GROUP_ADMIN_GROUP_NAME);
+ if (deprecatedGroupAdminGroupName != null
+ && !DEFAULT_GROUP_ADMIN_GROUP_NAME.equals(deprecatedUserAdminGroupName)) {
+ log.warn(
+ "Configuration setting for {} is deprecated and will not have any effect",
+ PAR_GROUP_ADMIN_GROUP_NAME);
}
}
protected static interface AuthorizableChecker {
public boolean isValid(Authorizable authorizable) throws RepositoryException;
}
+
protected static interface AccessChecker {
public boolean hasRights(String path) throws RepositoryException;
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/AbstractAuthorizablePostServlet.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/AbstractAuthorizablePostServlet.java
index fdf0618..f2d9651 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/AbstractAuthorizablePostServlet.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/AbstractAuthorizablePostServlet.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.jackrabbit.usermanager.impl.post;
+import javax.jcr.AccessDeniedException;
+import javax.jcr.Node;
+import javax.jcr.PropertyType;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.Value;
+import javax.jcr.ValueFactory;
+import javax.jcr.nodetype.NodeType;
+import javax.jcr.nodetype.PropertyDefinition;
+
import java.security.SecureRandom;
import java.util.Calendar;
import java.util.Collection;
@@ -28,16 +40,6 @@ import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;
-import javax.jcr.AccessDeniedException;
-import javax.jcr.Node;
-import javax.jcr.PropertyType;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.Value;
-import javax.jcr.ValueFactory;
-import javax.jcr.nodetype.NodeType;
-import javax.jcr.nodetype.PropertyDefinition;
-
import org.apache.jackrabbit.JcrConstants;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
@@ -62,8 +64,7 @@ import org.slf4j.LoggerFactory;
/**
* Base class for all the POST servlets for the UserManager operations
*/
-public abstract class AbstractAuthorizablePostServlet extends
- AbstractPostServlet {
+public abstract class AbstractAuthorizablePostServlet extends AbstractPostServlet {
private static final long serialVersionUID = -5918670409789895333L;
private static final class PrincipalNameGeneratorHolder {
@@ -78,11 +79,12 @@ public abstract class AbstractAuthorizablePostServlet extends
public PrincipalNameGenerator getGenerator() {
return generator;
}
-
}
- protected static final String RP_NODE_NAME_VALUE_FROM = String.format("%s%s", SlingPostConstants.RP_NODE_NAME, SlingPostConstants.VALUE_FROM_SUFFIX);
- protected static final String RP_NODE_NAME_HINT_VALUE_FROM = String.format("%s%s", SlingPostConstants.RP_NODE_NAME_HINT, SlingPostConstants.VALUE_FROM_SUFFIX);
+ protected static final String RP_NODE_NAME_VALUE_FROM =
+ String.format("%s%s", SlingPostConstants.RP_NODE_NAME, SlingPostConstants.VALUE_FROM_SUFFIX);
+ protected static final String RP_NODE_NAME_HINT_VALUE_FROM =
+ String.format("%s%s", SlingPostConstants.RP_NODE_NAME_HINT, SlingPostConstants.VALUE_FROM_SUFFIX);
public static final String PROP_DATE_FORMAT = "servlet.post.dateFormats";
@@ -110,15 +112,16 @@ public abstract class AbstractAuthorizablePostServlet extends
/**
* Bind a new principal name generator
*/
-// @Reference(service = PrincipalNameGenerator.class)
- protected void bindPrincipalNameGenerator(final PrincipalNameGenerator generator, final Map<String, Object> properties) {
+ // @Reference(service = PrincipalNameGenerator.class)
+ protected void bindPrincipalNameGenerator(
+ final PrincipalNameGenerator generator, final Map<String, Object> properties) {
final PrincipalNameGeneratorHolder pngh = new PrincipalNameGeneratorHolder(generator, getRanking(properties));
synchronized (principalNameGenerators) {
this.principalNameGenerators.add(pngh);
- Collections.sort(this.principalNameGenerators, (o1, o2) ->
- Integer.compare(o1.ranking, o2.ranking));
+ Collections.sort(this.principalNameGenerators, (o1, o2) -> Integer.compare(o1.ranking, o2.ranking));
}
}
+
protected void unbindPrincipalNameGenerator(final PrincipalNameGenerator generator) {
synchronized (principalNameGenerators) {
principalNameGenerators.removeIf(h -> h.generator == generator);
@@ -128,10 +131,11 @@ public abstract class AbstractAuthorizablePostServlet extends
/**
* Bind a new principal name filter
*/
-// @Reference(service = PrincipalNameFilter.class)
+ // @Reference(service = PrincipalNameFilter.class)
protected void bindPrincipalNameFilter(final PrincipalNameFilter filter) {
this.principalNameFilter = filter;
}
+
protected void unbindPrincipalNameFilter(final PrincipalNameFilter filter) {
if (Objects.equals(filter, this.principalNameFilter)) {
this.principalNameFilter = null;
@@ -140,41 +144,43 @@ public abstract class AbstractAuthorizablePostServlet extends
/**
* Get or generate the name of the principal being created
- *
+ *
* @param jcrSession the JCR session
* @param properties the properties to consider when generating a name
* @param type the type of authorizable
* @return the principal name
*/
- protected String getOrGeneratePrincipalName(Session jcrSession, Map<String, ?> properties, AuthorizableType type) throws RepositoryException {
+ protected String getOrGeneratePrincipalName(Session jcrSession, Map<String, ?> properties, AuthorizableType type)
+ throws RepositoryException {
String principalName = null;
PrincipalNameGenerator defaultPrincipalNameGenerator = null;
PrincipalNameGenerator principalNameGenerator = null;
synchronized (principalNameGenerators) {
if (!principalNameGenerators.isEmpty()) {
- defaultPrincipalNameGenerator = principalNameGenerators.getFirst().getGenerator();
+ defaultPrincipalNameGenerator =
+ principalNameGenerators.getFirst().getGenerator();
principalNameGenerator = principalNameGenerators.getLast().getGenerator();
}
}
if (principalNameGenerator != null) {
- NameInfo nameInfo = principalNameGenerator.getPrincipalName(properties, type,
- principalNameFilter, defaultPrincipalNameGenerator);
+ NameInfo nameInfo = principalNameGenerator.getPrincipalName(
+ properties, type, principalNameFilter, defaultPrincipalNameGenerator);
if (nameInfo == null && defaultPrincipalNameGenerator != null) {
// fallback to the default impl
- nameInfo = defaultPrincipalNameGenerator.getPrincipalName(properties, type,
- principalNameFilter, defaultPrincipalNameGenerator);
+ nameInfo = defaultPrincipalNameGenerator.getPrincipalName(
+ properties, type, principalNameFilter, defaultPrincipalNameGenerator);
}
if (nameInfo != null) {
principalName = nameInfo.getPrincipalName();
if (principalName != null && nameInfo.isMakeUnique()) {
// make sure the name is not already used
- UserManager um = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager um = ((JackrabbitSession) jcrSession).getUserManager();
// if resulting authorizable exists, add a random suffix until it's not the case
// anymore
final int MAX_TRIES = 1000;
- if (um.getAuthorizable(principalName) != null ) {
- for (int i=0; i < MAX_TRIES; i++) {
+ if (um.getAuthorizable(principalName) != null) {
+ for (int i = 0; i < MAX_TRIES; i++) {
final int uniqueIndex = randomCollisionIndex.nextInt(9999);
String newPrincipalName = principalName + "_" + uniqueIndex;
if (um.getAuthorizable(newPrincipalName) == null) {
@@ -185,9 +191,9 @@ public abstract class AbstractAuthorizablePostServlet extends
}
// Give up after MAX_TRIES
- if (um.getAuthorizable(principalName) != null ) {
- throw new RepositoryException(
- "Collision in generated principal names, generated name " + principalName + " already exists");
+ if (um.getAuthorizable(principalName) != null) {
+ throw new RepositoryException("Collision in generated principal names, generated name "
+ + principalName + " already exists");
}
}
}
@@ -198,7 +204,7 @@ public abstract class AbstractAuthorizablePostServlet extends
if (obj instanceof String[] values && values.length == 1) {
principalName = values[0];
} else if (obj instanceof String value) {
- principalName= value;
+ principalName = value;
}
}
@@ -228,8 +234,7 @@ public abstract class AbstractAuthorizablePostServlet extends
* @param properties the properties out of which to generate the {@link RequestProperty}s
* @return the list of {@link RequestProperty}s
*/
- protected Map<String, RequestProperty> collectContentMap(
- Map<String, ?> properties) {
+ protected Map<String, RequestProperty> collectContentMap(Map<String, ?> properties) {
boolean requireItemPrefix = requireItemPathPrefix(properties);
@@ -249,7 +254,8 @@ public abstract class AbstractAuthorizablePostServlet extends
skipParam = true;
}
- // ensure the paramName is an absolute property path (i.e. starts with "/", where root refers to the authorizable's root, https://issues.apache.org/jira/browse/SLING-1577)
+ // ensure the paramName is an absolute property path (i.e. starts with "/", where root refers to the
+ // authorizable's root, https://issues.apache.org/jira/browse/SLING-1577)
String propPath;
if (paramName.startsWith("./")) {
propPath = paramName.substring(1);
@@ -269,9 +275,8 @@ public abstract class AbstractAuthorizablePostServlet extends
// <input type="hidden" name="./age@TypeHint" value="long" />
// causes the setProperty using the 'long' property type
if (propPath.endsWith(SlingPostConstants.TYPE_HINT_SUFFIX)) {
- RequestProperty prop = getOrCreateRequestProperty(
- reqProperties, propPath,
- SlingPostConstants.TYPE_HINT_SUFFIX);
+ RequestProperty prop =
+ getOrCreateRequestProperty(reqProperties, propPath, SlingPostConstants.TYPE_HINT_SUFFIX);
String typeHintValue = convertToString(e.getValue());
if (typeHintValue != null) {
@@ -280,8 +285,7 @@ public abstract class AbstractAuthorizablePostServlet extends
} else if (propPath.endsWith(SlingPostConstants.DEFAULT_VALUE_SUFFIX)) {
// @DefaultValue
RequestProperty prop = getOrCreateRequestProperty(
- reqProperties, propPath,
- SlingPostConstants.DEFAULT_VALUE_SUFFIX);
+ reqProperties, propPath, SlingPostConstants.DEFAULT_VALUE_SUFFIX);
prop.setDefaultValues(convertToRequestParameterArray(paramName, e.getValue()));
} else if (propPath.endsWith(SlingPostConstants.VALUE_FROM_SUFFIX)) {
@@ -291,12 +295,11 @@ public abstract class AbstractAuthorizablePostServlet extends
// <input name="./Text@ValueFrom" type="hidden" value="fulltext" />
// causes the JCR Text property to be set to the value of the
// fulltext form field.
- RequestProperty prop = getOrCreateRequestProperty(
- reqProperties, propPath,
- SlingPostConstants.VALUE_FROM_SUFFIX);
+ RequestProperty prop =
+ getOrCreateRequestProperty(reqProperties, propPath, SlingPostConstants.VALUE_FROM_SUFFIX);
// @ValueFrom params must have exactly one value, else ignored
- String [] valueFrom = convertToStringArray(e.getValue());
+ String[] valueFrom = convertToStringArray(e.getValue());
if (valueFrom.length == 1) {
String refName = valueFrom[0];
prop.setValues(convertToRequestParameterArray(paramName, refName));
@@ -306,8 +309,8 @@ public abstract class AbstractAuthorizablePostServlet extends
// @Delete example:
// <input name="./Text@Delete" type="hidden" />
// causes the JCR Text property to be deleted before update
- RequestProperty prop = getOrCreateRequestProperty(
- reqProperties, propPath, SlingPostConstants.SUFFIX_DELETE);
+ RequestProperty prop =
+ getOrCreateRequestProperty(reqProperties, propPath, SlingPostConstants.SUFFIX_DELETE);
prop.setDelete(true);
} else if (propPath.endsWith(SlingPostConstants.SUFFIX_MOVE_FROM)) {
@@ -318,7 +321,10 @@ public abstract class AbstractAuthorizablePostServlet extends
// property to Text.
// don't support @MoveFrom here
- LOG.warn("Suffix {} not supported, skipping parameter {}", SlingPostConstants.SUFFIX_MOVE_FROM, paramName);
+ LOG.warn(
+ "Suffix {} not supported, skipping parameter {}",
+ SlingPostConstants.SUFFIX_MOVE_FROM,
+ paramName);
} else if (propPath.endsWith(SlingPostConstants.SUFFIX_COPY_FROM)) {
// SLING-455: @CopyFrom means moving content to another location
// @CopyFrom example:
@@ -327,11 +333,13 @@ public abstract class AbstractAuthorizablePostServlet extends
// property to Text.
// don't support @CopyFrom here
- LOG.warn("Suffix {} not supported, skipping parameter {}", SlingPostConstants.SUFFIX_COPY_FROM, paramName);
+ LOG.warn(
+ "Suffix {} not supported, skipping parameter {}",
+ SlingPostConstants.SUFFIX_COPY_FROM,
+ paramName);
} else {
// plain property, create from values
- RequestProperty prop = getOrCreateRequestProperty(reqProperties,
- propPath, null);
+ RequestProperty prop = getOrCreateRequestProperty(reqProperties, propPath, null);
prop.setValues(convertToRequestParameterArray(paramName, e.getValue()));
}
}
@@ -345,7 +353,7 @@ public abstract class AbstractAuthorizablePostServlet extends
* request property does not exist yet it is created and stored in the
* <code>props</code>.
*
- * @param props The map of already seen request properties
+ * @param props The map of already seen request properties
* (key is the property path).
* @param paramPath The absolute path of the property including the
* <code>suffix</code> to be looked up.
@@ -356,8 +364,7 @@ public abstract class AbstractAuthorizablePostServlet extends
private RequestProperty getOrCreateRequestProperty(
Map<String, RequestProperty> props, String paramPath, String suffix) {
if (suffix != null && paramPath.endsWith(suffix)) {
- paramPath = paramPath.substring(0, paramPath.length()
- - suffix.length());
+ paramPath = paramPath.substring(0, paramPath.length() - suffix.length());
}
return props.computeIfAbsent(paramPath, RequestProperty::new);
@@ -377,9 +384,9 @@ public abstract class AbstractAuthorizablePostServlet extends
* @throws RepositoryException Is thrown if an error occurrs checking or
* removing properties.
*/
- protected void processDeletes(Authorizable authorizable,
- Collection<RequestProperty> reqProperties,
- List<Modification> changes) throws RepositoryException {
+ protected void processDeletes(
+ Authorizable authorizable, Collection<RequestProperty> reqProperties, List<Modification> changes)
+ throws RepositoryException {
for (RequestProperty property : reqProperties) {
if (property.isDelete()) {
@@ -419,12 +426,14 @@ public abstract class AbstractAuthorizablePostServlet extends
* @throws RepositoryException Is thrown if an error occurrs checking or
* removing properties.
*/
- protected void processCreate(Session session, Authorizable authorizable,
+ protected void processCreate(
+ Session session,
+ Authorizable authorizable,
Map<String, RequestProperty> reqProperties,
- List<Modification> changes) throws RepositoryException {
+ List<Modification> changes)
+ throws RepositoryException {
- @NotNull
- String path = authorizable.getPath();
+ @NotNull String path = authorizable.getPath();
for (RequestProperty prop : reqProperties.values()) {
String propName = prop.getName();
if (JcrConstants.JCR_PRIMARYTYPE.equals(propName) || JcrConstants.JCR_MIXINTYPES.equals(propName)) {
@@ -437,7 +446,7 @@ public abstract class AbstractAuthorizablePostServlet extends
String tp = null;
if (parentPath == null || "/".equals(parentPath)) {
tp = path;
- } else if (parentPath.startsWith("/")){
+ } else if (parentPath.startsWith("/")) {
tp = path.concat(parentPath);
}
if (tp != null && (tp.equals(path) || tp.startsWith(path.concat("/")))) {
@@ -503,8 +512,7 @@ public abstract class AbstractAuthorizablePostServlet extends
* @param path path to check
* @return the primary type or <code>null</code>
*/
- private String getPrimaryType(Map<String, RequestProperty> reqProperties,
- String path) {
+ private String getPrimaryType(Map<String, RequestProperty> reqProperties, String path) {
RequestProperty prop = reqProperties.get(concatPath(path, JcrConstants.JCR_PRIMARYTYPE));
return prop == null ? null : prop.getStringValues()[0];
}
@@ -518,19 +526,22 @@ public abstract class AbstractAuthorizablePostServlet extends
*
* @throws RepositoryException if a repository error occurs
*/
- protected void writeContent(Session session, Authorizable authorizable,
+ protected void writeContent(
+ Session session,
+ Authorizable authorizable,
Collection<RequestProperty> reqProperties,
- List<Modification> changes) throws RepositoryException {
+ List<Modification> changes)
+ throws RepositoryException {
for (RequestProperty prop : reqProperties) {
if (prop.hasValues()) {
// remove artificial "/" prepended to the prop path
String relativePath = prop.getPath().substring(1);
-
+
// skip jcr special properties
String name = prop.getName();
- boolean isSpecialProp = name.equals(JcrConstants.JCR_PRIMARYTYPE)
- || name.equals(JcrConstants.JCR_MIXINTYPES);
+ boolean isSpecialProp =
+ name.equals(JcrConstants.JCR_PRIMARYTYPE) || name.equals(JcrConstants.JCR_MIXINTYPES);
if (authorizable.isGroup()) {
if (relativePath.equals("groupId")) {
// skip these
@@ -538,13 +549,14 @@ public abstract class AbstractAuthorizablePostServlet extends
}
} else {
if (relativePath.equals("userId")
- || relativePath.equals("pwd")
- || relativePath.equals("pwdConfirm")) {
+ || relativePath.equals("pwd")
+ || relativePath.equals("pwdConfirm")) {
// skip these
isSpecialProp = true;
}
}
- if (!isSpecialProp && // skip these
+ if (!isSpecialProp
+ && // skip these
!prop.isFileUpload()) { // don't handle files for user properties for now.
setPropertyAsIs(session, authorizable, prop, changes);
}
@@ -554,12 +566,13 @@ public abstract class AbstractAuthorizablePostServlet extends
/**
* Find the PropertyDefinition for the specified propName
- *
+ *
* @param propName the propertyName to check
* @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 @Nullable PropertyDefinition resolvePropertyDefinition(@NotNull String propName, @NotNull Node parentNode) throws RepositoryException {
+ private @Nullable PropertyDefinition resolvePropertyDefinition(@NotNull String propName, @NotNull Node parentNode)
+ throws RepositoryException {
NodeType primaryNodeType = parentNode.getPrimaryNodeType();
// try the primary type
PropertyDefinition propDef = resolvePropertyDefinition(propName, primaryNodeType);
@@ -579,16 +592,17 @@ public abstract class AbstractAuthorizablePostServlet extends
/**
* Inspect the NodeType definition to try to determine the
* requiredType for the specified property
- *
+ *
* @param propName the propertyName to check
* @param parentNode the parent node where the property will be set
* @return the required type of the property or {@link PropertyType#UNDEFINED} if it could not be determined
*/
- private @Nullable PropertyDefinition resolvePropertyDefinition(@NotNull String propName, @NotNull NodeType nodeType) {
+ private @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);
}
/**
@@ -598,17 +612,14 @@ public abstract class AbstractAuthorizablePostServlet extends
* @param prop the request property
* @throws RepositoryException if a repository error occurs.
*/
- private void setPropertyAsIs(Session session, Authorizable parent,
- RequestProperty prop, List<Modification> changes)
+ private void setPropertyAsIs(Session session, Authorizable parent, RequestProperty prop, List<Modification> changes)
throws RepositoryException {
String parentPath;
if (parent.isGroup()) {
- parentPath = systemUserManagerPaths.getGroupPrefix()
- + parent.getID();
+ parentPath = systemUserManagerPaths.getGroupPrefix() + parent.getID();
} else {
- parentPath = systemUserManagerPaths.getUserPrefix()
- + parent.getID();
+ parentPath = systemUserManagerPaths.getUserPrefix() + parent.getID();
}
// no explicit typehint
@@ -628,8 +639,7 @@ public abstract class AbstractAuthorizablePostServlet extends
if (session.nodeExists(propParentPath)) {
// try to determine required property type from the NodeType definition
Node parentNode = session.getNode(propParentPath);
- @Nullable
- PropertyDefinition propDef = resolvePropertyDefinition(prop.getName(), parentNode);
+ @Nullable PropertyDefinition propDef = resolvePropertyDefinition(prop.getName(), parentNode);
if (propDef != null) {
type = propDef.getRequiredType();
multiValue = propDef.isMultiple();
@@ -644,16 +654,14 @@ public abstract class AbstractAuthorizablePostServlet extends
// remove property
boolean removedProp = removePropertyIfExists(parent, relativePath);
if (removedProp) {
- changes.add(Modification.onDeleted(parentPath + "/"
- + relativePath));
+ changes.add(Modification.onDeleted(parentPath + "/" + relativePath));
}
} else if (values.length == 0) {
// do not create new prop here, but clear existing
if (parent.hasProperty(relativePath)) {
Value val = session.getValueFactory().createValue("");
parent.setProperty(relativePath, val);
- changes.add(Modification.onModified(parentPath + "/"
- + relativePath));
+ changes.add(Modification.onModified(parentPath + "/" + relativePath));
}
} else if (values.length == 1) {
// if the provided value is the empty string, we don't have to do
@@ -661,8 +669,7 @@ public abstract class AbstractAuthorizablePostServlet extends
if (values[0].length() == 0) {
boolean removedProp = removePropertyIfExists(parent, relativePath);
if (removedProp) {
- changes.add(Modification.onDeleted(parentPath + "/"
- + relativePath));
+ changes.add(Modification.onDeleted(parentPath + "/" + relativePath));
}
} else {
// modify property
@@ -674,37 +681,30 @@ public abstract class AbstractAuthorizablePostServlet extends
final Value[] array = new Value[1];
array[0] = session.getValueFactory().createValue(c);
parent.setProperty(relativePath, array);
- changes.add(Modification.onModified(parentPath
- + "/" + relativePath));
+ changes.add(Modification.onModified(parentPath + "/" + relativePath));
} else {
- Value cVal = session.getValueFactory().createValue(
- c);
+ Value cVal = session.getValueFactory().createValue(c);
parent.setProperty(relativePath, cVal);
- changes.add(Modification.onModified(parentPath
- + "/" + relativePath));
+ changes.add(Modification.onModified(parentPath + "/" + relativePath));
}
return;
}
// fall back to default behaviour
}
if (type == PropertyType.UNDEFINED) {
- Value val = session.getValueFactory().createValue(
- values[0], PropertyType.STRING);
+ Value val = session.getValueFactory().createValue(values[0], PropertyType.STRING);
parent.setProperty(relativePath, val);
} else {
if (multiValue) {
final Value[] array = new Value[1];
- array[0] = session.getValueFactory().createValue(
- values[0], type);
+ array[0] = session.getValueFactory().createValue(values[0], type);
parent.setProperty(relativePath, array);
} else {
- Value val = session.getValueFactory().createValue(
- values[0], type);
+ Value val = session.getValueFactory().createValue(values[0], type);
parent.setProperty(relativePath, val);
}
}
- changes.add(Modification.onModified(parentPath + "/"
- + relativePath));
+ changes.add(Modification.onModified(parentPath + "/" + relativePath));
}
} else {
if (type == PropertyType.DATE) {
@@ -712,12 +712,9 @@ public abstract class AbstractAuthorizablePostServlet extends
Calendar[] c = dateParser.parse(values);
if (c != null) {
ValueFactory vf = session.getValueFactory();
- Value[] cVals = Stream.of(c)
- .map(vf::createValue)
- .toArray(Value[]::new);
+ Value[] cVals = Stream.of(c).map(vf::createValue).toArray(Value[]::new);
parent.setProperty(relativePath, cVals);
- changes.add(Modification.onModified(parentPath + "/"
- + relativePath));
+ changes.add(Modification.onModified(parentPath + "/" + relativePath));
return;
}
// fall back to default behaviour
@@ -730,15 +727,12 @@ public abstract class AbstractAuthorizablePostServlet extends
}
} else {
for (int i = 0; i < values.length; i++) {
- vals[i] = session.getValueFactory().createValue(values[i],
- type);
+ vals[i] = session.getValueFactory().createValue(values[i], type);
}
}
parent.setProperty(relativePath, vals);
- changes.add(Modification.onModified(parentPath + "/"
- + relativePath));
+ changes.add(Modification.onModified(parentPath + "/" + relativePath));
}
-
}
/**
@@ -752,8 +746,7 @@ public abstract class AbstractAuthorizablePostServlet extends
* was not removed
* @throws RepositoryException if a repository error occurs.
*/
- private boolean removePropertyIfExists(Authorizable authorizable, String path)
- throws RepositoryException {
+ private boolean removePropertyIfExists(Authorizable authorizable, String path) throws RepositoryException {
if (authorizable.getProperty(path) != null) {
authorizable.removeProperty(path);
return true;
@@ -767,13 +760,13 @@ public abstract class AbstractAuthorizablePostServlet extends
* @param name the name
* @return <code>true</code> if the <code>name</code> starts with either of
* the prefixes {@link SlingPostConstants#ITEM_PREFIX_RELATIVE_CURRENT},
- * {@link SlingPostConstants#ITEM_PREFIX_RELATIVE_PARENT} and
+ * {@link SlingPostConstants#ITEM_PREFIX_RELATIVE_PARENT} and
* {@link SlingPostConstants#ITEM_PREFIX_ABSOLUTE}
*/
protected boolean hasItemPathPrefix(String name) {
return name.startsWith(SlingPostConstants.ITEM_PREFIX_ABSOLUTE)
- || name.startsWith(SlingPostConstants.ITEM_PREFIX_RELATIVE_CURRENT)
- || name.startsWith(SlingPostConstants.ITEM_PREFIX_RELATIVE_PARENT);
+ || name.startsWith(SlingPostConstants.ITEM_PREFIX_RELATIVE_CURRENT)
+ || name.startsWith(SlingPostConstants.ITEM_PREFIX_RELATIVE_PARENT);
}
/**
@@ -788,8 +781,7 @@ public abstract class AbstractAuthorizablePostServlet extends
* not starting with the command prefix <code>:</code> are considered as
* parameters to be stored.
*/
- protected final boolean requireItemPathPrefix(
- Map<String, ?> properties) {
+ protected final boolean requireItemPathPrefix(Map<String, ?> properties) {
boolean requirePrefix = false;
@@ -802,7 +794,6 @@ public abstract class AbstractAuthorizablePostServlet extends
return requirePrefix;
}
-
protected String convertToString(Object obj) {
String strValue = null;
if (obj instanceof String value) {
@@ -820,7 +811,7 @@ public abstract class AbstractAuthorizablePostServlet extends
}
protected @NotNull String[] convertToStringArray(Object obj) {
- String [] strArray = null;
+ String[] strArray = null;
if (obj instanceof String value) {
strArray = new String[] {value};
} else if (obj instanceof String[] value) {
@@ -829,7 +820,7 @@ public abstract class AbstractAuthorizablePostServlet extends
strArray = new String[] {value.getString()};
} else if (obj instanceof RequestParameter[] values) {
strArray = new String[values.length];
- for (int i=0; i < values.length; i++) {
+ for (int i = 0; i < values.length; i++) {
strArray[i] = values[i].getString();
}
}
@@ -838,14 +829,12 @@ public abstract class AbstractAuthorizablePostServlet extends
}
protected @NotNull RequestParameter[] convertToRequestParameterArray(String paramName, Object obj) {
- RequestParameter [] paramArray = null;
+ RequestParameter[] paramArray = null;
if (obj instanceof String value) {
- paramArray = new RequestParameter[] {
- Builders.newRequestParameter(paramName, value)
- };
+ paramArray = new RequestParameter[] {Builders.newRequestParameter(paramName, value)};
} else if (obj instanceof String[] strValues) {
paramArray = new RequestParameter[strValues.length];
- for (int i=0; i < strValues.length; i++) {
+ for (int i = 0; i < strValues.length; i++) {
paramArray[i] = Builders.newRequestParameter(paramName, strValues[i]);
}
} else if (obj instanceof RequestParameter reqParam) {
@@ -856,5 +845,4 @@ public abstract class AbstractAuthorizablePostServlet extends
return paramArray == null ? new RequestParameter[0] : paramArray;
}
-
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/AbstractGroupPostServlet.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/AbstractGroupPostServlet.java
index e599a34..751b4a0 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/AbstractGroupPostServlet.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/AbstractGroupPostServlet.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.jackrabbit.usermanager.impl.post;
-import java.util.List;
-import java.util.Map;
-
import javax.jcr.RepositoryException;
import javax.jcr.Session;
+import java.util.List;
+import java.util.Map;
+
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
@@ -34,41 +36,37 @@ import org.apache.sling.servlets.post.SlingPostConstants;
/**
* Base class for servlets manipulating groups
*/
-public abstract class AbstractGroupPostServlet extends
- AbstractAuthorizablePostServlet {
+public abstract class AbstractGroupPostServlet extends AbstractAuthorizablePostServlet {
private static final long serialVersionUID = 1159063041816944076L;
/**
* Update the group membership based on the ":member" request parameters. If
* the ":member" value ends with @Delete it is removed from the group
* membership, otherwise it is added to the group membership.
- *
+ *
* @param baseResource the group resource of the {@code authorizable}
* @param properties the request parameters
* @param authorizable the group to update
* @param changes the changes which are done by this operation (list is extended)
* @throws RepositoryException when updating the membership failed
*/
- protected void updateGroupMembership(Resource baseResource,
- Map<String, ?> properties,
- Authorizable authorizable,
- List<Modification> changes)
+ protected void updateGroupMembership(
+ Resource baseResource, Map<String, ?> properties, Authorizable authorizable, List<Modification> changes)
throws RepositoryException {
if (authorizable.isGroup()) {
Group group = ((Group) authorizable);
- String groupPath = systemUserManagerPaths.getGroupPrefix()
- + group.getID();
+ String groupPath = systemUserManagerPaths.getGroupPrefix() + group.getID();
ResourceResolver resolver = baseResource.getResourceResolver();
boolean changed = false;
-
- UserManager userManager = ((JackrabbitSession)resolver.adaptTo(Session.class)).getUserManager();
+
+ UserManager userManager = ((JackrabbitSession) resolver.adaptTo(Session.class)).getUserManager();
// first remove any members posted as ":member@Delete"
- String[] membersToDelete = convertToStringArray(properties.get(SlingPostConstants.RP_PREFIX
- + "member" + SlingPostConstants.SUFFIX_DELETE));
+ String[] membersToDelete = convertToStringArray(
+ properties.get(SlingPostConstants.RP_PREFIX + "member" + SlingPostConstants.SUFFIX_DELETE));
for (String member : membersToDelete) {
- Authorizable memberAuthorizable = getAuthorizable(baseResource, member,userManager,resolver);
+ Authorizable memberAuthorizable = getAuthorizable(baseResource, member, userManager, resolver);
if (memberAuthorizable != null) {
group.removeMember(memberAuthorizable);
changed = true;
@@ -76,10 +74,9 @@ public abstract class AbstractGroupPostServlet extends
}
// second add any members posted as ":member"
- String[] membersToAdd = convertToStringArray(properties.get(SlingPostConstants.RP_PREFIX
- + "member"));
+ String[] membersToAdd = convertToStringArray(properties.get(SlingPostConstants.RP_PREFIX + "member"));
for (String member : membersToAdd) {
- Authorizable memberAuthorizable = getAuthorizable(baseResource, member,userManager,resolver);
+ Authorizable memberAuthorizable = getAuthorizable(baseResource, member, userManager, resolver);
if (memberAuthorizable != null) {
group.addMember(memberAuthorizable);
changed = true;
@@ -101,17 +98,15 @@ public abstract class AbstractGroupPostServlet extends
* @param resolver the resource resolver for this request.
* @return the authorizable, or null if no authorizable was found.
*/
- private Authorizable getAuthorizable(Resource baseResource,
- String member,
- UserManager userManager,
- ResourceResolver resolver) {
+ private Authorizable getAuthorizable(
+ Resource baseResource, String member, UserManager userManager, ResourceResolver resolver) {
Authorizable memberAuthorizable = null;
try {
memberAuthorizable = userManager.getAuthorizable(member);
} catch (RepositoryException e) {
// if we can't find the members then it may be resolvable as a resource.
}
- if ( memberAuthorizable == null ) {
+ if (memberAuthorizable == null) {
Resource res = resolver.getResource(baseResource, member);
if (res != null) {
memberAuthorizable = res.adaptTo(Authorizable.class);
@@ -119,5 +114,4 @@ public abstract class AbstractGroupPostServlet extends
}
return memberAuthorizable;
}
-
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/AbstractPostServlet.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/AbstractPostServlet.java
index 2633d3e..ad5fd83 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/AbstractPostServlet.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/AbstractPostServlet.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.jackrabbit.usermanager.impl.post;
+import javax.jcr.AccessDeniedException;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
@@ -24,10 +30,9 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import javax.jcr.AccessDeniedException;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
import org.apache.sling.api.SlingJakartaHttpServletRequest;
import org.apache.sling.api.SlingJakartaHttpServletResponse;
import org.apache.sling.api.request.header.JakartaMediaRangeList;
@@ -45,18 +50,13 @@ import org.osgi.framework.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import jakarta.servlet.ServletException;
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
-
/**
* Base class for all the POST servlets for the UserManager operations
*/
-public abstract class AbstractPostServlet extends
- SlingJakartaAllMethodsServlet {
+public abstract class AbstractPostServlet extends SlingJakartaAllMethodsServlet {
private static final long serialVersionUID = 7408267654653472120L;
-
+
/**
* default log
*/
@@ -76,9 +76,8 @@ public abstract class AbstractPostServlet extends
* org.apache.sling.api.SlingJakartaHttpServletResponse)
*/
@Override
- protected void doPost(SlingJakartaHttpServletRequest request,
- SlingJakartaHttpServletResponse httpResponse) throws ServletException,
- IOException {
+ protected void doPost(SlingJakartaHttpServletRequest request, SlingJakartaHttpServletResponse httpResponse)
+ throws ServletException, IOException {
// prepare the response
JakartaPostResponse response = createPostResponse(request);
response.setReferer(request.getHeader("referer"));
@@ -113,19 +112,16 @@ public abstract class AbstractPostServlet extends
response.onDeleted(change.getSource());
break;
case MOVE:
- response.onMoved(change.getSource(),
- change.getDestination());
+ response.onMoved(change.getSource(), change.getDestination());
break;
case COPY:
- response.onCopied(change.getSource(),
- change.getDestination());
+ response.onCopied(change.getSource(), change.getDestination());
break;
case CREATE:
response.onCreated(change.getSource());
break;
case ORDER:
- response.onChange("ordered", change.getSource(),
- change.getDestination());
+ response.onChange("ordered", change.getSource(), change.getDestination());
break;
default:
break;
@@ -136,21 +132,21 @@ public abstract class AbstractPostServlet extends
session.save();
}
} catch (ResourceNotFoundException rnfe) {
- response.setStatus(HttpServletResponse.SC_NOT_FOUND,
- rnfe.getMessage());
+ response.setStatus(HttpServletResponse.SC_NOT_FOUND, rnfe.getMessage());
} catch (Exception throwable) {
if (log.isDebugEnabled()) {
- log.debug(String.format("Exception while handling POST %s with %s",
- request.getResource().getPath(), getClass().getName()),
- throwable);
+ log.debug(
+ String.format(
+ "Exception while handling POST %s with %s",
+ request.getResource().getPath(), getClass().getName()),
+ throwable);
}
Throwable cause = throwable.getCause();
if (cause == null) {
cause = throwable;
}
if (cause instanceof AccessDeniedException) {
- response.setStatus(HttpServletResponse.SC_FORBIDDEN,
- cause.getMessage());
+ response.setStatus(HttpServletResponse.SC_FORBIDDEN, cause.getMessage());
} else {
response.setError(throwable);
}
@@ -160,8 +156,7 @@ public abstract class AbstractPostServlet extends
session.refresh(false);
}
} catch (RepositoryException e) {
- log.warn("RepositoryException in finally block: {}",
- e.getMessage(), e);
+ log.warn("RepositoryException in finally block: {}", e.getMessage(), e);
}
}
@@ -172,8 +167,11 @@ public abstract class AbstractPostServlet extends
redirect = getRedirectUrl(request, response);
} catch (IOException e) {
if (log.isDebugEnabled()) {
- log.debug(String.format("Exception while handling redirect for POST %s with %s",
- request.getResource().getPath(), getClass().getName()), e);
+ log.debug(
+ String.format(
+ "Exception while handling redirect for POST %s with %s",
+ request.getResource().getPath(), getClass().getName()),
+ e);
}
// http status code for 422 Unprocessable Entity
response.setStatus(422, "invalid redirect");
@@ -208,14 +206,14 @@ public abstract class AbstractPostServlet extends
}
}
- //for backward compatibility, if no "accept" request param or header is supplied
+ // for backward compatibility, if no "accept" request param or header is supplied
// then prefer the SlingHttpServletRequest#getResponseContentType value
JakartaMediaRangeList mediaRangeList = null;
String queryParam = req.getParameter(JakartaMediaRangeList.PARAM_ACCEPT);
if (queryParam == null || queryParam.trim().length() == 0) {
String headerValue = req.getHeader(JakartaMediaRangeList.HEADER_ACCEPT);
if (headerValue == null || headerValue.trim().length() == 0) {
- //no param or header supplied, so try the response content type
+ // no param or header supplied, so try the response content type
mediaRangeList = new JakartaMediaRangeList(req.getResponseContentType());
}
}
@@ -224,7 +222,8 @@ public abstract class AbstractPostServlet extends
if (mediaRangeList == null) {
mediaRangeList = new JakartaMediaRangeList(req);
}
- if (JakartaJSONResponse.RESPONSE_CONTENT_TYPE.equals(mediaRangeList.prefer("text/html", JakartaJSONResponse.RESPONSE_CONTENT_TYPE))) {
+ if (JakartaJSONResponse.RESPONSE_CONTENT_TYPE.equals(
+ mediaRangeList.prefer("text/html", JakartaJSONResponse.RESPONSE_CONTENT_TYPE))) {
return new JakartaJSONResponse();
} else {
return new JakartaHtmlResponse();
@@ -233,14 +232,14 @@ public abstract class AbstractPostServlet extends
/**
* Extending Servlet should implement this operation to do the work
- *
+ *
* @param request the sling http request to process
* @param response the response
* @param changes the changes to report
* @throws RepositoryException in case of exceptions during the operation
*/
- protected abstract void handleOperation(SlingJakartaHttpServletRequest request,
- JakartaPostResponse response, List<Modification> changes)
+ protected abstract void handleOperation(
+ SlingJakartaHttpServletRequest request, JakartaPostResponse response, List<Modification> changes)
throws RepositoryException;
/**
@@ -258,7 +257,8 @@ public abstract class AbstractPostServlet extends
URI redirectUri = new URI(result);
if (redirectUri.getAuthority() != null) {
// if it has a host information
- throw new IOException("The redirect target included host information. This is not allowed for security reasons!");
+ throw new IOException(
+ "The redirect target included host information. This is not allowed for security reasons!");
}
} catch (URISyntaxException e) {
throw new IOException("The redirect target was not a valid uri");
@@ -300,28 +300,23 @@ public abstract class AbstractPostServlet extends
String statusParam = request.getParameter(SlingPostConstants.RP_STATUS);
if (statusParam == null) {
log.debug(
- "getStatusMode: Parameter {} not set, assuming standard status code",
- SlingPostConstants.RP_STATUS);
+ "getStatusMode: Parameter {} not set, assuming standard status code", SlingPostConstants.RP_STATUS);
return true;
}
if (SlingPostConstants.STATUS_VALUE_BROWSER.equals(statusParam)) {
- log.debug(
- "getStatusMode: Parameter {} asks for user-friendly status code",
- SlingPostConstants.RP_STATUS);
+ log.debug("getStatusMode: Parameter {} asks for user-friendly status code", SlingPostConstants.RP_STATUS);
return false;
}
if (SlingPostConstants.STATUS_VALUE_STANDARD.equals(statusParam)) {
- log.debug(
- "getStatusMode: Parameter {} asks for standard status code",
- SlingPostConstants.RP_STATUS);
+ log.debug("getStatusMode: Parameter {} asks for standard status code", SlingPostConstants.RP_STATUS);
return true;
}
log.debug(
- "getStatusMode: Parameter {} set to unknown value, assuming standard status code",
- SlingPostConstants.RP_STATUS);
+ "getStatusMode: Parameter {} set to unknown value, assuming standard status code",
+ SlingPostConstants.RP_STATUS);
return true;
}
@@ -342,13 +337,12 @@ public abstract class AbstractPostServlet extends
/**
* Returns an external form of the given path prepending the context path
* and appending a display extension.
- *
+ *
* @param request the request
* @param path the path to externalize
* @return the url
*/
- protected final String externalizePath(SlingJakartaHttpServletRequest request,
- String path) {
+ protected final String externalizePath(SlingJakartaHttpServletRequest request, String path) {
StringBuilder ret = new StringBuilder();
ret.append(SlingRequestPaths.getContextPath(request));
ret.append(request.getResourceResolver().map(path));
@@ -365,26 +359,28 @@ public abstract class AbstractPostServlet extends
return ret.toString();
}
-
/**
* Bind a new post response creator
*/
- // NOTE: the @Reference annotation is not inherited, so subclasses will need to override the #bindPostResponseCreator
+ // NOTE: the @Reference annotation is not inherited, so subclasses will need to override the
+ // #bindPostResponseCreator
// and #unbindPostResponseCreator methods to provide the @Reference annotation.
//
// @Reference(service = PostResponseCreator.class,
// cardinality = ReferenceCardinality.MULTIPLE,
// policy = ReferencePolicy.DYNAMIC)
- protected void bindPostResponseCreator(final JakartaPostResponseCreator creator, final Map<String, Object> properties) {
- final JakartaPostResponseCreatorHolder nngh = new JakartaPostResponseCreatorHolder(creator, getRanking(properties));
+ protected void bindPostResponseCreator(
+ final JakartaPostResponseCreator creator, final Map<String, Object> properties) {
+ final JakartaPostResponseCreatorHolder nngh =
+ new JakartaPostResponseCreatorHolder(creator, getRanking(properties));
- synchronized ( this.postResponseCreators ) {
+ synchronized (this.postResponseCreators) {
int index = 0;
- while ( index < this.postResponseCreators.size() &&
- nngh.ranking() < this.postResponseCreators.get(index).ranking() ) {
+ while (index < this.postResponseCreators.size()
+ && nngh.ranking() < this.postResponseCreators.get(index).ranking()) {
index++;
}
- if ( index == this.postResponseCreators.size() ) {
+ if (index == this.postResponseCreators.size()) {
this.postResponseCreators.add(nngh);
} else {
this.postResponseCreators.add(index, nngh);
@@ -396,12 +392,13 @@ public abstract class AbstractPostServlet extends
/**
* Unbind a post response creator
*/
- protected void unbindPostResponseCreator(final JakartaPostResponseCreator creator, final Map<String, Object> properties) { //NOSONAR
- synchronized ( this.postResponseCreators ) {
+ protected void unbindPostResponseCreator(
+ final JakartaPostResponseCreator creator, final Map<String, Object> properties) { // NOSONAR
+ synchronized (this.postResponseCreators) {
final Iterator<JakartaPostResponseCreatorHolder> i = this.postResponseCreators.iterator();
- while ( i.hasNext() ) {
+ while (i.hasNext()) {
final JakartaPostResponseCreatorHolder current = i.next();
- if ( current.creator() == creator ) {
+ if (current.creator() == creator) {
i.remove();
}
}
@@ -414,9 +411,10 @@ public abstract class AbstractPostServlet extends
* This method is called by sync'ed methods, no need to add additional syncing.
*/
private void updatePostResponseCreatorCache() {
- final JakartaPostResponseCreator[] localCache = new JakartaPostResponseCreator[this.postResponseCreators.size()];
+ final JakartaPostResponseCreator[] localCache =
+ new JakartaPostResponseCreator[this.postResponseCreators.size()];
int index = 0;
- for(final JakartaPostResponseCreatorHolder current : this.postResponseCreators) {
+ for (final JakartaPostResponseCreatorHolder current : this.postResponseCreators) {
localCache[index] = current.creator;
index++;
}
@@ -429,5 +427,4 @@ public abstract class AbstractPostServlet extends
}
private static final record JakartaPostResponseCreatorHolder(JakartaPostResponseCreator creator, int ranking) {}
-
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/ChangeUserPasswordServlet.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/ChangeUserPasswordServlet.java
index d798fd8..eb22e2a 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/ChangeUserPasswordServlet.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/ChangeUserPasswordServlet.java
@@ -1,29 +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.jackrabbit.usermanager.impl.post;
-import java.util.List;
-import java.util.Map;
-
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.security.AccessControlManager;
import javax.jcr.security.Privilege;
+import java.util.List;
+import java.util.Map;
+
+import jakarta.servlet.Servlet;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
@@ -53,8 +56,6 @@ import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import jakarta.servlet.Servlet;
-
/**
* <h2>
* Changes the password associated with a user.
@@ -95,36 +96,40 @@ import jakarta.servlet.Servlet;
*
* <h3>Notes</h3>
*/
-
-@Component(service = {Servlet.class, ChangeUserPassword.class},
- property = {
- "sling.servlet.resourceTypes=sling/user",
- "sling.servlet.methods=POST",
- "sling.servlet.selectors=changePassword",
- "sling.servlet.prefix:Integer=-1",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=EEE MMM dd yyyy HH:mm:ss 'GMT'Z",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd'T'HH:mm:ss.SSSZ",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd'T'HH:mm:ss",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=dd.MM.yyyy HH:mm:ss",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=dd.MM.yyyy"
- },
- reference = {
- @Reference(name="SystemUserManagerPaths",
- bind = "bindSystemUserManagerPaths",
- service = SystemUserManagerPaths.class)
- })
-@Designate(ocd=ChangeUserPasswordServlet.Config.class)
+@Component(
+ service = {Servlet.class, ChangeUserPassword.class},
+ property = {
+ "sling.servlet.resourceTypes=sling/user",
+ "sling.servlet.methods=POST",
+ "sling.servlet.selectors=changePassword",
+ "sling.servlet.prefix:Integer=-1",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=EEE MMM dd yyyy HH:mm:ss 'GMT'Z",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd'T'HH:mm:ss.SSSZ",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd'T'HH:mm:ss",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=dd.MM.yyyy HH:mm:ss",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=dd.MM.yyyy"
+ },
+ reference = {
+ @Reference(
+ name = "SystemUserManagerPaths",
+ bind = "bindSystemUserManagerPaths",
+ service = SystemUserManagerPaths.class)
+ })
+@Designate(ocd = ChangeUserPasswordServlet.Config.class)
public class ChangeUserPasswordServlet extends AbstractAuthorizablePostServlet implements ChangeUserPassword {
- @ObjectClassDefinition(name ="Apache Sling Change User Password")
+ @ObjectClassDefinition(name = "Apache Sling Change User Password")
public @interface Config {
- @AttributeDefinition(name = "User Admin Group Name",
- description = "Specifies the name of the group whose members are allowed to reset the password of another user.")
- String user_admin_group_name() default DEFAULT_USER_ADMIN_GROUP_NAME; //NOSONAR
+ @AttributeDefinition(
+ name = "User Admin Group Name",
+ description =
+ "Specifies the name of the group whose members are allowed to reset the password of another user.")
+ String user_admin_group_name() default DEFAULT_USER_ADMIN_GROUP_NAME; // NOSONAR
- @AttributeDefinition(name = "Allow Self Password Change",
+ @AttributeDefinition(
+ name = "Allow Self Password Change",
description = "Specifies whether a user is allowed to change their own password.")
boolean allowSelfChangePassword() default true;
}
@@ -178,14 +183,15 @@ public class ChangeUserPasswordServlet extends AbstractAuthorizablePostServlet i
if (props.containsKey("alwaysAllowSelfChangePassword")) {
// log warning about the wrong property name
- log.warn("Obsolete 'alwaysAllowSelfChangePassword' configuration key was detected. Please change the key name in your configuration to 'allowSelfChangePassword'");
+ log.warn(
+ "Obsolete 'alwaysAllowSelfChangePassword' configuration key was detected. Please change the key name in your configuration to 'allowSelfChangePassword'");
allowSelfChangePassword = OsgiUtil.toBoolean(props.get("alwaysAllowSelfChangePassword"), false);
} else {
allowSelfChangePassword = OsgiUtil.toBoolean(props.get("allowSelfChangePassword"), false);
}
- this.userAdminGroupName = OsgiUtil.toString(props.get(PAR_USER_ADMIN_GROUP_NAME),
- DEFAULT_USER_ADMIN_GROUP_NAME);
+ this.userAdminGroupName =
+ OsgiUtil.toString(props.get(PAR_USER_ADMIN_GROUP_NAME), DEFAULT_USER_ADMIN_GROUP_NAME);
log.debug("User Admin Group Name {}", this.userAdminGroupName);
}
@@ -197,13 +203,14 @@ public class ChangeUserPasswordServlet extends AbstractAuthorizablePostServlet i
/**
* Overridden since the @Reference annotation is not inherited from the super method
- *
+ *
* @see org.apache.sling.jackrabbit.usermanager.impl.post.AbstractPostServlet#bindPostResponseCreator(org.apache.sling.servlets.post.JakartaPostResponseCreator, java.util.Map)
*/
@Override
- @Reference(service = JakartaPostResponseCreator.class,
- cardinality = ReferenceCardinality.MULTIPLE,
- policy = ReferencePolicy.DYNAMIC)
+ @Reference(
+ service = JakartaPostResponseCreator.class,
+ cardinality = ReferenceCardinality.MULTIPLE,
+ policy = ReferencePolicy.DYNAMIC)
protected void bindPostResponseCreator(JakartaPostResponseCreator creator, Map<String, Object> properties) {
super.bindPostResponseCreator(creator, properties);
}
@@ -212,7 +219,8 @@ public class ChangeUserPasswordServlet extends AbstractAuthorizablePostServlet i
* @see org.apache.sling.jackrabbit.usermanager.impl.post.AbstractPostServlet#unbindPostResponseCreator(org.apache.sling.servlets.post.JakartaPostResponseCreator, java.util.Map)
*/
@Override
- protected void unbindPostResponseCreator(JakartaPostResponseCreator creator, Map<String, Object> properties) { //NOSONAR
+ protected void unbindPostResponseCreator(
+ JakartaPostResponseCreator creator, Map<String, Object> properties) { // NOSONAR
super.unbindPostResponseCreator(creator, properties);
}
@@ -224,13 +232,14 @@ public class ChangeUserPasswordServlet extends AbstractAuthorizablePostServlet i
* org.apache.sling.servlets.post.JakartaPostResponse, java.util.List)
*/
@Override
- protected void handleOperation(SlingJakartaHttpServletRequest request,
- JakartaPostResponse response, List<Modification> changes)
+ protected void handleOperation(
+ SlingJakartaHttpServletRequest request, JakartaPostResponse response, List<Modification> changes)
throws RepositoryException {
Resource resource = request.getResource();
Session session = request.getResourceResolver().adaptTo(Session.class);
- changePassword(session,
+ changePassword(
+ session,
resource.getName(),
request.getParameter("oldPwd"),
request.getParameter("newPwd"),
@@ -241,42 +250,41 @@ public class ChangeUserPasswordServlet extends AbstractAuthorizablePostServlet i
/* (non-Javadoc)
* @see org.apache.sling.jackrabbit.usermanager.ChangeUserPassword#changePassword(javax.jcr.Session, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.util.List)
*/
- public User changePassword(Session jcrSession,
- String name,
- String oldPassword,
- String newPassword,
- String newPasswordConfirm,
- List<Modification> changes)
- throws RepositoryException {
+ public User changePassword(
+ Session jcrSession,
+ String name,
+ String oldPassword,
+ String newPassword,
+ String newPasswordConfirm,
+ List<Modification> changes)
+ throws RepositoryException {
if ("anonymous".equals(name)) {
- throw new RepositoryException(
- "Can not change the password of the anonymous user.");
+ throw new RepositoryException("Can not change the password of the anonymous user.");
}
User user;
- UserManager userManager = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager userManager = ((JackrabbitSession) jcrSession).getUserManager();
Authorizable authorizable = userManager.getAuthorizable(name);
if (authorizable instanceof User u) {
user = u;
} else {
- throw new ResourceNotFoundException(
- "User to update could not be determined");
+ throw new ResourceNotFoundException("User to update could not be determined");
}
- //SLING-2069: if the current user is an administrator, then a missing oldPwd is ok,
+ // SLING-2069: if the current user is an administrator, then a missing oldPwd is ok,
// otherwise the oldPwd must be supplied.
boolean administrator = false;
// check that the submitted parameter values have valid values.
if (oldPassword == null || oldPassword.length() == 0) {
try {
- UserManager um = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager um = ((JackrabbitSession) jcrSession).getUserManager();
User currentUser = (User) um.getAuthorizable(jcrSession.getUserID());
administrator = currentUser.isAdmin();
if (!administrator) {
- //check if the user is a member of the 'User administrator' group
+ // check if the user is a member of the 'User administrator' group
Authorizable userAdmin = um.getAuthorizable(this.userAdminGroupName);
if (userAdmin instanceof Group userAdminGroup) {
boolean isMember = userAdminGroup.isMember(currentUser);
@@ -284,9 +292,8 @@ public class ChangeUserPasswordServlet extends AbstractAuthorizablePostServlet i
administrator = true;
}
}
-
}
- } catch ( Exception ex ) {
+ } catch (Exception ex) {
log.warn("Failed to determine if the user is an admin, assuming not. Cause: {}", ex.getMessage());
administrator = false;
}
@@ -298,8 +305,7 @@ public class ChangeUserPasswordServlet extends AbstractAuthorizablePostServlet i
throw new RepositoryException("New Password was not submitted");
}
if (!newPassword.equals(newPasswordConfirm)) {
- throw new RepositoryException(
- "New Password does not match the confirmation password");
+ throw new RepositoryException("New Password does not match the confirmation password");
}
if (oldPassword != null && oldPassword.length() > 0) {
@@ -308,9 +314,9 @@ public class ChangeUserPasswordServlet extends AbstractAuthorizablePostServlet i
// first check if the current user has enough permissions to do this without
// the aid of a service session
AccessControlManager acm = jcrSession.getAccessControlManager();
- boolean hasRights = acm.hasPrivileges(authorizable.getPath(), new Privilege[] {
- acm.privilegeFromName(PrivilegeConstants.REP_USER_MANAGEMENT)
- });
+ boolean hasRights = acm.hasPrivileges(
+ authorizable.getPath(),
+ new Privilege[] {acm.privilegeFromName(PrivilegeConstants.REP_USER_MANAGEMENT)});
if (hasRights) {
// we are good to do this without an extra service session
@@ -321,7 +327,7 @@ public class ChangeUserPasswordServlet extends AbstractAuthorizablePostServlet i
Session svcSession = null;
try {
svcSession = repository.loginService(null, null);
- UserManager um = ((JackrabbitSession)svcSession).getUserManager();
+ UserManager um = ((JackrabbitSession) svcSession).getUserManager();
User user2 = (User) um.getAuthorizable(name);
user2.changePassword(newPassword, oldPassword);
if (svcSession.hasPendingChanges()) {
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/CreateGroupServlet.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/CreateGroupServlet.java
index e69d3ad..2a0b0bc 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/CreateGroupServlet.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/CreateGroupServlet.java
@@ -1,29 +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.jackrabbit.usermanager.impl.post;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
+import jakarta.servlet.Servlet;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
@@ -51,8 +54,6 @@ import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;
-import jakarta.servlet.Servlet;
-
/**
* <p>
* Sling Post Servlet implementation for creating a group in the jackrabbit UserManager.
@@ -92,38 +93,39 @@ import jakarta.servlet.Servlet;
* <dd>Failure, including group already exists. HTML explains the failure.</dd>
* </dl>
* <h3>Example</h3>
- *
+ *
* <code>
* curl -F:name=newGroupA -Fproperty1=value1 http://localhost:8080/system/userManager/group.create.html
* </code>
- *
+ *
* <h4>Notes</h4>
*/
-
-@Component(service = {Servlet.class, CreateGroup.class},
-property = {
- "sling.servlet.resourceTypes=sling/groups",
- "sling.servlet.methods=POST",
- "sling.servlet.selectors=create",
- "sling.servlet.prefix:Integer=-1",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=EEE MMM dd yyyy HH:mm:ss 'GMT'Z",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd'T'HH:mm:ss.SSSZ",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd'T'HH:mm:ss",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=dd.MM.yyyy HH:mm:ss",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=dd.MM.yyyy"
-},
-reference = {
- @Reference(name="SystemUserManagerPaths",
- bind = "bindSystemUserManagerPaths",
- service = SystemUserManagerPaths.class)
-})
+@Component(
+ service = {Servlet.class, CreateGroup.class},
+ property = {
+ "sling.servlet.resourceTypes=sling/groups",
+ "sling.servlet.methods=POST",
+ "sling.servlet.selectors=create",
+ "sling.servlet.prefix:Integer=-1",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=EEE MMM dd yyyy HH:mm:ss 'GMT'Z",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd'T'HH:mm:ss.SSSZ",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd'T'HH:mm:ss",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=dd.MM.yyyy HH:mm:ss",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=dd.MM.yyyy"
+ },
+ reference = {
+ @Reference(
+ name = "SystemUserManagerPaths",
+ bind = "bindSystemUserManagerPaths",
+ service = SystemUserManagerPaths.class)
+ })
public class CreateGroupServlet extends AbstractGroupPostServlet implements CreateGroup {
private static final long serialVersionUID = -1084915263933901466L;
@Reference
private transient ResourceResolverFactory resourceResolverFactory;
-
+
@Override
@Activate
protected void activate(final Map<String, Object> props) {
@@ -136,8 +138,7 @@ public class CreateGroupServlet extends AbstractGroupPostServlet implements Crea
super.deactivate();
}
- @Reference(cardinality = ReferenceCardinality.MULTIPLE,
- policy = ReferencePolicy.DYNAMIC)
+ @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC)
@Override
protected void bindPrincipalNameGenerator(PrincipalNameGenerator generator, Map<String, Object> properties) {
super.bindPrincipalNameGenerator(generator, properties);
@@ -148,7 +149,8 @@ public class CreateGroupServlet extends AbstractGroupPostServlet implements Crea
super.unbindPrincipalNameGenerator(generator);
}
- @Reference(cardinality = ReferenceCardinality.OPTIONAL,
+ @Reference(
+ cardinality = ReferenceCardinality.OPTIONAL,
policy = ReferencePolicy.DYNAMIC,
policyOption = ReferencePolicyOption.GREEDY)
@Override
@@ -163,13 +165,14 @@ public class CreateGroupServlet extends AbstractGroupPostServlet implements Crea
/**
* Overridden since the @Reference annotation is not inherited from the super method
- *
+ *
* @see org.apache.sling.jackrabbit.usermanager.impl.post.AbstractPostServlet#bindPostResponseCreator(org.apache.sling.servlets.post.JakartaPostResponseCreator, java.util.Map)
*/
@Override
- @Reference(service = JakartaPostResponseCreator.class,
- cardinality = ReferenceCardinality.MULTIPLE,
- policy = ReferencePolicy.DYNAMIC)
+ @Reference(
+ service = JakartaPostResponseCreator.class,
+ cardinality = ReferenceCardinality.MULTIPLE,
+ policy = ReferencePolicy.DYNAMIC)
protected void bindPostResponseCreator(JakartaPostResponseCreator creator, Map<String, Object> properties) {
super.bindPostResponseCreator(creator, properties);
}
@@ -178,10 +181,11 @@ public class CreateGroupServlet extends AbstractGroupPostServlet implements Crea
* @see org.apache.sling.jackrabbit.usermanager.impl.post.AbstractPostServlet#unbindPostResponseCreator(org.apache.sling.servlets.post.JakartaPostResponseCreator, java.util.Map)
*/
@Override
- protected void unbindPostResponseCreator(JakartaPostResponseCreator creator, Map<String, Object> properties) { //NOSONAR
+ protected void unbindPostResponseCreator(
+ JakartaPostResponseCreator creator, Map<String, Object> properties) { // NOSONAR
super.unbindPostResponseCreator(creator, properties);
}
-
+
/*
* (non-Javadoc)
* @see
@@ -190,31 +194,25 @@ public class CreateGroupServlet extends AbstractGroupPostServlet implements Crea
* org.apache.sling.servlets.post.JakartaPostResponse, java.util.List)
*/
@Override
- protected void handleOperation(SlingJakartaHttpServletRequest request,
- JakartaPostResponse response, List<Modification> changes)
+ protected void handleOperation(
+ SlingJakartaHttpServletRequest request, JakartaPostResponse response, List<Modification> changes)
throws RepositoryException {
Session session = request.getResourceResolver().adaptTo(Session.class);
String principalName = request.getParameter(SlingPostConstants.RP_NODE_NAME);
- Group group = createGroup(session,
- principalName,
- request.getRequestParameterMap(),
- changes);
+ Group group = createGroup(session, principalName, request.getRequestParameterMap(), changes);
- String groupPath = systemUserManagerPaths.getGroupPrefix()
- + group.getID();
+ String groupPath = systemUserManagerPaths.getGroupPrefix() + group.getID();
response.setPath(groupPath);
response.setLocation(externalizePath(request, groupPath));
- response.setParentLocation(externalizePath(request,
- systemUserManagerPaths.getGroupsPath()));
-
+ response.setParentLocation(externalizePath(request, systemUserManagerPaths.getGroupsPath()));
}
-
+
/* (non-Javadoc)
* @see org.apache.sling.jackrabbit.usermanager.CreateGroup#createGroup(javax.jcr.Session, java.lang.String, java.util.Map, java.util.List)
*/
- public Group createGroup(Session jcrSession, final String name,
- Map<String, ?> properties, List<Modification> changes)
+ public Group createGroup(
+ Session jcrSession, final String name, Map<String, ?> properties, List<Modification> changes)
throws RepositoryException {
// check that the parameter values have valid values.
if (jcrSession == null) {
@@ -232,21 +230,18 @@ public class CreateGroupServlet extends AbstractGroupPostServlet implements Crea
throw new IllegalArgumentException("Group name was not supplied");
}
- UserManager userManager = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager userManager = ((JackrabbitSession) jcrSession).getUserManager();
Authorizable authorizable = userManager.getAuthorizable(principalName);
Group group = null;
if (authorizable != null) {
// principal already exists!
- throw new RepositoryException(
- "A group already exists with the requested name: "
- + principalName);
+ throw new RepositoryException("A group already exists with the requested name: " + principalName);
} else {
group = userManager.createGroup(() -> principalName);
- String groupPath = systemUserManagerPaths.getGroupPrefix()
- + group.getID();
-
+ String groupPath = systemUserManagerPaths.getGroupPrefix() + group.getID();
+
Map<String, RequestProperty> reqPropertiesMap = collectContentMap(properties);
Collection<RequestProperty> reqPropertyValues = reqPropertiesMap.values();
changes.add(Modification.onCreated(groupPath));
@@ -260,9 +255,10 @@ public class CreateGroupServlet extends AbstractGroupPostServlet implements Crea
// update the group memberships
ResourceResolver resourceResolver = null;
try {
- //create a resource resolver to resolve the relative paths used for group membership values
+ // create a resource resolver to resolve the relative paths used for group membership values
final Map<String, Object> authInfo = new HashMap<>();
- authInfo.put(org.apache.sling.jcr.resource.api.JcrResourceConstants.AUTHENTICATION_INFO_SESSION, jcrSession);
+ authInfo.put(
+ org.apache.sling.jcr.resource.api.JcrResourceConstants.AUTHENTICATION_INFO_SESSION, jcrSession);
resourceResolver = resourceResolverFactory.getResourceResolver(authInfo);
Resource baseResource = resourceResolver.getResource(systemUserManagerPaths.getGroupsPath());
updateGroupMembership(baseResource, properties, group, changes);
@@ -274,8 +270,7 @@ public class CreateGroupServlet extends AbstractGroupPostServlet implements Crea
}
}
}
-
+
return group;
}
-
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/CreateUserServlet.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/CreateUserServlet.java
index fe688c0..116c325 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/CreateUserServlet.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/CreateUserServlet.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.jackrabbit.usermanager.impl.post;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.security.AccessControlManager;
import javax.jcr.security.Privilege;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+
+import jakarta.servlet.Servlet;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.User;
@@ -59,8 +62,6 @@ import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import jakarta.servlet.Servlet;
-
/**
* <p>
* Sling Post Servlet implementation for creating a user in the jackrabbit UserManager.
@@ -108,35 +109,39 @@ import jakarta.servlet.Servlet;
* curl -F:name=ieb -Fpwd=password -FpwdConfirm=password -Fproperty1=value1 http://localhost:8080/system/userManager/user.create.html
* </code>
*/
-@Component(service = {Servlet.class, CreateUser.class},
- property = {
- "sling.servlet.resourceTypes=sling/users",
- "sling.servlet.methods=POST",
- "sling.servlet.selectors=create",
- "sling.servlet.prefix:Integer=-1",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=EEE MMM dd yyyy HH:mm:ss 'GMT'Z",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd'T'HH:mm:ss.SSSZ",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd'T'HH:mm:ss",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=dd.MM.yyyy HH:mm:ss",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=dd.MM.yyyy"
-},
-reference = {
- @Reference(name="SystemUserManagerPaths",
- bind = "bindSystemUserManagerPaths",
- service = SystemUserManagerPaths.class)
-})
+@Component(
+ service = {Servlet.class, CreateUser.class},
+ property = {
+ "sling.servlet.resourceTypes=sling/users",
+ "sling.servlet.methods=POST",
+ "sling.servlet.selectors=create",
+ "sling.servlet.prefix:Integer=-1",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=EEE MMM dd yyyy HH:mm:ss 'GMT'Z",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd'T'HH:mm:ss.SSSZ",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd'T'HH:mm:ss",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=dd.MM.yyyy HH:mm:ss",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=dd.MM.yyyy"
+ },
+ reference = {
+ @Reference(
+ name = "SystemUserManagerPaths",
+ bind = "bindSystemUserManagerPaths",
+ service = SystemUserManagerPaths.class)
+ })
@Designate(ocd = CreateUserServlet.Config.class)
public class CreateUserServlet extends AbstractAuthorizablePostServlet implements CreateUser {
private static final long serialVersionUID = 6871481922737658675L;
- @ObjectClassDefinition(name = "Apache Sling Create User",
+ @ObjectClassDefinition(
+ name = "Apache Sling Create User",
description = "The Sling operation to handle create user requests in Sling.")
public @interface Config {
- @AttributeDefinition(name = "Self-Registration Enabled",
+ @AttributeDefinition(
+ name = "Self-Registration Enabled",
description = "When selected, the anonymous user is allowed to register a new user with the system.")
- boolean self_registration_enabled() default false; //NOSONAR
+ boolean self_registration_enabled() default false; // NOSONAR
}
/**
@@ -160,10 +165,11 @@ public class CreateUserServlet extends AbstractAuthorizablePostServlet implement
private String usersPath;
- @Reference(cardinality=ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC)
+ @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC)
private void bindUserConfiguration(UserConfiguration userConfig, Map<String, Object> properties) {
- usersPath = (String)properties.get(UserConstants.PARAM_USER_PATH);
+ usersPath = (String) properties.get(UserConstants.PARAM_USER_PATH);
}
+
@SuppressWarnings("unused")
private void unbindUserConfiguration(UserConfiguration userConfig, Map<String, Object> properties) {
usersPath = null;
@@ -204,8 +210,7 @@ public class CreateUserServlet extends AbstractAuthorizablePostServlet implement
super.deactivate();
}
- @Reference(cardinality = ReferenceCardinality.MULTIPLE,
- policy = ReferencePolicy.DYNAMIC)
+ @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC)
@Override
protected void bindPrincipalNameGenerator(PrincipalNameGenerator generator, Map<String, Object> properties) {
super.bindPrincipalNameGenerator(generator, properties);
@@ -216,7 +221,8 @@ public class CreateUserServlet extends AbstractAuthorizablePostServlet implement
super.unbindPrincipalNameGenerator(generator);
}
- @Reference(cardinality = ReferenceCardinality.OPTIONAL,
+ @Reference(
+ cardinality = ReferenceCardinality.OPTIONAL,
policy = ReferencePolicy.DYNAMIC,
policyOption = ReferencePolicyOption.GREEDY)
@Override
@@ -231,13 +237,14 @@ public class CreateUserServlet extends AbstractAuthorizablePostServlet implement
/**
* Overridden since the @Reference annotation is not inherited from the super method
- *
+ *
* @see org.apache.sling.jackrabbit.usermanager.impl.post.AbstractPostServlet#bindPostResponseCreator(org.apache.sling.servlets.post.JakartaPostResponseCreator, java.util.Map)
*/
@Override
- @Reference(service = JakartaPostResponseCreator.class,
- cardinality = ReferenceCardinality.MULTIPLE,
- policy = ReferencePolicy.DYNAMIC)
+ @Reference(
+ service = JakartaPostResponseCreator.class,
+ cardinality = ReferenceCardinality.MULTIPLE,
+ policy = ReferencePolicy.DYNAMIC)
protected void bindPostResponseCreator(JakartaPostResponseCreator creator, Map<String, Object> properties) {
super.bindPostResponseCreator(creator, properties);
}
@@ -246,10 +253,11 @@ public class CreateUserServlet extends AbstractAuthorizablePostServlet implement
* @see org.apache.sling.jackrabbit.usermanager.impl.post.AbstractPostServlet#unbindPostResponseCreator(org.apache.sling.servlets.post.JakartaPostResponseCreator, java.util.Map)
*/
@Override
- protected void unbindPostResponseCreator(JakartaPostResponseCreator creator, Map<String, Object> properties) { //NOSONAR
+ protected void unbindPostResponseCreator(
+ JakartaPostResponseCreator creator, Map<String, Object> properties) { // NOSONAR
super.unbindPostResponseCreator(creator, properties);
}
-
+
/*
* (non-Javadoc)
* @see
@@ -258,19 +266,19 @@ public class CreateUserServlet extends AbstractAuthorizablePostServlet implement
* org.apache.sling.servlets.post.JakartaPostResponse, java.util.List)
*/
@Override
- protected void handleOperation(SlingJakartaHttpServletRequest request,
- JakartaPostResponse response, List<Modification> changes)
+ protected void handleOperation(
+ SlingJakartaHttpServletRequest request, JakartaPostResponse response, List<Modification> changes)
throws RepositoryException {
-
Session session = request.getResourceResolver().adaptTo(Session.class);
String principalName = request.getParameter(SlingPostConstants.RP_NODE_NAME);
- User user = createUser(session,
- principalName,
- request.getParameter("pwd"),
- request.getParameter("pwdConfirm"),
- request.getRequestParameterMap(),
- changes);
+ User user = createUser(
+ session,
+ principalName,
+ request.getParameter("pwd"),
+ request.getParameter("pwdConfirm"),
+ request.getRequestParameterMap(),
+ changes);
String userPath = null;
if (user == null) {
@@ -281,27 +289,26 @@ public class CreateUserServlet extends AbstractAuthorizablePostServlet implement
}
}
} else {
- userPath = systemUserManagerPaths.getUserPrefix()
- + user.getID();
+ userPath = systemUserManagerPaths.getUserPrefix() + user.getID();
}
if (userPath != null) {
response.setPath(userPath);
response.setLocation(externalizePath(request, userPath));
}
- response.setParentLocation(externalizePath(request,
- systemUserManagerPaths.getUsersPath()));
+ response.setParentLocation(externalizePath(request, systemUserManagerPaths.getUsersPath()));
}
/* (non-Javadoc)
* @see org.apache.sling.jackrabbit.usermanager.CreateUser#createUser(javax.jcr.Session, java.lang.String, java.lang.String, java.lang.String, java.util.Map, java.util.List)
*/
- public User createUser(Session jcrSession,
- String name,
- String password,
- String passwordConfirm,
- Map<String, ?> properties,
- List<Modification> changes)
+ public User createUser(
+ Session jcrSession,
+ String name,
+ String password,
+ String passwordConfirm,
+ Map<String, ?> properties,
+ List<Modification> changes)
throws RepositoryException {
if (jcrSession == null) {
@@ -318,34 +325,32 @@ public class CreateUserServlet extends AbstractAuthorizablePostServlet implement
// check for an administrator
boolean administrator = false;
try {
- UserManager um = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager um = ((JackrabbitSession) jcrSession).getUserManager();
User currentUser = (User) um.getAuthorizable(jcrSession.getUserID());
administrator = currentUser.isAdmin();
if (!administrator && usersPath != null) {
- //check if the current user has the minimum privileges needed to create a user
+ // check if the current user has the minimum privileges needed to create a user
AccessControlManager acm = jcrSession.getAccessControlManager();
administrator = acm.hasPrivileges(usersPath, new Privilege[] {
- acm.privilegeFromName(Privilege.JCR_READ),
- acm.privilegeFromName(Privilege.JCR_READ_ACCESS_CONTROL),
- acm.privilegeFromName(Privilege.JCR_MODIFY_ACCESS_CONTROL),
- acm.privilegeFromName(PrivilegeConstants.REP_WRITE),
- acm.privilegeFromName(PrivilegeConstants.REP_USER_MANAGEMENT)
- });
+ acm.privilegeFromName(Privilege.JCR_READ),
+ acm.privilegeFromName(Privilege.JCR_READ_ACCESS_CONTROL),
+ acm.privilegeFromName(Privilege.JCR_MODIFY_ACCESS_CONTROL),
+ acm.privilegeFromName(PrivilegeConstants.REP_WRITE),
+ acm.privilegeFromName(PrivilegeConstants.REP_USER_MANAGEMENT)
+ });
}
- } catch ( Exception ex ) {
+ } catch (Exception ex) {
log.warn("Failed to determine if the user is an admin, assuming not. Cause: {}", ex.getMessage());
administrator = false;
}
-
// make sure user self-registration is enabled
if (!administrator && !selfRegistrationEnabled) {
throw new RepositoryException(
- "Sorry, registration of new users is not currently enabled. Please try again later.");
+ "Sorry, registration of new users is not currently enabled. Please try again later.");
}
-
// check that the submitted parameter values have valid values.
if (principalName == null || principalName.length() == 0) {
throw new RepositoryException("User name was not submitted");
@@ -354,8 +359,7 @@ public class CreateUserServlet extends AbstractAuthorizablePostServlet implement
throw new RepositoryException("Password was not submitted");
}
if (!password.equals(passwordConfirm)) {
- throw new RepositoryException(
- "Password value does not match the confirmation password");
+ throw new RepositoryException("Password value does not match the confirmation password");
}
User user = null;
@@ -363,24 +367,21 @@ public class CreateUserServlet extends AbstractAuthorizablePostServlet implement
boolean useAdminSession = !administrator && selfRegistrationEnabled;
try {
if (useAdminSession) {
- //the current user doesn't have permission to create the user,
+ // the current user doesn't have permission to create the user,
// but self-registration is enabled, so use an admin session
// to do the work.
selfRegSession = getSession();
}
- UserManager userManager = ((JackrabbitSession)selfRegSession).getUserManager();
+ UserManager userManager = ((JackrabbitSession) selfRegSession).getUserManager();
Authorizable authorizable = userManager.getAuthorizable(principalName);
if (authorizable != null) {
// user already exists!
- throw new RepositoryException(
- "A principal already exists with the requested name: "
- + principalName);
+ throw new RepositoryException("A principal already exists with the requested name: " + principalName);
} else {
user = userManager.createUser(principalName, password);
- String userPath = systemUserManagerPaths.getUserPrefix()
- + user.getID();
+ String userPath = systemUserManagerPaths.getUserPrefix() + user.getID();
Map<String, RequestProperty> reqPropertiesMap = collectContentMap(properties);
Collection<RequestProperty> reqPropertyValues = reqPropertiesMap.values();
@@ -398,8 +399,8 @@ public class CreateUserServlet extends AbstractAuthorizablePostServlet implement
}
if (useAdminSession) {
- //lookup the user from the user session so we can return a live object
- UserManager userManager2 = ((JackrabbitSession)jcrSession).getUserManager();
+ // lookup the user from the user session so we can return a live object
+ UserManager userManager2 = ((JackrabbitSession) jcrSession).getUserManager();
Authorizable authorizable2 = userManager2.getAuthorizable(user.getID());
if (authorizable2 instanceof User u) {
user = u;
@@ -410,12 +411,11 @@ public class CreateUserServlet extends AbstractAuthorizablePostServlet implement
}
} finally {
if (useAdminSession) {
- //done with the self-reg admin session, so clean it up
+ // done with the self-reg admin session, so clean it up
ungetSession(selfRegSession);
}
}
return user;
}
-
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/DeleteAuthorizableServlet.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/DeleteAuthorizableServlet.java
index c12c3c0..7b470d4 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/DeleteAuthorizableServlet.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/DeleteAuthorizableServlet.java
@@ -1,29 +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.jackrabbit.usermanager.impl.post;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
+import jakarta.servlet.Servlet;
+import jakarta.servlet.http.HttpServletResponse;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
@@ -46,9 +50,6 @@ import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
-import jakarta.servlet.Servlet;
-import jakarta.servlet.http.HttpServletResponse;
-
/**
* <h2>Rest Service Description</h2>
* <p>
@@ -77,37 +78,38 @@ import jakarta.servlet.http.HttpServletResponse;
* <dd>Failure</dd>
* </dl>
* <h3>Example</h3>
- *
+ *
* <code>
* curl -Fgo=1 http://localhost:8080/system/userManager/user/ieb.delete.html
* </code>
*/
-
-@Component(service = {Servlet.class, DeleteUser.class, DeleteGroup.class, DeleteAuthorizables.class},
- property = {
- "sling.servlet.resourceTypes=sling/user",
- "sling.servlet.resourceTypes=sling/group",
- "sling.servlet.resourceTypes=sling/userManager",
- "sling.servlet.methods=POST",
- "sling.servlet.selectors=delete",
- "sling.servlet.prefix:Integer=-1"
-})
+@Component(
+ service = {Servlet.class, DeleteUser.class, DeleteGroup.class, DeleteAuthorizables.class},
+ property = {
+ "sling.servlet.resourceTypes=sling/user",
+ "sling.servlet.resourceTypes=sling/group",
+ "sling.servlet.resourceTypes=sling/userManager",
+ "sling.servlet.methods=POST",
+ "sling.servlet.selectors=delete",
+ "sling.servlet.prefix:Integer=-1"
+ })
public class DeleteAuthorizableServlet extends AbstractPostServlet
implements DeleteUser, DeleteGroup, DeleteAuthorizables {
private static final long serialVersionUID = 5874621724096106496L;
- @Reference
+ @Reference
private transient SystemUserManagerPaths systemUserManagerPaths;
/**
* Overridden since the @Reference annotation is not inherited from the super method
- *
+ *
* @see org.apache.sling.jackrabbit.usermanager.impl.post.AbstractPostServlet#bindPostResponseCreator(org.apache.sling.servlets.post.JakartaPostResponseCreator, java.util.Map)
*/
@Override
- @Reference(service = JakartaPostResponseCreator.class,
- cardinality = ReferenceCardinality.MULTIPLE,
- policy = ReferencePolicy.DYNAMIC)
+ @Reference(
+ service = JakartaPostResponseCreator.class,
+ cardinality = ReferenceCardinality.MULTIPLE,
+ policy = ReferencePolicy.DYNAMIC)
protected void bindPostResponseCreator(JakartaPostResponseCreator creator, Map<String, Object> properties) {
super.bindPostResponseCreator(creator, properties);
}
@@ -116,7 +118,8 @@ public class DeleteAuthorizableServlet extends AbstractPostServlet
* @see org.apache.sling.jackrabbit.usermanager.impl.post.AbstractPostServlet#unbindPostResponseCreator(org.apache.sling.servlets.post.JakartaPostResponseCreator, java.util.Map)
*/
@Override
- protected void unbindPostResponseCreator(JakartaPostResponseCreator creator, Map<String, Object> properties) { //NOSONAR
+ protected void unbindPostResponseCreator(
+ JakartaPostResponseCreator creator, Map<String, Object> properties) { // NOSONAR
super.unbindPostResponseCreator(creator, properties);
}
@@ -128,23 +131,19 @@ public class DeleteAuthorizableServlet extends AbstractPostServlet
* org.apache.sling.servlets.post.JakartaPostResponse, java.util.List)
*/
@Override
- protected void handleOperation(SlingJakartaHttpServletRequest request,
- JakartaPostResponse response, List<Modification> changes)
+ protected void handleOperation(
+ SlingJakartaHttpServletRequest request, JakartaPostResponse response, List<Modification> changes)
throws RepositoryException {
Session session = request.getResourceResolver().adaptTo(Session.class);
Resource resource = request.getResource();
String[] applyTo = request.getParameterValues(SlingPostConstants.RP_APPLY_TO);
if (applyTo != null) {
- deleteAuthorizables(session,
- resource,
- applyTo,
- changes);
+ deleteAuthorizables(session, resource, applyTo, changes);
} else {
Authorizable item = resource.adaptTo(Authorizable.class);
if (item == null) {
- String msg = "Missing source " + resource.getPath()
- + " for delete";
+ String msg = "Missing source " + resource.getPath() + " for delete";
response.setStatus(HttpServletResponse.SC_NOT_FOUND, msg);
throw new ResourceNotFoundException(msg);
} else {
@@ -156,48 +155,41 @@ public class DeleteAuthorizableServlet extends AbstractPostServlet
}
}
}
-
+
/* (non-Javadoc)
* @see org.apache.sling.jackrabbit.usermanager.DeleteUser#deleteUser(javax.jcr.Session, java.lang.String, java.util.List)
*/
- public void deleteUser(Session jcrSession, String name,
- List<Modification> changes) throws RepositoryException {
+ public void deleteUser(Session jcrSession, String name, List<Modification> changes) throws RepositoryException {
User user;
- UserManager userManager = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager userManager = ((JackrabbitSession) jcrSession).getUserManager();
Authorizable authorizable = userManager.getAuthorizable(name);
if (authorizable instanceof User u) {
user = u;
} else {
- throw new ResourceNotFoundException(
- "User to delete could not be determined");
+ throw new ResourceNotFoundException("User to delete could not be determined");
}
-
- String userPath = systemUserManagerPaths.getUserPrefix()
- + user.getID();
+
+ String userPath = systemUserManagerPaths.getUserPrefix() + user.getID();
user.remove();
changes.add(Modification.onDeleted(userPath));
}
-
+
/* (non-Javadoc)
* @see org.apache.sling.jackrabbit.usermanager.DeleteGroup#deleteGroup(javax.jcr.Session, java.lang.String, java.util.List)
*/
- public void deleteGroup(Session jcrSession,
- String name,
- List<Modification> changes) throws RepositoryException {
+ public void deleteGroup(Session jcrSession, String name, List<Modification> changes) throws RepositoryException {
Group group;
- UserManager userManager = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager userManager = ((JackrabbitSession) jcrSession).getUserManager();
Authorizable authorizable = userManager.getAuthorizable(name);
if (authorizable instanceof Group g) {
group = g;
} else {
- throw new ResourceNotFoundException(
- "Group to delete could not be determined");
+ throw new ResourceNotFoundException("Group to delete could not be determined");
}
-
- String groupPath = systemUserManagerPaths.getGroupPrefix()
- + group.getID();
+
+ String groupPath = systemUserManagerPaths.getGroupPrefix() + group.getID();
group.remove();
changes.add(Modification.onDeleted(groupPath));
}
@@ -205,10 +197,8 @@ public class DeleteAuthorizableServlet extends AbstractPostServlet
/* (non-Javadoc)
* @see org.apache.sling.jackrabbit.usermanager.DeleteAuthorizables#deleteAuthorizables(javax.jcr.Session, org.apache.sling.api.resource.Resource, java.lang.String[], java.util.List)
*/
- public void deleteAuthorizables(Session jcrSession,
- Resource baseResource,
- String[] paths,
- List<Modification> changes)
+ public void deleteAuthorizables(
+ Session jcrSession, Resource baseResource, String[] paths, List<Modification> changes)
throws RepositoryException {
ApplyToIterator iterator = new ApplyToIterator(baseResource, paths);
@@ -228,13 +218,13 @@ public class DeleteAuthorizableServlet extends AbstractPostServlet
private final Resource baseResource;
- private final String [] paths;
+ private final String[] paths;
private int pathIndex;
private Resource nextResource;
- ApplyToIterator(Resource baseResource, String [] paths) {
+ ApplyToIterator(Resource baseResource, String[] paths) {
this.resolver = baseResource.getResourceResolver();
this.baseResource = baseResource;
this.paths = paths;
@@ -278,5 +268,4 @@ public class DeleteAuthorizableServlet extends AbstractPostServlet
return null;
}
}
-
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/PrincipalNameGeneratorImpl.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/PrincipalNameGeneratorImpl.java
index 59c077f..b3a2f70 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/PrincipalNameGeneratorImpl.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/PrincipalNameGeneratorImpl.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.jackrabbit.usermanager.impl.post;
@@ -35,11 +37,11 @@ import org.osgi.service.metatype.annotations.Designate;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
/**
- * Default implementation that generates a principal name based on a set of
+ * Default implementation that generates a principal name based on a set of
* well-known request parameters
- *
+ *
* <p>
- * The value is resolved by the locating the first request parameter that is a
+ * The value is resolved by the locating the first request parameter that is a
* match of one of the choices in the following order:
* </p>
* <ol>
@@ -56,25 +58,27 @@ import org.osgi.service.metatype.annotations.ObjectClassDefinition;
@Designate(ocd = PrincipalNameGeneratorImpl.Config.class)
public class PrincipalNameGeneratorImpl implements PrincipalNameGenerator {
- @ObjectClassDefinition(name = "Apache Sling Principal Name Generator",
+ @ObjectClassDefinition(
+ name = "Apache Sling Principal Name Generator",
description = "The Sling helper to generate a principal name from a hint")
public @interface Config {
- @AttributeDefinition(name = "Maximum Principal Name Length",
- description = "Maximum number of characters to "+
- "use for automatically generated principal names. The default value is 20. Note, "+
- "that actual principal names may be generated with at most 4 more characters if "+
- "numeric suffixes must be appended to make the name unique.")
+ @AttributeDefinition(
+ name = "Maximum Principal Name Length",
+ description = "Maximum number of characters to "
+ + "use for automatically generated principal names. The default value is 20. Note, "
+ + "that actual principal names may be generated with at most 4 more characters if "
+ + "numeric suffixes must be appended to make the name unique.")
int principalNameMaxLength() default DEFAULT_MAX_NAME_LENGTH;
- @AttributeDefinition(name = "Principal Name Hint Properties",
- description = "The list of properties whose values "+
- "may be used to derive a name for newly created principal. When handling a request "+
- "to create a new principal, the name is automatically generated from this set if "+
- "no \":name\" or \":nameHint\" property is provided. In this case the request "+
- "parameters listed in this configuration value may be used as a hint to create the name.")
+ @AttributeDefinition(
+ name = "Principal Name Hint Properties",
+ description = "The list of properties whose values "
+ + "may be used to derive a name for newly created principal. When handling a request "
+ + "to create a new principal, the name is automatically generated from this set if "
+ + "no \":name\" or \":nameHint\" property is provided. In this case the request "
+ + "parameters listed in this configuration value may be used as a hint to create the name.")
String[] principalNameHints();
-
}
private String[] parameterNames;
@@ -94,9 +98,7 @@ public class PrincipalNameGeneratorImpl implements PrincipalNameGenerator {
this.parameterNames = parameterNames;
}
- this.maxLength = (maxNameLength > 0)
- ? maxNameLength
- : DEFAULT_MAX_NAME_LENGTH;
+ this.maxLength = (maxNameLength > 0) ? maxNameLength : DEFAULT_MAX_NAME_LENGTH;
}
@Activate
@@ -156,7 +158,8 @@ public class PrincipalNameGeneratorImpl implements PrincipalNameGenerator {
// check for a paramName@ValueFrom param
// SLING-130: VALUE_FROM_SUFFIX means take the value of this
// property from a different field
- values = valueToList(parameters.get(String.format("%s%s", paramName, SlingPostConstants.VALUE_FROM_SUFFIX)));
+ values =
+ valueToList(parameters.get(String.format("%s%s", paramName, SlingPostConstants.VALUE_FROM_SUFFIX)));
if (!values.isEmpty()) {
for (String specialParam : values) {
if (specialParam != null && !specialParam.isEmpty()) {
@@ -196,8 +199,11 @@ public class PrincipalNameGeneratorImpl implements PrincipalNameGenerator {
* @return the principal name to be created or null if other PrincipalNameGenerators should be consulted
*/
@Override
- public NameInfo getPrincipalName(Map<String, ?> parameters, AuthorizableType type,
- PrincipalNameFilter principalNameFilter, PrincipalNameGenerator defaultPrincipalNameGenerator) {
+ public NameInfo getPrincipalName(
+ Map<String, ?> parameters,
+ AuthorizableType type,
+ PrincipalNameFilter principalNameFilter,
+ PrincipalNameGenerator defaultPrincipalNameGenerator) {
String valueToUse = null;
boolean doFilter = true;
@@ -208,7 +214,7 @@ public class PrincipalNameGeneratorImpl implements PrincipalNameGenerator {
if (valueToUse != null) {
doFilter = false;
}
- if ( valueToUse == null ) {
+ if (valueToUse == null) {
valueToUse = getValueToUse(parameters, SlingPostConstants.RP_NODE_NAME_HINT);
if (valueToUse == null && parameterNames != null) {
@@ -239,5 +245,4 @@ public class PrincipalNameGeneratorImpl implements PrincipalNameGenerator {
return null;
}
}
-
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/UpdateGroupServlet.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/UpdateGroupServlet.java
index 6aa188a..575296a 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/UpdateGroupServlet.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/UpdateGroupServlet.java
@@ -1,29 +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.jackrabbit.usermanager.impl.post;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
+import jakarta.servlet.Servlet;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
@@ -48,11 +51,9 @@ import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
-import jakarta.servlet.Servlet;
-
/**
* <p>
- * Sling Post Operation implementation for updating a group in the
+ * Sling Post Operation implementation for updating a group in the
* jackrabbit UserManager.
* </p>
* <h2>Rest Service Description</h2>
@@ -84,32 +85,32 @@ import jakarta.servlet.Servlet;
* <dd>Failure</dd>
* </dl>
* <h3>Example</h3>
- *
+ *
* <code>
* curl -Fprop1=value2 -Fproperty1=value1 http://localhost:8080/system/userManager/group/testGroup.update.html
* </code>
*/
-
-@Component(service = {Servlet.class, UpdateGroup.class},
-property = {
- "sling.servlet.resourceTypes=sling/group",
- "sling.servlet.methods=POST",
- "sling.servlet.selectors=update",
- "sling.servlet.prefix:Integer=-1",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=EEE MMM dd yyyy HH:mm:ss 'GMT'Z",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd'T'HH:mm:ss.SSSZ",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd'T'HH:mm:ss",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=dd.MM.yyyy HH:mm:ss",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=dd.MM.yyyy"
-},
-reference = {
- @Reference(name="SystemUserManagerPaths",
- bind = "bindSystemUserManagerPaths",
- service = SystemUserManagerPaths.class)
-})
-public class UpdateGroupServlet extends AbstractGroupPostServlet
- implements UpdateGroup {
+@Component(
+ service = {Servlet.class, UpdateGroup.class},
+ property = {
+ "sling.servlet.resourceTypes=sling/group",
+ "sling.servlet.methods=POST",
+ "sling.servlet.selectors=update",
+ "sling.servlet.prefix:Integer=-1",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=EEE MMM dd yyyy HH:mm:ss 'GMT'Z",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd'T'HH:mm:ss.SSSZ",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd'T'HH:mm:ss",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=dd.MM.yyyy HH:mm:ss",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=dd.MM.yyyy"
+ },
+ reference = {
+ @Reference(
+ name = "SystemUserManagerPaths",
+ bind = "bindSystemUserManagerPaths",
+ service = SystemUserManagerPaths.class)
+ })
+public class UpdateGroupServlet extends AbstractGroupPostServlet implements UpdateGroup {
private static final long serialVersionUID = -8292054361992488797L;
@Reference
@@ -129,13 +130,14 @@ public class UpdateGroupServlet extends AbstractGroupPostServlet
/**
* Overridden since the @Reference annotation is not inherited from the super method
- *
+ *
* @see org.apache.sling.jackrabbit.usermanager.impl.post.AbstractPostServlet#bindPostResponseCreator(org.apache.sling.servlets.post.JakartaPostResponseCreator, java.util.Map)
*/
@Override
- @Reference(service = JakartaPostResponseCreator.class,
- cardinality = ReferenceCardinality.MULTIPLE,
- policy = ReferencePolicy.DYNAMIC)
+ @Reference(
+ service = JakartaPostResponseCreator.class,
+ cardinality = ReferenceCardinality.MULTIPLE,
+ policy = ReferencePolicy.DYNAMIC)
protected void bindPostResponseCreator(JakartaPostResponseCreator creator, Map<String, Object> properties) {
super.bindPostResponseCreator(creator, properties);
}
@@ -144,7 +146,8 @@ public class UpdateGroupServlet extends AbstractGroupPostServlet
* @see org.apache.sling.jackrabbit.usermanager.impl.post.AbstractPostServlet#unbindPostResponseCreator(org.apache.sling.servlets.post.JakartaPostResponseCreator, java.util.Map)
*/
@Override
- protected void unbindPostResponseCreator(JakartaPostResponseCreator creator, Map<String, Object> properties) { //NOSONAR
+ protected void unbindPostResponseCreator(
+ JakartaPostResponseCreator creator, Map<String, Object> properties) { // NOSONAR
super.unbindPostResponseCreator(creator, properties);
}
@@ -156,43 +159,36 @@ public class UpdateGroupServlet extends AbstractGroupPostServlet
* org.apache.sling.servlets.post.JakartaPostResponse, java.util.List)
*/
@Override
- protected void handleOperation(SlingJakartaHttpServletRequest request,
- JakartaPostResponse response, List<Modification> changes)
+ protected void handleOperation(
+ SlingJakartaHttpServletRequest request, JakartaPostResponse response, List<Modification> changes)
throws RepositoryException {
Resource resource = request.getResource();
Session session = request.getResourceResolver().adaptTo(Session.class);
- updateGroup(session,
- resource.getName(),
- request.getRequestParameterMap(),
- changes);
+ updateGroup(session, resource.getName(), request.getRequestParameterMap(), changes);
}
/* (non-Javadoc)
* @see org.apache.sling.jackrabbit.usermanager.UpdateGroup#updateGroup(javax.jcr.Session, java.lang.String, java.util.Map, java.util.List)
*/
- public Group updateGroup(Session jcrSession,
- String name,
- Map<String, ?> properties,
- List<Modification> changes)
+ public Group updateGroup(Session jcrSession, String name, Map<String, ?> properties, List<Modification> changes)
throws RepositoryException {
Group group = null;
- UserManager userManager = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager userManager = ((JackrabbitSession) jcrSession).getUserManager();
Authorizable authorizable = userManager.getAuthorizable(name);
if (authorizable instanceof Group g) {
group = g;
} else {
- throw new ResourceNotFoundException(
- "Group to update could not be determined");
+ throw new ResourceNotFoundException("Group to update could not be determined");
}
- String groupPath = systemUserManagerPaths.getGroupPrefix()
- + group.getID();
+ String groupPath = systemUserManagerPaths.getGroupPrefix() + group.getID();
Map<String, RequestProperty> reqPropertiesMap = collectContentMap(properties);
Collection<RequestProperty> reqPropertyValues = reqPropertiesMap.values();
// create a resource resolver to resolve the relative paths used for group membership values
- try (ResourceResolver resourceResolver = resourceResolverFactory.getResourceResolver(Collections.singletonMap(JcrResourceConstants.AUTHENTICATION_INFO_SESSION, jcrSession))) {
+ try (ResourceResolver resourceResolver = resourceResolverFactory.getResourceResolver(
+ Collections.singletonMap(JcrResourceConstants.AUTHENTICATION_INFO_SESSION, jcrSession))) {
// cleanup any old content (@Delete parameters)
processDeletes(group, reqPropertyValues, changes);
@@ -210,5 +206,4 @@ public class UpdateGroupServlet extends AbstractGroupPostServlet
}
return group;
}
-
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/UpdateUserServlet.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/UpdateUserServlet.java
index a078bad..c464ab8 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/UpdateUserServlet.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/post/UpdateUserServlet.java
@@ -1,28 +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.jackrabbit.usermanager.impl.post;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
import java.util.Collection;
import java.util.List;
import java.util.Map;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
+import jakarta.servlet.Servlet;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.User;
@@ -43,8 +46,6 @@ import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
-import jakarta.servlet.Servlet;
-
/**
* <p>
* Sling Post Operation implementation for updating a user in the jackrabbit UserManager.
@@ -83,28 +84,28 @@ import jakarta.servlet.Servlet;
* curl -Fprop1=value2 -Fproperty1=value1 http://localhost:8080/system/userManager/user/ieb.update.html
* </code>
*/
+@Component(
+ service = {Servlet.class, UpdateUser.class},
+ property = {
+ "sling.servlet.resourceTypes=sling/user",
+ "sling.servlet.methods=POST",
+ "sling.servlet.selectors=update",
+ "sling.servlet.prefix:Integer=-1",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=EEE MMM dd yyyy HH:mm:ss 'GMT'Z",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd'T'HH:mm:ss.SSSZ",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd'T'HH:mm:ss",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=dd.MM.yyyy HH:mm:ss",
+ AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=dd.MM.yyyy"
+ },
+ reference = {
+ @Reference(
+ name = "SystemUserManagerPaths",
+ bind = "bindSystemUserManagerPaths",
+ service = SystemUserManagerPaths.class)
+ })
+public class UpdateUserServlet extends AbstractAuthorizablePostServlet implements UpdateUser {
-@Component(service = {Servlet.class, UpdateUser.class},
-property = {
- "sling.servlet.resourceTypes=sling/user",
- "sling.servlet.methods=POST",
- "sling.servlet.selectors=update",
- "sling.servlet.prefix:Integer=-1",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=EEE MMM dd yyyy HH:mm:ss 'GMT'Z",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd'T'HH:mm:ss.SSSZ",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd'T'HH:mm:ss",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=yyyy-MM-dd",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=dd.MM.yyyy HH:mm:ss",
- AbstractAuthorizablePostServlet.PROP_DATE_FORMAT + "=dd.MM.yyyy"
-},
-reference = {
- @Reference(name="SystemUserManagerPaths",
- bind = "bindSystemUserManagerPaths",
- service = SystemUserManagerPaths.class)
-})
-public class UpdateUserServlet extends AbstractAuthorizablePostServlet
- implements UpdateUser {
-
private static final long serialVersionUID = 5874621724096106496L;
@Override
@@ -115,19 +116,20 @@ public class UpdateUserServlet extends AbstractAuthorizablePostServlet
@Override
@Deactivate
- protected void deactivate( ) {
+ protected void deactivate() {
super.deactivate();
}
/**
* Overridden since the @Reference annotation is not inherited from the super method
- *
+ *
* @see org.apache.sling.jackrabbit.usermanager.impl.post.AbstractPostServlet#bindPostResponseCreator(org.apache.sling.servlets.post.JakartaPostResponseCreator, java.util.Map)
*/
@Override
- @Reference(service = JakartaPostResponseCreator.class,
- cardinality = ReferenceCardinality.MULTIPLE,
- policy = ReferencePolicy.DYNAMIC)
+ @Reference(
+ service = JakartaPostResponseCreator.class,
+ cardinality = ReferenceCardinality.MULTIPLE,
+ policy = ReferencePolicy.DYNAMIC)
protected void bindPostResponseCreator(JakartaPostResponseCreator creator, Map<String, Object> properties) {
super.bindPostResponseCreator(creator, properties);
}
@@ -136,7 +138,8 @@ public class UpdateUserServlet extends AbstractAuthorizablePostServlet
* @see org.apache.sling.jackrabbit.usermanager.impl.post.AbstractPostServlet#unbindPostResponseCreator(org.apache.sling.servlets.post.JakartaPostResponseCreator, java.util.Map)
*/
@Override
- protected void unbindPostResponseCreator(JakartaPostResponseCreator creator, Map<String, Object> properties) { //NOSONAR
+ protected void unbindPostResponseCreator(
+ JakartaPostResponseCreator creator, Map<String, Object> properties) { // NOSONAR
super.unbindPostResponseCreator(creator, properties);
}
@@ -148,32 +151,27 @@ public class UpdateUserServlet extends AbstractAuthorizablePostServlet
* org.apache.sling.servlets.post.JakartaPostResponse, java.util.List)
*/
@Override
- protected void handleOperation(SlingJakartaHttpServletRequest request,
- JakartaPostResponse response, List<Modification> changes)
+ protected void handleOperation(
+ SlingJakartaHttpServletRequest request, JakartaPostResponse response, List<Modification> changes)
throws RepositoryException {
Resource resource = request.getResource();
Session session = request.getResourceResolver().adaptTo(Session.class);
- updateUser(session,
- resource.getName(),
- request.getRequestParameterMap(),
- changes);
+ updateUser(session, resource.getName(), request.getRequestParameterMap(), changes);
}
/* (non-Javadoc)
* @see org.apache.sling.jackrabbit.usermanager.UpdateUser#updateUser(javax.jcr.Session, java.lang.String, java.util.Map, java.util.List)
*/
- public User updateUser(Session jcrSession, String name,
- Map<String, ?> properties, List<Modification> changes)
+ public User updateUser(Session jcrSession, String name, Map<String, ?> properties, List<Modification> changes)
throws RepositoryException {
User user;
- UserManager userManager = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager userManager = ((JackrabbitSession) jcrSession).getUserManager();
Authorizable authorizable = userManager.getAuthorizable(name);
if (authorizable instanceof User u) {
user = u;
} else {
- throw new ResourceNotFoundException(
- "User to update could not be determined");
+ throw new ResourceNotFoundException("User to update could not be determined");
}
Map<String, RequestProperty> reqPropertiesMap = collectContentMap(properties);
@@ -188,18 +186,18 @@ public class UpdateUserServlet extends AbstractAuthorizablePostServlet
// write content from form
writeContent(jcrSession, user, reqPropertyValues, changes);
- //SLING-2072 set the user as enabled or disabled if the request
+ // SLING-2072 set the user as enabled or disabled if the request
// has supplied the relevant properties
String disabledParam = convertToString(properties.get(":disabled"));
if ("true".equalsIgnoreCase(disabledParam)) {
- //set the user as disabled
+ // set the user as disabled
String disabledReason = convertToString(properties.get(":disabledReason"));
if (disabledReason == null) {
disabledReason = "";
}
user.disable(disabledReason);
} else if ("false".equalsIgnoreCase(disabledParam)) {
- //re-enable a disabled user
+ // re-enable a disabled user
user.disable(null);
}
} catch (RepositoryException re) {
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/AuthorizableResource.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/AuthorizableResource.java
index 89a27b1..23cf1bb 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/AuthorizableResource.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/AuthorizableResource.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.jackrabbit.usermanager.impl.resource;
-import java.util.Map;
-
import javax.jcr.RepositoryException;
+import java.util.Map;
+
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.User;
@@ -33,18 +35,26 @@ import org.apache.sling.jackrabbit.usermanager.resource.SystemUserManagerPaths;
/**
* Resource implementation for Authorizable
*/
-@Adaptable(adaptableClass = Resource.class, adapters = {
- @Adapter({Map.class, ValueMap.class, Authorizable.class}),
- @Adapter(condition="If the resource is an AuthorizableResource and represents a JCR User", value = User.class),
- @Adapter(condition="If the resource is an AuthorizableResource and represents a JCR Group", value = Group.class)
-})
+@Adaptable(
+ adaptableClass = Resource.class,
+ adapters = {
+ @Adapter({Map.class, ValueMap.class, Authorizable.class}),
+ @Adapter(
+ condition = "If the resource is an AuthorizableResource and represents a JCR User",
+ value = User.class),
+ @Adapter(
+ condition = "If the resource is an AuthorizableResource and represents a JCR Group",
+ value = Group.class)
+ })
public class AuthorizableResource extends BaseResource {
protected final Authorizable authorizable;
private final String resourceType;
protected final SystemUserManagerPaths systemUserManagerPaths;
- public AuthorizableResource(Authorizable authorizable,
- ResourceResolver resourceResolver, String path,
+ public AuthorizableResource(
+ Authorizable authorizable,
+ ResourceResolver resourceResolver,
+ String path,
SystemUserManagerPaths systemUserManagerPaths) {
super(resourceResolver, path);
@@ -84,8 +94,8 @@ public class AuthorizableResource extends BaseResource {
ValueMap valueMap = new AuthorizableValueMap(authorizable, systemUserManagerPaths);
return type.cast(valueMap);
} else if (type == Authorizable.class
- || (type == User.class && !authorizable.isGroup())
- || (type == Group.class && authorizable.isGroup())) {
+ || (type == User.class && !authorizable.isGroup())
+ || (type == Group.class && authorizable.isGroup())) {
return type.cast(authorizable);
}
@@ -101,7 +111,6 @@ public class AuthorizableResource extends BaseResource {
// ignore it.
}
}
- return getClass().getSimpleName() + ", id=" + id + ", path="
- + getPath();
+ return getClass().getSimpleName() + ", id=" + id + ", path=" + getPath();
}
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/AuthorizableResourceProvider.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/AuthorizableResourceProvider.java
index e80192c..f950734 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/AuthorizableResourceProvider.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/AuthorizableResourceProvider.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.jackrabbit.usermanager.impl.resource;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collections;
@@ -23,9 +28,6 @@ import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.principal.GroupPrincipal;
import org.apache.jackrabbit.api.security.principal.PrincipalIterator;
@@ -56,26 +58,30 @@ import org.slf4j.LoggerFactory;
/**
* Resource Provider implementation for jackrabbit UserManager resources.
*/
-@Component(service = { ResourceProvider.class, SystemUserManagerPaths.class },
- property={
+@Component(
+ service = {ResourceProvider.class, SystemUserManagerPaths.class},
+ property = {
"service.description=Resource provider implementation for UserManager resources",
"service.vendor=The Apache Software Foundation",
ResourceProvider.PROPERTY_ROOT + "=" + AuthorizableResourceProvider.DEFAULT_SYSTEM_USER_MANAGER_PATH
- })
-@Designate(ocd=AuthorizableResourceProvider.Config.class)
+ })
+@Designate(ocd = AuthorizableResourceProvider.Config.class)
public class AuthorizableResourceProvider extends ResourceProvider<Object> implements SystemUserManagerPaths {
- @ObjectClassDefinition(name ="Apache Sling UserManager Resource Provider")
+ @ObjectClassDefinition(name = "Apache Sling UserManager Resource Provider")
public @interface Config {
- @AttributeDefinition(name = "Provider Root",
+ @AttributeDefinition(
+ name = "Provider Root",
description = "Specifies the root path for the UserManager resources.")
- String provider_root() default DEFAULT_SYSTEM_USER_MANAGER_PATH; //NOSONAR
-
- @AttributeDefinition(name = "Provide Resources For Nested Properties",
- description = "Specifies whether container resources are provided for any nested authorizable properties. "
- + "The resourceType for these ancestor resources would be 'sling/[user|group]/properties'")
- boolean resources_for_nested_properties() default false; //NOSONAR
+ String provider_root() default DEFAULT_SYSTEM_USER_MANAGER_PATH; // NOSONAR
+
+ @AttributeDefinition(
+ name = "Provide Resources For Nested Properties",
+ description =
+ "Specifies whether container resources are provided for any nested authorizable properties. "
+ + "The resourceType for these ancestor resources would be 'sling/[user|group]/properties'")
+ boolean resources_for_nested_properties() default false; // NOSONAR
}
/**
@@ -89,7 +95,7 @@ public class AuthorizableResourceProvider extends ResourceProvider<Object> imple
private String systemUserManagerGroupPath;
private String systemUserManagerGroupPrefix;
- public static final String DEFAULT_SYSTEM_USER_MANAGER_PATH = "/system/userManager"; //NOSONAR
+ public static final String DEFAULT_SYSTEM_USER_MANAGER_PATH = "/system/userManager"; // NOSONAR
private boolean resourcesForNestedProperties = true;
@@ -102,7 +108,7 @@ public class AuthorizableResourceProvider extends ResourceProvider<Object> imple
systemUserManagerGroupPrefix = String.format("%s/", systemUserManagerGroupPath);
resourcesForNestedProperties = config.resources_for_nested_properties();
}
-
+
/* (non-Javadoc)
* @see org.apache.sling.jackrabbit.usermanager.impl.resource.SystemUserManagerPaths#getPath()
*/
@@ -144,15 +150,12 @@ public class AuthorizableResourceProvider extends ResourceProvider<Object> imple
}
@Override
- public Resource getResource(ResolveContext<Object> ctx,
- String path,
- ResourceContext resourceContext,
- Resource parent) {
+ public Resource getResource(
+ ResolveContext<Object> ctx, String path, ResourceContext resourceContext, Resource parent) {
// handle resources for the virtual container resources
if (path.equals(systemUserManagerPath)) {
- return new SyntheticResource(ctx.getResourceResolver(), path,
- "sling/userManager");
+ return new SyntheticResource(ctx.getResourceResolver(), path, "sling/userManager");
} else if (path.equals(systemUserManagerUserPath)) {
return new SyntheticResource(ctx.getResourceResolver(), path, "sling/users");
} else if (path.equals(systemUserManagerGroupPath)) {
@@ -164,26 +167,23 @@ public class AuthorizableResourceProvider extends ResourceProvider<Object> imple
// found the Authorizable, so return the resource
// that wraps it.
if (relPath == null) {
- result = new AuthorizableResource(authorizable,
- ctx.getResourceResolver(), path,
- AuthorizableResourceProvider.this);
+ result = new AuthorizableResource(
+ authorizable, ctx.getResourceResolver(), path, AuthorizableResourceProvider.this);
} else if (resourcesForNestedProperties) {
// check if the relPath resolves valid property names
Iterator<String> propertyNames = getPropertyNames(relPath, authorizable);
if (propertyNames.hasNext()) {
// provide a resource that wraps for the specific nested properties
- result = new NestedAuthorizableResource(authorizable,
- ctx.getResourceResolver(), path,
- AuthorizableResourceProvider.this,
- relPath);
+ result = new NestedAuthorizableResource(
+ authorizable, ctx.getResourceResolver(), path, AuthorizableResourceProvider.this, relPath);
}
}
return result;
};
// found the Principal, so return the resource
// that wraps it.
- PrincipalWorker<Resource> principalWorker = principal -> new PrincipalResource(principal,
- ctx.getResourceResolver(), path);
+ PrincipalWorker<Resource> principalWorker =
+ principal -> new PrincipalResource(principal, ctx.getResourceResolver(), path);
return maybeDoAuthorizableWork(ctx, path, authorizableWorker, principalWorker);
}
@@ -191,8 +191,11 @@ public class AuthorizableResourceProvider extends ResourceProvider<Object> imple
* If the path resolves to a user or group (with optional relPath suffix)
* then invoke the worker to do some work.
*/
- protected <T> T maybeDoAuthorizableWork(@NotNull ResolveContext<Object> ctx, @NotNull String path,
- @NotNull AuthorizableWorker<T> authorizableWorker, @Nullable PrincipalWorker<T> principalWorker) {
+ protected <T> T maybeDoAuthorizableWork(
+ @NotNull ResolveContext<Object> ctx,
+ @NotNull String path,
+ @NotNull AuthorizableWorker<T> authorizableWorker,
+ @Nullable PrincipalWorker<T> principalWorker) {
T result = null;
// the principalId should be the first segment after the prefix
String suffix = null;
@@ -219,19 +222,18 @@ public class AuthorizableResourceProvider extends ResourceProvider<Object> imple
Session session = ctx.getResourceResolver().adaptTo(Session.class);
if (session != null) {
try {
- UserManager userManager = ((JackrabbitSession)session).getUserManager();
+ UserManager userManager = ((JackrabbitSession) session).getUserManager();
if (userManager != null) {
Authorizable authorizable = userManager.getAuthorizable(pid);
if (authorizable != null) {
if (expectedAuthorizableClass.isInstance(authorizable)) { // SLING-12185
result = authorizableWorker.doWork(authorizable, relPath);
}
- } else if (principalWorker != null && relPath == null){
+ } else if (principalWorker != null && relPath == null) {
// SLING-11098 check for a principal that is not an authorizable like the everyone group
- PrincipalManager principalManager = ((JackrabbitSession)session).getPrincipalManager();
+ PrincipalManager principalManager = ((JackrabbitSession) session).getPrincipalManager();
if (principalManager != null) {
- @Nullable
- Principal principal = principalManager.getPrincipal(pid);
+ @Nullable Principal principal = principalManager.getPrincipal(pid);
if (principal != null) {
result = principalWorker.doWork(principal);
}
@@ -239,8 +241,7 @@ public class AuthorizableResourceProvider extends ResourceProvider<Object> imple
}
}
} catch (RepositoryException re) {
- throw new SlingException(
- "Error looking up Authorizable for principal: " + pid, re);
+ throw new SlingException("Error looking up Authorizable for principal: " + pid, re);
}
}
}
@@ -272,10 +273,8 @@ public class AuthorizableResourceProvider extends ResourceProvider<Object> imple
// handle children of /system/userManager
if (systemUserManagerPath.equals(path)) {
List<Resource> resources = new ArrayList<>();
- resources.add(getResource(ctx,
- systemUserManagerUserPath, null, null));
- resources.add(getResource(ctx,
- systemUserManagerGroupPath, null, null));
+ resources.add(getResource(ctx, systemUserManagerUserPath, null, null));
+ resources.add(getResource(ctx, systemUserManagerGroupPath, null, null));
return resources.iterator();
}
@@ -290,7 +289,7 @@ public class AuthorizableResourceProvider extends ResourceProvider<Object> imple
ResourceResolver resourceResolver = parent.getResourceResolver();
Session session = resourceResolver.adaptTo(Session.class);
if (session != null) {
- PrincipalManager principalManager = ((JackrabbitSession)session).getPrincipalManager();
+ PrincipalManager principalManager = ((JackrabbitSession) session).getPrincipalManager();
principals = principalManager.getPrincipals(searchType);
}
@@ -310,7 +309,10 @@ public class AuthorizableResourceProvider extends ResourceProvider<Object> imple
// only include the children that are nested property containers
List<Resource> propContainers = filterPropertyContainers(relPath, authorizable, r);
if (!propContainers.isEmpty()) {
- result = new NestedChildrenIterator(parent, authorizable.getID(), r.getChildren().iterator());
+ result = new NestedChildrenIterator(
+ parent,
+ authorizable.getID(),
+ r.getChildren().iterator());
}
}
return result;
@@ -318,8 +320,7 @@ public class AuthorizableResourceProvider extends ResourceProvider<Object> imple
return maybeDoAuthorizableWork(ctx, path, authorizableWorker, null);
}
} catch (RepositoryException re) {
- throw new SlingException("Error listing children of resource: "
- + parent.getPath(), re);
+ throw new SlingException("Error listing children of resource: " + parent.getPath(), re);
}
return null;
@@ -328,7 +329,7 @@ public class AuthorizableResourceProvider extends ResourceProvider<Object> imple
/**
* Filter the resource children to return only the resources that are
* nested property containers
- *
+ *
* @param relPath the relative path to start from
* @param authorizable the user or group
* @param r the resource to filter the children of
@@ -385,26 +386,24 @@ public class AuthorizableResourceProvider extends ResourceProvider<Object> imple
next = createNext(child, principalName, resourceResolver, session);
}
} catch (RepositoryException re) {
- log.error("Exception while looking up authorizable resource.",
- re);
+ log.error("Exception while looking up authorizable resource.", re);
}
return next;
}
- protected @Nullable Resource createNext(Object child, String principalName,
- ResourceResolver resourceResolver, Session session) throws RepositoryException {
+ protected @Nullable Resource createNext(
+ Object child, String principalName, ResourceResolver resourceResolver, Session session)
+ throws RepositoryException {
Resource next = null;
- UserManager userManager = ((JackrabbitSession)session).getUserManager();
+ UserManager userManager = ((JackrabbitSession) session).getUserManager();
if (userManager != null) {
Authorizable authorizable = userManager.getAuthorizable(principalName);
if (authorizable != null) {
String path;
if (authorizable.isGroup()) {
- path = systemUserManagerGroupPrefix
- + principalName;
+ path = systemUserManagerGroupPrefix + principalName;
} else {
- path = systemUserManagerUserPrefix
- + principalName;
+ path = systemUserManagerUserPrefix + principalName;
}
next = createNext(child, resourceResolver, authorizable, path);
}
@@ -414,9 +413,9 @@ public class AuthorizableResourceProvider extends ResourceProvider<Object> imple
protected abstract String toPrincipalName(Object child);
- protected abstract Resource createNext(Object child, ResourceResolver resourceResolver,
- Authorizable authorizable, String path) throws RepositoryException;
-
+ protected abstract Resource createNext(
+ Object child, ResourceResolver resourceResolver, Authorizable authorizable, String path)
+ throws RepositoryException;
}
private final class NestedChildrenIterator extends BaseChildrenIterator {
@@ -434,25 +433,28 @@ public class AuthorizableResourceProvider extends ResourceProvider<Object> imple
}
@Override
- protected Resource createNext(Object child, ResourceResolver resourceResolver, Authorizable authorizable,
- String path) throws RepositoryException {
+ protected Resource createNext(
+ Object child, ResourceResolver resourceResolver, Authorizable authorizable, String path)
+ throws RepositoryException {
Resource next = null;
if (child instanceof Resource childResource) {
- //calculate the path relative to the home folder root
- String relPath = childResource.getPath().substring(authorizable.getPath().length() + 1);
+ // calculate the path relative to the home folder root
+ String relPath =
+ childResource.getPath().substring(authorizable.getPath().length() + 1);
// check if the relPath resolves any valid property names
Iterator<String> propertyNames = getPropertyNames(relPath, authorizable);
if (propertyNames.hasNext()) {
- next = new NestedAuthorizableResource(authorizable,
- resourceResolver, String.format("%s/%s", path, relPath),
+ next = new NestedAuthorizableResource(
+ authorizable,
+ resourceResolver,
+ String.format("%s/%s", path, relPath),
AuthorizableResourceProvider.this,
relPath);
}
}
return next;
}
-
}
private final class ChildrenIterator extends BaseChildrenIterator {
@@ -471,27 +473,23 @@ public class AuthorizableResourceProvider extends ResourceProvider<Object> imple
}
@Override
- protected @Nullable Resource createNext(Object child, String principalName, ResourceResolver resourceResolver,
- Session session) throws RepositoryException {
- @Nullable
- Resource next = super.createNext(child, principalName, resourceResolver, session);
+ protected @Nullable Resource createNext(
+ Object child, String principalName, ResourceResolver resourceResolver, Session session)
+ throws RepositoryException {
+ @Nullable Resource next = super.createNext(child, principalName, resourceResolver, session);
if (next == null) {
// SLING-11098 check for principal that is not authorizable
- PrincipalManager principalManager = ((JackrabbitSession)session).getPrincipalManager();
+ PrincipalManager principalManager = ((JackrabbitSession) session).getPrincipalManager();
if (principalManager != null) {
- @Nullable
- Principal principal = principalManager.getPrincipal(principalName);
+ @Nullable Principal principal = principalManager.getPrincipal(principalName);
if (principal != null) {
String path;
if (principal instanceof GroupPrincipal) {
- path = systemUserManagerGroupPrefix
- + principalName;
+ path = systemUserManagerGroupPrefix + principalName;
} else {
- path = systemUserManagerUserPrefix
- + principalName;
+ path = systemUserManagerUserPrefix + principalName;
}
- return new PrincipalResource(principal,
- resourceResolver, path);
+ return new PrincipalResource(principal, resourceResolver, path);
}
}
}
@@ -499,13 +497,11 @@ public class AuthorizableResourceProvider extends ResourceProvider<Object> imple
}
@Override
- protected Resource createNext(Object child, ResourceResolver resourceResolver, Authorizable authorizable,
- String path) throws RepositoryException {
- return new AuthorizableResource(authorizable,
- resourceResolver, path,
- AuthorizableResourceProvider.this);
+ protected Resource createNext(
+ Object child, ResourceResolver resourceResolver, Authorizable authorizable, String path)
+ throws RepositoryException {
+ return new AuthorizableResource(authorizable, resourceResolver, path, AuthorizableResourceProvider.this);
}
-
}
/**
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/AuthorizableValueMap.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/AuthorizableValueMap.java
index 308219b..26ba9f5 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/AuthorizableValueMap.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/AuthorizableValueMap.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.jackrabbit.usermanager.impl.resource;
+import javax.jcr.RepositoryException;
+import javax.jcr.UnsupportedRepositoryOperationException;
+
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
-import javax.jcr.RepositoryException;
-import javax.jcr.UnsupportedRepositoryOperationException;
-
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.sling.jackrabbit.usermanager.resource.SystemUserManagerPaths;
@@ -105,8 +107,7 @@ public class AuthorizableValueMap extends BaseAuthorizableValueMap {
private String[] getMembers(Group group, boolean includeAll) throws RepositoryException {
List<String> results = new ArrayList<>();
- for (Iterator<Authorizable> it = includeAll ? group.getMembers() : group.getDeclaredMembers();
- it.hasNext();) {
+ for (Iterator<Authorizable> it = includeAll ? group.getMembers() : group.getDeclaredMembers(); it.hasNext(); ) {
Authorizable auth = it.next();
if (auth.isGroup()) {
results.add(systemUserManagerPaths.getGroupPrefix() + auth.getID());
@@ -120,7 +121,7 @@ public class AuthorizableValueMap extends BaseAuthorizableValueMap {
private String[] getMemberships(boolean includeAll) throws RepositoryException {
List<String> results = new ArrayList<>();
for (Iterator<Group> it = includeAll ? authorizable.memberOf() : authorizable.declaredMemberOf();
- it.hasNext();) {
+ it.hasNext(); ) {
Group group = it.next();
results.add(systemUserManagerPaths.getGroupPrefix() + group.getID());
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/BaseAuthorizableValueMap.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/BaseAuthorizableValueMap.java
index 28dccd0..14117fe 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/BaseAuthorizableValueMap.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/BaseAuthorizableValueMap.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.jackrabbit.usermanager.impl.resource;
+import javax.jcr.Binary;
+import javax.jcr.PropertyType;
+import javax.jcr.RepositoryException;
+import javax.jcr.Value;
+import javax.jcr.ValueFormatException;
+
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
@@ -29,12 +37,6 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
-import javax.jcr.Binary;
-import javax.jcr.PropertyType;
-import javax.jcr.RepositoryException;
-import javax.jcr.Value;
-import javax.jcr.ValueFormatException;
-
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.jackrabbit.usermanager.resource.SystemUserManagerPaths;
@@ -166,16 +168,16 @@ public abstract class BaseAuthorizableValueMap implements ValueMap {
case PropertyType.LONG:
return value.getLong();
case PropertyType.NAME, // fall through
- PropertyType.PATH, // fall through
- PropertyType.REFERENCE, // fall through
- PropertyType.STRING, // fall through
- PropertyType.UNDEFINED: // not actually expected
+ PropertyType.PATH, // fall through
+ PropertyType.REFERENCE, // fall through
+ PropertyType.STRING, // fall through
+ PropertyType.UNDEFINED: // not actually expected
default: // not actually expected
return value.getString();
}
}
- protected Object valuesToJavaObject(Value[] values)
- throws RepositoryException {
+
+ protected Object valuesToJavaObject(Value[] values) throws RepositoryException {
if (values == null) {
return null;
} else if (values.length == 1) {
@@ -238,16 +240,14 @@ public abstract class BaseAuthorizableValueMap implements ValueMap {
if (multiValue) {
if (array) {
- result = (T) convertToArray(values,
- type.getComponentType());
+ result = (T) convertToArray(values, type.getComponentType());
} else if (values.length > 0) {
result = convertToType(values[0], type);
}
} else {
Value value = values[0];
if (array) {
- result = (T) convertToArray(new Value[] { value },
- type.getComponentType());
+ result = (T) convertToArray(new Value[] {value}, type.getComponentType());
} else {
result = convertToType(value, type);
}
@@ -267,8 +267,7 @@ public abstract class BaseAuthorizableValueMap implements ValueMap {
return result;
}
- private <T> T[] convertToArray(Value[] jcrValues, Class<T> type)
- throws RepositoryException {
+ private <T> T[] convertToArray(Value[] jcrValues, Class<T> type) throws RepositoryException {
// lazy create this list in case there are no valid type conversions
List<T> values = null;
for (int i = 0; i < jcrValues.length; i++) {
@@ -291,8 +290,7 @@ public abstract class BaseAuthorizableValueMap implements ValueMap {
}
@SuppressWarnings("unchecked")
- private <T> T convertToType(Value jcrValue, Class<T> type)
- throws RepositoryException {
+ private <T> T convertToType(Value jcrValue, Class<T> type) throws RepositoryException {
if (String.class == type) {
return (T) jcrValue.getString();
@@ -307,7 +305,7 @@ public abstract class BaseAuthorizableValueMap implements ValueMap {
} else if (Long.class == type) {
return (T) Long.valueOf(jcrValue.getLong());
} else if (Float.class == type) {
- return (T) Float.valueOf((float)jcrValue.getDouble());
+ return (T) Float.valueOf((float) jcrValue.getDouble());
} else if (Double.class == type) {
return (T) Double.valueOf(jcrValue.getDouble());
} else if (Boolean.class == type) {
@@ -425,6 +423,5 @@ public abstract class BaseAuthorizableValueMap implements ValueMap {
}
return delegatee;
}
-
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/BaseResource.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/BaseResource.java
index d62861c..ff7767b 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/BaseResource.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/BaseResource.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.jackrabbit.usermanager.impl.resource;
@@ -69,5 +71,4 @@ public abstract class BaseResource extends AbstractResource {
public String getResourceSuperType() {
return null;
}
-
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/NestedAuthorizableResource.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/NestedAuthorizableResource.java
index 677f7e2..4a4a50d 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/NestedAuthorizableResource.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/NestedAuthorizableResource.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.jackrabbit.usermanager.impl.resource;
@@ -31,16 +33,24 @@ import org.apache.sling.jackrabbit.usermanager.resource.SystemUserManagerPaths;
/**
* Resource implementation for nested property containers of Authorizable
*/
-@Adaptable(adaptableClass = Resource.class, adapters = {
- @Adapter({Map.class, ValueMap.class, Authorizable.class}),
- @Adapter(condition="If the resource is an AuthorizableResource and represents a JCR User", value = User.class),
- @Adapter(condition="If the resource is an AuthorizableResource and represents a JCR Group", value = Group.class)
-})
+@Adaptable(
+ adaptableClass = Resource.class,
+ adapters = {
+ @Adapter({Map.class, ValueMap.class, Authorizable.class}),
+ @Adapter(
+ condition = "If the resource is an AuthorizableResource and represents a JCR User",
+ value = User.class),
+ @Adapter(
+ condition = "If the resource is an AuthorizableResource and represents a JCR Group",
+ value = Group.class)
+ })
public class NestedAuthorizableResource extends AuthorizableResource {
private final String relPropPath;
- public NestedAuthorizableResource(Authorizable authorizable,
- ResourceResolver resourceResolver, String path,
+ public NestedAuthorizableResource(
+ Authorizable authorizable,
+ ResourceResolver resourceResolver,
+ String path,
SystemUserManagerPaths systemUserManagerPaths,
String relPropPath) {
super(authorizable, resourceResolver, path, systemUserManagerPaths);
@@ -65,5 +75,4 @@ public class NestedAuthorizableResource extends AuthorizableResource {
return super.adaptTo(type);
}
-
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/NestedAuthorizableValueMap.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/NestedAuthorizableValueMap.java
index 92e3d1d..f37b016 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/NestedAuthorizableValueMap.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/NestedAuthorizableValueMap.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.jackrabbit.usermanager.impl.resource;
-import java.util.Iterator;
-
import javax.jcr.RepositoryException;
+import java.util.Iterator;
+
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.sling.jackrabbit.usermanager.resource.SystemUserManagerPaths;
import org.jetbrains.annotations.NotNull;
@@ -30,8 +32,8 @@ import org.jetbrains.annotations.NotNull;
public class NestedAuthorizableValueMap extends BaseAuthorizableValueMap {
private final String relPropPath;
- public NestedAuthorizableValueMap(Authorizable authorizable, SystemUserManagerPaths systemUserManagerPaths,
- @NotNull String relPropPath) {
+ public NestedAuthorizableValueMap(
+ Authorizable authorizable, SystemUserManagerPaths systemUserManagerPaths, @NotNull String relPropPath) {
super(authorizable, systemUserManagerPaths);
this.relPropPath = relPropPath;
}
@@ -81,5 +83,4 @@ public class NestedAuthorizableValueMap extends BaseAuthorizableValueMap {
protected <T> T convertToType(String name, Class<T> type) {
return super.convertToType(String.format("%s/%s", relPropPath, name), type);
}
-
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/PrincipalResource.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/PrincipalResource.java
index 17a3f2a..691662d 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/PrincipalResource.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/impl/resource/PrincipalResource.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.jackrabbit.usermanager.impl.resource;
@@ -31,16 +33,19 @@ import org.apache.sling.api.wrappers.ValueMapDecorator;
/**
* Resource implementation for Principal (SLING-11098)
*/
-@Adaptable(adaptableClass = Resource.class, adapters = {
- @Adapter({Map.class, ValueMap.class, Principal.class}),
- @Adapter(condition="If the resource is an PrincipalResource and represents a JCR principal", value = Principal.class)
-})
+@Adaptable(
+ adaptableClass = Resource.class,
+ adapters = {
+ @Adapter({Map.class, ValueMap.class, Principal.class}),
+ @Adapter(
+ condition = "If the resource is an PrincipalResource and represents a JCR principal",
+ value = Principal.class)
+ })
public class PrincipalResource extends BaseResource {
protected final Principal principal;
private final String resourceType;
- public PrincipalResource(Principal principal,
- ResourceResolver resourceResolver, String path) {
+ public PrincipalResource(Principal principal, ResourceResolver resourceResolver, String path) {
super(resourceResolver, path);
this.principal = principal;
@@ -89,8 +94,6 @@ public class PrincipalResource extends BaseResource {
if (principal != null) {
id = principal.getName();
}
- return getClass().getSimpleName() + ", id=" + id + ", path="
- + getPath();
+ return getClass().getSimpleName() + ", id=" + id + ", path=" + getPath();
}
-
}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/package-info.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/package-info.java
index c3526b4..8b4ac59 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/package-info.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/package-info.java
@@ -19,5 +19,3 @@
@org.osgi.annotation.versioning.Version("2.6.0")
package org.apache.sling.jackrabbit.usermanager;
-
-
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/resource/SystemUserManagerPaths.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/resource/SystemUserManagerPaths.java
index c6ca882..bc33c88 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/resource/SystemUserManagerPaths.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/resource/SystemUserManagerPaths.java
@@ -1,23 +1,25 @@
/*
- * 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.jackrabbit.usermanager.resource;
/**
- * Helper for components that need to know the
+ * Helper for components that need to know the
* UserManager resource paths
*/
public interface SystemUserManagerPaths {
@@ -46,5 +48,4 @@ public interface SystemUserManagerPaths {
* The path prefix (before the id) for groups
*/
String getGroupPrefix();
-
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/apache/sling/jackrabbit/usermanager/resource/package-info.java b/src/main/java/org/apache/sling/jackrabbit/usermanager/resource/package-info.java
index 9e00de3..6fde046 100644
--- a/src/main/java/org/apache/sling/jackrabbit/usermanager/resource/package-info.java
+++ b/src/main/java/org/apache/sling/jackrabbit/usermanager/resource/package-info.java
@@ -19,5 +19,3 @@
@org.osgi.annotation.versioning.Version("1.0.0")
package org.apache.sling.jackrabbit.usermanager.resource;
-
-
diff --git a/src/test/java/org/apache/sling/jackrabbit/usermanager/AuthorizablePrivilegesInfoTest.java b/src/test/java/org/apache/sling/jackrabbit/usermanager/AuthorizablePrivilegesInfoTest.java
index fa08608..a3dcaa5 100644
--- a/src/test/java/org/apache/sling/jackrabbit/usermanager/AuthorizablePrivilegesInfoTest.java
+++ b/src/test/java/org/apache/sling/jackrabbit/usermanager/AuthorizablePrivilegesInfoTest.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.jackrabbit.usermanager;
-import static org.junit.Assert.*;
-
import javax.jcr.Session;
import org.apache.sling.jackrabbit.usermanager.AuthorizablePrivilegesInfo.PropertyUpdateTypes;
import org.junit.Test;
+import static org.junit.Assert.*;
+
/**
* Test coverage for AuthorizablePrivilegesInfo / PropertyUpdateTypes
*/
@@ -57,22 +59,30 @@ public class AuthorizablePrivilegesInfoTest {
public boolean canUpdateGroupMembers(Session jcrSession, String groupId) {
return false;
}
-
}
@SuppressWarnings("deprecation")
@Test
public void testConvertDeprecated() {
- assertEquals(PropertyUpdateTypes.ADD_PROPERTY, PropertyUpdateTypes.convertDeprecated(PropertyUpdateTypes.addProperty));
- assertEquals(PropertyUpdateTypes.ADD_NESTED_PROPERTY, PropertyUpdateTypes.convertDeprecated(PropertyUpdateTypes.addNestedProperty));
- assertEquals(PropertyUpdateTypes.ALTER_PROPERTY, PropertyUpdateTypes.convertDeprecated(PropertyUpdateTypes.alterProperty));
- assertEquals(PropertyUpdateTypes.REMOVE_PROPERTY, PropertyUpdateTypes.convertDeprecated(PropertyUpdateTypes.removeProperty));
-
- //and one that doesn't require conversion
- assertEquals(PropertyUpdateTypes.REMOVE_PROPERTY, PropertyUpdateTypes.convertDeprecated(PropertyUpdateTypes.REMOVE_PROPERTY));
+ assertEquals(
+ PropertyUpdateTypes.ADD_PROPERTY,
+ PropertyUpdateTypes.convertDeprecated(PropertyUpdateTypes.addProperty));
+ assertEquals(
+ PropertyUpdateTypes.ADD_NESTED_PROPERTY,
+ PropertyUpdateTypes.convertDeprecated(PropertyUpdateTypes.addNestedProperty));
+ assertEquals(
+ PropertyUpdateTypes.ALTER_PROPERTY,
+ PropertyUpdateTypes.convertDeprecated(PropertyUpdateTypes.alterProperty));
+ assertEquals(
+ PropertyUpdateTypes.REMOVE_PROPERTY,
+ PropertyUpdateTypes.convertDeprecated(PropertyUpdateTypes.removeProperty));
+
+ // and one that doesn't require conversion
+ assertEquals(
+ PropertyUpdateTypes.REMOVE_PROPERTY,
+ PropertyUpdateTypes.convertDeprecated(PropertyUpdateTypes.REMOVE_PROPERTY));
}
-
/**
* Test method for {@link org.apache.sling.jackrabbit.usermanager.AuthorizablePrivilegesInfo#canUpdateProperties(javax.jcr.Session, java.lang.String, org.apache.sling.jackrabbit.usermanager.AuthorizablePrivilegesInfo.PropertyUpdateTypes[])}.
*/
@@ -112,5 +122,4 @@ public class AuthorizablePrivilegesInfoTest {
Session jcrSession = null;
api.canChangePasswordWithoutOldPassword(jcrSession, "testuser1");
}
-
}
diff --git a/src/test/java/org/apache/sling/jackrabbit/usermanager/impl/AuthorizableAdapterFactoryTest.java b/src/test/java/org/apache/sling/jackrabbit/usermanager/impl/AuthorizableAdapterFactoryTest.java
index 4c79757..d9783bf 100644
--- a/src/test/java/org/apache/sling/jackrabbit/usermanager/impl/AuthorizableAdapterFactoryTest.java
+++ b/src/test/java/org/apache/sling/jackrabbit/usermanager/impl/AuthorizableAdapterFactoryTest.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.jackrabbit.usermanager.impl;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.mockito.Mockito.withSettings;
-
import javax.jcr.RepositoryException;
import javax.jcr.Session;
@@ -33,6 +31,10 @@ import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.mockito.Mockito.withSettings;
+
/**
*
*/
@@ -51,7 +53,6 @@ public class AuthorizableAdapterFactoryTest {
if (session instanceof JackrabbitSession jrSession) {
jrSession.getUserManager().createUser("admin", "test");
}
-
}
/**
* Test method for {@link org.apache.sling.jackrabbit.usermanager.impl.AuthorizableAdapterFactory#getAdapter(java.lang.Object, java.lang.Class)}.
@@ -75,10 +76,11 @@ public class AuthorizableAdapterFactoryTest {
ResourceResolver mockRR = Mockito.mock(ResourceResolver.class);
Session mockSession = Mockito.mock(Session.class, withSettings().extraInterfaces(JackrabbitSession.class));
Mockito.when(mockRR.adaptTo(Session.class)).thenReturn(mockSession);
- Mockito.doThrow(RepositoryException.class).when((JackrabbitSession)mockSession).getUserManager();
+ Mockito.doThrow(RepositoryException.class)
+ .when((JackrabbitSession) mockSession)
+ .getUserManager();
User user = factory.getAdapter(mockRR, User.class);
assertNull(user);
}
-
}
diff --git a/src/test/java/org/apache/sling/jackrabbit/usermanager/impl/post/AbstractAuthorizablePostServletTest.java b/src/test/java/org/apache/sling/jackrabbit/usermanager/impl/post/AbstractAuthorizablePostServletTest.java
index a560468..0b067c2 100644
--- a/src/test/java/org/apache/sling/jackrabbit/usermanager/impl/post/AbstractAuthorizablePostServletTest.java
+++ b/src/test/java/org/apache/sling/jackrabbit/usermanager/impl/post/AbstractAuthorizablePostServletTest.java
@@ -1,39 +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.jackrabbit.usermanager.impl.post;
-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.assertSame;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
+import javax.jcr.AccessDeniedException;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.ValueFactory;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
-import javax.jcr.AccessDeniedException;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.ValueFactory;
-
import org.apache.jackrabbit.JcrConstants;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
@@ -58,6 +52,14 @@ import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
+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.assertSame;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
/**
*
*/
@@ -136,27 +138,39 @@ public class AbstractAuthorizablePostServletTest {
Session jcrSession = context.resourceResolver().adaptTo(Session.class);
// try with no bound PrincipalNameGenerator
- assertEquals("test", taps.getOrGeneratePrincipalName(jcrSession,
- Map.of(SlingPostConstants.RP_NODE_NAME, "test"), AuthorizableType.USER));
- assertEquals("test1", taps.getOrGeneratePrincipalName(jcrSession,
- Map.of(SlingPostConstants.RP_NODE_NAME, new String[] {"test1"}), AuthorizableType.USER));
- assertNull(taps.getOrGeneratePrincipalName(jcrSession,
- Map.of(SlingPostConstants.RP_NODE_NAME, new String[] {"test1", "test2"}), AuthorizableType.USER));
- assertNull(taps.getOrGeneratePrincipalName(jcrSession,
- Map.of(SlingPostConstants.RP_NODE_NAME, new Object()), AuthorizableType.USER));
+ assertEquals(
+ "test",
+ taps.getOrGeneratePrincipalName(
+ jcrSession, Map.of(SlingPostConstants.RP_NODE_NAME, "test"), AuthorizableType.USER));
+ assertEquals(
+ "test1",
+ taps.getOrGeneratePrincipalName(
+ jcrSession,
+ Map.of(SlingPostConstants.RP_NODE_NAME, new String[] {"test1"}),
+ AuthorizableType.USER));
+ assertNull(taps.getOrGeneratePrincipalName(
+ jcrSession,
+ Map.of(SlingPostConstants.RP_NODE_NAME, new String[] {"test1", "test2"}),
+ AuthorizableType.USER));
+ assertNull(taps.getOrGeneratePrincipalName(
+ jcrSession, Map.of(SlingPostConstants.RP_NODE_NAME, new Object()), AuthorizableType.USER));
// try with bound PrincipalNameGenerator
taps.bindPrincipalNameGenerator(new PrincipalNameGeneratorImpl(), Map.of());
- assertEquals("test", taps.getOrGeneratePrincipalName(jcrSession,
- Map.of(SlingPostConstants.RP_NODE_NAME, "test"), AuthorizableType.USER));
- assertEquals("test", taps.getOrGeneratePrincipalName(jcrSession,
- Map.of(SlingPostConstants.RP_NODE_NAME_HINT, "test"), AuthorizableType.USER));
+ assertEquals(
+ "test",
+ taps.getOrGeneratePrincipalName(
+ jcrSession, Map.of(SlingPostConstants.RP_NODE_NAME, "test"), AuthorizableType.USER));
+ assertEquals(
+ "test",
+ taps.getOrGeneratePrincipalName(
+ jcrSession, Map.of(SlingPostConstants.RP_NODE_NAME_HINT, "test"), AuthorizableType.USER));
// create a user to trigger unique name calculation
- UserManager um = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager um = ((JackrabbitSession) jcrSession).getUserManager();
um.createUser("test", "test");
- String name = taps.getOrGeneratePrincipalName(jcrSession,
- Map.of(SlingPostConstants.RP_NODE_NAME_HINT, "test"), AuthorizableType.USER);
+ String name = taps.getOrGeneratePrincipalName(
+ jcrSession, Map.of(SlingPostConstants.RP_NODE_NAME_HINT, "test"), AuthorizableType.USER);
assertTrue(name.matches("test_\\d+"));
}
@@ -169,10 +183,10 @@ public class AbstractAuthorizablePostServletTest {
"_charset_", "UTF-8",
":item1", "value1",
"./item2/../subitem2", "value2",
- "item3", "value3"
- ));
+ "item3", "value3"));
assertTrue(contentMap.isEmpty());
}
+
@Test
public void testCollectContentMap() {
Map<String, RequestProperty> contentMap = taps.collectContentMap(Map.of(
@@ -182,8 +196,7 @@ public class AbstractAuthorizablePostServletTest {
"item3@ValueFrom", "item1",
"item4@Delete", "true",
"item5@MoveFrom", "/tmp/item5",
- "item6@CopyFrom", "/tmp/item6"
- ));
+ "item6@CopyFrom", "/tmp/item6"));
assertEquals(4, contentMap.size());
}
@@ -194,7 +207,7 @@ public class AbstractAuthorizablePostServletTest {
public void testProcessDeletes() throws RepositoryException {
Session jcrSession = context.resourceResolver().adaptTo(Session.class);
ValueFactory vf = jcrSession.getValueFactory();
- UserManager um = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager um = ((JackrabbitSession) jcrSession).getUserManager();
Authorizable user = um.createUser("test", "test");
user.setProperty("prop1", vf.createValue("value1"));
user.setProperty("prop2", vf.createValue("value2"));
@@ -207,9 +220,7 @@ public class AbstractAuthorizablePostServletTest {
// not existing prop
RequestProperty reqProp3 = new RequestProperty("/prop3");
reqProp3.setDelete(true);
- List<RequestProperty> reqProperties = List.of(
- reqProp1, reqProp2
- );
+ List<RequestProperty> reqProperties = List.of(reqProp1, reqProp2);
List<Modification> changes = new ArrayList<>();
taps.processDeletes(user, reqProperties, changes);
assertEquals(1, changes.size());
@@ -229,48 +240,44 @@ public class AbstractAuthorizablePostServletTest {
@Test
public void testProcessCreate() throws RepositoryException {
Session jcrSession = context.resourceResolver().adaptTo(Session.class);
- UserManager um = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager um = ((JackrabbitSession) jcrSession).getUserManager();
Authorizable user = um.createUser("test", "test");
String relPath1 = "/subnode1/prop1";
RequestProperty reqProp1 = toRequestProperty(relPath1, "value1");
String absPath1 = user.getPath() + relPath1;
- Map<String, RequestProperty> reqProperties = Map.of(
- absPath1, reqProp1
- );
+ Map<String, RequestProperty> reqProperties = Map.of(absPath1, reqProp1);
List<Modification> changes = new ArrayList<>();
taps.processCreate(jcrSession, user, reqProperties, changes);
assertTrue(changes.isEmpty());
}
+
@Test
public void testProcessCreateWithPrimaryTypeOnRoot() throws RepositoryException {
Session jcrSession = context.resourceResolver().adaptTo(Session.class);
- UserManager um = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager um = ((JackrabbitSession) jcrSession).getUserManager();
Authorizable user = um.createUser("test", "test");
String relPath1 = "/" + JcrConstants.JCR_PRIMARYTYPE;
RequestProperty reqProp1 = toRequestProperty(relPath1, "value1");
String absPath1 = user.getPath() + relPath1;
- Map<String, RequestProperty> reqProperties = Map.of(
- absPath1, reqProp1
- );
+ Map<String, RequestProperty> reqProperties = Map.of(absPath1, reqProp1);
List<Modification> changes = new ArrayList<>();
assertThrows(AccessDeniedException.class, () -> taps.processCreate(jcrSession, user, reqProperties, changes));
}
+
@Test
public void testProcessCreateWithPrimaryType() throws RepositoryException {
Session jcrSession = context.resourceResolver().adaptTo(Session.class);
- UserManager um = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager um = ((JackrabbitSession) jcrSession).getUserManager();
Authorizable user = um.createUser("test", "test");
String relPath = "/subnode1/" + JcrConstants.JCR_PRIMARYTYPE;
RequestProperty reqProp1 = toRequestProperty(relPath, "nt:folder");
String absPath = user.getPath() + relPath;
- Map<String, RequestProperty> reqProperties = Map.of(
- absPath, reqProp1
- );
+ Map<String, RequestProperty> reqProperties = Map.of(absPath, reqProp1);
List<Modification> changes = new ArrayList<>();
taps.processCreate(jcrSession, user, reqProperties, changes);
assertEquals(1, changes.size());
@@ -280,10 +287,11 @@ public class AbstractAuthorizablePostServletTest {
taps.processCreate(jcrSession, user, reqProperties, changes);
assertTrue(changes.isEmpty());
}
+
@Test
public void testProcessCreateWithMixin() throws RepositoryException {
Session jcrSession = context.resourceResolver().adaptTo(Session.class);
- UserManager um = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager um = ((JackrabbitSession) jcrSession).getUserManager();
Authorizable user = um.createUser("test", "test");
String relPath1 = "/" + JcrConstants.JCR_MIXINTYPES;
@@ -301,8 +309,7 @@ public class AbstractAuthorizablePostServletTest {
Map<String, RequestProperty> reqProperties = Map.of(
absPath1, reqProp1,
absPath2, reqProp2,
- absPath3, reqProp3
- );
+ absPath3, reqProp3);
List<Modification> changes = new ArrayList<>();
taps.processCreate(jcrSession, user, reqProperties, changes);
assertEquals(4, changes.size());
@@ -323,7 +330,7 @@ public class AbstractAuthorizablePostServletTest {
Session jcrSession = context.resourceResolver().adaptTo(Session.class);
List<Modification> changes = new ArrayList<>();
- UserManager um = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager um = ((JackrabbitSession) jcrSession).getUserManager();
User user = um.createUser("test", "test");
String relPath = "/subnode1/key1";
@@ -340,18 +347,17 @@ public class AbstractAuthorizablePostServletTest {
Session jcrSession = context.resourceResolver().adaptTo(Session.class);
List<Modification> changes = new ArrayList<>();
- UserManager um = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager um = ((JackrabbitSession) jcrSession).getUserManager();
User user = um.createUser("testUser", "test");
- RequestProperty reqProp1 = toRequestProperty( "/subnode1/" + JcrConstants.JCR_PRIMARYTYPE, "value1");
+ RequestProperty reqProp1 = toRequestProperty("/subnode1/" + JcrConstants.JCR_PRIMARYTYPE, "value1");
RequestProperty reqProp2 = toRequestProperty("/subnode1/" + JcrConstants.JCR_MIXINTYPES, "value1");
RequestProperty reqProp3 = toRequestProperty("/userId", "value1");
RequestProperty reqProp4 = toRequestProperty("/pwd", "value1");
RequestProperty reqProp5 = toRequestProperty("/pwdConfirm", "value1");
- List<RequestProperty> reqProperties = List.of(reqProp1, reqProp2,
- reqProp3, reqProp4, reqProp5);
+ List<RequestProperty> reqProperties = List.of(reqProp1, reqProp2, reqProp3, reqProp4, reqProp5);
taps.writeContent(jcrSession, user, reqProperties, changes);
assertTrue(changes.isEmpty());
@@ -362,32 +368,30 @@ public class AbstractAuthorizablePostServletTest {
String reqProp7RelPath = "/fileUpload";
RequestProperty reqProp7 = new RequestProperty(reqProp7RelPath);
reqProp7.setValues(new RequestParameter[] {
- Builders.newRequestParameter(reqProp7RelPath, "value1".getBytes(), "filename.txt", "text/plain")
- });
+ Builders.newRequestParameter(reqProp7RelPath, "value1".getBytes(), "filename.txt", "text/plain")
+ });
- reqProperties = List.of(reqProp1, reqProp2,
- reqProp6, reqProp7);
+ reqProperties = List.of(reqProp1, reqProp2, reqProp6, reqProp7);
changes.clear();
taps.writeContent(jcrSession, group, reqProperties, changes);
assertTrue(changes.isEmpty());
-
}
protected RequestProperty toRequestProperty(String relPath, String value) {
RequestProperty reqProp1 = new RequestProperty(relPath);
- reqProp1.setValues(new RequestParameter[] {
- Builders.newRequestParameter(relPath, value)
- });
+ reqProp1.setValues(new RequestParameter[] {Builders.newRequestParameter(relPath, value)});
return reqProp1;
}
/**
- *
+ *
*/
protected void mockSystemUserManagerPaths() {
SystemUserManagerPaths mockSump = Mockito.mock(SystemUserManagerPaths.class);
- Mockito.when(mockSump.getUserPrefix()).thenReturn(String.format("%s/user/", AuthorizableResourceProvider.DEFAULT_SYSTEM_USER_MANAGER_PATH));
- Mockito.when(mockSump.getGroupPrefix()).thenReturn(String.format("%s/group/", AuthorizableResourceProvider.DEFAULT_SYSTEM_USER_MANAGER_PATH));
+ Mockito.when(mockSump.getUserPrefix())
+ .thenReturn(String.format("%s/user/", AuthorizableResourceProvider.DEFAULT_SYSTEM_USER_MANAGER_PATH));
+ Mockito.when(mockSump.getGroupPrefix())
+ .thenReturn(String.format("%s/group/", AuthorizableResourceProvider.DEFAULT_SYSTEM_USER_MANAGER_PATH));
taps.bindSystemUserManagerPaths(mockSump);
}
@@ -444,8 +448,8 @@ public class AbstractAuthorizablePostServletTest {
// value as RequestParameter[]
str = taps.convertToString(new RequestParameter[] {
- Builders.newRequestParameter("param1", "value1"),
- Builders.newRequestParameter("param1", "value2")});
+ Builders.newRequestParameter("param1", "value1"), Builders.newRequestParameter("param1", "value2")
+ });
assertNotNull(str);
assertEquals("value1", str);
str = taps.convertToString(new RequestParameter[0]);
@@ -482,8 +486,8 @@ public class AbstractAuthorizablePostServletTest {
// value as RequestParameter[]
strArray = taps.convertToStringArray(new RequestParameter[] {
- Builders.newRequestParameter("param1", "value1"),
- Builders.newRequestParameter("param1", "value2")});
+ Builders.newRequestParameter("param1", "value1"), Builders.newRequestParameter("param1", "value2")
+ });
assertNotNull(strArray);
assertEquals(2, strArray.length);
assertEquals("value1", strArray[0]);
@@ -521,8 +525,8 @@ public class AbstractAuthorizablePostServletTest {
// value as RequestParameter[]
rpArray = taps.convertToRequestParameterArray("param1", new RequestParameter[] {
- Builders.newRequestParameter("param1", "value1"),
- Builders.newRequestParameter("param1", "value2")});
+ Builders.newRequestParameter("param1", "value1"), Builders.newRequestParameter("param1", "value2")
+ });
assertNotNull(rpArray);
assertEquals(2, rpArray.length);
assertEquals("value1", rpArray[0].getString());
@@ -534,13 +538,13 @@ public class AbstractAuthorizablePostServletTest {
assertEquals(0, rpArray.length);
}
-
private class TestAuthorizablePostServlet extends AbstractAuthorizablePostServlet {
private static final long serialVersionUID = -2948341218853558959L;
@Override
- protected void handleOperation(SlingJakartaHttpServletRequest request, JakartaPostResponse response,
- List<Modification> changes) throws RepositoryException {
+ protected void handleOperation(
+ SlingJakartaHttpServletRequest request, JakartaPostResponse response, List<Modification> changes)
+ throws RepositoryException {
// do nothing
}
}
diff --git a/src/test/java/org/apache/sling/jackrabbit/usermanager/impl/post/AbstractPostServletTest.java b/src/test/java/org/apache/sling/jackrabbit/usermanager/impl/post/AbstractPostServletTest.java
index d2de4a0..b0e74ca 100644
--- a/src/test/java/org/apache/sling/jackrabbit/usermanager/impl/post/AbstractPostServletTest.java
+++ b/src/test/java/org/apache/sling/jackrabbit/usermanager/impl/post/AbstractPostServletTest.java
@@ -1,36 +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.jackrabbit.usermanager.impl.post;
-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 static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyList;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
import java.io.IOException;
import java.util.List;
import java.util.Map;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-
+import jakarta.servlet.ServletException;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.User;
import org.apache.jackrabbit.api.security.user.UserManager;
@@ -56,7 +51,13 @@ import org.junit.Test;
import org.mockito.Mockito;
import org.osgi.framework.Constants;
-import jakarta.servlet.ServletException;
+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 static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
/**
*
@@ -81,30 +82,33 @@ public class AbstractPostServletTest {
ResourceResolver rr = context.resourceResolver();
// create a user to trigger unique name calculation
Session jcrSession = context.resourceResolver().adaptTo(Session.class);
- UserManager um = ((JackrabbitSession)jcrSession).getUserManager();
+ UserManager um = ((JackrabbitSession) jcrSession).getUserManager();
User testUser = um.createUser("test", "test");
context.currentResource(rr.getResource(testUser.getPath()));
tps = Mockito.spy(tps);
Mockito.doAnswer(invocation -> {
- @SuppressWarnings("unchecked")
- List<Modification> changes = invocation.getArgument(2, List.class);
- changes.add(Modification.onModified("/modified"));
- changes.add(Modification.onDeleted("/deleted"));
- changes.add(Modification.onMoved("/moveSrcPath", "/moveDestPath"));
- changes.add(Modification.onCopied("/copySrcPath", "/copyDestPath"));
- changes.add(Modification.onCreated("/created"));
- changes.add(Modification.onOrder("/ordered", "beforesibling"));
- changes.add(Modification.onCheckin("/checkin"));
-
- return null;
- }).when(tps).handleOperation(any(SlingJakartaHttpServletRequest.class), any(JakartaPostResponse.class), anyList());
+ @SuppressWarnings("unchecked")
+ List<Modification> changes = invocation.getArgument(2, List.class);
+ changes.add(Modification.onModified("/modified"));
+ changes.add(Modification.onDeleted("/deleted"));
+ changes.add(Modification.onMoved("/moveSrcPath", "/moveDestPath"));
+ changes.add(Modification.onCopied("/copySrcPath", "/copyDestPath"));
+ changes.add(Modification.onCreated("/created"));
+ changes.add(Modification.onOrder("/ordered", "beforesibling"));
+ changes.add(Modification.onCheckin("/checkin"));
+
+ return null;
+ })
+ .when(tps)
+ .handleOperation(any(SlingJakartaHttpServletRequest.class), any(JakartaPostResponse.class), anyList());
tps.doPost(jakartaRequest, jakartaResponse);
assertEquals(SlingJakartaHttpServletResponse.SC_OK, jakartaResponse.getStatus());
}
+
@Test
public void testDoPostWithResourceNotFound() throws ServletException, IOException, RepositoryException {
MockSlingHttpServletRequest request = context.request();
@@ -117,7 +121,8 @@ public class AbstractPostServletTest {
tps = Mockito.spy(tps);
Mockito.doThrow(ResourceNotFoundException.class)
- .when(tps).handleOperation(any(SlingJakartaHttpServletRequest.class), any(JakartaPostResponse.class), anyList());
+ .when(tps)
+ .handleOperation(any(SlingJakartaHttpServletRequest.class), any(JakartaPostResponse.class), anyList());
tps.doPost(jakartaRequest, jakartaResponse);
@@ -142,6 +147,7 @@ public class AbstractPostServletTest {
Mockito.when(mockPostResponseCreator.createPostResponse(jakartaRequest)).thenReturn(mockPostResponse);
assertEquals(mockPostResponse, tps.createPostResponse(jakartaRequest));
}
+
@Test
public void testCreatePostResponseWithNoAcceptParamOrHeader() {
MockSlingHttpServletRequest request = context.request();
@@ -154,6 +160,7 @@ public class AbstractPostServletTest {
request.setResponseContentType("application/json");
assertTrue(tps.createPostResponse(jakartaRequest) instanceof JakartaJSONResponse);
}
+
@Test
public void testCreatePostResponseWithEmptyAcceptParamOrHeader() {
MockSlingHttpServletRequest request = context.request();
@@ -163,6 +170,7 @@ public class AbstractPostServletTest {
request.setHeader(JakartaMediaRangeList.HEADER_ACCEPT, "");
assertTrue(tps.createPostResponse(jakartaRequest) instanceof JakartaHtmlResponse);
}
+
@Test
public void testCreatePostResponseWithAcceptParam() {
MockSlingHttpServletRequest request = context.request();
@@ -171,6 +179,7 @@ public class AbstractPostServletTest {
request.setParameterMap(Map.of(JakartaMediaRangeList.PARAM_ACCEPT, "application/json"));
assertTrue(tps.createPostResponse(jakartaRequest) instanceof JakartaJSONResponse);
}
+
@Test
public void testCreatePostResponseWithAcceptHeader() {
MockSlingHttpServletRequest request = context.request();
@@ -194,6 +203,7 @@ public class AbstractPostServletTest {
request.setParameterMap(Map.of(SlingPostConstants.RP_REDIRECT_TO, "/content/node"));
assertEquals("/content/node", tps.getRedirectUrl(jakartaRequest, postResponse));
}
+
@Test
public void testGetRedirectUrlWithHost() throws IOException {
MockSlingHttpServletRequest request = context.request();
@@ -205,6 +215,7 @@ public class AbstractPostServletTest {
request.setParameterMap(Map.of(SlingPostConstants.RP_REDIRECT_TO, "https://localhost/content/node"));
assertThrows(IOException.class, () -> tps.getRedirectUrl(jakartaRequest, postResponse));
}
+
@Test
public void testGetRedirectUrlWithInvalidSyntax() throws IOException {
MockSlingHttpServletRequest request = context.request();
@@ -216,6 +227,7 @@ public class AbstractPostServletTest {
request.setParameterMap(Map.of(SlingPostConstants.RP_REDIRECT_TO, "https://"));
assertThrows(IOException.class, () -> tps.getRedirectUrl(jakartaRequest, postResponse));
}
+
@Test
public void testGetRedirectUrlToCreated() throws IOException {
MockSlingHttpServletRequest request = context.request();
@@ -287,6 +299,7 @@ public class AbstractPostServletTest {
assertEquals("/path", tps.externalizePath(jakartaRequest, "/content/path"));
}
+
@Test
public void testExternalizePathWithDisplayExtension() {
MockSlingHttpServletRequest request = context.request();
@@ -370,8 +383,9 @@ public class AbstractPostServletTest {
private static final long serialVersionUID = -2948341218853558959L;
@Override
- protected void handleOperation(SlingJakartaHttpServletRequest request, JakartaPostResponse response,
- List<Modification> changes) throws RepositoryException {
+ protected void handleOperation(
+ SlingJakartaHttpServletRequest request, JakartaPostResponse response, List<Modification> changes)
+ throws RepositoryException {
// do nothing
}
}
diff --git a/src/test/java/org/apache/sling/jackrabbit/usermanager/impl/post/PrincipalNameGeneratorImplTest.java b/src/test/java/org/apache/sling/jackrabbit/usermanager/impl/post/PrincipalNameGeneratorImplTest.java
index 222327f..088d77d 100644
--- a/src/test/java/org/apache/sling/jackrabbit/usermanager/impl/post/PrincipalNameGeneratorImplTest.java
+++ b/src/test/java/org/apache/sling/jackrabbit/usermanager/impl/post/PrincipalNameGeneratorImplTest.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.jackrabbit.usermanager.impl.post;
-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 java.util.Arrays;
import java.util.HashMap;
import java.util.List;
@@ -40,6 +36,12 @@ 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.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
@RunWith(Parameterized.class)
public class PrincipalNameGeneratorImplTest {
@@ -57,16 +59,15 @@ public class PrincipalNameGeneratorImplTest {
/**
* Helper to reduce code duplication
- *
+ *
* @param map the map to add to
* @param paramName the parameter name
* @param paramValue the parameter value
* @return
*/
- private static RequestParameter[] addParam(Map<String, RequestParameter[]> map, String paramName, String paramValue) {
- return map.put(paramName, new RequestParameter[] {
- Builders.newRequestParameter(paramName, paramValue)
- });
+ private static RequestParameter[] addParam(
+ Map<String, RequestParameter[]> map, String paramName, String paramValue) {
+ return map.put(paramName, new RequestParameter[] {Builders.newRequestParameter(paramName, paramValue)});
}
@Test
@@ -123,7 +124,10 @@ public class PrincipalNameGeneratorImplTest {
PrincipalNameFilter filter = null;
Map<String, RequestParameter[]> parameters = new HashMap<>();
addParam(parameters, "displayName", "name1");
- addParam(parameters, String.format("%s%s", SlingPostConstants.RP_NODE_NAME, SlingPostConstants.VALUE_FROM_SUFFIX), "displayName");
+ addParam(
+ parameters,
+ String.format("%s%s", SlingPostConstants.RP_NODE_NAME, SlingPostConstants.VALUE_FROM_SUFFIX),
+ "displayName");
NameInfo nameInfo = generator.getPrincipalName(parameters, type, filter, defaultGenerator);
assertNotNull(nameInfo);
assertEquals("name1", nameInfo.getPrincipalName());
@@ -136,7 +140,10 @@ public class PrincipalNameGeneratorImplTest {
PrincipalNameFilter filter = null;
Map<String, RequestParameter[]> parameters = new HashMap<>();
addParam(parameters, "displayName", "namethatistoolong123456789");
- addParam(parameters, String.format("%s%s", SlingPostConstants.RP_NODE_NAME, SlingPostConstants.VALUE_FROM_SUFFIX), "displayName");
+ addParam(
+ parameters,
+ String.format("%s%s", SlingPostConstants.RP_NODE_NAME, SlingPostConstants.VALUE_FROM_SUFFIX),
+ "displayName");
NameInfo nameInfo = generator.getPrincipalName(parameters, type, filter, defaultGenerator);
assertNotNull(nameInfo);
assertEquals("namethatistoolong123456789", nameInfo.getPrincipalName());
@@ -149,7 +156,10 @@ public class PrincipalNameGeneratorImplTest {
PrincipalNameFilter filter = new CustomPrincipalNameFilterImpl();
Map<String, RequestParameter[]> parameters = new HashMap<>();
addParam(parameters, "displayName", "Na me1");
- addParam(parameters, String.format("%s%s", SlingPostConstants.RP_NODE_NAME, SlingPostConstants.VALUE_FROM_SUFFIX), "displayName");
+ addParam(
+ parameters,
+ String.format("%s%s", SlingPostConstants.RP_NODE_NAME, SlingPostConstants.VALUE_FROM_SUFFIX),
+ "displayName");
NameInfo nameInfo = generator.getPrincipalName(parameters, type, filter, defaultGenerator);
assertNotNull(nameInfo);
assertEquals("Na me1", nameInfo.getPrincipalName());
@@ -162,7 +172,10 @@ public class PrincipalNameGeneratorImplTest {
PrincipalNameFilter filter = null;
Map<String, RequestParameter[]> parameters = new HashMap<>();
addParam(parameters, "displayName", "name1");
- addParam(parameters, String.format("%s%s", SlingPostConstants.RP_NODE_NAME_HINT, SlingPostConstants.VALUE_FROM_SUFFIX), "displayName");
+ addParam(
+ parameters,
+ String.format("%s%s", SlingPostConstants.RP_NODE_NAME_HINT, SlingPostConstants.VALUE_FROM_SUFFIX),
+ "displayName");
NameInfo nameInfo = generator.getPrincipalName(parameters, type, filter, defaultGenerator);
assertNotNull(nameInfo);
assertEquals("name1", nameInfo.getPrincipalName());
@@ -175,7 +188,10 @@ public class PrincipalNameGeneratorImplTest {
PrincipalNameFilter filter = null;
Map<String, RequestParameter[]> parameters = new HashMap<>();
addParam(parameters, "displayName", "namethatistoolong123456789");
- addParam(parameters, String.format("%s%s", SlingPostConstants.RP_NODE_NAME_HINT, SlingPostConstants.VALUE_FROM_SUFFIX), "displayName");
+ addParam(
+ parameters,
+ String.format("%s%s", SlingPostConstants.RP_NODE_NAME_HINT, SlingPostConstants.VALUE_FROM_SUFFIX),
+ "displayName");
NameInfo nameInfo = generator.getPrincipalName(parameters, type, filter, defaultGenerator);
assertNotNull(nameInfo);
assertEquals("namethatistoolong123", nameInfo.getPrincipalName());
@@ -188,7 +204,10 @@ public class PrincipalNameGeneratorImplTest {
PrincipalNameFilter filter = new CustomPrincipalNameFilterImpl();
Map<String, RequestParameter[]> parameters = new HashMap<>();
addParam(parameters, "displayName", "Na me1");
- addParam(parameters, String.format("%s%s", SlingPostConstants.RP_NODE_NAME_HINT, SlingPostConstants.VALUE_FROM_SUFFIX), "displayName");
+ addParam(
+ parameters,
+ String.format("%s%s", SlingPostConstants.RP_NODE_NAME_HINT, SlingPostConstants.VALUE_FROM_SUFFIX),
+ "displayName");
NameInfo nameInfo = generator.getPrincipalName(parameters, type, filter, defaultGenerator);
assertNotNull(nameInfo);
assertEquals("na_me1", nameInfo.getPrincipalName());
@@ -197,10 +216,7 @@ public class PrincipalNameGeneratorImplTest {
@Test
public void testPrincipalNameFromConfiguredHint() {
- PrincipalNameGenerator generator = new PrincipalNameGeneratorImpl(new String[] {
- "displayName2"
- },
- 10);
+ PrincipalNameGenerator generator = new PrincipalNameGeneratorImpl(new String[] {"displayName2"}, 10);
PrincipalNameFilter filter = null;
Map<String, RequestParameter[]> parameters = new HashMap<>();
addParam(parameters, "displayName2", "name1");
@@ -212,10 +228,7 @@ public class PrincipalNameGeneratorImplTest {
@Test
public void testPrincipalNameFromConfiguredHintWithFilter() {
- PrincipalNameGenerator generator = new PrincipalNameGeneratorImpl(new String[] {
- "displayName2"
- },
- 10);
+ PrincipalNameGenerator generator = new PrincipalNameGeneratorImpl(new String[] {"displayName2"}, 10);
PrincipalNameFilter filter = new CustomPrincipalNameFilterImpl();
Map<String, RequestParameter[]> parameters = new HashMap<>();
addParam(parameters, "displayName2", "Na me1");
@@ -227,10 +240,7 @@ public class PrincipalNameGeneratorImplTest {
@Test
public void testPrincipalNameFromConfiguredHintTooLong() {
- PrincipalNameGenerator generator = new PrincipalNameGeneratorImpl(new String[] {
- "displayName2"
- },
- 10);
+ PrincipalNameGenerator generator = new PrincipalNameGeneratorImpl(new String[] {"displayName2"}, 10);
PrincipalNameFilter filter = null;
Map<String, RequestParameter[]> parameters = new HashMap<>();
addParam(parameters, "displayName2", "namethatistoolong");
@@ -255,8 +265,8 @@ public class PrincipalNameGeneratorImplTest {
assertEquals(List.of("value"), generator.valueToList("value"));
assertEquals(List.of("value1", "value2"), generator.valueToList(new String[] {"value1", "value2"}));
assertEquals(List.of("value1", "value2"), generator.valueToList(new RequestParameter[] {
- Builders.newRequestParameter("key1", "value1"), Builders.newRequestParameter("key1", "value2")}));
+ Builders.newRequestParameter("key1", "value1"), Builders.newRequestParameter("key1", "value2")
+ }));
assertEquals(List.of(), generator.valueToList(new Object()));
}
-
}
diff --git a/src/test/java/org/apache/sling/jackrabbit/usermanager/impl/resource/LazyInputStreamTest.java b/src/test/java/org/apache/sling/jackrabbit/usermanager/impl/resource/LazyInputStreamTest.java
index dcdf203..449cfe0 100644
--- a/src/test/java/org/apache/sling/jackrabbit/usermanager/impl/resource/LazyInputStreamTest.java
+++ b/src/test/java/org/apache/sling/jackrabbit/usermanager/impl/resource/LazyInputStreamTest.java
@@ -1,34 +1,36 @@
/*
- * 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.jackrabbit.usermanager.impl.resource;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import javax.jcr.ValueFactory;
import java.io.IOException;
-import javax.jcr.ValueFactory;
-
import org.apache.jackrabbit.value.ValueFactoryImpl;
import org.apache.sling.jackrabbit.usermanager.impl.resource.BaseAuthorizableValueMap.LazyInputStream;
import org.junit.Before;
import org.junit.Test;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
/**
* Provides code coverage for BaseAuthorizableValueMap.LazyInputStream
*/
@@ -39,7 +41,7 @@ public class LazyInputStreamTest {
@Before
public void setup() {
ValueFactory vf = ValueFactoryImpl.getInstance();
- lazyIS = new LazyInputStream(vf.createValue("Hello World"));
+ lazyIS = new LazyInputStream(vf.createValue("Hello World"));
}
public void teardown() {
@@ -57,7 +59,7 @@ public class LazyInputStreamTest {
public void testClose() throws IOException {
// first without any reads that would construct the delegatee
lazyIS.close();
- //then some call that initiates te delegatee
+ // then some call that initiates te delegatee
assertTrue(lazyIS.available() > 0);
// and close again
lazyIS.close();
@@ -112,11 +114,11 @@ public class LazyInputStreamTest {
assertEquals('e', lazyIS.read());
assertEquals('l', lazyIS.read());
- //also try exceeding the readlimit
+ // also try exceeding the readlimit
lazyIS.mark(readlimit);
lazyIS.read(new byte[readlimit + 1]);
lazyIS.reset();
- byte [] whatsleft = new byte[8];
+ byte[] whatsleft = new byte[8];
assertEquals(8, lazyIS.read(whatsleft));
assertArrayEquals("lo World".getBytes(), whatsleft);
}
@@ -130,5 +132,4 @@ public class LazyInputStreamTest {
lazyIS.reset();
assertEquals('H', lazyIS.read());
}
-
}
diff --git a/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/AceTools.java b/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/AceTools.java
index 9610d24..53552af 100644
--- a/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/AceTools.java
+++ b/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/AceTools.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.jackrabbit.usermanager.it;
-import java.security.Principal;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.security.AccessControlEntry;
@@ -30,6 +27,11 @@ import javax.jcr.security.AccessControlPolicy;
import javax.jcr.security.AccessControlPolicyIterator;
import javax.jcr.security.Privilege;
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
import org.apache.jackrabbit.api.security.JackrabbitAccessControlList;
import org.apache.jackrabbit.api.security.user.Authorizable;
@@ -40,17 +42,23 @@ import org.apache.jackrabbit.api.security.user.Authorizable;
public class AceTools {
/**
- *
+ *
*/
private AceTools() {
// to hide public ctor
}
- public static void modifyAce(Session jcrSession, String resourcePath, Authorizable authorizable,
- Set<String> grantedPrivileges, Set<String> deniedPrivileges) throws RepositoryException {
+ public static void modifyAce(
+ Session jcrSession,
+ String resourcePath,
+ Authorizable authorizable,
+ Set<String> grantedPrivileges,
+ Set<String> deniedPrivileges)
+ throws RepositoryException {
AccessControlManager accessControlManager = jcrSession.getAccessControlManager();
Principal principal = authorizable.getPrincipal();
- JackrabbitAccessControlList updatedAcl = (JackrabbitAccessControlList)getAccessControlListOrNull(accessControlManager, resourcePath, true);
+ JackrabbitAccessControlList updatedAcl =
+ (JackrabbitAccessControlList) getAccessControlListOrNull(accessControlManager, resourcePath, true);
if (grantedPrivileges != null) {
Privilege[] privileges = toPrivilegesArray(grantedPrivileges, accessControlManager);
updatedAcl.addEntry(principal, privileges, true);
@@ -60,15 +68,15 @@ public class AceTools {
updatedAcl.addEntry(principal, privileges, false);
}
- //apply the changed policy
+ // apply the changed policy
accessControlManager.setPolicy(resourcePath, updatedAcl);
// autosave
jcrSession.save();
}
- private static Privilege[] toPrivilegesArray(Set<String> grantedPrivileges,
- AccessControlManager accessControlManager) throws RepositoryException {
+ private static Privilege[] toPrivilegesArray(
+ Set<String> grantedPrivileges, AccessControlManager accessControlManager) throws RepositoryException {
List<Privilege> privilegesList = new ArrayList<>();
for (String name : grantedPrivileges) {
Privilege privilege = accessControlManager.privilegeFromName(name);
@@ -77,14 +85,15 @@ public class AceTools {
return privilegesList.toArray(Privilege[]::new);
}
- public static void deleteAces(Session jcrSession, String resourcePath, Authorizable authorizable) throws RepositoryException {
+ public static void deleteAces(Session jcrSession, String resourcePath, Authorizable authorizable)
+ throws RepositoryException {
AccessControlManager accessControlManager = jcrSession.getAccessControlManager();
Principal principal = authorizable.getPrincipal();
AccessControlList updatedAcl = getAccessControlListOrNull(accessControlManager, resourcePath, false);
// if there is no AccessControlList, then there is nothing to be deleted
if (updatedAcl != null) {
- //keep track of the existing Aces for the target principal
+ // keep track of the existing Aces for the target principal
AccessControlEntry[] accessControlEntries = updatedAcl.getAccessControlEntries();
List<AccessControlEntry> oldAces = new ArrayList<>();
for (AccessControlEntry ace : accessControlEntries) {
@@ -93,14 +102,14 @@ public class AceTools {
}
}
- //remove the old aces
+ // remove the old aces
if (!oldAces.isEmpty()) {
for (AccessControlEntry ace : oldAces) {
updatedAcl.removeAccessControlEntry(ace);
}
}
- //apply the changed policy
+ // apply the changed policy
accessControlManager.setPolicy(resourcePath, updatedAcl);
// autosave
@@ -122,8 +131,7 @@ public class AceTools {
* @throws RepositoryException if any errors reading the information
*/
protected static AccessControlList getAccessControlListOrNull(
- final AccessControlManager accessControlManager,
- final String resourcePath, final boolean mayCreate)
+ final AccessControlManager accessControlManager, final String resourcePath, final boolean mayCreate)
throws RepositoryException {
AccessControlList acl = null;
// check for an existing access control list to edit
@@ -146,5 +154,4 @@ public class AceTools {
}
return acl;
}
-
}
diff --git a/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/AuthorizablePrivilegesInfoIT.java b/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/AuthorizablePrivilegesInfoIT.java
index 105d5dd..b65ea44 100644
--- a/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/AuthorizablePrivilegesInfoIT.java
+++ b/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/AuthorizablePrivilegesInfoIT.java
@@ -18,11 +18,12 @@
*/
package org.apache.sling.jcr.jackrabbit.usermanager.it;
-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 javax.inject.Inject;
+import javax.jcr.AccessDeniedException;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.SimpleCredentials;
+import javax.jcr.security.Privilege;
import java.io.IOException;
import java.util.ArrayList;
@@ -33,13 +34,6 @@ import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
-import javax.inject.Inject;
-import javax.jcr.AccessDeniedException;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.SimpleCredentials;
-import javax.jcr.security.Privilege;
-
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.User;
@@ -71,6 +65,12 @@ import org.osgi.service.cm.ConfigurationAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+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;
+
/**
* Basic test of AuthorizablePrivilegesInfo component
*/
@@ -128,8 +128,13 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
adminSession = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
assertNotNull("Expected adminSession to not be null", adminSession);
- user1 = createUser.createUser(adminSession, createUniqueName("user"), "testPwd", "testPwd",
- Collections.emptyMap(), new ArrayList<>());
+ user1 = createUser.createUser(
+ adminSession,
+ createUniqueName("user"),
+ "testPwd",
+ "testPwd",
+ Collections.emptyMap(),
+ new ArrayList<>());
assertNotNull("Expected user1 to not be null", user1);
if (adminSession.hasPendingChanges()) {
@@ -174,35 +179,37 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
User user2 = null;
try {
// initially user can't do the operations
- assertFalse("Should not be allowed to add user",
- privilegesInfo.canAddUser(user1Session));
+ assertFalse("Should not be allowed to add user", privilegesInfo.canAddUser(user1Session));
String usersPath = userConfig.getParameters().getConfigValue("usersPath", null, String.class);
assertNotNull("Users Path should not be null", usersPath);
- assertTrue("Users Path should exist",
- adminSession.itemExists(usersPath));
+ assertTrue("Users Path should exist", adminSession.itemExists(usersPath));
// grant user1 rights
- AceTools.modifyAce(adminSession, usersPath, user1, Set.of(
- Privilege.JCR_READ,
- Privilege.JCR_READ_ACCESS_CONTROL,
- Privilege.JCR_MODIFY_ACCESS_CONTROL,
- PrivilegeConstants.REP_WRITE,
- PrivilegeConstants.REP_USER_MANAGEMENT
- ), null);
- assertTrue("Should be allowed to add user",
- privilegesInfo.canAddUser(user1Session));
+ AceTools.modifyAce(
+ adminSession,
+ usersPath,
+ user1,
+ Set.of(
+ Privilege.JCR_READ,
+ Privilege.JCR_READ_ACCESS_CONTROL,
+ Privilege.JCR_MODIFY_ACCESS_CONTROL,
+ PrivilegeConstants.REP_WRITE,
+ PrivilegeConstants.REP_USER_MANAGEMENT),
+ null);
+ assertTrue("Should be allowed to add user", privilegesInfo.canAddUser(user1Session));
// verify that the user can actually add the user
try {
Map<String, String> propMap = new HashMap<>();
propMap.put("prop1", "value1");
propMap.put("nested/prop2", "value2");
- user2 = createUser.createUser(user1Session, createUniqueName("user"), "testPwd", "testPwd",
- propMap, new ArrayList<>());
+ user2 = createUser.createUser(
+ user1Session, createUniqueName("user"), "testPwd", "testPwd", propMap, new ArrayList<>());
assertNotNull("Expected user2 to not be null", user2);
} catch (RepositoryException e) {
- logger.error(String.format("Did not expect RepositoryException when adding user: %s", e.getMessage()), e);
+ logger.error(
+ String.format("Did not expect RepositoryException when adding user: %s", e.getMessage()), e);
fail("Did not expect RepositoryException when adding user: " + e.getMessage());
}
} finally {
@@ -225,35 +232,36 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
Group group1 = null;
try {
// initially user can't do the operations
- assertFalse("Should not be allowed to add group",
- privilegesInfo.canAddGroup(user1Session));
+ assertFalse("Should not be allowed to add group", privilegesInfo.canAddGroup(user1Session));
String groupsPath = userConfig.getParameters().getConfigValue("groupsPath", null, String.class);
assertNotNull("Groups Path should not be null", groupsPath);
- assertTrue("Groups Path should exist",
- adminSession.itemExists(groupsPath));
+ assertTrue("Groups Path should exist", adminSession.itemExists(groupsPath));
// grant user1 rights
- AceTools.modifyAce(adminSession, groupsPath, user1, Set.of(
- Privilege.JCR_READ,
- Privilege.JCR_READ_ACCESS_CONTROL,
- Privilege.JCR_MODIFY_ACCESS_CONTROL,
- PrivilegeConstants.REP_WRITE,
- PrivilegeConstants.REP_USER_MANAGEMENT
- ), null);
- assertTrue("Should be allowed to add group",
- privilegesInfo.canAddGroup(user1Session));
+ AceTools.modifyAce(
+ adminSession,
+ groupsPath,
+ user1,
+ Set.of(
+ Privilege.JCR_READ,
+ Privilege.JCR_READ_ACCESS_CONTROL,
+ Privilege.JCR_MODIFY_ACCESS_CONTROL,
+ PrivilegeConstants.REP_WRITE,
+ PrivilegeConstants.REP_USER_MANAGEMENT),
+ null);
+ assertTrue("Should be allowed to add group", privilegesInfo.canAddGroup(user1Session));
// verify that the user can actually add the user
try {
Map<String, String> propMap = new HashMap<>();
propMap.put("prop1", "value1");
propMap.put("nested/prop2", "value2");
- group1 = createGroup.createGroup(user1Session, createUniqueName("group"),
- propMap, new ArrayList<>());
+ group1 = createGroup.createGroup(user1Session, createUniqueName("group"), propMap, new ArrayList<>());
assertNotNull("Expected group1 to not be null", group1);
} catch (RepositoryException e) {
- logger.error(String.format("Did not expect RepositoryException when adding group: %s", e.getMessage()), e);
+ logger.error(
+ String.format("Did not expect RepositoryException when adding group: %s", e.getMessage()), e);
fail("Did not expect RepositoryException when adding group: " + e.getMessage());
}
} finally {
@@ -274,12 +282,11 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
assertNotNull("Groups Path should not be null", groupsPath);
if (!adminSession.itemExists(groupsPath)) {
// create a group and the remove it
- Group tempGroup = createGroup.createGroup(adminSession, createUniqueName("group"),
- Collections.emptyMap(), new ArrayList<>());
+ Group tempGroup = createGroup.createGroup(
+ adminSession, createUniqueName("group"), Collections.emptyMap(), new ArrayList<>());
deleteGroup.deleteGroup(adminSession, tempGroup.getID(), new ArrayList<>());
}
- assertTrue("Groups Path should exist",
- adminSession.itemExists(groupsPath));
+ assertTrue("Groups Path should exist", adminSession.itemExists(groupsPath));
}
/**
@@ -297,19 +304,28 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
try {
// create a couple of test users
- user2 = createUser.createUser(adminSession, createUniqueName("user"), "testPwd", "testPwd",
- Collections.singletonMap("prop1", "value1"), new ArrayList<>());
+ user2 = createUser.createUser(
+ adminSession,
+ createUniqueName("user"),
+ "testPwd",
+ "testPwd",
+ Collections.singletonMap("prop1", "value1"),
+ new ArrayList<>());
assertNotNull("Expected user2 to not be null", user2);
- group1 = createGroup.createGroup(adminSession, createUniqueName("group"),
- Collections.singletonMap("prop1", "value1"), new ArrayList<>());
+ group1 = createGroup.createGroup(
+ adminSession,
+ createUniqueName("group"),
+ Collections.singletonMap("prop1", "value1"),
+ new ArrayList<>());
assertNotNull("Expected group1 to not be null", group1);
- String [] principalIds = new String[] { user2.getID(), group1.getID() };
+ String[] principalIds = new String[] {user2.getID(), group1.getID()};
// initially user can't do the operation
for (String pid : principalIds) {
- assertFalse("Should not be allowed to update properties for: " + pid,
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid));
}
@@ -317,21 +333,46 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
AceTools.modifyAce(adminSession, user2.getPath(), user1, Set.of(Privilege.JCR_READ), null);
AceTools.modifyAce(adminSession, group1.getPath(), user1, Set.of(Privilege.JCR_READ), null);
for (String pid : principalIds) {
- assertFalse("Should not be allowed to update properties for: " + pid,
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid));
- assertFalse("Should not be allowed to update properties for: " + pid,
- privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_PROPERTY, PropertyUpdateTypes.ADD_NESTED_PROPERTY, PropertyUpdateTypes.REMOVE_PROPERTY));
- assertFalse("Should not be allowed to update properties for: " + pid,
- privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_PROPERTY, PropertyUpdateTypes.ADD_NESTED_PROPERTY));
- assertFalse("Should not be allowed to update properties for: " + pid,
- privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_PROPERTY, PropertyUpdateTypes.REMOVE_PROPERTY));
- assertFalse("Should not be allowed to update properties for: " + pid,
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
+ privilegesInfo.canUpdateProperties(
+ user1Session,
+ pid,
+ PropertyUpdateTypes.ADD_PROPERTY,
+ PropertyUpdateTypes.ADD_NESTED_PROPERTY,
+ PropertyUpdateTypes.REMOVE_PROPERTY));
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
+ privilegesInfo.canUpdateProperties(
+ user1Session,
+ pid,
+ PropertyUpdateTypes.ADD_PROPERTY,
+ PropertyUpdateTypes.ADD_NESTED_PROPERTY));
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
+ privilegesInfo.canUpdateProperties(
+ user1Session,
+ pid,
+ PropertyUpdateTypes.ADD_PROPERTY,
+ PropertyUpdateTypes.REMOVE_PROPERTY));
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_PROPERTY));
- assertFalse("Should not be allowed to update properties for: " + pid,
- privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_NESTED_PROPERTY, PropertyUpdateTypes.REMOVE_PROPERTY));
- assertFalse("Should not be allowed to update properties for: " + pid,
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
+ privilegesInfo.canUpdateProperties(
+ user1Session,
+ pid,
+ PropertyUpdateTypes.ADD_NESTED_PROPERTY,
+ PropertyUpdateTypes.REMOVE_PROPERTY));
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_NESTED_PROPERTY));
- assertFalse("Should not be allowed to update properties for: " + pid,
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.REMOVE_PROPERTY));
}
} finally {
@@ -359,46 +400,79 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
try {
// create a couple of test users
- user2 = createUser.createUser(adminSession, createUniqueName("user"), "testPwd", "testPwd",
- Collections.singletonMap("prop1", "value1"), new ArrayList<>());
+ user2 = createUser.createUser(
+ adminSession,
+ createUniqueName("user"),
+ "testPwd",
+ "testPwd",
+ Collections.singletonMap("prop1", "value1"),
+ new ArrayList<>());
assertNotNull("Expected user2 to not be null", user2);
- group1 = createGroup.createGroup(adminSession, createUniqueName("group"),
- Collections.singletonMap("prop1", "value1"), new ArrayList<>());
+ group1 = createGroup.createGroup(
+ adminSession,
+ createUniqueName("group"),
+ Collections.singletonMap("prop1", "value1"),
+ new ArrayList<>());
assertNotNull("Expected group1 to not be null", group1);
- String [] principalIds = new String[] { user2.getID(), group1.getID() };
+ String[] principalIds = new String[] {user2.getID(), group1.getID()};
// initially user can't do the operation
for (String pid : principalIds) {
- assertFalse("Should not be allowed to update properties for: " + pid,
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid));
}
// start with only read rights
Set<String> grantedPrivilegeNames = Set.of(
- Privilege.JCR_READ,
- // + grant rights to only remove properties
- PrivilegeConstants.REP_REMOVE_PROPERTIES
- );
+ Privilege.JCR_READ,
+ // + grant rights to only remove properties
+ PrivilegeConstants.REP_REMOVE_PROPERTIES);
AceTools.modifyAce(adminSession, user2.getPath(), user1, grantedPrivilegeNames, null);
AceTools.modifyAce(adminSession, group1.getPath(), user1, grantedPrivilegeNames, null);
for (String pid : principalIds) {
- assertFalse("Should not be allowed to update properties for: " + pid,
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid));
- assertFalse("Should not be allowed to update properties for: " + pid,
- privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_PROPERTY, PropertyUpdateTypes.ADD_NESTED_PROPERTY, PropertyUpdateTypes.REMOVE_PROPERTY));
- assertFalse("Should not be allowed to update properties for: " + pid,
- privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_PROPERTY, PropertyUpdateTypes.ADD_NESTED_PROPERTY));
- assertFalse("Should not be allowed to update properties for: " + pid,
- privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_PROPERTY, PropertyUpdateTypes.REMOVE_PROPERTY));
- assertFalse("Should not be allowed to update properties for: " + pid,
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
+ privilegesInfo.canUpdateProperties(
+ user1Session,
+ pid,
+ PropertyUpdateTypes.ADD_PROPERTY,
+ PropertyUpdateTypes.ADD_NESTED_PROPERTY,
+ PropertyUpdateTypes.REMOVE_PROPERTY));
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
+ privilegesInfo.canUpdateProperties(
+ user1Session,
+ pid,
+ PropertyUpdateTypes.ADD_PROPERTY,
+ PropertyUpdateTypes.ADD_NESTED_PROPERTY));
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
+ privilegesInfo.canUpdateProperties(
+ user1Session,
+ pid,
+ PropertyUpdateTypes.ADD_PROPERTY,
+ PropertyUpdateTypes.REMOVE_PROPERTY));
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_PROPERTY));
- assertFalse("Should not be allowed to update properties for: " + pid,
- privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_NESTED_PROPERTY, PropertyUpdateTypes.REMOVE_PROPERTY));
- assertFalse("Should not be allowed to update properties for: " + pid,
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
+ privilegesInfo.canUpdateProperties(
+ user1Session,
+ pid,
+ PropertyUpdateTypes.ADD_NESTED_PROPERTY,
+ PropertyUpdateTypes.REMOVE_PROPERTY));
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_NESTED_PROPERTY));
- assertTrue("Should be allowed to update properties for: " + pid,
+ assertTrue(
+ "Should be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.REMOVE_PROPERTY));
}
@@ -411,7 +485,9 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
assertTrue("Expected pending changes in the jcr session", user1Session.hasPendingChanges());
user1Session.save();
} catch (RepositoryException e) {
- logger.error(String.format("Did not expect RepositoryException when deleting property: %s", e.getMessage()), e);
+ logger.error(
+ String.format("Did not expect RepositoryException when deleting property: %s", e.getMessage()),
+ e);
fail("Did not expect RepositoryException when deleting property: " + e.getMessage());
}
// verify that the user can not add nested property
@@ -452,46 +528,79 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
try {
// create a couple of test users
- user2 = createUser.createUser(adminSession, createUniqueName("user"), "testPwd", "testPwd",
- Collections.singletonMap("prop1", "value1"), new ArrayList<>());
+ user2 = createUser.createUser(
+ adminSession,
+ createUniqueName("user"),
+ "testPwd",
+ "testPwd",
+ Collections.singletonMap("prop1", "value1"),
+ new ArrayList<>());
assertNotNull("Expected user2 to not be null", user2);
- group1 = createGroup.createGroup(adminSession, createUniqueName("group"),
- Collections.singletonMap("prop1", "value1"), new ArrayList<>());
+ group1 = createGroup.createGroup(
+ adminSession,
+ createUniqueName("group"),
+ Collections.singletonMap("prop1", "value1"),
+ new ArrayList<>());
assertNotNull("Expected group1 to not be null", group1);
- String [] principalIds = new String[] { user2.getID(), group1.getID() };
+ String[] principalIds = new String[] {user2.getID(), group1.getID()};
// initially user can't do the operation
for (String pid : principalIds) {
- assertFalse("Should not be allowed to update properties for: " + pid,
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid));
}
// start with only read rights
Set<String> grantedPrivilegeNames = Set.of(
- Privilege.JCR_READ,
- // + grant rights to only alter (non-nested) properties
- PrivilegeConstants.REP_ADD_PROPERTIES
- );
+ Privilege.JCR_READ,
+ // + grant rights to only alter (non-nested) properties
+ PrivilegeConstants.REP_ADD_PROPERTIES);
AceTools.modifyAce(adminSession, user2.getPath(), user1, grantedPrivilegeNames, null);
AceTools.modifyAce(adminSession, group1.getPath(), user1, grantedPrivilegeNames, null);
for (String pid : principalIds) {
- assertFalse("Should not be allowed to update properties for: " + pid,
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid));
- assertFalse("Should not be allowed to update properties for: " + pid,
- privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_PROPERTY, PropertyUpdateTypes.ADD_NESTED_PROPERTY, PropertyUpdateTypes.REMOVE_PROPERTY));
- assertFalse("Should not be allowed to update properties for: " + pid,
- privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_PROPERTY, PropertyUpdateTypes.ADD_NESTED_PROPERTY));
- assertFalse("Should not be allowed to update properties for: " + pid,
- privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_PROPERTY, PropertyUpdateTypes.REMOVE_PROPERTY));
- assertTrue("Should be allowed to update properties for: " + pid,
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
+ privilegesInfo.canUpdateProperties(
+ user1Session,
+ pid,
+ PropertyUpdateTypes.ADD_PROPERTY,
+ PropertyUpdateTypes.ADD_NESTED_PROPERTY,
+ PropertyUpdateTypes.REMOVE_PROPERTY));
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
+ privilegesInfo.canUpdateProperties(
+ user1Session,
+ pid,
+ PropertyUpdateTypes.ADD_PROPERTY,
+ PropertyUpdateTypes.ADD_NESTED_PROPERTY));
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
+ privilegesInfo.canUpdateProperties(
+ user1Session,
+ pid,
+ PropertyUpdateTypes.ADD_PROPERTY,
+ PropertyUpdateTypes.REMOVE_PROPERTY));
+ assertTrue(
+ "Should be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_PROPERTY));
- assertFalse("Should not be allowed to update properties for: " + pid,
- privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_NESTED_PROPERTY, PropertyUpdateTypes.REMOVE_PROPERTY));
- assertFalse("Should not be allowed to update properties for: " + pid,
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
+ privilegesInfo.canUpdateProperties(
+ user1Session,
+ pid,
+ PropertyUpdateTypes.ADD_NESTED_PROPERTY,
+ PropertyUpdateTypes.REMOVE_PROPERTY));
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_NESTED_PROPERTY));
- assertFalse("Should not be allowed to update properties for: " + pid,
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.REMOVE_PROPERTY));
}
@@ -504,7 +613,9 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
assertTrue("Expected pending changes in the jcr session", user1Session.hasPendingChanges());
user1Session.save();
} catch (RepositoryException e) {
- logger.error(String.format("Did not expect RepositoryException when adding property: %s", e.getMessage()), e);
+ logger.error(
+ String.format("Did not expect RepositoryException when adding property: %s", e.getMessage()),
+ e);
fail("Did not expect RepositoryException when adding property: " + e.getMessage());
}
// verify that the user can not add nested property
@@ -544,48 +655,81 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
try {
// create a couple of test users
- user2 = createUser.createUser(adminSession, createUniqueName("user"), "testPwd", "testPwd",
- Collections.singletonMap("prop1", "value1"), new ArrayList<>());
+ user2 = createUser.createUser(
+ adminSession,
+ createUniqueName("user"),
+ "testPwd",
+ "testPwd",
+ Collections.singletonMap("prop1", "value1"),
+ new ArrayList<>());
assertNotNull("Expected user2 to not be null", user2);
- group1 = createGroup.createGroup(adminSession, createUniqueName("group"),
- Collections.singletonMap("prop1", "value1"), new ArrayList<>());
+ group1 = createGroup.createGroup(
+ adminSession,
+ createUniqueName("group"),
+ Collections.singletonMap("prop1", "value1"),
+ new ArrayList<>());
assertNotNull("Expected group1 to not be null", group1);
- String [] principalIds = new String[] { user2.getID(), group1.getID() };
+ String[] principalIds = new String[] {user2.getID(), group1.getID()};
// initially user can't do the operation
for (String pid : principalIds) {
- assertFalse("Should not be allowed to update properties for: " + pid,
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid));
}
// start with only read rights
Set<String> grantedPrivilegeNames = Set.of(
- Privilege.JCR_READ,
- // + grant rights to alter (non-nested or nested) properties
- PrivilegeConstants.REP_ADD_PROPERTIES,
- PrivilegeConstants.REP_ALTER_PROPERTIES,
- Privilege.JCR_ADD_CHILD_NODES
- );
+ Privilege.JCR_READ,
+ // + grant rights to alter (non-nested or nested) properties
+ PrivilegeConstants.REP_ADD_PROPERTIES,
+ PrivilegeConstants.REP_ALTER_PROPERTIES,
+ Privilege.JCR_ADD_CHILD_NODES);
AceTools.modifyAce(adminSession, user2.getPath(), user1, grantedPrivilegeNames, null);
AceTools.modifyAce(adminSession, group1.getPath(), user1, grantedPrivilegeNames, null);
for (String pid : principalIds) {
- assertFalse("Should not be allowed to update properties for: " + pid,
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid));
- assertFalse("Should not be allowed to update properties for: " + pid,
- privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_PROPERTY, PropertyUpdateTypes.ADD_NESTED_PROPERTY, PropertyUpdateTypes.REMOVE_PROPERTY));
- assertTrue("Should be allowed to update properties for: " + pid,
- privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_PROPERTY, PropertyUpdateTypes.ADD_NESTED_PROPERTY));
- assertFalse("Should not be allowed to update properties for: " + pid,
- privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_PROPERTY, PropertyUpdateTypes.REMOVE_PROPERTY));
- assertTrue("Should be allowed to update properties for: " + pid,
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
+ privilegesInfo.canUpdateProperties(
+ user1Session,
+ pid,
+ PropertyUpdateTypes.ADD_PROPERTY,
+ PropertyUpdateTypes.ADD_NESTED_PROPERTY,
+ PropertyUpdateTypes.REMOVE_PROPERTY));
+ assertTrue(
+ "Should be allowed to update properties for: " + pid,
+ privilegesInfo.canUpdateProperties(
+ user1Session,
+ pid,
+ PropertyUpdateTypes.ADD_PROPERTY,
+ PropertyUpdateTypes.ADD_NESTED_PROPERTY));
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
+ privilegesInfo.canUpdateProperties(
+ user1Session,
+ pid,
+ PropertyUpdateTypes.ADD_PROPERTY,
+ PropertyUpdateTypes.REMOVE_PROPERTY));
+ assertTrue(
+ "Should be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_PROPERTY));
- assertFalse("Should not be allowed to update properties for: " + pid,
- privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_NESTED_PROPERTY, PropertyUpdateTypes.REMOVE_PROPERTY));
- assertTrue("Should be allowed to update properties for: " + pid,
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
+ privilegesInfo.canUpdateProperties(
+ user1Session,
+ pid,
+ PropertyUpdateTypes.ADD_NESTED_PROPERTY,
+ PropertyUpdateTypes.REMOVE_PROPERTY));
+ assertTrue(
+ "Should be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_NESTED_PROPERTY));
- assertFalse("Should not be allowed to update properties for: " + pid,
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.REMOVE_PROPERTY));
}
@@ -599,7 +743,9 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
assertTrue("Expected pending changes in the jcr session", user1Session.hasPendingChanges());
user1Session.save();
} catch (RepositoryException e) {
- logger.error(String.format("Did not expect RepositoryException when adding properties: %s", e.getMessage()), e);
+ logger.error(
+ String.format("Did not expect RepositoryException when adding properties: %s", e.getMessage()),
+ e);
fail("Did not expect RepositoryException when adding properties: " + e.getMessage());
}
} finally {
@@ -627,49 +773,82 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
try {
// create a couple of test users
- user2 = createUser.createUser(adminSession, createUniqueName("user"), "testPwd", "testPwd",
- Collections.singletonMap("prop1", "value1"), new ArrayList<>());
+ user2 = createUser.createUser(
+ adminSession,
+ createUniqueName("user"),
+ "testPwd",
+ "testPwd",
+ Collections.singletonMap("prop1", "value1"),
+ new ArrayList<>());
assertNotNull("Expected user2 to not be null", user2);
- group1 = createGroup.createGroup(adminSession, createUniqueName("group"),
- Collections.singletonMap("prop1", "value1"), new ArrayList<>());
+ group1 = createGroup.createGroup(
+ adminSession,
+ createUniqueName("group"),
+ Collections.singletonMap("prop1", "value1"),
+ new ArrayList<>());
assertNotNull("Expected group1 to not be null", group1);
- String [] principalIds = new String[] { user2.getID(), group1.getID() };
+ String[] principalIds = new String[] {user2.getID(), group1.getID()};
// initially user can't do the operation
for (String pid : principalIds) {
- assertFalse("Should not be allowed to update properties for: " + pid,
+ assertFalse(
+ "Should not be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid));
}
// start with only read rights
Set<String> grantedPrivilegeNames = Set.of(
- Privilege.JCR_READ,
- // + grant rights to alter (non-nested or nested) properties and remove properties
- PrivilegeConstants.REP_ADD_PROPERTIES,
- PrivilegeConstants.REP_ALTER_PROPERTIES,
- Privilege.JCR_ADD_CHILD_NODES,
- PrivilegeConstants.REP_REMOVE_PROPERTIES
- );
+ Privilege.JCR_READ,
+ // + grant rights to alter (non-nested or nested) properties and remove properties
+ PrivilegeConstants.REP_ADD_PROPERTIES,
+ PrivilegeConstants.REP_ALTER_PROPERTIES,
+ Privilege.JCR_ADD_CHILD_NODES,
+ PrivilegeConstants.REP_REMOVE_PROPERTIES);
AceTools.modifyAce(adminSession, user2.getPath(), user1, grantedPrivilegeNames, null);
AceTools.modifyAce(adminSession, group1.getPath(), user1, grantedPrivilegeNames, null);
for (String pid : principalIds) {
- assertTrue("Should be allowed to update properties for: " + pid,
+ assertTrue(
+ "Should be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid));
- assertTrue("Should be allowed to update properties for: " + pid,
- privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_PROPERTY, PropertyUpdateTypes.ADD_NESTED_PROPERTY, PropertyUpdateTypes.REMOVE_PROPERTY));
- assertTrue("Should be allowed to update properties for: " + pid,
- privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_PROPERTY, PropertyUpdateTypes.ADD_NESTED_PROPERTY));
- assertTrue("Should be allowed to update properties for: " + pid,
- privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_PROPERTY, PropertyUpdateTypes.REMOVE_PROPERTY));
- assertTrue("Should be allowed to update properties for: " + pid,
+ assertTrue(
+ "Should be allowed to update properties for: " + pid,
+ privilegesInfo.canUpdateProperties(
+ user1Session,
+ pid,
+ PropertyUpdateTypes.ADD_PROPERTY,
+ PropertyUpdateTypes.ADD_NESTED_PROPERTY,
+ PropertyUpdateTypes.REMOVE_PROPERTY));
+ assertTrue(
+ "Should be allowed to update properties for: " + pid,
+ privilegesInfo.canUpdateProperties(
+ user1Session,
+ pid,
+ PropertyUpdateTypes.ADD_PROPERTY,
+ PropertyUpdateTypes.ADD_NESTED_PROPERTY));
+ assertTrue(
+ "Should be allowed to update properties for: " + pid,
+ privilegesInfo.canUpdateProperties(
+ user1Session,
+ pid,
+ PropertyUpdateTypes.ADD_PROPERTY,
+ PropertyUpdateTypes.REMOVE_PROPERTY));
+ assertTrue(
+ "Should be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_PROPERTY));
- assertTrue("Should be allowed to update properties for: " + pid,
- privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_NESTED_PROPERTY, PropertyUpdateTypes.REMOVE_PROPERTY));
- assertTrue("Should be allowed to update properties for: " + pid,
+ assertTrue(
+ "Should be allowed to update properties for: " + pid,
+ privilegesInfo.canUpdateProperties(
+ user1Session,
+ pid,
+ PropertyUpdateTypes.ADD_NESTED_PROPERTY,
+ PropertyUpdateTypes.REMOVE_PROPERTY));
+ assertTrue(
+ "Should be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.ADD_NESTED_PROPERTY));
- assertTrue("Should be allowed to update properties for: " + pid,
+ assertTrue(
+ "Should be allowed to update properties for: " + pid,
privilegesInfo.canUpdateProperties(user1Session, pid, PropertyUpdateTypes.REMOVE_PROPERTY));
}
@@ -685,7 +864,11 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
assertTrue("Expected pending changes in the jcr session", user1Session.hasPendingChanges());
user1Session.save();
} catch (RepositoryException e) {
- logger.error(String.format("Did not expect RepositoryException when adding or deleting properties: %s", e.getMessage()), e);
+ logger.error(
+ String.format(
+ "Did not expect RepositoryException when adding or deleting properties: %s",
+ e.getMessage()),
+ e);
fail("Did not expect RepositoryException when adding or deleting properties: " + e.getMessage());
}
} finally {
@@ -711,48 +894,56 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
User user2 = null;
Group group1 = null;
try {
- user2 = createUser.createUser(adminSession, createUniqueName("user"), "testPwd", "testPwd",
- Collections.singletonMap("prop1", "value1"), new ArrayList<>());
+ user2 = createUser.createUser(
+ adminSession,
+ createUniqueName("user"),
+ "testPwd",
+ "testPwd",
+ Collections.singletonMap("prop1", "value1"),
+ new ArrayList<>());
assertNotNull("Expected user2 to not be null", user2);
- group1 = createGroup.createGroup(adminSession, createUniqueName("group"),
- Collections.singletonMap("prop1", "value1"), new ArrayList<>());
+ group1 = createGroup.createGroup(
+ adminSession,
+ createUniqueName("group"),
+ Collections.singletonMap("prop1", "value1"),
+ new ArrayList<>());
assertNotNull("Expected group1 to not be null", group1);
// initially user can't do the operations
- assertFalse("Should not be allowed to remove user",
- privilegesInfo.canRemove(user1Session, user2.getID()));
- assertFalse("Should not be allowed to remove group",
- privilegesInfo.canRemove(user1Session, group1.getID()));
+ assertFalse("Should not be allowed to remove user", privilegesInfo.canRemove(user1Session, user2.getID()));
+ assertFalse(
+ "Should not be allowed to remove group", privilegesInfo.canRemove(user1Session, group1.getID()));
// grant user1 rights to user2 profile
AceTools.modifyAce(adminSession, user2.getPath(), user1, Set.of(Privilege.JCR_READ), null);
AceTools.modifyAce(adminSession, group1.getPath(), user1, Set.of(Privilege.JCR_READ), null);
- assertFalse("Should not be allowed to remove user",
- privilegesInfo.canRemove(user1Session, user2.getID()));
- assertFalse("Should not be allowed to remove group",
- privilegesInfo.canRemove(user1Session, group1.getID()));
-
- AceTools.modifyAce(adminSession, user2.getPath(), user1, Set.of(
- Privilege.JCR_READ,
- PrivilegeConstants.REP_USER_MANAGEMENT
- ), null);
- AceTools.modifyAce(adminSession, group1.getPath(), user1, Set.of(
- Privilege.JCR_READ,
- PrivilegeConstants.REP_USER_MANAGEMENT
- ), null);
+ assertFalse("Should not be allowed to remove user", privilegesInfo.canRemove(user1Session, user2.getID()));
+ assertFalse(
+ "Should not be allowed to remove group", privilegesInfo.canRemove(user1Session, group1.getID()));
+
+ AceTools.modifyAce(
+ adminSession,
+ user2.getPath(),
+ user1,
+ Set.of(Privilege.JCR_READ, PrivilegeConstants.REP_USER_MANAGEMENT),
+ null);
+ AceTools.modifyAce(
+ adminSession,
+ group1.getPath(),
+ user1,
+ Set.of(Privilege.JCR_READ, PrivilegeConstants.REP_USER_MANAGEMENT),
+ null);
AceTools.modifyAce(adminSession, group1.getPath(), user1, Set.of(Privilege.JCR_READ), null);
- assertTrue("Should be allowed to remove user",
- privilegesInfo.canRemove(user1Session, user2.getID()));
- assertTrue("Should be allowed to remove group",
- privilegesInfo.canRemove(user1Session, group1.getID()));
+ assertTrue("Should be allowed to remove user", privilegesInfo.canRemove(user1Session, user2.getID()));
+ assertTrue("Should be allowed to remove group", privilegesInfo.canRemove(user1Session, group1.getID()));
// verify that the user can actually delete the user
String user2Id = user2.getID();
deleteUser.deleteUser(user1Session, user2Id, new ArrayList<>());
user2 = null;
// verify the user is no longer there
- UserManager um = ((JackrabbitSession)user1Session).getUserManager();
+ UserManager um = ((JackrabbitSession) user1Session).getUserManager();
assertNull("Expected user to be gone: " + user2Id, um.getAuthorizable(user2Id));
// verify that the user can actually delete the group
@@ -782,24 +973,32 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
Group group1 = null;
try {
- group1 = createGroup.createGroup(adminSession, createUniqueName("group"),
- Collections.singletonMap("prop1", "value1"), new ArrayList<>());
+ group1 = createGroup.createGroup(
+ adminSession,
+ createUniqueName("group"),
+ Collections.singletonMap("prop1", "value1"),
+ new ArrayList<>());
assertNotNull("Expected group1 to not be null", group1);
// initially user can't do the operations
- assertFalse("Should not be allowed to update group members",
+ assertFalse(
+ "Should not be allowed to update group members",
privilegesInfo.canUpdateGroupMembers(user1Session, group1.getID()));
// grant user1 rights to group1 profile
AceTools.modifyAce(adminSession, group1.getPath(), user1, Set.of(Privilege.JCR_READ), null);
- assertFalse("Should not be allowed to update group members",
+ assertFalse(
+ "Should not be allowed to update group members",
privilegesInfo.canUpdateGroupMembers(user1Session, group1.getID()));
- AceTools.modifyAce(adminSession, group1.getPath(), user1, Set.of(
- Privilege.JCR_READ,
- PrivilegeConstants.REP_USER_MANAGEMENT
- ), null);
- assertTrue("Should be allowed to update group members",
+ AceTools.modifyAce(
+ adminSession,
+ group1.getPath(),
+ user1,
+ Set.of(Privilege.JCR_READ, PrivilegeConstants.REP_USER_MANAGEMENT),
+ null);
+ assertTrue(
+ "Should be allowed to update group members",
privilegesInfo.canUpdateGroupMembers(user1Session, group1.getID()));
// verify that the user can actually change the group members
@@ -810,7 +1009,10 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
assertTrue("Expected pending changes in the jcr session", user1Session.hasPendingChanges());
user1Session.save();
} catch (RepositoryException e) {
- logger.error(String.format("Did not expect RepositoryException when adding member to group: %s", e.getMessage()), e);
+ logger.error(
+ String.format(
+ "Did not expect RepositoryException when adding member to group: %s", e.getMessage()),
+ e);
fail("Did not expect RepositoryException when adding member to group: " + e.getMessage());
}
} finally {
@@ -821,13 +1023,15 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
}
protected void configMinimumUserPrivileges(User user) throws RepositoryException {
- //change the ACE for the user home folder to the minimum privileges
+ // change the ACE for the user home folder to the minimum privileges
// and without rep:userManagement
AceTools.deleteAces(adminSession, user.getPath(), user);
- AceTools.modifyAce(adminSession, user.getPath(), user, Set.of(
- Privilege.JCR_READ,
- PrivilegeConstants.REP_ALTER_PROPERTIES
- ), null);
+ AceTools.modifyAce(
+ adminSession,
+ user.getPath(),
+ user,
+ Set.of(Privilege.JCR_READ, PrivilegeConstants.REP_ALTER_PROPERTIES),
+ null);
}
/**
@@ -844,25 +1048,32 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
configMinimumUserPrivileges(user1);
// create another test user
- user2 = createUser.createUser(adminSession, createUniqueName("user"), "testPwd", "testPwd",
- Collections.singletonMap("prop1", "value1"), new ArrayList<>());
+ user2 = createUser.createUser(
+ adminSession,
+ createUniqueName("user"),
+ "testPwd",
+ "testPwd",
+ Collections.singletonMap("prop1", "value1"),
+ new ArrayList<>());
assertNotNull("Expected user2 to not be null", user2);
// setup the user privileges
configMinimumUserPrivileges(user2);
// initially user can't do the operations
- assertFalse("Should not be allowed to disable yourself",
+ assertFalse(
+ "Should not be allowed to disable yourself",
privilegesInfo.canDisable(user1Session, user1.getID()));
- assertFalse("Should not be allowed to disable user",
- privilegesInfo.canDisable(user1Session, user2.getID()));
+ assertFalse(
+ "Should not be allowed to disable user", privilegesInfo.canDisable(user1Session, user2.getID()));
// grant user1 rights to user2 profile
- AceTools.modifyAce(adminSession, user2.getPath(), user1, Set.of(
- Privilege.JCR_READ,
- PrivilegeConstants.REP_USER_MANAGEMENT
- ), null);
- assertTrue("Should be allowed to disable user",
- privilegesInfo.canDisable(user1Session, user2.getID()));
+ AceTools.modifyAce(
+ adminSession,
+ user2.getPath(),
+ user1,
+ Set.of(Privilege.JCR_READ, PrivilegeConstants.REP_USER_MANAGEMENT),
+ null);
+ assertTrue("Should be allowed to disable user", privilegesInfo.canDisable(user1Session, user2.getID()));
// verify that the user can actually disable the other user
Map<String, Object> propsMap = new HashMap<>();
@@ -873,7 +1084,9 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
assertTrue("Expected pending changes in the jcr session", user1Session.hasPendingChanges());
user1Session.save();
} catch (RepositoryException e) {
- logger.error(String.format("Did not expect RepositoryException when disabling the user: %s", e.getMessage()), e);
+ logger.error(
+ String.format("Did not expect RepositoryException when disabling the user: %s", e.getMessage()),
+ e);
fail("Did not expect RepositoryException when disabling the user: " + e.getMessage());
}
} finally {
@@ -894,29 +1107,43 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
User user2 = null;
try {
// create another test user
- user2 = createUser.createUser(adminSession, createUniqueName("user"), "testPwd", "testPwd",
- Collections.singletonMap("prop1", "value1"), new ArrayList<>());
+ user2 = createUser.createUser(
+ adminSession,
+ createUniqueName("user"),
+ "testPwd",
+ "testPwd",
+ Collections.singletonMap("prop1", "value1"),
+ new ArrayList<>());
assertNotNull("Expected user2 to not be null", user2);
// initially user can't do the operations
- assertFalse("Should not be allowed to change the user password",
+ assertFalse(
+ "Should not be allowed to change the user password",
privilegesInfo.canChangePassword(user1Session, user2.getID()));
// grant user1 rights to user2 profile
- AceTools.modifyAce(adminSession, user2.getPath(), user1, Set.of(
- Privilege.JCR_READ,
- PrivilegeConstants.REP_USER_MANAGEMENT
- ), null);
- assertTrue("Should be allowed to change the user password user",
+ AceTools.modifyAce(
+ adminSession,
+ user2.getPath(),
+ user1,
+ Set.of(Privilege.JCR_READ, PrivilegeConstants.REP_USER_MANAGEMENT),
+ null);
+ assertTrue(
+ "Should be allowed to change the user password user",
privilegesInfo.canChangePassword(user1Session, user2.getID()));
// verify that the user can actually change the password of the other user
try {
- changeUserPassword.changePassword(user1Session, user2.getID(), "testPwd", "newPassword", "newPassword", new ArrayList<>());
+ changeUserPassword.changePassword(
+ user1Session, user2.getID(), "testPwd", "newPassword", "newPassword", new ArrayList<>());
assertTrue("Expected pending changes in the jcr session", user1Session.hasPendingChanges());
user1Session.save();
} catch (RepositoryException e) {
- logger.error(String.format("Did not expect RepositoryException when changing the user password: %s", e.getMessage()), e);
+ logger.error(
+ String.format(
+ "Did not expect RepositoryException when changing the user password: %s",
+ e.getMessage()),
+ e);
fail("Did not expect RepositoryException when changing the user password: " + e.getMessage());
}
} finally {
@@ -933,7 +1160,8 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
public void canChangePasswordForSelf() throws RepositoryException {
assertNotNull("Expected privilegesInfo to not be null", privilegesInfo);
- assertTrue("Should be allowed to change the user password",
+ assertTrue(
+ "Should be allowed to change the user password",
privilegesInfo.canChangePassword(user1Session, user1.getID()));
}
@@ -946,19 +1174,22 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
AceTools.modifyAce(adminSession, user1.getPath(), user1, null, Set.of(PrivilegeConstants.REP_USER_MANAGEMENT));
// first try with the allowSelfChangePassword set to false
- org.osgi.service.cm.Configuration configuration = configAdmin.getConfiguration("org.apache.sling.jackrabbit.usermanager.impl.post.ChangeUserPasswordServlet", null);
+ org.osgi.service.cm.Configuration configuration = configAdmin.getConfiguration(
+ "org.apache.sling.jackrabbit.usermanager.impl.post.ChangeUserPasswordServlet", null);
Dictionary<String, Object> originalServiceProps = configuration.getProperties();
ServiceReference<ChangeUserPassword> serviceReference = null;
try {
// update the service configuration to ensure the option is disabled
- Dictionary<String, Object> newServiceProps = replaceConfigProp(originalServiceProps, "alwaysAllowSelfChangePassword", Boolean.FALSE);
+ Dictionary<String, Object> newServiceProps =
+ replaceConfigProp(originalServiceProps, "alwaysAllowSelfChangePassword", Boolean.FALSE);
configuration.update(newServiceProps);
- new WaitForServiceUpdated(5000, 100, bundleContext, ChangeUserPassword.class,
- "alwaysAllowSelfChangePassword", Boolean.FALSE);
+ new WaitForServiceUpdated(
+ 5000, 100, bundleContext, ChangeUserPassword.class, "alwaysAllowSelfChangePassword", Boolean.FALSE);
assertNotNull("Expected privilegesInfo to not be null", privilegesInfo);
- assertFalse("Should be not allowed to change the user password",
+ assertFalse(
+ "Should be not allowed to change the user password",
privilegesInfo.canChangePassword(user1Session, user1.getID()));
} finally {
if (serviceReference != null) {
@@ -966,26 +1197,34 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
bundleContext.ungetService(serviceReference);
}
- //put the original config back
+ // put the original config back
configuration.update(originalServiceProps);
- new WaitForServiceUpdated(5000, 100, bundleContext, ChangeUserPassword.class, "alwaysAllowSelfChangePassword",
- originalServiceProps == null ? null :originalServiceProps.get("alwaysAllowSelfChangePassword"));
+ new WaitForServiceUpdated(
+ 5000,
+ 100,
+ bundleContext,
+ ChangeUserPassword.class,
+ "alwaysAllowSelfChangePassword",
+ originalServiceProps == null ? null : originalServiceProps.get("alwaysAllowSelfChangePassword"));
}
// second try with the allowSelfChangePassword set to true
- configuration = configAdmin.getConfiguration("org.apache.sling.jackrabbit.usermanager.impl.post.ChangeUserPasswordServlet", null);
+ configuration = configAdmin.getConfiguration(
+ "org.apache.sling.jackrabbit.usermanager.impl.post.ChangeUserPasswordServlet", null);
originalServiceProps = configuration.getProperties();
serviceReference = null;
try {
// update the service configuration to ensure the option is disabled
- Dictionary<String, Object> newServiceProps = replaceConfigProp(originalServiceProps, "alwaysAllowSelfChangePassword", Boolean.TRUE);
+ Dictionary<String, Object> newServiceProps =
+ replaceConfigProp(originalServiceProps, "alwaysAllowSelfChangePassword", Boolean.TRUE);
configuration.update(newServiceProps);
- new WaitForServiceUpdated(5000, 100, bundleContext, ChangeUserPassword.class,
- "alwaysAllowSelfChangePassword", Boolean.TRUE);
+ new WaitForServiceUpdated(
+ 5000, 100, bundleContext, ChangeUserPassword.class, "alwaysAllowSelfChangePassword", Boolean.TRUE);
assertNotNull("Expected privilegesInfo to not be null", privilegesInfo);
- assertTrue("Should be allowed to change the user password",
+ assertTrue(
+ "Should be allowed to change the user password",
privilegesInfo.canChangePassword(user1Session, user1.getID()));
} finally {
if (serviceReference != null) {
@@ -993,10 +1232,15 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
bundleContext.ungetService(serviceReference);
}
- //put the original config back
+ // put the original config back
configuration.update(originalServiceProps);
- new WaitForServiceUpdated(5000, 100, bundleContext, ChangeUserPassword.class, "alwaysAllowSelfChangePassword",
- originalServiceProps == null ? null :originalServiceProps.get("alwaysAllowSelfChangePassword"));
+ new WaitForServiceUpdated(
+ 5000,
+ 100,
+ bundleContext,
+ ChangeUserPassword.class,
+ "alwaysAllowSelfChangePassword",
+ originalServiceProps == null ? null : originalServiceProps.get("alwaysAllowSelfChangePassword"));
}
}
@@ -1009,9 +1253,11 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
assertNotNull("Expected privilegesInfo to not be null", privilegesInfo);
// anonymous user has no password to change
- assertFalse("Should not be allowed to change the user password",
+ assertFalse(
+ "Should not be allowed to change the user password",
privilegesInfo.canChangePassword(user1Session, "anonymous"));
- assertFalse("Should not be allowed to change the user password",
+ assertFalse(
+ "Should not be allowed to change the user password",
privilegesInfo.canChangePassword(adminSession, "anonymous"));
}
@@ -1024,9 +1270,11 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
assertNotNull("Expected privilegesInfo to not be null", privilegesInfo);
// service user has no password to change
- assertFalse("Should not be allowed to change the user password",
+ assertFalse(
+ "Should not be allowed to change the user password",
privilegesInfo.canChangePassword(user1Session, "sling-jcr-usermanager"));
- assertFalse("Should not be allowed to change the user password",
+ assertFalse(
+ "Should not be allowed to change the user password",
privilegesInfo.canChangePassword(adminSession, "sling-jcr-usermanager"));
}
@@ -1037,22 +1285,26 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
public void canChangePasswordWithoutOldPasswordForSelf() throws RepositoryException {
assertFalse(privilegesInfo.canChangePasswordWithoutOldPassword(adminSession, "admin"));
}
+
@Test
public void canChangePasswordWithoutOldPasswordForAdminUser() throws RepositoryException {
assertTrue(privilegesInfo.canChangePasswordWithoutOldPassword(adminSession, user1.getID()));
}
+
@Test
public void canChangePasswordWithoutOldPasswordForAnonymousUser() throws RepositoryException {
assertFalse(privilegesInfo.canChangePasswordWithoutOldPassword(adminSession, "anonymous"));
}
+
@Test
public void canChangePasswordWithoutOldPasswordForServiceUser() throws RepositoryException {
- User systemuser1 = ((JackrabbitSession)adminSession).getUserManager().createSystemUser("systemuser1", null);
+ User systemuser1 = ((JackrabbitSession) adminSession).getUserManager().createSystemUser("systemuser1", null);
assertFalse(privilegesInfo.canChangePasswordWithoutOldPassword(adminSession, systemuser1.getID()));
}
+
@Test
public void canChangePasswordWithoutOldPasswordForUserAdminGroupMember() throws RepositoryException {
- User testuser2 = ((JackrabbitSession)adminSession).getUserManager().createUser("testuser2", "testPwd");
+ User testuser2 = ((JackrabbitSession) adminSession).getUserManager().createUser("testuser2", "testPwd");
Group userAdmin = createGroup.createGroup(adminSession, "UserAdmin", new HashMap<>(), new ArrayList<>());
// grant user1 rights to user2 profile
AceTools.modifyAce(adminSession, userAdmin.getPath(), user1, Set.of(Privilege.JCR_READ), null);
@@ -1066,5 +1318,4 @@ public class AuthorizablePrivilegesInfoIT extends UserManagerTestSupport {
user1Session.refresh(true);
assertTrue(privilegesInfo.canChangePasswordWithoutOldPassword(user1Session, testuser2.getID()));
}
-
}
diff --git a/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/Retry.java b/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/Retry.java
index 01d2b15..135a1b4 100644
--- a/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/Retry.java
+++ b/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/Retry.java
@@ -18,10 +18,10 @@
*/
package org.apache.sling.jcr.jackrabbit.usermanager.it;
-import static org.awaitility.Awaitility.await;
-
import java.util.concurrent.TimeUnit;
+import static org.awaitility.Awaitility.await;
+
/** Simple Retry loop for tests */
public abstract class Retry {
private long timeoutMsec;
diff --git a/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/UserManagerTestSupport.java b/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/UserManagerTestSupport.java
index 28c1196..285a712 100644
--- a/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/UserManagerTestSupport.java
+++ b/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/UserManagerTestSupport.java
@@ -18,26 +18,7 @@
*/
package org.apache.sling.jcr.jackrabbit.usermanager.it;
-import static org.apache.felix.hc.api.FormattingResultLog.msHumanReadable;
-import static org.apache.sling.testing.paxexam.SlingOptions.awaitility;
-import static org.apache.sling.testing.paxexam.SlingOptions.paxLoggingApi;
-import static org.apache.sling.testing.paxexam.SlingOptions.slingQuickstartOakTar;
-import static org.apache.sling.testing.paxexam.SlingOptions.versionResolver;
-import static org.apache.sling.testing.paxexam.SlingVersionResolver.SLING_GROUP_ID;
-import static org.awaitility.Awaitility.await;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-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.streamBundle;
-import static org.ops4j.pax.exam.CoreOptions.systemProperty;
-import static org.ops4j.pax.exam.CoreOptions.vmOption;
-import static org.ops4j.pax.exam.CoreOptions.when;
-import static org.ops4j.pax.exam.cm.ConfigurationAdminOptions.factoryConfiguration;
-import static org.ops4j.pax.tinybundles.TinyBundles.bndBuilder;
+import javax.inject.Inject;
import java.io.BufferedWriter;
import java.io.IOException;
@@ -51,8 +32,7 @@ import java.util.Hashtable;
import java.util.List;
import java.util.concurrent.TimeUnit;
-import javax.inject.Inject;
-
+import jakarta.json.JsonArray;
import org.apache.felix.hc.api.Result;
import org.apache.felix.hc.api.ResultLog;
import org.apache.felix.hc.api.execution.HealthCheckExecutionResult;
@@ -75,7 +55,26 @@ import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import jakarta.json.JsonArray;
+import static org.apache.felix.hc.api.FormattingResultLog.msHumanReadable;
+import static org.apache.sling.testing.paxexam.SlingOptions.awaitility;
+import static org.apache.sling.testing.paxexam.SlingOptions.paxLoggingApi;
+import static org.apache.sling.testing.paxexam.SlingOptions.slingQuickstartOakTar;
+import static org.apache.sling.testing.paxexam.SlingOptions.versionResolver;
+import static org.apache.sling.testing.paxexam.SlingVersionResolver.SLING_GROUP_ID;
+import static org.awaitility.Awaitility.await;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+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.streamBundle;
+import static org.ops4j.pax.exam.CoreOptions.systemProperty;
+import static org.ops4j.pax.exam.CoreOptions.vmOption;
+import static org.ops4j.pax.exam.CoreOptions.when;
+import static org.ops4j.pax.exam.cm.ConfigurationAdminOptions.factoryConfiguration;
+import static org.ops4j.pax.tinybundles.TinyBundles.bndBuilder;
/**
* Base class for UserManager related paxexam tests
@@ -105,9 +104,8 @@ public abstract class UserManagerTestSupport extends TestSupport {
*/
@Override
protected void finished(Description description) {
- logger.info("Finished test: {}", description.getMethodName());
+ logger.info("Finished test: {}", description.getMethodName());
}
-
};
/**
@@ -121,8 +119,13 @@ public abstract class UserManagerTestSupport extends TestSupport {
private Object expectedValue;
private Class<?> serviceClass;
- public WaitForServiceUpdated(long timeoutMsec, long nextIterationDelay, BundleContext bundleContext,
- Class<?> serviceClass, String expectedKey, Object expectedValue) {
+ public WaitForServiceUpdated(
+ long timeoutMsec,
+ long nextIterationDelay,
+ BundleContext bundleContext,
+ Class<?> serviceClass,
+ String expectedKey,
+ Object expectedValue) {
super(timeoutMsec, nextIterationDelay, false);
this.bundleContext = bundleContext;
this.serviceClass = serviceClass;
@@ -162,51 +165,55 @@ public abstract class UserManagerTestSupport extends TestSupport {
versionResolver.setVersionFromProject("org.apache.sling", "org.apache.sling.servlets.post");
return composite(
- super.baseConfiguration(),
- when(vmOption != null).useOptions(vmOption),
- optionalRemoteDebug(),
- quickstart(),
- paxLoggingApi(), // newer version to provide the 2.x version of slf4j
- systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"),
- // SLING-9809 - add server user for the o.a.s.jcr.jackrabbit.usermanager bundle
- factoryConfiguration("org.apache.sling.jcr.repoinit.RepositoryInitializer")
- .put("scripts", new String[] {
- """
+ super.baseConfiguration(),
+ when(vmOption != null).useOptions(vmOption),
+ optionalRemoteDebug(),
+ quickstart(),
+ paxLoggingApi(), // newer version to provide the 2.x version of slf4j
+ systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level")
+ .value("INFO"),
+ // SLING-9809 - add server user for the o.a.s.jcr.jackrabbit.usermanager bundle
+ factoryConfiguration("org.apache.sling.jcr.repoinit.RepositoryInitializer")
+ .put("scripts", new String[] {
+ """
create service user sling-jcr-usermanager with path system/sling
set ACL for sling-jcr-usermanager
allow jcr:read,jcr:readAccessControl,jcr:modifyAccessControl,rep:write,rep:userManagement on /home
end
"""
- })
- .asOption(),
- factoryConfiguration("org.apache.sling.serviceusermapping.impl.ServiceUserMapperImpl.amended")
- .put("user.mapping", new String[]{"org.apache.sling.jcr.jackrabbit.usermanager=sling-jcr-usermanager"})
- .asOption(),
-
- // Sling JCR UserManager
- testBundle("bundle.filename"),
- // SLING-12312 - begin extra bundles for sling api 3.x
- mavenBundle()
- .groupId("org.apache.felix")
- .artifactId("org.apache.felix.http.wrappers")
- .version("6.1.0"),
- mavenBundle()
- .groupId("org.apache.sling")
- .artifactId("org.apache.sling.commons.johnzon")
- .version("2.0.0"),
- // end extra bundles for sling api 3.x
- junitBundles(),
- awaitility()
- ).add(
- additionalOptions()
- ).remove(
- mavenBundle() .groupId(SLING_GROUP_ID).artifactId("org.apache.sling.jcr.jackrabbit.usermanager").version(versionResolver)
- ).getOptions();
+ })
+ .asOption(),
+ factoryConfiguration("org.apache.sling.serviceusermapping.impl.ServiceUserMapperImpl.amended")
+ .put("user.mapping", new String[] {
+ "org.apache.sling.jcr.jackrabbit.usermanager=sling-jcr-usermanager"
+ })
+ .asOption(),
+
+ // Sling JCR UserManager
+ testBundle("bundle.filename"),
+ // SLING-12312 - begin extra bundles for sling api 3.x
+ mavenBundle()
+ .groupId("org.apache.felix")
+ .artifactId("org.apache.felix.http.wrappers")
+ .version("6.1.0"),
+ mavenBundle()
+ .groupId("org.apache.sling")
+ .artifactId("org.apache.sling.commons.johnzon")
+ .version("2.0.0"),
+ // end extra bundles for sling api 3.x
+ junitBundles(),
+ awaitility())
+ .add(additionalOptions())
+ .remove(mavenBundle()
+ .groupId(SLING_GROUP_ID)
+ .artifactId("org.apache.sling.jcr.jackrabbit.usermanager")
+ .version(versionResolver))
+ .getOptions();
}
protected Option[] additionalOptions() {
- return new Option[]{};
+ return new Option[] {};
}
/**
@@ -221,13 +228,15 @@ public abstract class UserManagerTestSupport extends TestSupport {
}
return composite(option);
}
+
protected ModifiableCompositeOption quickstart() {
final int httpPort = findFreePort();
final String workingDirectory = workingDirectory();
return slingQuickstartOakTar(workingDirectory, httpPort);
}
- protected Dictionary<String, Object> replaceConfigProp(Dictionary<String, Object> originalProps, String newPropKey, Object newPropValue) {
+ protected Dictionary<String, Object> replaceConfigProp(
+ Dictionary<String, Object> originalProps, String newPropKey, Object newPropValue) {
Hashtable<String, Object> newProps = new Hashtable<>(); // NOSONAR
if (originalProps != null) {
Enumeration<String> keys = originalProps.keys();
@@ -300,16 +309,21 @@ public abstract class UserManagerTestSupport extends TestSupport {
* Produce a human readable report of the health check results that is suitable for
* debugging or writing to a log
*/
- protected String toHealthCheckResultInfo(final HealthCheckExecutionResult exResult, final boolean debug) throws IOException {
+ protected String toHealthCheckResultInfo(final HealthCheckExecutionResult exResult, final boolean debug)
+ throws IOException {
String value = null;
- try (StringWriter resultWriter = new StringWriter(); BufferedWriter writer = new BufferedWriter(resultWriter)) {
+ try (StringWriter resultWriter = new StringWriter();
+ BufferedWriter writer = new BufferedWriter(resultWriter)) {
final Result result = exResult.getHealthCheckResult();
- writer.append('"').append(exResult.getHealthCheckMetadata().getTitle()).append('"');
+ writer.append('"')
+ .append(exResult.getHealthCheckMetadata().getTitle())
+ .append('"');
writer.append(" result is: ").append(result.getStatus().toString());
writer.newLine();
- writer.append(" Finished: ").append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(exResult.getFinishedAt()) + " after "
- + msHumanReadable(exResult.getElapsedTimeInMs()));
+ writer.append(" Finished: ")
+ .append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(exResult.getFinishedAt()) + " after "
+ + msHumanReadable(exResult.getElapsedTimeInMs()));
for (final ResultLog.Entry e : result) {
if (!debug && e.isDebug()) {
@@ -364,7 +378,9 @@ public abstract class UserManagerTestSupport extends TestSupport {
final TinyBundle bundle = TinyBundles.bundle();
bundle.setHeader(Constants.BUNDLE_SYMBOLICNAME, BUNDLE_SYMBOLICNAME);
bundle.setHeader(SLING_BUNDLE_RESOURCES_HEADER, header);
- bundle.setHeader("Require-Capability", "osgi.extender;filter:=\"(&(osgi.extender=org.apache.sling.bundleresource)(version<=1.1.0)(!(version>=2.0.0)))\"");
+ bundle.setHeader(
+ "Require-Capability",
+ "osgi.extender;filter:=\"(&(osgi.extender=org.apache.sling.bundleresource)(version<=1.1.0)(!(version>=2.0.0)))\"");
for (final String entry : content) {
try {
@@ -373,18 +389,17 @@ public abstract class UserManagerTestSupport extends TestSupport {
fail(String.format("Failed to add content to the bundle: %s. Reason: %s", entry, e.getMessage()));
}
}
- return streamBundle(
- bundle.build(bndBuilder())
- ).start();
+ return streamBundle(bundle.build(bndBuilder())).start();
}
protected void assertContains(JsonArray json, String value) {
assertContains("Did not find the expected value in the array", json, value);
}
+
protected void assertContains(String message, JsonArray json, String value) {
assertNotNull(json);
boolean found = false;
- for (int i = 0; i < json.size(); i++) { // iterate through the JsonArray
+ for (int i = 0; i < json.size(); i++) { // iterate through the JsonArray
if (json.getString(i).equals(value)) {
found = true;
break;
@@ -392,5 +407,4 @@ public abstract class UserManagerTestSupport extends TestSupport {
}
assertTrue(message, found);
}
-
}
diff --git a/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/post/AnonymousSelfRegistrationIT.java b/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/post/AnonymousSelfRegistrationIT.java
index 416bfe0..49e6e98 100644
--- a/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/post/AnonymousSelfRegistrationIT.java
+++ b/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/post/AnonymousSelfRegistrationIT.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.jackrabbit.usermanager.it.post;
-import static org.ops4j.pax.exam.CoreOptions.composite;
-import static org.ops4j.pax.exam.cm.ConfigurationAdminOptions.newConfiguration;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
+import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.junit.Test;
@@ -32,7 +32,8 @@ import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerClass;
-import jakarta.servlet.http.HttpServletResponse;
+import static org.ops4j.pax.exam.CoreOptions.composite;
+import static org.ops4j.pax.exam.cm.ConfigurationAdminOptions.newConfiguration;
/**
* Tests for the 'createUser' Sling Post Operation
@@ -46,7 +47,8 @@ public class AnonymousSelfRegistrationIT extends UserManagerClientTestSupport {
// supply additional configuration that enables anonymous self registration
return composite(super.additionalOptions())
.add(newConfiguration("org.apache.sling.jackrabbit.usermanager.impl.post.CreateUserServlet")
- .put("self.registration.enabled", true).asOption())
+ .put("self.registration.enabled", true)
+ .asOption())
.getOptions();
}
@@ -59,8 +61,7 @@ public class AnonymousSelfRegistrationIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair(":name", userId));
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
- //user create without logging in as a privileged user should return ok
+ // user create without logging in as a privileged user should return ok
assertAuthenticatedPostStatus(null, postUrl, HttpServletResponse.SC_OK, postParams, null);
}
-
}
diff --git a/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/post/ChangeUserPasswordIT.java b/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/post/ChangeUserPasswordIT.java
index d82efa1..02b57c7 100644
--- a/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/post/ChangeUserPasswordIT.java
+++ b/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/post/ChangeUserPasswordIT.java
@@ -18,11 +18,12 @@
*/
package org.apache.sling.jcr.jackrabbit.usermanager.it.post;
-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 static org.junit.Assert.fail;
+import javax.inject.Inject;
+import javax.jcr.AccessDeniedException;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.SimpleCredentials;
+import javax.jcr.security.Privilege;
import java.io.IOException;
import java.util.ArrayList;
@@ -31,13 +32,6 @@ import java.util.Dictionary;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
-import javax.inject.Inject;
-import javax.jcr.AccessDeniedException;
-import javax.jcr.RepositoryException;
-import javax.jcr.Session;
-import javax.jcr.SimpleCredentials;
-import javax.jcr.security.Privilege;
-
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.User;
import org.apache.jackrabbit.oak.api.CommitFailedException;
@@ -66,6 +60,12 @@ import org.osgi.service.cm.ConfigurationAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+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 static org.junit.Assert.fail;
+
/**
* Basic test of ChangeUserPassword component
*/
@@ -110,17 +110,27 @@ public class ChangeUserPasswordIT extends UserManagerTestSupport {
adminSession = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
assertNotNull("Expected adminSession to not be null", adminSession);
- user1 = createUser.createUser(adminSession, createUniqueName("user"), "testPwd", "testPwd",
- Collections.emptyMap(), new ArrayList<>());
+ user1 = createUser.createUser(
+ adminSession,
+ createUniqueName("user"),
+ "testPwd",
+ "testPwd",
+ Collections.emptyMap(),
+ new ArrayList<>());
assertNotNull("Expected user1 to not be null", user1);
user1Session = repository.login(new SimpleCredentials(user1.getID(), "testPwd".toCharArray()));
assertNotNull("Expected user1Session to not be null", user1Session);
- //change the ACE for the user home folder to the minimum privileges
+ // change the ACE for the user home folder to the minimum privileges
// and without rep:userManagement
AceTools.deleteAces(adminSession, user1.getPath(), user1);
- AceTools.modifyAce(adminSession, user1.getPath(), user1, Set.of(Privilege.JCR_READ, PrivilegeConstants.REP_ALTER_PROPERTIES), null);
+ AceTools.modifyAce(
+ adminSession,
+ user1.getPath(),
+ user1,
+ Set.of(Privilege.JCR_READ, PrivilegeConstants.REP_ALTER_PROPERTIES),
+ null);
if (adminSession.hasPendingChanges()) {
adminSession.save();
}
@@ -153,15 +163,17 @@ public class ChangeUserPasswordIT extends UserManagerTestSupport {
*/
@Test
public void changePasswordAsSelfGranted() throws IOException, RepositoryException {
- org.osgi.service.cm.Configuration configuration = configAdmin.getConfiguration("org.apache.sling.jackrabbit.usermanager.impl.post.ChangeUserPasswordServlet", null);
+ org.osgi.service.cm.Configuration configuration = configAdmin.getConfiguration(
+ "org.apache.sling.jackrabbit.usermanager.impl.post.ChangeUserPasswordServlet", null);
Dictionary<String, Object> originalServiceProps = configuration.getProperties();
ServiceReference<ChangeUserPassword> serviceReference = null;
try {
// update the service configuration to ensure the option is enabled
- Dictionary<String, Object> newServiceProps = replaceConfigProp(originalServiceProps, "allowSelfChangePassword", Boolean.TRUE);
+ Dictionary<String, Object> newServiceProps =
+ replaceConfigProp(originalServiceProps, "allowSelfChangePassword", Boolean.TRUE);
configuration.update(newServiceProps);
- new WaitForServiceUpdated(5000, 100, bundleContext, ChangeUserPassword.class,
- "allowSelfChangePassword", Boolean.TRUE);
+ new WaitForServiceUpdated(
+ 5000, 100, bundleContext, ChangeUserPassword.class, "allowSelfChangePassword", Boolean.TRUE);
serviceReference = bundleContext.getServiceReference(ChangeUserPassword.class);
assertEquals(Boolean.TRUE, serviceReference.getProperty("allowSelfChangePassword"));
@@ -169,19 +181,20 @@ public class ChangeUserPasswordIT extends UserManagerTestSupport {
assertNotNull(changeUserPassword);
// user can do the operation
- assertTrue("Should be allowed to change the user password",
+ assertTrue(
+ "Should be allowed to change the user password",
privilegesInfo.canChangePassword(user1Session, user1.getID()));
- changeUserPassword.changePassword(user1Session,
- user1.getID(),
- "testPwd",
- "testPwdChanged",
- "testPwdChanged",
- new ArrayList<>());
+ changeUserPassword.changePassword(
+ user1Session, user1.getID(), "testPwd", "testPwdChanged", "testPwdChanged", new ArrayList<>());
try {
user1Session.save();
} catch (AccessDeniedException e) {
- logger.error(String.format("Did not expect AccessDeniedException when changing user passsword: %s", e.getMessage()), e);
+ logger.error(
+ String.format(
+ "Did not expect AccessDeniedException when changing user passsword: %s",
+ e.getMessage()),
+ e);
fail("Did not expect AccessDeniedException when changing user passsword: " + e.getMessage());
}
} finally {
@@ -190,10 +203,15 @@ public class ChangeUserPasswordIT extends UserManagerTestSupport {
bundleContext.ungetService(serviceReference);
}
- //put the original config back
+ // put the original config back
configuration.update(originalServiceProps);
- new WaitForServiceUpdated(5000, 100, bundleContext, ChangeUserPassword.class, "allowSelfChangePassword",
- originalServiceProps == null ? null :originalServiceProps.get("allowSelfChangePassword"));
+ new WaitForServiceUpdated(
+ 5000,
+ 100,
+ bundleContext,
+ ChangeUserPassword.class,
+ "allowSelfChangePassword",
+ originalServiceProps == null ? null : originalServiceProps.get("allowSelfChangePassword"));
}
}
@@ -202,15 +220,17 @@ public class ChangeUserPasswordIT extends UserManagerTestSupport {
*/
@Test
public void changePasswordAsSelfDenied() throws IOException, RepositoryException {
- org.osgi.service.cm.Configuration configuration = configAdmin.getConfiguration("org.apache.sling.jackrabbit.usermanager.impl.post.ChangeUserPasswordServlet", null);
+ org.osgi.service.cm.Configuration configuration = configAdmin.getConfiguration(
+ "org.apache.sling.jackrabbit.usermanager.impl.post.ChangeUserPasswordServlet", null);
Dictionary<String, Object> originalServiceProps = configuration.getProperties();
ServiceReference<ChangeUserPassword> serviceReference = null;
try {
// update the service configuration to ensure the option is disabled
- Dictionary<String, Object> newServiceProps = replaceConfigProp(originalServiceProps, "allowSelfChangePassword", Boolean.FALSE);
+ Dictionary<String, Object> newServiceProps =
+ replaceConfigProp(originalServiceProps, "allowSelfChangePassword", Boolean.FALSE);
configuration.update(newServiceProps);
- new WaitForServiceUpdated(5000, 100, bundleContext, ChangeUserPassword.class,
- "allowSelfChangePassword", Boolean.FALSE);
+ new WaitForServiceUpdated(
+ 5000, 100, bundleContext, ChangeUserPassword.class, "allowSelfChangePassword", Boolean.FALSE);
serviceReference = bundleContext.getServiceReference(ChangeUserPassword.class);
assertEquals(Boolean.FALSE, serviceReference.getProperty("allowSelfChangePassword"));
@@ -218,15 +238,12 @@ public class ChangeUserPasswordIT extends UserManagerTestSupport {
assertNotNull(changeUserPassword);
// user can't do the operation
- assertFalse("Should not be allowed to change the user password",
+ assertFalse(
+ "Should not be allowed to change the user password",
privilegesInfo.canChangePassword(user1Session, user1.getID()));
- changeUserPassword.changePassword(user1Session,
- user1.getID(),
- "testPwd",
- "testPwdChanged",
- "testPwdChanged",
- new ArrayList<>());
+ changeUserPassword.changePassword(
+ user1Session, user1.getID(), "testPwd", "testPwdChanged", "testPwdChanged", new ArrayList<>());
assertTrue(user1Session.hasPendingChanges());
try {
user1Session.save();
@@ -243,10 +260,15 @@ public class ChangeUserPasswordIT extends UserManagerTestSupport {
bundleContext.ungetService(serviceReference);
}
- //put the original config back
+ // put the original config back
configuration.update(originalServiceProps);
- new WaitForServiceUpdated(5000, 100, bundleContext, ChangeUserPassword.class, "allowSelfChangePassword",
- originalServiceProps == null ? null :originalServiceProps.get("allowSelfChangePassword"));
+ new WaitForServiceUpdated(
+ 5000,
+ 100,
+ bundleContext,
+ ChangeUserPassword.class,
+ "allowSelfChangePassword",
+ originalServiceProps == null ? null : originalServiceProps.get("allowSelfChangePassword"));
}
}
@@ -255,15 +277,17 @@ public class ChangeUserPasswordIT extends UserManagerTestSupport {
*/
@Test
public void changePasswordAsSelfWithoutOldPasswordFails() throws IOException, RepositoryException {
- org.osgi.service.cm.Configuration configuration = configAdmin.getConfiguration("org.apache.sling.jackrabbit.usermanager.impl.post.ChangeUserPasswordServlet", null);
+ org.osgi.service.cm.Configuration configuration = configAdmin.getConfiguration(
+ "org.apache.sling.jackrabbit.usermanager.impl.post.ChangeUserPasswordServlet", null);
Dictionary<String, Object> originalServiceProps = configuration.getProperties();
ServiceReference<ChangeUserPassword> serviceReference = null;
try {
// update the service configuration to ensure the option is enabled
- Dictionary<String, Object> newServiceProps = replaceConfigProp(originalServiceProps, "allowSelfChangePassword", Boolean.TRUE);
+ Dictionary<String, Object> newServiceProps =
+ replaceConfigProp(originalServiceProps, "allowSelfChangePassword", Boolean.TRUE);
configuration.update(newServiceProps);
- new WaitForServiceUpdated(5000, 100, bundleContext, ChangeUserPassword.class,
- "allowSelfChangePassword", Boolean.TRUE);
+ new WaitForServiceUpdated(
+ 5000, 100, bundleContext, ChangeUserPassword.class, "allowSelfChangePassword", Boolean.TRUE);
serviceReference = bundleContext.getServiceReference(ChangeUserPassword.class);
assertEquals(Boolean.TRUE, serviceReference.getProperty("allowSelfChangePassword"));
@@ -271,19 +295,15 @@ public class ChangeUserPasswordIT extends UserManagerTestSupport {
assertNotNull(changeUserPassword);
// user can do the operation
- assertTrue("Should be allowed to change the user password",
+ assertTrue(
+ "Should be allowed to change the user password",
privilegesInfo.canChangePassword(user1Session, user1.getID()));
// no oldPassword submitted
- @NotNull
- String user1Id = user1.getID();
+ @NotNull String user1Id = user1.getID();
try {
- changeUserPassword.changePassword(user1Session,
- user1Id,
- null,
- "testPwdChanged",
- "testPwdChanged",
- new ArrayList<>());
+ changeUserPassword.changePassword(
+ user1Session, user1Id, null, "testPwdChanged", "testPwdChanged", new ArrayList<>());
fail("Expected a RepositoryException when changing user passsword.");
} catch (RepositoryException e) {
assertEquals("Old Password was not submitted", e.getMessage());
@@ -292,12 +312,8 @@ public class ChangeUserPasswordIT extends UserManagerTestSupport {
// empty oldPassword submitted
try {
- changeUserPassword.changePassword(user1Session,
- user1Id,
- "",
- "testPwdChanged2",
- "testPwdChanged2",
- new ArrayList<>());
+ changeUserPassword.changePassword(
+ user1Session, user1Id, "", "testPwdChanged2", "testPwdChanged2", new ArrayList<>());
fail("Expected a RepositoryException when changing user passsword.");
} catch (RepositoryException e) {
assertEquals("Old Password was not submitted", e.getMessage());
@@ -310,10 +326,15 @@ public class ChangeUserPasswordIT extends UserManagerTestSupport {
bundleContext.ungetService(serviceReference);
}
- //put the original config back
+ // put the original config back
configuration.update(originalServiceProps);
- new WaitForServiceUpdated(5000, 100, bundleContext, ChangeUserPassword.class, "allowSelfChangePassword",
- originalServiceProps == null ? null :originalServiceProps.get("allowSelfChangePassword"));
+ new WaitForServiceUpdated(
+ 5000,
+ 100,
+ bundleContext,
+ ChangeUserPassword.class,
+ "allowSelfChangePassword",
+ originalServiceProps == null ? null : originalServiceProps.get("allowSelfChangePassword"));
}
}
@@ -327,35 +348,46 @@ public class ChangeUserPasswordIT extends UserManagerTestSupport {
ServiceReference<ChangeUserPassword> serviceReference = null;
try {
// create a second user to attempt the change password on
- user2 = createUser.createUser(adminSession, createUniqueName("user"), "testPwd", "testPwd",
- Collections.emptyMap(), new ArrayList<>());
+ user2 = createUser.createUser(
+ adminSession,
+ createUniqueName("user"),
+ "testPwd",
+ "testPwd",
+ Collections.emptyMap(),
+ new ArrayList<>());
if (adminSession.hasPendingChanges()) {
adminSession.save();
}
// figure out what the user admin group name has been configured as
serviceReference = bundleContext.getServiceReference(ChangeUserPassword.class);
- String userAdminGroupName = (String)serviceReference.getProperty("user.admin.group.name");
+ String userAdminGroupName = (String) serviceReference.getProperty("user.admin.group.name");
if (userAdminGroupName == null || userAdminGroupName.isEmpty()) {
userAdminGroupName = "UserAdmin"; // fallback to the default
}
// add user1 to the UserAdmin group
- Group userAdminGroup = createGroup.createGroup(adminSession, userAdminGroupName,
- Collections.singletonMap(":member", user1.getID()), new ArrayList<>());
+ Group userAdminGroup = createGroup.createGroup(
+ adminSession,
+ userAdminGroupName,
+ Collections.singletonMap(":member", user1.getID()),
+ new ArrayList<>());
if (adminSession.hasPendingChanges()) {
adminSession.save();
}
- //make sure the UserAdmin group has the expected privileges granted
- AceTools.modifyAce(adminSession, user2.getPath(), userAdminGroup, Set.of(
- Privilege.JCR_READ,
- Privilege.JCR_READ_ACCESS_CONTROL,
- Privilege.JCR_MODIFY_ACCESS_CONTROL,
- PrivilegeConstants.REP_WRITE,
- PrivilegeConstants.REP_USER_MANAGEMENT
- ), null);
-
+ // make sure the UserAdmin group has the expected privileges granted
+ AceTools.modifyAce(
+ adminSession,
+ user2.getPath(),
+ userAdminGroup,
+ Set.of(
+ Privilege.JCR_READ,
+ Privilege.JCR_READ_ACCESS_CONTROL,
+ Privilege.JCR_MODIFY_ACCESS_CONTROL,
+ PrivilegeConstants.REP_WRITE,
+ PrivilegeConstants.REP_USER_MANAGEMENT),
+ null);
// create a fresh session so changes from the adminSession are picked up
user1Session.logout();
@@ -366,42 +398,43 @@ public class ChangeUserPasswordIT extends UserManagerTestSupport {
assertNotNull(changeUserPassword);
// user can do the operation
- assertTrue("Should be allowed to change the user password",
+ assertTrue(
+ "Should be allowed to change the user password",
privilegesInfo.canChangePassword(user1Session, user2.getID()));
// no oldPassword submitted
try {
- changeUserPassword.changePassword(user1Session,
- user2.getID(),
- null,
- "testPwdChanged",
- "testPwdChanged",
- new ArrayList<>());
+ changeUserPassword.changePassword(
+ user1Session, user2.getID(), null, "testPwdChanged", "testPwdChanged", new ArrayList<>());
} catch (RepositoryException e) {
fail("Did not expect a RepositoryException when changing user passsword.");
}
try {
user1Session.save();
} catch (AccessDeniedException e) {
- logger.error(String.format("Did not expect AccessDeniedException when changing user passsword: %s", e.getMessage()), e);
+ logger.error(
+ String.format(
+ "Did not expect AccessDeniedException when changing user passsword: %s",
+ e.getMessage()),
+ e);
fail("Did not expect AccessDeniedException when changing user passsword: " + e.getMessage());
}
// empty oldPassword submitted
try {
- changeUserPassword.changePassword(user1Session,
- user2.getID(),
- "",
- "testPwdChanged2",
- "testPwdChanged2",
- new ArrayList<>());
+ changeUserPassword.changePassword(
+ user1Session, user2.getID(), "", "testPwdChanged2", "testPwdChanged2", new ArrayList<>());
} catch (RepositoryException e) {
fail("Did not expect a RepositoryException when changing user passsword.");
}
try {
user1Session.save();
} catch (AccessDeniedException e) {
- logger.error(String.format("Did not expect AccessDeniedException when changing user passsword: %s", e.getMessage()), e);
+ logger.error(
+ String.format(
+ "Did not expect AccessDeniedException when changing user passsword: %s",
+ e.getMessage()),
+ e);
fail("Did not expect AccessDeniedException when changing user passsword: " + e.getMessage());
}
@@ -418,40 +451,48 @@ public class ChangeUserPasswordIT extends UserManagerTestSupport {
}
/**
- * For code coverage, test that changing another user's password works while
+ * For code coverage, test that changing another user's password works while
* the allowSelfChangePassword config is true
*/
@Test
public void changePasswordAsSelfGrantedForOtherUserWithOldPassword() throws RepositoryException, IOException {
- org.osgi.service.cm.Configuration configuration = configAdmin.getConfiguration("org.apache.sling.jackrabbit.usermanager.impl.post.ChangeUserPasswordServlet", null);
+ org.osgi.service.cm.Configuration configuration = configAdmin.getConfiguration(
+ "org.apache.sling.jackrabbit.usermanager.impl.post.ChangeUserPasswordServlet", null);
Dictionary<String, Object> originalServiceProps = configuration.getProperties();
ServiceReference<ChangeUserPassword> serviceReference = null;
User user2 = null;
try {
// create a second user to attempt the change password on
- user2 = createUser.createUser(adminSession, createUniqueName("user"), "testPwd", "testPwd",
- Collections.emptyMap(), new ArrayList<>());
+ user2 = createUser.createUser(
+ adminSession,
+ createUniqueName("user"),
+ "testPwd",
+ "testPwd",
+ Collections.emptyMap(),
+ new ArrayList<>());
if (adminSession.hasPendingChanges()) {
adminSession.save();
}
// update the service configuration to ensure the option is enabled
- Dictionary<String, Object> newServiceProps = replaceConfigProp(originalServiceProps, "allowSelfChangePassword", Boolean.TRUE);
+ Dictionary<String, Object> newServiceProps =
+ replaceConfigProp(originalServiceProps, "allowSelfChangePassword", Boolean.TRUE);
configuration.update(newServiceProps);
- new WaitForServiceUpdated(5000, 100, bundleContext, ChangeUserPassword.class,
- "allowSelfChangePassword", Boolean.TRUE);
+ new WaitForServiceUpdated(
+ 5000, 100, bundleContext, ChangeUserPassword.class, "allowSelfChangePassword", Boolean.TRUE);
serviceReference = bundleContext.getServiceReference(ChangeUserPassword.class);
assertEquals(Boolean.TRUE, serviceReference.getProperty("allowSelfChangePassword"));
ChangeUserPassword changeUserPassword = bundleContext.getService(serviceReference);
assertNotNull(changeUserPassword);
- //make sure the user1 has the expected privileges granted
- AceTools.modifyAce(adminSession, user2.getPath(), user1, Set.of(
- Privilege.JCR_READ,
- PrivilegeConstants.REP_USER_MANAGEMENT
- ), null);
-
+ // make sure the user1 has the expected privileges granted
+ AceTools.modifyAce(
+ adminSession,
+ user2.getPath(),
+ user1,
+ Set.of(Privilege.JCR_READ, PrivilegeConstants.REP_USER_MANAGEMENT),
+ null);
// create a fresh session so changes from the adminSession are picked up
user1Session.logout();
@@ -459,24 +500,25 @@ public class ChangeUserPasswordIT extends UserManagerTestSupport {
assertNotNull("Expected user1Session to not be null", user1Session);
// user can do the operation
- assertTrue("Should be allowed to change the user password",
+ assertTrue(
+ "Should be allowed to change the user password",
privilegesInfo.canChangePassword(user1Session, user2.getID()));
// no oldPassword submitted
try {
- changeUserPassword.changePassword(user1Session,
- user2.getID(),
- "testPwd",
- "testPwdChanged",
- "testPwdChanged",
- new ArrayList<>());
+ changeUserPassword.changePassword(
+ user1Session, user2.getID(), "testPwd", "testPwdChanged", "testPwdChanged", new ArrayList<>());
} catch (RepositoryException e) {
fail("Did not expect a RepositoryException when changing user passsword.");
}
try {
user1Session.save();
} catch (AccessDeniedException e) {
- logger.error(String.format("Did not expect AccessDeniedException when changing user passsword: %s", e.getMessage()), e);
+ logger.error(
+ String.format(
+ "Did not expect AccessDeniedException when changing user passsword: %s",
+ e.getMessage()),
+ e);
fail("Did not expect AccessDeniedException when changing user passsword: " + e.getMessage());
}
} finally {
@@ -489,10 +531,15 @@ public class ChangeUserPasswordIT extends UserManagerTestSupport {
bundleContext.ungetService(serviceReference);
}
- //put the original config back
+ // put the original config back
configuration.update(originalServiceProps);
- new WaitForServiceUpdated(5000, 100, bundleContext, ChangeUserPassword.class, "allowSelfChangePassword",
- originalServiceProps == null ? null :originalServiceProps.get("allowSelfChangePassword"));
+ new WaitForServiceUpdated(
+ 5000,
+ 100,
+ bundleContext,
+ ChangeUserPassword.class,
+ "allowSelfChangePassword",
+ originalServiceProps == null ? null : originalServiceProps.get("allowSelfChangePassword"));
}
}
@@ -500,15 +547,17 @@ public class ChangeUserPasswordIT extends UserManagerTestSupport {
*/
@Test
public void changePasswordAsSelfGrantedWithObsoleteConfigurationKey() throws Exception {
- org.osgi.service.cm.Configuration configuration = configAdmin.getConfiguration("org.apache.sling.jackrabbit.usermanager.impl.post.ChangeUserPasswordServlet", null);
+ org.osgi.service.cm.Configuration configuration = configAdmin.getConfiguration(
+ "org.apache.sling.jackrabbit.usermanager.impl.post.ChangeUserPasswordServlet", null);
Dictionary<String, Object> originalServiceProps = configuration.getProperties();
ServiceReference<ChangeUserPassword> serviceReference = null;
try {
// update the service configuration to ensure the option is disabled
- Dictionary<String, Object> newServiceProps = replaceConfigProp(originalServiceProps, "alwaysAllowSelfChangePassword", Boolean.TRUE);
+ Dictionary<String, Object> newServiceProps =
+ replaceConfigProp(originalServiceProps, "alwaysAllowSelfChangePassword", Boolean.TRUE);
configuration.update(newServiceProps);
- new WaitForServiceUpdated(5000, 100, bundleContext, ChangeUserPassword.class,
- "alwaysAllowSelfChangePassword", Boolean.TRUE);
+ new WaitForServiceUpdated(
+ 5000, 100, bundleContext, ChangeUserPassword.class, "alwaysAllowSelfChangePassword", Boolean.TRUE);
serviceReference = bundleContext.getServiceReference(ChangeUserPassword.class);
assertEquals(Boolean.TRUE, serviceReference.getProperty("alwaysAllowSelfChangePassword"));
@@ -516,19 +565,20 @@ public class ChangeUserPasswordIT extends UserManagerTestSupport {
assertNotNull(changeUserPassword);
// user can do the operation
- assertTrue("Should be allowed to change the user password",
+ assertTrue(
+ "Should be allowed to change the user password",
privilegesInfo.canChangePassword(user1Session, user1.getID()));
- changeUserPassword.changePassword(user1Session,
- user1.getID(),
- "testPwd",
- "testPwdChanged",
- "testPwdChanged",
- new ArrayList<>());
+ changeUserPassword.changePassword(
+ user1Session, user1.getID(), "testPwd", "testPwdChanged", "testPwdChanged", new ArrayList<>());
try {
user1Session.save();
} catch (AccessDeniedException e) {
- logger.error(String.format("Did not expect AccessDeniedException when changing user passsword: %s", e.getMessage()), e);
+ logger.error(
+ String.format(
+ "Did not expect AccessDeniedException when changing user passsword: %s",
+ e.getMessage()),
+ e);
fail("Did not expect AccessDeniedException when changing user passsword: " + e.getMessage());
}
} finally {
@@ -537,11 +587,15 @@ public class ChangeUserPasswordIT extends UserManagerTestSupport {
bundleContext.ungetService(serviceReference);
}
- //put the original config back
+ // put the original config back
configuration.update(originalServiceProps);
- new WaitForServiceUpdated(5000, 100, bundleContext, ChangeUserPassword.class, "alwaysAllowSelfChangePassword",
- originalServiceProps == null ? null :originalServiceProps.get("alwaysAllowSelfChangePassword"));
+ new WaitForServiceUpdated(
+ 5000,
+ 100,
+ bundleContext,
+ ChangeUserPassword.class,
+ "alwaysAllowSelfChangePassword",
+ originalServiceProps == null ? null : originalServiceProps.get("alwaysAllowSelfChangePassword"));
}
}
-
}
diff --git a/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/post/CreateGroupIT.java b/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/post/CreateGroupIT.java
index 642f268..5791841 100644
--- a/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/post/CreateGroupIT.java
+++ b/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/post/CreateGroupIT.java
@@ -1,30 +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.jackrabbit.usermanager.it.post;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
+import jakarta.json.JsonException;
+import jakarta.json.JsonObject;
+import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
@@ -36,9 +36,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 jakarta.json.JsonException;
-import jakarta.json.JsonObject;
-import jakarta.servlet.http.HttpServletResponse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
/**
* Tests for the 'createGroup' Sling Post Operation
@@ -57,7 +58,7 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair("marker", testGroupId));
assertAuthenticatedAdminPostStatus(postUrl, HttpServletResponse.SC_OK, postParams, null);
- //fetch the group profile json to verify the settings
+ // fetch the group profile json to verify the settings
String getUrl = String.format("%s/system/userManager/group/%s.json", baseServerUri, testGroupId);
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
String json = getAuthenticatedContent(creds, getUrl, CONTENT_TYPE_JSON, HttpServletResponse.SC_OK);
@@ -95,7 +96,7 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair("marker", testGroupId));
assertAuthenticatedPostStatus(creds, postUrl, HttpServletResponse.SC_OK, postParams, null);
- //fetch the group profile json to verify the settings
+ // fetch the group profile json to verify the settings
String getUrl = String.format("%s/system/userManager/group/%s.json", baseServerUri, testGroupId);
String json = getAuthenticatedContent(creds, getUrl, CONTENT_TYPE_JSON, HttpServletResponse.SC_OK);
assertNotNull(json);
@@ -117,8 +118,9 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair("marker", testGroupId));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String content = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_HTML, postParams, HttpServletResponse.SC_OK);
- assertEquals("Thanks!", content); //verify that the content matches the custom response
+ String content =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_HTML, postParams, HttpServletResponse.SC_OK);
+ assertEquals("Thanks!", content); // verify that the content matches the custom response
}
@Test
@@ -138,7 +140,7 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair(":name", testGroupId));
assertAuthenticatedAdminPostStatus(postUrl, HttpServletResponse.SC_OK, postParams, null);
- //post the same info again, should fail
+ // post the same info again, should fail
assertAuthenticatedAdminPostStatus(postUrl, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, postParams, null);
}
@@ -154,7 +156,7 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair("url", "http://www.apache.org"));
assertAuthenticatedAdminPostStatus(postUrl, HttpServletResponse.SC_OK, postParams, null);
- //fetch the group profile json to verify the settings
+ // fetch the group profile json to verify the settings
String getUrl = String.format("%s/system/userManager/group/%s.json", baseServerUri, testGroupId);
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
String json = getAuthenticatedContent(creds, getUrl, CONTENT_TYPE_JSON, HttpServletResponse.SC_OK);
@@ -165,7 +167,6 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
assertEquals("http://www.apache.org", jsonObj.getString("url"));
}
-
/**
* Test for SLING-1677
*/
@@ -178,9 +179,10 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair(":name", testGroupId));
postParams.add(new BasicNameValuePair("marker", testGroupId));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
}
@@ -221,17 +223,19 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
List<NameValuePair> postParams = new ArrayList<>();
postParams.add(new BasicNameValuePair(":name", marker));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
+ testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testGroupId);
assertEquals(marker, testGroupId);
// second time with the same info fails since it is not unique
- getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ getAuthenticatedPostContent(
+ creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
@@ -246,19 +250,21 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair(":name@ValueFrom", "marker"));
postParams.add(new BasicNameValuePair("marker", marker));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
+ testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testGroupId);
assertEquals(marker, testGroupId);
// second time with the same info fails since it is not unique
- getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ getAuthenticatedPostContent(
+ creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
-
+
/**
* SLING-10902 Test for group name generated from a hint
*/
@@ -270,28 +276,28 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
List<NameValuePair> postParams = new ArrayList<>();
postParams.add(new BasicNameValuePair(":nameHint", hint));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
+ testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testGroupId);
assertEquals(hint.substring(0, 20), testGroupId);
// second time with the same info generates a different unique name
json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testGroupId2 = ResourceUtil.getName(jsonObj.getString("path"));
+ testGroupId2 = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testGroupId2);
assertTrue(testGroupId2.startsWith(hint.substring(0, 20)));
assertNotEquals(testGroupId, testGroupId2);
}
-
/**
* SLING-10902 Test for group name generated from the value of another param
*/
@@ -304,12 +310,13 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair(":name@ValueFrom", "marker"));
postParams.add(new BasicNameValuePair("marker", marker));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
+ testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testGroupId);
assertEquals(marker, testGroupId);
}
@@ -326,12 +333,13 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair(":nameHint", hint));
postParams.add(new BasicNameValuePair("marker", testUserId));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
+ testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testGroupId);
assertEquals(hint.substring(0, 20), testGroupId);
}
@@ -348,12 +356,13 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair(":nameHint@ValueFrom", "marker"));
postParams.add(new BasicNameValuePair("marker", marker));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
+ testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testGroupId);
assertEquals(marker.substring(0, 20), testGroupId);
}
@@ -369,7 +378,8 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
List<NameValuePair> postParams = new ArrayList<>();
postParams.add(new BasicNameValuePair("marker", marker));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ getAuthenticatedPostContent(
+ creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
@@ -384,7 +394,8 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair(":name", ""));
postParams.add(new BasicNameValuePair("marker", marker));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ getAuthenticatedPostContent(
+ creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
@@ -399,10 +410,10 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair(":nameHint", ""));
postParams.add(new BasicNameValuePair("marker", marker));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ getAuthenticatedPostContent(
+ creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
-
/**
* SLING-10902 Test for group name generated from a default property name
*/
@@ -414,12 +425,13 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
List<NameValuePair> postParams = new ArrayList<>();
postParams.add(new BasicNameValuePair("displayName", marker));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
+ testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testGroupId);
assertEquals(marker.substring(0, 20), testGroupId);
}
@@ -436,12 +448,13 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair(":name", ""));
postParams.add(new BasicNameValuePair("displayName", marker));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
+ testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testGroupId);
assertEquals(marker.substring(0, 20), testGroupId);
}
@@ -458,17 +471,17 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair(":nameHint", ""));
postParams.add(new BasicNameValuePair("displayName", marker));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
+ testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testGroupId);
assertEquals(marker.substring(0, 20), testGroupId);
}
-
/**
* SLING-11023 Test for setting jcr:mixinTypes values
*/
@@ -486,9 +499,10 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
assertAuthenticatedPostStatus(creds, postUrl, HttpServletResponse.SC_OK, postParams, null);
- //fetch the user profile json to verify the settings
+ // fetch the user profile json to verify the settings
String getUrl = String.format("%s/system/userManager/group/%s.json", baseServerUri, testGroupId);
- assertAuthenticatedHttpStatus(creds, getUrl, HttpServletResponse.SC_OK, null); //make sure the profile request returns some data
+ assertAuthenticatedHttpStatus(
+ creds, getUrl, HttpServletResponse.SC_OK, null); // make sure the profile request returns some data
String json = getAuthenticatedContent(creds, getUrl, CONTENT_TYPE_JSON, HttpServletResponse.SC_OK);
assertNotNull(json);
JsonObject jsonObj = parseJson(json);
@@ -531,9 +545,10 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
assertAuthenticatedPostStatus(creds, postUrl, HttpServletResponse.SC_OK, postParams, null);
- //fetch the user profile json to verify the settings
+ // fetch the user profile json to verify the settings
String getUrl = String.format("%s/system/userManager/group/%s.json", baseServerUri, testGroupId);
- assertAuthenticatedHttpStatus(creds, getUrl, HttpServletResponse.SC_OK, null); //make sure the profile request returns some data
+ assertAuthenticatedHttpStatus(
+ creds, getUrl, HttpServletResponse.SC_OK, null); // make sure the profile request returns some data
String json = getAuthenticatedContent(creds, getUrl, CONTENT_TYPE_JSON, HttpServletResponse.SC_OK);
assertNotNull(json);
JsonObject jsonObj = parseJson(json);
@@ -569,10 +584,10 @@ public class CreateGroupIT extends UserManagerClientTestSupport {
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
assertAuthenticatedPostStatus(creds, postUrl, HttpServletResponse.SC_FORBIDDEN, postParams, null);
- //fetch the user profile json to verify the settings
+ // fetch the user profile json to verify the settings
String getUrl = String.format("%s/system/userManager/group/%s.json", baseServerUri, testGroupId);
- assertAuthenticatedHttpStatus(creds, getUrl, HttpServletResponse.SC_NOT_FOUND, null); //make sure the profile request returns no data
+ assertAuthenticatedHttpStatus(
+ creds, getUrl, HttpServletResponse.SC_NOT_FOUND, null); // make sure the profile request returns no data
testGroupId = null;
}
-
}
diff --git a/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/post/CreatePrincipalWithCustomNameGeneratorIT.java b/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/post/CreatePrincipalWithCustomNameGeneratorIT.java
index 50ed0b8..50b1515 100644
--- a/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/post/CreatePrincipalWithCustomNameGeneratorIT.java
+++ b/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/post/CreatePrincipalWithCustomNameGeneratorIT.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.jackrabbit.usermanager.it.post;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
@@ -26,6 +25,9 @@ import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
+import jakarta.json.JsonException;
+import jakarta.json.JsonObject;
+import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
@@ -43,9 +45,8 @@ import org.osgi.framework.Constants;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceRegistration;
-import jakarta.json.JsonException;
-import jakarta.json.JsonObject;
-import jakarta.servlet.http.HttpServletResponse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
/**
* Tests for the 'createUser' and 'createGroup' Sling Post Operation
@@ -62,13 +63,13 @@ public class CreatePrincipalWithCustomNameGeneratorIT extends UserManagerClientT
Bundle bundle = FrameworkUtil.getBundle(getClass());
Dictionary<String, Object> props = new Hashtable<>(); // NOSONAR
props.put(Constants.SERVICE_RANKING, 1);
- principalNameGeneratorServiceReg = bundle.getBundleContext().registerService(PrincipalNameGenerator.class,
- new CustomPrincipalNameGeneratorImpl(), props);
+ principalNameGeneratorServiceReg = bundle.getBundleContext()
+ .registerService(PrincipalNameGenerator.class, new CustomPrincipalNameGeneratorImpl(), props);
Dictionary<String, Object> props2 = new Hashtable<>(); // NOSONAR
props2.put(Constants.SERVICE_RANKING, 1);
- principalNameFilterServiceReg = bundle.getBundleContext().registerService(PrincipalNameFilter.class,
- new CustomPrincipalNameFilterImpl(), props2);
+ principalNameFilterServiceReg = bundle.getBundleContext()
+ .registerService(PrincipalNameFilter.class, new CustomPrincipalNameFilterImpl(), props2);
super.before();
}
@@ -101,12 +102,13 @@ public class CreatePrincipalWithCustomNameGeneratorIT extends UserManagerClientT
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testUserId = ResourceUtil.getName(jsonObj.getString("path"));
+ testUserId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testUserId);
assertTrue(testUserId.startsWith("custom_user_"));
}
@@ -125,12 +127,13 @@ public class CreatePrincipalWithCustomNameGeneratorIT extends UserManagerClientT
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testUserId = ResourceUtil.getName(jsonObj.getString("path"));
+ testUserId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testUserId);
assertTrue(testUserId.startsWith("custom_user_"));
}
@@ -148,7 +151,8 @@ public class CreatePrincipalWithCustomNameGeneratorIT extends UserManagerClientT
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ getAuthenticatedPostContent(
+ creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
@@ -165,7 +169,8 @@ public class CreatePrincipalWithCustomNameGeneratorIT extends UserManagerClientT
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ getAuthenticatedPostContent(
+ creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
@@ -182,7 +187,8 @@ public class CreatePrincipalWithCustomNameGeneratorIT extends UserManagerClientT
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ getAuthenticatedPostContent(
+ creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
@@ -199,18 +205,17 @@ public class CreatePrincipalWithCustomNameGeneratorIT extends UserManagerClientT
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testUserId = ResourceUtil.getName(jsonObj.getString("path"));
+ testUserId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testUserId);
assertTrue(testUserId.startsWith("custom_user_"));
}
-
-
/**
* Test for group name generated from a hint
*/
@@ -223,12 +228,13 @@ public class CreatePrincipalWithCustomNameGeneratorIT extends UserManagerClientT
postParams.add(new BasicNameValuePair(":nameHint", hint));
postParams.add(new BasicNameValuePair("marker", testUserId));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
+ testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testGroupId);
assertTrue(testGroupId.startsWith("custom_group_"));
}
@@ -245,12 +251,13 @@ public class CreatePrincipalWithCustomNameGeneratorIT extends UserManagerClientT
postParams.add(new BasicNameValuePair(":nameHint@ValueFrom", "marker"));
postParams.add(new BasicNameValuePair("marker", marker));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
+ testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testGroupId);
assertTrue(testGroupId.startsWith("custom_group_"));
}
@@ -266,7 +273,8 @@ public class CreatePrincipalWithCustomNameGeneratorIT extends UserManagerClientT
List<NameValuePair> postParams = new ArrayList<>();
postParams.add(new BasicNameValuePair("marker", marker));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ getAuthenticatedPostContent(
+ creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
@@ -281,7 +289,8 @@ public class CreatePrincipalWithCustomNameGeneratorIT extends UserManagerClientT
postParams.add(new BasicNameValuePair(":name", ""));
postParams.add(new BasicNameValuePair("marker", marker));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ getAuthenticatedPostContent(
+ creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
@@ -296,7 +305,8 @@ public class CreatePrincipalWithCustomNameGeneratorIT extends UserManagerClientT
postParams.add(new BasicNameValuePair(":nameHint", ""));
postParams.add(new BasicNameValuePair("marker", marker));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ getAuthenticatedPostContent(
+ creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
@@ -311,14 +321,14 @@ public class CreatePrincipalWithCustomNameGeneratorIT extends UserManagerClientT
postParams.add(new BasicNameValuePair("marker", marker));
postParams.add(new BasicNameValuePair("displayName", marker));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
+ testGroupId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testGroupId);
assertTrue(testGroupId.startsWith("custom_group_"));
}
-
}
diff --git a/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/post/CreateUserIT.java b/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/post/CreateUserIT.java
index c666602..74f9109 100644
--- a/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/post/CreateUserIT.java
+++ b/src/test/java/org/apache/sling/jcr/jackrabbit/usermanager/it/post/CreateUserIT.java
@@ -1,31 +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.jackrabbit.usermanager.it.post;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
+import jakarta.json.JsonException;
+import jakarta.json.JsonObject;
+import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
@@ -37,9 +36,11 @@ import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerClass;
-import jakarta.json.JsonException;
-import jakarta.json.JsonObject;
-import jakarta.servlet.http.HttpServletResponse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
/**
* Tests for the 'createUser' Sling Post Operation
@@ -49,13 +50,13 @@ import jakarta.servlet.http.HttpServletResponse;
public class CreateUserIT extends UserManagerClientTestSupport {
/*
- <form action="/system/userManager/user.create.html" method="POST">
- <div>Name: <input type="text" name=":name" value="testUser" /></div>
- <div>Password: <input type="text" name="pwd" value="testUser" /></div>
- <div>Password Confirm: <input type="text" name="pwdConfirm" value="testUser" /></div>
- <input type="submit" value="Submit" />
- </form>
- */
+ <form action="/system/userManager/user.create.html" method="POST">
+ <div>Name: <input type="text" name=":name" value="testUser" /></div>
+ <div>Password: <input type="text" name="pwd" value="testUser" /></div>
+ <div>Password Confirm: <input type="text" name="pwdConfirm" value="testUser" /></div>
+ <input type="submit" value="Submit" />
+ </form>
+ */
@Test
public void testCreateUser() throws IOException, JsonException {
testUserId = "testUser" + getNextInt();
@@ -81,7 +82,8 @@ public class CreateUserIT extends UserManagerClientTestSupport {
// fetch the session info to verify that the user can log in
final Credentials newUserCreds = new UsernamePasswordCredentials(testUserId, "testPwd");
final String getUrl2 = String.format("%s/system/sling/info.sessionInfo.json", baseServerUri);
- final String json2 = getAuthenticatedContent(newUserCreds, getUrl2, CONTENT_TYPE_JSON, HttpServletResponse.SC_OK);
+ final String json2 =
+ getAuthenticatedContent(newUserCreds, getUrl2, CONTENT_TYPE_JSON, HttpServletResponse.SC_OK);
assertNotNull(json2);
final JsonObject jsonObj2 = parseJson(json2);
assertEquals(testUserId, jsonObj2.getString("userID"));
@@ -130,7 +132,8 @@ public class CreateUserIT extends UserManagerClientTestSupport {
// fetch the session info to verify that the user can log in
final Credentials newUserCreds = new UsernamePasswordCredentials(testUserId, "testPwd");
final String getUrl2 = String.format("%s/system/sling/info.sessionInfo.json", baseServerUri);
- final String json2 = getAuthenticatedContent(newUserCreds, getUrl2, CONTENT_TYPE_JSON, HttpServletResponse.SC_OK);
+ final String json2 =
+ getAuthenticatedContent(newUserCreds, getUrl2, CONTENT_TYPE_JSON, HttpServletResponse.SC_OK);
assertNotNull(json2);
final JsonObject jsonObj2 = parseJson(json2);
assertEquals(testUserId, jsonObj2.getString("userID"));
@@ -181,7 +184,7 @@ public class CreateUserIT extends UserManagerClientTestSupport {
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
assertAuthenticatedPostStatus(creds, postUrl, HttpServletResponse.SC_OK, postParams, null);
- //post the same info again, should fail
+ // post the same info again, should fail
assertAuthenticatedPostStatus(creds, postUrl, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, postParams, null);
}
@@ -210,7 +213,7 @@ public class CreateUserIT extends UserManagerClientTestSupport {
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
assertAuthenticatedPostStatus(creds, postUrl, HttpServletResponse.SC_OK, postParams, null);
- //fetch the user profile json to verify the settings
+ // fetch the user profile json to verify the settings
String getUrl = String.format("%s/system/userManager/user/%s.json", baseServerUri, testUserId);
String json = getAuthenticatedContent(creds, getUrl, CONTENT_TYPE_JSON, HttpServletResponse.SC_OK);
assertNotNull(json);
@@ -236,11 +239,10 @@ public class CreateUserIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair(":name", userId));
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
- //user create without logging in as a privileged user should return a 500 error
+ // user create without logging in as a privileged user should return a 500 error
assertAuthenticatedPostStatus(null, postUrl, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, postParams, null);
}
-
/**
* Test for SLING-1677
*/
@@ -255,9 +257,10 @@ public class CreateUserIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
}
@@ -276,8 +279,9 @@ public class CreateUserIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String content = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_HTML, postParams, HttpServletResponse.SC_OK);
- assertEquals("Thanks!", content); //verify that the content matches the custom response
+ String content =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_HTML, postParams, HttpServletResponse.SC_OK);
+ assertEquals("Thanks!", content); // verify that the content matches the custom response
}
private void testCreateUserRedirect(String redirectTo, int expectedStatus) throws IOException {
@@ -319,17 +323,19 @@ public class CreateUserIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testUserId = ResourceUtil.getName(jsonObj.getString("path"));
+ testUserId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testUserId);
assertEquals(marker, testUserId);
// second time with the same info fails since it is not unique
- getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ getAuthenticatedPostContent(
+ creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
@@ -346,17 +352,19 @@ public class CreateUserIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testUserId = ResourceUtil.getName(jsonObj.getString("path"));
+ testUserId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testUserId);
assertEquals(marker, testUserId);
// second time with the same info fails since it is not unique
- getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ getAuthenticatedPostContent(
+ creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
@@ -372,28 +380,28 @@ public class CreateUserIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testUserId = ResourceUtil.getName(jsonObj.getString("path"));
+ testUserId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testUserId);
assertEquals(hint.substring(0, 20), testUserId);
// second time with the same info generates a different unique name
json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testUserId2 = ResourceUtil.getName(jsonObj.getString("path"));
+ testUserId2 = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testUserId2);
assertTrue(testUserId2.startsWith(hint.substring(0, 20)));
assertNotEquals(testUserId, testUserId2);
}
-
/**
* SLING-10902 Test for user name generated from the value of another param
*/
@@ -408,12 +416,13 @@ public class CreateUserIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testUserId = ResourceUtil.getName(jsonObj.getString("path"));
+ testUserId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testUserId);
assertEquals(marker, testUserId);
}
@@ -431,12 +440,13 @@ public class CreateUserIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testUserId = ResourceUtil.getName(jsonObj.getString("path"));
+ testUserId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testUserId);
assertEquals(hint.substring(0, 20), testUserId);
}
@@ -455,12 +465,13 @@ public class CreateUserIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testUserId = ResourceUtil.getName(jsonObj.getString("path"));
+ testUserId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testUserId);
assertEquals(marker.substring(0, 20), testUserId);
}
@@ -477,7 +488,8 @@ public class CreateUserIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ getAuthenticatedPostContent(
+ creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
@@ -493,7 +505,8 @@ public class CreateUserIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ getAuthenticatedPostContent(
+ creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
@@ -509,7 +522,8 @@ public class CreateUserIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ getAuthenticatedPostContent(
+ creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
@@ -526,12 +540,13 @@ public class CreateUserIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testUserId = ResourceUtil.getName(jsonObj.getString("path"));
+ testUserId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testUserId);
assertEquals(marker.substring(0, 20), testUserId);
}
@@ -551,12 +566,13 @@ public class CreateUserIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testUserId = ResourceUtil.getName(jsonObj.getString("path"));
+ testUserId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testUserId);
assertEquals(marker.substring(0, 20), testUserId);
}
@@ -576,12 +592,13 @@ public class CreateUserIT extends UserManagerClientTestSupport {
postParams.add(new BasicNameValuePair("pwd", "testPwd"));
postParams.add(new BasicNameValuePair("pwdConfirm", "testPwd"));
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
- String json = getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
+ String json =
+ getAuthenticatedPostContent(creds, postUrl, CONTENT_TYPE_JSON, postParams, HttpServletResponse.SC_OK);
- //make sure the json response can be parsed as a JSON object
+ // make sure the json response can be parsed as a JSON object
JsonObject jsonObj = parseJson(json);
assertNotNull(jsonObj);
- testUserId = ResourceUtil.getName(jsonObj.getString("path"));
+ testUserId = ResourceUtil.getName(jsonObj.getString("path"));
assertNotNull(testUserId);
assertEquals(marker.substring(0, 20), testUserId);
}
@@ -604,9 +621,10 @@ public class CreateUserIT extends UserManagerClientTestSupport {
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
assertAuthenticatedPostStatus(creds, postUrl, HttpServletResponse.SC_OK, postParams, null);
- //fetch the user profile json to verify the settings
+ // fetch the user profile json to verify the settings
String getUrl = String.format("%s/system/userManager/user/%s.json", baseServerUri, testUserId);
- assertAuthenticatedHttpStatus(creds, getUrl, HttpServletResponse.SC_OK, null); //make sure the profile request returns some data
+ assertAuthenticatedHttpStatus(
+ creds, getUrl, HttpServletResponse.SC_OK, null); // make sure the profile request returns some data
String json = getAuthenticatedContent(creds, getUrl, CONTENT_TYPE_JSON, HttpServletResponse.SC_OK);
assertNotNull(json);
JsonObject jsonObj = parseJson(json);
@@ -650,9 +668,10 @@ public class CreateUserIT extends UserManagerClientTestSupport {
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
assertAuthenticatedPostStatus(creds, postUrl, HttpServletResponse.SC_OK, postParams, null);
- //fetch the user profile json to verify the settings
+ // fetch the user profile json to verify the settings
String getUrl = String.format("%s/system/userManager/user/%s.json", baseServerUri, testUserId);
- assertAuthenticatedHttpStatus(creds, getUrl, HttpServletResponse.SC_OK, null); //make sure the profile request returns some data
+ assertAuthenticatedHttpStatus(
+ creds, getUrl, HttpServletResponse.SC_OK, null); // make sure the profile request returns some data
String json = getAuthenticatedContent(creds, getUrl, CONTENT_TYPE_JSON, HttpServletResponse.SC_OK);
assertNotNull(json);
JsonObject jsonObj = parseJson(json);
@@ -689,10 +708,10 @@ public class CreateUserIT extends UserManagerClientTestSupport {
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
assertAuthenticatedPostStatus(creds, postUrl, HttpServletResponse.SC_FORBIDDEN, postParams, null);
- //fetch the user profile json to verify the settings
+ // fetch the user profile json to verify the settings
String getUrl = String.format("%s/system/userManager/user/%s.json", baseServerUri, testUserId);
- assertAuthenticatedHttpStatus(creds, getUrl, HttpServletResponse.SC_NOT_FOUND, null); //make sure the profile request returns no data
... 3999 lines suppressed ...