Search in sources :

Example 56 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method importOpenAPIDefinition.

private APIDTO importOpenAPIDefinition(InputStream definition, String definitionUrl, String inlineDefinition, APIDTO apiDTOFromProperties, Attachment fileDetail, ServiceEntry service, String organization) throws APIManagementException {
    // Validate and retrieve the OpenAPI definition
    Map validationResponseMap = null;
    boolean isServiceAPI = false;
    try {
        if (service != null) {
            isServiceAPI = true;
        }
        validationResponseMap = validateOpenAPIDefinition(definitionUrl, definition, fileDetail, inlineDefinition, true, isServiceAPI);
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error occurred while validating API Definition", e, log);
    }
    OpenAPIDefinitionValidationResponseDTO validationResponseDTO = (OpenAPIDefinitionValidationResponseDTO) validationResponseMap.get(RestApiConstants.RETURN_DTO);
    APIDefinitionValidationResponse validationResponse = (APIDefinitionValidationResponse) validationResponseMap.get(RestApiConstants.RETURN_MODEL);
    if (!validationResponseDTO.isIsValid()) {
        ErrorDTO errorDTO = APIMappingUtil.getErrorDTOFromErrorListItems(validationResponseDTO.getErrors());
        throw RestApiUtil.buildBadRequestException(errorDTO);
    }
    // Only HTTP or WEBHOOK type APIs should be allowed
    if (!(APIDTO.TypeEnum.HTTP.equals(apiDTOFromProperties.getType()) || APIDTO.TypeEnum.WEBHOOK.equals(apiDTOFromProperties.getType()))) {
        throw RestApiUtil.buildBadRequestException("The API's type is not supported when importing an OpenAPI definition");
    }
    // Import the API and Definition
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    if (isServiceAPI) {
        apiDTOFromProperties.setType(PublisherCommonUtils.getAPIType(service.getDefinitionType(), null));
    }
    API apiToAdd = PublisherCommonUtils.prepareToCreateAPIByDTO(apiDTOFromProperties, apiProvider, RestApiCommonUtil.getLoggedInUsername(), organization);
    if (isServiceAPI) {
        apiToAdd.setServiceInfo("key", service.getKey());
        apiToAdd.setServiceInfo("md5", service.getMd5());
        apiToAdd.setEndpointConfig(PublisherCommonUtils.constructEndpointConfigForService(service.getServiceUrl(), null));
    }
    boolean syncOperations = apiDTOFromProperties.getOperations().size() > 0;
    // Rearrange paths according to the API payload and save the OpenAPI definition
    APIDefinition apiDefinition = validationResponse.getParser();
    SwaggerData swaggerData;
    String definitionToAdd = validationResponse.getJsonContent();
    if (syncOperations) {
        PublisherCommonUtils.validateScopes(apiToAdd);
        swaggerData = new SwaggerData(apiToAdd);
        definitionToAdd = apiDefinition.populateCustomManagementInfo(definitionToAdd, swaggerData);
    }
    definitionToAdd = OASParserUtil.preProcess(definitionToAdd);
    Set<URITemplate> uriTemplates = apiDefinition.getURITemplates(definitionToAdd);
    Set<Scope> scopes = apiDefinition.getScopes(definitionToAdd);
    apiToAdd.setUriTemplates(uriTemplates);
    apiToAdd.setScopes(scopes);
    // Set extensions from API definition to API object
    apiToAdd = OASParserUtil.setExtensionsToAPI(definitionToAdd, apiToAdd);
    if (!syncOperations) {
        PublisherCommonUtils.validateScopes(apiToAdd);
        swaggerData = new SwaggerData(apiToAdd);
        definitionToAdd = apiDefinition.populateCustomManagementInfo(validationResponse.getJsonContent(), swaggerData);
    }
    // adding the API and definition
    apiToAdd.setSwaggerDefinition(definitionToAdd);
    API addedAPI = apiProvider.addAPI(apiToAdd);
    // apiProvider.saveSwaggerDefinition(apiToAdd, definitionToAdd);
    // retrieving the added API for returning as the response
    // this would provide the updated templates
    addedAPI = apiProvider.getAPIbyUUID(addedAPI.getUuid(), organization);
    return APIMappingUtil.fromAPItoDTO(addedAPI);
}
Also used : SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Scope(org.wso2.carbon.apimgt.api.model.Scope) OpenAPIDefinitionValidationResponseDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.OpenAPIDefinitionValidationResponseDTO) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap)

Example 57 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method getAPISubscriptionPolicies.

@Override
public Response getAPISubscriptionPolicies(String apiId, String ifNoneMatch, String xWSO2Tenant, MessageContext messageContext) throws APIManagementException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    String organization = RestApiUtil.getValidatedOrganization(messageContext);
    APIDTO apiInfo = getAPIByID(apiId, apiProvider, organization);
    List<Tier> availableThrottlingPolicyList = new ThrottlingPoliciesApiServiceImpl().getThrottlingPolicyList(ThrottlingPolicyDTO.PolicyLevelEnum.SUBSCRIPTION.toString(), true);
    if (apiInfo != null) {
        List<String> apiPolicies = apiInfo.getPolicies();
        if (apiPolicies != null && !apiPolicies.isEmpty()) {
            List<Tier> apiThrottlingPolicies = new ArrayList<>();
            for (Tier tier : availableThrottlingPolicyList) {
                if (apiPolicies.contains(tier.getName())) {
                    apiThrottlingPolicies.add(tier);
                }
            }
            return Response.ok().entity(apiThrottlingPolicies).build();
        }
    }
    return null;
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) Tier(org.wso2.carbon.apimgt.api.model.Tier) ArrayList(java.util.ArrayList) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 58 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method restoreAPIRevision.

/**
 * Restore a revision to the working copy of the API
 *
 * @param apiId          UUID of the API
 * @param revisionId  Revision ID of the API
 * @param messageContext message context object
 * @return response with 200 status code
 */
@Override
public Response restoreAPIRevision(String apiId, String revisionId, MessageContext messageContext) throws APIManagementException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    String organization = RestApiUtil.getValidatedOrganization(messageContext);
    // validate if api exists
    APIInfo apiInfo = validateAPIExistence(apiId);
    // validate API update operation permitted based on the LC state
    validateAPIOperationsPerLC(apiInfo.getStatus().toString());
    apiProvider.restoreAPIRevision(apiId, revisionId, organization);
    APIDTO apiToReturn = getAPIByID(apiId, apiProvider, organization);
    Response.Status status = Response.Status.CREATED;
    return Response.status(status).entity(apiToReturn).build();
}
Also used : HttpResponse(org.apache.http.HttpResponse) WSDLValidationResponse(org.wso2.carbon.apimgt.impl.wsdl.model.WSDLValidationResponse) Response(javax.ws.rs.core.Response) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse) APIStateChangeResponse(org.wso2.carbon.apimgt.api.model.APIStateChangeResponse) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) APIInfo(org.wso2.carbon.apimgt.api.model.APIInfo) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 59 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method importOpenAPIDefinition.

/**
 * Importing an OpenAPI definition and create an API
 *
 * @param fileInputStream InputStream for the provided file
 * @param fileDetail File meta-data
 * @param url URL of the OpenAPI definition
 * @param additionalProperties API object (json) including additional properties like name, version, context
 * @param inlineApiDefinition Swagger API definition String
 * @param messageContext CXF message context
 * @return API Import using OpenAPI definition response
 * @throws APIManagementException when error occurs while importing the OpenAPI definition
 */
@Override
public Response importOpenAPIDefinition(InputStream fileInputStream, Attachment fileDetail, String url, String additionalProperties, String inlineApiDefinition, MessageContext messageContext) throws APIManagementException {
    // validate 'additionalProperties' json
    if (StringUtils.isBlank(additionalProperties)) {
        RestApiUtil.handleBadRequest("'additionalProperties' is required and should not be null", log);
    }
    // Convert the 'additionalProperties' json into an APIDTO object
    ObjectMapper objectMapper = new ObjectMapper();
    APIDTO apiDTOFromProperties;
    try {
        apiDTOFromProperties = objectMapper.readValue(additionalProperties, APIDTO.class);
    } catch (IOException e) {
        throw RestApiUtil.buildBadRequestException("Error while parsing 'additionalProperties'", e);
    }
    // validate sandbox and production endpoints
    if (!PublisherCommonUtils.validateEndpoints(apiDTOFromProperties)) {
        throw new APIManagementException("Invalid/Malformed endpoint URL(s) detected", ExceptionCodes.INVALID_ENDPOINT_URL);
    }
    try {
        LinkedHashMap endpointConfig = (LinkedHashMap) apiDTOFromProperties.getEndpointConfig();
        // OAuth 2.0 backend protection: API Key and API Secret encryption
        PublisherCommonUtils.encryptEndpointSecurityOAuthCredentials(endpointConfig, CryptoUtil.getDefaultCryptoUtil(), StringUtils.EMPTY, StringUtils.EMPTY, apiDTOFromProperties);
        // Import the API and Definition
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIDTO createdApiDTO = importOpenAPIDefinition(fileInputStream, url, inlineApiDefinition, apiDTOFromProperties, fileDetail, null, organization);
        if (createdApiDTO != null) {
            // This URI used to set the location header of the POST response
            URI createdApiUri = new URI(RestApiConstants.RESOURCE_PATH_APIS + "/" + createdApiDTO.getId());
            return Response.created(createdApiUri).entity(createdApiDTO).build();
        }
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving API location : " + apiDTOFromProperties.getProvider() + "-" + apiDTOFromProperties.getName() + "-" + apiDTOFromProperties.getVersion();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (CryptoException e) {
        String errorMessage = "Error while encrypting the secret key of API : " + apiDTOFromProperties.getProvider() + "-" + apiDTOFromProperties.getName() + "-" + apiDTOFromProperties.getVersion();
        throw new APIManagementException(errorMessage, e);
    }
    return null;
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) CryptoException(org.wso2.carbon.core.util.CryptoException) URI(java.net.URI) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) LinkedHashMap(java.util.LinkedHashMap)

Example 60 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method importGraphQLSchema.

/**
 * Import a GraphQL Schema
 * @param type APIType
 * @param fileInputStream input file
 * @param fileDetail file Detail
 * @param additionalProperties api object as string format
 * @param ifMatch If--Match header value
 * @param messageContext messageContext
 * @return Response with GraphQL API
 */
@Override
public Response importGraphQLSchema(String ifMatch, String type, InputStream fileInputStream, Attachment fileDetail, String additionalProperties, MessageContext messageContext) {
    APIDTO additionalPropertiesAPI = null;
    String schema = "";
    try {
        if (fileInputStream == null || StringUtils.isBlank(additionalProperties)) {
            String errorMessage = "GraphQL schema and api details cannot be empty.";
            RestApiUtil.handleBadRequest(errorMessage, log);
        } else {
            schema = IOUtils.toString(fileInputStream, RestApiConstants.CHARSET);
        }
        if (!StringUtils.isBlank(additionalProperties) && !StringUtils.isBlank(schema)) {
            if (log.isDebugEnabled()) {
                log.debug("Deseriallizing additionalProperties: " + additionalProperties + "/n" + "importing schema: " + schema);
            }
        }
        additionalPropertiesAPI = new ObjectMapper().readValue(additionalProperties, APIDTO.class);
        additionalPropertiesAPI.setType(APIDTO.TypeEnum.GRAPHQL);
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        API apiToAdd = PublisherCommonUtils.prepareToCreateAPIByDTO(additionalPropertiesAPI, apiProvider, RestApiCommonUtil.getLoggedInUsername(), organization);
        // Save swagger definition of graphQL
        APIDefinition parser = new OAS3Parser();
        SwaggerData swaggerData = new SwaggerData(apiToAdd);
        String apiDefinition = parser.generateAPIDefinition(swaggerData);
        apiToAdd.setSwaggerDefinition(apiDefinition);
        // adding the api
        API createdApi = apiProvider.addAPI(apiToAdd);
        apiProvider.saveGraphqlSchemaDefinition(createdApi.getUuid(), schema, organization);
        APIDTO createdApiDTO = APIMappingUtil.fromAPItoDTO(createdApi);
        // This URI used to set the location header of the POST response
        URI createdApiUri = new URI(RestApiConstants.RESOURCE_PATH_APIS + "/" + createdApiDTO.getId());
        return Response.created(createdApiUri).entity(createdApiDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while adding new API : " + additionalPropertiesAPI.getProvider() + "-" + additionalPropertiesAPI.getName() + "-" + additionalPropertiesAPI.getVersion() + " - " + e.getMessage();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving API location : " + additionalPropertiesAPI.getProvider() + "-" + additionalPropertiesAPI.getName() + "-" + additionalPropertiesAPI.getVersion();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (IOException e) {
        String errorMessage = "Error while retrieving content from file : " + additionalPropertiesAPI.getProvider() + "-" + additionalPropertiesAPI.getName() + "-" + additionalPropertiesAPI.getVersion();
        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) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) OAS3Parser(org.wso2.carbon.apimgt.impl.definitions.OAS3Parser) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO)29 HashMap (java.util.HashMap)28 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)27 ArrayList (java.util.ArrayList)25 API (org.wso2.carbon.apimgt.api.model.API)25 IOException (java.io.IOException)18 API (org.wso2.carbon.apimgt.core.models.API)17 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)15 APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDTO)15 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)14 File (java.io.File)12 Response (javax.ws.rs.core.Response)12 Map (java.util.Map)11 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)11 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)11 Test (org.junit.Test)10 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)10 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)10 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)10 GeneralWorkflowResponse (org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse)10