Search in sources :

Example 76 with PathItem

use of io.swagger.v3.oas.models.PathItem in project carbon-apimgt by wso2.

the class OAS3Parser method updateOperations.

/**
 * Update OAS operations for Store
 *
 * @param openAPI OpenAPI to be updated
 */
private void updateOperations(OpenAPI openAPI) {
    for (String pathKey : openAPI.getPaths().keySet()) {
        PathItem pathItem = openAPI.getPaths().get(pathKey);
        for (Map.Entry<PathItem.HttpMethod, Operation> entry : pathItem.readOperationsMap().entrySet()) {
            Operation operation = entry.getValue();
            Map<String, Object> extensions = operation.getExtensions();
            if (extensions != null) {
                // remove mediation extension
                if (extensions.containsKey(APIConstants.SWAGGER_X_MEDIATION_SCRIPT)) {
                    extensions.remove(APIConstants.SWAGGER_X_MEDIATION_SCRIPT);
                }
                // set x-scope value to security definition if it not there.
                if (extensions.containsKey(APIConstants.SWAGGER_X_WSO2_SCOPES)) {
                    String scope = (String) extensions.get(APIConstants.SWAGGER_X_WSO2_SCOPES);
                    List<SecurityRequirement> security = operation.getSecurity();
                    if (security == null) {
                        security = new ArrayList<>();
                        operation.setSecurity(security);
                    }
                    for (Map<String, List<String>> requirement : security) {
                        if (requirement.get(OPENAPI_SECURITY_SCHEMA_KEY) == null || !requirement.get(OPENAPI_SECURITY_SCHEMA_KEY).contains(scope)) {
                            requirement.put(OPENAPI_SECURITY_SCHEMA_KEY, Collections.singletonList(scope));
                        }
                    }
                }
            }
        }
    }
}
Also used : Operation(io.swagger.v3.oas.models.Operation) PathItem(io.swagger.v3.oas.models.PathItem) JSONObject(org.json.simple.JSONObject) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HttpMethod(io.swagger.models.HttpMethod) SecurityRequirement(io.swagger.v3.oas.models.security.SecurityRequirement)

Example 77 with PathItem

use of io.swagger.v3.oas.models.PathItem in project carbon-apimgt by wso2.

the class OAS3Parser method generateAPIDefinition.

/**
 * This method generates API definition using the given api's URI templates and the swagger.
 * It will alter the provided swagger definition based on the URI templates. For example: if there is a new
 * URI template which is not included in the swagger, it will be added to the swagger as a basic resource. Any
 * additional resources inside the swagger will be removed from the swagger. Changes to scopes, throtting policies,
 * on the resource will be updated on the swagger
 *
 * @param swaggerData api
 * @param openAPI     OpenAPI
 * @return API definition in string format
 * @throws APIManagementException if error occurred when generating API Definition
 */
private String generateAPIDefinition(SwaggerData swaggerData, OpenAPI openAPI) throws APIManagementException {
    Set<SwaggerData.Resource> copy = new HashSet<>(swaggerData.getResources());
    Iterator<Map.Entry<String, PathItem>> itr = openAPI.getPaths().entrySet().iterator();
    while (itr.hasNext()) {
        Map.Entry<String, PathItem> pathEntry = itr.next();
        String pathKey = pathEntry.getKey();
        PathItem pathItem = pathEntry.getValue();
        for (Map.Entry<PathItem.HttpMethod, Operation> entry : pathItem.readOperationsMap().entrySet()) {
            Operation operation = entry.getValue();
            boolean operationFound = false;
            for (SwaggerData.Resource resource : swaggerData.getResources()) {
                if (pathKey.equalsIgnoreCase(resource.getPath()) && entry.getKey().name().equalsIgnoreCase(resource.getVerb())) {
                    // update operations in definition
                    operationFound = true;
                    copy.remove(resource);
                    updateOperationManagedInfo(resource, operation);
                    break;
                }
            }
            // remove operation from definition
            if (!operationFound) {
                pathItem.operation(entry.getKey(), null);
            }
        }
        if (pathItem.readOperations().isEmpty()) {
            itr.remove();
        }
    }
    if (APIConstants.GRAPHQL_API.equals(swaggerData.getTransportType())) {
        modifyGraphQLSwagger(openAPI);
    } else {
        // adding new operations to the definition
        for (SwaggerData.Resource resource : copy) {
            addOrUpdatePathToSwagger(openAPI, resource);
        }
    }
    updateSwaggerSecurityDefinition(openAPI, swaggerData, OPENAPI_DEFAULT_AUTHORIZATION_URL);
    updateLegacyScopesFromSwagger(openAPI, swaggerData);
    openAPI.getInfo().setTitle(swaggerData.getTitle());
    if (StringUtils.isEmpty(openAPI.getInfo().getVersion())) {
        openAPI.getInfo().setVersion(swaggerData.getVersion());
    }
    if (!APIConstants.GRAPHQL_API.equals(swaggerData.getTransportType())) {
        preserveResourcePathOrderFromAPI(swaggerData, openAPI);
    }
    return Json.pretty(openAPI);
}
Also used : SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) Operation(io.swagger.v3.oas.models.Operation) PathItem(io.swagger.v3.oas.models.PathItem) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HttpMethod(io.swagger.models.HttpMethod) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 78 with PathItem

use of io.swagger.v3.oas.models.PathItem in project carbon-apimgt by wso2.

the class OASParserUtil method extractRelevantSourceData.

private static void extractRelevantSourceData(Map<API, List<APIProductResource>> apiToProductResourceMapping, SwaggerUpdateContext context) throws APIManagementException {
    // Extract Paths that exist in the destination swagger from the source swagger
    for (Map.Entry<API, List<APIProductResource>> mappingEntry : apiToProductResourceMapping.entrySet()) {
        String sourceSwagger = mappingEntry.getKey().getSwaggerDefinition();
        SwaggerVersion sourceSwaggerVersion = getSwaggerVersion(sourceSwagger);
        if (sourceSwaggerVersion == SwaggerVersion.OPEN_API) {
            OpenAPI srcOpenAPI = ((OAS3Parser) oas3Parser).getOpenAPI(sourceSwagger);
            Set<Components> aggregatedComponents = context.getAggregatedComponents();
            Components components = srcOpenAPI.getComponents();
            if (components != null) {
                aggregatedComponents.add(components);
            }
            Set<Scope> allScopes = oas3Parser.getScopes(sourceSwagger);
            Paths srcPaths = srcOpenAPI.getPaths();
            List<APIProductResource> apiProductResources = mappingEntry.getValue();
            for (APIProductResource apiProductResource : apiProductResources) {
                URITemplate uriTemplate = apiProductResource.getUriTemplate();
                PathItem srcPathItem = srcPaths.get(uriTemplate.getUriTemplate());
                readPathsAndScopes(srcPathItem, uriTemplate, allScopes, context);
            }
        } else if (sourceSwaggerVersion == SwaggerVersion.SWAGGER) {
            Swagger srcSwagger = ((OAS2Parser) oas2Parser).getSwagger(sourceSwagger);
            Set<Components> aggregatedComponents = context.getAggregatedComponents();
            Components components = swaggerConverter.readContents(sourceSwagger, null, null).getOpenAPI().getComponents();
            if (components != null) {
                aggregatedComponents.add(components);
            }
            Set<Scope> allScopes = oas2Parser.getScopes(sourceSwagger);
            Map<String, Path> srcPaths = srcSwagger.getPaths();
            List<APIProductResource> apiProductResources = mappingEntry.getValue();
            for (APIProductResource apiProductResource : apiProductResources) {
                URITemplate uriTemplate = apiProductResource.getUriTemplate();
                Path srcPath = srcPaths.get(uriTemplate.getUriTemplate());
                readPathsAndScopes(swaggerConverter.convert(srcPath), uriTemplate, allScopes, context);
            }
        }
    }
}
Also used : RefPath(io.swagger.models.RefPath) Path(io.swagger.models.Path) Set(java.util.Set) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Components(io.swagger.v3.oas.models.Components) PathItem(io.swagger.v3.oas.models.PathItem) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) Swagger(io.swagger.models.Swagger) OpenAPI(io.swagger.v3.oas.models.OpenAPI) API(org.wso2.carbon.apimgt.api.model.API) List(java.util.List) ArrayList(java.util.ArrayList) Paths(io.swagger.v3.oas.models.Paths) Map(java.util.Map) HashMap(java.util.HashMap) OpenAPI(io.swagger.v3.oas.models.OpenAPI)

Example 79 with PathItem

use of io.swagger.v3.oas.models.PathItem in project carbon-apimgt by wso2.

the class OASParserUtil method readPathsAndScopes.

private static void readPathsAndScopes(PathItem srcPathItem, URITemplate uriTemplate, final Set<Scope> allScopes, SwaggerUpdateContext context) {
    Map<PathItem.HttpMethod, Operation> srcOperations = srcPathItem.readOperationsMap();
    PathItem.HttpMethod httpMethod = PathItem.HttpMethod.valueOf(uriTemplate.getHTTPVerb().toUpperCase());
    Operation srcOperation = srcOperations.get(httpMethod);
    Paths paths = context.getPaths();
    Set<Scope> aggregatedScopes = context.getAggregatedScopes();
    if (!paths.containsKey(uriTemplate.getUriTemplate())) {
        paths.put(uriTemplate.getUriTemplate(), new PathItem());
    }
    PathItem pathItem = paths.get(uriTemplate.getUriTemplate());
    pathItem.operation(httpMethod, srcOperation);
    readReferenceObjects(srcOperation, context);
    List<SecurityRequirement> srcOperationSecurity = srcOperation.getSecurity();
    if (srcOperationSecurity != null) {
        for (SecurityRequirement requirement : srcOperationSecurity) {
            List<String> scopes = requirement.get(OAS3Parser.OPENAPI_SECURITY_SCHEMA_KEY);
            if (scopes != null) {
                for (String scopeKey : scopes) {
                    for (Scope scope : allScopes) {
                        if (scope.getKey().equals(scopeKey)) {
                            aggregatedScopes.add(scope);
                        }
                    }
                }
            }
        }
    }
}
Also used : PathItem(io.swagger.v3.oas.models.PathItem) Scope(org.wso2.carbon.apimgt.api.model.Scope) Operation(io.swagger.v3.oas.models.Operation) Paths(io.swagger.v3.oas.models.Paths) SecurityRequirement(io.swagger.v3.oas.models.security.SecurityRequirement)

Example 80 with PathItem

use of io.swagger.v3.oas.models.PathItem in project carbon-apimgt by wso2.

the class OAS3Parser method getURITemplates.

/**
 * This method returns URI templates according to the given swagger file
 *
 * @param resourceConfigsJSON swaggerJSON
 * @return URI Templates
 * @throws APIManagementException
 */
@Override
public Set<URITemplate> getURITemplates(String resourceConfigsJSON) throws APIManagementException {
    OpenAPI openAPI = getOpenAPI(resourceConfigsJSON);
    Set<URITemplate> urlTemplates = new LinkedHashSet<>();
    Set<Scope> scopes = getScopes(resourceConfigsJSON);
    for (String pathKey : openAPI.getPaths().keySet()) {
        PathItem pathItem = openAPI.getPaths().get(pathKey);
        for (Map.Entry<PathItem.HttpMethod, Operation> entry : pathItem.readOperationsMap().entrySet()) {
            Operation operation = entry.getValue();
            URITemplate template = new URITemplate();
            if (APIConstants.SUPPORTED_METHODS.contains(entry.getKey().name().toLowerCase())) {
                template.setHTTPVerb(entry.getKey().name().toUpperCase());
                template.setHttpVerbs(entry.getKey().name().toUpperCase());
                template.setUriTemplate(pathKey);
                List<String> opScopes = getScopeOfOperations(OPENAPI_SECURITY_SCHEMA_KEY, operation);
                if (!opScopes.isEmpty()) {
                    if (opScopes.size() == 1) {
                        String firstScope = opScopes.get(0);
                        if (StringUtils.isNoneBlank(firstScope)) {
                            Scope scope = APIUtil.findScopeByKey(scopes, firstScope);
                            if (scope == null) {
                                throw new APIManagementException("Scope '" + firstScope + "' not found.");
                            }
                            template.setScope(scope);
                            template.setScopes(scope);
                        }
                    } else {
                        template = OASParserUtil.setScopesToTemplate(template, opScopes, scopes);
                    }
                } else if (!getScopeOfOperations("OAuth2Security", operation).isEmpty()) {
                    opScopes = getScopeOfOperations("OAuth2Security", operation);
                    if (opScopes.size() == 1) {
                        String firstScope = opScopes.get(0);
                        Scope scope = APIUtil.findScopeByKey(scopes, firstScope);
                        if (scope == null) {
                            throw new APIManagementException("Scope '" + firstScope + "' not found.");
                        }
                        template.setScope(scope);
                        template.setScopes(scope);
                    } else {
                        template = OASParserUtil.setScopesToTemplate(template, opScopes, scopes);
                    }
                }
                Map<String, Object> extensions = operation.getExtensions();
                if (extensions != null) {
                    if (extensions.containsKey(APIConstants.SWAGGER_X_AUTH_TYPE)) {
                        String scopeKey = (String) extensions.get(APIConstants.SWAGGER_X_AUTH_TYPE);
                        template.setAuthType(scopeKey);
                        template.setAuthTypes(scopeKey);
                    } else {
                        template.setAuthType("Any");
                        template.setAuthTypes("Any");
                    }
                    if (extensions.containsKey(APIConstants.SWAGGER_X_THROTTLING_TIER)) {
                        String throttlingTier = (String) extensions.get(APIConstants.SWAGGER_X_THROTTLING_TIER);
                        template.setThrottlingTier(throttlingTier);
                        template.setThrottlingTiers(throttlingTier);
                    }
                    if (extensions.containsKey(APIConstants.SWAGGER_X_MEDIATION_SCRIPT)) {
                        String mediationScript = (String) extensions.get(APIConstants.SWAGGER_X_MEDIATION_SCRIPT);
                        template.setMediationScript(mediationScript);
                        template.setMediationScripts(template.getHTTPVerb(), mediationScript);
                    }
                    if (extensions.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME)) {
                        template.setAmznResourceName((String) extensions.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME));
                    }
                    if (extensions.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)) {
                        template.setAmznResourceTimeout(((Number) extensions.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)).intValue());
                    }
                }
                urlTemplates.add(template);
            }
        }
    }
    return urlTemplates;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Operation(io.swagger.v3.oas.models.Operation) PathItem(io.swagger.v3.oas.models.PathItem) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HttpMethod(io.swagger.models.HttpMethod)

Aggregations

PathItem (io.swagger.v3.oas.models.PathItem)135 OpenAPI (io.swagger.v3.oas.models.OpenAPI)109 Operation (io.swagger.v3.oas.models.Operation)104 Test (org.testng.annotations.Test)92 Schema (io.swagger.v3.oas.models.media.Schema)57 ArraySchema (io.swagger.v3.oas.models.media.ArraySchema)50 IntegerSchema (io.swagger.v3.oas.models.media.IntegerSchema)45 StringSchema (io.swagger.v3.oas.models.media.StringSchema)44 ObjectSchema (io.swagger.v3.oas.models.media.ObjectSchema)42 ApiResponse (io.swagger.v3.oas.models.responses.ApiResponse)42 MediaType (io.swagger.v3.oas.models.media.MediaType)41 Content (io.swagger.v3.oas.models.media.Content)38 Paths (io.swagger.v3.oas.models.Paths)36 ApiResponses (io.swagger.v3.oas.models.responses.ApiResponses)35 Parameter (io.swagger.v3.oas.models.parameters.Parameter)29 Components (io.swagger.v3.oas.models.Components)26 SwaggerParseResult (io.swagger.v3.parser.core.models.SwaggerParseResult)25 RequestBody (io.swagger.v3.oas.models.parameters.RequestBody)24 Map (java.util.Map)22 HashMap (java.util.HashMap)20