io.swagger.v3.oas.models.servers.Server Java Examples

The following examples show how to use io.swagger.v3.oas.models.servers.Server. 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: SerializerUtilsTest.java    From openapi-generator with Apache License 2.0 7 votes vote down vote up
private OpenAPI createCompleteExample() {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setInfo(new Info().title("Some title").description("Some description"));
    openAPI.setExternalDocs(new ExternalDocumentation().url("http://abcdef.com").description("a-description"));
    openAPI.setServers(Arrays.asList(
            new Server().url("http://www.server1.com").description("first server"),
            new Server().url("http://www.server2.com").description("second server")
        ));
    openAPI.setSecurity(Arrays.asList(
            new SecurityRequirement().addList("some_auth", Arrays.asList("write", "read"))
        ));
    openAPI.setTags(Arrays.asList(
            new Tag().name("tag1").description("some 1 description"),
            new Tag().name("tag2").description("some 2 description"),
            new Tag().name("tag3").description("some 3 description")
        ));
    openAPI.path("/ping/pong", new PathItem().get(new Operation()
            .description("Some description")
            .operationId("pingOp")
            .responses(new ApiResponses().addApiResponse("200", new ApiResponse().description("Ok")))));
    openAPI.components(new Components().addSchemas("SomeObject", new ObjectSchema().description("An Obj").addProperties("id", new StringSchema())));
    openAPI.setExtensions(new LinkedHashMap<>()); // required because swagger-core is using HashMap instead of LinkedHashMap internally.
    openAPI.addExtension("x-custom", "value1");
    openAPI.addExtension("x-other", "value2");
    return openAPI;
}
 
Example #2
Source File: OpenAPIDeserializer.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
public List<Server> getServersList(ArrayNode obj, String location, ParseResult result, String path) {

        List<Server> servers = new ArrayList<>();
        if (obj == null) {
            return null;

        }
        for (JsonNode item : obj) {
            if (item.getNodeType().equals(JsonNodeType.OBJECT)) {
                Server server = getServer((ObjectNode) item, location, result, path);
                if (server != null) {
                    servers.add(server);
                }else{
                    Server defaultServer = new Server();
                    defaultServer.setUrl("/");
                    servers.add(defaultServer);
                }
            }
        }
        return servers;
    }
 
Example #3
Source File: AbstractApexCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List<Server> servers) {

    CodegenOperation op = super.fromOperation(
            path, httpMethod, operation, null);

    if (op.getHasExamples()) {
        // prepare examples for Apex test classes
        ApiResponse apiResponse = findMethodResponse(operation.getResponses());
        final Schema responseSchema = ModelUtils.getSchemaFromResponse(apiResponse);
        String deserializedExample = toExampleValue(responseSchema);
        for (Map<String, String> example : op.examples) {
            example.put("example", escapeText(example.get("example")));
            example.put("deserializedExample", deserializedExample);
        }
    }

    return op;
}
 
Example #4
Source File: OpenApi30SpecificationGenerator.java    From restdocs-spec with Apache License 2.0 6 votes vote down vote up
@Override
public String generate(ApiDetails details, List<ResourceModel> models) {
  List<Server> servers = new ArrayList<>();
  for (String scheme : details.getSchemes()) {
    try {
      URL url = new URL(scheme, details.getHost(), details.getBasePath() == null ? "" : details.getBasePath());
      servers.add(new Server().url(url.toString()));
    } catch (MalformedURLException e) {
    	throw new IllegalArgumentException("Invalid server URL", e);
    }
  }
  return generator.generateAndSerialize(
          models,
          servers,
          details.getName(),
          details.getDescription(),
          SpecificationGeneratorUtils.createTagDescriptionsMap(details.getTags()),
          details.getVersion(),
          SpecificationGeneratorUtils.createOauth2Configuration(details.getAuthConfig()),
          details.getFormat().name().toLowerCase()
  );
}
 
Example #5
Source File: OpenAPIBuilder.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Build open api with open api definition.
 *
 * @param openAPI the open api
 * @param apiDef the api def
 */
private void buildOpenAPIWithOpenAPIDefinition(OpenAPI openAPI, OpenAPIDefinition apiDef) {
	// info
	AnnotationsUtils.getInfo(apiDef.info()).map(this::resolveProperties).ifPresent(openAPI::setInfo);
	// OpenApiDefinition security requirements
	securityParser.getSecurityRequirements(apiDef.security()).ifPresent(openAPI::setSecurity);
	// OpenApiDefinition external docs
	AnnotationsUtils.getExternalDocumentation(apiDef.externalDocs()).ifPresent(openAPI::setExternalDocs);
	// OpenApiDefinition tags
	AnnotationsUtils.getTags(apiDef.tags(), false).ifPresent(tags -> openAPI.setTags(new ArrayList<>(tags)));
	// OpenApiDefinition servers
	Optional<List<Server>> optionalServers = AnnotationsUtils.getServers(apiDef.servers());
	if (optionalServers.isPresent()) {
		openAPI.setServers(optionalServers.get());
		this.isServersPresent = true;
	}
	// OpenApiDefinition extensions
	if (apiDef.extensions().length > 0) {
		openAPI.setExtensions(AnnotationsUtils.getExtensions(apiDef.extensions()));
	}
}
 
Example #6
Source File: CppPistacheServerCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List<Server> servers) {
    CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers);

    if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
        ApiResponse apiResponse = findMethodResponse(operation.getResponses());

        if (apiResponse != null) {
            Schema response = ModelUtils.getSchemaFromResponse(apiResponse);
            if (response != null) {
                CodegenProperty cm = fromProperty("response", response);
                op.vendorExtensions.put("x-codegen-response", cm);
                if ("HttpContent".equals(cm.dataType)) {
                    op.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
                }
            }
        }
    }

    String pathForPistache = path.replaceAll("\\{(.*?)}", ":$1");
    op.vendorExtensions.put("x-codegen-pistache-path", pathForPistache);

    return op;
}
 
Example #7
Source File: InputModeller.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Returns default URL for the given server.
 */
static String getServerUrl( Server server)
  {
  StringBuilder url = new StringBuilder();
  Matcher segmentMatcher = uriSegmentPattern_.matcher( server.getUrl());
  while( segmentMatcher.find())
    {
    String constantSegment = segmentMatcher.group(1);
    url.append(
      constantSegment != null
      ? constantSegment
      : getServerVarValue( server, segmentMatcher.group(2)));
    }
  
  return url.toString();
  }
 
Example #8
Source File: OpenApiObjectGenerator.java    From flow with Apache License 2.0 6 votes vote down vote up
private OpenAPI createBasicModel() {
    OpenAPI openAPI = new OpenAPI();

    Info info = new Info();
    info.setTitle(configuration.getApplicationTitle());
    info.setVersion(configuration.getApplicationApiVersion());
    openAPI.setInfo(info);

    Paths paths = new Paths();
    openAPI.setPaths(paths);

    Server server = new Server();
    server.setUrl(configuration.getServerUrl());
    server.setDescription(configuration.getServerDescription());
    openAPI.setServers(Collections.singletonList(server));
    Components components = new Components();
    SecurityScheme vaadinConnectOAuth2Scheme = new SecurityScheme()
            .type(SecurityScheme.Type.OAUTH2)
            .flows(new OAuthFlows().password(new OAuthFlow()
                    .tokenUrl(VAADIN_CONNECT_OAUTH2_TOKEN_URL)
                    .scopes(new Scopes())));
    components.addSecuritySchemes(VAADIN_CONNECT_OAUTH2_SECURITY_SCHEME,
            vaadinConnectOAuth2Scheme);
    openAPI.components(components);
    return openAPI;
}
 
Example #9
Source File: CppRestSdkClientCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List<Server> servers) {
    CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers);

    if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
        ApiResponse methodResponse = findMethodResponse(operation.getResponses());

        if (methodResponse != null) {
            Schema response = ModelUtils.getSchemaFromResponse(methodResponse);
            response = ModelUtils.unaliasSchema(this.openAPI, response, importMapping);
            if (response != null) {
                CodegenProperty cm = fromProperty("response", response);
                op.vendorExtensions.put("x-codegen-response", cm);
                if ("std::shared_ptr<HttpContent>".equals(cm.dataType)) {
                    op.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
                }
            }
        }
    }

    return op;
}
 
Example #10
Source File: EntrypointsOAITransformer.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@Override
public void transform(OAIDescriptor descriptor) {
    if (asBoolean(SwaggerProperties.ENTRYPOINTS_AS_SERVERS) && entrypoints != null && ! entrypoints.isEmpty()) {
        List<Server> servers = new ArrayList<>();

        // Add server according to entrypoints
        entrypoints.forEach(entrypoint -> {
            Server server = new Server();

            if (getProperty(SwaggerProperties.ENTRYPOINT_AS_BASEPATH) == null
                    || getProperty(SwaggerProperties.ENTRYPOINT_AS_BASEPATH).isEmpty()
                    || asBoolean(SwaggerProperties.ENTRYPOINT_AS_BASEPATH)) {
                server.setUrl(entrypoint.getTarget());
            } else {
                URI target = URI.create(entrypoint.getTarget());
                server.setUrl(entrypoint.getTarget().substring(0, entrypoint.getTarget().indexOf(target.getRawPath())));
            }

            servers.add(server);

        });

        descriptor.getSpecification().setServers(servers);
    }
}
 
Example #11
Source File: OAIToAPIConverter.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
private List<String> mapServersToEndpoint(List<Server> servers) {
    List<String> endpoints = new ArrayList<>();
    for (Server server : servers) {
        ServerVariables serverVariables = server.getVariables();
        String serverUrl = server.getUrl();
        if (CollectionUtils.isEmpty(serverVariables)) {
            endpoints.add(serverUrl);
        } else {
            List<String> evaluatedUrls = Collections.singletonList(serverUrl);
            for (Map.Entry<String, ServerVariable> serverVar : serverVariables.entrySet()) {
                evaluatedUrls = evaluateServerUrlsForOneVar(serverVar.getKey(), serverVar.getValue(),
                        evaluatedUrls);
            }
            endpoints.addAll(evaluatedUrls);
        }
    }
    return endpoints;
}
 
Example #12
Source File: OpenApiCustomizer.java    From cxf with Apache License 2.0 6 votes vote down vote up
public OpenAPIConfiguration customize(final OpenAPIConfiguration configuration) {
    if (configuration == null) {
        return configuration;
    }

    if (dynamicBasePath) {
        final MessageContext ctx = createMessageContext();

        // If the JAX-RS application with custom path is defined, it might be present twice, in the 
        // request URI as well as in each resource operation URI. To properly represent server URL, 
        // the application path should be removed from it.
        final String url = StringUtils.removeEnd(
                StringUtils.substringBeforeLast(ctx.getUriInfo().getRequestUri().toString(), "/"),
                applicationPath);

        final Collection<Server> servers = configuration.getOpenAPI().getServers();
        if (servers == null || servers.stream().noneMatch(s -> s.getUrl().equalsIgnoreCase(url))) {
            configuration.getOpenAPI().setServers(Collections.singletonList(new Server().url(url)));
        }
    }

    return configuration;
}
 
Example #13
Source File: JavaJerseyServerCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testInitialConfigValues() throws Exception {
    codegen.processOpts();

    OpenAPI openAPI = new OpenAPI();
    openAPI.addServersItem(new Server().url("https://api.abcde.xy:8082/v2"));
    codegen.preprocessOpenAPI(openAPI);

    Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE);
    Assert.assertEquals(codegen.isHideGenerationTimestamp(), false);
    Assert.assertEquals(codegen.modelPackage(), "org.openapitools.model");
    Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "org.openapitools.model");
    Assert.assertEquals(codegen.apiPackage(), "org.openapitools.api");
    Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "org.openapitools.api");
    Assert.assertEquals(codegen.getInvokerPackage(), "org.openapitools.api");
    Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "org.openapitools.api");
    Assert.assertEquals(codegen.additionalProperties().get(JavaJerseyServerCodegen.SERVER_PORT), "8082");
}
 
Example #14
Source File: JavaJerseyServerCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testAdditionalPropertiesPutForConfigValues() throws Exception {
    codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true");
    codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.mmmmm.model");
    codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.yyyyy.aaaaa.api");
    codegen.additionalProperties().put(CodegenConstants.INVOKER_PACKAGE, "xyz.yyyyy.iiii.invoker");
    codegen.additionalProperties().put("serverPort", "8088");
    codegen.processOpts();

    OpenAPI openAPI = new OpenAPI();
    openAPI.addServersItem(new Server().url("https://api.abcde.xy:8082/v2"));
    codegen.preprocessOpenAPI(openAPI);

    Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE);
    Assert.assertEquals(codegen.isHideGenerationTimestamp(), true);
    Assert.assertEquals(codegen.modelPackage(), "xyz.yyyyy.mmmmm.model");
    Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "xyz.yyyyy.mmmmm.model");
    Assert.assertEquals(codegen.apiPackage(), "xyz.yyyyy.aaaaa.api");
    Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "xyz.yyyyy.aaaaa.api");
    Assert.assertEquals(codegen.getInvokerPackage(), "xyz.yyyyy.iiii.invoker");
    Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "xyz.yyyyy.iiii.invoker");
    Assert.assertEquals(codegen.additionalProperties().get(JavaJerseyServerCodegen.SERVER_PORT), "8088");
}
 
Example #15
Source File: OpenAPICodegenUtils.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
/**
 * Open API server object can have server templating. Ex: https://{customerId}.saas-app.com:{port}/v2.
 * When adding the back end url this method will replace the template values with the default value.
 *
 * @param server  {@link Server} object of the open API definition
 * @return templated server url replaced with default values
 */
private static String replaceOpenAPIServerTemplate(Server server) {
    //server url templating can have urls similar to 'https://{customerId}.saas-app.com:{port}/v2'
    String url = server.getUrl();
    Pattern serverTemplate = Pattern.compile("\\{.*?}");
    Matcher matcher = serverTemplate.matcher(url);
    while (matcher.find()) {
        if (server.getVariables() != null && server.getVariables()
                .containsKey(matcher.group(0).substring(1, matcher.group(0).length() - 1))) {
            String defaultValue = server.getVariables()
                    .get(matcher.group(0).substring(1, matcher.group(0).length() - 1)).getDefault();
            url = url.replaceAll("\\" + matcher.group(0), defaultValue);
        } else {
            outStream.println(
                    CliConstants.WARN_LOG_PATTERN + "Open API server url templating is used for the url : " + url
                            + ". But default values is not provided for the variable '" + matcher.group(0)
                            + "'. Hence correct url will not be resolved during the runtime "
                            + "unless url is overridden during the runtime");
        }
    }
    return url;
}
 
Example #16
Source File: AbstractApiDocServiceTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
private OpenAPI getDummyOpenApiObject(List<Server> servers) {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setPaths(new Paths());
    openAPI.setTags(new ArrayList<>());
    openAPI.setOpenapi("3.0.0");
    openAPI.setServers(servers);

    Info info = new Info();
    info.setTitle("API Catalog");
    info.setDescription("REST API for the API Catalog service which is a component of the API Mediation Layer. Use this API to retrieve information regarding catalog dashboard tiles, tile contents and its status, API documentation and status for the registered services.");
    info.setVersion("1.0.0");
    openAPI.setInfo(info);

    Tag tag = new Tag();
    tag.setName("API Catalog");
    tag.setDescription("Current state information");
    openAPI.getTags().add(tag);

    openAPI.getPaths().put("/api1", new PathItem());
    openAPI.getPaths().put("/api2", new PathItem());
    return openAPI;
}
 
Example #17
Source File: JavaJAXRSSpecServerCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testInitialConfigValues() throws Exception {
    final JavaJAXRSSpecServerCodegen codegen = new JavaJAXRSSpecServerCodegen();
    codegen.processOpts();

    OpenAPI openAPI = new OpenAPI();
    openAPI.addServersItem(new Server().url("https://api.abcde.xy:8082/v2"));
    codegen.preprocessOpenAPI(openAPI);

    Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE);
    Assert.assertEquals(codegen.isHideGenerationTimestamp(), false);
    Assert.assertEquals(codegen.modelPackage(), "org.openapitools.model");
    Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "org.openapitools.model");
    Assert.assertEquals(codegen.apiPackage(), "org.openapitools.api");
    Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "org.openapitools.api");
    Assert.assertEquals(codegen.getInvokerPackage(), "org.openapitools.api");
    Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "org.openapitools.api");
    Assert.assertEquals(codegen.additionalProperties().get(JavaJAXRSSpecServerCodegen.SERVER_PORT), "8082");
    Assert.assertEquals(codegen.getOpenApiSpecFileLocation(), "src/main/openapi/openapi.yaml");
    Assert.assertEquals(codegen.additionalProperties().get(JavaJAXRSSpecServerCodegen.OPEN_API_SPEC_FILE_LOCATION), "src/main/openapi/openapi.yaml");
}
 
Example #18
Source File: URLPathUtilsTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testSanitizeUrl() {
    String[][] testData = {
        { "https://abc1.xyz:9999/some/path", "https://abc1.xyz:9999/some/path" },
        { "HTTPS://abc2.xyz:9999/some/path", "https://abc2.xyz:9999/some/path" },
        { "http://abc3.xyz:9999/some/path", "http://abc3.xyz:9999/some/path" },
        { "HTTP://abc4.xyz:9999/some/path", "http://abc4.xyz:9999/some/path" },
        { "//abc5.xyz:9999/some/path", "http://abc5.xyz:9999/some/path" },
        { "abc6.xyz:9999/some/path", "http://abc6.xyz:9999/some/path" },
        { "localhost:9000/api", "http://localhost:9000/api" },
        { "/some/path", "http://localhost/some/path" } };

    for (String[] t:testData) {
        OpenAPI openAPI = new OpenAPI();
        openAPI.addServersItem(new Server().url(t[0]));

        Assert.assertEquals(URLPathUtils.getServerURL(openAPI, null).toString(), t[1]);
    }
}
 
Example #19
Source File: TestUtils.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
public static OpenAPI createOpenAPI() {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setComponents(new Components());
    openAPI.setPaths(new Paths());

    final Info info = new Info();
    info.setDescription("API under test");
    info.setVersion("1.0.7");
    info.setTitle("My title");
    openAPI.setInfo(info);

    final Server server = new Server();
    server.setUrl("https://localhost:9999/root");
    openAPI.setServers(Collections.singletonList(server));
    return openAPI;
}
 
Example #20
Source File: ApiDocV3Service.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
private Server getBestMatchingServer(List<Server> servers, ApiDocInfo apiDocInfo) {
    if (servers != null && !servers.isEmpty()) {
        for (Server server : servers) {
            String basePath = getBasePath(server.getUrl());
            RoutedService route = getRoutedServiceByApiInfo(apiDocInfo, basePath);
            if (route != null) {
                return server;
            }
        }
        return servers.get(0);
    }
    return null;
}
 
Example #21
Source File: SwaggerConverterUnitTest.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
@Test
public void
        shouldCreateUriBuildersFromServerWithAbsolutePathDefaultingToSchemeAndAuthorityOfDefinitionUrl() {
    // Given
    List<Server> servers = asList(server("/absolutePath"));
    UriBuilder defnUriBuilder = UriBuilder.parse("http://example.com/path");
    // When
    List<UriBuilder> uriBuilders = SwaggerConverter.createUriBuilders(servers, defnUriBuilder);
    // Then
    assertThat(uriBuilders, hasSize(1));
    assertUriBuilder(uriBuilders.get(0), "http", "example.com", "/absolutePath");
}
 
Example #22
Source File: SwaggerConverter.java    From raptor with Apache License 2.0 5 votes vote down vote up
/**
     * https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#server-object
     *
     * @return
     */
    protected Server getServer() {
        Server server = new Server();
        // TODO: 2018/5/18 现在还没有定义server

        server.url("http://localhost:8080");
        server.description("本地");
        // TODO: 2018/5/18 暂时不知道下面这个有什么用
//        server.variables(getServerVariables());
        return server;
    }
 
Example #23
Source File: SyncopeOpenApiCustomizer.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public OpenAPIConfiguration customize(final OpenAPIConfiguration configuration) {
    init();
    super.customize(configuration);

    MessageContext ctx = JAXRSUtils.createContextValue(
            JAXRSUtils.getCurrentMessage(), null, MessageContext.class);

    String url = StringUtils.substringBeforeLast(ctx.getUriInfo().getRequestUri().getRawPath(), "/");
    configuration.getOpenAPI().setServers(List.of(new Server().url(url)));

    return configuration;
}
 
Example #24
Source File: ServerUrlTest.java    From tcases with MIT License 5 votes vote down vote up
@Test
public void whenVarUndefined()
  {
  // Given...
  OpenAPI api = readApi( "server-url-test");
  Server server = api.getServers().get(3);

  expectFailure( IllegalStateException.class)
    .when( () -> getServerUrl( server))
    .then( failure -> assertThat( "Failure", failure.getMessage(), is( "No value defined for server variable=version")));
  }
 
Example #25
Source File: SwaggerConverterUnitTest.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateUriBuildersFromServerWithSchemeAuthorityAndNonEmptyPath() {
    // Given
    List<Server> servers = asList(server("http://example.com/path"));
    // When
    List<UriBuilder> uriBuilders =
            SwaggerConverter.createUriBuilders(servers, EMPTY_URI_BUILDER);
    // Then
    assertThat(uriBuilders, hasSize(1));
    assertUriBuilder(uriBuilders.get(0), "http", "example.com", "/path");
}
 
Example #26
Source File: SwaggerConverterUnitTest.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
@Test
public void
        shouldCreateUriBuildersFromServerWithJustRelativePathDefaultingToSchemeAndAuthorityOfDefinitionUrl() {
    // Given
    List<Server> servers = asList(server("relativePath"));
    UriBuilder defnUriBuilder = UriBuilder.parse("http://example.com");
    // When
    List<UriBuilder> uriBuilders = SwaggerConverter.createUriBuilders(servers, defnUriBuilder);
    // Then
    assertThat(uriBuilders, hasSize(1));
    assertUriBuilder(uriBuilders.get(0), "http", "example.com", "relativePath");
}
 
Example #27
Source File: ApiDocV3Service.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
private void updateServerUrl(OpenAPI openAPI, Server server, String basePath) {
    if (server != null) {
        server.setUrl(basePath);
        openAPI.setServers(Collections.singletonList(server));
    } else {
        openAPI.addServersItem(new Server().url(basePath));
    }
}
 
Example #28
Source File: SwaggerConverterUnitTest.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateUriBuildersFromServerWithVariables() {
    // Given
    Server server = server("{scheme}://example.com/");
    ServerVariables variables = new ServerVariables();
    variables.put("scheme", new ServerVariable()._default("http"));
    server.setVariables(variables);
    List<Server> servers = asList(server);
    // When
    List<UriBuilder> uriBuilders =
            SwaggerConverter.createUriBuilders(servers, EMPTY_URI_BUILDER);
    // Then
    assertThat(uriBuilders, hasSize(1));
    assertUriBuilder(uriBuilders.get(0), "http", "example.com", "/");
}
 
Example #29
Source File: SwaggerConverterUnitTest.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateUriBuildersFromServerWithSchemeAndAuthority() {
    // Given
    List<Server> servers = asList(server("http://example.com"));
    // When
    List<UriBuilder> uriBuilders =
            SwaggerConverter.createUriBuilders(servers, EMPTY_URI_BUILDER);
    // Then
    assertThat(uriBuilders, hasSize(1));
    assertUriBuilder(uriBuilders.get(0), "http", "example.com", "");
}
 
Example #30
Source File: SwaggerConverterUnitTest.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateUriBuildersFromServerWithJustRelativePath() {
    // Given
    List<Server> servers = asList(server("relativePath"));
    // When
    List<UriBuilder> uriBuilders =
            SwaggerConverter.createUriBuilders(servers, EMPTY_URI_BUILDER);
    // Then
    assertThat(uriBuilders, hasSize(1));
    assertUriBuilder(uriBuilders.get(0), null, null, "relativePath");
}