io.swagger.v3.parser.core.models.AuthorizationValue Java Examples

The following examples show how to use io.swagger.v3.parser.core.models.AuthorizationValue. 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: ModelUtils.java    From openapi-generator with Apache License 2.0 8 votes vote down vote up
/**
 * Parse the OAS document at the specified location, get the swagger or openapi version
 * as specified in the source document, and return the version.
 * 
 * For OAS 2.0 documents, return the value of the 'swagger' attribute.
 * For OAS 3.x documents, return the value of the 'openapi' attribute.
 * 
 * @param openAPI the object that encapsulates the OAS document.
 * @param location the URL of the OAS document.
 * @param auths the list of authorization values to access the remote URL.
 * 
 * @return the version of the OpenAPI document.
 */
public static SemVer getOpenApiVersion(OpenAPI openAPI, String location, List<AuthorizationValue> auths) {
    String version;
    try {
        JsonNode document = readWithInfo(location, auths);
        JsonNode value = document.findValue("swagger");
        if (value == null) {
            // This is not a OAS 2.0 document.
            // Note: we cannot simply return the value of the "openapi" attribute
            // because the 2.0 to 3.0 converter always sets the value to '3.0'.
            value = document.findValue("openapi");
        }
        version = value.asText();
    } catch (Exception ex) {
        // Fallback to using the 'openapi' attribute.
        LOGGER.warn("Unable to read swagger/openapi attribute");
        version = openAPI.getOpenapi();
    }
    // Cache the OAS version in global settings so it can be looked up in the helper functions.
    //GlobalSettings.setProperty(openapiDocVersion, version);

    return new SemVer(version);
}
 
Example #2
Source File: ExtensionsUtilTest.java    From swagger-inflector with Apache License 2.0 7 votes vote down vote up
@Test
public void resolveComposedAllOfReferenceSchema(@Injectable final List<AuthorizationValue> auths){

    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveFully(true);

    OpenAPI openAPI = new OpenAPIV3Parser().readLocation("./src/test/swagger/oas3.yaml",auths,options).getOpenAPI();
    ResolverFully resolverUtil = new ResolverFully();
    resolverUtil.resolveFully(openAPI);

    assertTrue(openAPI.getPaths().get("/withInvalidComposedModelArray").getPost().getRequestBody().getContent().get("*/*").getSchema() instanceof ArraySchema);
    ArraySchema arraySchema = (ArraySchema) openAPI.getPaths().get("/withInvalidComposedModelArray").getPost().getRequestBody().getContent().get("*/*").getSchema();
    assertTrue(arraySchema.getItems() instanceof ObjectSchema);

}
 
Example #3
Source File: RefUtils.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
public static String readExternalUrlRef(String file, RefFormat refFormat, List<AuthorizationValue> auths,
                                        String rootPath) {

    if (!RefUtils.isAnExternalRefFormat(refFormat)) {
        throw new RuntimeException("Ref is not external");
    }

    String result;

    try {
        if (refFormat == RefFormat.URL) {
            result = RemoteUrl.urlToString(file, auths);
        } else {
            //its assumed to be a relative ref
            String url = buildUrl(rootPath, file);

            return readExternalRef(url, RefFormat.URL, auths, null);
        }
    } catch (Exception e) {
        throw new RuntimeException("Unable to load " + refFormat + " ref: " + file, e);
    }

    return result;

}
 
Example #4
Source File: ExampleBuilderTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void testAdjacentComposedSchema(@Injectable List<AuthorizationValue> auth){

    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveFully(true);

    OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/swagger/oneOf-anyOf.yaml", auth, options);


    ApiResponse responseAdjacent = openAPI.getPaths().get("/adjacent").getGet().getResponses().get("200");
    Example exampleAdjacent = ExampleBuilder.fromSchema(responseAdjacent.getContent().get("application/json").getSchema(),null,ExampleBuilder.RequestType.READ);
    String outputAdjacent = Json.pretty(exampleAdjacent);
    assertEqualsIgnoreLineEnding(outputAdjacent, "[ {\n" +
            "  \"title\" : \"The Hitchhiker's Guide to the Galaxy\",\n" +
            "  \"authors\" : [ \"Douglas Adams\" ],\n" +
            "  \"isbn\" : \"0-330-25864-8\"\n" +
            "}, {\n" +
            "  \"title\" : \"Blade Runner\",\n" +
            "  \"directors\" : [ \"Ridley Scott\" ],\n" +
            "  \"year\" : 1982\n" +
            "} ]");

}
 
Example #5
Source File: VaadinConnectTsGenerator.java    From flow with Apache License 2.0 6 votes vote down vote up
private static SwaggerParseResult getParseResult(
        CodegenConfigurator configurator) {
    try {
        List<AuthorizationValue> authorizationValues = AuthParser
                .parse(configurator.getAuth());
        String inputSpec = configurator.loadSpecContent(
                configurator.getInputSpecURL(), authorizationValues);
        ParseOptions options = new ParseOptions();
        options.setResolve(true);
        return new OpenAPIParser().readContents(inputSpec,
                authorizationValues, options);
    } catch (Exception e) {
        throw new IllegalStateException(
                "Unexpected error while generating vaadin-connect TypeScript endpoint wrappers. "
                        + String.format("Can't read file '%s'",
                                configurator.getInputSpecURL()),
                e);
    }
}
 
Example #6
Source File: ExtensionsUtilTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void allowBooleanAdditionalProperties(@Injectable final List<AuthorizationValue> auths) {

    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveFully(true);

    SwaggerParseResult result = new OpenAPIV3Parser().readLocation("./src/test/swagger/additionalProperties.yaml", auths, options);

    assertNotNull(result);
    assertNotNull(result.getOpenAPI());
    OpenAPI openAPI = result.getOpenAPI();
    Assert.assertEquals(result.getOpenAPI().getOpenapi(), "3.0.0");
    List<String> messages = result.getMessages();

    Assert.assertTrue(openAPI.getComponents().getSchemas().get("someObject").getAdditionalProperties() instanceof Schema);
    Assert.assertTrue(((Schema)(openAPI.getComponents().getSchemas().get("someObject").getProperties().get("innerObject"))).getAdditionalProperties() instanceof Boolean);

}
 
Example #7
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testInlineModelResolver(@Injectable final List<AuthorizationValue> auths) throws Exception{

    String pathFile = FileUtils.readFileToString(new File("src/test/resources/flatten.json"));
    pathFile = pathFile.replace("${dynamicPort}", String.valueOf(this.serverPort));
    ParseOptions options = new ParseOptions();
    options.setFlatten(true);

    SwaggerParseResult result = new OpenAPIV3Parser().readContents(pathFile, auths, options);

    Assert.assertNotNull(result);
    OpenAPI openAPI = result.getOpenAPI();
    Assert.assertNotNull(openAPI);
    Schema user = openAPI.getComponents().getSchemas().get("User");

    assertNotNull(user);
    Schema address = (Schema)user.getProperties().get("address");

    assertTrue((address.get$ref()!= null));

    Schema userAddress = openAPI.getComponents().getSchemas().get("User_address");
    assertNotNull(userAddress);
    assertNotNull(userAddress.getProperties().get("city"));
    assertNotNull(userAddress.getProperties().get("street"));
}
 
Example #8
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue1177(@Injectable final List<AuthorizationValue> auths) {
    String path = "/issue-1177/swagger.yaml";

    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveFully(true);

    OpenAPI openAPI = new OpenAPIV3Parser().readLocation(path, auths, options).getOpenAPI();

    // $ref response with $ref header
    ApiResponse petsListApiResponse = openAPI.getPaths().get("/update-pets").getPost().getResponses().get("200");
    assertNotNull(petsListApiResponse);

    Header sessionIdHeader = petsListApiResponse.getHeaders().get("x-session-id");
    assertNotNull(sessionIdHeader);

    Schema petsListSchema = openAPI.getComponents().getSchemas().get("PetsList");
    assertNotNull(petsListSchema);

    assertNotNull(openAPI.getComponents().getHeaders());
    Header sessionIdHeaderComponent = openAPI.getComponents().getHeaders().get("x-session-id");
    assertTrue(sessionIdHeader == sessionIdHeaderComponent);

    assertTrue(petsListApiResponse.getContent().get("application/json").getSchema() == petsListSchema);
}
 
Example #9
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testComposedSchemaAdjacentWithExamples(@Injectable final List<AuthorizationValue> auths) throws Exception {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveFully(true);
    OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/resources/anyOf_OneOf.yaml", auths, options);

    Assert.assertNotNull(openAPI);

    Assert.assertTrue(openAPI.getComponents().getSchemas().size() == 2);

    Schema schemaPath = openAPI.getPaths().get("/path").getGet().getResponses().get("200").getContent().get("application/json").getSchema();
    Assert.assertTrue(schemaPath instanceof Schema);
    Assert.assertTrue(schemaPath.getProperties().size() == 5);
    Assert.assertTrue(schemaPath.getExample() instanceof HashSet);
    Set<Object> examples = (HashSet) schemaPath.getExample();
    Assert.assertTrue(examples.size() == 2);
}
 
Example #10
Source File: AuthParser.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
public static List<AuthorizationValue> parse(String urlEncodedAuthStr) {
    List<AuthorizationValue> auths = new ArrayList<AuthorizationValue>();
    if (isNotEmpty(urlEncodedAuthStr)) {
        String[] parts = urlEncodedAuthStr.split(",");
        for (String part : parts) {
            String[] kvPair = part.split(":");
            if (kvPair.length == 2) {
                try {
                    auths.add(new AuthorizationValue(URLDecoder.decode(kvPair[0], "UTF-8"), URLDecoder.decode(kvPair[1], "UTF-8"), "header"));
                } catch (UnsupportedEncodingException e) {
                    LOGGER.warn(e.getMessage());
                }
            }
        }
    }
    return auths;
}
 
Example #11
Source File: ModelUtils.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Parse and return a JsonNode representation of the input OAS document.
 * 
 * @param location the URL of the OAS document.
 * @param auths the list of authorization values to access the remote URL.
 * 
 * @throws java.lang.Exception if an error occurs while retrieving the OpenAPI document.
 * 
 * @return A JsonNode representation of the input OAS document.
 */
public static JsonNode readWithInfo(String location, List<AuthorizationValue> auths) throws Exception {
    String data;
    location = location.replaceAll("\\\\","/");
    if (location.toLowerCase(Locale.ROOT).startsWith("http")) {
        data = RemoteUrl.urlToString(location, auths);
    } else {
        final String fileScheme = "file:";
        Path path;
        if (location.toLowerCase(Locale.ROOT).startsWith(fileScheme)) {
            path = Paths.get(URI.create(location));
        } else {
            path = Paths.get(location);
        }
        if (Files.exists(path)) {
            data = FileUtils.readFileToString(path.toFile(), "UTF-8");
        } else {
            data = ClasspathHelper.loadFileFromClasspath(location);
        }
    }
    return getRightMapper(data).readTree(data);
}
 
Example #12
Source File: RelativeReferenceTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue213() throws Exception {
    new Expectations() {{
        RemoteUrl.urlToString("http://foo.bar.com/swagger.json", Arrays.asList(new AuthorizationValue[]{}));
        times = 1;
        result = spec;

        RemoteUrl.urlToString("http://foo.bar.com/path/samplePath.yaml", Arrays.asList(new AuthorizationValue[]{}));
        times = 1;
        result = samplePath;
    }};


    OpenAPI swagger = new OpenAPIV3Parser().read("http://foo.bar.com/swagger.json");
    assertNotNull(swagger);
    assertNotNull(swagger.getPaths().get("/samplePath"));

    assertNotNull(swagger.getPaths().get("/samplePath").getGet());
    assertNotNull(swagger.getPaths().get("/samplePath").getGet().getRequestBody());
    RequestBody body = swagger.getPaths().get("/samplePath").getGet().getRequestBody();
    assertNotNull(body.getContent().get("application/json").getSchema());
}
 
Example #13
Source File: RemoteUrlTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthorizationHeaderWithNonMatchingUrl() throws Exception {

    final String expectedBody = setupStub();

    final String headerValue = "foobar";
    String authorization = "Authorization";
    final AuthorizationValue authorizationValue = new AuthorizationValue(authorization,
        headerValue, "header", u -> false);
    final String actualBody = RemoteUrl.urlToString(getUrl(), Arrays.asList(authorizationValue));

    assertEquals(actualBody, expectedBody);

    List<LoggedRequest> requests = WireMock.findAll(getRequestedFor(urlEqualTo("/v2/pet/1")));
    assertEquals(1, requests.size());
    assertFalse(requests.get(0).containsHeader(authorization));
}
 
Example #14
Source File: ExtensionsUtilTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void testArrayParam(@Injectable final List<AuthorizationValue> auths) throws IOException{
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveFully(true);

    String pathFile = FileUtils.readFileToString(new File("./src/test/swagger/oas3.yaml"),"UTF-8");
    SwaggerParseResult result = new OpenAPIV3Parser().readContents(pathFile, auths, options);
    OpenAPI openAPI = result.getOpenAPI();

    new ExtensionsUtil().addExtensions(openAPI);

    Operation operation = openAPI.getPaths().get("/pet").getPost();
    RequestBody body = operation.getRequestBody();

    assertNotNull(body);
    Schema model = body.getContent().get("application/json").getSchema();
    assertEquals("object", model.getType());
}
 
Example #15
Source File: ExtensionsUtilTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void testResolveRequestBody(@Injectable final List<AuthorizationValue> auths) throws Exception {
    ReflectionUtils utils = new ReflectionUtils();
    utils.setConfiguration( Configuration.read("src/test/config/config1.yaml"));

    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveFully(true);


    String pathFile = FileUtils.readFileToString(new File("./src/test/swagger/oas3.yaml"),"UTF-8");
    SwaggerParseResult result = new OpenAPIV3Parser().readContents(pathFile, auths, options);
    OpenAPI openAPI = result.getOpenAPI();

    new ExtensionsUtil().addExtensions(openAPI);

    Operation operation = openAPI.getPaths().get("/mappedWithDefinedModel/{id}").getPost();
    RequestBody body = operation.getRequestBody();

    for (String mediaType: body.getContent().keySet()) {
        JavaType jt = utils.getTypeFromRequestBody(body, mediaType , openAPI.getComponents().getSchemas())[0];
        assertEquals(jt.getRawClass(), Dog.class);
    }
}
 
Example #16
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testComposedSchemaAdjacent(@Injectable final List<AuthorizationValue> auths) throws Exception {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveFully(true);
    OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/resources/composedSchemaRef.yaml", auths, options);

    Assert.assertNotNull(openAPI);

    Assert.assertTrue(openAPI.getComponents().getSchemas().size() == 5);
    Schema schema = openAPI.getPaths().get("/path").getGet().getResponses().get("200").getContent().get("application/json").getSchema();
    Assert.assertTrue(schema.getProperties().size() == 4);

    ComposedSchema schemaOneOf = (ComposedSchema) openAPI.getPaths().get("/oneOf").getGet().getResponses().get("200").getContent().get("application/json").getSchema();
    Assert.assertTrue(schemaOneOf.getOneOf().size() == 3);

    ComposedSchema schemaAnyOf = (ComposedSchema) openAPI.getPaths().get("/anyOf").getGet().getResponses().get("200").getContent().get("application/json").getSchema();
    Assert.assertTrue(schemaAnyOf.getAnyOf().size() == 3);

}
 
Example #17
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testAlmostEmpty(@Injectable List<AuthorizationValue> auths) {
    String yaml = "openapi: '3.0.1'\n" +
                  "new: extra";

    OpenAPIV3Parser parser = new OpenAPIV3Parser();

    ParseOptions options = new ParseOptions();
    options.setResolve(true);

    SwaggerParseResult result = parser.readContents(yaml,auths,options);
    List<String> messageList = result.getMessages();
    Set<String> messages = new HashSet<>(messageList);

    assertTrue(messages.contains("attribute info is missing"));
    assertTrue(messages.contains("attribute paths is missing"));
    assertTrue(messages.contains("attribute new is unexpected"));
}
 
Example #18
Source File: SwaggerConverter.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
private SwaggerParseResult readResult(SwaggerDeserializationResult result, List<AuthorizationValue> auth, ParseOptions options) {
    SwaggerParseResult out = convert(result);
    if (out != null && options != null && options.isFlatten()) {
        try {
            SwaggerParseResult resultV3 = new OpenAPIV3Parser().readContents(Yaml.pretty(out.getOpenAPI()), auth, options);
            out.setOpenAPI(resultV3.getOpenAPI());
            if (out.getMessages() != null) {
                out.getMessages().addAll(resultV3.getMessages());
                out.messages(out.getMessages().stream()
                        .distinct()
                        .collect(Collectors.toList()));
            } else {
                out.messages(resultV3.getMessages());
            }
        } catch (Exception ignore) {}
    }
    return out;
}
 
Example #19
Source File: OpenAPI3Examples.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
public void constructRouterFactoryFromUrlWithAuthenticationHeader(Vertx vertx) {
  AuthorizationValue authorizationValue = new AuthorizationValue()
    .type("header")
    .keyName("Authorization")
    .value("Bearer xx.yy.zz");
  List<JsonObject> authorizations = Collections.singletonList(JsonObject.mapFrom(authorizationValue));
  OpenAPI3RouterFactory.create(
    vertx,
    "https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v3.0/petstore.yaml",
    authorizations,
    ar -> {
      if (ar.succeeded()) {
        // Spec loaded with success
        OpenAPI3RouterFactory routerFactory = ar.result();
      } else {
        // Something went wrong during router factory initialization
        Throwable exception = ar.cause();
      }
    });
}
 
Example #20
Source File: RefUtilsTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadExternalRef_RelativeFileFormat(@Injectable final List<AuthorizationValue> auths,
                                                   @Mocked IOUtils ioUtils,
                                                   @Mocked Files files,
                                                   @Injectable final Path parentDirectory,
                                                   @Injectable final Path pathToUse
) throws Exception {
    final String filePath = "file.json";
    File file = tempFolder.newFile(filePath);
    final String expectedResult = "really good json";

    setupRelativeFileExpectations(parentDirectory, pathToUse, file, filePath);

    new StrictExpectations() {{
        IOUtils.toString((FileInputStream) any, UTF_8);
        times = 1;
        result = expectedResult;

    }};

    String actualResult = RefUtils.readExternalRef(filePath, RefFormat.RELATIVE, auths, parentDirectory);
    assertEquals(expectedResult, actualResult);

}
 
Example #21
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void resolveComposedSchema(@Injectable final List<AuthorizationValue> auths){

    ParseOptions options = new ParseOptions();
    options.setResolveCombinators(false);
    options.setResolveFully(true);
    OpenAPI openAPI = new OpenAPIV3Parser().readLocation("src/test/resources/oneof-anyof.yaml",auths,options).getOpenAPI();


    assertTrue(openAPI.getPaths().get("/mixed-array").getGet().getResponses().get("200").getContent().get("application/json").getSchema() instanceof ArraySchema);
    ArraySchema arraySchema = (ArraySchema) openAPI.getPaths().get("/mixed-array").getGet().getResponses().get("200").getContent().get("application/json").getSchema();
    assertTrue(arraySchema.getItems() instanceof ComposedSchema);
    ComposedSchema oneOf = (ComposedSchema) arraySchema.getItems();
    assertEquals(oneOf.getOneOf().get(0).getType(), "string");

    //System.out.println(openAPI.getPaths().get("/oneOf").getGet().getResponses().get("200").getContent().get("application/json").getSchema() );
    assertTrue(openAPI.getPaths().get("/oneOf").getGet().getResponses().get("200").getContent().get("application/json").getSchema() instanceof ComposedSchema);
    ComposedSchema oneOfSchema = (ComposedSchema) openAPI.getPaths().get("/oneOf").getGet().getResponses().get("200").getContent().get("application/json").getSchema();
    assertEquals(oneOfSchema.getOneOf().get(0).getType(), "object");

}
 
Example #22
Source File: OpenAPIV3Parser.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
public OpenAPI read(String location, List<AuthorizationValue> auths, ParseOptions resolve) {
    if (location == null) {
        return null;
    }

    final List<SwaggerParserExtension> parserExtensions = getExtensions();
    SwaggerParseResult parsed;
    for (SwaggerParserExtension extension : parserExtensions) {
        parsed = extension.readLocation(location, auths, resolve);
        for (String message : parsed.getMessages()) {
            LOGGER.info("{}: {}", extension, message);
        }
        final OpenAPI result = parsed.getOpenAPI();
        if (result != null) {
            return result;
        }
    }
    return null;
}
 
Example #23
Source File: OpenAPIV3Parser.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
private SwaggerParseResult readContents(String swaggerAsString, List<AuthorizationValue> auth, ParseOptions options,
                                        String location) {
    if (swaggerAsString == null || swaggerAsString.trim().isEmpty()) {
        return SwaggerParseResult.ofError("Null or empty definition");
    }

    try {
        final ObjectMapper mapper = getRightMapper(swaggerAsString);
        final JsonNode rootNode = mapper.readTree(swaggerAsString);
        final SwaggerParseResult result = parseJsonNode(location, rootNode);
        return resolve(result, auth, options, location);
    } catch (JsonProcessingException e) {
        LOGGER.warn("Exception while parsing:", e);
        final String message = getParseErrorMessage(e.getOriginalMessage(), location);
        return SwaggerParseResult.ofError(message);
    }
}
 
Example #24
Source File: RefUtils.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
public static String readExternalClasspathRef(String file, RefFormat refFormat, List<AuthorizationValue> auths,
                                              String rootPath) {

    if (!RefUtils.isAnExternalRefFormat(refFormat)) {
        throw new RuntimeException("Ref is not external");
    }

    String result;

    try {
        if (refFormat == RefFormat.URL) {
            result = RemoteUrl.urlToString(file, auths);
        } else {
            //its assumed to be a relative ref
            String pathRef = ExternalRefProcessor.join(rootPath, file);

            result = ClasspathHelper.loadFileFromClasspath(pathRef);
        }
    } catch (Exception e) {
        throw new RuntimeException("Unable to load " + refFormat + " ref: " + file, e);
    }

    return result;

}
 
Example #25
Source File: OpenAPIV3Parser.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
private SwaggerParseResult resolve(SwaggerParseResult result, List<AuthorizationValue> auth, ParseOptions options,
        String location) {
    try {
        if (options != null) {
            if (options.isResolve() || options.isResolveFully()) {
                result.setOpenAPI(new OpenAPIResolver(result.getOpenAPI(), emptyListIfNull(auth),
                        location).resolve());
                if (options.isResolveFully()) {
                    new ResolverFully(options.isResolveCombinators()).resolveFully(result.getOpenAPI());
                }
            }
            if (options.isFlatten()) {
                final InlineModelResolver inlineModelResolver =
                        new InlineModelResolver(options.isFlattenComposedSchemas(),
                                options.isCamelCaseFlattenNaming(), options.isSkipMatches());
                inlineModelResolver.flatten(result.getOpenAPI());
            }
        }
    } catch (Exception e) {
        LOGGER.warn("Exception while resolving:", e);
        result.setMessages(Collections.singletonList(e.getMessage()));
    }
    return result;
}
 
Example #26
Source File: OpenAPIV3Parser.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
/**
 * Transform the swagger-model version of AuthorizationValue into a parser-specific one, to avoid
 * dependencies across extensions
 *
 * @param input
 * @return
 */
@Deprecated
protected List<AuthorizationValue> transform(List<AuthorizationValue> input) {
    if(input == null) {
        return null;
    }

    List<AuthorizationValue> output = new ArrayList<>();

    for(AuthorizationValue value : input) {
        AuthorizationValue v = new AuthorizationValue();

        v.setKeyName(value.getKeyName());
        v.setValue(value.getValue());
        v.setType(value.getType());
        v.setUrlMatcher(value.getUrlMatcher());

        output.add(v);
    }

    return output;
}
 
Example #27
Source File: ResolverCache.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
public ResolverCache(OpenAPI openApi, List<AuthorizationValue> auths, String parentFileLocation) {
    this.openApi = openApi;
    this.auths = auths;
    this.rootPath = parentFileLocation;

    if(parentFileLocation != null) {
        if(parentFileLocation.startsWith("http")) {
            parentDirectory = null;
        } else {
            parentDirectory = PathUtils.getParentDirectoryOfFile(parentFileLocation);
        }
    } else {
        File file = new File(".");
        parentDirectory = file.toPath();
    }

}
 
Example #28
Source File: RemoteUrlTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthorizationHeaderWithMatchingUrl() throws Exception {

    final String expectedBody = setupStub();

    final String headerName = "Authorization";
    final String headerValue = "foobar";
    final AuthorizationValue authorizationValue = new AuthorizationValue(headerName, headerValue, "header",
        url -> url.toString().startsWith("http://localhost"));
    final String actualBody = RemoteUrl.urlToString(getUrl(), Arrays.asList(authorizationValue));

    assertEquals(actualBody, expectedBody);

    verify(getRequestedFor(urlEqualTo("/v2/pet/1"))
                    .withHeader("Accept", equalTo(EXPECTED_ACCEPTS_HEADER))
                    .withHeader(headerName, equalTo(headerValue))
    );
}
 
Example #29
Source File: RemoteUrl.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
private static void appendValue(URL url, AuthorizationValue value, Collection<AuthorizationValue> to) {
    if (value instanceof ManagedValue) {
        if (!((ManagedValue) value).process(url)) {
            return;
        }
    }
    to.add(value);
}
 
Example #30
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testComposedRefResolvingIssue628(@Injectable final List<AuthorizationValue> auths) throws Exception {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/resources/composedSchemaRef.yaml", auths, options);

    Assert.assertNotNull(openAPI);

    Assert.assertTrue(openAPI.getComponents().getSchemas().size() == 5);
    Assert.assertNotNull(openAPI.getComponents().getSchemas().get("Cat"));
    Assert.assertNotNull(openAPI.getComponents().getSchemas().get("Dog"));
    Assert.assertNotNull(openAPI.getComponents().getSchemas().get("Pet"));
    Assert.assertNotNull(openAPI.getComponents().getSchemas().get("Lion"));
    Assert.assertNotNull(openAPI.getComponents().getSchemas().get("Bear"));
}