Search in sources :

Example 36 with RefFormat

use of io.swagger.v3.parser.models.RefFormat in project swagger-parser by swagger-api.

the class ResponseProcessor method processReferenceResponse.

public void processReferenceResponse(ApiResponse response) {
    RefFormat refFormat = computeRefFormat(response.get$ref());
    String $ref = response.get$ref();
    if (isAnExternalRefFormat(refFormat)) {
        final String newRef = externalRefProcessor.processRefToExternalResponse($ref, refFormat);
        if (newRef != null) {
            response.set$ref(newRef);
        }
    }
}
Also used : RefFormat(io.swagger.v3.parser.models.RefFormat) RefUtils.isAnExternalRefFormat(io.swagger.v3.parser.util.RefUtils.isAnExternalRefFormat) RefUtils.computeRefFormat(io.swagger.v3.parser.util.RefUtils.computeRefFormat)

Example 37 with RefFormat

use of io.swagger.v3.parser.models.RefFormat 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 38 with RefFormat

use of io.swagger.v3.parser.models.RefFormat in project swagger-parser by swagger-api.

the class CallbackProcessor method processReferenceCallback.

public void processReferenceCallback(Callback callback) {
    String $ref = callback.get$ref();
    RefFormat refFormat = computeRefFormat($ref);
    if (isAnExternalRefFormat(refFormat)) {
        final String newRef = externalRefProcessor.processRefToExternalCallback($ref, refFormat);
        if (newRef != null) {
            callback.set$ref("#/components/callbacks/" + newRef);
        }
    }
}
Also used : RefFormat(io.swagger.v3.parser.models.RefFormat) RefUtils.isAnExternalRefFormat(io.swagger.v3.parser.util.RefUtils.isAnExternalRefFormat) RefUtils.computeRefFormat(io.swagger.v3.parser.util.RefUtils.computeRefFormat)

Example 39 with RefFormat

use of io.swagger.v3.parser.models.RefFormat in project swagger-parser by swagger-api.

the class ResolverCacheTest method testLoadExternalRefWithEscapedCharacters.

@Test
public void testLoadExternalRefWithEscapedCharacters() throws Exception {
    final RefFormat format = RefFormat.URL;
    final String ref = "http://my.company.com/path/to/main.yaml";
    final String contentsOfExternalFile = "openAPI: \"2.0\"\n" + "\n" + "info:\n" + "  version: 1.0.0\n" + "  title: Path include test case child\n" + "\n" + "paths:\n" + "  /foo~bar~1:\n" + "    get:\n" + "      responses:\n" + "        200:\n" + "          description: \"Request successful\"\n";
    new Expectations() {

        {
            RefUtils.readExternalUrlRef(ref, format, auths, "http://my.company.com/path/parent.json");
            times = 1;
            result = contentsOfExternalFile;
        }
    };
    ResolverCache cache = new ResolverCache(openAPI, auths, "http://my.company.com/path/parent.json");
    PathItem path = cache.loadRef(ref + "#/paths/~1foo~0bar~01", RefFormat.URL, PathItem.class);
    assertNotNull(path);
}
Also used : Expectations(mockit.Expectations) PathItem(io.swagger.v3.oas.models.PathItem) RefFormat(io.swagger.v3.parser.models.RefFormat) ResolverCache(io.swagger.v3.parser.ResolverCache) Test(org.testng.annotations.Test)

Example 40 with RefFormat

use of io.swagger.v3.parser.models.RefFormat in project swagger-parser by swagger-api.

the class ResolverCacheTest method testLoadExternalRef_NoDefinitionPath.

@Test
public void testLoadExternalRef_NoDefinitionPath() throws Exception {
    final RefFormat format = RefFormat.URL;
    final String ref = "http://my.company.com/path/to/file.json";
    final String contentsOfExternalFile = "really good json";
    ParseOptions parseOptions = new ParseOptions();
    parseOptions.setResolve(true);
    parseOptions.setValidateExternalRefs(true);
    new Expectations(DeserializationUtils.class) {

        {
            RefUtils.readExternalUrlRef(ref, format, auths, "http://my.company.com/path/parent.json");
            times = 1;
            result = contentsOfExternalFile;
            DeserializationUtils.deserializeIntoTree(contentsOfExternalFile, ref, parseOptions, (SwaggerParseResult) any);
            times = 1;
            result = new ObjectMapper().readTree("{\"type\":  \"string\"}");
        }
    };
    ResolverCache cache = new ResolverCache(openAPI, auths, "http://my.company.com/path/parent.json", new HashSet<>(), parseOptions);
    Schema firstActualResult = cache.loadRef(ref, RefFormat.URL, Schema.class);
    assertEquals(contentsOfExternalFile, cache.getExternalFileCache().get(ref));
    assertEquals(((Schema) cache.getResolutionCache().get(ref)).getType(), "string");
    assertEquals(firstActualResult.getType(), "string");
    // requesting the same ref a second time should not result in reading the external file again
    Schema secondActualResult = cache.loadRef(ref, format, Schema.class);
    assertEquals(secondActualResult.getType(), "string");
}
Also used : Expectations(mockit.Expectations) Schema(io.swagger.v3.oas.models.media.Schema) RefFormat(io.swagger.v3.parser.models.RefFormat) ParseOptions(io.swagger.v3.parser.core.models.ParseOptions) ResolverCache(io.swagger.v3.parser.ResolverCache) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.testng.annotations.Test)

Aggregations

RefFormat (io.swagger.v3.parser.models.RefFormat)38 RefUtils.computeRefFormat (io.swagger.v3.parser.util.RefUtils.computeRefFormat)30 RefUtils.isAnExternalRefFormat (io.swagger.v3.parser.util.RefUtils.isAnExternalRefFormat)29 Components (io.swagger.v3.oas.models.Components)12 Schema (io.swagger.v3.oas.models.media.Schema)8 Test (org.testng.annotations.Test)7 ResolverCache (io.swagger.v3.parser.ResolverCache)6 Expectations (mockit.Expectations)6 Example (io.swagger.v3.oas.models.examples.Example)5 PathItem (io.swagger.v3.oas.models.PathItem)4 MediaType (io.swagger.v3.oas.models.media.MediaType)4 Parameter (io.swagger.v3.oas.models.parameters.Parameter)4 ApiResponse (io.swagger.v3.oas.models.responses.ApiResponse)4 OpenAPI (io.swagger.v3.oas.models.OpenAPI)3 Callback (io.swagger.v3.oas.models.callbacks.Callback)3 Header (io.swagger.v3.oas.models.headers.Header)3 Link (io.swagger.v3.oas.models.links.Link)3 RequestBody (io.swagger.v3.oas.models.parameters.RequestBody)3 SecurityScheme (io.swagger.v3.oas.models.security.SecurityScheme)3 Map (java.util.Map)3