Java Code Examples for io.swagger.v3.oas.models.OpenAPI#getExtensions()

The following examples show how to use io.swagger.v3.oas.models.OpenAPI#getExtensions() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OpenAPICodegenUtils.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
/**
 * Get http, https and mutualSSL from API Definition x-wso2-transport and x-wso2-mutual-ssl extensions.
 *
 * @param api       Extended api
 * @param openAPI   API definition
 */
private static void populateTransportSecurity(ExtendedAPI api, OpenAPI openAPI) throws CLIRuntimeException {
    List<String> transports = new ArrayList<>();
    String mutualSSL = null;
    Map<String, Object> apiDefExtensions = openAPI.getExtensions();
    if (apiDefExtensions.containsKey(OpenAPIConstants.MUTUAL_SSL)) {
        if (logger.isDebugEnabled()) {
            logger.debug(OpenAPIConstants.MUTUAL_SSL + " extension found in the API Definition");
        }
        mutualSSL = validateMutualSSL(apiDefExtensions.get(OpenAPIConstants.MUTUAL_SSL), openAPI);
        api.setMutualSSL(mutualSSL);
    }
    if (apiDefExtensions.containsKey(OpenAPIConstants.TRANSPORT_SECURITY)) {
        if (logger.isDebugEnabled()) {
            logger.debug(OpenAPIConstants.TRANSPORT_SECURITY + " extension found in the API Definition");
        }
        transports = validateTransports(apiDefExtensions.get(OpenAPIConstants.TRANSPORT_SECURITY), mutualSSL,
                openAPI);
    }
    if (transports.isEmpty()) {
        transports = Arrays.asList(OpenAPIConstants.TRANSPORT_HTTP, OpenAPIConstants.TRANSPORT_HTTPS);
    }
    api.setTransport(transports);
}
 
Example 2
Source File: OpenAPIUtils.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Check whether the tier for the API is content aware or not.
 * @param openAPI OpenAPI of the API
 * @param synCtx The message containing resource request
 * @return whether tier is content aware or not.
 */
public static boolean isContentAwareTierAvailable(OpenAPI openAPI, MessageContext synCtx) {
    boolean status = false;
    Map<String, Object> vendorExtensions;
    if (openAPI != null) {
        vendorExtensions = openAPI.getExtensions();
        if (vendorExtensions != null
                && vendorExtensions.get(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH) != null
                && (boolean) vendorExtensions.get(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH)) {
            // check for api level policy
            status = true;
        } 
        // if there is api level policy. no need to check for resource level. if not, check for resource level
        if(!status) {
            vendorExtensions = getPathItemExtensions(synCtx, openAPI);
            if (vendorExtensions != null
                    && vendorExtensions.get(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH) != null
                    && (boolean) vendorExtensions.get(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH)) {
                // check for resource level policy
                status = true;
            } 
        }
    }
    return status;
}
 
Example 3
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Get scope information from the extensions
 *
 * @param openAPI openAPI object
 * @return Scope set
 * @throws APIManagementException if an error occurred
 */
private Set<Scope> getScopesFromExtensions(OpenAPI openAPI) throws APIManagementException {
    Set<Scope> scopeList = new LinkedHashSet<>();
    Map<String, Object> extensions = openAPI.getExtensions();
    if (extensions != null && extensions.containsKey(APIConstants.SWAGGER_X_WSO2_SECURITY)) {
        Map<String, Object> securityDefinitions =
                (Map<String, Object>) extensions.get(APIConstants.SWAGGER_X_WSO2_SECURITY);
        for (Map.Entry<String, Object> entry : securityDefinitions.entrySet()) {
            Map<String, Object> securityDefinition = (Map<String, Object>) entry.getValue();
            if (securityDefinition.containsKey(APIConstants.SWAGGER_X_WSO2_SCOPES)) {
                List<Map<String, String>> oauthScope =
                        (List<Map<String, String>>) securityDefinition.get(APIConstants.SWAGGER_X_WSO2_SCOPES);
                for (Map<String, String> anOauthScope : oauthScope) {
                    Scope scope = new Scope();
                    scope.setKey(anOauthScope.get(APIConstants.SWAGGER_SCOPE_KEY));
                    scope.setName(anOauthScope.get(APIConstants.SWAGGER_NAME));
                    scope.setDescription(anOauthScope.get(APIConstants.SWAGGER_DESCRIPTION));
                    scope.setRoles(anOauthScope.get(APIConstants.SWAGGER_ROLES));
                    scopeList.add(scope);
                }
            }
        }
    }
    return scopeList;
}
 
Example 4
Source File: OpenAPISerializer.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(OpenAPI value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
    if (value != null) {
        gen.writeStartObject();
        gen.writeStringField("openapi", value.getOpenapi());
        if(value.getInfo() != null) {
            gen.writeObjectField("info", value.getInfo());
        }
        if(value.getExternalDocs() != null) {
            gen.writeObjectField("externalDocs", value.getExternalDocs());
        }
        if(value.getServers() != null) {
            gen.writeObjectField("servers", value.getServers());
        }
        if(value.getSecurity() != null) {
            gen.writeObjectField("security", value.getSecurity());
        }
        if(value.getTags() != null) {
            gen.writeObjectField("tags", value.getTags());
        }
        if(value.getPaths() != null) {
            gen.writeObjectField("paths", value.getPaths());
        }
        if(value.getComponents() != null) {
            gen.writeObjectField("components", value.getComponents());
        }
        if(value.getExtensions() != null) {
            for (Entry<String, Object> e : value.getExtensions().entrySet()) {
                gen.writeObjectField(e.getKey(), e.getValue());
            }
        }
        gen.writeEndObject();
    }
}
 
Example 5
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Remove MG related information
 *
 * @param openAPI OpenAPI
 */
private void removePublisherSpecificInfo(OpenAPI openAPI) {
    Map<String, Object> extensions = openAPI.getExtensions();
    OASParserUtil.removePublisherSpecificInfo(extensions);
    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();
            OASParserUtil.removePublisherSpecificInfofromOperation(operation.getExtensions());
        }
    }
}
 
Example 6
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Remove legacy scope from swagger
 *
 * @param openAPI
 */
private void updateLegacyScopesFromSwagger(OpenAPI openAPI, SwaggerData swaggerData) {

    Map<String, Object> extensions = openAPI.getExtensions();
    if (extensions != null && extensions.containsKey(APIConstants.SWAGGER_X_WSO2_SECURITY)) {
        extensions.remove(APIConstants.SWAGGER_X_WSO2_SECURITY);
    }
}
 
Example 7
Source File: OAS3ParserTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateAPIDefinitionWithExtensions() throws Exception {
    String relativePath = "definitions" + File.separator + "oas3" + File.separator + "oas3Resources.json";
    String oas3Resources = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(relativePath), "UTF-8");
    OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();

    // check remove vendor extensions
    String definition = testGenerateAPIDefinitionWithExtension(oas3Parser, oas3Resources);
    SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(definition, null, null);
    OpenAPI openAPI = parseAttemptForV3.getOpenAPI();
    boolean isExtensionNotFound = openAPI.getExtensions() == null || !openAPI.getExtensions()
            .containsKey(APIConstants.SWAGGER_X_WSO2_SECURITY);
    Assert.assertTrue(isExtensionNotFound);
    Assert.assertEquals(2, openAPI.getPaths().size());

    Iterator<Map.Entry<String, PathItem>> itr = openAPI.getPaths().entrySet().iterator();
    while (itr.hasNext()) {
        Map.Entry<String, PathItem> pathEntry = itr.next();
        PathItem path = pathEntry.getValue();
        for (Operation operation : path.readOperations()) {
            Assert.assertFalse(operation.getExtensions().containsKey(APIConstants.SWAGGER_X_SCOPE));
        }
    }

    // check updated scopes in security definition
    Operation itemGet = openAPI.getPaths().get("/items").getGet();
    Assert.assertTrue(itemGet.getSecurity().get(0).get("default").contains("newScope"));

    // check available scopes in security definition
    SecurityScheme securityScheme = openAPI.getComponents().getSecuritySchemes().get("default");
    OAuthFlow implicityOauth = securityScheme.getFlows().getImplicit();
    Assert.assertTrue(implicityOauth.getScopes().containsKey("newScope"));
    Assert.assertEquals("newScopeDescription", implicityOauth.getScopes().get("newScope"));

    Assert.assertTrue(implicityOauth.getExtensions().containsKey(APIConstants.SWAGGER_X_SCOPES_BINDINGS));
    Map<String, String> scopeBinding =
            (Map<String, String>) implicityOauth.getExtensions().get(APIConstants.SWAGGER_X_SCOPES_BINDINGS);
    Assert.assertTrue(scopeBinding.containsKey("newScope"));
    Assert.assertEquals("admin", scopeBinding.get("newScope"));
}
 
Example 8
Source File: StaticHtml2Generator.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
    super.preprocessOpenAPI(openAPI);

    if (openAPI.getInfo() != null) {
        Info info = openAPI.getInfo();
        if (StringUtils.isBlank(jsProjectName) && info.getTitle() != null) {
            // when jsProjectName is not specified, generate it from info.title
            jsProjectName = sanitizeName(dashize(info.getTitle()));
        }
    }

    // default values
    if (StringUtils.isBlank(jsProjectName)) {
        jsProjectName = "openapi-js-client";
    }
    if (StringUtils.isBlank(jsModuleName)) {
        jsModuleName = camelize(underscore(jsProjectName));
    }

    additionalProperties.put("jsProjectName", jsProjectName);
    additionalProperties.put("jsModuleName", jsModuleName);

    preparHtmlForGlobalDescription(openAPI);

    Map<String, Object> vendorExtensions = openAPI.getExtensions();
    if (vendorExtensions != null) {
        for (Map.Entry<String, Object> vendorExtension : vendorExtensions.entrySet()) {
            // Vendor extensions could be Maps (objects). If we wanted to iterate through them in our template files
            // without knowing the keys beforehand, the default `toString` method renders them unusable. Instead, we
            // convert them to JSON strings now, which means we can easily use them later.
            if (vendorExtension.getValue() instanceof Map) {
                this.vendorExtensions().put(vendorExtension.getKey(), Json.mapper().convertValue(vendorExtension.getValue(), JsonNode.class));
            } else {
                this.vendorExtensions().put(vendorExtension.getKey(), vendorExtension.getValue());
            }
        }
    }
    openAPI.setExtensions(this.vendorExtensions);

}
 
Example 9
Source File: OpenAPIUtils.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Return the roles of a given scope attached to a resource using the API swagger.
 *
 * @param openAPI OpenAPI of the API
 * @param synCtx  The message containing resource request
 * @param resourceScope  The scope of the resource
 * @return the roles of the scope in the comma separated format
 */
public static String getRolesOfScope(OpenAPI openAPI, MessageContext synCtx, String resourceScope) {
    String resourceRoles = null;

    Map<String, Object> vendorExtensions = getPathItemExtensions(synCtx, openAPI);
    if (vendorExtensions != null) {
        if (StringUtils.isNotBlank(resourceScope)) {
            if (openAPI.getExtensions() != null &&
                    openAPI.getExtensions().get(APIConstants.SWAGGER_X_WSO2_SECURITY) != null) {
                LinkedHashMap swaggerWSO2Security = (LinkedHashMap) openAPI.getExtensions()
                        .get(APIConstants.SWAGGER_X_WSO2_SECURITY);
                if (swaggerWSO2Security != null &&
                        swaggerWSO2Security.get(APIConstants.SWAGGER_OBJECT_NAME_APIM) != null) {
                    LinkedHashMap swaggerObjectAPIM = (LinkedHashMap) swaggerWSO2Security
                            .get(APIConstants.SWAGGER_OBJECT_NAME_APIM);
                    if (swaggerObjectAPIM != null && swaggerObjectAPIM.get(APIConstants.SWAGGER_X_WSO2_SCOPES) != null) {
                        ArrayList<LinkedHashMap> apiScopes =
                                (ArrayList<LinkedHashMap>) swaggerObjectAPIM.get(APIConstants.SWAGGER_X_WSO2_SCOPES);
                        for (LinkedHashMap scope: apiScopes) {
                            if (resourceScope.equals(scope.get(APIConstants.SWAGGER_SCOPE_KEY))) {
                                resourceRoles = (String) scope.get(APIConstants.SWAGGER_ROLES);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    if (resourceRoles == null) {
        LinkedHashMap<String, Object> scopeBindings = null;
        Map<String, Object> extensions = openAPI.getComponents().getSecuritySchemes()
                .get(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY).getExtensions();
        if (extensions != null && extensions.get(APIConstants.SWAGGER_X_SCOPES_BINDINGS) != null) {
            scopeBindings = (LinkedHashMap<String, Object>) extensions.get(APIConstants.SWAGGER_X_SCOPES_BINDINGS);
        } else {
            scopeBindings = (LinkedHashMap<String, Object>) openAPI.getComponents().getSecuritySchemes().
                    get(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY).getFlows().getImplicit().getExtensions().
                    get(APIConstants.SWAGGER_X_SCOPES_BINDINGS);
        }
        if (scopeBindings != null) {
            return (String) scopeBindings.get(resourceScope);
        }
    }

    return null;
}
 
Example 10
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * This method returns api that is attached with api extensions related to micro-gw
 *
 * @param apiDefinition                  String
 * @param api                            API
 * @param isBasepathExtractedFromSwagger boolean
 * @return API
 */
@Override
public API setExtensionsToAPI(String apiDefinition, API api, boolean isBasepathExtractedFromSwagger) throws APIManagementException {
    OpenAPI openAPI = getOpenAPI(apiDefinition);
    Map<String, Object> extensions = openAPI.getExtensions();
    if (extensions == null) {
        return api;
    }

    //Setup Custom auth header for API
    String authHeader = OASParserUtil.getAuthorizationHeaderFromSwagger(extensions);
    if (StringUtils.isNotBlank(authHeader)) {
        api.setAuthorizationHeader(authHeader);
    }
    //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 = securityList + "," + APIConstants.API_SECURITY_MUTUAL_SSL;
        } else if (APIConstants.MANDATORY.equals(mutualSSL)) {
            securityList = securityList + "," + 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);
    }
    //Setup Basepath
    String basePath = OASParserUtil.getBasePathFromSwagger(extensions);
    if (StringUtils.isNotBlank(basePath) && isBasepathExtractedFromSwagger) {
        basePath = basePath.replace("{version}", api.getId().getVersion());
        api.setContextTemplate(basePath);
        api.setContext(basePath);
    }
    return api;
}