Search in sources :

Example 21 with OpenAPIDeserializer

use of io.swagger.v3.parser.util.OpenAPIDeserializer in project swagger-parser by swagger-api.

the class OpenAPIDeserializerTest method readSchemaObject.

@Test(dataProvider = "data")
public void readSchemaObject(JsonNode rootNode) throws Exception {
    final OpenAPIDeserializer deserializer = new OpenAPIDeserializer();
    final SwaggerParseResult result = deserializer.deserialize(rootNode);
    Assert.assertNotNull(result);
    final OpenAPI openAPI = result.getOpenAPI();
    Assert.assertNotNull(openAPI);
    final Paths paths = openAPI.getPaths();
    Assert.assertNotNull(paths);
    Assert.assertEquals(paths.size(), 19);
    // parameters operation get
    PathItem petByStatusEndpoint = paths.get("/pet/findByStatus");
    Assert.assertNotNull(petByStatusEndpoint.getGet());
    Assert.assertNotNull(petByStatusEndpoint.getGet().getParameters());
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().size(), 1);
    Assert.assertNotNull(petByStatusEndpoint.getGet().getParameters().get(0).getSchema());
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getSchema().getFormat(), "int64");
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getSchema().getXml().getNamespace(), "http://example.com/schema/sample");
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getSchema().getXml().getPrefix(), "sample");
    Assert.assertEquals(petByStatusEndpoint.getGet().getParameters().get(0).getIn(), "query");
}
Also used : PathItem(io.swagger.v3.oas.models.PathItem) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) Paths(io.swagger.v3.oas.models.Paths) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Test(org.testng.annotations.Test)

Example 22 with OpenAPIDeserializer

use of io.swagger.v3.parser.util.OpenAPIDeserializer in project swagger-parser by swagger-api.

the class ResolverCache method loadRef.

public <T> T loadRef(String ref, RefFormat refFormat, Class<T> expectedType) {
    if (refFormat == RefFormat.INTERNAL) {
        // we don't need to go get anything for internal refs
        Object loadedRef = loadInternalRef(ref);
        try {
            return expectedType.cast(loadedRef);
        } catch (Exception e) {
            return null;
        }
    }
    final String[] refParts = ref.split("#/");
    if (refParts.length > 2) {
        throw new RuntimeException("Invalid ref format: " + ref);
    }
    final String file = refParts[0];
    final String definitionPath = refParts.length == 2 ? refParts[1] : null;
    // we might have already resolved this ref, so check the resolutionCache
    Object previouslyResolvedEntity = resolutionCache.get(ref);
    if (previouslyResolvedEntity != null) {
        if (expectedType.equals(Header.class)) {
            if (expectedType.getClass().equals(previouslyResolvedEntity.getClass())) {
                return expectedType.cast(previouslyResolvedEntity);
            }
        } else {
            return expectedType.cast(previouslyResolvedEntity);
        }
    }
    // we have not resolved this particular ref
    // but we may have already loaded the file or url in question
    String contents = externalFileCache.get(file);
    if (contents == null) {
        if (parentDirectory != null) {
            contents = RefUtils.readExternalRef(file, refFormat, auths, parentDirectory);
        } else if (rootPath != null && rootPath.startsWith("http")) {
            contents = RefUtils.readExternalUrlRef(file, refFormat, auths, rootPath);
        } else if (rootPath != null) {
            contents = RefUtils.readExternalClasspathRef(file, refFormat, auths, rootPath);
        }
        externalFileCache.put(file, contents);
    }
    SwaggerParseResult deserializationUtilResult = new SwaggerParseResult();
    JsonNode tree = DeserializationUtils.deserializeIntoTree(contents, file, parseOptions, deserializationUtilResult);
    if (definitionPath == null) {
        T result = null;
        if (parseOptions.isValidateExternalRefs()) {
            result = deserializeFragment(tree, expectedType, file, "/");
        } else {
            result = DeserializationUtils.deserialize(contents, file, expectedType);
        }
        resolutionCache.put(ref, result);
        if (deserializationUtilResult.getMessages() != null) {
            if (this.resolveValidationMessages != null) {
                this.resolveValidationMessages.addAll(deserializationUtilResult.getMessages());
            }
        }
        return result;
    }
    // a definition path is defined, meaning we need to "dig down" through the JSON tree and get the desired entity
    String[] jsonPathElements = definitionPath.split("/");
    for (String jsonPathElement : jsonPathElements) {
        tree = tree.get(unescapePointer(jsonPathElement));
        // if at any point we do find an element we expect, print and error and abort
        if (tree == null) {
            throw new RuntimeException("Could not find " + definitionPath + " in contents of " + file);
        }
    }
    T result = null;
    if (parseOptions.isValidateExternalRefs()) {
        result = deserializeFragment(tree, expectedType, file, definitionPath);
    } else {
        if (expectedType.equals(Schema.class)) {
            OpenAPIDeserializer deserializer = new OpenAPIDeserializer();
            result = (T) deserializer.getSchema((ObjectNode) tree, definitionPath.replace("/", "."), null);
        } else {
            result = DeserializationUtils.deserialize(tree, file, expectedType);
        }
    }
    updateLocalRefs(file, result);
    resolutionCache.put(ref, result);
    if (deserializationUtilResult.getMessages() != null) {
        if (this.resolveValidationMessages != null) {
            this.resolveValidationMessages.addAll(deserializationUtilResult.getMessages());
        }
    }
    return result;
}
Also used : OpenAPIDeserializer(io.swagger.v3.parser.util.OpenAPIDeserializer) JsonNode(com.fasterxml.jackson.databind.JsonNode) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 23 with OpenAPIDeserializer

use of io.swagger.v3.parser.util.OpenAPIDeserializer in project swagger-parser by swagger-api.

the class OpenAPIResolverTest method pathsResolver.

@Test
public void pathsResolver() throws Exception {
    final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    String pathFile = FileUtils.readFileToString(new File("src/test/resources/oas3.yaml.template"));
    pathFile = pathFile.replace("${dynamicPort}", String.valueOf(this.serverPort));
    final JsonNode rootNode = mapper.readTree(pathFile.getBytes());
    final OpenAPIDeserializer deserializer = new OpenAPIDeserializer();
    final SwaggerParseResult result = deserializer.deserialize(rootNode);
    Assert.assertNotNull(result);
    final OpenAPI openAPI = result.getOpenAPI();
    Assert.assertNotNull(openAPI);
    assertEquals(new OpenAPIResolver(openAPI, new ArrayList<>(), null).resolve(), openAPI);
    // internal url pathItem
    assertEquals(openAPI.getPaths().get("/pathItemRef2"), openAPI.getPaths().get("/pet"));
    // internal array schema inside operation -> responses -> content
    ArraySchema schema = (ArraySchema) openAPI.getPaths().get("/pet").getPut().getResponses().get("400").getContent().get("application/json").getSchema();
    assertEquals(schema.getItems().get$ref(), "#/components/schemas/VeryComplexType");
    // replace of parameters in operation and remove the ones from the pathItem
    Assert.assertNotNull(openAPI.getPaths().get("/pet").getPost().getParameters());
    Assert.assertNull(openAPI.getPaths().get("/pet").getParameters());
    // remote ref pathItem
    assertEquals(openAPI.getPaths().get("/pathItemRef").getSummary(), "summary");
    assertEquals(openAPI.getPaths().get("/pathItemRef").getPost().getResponses().get("405").getDescription(), "Invalid input");
    // internal pathItem operation -> response -> schema
    Assert.assertNotNull(openAPI.getPaths().get("/pet/{petId}").getGet().getResponses());
    assertEquals(openAPI.getPaths().get("/pet/{petId}").getGet().getResponses().get("200").getContent().get("application/xml").getSchema().get$ref(), "#/components/schemas/Pet");
    // internal pathItem -> operation -> callback -> pathItem -> operation -> response -> schema
    assertEquals(openAPI.getPaths().get("/pet/{petId}").getGet().getCallbacks().get("mainHook").get("$request.body#/url").getPost().getResponses().get("200").getContent().get("application/xml").getSchema().get$ref(), "#/components/schemas/Pet");
    // internal pathItem -> operation -> requestBody
    Schema id = (Schema) openAPI.getPaths().get("/pet/findByStatus").getGet().getRequestBody().getContent().get("multipart/mixed").getSchema().getProperties().get("id");
    assertEquals(id.get$ref(), "#/components/schemas/Pet");
    // internal parameter url
    assertEquals(openAPI.getPaths().get("/store/inventory").getGet().getParameters().get(0), openAPI.getComponents().getParameters().get("limitParam"));
}
Also used : OpenAPIDeserializer(io.swagger.v3.parser.util.OpenAPIDeserializer) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) ComposedSchema(io.swagger.v3.oas.models.media.ComposedSchema) IntegerSchema(io.swagger.v3.oas.models.media.IntegerSchema) StringSchema(io.swagger.v3.oas.models.media.StringSchema) ObjectSchema(io.swagger.v3.oas.models.media.ObjectSchema) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) Schema(io.swagger.v3.oas.models.media.Schema) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) OpenAPIResolver(io.swagger.v3.parser.OpenAPIResolver) JsonNode(com.fasterxml.jackson.databind.JsonNode) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) File(java.io.File) OpenAPI(io.swagger.v3.oas.models.OpenAPI) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.testng.annotations.Test)

Aggregations

SwaggerParseResult (io.swagger.v3.parser.core.models.SwaggerParseResult)23 OpenAPI (io.swagger.v3.oas.models.OpenAPI)21 Test (org.testng.annotations.Test)21 PathItem (io.swagger.v3.oas.models.PathItem)9 Paths (io.swagger.v3.oas.models.Paths)8 JsonNode (com.fasterxml.jackson.databind.JsonNode)7 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)6 YAMLFactory (com.fasterxml.jackson.dataformat.yaml.YAMLFactory)6 ArraySchema (io.swagger.v3.oas.models.media.ArraySchema)6 ComposedSchema (io.swagger.v3.oas.models.media.ComposedSchema)5 IntegerSchema (io.swagger.v3.oas.models.media.IntegerSchema)5 ObjectSchema (io.swagger.v3.oas.models.media.ObjectSchema)5 Schema (io.swagger.v3.oas.models.media.Schema)5 StringSchema (io.swagger.v3.oas.models.media.StringSchema)5 ByteArraySchema (io.swagger.v3.oas.models.media.ByteArraySchema)4 ApiResponse (io.swagger.v3.oas.models.responses.ApiResponse)4 OpenAPIDeserializer (io.swagger.v3.parser.util.OpenAPIDeserializer)4 BinarySchema (io.swagger.v3.oas.models.media.BinarySchema)3 DateSchema (io.swagger.v3.oas.models.media.DateSchema)3 DateTimeSchema (io.swagger.v3.oas.models.media.DateTimeSchema)3