下面列出了io.swagger.annotations.SwaggerDefinition#io.swagger.models.Info 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Bean
public BeanConfig swaggerConfig() {
BeanConfig beanConfig = new BeanConfig();
beanConfig.setSchemes(new String[]{"http", "https"});
beanConfig.setBasePath(BASE_PATH);
beanConfig.setTitle(TITLE);
beanConfig.setDescription(DESCRIPTION);
beanConfig.setLicense(LICENSE);
beanConfig.setLicenseUrl(LICENSE_URL);
beanConfig.setScan(true);
beanConfig.setVersion(VERSION);
beanConfig.setResourcePackage(ServiceLogsResource.class.getPackage().getName());
License license = new License();
license.setName(LICENSE);
license.setUrl(LICENSE_URL);
Info info = new Info();
info.setDescription(DESCRIPTION);
info.setTitle(TITLE);
info.setVersion(VERSION);
info.setLicense(license);
beanConfig.setInfo(info);
return beanConfig;
}
private void init() {
mockMap.put("xxxx", apiListing);
mockDoc = new Documentation("xx", "/xx", null, mockMap,
null, Collections.emptySet(), Collections.emptySet(), null, Collections.emptySet(), Collections.emptyList());
mockSwagger = new Swagger();
mockSwagger.setInfo(new Info());
Map<String, Model> defMap = new HashMap<>();
defMap.put("xx", new ModelImpl());
mockSwagger.setDefinitions(defMap);
Map<String, Path> pathMap = new HashMap<>();
pathMap.put("xx", new Path());
mockSwagger.setPaths(pathMap);
new Expectations() {
{
documentationCache.documentationByGroup(anyString);
result = mockDoc;
DefinitionCache.getClassNameBySchema(anyString);
result = "app";
mapper.mapDocumentation((Documentation) any);
result = mockSwagger;
}
};
}
public OpenAPIV2Generator(List<String> modelPackages, List<String> controllerBasePackages, Info info,
List<SchemaInterceptor> schemaInterceptors,
List<SchemaFieldInterceptor> schemaFieldInterceptors,
List<OperationParameterInterceptor> operationParameterInterceptors,
List<OperationInterceptor> operationInterceptors,
List<RequestBodyInterceptor> requestBodyInterceptors) {
this.modelPackages = modelPackages;
this.controllerBasePackages = controllerBasePackages;
componentSchemaTransformer = new ComponentSchemaTransformer(schemaFieldInterceptors);
globalHeaders = new ArrayList<>();
GenerationContext operationsGenerationContext = new GenerationContext(null, removeRegexFormatFromPackages(modelPackages));
operationsTransformer = new OperationsTransformer(
operationsGenerationContext, operationParameterInterceptors, operationInterceptors, requestBodyInterceptors, globalHeaders
);
this.info = info;
this.schemaInterceptors = schemaInterceptors;
this.schemaFieldInterceptors = schemaFieldInterceptors;
this.operationParameterInterceptors = operationParameterInterceptors;
this.operationInterceptors = operationInterceptors;
this.requestBodyInterceptors = requestBodyInterceptors;
}
@Override
public void preprocessSwagger(Swagger swagger) {
Info info = swagger.getInfo();
String calloutLabel = info.getTitle();
additionalProperties.put("calloutLabel", calloutLabel);
String sanitized = sanitizeName(calloutLabel);
additionalProperties.put("calloutName", sanitized);
supportingFiles.add(new SupportingFile("namedCredential.mustache", srcPath + "/namedCredentials",
sanitized + ".namedCredential"
));
if (additionalProperties.get(BUILD_METHOD).equals("sfdx")) {
generateSfdxSupportingFiles();
} else if (additionalProperties.get(BUILD_METHOD).equals("ant")) {
generateAntSupportingFiles();
}
}
@Override
public void preprocessSwagger(Swagger swagger) {
super.preprocessSwagger(swagger);
if (swagger.getInfo() != null) {
Info info = swagger.getInfo();
if (StringUtils.isBlank(jsProjectName) && info.getTitle() != null) {
// when jsProjectName is not specified, generate it from info.title
jsProjectName = sanitizeName(dashize(info.getTitle()));
}
}
// default values
if (StringUtils.isBlank(jsProjectName)) {
jsProjectName = "swagger-js-client";
}
if (StringUtils.isBlank(jsModuleName)) {
jsModuleName = camelize(underscore(jsProjectName));
}
additionalProperties.put("jsProjectName", jsProjectName);
additionalProperties.put("jsModuleName", jsModuleName);
preparHtmlForGlobalDescription(swagger);
}
@Override
// 这里定制Api全局信息,如文档描述、license,contact等信息
public ApiContext buildApiContext() {
Info info = new Info()
.contact(new Contact().email("[email protected]").name("weiping wang")
.url("http://github.com/javagossip/dorado"))
.license(new License().name("apache v2.0").url("http://www.apache.org"))
.termsOfService("http://swagger.io/terms/").description("Dorado服务框架api接口文档")
.title("dorado demo api接口文档").version("1.0.0");
//构造api访问授权的apiKey
ApiKey apiKey = ApiKey.builder().withName("Authorization").withIn("header").build();
ApiContext apiContext = ApiContext.builder().withApiKey(apiKey)
.withInfo(info).build();
return apiContext;
}
@Bean(name = "swaggerApiContext")
public ApiContext buildApiContext() {
Info info = new Info();
info.title(swaggerConfig.getTitle()).description(swaggerConfig.getDescription())
.termsOfService(swaggerConfig.getTermsOfServiceUrl()).version(swaggerConfig.getVersion());
Contact contact = swaggerConfig.getContact();
if (contact != null)
info.setContact(new io.swagger.models.Contact().email(contact.getEmail()).name(contact.getName())
.url(contact.getUrl()));
info.setLicense(new License().name(swaggerConfig.getLicense()).url(swaggerConfig.getLicenseUrl()));
ApiContext.Builder apiContextBuilder = ApiContext.builder().withInfo(info);
ai.houyi.dorado.swagger.springboot.SwaggerProperties.ApiKey apiKey = swaggerConfig.getApiKey();
if (apiKey != null) {
ApiKey _apiKey = ApiKey.builder().withIn(swaggerConfig.getApiKey().getIn())
.withName(swaggerConfig.getApiKey().getName()).build();
apiContextBuilder.withApiKey(_apiKey);
}
return apiContextBuilder.build();
}
protected void setJavaInterface(Info info) {
if (!swaggerGeneratorFeature.isExtJavaInterfaceInVendor()) {
return;
}
if (cls.isInterface()) {// && !isInterfaceReactive(cls)) {
info.setVendorExtension(SwaggerConst.EXT_JAVA_INTF, cls.getName());
return;
}
// if (cls.getInterfaces().length > 0) {
// info.setVendorExtension(SwaggerConst.EXT_JAVA_INTF, cls.getInterfaces()[0].getName());
// return;
// }
if (StringUtils.isEmpty(swaggerGeneratorFeature.getPackageName())) {
return;
}
String intfName = swaggerGeneratorFeature.getPackageName() + "." + cls.getSimpleName() + "Intf";
info.setVendorExtension(SwaggerConst.EXT_JAVA_INTF, intfName);
}
/**
* Preconfigure generator. By default it will genrate api for Data and RCP with JSon payloads only.
* The api will be in YAML format. You might change default setting with config methods of the class
* @param ctx context for generation
* @param modulesToGenerate modules that will be transformed to swagger API
*/
@Inject
public IoCSwaggerGenerator(@Assisted SchemaContext ctx, @Assisted Set<Module> modulesToGenerate) {
Objects.requireNonNull(ctx);
Objects.requireNonNull(modulesToGenerate);
if(modulesToGenerate.isEmpty()) throw new IllegalStateException("No modules to generate has been specified");
this.ctx = ctx;
this.modules = modulesToGenerate;
target = new Swagger();
converter = new AnnotatingTypeConverter(ctx);
moduleUtils = new ModuleUtils(ctx);
this.moduleNames = modulesToGenerate.stream().map(ModuleIdentifier::getName).collect(Collectors.toSet());
//assign default strategy
strategy(Strategy.optimizing);
//no exposed swagger API
target.info(new Info());
//default postprocessors
postprocessor = new ReplaceEmptyWithParent();
}
@Override
public void afterPropertiesSet() throws Exception {
swagger = new Swagger();
Info info = new Info();
info.setTitle("GreetingService");
swagger.setInfo(info);
Map<String, Object> beans = applicationContext.getBeansWithAnnotation(SpringTimeService.class);
Set<Class<?>> classes = new HashSet<Class<?>>();
for (Object bean : beans.values()) {
classes.add(bean.getClass());
}
Reader reader = new Reader(swagger, ReaderConfigUtils.getReaderConfig(null));
swagger = reader.read(classes);
}
/**
* Adds additional information to {@link Service} object.
*
* @throws OpenApiConversionException
*/
private void createServiceInfoFromOpenApi(
Service.Builder serviceBuilder, List<OpenApiFile> openApiFiles)
throws OpenApiConversionException {
for (OpenApiFile openApiFile : openApiFiles) {
//TODO(user): need better way to resolve conflicts here
if (openApiFile.swagger().getInfo() != null) {
Info info = openApiFile.swagger().getInfo();
if (info.getTitle() != null) {
serviceBuilder.setTitle(info.getTitle());
}
if (info.getDescription() != null) {
serviceBuilder.getDocumentationBuilder().setSummary(info.getDescription());
}
}
}
}
private Swagger writeSwagger(Iterable<ApiConfig> configs, SwaggerContext context,
GenerationContext genCtx)
throws ApiConfigException {
ImmutableListMultimap<ApiKey, ? extends ApiConfig> configsByKey = FluentIterable.from(configs)
.index(CONFIG_TO_ROOTLESS_KEY);
Swagger swagger = new Swagger()
.produces("application/json")
.consumes("application/json")
.scheme(context.scheme)
.host(context.hostname)
.basePath(context.basePath)
.info(new Info()
.title(context.hostname)
.version(context.docVersion));
for (ApiKey apiKey : configsByKey.keySet()) {
writeApi(apiKey, configsByKey.get(apiKey), swagger, genCtx);
}
writeQuotaDefinitions(swagger, genCtx);
return swagger;
}
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
Info info = params.info;
License license = info.getLicense();
String termOfService = info.getTermsOfService();
if ((license != null && (isNotBlank(license.getName()) || isNotBlank(license.getUrl()))) || isNotBlank(termOfService)) {
markupDocBuilder.sectionTitleLevel(params.titleLevel, labels.getLabel(LICENSE_INFORMATION));
MarkupDocBuilder paragraph = copyMarkupDocBuilder(markupDocBuilder);
if (license != null) {
if (isNotBlank(license.getName())) {
paragraph.italicText(labels.getLabel(LICENSE)).textLine(COLON + license.getName());
}
if (isNotBlank(license.getUrl())) {
paragraph.italicText(labels.getLabel(LICENSE_URL)).textLine(COLON + license.getUrl());
}
}
paragraph.italicText(labels.getLabel(TERMS_OF_SERVICE)).textLine(COLON + termOfService);
markupDocBuilder.paragraph(paragraph.toString(), true);
}
return markupDocBuilder;
}
@Test
public void testLicenseInfoComponent() throws URISyntaxException {
Info info = new Info()
.license(new License().name("Apache 2.0").url("http://www.apache.org/licenses/LICENSE-2.0"))
.termsOfService("Bla bla bla");
Swagger2MarkupConverter.SwaggerContext context = createContext();
MarkupDocBuilder markupDocBuilder = context.createMarkupDocBuilder();
markupDocBuilder = new LicenseInfoComponent(context).apply(markupDocBuilder, LicenseInfoComponent.parameters(info, OverviewDocument.SECTION_TITLE_LEVEL));
markupDocBuilder.writeToFileWithoutExtension(outputDirectory, StandardCharsets.UTF_8);
Path expectedFile = getExpectedFile(COMPONENT_NAME);
DiffUtils.assertThatFileIsEqual(expectedFile, outputDirectory, getReportName(COMPONENT_NAME));
}
private String createData() throws Exception {
final Swagger expected = new Swagger();
expected.host(HOST);
when(request.getHeader("Host")).thenReturn(HOST);
expected.info(new Info().title(CONTEXT_PATH.substring(1)).description("API Documentation").version("1.0"));
createData(DummyService.class, "/api", expected, endpointsByPathMap, GET);
createData(DummyService.class, "/api", expected, endpointsByPathMap, POST);
createData(AnnotatedDummyService.class, "/apiAnnotated", expected, endpointsByPathMap,
"an annotated test service", ANY, "millis", "millis since epoch");
final ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.writeValueAsString(expected);
}
private void configureSwagger() {
swagger = new Swagger();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
Info info = new Info();
Contact swaggerContact = new Contact();
License swaggerLicense = new License();
swaggerLicense.name(this.license)
.url(this.licenseUrl);
swaggerContact.name(this.contact);
info.version(this.version)
.description(this.description)
.contact(swaggerContact)
.license(swaggerLicense)
.title(this.title);
swagger.setInfo(info);
if (this.schemes != null) {
for (String scheme : this.schemes) {
swagger.scheme(Scheme.forValue(scheme));
}
}
swagger.setHost(this.host);
swagger.setBasePath(this.basePath);
}
@Test
public void testGetInfo0VendorExtensions() {
Map<String, Object> logo = new HashMap<String, Object>();
logo.put("logo", "logo url");
logo.put("description", "This is our logo.");
Map<String, Object> website = new HashMap<String, Object>();
website.put("website", "website url");
website.put("description", "This is our website.");
Map<String, Object> expectedExtensions = new HashMap<String, Object>();
expectedExtensions.put("x-logo", logo);
expectedExtensions.put("x-website", website);
Set<Class<?>> validClasses = Sets.newHashSet(ApiSourceTestClass.class);
ApiSource apiSource = spy(ApiSource.class);
when(apiSource.getValidClasses(SwaggerDefinition.class)).thenReturn(validClasses);
Info info = apiSource.getInfo();
Map<String, Object> vendorExtensions = info.getVendorExtensions();
Assert.assertEquals(vendorExtensions.size(), 2);
Assert.assertEquals(vendorExtensions, expectedExtensions);
}
@Test
public void testAddDescriptionFile() throws URISyntaxException, MojoFailureException {
// arrange
URI fileUri = this.getClass().getResource("descriptionFile.txt").toURI();
File descriptionFile = new File(fileUri);
when(apiSource.getDescriptionFile()).thenReturn(descriptionFile);
when(apiSource.getInfo()).thenReturn(new Info());
// act
AbstractDocumentSource externalDocsSource = new AbstractDocumentSource(log, apiSource, "UTF-8") {
@Override
protected ClassSwaggerReader resolveApiReader() throws GenerateException {
return null;
}
@Override
protected AbstractReader createReader() {
return null;
}
};
// assert
assertThat(externalDocsSource.swagger.getInfo().getDescription(), is("Description file content\n"));
}
private void changeSwaggerInfo(String originalSchemaId, Swagger swagger) {
String fullClassName = DefinitionCache.getFullClassNameBySchema(originalSchemaId);
String xInterfaceName = genXInterfaceName(appName, serviceName, mapSchemaId(originalSchemaId));
Info info = swagger.getInfo();
info.setTitle(TITLE_PREFIX + fullClassName);
info.setVendorExtension(X_JAVA_INTERFACE, xInterfaceName);
}
/**
* This method will create the info section of the swagger document.
*
* @param dataServiceName name of the data-service.
* @param transports enabled transports.
* @param serverConfig Server config object.
* @param swaggerDoc Swagger document object.
* @throws AxisFault Exception occured while getting the host address from transports.
*/
private static void addSwaggerInfoSection(String dataServiceName, List<String> transports,
MIServerConfig serverConfig, Swagger swaggerDoc) throws AxisFault {
swaggerDoc.basePath("/" + SwaggerProcessorConstants.SERVICES_PREFIX + "/" + dataServiceName);
if (transports.contains("https")) {
swaggerDoc.addScheme(Scheme.HTTPS);
swaggerDoc.addScheme(Scheme.HTTP);
swaggerDoc.setHost(serverConfig.getHost("https"));
} else {
swaggerDoc.addScheme(Scheme.HTTP);
swaggerDoc.setHost(serverConfig.getHost("http"));
}
Info info = new Info();
info.title(dataServiceName);
info.setVersion("1.0");
info.description("API Definition of dataservice : " + dataServiceName);
swaggerDoc.setInfo(info);
swaggerDoc.addConsumes("application/json");
swaggerDoc.addConsumes("application/xml");
swaggerDoc.addProduces("application/json");
swaggerDoc.addProduces("application/xml");
}
private Info createTestInfo() {
Info info = new Info();
info.setTitle("Test API");
info.setDescription("Test description");
info.setVersion("1.0.0");
return info;
}
/**
* Creates Swagger Info
*
* @param api API sent by controller
* @return Swagger Info
*/
private static Info createSwaggerInfo(API api) {
Info info = new Info();
info.setVersion(cellConfig.getVersion());
info.setTitle(generateAPIName(api));
return info;
}
public void preprocessSwagger(Swagger swagger) {
Info info = swagger.getInfo();
info.setDescription(toHtml(info.getDescription()));
info.setTitle(toHtml(info.getTitle()));
Map<String, Model> models = swagger.getDefinitions();
for (Model model : models.values()) {
model.setDescription(toHtml(model.getDescription()));
model.setTitle(toHtml(model.getTitle()));
}
}
@Override
public void preprocessSwagger(Swagger swagger) {
Info info = swagger.getInfo();
if (moduleName == null) {
if (info.getTitle() != null) {
// default to the appName (from title field)
setModuleName(modulized(escapeText(info.getTitle())));
} else {
setModuleName(defaultModuleName);
}
}
additionalProperties.put("moduleName", moduleName);
if (!additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
additionalProperties.put(CodegenConstants.PACKAGE_NAME, underscored(moduleName));
}
supportingFiles.add(new SupportingFile("connection.ex.mustache",
sourceFolder(),
"connection.ex"));
supportingFiles.add(new SupportingFile("request_builder.ex.mustache",
sourceFolder(),
"request_builder.ex"));
supportingFiles.add(new SupportingFile("deserializer.ex.mustache",
sourceFolder(),
"deserializer.ex"));
}
private Info getInfoByApi(Api api) {
Info info = new Info();
info.setTitle(api.getName());
info.setDescription(api.getDescription());
info.setVersion(api.getVersion());
return info;
}
public void init() {
if (!config.isConfigOk()) {
return;
}
swagger = new Swagger();
swagger.setHost(config.getHost());
swagger.setBasePath("/");
swagger.addScheme(HTTP);
swagger.addScheme(HTTPS);
Info swaggerInfo = new Info();
swaggerInfo.setDescription(config.getDescription());
swaggerInfo.setVersion(config.getVersion());
swaggerInfo.setTitle(config.getTitle());
swaggerInfo.setTermsOfService(config.getTermsOfService());
Contact contact = new Contact();
contact.setName(config.getContactName());
contact.setEmail(config.getContactEmail());
contact.setUrl(config.getContactUrl());
swaggerInfo.setContact(contact);
License license = new License();
license.setName(config.getLicenseName());
license.setUrl(config.getLicenseUrl());
swaggerInfo.setLicense(license);
swagger.setInfo(swaggerInfo);
List<Class> classes = ClassScanner.scanClassByAnnotation(RequestMapping.class, false);
Reader.read(swagger, classes);
}
public static Class<?> getInterface(Swagger swagger) {
Info info = swagger.getInfo();
if (info == null) {
return null;
}
String name = getInterfaceName(info.getVendorExtensions());
if (StringUtils.isEmpty(name)) {
return null;
}
return ReflectUtils.getClassByName(name);
}
@Before
public void setupTestClass(){
definitionParserService = new DefinitionParserService();
this.swagger = new Swagger();
Info info = new Info();
swagger.setInfo(info);
objectMapper = new ObjectMapper();
}
/**
* Preconfigure generator. By default it will genrate api for Data and RCP with JSon payloads only.
* The api will be in YAML format. You might change default setting with config methods of the class
* @param ctx context for generation
* @param modulesToGenerate modules that will be transformed to swagger API
*/
public SwaggerGenerator(SchemaContext ctx, Set<org.opendaylight.yangtools.yang.model.api.Module> modulesToGenerate) {
Objects.requireNonNull(ctx);
Objects.requireNonNull(modulesToGenerate);
if(ctx.getModules().isEmpty()) {
log.error("No modules found in the context.");
throw new IllegalStateException("No modules found in the context.");
}
if(modulesToGenerate.isEmpty()) {
log.error("No modules has been specified for swagger generation");
if(log.isInfoEnabled()) {
String msg = ctx.getModules().stream().map(ModuleIdentifier::getName).collect(Collectors.joining(", "));
log.info("Modules in the context are: {}", msg);
}
throw new IllegalStateException("No modules to generate has been specified");
}
this.ctx = ctx;
this.modules = modulesToGenerate;
target = new Swagger();
converter = new AnnotatingTypeConverter(ctx);
moduleUtils = new ModuleUtils(ctx);
this.moduleNames = modulesToGenerate.stream().map(ModuleIdentifier::getName).collect(Collectors.toSet());
//assign default strategy
strategy(Strategy.optimizing);
//no exposed swagger API
target.info(new Info());
pathHandlerBuilder = new com.mrv.yangtools.codegen.impl.path.rfc8040.PathHandlerBuilder();
//default postprocessors
postprocessor = new ReplaceEmptyWithParent();
}
private void updateInfoFromConfig() {
if (getSwagger().getInfo() == null) {
setInfo(new Info());
}
if (StringUtils.isNotBlank(getDescription())) {
getSwagger().getInfo().setDescription(getDescription());
}
if (StringUtils.isNotBlank(getTitle())) {
getSwagger().getInfo().setTitle(getTitle());
}
if (StringUtils.isNotBlank(getVersion())) {
getSwagger().getInfo().setVersion(getVersion());
}
if (StringUtils.isNotBlank(getTermsOfServiceUrl())) {
getSwagger().getInfo().setTermsOfService(getTermsOfServiceUrl());
}
if (getContact() != null) {
getSwagger().getInfo().setContact((new Contact()).name(getContact()));
}
if (getLicense() != null && getLicenseUrl() != null) {
getSwagger().getInfo().setLicense((new License()).name(getLicense()).url(getLicenseUrl()));
}
if (getSchemes() != null) {
for (String scheme : getSchemes()) {
reader.getSwagger().scheme(Scheme.forValue(scheme));
}
}
reader.getSwagger().setInfo(getInfo());
}