Search in sources :

Example 1 with InternalServerErrorException

use of org.wso2.carbon.apimgt.rest.api.util.exception.InternalServerErrorException in project carbon-apimgt by wso2.

the class RestApiUtil method handleInternalServerError.

/**
 * Logs the error, builds a internalServerErrorException with specified details and throws it
 *
 * @param msg error message
 * @param t Throwable instance
 * @param log Log instance
 * @throws InternalServerErrorException
 */
public static void handleInternalServerError(String msg, Throwable t, Log log) throws InternalServerErrorException {
    InternalServerErrorException internalServerErrorException = buildInternalServerErrorException(msg);
    log.error(msg, t);
    throw internalServerErrorException;
}
Also used : InternalServerErrorException(org.wso2.carbon.apimgt.rest.api.util.exception.InternalServerErrorException)

Example 2 with InternalServerErrorException

use of org.wso2.carbon.apimgt.rest.api.util.exception.InternalServerErrorException 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 3 with InternalServerErrorException

use of org.wso2.carbon.apimgt.rest.api.util.exception.InternalServerErrorException in project carbon-apimgt by wso2.

the class RestApiUtil method handleInternalServerError.

/**
 * Logs the error, builds a internalServerErrorException with specified details and throws it
 *
 * @param msg error message
 * @param log Log instance
 * @throws InternalServerErrorException
 */
public static void handleInternalServerError(String msg, Log log) throws InternalServerErrorException {
    InternalServerErrorException internalServerErrorException = buildInternalServerErrorException();
    log.error(msg);
    throw internalServerErrorException;
}
Also used : InternalServerErrorException(org.wso2.carbon.apimgt.rest.api.util.exception.InternalServerErrorException)

Example 4 with InternalServerErrorException

use of org.wso2.carbon.apimgt.rest.api.util.exception.InternalServerErrorException in project carbon-apimgt by wso2.

the class RestApiUtilTest method testIsDueToResourceNotFoundWithAPIMgtResourceNotFoundException.

// TODO : The passed error message will not get displayed in the thrown exception. Implementation in
// InternalServerErrorException class is not done right to reflect the error message description
// @Test
// public void testHandleInternalServerError() {
// String errorMessage = "Error while updating application owner.";
// 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.handleInternalServerError(errorMessage, throwable, log);
// } catch (InternalServerErrorException exception) {
// exceptionCaught = exception;
// }
// 
// Assert.assertEquals(errorMessage, exceptionCaught.getMessage());
// Mockito.verify(log).error(errorMessage, throwable);
// }
@Test
public void testIsDueToResourceNotFoundWithAPIMgtResourceNotFoundException() throws Exception {
    APIMgtResourceNotFoundException sampleAPIMgtResourceNotFoundException = new APIMgtResourceNotFoundException("New Sample exception");
    Throwable testThrowable = new Throwable();
    PowerMockito.spy(RestApiUtil.class);
    PowerMockito.doReturn(sampleAPIMgtResourceNotFoundException).when(RestApiUtil.class, "getPossibleErrorCause", testThrowable);
    Assert.assertTrue("Invalid exception has been passed.", RestApiUtil.isDueToResourceNotFound(testThrowable));
}
Also used : APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 5 with InternalServerErrorException

use of org.wso2.carbon.apimgt.rest.api.util.exception.InternalServerErrorException in project carbon-apimgt by wso2.

the class ApplicationKeyMappingUtil method fromApplicationKeyToDTO.

/**
 * Insert the application related details to a DTO Object
 *
 * @param keyDetails Application related details map
 * @param applicationKeyType Key type of the application
 * @return DTO object with application related details
 */
@SuppressWarnings("unchecked")
public static ApplicationKeyDTO fromApplicationKeyToDTO(Map<String, Object> keyDetails, String applicationKeyType) {
    ApplicationKeyDTO applicationKeyDTO = new ApplicationKeyDTO();
    applicationKeyDTO.setConsumerKey((String) keyDetails.get(APIConstants.FrontEndParameterNames.CONSUMER_KEY));
    applicationKeyDTO.setKeyMappingId((String) keyDetails.get(APIConstants.FrontEndParameterNames.KEY_MAPPING_ID));
    applicationKeyDTO.setConsumerSecret((String) keyDetails.get(APIConstants.FrontEndParameterNames.CONSUMER_SECRET));
    applicationKeyDTO.setKeyState((String) keyDetails.get(APIConstants.FrontEndParameterNames.KEY_STATE));
    applicationKeyDTO.setKeyType(ApplicationKeyDTO.KeyTypeEnum.valueOf(applicationKeyType));
    Object mode = keyDetails.get(APIConstants.FrontEndParameterNames.MODE);
    if (mode != null) {
        applicationKeyDTO.setMode(ApplicationKeyDTO.ModeEnum.valueOf((String) mode));
    }
    try {
        String appDetailsString = (String) keyDetails.get(ApplicationConstants.OAUTH_APP_DETAILS);
        if (appDetailsString != null) {
            JSONObject appDetailsJsonObj = (JSONObject) new JSONParser().parse(appDetailsString);
            if (appDetailsJsonObj != null) {
                String supportedGrantTypes = (String) appDetailsJsonObj.get(ApplicationConstants.OAUTH_CLIENT_GRANT);
                if (supportedGrantTypes != null) {
                    applicationKeyDTO.setSupportedGrantTypes(Arrays.asList(supportedGrantTypes.split(" ")));
                }
                String callbackUrl = (String) appDetailsJsonObj.get(ApplicationConstants.OAUTH_REDIRECT_URIS);
                applicationKeyDTO.setCallbackUrl(callbackUrl);
                Object additionalPropertiesObj = appDetailsJsonObj.get(APIConstants.JSON_ADDITIONAL_PROPERTIES);
                if (additionalPropertiesObj != null) {
                    if (additionalPropertiesObj instanceof JSONObject) {
                        Map additionalPropertiesMap = new HashMap();
                        additionalPropertiesMap.putAll((Map) additionalPropertiesObj);
                        applicationKeyDTO.setAdditionalProperties(additionalPropertiesMap);
                    } else if (additionalPropertiesObj instanceof String) {
                        applicationKeyDTO.setAdditionalProperties(additionalPropertiesObj);
                    }
                }
            }
        }
        ApplicationTokenDTO tokenDTO = new ApplicationTokenDTO();
        tokenDTO.setValidityTime((Long) keyDetails.get(APIConstants.AccessTokenConstants.VALIDITY_TIME));
        tokenDTO.setAccessToken((String) keyDetails.get(APIConstants.AccessTokenConstants.ACCESS_TOKEN));
        String[] tokenScopes = (String[]) keyDetails.get(APIConstants.AccessTokenConstants.TOKEN_SCOPES);
        if (tokenScopes != null) {
            tokenDTO.setTokenScopes(Arrays.asList(tokenScopes));
        }
        applicationKeyDTO.setToken(tokenDTO);
    } catch (ParseException e) {
        String errorMsg = "Error while parsing application details string";
        log.error(errorMsg, e);
        throw new InternalServerErrorException(errorMsg, e);
    }
    return applicationKeyDTO;
}
Also used : ApplicationTokenDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationTokenDTO) JSONObject(org.json.simple.JSONObject) ApplicationKeyDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO) HashMap(java.util.HashMap) InternalServerErrorException(org.wso2.carbon.apimgt.rest.api.util.exception.InternalServerErrorException) JSONObject(org.json.simple.JSONObject) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

InternalServerErrorException (org.wso2.carbon.apimgt.rest.api.util.exception.InternalServerErrorException)3 JsonParseException (com.fasterxml.jackson.core.JsonParseException)1 JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)1 UnrecognizedPropertyException (com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException)1 EOFException (java.io.EOFException)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 ClientErrorException (javax.ws.rs.ClientErrorException)1 AuthenticationException (org.apache.cxf.interceptor.security.AuthenticationException)1 JSONObject (org.json.simple.JSONObject)1 JSONParser (org.json.simple.parser.JSONParser)1 ParseException (org.json.simple.parser.ParseException)1 Test (org.junit.Test)1 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)1 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)1 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)1 ErrorHandler (org.wso2.carbon.apimgt.api.ErrorHandler)1 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)1 ApplicationKeyDTO (org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO)1 ApplicationTokenDTO (org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationTokenDTO)1