use of org.wso2.carbon.apimgt.rest.api.util.exception.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);
}
}
use of org.wso2.carbon.apimgt.rest.api.util.exception.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();
}
use of org.wso2.carbon.apimgt.rest.api.util.exception.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);
}
use of org.wso2.carbon.apimgt.rest.api.util.exception.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);
}
Aggregations