Search in sources :

Example 6 with ErrorHandler

use of org.wso2.carbon.apimgt.api.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.api.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.api.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.api.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.api.ErrorHandler in project carbon-apimgt by wso2.

the class OASParserUtil method validateAPIDefinitionByURL.

/**
 * This method validates the given OpenAPI definition by URL
 *
 * @param url               URL of the API definition
 * @param returnJsonContent whether to return the converted json form of the
 * @return APIDefinitionValidationResponse object with validation information
 */
public static APIDefinitionValidationResponse validateAPIDefinitionByURL(String url, boolean returnJsonContent) throws APIManagementException {
    APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
    try {
        URL urlObj = new URL(url);
        String host = urlObj.getHost();
        HttpClient httpClient = APIUtil.getHttpClient(urlObj.getPort(), urlObj.getProtocol());
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpGet);
        if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
            String responseStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            validationResponse = validateAPIDefinition(responseStr, host, returnJsonContent);
        } else {
            validationResponse.setValid(false);
            validationResponse.getErrorItems().add(ExceptionCodes.OPENAPI_URL_NO_200);
        }
    } catch (IOException e) {
        ErrorHandler errorHandler = ExceptionCodes.OPENAPI_URL_MALFORMED;
        // Log the error and continue since this method is only intended to validate a definition
        log.error(errorHandler.getErrorDescription(), e);
        validationResponse.setValid(false);
        validationResponse.getErrorItems().add(errorHandler);
    }
    return validationResponse;
}
Also used : ErrorHandler(org.wso2.carbon.apimgt.api.ErrorHandler) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) URL(java.net.URL) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

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