Java源码示例:io.swagger.v3.oas.integration.api.OpenApiContext
示例1
private OpenAPI updateOpenApi() {
OpenApiContext openApiContext = OpenApiContextLocator.getInstance().getOpenApiContext(
OpenApiContext.OPENAPI_CONTEXT_ID_DEFAULT);
if (openApiContext instanceof GenericOpenApiContext) {
restfulServices = getAllRestfulService();
SwaggerConfiguration oasConfig = new SwaggerConfiguration().resourceClasses(restfulServices);
((GenericOpenApiContext) openApiContext).getOpenApiScanner().setConfiguration(oasConfig);
try {
((GenericOpenApiContext) openApiContext).setCacheTTL(0);
return openApiContext.read();
} finally {
((GenericOpenApiContext) openApiContext).setCacheTTL(-1);
}
} else {
return null;
}
}
示例2
private OpenAPI buildOpenApi() {
try {
restfulServices = getAllRestfulService();
SwaggerConfiguration oasConfig = new SwaggerConfiguration().resourceClasses(restfulServices);
OpenApiContext oac = new JaxrsOpenApiContextBuilder()
.openApiConfiguration(oasConfig)
.buildContext(true);
return oac.read();
} catch (OpenApiConfigurationException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
示例3
@GET
@Produces({MediaType.APPLICATION_JSON, "application/yaml"})
@Operation(hidden = true)
public Response getOpenApi(@Context HttpHeaders headers,
@Context UriInfo uriInfo,
@PathParam("type") String type) throws Exception {
String ctxId = app.getClass().getCanonicalName()
.concat("#").concat(String.valueOf(System.identityHashCode(app)));
OpenApiContext ctx = new JaxrsOpenApiContextBuilder<>()
.servletConfig(config)
.application(app)
.configLocation(configLocation)
.openApiConfiguration(openApiConfiguration)
.ctxId(ctxId)
.buildContext(true);
ctx.setOpenApiScanner(new JaxrsWhiteboardScanner(applicationClasses));
OpenAPI oas = ctx.read();
if (oas == null) {
return Response.status(404).build();
}
boolean pretty = Optional.ofNullable(ctx.getOpenApiConfiguration()).map(OpenAPIConfiguration::isPrettyPrint).orElse(Boolean.FALSE);
if (Optional.ofNullable(type).map(String::trim).map("yaml"::equalsIgnoreCase).orElse(Boolean.FALSE)) {
return Response.status(Response.Status.OK)
.entity(pretty ? Yaml.pretty(oas) : Yaml.mapper().writeValueAsString(oas))
.type("application/yaml")
.build();
} else {
return Response.status(Response.Status.OK)
.entity(pretty ? Json.pretty(oas) : Json.mapper().writeValueAsString(oas))
.type(MediaType.APPLICATION_JSON_TYPE)
.build();
}
}
示例4
@GET
@Produces({ MediaType.APPLICATION_JSON, "application/yaml" })
@Operation(hidden = true)
public Response getOpenApi(@Context Application app, @Context ServletConfig config,
@Context HttpHeaders headers, @Context UriInfo uriInfo, @PathParam("type") String type) throws Exception {
if (customizer != null) {
final OpenAPIConfiguration configuration = customizer.customize(getOpenApiConfiguration());
setOpenApiConfiguration(configuration);
// By default, the OpenApiContext instance is cached. It means that the configuration
// changes won't be taken into account (due to the deep copying rather than reference
// passing). In order to reflect any changes which customization may do, we have to
// update reader's configuration directly.
OpenApiContext ctx = getOpenApiContext(config);
if (ctx == null) {
// If there is no context associated with the servlet config, let us
// try to fallback to default one.
ctx = getOpenApiContext(null);
}
if (ctx instanceof GenericOpenApiContext<?>) {
((GenericOpenApiContext<?>) ctx).getOpenApiReader().setConfiguration(configuration);
final OpenAPI oas = ctx.read();
customizer.customize(oas);
if (!Objects.equals(configuration.getOpenAPI().getInfo(), oas.getInfo())) {
configuration.getOpenAPI().setInfo(oas.getInfo());
}
if (!Objects.equals(configuration.getOpenAPI().getComponents(), oas.getComponents())) {
configuration.getOpenAPI().setComponents(oas.getComponents());
}
if (!Objects.equals(configuration.getOpenAPI().getExternalDocs(), oas.getExternalDocs())) {
configuration.getOpenAPI().setExternalDocs(oas.getExternalDocs());
}
if (!Objects.equals(configuration.getOpenAPI().getPaths(), oas.getPaths())) {
configuration.getOpenAPI().setPaths(oas.getPaths());
}
if (!Objects.equals(configuration.getOpenAPI().getTags(), oas.getTags())) {
configuration.getOpenAPI().setTags(oas.getTags());
}
if (!Objects.equals(configuration.getOpenAPI().getExtensions(), oas.getExtensions())) {
configuration.getOpenAPI().setExtensions(oas.getExtensions());
}
}
}
return super.getOpenApi(headers, config, app, uriInfo, type);
}
示例5
private OpenApiContext getOpenApiContext(ServletConfig config) {
final String ctxId = ServletConfigContextUtils.getContextIdFromServletConfig(config);
return OpenApiContextLocator.getInstance().getOpenApiContext(ctxId);
}
示例6
@Override
public void initialize(Server server, Bus bus) {
final JAXRSServiceFactoryBean sfb = (JAXRSServiceFactoryBean)server
.getEndpoint()
.get(JAXRSServiceFactoryBean.class.getName());
final ServerProviderFactory factory = (ServerProviderFactory)server
.getEndpoint()
.get(ServerProviderFactory.class.getName());
final Set<String> packages = new HashSet<>();
if (resourcePackages != null) {
packages.addAll(resourcePackages);
}
// Generate random Context ID for Swagger
if (useContextBasedConfig) {
ctxId = UUID.randomUUID().toString();
}
Properties swaggerProps = null;
GenericOpenApiContextBuilder<?> openApiConfiguration;
final Application application = DefaultApplicationFactory.createApplicationOrDefault(server, factory,
sfb, bus, resourcePackages, isScan());
String defaultConfigLocation = getConfigLocation();
if (scanKnownConfigLocations && StringUtils.isEmpty(defaultConfigLocation)) {
defaultConfigLocation = OpenApiDefaultConfigurationScanner.locateDefaultConfiguration().orElse(null);
}
if (StringUtils.isEmpty(defaultConfigLocation)) {
swaggerProps = getSwaggerProperties(propertiesLocation, bus);
if (isScan()) {
packages.addAll(scanResourcePackages(sfb));
}
final OpenAPI oas = new OpenAPI().info(getInfo(swaggerProps));
registerComponents(securityDefinitions).ifPresent(oas::setComponents);
final SwaggerConfiguration config = new SwaggerConfiguration()
.openAPI(oas)
.prettyPrint(getOrFallback(isPrettyPrint(), swaggerProps, PRETTY_PRINT_PROPERTY))
.readAllResources(isReadAllResources())
.ignoredRoutes(getIgnoredRoutes())
.filterClass(getOrFallback(getFilterClass(), swaggerProps, FILTER_CLASS_PROPERTY))
.resourceClasses(getResourceClasses())
.resourcePackages(getOrFallback(packages, swaggerProps, RESOURCE_PACKAGE_PROPERTY));
if (!StringUtils.isEmpty(getScannerClass())) {
config.setScannerClass(getScannerClass());
}
openApiConfiguration = new JaxrsOpenApiContextBuilder<>()
.application(application)
.openApiConfiguration(config)
.ctxId(ctxId); /* will be null if not used */
} else {
openApiConfiguration = new JaxrsOpenApiContextBuilder<>()
.application(application)
.configLocation(defaultConfigLocation)
.ctxId(ctxId); /* will be null if not used */
}
try {
final OpenApiContext context = openApiConfiguration.buildContext(true);
final Properties userProperties = getUserProperties(
context
.getOpenApiConfiguration()
.getUserDefinedOptions());
registerOpenApiResources(sfb, packages, context.getOpenApiConfiguration());
registerSwaggerUiResources(sfb, combine(swaggerProps, userProperties), factory, bus);
registerSwaggerContainerRequestFilter(factory, application);
if (useContextBasedConfig) {
registerServletConfigProvider(factory);
}
if (customizer != null) {
customizer.setApplicationInfo(factory.getApplicationProvider());
}
bus.setProperty("openapi.service.description.available", "true");
} catch (OpenApiConfigurationException ex) {
throw new RuntimeException("Unable to initialize OpenAPI context", ex);
}
}
示例7
@SuppressWarnings("rawtypes")
protected void generateSpec() throws Exception
{
Set<Class<?>> classes = this.registeredControllers;
OpenAPIExtensions.setExtensions(Collections.singletonList(new ServerParameterExtension()));
OpenAPI openApi = new OpenAPI();
Info info = mapper.convertValue(openAPIConfig.getValue("info").unwrapped(), Info.class);
openApi.setInfo(info);
Map<String, SecurityScheme> securitySchemes = mapper.convertValue( openAPIConfig.getValue("securitySchemes").unwrapped(),new TypeReference<Map<String, SecurityScheme>>(){});
if (openApi.getComponents() == null)
{
openApi.setComponents(new Components());
}
openApi.getComponents().setSecuritySchemes(securitySchemes);
List<Server> servers = mapper.convertValue(openAPIConfig.getValue("servers").unwrapped(), new TypeReference<List<Server>>(){});
openApi.setServers(servers);
SwaggerConfiguration config = new SwaggerConfiguration().resourceClasses(classes.stream().map(Class::getName).collect(Collectors.toSet())).openAPI(openApi);
if(jsonViewQueryParameterName != null) {
if(config.getUserDefinedOptions() == null)
{
config.setUserDefinedOptions(new HashMap<>());
}
config.getUserDefinedOptions().put("jsonViewQueryParameterName", jsonViewQueryParameterName);
}
Set<String> modelConverterClasses = new HashSet<>();
modelConverterClasses.add(ServerModelResolver.class.getName());
List<String> additionalConverterClasses = openAPIConfig.getStringList("converterClasses");
modelConverterClasses.addAll(additionalConverterClasses);
config.setModelConverterClassess(modelConverterClasses);
OpenApiContext ctx = new GenericOpenApiContext().openApiConfiguration(config)
.openApiReader(new Reader(config))
.openApiScanner(new JaxrsApplicationAndAnnotationScanner().openApiConfiguration(config))
.init();
openApi = ctx.read();
this.openApi = openApi;
this.spec = writer.writeValueAsString(openApi);
}