Search in sources :

Example 6 with ErrorHandler

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

the class SubscriptionsApiServiceImpl method subscriptionsPost.

/**
 * Adds a new subscription
 *
 * @param body        Subscription details to be added
 * @param request     msf4j request object
 * @return Newly added subscription as the response
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response subscriptionsPost(SubscriptionDTO body, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    SubscriptionDTO subscriptionDTO = null;
    URI location = null;
    try {
        APIStore apiStore = RestApiUtil.getConsumer(username);
        String applicationId = body.getApplicationId();
        String apiId = body.getApiIdentifier();
        String tier = body.getPolicy();
        Application application = apiStore.getApplicationByUuid(applicationId);
        if (application != null && !ApplicationStatus.APPLICATION_APPROVED.equals(application.getStatus())) {
            String errorMessage = "Application " + applicationId + " is not active";
            ExceptionCodes exceptionCode = ExceptionCodes.APPLICATION_INACTIVE;
            APIManagementException e = new APIManagementException(errorMessage, exceptionCode);
            Map<String, String> paramList = new HashMap<>();
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
            log.error(errorMessage, e);
            return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
        }
        if (application != null) {
            SubscriptionResponse addSubResponse = apiStore.addApiSubscription(apiId, applicationId, tier);
            String subscriptionId = addSubResponse.getSubscriptionUUID();
            Subscription subscription = apiStore.getSubscriptionByUUID(subscriptionId);
            location = new URI(RestApiConstants.RESOURCE_PATH_SUBSCRIPTION + "/" + subscriptionId);
            subscriptionDTO = SubscriptionMappingUtil.fromSubscriptionToDTO(subscription);
            // be in either pending or approved state) send back the workflow response
            if (SubscriptionStatus.ON_HOLD == subscription.getStatus()) {
                WorkflowResponseDTO workflowResponse = MiscMappingUtil.fromWorkflowResponseToDTO(addSubResponse.getWorkflowResponse());
                return Response.status(Response.Status.ACCEPTED).header(RestApiConstants.LOCATION_HEADER, location).entity(workflowResponse).build();
            }
        } else {
            String errorMessage = null;
            ExceptionCodes exceptionCode = null;
            exceptionCode = ExceptionCodes.APPLICATION_NOT_FOUND;
            errorMessage = "Application not found";
            APIMgtResourceNotFoundException e = new APIMgtResourceNotFoundException(errorMessage, exceptionCode);
            Map<String, String> paramList = new HashMap<>();
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
            log.error(errorMessage, e);
            return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
        }
    } catch (GatewayException e) {
        String errorMessage = "Failed to add subscription of API : " + body.getApiIdentifier() + " to gateway";
        log.error(errorMessage, e);
        return Response.status(Response.Status.ACCEPTED).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while adding subscriptions";
        Map<String, String> paramList = new HashMap<>();
        paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, body.getApiIdentifier());
        paramList.put(APIMgtConstants.ExceptionsConstants.APPLICATION_ID, body.getApplicationId());
        paramList.put(APIMgtConstants.ExceptionsConstants.TIER, body.getPolicy());
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    } catch (URISyntaxException e) {
        String errorMessage = "Error while adding location header in response for subscription : " + body.getSubscriptionId();
        Map<String, String> paramList = new HashMap<>();
        paramList.put(APIMgtConstants.ExceptionsConstants.SUBSCRIPTION_ID, body.getSubscriptionId());
        ErrorHandler errorHandler = ExceptionCodes.LOCATION_HEADER_INCORRECT;
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(errorHandler, paramList);
        log.error(errorMessage, e);
        return Response.status(errorHandler.getHttpStatusCode()).entity(errorDTO).build();
    }
    return Response.status(Response.Status.CREATED).header(RestApiConstants.LOCATION_HEADER, location).entity(subscriptionDTO).build();
}
Also used : ErrorHandler(org.wso2.carbon.apimgt.core.exception.ErrorHandler) HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) URISyntaxException(java.net.URISyntaxException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.core.exception.APIMgtResourceNotFoundException) URI(java.net.URI) WorkflowResponseDTO(org.wso2.carbon.apimgt.rest.api.store.dto.WorkflowResponseDTO) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) GatewayException(org.wso2.carbon.apimgt.core.exception.GatewayException) SubscriptionResponse(org.wso2.carbon.apimgt.core.models.SubscriptionResponse) ExceptionCodes(org.wso2.carbon.apimgt.core.exception.ExceptionCodes) Subscription(org.wso2.carbon.apimgt.core.models.Subscription) SubscriptionDTO(org.wso2.carbon.apimgt.rest.api.store.dto.SubscriptionDTO) Application(org.wso2.carbon.apimgt.core.models.Application) HashMap(java.util.HashMap) Map(java.util.Map) APIStore(org.wso2.carbon.apimgt.core.api.APIStore)

Example 7 with ErrorHandler

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

the class AuthUtil method getErrorDTO.

/**
 * Returns a generic errorDTO
 *
 * @param errorHandler The error handler object.
 * @param paramList list of parameters for more detail
 * @return A generic errorDTO with the specified details
 */
public static ErrorDTO getErrorDTO(ErrorHandler errorHandler, HashMap<String, String> paramList) {
    ErrorDTO errorDTO = new ErrorDTO();
    errorDTO.setCode(errorHandler.getErrorCode());
    errorDTO.setMoreInfo(paramList);
    errorDTO.setMessage(errorHandler.getErrorMessage());
    errorDTO.setDescription(errorHandler.getErrorDescription());
    return errorDTO;
}
Also used : ErrorDTO(org.wso2.carbon.apimgt.rest.api.authenticator.dto.ErrorDTO)

Example 8 with ErrorHandler

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

the class AuthUtilTestCase method testGetErrorDTO.

@Test
public void testGetErrorDTO() {
    ErrorHandler errorHandler = new ErrorHandler() {

        @Override
        public long getErrorCode() {
            return 1234567890L;
        }

        @Override
        public String getErrorMessage() {
            return "xxx-error-message-xxx";
        }

        @Override
        public String getErrorDescription() {
            return "xxx-error-description-xxx";
        }
    };
    HashMap<String, String> paramList = new HashMap<>();
    paramList.put("param_1", "xxx-param_1-xxx");
    paramList.put("param_2", "xxx-param_2-xxx");
    // // expected error dto
    ErrorDTO expectedErrorDTO = new ErrorDTO();
    expectedErrorDTO.setCode(1234567890L);
    expectedErrorDTO.setMessage("xxx-error-message-xxx");
    expectedErrorDTO.setDescription("xxx-error-description-xxx");
    expectedErrorDTO.setMoreInfo(paramList);
    ErrorDTO actualErrorDTO = AuthUtil.getErrorDTO(errorHandler, paramList);
    Assert.assertEquals(expectedErrorDTO.getCode(), actualErrorDTO.getCode());
    Assert.assertEquals(expectedErrorDTO.getMessage(), actualErrorDTO.getMessage());
    Assert.assertEquals(expectedErrorDTO.getDescription(), actualErrorDTO.getDescription());
    Assert.assertEquals(expectedErrorDTO.getMoreInfo(), actualErrorDTO.getMoreInfo());
}
Also used : ErrorHandler(org.wso2.carbon.apimgt.core.exception.ErrorHandler) HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.authenticator.dto.ErrorDTO) Test(org.junit.Test)

Example 9 with ErrorHandler

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

the class RestApiUtilTestCase method testGetErrorDTO2.

@Test(description = "Test get Error DTO as String")
public void testGetErrorDTO2() throws Exception {
    ErrorHandler errorHandler = Mockito.mock(ErrorHandler.class);
    Map<String, String> paramList = new HashMap<>();
    APIManagementException ex = Mockito.mock(APIManagementException.class);
    paramList.put("param1", "test1");
    paramList.put("param2", "test2");
    paramList.put("param3", "test3");
    when(errorHandler.getErrorDescription()).thenReturn("Test Error Description");
    when(ex.getMessage()).thenReturn("Error Message");
    when(errorHandler.getErrorCode()).thenReturn((long) 900300);
    final String expectedErrorDTOString1 = "class ErrorDTO {\n" + "  code: 900300\n" + "  message: Error Message\n" + "  description: Test Error Description\n" + "  moreInfo: {param3=test3, param1=test1, param2=test2}\n" + "  error: []\n" + "}\n";
    final String expectedErrorDTOString2 = "class ErrorDTO {\n" + "  code: 900300\n" + "  message: null\n" + "  description: Test Error Description\n" + "  moreInfo: {param3=test3, param1=test1, param2=test2}\n" + "  error: []\n" + "}\n";
    ErrorDTO errorDTO1 = RestApiUtil.getErrorDTO(errorHandler, (HashMap<String, String>) paramList, ex);
    Assert.assertEquals(errorDTO1.toString(), expectedErrorDTOString1);
    when(ex.getMessage()).thenReturn(null);
    ErrorDTO errorDTO2 = RestApiUtil.getErrorDTO(errorHandler, (HashMap<String, String>) paramList, ex);
    Assert.assertEquals(errorDTO2.toString(), expectedErrorDTOString2);
}
Also used : ErrorHandler(org.wso2.carbon.apimgt.core.exception.ErrorHandler) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 10 with ErrorHandler

use of org.wso2.carbon.apimgt.core.exception.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)18 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 Application (org.wso2.carbon.apimgt.core.models.Application)4 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 ErrorDTO (org.wso2.carbon.apimgt.rest.api.authenticator.dto.ErrorDTO)2 APIMgtSecurityException (org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException)2