Search in sources :

Example 21 with FaultGatewaysException

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

the class ApisApiServiceImpl method updateTopics.

@Override
public Response updateTopics(String apiId, TopicListDTO topicListDTO, String ifMatch, MessageContext messageContext) throws APIManagementException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    String organization = RestApiUtil.getValidatedOrganization(messageContext);
    // validate if api exists
    validateAPIExistence(apiId);
    API existingAPI = apiProvider.getAPIbyUUID(apiId, organization);
    // validate API update operation permitted based on the LC state
    validateAPIOperationsPerLC(existingAPI.getStatus());
    Set<URITemplate> uriTemplates = existingAPI.getUriTemplates();
    uriTemplates.clear();
    for (TopicDTO topicDTO : topicListDTO.getList()) {
        URITemplate uriTemplate = new URITemplate();
        uriTemplate.setUriTemplate(topicDTO.getName());
        uriTemplate.setHTTPVerb(topicDTO.getMode().toUpperCase());
        // TODO: Get these from proper locations
        uriTemplate.setAuthType(APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN);
        uriTemplate.setThrottlingTier(APIConstants.UNLIMITED_TIER);
        uriTemplates.add(uriTemplate);
    }
    existingAPI.setUriTemplates(uriTemplates);
    // TODO: Add scopes
    existingAPI.setOrganization(organization);
    try {
        apiProvider.updateAPI(existingAPI);
    } catch (FaultGatewaysException e) {
        String errorMessage = "Error while updating API : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return Response.ok().build();
}
Also used : URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) TopicDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.TopicDTO) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 22 with FaultGatewaysException

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

the class ApisApiServiceImpl method updateAPIClientCertificateByAlias.

@Override
public Response updateAPIClientCertificateByAlias(String alias, String apiId, InputStream certificateInputStream, Attachment certificateDetail, String tier, MessageContext messageContext) {
    try {
        // validate if api exists
        validateAPIExistence(apiId);
        ContentDisposition contentDisposition;
        String fileName;
        String base64EncodedCert = null;
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        API api = apiProvider.getAPIbyUUID(apiId, organization);
        api.setOrganization(organization);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(api.getStatus());
        String userName = RestApiCommonUtil.getLoggedInUsername();
        int tenantId = APIUtil.getInternalOrganizationId(organization);
        ClientCertificateDTO clientCertificateDTO = CertificateRestApiUtils.preValidateClientCertificate(alias, api.getId(), organization);
        if (certificateDetail != null) {
            contentDisposition = certificateDetail.getContentDisposition();
            fileName = contentDisposition.getParameter(RestApiConstants.CONTENT_DISPOSITION_FILENAME);
            if (StringUtils.isNotBlank(fileName)) {
                base64EncodedCert = CertificateRestApiUtils.generateEncodedCertificate(certificateInputStream);
            }
        }
        if (StringUtils.isEmpty(base64EncodedCert) && StringUtils.isEmpty(tier)) {
            return Response.ok().entity("Client Certificate is not updated for alias " + alias).build();
        }
        int responseCode = apiProvider.updateClientCertificate(base64EncodedCert, alias, clientCertificateDTO.getApiIdentifier(), tier, tenantId, organization);
        if (ResponseCode.SUCCESS.getResponseCode() == responseCode) {
            // Handle api product case.
            if (API_PRODUCT_TYPE.equals(api.getType())) {
                APIIdentifier apiIdentifier = api.getId();
                APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(apiIdentifier.getProviderName(), apiIdentifier.getApiName(), apiIdentifier.getVersion());
                APIProduct apiProduct = apiProvider.getAPIProduct(apiProductIdentifier);
                apiProduct.setOrganization(organization);
                apiProvider.updateAPIProduct(apiProduct);
            } else {
                apiProvider.updateAPI(api);
            }
            ClientCertMetadataDTO clientCertMetadataDTO = new ClientCertMetadataDTO();
            clientCertMetadataDTO.setAlias(alias);
            clientCertMetadataDTO.setApiId(api.getUUID());
            clientCertMetadataDTO.setTier(clientCertificateDTO.getTierName());
            URI updatedCertUri = new URI(RestApiConstants.CLIENT_CERTS_BASE_PATH + "?alias=" + alias);
            return Response.ok(updatedCertUri).entity(clientCertMetadataDTO).build();
        } else if (ResponseCode.INTERNAL_SERVER_ERROR.getResponseCode() == responseCode) {
            RestApiUtil.handleInternalServerError("Error while updating the client certificate for the alias " + alias + " due to an internal " + "server error", log);
        } else if (ResponseCode.CERTIFICATE_NOT_FOUND.getResponseCode() == responseCode) {
            RestApiUtil.handleResourceNotFoundError("", log);
        } else if (ResponseCode.CERTIFICATE_EXPIRED.getResponseCode() == responseCode) {
            RestApiUtil.handleBadRequest("Error while updating the client certificate for the alias " + alias + " Certificate Expired.", log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while updating the client certificate for the alias " + alias + " due to an internal " + "server error", e, log);
    } catch (IOException e) {
        RestApiUtil.handleInternalServerError("Error while encoding client certificate for the alias " + alias, e, log);
    } catch (URISyntaxException e) {
        RestApiUtil.handleInternalServerError("Error while generating the resource location URI for alias '" + alias + "'", e, log);
    } catch (FaultGatewaysException e) {
        RestApiUtil.handleInternalServerError("Error while publishing the certificate change to gateways for the alias " + alias, e, log);
    }
    return null;
}
Also used : FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ClientCertMetadataDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ClientCertMetadataDTO) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 23 with FaultGatewaysException

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

the class ApisApiServiceImpl method updateAPIGraphQLSchema.

/**
 * Update GraphQL Schema
 *
 * @param apiId            api Id
 * @param schemaDefinition graphQL schema definition
 * @param ifMatch
 * @param messageContext
 * @return
 */
@Override
public Response updateAPIGraphQLSchema(String apiId, String schemaDefinition, String ifMatch, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        // validate if api exists
        validateAPIExistence(apiId);
        API originalAPI = apiProvider.getAPIbyUUID(apiId, organization);
        originalAPI.setOrganization(organization);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(originalAPI.getStatus());
        PublisherCommonUtils.addGraphQLSchema(originalAPI, schemaDefinition, apiProvider);
        APIDTO modifiedAPI = APIMappingUtil.fromAPItoDTO(originalAPI);
        return Response.ok().entity(modifiedAPI.getOperations()).build();
    } catch (APIManagementException | FaultGatewaysException e) {
        // to expose the existence of the resource
        if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure("Authorization failure while retrieving schema of API: " + apiId, e, log);
        } else {
            String errorMessage = "Error while uploading schema of the API: " + apiId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 24 with FaultGatewaysException

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

the class ApisApiServiceImpl method reimportServiceFromCatalog.

@Override
public Response reimportServiceFromCatalog(String apiId, MessageContext messageContext) throws APIManagementException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    String username = RestApiCommonUtil.getLoggedInUsername();
    String organization = RestApiUtil.getValidatedOrganization(messageContext);
    int tenantId = APIUtil.getTenantId(username);
    try {
        // validate if api exists
        APIInfo apiInfo = validateAPIExistence(apiId);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(apiInfo.getStatus().toString());
        API api = apiProvider.getLightweightAPIByUUID(apiId, organization);
        API originalAPI = apiProvider.getAPIbyUUID(apiId, organization);
        String serviceKey = apiProvider.retrieveServiceKeyByApiId(originalAPI.getId().getId(), tenantId);
        ServiceCatalogImpl serviceCatalog = new ServiceCatalogImpl();
        ServiceEntry service = serviceCatalog.getServiceByKey(serviceKey, tenantId);
        JSONObject serviceInfo = new JSONObject();
        serviceInfo.put("name", service.getName());
        serviceInfo.put("version", service.getVersion());
        serviceInfo.put("key", service.getKey());
        serviceInfo.put("md5", service.getMd5());
        api.setServiceInfo(serviceInfo);
        Map validationResponseMap = new HashMap();
        if (ServiceEntry.DefinitionType.OAS2.equals(service.getDefinitionType()) || ServiceEntry.DefinitionType.OAS3.equals(service.getDefinitionType())) {
            validationResponseMap = validateOpenAPIDefinition(null, service.getEndpointDef(), null, null, true, true);
        } else if (ServiceEntry.DefinitionType.ASYNC_API.equals(service.getDefinitionType())) {
            validationResponseMap = validateAsyncAPISpecification(null, service.getEndpointDef(), null, true, true);
        } else if (!ServiceEntry.DefinitionType.WSDL1.equals(service.getDefinitionType())) {
            RestApiUtil.handleBadRequest("Unsupported definition type provided. Cannot re-import service to " + "API using the service type " + service.getDefinitionType(), log);
        }
        APIDefinitionValidationResponse validationAPIResponse = null;
        if (ServiceEntry.DefinitionType.WSDL1.equals(service.getDefinitionType())) {
            PublisherCommonUtils.addWsdl(RestApiConstants.APPLICATION_OCTET_STREAM, service.getEndpointDef(), api, apiProvider, organization);
        } else {
            validationAPIResponse = (APIDefinitionValidationResponse) validationResponseMap.get(RestApiConstants.RETURN_MODEL);
            if (!validationAPIResponse.isValid()) {
                RestApiUtil.handleBadRequest(validationAPIResponse.getErrorItems(), log);
            }
        }
        String protocol = (validationAPIResponse != null ? validationAPIResponse.getProtocol() : "");
        if (!APIConstants.API_TYPE_WEBSUB.equalsIgnoreCase(protocol)) {
            api.setEndpointConfig(PublisherCommonUtils.constructEndpointConfigForService(service.getServiceUrl(), protocol));
        }
        API updatedApi = apiProvider.updateAPI(api, originalAPI);
        if (validationAPIResponse != null) {
            PublisherCommonUtils.updateAPIDefinition(apiId, validationAPIResponse, service, organization);
        }
        return Response.ok().entity(APIMappingUtil.fromAPItoDTO(updatedApi)).build();
    } catch (APIManagementException e) {
        if (ExceptionCodes.MISSING_PROTOCOL_IN_ASYNC_API_DEFINITION.getErrorCode() == e.getErrorHandler().getErrorCode()) {
            RestApiUtil.handleBadRequest("Missing protocol in the Service Definition", log);
        } else if (ExceptionCodes.UNSUPPORTED_PROTOCOL_SPECIFIED_IN_ASYNC_API_DEFINITION.getErrorCode() == e.getErrorHandler().getErrorCode()) {
            RestApiUtil.handleBadRequest("Unsupported protocol specified in the Service Definition. Protocol " + "should be either sse or websub or ws", log);
        }
        RestApiUtil.handleInternalServerError("Error while retrieving the service key of the service " + "associated with API with id " + apiId, log);
    } catch (FaultGatewaysException e) {
        String errorMessage = "Error while updating API : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) APIInfo(org.wso2.carbon.apimgt.api.model.APIInfo) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) ServiceEntry(org.wso2.carbon.apimgt.api.model.ServiceEntry) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) ServiceCatalogImpl(org.wso2.carbon.apimgt.impl.ServiceCatalogImpl) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap)

Example 25 with FaultGatewaysException

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

the class ApisApiServiceImpl method updateAPI.

@Override
public Response updateAPI(String apiId, APIDTO body, String ifMatch, MessageContext messageContext) {
    String[] tokenScopes = (String[]) PhaseInterceptorChain.getCurrentMessage().getExchange().get(RestApiConstants.USER_REST_API_SCOPES);
    String username = RestApiCommonUtil.getLoggedInUsername();
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        // validate if api exists
        validateAPIExistence(apiId);
        // validate sandbox and production endpoints
        if (!PublisherCommonUtils.validateEndpoints(body)) {
            throw new APIManagementException("Invalid/Malformed endpoint URL(s) detected", ExceptionCodes.INVALID_ENDPOINT_URL);
        }
        APIProvider apiProvider = RestApiCommonUtil.getProvider(username);
        API originalAPI = apiProvider.getAPIbyUUID(apiId, organization);
        originalAPI.setOrganization(organization);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(originalAPI.getStatus());
        API updatedApi = PublisherCommonUtils.updateApi(originalAPI, body, apiProvider, tokenScopes);
        return Response.ok().entity(APIMappingUtil.fromAPItoDTO(updatedApi)).build();
    } catch (APIManagementException e) {
        // to expose the existence of the resource
        if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure("Authorization failure while updating API : " + apiId, e, log);
        } else {
            String errorMessage = "Error while updating the API : " + apiId + " - " + e.getMessage();
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    } catch (FaultGatewaysException e) {
        String errorMessage = "Error while updating API : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (CryptoException e) {
        String errorMessage = "Error while encrypting the secret key of API : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (ParseException e) {
        String errorMessage = "Error while parsing endpoint config of API : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) ParseException(org.json.simple.parser.ParseException) CryptoException(org.wso2.carbon.core.util.CryptoException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Aggregations

API (org.wso2.carbon.apimgt.api.model.API)26 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)25 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)20 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)18 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)18 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)17 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)16 HashMap (java.util.HashMap)11 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)11 Test (org.junit.Test)10 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)10 Map (java.util.Map)8 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)8 ArrayList (java.util.ArrayList)7 List (java.util.List)7 JSONObject (org.json.simple.JSONObject)6 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)6 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)6 HashSet (java.util.HashSet)5