Search in sources :

Example 11 with Extension

use of io.swagger.v3.oas.annotations.extensions.Extension in project carbon-apimgt by wso2.

the class OAS3Parser method processDisableSecurityExtension.

/**
 * This method will extractX-WSO2-disable-security extension provided in API level
 * by mgw and inject that extension to all resources in OAS file
 *
 * @param swaggerContent String
 * @return String
 * @throws APIManagementException
 */
@Override
public String processDisableSecurityExtension(String swaggerContent) throws APIManagementException {
    OpenAPI openAPI = getOpenAPI(swaggerContent);
    Map<String, Object> apiExtensions = openAPI.getExtensions();
    if (apiExtensions == null) {
        return swaggerContent;
    }
    // Check Disable Security is enabled in API level
    boolean apiLevelDisableSecurity = OASParserUtil.getDisableSecurity(apiExtensions);
    Paths paths = openAPI.getPaths();
    for (String pathKey : paths.keySet()) {
        Map<PathItem.HttpMethod, Operation> operationsMap = paths.get(pathKey).readOperationsMap();
        for (Map.Entry<PathItem.HttpMethod, Operation> entry : operationsMap.entrySet()) {
            Operation operation = entry.getValue();
            Map<String, Object> resourceExtensions = operation.getExtensions();
            boolean extensionsAreEmpty = false;
            if (apiLevelDisableSecurity) {
                if (resourceExtensions == null) {
                    resourceExtensions = new HashMap<>();
                    extensionsAreEmpty = true;
                }
                resourceExtensions.put(APIConstants.SWAGGER_X_AUTH_TYPE, "None");
                if (extensionsAreEmpty) {
                    operation.setExtensions(resourceExtensions);
                }
            } else if (resourceExtensions != null && resourceExtensions.containsKey(APIConstants.X_WSO2_DISABLE_SECURITY)) {
                // Check Disable Security is enabled in resource level
                boolean resourceLevelDisableSecurity = Boolean.parseBoolean(String.valueOf(resourceExtensions.get(APIConstants.X_WSO2_DISABLE_SECURITY)));
                if (resourceLevelDisableSecurity) {
                    resourceExtensions.put(APIConstants.SWAGGER_X_AUTH_TYPE, "None");
                }
            }
        }
    }
    return Json.pretty(openAPI);
}
Also used : JSONObject(org.json.simple.JSONObject) Paths(io.swagger.v3.oas.models.Paths) Operation(io.swagger.v3.oas.models.Operation) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HttpMethod(io.swagger.models.HttpMethod)

Example 12 with Extension

use of io.swagger.v3.oas.annotations.extensions.Extension in project carbon-apimgt by wso2.

the class OAS3Parser method injectMgwThrottlingExtensionsToDefault.

/**
 * This method returns openAPI definition which replaced X-WSO2-throttling-tier extension comes from
 * mgw with X-throttling-tier extensions in openAPI file(openAPI version 3)
 *
 * @param swaggerContent String
 * @return String
 * @throws APIManagementException
 */
@Override
public String injectMgwThrottlingExtensionsToDefault(String swaggerContent) throws APIManagementException {
    OpenAPI openAPI = getOpenAPI(swaggerContent);
    Paths paths = openAPI.getPaths();
    for (String pathKey : paths.keySet()) {
        Map<PathItem.HttpMethod, Operation> operationsMap = paths.get(pathKey).readOperationsMap();
        for (Map.Entry<PathItem.HttpMethod, Operation> entry : operationsMap.entrySet()) {
            Operation operation = entry.getValue();
            Map<String, Object> extensions = operation.getExtensions();
            if (extensions != null && extensions.containsKey(APIConstants.X_WSO2_THROTTLING_TIER)) {
                Object tier = extensions.get(APIConstants.X_WSO2_THROTTLING_TIER);
                extensions.remove(APIConstants.X_WSO2_THROTTLING_TIER);
                extensions.put(APIConstants.SWAGGER_X_THROTTLING_TIER, tier);
            }
        }
    }
    return Json.pretty(openAPI);
}
Also used : JSONObject(org.json.simple.JSONObject) Paths(io.swagger.v3.oas.models.Paths) Operation(io.swagger.v3.oas.models.Operation) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HttpMethod(io.swagger.models.HttpMethod)

Example 13 with Extension

use of io.swagger.v3.oas.annotations.extensions.Extension in project swagger-parser by swagger-api.

the class SwaggerConverter method convert.

public SwaggerParseResult convert(SwaggerDeserializationResult parse) {
    if (parse == null) {
        return null;
    }
    SwaggerParseResult output = new SwaggerParseResult().messages(parse.getMessages());
    if (parse.getSwagger() == null) {
        return output;
    }
    OpenAPI openAPI = new OpenAPI();
    SwaggerInventory inventory = new SwaggerInventory().process(parse.getSwagger());
    Swagger swagger = parse.getSwagger();
    if (swagger.getVendorExtensions() != null) {
        openAPI.setExtensions(convert(swagger.getVendorExtensions()));
    }
    // Set extension to retain original version of OAS document.
    openAPI.addExtension("x-original-swagger-version", swagger.getSwagger());
    if (swagger.getExternalDocs() != null) {
        openAPI.setExternalDocs(convert(swagger.getExternalDocs()));
    }
    if (swagger.getInfo() != null) {
        openAPI.setInfo(convert(swagger.getInfo()));
    }
    openAPI.setServers(convert(swagger.getSchemes(), swagger.getHost(), swagger.getBasePath()));
    if (swagger.getTags() != null) {
        openAPI.setTags(convertTags(swagger.getTags()));
    }
    if (swagger.getConsumes() != null) {
        this.globalConsumes.addAll(swagger.getConsumes());
    }
    if (swagger.getProduces() != null) {
        this.globalProduces.addAll(swagger.getProduces());
    }
    if (swagger.getSecurity() != null && swagger.getSecurity().size() > 0) {
        openAPI.setSecurity(convertSecurityRequirements(swagger.getSecurity()));
    }
    List<Model> models = inventory.getModels();
    // TODO until we have the example object working correctly in v3 pojos...
    for (Model model : models) {
        if (model instanceof RefModel) {
            RefModel ref = (RefModel) model;
            if (ref.get$ref().indexOf("#/definitions") == 0) {
                String updatedRef = "#/components/schemas" + ref.get$ref().substring("#/definitions".length());
                ref.set$ref(updatedRef);
            }
        }
    }
    for (Property property : inventory.getProperties()) {
        if (property instanceof RefProperty) {
            RefProperty ref = (RefProperty) property;
            if (ref.get$ref().indexOf("#/definitions") == 0) {
                String updatedRef = "#/components/schemas" + ref.get$ref().substring("#/definitions".length());
                ref.set$ref(updatedRef);
            }
        }
        if (property instanceof ComposedProperty) {
            ComposedProperty comprop = (ComposedProperty) property;
            if (comprop.getAllOf() != null) {
                for (Property item : comprop.getAllOf()) {
                    if (item instanceof RefProperty) {
                        RefProperty ref = (RefProperty) item;
                        if (ref.get$ref().indexOf("#/definitions") == 0) {
                            String updatedRef = "#/components/schemas" + ref.get$ref().substring("#/definitions".length());
                            ref.set$ref(updatedRef);
                        }
                    }
                }
            }
        }
    }
    if (swagger.getParameters() != null) {
        globalV2Parameters.putAll(swagger.getParameters());
        swagger.getParameters().forEach((k, v) -> {
            if ("body".equals(v.getIn())) {
                components.addRequestBodies(k, convertParameterToRequestBody(v));
            } else if ("formData".equals(v.getIn())) {
                // formData_ is added not to overwrite existing schemas
                components.addSchemas("formData_" + k, convertFormDataToSchema(v));
            } else {
                components.addParameters(k, convert(v));
            }
        });
    }
    Paths v3Paths = new Paths();
    Map<String, Path> pathMap = Optional.ofNullable(swagger.getPaths()).orElse(new HashMap<>());
    for (String pathname : pathMap.keySet()) {
        io.swagger.models.Path v2Path = swagger.getPath(pathname);
        PathItem v3Path = convert(v2Path);
        v3Paths.put(pathname, v3Path);
    }
    openAPI.setPaths(v3Paths);
    if (swagger.getResponses() != null) {
        swagger.getResponses().forEach((k, v) -> components.addResponses(k, convert(v)));
    }
    if (swagger.getDefinitions() != null) {
        for (String key : swagger.getDefinitions().keySet()) {
            Model model = swagger.getDefinitions().get(key);
            Schema schema = convert(model);
            components.addSchemas(key, schema);
        }
    }
    if (swagger.getSecurityDefinitions() != null) {
        swagger.getSecurityDefinitions().forEach((k, v) -> components.addSecuritySchemes(k, convert(v)));
    }
    openAPI.setComponents(components);
    output.setOpenAPI(openAPI);
    return output;
}
Also used : RefPath(io.swagger.models.RefPath) Path(io.swagger.models.Path) RefModel(io.swagger.models.RefModel) ComposedSchema(io.swagger.v3.oas.models.media.ComposedSchema) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) Schema(io.swagger.v3.oas.models.media.Schema) FileSchema(io.swagger.v3.oas.models.media.FileSchema) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) PathItem(io.swagger.v3.oas.models.PathItem) Path(io.swagger.models.Path) Swagger(io.swagger.models.Swagger) Model(io.swagger.models.Model) RefModel(io.swagger.models.RefModel) ComposedModel(io.swagger.models.ComposedModel) ArrayModel(io.swagger.models.ArrayModel) Paths(io.swagger.v3.oas.models.Paths) OpenAPI(io.swagger.v3.oas.models.OpenAPI)

Example 14 with Extension

use of io.swagger.v3.oas.annotations.extensions.Extension in project swagger-parser by swagger-api.

the class V2ConverterTest method testIssue15.

@Test(description = "Convert extensions everywhere applicable #15")
public void testIssue15() throws Exception {
    OpenAPI oas = getConvertedOpenAPIFromJsonFile(ISSUE_15_JSON);
    assertNotNull(oas);
    Info info = oas.getInfo();
    assertNotNull(info.getExtensions().get("x-apis-json"));
    assertNotNull(info.getLicense().getExtensions().get("x-notes"));
    assertNotNull(oas.getExternalDocs().getExtensions().get("x-docs-extension"));
    assertNotNull(oas.getTags().get(0).getExtensions().get("x-tag-extension"));
    assertNotNull(oas.getTags().get(0).getExternalDocs().getExtensions().get("x-tag-docs-extension"));
    PathItem pathItem = oas.getPaths().get("/something");
    assertNotNull(pathItem.getExtensions().get("x-path-item-extension"));
    Operation get = pathItem.getGet();
    assertNotNull(get.getExtensions().get("x-version"));
    assertNotNull(get.getExternalDocs().getExtensions().get("x-operation-docs-extension"));
    assertNotNull(get.getResponses().get("200").getExtensions().get("x-response-extension"));
    ArraySchema schema = (ArraySchema) get.getParameters().get(0).getSchema();
    assertNull(schema.getItems().getExtensions().get(X_EXAMPLE));
    Map<String, SecurityScheme> securitySchemes = oas.getComponents().getSecuritySchemes();
    assertNotNull(securitySchemes);
    assertNotNull(securitySchemes.get("OAuth2Implicit").getExtensions().get("x-auth-extension"));
}
Also used : PathItem(io.swagger.v3.oas.models.PathItem) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) Operation(io.swagger.v3.oas.models.Operation) Info(io.swagger.v3.oas.models.info.Info) OpenAPI(io.swagger.v3.oas.models.OpenAPI) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme) Test(org.testng.annotations.Test)

Example 15 with Extension

use of io.swagger.v3.oas.annotations.extensions.Extension in project swagger-parser by swagger-api.

the class V2ConverterTest method testPreserveBodyParameterName.

@Test(description = "OpenAPI v2 Converter: Ensure body name is preserved in x-codegen-request-body-name extension")
public void testPreserveBodyParameterName() throws Exception {
    final OpenAPI oas = getConvertedOpenAPIFromJsonFile(ISSUE_762_JSON);
    assertNotNull(oas);
    assertEquals(oas.getPaths().get("/").getPut().getExtensions().get("x-codegen-request-body-name"), "pet");
}
Also used : OpenAPI(io.swagger.v3.oas.models.OpenAPI) Test(org.testng.annotations.Test)

Aggregations

OpenAPI (io.swagger.v3.oas.models.OpenAPI)17 Test (org.testng.annotations.Test)11 SwaggerParseResult (io.swagger.v3.parser.core.models.SwaggerParseResult)9 Operation (io.swagger.v3.oas.models.Operation)8 HashMap (java.util.HashMap)8 LinkedHashMap (java.util.LinkedHashMap)8 Map (java.util.Map)8 PathItem (io.swagger.v3.oas.models.PathItem)7 Schema (io.swagger.v3.oas.models.media.Schema)6 Paths (io.swagger.v3.oas.models.Paths)5 ArrayList (java.util.ArrayList)5 JsonNode (com.fasterxml.jackson.databind.JsonNode)4 HttpMethod (io.swagger.models.HttpMethod)4 Components (io.swagger.v3.oas.models.Components)4 ArraySchema (io.swagger.v3.oas.models.media.ArraySchema)4 JSONObject (org.json.simple.JSONObject)4 Info (io.swagger.v3.oas.models.info.Info)3 ComposedSchema (io.swagger.v3.oas.models.media.ComposedSchema)3 IntegerSchema (io.swagger.v3.oas.models.media.IntegerSchema)3 MediaType (io.swagger.v3.oas.models.media.MediaType)3