Search in sources :

Example 41 with Patch

use of org.wso2.carbon.identity.api.server.idp.v1.model.Patch in project ballerina by ballerina-lang.

the class ServiceTest method testPATCHMethodWithBody.

@Test(description = "Test Http PATCH verb dispatching with a responseMsgPayload")
public void testPATCHMethodWithBody() {
    String path = "/echo/modify";
    HTTPTestRequest requestMsg = MessageUtils.generateHTTPMessage(path, "PATCH", "WSO2");
    HTTPCarbonMessage responseMsg = Services.invokeNew(compileResult, TEST_ENDPOINT_NAME, requestMsg);
    Assert.assertNotNull(responseMsg, "responseMsg message not found");
    Assert.assertEquals(responseMsg.getProperty(HttpConstants.HTTP_STATUS_CODE), 204);
}
Also used : HTTPCarbonMessage(org.wso2.transport.http.netty.message.HTTPCarbonMessage) HTTPTestRequest(org.ballerinalang.test.services.testutils.HTTPTestRequest) Test(org.testng.annotations.Test)

Example 42 with Patch

use of org.wso2.carbon.identity.api.server.idp.v1.model.Patch in project ballerina by ballerina-lang.

the class ServiceTest method testPATCHMethodWithoutBody.

@Test(description = "Test Http PATCH verb dispatching without a responseMsgPayload")
public void testPATCHMethodWithoutBody() {
    String path = "/echo/modify";
    HTTPTestRequest requestMsg = MessageUtils.generateHTTPMessage(path, "PATCH");
    HTTPCarbonMessage responseMsg = Services.invokeNew(compileResult, TEST_ENDPOINT_NAME, requestMsg);
    Assert.assertNotNull(responseMsg, "responseMsg message not found");
    Assert.assertEquals(responseMsg.getProperty(HttpConstants.HTTP_STATUS_CODE), 204);
}
Also used : HTTPCarbonMessage(org.wso2.transport.http.netty.message.HTTPCarbonMessage) HTTPTestRequest(org.ballerinalang.test.services.testutils.HTTPTestRequest) Test(org.testng.annotations.Test)

Example 43 with Patch

use of org.wso2.carbon.identity.api.server.idp.v1.model.Patch in project charon by wso2.

the class UserResourceManager method updateWithPATCH.

/**
 * Update the user resource by sequence of operations.
 *
 * @param existingId
 * @param scimObjectString
 * @param userManager
 * @param attributes
 * @param excludeAttributes
 * @return
 */
public SCIMResponse updateWithPATCH(String existingId, String scimObjectString, UserManager userManager, String attributes, String excludeAttributes) {
    try {
        if (userManager == null) {
            String error = "Provided user manager handler is null.";
            throw new InternalErrorException(error);
        }
        // obtain the json decoder.
        JSONDecoder decoder = getDecoder();
        // decode the SCIM User object, encoded in the submitted payload.
        List<PatchOperation> opList = decoder.decodeRequest(scimObjectString);
        SCIMResourceTypeSchema schema = getSchema(userManager);
        ;
        List<String> allSimpleMultiValuedAttributes = ResourceManagerUtil.getAllSimpleMultiValuedAttributes(schema);
        // get the user from the user core
        User oldUser = userManager.getUser(existingId, ResourceManagerUtil.getAllAttributeURIs(schema));
        if (oldUser == null) {
            throw new NotFoundException("No user with the id : " + existingId + " in the user store.");
        }
        // make a copy of the original user
        User copyOfOldUser = (User) CopyUtil.deepCopy(oldUser);
        // make another copy of original user.
        // this will be used to restore to the original condition if failure occurs.
        User originalUser = (User) CopyUtil.deepCopy(copyOfOldUser);
        User newUser = null;
        for (PatchOperation operation : opList) {
            if (operation.getOperation().equals(SCIMConstants.OperationalConstants.ADD)) {
                if (newUser == null) {
                    newUser = (User) PatchOperationUtil.doPatchAdd(operation, getDecoder(), oldUser, copyOfOldUser, schema);
                    copyOfOldUser = (User) CopyUtil.deepCopy(newUser);
                } else {
                    newUser = (User) PatchOperationUtil.doPatchAdd(operation, getDecoder(), newUser, copyOfOldUser, schema);
                    copyOfOldUser = (User) CopyUtil.deepCopy(newUser);
                }
            } else if (operation.getOperation().equals(SCIMConstants.OperationalConstants.REMOVE)) {
                if (newUser == null) {
                    newUser = (User) PatchOperationUtil.doPatchRemove(operation, oldUser, copyOfOldUser, schema);
                    copyOfOldUser = (User) CopyUtil.deepCopy(newUser);
                } else {
                    newUser = (User) PatchOperationUtil.doPatchRemove(operation, newUser, copyOfOldUser, schema);
                    copyOfOldUser = (User) CopyUtil.deepCopy(newUser);
                }
            } else if (operation.getOperation().equals(SCIMConstants.OperationalConstants.REPLACE)) {
                if (newUser == null) {
                    newUser = (User) PatchOperationUtil.doPatchReplace(operation, getDecoder(), oldUser, copyOfOldUser, schema);
                    copyOfOldUser = (User) CopyUtil.deepCopy(newUser);
                } else {
                    newUser = (User) PatchOperationUtil.doPatchReplace(operation, getDecoder(), newUser, copyOfOldUser, schema);
                    copyOfOldUser = (User) CopyUtil.deepCopy(newUser);
                }
            } else {
                throw new BadRequestException("Unknown operation.", ResponseCodeConstants.INVALID_SYNTAX);
            }
        }
        // get the URIs of required attributes which must be given a value
        Map<String, Boolean> requiredAttributes = ResourceManagerUtil.getOnlyRequiredAttributesURIs((SCIMResourceTypeSchema) CopyUtil.deepCopy(schema), attributes, excludeAttributes);
        User validatedUser = (User) ServerSideValidator.validateUpdatedSCIMObject(originalUser, newUser, schema);
        try {
            newUser = userManager.updateUser(validatedUser, requiredAttributes, allSimpleMultiValuedAttributes);
        } catch (NotImplementedException e) {
            newUser = userManager.updateUser(validatedUser, requiredAttributes);
        }
        // encode the newly created SCIM user object and add id attribute to Location header.
        String encodedUser;
        Map<String, String> httpHeaders = new HashMap<String, String>();
        if (newUser != null) {
            // create a deep copy of the user object since we are going to change it.
            User copiedUser = (User) CopyUtil.deepCopy(newUser);
            // need to remove password before returning
            ServerSideValidator.validateReturnedAttributes(copiedUser, attributes, excludeAttributes);
            encodedUser = getEncoder().encodeSCIMObject(copiedUser);
            // add location header
            httpHeaders.put(SCIMConstants.LOCATION_HEADER, getResourceEndpointURL(SCIMConstants.USER_ENDPOINT) + "/" + newUser.getId());
            httpHeaders.put(SCIMConstants.CONTENT_TYPE_HEADER, SCIMConstants.APPLICATION_JSON);
        } else {
            String error = "Updated User resource is null.";
            throw new CharonException(error);
        }
        // put the URI of the User object in the response header parameter.
        return new SCIMResponse(ResponseCodeConstants.CODE_OK, encodedUser, httpHeaders);
    } catch (NotFoundException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (BadRequestException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (NotImplementedException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (CharonException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (InternalErrorException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (RuntimeException e) {
        CharonException e1 = new CharonException("Error in performing the patch operation on user resource.", e);
        return AbstractResourceManager.encodeSCIMException(e1);
    }
}
Also used : User(org.wso2.charon3.core.objects.User) HashMap(java.util.HashMap) NotImplementedException(org.wso2.charon3.core.exceptions.NotImplementedException) NotFoundException(org.wso2.charon3.core.exceptions.NotFoundException) InternalErrorException(org.wso2.charon3.core.exceptions.InternalErrorException) JSONDecoder(org.wso2.charon3.core.encoder.JSONDecoder) PatchOperation(org.wso2.charon3.core.utils.codeutils.PatchOperation) BadRequestException(org.wso2.charon3.core.exceptions.BadRequestException) SCIMResourceTypeSchema(org.wso2.charon3.core.schema.SCIMResourceTypeSchema) CharonException(org.wso2.charon3.core.exceptions.CharonException) SCIMResponse(org.wso2.charon3.core.protocol.SCIMResponse)

Example 44 with Patch

use of org.wso2.carbon.identity.api.server.idp.v1.model.Patch in project charon by wso2.

the class RoleResourceManager method updateWithPATCHRole.

@Override
public SCIMResponse updateWithPATCHRole(String id, String patchRequest, RoleManager roleManager) {
    try {
        if (roleManager == null) {
            String error = "Provided role manager handler is null.";
            throw new InternalErrorException(error);
        }
        JSONEncoder encoder = getEncoder();
        SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getRoleResourceSchema();
        Map<String, Boolean> requestAttributes = ResourceManagerUtil.getAllAttributeURIs(schema);
        Role oldRole = roleManager.getRole(id, requestAttributes);
        if (oldRole == null) {
            throw new NotFoundException("No role with the id : " + id + " exists in the system.");
        }
        // Make a copy of original group. This will be used to restore to the original condition if failure occurs.
        Role originalRole = (Role) CopyUtil.deepCopy(oldRole);
        Role patchedRole = doPatchRole(oldRole, schema, patchRequest);
        Role updatedRole = roleManager.updateRole(originalRole, patchedRole);
        return getScimResponse(encoder, updatedRole);
    } catch (NotFoundException | BadRequestException | NotImplementedException | CharonException | ConflictException | InternalErrorException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (RuntimeException e) {
        CharonException ex = new CharonException("Error in performing the patch operation on role resource.", e);
        return AbstractResourceManager.encodeSCIMException(ex);
    }
}
Also used : ConflictException(org.wso2.charon3.core.exceptions.ConflictException) NotImplementedException(org.wso2.charon3.core.exceptions.NotImplementedException) NotFoundException(org.wso2.charon3.core.exceptions.NotFoundException) InternalErrorException(org.wso2.charon3.core.exceptions.InternalErrorException) Role(org.wso2.charon3.core.objects.Role) BadRequestException(org.wso2.charon3.core.exceptions.BadRequestException) JSONEncoder(org.wso2.charon3.core.encoder.JSONEncoder) SCIMResourceTypeSchema(org.wso2.charon3.core.schema.SCIMResourceTypeSchema) CharonException(org.wso2.charon3.core.exceptions.CharonException)

Example 45 with Patch

use of org.wso2.carbon.identity.api.server.idp.v1.model.Patch in project charon by wso2.

the class PatchOperationUtil method doPatchReplaceOnPathWithFilters.

/*
     * This method is to do patch replace for level three attributes with a filter and path value present.
     * @param oldResource
     * @param copyOfOldResource
     * @param schema
     * @param decoder
     * @param operation
     * @param parts
     * @throws NotImplementedException
     * @throws BadRequestException
     * @throws CharonException
     * @throws JSONException
     * @throws InternalErrorException
     */
private static void doPatchReplaceOnPathWithFilters(AbstractSCIMObject oldResource, SCIMResourceTypeSchema schema, JSONDecoder decoder, PatchOperation operation, String[] parts) throws NotImplementedException, BadRequestException, CharonException, JSONException, InternalErrorException {
    if (parts.length != 1) {
        // currently we only support simple filters here.
        String[] filterParts = parts[1].split(" ");
        ExpressionNode expressionNode = new ExpressionNode();
        expressionNode.setAttributeValue(filterParts[0]);
        expressionNode.setOperation(filterParts[1]);
        // According to the specification filter attribute value specified with quotation mark, so we need to
        // remove it if exists.
        expressionNode.setValue(filterParts[2].replaceAll("^\"|\"$", ""));
        if (expressionNode.getOperation().equalsIgnoreCase((SCIMConstants.OperationalConstants.EQ).trim())) {
            if (parts.length == 3) {
                parts[0] = parts[0] + parts[2];
            }
            String[] attributeParts = getAttributeParts(parts[0]);
            if (attributeParts.length == 1) {
                doPatchReplaceWithFiltersForLevelOne(oldResource, attributeParts, expressionNode, operation, schema, decoder);
            } else if (attributeParts.length == 2) {
                doPatchReplaceWithFiltersForLevelTwo(oldResource, attributeParts, expressionNode, operation, schema, decoder);
            } else if (attributeParts.length == 3) {
                doPatchReplaceWithFiltersForLevelThree(oldResource, attributeParts, expressionNode, operation, schema, decoder);
            }
        } else {
            throw new NotImplementedException("Only Eq filter is supported");
        }
    }
}
Also used : ExpressionNode(org.wso2.charon3.core.utils.codeutils.ExpressionNode) NotImplementedException(org.wso2.charon3.core.exceptions.NotImplementedException)

Aggregations

BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)19 ArrayList (java.util.ArrayList)11 HashMap (java.util.HashMap)11 Test (org.testng.annotations.Test)11 JSONArray (org.json.JSONArray)9 JSONObject (org.json.JSONObject)9 Attribute (org.wso2.charon3.core.attributes.Attribute)9 ComplexAttribute (org.wso2.charon3.core.attributes.ComplexAttribute)9 MultiValuedAttribute (org.wso2.charon3.core.attributes.MultiValuedAttribute)9 SimpleAttribute (org.wso2.charon3.core.attributes.SimpleAttribute)9 CharonException (org.wso2.charon3.core.exceptions.CharonException)9 SCIMResponse (org.wso2.charon3.core.protocol.SCIMResponse)8 List (java.util.List)7 NotImplementedException (org.wso2.charon3.core.exceptions.NotImplementedException)7 LinkedHashMap (java.util.LinkedHashMap)6 Map (java.util.Map)6 JSONException (org.json.JSONException)6 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)6 AttributeSchema (org.wso2.charon3.core.schema.AttributeSchema)6 ExtractableResponse (io.restassured.response.ExtractableResponse)5