Search in sources :

Example 76 with APIDefinition

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

the class OASParserUtil method preProcess.

/**
 * Preprocessing of scopes schemes to support multiple schemes other than 'default' type
 * This method will change the given definition
 *
 * @param swaggerContent String
 * @return swagger definition as String
 */
public static String preProcess(String swaggerContent) throws APIManagementException {
    // Load required properties from swagger to the API
    APIDefinition apiDefinition = getOASParser(swaggerContent);
    // Inject and map mgw throttling extensions to default type
    swaggerContent = apiDefinition.injectMgwThrottlingExtensionsToDefault(swaggerContent);
    // Process mgw disable security extension
    swaggerContent = apiDefinition.processDisableSecurityExtension(swaggerContent);
    return apiDefinition.processOtherSchemeScopes(swaggerContent);
}
Also used : APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition)

Example 77 with APIDefinition

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

the class OAS2Parser method setExtensionsToAPI.

/**
 * This method returns api that is attached with api extensions related to micro-gw
 *
 * @param apiDefinition String
 * @param api           API
 * @return API
 */
@Override
public API setExtensionsToAPI(String apiDefinition, API api) throws APIManagementException {
    Swagger swagger = getSwagger(apiDefinition);
    Map<String, Object> extensions = swagger.getVendorExtensions();
    if (extensions == null) {
        return api;
    }
    // Setup Custom auth header for API
    String authHeader = OASParserUtil.getAuthorizationHeaderFromSwagger(extensions);
    if (StringUtils.isNotBlank(authHeader)) {
        api.setAuthorizationHeader(authHeader);
    }
    // Setup application Security
    List<String> applicationSecurity = OASParserUtil.getApplicationSecurityTypes(extensions);
    Boolean isOptional = OASParserUtil.getAppSecurityStateFromSwagger(extensions);
    if (!applicationSecurity.isEmpty()) {
        String securityList = api.getApiSecurity();
        securityList = securityList == null ? "" : securityList;
        for (String securityType : applicationSecurity) {
            if (APIConstants.DEFAULT_API_SECURITY_OAUTH2.equals(securityType) && !securityList.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2)) {
                securityList = securityList + "," + APIConstants.DEFAULT_API_SECURITY_OAUTH2;
            }
            if (APIConstants.API_SECURITY_BASIC_AUTH.equals(securityType) && !securityList.contains(APIConstants.API_SECURITY_BASIC_AUTH)) {
                securityList = securityList + "," + APIConstants.API_SECURITY_BASIC_AUTH;
            }
            if (APIConstants.API_SECURITY_API_KEY.equals(securityType) && !securityList.contains(APIConstants.API_SECURITY_API_KEY)) {
                securityList = securityList + "," + APIConstants.API_SECURITY_API_KEY;
            }
        }
        if (!(isOptional || securityList.contains(APIConstants.MANDATORY))) {
            securityList = securityList + "," + APIConstants.MANDATORY;
        }
        api.setApiSecurity(securityList);
    }
    // Setup mutualSSL configuration
    String mutualSSL = OASParserUtil.getMutualSSLEnabledFromSwagger(extensions);
    if (StringUtils.isNotBlank(mutualSSL)) {
        String securityList = api.getApiSecurity();
        if (StringUtils.isBlank(securityList)) {
            securityList = APIConstants.DEFAULT_API_SECURITY_OAUTH2;
        }
        if (APIConstants.OPTIONAL.equals(mutualSSL) && !securityList.contains(APIConstants.API_SECURITY_MUTUAL_SSL)) {
            securityList = securityList + "," + APIConstants.API_SECURITY_MUTUAL_SSL;
        } else if (APIConstants.MANDATORY.equals(mutualSSL) && !securityList.contains(APIConstants.API_SECURITY_MUTUAL_SSL_MANDATORY)) {
            securityList = securityList + "," + APIConstants.API_SECURITY_MUTUAL_SSL + "," + APIConstants.API_SECURITY_MUTUAL_SSL_MANDATORY;
        }
        api.setApiSecurity(securityList);
    }
    // Setup CORSConfigurations
    CORSConfiguration corsConfiguration = OASParserUtil.getCorsConfigFromSwagger(extensions);
    if (corsConfiguration != null) {
        api.setCorsConfiguration(corsConfiguration);
    }
    // Setup Response cache enabling
    boolean responseCacheEnable = OASParserUtil.getResponseCacheFromSwagger(extensions);
    if (responseCacheEnable) {
        api.setResponseCache(APIConstants.ENABLED);
    }
    // Setup cache timeOut
    int cacheTimeOut = OASParserUtil.getCacheTimeOutFromSwagger(extensions);
    if (cacheTimeOut != 0) {
        api.setCacheTimeout(cacheTimeOut);
    }
    // Setup Transports
    String transports = OASParserUtil.getTransportsFromSwagger(extensions);
    if (StringUtils.isNotBlank(transports)) {
        api.setTransports(transports);
    }
    // Setup Throttlingtiers
    String throttleTier = OASParserUtil.getThrottleTierFromSwagger(extensions);
    if (StringUtils.isNotBlank(throttleTier)) {
        api.setApiLevelPolicy(throttleTier);
    }
    return api;
}
Also used : CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) Swagger(io.swagger.models.Swagger)

Example 78 with APIDefinition

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

the class AsyncApiParser method getURITemplates.

public Set<URITemplate> getURITemplates(String apiDefinition, boolean includePublish) throws APIManagementException {
    Set<URITemplate> uriTemplates = new HashSet<>();
    Set<Scope> scopes = getScopes(apiDefinition);
    Aai20Document document = (Aai20Document) Library.readDocumentFromJSONString(apiDefinition);
    if (document.channels != null && document.channels.size() > 0) {
        for (Map.Entry<String, AaiChannelItem> entry : document.channels.entrySet()) {
            Aai20ChannelItem channel = (Aai20ChannelItem) entry.getValue();
            if (includePublish && channel.publish != null) {
                uriTemplates.add(buildURITemplate(entry.getKey(), APIConstants.HTTP_VERB_PUBLISH, (Aai20Operation) channel.publish, scopes, channel));
            }
            if (channel.subscribe != null) {
                uriTemplates.add(buildURITemplate(entry.getKey(), APIConstants.HTTP_VERB_SUBSCRIBE, (Aai20Operation) channel.subscribe, scopes, channel));
            }
        }
    }
    return uriTemplates;
}
Also used : AaiChannelItem(io.apicurio.datamodels.asyncapi.models.AaiChannelItem) Scope(org.wso2.carbon.apimgt.api.model.Scope) Aai20Document(io.apicurio.datamodels.asyncapi.v2.models.Aai20Document) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Aai20ChannelItem(io.apicurio.datamodels.asyncapi.v2.models.Aai20ChannelItem) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) Aai20Operation(io.apicurio.datamodels.asyncapi.v2.models.Aai20Operation)

Example 79 with APIDefinition

use of org.wso2.carbon.apimgt.api.APIDefinition 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 80 with APIDefinition

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

the class ApisApiServiceImpl method validateOpenAPIDefinition.

/**
 * Validate the provided OpenAPI definition (via file or url) and return a Map with the validation response
 * information.
 *
 * @param url OpenAPI definition url
 * @param fileInputStream file as input stream
 * @param apiDefinition Swagger API definition String
 * @param returnContent whether to return the content of the definition in the response DTO
 * @return Map with the validation response information. A value with key 'dto' will have the response DTO
 *  of type OpenAPIDefinitionValidationResponseDTO for the REST API. A value with key 'model' will have the
 *  validation response of type APIDefinitionValidationResponse coming from the impl level.
 */
private Map validateOpenAPIDefinition(String url, InputStream fileInputStream, Attachment fileDetail, String apiDefinition, Boolean returnContent, Boolean isServiceAPI) throws APIManagementException {
    // validate inputs
    handleInvalidParams(fileInputStream, fileDetail, url, apiDefinition, isServiceAPI);
    OpenAPIDefinitionValidationResponseDTO responseDTO;
    APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
    if (url != null) {
        validationResponse = OASParserUtil.validateAPIDefinitionByURL(url, returnContent);
    } else if (fileInputStream != null) {
        try {
            if (fileDetail != null) {
                String filename = fileDetail.getContentDisposition().getFilename();
                if (filename.endsWith(".zip")) {
                    validationResponse = OASParserUtil.extractAndValidateOpenAPIArchive(fileInputStream, returnContent);
                } else {
                    String openAPIContent = IOUtils.toString(fileInputStream, RestApiConstants.CHARSET);
                    validationResponse = OASParserUtil.validateAPIDefinition(openAPIContent, returnContent);
                }
            } else {
                String openAPIContent = IOUtils.toString(fileInputStream, RestApiConstants.CHARSET);
                validationResponse = OASParserUtil.validateAPIDefinition(openAPIContent, returnContent);
            }
        } catch (IOException e) {
            RestApiUtil.handleInternalServerError("Error while reading file content", e, log);
        }
    } else if (apiDefinition != null) {
        validationResponse = OASParserUtil.validateAPIDefinition(apiDefinition, returnContent);
    }
    responseDTO = APIMappingUtil.getOpenAPIDefinitionValidationResponseFromModel(validationResponse, returnContent);
    Map response = new HashMap();
    response.put(RestApiConstants.RETURN_MODEL, validationResponse);
    response.put(RestApiConstants.RETURN_DTO, responseDTO);
    return response;
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) OpenAPIDefinitionValidationResponseDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.OpenAPIDefinitionValidationResponseDTO) IOException(java.io.IOException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)32 HashMap (java.util.HashMap)30 APIDefinition (org.wso2.carbon.apimgt.api.APIDefinition)30 API (org.wso2.carbon.apimgt.core.models.API)30 CompositeAPI (org.wso2.carbon.apimgt.core.models.CompositeAPI)25 ArrayList (java.util.ArrayList)23 API (org.wso2.carbon.apimgt.api.model.API)20 Map (java.util.Map)19 IOException (java.io.IOException)18 Test (org.testng.annotations.Test)18 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)18 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)16 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)15 Scope (org.wso2.carbon.apimgt.api.model.Scope)15 HashSet (java.util.HashSet)13 APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)13 APIDefinitionValidationResponse (org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)12 SwaggerData (org.wso2.carbon.apimgt.api.model.SwaggerData)12 BusinessInformation (org.wso2.carbon.apimgt.core.models.BusinessInformation)12 CorsConfiguration (org.wso2.carbon.apimgt.core.models.CorsConfiguration)12