Search in sources :

Example 6 with ConflictException

use of org.wso2.charon3.core.exceptions.ConflictException in project charon by wso2.

the class UserResourceManager method create.

/*
     * Returns SCIMResponse based on the sucess or failure of the create user operation
     *
     * @param scimObjectString -raw string containing user info
     * @return usermanager - usermanager instance defined by the external implementor of charon
     */
public SCIMResponse create(String scimObjectString, UserManager userManager, String attributes, String excludeAttributes) {
    JSONEncoder encoder = null;
    try {
        // obtain the json encoder
        encoder = getEncoder();
        // obtain the json decoder
        JSONDecoder decoder = getDecoder();
        // obtain the schema corresponding to user
        // unless configured returns core-user schema or else returns extended user schema)
        SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getUserResourceSchema();
        // decode the SCIM User object, encoded in the submitted payload.
        User user = (User) decoder.decodeResource(scimObjectString, schema, new User());
        // validate the created user.
        ServerSideValidator.validateCreatedSCIMObject(user, schema);
        // 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 createdUser;
        if (userManager != null) {
            /*handover the SCIM User object to the user usermanager provided by the SP.
            need to send back the newly created user in the response payload*/
            createdUser = userManager.createUser(user, requiredAttributes);
        } else {
            String error = "Provided user manager handler is null.";
            // throw internal server error.
            throw new InternalErrorException(error);
        }
        // encode the newly created SCIM user object and add id attribute to Location header.
        String encodedUser;
        Map<String, String> responseHeaders = new HashMap<String, String>();
        if (createdUser != null) {
            // create a deep copy of the user object since we are going to change it.
            User copiedUser = (User) CopyUtil.deepCopy(createdUser);
            // need to remove password before returning
            ServerSideValidator.validateReturnedAttributes(copiedUser, attributes, excludeAttributes);
            encodedUser = encoder.encodeSCIMObject(copiedUser);
            // add location header
            responseHeaders.put(SCIMConstants.LOCATION_HEADER, getResourceEndpointURL(SCIMConstants.USER_ENDPOINT) + "/" + createdUser.getId());
            responseHeaders.put(SCIMConstants.CONTENT_TYPE_HEADER, SCIMConstants.APPLICATION_JSON);
        } else {
            String error = "Newly created User resource is null.";
            throw new InternalErrorException(error);
        }
        // put the uri of the User object in the response header parameter.
        return new SCIMResponse(ResponseCodeConstants.CODE_CREATED, encodedUser, responseHeaders);
    } catch (CharonException e) {
        // because inside API code throws CharonException.
        if (e.getStatus() == -1) {
            e.setStatus(ResponseCodeConstants.CODE_INTERNAL_ERROR);
        }
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (BadRequestException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (ConflictException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (InternalErrorException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (NotFoundException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    }
}
Also used : User(org.wso2.charon3.core.objects.User) HashMap(java.util.HashMap) ConflictException(org.wso2.charon3.core.exceptions.ConflictException) NotFoundException(org.wso2.charon3.core.exceptions.NotFoundException) InternalErrorException(org.wso2.charon3.core.exceptions.InternalErrorException) JSONDecoder(org.wso2.charon3.core.encoder.JSONDecoder) 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) SCIMResponse(org.wso2.charon3.core.protocol.SCIMResponse)

Example 7 with ConflictException

use of org.wso2.charon3.core.exceptions.ConflictException in project carbon-apimgt by wso2.

the class GlobalThrowableMapper method toResponse.

@Override
public Response toResponse(Throwable e) {
    if (e instanceof ClientErrorException) {
        log.error("Client error", e);
        return ((ClientErrorException) e).getResponse();
    }
    if (e instanceof NotFoundException) {
        log.error("Resource not found", e);
        return ((NotFoundException) e).getResponse();
    }
    if (e instanceof PreconditionFailedException) {
        log.error("Precondition failed", e);
        return ((PreconditionFailedException) e).getResponse();
    }
    if (e instanceof BadRequestException) {
        log.error("Bad request", e);
        return ((BadRequestException) e).getResponse();
    }
    if (e instanceof ConstraintViolationException) {
        log.error("Constraint violation", e);
        return ((ConstraintViolationException) e).getResponse();
    }
    if (e instanceof ForbiddenException) {
        log.error("Resource forbidden", e);
        return ((ForbiddenException) e).getResponse();
    }
    if (e instanceof ConflictException) {
        log.error("Conflict", e);
        return ((ConflictException) e).getResponse();
    }
    if (e instanceof MethodNotAllowedException) {
        log.error("Method not allowed", e);
        return ((MethodNotAllowedException) e).getResponse();
    }
    if (e instanceof InternalServerErrorException) {
        String errorMessage = "The server encountered an internal error : " + e.getMessage();
        log.error(errorMessage, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).type(MediaType.APPLICATION_JSON_TYPE).entity(e500).build();
    }
    if (e instanceof JsonParseException) {
        String errorMessage = "Malformed request body.";
        log.error(errorMessage, e);
        // noinspection ThrowableResultOfMethodCallIgnored
        return RestApiUtil.buildBadRequestException(errorMessage).getResponse();
    }
    if (e instanceof JsonMappingException) {
        if (e instanceof UnrecognizedPropertyException) {
            UnrecognizedPropertyException unrecognizedPropertyException = (UnrecognizedPropertyException) e;
            String unrecognizedProperty = unrecognizedPropertyException.getPropertyName();
            String errorMessage = "Unrecognized property '" + unrecognizedProperty + "'";
            log.error(errorMessage, e);
            // noinspection ThrowableResultOfMethodCallIgnored
            return RestApiUtil.buildBadRequestException(errorMessage).getResponse();
        } else {
            String errorMessage = "One or more request body parameters contain disallowed values.";
            log.error(errorMessage, e);
            // noinspection ThrowableResultOfMethodCallIgnored
            return RestApiUtil.buildBadRequestException(errorMessage).getResponse();
        }
    }
    if (e instanceof AuthenticationException) {
        ErrorDTO errorDetail = new ErrorDTO();
        errorDetail.setCode((long) 401);
        errorDetail.setMoreInfo("");
        errorDetail.setMessage("");
        errorDetail.setDescription(e.getMessage());
        return Response.status(Response.Status.UNAUTHORIZED).type(MediaType.APPLICATION_JSON_TYPE).entity(errorDetail).build();
    }
    // This occurs when received an empty body in an occasion where the body is mandatory
    if (e instanceof EOFException) {
        String errorMessage = "Request payload cannot be empty.";
        log.error(errorMessage, e);
        // noinspection ThrowableResultOfMethodCallIgnored
        return RestApiUtil.buildBadRequestException(errorMessage).getResponse();
    }
    if (e instanceof APIManagementException) {
        ErrorHandler selectedErrorHandler = null;
        List<Throwable> throwableList = ExceptionUtils.getThrowableList(e);
        for (Throwable t : throwableList) {
            if (t instanceof APIManagementException) {
                APIManagementException apimException = (APIManagementException) t;
                ErrorHandler errorHandler = apimException.getErrorHandler();
                if (errorHandler != null) {
                    if (selectedErrorHandler == null) {
                        selectedErrorHandler = errorHandler;
                    } else {
                        selectedErrorHandler = errorHandler.getHttpStatusCode() < selectedErrorHandler.getHttpStatusCode() && errorHandler.getHttpStatusCode() > 0 ? errorHandler : selectedErrorHandler;
                    }
                }
            }
        }
        if (selectedErrorHandler != null) {
            // logs the error as the error may be not logged by the origin
            if (selectedErrorHandler.printStackTrace()) {
                log.error("A defined exception has been captured and mapped to an HTTP response " + "by the global exception mapper ", e);
            } else {
                // Not to log the stack trace due to error code was mark as not print stacktrace.
                log.error(e.getMessage());
                if (log.isDebugEnabled()) {
                    log.debug("A defined exception has been captured and mapped to an HTTP response " + "by the global exception mapper ", e);
                }
            }
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(selectedErrorHandler);
            return Response.status(Response.Status.fromStatusCode(selectedErrorHandler.getHttpStatusCode())).type(MediaType.APPLICATION_JSON_TYPE).entity(errorDTO).build();
        }
    }
    // unknown exception log and return
    log.error("An unknown exception has been captured by the global exception mapper.", e);
    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).type(MediaType.APPLICATION_JSON_TYPE).entity(e500).build();
}
Also used : ErrorHandler(org.wso2.carbon.apimgt.api.ErrorHandler) AuthenticationException(org.apache.cxf.interceptor.security.AuthenticationException) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) UnrecognizedPropertyException(com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) EOFException(java.io.EOFException) ClientErrorException(javax.ws.rs.ClientErrorException)

Example 8 with ConflictException

use of org.wso2.charon3.core.exceptions.ConflictException in project carbon-apimgt by wso2.

the class RestApiUtilTest method testHandleResourceNotFoundError.

@Test
public void testHandleResourceNotFoundError() {
    String errorMessage = "Requested new version already exists";
    Throwable throwable = new Throwable();
    Exception exceptionCaught = null;
    Log log = Mockito.mock(Log.class);
    PowerMockito.mockStatic(LogFactory.class);
    PowerMockito.when(LogFactory.getLog(Mockito.any(Class.class))).thenReturn(log);
    try {
        RestApiUtil.handleResourceAlreadyExistsError(errorMessage, throwable, log);
    } catch (ConflictException exception) {
        exceptionCaught = exception;
    }
    Assert.assertEquals(errorMessage, exceptionCaught.getMessage());
    Mockito.verify(log).error(errorMessage, throwable);
}
Also used : Log(org.apache.commons.logging.Log) ConflictException(org.wso2.carbon.apimgt.rest.api.util.exception.ConflictException) AuthorizationFailedException(org.wso2.carbon.registry.core.secure.AuthorizationFailedException) ConflictException(org.wso2.carbon.apimgt.rest.api.util.exception.ConflictException) ForbiddenException(org.wso2.carbon.apimgt.rest.api.util.exception.ForbiddenException) APIMgtAuthorizationFailedException(org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException) ApplicationNameWhiteSpaceValidationException(org.wso2.carbon.apimgt.api.ApplicationNameWhiteSpaceValidationException) BadRequestException(org.wso2.carbon.apimgt.rest.api.util.exception.BadRequestException) DuplicateAPIException(org.wso2.carbon.apimgt.api.model.DuplicateAPIException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) ApplicationNameWithInvalidCharactersException(org.wso2.carbon.apimgt.api.ApplicationNameWithInvalidCharactersException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ResourceNotFoundException(org.wso2.carbon.registry.core.exceptions.ResourceNotFoundException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 9 with ConflictException

use of org.wso2.charon3.core.exceptions.ConflictException in project carbon-apimgt by wso2.

the class RestApiUtilTest method testHandleResourceAlreadyExistsError.

@Test
public void testHandleResourceAlreadyExistsError() {
    String errorMessage = "Requested new version already exists";
    Throwable throwable = new Throwable();
    Exception exceptionCaught = null;
    Log log = Mockito.mock(Log.class);
    PowerMockito.mockStatic(LogFactory.class);
    PowerMockito.when(LogFactory.getLog(Mockito.any(Class.class))).thenReturn(log);
    try {
        RestApiUtil.handleResourceAlreadyExistsError(errorMessage, throwable, log);
    } catch (ConflictException exception) {
        exceptionCaught = exception;
    }
    Assert.assertEquals(errorMessage, exceptionCaught.getMessage());
    Mockito.verify(log).error(errorMessage, throwable);
}
Also used : Log(org.apache.commons.logging.Log) ConflictException(org.wso2.carbon.apimgt.rest.api.util.exception.ConflictException) AuthorizationFailedException(org.wso2.carbon.registry.core.secure.AuthorizationFailedException) ConflictException(org.wso2.carbon.apimgt.rest.api.util.exception.ConflictException) ForbiddenException(org.wso2.carbon.apimgt.rest.api.util.exception.ForbiddenException) APIMgtAuthorizationFailedException(org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException) ApplicationNameWhiteSpaceValidationException(org.wso2.carbon.apimgt.api.ApplicationNameWhiteSpaceValidationException) BadRequestException(org.wso2.carbon.apimgt.rest.api.util.exception.BadRequestException) DuplicateAPIException(org.wso2.carbon.apimgt.api.model.DuplicateAPIException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) ApplicationNameWithInvalidCharactersException(org.wso2.carbon.apimgt.api.ApplicationNameWithInvalidCharactersException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ResourceNotFoundException(org.wso2.carbon.registry.core.exceptions.ResourceNotFoundException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

ConflictException (org.wso2.carbon.apimgt.rest.api.util.exception.ConflictException)5 HashMap (java.util.HashMap)3 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)3 JSONDecoder (org.wso2.charon3.core.encoder.JSONDecoder)3 JSONEncoder (org.wso2.charon3.core.encoder.JSONEncoder)3 BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)3 CharonException (org.wso2.charon3.core.exceptions.CharonException)3 ConflictException (org.wso2.charon3.core.exceptions.ConflictException)3 InternalErrorException (org.wso2.charon3.core.exceptions.InternalErrorException)3 NotFoundException (org.wso2.charon3.core.exceptions.NotFoundException)3 SCIMResponse (org.wso2.charon3.core.protocol.SCIMResponse)3 SCIMResourceTypeSchema (org.wso2.charon3.core.schema.SCIMResourceTypeSchema)3 Log (org.apache.commons.logging.Log)2 Test (org.junit.Test)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 APIMgtAuthorizationFailedException (org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException)2 APIMgtResourceAlreadyExistsException (org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException)2 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)2 ApplicationNameWhiteSpaceValidationException (org.wso2.carbon.apimgt.api.ApplicationNameWhiteSpaceValidationException)2 ApplicationNameWithInvalidCharactersException (org.wso2.carbon.apimgt.api.ApplicationNameWithInvalidCharactersException)2