Search in sources :

Example 1 with OpenAPIV3Parser

use of io.swagger.v3.parser.OpenAPIV3Parser in project vertx-web by vert-x3.

the class OpenAPI3ParametersUnitTest method loadSwagger.

private OpenAPI loadSwagger(String filename) throws IOException {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveCombinators(false);
    options.setResolveFully(true);
    return new OpenAPIV3Parser().readContents(String.join("\n", Files.readAllLines(Paths.get(filename), StandardCharsets.UTF_8)), null, options).getOpenAPI();
}
Also used : ParseOptions(io.swagger.v3.parser.core.models.ParseOptions) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser)

Example 2 with OpenAPIV3Parser

use of io.swagger.v3.parser.OpenAPIV3Parser in project hippo by NHS-digital-website.

the class SwaggerCodeGenOpenApiSpecificationJsonToHtmlConverter method openApiModelFrom.

private OpenAPI openApiModelFrom(final String openApiSpecificationJson) {
    final ParseOptions parseOptions = new ParseOptions();
    parseOptions.setResolve(true);
    final SwaggerParseResult swaggerParseResult = new OpenAPIV3Parser().readContents(openApiSpecificationJson, null, parseOptions);
    Optional.ofNullable(swaggerParseResult.getMessages()).orElse(Collections.emptyList()).forEach(log::warn);
    return swaggerParseResult.getOpenAPI();
}
Also used : ParseOptions(io.swagger.v3.parser.core.models.ParseOptions) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser)

Example 3 with OpenAPIV3Parser

use of io.swagger.v3.parser.OpenAPIV3Parser in project carbon-apimgt by wso2.

the class OAS3Parser method getOASDefinitionWithTierContentAwareProperty.

@Override
public String getOASDefinitionWithTierContentAwareProperty(String oasDefinition, List<String> contentAwareTiersList, String apiLevelTier) throws APIManagementException {
    OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
    SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(oasDefinition, null, null);
    if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) {
        log.debug("Errors found when parsing OAS definition");
    }
    OpenAPI swagger = parseAttemptForV3.getOpenAPI();
    // check if API Level tier is content aware. if so, we set a extension as a global property
    if (contentAwareTiersList.contains(apiLevelTier)) {
        swagger.addExtension(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH, true);
        // no need to check resource levels since both cannot exist at the same time.
        log.debug("API Level policy is content aware..");
        return Json.pretty(swagger);
    }
    // if api level tier exists, skip checking for resource level tiers since both cannot exist at the same time.
    if (apiLevelTier != null) {
        log.debug("API Level policy is not content aware..");
        return oasDefinition;
    } else {
        log.debug("API Level policy does not exist. Checking for resource level");
        for (Map.Entry<String, PathItem> entry : swagger.getPaths().entrySet()) {
            String path = entry.getKey();
            List<Operation> operations = swagger.getPaths().get(path).readOperations();
            for (Operation op : operations) {
                if (contentAwareTiersList.contains(op.getExtensions().get(APIConstants.SWAGGER_X_THROTTLING_TIER))) {
                    if (log.isDebugEnabled()) {
                        log.debug("API resource Level policy is content aware for operation " + op.getOperationId());
                    }
                    op.addExtension(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH, true);
                }
            }
        }
        return Json.pretty(swagger);
    }
}
Also used : PathItem(io.swagger.v3.oas.models.PathItem) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) Operation(io.swagger.v3.oas.models.Operation) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 4 with OpenAPIV3Parser

use of io.swagger.v3.parser.OpenAPIV3Parser in project carbon-apimgt by wso2.

the class OAS3Parser method removeExamplesFromOpenAPI.

/**
 * Remove x-examples from all the paths from the OpenAPI definition.
 *
 * @param apiDefinition OpenAPI definition as String
 */
public static String removeExamplesFromOpenAPI(String apiDefinition) throws APIManagementException {
    try {
        OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
        SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(apiDefinition, null, null);
        if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) {
            log.debug("Errors found when parsing OAS definition");
        }
        OpenAPI openAPI = parseAttemptForV3.getOpenAPI();
        for (Map.Entry<String, PathItem> entry : openAPI.getPaths().entrySet()) {
            String path = entry.getKey();
            List<Operation> operations = openAPI.getPaths().get(path).readOperations();
            for (Operation operation : operations) {
                if (operation.getExtensions() != null && operation.getExtensions().keySet().contains(APIConstants.SWAGGER_X_EXAMPLES)) {
                    operation.getExtensions().remove(APIConstants.SWAGGER_X_EXAMPLES);
                }
            }
        }
        return Yaml.pretty().writeValueAsString(openAPI);
    } catch (JsonProcessingException e) {
        throw new APIManagementException("Error while removing examples from OpenAPI definition", e, ExceptionCodes.ERROR_REMOVING_EXAMPLES);
    }
}
Also used : PathItem(io.swagger.v3.oas.models.PathItem) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) Operation(io.swagger.v3.oas.models.Operation) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 5 with OpenAPIV3Parser

use of io.swagger.v3.parser.OpenAPIV3Parser in project carbon-apimgt by wso2.

the class OAS3Parser method validateAPIDefinition.

/**
 * This method validates the given OpenAPI definition by content
 *
 * @param apiDefinition     OpenAPI Definition content
 * @param host OpenAPI Definition url
 * @param returnJsonContent whether to return the converted json form of the OpenAPI definition
 * @return APIDefinitionValidationResponse object with validation information
 */
@Override
public APIDefinitionValidationResponse validateAPIDefinition(String apiDefinition, String host, boolean returnJsonContent) throws APIManagementException {
    APIDefinitionValidationResponse validationResponse = new APIDefinitionValidationResponse();
    OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(apiDefinition, null, options);
    if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) {
        validationResponse.setValid(false);
        for (String message : parseAttemptForV3.getMessages()) {
            OASParserUtil.addErrorToValidationResponse(validationResponse, message);
            if (message.contains(APIConstants.OPENAPI_IS_MISSING_MSG)) {
                ErrorItem errorItem = new ErrorItem();
                errorItem.setErrorCode(ExceptionCodes.INVALID_OAS3_FOUND.getErrorCode());
                errorItem.setMessage(ExceptionCodes.INVALID_OAS3_FOUND.getErrorMessage());
                errorItem.setDescription(ExceptionCodes.INVALID_OAS3_FOUND.getErrorMessage());
                validationResponse.getErrorItems().add(errorItem);
            }
        }
    } else {
        OpenAPI openAPI = parseAttemptForV3.getOpenAPI();
        io.swagger.v3.oas.models.info.Info info = openAPI.getInfo();
        List<String> endpoints;
        String endpointWithHost = "";
        if (openAPI.getServers() == null || openAPI.getServers().isEmpty()) {
            endpoints = null;
        } else {
            endpoints = openAPI.getServers().stream().map(url -> url.getUrl()).collect(Collectors.toList());
            for (String endpoint : endpoints) {
                if (endpoint.startsWith("/")) {
                    if (StringUtils.isEmpty(host)) {
                        endpointWithHost = "http://api.yourdomain.com" + endpoint;
                    } else {
                        endpointWithHost = host + endpoint;
                    }
                    endpoints.set(endpoints.indexOf(endpoint), endpointWithHost);
                }
            }
        }
        String title = null;
        String context = null;
        if (!StringUtils.isBlank(info.getTitle())) {
            title = info.getTitle();
            context = info.getTitle().replaceAll("\\s", "").toLowerCase();
        }
        OASParserUtil.updateValidationResponseAsSuccess(validationResponse, apiDefinition, openAPI.getOpenapi(), title, info.getVersion(), context, info.getDescription(), endpoints);
        validationResponse.setParser(this);
        if (returnJsonContent) {
            if (!apiDefinition.trim().startsWith("{")) {
                // not a json (it is yaml)
                JsonNode jsonNode = DeserializationUtils.readYamlTree(apiDefinition);
                validationResponse.setJsonContent(jsonNode.toString());
            } else {
                validationResponse.setJsonContent(apiDefinition);
            }
        }
    }
    return validationResponse;
}
Also used : Info(io.swagger.v3.oas.models.info.Info) ErrorItem(org.wso2.carbon.apimgt.api.ErrorItem) JsonNode(com.fasterxml.jackson.databind.JsonNode) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse) ParseOptions(io.swagger.v3.parser.core.models.ParseOptions) OpenAPI(io.swagger.v3.oas.models.OpenAPI)

Aggregations

OpenAPIV3Parser (io.swagger.v3.parser.OpenAPIV3Parser)295 Test (org.testng.annotations.Test)279 OpenAPI (io.swagger.v3.oas.models.OpenAPI)219 SwaggerParseResult (io.swagger.v3.parser.core.models.SwaggerParseResult)184 ParseOptions (io.swagger.v3.parser.core.models.ParseOptions)169 ArraySchema (io.swagger.v3.oas.models.media.ArraySchema)83 Schema (io.swagger.v3.oas.models.media.Schema)83 ComposedSchema (io.swagger.v3.oas.models.media.ComposedSchema)80 StringSchema (io.swagger.v3.oas.models.media.StringSchema)77 IntegerSchema (io.swagger.v3.oas.models.media.IntegerSchema)76 ObjectSchema (io.swagger.v3.oas.models.media.ObjectSchema)75 ByteArraySchema (io.swagger.v3.oas.models.media.ByteArraySchema)66 MapSchema (io.swagger.v3.oas.models.media.MapSchema)63 BinarySchema (io.swagger.v3.oas.models.media.BinarySchema)25 QueryParameter (io.swagger.v3.oas.models.parameters.QueryParameter)25 DateSchema (io.swagger.v3.oas.models.media.DateSchema)24 DateTimeSchema (io.swagger.v3.oas.models.media.DateTimeSchema)24 Parameter (io.swagger.v3.oas.models.parameters.Parameter)23 HashSet (java.util.HashSet)22 PathParameter (io.swagger.v3.oas.models.parameters.PathParameter)17