index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client
Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client/rest/ResourceTypesClient.java
/* * 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 * 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.directory.scim.client.rest; import java.util.List; import java.util.Optional; import jakarta.ws.rs.ProcessingException; import jakarta.ws.rs.client.Client; import jakarta.ws.rs.client.WebTarget; import jakarta.ws.rs.core.GenericType; import jakarta.ws.rs.core.Response; import org.apache.directory.scim.protocol.ResourceTypesResource; import org.apache.directory.scim.spec.schema.ResourceType; public class ResourceTypesClient implements AutoCloseable { private static final GenericType<List<ResourceType>> LIST_RESOURCE_TYPE = new GenericType<List<ResourceType>>(){}; private final Client client; private final WebTarget target; private final ResourceTypesResourceClient resourceTypesResourceClient = new ResourceTypesResourceClient(); public ResourceTypesClient(Client client, String baseUrl) { this.client = client.register(ScimJacksonXmlBindJsonProvider.class); this.target = this.client.target(baseUrl).path("ResourceTypes"); } public List<ResourceType> getAllResourceTypes(String filter) throws RestException { List<ResourceType> resourceTypes; Response response = this.resourceTypesResourceClient.getAllResourceTypes(filter); try { RestClientUtil.checkForSuccess(response); resourceTypes = response.readEntity(LIST_RESOURCE_TYPE); } finally { RestClientUtil.close(response); } return resourceTypes; } public Optional<ResourceType> getResourceType(String name) throws RestException, ProcessingException, IllegalStateException { Optional<ResourceType> resourceType; Response response = this.resourceTypesResourceClient.getResourceType(name); try { resourceType = RestClientUtil.readEntity(response, ResourceType.class); } finally { RestClientUtil.close(response); } return resourceType; } @Override public void close() throws Exception { this.client.close(); } private class ResourceTypesResourceClient implements ResourceTypesResource { @Override public Response getAllResourceTypes(String filter) throws RestException { Response response = ResourceTypesClient.this.target .queryParam("filter", filter) .request("application/scim+json") .get(); return response; } @Override public Response getResourceType(String name) throws RestException { Response response = ResourceTypesClient.this.target .path(name) .request("application/scim+json") .get(); return response; } } }
4,300
0
Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client
Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client/rest/ScimJacksonXmlBindJsonProvider.java
/* * 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 * 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.directory.scim.client.rest; import com.fasterxml.jackson.jakarta.rs.json.JacksonXmlBindJsonProvider; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.Produces; import jakarta.ws.rs.ext.Provider; import org.apache.directory.scim.core.json.ObjectMapperFactory; import org.apache.directory.scim.core.schema.SchemaRegistry; import org.apache.directory.scim.protocol.Constants; /** * Adds JacksonJaxbJsonProvider for custom MediaType {@code application/scim+json}. */ @Provider @Consumes(Constants.SCIM_CONTENT_TYPE) @Produces(Constants.SCIM_CONTENT_TYPE) @ApplicationScoped public class ScimJacksonXmlBindJsonProvider extends JacksonXmlBindJsonProvider { @Inject public ScimJacksonXmlBindJsonProvider(SchemaRegistry schemaRegistry) { super(ObjectMapperFactory.createObjectMapper(schemaRegistry), DEFAULT_ANNOTATIONS); } }
4,301
0
Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client
Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client/rest/RestClientUtil.java
/* * The Pennsylvania State University © 2016 * * Licensed 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 * * 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.directory.scim.client.rest; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Function; import jakarta.ws.rs.ProcessingException; import jakarta.ws.rs.client.WebTarget; import jakarta.ws.rs.core.GenericType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.Response.Status; import jakarta.ws.rs.core.Response.Status.Family; public final class RestClientUtil { private RestClientUtil() { } public static void checkForSuccess(Response response) throws RestException{ if (!isSuccessful(response)) { throw new RestException(response); } } public static boolean checkForFourOhFour(WebTarget target, Response response) { try { verifyNotFourOhFour(target, response); return false; } catch (RestException e) { return true; } } public static void verifyNotFourOhFour(WebTarget target, Response response) throws RestException { if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) { throw new RestException(response); } } public static boolean isSuccessful(Response response) { boolean isSuccessful; Family responseFamily = response.getStatusInfo() .getFamily(); isSuccessful = responseFamily != Family.CLIENT_ERROR && responseFamily != Family.SERVER_ERROR; return isSuccessful; } /** * Closes <code>response</code> and suppresses any known/expected exceptions * from closing it. * * @param response */ public static void close(Response response) { try { response.close(); } catch (ProcessingException ignored) { } } /** * Closes <code>response</code> and passes any known/expected exceptions from * closing it to <code>consumer</code> (e.g. for logging). * * @param response * @param consumer */ public static void close(Response response, Consumer<Throwable> consumer) { try { response.close(); } catch (ProcessingException processingException) { consumer.accept(processingException); } } /** * Read an entity from the response if it was found and returned. * * @param response * the {@link Response} to read from * @param entityType * the type of entity * @return <code>Optional.empty()</code> if <b>Not Found</b> or empty * response, otherwise <code>Optional.ofNullable(T)</code> * @throws RestException * if <code>response</code> is an error response other than * <code>404 Not Found</code> * @throws ProcessingException * see {@link Response#readEntity(Class)} * @throws IllegalStateException * see {@link Response#readEntity(Class)} * @throws RestException */ public <T> Optional<T> tryReadEntity(Response response, Class<T> entityType) throws RestException, ProcessingException, IllegalStateException{ return readEntity(response, entityType, response::readEntity, Optional::ofNullable); } /** * Read an entity from the response if it was found and returned. * * @param response * the {@link Response} to read from * @param entityType * the type of entity * @return <code>Optional.empty()</code> if <code>Not Found</code> or empty * response, otherwise <code>Optional.ofNullable(T)</code> * @throws RestException * if <code>response</code> is an error response other than * <code>404 Not Found</code> * @throws ProcessingException * see {@link Response#readEntity(GenericType)} * @throws IllegalStateException * see {@link Response#readEntity(GenericType)} * @throws RestException */ public <T> Optional<T> tryReadEntity(Response response, GenericType<T> entityType) throws RestException, ProcessingException, IllegalStateException { return readEntity(response, entityType, response::readEntity, Optional::ofNullable); } /** * <p> * Read an entity from the response if it was found. * </p> * <p> * Useful for REST endpoints that <b>MUST</b> return an entity. * </p> * * @param response * the {@link Response} to read from * @param entityType * the type of entity * @return <code>Optional.empty()</code> if <code>Not Found</code>, otherwise * <code>Optional.of(T)</code> * @throws RestException * if <code>response</code> is an error response other than * <code>404 Not Found</code> * @throws ProcessingException * see {@link Response#readEntity(Class)} * @throws IllegalStateException * see {@link Response#readEntity(Class)} * @throws RestException */ public static <T> Optional<T> readEntity(Response response, Class<T> entityType) throws RestException, ProcessingException, IllegalStateException{ return readEntity(response, entityType, response::readEntity, Optional::of); } /** * <p> * Read an entity from the response if it was found. * </p> * <p> * Useful for REST endpoints that <b>MUST</b> return an entity. * </p> * * @param response * the {@link Response} to read from * @param entityType * the type of entity * @return <code>Optional.empty()</code> if <code>Not Found</code>, otherwise * <code>Optional.of(T)</code> * @throws RestException * if <code>response</code> is an error response other than * <code>404 Not Found</code> * @throws ProcessingException * see {@link Response#readEntity(GenericType)} * @throws IllegalStateException * see {@link Response#readEntity(GenericType)} * @throws RestException */ public static <T> Optional<T> readEntity(Response response, GenericType<T> entityType) throws RestException, ProcessingException, IllegalStateException{ return readEntity(response, entityType, response::readEntity, Optional::of); } private static <T, E> Optional<E> readEntity(Response response, T entityType, Function<T, E> readEntity, Function<E, Optional<E>> optionalOf) throws RestException, ProcessingException, IllegalStateException{ Optional<E> result; if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) { result = Optional.empty(); } else { checkForSuccess(response); E responseEntity = readEntity.apply(entityType); result = optionalOf.apply(responseEntity); } return result; } public static Optional<String> extractIdFromLocationTag(Response response) { String location = response.getHeaderString("Location"); if (location == null) { return Optional.empty(); } String[] uriParts = location.split("/"); Integer nbrParts = uriParts.length; return Optional.of(uriParts[nbrParts - 1]); } }
4,302
0
Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client/rest
Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client/rest/legacy/Version1ScimGroupClient.java
/* * 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 * 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.directory.scim.client.rest.legacy; import jakarta.ws.rs.client.Client; import jakarta.ws.rs.core.MediaType; import org.apache.directory.scim.client.rest.ScimGroupClient; import org.apache.directory.scim.client.rest.RestCall; public class Version1ScimGroupClient extends ScimGroupClient { public Version1ScimGroupClient(Client client, String baseUrl) { super(client, baseUrl); } public Version1ScimGroupClient(Client client, String baseUrl, RestCall invoke) { super(client, baseUrl, invoke); } @Override protected String getContentType() { return MediaType.APPLICATION_JSON; } }
4,303
0
Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client/rest
Create_ds/directory-scimple/scim-client/src/main/java/org/apache/directory/scim/client/rest/legacy/Version1ScimUserClient.java
/* * 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 * 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.directory.scim.client.rest.legacy; import jakarta.ws.rs.client.Client; import jakarta.ws.rs.core.MediaType; import org.apache.directory.scim.client.rest.ScimUserClient; import org.apache.directory.scim.client.rest.RestCall; public class Version1ScimUserClient extends ScimUserClient { public Version1ScimUserClient(Client client, String baseUrl) { super(client, baseUrl); } public Version1ScimUserClient(Client client, String baseUrl, RestCall invoke) { super(client, baseUrl, invoke); } @Override protected String getContentType() { return MediaType.APPLICATION_JSON; } }
4,304
0
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core/repository/UpdateRequestTest.java
/* * 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 * 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.directory.scim.core.repository; import static org.apache.directory.scim.core.repository.UpdateRequestTest.PatchOperationCondition.op; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.directory.scim.core.repository.utility.ExampleObjectExtension; import org.apache.directory.scim.core.repository.utility.Subobject; import org.apache.directory.scim.spec.extension.EnterpriseExtension; import org.apache.directory.scim.spec.extension.EnterpriseExtension.Manager; import org.apache.directory.scim.spec.phonenumber.PhoneNumberParseException; import org.apache.directory.scim.spec.patch.PatchOperation; import org.apache.directory.scim.spec.patch.PatchOperation.Type; import org.apache.directory.scim.spec.patch.PatchOperationPath; import org.apache.directory.scim.spec.filter.FilterParseException; import org.apache.directory.scim.spec.resources.Address; import org.apache.directory.scim.spec.resources.Email; import org.apache.directory.scim.spec.resources.Name; import org.apache.directory.scim.spec.resources.PhoneNumber; import org.apache.directory.scim.spec.resources.PhoneNumber.GlobalPhoneNumberBuilder; import org.apache.directory.scim.spec.resources.Photo; import org.apache.directory.scim.spec.resources.ScimUser; import org.apache.directory.scim.core.schema.SchemaRegistry; import org.apache.directory.scim.spec.schema.Schemas; import org.assertj.core.api.AbstractAssert; import org.assertj.core.api.Condition; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import lombok.AllArgsConstructor; import lombok.Data; import lombok.extern.slf4j.Slf4j; import static org.assertj.core.groups.Tuple.tuple; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @Slf4j public class UpdateRequestTest { private static final String FIRST = "first"; private static final String SECOND = "second"; private static final String THIRD = "third"; private static final String FOURTH = "fourth"; private static final String A = "A"; private static final String B = "B"; private static final String C = "C"; private SchemaRegistry schemaRegistry; @BeforeEach public void initialize() throws Exception { schemaRegistry = mock(SchemaRegistry.class); when(schemaRegistry.getSchema(ScimUser.SCHEMA_URI)).thenReturn(Schemas.schemaFor(ScimUser.class)); when(schemaRegistry.getSchema(EnterpriseExtension.URN)).thenReturn(Schemas.schemaForExtension(EnterpriseExtension.class)); when(schemaRegistry.getSchema(ExampleObjectExtension.URN)).thenReturn(Schemas.schemaForExtension(ExampleObjectExtension.class)); } @Test public void testResourcePassthrough() throws Exception { UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", createUser(), createUser(), schemaRegistry); ScimUser result = updateRequest.getResource(); log.debug("testResourcePassthrough: {}", result); assertThat(result) .isNotNull(); } @Test public void testPatchPassthrough() throws Exception { UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", createUser(), createUser1PatchOps(), schemaRegistry); List<PatchOperation> result = updateRequest.getPatchOperations(); log.debug("testPatchPassthrough: {}", result); assertThat(result) .isNotNull(); } @Test public void testAddSingleAttribute() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); user2.setNickName("Jon"); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> result = updateRequest.getPatchOperations(); PatchOperation actual = assertSingleResult(result); checkAssertions(actual, Type.ADD, "nickName", "Jon"); } @Test public void testAddSingleExtension() throws Exception { ScimUser user1 = createUser(); EnterpriseExtension ext = user1.removeExtension(EnterpriseExtension.class); ScimUser user2 = createUser(); user2.addExtension(ext); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> result = updateRequest.getPatchOperations(); PatchOperation actual = assertSingleResult(result); checkAssertions(actual, Type.ADD, "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User", ext); } @Test public void testAddComplexAttribute() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); user2.getName() .setHonorificPrefix("Dr."); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> result = updateRequest.getPatchOperations(); PatchOperation actual = assertSingleResult(result); checkAssertions(actual, Type.ADD, "name.honorificPrefix", "Dr."); } @Test public void testAddMultiValuedAttribute() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); PhoneNumber mobilePhone = new GlobalPhoneNumberBuilder().globalNumber("+1(814)867-5306").build(); mobilePhone.setType("mobile"); mobilePhone.setPrimary(false); user2.getPhoneNumbers().add(mobilePhone); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> result = updateRequest.getPatchOperations(); PatchOperation actual = assertSingleResult(result); checkAssertions(actual, Type.ADD, "phoneNumbers", mobilePhone); } /** * This unit test is to replicate the issue where a replace is sent back * from the differencing engine for a collection that is currently empty * but is having an object added to it. This should produce an ADD with an * ArrayList of objects to add. */ @Test public void testAddObjectToEmptyCollection() throws Exception { ScimUser user1 = createUser(); user1.setPhoneNumbers(new ArrayList<>()); ScimUser user2 = createUser(); user2.setPhoneNumbers(new ArrayList<>()); PhoneNumber mobilePhone = new GlobalPhoneNumberBuilder().globalNumber("+1(814)867-5306").build(); mobilePhone.setType("mobile"); mobilePhone.setPrimary(true); user2.getPhoneNumbers().add(mobilePhone); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> operations = updateRequest.getPatchOperations(); assertNotNull(operations); assertThat(operations).hasSize(1); PatchOperation operation = operations.get(0); assertNotNull(operation.getValue()); assertEquals(Type.ADD, operation.getOperation()); assertEquals(PhoneNumber.class, operation.getValue().getClass()); } @Test public void testAddObjectsToEmptyCollection() throws Exception { ScimUser user1 = createUser(); user1.setPhoneNumbers(new ArrayList<>()); ScimUser user2 = createUser(); user2.setPhoneNumbers(new ArrayList<>()); PhoneNumber mobilePhone = new GlobalPhoneNumberBuilder().globalNumber("+1(814)867-5306").build(); mobilePhone.setType("mobile"); mobilePhone.setPrimary(true); PhoneNumber homePhone = new GlobalPhoneNumberBuilder().globalNumber("+1(814)867-5307").build(); homePhone.setType("home"); homePhone.setPrimary(true); user2.getPhoneNumbers().add(mobilePhone); user2.getPhoneNumbers().add(homePhone); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> operations = updateRequest.getPatchOperations(); assertNotNull(operations); assertEquals(2, operations.size()); PatchOperation operation = operations.get(0); assertNotNull(operation.getValue()); assertEquals(Type.ADD, operation.getOperation()); assertEquals(PhoneNumber.class, operation.getValue().getClass()); operation = operations.get(1); assertNotNull(operation.getValue()); assertEquals(Type.ADD, operation.getOperation()); assertEquals(PhoneNumber.class, operation.getValue().getClass()); } @Test public void testReplaceSingleAttribute() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); user2.setActive(false); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> result = updateRequest.getPatchOperations(); PatchOperation actual = assertSingleResult(result); checkAssertions(actual, Type.REPLACE, "active", false); } @Test public void testReplaceExtensionSingleAttribute() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); user2.getExtension(EnterpriseExtension.class).setDepartment("Dept XYZ."); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> result = updateRequest.getPatchOperations(); PatchOperation actual = assertSingleResult(result); checkAssertions(actual, Type.REPLACE, "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User:department", "Dept XYZ."); } @Test public void testReplaceComplexAttribute() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); user2.getName() .setFamilyName("Nobody"); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> result = updateRequest.getPatchOperations(); PatchOperation actual = assertSingleResult(result); checkAssertions(actual, Type.REPLACE, "name.familyName", "Nobody"); } @Test public void testReplaceMultiValuedAttribute() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); user2.getEmails() .stream() .filter(e -> e.getType() .equals("work")) .forEach(e -> e.setValue("nobody@example.com")); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> result = updateRequest.getPatchOperations(); PatchOperation actual = assertSingleResult(result); checkAssertions(actual, Type.REPLACE, "emails[type EQ \"work\"].value", "nobody@example.com"); } @Test public void testRemoveSingleAttribute() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); user2.setUserName(null); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> result = updateRequest.getPatchOperations(); PatchOperation actual = assertSingleResult(result); checkAssertions(actual, Type.REMOVE, "userName", null); } @Test public void testRemoveSingleExtension() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); user2.removeExtension(EnterpriseExtension.class); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> result = updateRequest.getPatchOperations(); PatchOperation actual = assertSingleResult(result); checkAssertions(actual, Type.REMOVE, "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User", null); } @Test public void testRemoveComplexAttribute() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); user2.getName() .setMiddleName(null); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> result = updateRequest.getPatchOperations(); PatchOperation actual = assertSingleResult(result); checkAssertions(actual, Type.REMOVE, "name.middleName", null); } @Test public void testRemoveFullComplexAttribute() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); user2.setName(null); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> result = updateRequest.getPatchOperations(); PatchOperation actual = assertSingleResult(result); checkAssertions(actual, Type.REMOVE, "name", null); } @Test public void testRemoveMultiValuedAttribute() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); List<Email> newEmails = user2.getEmails() .stream() .filter(e -> e.getType() .equals("work")) .collect(Collectors.toList()); user2.setEmails(newEmails); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> result = updateRequest.getPatchOperations(); PatchOperation actual = assertSingleResult(result); checkAssertions(actual, Type.REMOVE, "emails[type EQ \"home\"]", null); } @Test public void testRemoveMultiValuedAttributeWithSorting() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); Address localAddress = new Address(); localAddress.setStreetAddress("123 Main Street"); localAddress.setLocality("State College"); localAddress.setRegion("PA"); localAddress.setCountry("USA"); localAddress.setType("local"); user1.getAddresses().add(localAddress); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> result = updateRequest.getPatchOperations(); PatchOperation actual = assertSingleResult(result); checkAssertions(actual, Type.REMOVE, "addresses[type EQ \"local\"]", null); } @Test public void testAddMultiValuedAttributeWithSorting() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); Address localAddress = new Address(); localAddress.setStreetAddress("123 Main Street"); localAddress.setLocality("State College"); localAddress.setRegion("PA"); localAddress.setCountry("USA"); localAddress.setType("local"); user2.getAddresses().add(localAddress); user1.getAddresses().get(0).setPostalCode("01234"); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> result = updateRequest.getPatchOperations(); assertEquals(2, result.size()); checkAssertions(result.get(1), Type.ADD, "addresses", localAddress); } @Test public void verifyEmptyArraysDoNotCauseMove() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); user1.setPhotos(new ArrayList<>()); ExampleObjectExtension ext1 = new ExampleObjectExtension(); user1.addExtension(ext1); ExampleObjectExtension ext2 = new ExampleObjectExtension(); ext2.setList(new ArrayList<>()); user2.addExtension(ext2); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> operations = updateRequest.getPatchOperations(); assertTrue(operations.isEmpty(), "Empty Arrays caused a diff"); } @Test public void verifyEmptyArraysAreNulled() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); //Set empty list on root object and verify no differences user1.setPhotos(new ArrayList<>()); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> operations = updateRequest.getPatchOperations(); assertTrue(operations.isEmpty(), "Empty Arrays are not being nulled out"); //Reset user 1 and empty list on Extension and verify no differences user1 = createUser(); ExampleObjectExtension ext = new ExampleObjectExtension(); ext.setList(new ArrayList<>()); operations = updateRequest.getPatchOperations(); assertTrue(operations.isEmpty(), "Empty Arrays are not being nulled out"); //Reset extension and set empty list on element of extension then verify no differences Subobject subobject = new Subobject(); subobject.setList1(new ArrayList<>()); ext = new ExampleObjectExtension(); ext.setSubobject(subobject); operations = updateRequest.getPatchOperations(); assertTrue(operations.isEmpty(), "Empty Arrays are not being nulled out"); } /** * This unit test is to replicate the issue where */ @Test public void testAddArray() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); Photo photo = new Photo(); photo.setType("photo"); photo.setValue("photo1.png"); user2.setPhotos(Stream.of(photo).collect(Collectors.toList())); ExampleObjectExtension ext1 = new ExampleObjectExtension(); ext1.setList(null); user1.addExtension(ext1); ExampleObjectExtension ext2 = new ExampleObjectExtension(); ext2.setList(Stream.of(FIRST,SECOND).collect(Collectors.toList())); user2.addExtension(ext2); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> operations = updateRequest.getPatchOperations(); assertThat(operations) .hasSize(3) .extracting("operation","value") .contains( tuple(Type.ADD, photo), tuple(Type.ADD, "first"), tuple(Type.ADD, "second")); } @Test public void testRemoveArray() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); Photo photo = new Photo(); photo.setType("photo"); photo.setValue("photo1.png"); user1.setPhotos(Stream.of(photo).collect(Collectors.toList())); ExampleObjectExtension ext1 = new ExampleObjectExtension(); ext1.setList(Stream.of(FIRST,SECOND).collect(Collectors.toList())); user1.addExtension(ext1); ExampleObjectExtension ext2 = new ExampleObjectExtension(); ext2.setList(null); user2.addExtension(ext2); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> operations = updateRequest.getPatchOperations(); assertNotNull(operations); assertEquals(2, operations.size()); PatchOperation operation = operations.get(0); assertEquals(Type.REMOVE, operation.getOperation()); assertNull(operation.getValue()); } @Test public void testNonTypedAttributeListGetUseablePath() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); ExampleObjectExtension ext1 = new ExampleObjectExtension(); ext1.setList(Stream.of(FIRST,SECOND,THIRD).collect(Collectors.toList())); user1.addExtension(ext1); ExampleObjectExtension ext2 = new ExampleObjectExtension(); ext2.setList(Stream.of(FIRST,SECOND,FOURTH).collect(Collectors.toList())); user2.addExtension(ext2); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> operations = updateRequest.getPatchOperations(); assertThat(operations) .hasSize(1); PatchOperation patchOp = operations.get(0); PatchOperationAssert.assertThat(patchOp) .hasType(Type.REPLACE) .hashPath(ExampleObjectExtension.URN + ":list[value EQ \"third\"]") .hasValue(FOURTH); } @Test public void testMoveFormatNameToNicknamePart1() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); String nickname = "John Xander Anyman"; user1.setNickName(nickname); user2.getName().setFormatted(nickname); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> operations = updateRequest.getPatchOperations(); assertThat(operations).hasSize(2); assertThat(operations).filteredOn(op(Type.ADD, "name.formatted", nickname)).hasSize(1); assertThat(operations).filteredOn(op(Type.REMOVE, "nickName")).hasSize(1); } @Test public void testMoveFormatNameToNicknamePart2() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); String nickname = "John Xander Anyman"; user1.setNickName(nickname); user2.setNickName(""); user1.getName().setFormatted(""); user2.getName().setFormatted(nickname); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> operations = updateRequest.getPatchOperations(); assertThat(operations).hasSize(2); assertThat(operations).filteredOn(op(Type.REPLACE, "name.formatted", nickname)).hasSize(1); assertThat(operations).filteredOn(op(Type.REPLACE, "nickName", "")).hasSize(1); } @Test public void testMoveFormatNameToNicknamePart3() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); String nickname = "John Xander Anyman"; user1.setNickName(nickname); user2.setNickName(null); user1.getName().setFormatted(""); user2.getName().setFormatted(nickname); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> operations = updateRequest.getPatchOperations(); assertThat(operations).hasSize(2); assertThat(operations).filteredOn(op(Type.REPLACE, "name.formatted", nickname)).hasSize(1); assertThat(operations).filteredOn(op(Type.REMOVE, "nickName")).hasSize(1); } @Test public void testMoveFormatNameToNicknamePart4() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); String nickname = "John Xander Anyman"; user1.setNickName(nickname); user2.setNickName(""); user1.getName().setFormatted(null); user2.getName().setFormatted(nickname); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> operations = updateRequest.getPatchOperations(); assertThat(operations).hasSize(2); assertThat(operations).filteredOn(op(Type.ADD, "name.formatted", nickname)).hasSize(1); assertThat(operations).filteredOn(op(Type.REPLACE, "nickName", "")).hasSize(1); } @Test public void testMoveFormatNameToNicknamePart5() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); String nickname = "John Xander Anyman"; user1.setNickName(""); user2.setNickName(nickname); user1.getName().setFormatted(nickname); user2.getName().setFormatted(null); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> operations = updateRequest.getPatchOperations(); assertThat(operations).hasSize(2); assertThat(operations).filteredOn(op(Type.REMOVE, "name.formatted")).hasSize(1); assertThat(operations).filteredOn(op(Type.REPLACE, "nickName", nickname)).hasSize(1); } @ParameterizedTest @MethodSource("testListOfStringsParameters") public void testListOfStringsParameterized(List<String> list1, List<String> list2, List<ExpectedPatchOperation> ops) throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); ExampleObjectExtension ext1 = new ExampleObjectExtension(); ext1.setList(list1); user1.addExtension(ext1); ExampleObjectExtension ext2 = new ExampleObjectExtension(); ext2.setList(list2); user2.addExtension(ext2); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> operations = updateRequest.getPatchOperations(); assertEquals(ops.size(), operations.size()); for(int i = 0; i < operations.size(); i++) { PatchOperation actualOp = operations.get(i); ExpectedPatchOperation expectedOp = ops.get(i); assertEquals(expectedOp.getOp(), actualOp.getOperation().toString()); assertEquals(expectedOp.getPath(), actualOp.getPath().toString()); if (expectedOp.getValue() == null) { assertNull(actualOp.getValue()); } else { assertEquals(expectedOp.getValue(), actualOp.getValue().toString()); } } } @SuppressWarnings("unused") private static Object[] testListOfStringsParameters() throws Exception { List<Object> params = new ArrayList<>(); String nickName = "John Xander Anyman"; //Parameter order //1 Original list of Strings //2 Update list of Strings //3 Array of Expected Operations // 3a Operation // 3b Path // 3c Value List<ExpectedPatchOperation> multipleOps = new ArrayList<ExpectedPatchOperation>(); multipleOps.add(new ExpectedPatchOperation("ADD", "urn:ietf:params:scim:schemas:extension:example:2.0:Object:list", "A")); multipleOps.add(new ExpectedPatchOperation("ADD", "urn:ietf:params:scim:schemas:extension:example:2.0:Object:list", "B")); multipleOps.add(new ExpectedPatchOperation("ADD", "urn:ietf:params:scim:schemas:extension:example:2.0:Object:list", "C")); params.add(new Object[] {Stream.of(A).collect(Collectors.toList()), new ArrayList<String>(), Stream.of(new ExpectedPatchOperation("REMOVE", "urn:ietf:params:scim:schemas:extension:example:2.0:Object:list", null)).collect(Collectors.toList())}); params.add(new Object[] {Stream.of(A).collect(Collectors.toList()), null, Stream.of(new ExpectedPatchOperation("REMOVE", "urn:ietf:params:scim:schemas:extension:example:2.0:Object:list", null)).collect(Collectors.toList())}); params.add(new Object[] {null, Stream.of(A).collect(Collectors.toList()), Stream.of(new ExpectedPatchOperation("ADD", "urn:ietf:params:scim:schemas:extension:example:2.0:Object:list", "A")).collect(Collectors.toList())}); params.add(new Object[] {null, Stream.of(C,B,A).collect(Collectors.toList()), multipleOps}); params.add(new Object[] {Stream.of(A,B,C).collect(Collectors.toList()), new ArrayList<String>(), Stream.of(new ExpectedPatchOperation("REMOVE", "urn:ietf:params:scim:schemas:extension:example:2.0:Object:list", null)).collect(Collectors.toList())}); params.add(new Object[] {Stream.of(C,B,A).collect(Collectors.toList()), new ArrayList<String>(), Stream.of(new ExpectedPatchOperation("REMOVE", "urn:ietf:params:scim:schemas:extension:example:2.0:Object:list", null)).collect(Collectors.toList())}); params.add(new Object[] {new ArrayList<String>(), Stream.of(A).collect(Collectors.toList()), Stream.of(new ExpectedPatchOperation("ADD", "urn:ietf:params:scim:schemas:extension:example:2.0:Object:list", "A")).collect(Collectors.toList())}); params.add(new Object[] {new ArrayList<String>(), Stream.of(C,B,A).collect(Collectors.toList()), multipleOps}); params.add(new Object[] {Stream.of(A, B).collect(Collectors.toList()), Stream.of(B).collect(Collectors.toList()), Stream.of(new ExpectedPatchOperation("REMOVE", "urn:ietf:params:scim:schemas:extension:example:2.0:Object:list[value EQ \"A\"]", null)).collect(Collectors.toList())}); params.add(new Object[] {Stream.of(B, A).collect(Collectors.toList()), Stream.of(B).collect(Collectors.toList()), Stream.of(new ExpectedPatchOperation("REMOVE", "urn:ietf:params:scim:schemas:extension:example:2.0:Object:list[value EQ \"A\"]", null)).collect(Collectors.toList())}); params.add(new Object[] {Stream.of(B).collect(Collectors.toList()), Stream.of(A,B).collect(Collectors.toList()), Stream.of(new ExpectedPatchOperation("ADD", "urn:ietf:params:scim:schemas:extension:example:2.0:Object:list", A)).collect(Collectors.toList())}); params.add(new Object[] {Stream.of(B).collect(Collectors.toList()), Stream.of(B,A).collect(Collectors.toList()), Stream.of(new ExpectedPatchOperation("ADD", "urn:ietf:params:scim:schemas:extension:example:2.0:Object:list", A)).collect(Collectors.toList())}); params.add(new Object[] {Stream.of(A).collect(Collectors.toList()), Stream.of(A,B,C).collect(Collectors.toList()), Stream.of(new ExpectedPatchOperation("ADD", "urn:ietf:params:scim:schemas:extension:example:2.0:Object:list", B),new ExpectedPatchOperation("ADD", "urn:ietf:params:scim:schemas:extension:example:2.0:Object:list", C)).collect(Collectors.toList())}); return params.toArray(); } @Test @Disabled public void offsetTest1() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); ExampleObjectExtension ext1 = new ExampleObjectExtension(); ext1.setList(Stream.of("D","M","Y","Z","Z","Z","Z","Z").collect(Collectors.toList())); user1.addExtension(ext1); ExampleObjectExtension ext2 = new ExampleObjectExtension(); //ext2.setList(Stream.of("A","A","B","B","D","F","N","Q","Z").collect(Collectors.toList())); ext2.setList(Stream.of("A","Z").collect(Collectors.toList())); user2.addExtension(ext2); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> operations = updateRequest.getPatchOperations(); System.out.println("Number of operations: "+operations.size()); operations.stream().forEach(op -> System.out.println(op)); // TODO this is likely a flaky test, below, "A" replaces one of the "Z" values, but per order of the lists it should be "D" assertThat(operations).hasSize(7); assertThat(operations).filteredOn(op(Type.REPLACE, ExampleObjectExtension.URN + ":list[value EQ \"Z\"]", "A")).hasSize(1); assertThat(operations).filteredOn(op(Type.REMOVE, ExampleObjectExtension.URN + ":list[value EQ \"Z\"]")).hasSize(3); assertThat(operations).filteredOn(op(Type.REMOVE, ExampleObjectExtension.URN + ":list[value EQ \"D\"]")).hasSize(1); assertThat(operations).filteredOn(op(Type.REMOVE, ExampleObjectExtension.URN + ":list[value EQ \"M\"]")).hasSize(1); assertThat(operations).filteredOn(op(Type.REMOVE, ExampleObjectExtension.URN + ":list[value EQ \"Y\"]")).hasSize(1); } @Test public void testMoveFormatNameToNicknamePart6() throws Exception { ScimUser user1 = createUser(); ScimUser user2 = createUser(); String nickname = "John Xander Anyman"; user1.setNickName(null); user2.setNickName(nickname); user1.getName().setFormatted(nickname); user2.getName().setFormatted(""); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> operations = updateRequest.getPatchOperations(); assertThat(operations).hasSize(2); assertThat(operations).filteredOn(op(Type.REPLACE, "name.formatted", "")).hasSize(1); assertThat(operations).filteredOn(op(Type.ADD, "nickName", nickname)).hasSize(1); } /** * This is used to test an error condition. In this scenario a user has multiple phone numbers where home is marked primary and work is not. A SCIM update * is performed in which the new user only contains a work phone number where the type is null. When this happens it should only be a single DELETE * operation. Instead it creates four operations: replace value of the home number with the work number value, replace the home type to work, * remove the primary flag, and remove the work number */ @Test @Disabled public void testShowBugWhereDeleteIsTreatedAsMultipleReplace() throws Exception { final int expectedNumberOfOperationsWithoutBug = 1; final int expectedNumberOfOperationsWithBug = 4; ScimUser user1 = createUser(); ScimUser user2 = createUser(); user2.getPhoneNumbers().removeIf(p -> p.getType().equals("home")); PhoneNumber workNumber = user2.getPhoneNumbers().stream().filter(p -> p.getType().equals("work")).findFirst().orElse(null); assertNotNull(workNumber); workNumber.setType(null); UpdateRequest<ScimUser> updateRequest = new UpdateRequest<>("1234", user1, user2, schemaRegistry); List<PatchOperation> operations = updateRequest.getPatchOperations(); assertNotNull(operations); System.out.println("Number of operations: "+operations.size()); operations.stream().forEach(op -> System.out.println(op)); assertEquals(expectedNumberOfOperationsWithBug, operations.size()); assertNotEquals(expectedNumberOfOperationsWithoutBug, operations.size()); } private PatchOperation assertSingleResult(List<PatchOperation> result) { assertThat(result) .isNotNull(); assertThat(result) .hasSize(1); PatchOperation actual = result.get(0); return actual; } private void checkAssertions(PatchOperation actual, Type op, String path, Object value) throws FilterParseException { assertThat(actual.getOperation()) .isEqualTo(op); assertThat(actual.getPath() .toString()) .isEqualTo(path); assertThat(actual.getValue()) .isEqualTo(value); } @Data @AllArgsConstructor private static class ExpectedPatchOperation { private String op; private String path; private String value; } public static final Address createHomeAddress() { Address homeAddress = new Address(); homeAddress.setType("home"); homeAddress.setStreetAddress("123 Fake Street"); homeAddress.setLocality("State College"); homeAddress.setRegion("Pennsylvania"); homeAddress.setCountry("USA"); homeAddress.setPostalCode("16801"); return homeAddress; } public static ScimUser createUser() throws PhoneNumberParseException { ScimUser user = new ScimUser(); user.setId("912345678"); user.setExternalId("912345678"); user.setActive(true); user.setDisplayName("John Anyman"); user.setTitle("Professor"); user.setUserName("jxa123"); Name name = new Name(); name.setGivenName("John"); name.setMiddleName("Xander"); name.setFamilyName("Anyman"); name.setHonorificSuffix("Jr."); user.setName(name); Address homeAddress = new Address(); homeAddress.setType("home"); homeAddress.setStreetAddress("123 Fake Street"); homeAddress.setLocality("State College"); homeAddress.setRegion("Pennsylvania"); homeAddress.setCountry("USA"); homeAddress.setPostalCode("16801"); Address workAddress = new Address(); workAddress.setType("work"); workAddress.setStreetAddress("2 Old Main"); workAddress.setLocality("State College"); workAddress.setRegion("Pennsylvania"); workAddress.setCountry("USA"); workAddress.setPostalCode("16802"); List<Address> address = Stream.of(workAddress, homeAddress) .collect(Collectors.toList()); user.setAddresses(address); Email workEmail = new Email(); workEmail.setPrimary(true); workEmail.setType("work"); workEmail.setValue("jxa123@psu.edu"); workEmail.setDisplay("jxa123@psu.edu"); Email homeEmail = new Email(); homeEmail.setPrimary(true); homeEmail.setType("home"); homeEmail.setValue("john@gmail.com"); homeEmail.setDisplay("john@gmail.com"); Email otherEmail = new Email(); otherEmail.setPrimary(true); otherEmail.setType("other"); otherEmail.setValue("outside@version.net"); otherEmail.setDisplay("outside@version.net"); List<Email> emails = Stream.of(homeEmail, workEmail) .collect(Collectors.toList()); user.setEmails(emails); //"+1(814)867-5309" PhoneNumber homePhone = new GlobalPhoneNumberBuilder().globalNumber("+1(814)867-5309").build(); homePhone.setType("home"); homePhone.setPrimary(true); //"+1(814)867-5307" PhoneNumber workPhone = new GlobalPhoneNumberBuilder().globalNumber("+1(814)867-5307").build(); workPhone.setType("work"); workPhone.setPrimary(false); List<PhoneNumber> phones = Stream.of(homePhone, workPhone) .collect(Collectors.toList()); user.setPhoneNumbers(phones); EnterpriseExtension enterpriseExtension = new EnterpriseExtension(); enterpriseExtension.setEmployeeNumber("7865"); enterpriseExtension.setDepartment("Dept B."); Manager manager = new Manager(); manager.setValue("Pointy Haired Boss"); manager.setRef("45353"); enterpriseExtension.setManager(manager); user.addExtension(enterpriseExtension); return user; } private List<PatchOperation> createUser1PatchOps() throws FilterParseException { List<PatchOperation> patchOperations = new ArrayList<>(); PatchOperation removePhoneNumberOp = new PatchOperation(); removePhoneNumberOp.setOperation(Type.REMOVE); removePhoneNumberOp.setPath(new PatchOperationPath("phoneNumbers[type eq \"home\"]")); patchOperations.add(removePhoneNumberOp); return patchOperations; } static class PatchOperationAssert extends AbstractAssert<PatchOperationAssert, PatchOperation> { public PatchOperationAssert(PatchOperation actual) { super(actual, PatchOperationAssert.class); } public PatchOperationAssert hashPath(String path) { isNotNull(); PatchOperationPath actualPath = actual.getPath(); if (actualPath == null || !actualPath.toString().equals(path)) { failWithMessage("Expecting path in:\n <%s>\nto be: <%s>\nbut was: <%s>", actual, actualPath, path); } return this; } public PatchOperationAssert hasType(Type opType) { isNotNull(); Type actualType = actual.getOperation(); if (!Objects.equals(actualType, opType)) { failWithMessage("Expecting operation type in:\n <%s>\nto be: <%s>\nbut was: <%s>", actual, actualType, opType); } return this; } public PatchOperationAssert hasValue(Object value) { isNotNull(); Object actualValue = actual.getValue(); if (!Objects.equals(actualValue, value)) { failWithMessage("Expecting value in:\n <%s>\nto be: <%s>\nbut was: <%s>", actual, actualValue, value); } return this; } public PatchOperationAssert nullValue() { return hasValue(null); } public static PatchOperationAssert assertThat(PatchOperation actual) { return new PatchOperationAssert(actual); } } static class PatchOperationCondition extends Condition<PatchOperation> { private final Type type; private final String path; private final Object value; public PatchOperationCondition(Type type, String path, Object value) { this.type = type; this.path = path; this.value = value; } @Override public boolean matches(PatchOperation patchOperation){ return Objects.equals(type, patchOperation.getOperation()) && Objects.equals(path, Objects.toString(patchOperation.getPath().toString())) && Objects.equals(value, patchOperation.getValue()); } static PatchOperationCondition op(Type type, String path, Object value) { return new PatchOperationCondition(type, path, value); } static PatchOperationCondition op(Type type, String path) { return op(type, path, null); } } }
4,305
0
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core/repository/RepositoryRegistryTest.java
/* * 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 * 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.directory.scim.core.repository; import org.apache.directory.scim.core.schema.SchemaRegistry; import org.apache.directory.scim.spec.annotation.ScimExtensionType; import org.apache.directory.scim.spec.annotation.ScimResourceType; import org.apache.directory.scim.spec.exception.ResourceException; import org.apache.directory.scim.spec.exception.ScimResourceInvalidException; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.resources.ScimResource; import org.apache.directory.scim.spec.resources.ScimUser; import org.junit.jupiter.api.Test; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.*; public class RepositoryRegistryTest { @Test public void initializeWithException() throws InvalidRepositoryException { SchemaRegistry schemaRegistry = new SchemaRegistry(); Repository<ScimUser> repository = mock(Repository.class); doThrow(new InvalidRepositoryException("test exception")).when(repository).getExtensionList(); assertThrows(ScimResourceInvalidException.class, () -> new RepositoryRegistry(schemaRegistry, List.of(repository))); } @Test public void registerRepository() throws InvalidRepositoryException, ResourceException { SchemaRegistry schemaRegistry = spy(new SchemaRegistry()); Repository<StubResource> repository = mock(Repository.class); RepositoryRegistry repositoryRegistry = spy(new RepositoryRegistry(schemaRegistry)); when(repository.getExtensionList()).thenReturn(List.of(StubExtension.class)); repositoryRegistry.registerRepository(StubResource.class, repository); assertThat(schemaRegistry.getExtensionClass(StubResource.class, StubExtension.URN)).isNotNull(); assertThat(repositoryRegistry.getRepository(StubResource.class)).isEqualTo(repository); } @ScimResourceType(id = StubResource.NAME, endpoint = "/Stub", schema = StubResource.URN) static class StubResource extends ScimResource { final static String URN = "urn:test:stub"; final static String NAME = "Stub"; public StubResource() { super(URN, NAME); } } @ScimExtensionType(name = StubExtension.NAME, id = StubExtension.URN) static class StubExtension implements ScimExtension { final static String URN = "urn:test:stub:extension"; final static String NAME = "StubExtension"; @Override public String getUrn() { return URN; } } }
4,306
0
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core/repository/RepositorySchemaRegistryTest.java
/* * 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 * 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.directory.scim.core.repository; import static org.assertj.core.api.Assertions.assertThat; import org.apache.directory.scim.spec.resources.ScimUser; import org.apache.directory.scim.spec.schema.Schema; import org.apache.directory.scim.core.schema.SchemaRegistry; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public class RepositorySchemaRegistryTest { SchemaRegistry schemaRegistry; @Mock Repository<ScimUser> repository; RepositoryRegistry repositoryRegistry; public RepositorySchemaRegistryTest() { schemaRegistry = new SchemaRegistry(); repositoryRegistry = new RepositoryRegistry(schemaRegistry); } @Test public void testAddRepository() throws Exception { repositoryRegistry.registerRepository(ScimUser.class, repository); Schema schema = schemaRegistry.getSchema(ScimUser.SCHEMA_URI); assertThat(schema).isNotNull(); assertThat(schema.getId()).isEqualTo(ScimUser.SCHEMA_URI); } }
4,307
0
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core/repository/PrioritySortingComparatorTest.java
/* * 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 * 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.directory.scim.core.repository; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; public class PrioritySortingComparatorTest { @Test public void testSorting() throws Exception { Set<Object> priorities = new HashSet<>(); priorities.add("1P"); priorities.add("2P"); PrioritySortingComparator comparitor = new PrioritySortingComparator(priorities); List<String> list = Arrays.asList("1", "2", "1P", "2P", "3", "4"); Collections.sort(list, comparitor); System.out.println(list); Assertions.assertThat(list).hasSameElementsAs(Arrays.asList("1P", "2P", "1", "2", "3", "4")); } @Test public void testSorting2() throws Exception { Set<Object> priorities = new HashSet<>(); priorities.add("home"); priorities.add("work"); PrioritySortingComparator comparitor = new PrioritySortingComparator(priorities); List<String> list = Arrays.asList("work", "local", "home"); Collections.sort(list, comparitor); System.out.println(list); Assertions.assertThat(list).hasSameElementsAs(Arrays.asList("home", "work", "local")); } }
4,308
0
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core/repository/PatchHandlerTest.java
/* * 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 * 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.directory.scim.core.repository; import lombok.SneakyThrows; import org.apache.directory.scim.core.schema.SchemaRegistry; import org.apache.directory.scim.spec.extension.EnterpriseExtension; import org.apache.directory.scim.spec.filter.FilterParseException; import org.apache.directory.scim.spec.patch.PatchOperation; import org.apache.directory.scim.spec.patch.PatchOperation.Type; import org.apache.directory.scim.spec.patch.PatchOperationPath; import org.apache.directory.scim.spec.phonenumber.PhoneNumberParseException; import org.apache.directory.scim.spec.resources.Address; import org.apache.directory.scim.spec.resources.Email; import org.apache.directory.scim.spec.resources.Name; import org.apache.directory.scim.spec.resources.PhoneNumber; import org.apache.directory.scim.spec.resources.ScimUser; import org.junit.jupiter.api.Test; import static org.apache.directory.scim.spec.patch.PatchOperation.Type.*; import static java.util.Map.entry; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.Map; import java.util.Optional; public class PatchHandlerTest { PatchHandlerImpl patchHandler; public PatchHandlerTest() { SchemaRegistry schemaRegistry = new SchemaRegistry(); schemaRegistry.addSchema(ScimUser.class, List.of(EnterpriseExtension.class)); this.patchHandler = new PatchHandlerImpl(schemaRegistry); } @Test public void applyReplaceUserName() { String newUserName = "testUser_updated@test.com"; PatchOperation op = patchOperation(REPLACE, "userName", newUserName); ScimUser updatedUser = patchHandler.apply(user(), List.of(op)); assertThat(updatedUser.getUserName()).isEqualTo(newUserName); } @Test public void applyReplaceMappedValueWhenPathIsNull() { String newDisplayName = "Test User - Updated"; PatchOperation op = patchOperation(REPLACE, null, Map.ofEntries(entry("displayName", newDisplayName))); ScimUser updatedUser = patchHandler.apply(user(), List.of(op)); assertThat(updatedUser.getDisplayName()).isEqualTo(newDisplayName); } @Test public void applyReplaceWithExpressionFilter() { String newNumber = "tel:+1-123-456-7890"; PatchOperation op = patchOperation(REPLACE, "phoneNumbers[type eq \"mobile\"].value", newNumber); ScimUser updatedUser = patchHandler.apply(user(), List.of(op)); assertThat(updatedUser.getPhoneNumbers().get(0).getValue()).isEqualTo(newNumber); } @Test public void applyReplaceSubAttribute() { String newFormattedName = "Maverick"; PatchOperation op = patchOperation(REPLACE, "name.formatted", newFormattedName); ScimUser updatedUser = patchHandler.apply(user(), List.of(op)); assertThat(updatedUser.getName().getFormatted()).isEqualTo(newFormattedName); } @Test public void applyAddWhenFilterDoesNotMatchAny() { String faxNumber = "tel:+1-123-456-7899"; PatchOperation op = patchOperation(ADD, "phoneNumbers[type eq \"fax\"].value", faxNumber); ScimUser updatedUser = patchHandler.apply(user(), List.of(op)); List<PhoneNumber> phoneNumbers = updatedUser.getPhoneNumbers(); assertThat(phoneNumbers.size()).isEqualTo(2); Optional<PhoneNumber> addedFaxNumber = phoneNumbers.stream().filter(phoneNumber -> phoneNumber.getType().equals("fax")).findFirst(); assertThat(addedFaxNumber).isNotEmpty(); assertThat(addedFaxNumber.get().getValue()).isEqualTo(faxNumber); } @Test public void applyAddToMultiValuedComplexAttribute() { Address workAddress = new Address() .setType("work") .setStreetAddress("101 Main Street") .setRegion("Springfield"); Address homeAddress = new Address() .setType("home") .setStreetAddress("202 Maple Street") .setRegion("Otherton") .setPostalCode("43210"); List<Address> expectedAddresses = List.of( new Address() .setType("work") .setStreetAddress("101 Main Street") .setRegion("Springfield") .setPostalCode("ko4 8qq"), homeAddress); ScimUser user = user().setAddresses(List.of(workAddress, homeAddress)); PatchOperation op = patchOperation(ADD, "addresses[type eq \"work\"].postalCode", "ko4 8qq"); ScimUser updatedUser = patchHandler.apply(user, List.of(op)); assertThat(updatedUser.getAddresses()).isEqualTo(expectedAddresses); } @Test public void applyAddSingleComplexAttribute() { ScimUser user = user(); PatchOperation op = patchOperation(ADD, "name.honorificSuffix", "II"); ScimUser updatedUser = patchHandler.apply(user, List.of(op)); Name expectedName = new Name() .setFormatted(user.getName().getFormatted()) .setHonorificSuffix("II"); assertThat(updatedUser.getName()).isEqualTo(expectedName); } @Test public void applyReplaceSingleComplexAttribute() { ScimUser user = user(); PatchOperation op = patchOperation(REPLACE, "name.formatted", "Charlie"); ScimUser updatedUser = patchHandler.apply(user, List.of(op)); Name expectedName = new Name() .setFormatted("Charlie"); assertThat(updatedUser.getName()).isEqualTo(expectedName); } @Test public void applyAddToMissingSingleComplexAttribute() { ScimUser user = user(); PatchOperation op = patchOperation(ADD, "addresses[type eq \"work\"].postalCode", "ko4 8qq"); ScimUser updatedUser = patchHandler.apply(user, List.of(op)); List<Address> expectedAddresses = List.of( new Address() .setType("work") .setPostalCode("ko4 8qq")); assertThat(updatedUser.getAddresses()).isEqualTo(expectedAddresses); } @Test public void settingPrimaryOnMultiValuedShouldResetAllOthersToFalse() { // https://www.rfc-editor.org/rfc/rfc7644#section-3.5.2 ScimUser user = user(); PatchOperation op = patchOperation(REPLACE, "emails[type eq \"home\"].primary", true); ScimUser updatedUser = patchHandler.apply(user, List.of(op)); List<Email> expectedEmails = List.of( new Email() .setPrimary(false) .setType("work") .setValue("work@example.com"), new Email() .setPrimary(true) .setType("home") .setValue("home@example.com")); assertThat(updatedUser.getEmails()).isEqualTo(expectedEmails); } @Test public void applyRemoveSubAttribute() { PatchOperation op = patchOperation(REMOVE, "name.formatted", null); ScimUser updatedUser = patchHandler.apply(user(), List.of(op)); assertThat(updatedUser.getName().getFormatted()).isNull(); } @Test public void applyRemoveItemWithFilter() { ScimUser user = user().setAddresses(List.of( new Address() .setType("work") .setStreetAddress("101 Main Street") .setRegion("Springfield") .setPostalCode("01234"), new Address() .setType("home") .setStreetAddress("202 Maple Street") .setRegion("Otherton") .setPostalCode("43210") )); PatchOperation op = patchOperation(REMOVE, "addresses[type eq \"work\"]", null); ScimUser updatedUser = patchHandler.apply(user, List.of(op)); assertThat(updatedUser.getAddresses().size()).isEqualTo(1); assertThat(updatedUser.getAddresses().get(0).getType()).isEqualTo("home"); assertThat(updatedUser.getAddresses().get(0).getPostalCode()).isEqualTo("43210"); } @Test public void applyRemoveAttributeWithFilter() { Address workAddress = new Address() .setType("work") .setStreetAddress("101 Main Street") .setRegion("Springfield") .setPostalCode("01234"); Address homeAddress = new Address() .setType("home") .setStreetAddress("202 Maple Street") .setRegion("Otherton") .setPostalCode("43210"); Address updatedWorkAddress = new Address() .setType("work") .setStreetAddress("101 Main Street") .setRegion("Springfield"); ScimUser user = user().setAddresses(List.of(workAddress, homeAddress)); PatchOperation op = patchOperation(REMOVE, "addresses[type eq \"work\"].postalCode", null); ScimUser updatedUser = patchHandler.apply(user, List.of(op)); assertThat(updatedUser.getAddresses().size()).isEqualTo(2); assertThat(updatedUser.getAddresses().get(0)).isEqualTo(updatedWorkAddress); } @Test public void applyReplaceItemWithFilter() { Address workAddress = new Address() .setType("work") .setStreetAddress("101 Main Street") .setRegion("Springfield") .setPostalCode("01234"); Address homeAddress = new Address() .setType("home") .setStreetAddress("202 Maple Street") .setRegion("Othertown") .setPostalCode("43210"); Address otherAddress = new Address() .setType("other") .setStreetAddress("303 Loop Road") .setRegion("Thirdtown") .setPostalCode("11223") .setPrimary(true); Map<String, Object> newAddress = Map.of( "type", otherAddress.getType(), "streetAddress", otherAddress.getStreetAddress(), "region", otherAddress.getRegion(), "postalCode", otherAddress.getPostalCode(), "primary", otherAddress.getPrimary() ); ScimUser user = user().setAddresses(List.of(workAddress, homeAddress)); PatchOperation op = patchOperation(REPLACE, "addresses[type eq \"work\"]", newAddress); ScimUser updatedUser = patchHandler.apply(user, List.of(op)); assertThat(updatedUser.getAddresses().size()).isEqualTo(2); assertThat(updatedUser.getAddresses().get(0)).isEqualTo(otherAddress); assertThat(updatedUser.getAddresses().get(1)).isEqualTo(homeAddress); } @Test public void applyReplaceItemAttributeWithFilter() { Address workAddress = new Address() .setType("work") .setStreetAddress("101 Main Street") .setRegion("Springfield") .setPostalCode("01234"); Address homeAddress = new Address() .setType("home") .setStreetAddress("202 Maple Street") .setRegion("Othertown") .setPostalCode("43210"); Address updatedHome = new Address() .setType("home") .setStreetAddress("202 Maple Street") .setRegion("Othertown") .setPostalCode("43210") .setPrimary(true); ScimUser user = user().setAddresses(List.of(workAddress, homeAddress)); PatchOperation op = patchOperation(REPLACE, "addresses[type eq \"home\"].primary", true); ScimUser updatedUser = patchHandler.apply(user, List.of(op)); assertThat(updatedUser.getAddresses().size()).isEqualTo(2); assertThat(updatedUser.getAddresses().get(0)).isEqualTo(workAddress); assertThat(updatedUser.getAddresses().get(1)).isEqualTo(updatedHome); } @Test public void applyReplaceEnterpriseExtension() { String employeeNumberUrn = "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User:employeeNumber"; String employeeNumber = "NCIR48XM6D84"; PatchOperation op = patchOperation(ADD, null, Map.ofEntries(entry(employeeNumberUrn, employeeNumber))); ScimUser updatedUser = patchHandler.apply(user(), List.of(op)); assertThat(updatedUser.getSchemas().size()).isEqualTo(2); EnterpriseExtension enterpriseUser = (EnterpriseExtension) updatedUser.getExtension(EnterpriseExtension.URN); assertThat(enterpriseUser.getEmployeeNumber()).isEqualTo(employeeNumber); } @Test public void applyRemove() { PatchOperation op = patchOperation(REMOVE, "displayName", null); ScimUser updatedUser = patchHandler.apply(user(), List.of(op)); assertThat(updatedUser.getDisplayName()).isNull(); } @Test public void applyWithFilterExpression() throws FilterParseException { PatchOperation op = new PatchOperation(); op.setOperation(REPLACE); op.setPath(new PatchOperationPath("emails[type EQ \"home\"].value")); op.setValue("new-home@example.com"); ScimUser updatedUser = patchHandler.apply(user(), List.of(op)); List<Email> emails = updatedUser.getEmails(); assertThat(emails).isEqualTo(List.of( new Email() .setPrimary(true) .setType("work") .setValue("work@example.com"), new Email() .setType("home") .setValue("new-home@example.com") // updated email )); } @Test public void replaceItem() throws FilterParseException { PatchOperation op = new PatchOperation(); op.setOperation(REPLACE); op.setPath(new PatchOperationPath("emails[type EQ \"home\"]")); op.setValue(Map.of( "type", "other", "value", "other@example.com" )); ScimUser updatedUser = patchHandler.apply(user(), List.of(op)); List<Email> emails = updatedUser.getEmails(); assertThat(emails).isEqualTo(List.of( new Email() .setPrimary(true) .setType("work") .setValue("work@example.com"), new Email() .setType("other") .setValue("other@example.com") )); } @Test public void replaceMultipleAttributes() { PatchOperation op = new PatchOperation(); op.setOperation(REPLACE); op.setValue(Map.of( "emails", List.of( Map.of( "type", "home", "value", "first@example.com"), Map.of( "type", "work", "value", "second@example.com", "primary", true) ), "nickName", "Babs" )); ScimUser updatedUser = patchHandler.apply(user(), List.of(op)); List<Email> emails = updatedUser.getEmails(); assertThat(emails).isEqualTo(List.of( new Email() .setType("home") .setValue("first@example.com"), new Email() .setPrimary(true) .setType("work") .setValue("second@example.com") )); assertThat(updatedUser.getNickName()).isEqualTo("Babs"); } @Test public void replaceCollection() throws FilterParseException { PatchOperation op = new PatchOperation(); op.setOperation(REPLACE); op.setPath(new PatchOperationPath("emails")); op.setValue(List.of( Map.of( "value", "first@example.com", "type", "home"), Map.of( "primary", true, "value", "second@example.com", "type", "work") )); ScimUser updatedUser = patchHandler.apply(user(), List.of(op)); List<Email> emails = updatedUser.getEmails(); assertThat(emails).isEqualTo(List.of( new Email() .setType("home") .setValue("first@example.com"), new Email() .setPrimary(true) .setType("work") .setValue("second@example.com") )); } @Test public void deleteItemWithFilter() throws FilterParseException { PatchOperation op = new PatchOperation(); op.setOperation(REMOVE); op.setPath(new PatchOperationPath("emails[type EQ \"home\"]")); ScimUser updatedUser = patchHandler.apply(user(), List.of(op)); List<Email> emails = updatedUser.getEmails(); assertThat(emails).isEqualTo(List.of( new Email() .setPrimary(true) .setType("work") .setValue("work@example.com") )); } @Test public void deleteAttributeWithPath() throws FilterParseException { PatchOperation op = new PatchOperation(); op.setOperation(REMOVE); op.setPath(new PatchOperationPath("nickName")); ScimUser updatedUser = patchHandler.apply(user(), List.of(op)); assertThat(updatedUser.getNickName()).isNull(); } @Test public void deleteCollectionWithPath() throws FilterParseException { PatchOperation op = new PatchOperation(); op.setOperation(REMOVE); op.setPath(new PatchOperationPath("emails")); ScimUser updatedUser = patchHandler.apply(user(), List.of(op)); assertThat(updatedUser.getEmails()).isNull(); } @Test public void deleteItemWithComplexFilter() throws FilterParseException { PatchOperation op = new PatchOperation(); op.setOperation(REMOVE); op.setPath(new PatchOperationPath("emails[type EQ \"home\"] and value ew \"example.com\"")); ScimUser updatedUser = patchHandler.apply(user(), List.of(op)); assertThat(updatedUser.getEmails()).isEqualTo(List.of( new Email() .setPrimary(true) .setType("work") .setValue("work@example.com") )); } @Test public void addAttribute() throws FilterParseException { PatchOperation op = new PatchOperation(); op.setOperation(ADD); op.setPath(new PatchOperationPath("profileUrl")); op.setValue("https://profile.example.com"); ScimUser expectedUser = user() .setProfileUrl("https://profile.example.com"); ScimUser updatedUser = patchHandler.apply(user(), List.of(op)); assertThat(updatedUser).isEqualTo(expectedUser); } @Test public void addItem() throws FilterParseException { PatchOperation op = new PatchOperation(); op.setOperation(ADD); op.setPath(new PatchOperationPath("emails")); op.setValue(Map.of( "type", "other", "value", "other@example.com")); ScimUser updatedUser = patchHandler.apply(user(), List.of(op)); List<Email> emails = updatedUser.getEmails(); assertThat(emails).isEqualTo(List.of( new Email() .setPrimary(true) .setType("work") .setValue("work@example.com"), new Email() .setType("home") .setValue("home@example.com"), new Email() .setType("other") .setValue("other@example.com") )); } @Test public void addMultipleProperties() throws FilterParseException { // From Section 3.5.2.1 Add Operation of SCIM Protocol RFC PatchOperation op = new PatchOperation(); op.setOperation(ADD); op.setValue(Map.of( "emails", Map.of( "value", "babs@example.com", "type", "other"), "profileUrl", "https://profile.example.com" )); ScimUser updatedUser = patchHandler.apply(user(), List.of(op)); List<Email> emails = updatedUser.getEmails(); assertThat(emails).isEqualTo(List.of( new Email() .setPrimary(true) .setType("work") .setValue("work@example.com"), new Email() .setType("home") .setValue("home@example.com"), new Email() .setType("other") .setValue("babs@example.com") )); assertThat(updatedUser.getProfileUrl()).isEqualTo("https://profile.example.com"); } @Test public void multiplePatchOperations() throws FilterParseException { PatchOperation opRm = new PatchOperation(); opRm.setOperation(REMOVE); opRm.setPath(new PatchOperationPath("emails[type EQ \"home\"]")); PatchOperation opAdd = new PatchOperation(); opAdd.setOperation(ADD); opAdd.setPath(new PatchOperationPath("emails")); opAdd.setValue(Map.of( "value", "babs@example.com", "type", "other") ); ScimUser updatedUser = patchHandler.apply(user(), List.of(opRm, opAdd)); List<Email> emails = updatedUser.getEmails(); assertThat(emails).isEqualTo(List.of( new Email() .setPrimary(true) .setType("work") .setValue("work@example.com"), new Email() .setType("other") .setValue("babs@example.com") )); } @Test public void replaceCollectionWithMultipleOps() throws FilterParseException { PatchOperation opRm = new PatchOperation(); opRm.setOperation(REMOVE); opRm.setPath(new PatchOperationPath("emails")); PatchOperation opAdd = new PatchOperation(); opAdd.setOperation(ADD); opAdd.setPath(new PatchOperationPath("emails")); opAdd.setValue(List.of( Map.of( "value", "first@example.com", "type", "home"), Map.of( "primary", true, "value", "second@example.com", "type", "work") )); ScimUser updatedUser = patchHandler.apply(user(), List.of(opRm, opAdd)); List<Email> emails = updatedUser.getEmails(); assertThat(emails).isEqualTo(List.of( new Email() .setType("home") .setValue("first@example.com"), new Email() .setPrimary(true) .setType("work") .setValue("second@example.com") )); } @SneakyThrows private PatchOperation patchOperation(Type operationType, String path, Object value) { PatchOperation op = new PatchOperation(); op.setOperation(operationType); if (path != null) { op.setPath(new PatchOperationPath(path)); } if (value != null) { op.setValue(value); } return op; } private static ScimUser user() { try { return new ScimUser() .setUserName("testUser@test.com") .setDisplayName("Test User") .setNickName("tester") .setName(new Name() .setFormatted("Berry")) .setPhoneNumbers(List.of(new PhoneNumber() .setType("mobile") .setValue("tel:+1-111-111-1111"))) .setEmails(List.of( new Email() .setPrimary(true) .setType("work") .setValue("work@example.com"), new Email() .setType("home") .setValue("home@example.com") )); } catch (PhoneNumberParseException e) { throw new IllegalStateException("Invalid phone number", e); } } }
4,309
0
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core/repository
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core/repository/utility/Order.java
/* * 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 * 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.directory.scim.core.repository.utility; public enum Order { FIRST("first"), SECOND("second"), THIRD("third"), FOURTH("fourth"); Order(String value) { this.value = value; } private final String value; public String getValue() { return value; } @Override public String toString() { return value; } }
4,310
0
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core/repository
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core/repository/utility/ExampleObjectExtension.java
/* * 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 * 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.directory.scim.core.repository.utility; import jakarta.xml.bind.annotation.*; import lombok.Data; import org.apache.directory.scim.spec.annotation.ScimAttribute; import org.apache.directory.scim.spec.annotation.ScimExtensionType; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.schema.Schema.Attribute.Mutability; import org.apache.directory.scim.spec.schema.Schema.Attribute.Returned; import java.io.Serializable; import java.util.List; @XmlRootElement @XmlAccessorType(XmlAccessType.NONE) @ScimExtensionType(required = false, name = "ExampleObject", id = ExampleObjectExtension.URN, description = "Example Object Extensions.") @Data public class ExampleObjectExtension implements ScimExtension { private static final long serialVersionUID = -5398090056271556423L; public static final String URN = "urn:ietf:params:scim:schemas:extension:example:2.0:Object"; @XmlType @XmlAccessorType(XmlAccessType.NONE) @Data public static class ComplexObject implements Serializable { private static final long serialVersionUID = 2822581434679824690L; @ScimAttribute(description = "The \"id\" of the complex object.") @XmlElement private String value; @ScimAttribute(mutability = Mutability.READ_ONLY, description = "displayName of the object.") @XmlElement private String displayName; } @ScimAttribute(returned = Returned.ALWAYS) @XmlElement private String valueAlways; @ScimAttribute(returned = Returned.DEFAULT) @XmlElement private String valueDefault; @ScimAttribute(returned = Returned.NEVER) @XmlElement private String valueNever; @ScimAttribute(returned = Returned.REQUEST) @XmlElement private String valueRequest; @ScimAttribute(returned = Returned.REQUEST) @XmlElement private ComplexObject valueComplex; @ScimAttribute @XmlElement private List<String> list; @ScimAttribute @XmlElement private List<Order> enumList; @ScimAttribute @XmlElement private Subobject subobject; @Override public String getUrn() { return URN; } }
4,311
0
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core/repository
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core/repository/utility/Subobject.java
/* * 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 * 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.directory.scim.core.repository.utility; import jakarta.xml.bind.annotation.XmlElement; import lombok.Data; import org.apache.directory.scim.spec.annotation.ScimAttribute; import java.io.Serializable; import java.util.List; @Data public class Subobject implements Serializable { private static final long serialVersionUID = -8081556701833520316L; @ScimAttribute @XmlElement private String string1; @ScimAttribute @XmlElement private String string2; @ScimAttribute @XmlElement private Boolean boolean1; @ScimAttribute @XmlElement private Boolean boolean2; @ScimAttribute @XmlElement private List<String> list1; @ScimAttribute @XmlElement private List<String> list2; }
4,312
0
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core/schema/SchemaRegistryTest.java
/* * 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 * 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.directory.scim.core.schema; import org.apache.directory.scim.core.repository.utility.ExampleObjectExtension; import org.apache.directory.scim.spec.resources.ScimGroup; import org.apache.directory.scim.spec.resources.ScimUser; import org.apache.directory.scim.spec.schema.ResourceType; import org.apache.directory.scim.spec.schema.Schema; import org.apache.directory.scim.spec.schema.Schemas; import org.junit.jupiter.api.Test; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class SchemaRegistryTest { @Test public void registerSchema() { SchemaRegistry schemaRegistry = new SchemaRegistry(); Schema userSchema = Schemas.schemaFor(ScimUser.class); Schema groupsSchema = Schemas.schemaFor(ScimGroup.class); Schema extSchema = Schemas.schemaForExtension(ExampleObjectExtension.class); ResourceType userType = new ResourceType(); userType.setId(ScimUser.RESOURCE_NAME); userType.setEndpoint("/Users"); userType.setSchemaUrn(ScimUser.SCHEMA_URI); userType.setName(ScimUser.RESOURCE_NAME); userType.setDescription("Top level ScimUser"); userType.setSchemaExtensions(List.of(new ResourceType.SchemaExtensionConfiguration().setSchemaUrn(ExampleObjectExtension.URN))); ResourceType groupType = new ResourceType(); groupType.setId(ScimGroup.RESOURCE_NAME); groupType.setEndpoint("/Groups"); groupType.setSchemaUrn(ScimGroup.SCHEMA_URI); groupType.setName(ScimGroup.RESOURCE_NAME); groupType.setDescription("Top level ScimGroup"); schemaRegistry.addSchema(ScimUser.class, List.of(ExampleObjectExtension.class)); schemaRegistry.addSchema(ScimGroup.class, null); assertThat(schemaRegistry.getSchema(ScimUser.SCHEMA_URI)).isEqualTo(userSchema); assertThat(schemaRegistry.getAllSchemas()).containsOnly(userSchema, groupsSchema, extSchema); assertThat(schemaRegistry.getAllSchemaUrns()).containsOnly(ScimUser.SCHEMA_URI, ScimGroup.SCHEMA_URI, ExampleObjectExtension.URN); assertThat(schemaRegistry.getAllResourceTypes()).containsOnly(userType, groupType); assertThat(schemaRegistry.getResourceType(ScimUser.RESOURCE_NAME)).isEqualTo(userType); assertThat(schemaRegistry.getScimResourceClassFromEndpoint("/Users")).isEqualTo(ScimUser.class); assertThat(schemaRegistry.getScimResourceClassFromEndpoint("/Groups")).isEqualTo(ScimGroup.class); assertThat(schemaRegistry.getScimResourceClass(ScimUser.SCHEMA_URI)).isEqualTo(ScimUser.class); assertThat(schemaRegistry.getBaseSchemaOfResourceType(ScimUser.RESOURCE_NAME)).isEqualTo(Schemas.schemaFor(ScimUser.class)); } }
4,313
0
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core/json/ObjectMapperFactoryTest.java
/* * 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 * 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.directory.scim.core.json; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.directory.scim.core.schema.SchemaRegistry; import org.apache.directory.scim.core.utility.ExampleObjectExtension; import org.apache.directory.scim.spec.resources.ScimResource; import org.apache.directory.scim.spec.resources.ScimUser; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.util.List; public class ObjectMapperFactoryTest { @Test public void serialize() throws JsonProcessingException { SchemaRegistry schemaRegistry = new SchemaRegistry(); schemaRegistry.addSchema(ScimUser.class, List.of(ExampleObjectExtension.class)); schemaRegistry.addExtension(ScimUser.class, ExampleObjectExtension.class); ScimResource resource = new ScimUser().setId("test1"); ExampleObjectExtension extension = new ExampleObjectExtension().setValueDefault("test-value"); resource.addExtension(extension); ObjectMapper objectMapper = ObjectMapperFactory.createObjectMapper(schemaRegistry); String json = objectMapper.writeValueAsString(resource); ScimResource actual = objectMapper.readValue(json, ScimResource.class); Assertions.assertThat(actual).isEqualTo(resource); } }
4,314
0
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core/utility/Order.java
/* * 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 * 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.directory.scim.core.utility; public enum Order { FIRST("first"), SECOND("second"), THIRD("third"), FOURTH("fourth"); Order(String value) { this.value = value; } private final String value; public String getValue() { return value; } @Override public String toString() { return value; } }
4,315
0
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core/utility/ExampleObjectExtension.java
/* * 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 * 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.directory.scim.core.utility; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlType; import lombok.Data; import org.apache.directory.scim.spec.annotation.ScimAttribute; import org.apache.directory.scim.spec.annotation.ScimExtensionType; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.schema.Schema.Attribute.Mutability; import org.apache.directory.scim.spec.schema.Schema.Attribute.Returned; import java.io.Serializable; import java.util.List; @XmlRootElement @XmlAccessorType(XmlAccessType.NONE) @ScimExtensionType(required = false, name = "ExampleObject", id = ExampleObjectExtension.URN, description = "Example Object Extensions.") @Data public class ExampleObjectExtension implements ScimExtension { private static final long serialVersionUID = -5398090056271556423L; public static final String URN = "urn:ietf:params:scim:schemas:extension:example:2.0:Object"; @XmlType @XmlAccessorType(XmlAccessType.NONE) @Data public static class ComplexObject implements Serializable { private static final long serialVersionUID = 2822581434679824690L; @ScimAttribute(description = "The \"id\" of the complex object.") @XmlElement private String value; @ScimAttribute(mutability = Mutability.READ_ONLY, description = "displayName of the object.") @XmlElement private String displayName; } @ScimAttribute(returned = Returned.ALWAYS) @XmlElement private String valueAlways; @ScimAttribute(returned = Returned.DEFAULT) @XmlElement private String valueDefault; @ScimAttribute(returned = Returned.NEVER) @XmlElement private String valueNever; @ScimAttribute(returned = Returned.REQUEST) @XmlElement private String valueRequest; @ScimAttribute(returned = Returned.REQUEST) @XmlElement private ComplexObject valueComplex; @ScimAttribute @XmlElement private List<String> list; @ScimAttribute @XmlElement private List<Order> enumList; @ScimAttribute @XmlElement private Subobject subobject; @Override public String getUrn() { return URN; } }
4,316
0
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/test/java/org/apache/directory/scim/core/utility/Subobject.java
/* * 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 * 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.directory.scim.core.utility; import jakarta.xml.bind.annotation.XmlElement; import lombok.Data; import org.apache.directory.scim.spec.annotation.ScimAttribute; import java.io.Serializable; import java.util.List; @Data public class Subobject implements Serializable { private static final long serialVersionUID = -8081556701833520316L; @ScimAttribute @XmlElement private String string1; @ScimAttribute @XmlElement private String string2; @ScimAttribute @XmlElement private Boolean boolean1; @ScimAttribute @XmlElement private Boolean boolean2; @ScimAttribute @XmlElement private List<String> list1; @ScimAttribute @XmlElement private List<String> list2; }
4,317
0
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/repository/PrioritySortingComparator.java
/* * 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 * 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.directory.scim.core.repository; import java.io.Serializable; import java.util.Comparator; import java.util.Set; import org.apache.directory.scim.spec.resources.TypedAttribute; class PrioritySortingComparator implements Comparator<Object>, Serializable { private static final long serialVersionUID = -8759531575215428525L; private final Set<Object> priorities; public PrioritySortingComparator(Set<Object> priorities) { this.priorities = priorities; } @Override public int compare(Object o1, Object o2) { if (o1 == null) { return -1; } if (o2 == null) { return 1; } Comparable c1 = getComparableValue(o1); Comparable c2 = getComparableValue(o2); boolean o1Priority = priorities.contains(c1); boolean o2Priority = priorities.contains(c2); if (o1Priority == o2Priority) { return c1.compareTo(c2); } else { return o1Priority ? -1 : 1; } } public static Comparable getComparableValue(Object obj) { if (obj instanceof TypedAttribute) { TypedAttribute typed = (TypedAttribute) obj; return typed.getType(); } else if (obj instanceof Comparable) { return (Comparable) obj; } else { return obj.toString(); } } }
4,318
0
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/repository/RepositoryRegistry.java
/* * 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 * 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.directory.scim.core.repository; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.apache.directory.scim.spec.exception.ScimResourceInvalidException; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.resources.ScimResource; import org.apache.directory.scim.core.schema.SchemaRegistry; import java.util.HashMap; import java.util.List; import java.util.Map; @Data @Slf4j public class RepositoryRegistry { private SchemaRegistry schemaRegistry; private Map<Class<? extends ScimResource>, Repository<? extends ScimResource>> repositoryMap = new HashMap<>(); public RepositoryRegistry() { // CDI } public RepositoryRegistry(SchemaRegistry schemaRegistry) { this.schemaRegistry = schemaRegistry; } public RepositoryRegistry(SchemaRegistry schemaRegistry, List<Repository<? extends ScimResource>> scimRepositories) { this.schemaRegistry = schemaRegistry; scimRepositories.stream() .map(repository -> (Repository<ScimResource>) repository) .forEach(repository -> { try { registerRepository(repository.getResourceClass(), repository); } catch (InvalidRepositoryException e) { throw new ScimResourceInvalidException("Failed to register repository " + repository.getClass() + " for ScimResource type " + repository.getResourceClass(), e); } }); } public synchronized <T extends ScimResource> void registerRepository(Class<T> clazz, Repository<T> repository) throws InvalidRepositoryException { List<Class<? extends ScimExtension>> extensionList = repository.getExtensionList(); log.debug("Calling addSchema on the base class: {}", clazz); schemaRegistry.addSchema(clazz, extensionList); repositoryMap.put(clazz, repository); } @SuppressWarnings("unchecked") public <T extends ScimResource> Repository<T> getRepository(Class<T> clazz) { return (Repository<T>) repositoryMap.get(clazz); } }
4,319
0
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/repository/Repository.java
/* * 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 * 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.directory.scim.core.repository; import java.util.Collections; import java.util.List; import org.apache.directory.scim.spec.exception.ResourceException; import org.apache.directory.scim.spec.filter.FilterResponse; import org.apache.directory.scim.spec.filter.Filter; import org.apache.directory.scim.spec.filter.PageRequest; import org.apache.directory.scim.spec.filter.SortRequest; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.resources.ScimResource; /** * Defines the interface between the SCIM protocol implementation and the * Repository implementation for type T. * * @author Chris Harm &lt;crh5255@psu.edu&gt; * * @param <T> a SCIM ResourceType that extends ScimResource */ public interface Repository<T extends ScimResource> { /** * Returns the type of ScimResource this repository manages. * @return The type of resource this repository manages. */ Class<T> getResourceClass(); /** * Allows the SCIM server's REST implementation to create a resource via * a POST to a valid end-point. * * @param resource The ScimResource to create and persist. * @return The newly created ScimResource. * @throws ResourceException When the ScimResource cannot be * created. */ T create(T resource) throws ResourceException; /** * Allows the SCIM server's REST implementation to update and existing * resource via a PUT to a valid end-point. * * @param updateRequest The ScimResource to update and persist. * @return The newly updated ScimResource. * @throws ResourceException When the ScimResource cannot be * updated. */ T update(UpdateRequest<T> updateRequest) throws ResourceException; /** * Retrieves the ScimResource associated with the provided identifier. * @param id The identifier of the target ScimResource. * @return The requested ScimResource. * @throws ResourceException When the ScimResource cannot be * retrieved. */ T get(String id) throws ResourceException; /** * Finds and retrieves all ScimResource objects known to the persistence * layer that match the criteria specified by the passed Filter. The results * may be truncated by the scope specified by the passed PageRequest and * the order of the returned resources may be controlled by the passed * SortRequest. * * @param filter The filter that determines the ScimResources that will be * part of the ResultList * @param pageRequest For paged requests, this object specifies the start * index and number of ScimResources that should be returned. * @param sortRequest Specifies which fields the returned ScimResources * should be sorted by and whether the sort order is ascending or * descending. * @return A list of the ScimResources that pass the filter criteria, * truncated to match the requested "page" and sorted according * to the provided requirements. * @throws ResourceException If one or more ScimResources * cannot be retrieved. */ FilterResponse<T> find(Filter filter, PageRequest pageRequest, SortRequest sortRequest) throws ResourceException; /** * Deletes the ScimResource with the provided identifier (if it exists). * This interface makes no distinction between hard and soft deletes but * rather leaves that to the designer of the persistence layer. * * @param id The ScimResource's identifier. * @throws ResourceException When the specified ScimResource * cannot be deleted. */ void delete(String id) throws ResourceException; /** * Returns a list of the SCIM Extensions that this repository considers to be * associated with the ScimResource of type T. * * @return A list of ScimExtension classes. * @throws InvalidRepositoryException If the repository cannot return * the appropriate list. */ default List<Class<? extends ScimExtension>> getExtensionList() throws InvalidRepositoryException { return Collections.emptyList(); } }
4,320
0
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/repository/PatchHandlerImpl.java
/* * 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 * 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.directory.scim.core.repository; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.apache.directory.scim.core.json.ObjectMapperFactory; import org.apache.directory.scim.core.schema.SchemaRegistry; import org.apache.directory.scim.spec.exception.MutabilityException; import org.apache.directory.scim.spec.exception.UnsupportedFilterException; import org.apache.directory.scim.spec.filter.AttributeComparisonExpression; import org.apache.directory.scim.spec.filter.FilterExpressions; import org.apache.directory.scim.spec.filter.FilterParseException; import org.apache.directory.scim.spec.filter.ValuePathExpression; import org.apache.directory.scim.spec.filter.attribute.AttributeReference; import org.apache.directory.scim.spec.patch.PatchOperation; import org.apache.directory.scim.spec.patch.PatchOperationPath; import org.apache.directory.scim.spec.resources.ScimResource; import org.apache.directory.scim.spec.schema.Schema; import org.apache.directory.scim.spec.schema.Schema.Attribute; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; import static java.util.stream.Collectors.toList; /** * The default implementation of a PatchHandler that applies PatchOperations by walking an map equivalent * of ScimResource. */ @SuppressWarnings("unchecked") @Slf4j public class PatchHandlerImpl implements PatchHandler { public static final String PRIMARY = "primary"; private static final TypeReference<Map<String, Object>> MAP_TYPE = new TypeReference<>() {}; private final Map<PatchOperation.Type, PatchOperationHandler> patchOperationHandlers = Map.of( PatchOperation.Type.ADD, new AddOperationHandler(), PatchOperation.Type.REPLACE, new ReplaceOperationHandler(), PatchOperation.Type.REMOVE, new RemoveOperationHandler() ); private final ObjectMapper objectMapper; private final SchemaRegistry schemaRegistry; public PatchHandlerImpl(SchemaRegistry schemaRegistry) { this.schemaRegistry = schemaRegistry; this.objectMapper = ObjectMapperFactory.createObjectMapper(this.schemaRegistry); } @Override public <T extends ScimResource> T apply(final T original, final List<PatchOperation> patchOperations) { if (original == null) { throw new UnsupportedFilterException("Original resource is null. Cannot apply patch."); } if (patchOperations == null) { throw new UnsupportedFilterException("patchOperations is null. Cannot apply patch."); } Map<String, Object> sourceAsMap = objectAsMap(original); for (PatchOperation patchOperation : patchOperations) { if (patchOperation.getPath() == null) { if (!(patchOperation.getValue() instanceof Map)) { throw new UnsupportedFilterException("Cannot apply patch. value is required"); } Map<String, Object> properties = (Map<String, Object>) patchOperation.getValue(); for (Map.Entry<String, Object> entry : properties.entrySet()) { // convert SCIM patch to RFC-6902 patch PatchOperation newPatchOperation = new PatchOperation(); newPatchOperation.setOperation(patchOperation.getOperation()); newPatchOperation.setPath(tryGetOperationPath(entry.getKey())); newPatchOperation.setValue(entry.getValue()); apply(original, sourceAsMap, newPatchOperation); } } else { apply(original, sourceAsMap, patchOperation); } } return (T) objectMapper.convertValue(sourceAsMap, original.getClass()); } private <T extends ScimResource> void apply(T source, Map<String, Object> sourceAsMap, final PatchOperation patchOperation) { final ValuePathExpression valuePathExpression = valuePathExpression(patchOperation); final AttributeReference attributeReference = attributeReference(valuePathExpression); PatchOperationHandler patchOperationHandler = patchOperationHandlers.get(patchOperation.getOperation()); // if the attribute has a URN, assume it's an extension that URN does not match the baseUrn if (attributeReference.hasUrn() && !attributeReference.getUrn().equals(source.getBaseUrn())) { Schema schema = this.schemaRegistry.getSchema(attributeReference.getUrn()); Attribute attribute = schema.getAttribute(attributeReference.getAttributeName()); checkMutability(schema.getAttributeFromPath(attributeReference.getFullAttributeName())); patchOperationHandler.applyExtensionValue(source, sourceAsMap, schema, attribute, valuePathExpression, attributeReference.getUrn(), patchOperation.getValue()); } else { Schema schema = this.schemaRegistry.getSchema(source.getBaseUrn()); Attribute attribute = schema.getAttribute(attributeReference.getAttributeName()); checkMutability(schema.getAttributeFromPath(attributeReference.getFullAttributeName())); patchOperationHandler.applyValue(source, sourceAsMap, schema, attribute, valuePathExpression, patchOperation.getValue()); } } private PatchOperationPath tryGetOperationPath(String key) { try { return new PatchOperationPath(key); } catch (FilterParseException e) { log.warn("Parsing path failed with exception.", e); throw new UnsupportedFilterException("Cannot parse path expression: " + e.getMessage()); } } private Map<String, Object> objectAsMap(final Object object) { return objectMapper.convertValue(object, MAP_TYPE); } public static ValuePathExpression valuePathExpression(final PatchOperation operation) { return Optional.ofNullable(operation.getPath()) .map(PatchOperationPath::getValuePathExpression) .orElseThrow(() -> new UnsupportedFilterException("Patch operation must have a value path expression")); } public static AttributeReference attributeReference(final ValuePathExpression expression) { return Optional.ofNullable(expression.getAttributePath()) .orElseThrow(() -> new UnsupportedFilterException("Patch operation must have an expression with a valid attribute path")); } private static void checkMutability(Attribute attribute) throws MutabilityException { if (attribute.getMutability().equals(Attribute.Mutability.READ_ONLY)) { String message = "Can not update a read-only attribute '" + attribute.getName() + "'"; log.error(message); throw new MutabilityException(message); } } private static void checkMutability(Attribute attribute, Object currentValue) throws MutabilityException { checkMutability(attribute); if (attribute.getMutability().equals(Attribute.Mutability.IMMUTABLE) && currentValue != null) { String message = "Can not update a immutable attribute that contains a value '" + attribute.getName() + "'"; log.error(message); throw new MutabilityException(message); } } private static void checkPrimary(String subAttributeName, Collection<Map<String, Object>> items, Object value) { if (subAttributeName.equals(PRIMARY) && value.equals(true)) { // reset all other values with primary -> false items.forEach(item -> { if (item.containsKey(PRIMARY)) { item.put(PRIMARY, false); } }); } } private interface PatchOperationHandler { default <T extends ScimResource> void applyValue(final T source, Map<String, Object> sourceAsMap, Schema schema, Attribute attribute, ValuePathExpression valuePathExpression, Object value) { if (attribute.isMultiValued()) { if (valuePathExpression.getAttributeExpression() != null) { applyMultiValue(source, sourceAsMap, schema, attribute, valuePathExpression, value); } else { this.applyMultiValue(source, sourceAsMap, schema, attribute, valuePathExpression.getAttributePath(), value); } } else { // no filter expression applySingleValue(sourceAsMap, attribute, valuePathExpression.getAttributePath(), value); } } default <T extends ScimResource> void applyExtensionValue(final T source, Map<String, Object> sourceAsMap, Schema schema, Attribute attribute, ValuePathExpression valuePathExpression, String urn, Object value) { Map<String, Object> data = (Map<String, Object>) sourceAsMap.get(urn); if (attribute.isMultiValued()) { if (valuePathExpression.getAttributeExpression() != null) { this.applyMultiValue(source, data, schema, attribute, valuePathExpression, value); } else { this.applyMultiValue(source, data, schema, attribute, valuePathExpression.getAttributePath(), value); } } else { this.applySingleValue(data, attribute, valuePathExpression.getAttributePath(), value); } } void applySingleValue(Map<String, Object> sourceAsMap, Attribute attribute, AttributeReference attributeReference, Object value); <T extends ScimResource> void applyMultiValue(final T source, Map<String, Object> sourceAsMap, Schema schema, Attribute attribute, AttributeReference attributeReference, Object value); <T extends ScimResource> void applyMultiValue(final T source, Map<String, Object> sourceAsMap, Schema schema, Attribute attribute, ValuePathExpression valuePathExpression, Object value); } private static class AddOperationHandler implements PatchOperationHandler { @Override public <T extends ScimResource> void applyExtensionValue(T source, Map<String, Object> sourceAsMap, Schema schema, Attribute attribute, ValuePathExpression valuePathExpression, String urn, Object value) { // add the extension URN Collection<String> schemas = (Collection<String>) sourceAsMap.get("schemas"); schemas.add(urn); // if the extension object does not yet exist, create it if (!sourceAsMap.containsKey(urn)) { sourceAsMap.put(urn, new HashMap<>()); } PatchOperationHandler.super.applyExtensionValue(source, sourceAsMap, schema, attribute, valuePathExpression, urn, value); } @Override public void applySingleValue(Map<String, Object> sourceAsMap, Attribute attribute, AttributeReference attributeReference, Object value) { String attributeName = attribute.getName(); checkMutability(attribute, sourceAsMap.get(attributeName)); if (attributeReference.hasSubAttribute()) { Map<String, Object> parentValue = (Map<String, Object>) sourceAsMap.getOrDefault(attributeName, new HashMap<String, Object>()); String subAttributeName = attributeReference.getSubAttributeName(); checkMutability(attribute.getAttribute(subAttributeName), parentValue.get(subAttributeName)); parentValue.put(subAttributeName, value); sourceAsMap.put(attributeName, parentValue); } else { sourceAsMap.put(attributeName, value); } } @Override public <T extends ScimResource> void applyMultiValue(T source, Map<String, Object> sourceAsMap, Schema schema, Attribute attribute, AttributeReference attributeReference, Object value) { Collection<Object> items = (Collection<Object>) sourceAsMap.get(attributeReference.getAttributeName()); checkMutability(attribute, items); if (items == null) { items = new ArrayList<>(); } if (value instanceof Collection) { items.addAll((Collection<Object>) value); } else { items.add(value); } sourceAsMap.put(attributeReference.getAttributeName(), items); } @Override public <T extends ScimResource> void applyMultiValue(T source, Map<String, Object> sourceAsMap, Schema schema, Attribute attribute, ValuePathExpression valuePathExpression, Object value) { String attributeName = valuePathExpression.getAttributePath().getAttributeName(); if (!valuePathExpression.getAttributePath().hasSubAttribute()) { throw new UnsupportedFilterException("Invalid filter, expecting patch filter with expression to have a sub-attribute."); } // apply expression filter Collection<Map<String, Object>> items = (Collection<Map<String, Object>>) sourceAsMap.getOrDefault(attributeName, new ArrayList<Map<String, Object>>()); Predicate<Object> pred = FilterExpressions.inMemoryMap(valuePathExpression.getAttributeExpression(), schema); String subAttributeName = valuePathExpression.getAttributePath().getSubAttributeName(); boolean matchFound = false; for (Map<String, Object> item : items) { if (pred.test(item)) { matchFound = true; checkMutability(attribute, item.get(subAttributeName)); checkPrimary(subAttributeName, items, value); item.put(subAttributeName, value); } } // if the value was not added to an existing item, create a new value and add the patch value and the expression // values for example in the expression `emails[type eq "work"].value` with a patch value of `foo@example.com` // the map will contain `type: "work", value: "foo@example.com"` if (!matchFound) { if (!(valuePathExpression.getAttributeExpression() instanceof AttributeComparisonExpression)) { throw new UnsupportedFilterException("Attribute cannot be added, only comparison expressions are supported when the existing item does not exist."); } AttributeComparisonExpression comparisonExpression = (AttributeComparisonExpression) valuePathExpression.getAttributeExpression(); checkPrimary(subAttributeName, items, value); // Add a new mutable map items.add(new HashMap<>(Map.of( comparisonExpression.getAttributePath().getSubAttributeName(), comparisonExpression.getCompareValue(), subAttributeName, value))); } sourceAsMap.put(attributeName, items); } } private static class ReplaceOperationHandler implements PatchOperationHandler { @Override public void applySingleValue(Map<String, Object> sourceAsMap, Attribute attribute, AttributeReference attributeReference, Object value) { if (attributeReference.hasSubAttribute()) { Map<String, Object> parentValue = (Map<String, Object>) sourceAsMap.get(attributeReference.getAttributeName()); String subAttributeName = attributeReference.getSubAttributeName(); checkMutability(attribute.getAttribute(subAttributeName), parentValue.get(subAttributeName)); parentValue.put(subAttributeName, value); } else { checkMutability(attribute, sourceAsMap.get(attribute.getName())); sourceAsMap.put(attribute.getName(), value); } } @Override public <T extends ScimResource> void applyMultiValue(T source, Map<String, Object> sourceAsMap, Schema schema, Attribute attribute, AttributeReference attributeReference, Object value) { checkMutability(attribute, sourceAsMap.get(attribute.getName())); // replace the collection sourceAsMap.put(attribute.getName(), value); } @Override public <T extends ScimResource> void applyMultiValue(T source, Map<String, Object> sourceAsMap, Schema schema, Attribute attribute, ValuePathExpression valuePathExpression, Object value) { String attributeName = attribute.getName(); checkMutability(attribute, sourceAsMap.get(attributeName)); // apply expression filter Collection<Map<String, Object>> items = (Collection<Map<String, Object>>) sourceAsMap.get(attributeName); Predicate<Object> pred = FilterExpressions.inMemoryMap(valuePathExpression.getAttributeExpression(), schema); Collection<Object> updatedCollection = items.stream() .map(item -> { // find items that need to be updated if (pred.test(item)) { String subAttributeName = valuePathExpression.getAttributePath().getSubAttributeName(); // if there is a sub-attribute set it, otherwise replace the whole item if (item.containsKey(subAttributeName)) { checkMutability(attribute.getAttribute(subAttributeName), item.get(subAttributeName)); checkPrimary(subAttributeName, items, value); item.put(subAttributeName, value); } else { item = (Map<String, Object>) value; } } return item; }).collect(toList()); sourceAsMap.put(attribute.getName(), updatedCollection); } } private static class RemoveOperationHandler implements PatchOperationHandler { @Override public void applySingleValue(Map<String, Object> sourceAsMap, Attribute attribute, AttributeReference attributeReference, Object value) { if (attributeReference.hasSubAttribute()) { Map<String, Object> child = (Map<String, Object>) sourceAsMap.get(attributeReference.getAttributeName()); String subAttributeName = attributeReference.getSubAttributeName(); checkMutability(attribute.getAttribute(subAttributeName), child.get(subAttributeName)); child.remove(attributeReference.getSubAttributeName()); } else { checkMutability(attribute, sourceAsMap.get(attributeReference.getAttributeName())); sourceAsMap.remove(attributeReference.getAttributeName()); } } @Override public <T extends ScimResource> void applyMultiValue(T source, Map<String, Object> sourceAsMap, Schema schema, Attribute attribute, AttributeReference attributeReference, Object value) { checkMutability(attribute, sourceAsMap.get(attribute.getName())); // remove the collection sourceAsMap.remove(attribute.getName()); } @Override public <T extends ScimResource> void applyMultiValue(T source, Map<String, Object> sourceAsMap, Schema schema, Attribute attribute, ValuePathExpression valuePathExpression, Object value) { AttributeReference attributeReference = valuePathExpression.getAttributePath(); Collection<Map<String, Object>> items = (Collection<Map<String, Object>>) sourceAsMap.get(attributeReference.getAttributeName()); Predicate<Object> pred = FilterExpressions.inMemoryMap(valuePathExpression.getAttributeExpression(), schema); // if there is a sub-attribute in the filter, only that sub-attribute is removed, otherwise the whole item is // removed from the collection if(attributeReference.hasSubAttribute()) { items.forEach(item -> { if (pred.test(item)) { String subAttributeName = attributeReference.getSubAttributeName(); checkMutability(attribute.getAttribute(subAttributeName), item.get(subAttributeName)); item.remove(subAttributeName); } }); } else { // remove any items that match for (Iterator<Map<String, Object>> iter = items.iterator(); iter.hasNext();) { Map<String, Object> item = iter.next(); if (pred.test(item)) { checkMutability(attribute, item); iter.remove(); } } } } } }
4,321
0
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/repository/SelfIdResolver.java
/* * 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 * 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.directory.scim.core.repository; import org.apache.directory.scim.spec.exception.ResourceException; import java.security.Principal; public interface SelfIdResolver { String resolveToInternalId(Principal principal) throws ResourceException; }
4,322
0
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/repository/InvalidRepositoryException.java
/* * 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 * 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.directory.scim.core.repository; public class InvalidRepositoryException extends Exception { public InvalidRepositoryException(String message) { super(message); } }
4,323
0
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/repository/PatchHandler.java
/* * 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 * 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.directory.scim.core.repository; import org.apache.directory.scim.spec.exception.UnsupportedFilterException; import org.apache.directory.scim.spec.exception.MutabilityException; import org.apache.directory.scim.spec.patch.PatchOperation; import org.apache.directory.scim.spec.resources.ScimResource; import java.util.List; /** * A PatchHandler applies PatchOperations to a ScimResource. PatchOperations are a payload in a PATCH REST request. */ public interface PatchHandler { /** * Applies patch operations to a ScimResource. * * @param original The source ScimResource to apply patches to. * @param patchOperations The list of patch operations to apply. * @return An updated ScimResource with all patches applied * @param <T> The type of ScimResource. * @throws UnsupportedFilterException if the patch operations are invalid. * @throws MutabilityException if an attribute is not allowed to be updated. */ <T extends ScimResource> T apply(final T original, final List<PatchOperation> patchOperations); }
4,324
0
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/repository/UpdateRequest.java
/* * 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 * 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.directory.scim.core.repository; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.BooleanNode; import com.fasterxml.jackson.databind.node.DoubleNode; import com.fasterxml.jackson.databind.node.FloatNode; import com.fasterxml.jackson.databind.node.IntNode; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.POJONode; import com.fasterxml.jackson.databind.node.TextNode; import com.flipkart.zjsonpatch.DiffFlags; import com.flipkart.zjsonpatch.JsonDiff; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import lombok.extern.slf4j.Slf4j; import org.apache.directory.scim.core.json.ObjectMapperFactory; import org.apache.directory.scim.core.schema.SchemaRegistry; import org.apache.directory.scim.spec.filter.*; import org.apache.directory.scim.spec.filter.attribute.AttributeReference; import org.apache.directory.scim.spec.patch.PatchOperation; import org.apache.directory.scim.spec.patch.PatchOperation.Type; import org.apache.directory.scim.spec.patch.PatchOperationPath; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.resources.ScimResource; import org.apache.directory.scim.spec.resources.TypedAttribute; import org.apache.directory.scim.spec.schema.AttributeContainer; import org.apache.directory.scim.spec.schema.Schema; import org.apache.directory.scim.spec.schema.Schema.Attribute; import java.util.*; import java.util.stream.Collectors; @Slf4j @EqualsAndHashCode @ToString public class UpdateRequest<T extends ScimResource> { private static final String OPERATION = "op"; private static final String PATH = "path"; private static final String VALUE = "value"; // Create a Jackson ObjectMapper that reads JaxB annotations private final ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper(); @Getter private String id; private T resource; @Getter private T original; private List<PatchOperation> patchOperations; private boolean initialized = false; private Schema schema; private PatchHandler patchHandler; private SchemaRegistry schemaRegistry; private Map<Attribute, Integer> addRemoveOffsetMap = new HashMap<>(); public UpdateRequest(SchemaRegistry schemaRegistry) { this.schemaRegistry = schemaRegistry; } public UpdateRequest(String id, T original, T resource, SchemaRegistry schemaRegistry) { this(schemaRegistry); this.id = id; this.original = original; this.resource = resource; this.patchHandler = new PatchHandlerImpl(schemaRegistry); this.schema = schemaRegistry.getSchema(original.getBaseUrn()); initialized = true; } public UpdateRequest(String id, T original, List<PatchOperation> patchOperations, SchemaRegistry schemaRegistry) { this(schemaRegistry); this.id = id; this.original = original; this.patchOperations = patchOperations; this.patchHandler = new PatchHandlerImpl(schemaRegistry); this.schema = schemaRegistry.getSchema(original.getBaseUrn()); initialized = true; } public T getResource() { if (!initialized) { throw new IllegalStateException("UpdateRequest was not initialized"); } if (resource == null) { this.resource = this.patchHandler.apply(this.original, this.patchOperations); } return this.resource; } public List<PatchOperation> getPatchOperations() { if (!initialized) { throw new IllegalStateException("UpdateRequest was not initialized"); } if (patchOperations == null) { try { patchOperations = createPatchOperations(); } catch (IllegalArgumentException | IllegalAccessException | JsonProcessingException e) { throw new IllegalStateException("Error creating the patch list", e); } } return patchOperations; } private void sortMultiValuedCollections(Object obj1, Object obj2, AttributeContainer ac) throws IllegalArgumentException { for (Attribute attribute : ac.getAttributes()) { Schema.AttributeAccessor accessor = attribute.getAccessor(); if (attribute.isMultiValued()) { @SuppressWarnings("unchecked") List<Object> collection1 = obj1 != null ? (List<Object>) accessor.get(obj1) : null; @SuppressWarnings("unchecked") List<Object> collection2 = obj2 != null ? (List<Object>) accessor.get(obj2) : null; Set<Object> priorities = findCommonElements(collection1, collection2); PrioritySortingComparator prioritySortingComparator = new PrioritySortingComparator(priorities); if (collection1 != null) { Collections.sort(collection1, prioritySortingComparator); } if (collection2 != null) { Collections.sort(collection2, prioritySortingComparator); } } else if (attribute.getType() == Attribute.Type.COMPLEX) { Object nextObj1 = obj1 != null ? accessor.get(obj1) : null; Object nextObj2 = obj2 != null ? accessor.get(obj2) : null; sortMultiValuedCollections(nextObj1, nextObj2, attribute); } } } private Set<Object> findCommonElements(List<Object> list1, List<Object> list2) { if (list1 == null || list2 == null) { return Collections.emptySet(); } Set<Object> set1 = new HashSet<>(list1); Set<Object> set2 = new HashSet<>(list2); set1 = set1.stream().map(PrioritySortingComparator::getComparableValue).collect(Collectors.toSet()); set2 = set2.stream().map(PrioritySortingComparator::getComparableValue).collect(Collectors.toSet()); set1.retainAll(set2); return set1; } /** * There is a know issue with the diffing tool that the tool will attempt to move empty arrays. By * nulling out the empty arrays during comparison, this will prevent that error from occurring. Because * deleting requires the parent node * @param node Parent node. */ private static void nullEmptyLists(JsonNode node) { List<String> objectsToDelete = new ArrayList<>(); if (node != null) { Iterator<Map.Entry<String, JsonNode>> children = node.fields(); while(children.hasNext()) { Map.Entry<String, JsonNode> child = children.next(); String name = child.getKey(); JsonNode childNode = child.getValue(); //Attempt to delete children before analyzing if (childNode.isContainerNode()) { nullEmptyLists(childNode); } if (childNode instanceof ArrayNode) { ArrayNode ar = (ArrayNode)childNode; if (ar.size() == 0) { objectsToDelete.add(name); } } } if (!objectsToDelete.isEmpty() && node instanceof ObjectNode) { ObjectNode on = (ObjectNode)node; for(String name : objectsToDelete) { on.remove(name); } } } } private List<PatchOperation> createPatchOperations() throws IllegalArgumentException, IllegalAccessException, JsonProcessingException { sortMultiValuedCollections(this.original, this.resource, schema); Map<String, ScimExtension> originalExtensions = this.original.getExtensions(); Map<String, ScimExtension> resourceExtensions = this.resource.getExtensions(); Set<String> keys = new HashSet<>(); keys.addAll(originalExtensions.keySet()); keys.addAll(resourceExtensions.keySet()); for(String key: keys) { Schema extSchema = schemaRegistry.getSchema(key); ScimExtension originalExtension = originalExtensions.get(key); ScimExtension resourceExtension = resourceExtensions.get(key); sortMultiValuedCollections(originalExtension, resourceExtension, extSchema); } JsonNode node1 = objectMapper.valueToTree(original); nullEmptyLists(node1); JsonNode node2 = objectMapper.valueToTree(resource); nullEmptyLists(node2); JsonNode differences = JsonDiff.asJson(node1, node2, DiffFlags.dontNormalizeOpIntoMoveAndCopy()); /* Commenting out debug statement to prevent PII from appearing in log ObjectWriter writer = objMapper.writerWithDefaultPrettyPrinter(); try { log.debug("Original: "+writer.writeValueAsString(node1)); log.debug("Resource: "+writer.writeValueAsString(node2)); } catch (IOException e) { }*/ /*try { log.debug("Differences: " + objMapper.writerWithDefaultPrettyPrinter().writeValueAsString(differences)); } catch (JsonProcessingException e) { log.debug("Unable to debug differences: ", e); }*/ List<PatchOperation> patchOps = convertToPatchOperations(differences); /*try { log.debug("Patch Ops: " + objMapper.writerWithDefaultPrettyPrinter().writeValueAsString(patchOps)); } catch (JsonProcessingException e) { log.debug("Unable to debug patch ops: ", e); }*/ return patchOps; } List<PatchOperation> convertToPatchOperations(JsonNode node) throws IllegalArgumentException, IllegalAccessException, JsonProcessingException { List<PatchOperation> operations = new ArrayList<>(); if (node == null) { return Collections.emptyList(); } if (!(node instanceof ArrayNode)) { throw new RuntimeException("Expecting an instance of a ArrayNode, but got: " + node.getClass()); } ArrayNode root = (ArrayNode) node; for (int i = 0; i < root.size(); i++) { ObjectNode patchNode = (ObjectNode) root.get(i); JsonNode operationNode = patchNode.get(OPERATION); JsonNode pathNode = patchNode.get(PATH); JsonNode valueNode = patchNode.get(VALUE); List<PatchOperation> nodeOperations = convertNodeToPatchOperations(operationNode.asText(), pathNode.asText(), valueNode); if (!nodeOperations.isEmpty()) { operations.addAll(nodeOperations); } } return operations; } private List<PatchOperation> convertNodeToPatchOperations(String operationNode, String diffPath, JsonNode valueNode) throws IllegalArgumentException, IllegalAccessException, JsonProcessingException { log.debug("convertNodeToPatchOperations: {} , {}", operationNode, diffPath); List<PatchOperation> operations = new ArrayList<>(); PatchOperation.Type patchOpType = PatchOperation.Type.valueOf(operationNode.toUpperCase(Locale.ROOT)); if (diffPath != null && diffPath.length() >= 1) { ParseData parseData = new ParseData(diffPath); if (parseData.pathParts.isEmpty()) { operations.add(handleExtensions(valueNode, patchOpType, parseData)); } else { operations.addAll(handleAttributes(valueNode, patchOpType, parseData)); } } return operations; } private PatchOperation handleExtensions(JsonNode valueNode, Type patchOpType, ParseData parseData) throws JsonProcessingException { PatchOperation operation = new PatchOperation(); operation.setOperation(patchOpType); AttributeReference attributeReference = new AttributeReference(parseData.pathUri, null); PatchOperationPath patchOperationPath = new PatchOperationPath(); ValuePathExpression valuePathExpression = new ValuePathExpression(attributeReference); patchOperationPath.setValuePathExpression(valuePathExpression); operation.setPath(patchOperationPath); operation.setValue(determineValue(patchOpType, valueNode, parseData)); return operation; } @SuppressWarnings("unchecked") private List<PatchOperation> handleAttributes(JsonNode valueNode, PatchOperation.Type patchOpType, ParseData parseData) throws IllegalAccessException, JsonProcessingException { log.trace("in handleAttributes"); List<PatchOperation> operations = new ArrayList<>(); List<String> attributeReferenceList = new ArrayList<>(); FilterExpression valueFilterExpression = null; List<String> subAttributes = new ArrayList<>(); boolean processingMultiValued = false; boolean processedMultiValued = false; boolean done = false; int i = 0; for (String pathPart : parseData.pathParts) { log.trace("path part: {}", pathPart); if (done) { throw new RuntimeException("Path should be done... Attribute not supported by the schema: " + pathPart); } else if (processingMultiValued) { parseData.traverseObjectsInArray(pathPart, patchOpType); if (!parseData.isLastIndex(i) || patchOpType != PatchOperation.Type.ADD) { if (parseData.originalObject instanceof TypedAttribute) { TypedAttribute typedAttribute = (TypedAttribute) parseData.originalObject; String type = typedAttribute.getType(); valueFilterExpression = new AttributeComparisonExpression(new AttributeReference("type"), CompareOperator.EQ, type); } else if (parseData.originalObject instanceof String || parseData.originalObject instanceof Number) { String toString = parseData.originalObject.toString(); valueFilterExpression = new AttributeComparisonExpression(new AttributeReference("value"), CompareOperator.EQ, toString); } else if(parseData.originalObject instanceof Enum) { Enum<?> tempEnum = (Enum<?>)parseData.originalObject; valueFilterExpression = new AttributeComparisonExpression(new AttributeReference("value"), CompareOperator.EQ, tempEnum.name()); } else { if (parseData.originalObject != null) { log.debug("Attribute: {} doesn't implement TypedAttribute, can't create ValueFilterExpression", parseData.originalObject.getClass()); } else { log.debug("Attribute: null doesn't implement TypedAttribute, can't create ValueFilterExpression"); } valueFilterExpression = new AttributeComparisonExpression(new AttributeReference("value"), CompareOperator.EQ, "?"); } processingMultiValued = false; processedMultiValued = true; } } else { Attribute attribute = parseData.ac.getAttribute(pathPart); if (attribute != null) { if (processedMultiValued) { subAttributes.add(pathPart); } else { log.debug("Adding {} to attributeReferenceList", pathPart); attributeReferenceList.add(pathPart); } parseData.traverseObjects(pathPart, attribute); if (patchOpType == Type.REPLACE && (parseData.resourceObject != null && parseData.resourceObject instanceof Collection && !((Collection<?>)parseData.resourceObject).isEmpty()) && (parseData.originalObject == null || (parseData.originalObject instanceof Collection && ((Collection<?>)parseData.originalObject).isEmpty()))) { patchOpType = Type.ADD; } if (attribute.isMultiValued()) { processingMultiValued = true; } else if (attribute.getType() != Attribute.Type.COMPLEX) { done = true; } } } ++i; } if (patchOpType == Type.REPLACE && (parseData.resourceObject == null || (parseData.resourceObject instanceof Collection && ((Collection<?>)parseData.resourceObject).isEmpty()))) { patchOpType = Type.REMOVE; valueNode = null; } if (patchOpType == Type.REPLACE && parseData.originalObject == null) { patchOpType = Type.ADD; } if (!attributeReferenceList.isEmpty()) { Object value = determineValue(patchOpType, valueNode, parseData); if (value != null && value instanceof ArrayList) { List<Object> objList = (List<Object>)value; if (!objList.isEmpty()) { Object firstElement = objList.get(0); if (firstElement instanceof ArrayList) { objList = (List<Object>) firstElement; } for (Object obj : objList) { PatchOperation operation = buildPatchOperation(patchOpType, parseData, attributeReferenceList, valueFilterExpression, subAttributes, obj); if (operation != null) { operations.add(operation); } } } } else { PatchOperation operation = buildPatchOperation(patchOpType, parseData, attributeReferenceList, valueFilterExpression, subAttributes, value); if (operation != null) { operations.add(operation); } } } return operations; } private PatchOperation buildPatchOperation(PatchOperation.Type patchOpType, ParseData parseData, List<String> attributeReferenceList, FilterExpression valueFilterExpression, List<String> subAttributes, Object value) { PatchOperation operation = new PatchOperation(); operation.setOperation(patchOpType); String attribute = attributeReferenceList.get(0); String subAttribute = attributeReferenceList.size() > 1 ? attributeReferenceList.get(1) : null; if (subAttribute == null && !subAttributes.isEmpty()) { subAttribute = subAttributes.get(0); } AttributeReference attributeReference = new AttributeReference(parseData.pathUri, attribute, subAttribute); PatchOperationPath patchOperationPath = new PatchOperationPath(); ValuePathExpression valuePathExpression = new ValuePathExpression(attributeReference, valueFilterExpression); patchOperationPath.setValuePathExpression(valuePathExpression); operation.setPath(patchOperationPath); operation.setValue(value); return operation; } private Object determineValue(PatchOperation.Type patchOpType, JsonNode valueNode, ParseData parseData) throws JsonProcessingException { if (patchOpType == PatchOperation.Type.REMOVE) { return null; } if (valueNode != null) { if (valueNode instanceof TextNode) { return valueNode.asText(); } else if (valueNode instanceof BooleanNode) { return valueNode.asBoolean(); } else if (valueNode instanceof DoubleNode || valueNode instanceof FloatNode) { return valueNode.asDouble(); } else if (valueNode instanceof IntNode) { return valueNode.asInt(); } else if (valueNode instanceof NullNode) { return null; } else if (valueNode instanceof ObjectNode) { return parseData.resourceObject; } else if (valueNode instanceof POJONode) { POJONode pojoNode = (POJONode) valueNode; return pojoNode.getPojo(); } else if (valueNode instanceof ArrayNode) { ArrayNode arrayNode = (ArrayNode) valueNode; List<Object> objectList = new ArrayList<>(); for(int i = 0; i < arrayNode.size(); i++) { Object subObject = determineValue(patchOpType, arrayNode.get(i), parseData); if (subObject != null) { objectList.add(subObject); } } return objectList; } } return null; } private class ParseData { List<String> pathParts; Object originalObject; Object resourceObject; AttributeContainer ac; String pathUri; public ParseData(String diffPath) { String path = diffPath.substring(1); pathParts = new ArrayList<>(Arrays.asList(path.split("/"))); // Extract namespace pathUri = null; String firstPathPart = pathParts.get(0); if (firstPathPart.contains(":")) { pathUri = firstPathPart; pathParts.remove(0); } if (pathUri != null) { ac = schemaRegistry.getSchema(pathUri); originalObject = original.getExtension(pathUri); resourceObject = resource.getExtension(pathUri); } else { ac = schema; originalObject = original; resourceObject = resource; } } public void traverseObjects(String pathPart, Attribute attribute) throws IllegalArgumentException, IllegalAccessException { originalObject = lookupAttribute(originalObject, ac, pathPart); resourceObject = lookupAttribute(resourceObject, ac, pathPart); ac = attribute; } public void traverseObjectsInArray(String pathPart, Type patchOpType) { int index = Integer.parseInt(pathPart); Attribute attr = (Attribute) ac; Integer addRemoveOffset = addRemoveOffsetMap.getOrDefault(attr, 0); switch (patchOpType) { case ADD: addRemoveOffsetMap.put(attr, addRemoveOffset - 1); break; case REMOVE: addRemoveOffsetMap.put(attr, addRemoveOffset + 1); break; case REPLACE: default: // Do Nothing break; } int newindex = index + addRemoveOffset; if (newindex < 0) { log.error("Attempting to retrieve a negative index:{} on pathPath: {}", newindex, pathPart); } originalObject = lookupIndexInArray(originalObject, newindex); resourceObject = lookupIndexInArray(resourceObject, index); } public boolean isLastIndex(int index) { int numPathParts = pathParts.size(); return index == (numPathParts - 1); } @SuppressWarnings("rawtypes") private Object lookupIndexInArray(Object object, int index) { if (!(object instanceof List)) { throw new RuntimeException("Unsupported collection type: " + object.getClass()); } List list = (List) object; if (index >= list.size()) { return null; } return list.get(index); } private Object lookupAttribute(Object object, AttributeContainer ac, String attributeName) throws IllegalArgumentException, IllegalAccessException { if (object == null) { return null; } Attribute attribute = ac.getAttribute(attributeName); return attribute.getAccessor().get(object); } } }
4,325
0
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/repository
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/repository/extensions/ProcessingExtension.java
/* * 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 * 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.directory.scim.core.repository.extensions; public interface ProcessingExtension { }
4,326
0
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/repository
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/repository/extensions/ClientFilterException.java
/* * 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 * 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.directory.scim.core.repository.extensions; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) public class ClientFilterException extends Exception { private static final long serialVersionUID = 3308947684934769952L; private final int status; public ClientFilterException(int statusCode, String message) { super(message); this.status = statusCode; } }
4,327
0
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/repository
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/repository/extensions/AttributeFilterExtension.java
/* * 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 * 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.directory.scim.core.repository.extensions; import org.apache.directory.scim.spec.filter.attribute.ScimRequestContext; import org.apache.directory.scim.spec.resources.ScimResource; public interface AttributeFilterExtension extends ProcessingExtension { ScimResource filterAttributes(ScimResource scimResource, ScimRequestContext scimRequestContext) throws ClientFilterException; }
4,328
0
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/repository
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/repository/annotations/ProcessingExtensions.java
/* * 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 * 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.directory.scim.core.repository.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface ProcessingExtensions { /** * An array of one or more {@link ExtendWith @ExtendWith} declarations. */ ScimProcessingExtension[] value(); }
4,329
0
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/repository
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/repository/annotations/ScimProcessingExtension.java
/* * 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 * 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.directory.scim.core.repository.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.apache.directory.scim.core.repository.extensions.ProcessingExtension; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Documented @Inherited @Repeatable(ProcessingExtensions.class) public @interface ScimProcessingExtension { Class<? extends ProcessingExtension >[] value(); }
4,330
0
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/schema/SchemaRegistry.java
/* * 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 * 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.directory.scim.core.schema; import java.io.Serializable; import java.util.*; import org.apache.directory.scim.spec.annotation.ScimExtensionType; import org.apache.directory.scim.spec.annotation.ScimResourceType; import org.apache.directory.scim.spec.exception.InvalidExtensionException; import org.apache.directory.scim.spec.exception.ScimResourceInvalidException; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.resources.ScimResource; import org.apache.directory.scim.spec.schema.ResourceType; import org.apache.directory.scim.spec.schema.Schema; import lombok.extern.slf4j.Slf4j; import org.apache.directory.scim.spec.schema.Schemas; @Slf4j public class SchemaRegistry implements Serializable { private static final long serialVersionUID = 2644269305703474835L; private final Map<String, Schema> schemaMap = new HashMap<>(); private final Map<String, Class<? extends ScimResource>> schemaUrnToScimResourceClass = new HashMap<>(); private final Map<String, Class<? extends ScimResource>> endpointToScimResourceClass = new HashMap<>(); private final Map<String, ResourceType> resourceTypeMap = new HashMap<>(); private final Map<Class<? extends ScimResource>, Map<String, Class<? extends ScimExtension>>> resourceExtensionsMap = new HashMap<>(); public Schema getSchema(String urn) { return schemaMap.get(urn); } public Set<String> getAllSchemaUrns() { return Collections.unmodifiableSet(schemaMap.keySet()); } public Collection<Schema> getAllSchemas() { return Collections.unmodifiableCollection(schemaMap.values()); } public Schema getBaseSchemaOfResourceType(String resourceType) { ResourceType rt = resourceTypeMap.get(resourceType); if (rt == null) { return null; } String schemaUrn = rt.getSchemaUrn(); return schemaMap.get(schemaUrn); } private void addSchema(Schema schema) { log.debug("Adding schema " + schema.getId() + " into the registry"); schemaMap.put(schema.getId(), schema); } public <T extends ScimResource> void addSchema(Class<T> clazz, List<Class<? extends ScimExtension>> extensionList) { ScimResourceType scimResourceType = clazz.getAnnotation(ScimResourceType.class); if (scimResourceType == null) { throw new ScimResourceInvalidException("Missing annotation: ScimResource must be annotated with @ScimResourceType."); } ResourceType resourceType = generateResourceType(scimResourceType, extensionList); String schemaUrn = scimResourceType.schema(); String endpoint = scimResourceType.endpoint(); addSchema(Schemas.schemaFor(clazz)); addScimResourceSchemaUrn(schemaUrn, clazz); addScimResourceEndPoint(endpoint, clazz); addResourceType(resourceType); if (extensionList != null) { for (Class<? extends ScimExtension> scimExtension : extensionList) { log.debug("Calling addSchema on an extension: " + scimExtension); addSchema(Schemas.schemaForExtension(scimExtension)); log.debug("Registering a extension of type: " + scimExtension); addExtension(clazz, scimExtension); } } } private <T extends ScimResource> void addScimResourceSchemaUrn(String schemaUrn, Class<T> scimResourceClass) { schemaUrnToScimResourceClass.put(schemaUrn, scimResourceClass); } private <T extends ScimResource> void addScimResourceEndPoint(String endpoint, Class<T> scimResourceClass) { endpointToScimResourceClass.put(endpoint, scimResourceClass); } public <T extends ScimResource> Class<T> getScimResourceClassFromEndpoint(String endpoint) { @SuppressWarnings("unchecked") Class<T> scimResourceClass = (Class<T>) endpointToScimResourceClass.get(endpoint); return scimResourceClass; } public <T extends ScimResource> Class<T> getScimResourceClass(String schemaUrn) { @SuppressWarnings("unchecked") Class<T> scimResourceClass = (Class<T>) schemaUrnToScimResourceClass.get(schemaUrn); return scimResourceClass; } public ResourceType getResourceType(String name) { return resourceTypeMap.get(name); } public Collection<ResourceType> getAllResourceTypes() { return Collections.unmodifiableCollection(resourceTypeMap.values()); } private void addResourceType(ResourceType resourceType) { resourceTypeMap.put(resourceType.getName(), resourceType); } public Class<? extends ScimExtension> getExtensionClass(Class<? extends ScimResource> resourceClass, String urn) { Class<? extends ScimExtension> extensionClass = null; if(resourceExtensionsMap.containsKey(resourceClass)) { Map<String, Class<? extends ScimExtension>> resourceMap = resourceExtensionsMap.get(resourceClass); if(resourceMap.containsKey(urn)) { extensionClass = resourceMap.get(urn); } } return extensionClass; } public void addExtension(Class<? extends ScimResource> resourceClass, Class<? extends ScimExtension> extensionClass) { ScimExtensionType[] se = extensionClass.getAnnotationsByType(ScimExtensionType.class); if (se.length != 1) { throw new InvalidExtensionException("Registered extensions must a single @ScimExtensionType annotation"); } String urn = se[0].id(); log.debug("Registering extension for URN: '{}' associated resource class: '{}' and extension class: '{}'", urn, resourceClass.getSimpleName(), extensionClass.getSimpleName() ); Map<String, Class<? extends ScimExtension>> resourceMap = resourceExtensionsMap.computeIfAbsent(resourceClass, k -> new HashMap<>()); if(!resourceMap.containsKey(urn)) { resourceMap.put(urn, extensionClass); } } private ResourceType generateResourceType(ScimResourceType scimResourceType, List<Class<? extends ScimExtension>> extensionList) throws InvalidExtensionException { ResourceType resourceType = new ResourceType(); resourceType.setDescription(scimResourceType.description()); resourceType.setId(scimResourceType.id()); resourceType.setName(scimResourceType.name()); resourceType.setEndpoint(scimResourceType.endpoint()); resourceType.setSchemaUrn(scimResourceType.schema()); if (extensionList != null) { List<ResourceType.SchemaExtensionConfiguration> extensionSchemaList = new ArrayList<>(); for (Class<? extends ScimExtension> se : extensionList) { ScimExtensionType extensionType = se.getAnnotation(ScimExtensionType.class); if (extensionType == null) { throw new InvalidExtensionException("Missing annotation: @ScimExtensionType on ScimExtensionL " + se.getSimpleName()); } ResourceType.SchemaExtensionConfiguration ext = new ResourceType.SchemaExtensionConfiguration(); ext.setRequired(extensionType.required()); ext.setSchemaUrn(extensionType.id()); extensionSchemaList.add(ext); } resourceType.setSchemaExtensions(extensionSchemaList); } return resourceType; } }
4,331
0
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/spi/ScimpleComponents.java
/* * 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 * 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.directory.scim.core.spi; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.context.Dependent; import jakarta.enterprise.event.Observes; import jakarta.enterprise.event.Startup; import jakarta.enterprise.inject.Instance; import jakarta.enterprise.inject.Produces; import org.apache.directory.scim.core.repository.Repository; import org.apache.directory.scim.core.repository.RepositoryRegistry; import org.apache.directory.scim.core.schema.SchemaRegistry; import org.apache.directory.scim.spec.resources.ScimResource; import java.util.stream.Collectors; @Dependent public class ScimpleComponents { @Produces @ApplicationScoped public SchemaRegistry schemaRegistry() { return new SchemaRegistry(); } @Produces @ApplicationScoped public RepositoryRegistry repositoryRegistry(SchemaRegistry schemaRegistry, Instance<Repository<? extends ScimResource>> repositoryInstances) { return new RepositoryRegistry(schemaRegistry, repositoryInstances.stream().collect(Collectors.toList())); } /* * Eagerly initialize the RepositoryRegistry bean on startup. */ public void startup(@Observes Startup startup, RepositoryRegistry repositoryRegistry) { repositoryRegistry.toString(); // call toString() to resolve real object from proxy } }
4,332
0
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/json/ObjectMapperFactory.java
/* * 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 * 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.directory.scim.core.json; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler; import com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.module.jakarta.xmlbind.JakartaXmlBindAnnotationIntrospector; import com.fasterxml.jackson.module.jakarta.xmlbind.JakartaXmlBindAnnotationModule; import org.apache.directory.scim.core.schema.SchemaRegistry; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.resources.ScimResource; import java.io.IOException; /** * Creates and configures an {@link ObjectMapper} used for {@code application/scim+json} parsing. */ public class ObjectMapperFactory { private final static ObjectMapper objectMapper = createObjectMapper(); /** * Returns an ObjectMapper configured for use with Jackson and Jakarta bindings. * This ObjectMapper does NOT unmarshal SCIM Extension values, use {@link #createObjectMapper(SchemaRegistry)} when * serializing REST response and requests. * @return an ObjectMapper configured for use with Jackson and Jakarta bindings. */ public static ObjectMapper getObjectMapper() { return objectMapper; } private static ObjectMapper createObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); AnnotationIntrospector pair = new AnnotationIntrospectorPair( new JakartaXmlBindAnnotationIntrospector(objectMapper.getTypeFactory()), new JacksonAnnotationIntrospector()); objectMapper.setAnnotationIntrospector(pair); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, true); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return objectMapper; } /** * Creates and configures an {@link ObjectMapper} SCIM Resource in REST request and responses {@code application/scim+json}. */ public static ObjectMapper createObjectMapper(SchemaRegistry schemaRegistry) { ObjectMapper objectMapper = createObjectMapper().copy(); objectMapper.registerModule(new JakartaXmlBindAnnotationModule()); objectMapper.registerModule(new ScimResourceModule(schemaRegistry)); return objectMapper; } static class ScimResourceModule extends SimpleModule { private static final long serialVersionUID = 6849840952304999849L; private final SchemaRegistry schemaRegistry; public ScimResourceModule(SchemaRegistry schemaRegistry) { super("scim-resources", Version.unknownVersion()); this.schemaRegistry = schemaRegistry; addDeserializer(ScimResource.class, new ScimResourceDeserializer(schemaRegistry)); } @Override public void setupModule(SetupContext context) { super.setupModule(context); context.addDeserializationProblemHandler(new UnknownPropertyHandler(schemaRegistry)); } } static class UnknownPropertyHandler extends DeserializationProblemHandler { private final SchemaRegistry schemaRegistry; UnknownPropertyHandler(SchemaRegistry schemaRegistry) { this.schemaRegistry = schemaRegistry; } @Override public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser p, JsonDeserializer<?> deserializer, Object beanOrClass, String propertyName) throws IOException { if (beanOrClass instanceof ScimResource) { ScimResource scimResource = (ScimResource) beanOrClass; Class<? extends ScimResource> resourceClass = scimResource.getClass(); Class<? extends ScimExtension> extensionClass = schemaRegistry.getExtensionClass(resourceClass, propertyName); if (extensionClass != null) { ScimExtension ext = ctxt.readPropertyValue(p, null, extensionClass); if (ext != null) { scimResource.addExtension(ext); } } } return super.handleUnknownProperty(ctxt, p, deserializer, beanOrClass, propertyName); } } }
4,333
0
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core
Create_ds/directory-scimple/scim-core/src/main/java/org/apache/directory/scim/core/json/ScimResourceDeserializer.java
/* * 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 * 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.directory.scim.core.json; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.node.ArrayNode; import org.apache.directory.scim.core.schema.SchemaRegistry; import org.apache.directory.scim.spec.resources.ScimResource; import java.io.IOException; import java.util.Objects; import java.util.stream.StreamSupport; public class ScimResourceDeserializer extends StdDeserializer<ScimResource> { private static final long serialVersionUID = -2125441391108866034L; private final SchemaRegistry schemaRegistry; public ScimResourceDeserializer(SchemaRegistry schemaRegistry) { super(ScimResource.class); this.schemaRegistry = schemaRegistry; } @Override public ScimResource deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { JsonLocation location = jsonParser.getCurrentLocation(); TreeNode node = jsonParser.getCodec().readTree(jsonParser); ArrayNode schemas = (ArrayNode) node.get("schemas"); Class<? extends ScimResource> scimResourceClass = StreamSupport.stream(schemas.spliterator(), false) .map(JsonNode::textValue) .map(schemaRegistry::getScimResourceClass) .filter(Objects::nonNull) .findFirst() .orElseThrow(() -> new JsonParseException(jsonParser, "Could not find a valid schema in: " + schemas + ", valid schemas are: " + schemaRegistry.getAllSchemaUrns(), location)); return jsonParser.getCodec().treeToValue(node, scimResourceClass); } }
4,334
0
Create_ds/directory-scimple/scim-server-examples/scim-server-quarkus/src/test/java/org/apache/directory/scim/example
Create_ds/directory-scimple/scim-server-examples/scim-server-quarkus/src/test/java/org/apache/directory/scim/example/quarkus/QuarkusServiceProviderConfigIT.java
/* * 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 * 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.directory.scim.example.quarkus; import io.quarkus.test.common.http.TestHTTPResource; import io.quarkus.test.junit.QuarkusIntegrationTest; import org.apache.directory.scim.compliance.tests.ServiceProviderConfigIT; import java.net.URI; /** * Wraps ServiceProviderConfigIT in a Quarkus friendly runner. */ @QuarkusIntegrationTest public class QuarkusServiceProviderConfigIT extends ServiceProviderConfigIT { @TestHTTPResource("/v2") URI uri; @Override protected URI uri() { return uri; } }
4,335
0
Create_ds/directory-scimple/scim-server-examples/scim-server-quarkus/src/test/java/org/apache/directory/scim/example
Create_ds/directory-scimple/scim-server-examples/scim-server-quarkus/src/test/java/org/apache/directory/scim/example/quarkus/QuarkusUsersIT.java
/* * 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 * 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.directory.scim.example.quarkus; import io.quarkus.test.common.http.TestHTTPResource; import io.quarkus.test.junit.QuarkusIntegrationTest; import org.apache.directory.scim.compliance.tests.UsersIT; import java.net.URI; /** * Wraps UsersIT in a Quarkus friendly runner. */ @QuarkusIntegrationTest public class QuarkusUsersIT extends UsersIT { @TestHTTPResource("/v2") URI uri; @Override protected URI uri() { return uri; } }
4,336
0
Create_ds/directory-scimple/scim-server-examples/scim-server-quarkus/src/test/java/org/apache/directory/scim/example
Create_ds/directory-scimple/scim-server-examples/scim-server-quarkus/src/test/java/org/apache/directory/scim/example/quarkus/QuarkusResourceTypesIT.java
/* * 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 * 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.directory.scim.example.quarkus; import io.quarkus.test.common.http.TestHTTPResource; import io.quarkus.test.junit.QuarkusIntegrationTest; import org.apache.directory.scim.compliance.tests.ResourceTypesIT; import java.net.URI; /** * Wraps ResourceTypesIT in a Quarkus friendly runner. */ @QuarkusIntegrationTest public class QuarkusResourceTypesIT extends ResourceTypesIT { @TestHTTPResource("/v2") URI uri; @Override protected URI uri() { return uri; } }
4,337
0
Create_ds/directory-scimple/scim-server-examples/scim-server-quarkus/src/test/java/org/apache/directory/scim/example
Create_ds/directory-scimple/scim-server-examples/scim-server-quarkus/src/test/java/org/apache/directory/scim/example/quarkus/QuarkusSchemasIT.java
/* * 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 * 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.directory.scim.example.quarkus; import io.quarkus.test.common.http.TestHTTPResource; import io.quarkus.test.junit.QuarkusIntegrationTest; import org.apache.directory.scim.compliance.tests.SchemasIT; import java.net.URI; /** * Wraps SchemasIT in a Quarkus friendly runner. */ @QuarkusIntegrationTest public class QuarkusSchemasIT extends SchemasIT { @TestHTTPResource("/v2") URI uri; @Override protected URI uri() { return uri; } }
4,338
0
Create_ds/directory-scimple/scim-server-examples/scim-server-quarkus/src/test/java/org/apache/directory/scim/example
Create_ds/directory-scimple/scim-server-examples/scim-server-quarkus/src/test/java/org/apache/directory/scim/example/quarkus/QuarkusGroupsIT.java
/* * 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 * 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.directory.scim.example.quarkus; import io.quarkus.test.common.http.TestHTTPResource; import io.quarkus.test.junit.QuarkusIntegrationTest; import org.apache.directory.scim.compliance.tests.GroupsIT; import java.net.URI; /** * Wraps GroupsIT in a Quarkus friendly runner. */ @QuarkusIntegrationTest public class QuarkusGroupsIT extends GroupsIT { @TestHTTPResource("/v2") URI uri; @Override protected URI uri() { return uri; } }
4,339
0
Create_ds/directory-scimple/scim-server-examples/scim-server-quarkus/src/main/java/org/apache/directory/scim/example
Create_ds/directory-scimple/scim-server-examples/scim-server-quarkus/src/main/java/org/apache/directory/scim/example/quarkus/QuarkusApplication.java
/* * 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 * 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.directory.scim.example.quarkus; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Produces; import jakarta.ws.rs.ApplicationPath; import org.apache.directory.scim.server.configuration.ServerConfiguration; import java.util.Set; import jakarta.ws.rs.core.Application; import org.apache.directory.scim.server.rest.ScimResourceHelper; import static org.apache.directory.scim.spec.schema.ServiceProviderConfiguration.AuthenticationSchema.oauthBearer; @ApplicationPath("v2") @ApplicationScoped public class QuarkusApplication extends Application { @Override public Set<Class<?>> getClasses() { return ScimResourceHelper.scimpleFeatureAndResourceClasses(); } @Produces ServerConfiguration serverConfiguration() { return new ServerConfiguration() // Set any unique configuration bits .setId("scimple-quarkus-example") .setDocumentationUri("https://github.com/apache/directory-scimple") // set the auth scheme too .addAuthenticationSchema(oauthBearer()); } }
4,340
0
Create_ds/directory-scimple/scim-server-examples/scim-server-quarkus/src/main/java/org/apache/directory/scim/example/quarkus
Create_ds/directory-scimple/scim-server-examples/scim-server-quarkus/src/main/java/org/apache/directory/scim/example/quarkus/extensions/LuckyNumberExtension.java
/* * 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 * 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.directory.scim.example.quarkus.extensions; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import lombok.Data; import org.apache.directory.scim.spec.annotation.ScimAttribute; import org.apache.directory.scim.spec.annotation.ScimExtensionType; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.schema.Schema; /** * Allows a User's lucky number to be passed as part of the User's entry via * the SCIM protocol. * * @author Chris Harm &lt;crh5255@psu.edu&gt; */ @XmlRootElement( name = "LuckyNumberExtension", namespace = "http://www.psu.edu/schemas/psu-scim" ) @XmlAccessorType(XmlAccessType.NONE) @Data @ScimExtensionType(id = LuckyNumberExtension.SCHEMA_URN, description="Lucky Numbers", name="LuckyNumbers", required=true) public class LuckyNumberExtension implements ScimExtension { public static final String SCHEMA_URN = "urn:mem:params:scim:schemas:extension:LuckyNumberExtension"; @ScimAttribute(returned=Schema.Attribute.Returned.DEFAULT, required=true) @XmlElement private long luckyNumber; /** * Provides the URN associated with this extension which, as defined by the * SCIM specification is the extension's unique identifier. * * @return The extension's URN. */ @Override public String getUrn() { return SCHEMA_URN; } }
4,341
0
Create_ds/directory-scimple/scim-server-examples/scim-server-quarkus/src/main/java/org/apache/directory/scim/example/quarkus
Create_ds/directory-scimple/scim-server-examples/scim-server-quarkus/src/main/java/org/apache/directory/scim/example/quarkus/service/InMemorySelfResolverImpl.java
/* * 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 * 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.directory.scim.example.quarkus.service; import jakarta.enterprise.context.ApplicationScoped; import org.apache.directory.scim.server.exception.UnableToResolveIdResourceException; import org.apache.directory.scim.core.repository.SelfIdResolver; import java.security.Principal; import jakarta.ws.rs.core.Response.Status; @ApplicationScoped public class InMemorySelfResolverImpl implements SelfIdResolver { @Override public String resolveToInternalId(Principal principal) throws UnableToResolveIdResourceException { throw new UnableToResolveIdResourceException(Status.NOT_IMPLEMENTED, "Caller Principal not available"); } }
4,342
0
Create_ds/directory-scimple/scim-server-examples/scim-server-quarkus/src/main/java/org/apache/directory/scim/example/quarkus
Create_ds/directory-scimple/scim-server-examples/scim-server-quarkus/src/main/java/org/apache/directory/scim/example/quarkus/service/InMemoryGroupService.java
/* * 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 * 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.directory.scim.example.quarkus.service; import jakarta.annotation.PostConstruct; import jakarta.inject.Inject; import jakarta.ws.rs.core.Response; import org.apache.commons.lang3.StringUtils; import org.apache.directory.scim.server.exception.UnableToCreateResourceException; import org.apache.directory.scim.server.exception.UnableToUpdateResourceException; import org.apache.directory.scim.core.repository.Repository; import org.apache.directory.scim.core.repository.UpdateRequest; import org.apache.directory.scim.spec.filter.FilterExpressions; import org.apache.directory.scim.spec.filter.FilterResponse; import org.apache.directory.scim.spec.filter.Filter; import org.apache.directory.scim.spec.filter.PageRequest; import org.apache.directory.scim.spec.filter.SortRequest; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.resources.ScimGroup; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Named; import org.apache.directory.scim.core.schema.SchemaRegistry; @Named @ApplicationScoped public class InMemoryGroupService implements Repository<ScimGroup> { private final Map<String, ScimGroup> groups = new HashMap<>(); private SchemaRegistry schemaRegistry; @Inject public InMemoryGroupService(SchemaRegistry schemaRegistry) { this.schemaRegistry = schemaRegistry; } protected InMemoryGroupService() {} @PostConstruct public void init() { ScimGroup group = new ScimGroup(); group.setId(UUID.randomUUID().toString()); group.setDisplayName("example-group"); group.setExternalId("example-group"); groups.put(group.getId(), group); } @Override public Class<ScimGroup> getResourceClass() { return ScimGroup.class; } @Override public ScimGroup create(ScimGroup resource) throws UnableToCreateResourceException { String id = UUID.randomUUID().toString(); // if the external ID is not set, use the displayName instead if (StringUtils.isEmpty(resource.getExternalId())) { resource.setExternalId(resource.getDisplayName()); } // check to make sure the group doesn't already exist boolean existingGroupFound = groups.values().stream() .anyMatch(group -> resource.getExternalId().equals(group.getExternalId())); if (existingGroupFound) { // HTTP leaking into data layer throw new UnableToCreateResourceException(Response.Status.CONFLICT, "Group '" + resource.getExternalId() + "' already exists."); } resource.setId(id); groups.put(id, resource); return resource; } @Override public ScimGroup update(UpdateRequest<ScimGroup> updateRequest) throws UnableToUpdateResourceException { String id = updateRequest.getId(); ScimGroup resource = updateRequest.getResource(); groups.put(id, resource); return resource; } @Override public ScimGroup get(String id) { return groups.get(id); } @Override public void delete(String id) { groups.remove(id); } @Override public FilterResponse<ScimGroup> find(Filter filter, PageRequest pageRequest, SortRequest sortRequest) { long count = pageRequest.getCount() != null ? pageRequest.getCount() : groups.size(); long startIndex = pageRequest.getStartIndex() != null ? pageRequest.getStartIndex() - 1 // SCIM is 1-based indexed : 0; List<ScimGroup> result = groups.values().stream() .skip(startIndex) .limit(count) .filter(FilterExpressions.inMemory(filter, schemaRegistry.getSchema(ScimGroup.SCHEMA_URI))) .collect(Collectors.toList()); return new FilterResponse<>(result, pageRequest, result.size()); } @Override public List<Class<? extends ScimExtension>> getExtensionList() { return Collections.emptyList(); } }
4,343
0
Create_ds/directory-scimple/scim-server-examples/scim-server-quarkus/src/main/java/org/apache/directory/scim/example/quarkus
Create_ds/directory-scimple/scim-server-examples/scim-server-quarkus/src/main/java/org/apache/directory/scim/example/quarkus/service/InMemoryUserService.java
/* * 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 * 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.directory.scim.example.quarkus.service; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; import jakarta.annotation.PostConstruct; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.inject.Named; import jakarta.ws.rs.core.Response; import org.apache.directory.scim.example.quarkus.extensions.LuckyNumberExtension; import org.apache.directory.scim.server.exception.UnableToCreateResourceException; import org.apache.directory.scim.server.exception.UnableToUpdateResourceException; import org.apache.directory.scim.core.repository.Repository; import org.apache.directory.scim.core.repository.UpdateRequest; import org.apache.directory.scim.spec.extension.EnterpriseExtension; import org.apache.directory.scim.spec.filter.FilterExpressions; import org.apache.directory.scim.spec.filter.FilterResponse; import org.apache.directory.scim.spec.filter.Filter; import org.apache.directory.scim.spec.filter.PageRequest; import org.apache.directory.scim.spec.filter.SortRequest; import org.apache.directory.scim.spec.resources.*; import org.apache.directory.scim.core.schema.SchemaRegistry; /** * Creates a singleton (effectively) Repository<ScimUser> with a memory-based * persistence layer. * * @author Chris Harm &lt;crh5255@psu.edu&gt; */ @Named @ApplicationScoped public class InMemoryUserService implements Repository<ScimUser> { static final String DEFAULT_USER_ID = UUID.randomUUID().toString(); static final String DEFAULT_USER_EXTERNAL_ID = "e" + DEFAULT_USER_ID; static final String DEFAULT_USER_DISPLAY_NAME = "User " + DEFAULT_USER_ID; static final String DEFAULT_USER_EMAIL_VALUE = "e1@example.com"; static final String DEFAULT_USER_EMAIL_TYPE = "work"; static final int DEFAULT_USER_LUCKY_NUMBER = 7; private final Map<String, ScimUser> users = new HashMap<>(); private SchemaRegistry schemaRegistry; @Inject public InMemoryUserService(SchemaRegistry schemaRegistry) { this.schemaRegistry = schemaRegistry; } protected InMemoryUserService() {} @PostConstruct public void init() { ScimUser user = new ScimUser(); user.setId(DEFAULT_USER_ID); user.setExternalId(DEFAULT_USER_EXTERNAL_ID); user.setUserName(DEFAULT_USER_EXTERNAL_ID); user.setDisplayName(DEFAULT_USER_DISPLAY_NAME); user.setName(new Name() .setGivenName("Tester") .setFamilyName("McTest")); Email email = new Email(); email.setDisplay(DEFAULT_USER_EMAIL_VALUE); email.setValue(DEFAULT_USER_EMAIL_VALUE); email.setType(DEFAULT_USER_EMAIL_TYPE); email.setPrimary(true); user.setEmails(List.of(email)); LuckyNumberExtension luckyNumberExtension = new LuckyNumberExtension(); luckyNumberExtension.setLuckyNumber(DEFAULT_USER_LUCKY_NUMBER); user.addExtension(luckyNumberExtension); EnterpriseExtension enterpriseExtension = new EnterpriseExtension(); enterpriseExtension.setEmployeeNumber("12345"); EnterpriseExtension.Manager manager = new EnterpriseExtension.Manager(); manager.setValue("bulkId:qwerty"); enterpriseExtension.setManager(manager); user.addExtension(enterpriseExtension); users.put(user.getId(), user); } @Override public Class<ScimUser> getResourceClass() { return ScimUser.class; } /** * @see Repository#create(ScimResource) */ @Override public ScimUser create(ScimUser resource) throws UnableToCreateResourceException { String id = UUID.randomUUID().toString(); // check to make sure the user doesn't already exist boolean existingUserFound = users.values().stream() .anyMatch(user -> user.getUserName().equals(resource.getUserName())); if (existingUserFound) { // HTTP leaking into data layer throw new UnableToCreateResourceException(Response.Status.CONFLICT, "User '" + resource.getUserName() + "' already exists."); } resource.setId(id); users.put(id, resource); return resource; } /** * @see Repository#update(UpdateRequest) */ @Override public ScimUser update(UpdateRequest<ScimUser> updateRequest) throws UnableToUpdateResourceException { String id = updateRequest.getId(); ScimUser resource = updateRequest.getResource(); users.put(id, resource); return resource; } /** * @see Repository#get(java.lang.String) */ @Override public ScimUser get(String id) { return users.get(id); } /** * @see Repository#delete(java.lang.String) */ @Override public void delete(String id) { users.remove(id); } /** * @see Repository#find(Filter, PageRequest, SortRequest) */ @Override public FilterResponse<ScimUser> find(Filter filter, PageRequest pageRequest, SortRequest sortRequest) { long count = pageRequest.getCount() != null ? pageRequest.getCount() : users.size(); long startIndex = pageRequest.getStartIndex() != null ? pageRequest.getStartIndex() - 1 // SCIM is 1-based indexed : 0; List<ScimUser> result = users.values().stream() .skip(startIndex) .limit(count) .filter(FilterExpressions.inMemory(filter, schemaRegistry.getSchema(ScimUser.SCHEMA_URI))) .collect(Collectors.toList()); return new FilterResponse<>(result, pageRequest, result.size()); } /** * @see Repository#getExtensionList() */ @Override public List<Class<? extends ScimExtension>> getExtensionList() { return List.of(LuckyNumberExtension.class, EnterpriseExtension.class); } }
4,344
0
Create_ds/directory-scimple/scim-server-examples/scim-server-spring-boot/src/main/java/org/apache/directory/scim/example
Create_ds/directory-scimple/scim-server-examples/scim-server-spring-boot/src/main/java/org/apache/directory/scim/example/spring/ScimpleSpringBootApplication.java
/* * 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 * 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.directory.scim.example.spring; import org.apache.directory.scim.server.configuration.ServerConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import static org.apache.directory.scim.spec.schema.ServiceProviderConfiguration.AuthenticationSchema.httpBasic; @SpringBootApplication public class ScimpleSpringBootApplication { public static void main(String[] args) { SpringApplication.run(ScimpleSpringBootApplication.class, args); } @Bean ServerConfiguration serverConfiguration() { // Set any unique configuration bits return new ServerConfiguration() .setId("scimple-spring-boot-example") .setDocumentationUri("https://github.com/apache/directory-scimple") // set the auth scheme .addAuthenticationSchema(httpBasic()); } }
4,345
0
Create_ds/directory-scimple/scim-server-examples/scim-server-spring-boot/src/main/java/org/apache/directory/scim/example/spring
Create_ds/directory-scimple/scim-server-examples/scim-server-spring-boot/src/main/java/org/apache/directory/scim/example/spring/extensions/LuckyNumberExtension.java
/* * 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 * 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.directory.scim.example.spring.extensions; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import lombok.Data; import org.apache.directory.scim.spec.annotation.ScimAttribute; import org.apache.directory.scim.spec.annotation.ScimExtensionType; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.schema.Schema; /** * Allows a User's lucky number to be passed as part of the User's entry via * the SCIM protocol. * * @author Chris Harm &lt;crh5255@psu.edu&gt; */ @XmlRootElement( name = "LuckyNumberExtension", namespace = "http://www.psu.edu/schemas/psu-scim" ) @XmlAccessorType(XmlAccessType.NONE) @Data @ScimExtensionType(id = LuckyNumberExtension.SCHEMA_URN, description="Lucky Numbers", name="LuckyNumbers", required=true) public class LuckyNumberExtension implements ScimExtension { public static final String SCHEMA_URN = "urn:mem:params:scim:schemas:extension:LuckyNumberExtension"; @ScimAttribute(returned=Schema.Attribute.Returned.DEFAULT, required=true) @XmlElement private long luckyNumber; /** * Provides the URN associated with this extension which, as defined by the * SCIM specification is the extension's unique identifier. * * @return The extension's URN. */ @Override public String getUrn() { return SCHEMA_URN; } }
4,346
0
Create_ds/directory-scimple/scim-server-examples/scim-server-spring-boot/src/main/java/org/apache/directory/scim/example/spring
Create_ds/directory-scimple/scim-server-examples/scim-server-spring-boot/src/main/java/org/apache/directory/scim/example/spring/service/InMemorySelfResolverImpl.java
/* * 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 * 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.directory.scim.example.spring.service; import org.apache.directory.scim.core.repository.SelfIdResolver; import org.apache.directory.scim.server.exception.UnableToResolveIdResourceException; import java.security.Principal; import jakarta.ws.rs.core.Response.Status; import org.springframework.stereotype.Service; @Service public class InMemorySelfResolverImpl implements SelfIdResolver { @Override public String resolveToInternalId(Principal principal) throws UnableToResolveIdResourceException { throw new UnableToResolveIdResourceException(Status.NOT_IMPLEMENTED, "Caller Principal not available"); } }
4,347
0
Create_ds/directory-scimple/scim-server-examples/scim-server-spring-boot/src/main/java/org/apache/directory/scim/example/spring
Create_ds/directory-scimple/scim-server-examples/scim-server-spring-boot/src/main/java/org/apache/directory/scim/example/spring/service/InMemoryGroupService.java
/* * 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 * 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.directory.scim.example.spring.service; import jakarta.annotation.PostConstruct; import jakarta.ws.rs.core.Response; import org.apache.directory.scim.core.repository.Repository; import org.apache.directory.scim.core.repository.UpdateRequest; import org.apache.directory.scim.core.schema.SchemaRegistry; import org.apache.directory.scim.server.exception.UnableToCreateResourceException; import org.apache.directory.scim.server.exception.UnableToUpdateResourceException; import org.apache.directory.scim.spec.filter.*; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.resources.ScimGroup; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; @Service public class InMemoryGroupService implements Repository<ScimGroup> { private final Map<String, ScimGroup> groups = new HashMap<>(); private final SchemaRegistry schemaRegistry; public InMemoryGroupService(SchemaRegistry schemaRegistry) { this.schemaRegistry = schemaRegistry; } @PostConstruct public void init() { ScimGroup group = new ScimGroup(); group.setId(UUID.randomUUID().toString()); group.setDisplayName("example-group"); group.setExternalId("example-group"); groups.put(group.getId(), group); } @Override public Class<ScimGroup> getResourceClass() { return ScimGroup.class; } @Override public ScimGroup create(ScimGroup resource) throws UnableToCreateResourceException { String id = UUID.randomUUID().toString(); // if the external ID is not set, use the displayName instead if (!StringUtils.hasText(resource.getExternalId())) { resource.setExternalId(resource.getDisplayName()); } // check to make sure the group doesn't already exist boolean existingGroupFound = groups.values().stream() .anyMatch(group -> resource.getExternalId().equals(group.getExternalId())); if (existingGroupFound) { // HTTP leaking into data layer throw new UnableToCreateResourceException(Response.Status.CONFLICT, "Group '" + resource.getExternalId() + "' already exists."); } resource.setId(id); groups.put(id, resource); return resource; } @Override public ScimGroup update(UpdateRequest<ScimGroup> updateRequest) throws UnableToUpdateResourceException { String id = updateRequest.getId(); ScimGroup resource = updateRequest.getResource(); groups.put(id, resource); return resource; } @Override public ScimGroup get(String id) { return groups.get(id); } @Override public void delete(String id) { groups.remove(id); } @Override public FilterResponse<ScimGroup> find(Filter filter, PageRequest pageRequest, SortRequest sortRequest) { long count = pageRequest.getCount() != null ? pageRequest.getCount() : groups.size(); long startIndex = pageRequest.getStartIndex() != null ? pageRequest.getStartIndex() - 1 // SCIM is 1-based indexed : 0; List<ScimGroup> result = groups.values().stream() .skip(startIndex) .limit(count) .filter(FilterExpressions.inMemory(filter, schemaRegistry.getSchema(ScimGroup.SCHEMA_URI))) .collect(Collectors.toList()); return new FilterResponse<>(result, pageRequest, result.size()); } @Override public List<Class<? extends ScimExtension>> getExtensionList() { return Collections.emptyList(); } }
4,348
0
Create_ds/directory-scimple/scim-server-examples/scim-server-spring-boot/src/main/java/org/apache/directory/scim/example/spring
Create_ds/directory-scimple/scim-server-examples/scim-server-spring-boot/src/main/java/org/apache/directory/scim/example/spring/service/InMemoryUserService.java
/* * 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 * 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.directory.scim.example.spring.service; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; import jakarta.annotation.PostConstruct; import jakarta.ws.rs.core.Response; import org.apache.directory.scim.core.repository.Repository; import org.apache.directory.scim.core.repository.UpdateRequest; import org.apache.directory.scim.core.schema.SchemaRegistry; import org.apache.directory.scim.example.spring.extensions.LuckyNumberExtension; import org.apache.directory.scim.server.exception.UnableToCreateResourceException; import org.apache.directory.scim.server.exception.UnableToUpdateResourceException; import org.apache.directory.scim.spec.extension.EnterpriseExtension; import org.apache.directory.scim.spec.filter.*; import org.apache.directory.scim.spec.resources.*; import org.springframework.stereotype.Service; /** * Creates a singleton (effectively) Provider<User> with a memory-based * persistence layer. * * @author Chris Harm &lt;crh5255@psu.edu&gt; */ @Service public class InMemoryUserService implements Repository<ScimUser> { static final String DEFAULT_USER_ID = UUID.randomUUID().toString(); static final String DEFAULT_USER_EXTERNAL_ID = "e" + DEFAULT_USER_ID; static final String DEFAULT_USER_DISPLAY_NAME = "User " + DEFAULT_USER_ID; static final String DEFAULT_USER_EMAIL_VALUE = "e1@example.com"; static final String DEFAULT_USER_EMAIL_TYPE = "work"; static final int DEFAULT_USER_LUCKY_NUMBER = 7; private final Map<String, ScimUser> users = new HashMap<>(); private final SchemaRegistry schemaRegistry; public InMemoryUserService(SchemaRegistry schemaRegistry) { this.schemaRegistry = schemaRegistry; } @PostConstruct public void init() { ScimUser user = new ScimUser(); user.setId(DEFAULT_USER_ID); user.setExternalId(DEFAULT_USER_EXTERNAL_ID); user.setUserName(DEFAULT_USER_EXTERNAL_ID); user.setDisplayName(DEFAULT_USER_DISPLAY_NAME); user.setName(new Name() .setGivenName("Tester") .setFamilyName("McTest")); Email email = new Email(); email.setDisplay(DEFAULT_USER_EMAIL_VALUE); email.setValue(DEFAULT_USER_EMAIL_VALUE); email.setType(DEFAULT_USER_EMAIL_TYPE); email.setPrimary(true); user.setEmails(List.of(email)); LuckyNumberExtension luckyNumberExtension = new LuckyNumberExtension(); luckyNumberExtension.setLuckyNumber(DEFAULT_USER_LUCKY_NUMBER); user.addExtension(luckyNumberExtension); EnterpriseExtension enterpriseExtension = new EnterpriseExtension(); enterpriseExtension.setEmployeeNumber("12345"); EnterpriseExtension.Manager manager = new EnterpriseExtension.Manager(); manager.setValue("bulkId:qwerty"); enterpriseExtension.setManager(manager); user.addExtension(enterpriseExtension); users.put(user.getId(), user); } @Override public Class<ScimUser> getResourceClass() { return ScimUser.class; } /** * @see Repository#create(ScimResource) */ @Override public ScimUser create(ScimUser resource) throws UnableToCreateResourceException { String id = UUID.randomUUID().toString(); // check to make sure the user doesn't already exist boolean existingUserFound = users.values().stream() .anyMatch(user -> user.getUserName().equals(resource.getUserName())); if (existingUserFound) { // HTTP leaking into data layer throw new UnableToCreateResourceException(Response.Status.CONFLICT, "User '" + resource.getUserName() + "' already exists."); } resource.setId(id); users.put(id, resource); return resource; } /** * @see Repository#update(UpdateRequest) */ @Override public ScimUser update(UpdateRequest<ScimUser> updateRequest) throws UnableToUpdateResourceException { String id = updateRequest.getId(); ScimUser resource = updateRequest.getResource(); users.put(id, resource); return resource; } /** * @see Repository#get(java.lang.String) */ @Override public ScimUser get(String id) { return users.get(id); } /** * @see Repository#delete(java.lang.String) */ @Override public void delete(String id) { users.remove(id); } /** * @see Repository#find(Filter, PageRequest, SortRequest) */ @Override public FilterResponse<ScimUser> find(Filter filter, PageRequest pageRequest, SortRequest sortRequest) { long count = pageRequest.getCount() != null ? pageRequest.getCount() : users.size(); long startIndex = pageRequest.getStartIndex() != null ? pageRequest.getStartIndex() - 1 // SCIM is 1-based indexed : 0; List<ScimUser> result = users.values().stream() .skip(startIndex) .limit(count) .filter(FilterExpressions.inMemory(filter, schemaRegistry.getSchema(ScimUser.SCHEMA_URI))) .collect(Collectors.toList()); return new FilterResponse<>(result, pageRequest, result.size()); } /** * @see Repository#getExtensionList() */ @Override public List<Class<? extends ScimExtension>> getExtensionList() { return List.of(LuckyNumberExtension.class, EnterpriseExtension.class); } }
4,349
0
Create_ds/directory-scimple/scim-server-examples/scim-server-memory/src/main/java/org/apache/directory/scim/example/memory
Create_ds/directory-scimple/scim-server-examples/scim-server-memory/src/main/java/org/apache/directory/scim/example/memory/extensions/LuckyNumberExtension.java
/* * 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 * 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.directory.scim.example.memory.extensions; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import lombok.Data; import org.apache.directory.scim.spec.annotation.ScimAttribute; import org.apache.directory.scim.spec.annotation.ScimExtensionType; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.schema.Schema; /** * Allows a User's lucky number to be passed as part of the User's entry via * the SCIM protocol. * * @author Chris Harm &lt;crh5255@psu.edu&gt; */ @XmlRootElement( name = "LuckyNumberExtension", namespace = "http://www.psu.edu/schemas/psu-scim" ) @XmlAccessorType(XmlAccessType.NONE) @Data @ScimExtensionType(id = LuckyNumberExtension.SCHEMA_URN, description="Lucky Numbers", name="LuckyNumbers", required=true) public class LuckyNumberExtension implements ScimExtension { public static final String SCHEMA_URN = "urn:mem:params:scim:schemas:extension:LuckyNumberExtension"; @ScimAttribute(returned=Schema.Attribute.Returned.DEFAULT, required=true) @XmlElement private long luckyNumber; /** * Provides the URN associated with this extension which, as defined by the * SCIM specification is the extension's unique identifier. * * @return The extension's URN. */ @Override public String getUrn() { return SCHEMA_URN; } }
4,350
0
Create_ds/directory-scimple/scim-server-examples/scim-server-memory/src/main/java/org/apache/directory/scim/example/memory
Create_ds/directory-scimple/scim-server-examples/scim-server-memory/src/main/java/org/apache/directory/scim/example/memory/service/InMemorySelfResolverImpl.java
/* * 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 * 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.directory.scim.example.memory.service; import jakarta.enterprise.context.ApplicationScoped; import org.apache.directory.scim.server.exception.UnableToResolveIdResourceException; import org.apache.directory.scim.core.repository.SelfIdResolver; import java.security.Principal; import jakarta.ws.rs.core.Response.Status; @ApplicationScoped public class InMemorySelfResolverImpl implements SelfIdResolver { @Override public String resolveToInternalId(Principal principal) throws UnableToResolveIdResourceException { throw new UnableToResolveIdResourceException(Status.NOT_IMPLEMENTED, "Caller Principal not available"); } }
4,351
0
Create_ds/directory-scimple/scim-server-examples/scim-server-memory/src/main/java/org/apache/directory/scim/example/memory
Create_ds/directory-scimple/scim-server-examples/scim-server-memory/src/main/java/org/apache/directory/scim/example/memory/service/InMemoryGroupService.java
/* * 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 * 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.directory.scim.example.memory.service; import jakarta.annotation.PostConstruct; import jakarta.inject.Inject; import jakarta.ws.rs.core.Response; import org.apache.commons.lang3.StringUtils; import org.apache.directory.scim.server.exception.UnableToCreateResourceException; import org.apache.directory.scim.server.exception.UnableToUpdateResourceException; import org.apache.directory.scim.core.repository.Repository; import org.apache.directory.scim.core.repository.UpdateRequest; import org.apache.directory.scim.spec.filter.FilterExpressions; import org.apache.directory.scim.spec.filter.FilterResponse; import org.apache.directory.scim.spec.filter.Filter; import org.apache.directory.scim.spec.filter.PageRequest; import org.apache.directory.scim.spec.filter.SortRequest; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.resources.ScimGroup; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Named; import org.apache.directory.scim.core.schema.SchemaRegistry; @Named @ApplicationScoped public class InMemoryGroupService implements Repository<ScimGroup> { private final Map<String, ScimGroup> groups = new HashMap<>(); private SchemaRegistry schemaRegistry; @Inject public InMemoryGroupService(SchemaRegistry schemaRegistry) { this.schemaRegistry = schemaRegistry; } protected InMemoryGroupService() {} @PostConstruct public void init() { ScimGroup group = new ScimGroup(); group.setId(UUID.randomUUID().toString()); group.setDisplayName("example-group"); group.setExternalId("example-group"); groups.put(group.getId(), group); } @Override public Class<ScimGroup> getResourceClass() { return ScimGroup.class; } @Override public ScimGroup create(ScimGroup resource) throws UnableToCreateResourceException { String id = UUID.randomUUID().toString(); // if the external ID is not set, use the displayName instead if (StringUtils.isEmpty(resource.getExternalId())) { resource.setExternalId(resource.getDisplayName()); } // check to make sure the group doesn't already exist boolean existingGroupFound = groups.values().stream() .anyMatch(group -> resource.getExternalId().equals(group.getExternalId())); if (existingGroupFound) { // HTTP leaking into data layer throw new UnableToCreateResourceException(Response.Status.CONFLICT, "Group '" + resource.getExternalId() + "' already exists."); } resource.setId(id); groups.put(id, resource); return resource; } @Override public ScimGroup update(UpdateRequest<ScimGroup> updateRequest) throws UnableToUpdateResourceException { String id = updateRequest.getId(); ScimGroup resource = updateRequest.getResource(); groups.put(id, resource); return resource; } @Override public ScimGroup get(String id) { return groups.get(id); } @Override public void delete(String id) { groups.remove(id); } @Override public FilterResponse<ScimGroup> find(Filter filter, PageRequest pageRequest, SortRequest sortRequest) { long count = pageRequest.getCount() != null ? pageRequest.getCount() : groups.size(); long startIndex = pageRequest.getStartIndex() != null ? pageRequest.getStartIndex() - 1 // SCIM is 1-based indexed : 0; List<ScimGroup> result = groups.values().stream() .skip(startIndex) .limit(count) .filter(FilterExpressions.inMemory(filter, schemaRegistry.getSchema(ScimGroup.SCHEMA_URI))) .collect(Collectors.toList()); return new FilterResponse<>(result, pageRequest, result.size()); } @Override public List<Class<? extends ScimExtension>> getExtensionList() { return Collections.emptyList(); } }
4,352
0
Create_ds/directory-scimple/scim-server-examples/scim-server-memory/src/main/java/org/apache/directory/scim/example/memory
Create_ds/directory-scimple/scim-server-examples/scim-server-memory/src/main/java/org/apache/directory/scim/example/memory/service/InMemoryUserService.java
/* * 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 * 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.directory.scim.example.memory.service; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; import jakarta.annotation.PostConstruct; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.inject.Named; import jakarta.ws.rs.core.Response; import org.apache.directory.scim.example.memory.extensions.LuckyNumberExtension; import org.apache.directory.scim.server.exception.UnableToCreateResourceException; import org.apache.directory.scim.server.exception.UnableToUpdateResourceException; import org.apache.directory.scim.core.repository.Repository; import org.apache.directory.scim.core.repository.UpdateRequest; import org.apache.directory.scim.spec.extension.EnterpriseExtension; import org.apache.directory.scim.spec.filter.FilterExpressions; import org.apache.directory.scim.spec.filter.FilterResponse; import org.apache.directory.scim.spec.filter.Filter; import org.apache.directory.scim.spec.filter.PageRequest; import org.apache.directory.scim.spec.filter.SortRequest; import org.apache.directory.scim.spec.resources.*; import org.apache.directory.scim.core.schema.SchemaRegistry; /** * Creates a singleton (effectively) Repository<ScimUser> with a memory-based * persistence layer. * * @author Chris Harm &lt;crh5255@psu.edu&gt; */ @Named @ApplicationScoped public class InMemoryUserService implements Repository<ScimUser> { static final String DEFAULT_USER_ID = UUID.randomUUID().toString(); static final String DEFAULT_USER_EXTERNAL_ID = "e" + DEFAULT_USER_ID; static final String DEFAULT_USER_DISPLAY_NAME = "User " + DEFAULT_USER_ID; static final String DEFAULT_USER_EMAIL_VALUE = "e1@example.com"; static final String DEFAULT_USER_EMAIL_TYPE = "work"; static final int DEFAULT_USER_LUCKY_NUMBER = 7; private final Map<String, ScimUser> users = new HashMap<>(); private SchemaRegistry schemaRegistry; @Inject public InMemoryUserService(SchemaRegistry schemaRegistry) { this.schemaRegistry = schemaRegistry; } protected InMemoryUserService() {} @PostConstruct public void init() { ScimUser user = new ScimUser(); user.setId(DEFAULT_USER_ID); user.setExternalId(DEFAULT_USER_EXTERNAL_ID); user.setUserName(DEFAULT_USER_EXTERNAL_ID); user.setDisplayName(DEFAULT_USER_DISPLAY_NAME); user.setName(new Name() .setGivenName("Tester") .setFamilyName("McTest")); Email email = new Email(); email.setDisplay(DEFAULT_USER_EMAIL_VALUE); email.setValue(DEFAULT_USER_EMAIL_VALUE); email.setType(DEFAULT_USER_EMAIL_TYPE); email.setPrimary(true); user.setEmails(List.of(email)); LuckyNumberExtension luckyNumberExtension = new LuckyNumberExtension(); luckyNumberExtension.setLuckyNumber(DEFAULT_USER_LUCKY_NUMBER); user.addExtension(luckyNumberExtension); EnterpriseExtension enterpriseExtension = new EnterpriseExtension(); enterpriseExtension.setEmployeeNumber("12345"); EnterpriseExtension.Manager manager = new EnterpriseExtension.Manager(); manager.setValue("bulkId:qwerty"); enterpriseExtension.setManager(manager); user.addExtension(enterpriseExtension); users.put(user.getId(), user); } @Override public Class<ScimUser> getResourceClass() { return ScimUser.class; } /** * @see Repository#create(ScimResource) */ @Override public ScimUser create(ScimUser resource) throws UnableToCreateResourceException { String id = UUID.randomUUID().toString(); // check to make sure the user doesn't already exist boolean existingUserFound = users.values().stream() .anyMatch(user -> user.getUserName().equals(resource.getUserName())); if (existingUserFound) { // HTTP leaking into data layer throw new UnableToCreateResourceException(Response.Status.CONFLICT, "User '" + resource.getUserName() + "' already exists."); } resource.setId(id); users.put(id, resource); return resource; } /** * @see Repository#update(UpdateRequest) */ @Override public ScimUser update(UpdateRequest<ScimUser> updateRequest) throws UnableToUpdateResourceException { String id = updateRequest.getId(); ScimUser resource = updateRequest.getResource(); users.put(id, resource); return resource; } /** * @see Repository#get(java.lang.String) */ @Override public ScimUser get(String id) { return users.get(id); } /** * @see Repository#delete(java.lang.String) */ @Override public void delete(String id) { users.remove(id); } /** * @see Repository#find(Filter, PageRequest, SortRequest) */ @Override public FilterResponse<ScimUser> find(Filter filter, PageRequest pageRequest, SortRequest sortRequest) { long count = pageRequest.getCount() != null ? pageRequest.getCount() : users.size(); long startIndex = pageRequest.getStartIndex() != null ? pageRequest.getStartIndex() - 1 // SCIM is 1-based indexed : 0; List<ScimUser> result = users.values().stream() .skip(startIndex) .limit(count) .filter(FilterExpressions.inMemory(filter, schemaRegistry.getSchema(ScimUser.SCHEMA_URI))) .collect(Collectors.toList()); return new FilterResponse<>(result, pageRequest, result.size()); } /** * @see Repository#getExtensionList() */ @Override public List<Class<? extends ScimExtension>> getExtensionList() { return List.of(LuckyNumberExtension.class, EnterpriseExtension.class); } }
4,353
0
Create_ds/directory-scimple/scim-server-examples/scim-server-memory/src/main/java/org/apache/directory/scim/example/memory
Create_ds/directory-scimple/scim-server-examples/scim-server-memory/src/main/java/org/apache/directory/scim/example/memory/rest/RestApplication.java
/* * 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 * 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.directory.scim.example.memory.rest; import jakarta.enterprise.inject.Produces; import org.apache.directory.scim.server.configuration.ServerConfiguration; import jakarta.ws.rs.ApplicationPath; import jakarta.ws.rs.core.Application; import static org.apache.directory.scim.spec.schema.ServiceProviderConfiguration.AuthenticationSchema.httpBasic; @ApplicationPath("v2") public class RestApplication extends Application { @Produces ServerConfiguration serverConfiguration() { return new ServerConfiguration() .setId("scimple-in-memory-example") .addAuthenticationSchema(httpBasic()); } }
4,354
0
Create_ds/directory-scimple/scim-server-examples/scim-server-jersey/src/test/java/org/apache/directory/scim/example
Create_ds/directory-scimple/scim-server-examples/scim-server-jersey/src/test/java/org/apache/directory/scim/example/jersey/JerseyTestServer.java
/* * 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 * 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.directory.scim.example.jersey; import jakarta.enterprise.inject.se.SeContainer; import jakarta.enterprise.inject.se.SeContainerInitializer; import jakarta.ws.rs.SeBootstrap; import jakarta.ws.rs.core.UriBuilder; import org.apache.directory.scim.compliance.junit.EmbeddedServerExtension; import java.net.URI; import java.util.concurrent.TimeUnit; public class JerseyTestServer implements EmbeddedServerExtension.ScimTestServer { private SeContainer container; private SeBootstrap.Instance server; @Override public URI start(int port) throws Exception { // It doesn't look like Weld finds the beans in src/main/java, so enable implicit scanning // NOTE: this isn't an issue for the scim-server tests, but those beans are located in src/test/java container = SeContainerInitializer.newInstance() .addPackages(true, JerseyApplication.class) .initialize(); JerseyApplication app = new JerseyApplication(); server = SeBootstrap.start(app, SeBootstrap.Configuration.builder().port(port).build()) .toCompletableFuture().get(1, TimeUnit.MINUTES); // shut down CDI container on stop server.stopOnShutdown(stopResult -> container.close()); return UriBuilder.fromUri("http://localhost/").port(port).build(); } @Override public void shutdown() throws Exception { if (server != null) { server.stop().toCompletableFuture() .get(10, TimeUnit.SECONDS); } if (container != null) { container.close(); } } }
4,355
0
Create_ds/directory-scimple/scim-server-examples/scim-server-jersey/src/main/java/org/apache/directory/scim/example
Create_ds/directory-scimple/scim-server-examples/scim-server-jersey/src/main/java/org/apache/directory/scim/example/jersey/JerseyApplication.java
/* * 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 * 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.directory.scim.example.jersey; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Produces; import jakarta.enterprise.inject.se.SeContainer; import jakarta.enterprise.inject.se.SeContainerInitializer; import jakarta.ws.rs.SeBootstrap; import jakarta.ws.rs.core.UriBuilder; import org.apache.directory.scim.server.configuration.ServerConfiguration; import java.net.URI; import java.util.Set; import jakarta.ws.rs.core.Application; import org.apache.directory.scim.server.rest.ScimResourceHelper; import org.slf4j.LoggerFactory; import org.slf4j.bridge.SLF4JBridgeHandler; import static org.apache.directory.scim.spec.schema.ServiceProviderConfiguration.AuthenticationSchema.oauthBearer; // @ApplicationPath("v2") // Embedded Jersey + Jetty ignores the ApplicationPath annotation // https://github.com/eclipse-ee4j/jersey/issues/3222 @ApplicationScoped public class JerseyApplication extends Application { private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(JerseyApplication.class); @Override public Set<Class<?>> getClasses() { return ScimResourceHelper.scimpleFeatureAndResourceClasses(); } @Produces ServerConfiguration serverConfiguration() { return new ServerConfiguration() // Set any unique configuration bits .setId("scimple-jersey-example") .setDocumentationUri("https://github.com/apache/directory-scimple") // set the auth scheme too .addAuthenticationSchema(oauthBearer()); } public static void main(String[] args) { // configure JUL logging SLF4JBridgeHandler.install(); try { SeContainer container = SeContainerInitializer.newInstance() .addPackages(true, JerseyApplication.class) .initialize(); JerseyApplication app = new JerseyApplication(); SeBootstrap.start(app, SeBootstrap.Configuration.builder().port(8080).build()) .thenAccept(instance -> instance.stopOnShutdown(stopResult -> container.close())); URI uri = UriBuilder.fromUri("http://localhost/").port(8080).build(); System.out.printf("Application started: %s%nStop the application using CTRL+C%n", uri.toString()); // block and wait shut down signal, like CTRL+C Thread.currentThread().join(); } catch (InterruptedException ex) { LOG.error("Service Interrupted", ex); } } }
4,356
0
Create_ds/directory-scimple/scim-server-examples/scim-server-jersey/src/main/java/org/apache/directory/scim/example/jersey
Create_ds/directory-scimple/scim-server-examples/scim-server-jersey/src/main/java/org/apache/directory/scim/example/jersey/extensions/LuckyNumberExtension.java
/* * 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 * 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.directory.scim.example.jersey.extensions; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import lombok.Data; import org.apache.directory.scim.spec.annotation.ScimAttribute; import org.apache.directory.scim.spec.annotation.ScimExtensionType; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.schema.Schema; /** * Allows a User's lucky number to be passed as part of the User's entry via * the SCIM protocol. * * @author Chris Harm &lt;crh5255@psu.edu&gt; */ @XmlRootElement( name = "LuckyNumberExtension", namespace = "http://www.psu.edu/schemas/psu-scim" ) @XmlAccessorType(XmlAccessType.NONE) @Data @ScimExtensionType(id = LuckyNumberExtension.SCHEMA_URN, description="Lucky Numbers", name="LuckyNumbers", required=true) public class LuckyNumberExtension implements ScimExtension { public static final String SCHEMA_URN = "urn:mem:params:scim:schemas:extension:LuckyNumberExtension"; @ScimAttribute(returned=Schema.Attribute.Returned.DEFAULT, required=true) @XmlElement private long luckyNumber; /** * Provides the URN associated with this extension which, as defined by the * SCIM specification is the extension's unique identifier. * * @return The extension's URN. */ @Override public String getUrn() { return SCHEMA_URN; } }
4,357
0
Create_ds/directory-scimple/scim-server-examples/scim-server-jersey/src/main/java/org/apache/directory/scim/example/jersey
Create_ds/directory-scimple/scim-server-examples/scim-server-jersey/src/main/java/org/apache/directory/scim/example/jersey/service/InMemorySelfResolverImpl.java
/* * 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 * 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.directory.scim.example.jersey.service; import jakarta.enterprise.context.ApplicationScoped; import org.apache.directory.scim.server.exception.UnableToResolveIdResourceException; import org.apache.directory.scim.core.repository.SelfIdResolver; import java.security.Principal; import jakarta.ws.rs.core.Response.Status; @ApplicationScoped public class InMemorySelfResolverImpl implements SelfIdResolver { @Override public String resolveToInternalId(Principal principal) throws UnableToResolveIdResourceException { throw new UnableToResolveIdResourceException(Status.NOT_IMPLEMENTED, "Caller Principal not available"); } }
4,358
0
Create_ds/directory-scimple/scim-server-examples/scim-server-jersey/src/main/java/org/apache/directory/scim/example/jersey
Create_ds/directory-scimple/scim-server-examples/scim-server-jersey/src/main/java/org/apache/directory/scim/example/jersey/service/InMemoryGroupService.java
/* * 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 * 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.directory.scim.example.jersey.service; import jakarta.annotation.PostConstruct; import jakarta.inject.Inject; import jakarta.ws.rs.core.Response; import org.apache.commons.lang3.StringUtils; import org.apache.directory.scim.server.exception.UnableToCreateResourceException; import org.apache.directory.scim.server.exception.UnableToUpdateResourceException; import org.apache.directory.scim.core.repository.Repository; import org.apache.directory.scim.core.repository.UpdateRequest; import org.apache.directory.scim.spec.filter.FilterExpressions; import org.apache.directory.scim.spec.filter.FilterResponse; import org.apache.directory.scim.spec.filter.Filter; import org.apache.directory.scim.spec.filter.PageRequest; import org.apache.directory.scim.spec.filter.SortRequest; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.resources.ScimGroup; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Named; import org.apache.directory.scim.core.schema.SchemaRegistry; @Named @ApplicationScoped public class InMemoryGroupService implements Repository<ScimGroup> { private final Map<String, ScimGroup> groups = new HashMap<>(); private SchemaRegistry schemaRegistry; @Inject public InMemoryGroupService(SchemaRegistry schemaRegistry) { this.schemaRegistry = schemaRegistry; } protected InMemoryGroupService() {} @PostConstruct public void init() { ScimGroup group = new ScimGroup(); group.setId(UUID.randomUUID().toString()); group.setDisplayName("example-group"); group.setExternalId("example-group"); groups.put(group.getId(), group); } @Override public Class<ScimGroup> getResourceClass() { return ScimGroup.class; } @Override public ScimGroup create(ScimGroup resource) throws UnableToCreateResourceException { String id = UUID.randomUUID().toString(); // if the external ID is not set, use the displayName instead if (StringUtils.isEmpty(resource.getExternalId())) { resource.setExternalId(resource.getDisplayName()); } // check to make sure the group doesn't already exist boolean existingGroupFound = groups.values().stream() .anyMatch(group -> resource.getExternalId().equals(group.getExternalId())); if (existingGroupFound) { // HTTP leaking into data layer throw new UnableToCreateResourceException(Response.Status.CONFLICT, "Group '" + resource.getExternalId() + "' already exists."); } resource.setId(id); groups.put(id, resource); return resource; } @Override public ScimGroup update(UpdateRequest<ScimGroup> updateRequest) throws UnableToUpdateResourceException { String id = updateRequest.getId(); ScimGroup resource = updateRequest.getResource(); groups.put(id, resource); return resource; } @Override public ScimGroup get(String id) { return groups.get(id); } @Override public void delete(String id) { groups.remove(id); } @Override public FilterResponse<ScimGroup> find(Filter filter, PageRequest pageRequest, SortRequest sortRequest) { long count = pageRequest.getCount() != null ? pageRequest.getCount() : groups.size(); long startIndex = pageRequest.getStartIndex() != null ? pageRequest.getStartIndex() - 1 // SCIM is 1-based indexed : 0; List<ScimGroup> result = groups.values().stream() .skip(startIndex) .limit(count) .filter(FilterExpressions.inMemory(filter, schemaRegistry.getSchema(ScimGroup.SCHEMA_URI))) .collect(Collectors.toList()); return new FilterResponse<>(result, pageRequest, result.size()); } @Override public List<Class<? extends ScimExtension>> getExtensionList() { return Collections.emptyList(); } }
4,359
0
Create_ds/directory-scimple/scim-server-examples/scim-server-jersey/src/main/java/org/apache/directory/scim/example/jersey
Create_ds/directory-scimple/scim-server-examples/scim-server-jersey/src/main/java/org/apache/directory/scim/example/jersey/service/InMemoryUserService.java
/* * 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 * 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.directory.scim.example.jersey.service; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; import jakarta.annotation.PostConstruct; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.inject.Named; import jakarta.ws.rs.core.Response; import org.apache.directory.scim.example.jersey.extensions.LuckyNumberExtension; import org.apache.directory.scim.server.exception.UnableToCreateResourceException; import org.apache.directory.scim.server.exception.UnableToUpdateResourceException; import org.apache.directory.scim.core.repository.Repository; import org.apache.directory.scim.core.repository.UpdateRequest; import org.apache.directory.scim.spec.extension.EnterpriseExtension; import org.apache.directory.scim.spec.filter.FilterExpressions; import org.apache.directory.scim.spec.filter.FilterResponse; import org.apache.directory.scim.spec.filter.Filter; import org.apache.directory.scim.spec.filter.PageRequest; import org.apache.directory.scim.spec.filter.SortRequest; import org.apache.directory.scim.spec.resources.*; import org.apache.directory.scim.core.schema.SchemaRegistry; /** * Creates a singleton (effectively) Repository<ScimUser> with a memory-based * persistence layer. * * @author Chris Harm &lt;crh5255@psu.edu&gt; */ @Named @ApplicationScoped public class InMemoryUserService implements Repository<ScimUser> { static final String DEFAULT_USER_ID = UUID.randomUUID().toString(); static final String DEFAULT_USER_EXTERNAL_ID = "e" + DEFAULT_USER_ID; static final String DEFAULT_USER_DISPLAY_NAME = "User " + DEFAULT_USER_ID; static final String DEFAULT_USER_EMAIL_VALUE = "e1@example.com"; static final String DEFAULT_USER_EMAIL_TYPE = "work"; static final int DEFAULT_USER_LUCKY_NUMBER = 7; private final Map<String, ScimUser> users = new HashMap<>(); private SchemaRegistry schemaRegistry; @Inject public InMemoryUserService(SchemaRegistry schemaRegistry) { this.schemaRegistry = schemaRegistry; } protected InMemoryUserService() {} @PostConstruct public void init() { ScimUser user = new ScimUser(); user.setId(DEFAULT_USER_ID); user.setExternalId(DEFAULT_USER_EXTERNAL_ID); user.setUserName(DEFAULT_USER_EXTERNAL_ID); user.setDisplayName(DEFAULT_USER_DISPLAY_NAME); user.setName(new Name() .setGivenName("Tester") .setFamilyName("McTest")); Email email = new Email(); email.setDisplay(DEFAULT_USER_EMAIL_VALUE); email.setValue(DEFAULT_USER_EMAIL_VALUE); email.setType(DEFAULT_USER_EMAIL_TYPE); email.setPrimary(true); user.setEmails(List.of(email)); LuckyNumberExtension luckyNumberExtension = new LuckyNumberExtension(); luckyNumberExtension.setLuckyNumber(DEFAULT_USER_LUCKY_NUMBER); user.addExtension(luckyNumberExtension); EnterpriseExtension enterpriseExtension = new EnterpriseExtension(); enterpriseExtension.setEmployeeNumber("12345"); EnterpriseExtension.Manager manager = new EnterpriseExtension.Manager(); manager.setValue("bulkId:qwerty"); enterpriseExtension.setManager(manager); user.addExtension(enterpriseExtension); users.put(user.getId(), user); } @Override public Class<ScimUser> getResourceClass() { return ScimUser.class; } /** * @see Repository#create(ScimResource) */ @Override public ScimUser create(ScimUser resource) throws UnableToCreateResourceException { String id = UUID.randomUUID().toString(); // check to make sure the user doesn't already exist boolean existingUserFound = users.values().stream() .anyMatch(user -> user.getUserName().equals(resource.getUserName())); if (existingUserFound) { // HTTP leaking into data layer throw new UnableToCreateResourceException(Response.Status.CONFLICT, "User '" + resource.getUserName() + "' already exists."); } resource.setId(id); users.put(id, resource); return resource; } /** * @see Repository#update(UpdateRequest) */ @Override public ScimUser update(UpdateRequest<ScimUser> updateRequest) throws UnableToUpdateResourceException { String id = updateRequest.getId(); ScimUser resource = updateRequest.getResource(); users.put(id, resource); return resource; } /** * @see Repository#get(java.lang.String) */ @Override public ScimUser get(String id) { return users.get(id); } /** * @see Repository#delete(java.lang.String) */ @Override public void delete(String id) { users.remove(id); } /** * @see Repository#find(Filter, PageRequest, SortRequest) */ @Override public FilterResponse<ScimUser> find(Filter filter, PageRequest pageRequest, SortRequest sortRequest) { long count = pageRequest.getCount() != null ? pageRequest.getCount() : users.size(); long startIndex = pageRequest.getStartIndex() != null ? pageRequest.getStartIndex() - 1 // SCIM is 1-based indexed : 0; List<ScimUser> result = users.values().stream() .skip(startIndex) .limit(count) .filter(FilterExpressions.inMemory(filter, schemaRegistry.getSchema(ScimUser.SCHEMA_URI))) .collect(Collectors.toList()); return new FilterResponse<>(result, pageRequest, result.size()); } /** * @see Repository#getExtensionList() */ @Override public List<Class<? extends ScimExtension>> getExtensionList() { return List.of(LuckyNumberExtension.class, EnterpriseExtension.class); } }
4,360
0
Create_ds/directory-scimple/scim-tools/src/test/java/org/apache/directory/scim/tools
Create_ds/directory-scimple/scim-tools/src/test/java/org/apache/directory/scim/tools/lint/LintTest.java
/* * 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 * 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.directory.scim.tools.lint; import java.io.IOException; import java.io.InputStream; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertTrue; public class LintTest { @ParameterizedTest @Disabled // TODO - Change the file names to match those provided by the // scim-spec-schema module and figure out why some schemas // don't have meta attributes. @ValueSource(strings = { "schemas/user-schema.json", "schemas/group-schema.json", "schemas/resource-type-schema.json", "schemas/schema-schema.json", "schemas/service-provider-configuration-schema.json", "schemas/enterprise-user-schema.json" }) public void testConvertWithSchemas(String schemaFileName) throws IOException { Lint lint = new Lint(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream inputStream = classLoader.getResourceAsStream(schemaFileName); try { JsonNode jsonNode = lint.convert(inputStream); assertTrue(jsonNode.isObject()); assertFalse(lint.hasSchemas(jsonNode)); assertTrue(lint.isSchema(jsonNode)); } catch (JsonProcessingException e) { fail(); } } @ParameterizedTest @ValueSource(strings = { "examples/enterprise-user-example.json", "examples/full-user-example.json", "examples/group-example.json", "examples/minimal-user-example.json", "examples/resource-type-group-example.json", "examples/resource-type-user-example.json" }) public void testConvertWithExamples(String exampleFileName) throws IOException { Lint lint = new Lint(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream inputStream = classLoader.getResourceAsStream(exampleFileName); try { JsonNode jsonNode = lint.convert(inputStream); assertTrue(jsonNode.isObject()); assertTrue(lint.hasSchemas(jsonNode)); } catch (JsonProcessingException e) { fail(); } } }
4,361
0
Create_ds/directory-scimple/scim-tools/src/main/java/org/apache/directory/scim/tools
Create_ds/directory-scimple/scim-tools/src/main/java/org/apache/directory/scim/tools/lint/LintException.java
/* * 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 * 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.directory.scim.tools.lint; public class LintException extends Exception { public LintException(String message) { super(message); } public LintException(String message, Throwable cause) { super(message, cause); } }
4,362
0
Create_ds/directory-scimple/scim-tools/src/main/java/org/apache/directory/scim/tools
Create_ds/directory-scimple/scim-tools/src/main/java/org/apache/directory/scim/tools/lint/Lint.java
/* * 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 * 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.directory.scim.tools.lint; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.InputStream; /** * Validates that a SCIM resource conforms to the associated schema definition. * Note that it's possible to validate schemas since the associated schema * definition is provided. It's also possible to validate the schema definition * against itself. This class provides the code to provide linting SCIM * resources, but there will be CLI and web tools that * @author smoyer1 * */ public class Lint { JsonNode convert(InputStream inputStream) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readTree(inputStream); } boolean hasMeta(JsonNode jsonNode) { return jsonNode.has("meta"); } boolean hasSchemas(JsonNode jsonNode) { return jsonNode.has("schemas"); } boolean isSchema(JsonNode jsonNode) { boolean schema = false; JsonNode metaJsonNode = jsonNode.get("meta"); if(metaJsonNode != null) { schema = "Schema".equals(metaJsonNode.get("resourceType").asText()); } return schema; } public boolean lint(InputStream inputStream) throws LintException, IOException { return lint(convert(inputStream)); } boolean lint(JsonNode jsonNode) throws LintException { boolean output = true; if(jsonNode.isArray()) { output = lintArray(jsonNode); } else if(jsonNode.isObject()) { output = lintObject(jsonNode); } else { throw new LintException("Unsupported JSON node type: " + jsonNode.getNodeType().name()); } return output; } boolean lintArray(JsonNode arrayJsonNode) throws LintException { boolean output = true; for(JsonNode jsonNode: arrayJsonNode) { if(jsonNode.isObject()) { output = output && lintObject(jsonNode); } else { throw new LintException("Unsupported JSON node type, expected Object, found " + jsonNode.getNodeType().name()); } } return output; } boolean lintObject(JsonNode objectJsonNode) throws LintException { boolean output = true; if(objectJsonNode.isObject()) { if(isSchema(objectJsonNode)) { output = lintSchema(objectJsonNode); } else { output = lintResource(objectJsonNode); } } else { throw new LintException("Unsupported JSON node type, expected Object, found " + objectJsonNode.getNodeType().name()); } return output; } boolean lintResource(JsonNode resourceJsonNode) { return false; } boolean lintSchema(JsonNode schemaJsonNode) { return false; } }
4,363
0
Create_ds/directory-scimple/support/spring-boot/src/test/java/org/apache/directory/scim/spring/it
Create_ds/directory-scimple/support/spring-boot/src/test/java/org/apache/directory/scim/spring/it/app/ScimpleSpringApp.java
/* * 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 * 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.directory.scim.spring.it.app; import org.apache.directory.scim.server.configuration.ServerConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import static org.apache.directory.scim.spec.schema.ServiceProviderConfiguration.AuthenticationSchema.httpBasic; @SpringBootApplication public class ScimpleSpringApp { public static void main(String[] args) { SpringApplication.run(ScimpleSpringApp.class, args); } @Bean ServerConfiguration serverConfiguration() { return new ServerConfiguration() .addAuthenticationSchema(httpBasic()); } }
4,364
0
Create_ds/directory-scimple/support/spring-boot/src/test/java/org/apache/directory/scim/spring/it
Create_ds/directory-scimple/support/spring-boot/src/test/java/org/apache/directory/scim/spring/it/app/SpringScimServer.java
/* * 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 * 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.directory.scim.spring.it.app; import org.apache.directory.scim.compliance.junit.EmbeddedServerExtension; import org.springframework.boot.SpringApplication; import org.springframework.context.ConfigurableApplicationContext; import java.net.URI; public class SpringScimServer implements EmbeddedServerExtension.ScimTestServer { private ConfigurableApplicationContext context; @Override public URI start(int port) { context = SpringApplication.run(ScimpleSpringApp.class, "--server.servlet.context-path=/v2", "--server.port=" + port ); return URI.create("http://localhost:" + port + "/v2"); } @Override public void shutdown() { context.stop(); } }
4,365
0
Create_ds/directory-scimple/support/spring-boot/src/test/java/org/apache/directory/scim/spring/it
Create_ds/directory-scimple/support/spring-boot/src/test/java/org/apache/directory/scim/spring/it/app/InMemoryGroupService.java
/* * 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 * 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.directory.scim.spring.it.app; import jakarta.annotation.PostConstruct; import jakarta.ws.rs.core.Response; import org.apache.commons.lang3.StringUtils; import org.apache.directory.scim.core.repository.Repository; import org.apache.directory.scim.core.repository.UpdateRequest; import org.apache.directory.scim.core.schema.SchemaRegistry; import org.apache.directory.scim.server.exception.UnableToCreateResourceException; import org.apache.directory.scim.server.exception.UnableToUpdateResourceException; import org.apache.directory.scim.spec.filter.*; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.resources.ScimGroup; import org.springframework.stereotype.Service; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; @Service public class InMemoryGroupService implements Repository<ScimGroup> { private final Map<String, ScimGroup> groups = new HashMap<>(); private final SchemaRegistry schemaRegistry; public InMemoryGroupService(SchemaRegistry schemaRegistry) { this.schemaRegistry = schemaRegistry; } @PostConstruct public void init() { ScimGroup group = new ScimGroup(); group.setId(UUID.randomUUID().toString()); group.setDisplayName("example-group"); group.setExternalId("example-group"); groups.put(group.getId(), group); } @Override public Class<ScimGroup> getResourceClass() { return ScimGroup.class; } @Override public ScimGroup create(ScimGroup resource) throws UnableToCreateResourceException { String id = UUID.randomUUID().toString(); // if the external ID is not set, use the displayName instead if (StringUtils.isEmpty(resource.getExternalId())) { resource.setExternalId(resource.getDisplayName()); } // check to make sure the group doesn't already exist boolean existingGroupFound = groups.values().stream() .anyMatch(group -> resource.getExternalId().equals(group.getExternalId())); if (existingGroupFound) { // HTTP leaking into data layer throw new UnableToCreateResourceException(Response.Status.CONFLICT, "Group '" + resource.getExternalId() + "' already exists."); } resource.setId(id); groups.put(id, resource); return resource; } @Override public ScimGroup update(UpdateRequest<ScimGroup> updateRequest) throws UnableToUpdateResourceException { String id = updateRequest.getId(); ScimGroup resource = updateRequest.getResource(); groups.put(id, resource); return resource; } @Override public ScimGroup get(String id) { return groups.get(id); } @Override public void delete(String id) { groups.remove(id); } @Override public FilterResponse<ScimGroup> find(Filter filter, PageRequest pageRequest, SortRequest sortRequest) { long count = pageRequest.getCount() != null ? pageRequest.getCount() : groups.size(); long startIndex = pageRequest.getStartIndex() != null ? pageRequest.getStartIndex() - 1 // SCIM is 1-based indexed : 0; List<ScimGroup> result = groups.values().stream() .skip(startIndex) .limit(count) .filter(FilterExpressions.inMemory(filter, schemaRegistry.getSchema(ScimGroup.SCHEMA_URI))) .collect(Collectors.toList()); return new FilterResponse<>(result, pageRequest, result.size()); } @Override public List<Class<? extends ScimExtension>> getExtensionList() { return Collections.emptyList(); } }
4,366
0
Create_ds/directory-scimple/support/spring-boot/src/test/java/org/apache/directory/scim/spring/it
Create_ds/directory-scimple/support/spring-boot/src/test/java/org/apache/directory/scim/spring/it/app/InMemoryUserService.java
/* * 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 * 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.directory.scim.spring.it.app; import jakarta.annotation.PostConstruct; import jakarta.ws.rs.core.Response; import org.apache.directory.scim.core.repository.Repository; import org.apache.directory.scim.core.repository.UpdateRequest; import org.apache.directory.scim.core.schema.SchemaRegistry; import org.apache.directory.scim.server.exception.UnableToCreateResourceException; import org.apache.directory.scim.server.exception.UnableToUpdateResourceException; import org.apache.directory.scim.spec.filter.*; import org.apache.directory.scim.spec.resources.*; import org.springframework.stereotype.Service; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Creates a singleton (effectively) Provider<User> with a memory-based * persistence layer. * * @author Chris Harm &lt;crh5255@psu.edu&gt; */ @Service public class InMemoryUserService implements Repository<ScimUser> { static final String DEFAULT_USER_ID = "1"; static final String DEFAULT_USER_EXTERNAL_ID = "e" + DEFAULT_USER_ID; static final String DEFAULT_USER_DISPLAY_NAME = "User " + DEFAULT_USER_ID; static final String DEFAULT_USER_EMAIL_VALUE = "e1@example.com"; static final String DEFAULT_USER_EMAIL_TYPE = "work"; static final int DEFAULT_USER_LUCKY_NUMBER = 7; private final Map<String, ScimUser> users = new HashMap<>(); private final SchemaRegistry schemaRegistry; public InMemoryUserService(SchemaRegistry schemaRegistry) { this.schemaRegistry = schemaRegistry; } @PostConstruct public void init() { ScimUser user = new ScimUser(); user.setId(DEFAULT_USER_ID); user.setExternalId(DEFAULT_USER_EXTERNAL_ID); user.setUserName(DEFAULT_USER_EXTERNAL_ID); user.setDisplayName(DEFAULT_USER_DISPLAY_NAME); user.setName(new Name() .setGivenName("Tester") .setFamilyName("McTest")); Email email = new Email(); email.setDisplay(DEFAULT_USER_EMAIL_VALUE); email.setValue(DEFAULT_USER_EMAIL_VALUE); email.setType(DEFAULT_USER_EMAIL_TYPE); email.setPrimary(true); user.setEmails(List.of(email)); // LuckyNumberExtension luckyNumberExtension = new LuckyNumberExtension(); // luckyNumberExtension.setLuckyNumber(DEFAULT_USER_LUCKY_NUMBER); // // user.addExtension(luckyNumberExtension); users.put(user.getId(), user); } @Override public Class<ScimUser> getResourceClass() { return ScimUser.class; } /** * @see Repository#create(ScimResource) */ @Override public ScimUser create(ScimUser resource) throws UnableToCreateResourceException { String resourceId = resource.getId(); int idCandidate = resource.hashCode(); String id = resourceId != null ? resourceId : Integer.toString(idCandidate); while (users.containsKey(id)) { id = Integer.toString(idCandidate); ++idCandidate; } // check to make sure the user doesn't already exist boolean existingUserFound = users.values().stream() .anyMatch(user -> user.getUserName().equals(resource.getUserName())); if (existingUserFound) { // HTTP leaking into data layer throw new UnableToCreateResourceException(Response.Status.CONFLICT, "User '" + resource.getUserName() + "' already exists."); } resource.setId(id); users.put(id, resource); return resource; } /** * @see Repository#update(UpdateRequest) */ @Override public ScimUser update(UpdateRequest<ScimUser> updateRequest) throws UnableToUpdateResourceException { String id = updateRequest.getId(); ScimUser resource = updateRequest.getResource(); users.put(id, resource); return resource; } /** * @see Repository#get(String) */ @Override public ScimUser get(String id) { return users.get(id); } /** * @see Repository#delete(String) */ @Override public void delete(String id) { users.remove(id); } /** * @see Repository#find(Filter, PageRequest, SortRequest) */ @Override public FilterResponse<ScimUser> find(Filter filter, PageRequest pageRequest, SortRequest sortRequest) { long count = pageRequest.getCount() != null ? pageRequest.getCount() : users.size(); long startIndex = pageRequest.getStartIndex() != null ? pageRequest.getStartIndex() - 1 // SCIM is 1-based indexed : 0; List<ScimUser> result = users.values().stream() .skip(startIndex) .limit(count) .filter(FilterExpressions.inMemory(filter, schemaRegistry.getSchema(ScimUser.SCHEMA_URI))) .collect(Collectors.toList()); return new FilterResponse<>(result, pageRequest, result.size()); } /** * @see Repository#getExtensionList() */ @Override public List<Class<? extends ScimExtension>> getExtensionList() { return Collections.emptyList(); } }
4,367
0
Create_ds/directory-scimple/support/spring-boot/src/main/java/org/apache/directory/scim
Create_ds/directory-scimple/support/spring-boot/src/main/java/org/apache/directory/scim/spring/ScimpleSpringConfiguration.java
/* * 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 * 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.directory.scim.spring; import jakarta.enterprise.inject.Instance; import jakarta.enterprise.util.TypeLiteral; import jakarta.ws.rs.core.Application; import org.apache.commons.lang3.NotImplementedException; import org.apache.directory.scim.core.repository.Repository; import org.apache.directory.scim.core.repository.RepositoryRegistry; import org.apache.directory.scim.core.repository.SelfIdResolver; import org.apache.directory.scim.core.schema.SchemaRegistry; import org.apache.directory.scim.protocol.UserResource; import org.apache.directory.scim.server.configuration.ServerConfiguration; import org.apache.directory.scim.server.rest.EtagGenerator; import org.apache.directory.scim.server.rest.ScimResourceHelper; import org.apache.directory.scim.server.rest.UserResourceImpl; import org.apache.directory.scim.spec.resources.ScimResource; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Autoconfigures default beans needed for Apache SCIMple. */ @Configuration @AutoConfigureBefore(JerseyAutoConfiguration.class) public class ScimpleSpringConfiguration { @Bean @ConditionalOnMissingBean ServerConfiguration serverConfiguration() { return new ServerConfiguration(); } @Bean @ConditionalOnMissingBean EtagGenerator etagGenerator() { return new EtagGenerator(); } @Bean @ConditionalOnMissingBean SchemaRegistry schemaRegistry() { return new SchemaRegistry(); } @Bean @ConditionalOnMissingBean @ConditionalOnBean(SelfIdResolver.class) Instance<SelfIdResolver> selfIdResolverInstance(SelfIdResolver selfIdResolver) { return SpringInstance.of(selfIdResolver); } @Bean @ConditionalOnMissingBean RepositoryRegistry repositoryRegistry(SchemaRegistry schemaRegistry, List<Repository<? extends ScimResource>> scimResources) { return new RepositoryRegistry(schemaRegistry, scimResources); } @Bean @ConditionalOnMissingBean Application jaxrsApplication() { return new ScimpleJaxRsApplication(); } @Bean @ConditionalOnMissingBean public ResourceConfig conf(Application app) { ResourceConfig config = ResourceConfig.forApplication(app); config.register(new AbstractBinder() { @Override protected void configure() { bind(UserResourceImpl.class).to(UserResource.class); // Used by SelfResource } }); return config; } /** * Basic JAX-RS application that includes the required SCIMple classes. */ static class ScimpleJaxRsApplication extends Application { @Override public Set<Class<?>> getClasses() { return ScimResourceHelper.scimpleFeatureAndResourceClasses(); } } /** * An implementation of {@code Instance} to expose Spring beans. * @param <T> the required bean type */ static class SpringInstance<T> implements Instance<T> { private final List<T> beans; public SpringInstance(T[] beans) { this(Arrays.asList(beans)); } public SpringInstance(List<T> beans) { this.beans = beans; } @Override public Instance<T> select(Annotation... qualifiers) { throw new NotImplementedException("This implementation does not support the `select` method."); } @Override public <U extends T> Instance<U> select(Class<U> subtype, Annotation... qualifiers) { throw new NotImplementedException("This implementation does not support the `select` method."); } @Override public <U extends T> Instance<U> select(TypeLiteral<U> subtype, Annotation... qualifiers) { throw new NotImplementedException("This implementation does not support the `select` method."); } @Override public boolean isUnsatisfied() { return beans.isEmpty(); } @Override public boolean isAmbiguous() { return beans.size() > 1; } @Override public void destroy(T instance) { beans.remove(instance); } @Override public Handle<T> getHandle() { throw new NotImplementedException("This implementation does not support the `getHandle` method."); } @Override public Iterable<? extends Handle<T>> handles() { throw new NotImplementedException("This implementation does not support the `handles` method."); } @Override public T get() { if (isAmbiguous()) { throw new IllegalStateException("Multiple bean instances found, expecting only one."); } return beans.stream() .findFirst() .orElse(null); } @Override public Iterator<T> iterator() { return beans.iterator(); } public static <T> SpringInstance<T> of(T... beans) { return new SpringInstance<>(beans); } } }
4,368
0
Create_ds/directory-scimple/.mvn
Create_ds/directory-scimple/.mvn/wrapper/MavenWrapperDownloader.java
/* 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 https://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. */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.Properties; public class MavenWrapperDownloader { /** * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. */ private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; /** * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to * use instead of the default one. */ private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties"; /** * Path where the maven-wrapper.jar will be saved to. */ private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; /** * Name of the property which should be used to override the default download url for the wrapper. */ private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; public static void main(String args[]) { System.out.println("- Downloader started"); File baseDirectory = new File(args[0]); System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); // If the maven-wrapper.properties exists, read it and check if it contains a custom // wrapperUrl parameter. File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); String url = DEFAULT_DOWNLOAD_URL; if (mavenWrapperPropertyFile.exists()) { FileInputStream mavenWrapperPropertyFileInputStream = null; try { mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); Properties mavenWrapperProperties = new Properties(); mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); } catch (IOException e) { System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); } finally { try { if (mavenWrapperPropertyFileInputStream != null) { mavenWrapperPropertyFileInputStream.close(); } } catch (IOException e) { // Ignore ... } } } System.out.println("- Downloading from: : " + url); File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); if (!outputFile.getParentFile().exists()) { if (!outputFile.getParentFile().mkdirs()) { System.out.println( "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); } } System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); try { downloadFileFromURL(url, outputFile); System.out.println("Done"); System.exit(0); } catch (Throwable e) { System.out.println("- Error downloading"); e.printStackTrace(); System.exit(1); } } private static void downloadFileFromURL(String urlString, File destination) throws Exception { URL website = new URL(urlString); ReadableByteChannel rbc; rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(destination); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); } }
4,369
0
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server/it/JerseyTestServer.java
/* * 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 * 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.directory.scim.server.it; import jakarta.enterprise.inject.se.SeContainer; import jakarta.enterprise.inject.se.SeContainerInitializer; import jakarta.ws.rs.SeBootstrap; import jakarta.ws.rs.core.UriBuilder; import org.apache.directory.scim.compliance.junit.EmbeddedServerExtension; import org.apache.directory.scim.server.it.testapp.App; import org.glassfish.jersey.server.JerseySeBootstrapConfiguration; import org.glassfish.jersey.server.internal.RuntimeDelegateImpl; import java.net.URI; import java.util.concurrent.TimeUnit; public class JerseyTestServer implements EmbeddedServerExtension.ScimTestServer { private SeBootstrap.Instance server; private SeContainer container; @Override public URI start(int port) throws Exception { container = SeContainerInitializer.newInstance() .addPackages(true, App.class.getPackage()) .initialize(); // There are multiple JAX-RS implementations on the classpath, Jersey for the server and RestEasy for testing // explicitly use Jersey so the test implementation is not use to start the server server = new RuntimeDelegateImpl().bootstrap(new App(), JerseySeBootstrapConfiguration.builder().port(port).build()) .toCompletableFuture().get(1, TimeUnit.MINUTES); // shut down CDI container on stop server.stopOnShutdown(stopResult -> container.close()); return UriBuilder.fromUri("http://localhost/").port(port).build(); } @Override public void shutdown() throws Exception { if (server != null) { server.stop().toCompletableFuture() .get(10, TimeUnit.SECONDS); } if (container != null) { container.close(); } } }
4,370
0
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server/it/CustomExtensionIT.java
/* * 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 * 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.directory.scim.server.it; import org.apache.directory.scim.compliance.junit.EmbeddedServerExtension; import org.apache.directory.scim.compliance.tests.ScimpleITSupport; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import static org.hamcrest.Matchers.*; @ExtendWith(EmbeddedServerExtension.class) public class CustomExtensionIT extends ScimpleITSupport { @Test public void extensionDataTest() { String body = "{" + "\"schemas\":[\"urn:ietf:params:scim:schemas:core:2.0:User\"]," + "\"userName\":\"test@example.com\"," + "\"name\":{" + "\"givenName\":\"Tester\"," + "\"familyName\":\"McTest\"}," + "\"emails\":[{" + "\"primary\":true," + "\"value\":\"test@example.com\"," + "\"type\":\"work\"}]," + "\"displayName\":\"Tester McTest\"," + "\"active\":true," + "\"urn:mem:params:scim:schemas:extension:LuckyNumberExtension\": {" + "\"luckyNumber\": \"1234\"}" + // This value can be a number or string, but will always be a number in the body "}"; post("/Users", body) .statusCode(201) .body( "schemas", contains("urn:ietf:params:scim:schemas:core:2.0:User", "urn:mem:params:scim:schemas:extension:LuckyNumberExtension"), "active", is(true), "id", not(emptyString()), "'urn:mem:params:scim:schemas:extension:LuckyNumberExtension'", notNullValue(), "'urn:mem:params:scim:schemas:extension:LuckyNumberExtension'.luckyNumber", is(1234) ); } }
4,371
0
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server/it
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server/it/testapp/LuckyNumberExtension.java
/* * 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 * 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.directory.scim.server.it.testapp; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import lombok.Data; import org.apache.directory.scim.spec.annotation.ScimAttribute; import org.apache.directory.scim.spec.annotation.ScimExtensionType; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.schema.Schema; /** * Allows a User's lucky number to be passed as part of the User's entry via * the SCIM protocol. * * @author Chris Harm &lt;crh5255@psu.edu&gt; */ @XmlRootElement( name = "LuckyNumberExtension", namespace = "http://www.psu.edu/schemas/psu-scim" ) @XmlAccessorType(XmlAccessType.NONE) @Data @ScimExtensionType(id = LuckyNumberExtension.SCHEMA_URN, description="Lucky Numbers", name="LuckyNumbers", required=true) public class LuckyNumberExtension implements ScimExtension { public static final String SCHEMA_URN = "urn:mem:params:scim:schemas:extension:LuckyNumberExtension"; @ScimAttribute(returned=Schema.Attribute.Returned.DEFAULT, required=true) @XmlElement private long luckyNumber; /** * Provides the URN associated with this extension which, as defined by the * SCIM specification is the extension's unique identifier. * * @return The extension's URN. */ @Override public String getUrn() { return SCHEMA_URN; } }
4,372
0
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server/it
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server/it/testapp/InMemorySelfResolverImpl.java
/* * 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 * 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.directory.scim.server.it.testapp; import jakarta.enterprise.context.ApplicationScoped; import jakarta.ws.rs.core.Response.Status; import org.apache.directory.scim.server.exception.UnableToResolveIdResourceException; import org.apache.directory.scim.core.repository.SelfIdResolver; import java.security.Principal; @ApplicationScoped public class InMemorySelfResolverImpl implements SelfIdResolver { @Override public String resolveToInternalId(Principal principal) throws UnableToResolveIdResourceException { throw new UnableToResolveIdResourceException(Status.NOT_IMPLEMENTED, "Caller Principal not available"); } }
4,373
0
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server/it
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server/it/testapp/InMemoryGroupService.java
/* * 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 * 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.directory.scim.server.it.testapp; import jakarta.annotation.PostConstruct; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.inject.Named; import jakarta.ws.rs.core.Response; import org.apache.commons.lang3.StringUtils; import org.apache.directory.scim.server.exception.UnableToCreateResourceException; import org.apache.directory.scim.server.exception.UnableToUpdateResourceException; import org.apache.directory.scim.core.repository.Repository; import org.apache.directory.scim.core.repository.UpdateRequest; import org.apache.directory.scim.spec.filter.FilterExpressions; import org.apache.directory.scim.spec.filter.FilterResponse; import org.apache.directory.scim.spec.filter.Filter; import org.apache.directory.scim.spec.filter.PageRequest; import org.apache.directory.scim.spec.filter.SortRequest; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.resources.ScimGroup; import org.apache.directory.scim.core.schema.SchemaRegistry; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; @Named @ApplicationScoped public class InMemoryGroupService implements Repository<ScimGroup> { private final Map<String, ScimGroup> groups = new HashMap<>(); private SchemaRegistry schemaRegistry; @Inject public InMemoryGroupService(SchemaRegistry schemaRegistry) { this.schemaRegistry = schemaRegistry; } protected InMemoryGroupService() {} @PostConstruct public void init() { ScimGroup group = new ScimGroup(); group.setId(UUID.randomUUID().toString()); group.setDisplayName("example-group"); group.setExternalId("example-group"); groups.put(group.getId(), group); } @Override public Class<ScimGroup> getResourceClass() { return ScimGroup.class; } @Override public ScimGroup create(ScimGroup resource) throws UnableToCreateResourceException { String id = UUID.randomUUID().toString(); // if the external ID is not set, use the displayName instead if (StringUtils.isEmpty(resource.getExternalId())) { resource.setExternalId(resource.getDisplayName()); } // check to make sure the group doesn't already exist boolean existingGroupFound = groups.values().stream() .anyMatch(group -> resource.getExternalId().equals(group.getExternalId())); if (existingGroupFound) { // HTTP leaking into data layer throw new UnableToCreateResourceException(Response.Status.CONFLICT, "Group '" + resource.getExternalId() + "' already exists."); } resource.setId(id); groups.put(id, resource); return resource; } @Override public ScimGroup update(UpdateRequest<ScimGroup> updateRequest) throws UnableToUpdateResourceException { String id = updateRequest.getId(); ScimGroup resource = updateRequest.getResource(); groups.put(id, resource); return resource; } @Override public ScimGroup get(String id) { return groups.get(id); } @Override public void delete(String id) { groups.remove(id); } @Override public FilterResponse<ScimGroup> find(Filter filter, PageRequest pageRequest, SortRequest sortRequest) { long count = pageRequest.getCount() != null ? pageRequest.getCount() : groups.size(); long startIndex = pageRequest.getStartIndex() != null ? pageRequest.getStartIndex() - 1 // SCIM is 1-based indexed : 0; List<ScimGroup> result = groups.values().stream() .skip(startIndex) .limit(count) .filter(FilterExpressions.inMemory(filter, schemaRegistry.getSchema(ScimGroup.SCHEMA_URI))) .collect(Collectors.toList()); return new FilterResponse<>(result, pageRequest, result.size()); } @Override public List<Class<? extends ScimExtension>> getExtensionList() { return Collections.emptyList(); } }
4,374
0
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server/it
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server/it/testapp/App.java
/* * 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 * 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.directory.scim.server.it.testapp; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Produces; import jakarta.ws.rs.core.Application; import org.apache.directory.scim.server.configuration.ServerConfiguration; import org.apache.directory.scim.server.rest.ScimResourceHelper; import java.util.Set; import static org.apache.directory.scim.spec.schema.ServiceProviderConfiguration.AuthenticationSchema.httpBasic; @ApplicationScoped public class App extends Application { @Override public Set<Class<?>> getClasses() { return ScimResourceHelper.scimpleFeatureAndResourceClasses(); } @Produces ServerConfiguration serverConfiguration() { return new ServerConfiguration() .setId("scimple-server-its") .addAuthenticationSchema(httpBasic()); } }
4,375
0
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server/it
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server/it/testapp/InMemoryUserService.java
/* * 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 * 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.directory.scim.server.it.testapp; import jakarta.annotation.PostConstruct; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.inject.Named; import jakarta.ws.rs.core.Response; import org.apache.directory.scim.server.exception.UnableToCreateResourceException; import org.apache.directory.scim.server.exception.UnableToUpdateResourceException; import org.apache.directory.scim.core.repository.Repository; import org.apache.directory.scim.core.repository.UpdateRequest; import org.apache.directory.scim.spec.filter.FilterExpressions; import org.apache.directory.scim.spec.filter.FilterResponse; import org.apache.directory.scim.spec.filter.Filter; import org.apache.directory.scim.spec.filter.PageRequest; import org.apache.directory.scim.spec.filter.SortRequest; import org.apache.directory.scim.spec.resources.*; import org.apache.directory.scim.core.schema.SchemaRegistry; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Creates a singleton (effectively) Repository<ScimUser> with a memory-based * persistence layer. * * @author Chris Harm &lt;crh5255@psu.edu&gt; */ @Named @ApplicationScoped public class InMemoryUserService implements Repository<ScimUser> { static final String DEFAULT_USER_ID = "1"; static final String DEFAULT_USER_EXTERNAL_ID = "e" + DEFAULT_USER_ID; static final String DEFAULT_USER_DISPLAY_NAME = "User " + DEFAULT_USER_ID; static final String DEFAULT_USER_EMAIL_VALUE = "e1@example.com"; static final String DEFAULT_USER_EMAIL_TYPE = "work"; static final int DEFAULT_USER_LUCKY_NUMBER = 7; private final Map<String, ScimUser> users = new HashMap<>(); private SchemaRegistry schemaRegistry; @Inject public InMemoryUserService(SchemaRegistry schemaRegistry) { this.schemaRegistry = schemaRegistry; } protected InMemoryUserService() {} @PostConstruct public void init() { ScimUser user = new ScimUser(); user.setId(DEFAULT_USER_ID); user.setExternalId(DEFAULT_USER_EXTERNAL_ID); user.setUserName(DEFAULT_USER_EXTERNAL_ID); user.setDisplayName(DEFAULT_USER_DISPLAY_NAME); user.setName(new Name() .setGivenName("Tester") .setFamilyName("McTest")); Email email = new Email(); email.setDisplay(DEFAULT_USER_EMAIL_VALUE); email.setValue(DEFAULT_USER_EMAIL_VALUE); email.setType(DEFAULT_USER_EMAIL_TYPE); email.setPrimary(true); user.setEmails(List.of(email)); user.addExtension(new LuckyNumberExtension().setLuckyNumber(DEFAULT_USER_LUCKY_NUMBER)); users.put(user.getId(), user); } @Override public Class<ScimUser> getResourceClass() { return ScimUser.class; } /** * @see Repository#create(ScimResource) */ @Override public ScimUser create(ScimUser resource) throws UnableToCreateResourceException { String resourceId = resource.getId(); int idCandidate = resource.hashCode(); String id = resourceId != null ? resourceId : Integer.toString(idCandidate); while (users.containsKey(id)) { id = Integer.toString(idCandidate); ++idCandidate; } // check to make sure the user doesn't already exist boolean existingUserFound = users.values().stream() .anyMatch(user -> user.getUserName().equals(resource.getUserName())); if (existingUserFound) { // HTTP leaking into data layer throw new UnableToCreateResourceException(Response.Status.CONFLICT, "User '" + resource.getUserName() + "' already exists."); } resource.setId(id); users.put(id, resource); return resource; } /** * @see Repository#update(UpdateRequest) */ @Override public ScimUser update(UpdateRequest<ScimUser> updateRequest) throws UnableToUpdateResourceException { String id = updateRequest.getId(); ScimUser resource = updateRequest.getResource(); users.put(id, resource); return resource; } /** * @see Repository#get(String) */ @Override public ScimUser get(String id) { return users.get(id); } /** * @see Repository#delete(String) */ @Override public void delete(String id) { users.remove(id); } /** * @see Repository#find(Filter, PageRequest, SortRequest) */ @Override public FilterResponse<ScimUser> find(Filter filter, PageRequest pageRequest, SortRequest sortRequest) { long count = pageRequest.getCount() != null ? pageRequest.getCount() : users.size(); long startIndex = pageRequest.getStartIndex() != null ? pageRequest.getStartIndex() - 1 // SCIM is 1-based indexed : 0; List<ScimUser> result = users.values().stream() .skip(startIndex) .limit(count) .filter(FilterExpressions.inMemory(filter, schemaRegistry.getSchema(ScimUser.SCHEMA_URI))) .collect(Collectors.toList()); return new FilterResponse<>(result, pageRequest, result.size()); } /** * @see Repository#getExtensionList() */ @Override public List<Class<? extends ScimExtension>> getExtensionList() { return List.of(LuckyNumberExtension.class); } }
4,376
0
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server/rest/AttributeUtilTest.java
/* * 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 * 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.directory.scim.server.rest; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.directory.scim.core.json.ObjectMapperFactory; import org.apache.directory.scim.server.utility.ExampleObjectExtension; import org.apache.directory.scim.server.utility.ExampleObjectExtension.ComplexObject; import org.apache.directory.scim.spec.extension.EnterpriseExtension; import org.apache.directory.scim.spec.extension.EnterpriseExtension.Manager; import org.apache.directory.scim.spec.phonenumber.PhoneNumberParseException; import org.apache.directory.scim.spec.filter.attribute.AttributeReference; import org.apache.directory.scim.spec.resources.Address; import org.apache.directory.scim.spec.resources.Name; import org.apache.directory.scim.spec.resources.PhoneNumber; import org.apache.directory.scim.spec.resources.PhoneNumber.LocalPhoneNumberBuilder; import org.apache.directory.scim.spec.resources.ScimUser; import org.apache.directory.scim.spec.schema.Schema; import org.apache.directory.scim.core.schema.SchemaRegistry; import org.apache.directory.scim.spec.schema.Schemas; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; public class AttributeUtilTest { private static final Logger LOG = LoggerFactory.getLogger(AttributeUtilTest.class); SchemaRegistry schemaRegistry; AttributeUtil attributeUtil; final private ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper(); @BeforeEach public void setup() { schemaRegistry = new SchemaRegistry(); schemaRegistry.addSchema(ScimUser.class, List.of(EnterpriseExtension.class, ExampleObjectExtension.class)); attributeUtil = new AttributeUtil(schemaRegistry); } @Test public void testBaseResource() throws Exception { ScimUser resource = getScimUser(); debugJson(resource); resource = attributeUtil.setAttributesForDisplay(resource); debugJson(resource); Assertions.assertThat(resource.getId()).isNotNull(); Assertions.assertThat(resource.getPassword()).isNull(); EnterpriseExtension extension = resource.getExtension(EnterpriseExtension.class); Assertions.assertThat(extension.getCostCenter()).isNotNull(); ExampleObjectExtension exampleObjectExtension = resource.getExtension(ExampleObjectExtension.class); Assertions.assertThat(exampleObjectExtension.getValueAlways()).isNotNull(); Assertions.assertThat(exampleObjectExtension.getValueDefault()).isNotNull(); Assertions.assertThat(exampleObjectExtension.getValueRequest()).isNull(); Assertions.assertThat(exampleObjectExtension.getValueNever()).isNull(); } @Test public void testIncludeAttributes() throws Exception { ScimUser resource = getScimUser(); debugJson(resource); Set<AttributeReference> attributes = new HashSet<>(); attributes.add(new AttributeReference("userName")); attributes.add(new AttributeReference("addresses.streetAddress")); resource = attributeUtil.setAttributesForDisplay(resource, attributes); debugJson(resource); Assertions.assertThat(resource.getUserName()).isNotNull(); Assertions.assertThat(resource.getId()).isNotNull(); Assertions.assertThat(resource.getPassword()).isNull(); Assertions.assertThat(resource.getActive()).isNull(); Assertions.assertThat(resource.getAddresses().get(0).getCountry()).isNull(); Assertions.assertThat(resource.getAddresses().get(0).getStreetAddress()).isNotNull(); EnterpriseExtension extension = resource.getExtension(EnterpriseExtension.class); Assertions.assertThat(extension).as("%s should have been removed from extensions", EnterpriseExtension.URN).isNull(); } @Test public void testIncludeFullAttributes() throws Exception { ScimUser resource = getScimUser(); debugJson(resource); Set<AttributeReference> attributes = new HashSet<>(); attributes.add(new AttributeReference("userName")); attributes.add(new AttributeReference("name")); attributes.add(new AttributeReference("addresses")); resource = attributeUtil.setAttributesForDisplay(resource, attributes); debugJson(resource); Assertions.assertThat(resource.getUserName()).isNotNull(); Assertions.assertThat(resource.getId()).isNotNull(); Assertions.assertThat(resource.getPassword()).isNull(); Assertions.assertThat(resource.getActive()).isNull(); Assertions.assertThat(resource.getAddresses().get(0).getCountry()).isNotNull(); Assertions.assertThat(resource.getAddresses().get(0).getStreetAddress()).isNotNull(); Assertions.assertThat(resource.getAddresses().get(0).getCountry()).isNotNull(); EnterpriseExtension extension = resource.getExtension(EnterpriseExtension.class); Assertions.assertThat(extension).as("%s should have been removed from extensions", EnterpriseExtension.URN).isNull(); } @Test public void testIncludeAttributesWithExtension() throws Exception { ScimUser resource = getScimUser(); debugJson(resource); Set<AttributeReference> attributeSet = new HashSet<>(); attributeSet.add(new AttributeReference("userName")); attributeSet.add(new AttributeReference(EnterpriseExtension.URN + ":costCenter")); resource = attributeUtil.setAttributesForDisplay(resource, attributeSet); debugJson(resource); Assertions.assertThat(resource.getUserName()).isNotNull(); Assertions.assertThat(resource.getId()).isNotNull(); Assertions.assertThat(resource.getPassword()).isNull(); Assertions.assertThat(resource.getActive()).isNull(); EnterpriseExtension extension = resource.getExtension(EnterpriseExtension.class); Assertions.assertThat(extension.getCostCenter()).isNotNull(); Assertions.assertThat(extension.getDepartment()).isNull(); } @Test public void testExcludeAttributes() throws Exception { ScimUser resource = getScimUser(); debugJson(resource); Set<AttributeReference> attributeSet = new HashSet<>(); attributeSet.add(new AttributeReference("userName")); attributeSet.add(new AttributeReference("addresses")); attributeSet.add(new AttributeReference("name")); resource = attributeUtil.setExcludedAttributesForDisplay(resource, attributeSet); debugJson(resource); Assertions.assertThat(resource.getId()).isNotNull(); Assertions.assertThat(resource.getPassword()).isNull(); Assertions.assertThat(resource.getUserName()).isNull(); Assertions.assertThat(resource.getActive()).isNotNull(); Assertions.assertThat(resource.getAddresses()).isNull(); Assertions.assertThat(resource.getName()).isNull(); EnterpriseExtension extension = resource.getExtension(EnterpriseExtension.class); Assertions.assertThat(extension.getCostCenter()).isNotNull(); } @Test public void testExcludeAttributesWithExtensions() throws Exception { ScimUser resource = getScimUser(); Set<AttributeReference> attributeSet = new HashSet<>(); attributeSet.add(new AttributeReference("userName")); attributeSet.add(new AttributeReference(EnterpriseExtension.URN + ":costCenter")); resource = attributeUtil.setExcludedAttributesForDisplay(resource, attributeSet); Assertions.assertThat(resource.getId()).isNotNull(); Assertions.assertThat(resource.getPassword()).isNull(); Assertions.assertThat(resource.getUserName()).isNull(); Assertions.assertThat(resource.getActive()).isNotNull(); EnterpriseExtension extension = resource.getExtension(EnterpriseExtension.class); Assertions.assertThat(extension.getCostCenter()).isNull(); Assertions.assertThat(extension.getDepartment()).isNotNull(); } private void debugJson(Object resource) throws JsonGenerationException, JsonMappingException, IOException { StringWriter sw = new StringWriter(); objectMapper.writeValue(sw, resource); LOG.debug(sw.toString()); } private ScimUser getScimUser() throws PhoneNumberParseException { ScimUser user = new ScimUser(); user.setActive(true); user.setId("1"); user.setExternalId("e1"); user.setUserName("jed1"); user.setActive(true); user.setNickName("Jonny"); user.setPassword("secret"); user.setPreferredLanguage("English"); user.setProfileUrl("http://example.com/Users/JohnDoe"); user.setUserName("jed1"); user.setDisplayName("John Doe"); Name name = new Name(); name.setHonorificPrefix("Mr."); name.setGivenName("John"); name.setMiddleName("E"); name.setFamilyName("Doe"); name.setHonorificSuffix("Jr."); name.setFormatted("Mr. John E. Doe Jr."); user.setName(name); List<Address> addresses = new ArrayList<>(); Address address = new Address(); address.setStreetAddress("123 Main St."); address.setLocality("State College"); address.setRegion("PA"); address.setPostalCode("16801"); address.setCountry("USA"); address.setType("home"); address.setPrimary(true); address.setDisplay("123 Main St. State College, PA 16801"); address.setFormatted("123 Main St. State College, PA 16801"); addresses.add(address); address = new Address(); address.setStreetAddress("456 Main St."); address.setLocality("State College"); address.setRegion("PA"); address.setPostalCode("16801"); address.setCountry("USA"); address.setType("work"); address.setPrimary(false); address.setDisplay("456 Main St. State College, PA 16801"); address.setFormatted("456 Main St. State College, PA 16801"); addresses.add(address); user.setAddresses(addresses); List<PhoneNumber> phoneNumbers = new ArrayList<>(); LocalPhoneNumberBuilder lpnb = new LocalPhoneNumberBuilder(); PhoneNumber phoneNumber = lpnb.areaCode("123").countryCode("1").subscriberNumber("456-7890").build(); phoneNumber.setDisplay("123-456-7890"); phoneNumber.setPrimary(true); phoneNumber.setType("home"); phoneNumbers.add(phoneNumber); phoneNumber = new PhoneNumber(); phoneNumber.setValue("tel:+1-800-555-1234"); phoneNumber.setDisplay("1-800-555-1234"); phoneNumber.setPrimary(false); phoneNumber.setType("work"); phoneNumbers.add(phoneNumber); user.setPhoneNumbers(phoneNumbers); EnterpriseExtension enterpriseEntension = new EnterpriseExtension(); enterpriseEntension.setCostCenter("CC-123"); enterpriseEntension.setDepartment("DEPT-xyz"); enterpriseEntension.setDivision("DIV-1"); enterpriseEntension.setEmployeeNumber("1234567890"); Manager manager = new Manager(); manager.setDisplayName("Bob Smith"); manager.setValue("0987654321"); enterpriseEntension.setManager(manager); enterpriseEntension.setOrganization("ORG-X"); user.addExtension(enterpriseEntension); ExampleObjectExtension exampleObjectExtension = new ExampleObjectExtension(); exampleObjectExtension.setValueAlways("always"); exampleObjectExtension.setValueDefault("default"); exampleObjectExtension.setValueNever("never"); exampleObjectExtension.setValueRequest("request"); ComplexObject valueComplex = new ComplexObject(); valueComplex.setDisplayName("ValueComplex"); valueComplex.setValue("Value"); exampleObjectExtension.setValueComplex(valueComplex); user.addExtension(exampleObjectExtension); return user; } }
4,377
0
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server/rest/SelfResourceImplTest.java
/* * 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 * 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.directory.scim.server.rest; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.security.Principal; import jakarta.enterprise.inject.Instance; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; import org.apache.directory.scim.server.exception.UnableToResolveIdResourceException; import org.apache.directory.scim.spec.exception.ResourceException; import org.apache.directory.scim.core.repository.SelfIdResolver; import org.apache.directory.scim.protocol.UserResource; import org.apache.directory.scim.protocol.exception.ScimException; import org.junit.jupiter.api.Test; public class SelfResourceImplTest { @Test public void noSelfIdResolverTest() { Principal principal = mock(Principal.class); SecurityContext securityContext = mock(SecurityContext.class); @SuppressWarnings("unchecked") Instance<SelfIdResolver> selfIdResolverInstance = mock(Instance.class); when(securityContext.getUserPrincipal()).thenReturn(principal); when(principal.getName()).thenReturn("test-user"); when(selfIdResolverInstance.isUnsatisfied()).thenReturn(true); SelfResourceImpl selfResource = new SelfResourceImpl(null, selfIdResolverInstance); selfResource.securityContext = securityContext; UnableToResolveIdResourceException exception = assertThrows(UnableToResolveIdResourceException.class, () -> selfResource.getSelf(null, null)); assertThat(exception.getMessage(), is("Caller SelfIdResolver not available")); } @Test public void withSelfIdResolverTest() throws ResourceException, ScimException { String internalId = "test-user-resolved"; Principal principal = mock(Principal.class); SecurityContext securityContext = mock(SecurityContext.class); @SuppressWarnings("unchecked") Instance<SelfIdResolver> selfIdResolverInstance = mock(Instance.class); SelfIdResolver selfIdResolver = mock(SelfIdResolver.class); UserResource userResource = mock(UserResource.class); Response mockResponse = mock(Response.class); when(securityContext.getUserPrincipal()).thenReturn(principal); when(principal.getName()).thenReturn("test-user"); when(selfIdResolverInstance.isUnsatisfied()).thenReturn(false); when(selfIdResolverInstance.get()).thenReturn(selfIdResolver); when(selfIdResolver.resolveToInternalId(principal)).thenReturn(internalId); when(userResource.getById(internalId, null, null)).thenReturn(mockResponse); SelfResourceImpl selfResource = new SelfResourceImpl(userResource, selfIdResolverInstance); selfResource.securityContext = securityContext; // the response is just a passed along from the UserResource, so just validate it is the same instance. assertThat(selfResource.getSelf(null, null), sameInstance(mockResponse)); } }
4,378
0
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server/rest/BaseResourceTypeResourceImplTest.java
/* * 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 * 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.directory.scim.server.rest; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.Response.Status; import jakarta.ws.rs.core.UriInfo; import org.apache.directory.scim.protocol.exception.ScimException; import org.apache.directory.scim.spec.exception.ResourceException; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.apache.directory.scim.core.repository.Repository; import org.apache.directory.scim.server.utility.ExampleObjectExtension; import org.apache.directory.scim.server.utility.ExampleObjectExtension.ComplexObject; import org.apache.directory.scim.spec.extension.EnterpriseExtension; import org.apache.directory.scim.spec.extension.EnterpriseExtension.Manager; import org.apache.directory.scim.spec.phonenumber.PhoneNumberParseException; import org.apache.directory.scim.spec.filter.attribute.AttributeReferenceListWrapper; import org.apache.directory.scim.protocol.data.PatchRequest; import org.apache.directory.scim.protocol.data.SearchRequest; import org.apache.directory.scim.spec.resources.Address; import org.apache.directory.scim.spec.resources.Name; import org.apache.directory.scim.spec.resources.PhoneNumber; import org.apache.directory.scim.spec.resources.ScimUser; import org.apache.directory.scim.spec.resources.PhoneNumber.GlobalPhoneNumberBuilder; import org.apache.directory.scim.spec.resources.PhoneNumber.LocalPhoneNumberBuilder; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public class BaseResourceTypeResourceImplTest { @Mock Repository<ScimUser> repository; AttributeReferenceListWrapper includedAttributeList = new AttributeReferenceListWrapper("name.givenName, name.familyName"); AttributeReferenceListWrapper excludedAttributeList = new AttributeReferenceListWrapper("emails, phoneNumbers"); @Test public void testGetProviderInternal_ScimServerExceptionThrownWhenNoProvider() throws ScimException { // given @SuppressWarnings("rawtypes") BaseResourceTypeResourceImpl baseResourceImpl = mock(BaseResourceTypeResourceImpl.class); when(baseResourceImpl.getRepositoryInternal()).thenCallRealMethod(); // when assertThrows(ScimException.class, () -> baseResourceImpl.getRepositoryInternal()); } @SuppressWarnings("unchecked") @Test public void testGetById_ForbiddenIfNoFilter() throws ScimException, ResourceException { // given @SuppressWarnings("rawtypes") BaseResourceTypeResourceImpl baseResourceImpl = mock(BaseResourceTypeResourceImpl.class); UriInfo uriInfo = mock(UriInfo.class); MultivaluedMap queryParams = mock(MultivaluedMap.class); baseResourceImpl.uriInfo = uriInfo; when(uriInfo.getQueryParameters()).thenReturn(queryParams); when(queryParams.getFirst("filter")).thenReturn("not null"); when(baseResourceImpl.getById("1", includedAttributeList, excludedAttributeList)).thenCallRealMethod(); // when Response response = baseResourceImpl.getById("1", includedAttributeList, excludedAttributeList); // then assertNotNull(response); assertEquals(response.getStatus(), Status.FORBIDDEN.getStatusCode()); } @Test public void testQuery_NullParametersValid() throws ScimException, ResourceException { // given @SuppressWarnings("rawtypes") BaseResourceTypeResourceImpl baseResourceImpl = mock(BaseResourceTypeResourceImpl.class); SearchRequest searchRequest = new SearchRequest(); searchRequest.setAttributes(Collections.emptySet()); searchRequest.setExcludedAttributes(Collections.emptySet()); when(baseResourceImpl.find(searchRequest)).thenReturn(Response.ok().build()); when(baseResourceImpl.query(null, null, null, null, null, null, null)).thenCallRealMethod(); // when Response response = baseResourceImpl.query(null, null, null, null, null, null, null); // then verify(baseResourceImpl, times(1)).find(searchRequest); assertNotNull(response); assertEquals(response.getStatus(), Status.OK.getStatusCode()); } @Test public void testCreate_ErrorIfBothAttributesAndExcludedAttributesExist() throws ScimException, ResourceException, PhoneNumberParseException { // given @SuppressWarnings("unchecked") BaseResourceTypeResourceImpl<ScimUser> baseResourceImpl = mock(BaseResourceTypeResourceImpl.class); ScimUser scimUser = getScimUser(); when(baseResourceImpl.create(scimUser, includedAttributeList, excludedAttributeList)).thenCallRealMethod(); // when ScimException exception = assertThrows(ScimException.class, () -> baseResourceImpl.create(scimUser, includedAttributeList, excludedAttributeList)); // then assertEquals(exception.getStatus(), Status.BAD_REQUEST); assertThat(exception.getError().getDetail(), is("Cannot include both attributes and excluded attributes in a single request")); } @Test public void testFind_ErrorIfBothAttributesAndExcludedAttributesExist() throws ScimException, ResourceException { // given @SuppressWarnings("rawtypes") BaseResourceTypeResourceImpl baseResourceImpl = mock(BaseResourceTypeResourceImpl.class); SearchRequest searchRequest = new SearchRequest(); searchRequest.setAttributes(includedAttributeList.getAttributeReferences()); searchRequest.setExcludedAttributes(excludedAttributeList.getAttributeReferences()); when(baseResourceImpl.find(searchRequest)).thenCallRealMethod(); // when ScimException exception = assertThrows(ScimException.class, () -> baseResourceImpl.find(searchRequest)); // then assertEquals(exception.getStatus(), Status.BAD_REQUEST); assertThat(exception.getError().getDetail(), is("Cannot include both attributes and excluded attributes in a single request")); } @Test public void testUpdate_ErrorIfBothAttributesAndExcludedAttributesExist() throws ScimException, ResourceException, PhoneNumberParseException { // given @SuppressWarnings("unchecked") BaseResourceTypeResourceImpl<ScimUser> baseResourceImpl = mock(BaseResourceTypeResourceImpl.class); ScimUser scimUser = getScimUser(); when(baseResourceImpl.update(scimUser, "1", includedAttributeList, excludedAttributeList)).thenCallRealMethod(); // when ScimException exception = assertThrows(ScimException.class, () -> baseResourceImpl.update(scimUser, "1", includedAttributeList, excludedAttributeList)); // then assertEquals(exception.getStatus(), Status.BAD_REQUEST); assertThat(exception.getError().getDetail(), is("Cannot include both attributes and excluded attributes in a single request")); } @Test public void testPatch_ErrorIfBothAttributesAndExcludedAttributesExist() throws Exception { // given @SuppressWarnings("unchecked") BaseResourceTypeResourceImpl<ScimUser> baseResourceImpl = mock(BaseResourceTypeResourceImpl.class); PatchRequest patchRequest = new PatchRequest(); when(baseResourceImpl.patch(patchRequest, "1", includedAttributeList, excludedAttributeList)).thenCallRealMethod(); // when ScimException exception = assertThrows(ScimException.class, () -> baseResourceImpl.patch(patchRequest, "1", includedAttributeList, excludedAttributeList)); // then assertEquals(exception.getStatus(), Status.BAD_REQUEST); assertThat(exception.getError().getDetail(), is("Cannot include both attributes and excluded attributes in a single request")); } @Test public void repositoryNotImplemented() throws ScimException { // given @SuppressWarnings("rawtypes") BaseResourceTypeResourceImpl baseResourceImpl = mock(BaseResourceTypeResourceImpl.class); when(baseResourceImpl.getRepository()).thenReturn(null); when(baseResourceImpl.getRepositoryInternal()).thenCallRealMethod(); // when ScimException exception = assertThrows(ScimException.class, baseResourceImpl::getRepositoryInternal); // then assertEquals(exception.getStatus(), Status.NOT_IMPLEMENTED); assertThat(exception.getError().getDetail(), is("Provider not defined")); } private ScimUser getScimUser() throws PhoneNumberParseException { ScimUser user = new ScimUser(); user.setActive(true); user.setId("1"); user.setExternalId("e1"); user.setUserName("jed1"); user.setActive(true); user.setNickName("Jonny"); user.setPassword("secret"); user.setPreferredLanguage("English"); user.setProfileUrl("http://example.com/Users/JohnDoe"); user.setUserName("jed1"); user.setDisplayName("John Doe"); Name name = new Name(); name.setHonorificPrefix("Mr."); name.setGivenName("John"); name.setMiddleName("E"); name.setFamilyName("Doe"); name.setHonorificSuffix("Jr."); name.setFormatted("Mr. John E. Doe Jr."); user.setName(name); List<Address> addresses = new ArrayList<>(); Address address = new Address(); address.setStreetAddress("123 Main St."); address.setLocality("State College"); address.setRegion("PA"); address.setPostalCode("16801"); address.setCountry("USA"); address.setType("home"); address.setPrimary(true); address.setDisplay("123 Main St. State College, PA 16801"); address.setFormatted("123 Main St. State College, PA 16801"); addresses.add(address); address = new Address(); address.setStreetAddress("456 Main St."); address.setLocality("State College"); address.setRegion("PA"); address.setPostalCode("16801"); address.setCountry("USA"); address.setType("work"); address.setPrimary(false); address.setDisplay("456 Main St. State College, PA 16801"); address.setFormatted("456 Main St. State College, PA 16801"); addresses.add(address); user.setAddresses(addresses); List<PhoneNumber> phoneNumbers = new ArrayList<>(); PhoneNumber phoneNumber = new LocalPhoneNumberBuilder().subscriberNumber("123-456-7890").countryCode("+1").build(); phoneNumber.setDisplay("123-456-7890"); phoneNumber.setPrimary(true); phoneNumber.setType("home"); phoneNumbers.add(phoneNumber); phoneNumber = new GlobalPhoneNumberBuilder().globalNumber("1-800-555-1234").build(); phoneNumber.setDisplay("1-800-555-1234"); phoneNumber.setPrimary(false); phoneNumber.setType("work"); phoneNumbers.add(phoneNumber); user.setPhoneNumbers(phoneNumbers); EnterpriseExtension enterpriseEntension = new EnterpriseExtension(); enterpriseEntension.setCostCenter("CC-123"); enterpriseEntension.setDepartment("DEPT-xyz"); enterpriseEntension.setDivision("DIV-1"); enterpriseEntension.setEmployeeNumber("1234567890"); Manager manager = new Manager(); manager.setDisplayName("Bob Smith"); manager.setValue("0987654321"); enterpriseEntension.setManager(manager); enterpriseEntension.setOrganization("ORG-X"); user.addExtension(enterpriseEntension); ExampleObjectExtension exampleObjectExtension = new ExampleObjectExtension(); exampleObjectExtension.setValueAlways("always"); exampleObjectExtension.setValueDefault("default"); exampleObjectExtension.setValueNever("never"); exampleObjectExtension.setValueRequest("request"); ComplexObject valueComplex = new ComplexObject(); valueComplex.setDisplayName("ValueComplex"); valueComplex.setValue("Value"); exampleObjectExtension.setValueComplex(valueComplex); user.addExtension(exampleObjectExtension); return user; } }
4,379
0
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server/rest/BulkResourceImplTest.java
/* * 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 * 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.directory.scim.server.rest; import jakarta.enterprise.inject.Instance; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.UriBuilder; import jakarta.ws.rs.core.UriInfo; import org.apache.directory.scim.server.exception.UnableToCreateResourceException; import org.apache.directory.scim.core.repository.Repository; import org.apache.directory.scim.core.repository.RepositoryRegistry; import org.apache.directory.scim.protocol.data.BulkOperation; import org.apache.directory.scim.protocol.data.BulkRequest; import org.apache.directory.scim.protocol.data.BulkResponse; import org.apache.directory.scim.protocol.data.ErrorResponse; import org.apache.directory.scim.spec.resources.ScimGroup; import org.apache.directory.scim.spec.resources.ScimResource; import org.apache.directory.scim.spec.resources.ScimUser; import org.apache.directory.scim.spec.schema.ResourceReference; import org.apache.directory.scim.core.schema.SchemaRegistry; import org.junit.jupiter.api.Test; import org.mockito.InOrder; import java.net.URI; import java.util.Collections; import java.util.List; import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class BulkResourceImplTest { @Test public void bulkIdTemporaryIdentifiersTest() throws Exception { // Request copied from RFC 7644 section 3.7.2 ScimUser alice = new ScimUser() .setUserName("Alice"); ScimGroup tourGuides = new ScimGroup() .setDisplayName("Tour Guides") .setMembers(List.of(new ResourceReference() .setType(ResourceReference.ReferenceType.USER) .setValue("bulkId:qwerty"))); BulkRequest bulkRequest = new BulkRequest() .setOperations(List.of( new BulkOperation() .setMethod(BulkOperation.Method.POST) .setPath("/Users") .setBulkId("qwerty") .setData(alice), new BulkOperation() .setMethod(BulkOperation.Method.POST) .setPath("/Groups") .setBulkId("ytrewq") .setData(tourGuides))); Instance<Repository<? extends ScimResource>> emptyInstance = mock(Instance.class); when(emptyInstance.stream()).thenReturn(Stream.empty()); SchemaRegistry schemaRegistry = new SchemaRegistry(); RepositoryRegistry repositoryRegistry = new RepositoryRegistry(schemaRegistry); Instance<Repository<ScimUser>> userRepositoryInstance = mock(Instance.class); Repository<ScimUser> userRepository = mock(Repository.class); ScimUser user = new ScimUser(); user.setId("alice-id"); when(userRepositoryInstance.get()).thenReturn(userRepository); repositoryRegistry.registerRepository(ScimUser.class, userRepository); when(userRepository.create(any())).thenReturn(user); Instance<Repository<ScimGroup>> groupProviderInstance = mock(Instance.class); Repository<ScimGroup> groupRepository = mock(Repository.class); ScimGroup group = new ScimGroup(); group.setId("tour-guides"); when(groupProviderInstance.get()).thenReturn(groupRepository); repositoryRegistry.registerRepository(ScimGroup.class, groupRepository); when(groupRepository.getExtensionList()).thenReturn(Collections.emptyList()); when(groupRepository.create(any())).thenReturn(group); BulkResourceImpl impl = new BulkResourceImpl(schemaRegistry, repositoryRegistry); UriInfo uriInfo = mock(UriInfo.class); UriBuilder uriBuilder = mock(UriBuilder.class); when(uriInfo.getBaseUriBuilder()).thenReturn(uriBuilder); when(uriBuilder.path("/Users")).thenReturn(uriBuilder); when(uriBuilder.path("alice-id")).thenReturn(uriBuilder); when(uriBuilder.build()) .thenReturn(URI.create("https://scim.example.com/Users/alice-id")) .thenReturn(URI.create("https://scim.example.com/Groups/tour-guides")); when(uriBuilder.path("/Groups")).thenReturn(uriBuilder); when(uriBuilder.path("tour-guides")).thenReturn(uriBuilder); Response response = impl.doBulk(bulkRequest, uriInfo); BulkResponse bulkResponse = (BulkResponse) response.getEntity(); assertThat(bulkResponse.getErrorResponse()).isNull(); assertThat(bulkResponse.getStatus()).isEqualTo(Response.Status.OK); assertThat(bulkResponse.getSchemas()).containsOnly(BulkResponse.SCHEMA_URI); assertThat(bulkResponse.getOperations()) .hasSize(2) .contains(new BulkOperation() .setMethod(BulkOperation.Method.POST) .setBulkId("qwerty") .setData(new ScimUser() .setId("alice-id")) .setLocation("https://scim.example.com/Users/alice-id") .setStatus(new BulkOperation.StatusWrapper(Response.Status.CREATED))) .contains(new BulkOperation() .setMethod(BulkOperation.Method.POST) .setBulkId("ytrewq") .setData(new ScimGroup() .setId("tour-guides")) .setLocation("https://scim.example.com/Groups/tour-guides") .setStatus(new BulkOperation.StatusWrapper(Response.Status.CREATED))); // Verify behavior InOrder inOrder = inOrder(userRepository, groupRepository); inOrder.verify(userRepository, atLeast(1)).getExtensionList(); inOrder.verify(groupRepository, atLeast(1)).getExtensionList(); // User was created before group due to calculated dependency inOrder.verify(userRepository).create(alice); inOrder.verify(groupRepository).create(tourGuides); inOrder.verifyNoMoreInteractions(); } @Test public void bulkFailedTest() throws Exception { ScimUser alice = new ScimUser() .setUserName("Alice"); ScimUser bob = new ScimUser() .setUserName("Bob"); BulkRequest bulkRequest = new BulkRequest() .setFailOnErrors(1) .setOperations(List.of( new BulkOperation() .setMethod(BulkOperation.Method.POST) .setPath("/Users") .setBulkId("bulk-id-alice") .setData(alice), new BulkOperation() .setMethod(BulkOperation.Method.POST) .setPath("/Users") .setBulkId("bulk-id-bob") .setData(bob) )); Instance<Repository<? extends ScimResource>> emptyInstance = mock(Instance.class); when(emptyInstance.stream()).thenReturn(Stream.empty()); SchemaRegistry schemaRegistry = new SchemaRegistry(); RepositoryRegistry repositoryRegistry = new RepositoryRegistry(schemaRegistry); Instance<Repository<ScimUser>> userProviderInstance = mock(Instance.class); Repository<ScimUser> userRepository = mock(Repository.class); when(userProviderInstance.get()).thenReturn(userRepository); repositoryRegistry.registerRepository(ScimUser.class, userRepository); when(userProviderInstance.get()).thenReturn(userRepository); ScimUser userAlice = new ScimUser(); userAlice.setId("alice-id"); ScimUser userBob = new ScimUser(); userBob.setId("bob-id"); when(userRepository.create(any())) .thenReturn(userAlice) .thenThrow(new UnableToCreateResourceException(Response.Status.BAD_REQUEST, "Expected Test Exception when bob is created")); BulkResourceImpl impl = new BulkResourceImpl(schemaRegistry, repositoryRegistry); UriInfo uriInfo = mock(UriInfo.class); UriBuilder uriBuilder = mock(UriBuilder.class); when(uriInfo.getBaseUriBuilder()).thenReturn(uriBuilder); when(uriBuilder.path("/Users")).thenReturn(uriBuilder); when(uriBuilder.path("alice-id")).thenReturn(uriBuilder); when(uriBuilder.path("bob-id")).thenReturn(uriBuilder); when(uriBuilder.build()) .thenReturn(URI.create("https://scim.example.com/Users/alice-id")) .thenReturn(URI.create("https://scim.example.com/Users/bob-id")); Response response = impl.doBulk(bulkRequest, uriInfo); BulkResponse bulkResponse = (BulkResponse) response.getEntity(); assertThat(bulkResponse.getErrorResponse()).isNull(); assertThat(bulkResponse.getStatus()).isEqualTo(Response.Status.BAD_REQUEST); assertThat(bulkResponse.getSchemas()).containsOnly(BulkResponse.SCHEMA_URI); assertThat(bulkResponse.getOperations()) .hasSize(2) .contains(new BulkOperation() .setMethod(BulkOperation.Method.POST) .setBulkId("bulk-id-alice") .setData(new ScimUser() .setId("alice-id")) .setLocation("https://scim.example.com/Users/alice-id") .setStatus(new BulkOperation.StatusWrapper(Response.Status.CREATED))) .contains(new BulkOperation() .setMethod(BulkOperation.Method.POST) .setBulkId("bulk-id-bob") .setResponse(new ErrorResponse(Response.Status.BAD_REQUEST, "Expected Test Exception when bob is created")) .setStatus(new BulkOperation.StatusWrapper(Response.Status.BAD_REQUEST))); } }
4,380
0
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server/utility/Order.java
/* * 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 * 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.directory.scim.server.utility; public enum Order { FIRST("first"), SECOND("second"), THIRD("third"), FOURTH("fourth"); Order(String value) { this.value = value; } private final String value; public String getValue() { return value; } @Override public String toString() { return value; } }
4,381
0
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server/utility/ExampleObjectExtension.java
/* * 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 * 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.directory.scim.server.utility; import java.io.Serializable; import java.util.List; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlType; import lombok.Data; import org.apache.directory.scim.spec.annotation.ScimAttribute; import org.apache.directory.scim.spec.annotation.ScimExtensionType; import org.apache.directory.scim.spec.resources.ScimExtension; import org.apache.directory.scim.spec.schema.Schema.Attribute.Mutability; import org.apache.directory.scim.spec.schema.Schema.Attribute.Returned; @XmlRootElement @XmlAccessorType(XmlAccessType.NONE) @ScimExtensionType(required = false, name = "ExampleObject", id = ExampleObjectExtension.URN, description = "Example Object Extensions.") @Data public class ExampleObjectExtension implements ScimExtension { private static final long serialVersionUID = -5398090056271556423L; public static final String URN = "urn:ietf:params:scim:schemas:extension:example:2.0:Object"; @XmlType @XmlAccessorType(XmlAccessType.NONE) @Data public static class ComplexObject implements Serializable { private static final long serialVersionUID = 2822581434679824690L; @ScimAttribute(description = "The \"id\" of the complex object.") @XmlElement private String value; @ScimAttribute(mutability = Mutability.READ_ONLY, description = "displayName of the object.") @XmlElement private String displayName; } @ScimAttribute(returned = Returned.ALWAYS) @XmlElement private String valueAlways; @ScimAttribute(returned = Returned.DEFAULT) @XmlElement private String valueDefault; @ScimAttribute(returned = Returned.NEVER) @XmlElement private String valueNever; @ScimAttribute(returned = Returned.REQUEST) @XmlElement private String valueRequest; @ScimAttribute(returned = Returned.REQUEST) @XmlElement private ComplexObject valueComplex; @ScimAttribute @XmlElement private List<String> list; @ScimAttribute @XmlElement private List<Order> enumList; @ScimAttribute @XmlElement private Subobject subobject; @Override public String getUrn() { return URN; } }
4,382
0
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/test/java/org/apache/directory/scim/server/utility/Subobject.java
/* * 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 * 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.directory.scim.server.utility; import java.io.Serializable; import java.util.List; import jakarta.xml.bind.annotation.XmlElement; import org.apache.directory.scim.spec.annotation.ScimAttribute; import lombok.Data; @Data public class Subobject implements Serializable { private static final long serialVersionUID = -8081556701833520316L; @ScimAttribute @XmlElement private String string1; @ScimAttribute @XmlElement private String string2; @ScimAttribute @XmlElement private Boolean boolean1; @ScimAttribute @XmlElement private Boolean boolean2; @ScimAttribute @XmlElement private List<String> list1; @ScimAttribute @XmlElement private List<String> list2; }
4,383
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/configuration/ServerConfiguration.java
/* * 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 * 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.directory.scim.server.configuration; import java.util.ArrayList; import java.util.Collections; import java.util.List; import lombok.AccessLevel; import lombok.Data; import lombok.Setter; import org.apache.directory.scim.spec.schema.ServiceProviderConfiguration.AuthenticationSchema; import org.apache.directory.scim.spec.schema.ServiceProviderConfiguration.BulkConfiguration; import org.apache.directory.scim.spec.schema.ServiceProviderConfiguration.FilterConfiguration; import org.apache.directory.scim.spec.schema.ServiceProviderConfiguration.SupportedConfiguration; /** * Provides a default server configuration with the values that are ultimately * returned by the ServerProviderConfig end-point. * * @author Chris Harm &lt;crh5255@psu.edu&gt; */ @Data public class ServerConfiguration { static final int BULK_MAXIMUM_OPERATIONS = 100; static final int BULK_MAXIMUM_PAYLOAD_SIZE = 1024; static final int FILTER_MAXIMUM_RESULTS = 100; String id = "spc"; boolean supportsChangePassword = false; @Setter(AccessLevel.NONE) boolean supportsBulk = true; int bulkMaxOperations = BULK_MAXIMUM_OPERATIONS; int bulkMaxPayloadSize = BULK_MAXIMUM_PAYLOAD_SIZE; //TODO what should this be? @Setter(AccessLevel.NONE) boolean supportsETag = true; boolean supportsFilter = false; int filterMaxResults = FILTER_MAXIMUM_RESULTS; @Setter(AccessLevel.NONE) boolean supportsPatch = true; boolean supportsSort = false; String documentationUri; @Setter(AccessLevel.NONE) List<AuthenticationSchema> authenticationSchemas = new ArrayList<>(); public List<AuthenticationSchema> getAuthenticationSchemas() { return Collections.unmodifiableList(authenticationSchemas); } public ServerConfiguration addAuthenticationSchema(AuthenticationSchema authenticationSchema) { authenticationSchemas.add(authenticationSchema); return this; } public SupportedConfiguration getChangePasswordConfiguration() { return createSupportedConfiguration(supportsChangePassword); } public BulkConfiguration getBulkConfiguration() { BulkConfiguration bulkConfiguration = new BulkConfiguration(); bulkConfiguration.setSupported(supportsBulk); bulkConfiguration.setMaxOperations(bulkMaxOperations); bulkConfiguration.setMaxPayloadSize(bulkMaxPayloadSize); return bulkConfiguration; } public SupportedConfiguration getEtagConfiguration() { return createSupportedConfiguration(supportsETag); } public FilterConfiguration getFilterConfiguration() { FilterConfiguration filterConfiguration = new FilterConfiguration(); filterConfiguration.setSupported(supportsFilter); filterConfiguration.setMaxResults(filterMaxResults); return filterConfiguration; } public SupportedConfiguration getPatchConfiguration() { return createSupportedConfiguration(supportsPatch); } public SupportedConfiguration getSortConfiguration() { return createSupportedConfiguration(supportsSort); } private SupportedConfiguration createSupportedConfiguration(boolean supported) { SupportedConfiguration supportedConfiguration = new SupportedConfiguration(); supportedConfiguration.setSupported(supported); return supportedConfiguration; } }
4,384
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/spi/ScimServerBuildCompatibleExtension.java
/* * 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 * 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.directory.scim.server.spi; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Instance; import jakarta.enterprise.inject.build.compatible.spi.BeanInfo; import jakarta.enterprise.inject.build.compatible.spi.BuildCompatibleExtension; import jakarta.enterprise.inject.build.compatible.spi.Messages; import jakarta.enterprise.inject.build.compatible.spi.Parameters; import jakarta.enterprise.inject.build.compatible.spi.Registration; import jakarta.enterprise.inject.build.compatible.spi.Synthesis; import jakarta.enterprise.inject.build.compatible.spi.SyntheticBeanCreator; import jakarta.enterprise.inject.build.compatible.spi.SyntheticComponents; import org.apache.directory.scim.server.configuration.ServerConfiguration; /** * CDI Lite build compatible extension that adds a default ServerConfiguration implementation. * */ public class ScimServerBuildCompatibleExtension implements BuildCompatibleExtension { private boolean serverConfigFound = false; @Registration(types = ServerConfiguration.class) public void registration(BeanInfo beanInfo) { // detect if any ServerConfiguration beans are found, if a default bean will be created below serverConfigFound = true; } @Synthesis public void synthesise(SyntheticComponents syn, Messages messages) { // if a ServerConfiguration bean was not found during registration, a default one will be added (along with a warning) if (!serverConfigFound) { messages.warn("It is recommended to provide a ServerConfiguration bean to configure SCIMple, a default instance will be used."); syn.addBean(ServerConfiguration.class) .type(ServerConfiguration.class) .scope(ApplicationScoped.class) .createWith(DefaultServerConfigurationCreator.class); } } public static class DefaultServerConfigurationCreator implements SyntheticBeanCreator<ServerConfiguration> { @Override public ServerConfiguration create(Instance<Object> lookup, Parameters params) { return new ServerConfiguration(); } } }
4,385
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/filter/ApiOriginFilter.java
/* * 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 * 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.directory.scim.server.filter; import java.io.IOException; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.container.ContainerResponseContext; import jakarta.ws.rs.container.ContainerResponseFilter; import jakarta.ws.rs.core.MultivaluedMap; public class ApiOriginFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { MultivaluedMap<String, Object> headers = responseContext.getHeaders(); headers.add("Access-Control-Allow-Origin", "*"); headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); headers.add("Access-Control-Allow-Headers", "Content-Type, Authorization"); } }
4,386
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/exception/FilterParseExceptionMapper.java
/* * 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 * 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.directory.scim.server.exception; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response.Status; import jakarta.ws.rs.ext.Provider; import org.apache.directory.scim.protocol.Constants; import org.apache.directory.scim.protocol.ErrorMessageType; import org.apache.directory.scim.protocol.data.ErrorResponse; import org.apache.directory.scim.spec.filter.FilterParseException; @Provider @Produces({Constants.SCIM_CONTENT_TYPE, MediaType.APPLICATION_JSON}) public class FilterParseExceptionMapper extends BaseScimExceptionMapper<FilterParseException> { @Override protected ErrorResponse errorResponse(FilterParseException exception) { return new ErrorResponse(Status.BAD_REQUEST, exception.getMessage()) .setScimType(ErrorMessageType.INVALID_FILTER); } }
4,387
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/exception/UnableToDeleteResourceException.java
/* * 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 * 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.directory.scim.server.exception; import jakarta.ws.rs.core.Response.Status; import lombok.Data; import lombok.EqualsAndHashCode; import org.apache.directory.scim.spec.exception.ResourceException; @Data @EqualsAndHashCode(callSuper=true) public class UnableToDeleteResourceException extends ResourceException { private static final long serialVersionUID = -3872700870424005641L; public UnableToDeleteResourceException(Status status, String message) { super(status.getStatusCode(), message); } public UnableToDeleteResourceException(Status status, String message, Throwable cause) { super(status.getStatusCode(), message, cause); } }
4,388
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/exception/UnsupportedFilterExceptionMapper.java
/* * 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 * 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.directory.scim.server.exception; import jakarta.ws.rs.core.Response; import org.apache.directory.scim.protocol.ErrorMessageType; import org.apache.directory.scim.protocol.data.ErrorResponse; import org.apache.directory.scim.spec.exception.UnsupportedFilterException; public class UnsupportedFilterExceptionMapper extends BaseScimExceptionMapper<UnsupportedFilterException> { @Override protected ErrorResponse errorResponse(UnsupportedFilterException throwable) { return new ErrorResponse(Response.Status.BAD_REQUEST, ErrorMessageType.INVALID_FILTER.getDetail()) .setScimType(ErrorMessageType.INVALID_FILTER); } }
4,389
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/exception/WebApplicationExceptionMapper.java
/* * 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 * 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.directory.scim.server.exception; import jakarta.ws.rs.Produces; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response.Status; import jakarta.ws.rs.ext.Provider; import org.apache.directory.scim.protocol.Constants; import org.apache.directory.scim.protocol.data.ErrorResponse; @Provider @Produces({Constants.SCIM_CONTENT_TYPE, MediaType.APPLICATION_JSON}) public class WebApplicationExceptionMapper extends BaseScimExceptionMapper<WebApplicationException> { @Override protected ErrorResponse errorResponse(WebApplicationException e) { return new ErrorResponse(Status.fromStatusCode(e.getResponse().getStatus()), e.getMessage()); } }
4,390
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/exception/UnableToRetrieveResourceException.java
/* * 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 * 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.directory.scim.server.exception; import jakarta.ws.rs.core.Response.Status; import lombok.Data; import lombok.EqualsAndHashCode; import org.apache.directory.scim.spec.exception.ResourceException; @Data @EqualsAndHashCode(callSuper=true) public class UnableToRetrieveResourceException extends ResourceException { private static final long serialVersionUID = -3872700870424005641L; public UnableToRetrieveResourceException(Status status, String message) { super(status.getStatusCode(), message); } public UnableToRetrieveResourceException(Status status, String message, Throwable cause) { super(status.getStatusCode(), message, cause); } }
4,391
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/exception/BaseScimExceptionMapper.java
/* * 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 * 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.directory.scim.server.exception; import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.ext.ExceptionMapper; import lombok.extern.slf4j.Slf4j; import org.apache.directory.scim.protocol.Constants; import org.apache.directory.scim.protocol.data.ErrorResponse; @Slf4j abstract class BaseScimExceptionMapper<E extends Throwable> implements ExceptionMapper<E> { protected abstract ErrorResponse errorResponse(E throwable); @Override public Response toResponse(E throwable) { Response response = errorResponse(throwable).toResponse(); // log client errors (e.g. 404s) at debug, and anything else at warn if (Response.Status.Family.CLIENT_ERROR.equals(response.getStatusInfo().getFamily())) { log.debug("Returning error status: {}", response.getStatus(), throwable); } else { log.warn("Returning error status: {}", response.getStatus(), throwable); } response.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, Constants.SCIM_CONTENT_TYPE); return response; } }
4,392
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/exception/AttributeException.java
/* * 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 * 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.directory.scim.server.exception; public class AttributeException extends Exception { private static final long serialVersionUID = 547510233114396694L; public AttributeException() { } public AttributeException(String message) { super(message); } public AttributeException(Throwable cause) { super(cause); } public AttributeException(String message, Throwable cause) { super(message, cause); } public AttributeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
4,393
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/exception/ResourceExceptionMapper.java
/* * 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 * 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.directory.scim.server.exception; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response.Status; import jakarta.ws.rs.ext.Provider; import org.apache.directory.scim.protocol.Constants; import org.apache.directory.scim.protocol.ErrorMessageType; import org.apache.directory.scim.protocol.data.ErrorResponse; import org.apache.directory.scim.spec.exception.ResourceException; @Provider @Produces({Constants.SCIM_CONTENT_TYPE, MediaType.APPLICATION_JSON}) public class ResourceExceptionMapper extends BaseScimExceptionMapper<ResourceException> { @Override protected ErrorResponse errorResponse(ResourceException e) { Status status = Status.fromStatusCode(e.getStatus()); ErrorResponse errorResponse = new ErrorResponse(status, e.getMessage()); if (status == Status.CONFLICT) { errorResponse.setScimType(ErrorMessageType.UNIQUENESS); //only use default error message if the ErrorResponse does not already contain a message if (e.getMessage() == null) { errorResponse.setDetail(ErrorMessageType.UNIQUENESS.getDetail()); } else { errorResponse.setDetail(e.getMessage()); } } else { errorResponse.setDetail(e.getMessage()); } return errorResponse; } }
4,394
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/exception/ScimExceptionMapper.java
/* * 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 * 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.directory.scim.server.exception; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.ext.Provider; import org.apache.directory.scim.protocol.Constants; import org.apache.directory.scim.protocol.data.ErrorResponse; import org.apache.directory.scim.protocol.exception.ScimException; @Provider @Produces({Constants.SCIM_CONTENT_TYPE, MediaType.APPLICATION_JSON}) public class ScimExceptionMapper extends BaseScimExceptionMapper<ScimException> { @Override protected ErrorResponse errorResponse(ScimException e) { return e.getError(); } }
4,395
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/exception/EtagGenerationException.java
/* * 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 * 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.directory.scim.server.exception; public class EtagGenerationException extends Exception { public EtagGenerationException(String message) { super(message); } public EtagGenerationException(String message, Throwable cause) { super(message, cause); } }
4,396
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/exception/UnableToUpdateResourceException.java
/* * 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 * 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.directory.scim.server.exception; import jakarta.ws.rs.core.Response.Status; import lombok.Data; import lombok.EqualsAndHashCode; import org.apache.directory.scim.spec.exception.ResourceException; @Data @EqualsAndHashCode(callSuper=true) public class UnableToUpdateResourceException extends ResourceException { private static final long serialVersionUID = -3872700870424005641L; public UnableToUpdateResourceException(Status status, String message) { super(status.getStatusCode(), message); } public UnableToUpdateResourceException(Status status, String message, Throwable cause) { super(status.getStatusCode(), message, cause); } }
4,397
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/exception/UnsupportedOperationExceptionMapper.java
/* * 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 * 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.directory.scim.server.exception; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.ext.Provider; import org.apache.directory.scim.protocol.Constants; import org.apache.directory.scim.protocol.data.ErrorResponse; @Provider @Produces({Constants.SCIM_CONTENT_TYPE, MediaType.APPLICATION_JSON}) public class UnsupportedOperationExceptionMapper extends BaseScimExceptionMapper<UnsupportedOperationException> { @Override protected ErrorResponse errorResponse(UnsupportedOperationException throwable) { return new ErrorResponse(Response.Status.NOT_IMPLEMENTED, throwable.getMessage()); } }
4,398
0
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server
Create_ds/directory-scimple/scim-server/src/main/java/org/apache/directory/scim/server/exception/UnableToRetrieveExtensionsResourceException.java
/* * 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 * 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.directory.scim.server.exception; import jakarta.ws.rs.core.Response.Status; import lombok.Data; import lombok.EqualsAndHashCode; import org.apache.directory.scim.spec.exception.ResourceException; @Data @EqualsAndHashCode(callSuper=true) public class UnableToRetrieveExtensionsResourceException extends ResourceException { private static final long serialVersionUID = -3872700870424005641L; public UnableToRetrieveExtensionsResourceException(Status status, String message) { super(status.getStatusCode(), message); } public UnableToRetrieveExtensionsResourceException(Status status, String message, Throwable cause) { super(status.getStatusCode(), message, cause); } }
4,399