Search in sources :

Example 11 with ErrorHandler

use of org.wso2.carbon.apimgt.api.ErrorHandler in project carbon-apimgt by wso2.

the class APIMWSDLReader method handleExceptionDuringValidation.

/**
 * Handles the provided exception occurred during validation and return a validation response or the exception.
 *
 * @param e exception object
 * @return a validation response if the exception contains an ErrorHandler
 * @throws APIManagementException if the exception doesn't contains an ErrorHandler. Throws the same error as 'e'
 */
private static WSDLValidationResponse handleExceptionDuringValidation(APIManagementException e) throws APIManagementException {
    if (e.getErrorHandler() != null && e.getErrorHandler().getHttpStatusCode() < 500) {
        log.debug("Validation error occurred due to invalid WSDL", e);
        WSDLValidationResponse validationResponse = new WSDLValidationResponse();
        validationResponse.setError(e.getErrorHandler());
        return validationResponse;
    } else {
        throw e;
    }
}
Also used : WSDLValidationResponse(org.wso2.carbon.apimgt.impl.wsdl.model.WSDLValidationResponse)

Example 12 with ErrorHandler

use of org.wso2.carbon.apimgt.api.ErrorHandler in project carbon-apimgt by wso2.

the class RestApiUtil method handleBadRequest.

/**
 * Logs the error, builds a BadRequestException with specified details and throws it
 *
 * @param errorHandlers A List of error handler objects containing the error information
 * @param log Log instance
 * @throws BadRequestException
 */
public static void handleBadRequest(List<ErrorHandler> errorHandlers, Log log) throws BadRequestException {
    BadRequestException badRequestException = buildBadRequestException(errorHandlers);
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < errorHandlers.size(); i++) {
        ErrorHandler handler = errorHandlers.get(i);
        builder.append(handler.getErrorMessage());
        if (StringUtils.isNotBlank(handler.getErrorDescription())) {
            builder.append(":");
            builder.append(handler.getErrorDescription());
        }
        if (i < errorHandlers.size() - 1) {
            builder.append(", ");
        }
    }
    log.error(builder.toString());
    throw badRequestException;
}
Also used : ErrorHandler(org.wso2.carbon.apimgt.api.ErrorHandler) BadRequestException(org.wso2.carbon.apimgt.rest.api.util.exception.BadRequestException)

Example 13 with ErrorHandler

use of org.wso2.carbon.apimgt.api.ErrorHandler in project carbon-apimgt by wso2.

the class RestApiUtil method handleBadRequest.

/**
 * Logs the error, builds a BadRequestException with specified details and throws it
 *
 * @param errorHandler ErrorHandler object containing the error information
 * @param log Log instance
 * @throws BadRequestException
 */
public static void handleBadRequest(ErrorHandler errorHandler, Log log) throws BadRequestException {
    BadRequestException badRequestException = buildBadRequestException(errorHandler);
    log.error(errorHandler.getErrorMessage());
    throw badRequestException;
}
Also used : BadRequestException(org.wso2.carbon.apimgt.rest.api.util.exception.BadRequestException)

Example 14 with ErrorHandler

use of org.wso2.carbon.apimgt.api.ErrorHandler in project carbon-apimgt by wso2.

the class APIMappingUtil method getErrorListItemsDTOsFromErrorHandler.

public static List<ErrorListItemDTO> getErrorListItemsDTOsFromErrorHandler(ErrorHandler error) {
    List<ErrorListItemDTO> errorListItemDTOs = new ArrayList<>();
    ErrorListItemDTO dto = new ErrorListItemDTO();
    dto.setCode(error.getErrorCode() + "");
    dto.setMessage(error.getErrorMessage());
    dto.setDescription(error.getErrorDescription());
    errorListItemDTOs.add(dto);
    return errorListItemDTOs;
}
Also used : ArrayList(java.util.ArrayList) ErrorListItemDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ErrorListItemDTO)

Example 15 with ErrorHandler

use of org.wso2.carbon.apimgt.api.ErrorHandler in project carbon-apimgt by wso2.

the class RESTAPISecurityInterceptor method preCall.

/**
 * preCall is run before a handler method call is made. If any of the preCalls throw exception or return false then
 * no other subsequent preCalls will be called and the request processing will be terminated,
 * also no postCall interceptors will be called.
 *
 * @param request           HttpRequest being processed.
 * @param response          HttpResponder to send response.
 * @param serviceMethodInfo Info on handler method that will be called.
 * @return true if the request processing can continue, otherwise the hook should send response and return false to
 * stop further processing.
 * @throws APIMgtSecurityException if error occurs while executing the preCall
 */
@Override
public boolean preCall(Request request, Response response, ServiceMethodInfo serviceMethodInfo) throws APIMgtSecurityException {
    ErrorHandler errorHandler = null;
    boolean isAuthenticated = false;
    // CORS for Environments - Add allowed Origin when User-Agent sent 'Origin' header.
    String origin = request.getHeader(RestApiConstants.ORIGIN_HEADER);
    String allowedOrigin = EnvironmentUtils.getAllowedOrigin(origin);
    if (allowedOrigin != null) {
        response.setHeader(RestApiConstants.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, allowedOrigin).setHeader(RestApiConstants.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER, "true");
    }
    // CORS for Environments - Add allowed Methods and Headers when 'OPTIONS' method is called.
    if (request.getHttpMethod().equalsIgnoreCase(APIConstants.HTTP_OPTIONS)) {
        try {
            String definedHttpMethods = RestApiUtil.getDefinedMethodHeadersInSwaggerContent(request, serviceMethodInfo);
            if (definedHttpMethods != null) {
                response.setHeader(RestApiConstants.ACCESS_CONTROL_ALLOW_METHODS_HEADER, definedHttpMethods).setHeader(RestApiConstants.ACCESS_CONTROL_ALLOW_HEADERS_HEADER, RestApiConstants.ACCESS_CONTROL_ALLOW_HEADERS_LIST).setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).send();
                return false;
            }
        } catch (APIManagementException e) {
            String msg = "Couldn't find declared HTTP methods in swagger.yaml";
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
            log.error(msg, e);
            response.setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setEntity(errorDTO).send();
            return false;
        }
    }
    /* TODO: Following string contains check is done to avoid checking security headers in non API requests.
         * Consider this as a temporary fix until MSF4J support context based interceptor registration */
    String requestURI = request.getUri().toLowerCase(Locale.ENGLISH);
    if (!requestURI.contains("/api/am/")) {
        return true;
    }
    if (requestURI.contains("/login/token")) {
        return true;
    }
    String yamlContent = null;
    String protocol = (String) request.getProperty(PROTOCOL);
    Swagger swagger = null;
    if (requestURI.contains("/api/am/publisher")) {
        if (requestURI.contains("swagger.yaml")) {
            try {
                yamlContent = RestApiUtil.getPublisherRestAPIResource();
                response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(yamlContent).setMediaType("text/x-yaml").send();
            } catch (APIManagementException e) {
                String msg = "Couldn't find swagger.yaml for publisher";
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
                log.error(msg, e);
                response.setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setEntity(errorDTO).send();
            }
            return false;
        }
    } else if (requestURI.contains("/api/am/store")) {
        if (requestURI.contains("swagger.json")) {
            try {
                yamlContent = RestApiUtil.getStoreRestAPIResource();
                swagger = new SwaggerParser().parse(yamlContent);
                swagger.setBasePath(RestApiUtil.getContext(RestApiConstants.APPType.STORE));
                swagger.setHost(RestApiUtil.getHost(protocol.toLowerCase(Locale.ENGLISH)));
                response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(Json.pretty(swagger)).setMediaType(MediaType.APPLICATION_JSON).send();
            } catch (APIManagementException e) {
                String msg = "Couldn't find swagger.json for store";
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
                log.error(msg, e);
                response.setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setEntity(errorDTO).send();
            }
            return false;
        } else if (requestURI.contains("swagger.yaml")) {
            try {
                yamlContent = RestApiUtil.getStoreRestAPIResource();
                response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(yamlContent).setMediaType("text/x-yaml").send();
            } catch (APIManagementException e) {
                String msg = "Couldn't find swagger.yaml for store";
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
                log.error(msg, e);
                response.setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setEntity(errorDTO).send();
            }
            return false;
        }
    } else if (requestURI.contains("/api/am/analytics")) {
        if (requestURI.contains("swagger.json")) {
            try {
                yamlContent = RestApiUtil.getAnalyticsRestAPIResource();
                swagger = new SwaggerParser().parse(yamlContent);
                swagger.setBasePath(RestApiUtil.getContext(RestApiConstants.APPType.ANALYTICS));
                swagger.setHost(RestApiUtil.getHost(protocol.toLowerCase(Locale.ENGLISH)));
            } catch (APIManagementException e) {
                log.error("Couldn't find swagger.json for analytics", e);
            }
            response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(Json.pretty(swagger)).setMediaType(MediaType.APPLICATION_JSON).send();
            return false;
        }
    } else if (requestURI.contains("/editor") || requestURI.contains("keyserver") || requestURI.contains("core") || requestURI.contains("/api/am/config")) {
        return true;
    } else if (requestURI.contains("/api/am/admin")) {
        if (requestURI.contains("swagger.json")) {
            try {
                yamlContent = RestApiUtil.getAdminRestAPIResource();
                swagger = new SwaggerParser().parse(yamlContent);
                swagger.setBasePath(RestApiUtil.getContext(RestApiConstants.APPType.ADMIN));
                swagger.setHost(RestApiUtil.getHost(protocol.toLowerCase(Locale.ENGLISH)));
                response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(Json.pretty(swagger)).setMediaType(MediaType.APPLICATION_JSON).send();
            } catch (APIManagementException e) {
                String msg = "Couldn't find swagger.yaml for admin";
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
                log.error(msg, e);
                response.setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setEntity(errorDTO).send();
            }
            return false;
        } else if (requestURI.contains("swagger.yaml")) {
            try {
                yamlContent = RestApiUtil.getAdminRestAPIResource();
                response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(yamlContent).setMediaType("text/x-yaml").send();
            } catch (APIManagementException e) {
                String msg = "Couldn't find swagger.yaml for admin";
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
                log.error(msg, e);
                response.setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setEntity(errorDTO).send();
            }
            return false;
        }
    }
    try {
        if (authenticatorImplClass == null) {
            Class<?> implClass = null;
            try {
                implClass = Class.forName(authenticatorName);
            } catch (ClassNotFoundException e) {
                throw new APIMgtSecurityException("Error while loading class " + authenticatorName, e);
            }
            authenticatorImplClass = (RESTAPIAuthenticator) implClass.newInstance();
        }
        isAuthenticated = authenticatorImplClass.authenticate(request, response, serviceMethodInfo);
    } catch (APIMgtSecurityException e) {
        errorHandler = e.getErrorHandler();
        log.error(e.getMessage() + " Requested Path: " + request.getUri());
    } catch (InstantiationException e) {
        log.error(e.getMessage() + " Error while instantiating authenticator: " + authenticatorName);
        isAuthenticated = false;
        errorHandler = ExceptionCodes.AUTH_GENERAL_ERROR;
    } catch (IllegalAccessException e) {
        log.error(e.getMessage() + " Error while accessing resource : " + authenticatorName);
        isAuthenticated = false;
        errorHandler = ExceptionCodes.AUTH_GENERAL_ERROR;
    }
    if (!isAuthenticated) {
        handleSecurityError(errorHandler, response);
    }
    return isAuthenticated;
}
Also used : SwaggerParser(io.swagger.parser.SwaggerParser) ErrorHandler(org.wso2.carbon.apimgt.core.exception.ErrorHandler) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIMgtSecurityException(org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) Swagger(io.swagger.models.Swagger)

Aggregations

ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)21 ErrorHandler (org.wso2.carbon.apimgt.core.exception.ErrorHandler)16 HashMap (java.util.HashMap)13 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)12 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)7 URI (java.net.URI)6 URISyntaxException (java.net.URISyntaxException)6 Map (java.util.Map)5 ErrorHandler (org.wso2.carbon.apimgt.api.ErrorHandler)5 Application (org.wso2.carbon.apimgt.core.models.Application)4 ArrayList (java.util.ArrayList)3 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)3 Test (org.testng.annotations.Test)3 WorkflowResponseDTO (org.wso2.carbon.apimgt.rest.api.store.dto.WorkflowResponseDTO)3 APIMgtAdminService (org.wso2.carbon.apimgt.core.api.APIMgtAdminService)2 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)2 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.core.exception.APIMgtResourceNotFoundException)2 ExceptionCodes (org.wso2.carbon.apimgt.core.exception.ExceptionCodes)2 Label (org.wso2.carbon.apimgt.core.models.Label)2 Subscription (org.wso2.carbon.apimgt.core.models.Subscription)2