io.swagger.v3.oas.models.OpenAPI.getServers()方法的使用及代码示例

x33g5p2x  于2022-01-25 转载在 其他  
字(11.9k)|赞(0)|评价(0)|浏览(187)

本文整理了Java中io.swagger.v3.oas.models.OpenAPI.getServers()方法的一些代码示例,展示了OpenAPI.getServers()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。OpenAPI.getServers()方法的具体详情如下:
包路径:io.swagger.v3.oas.models.OpenAPI
类名称:OpenAPI
方法名:getServers

OpenAPI.getServers介绍

[英]Servers defined in the API
[中]API中定义的服务器

代码示例

代码示例来源:origin: swagger-api/swagger-core

clone.setExternalDocs(openAPI.getExternalDocs());
clone.setSecurity(openAPI.getSecurity());
clone.setServers(openAPI.getServers());
clone.tags(filteredOpenAPI.getTags() == null ? null : new ArrayList<>(openAPI.getTags()));

代码示例来源:origin: org.openapitools/openapi-generator

/**
 * Return the first complete URL from the OpenAPI specification
 * @param openAPI current OpenAPI specification
 * @return host
 */
public static String getHost(OpenAPI openAPI) {
  if (openAPI.getServers() != null && openAPI.getServers().size() > 0) {
    return sanitizeUrl(getServerURL(openAPI.getServers().get(0)).toString());
  }
  return LOCAL_HOST;
}

代码示例来源:origin: org.openapitools/openapi-generator

public static URL getServerURL(OpenAPI openAPI) {
  final List<Server> servers = openAPI.getServers();
  if (servers == null || servers.isEmpty()) {
    LOGGER.warn("Server information seems not defined in the spec. Default to {}.", LOCAL_HOST);
    return getDefaultUrl();
  }
  // TODO need a way to obtain all server URLs
  return getServerURL(servers.get(0));
}

代码示例来源:origin: com.atlassian.swagger/atlassian-swagger-doclet

private String getBaseUrlFromServerUrls(OpenAPI openAPI) {
  List<String> urls = openAPI
      .getServers()
      .stream()
      .map(server -> server.getUrl())

代码示例来源:origin: io.gravitee.management/gravitee-management-api-service

private OpenAPI transformV3(String content, Map<String, String> config) {
  SwaggerParseResult result = new OpenAPIV3Parser().readContents(content, null, null);
  if (result != null && config != null && config.get("tryItURL") != null) {
    URI newURI = URI.create(config.get("tryItURL"));
    result.getOpenAPI().getServers().forEach(server -> {
      try {
        server.setUrl(new URI(newURI.getScheme(),
            newURI.getUserInfo(),
            newURI.getHost(),
            newURI.getPort(),
            newURI.getPath(),
            newURI.getQuery(),
            newURI.getFragment()).toString());
      } catch (URISyntaxException e) {
        logger.error(e.getMessage(), e);
      }
    });
  }
  if (result != null) {
    return result.getOpenAPI();
  } else {
    return null;
  }
}

代码示例来源:origin: gravitee-io/gravitee-management-rest-api

private OpenAPI transformV3(String content, Map<String, String> config) {
  SwaggerParseResult result = new OpenAPIV3Parser().readContents(content, null, null);
  if (result != null && config != null && config.get("tryItURL") != null) {
    URI newURI = URI.create(config.get("tryItURL"));
    result.getOpenAPI().getServers().forEach(server -> {
      try {
        server.setUrl(new URI(newURI.getScheme(),
            newURI.getUserInfo(),
            newURI.getHost(),
            newURI.getPort(),
            newURI.getPath(),
            newURI.getQuery(),
            newURI.getFragment()).toString());
      } catch (URISyntaxException e) {
        logger.error(e.getMessage(), e);
      }
    });
  }
  if (result != null) {
    return result.getOpenAPI();
  } else {
    return null;
  }
}

代码示例来源:origin: apache/cxf

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;
}

代码示例来源:origin: com.atlassian.oai/swagger-request-validator-core

/**
 * A utility for finding the best fitting API path.
 *
 * @param api              the OpenAPI definition
 * @param basePathOverride (Optional) override for the base path defined in the OpenAPI specification.
 */
public ApiOperationResolver(final OpenAPI api, @Nullable final String basePathOverride) {
  apiPrefix = ofNullable(basePathOverride).orElse(getBasePathFrom(api.getServers()));
  final Paths apiPaths = ofNullable(api.getPaths()).orElse(new Paths());
  // normalise all API paths and group them by their number of parts
  apiPathsGroupedByNumberOfParts = apiPaths.keySet().stream()
      .map(p -> new ApiPathImpl(p, apiPrefix))
      .collect(groupingBy(NormalisedPath::numberOfParts));
  // create a operation mapping for the API path and HTTP method
  operations = HashBasedTable.create();
  apiPaths.forEach((pathKey, apiPath) ->
      apiPath.readOperationsMap().forEach((httpMethod, operation) ->
          operations.put(pathKey, httpMethod, operation))
  );
}

代码示例来源:origin: org.apache.cxf/cxf-rt-rs-service-description-openapi-v3

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;
}

代码示例来源:origin: com.atlassian.swagger/atlassian-swagger-doclet

private void fixPathAndServerUrls(OpenAPI openAPI) {
  String baseUrl = getBaseUrlFromServerUrls(openAPI);
  Map<String, PathItem> prefixedPaths = openAPI.getPaths().entrySet().stream()
      .map(entry -> new AbstractMap.SimpleEntry<>(baseUrl + entry.getKey(), entry.getValue()))
      .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
  Paths paths = new Paths();
  paths.putAll(prefixedPaths);
  openAPI.setPaths(paths);
  List<Server> servers = openAPI.getServers()
      .stream()
      .map(server -> {
        String url = server.getUrl();
        return new Server()
            .url(url.substring(0, url.indexOf(baseUrl) > 0 ? url.indexOf(baseUrl) : 0))
            .description(server.getDescription());
      })
      .collect(Collectors.toList());
  openAPI.setServers(servers);
}

代码示例来源:origin: org.openapitools/openapi-generator

List<CodegenServer> servers = config.fromServers(openAPI.getServers());
if (servers != null && !servers.isEmpty()) {
  bundle.put("servers", servers);

代码示例来源:origin: org.ballerinalang/swagger-to-ballerina-generator

/**
 * Extract endpoint information from OpenAPI server list.
 * If no servers were found, default {@link BallerinaServer} will be set as the server
 *
 * @param openAPI <code>OpenAPI</code> definition object with server details
 * @throws BallerinaOpenApiException on failure to parse {@code Server} list
 */
private void setServers(OpenAPI openAPI) throws BallerinaOpenApiException {
  this.servers = new ArrayList<>();
  List<Server> serverList = openAPI.getServers();
  if (serverList == null) {
    BallerinaServer server = new BallerinaServer().getDefaultValue();
    servers.add(server);
    return;
  }
  serverList.forEach(server -> {
    try {
      // Note that only one base path is allowed. Though we extract base path per each server
      // defined in the Open Api definition, only the base path of first server will be used
      // in ballerina code generation. Ballerina all endpoints to be in a single base path
      BallerinaServer balServer = new BallerinaServer().buildContext(server);
      servers.add(balServer);
    } catch (BallerinaOpenApiException e) {
      // Ignore the exception, set default value for this server and move forward
      servers.add(new BallerinaServer().getDefaultValue());
    }
  });
}

代码示例来源:origin: org.openapitools/openapi-generator

gen.writeObjectField("externalDocs", value.getExternalDocs());
if(value.getServers() != null) {
  gen.writeObjectField("servers", value.getServers());

代码示例来源:origin: gravitee-io/gravitee-management-rest-api

private NewApiEntity mapOpenApiToNewApi(SwaggerParseResult swagger) {
  if (swagger == null || swagger.getOpenAPI() == null || swagger.getOpenAPI().getInfo() == null) {
    return null;
  }
  NewApiEntity apiEntity = new NewApiEntity();
  apiEntity.setName(swagger.getOpenAPI().getInfo().getTitle());
  apiEntity.setDescription(swagger.getOpenAPI().getInfo().getDescription());
  apiEntity.setVersion(swagger.getOpenAPI().getInfo().getVersion());
  if (!swagger.getOpenAPI().getServers().isEmpty()) {
    apiEntity.setEndpoint(swagger.getOpenAPI().getServers().get(0).getUrl());
  }
  apiEntity.setPaths(new ArrayList<>(
      swagger.getOpenAPI().getPaths().keySet()
          .stream()
          .map(path -> path.replaceAll("\\{(.[^/]*)\\}", ":$1"))
          .collect(Collectors.toList())));
  return apiEntity;
}

代码示例来源:origin: io.gravitee.management/gravitee-management-api-service

private NewApiEntity mapOpenApiToNewApi(SwaggerParseResult swagger) {
  if (swagger == null || swagger.getOpenAPI() == null || swagger.getOpenAPI().getInfo() == null) {
    return null;
  }
  NewApiEntity apiEntity = new NewApiEntity();
  apiEntity.setName(swagger.getOpenAPI().getInfo().getTitle());
  apiEntity.setDescription(swagger.getOpenAPI().getInfo().getDescription());
  apiEntity.setVersion(swagger.getOpenAPI().getInfo().getVersion());
  if (!swagger.getOpenAPI().getServers().isEmpty()) {
    apiEntity.setEndpoint(swagger.getOpenAPI().getServers().get(0).getUrl());
  }
  apiEntity.setPaths(new ArrayList<>(
      swagger.getOpenAPI().getPaths().keySet()
          .stream()
          .map(path -> path.replaceAll("\\{(.[^/]*)\\}", ":$1"))
          .collect(Collectors.toList())));
  return apiEntity;
}

代码示例来源:origin: org.tomitribe/swagger2markup

@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
  OpenAPI swagger = params.swagger;
  List<Server> servers = swagger.getServers();
  markupDocBuilder.sectionTitleLevel(params.titleLevel, labels.getLabel(Labels.URI_SCHEME));
  MarkupDocBuilder paragraphBuilder = copyMarkupDocBuilder(markupDocBuilder);
  for (Server server : servers) {
    paragraphBuilder.italicText(labels.getLabel(Labels.SERVER)).textLine(COLON + server.getUrl());
  }
  markupDocBuilder.paragraph(paragraphBuilder.toString(), true);
  return markupDocBuilder;
}

代码示例来源:origin: io.swagger.core.v3/swagger-core

clone.setExternalDocs(openAPI.getExternalDocs());
clone.setSecurity(openAPI.getSecurity());
clone.setServers(openAPI.getServers());
clone.tags(filteredOpenAPI.getTags() == null ? null : new ArrayList<>(openAPI.getTags()));

代码示例来源:origin: org.geoserver.community/gs-wfs3

private void validateApi(OpenAPI api) {
  List<Server> servers = api.getServers();
  assertThat(servers, hasSize(1));
  assertThat(servers.get(0).getUrl(), equalTo("http://localhost:8080/geoserver/wfs3"));

代码示例来源:origin: com.atlassian.swagger/atlassian-swagger-doclet

public OpenAPI produce() {
  // Not exactly ideal, but not sure there's a better place to register this
  // Doing this here rather than in the constructor so that tests can modify options ...
  setupModelConverters();
  SwaggerTemplateReader swaggerTemplateReader = new SwaggerTemplateReader();
  //
  // we start with a template swagger model and then deviate from that
  OpenAPI swaggerModel = swaggerTemplateReader.readTemplate(docletOptions.getSwaggerTemplateFile());
  ParseContext parseCtx = new ParseContext(swaggerModel);
  ResourceClassFilter resourceClassFilter = new ResourceClassFilter(docletOptions);
  List<ClassDoc> resourceClasses = resourceClassFilter.filter(rootDoc);
  SwaggerParser swaggerParser = new SwaggerParser(docletOptions, parseCtx);
  swaggerModel = swaggerParser.parse(resourceClasses);
  swaggerModel = new NarrativeDocProducer(docletOptions).addNarrativeDocs(swaggerModel);
  SensibleSwaggerDefaults swaggerDefaults = new SensibleSwaggerDefaults();
  swaggerModel = swaggerDefaults.defaults(swaggerModel);
  swaggerModel = AtlassianPluginUtil.prefixPaths(swaggerModel, docletOptions.getPluginDescriptor());
  // Fix server and path urls. Have to do this because contract-testing-cli is not able to handle server urls when
  // validate swagger against pact files. see https://trello.com/c/rz9QV6uS
  if (swaggerModel.getServers() != null) {
    fixPathAndServerUrls(swaggerModel);
  }
  SchemaUtil.resetReadOnlyForComponentSchemas(swaggerModel);
  SwaggerSorter swaggerSorter = new SwaggerSorter();
  swaggerModel = swaggerSorter.sort(swaggerModel);
  return swaggerModel;
}

相关文章