下面列出了io.swagger.annotations.SwaggerDefinition#io.swagger.models.Scheme 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void applySchemes(ReaderContext context, Operation operation, Method method) {
final List<Scheme> schemes = new ArrayList<Scheme>();
final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
final Api apiAnnotation = context.getCls().getAnnotation(Api.class);
if (apiOperation != null) {
schemes.addAll(parseSchemes(apiOperation.protocols()));
}
if (schemes.isEmpty() && apiAnnotation != null) {
schemes.addAll(parseSchemes(apiAnnotation.protocols()));
}
for (Scheme scheme : schemes) {
operation.scheme(scheme);
}
}
@Override
public void applySchemes(ReaderContext context, Operation operation, Method method) {
final List<Scheme> schemes = new ArrayList<Scheme>();
final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
final Api apiAnnotation = context.getCls().getAnnotation(Api.class);
if (apiOperation != null) {
schemes.addAll(parseSchemes(apiOperation.protocols()));
}
if (schemes.isEmpty() && apiAnnotation != null) {
schemes.addAll(parseSchemes(apiAnnotation.protocols()));
}
for (Scheme scheme : schemes) {
operation.scheme(scheme);
}
}
private void testBase(Path path) {
Assert.assertEquals(1, path.getOperations().size());
Operation operation = path.getGet();
Assert.assertEquals("summary", operation.getSummary());
Assert.assertEquals("notes", operation.getDescription());
Assert.assertEquals(Arrays.asList("tag1", "tag2"), operation.getTags());
Assert.assertEquals(Arrays.asList("application/json"), operation.getProduces());
Assert.assertEquals(Arrays.asList("application/json"), operation.getConsumes());
Assert.assertEquals(Arrays.asList(Scheme.HTTP, Scheme.HTTPS), operation.getSchemes());
Map<String, Response> responseMap = operation.getResponses();
Assert.assertEquals(2, responseMap.size());
Response response = responseMap.get(SwaggerConst.SUCCESS_KEY);
Assert.assertNotNull(response);
Assert.assertEquals(null, response.getResponseSchema());
response = responseMap.get("202");
Assert.assertNotNull(response);
Assert.assertEquals(null, response.getResponseSchema());
Assert.assertEquals(1, response.getHeaders().size());
Assert.assertEquals("integer", response.getHeaders().get("h1").getType());
}
public int getPort(
Swagger swagger, Scheme scheme
) {
int port;
if (swagger.getHost().split(":").length > 1) {
port = Integer.valueOf(swagger.getHost().split(":")[1]);
} else {
if (scheme.toValue().toUpperCase().equals("HTTPS")) {
port = 443;
} else {
port = 80;
}
}
return port;
}
@Override
public void transform(SwaggerV2Descriptor descriptor) {
if (asBoolean(SwaggerProperties.ENTRYPOINTS_AS_SERVERS) && entrypoints != null && ! entrypoints.isEmpty()) {
Swagger swagger = descriptor.getSpecification();
// Swagger vs2 supports only a single server
ApiEntrypointEntity first = entrypoints.iterator().next();
URI target = URI.create(first.getTarget());
swagger.setSchemes(Collections.singletonList(Scheme.forValue(target.getScheme())));
swagger.setHost(target.getHost());
if (getProperty(SwaggerProperties.ENTRYPOINT_AS_BASEPATH) == null
|| getProperty(SwaggerProperties.ENTRYPOINT_AS_BASEPATH).isEmpty()
|| asBoolean(SwaggerProperties.ENTRYPOINT_AS_BASEPATH)) {
swagger.setBasePath(target.getPath());
}
}
}
@Test
public void testUriSchemeComponent() throws URISyntaxException {
Swagger swagger = new Swagger().host("http://localhost").basePath("/v2");
swagger.addScheme(Scheme.HTTP);
swagger.addScheme(Scheme.HTTPS);
Swagger2MarkupConverter.SwaggerContext context = createContext();
MarkupDocBuilder markupDocBuilder = context.createMarkupDocBuilder();
markupDocBuilder = new UriSchemeComponent(context).apply(markupDocBuilder, UriSchemeComponent.parameters(swagger, OverviewDocument.SECTION_TITLE_LEVEL));
markupDocBuilder.writeToFileWithoutExtension(outputDirectory, StandardCharsets.UTF_8);
Path expectedFile = getExpectedFile(COMPONENT_NAME);
DiffUtils.assertThatFileIsEqual(expectedFile, outputDirectory, getReportName(COMPONENT_NAME));
}
/**
* Update OAS definition with GW endpoints and API information
*
* @param swagger Swagger
* @param basePath API context
* @param transports transports types
* @param hostsWithSchemes GW hosts with protocol mapping
*/
private void updateEndpoints(Swagger swagger, String basePath, String transports,
Map<String, String> hostsWithSchemes) {
String host = StringUtils.EMPTY;
String[] apiTransports = transports.split(",");
List<Scheme> schemes = new ArrayList<>();
if (ArrayUtils.contains(apiTransports, APIConstants.HTTPS_PROTOCOL)
&& hostsWithSchemes.get(APIConstants.HTTPS_PROTOCOL) != null) {
schemes.add(Scheme.HTTPS);
host = hostsWithSchemes.get(APIConstants.HTTPS_PROTOCOL).trim()
.replace(APIConstants.HTTPS_PROTOCOL_URL_PREFIX, "");
}
if (ArrayUtils.contains(apiTransports, APIConstants.HTTP_PROTOCOL)
&& hostsWithSchemes.get(APIConstants.HTTP_PROTOCOL) != null) {
schemes.add(Scheme.HTTP);
if (StringUtils.isEmpty(host)) {
host = hostsWithSchemes.get(APIConstants.HTTP_PROTOCOL).trim()
.replace(APIConstants.HTTP_PROTOCOL_URL_PREFIX, "");
}
}
swagger.setSchemes(schemes);
swagger.setBasePath(basePath);
swagger.setHost(host);
}
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);
}
/**
* 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");
}
/**
* Updates scheme and hostname, and adds API doc link to Swagger
*
* @param swagger the API doc
* @param serviceId the unique service id
* @param hidden do not add link for automatically generated API doc
*/
private void updateSchemeHostAndLink(Swagger swagger, String serviceId, boolean hidden) {
GatewayConfigProperties gatewayConfigProperties = gatewayClient.getGatewayConfigProperties();
String swaggerLink = OpenApiUtil.getOpenApiLink(serviceId, gatewayConfigProperties);
log.debug("Updating host for service with id: " + serviceId + " to: " + gatewayConfigProperties.getHostname());
swagger.setSchemes(Collections.singletonList(Scheme.forValue(gatewayConfigProperties.getScheme())));
swagger.setHost(gatewayConfigProperties.getHostname());
if (!hidden) {
swagger.getInfo().setDescription(swagger.getInfo().getDescription() + swaggerLink);
}
}
private static Set<Scheme> parseSchemes(String schemes) {
final Set<Scheme> result = EnumSet.noneOf(Scheme.class);
for (String item : StringUtils.trimToEmpty(schemes).split(",")) {
final Scheme scheme = Scheme.forValue(StringUtils.trimToNull(item));
if (scheme != null) {
result.add(scheme);
}
}
return result;
}
private static List<Scheme> parseSchemes(String schemes) {
final List<Scheme> result = new ArrayList<Scheme>();
for (String item : StringUtils.trimToEmpty(schemes).split(",")) {
final Scheme scheme = Scheme.forValue(StringUtils.trimToNull(item));
if (scheme != null && !result.contains(scheme)) {
result.add(scheme);
}
}
return result;
}
private static List<Scheme> parseSchemes(String schemes) {
final List<Scheme> result = new ArrayList<Scheme>();
for (String item : StringUtils.trimToEmpty(schemes).split(",")) {
final Scheme scheme = Scheme.forValue(StringUtils.trimToNull(item));
if (scheme != null && !result.contains(scheme)) {
result.add(scheme);
}
}
return result;
}
private void convertProtocols(String protocols, Operation operation) {
if (protocols == null) {
return;
}
for (String protocol : protocols.split(SEPARATOR)) {
if (StringUtils.isEmpty(protocol)) {
continue;
}
operation.addScheme(Scheme.forValue(protocol));
}
}
@Override
public void onAfterTransport(BootEvent event) {
// register schema to microservice;
Microservice microservice = RegistrationManager.INSTANCE.getMicroservice();
String swaggerSchema = "http";
for (String endpoint : microservice.getInstance().getEndpoints()) {
if (endpoint.startsWith("rest://") && endpoint.indexOf("sslEnabled=true") > 0) {
swaggerSchema = "https";
}
}
MicroserviceMeta microserviceMeta = event.getScbEngine().getProducerMicroserviceMeta();
for (SchemaMeta schemaMeta : microserviceMeta.getSchemaMetas().values()) {
Swagger swagger = schemaMeta.getSwagger();
swagger.addScheme(Scheme.forValue(swaggerSchema));
String content = SwaggerUtils.swaggerToString(swagger);
LOGGER.info("generate swagger for {}/{}/{}, swagger: {}",
microserviceMeta.getAppId(),
microserviceMeta.getMicroserviceName(),
schemaMeta.getSchemaId(),
content);
RegistrationManager.INSTANCE.addSchema(schemaMeta.getSchemaId(), content);
}
saveBasePaths(microserviceMeta);
}
public boolean isUseHttps(Scheme scheme) {
boolean useHttps;
useHttps = scheme.toValue().toUpperCase().equals("HTTPS") || scheme.toValue().toUpperCase()
.equals("WSS");
return useHttps;
}
@Override
public void transform(SwaggerV2Descriptor descriptor) {
String tryItUrl = asString(SwaggerProperties.TRY_IT);
if (tryItUrl != null && ! tryItUrl.isEmpty()) {
URI newURI = URI.create(tryItUrl);
descriptor.getSpecification().setSchemes(Collections.singletonList(Scheme.forValue(newURI.getScheme())));
descriptor.getSpecification().setHost((newURI.getPort() != -1) ? newURI.getHost() + ':' + newURI.getPort() : newURI.getHost());
descriptor.getSpecification().setBasePath((newURI.getRawPath().isEmpty()) ? "/" : newURI.getRawPath());
}
}
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());
}
private static Set<Scheme> parseSchemes(String schemes) {
final Set<Scheme> result = EnumSet.noneOf(Scheme.class);
for (String item : StringUtils.trimToEmpty(schemes).split(",")) {
final Scheme scheme = Scheme.forValue(StringUtils.trimToNull(item));
if (scheme != null) {
result.add(scheme);
}
}
return result;
}
public AbstractDocumentSource(Log log, ApiSource apiSource, String encoding) throws MojoFailureException {
LOG = log;
this.outputPath = apiSource.getOutputPath();
this.templatePath = apiSource.getTemplatePath();
this.swaggerPath = apiSource.getSwaggerDirectory();
this.modelSubstitute = apiSource.getModelSubstitute();
this.jsonExampleValues = apiSource.isJsonExampleValues();
swagger = new Swagger();
if (apiSource.getSchemes() != null) {
for (String scheme : apiSource.getSchemes()) {
swagger.scheme(Scheme.forValue(scheme));
}
}
// read description from file
if (apiSource.getDescriptionFile() != null) {
InputStream is = null;
try {
is = new FileInputStream(apiSource.getDescriptionFile());
apiSource.getInfo().setDescription(IOUtils.toString(is));
} catch (IOException e) {
throw new MojoFailureException(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(is);
}
}
swagger.setHost(apiSource.getHost());
swagger.setInfo(apiSource.getInfo());
swagger.setBasePath(apiSource.getBasePath());
swagger.setExternalDocs(apiSource.getExternalDocs());
this.apiSource = apiSource;
if (encoding != null) {
this.encoding = encoding;
}
}
public static Swagger getSwagger() {
if (!swaggerEnable)
return new Swagger();
if (swagger != null)
return swagger;
Reader reader = new Reader(new Swagger());
String[] packages = null;
Class<?> mainClass = Dorado.mainClass;
EnableSwagger enableSwagger = mainClass.getAnnotation(EnableSwagger.class);
if (enableSwagger != null) {
packages = enableSwagger.value();
}
if (packages == null || packages.length == 0) {
packages = Dorado.serverConfig.scanPackages();
}
if (packages == null || packages.length == 0) {
packages = new String[] { mainClass.getPackage().getName() };
}
if (packages == null || packages.length == 0) {
throw new IllegalArgumentException("缺少scanPackages设置");
}
Set<Class<?>> classes = new HashSet<>();
for (String pkg : packages) {
try {
classes.addAll(PackageScanner.scan(pkg));
} catch (Exception ex) {
// ignore this ex
}
}
Swagger _swagger = reader.read(classes);
_swagger.setSchemes(Arrays.asList(Scheme.HTTP, Scheme.HTTPS));
ApiKey apiKey = apiContext.getApiKey();
if (apiKey != null) {
ApiKeyAuthDefinition apiKeyAuth = new ApiKeyAuthDefinition(apiKey.getName(),
In.forValue(apiKey.getIn() == null ? "header" : apiKey.getIn()));
_swagger.securityDefinition("auth", apiKeyAuth);
List<SecurityRequirement> securityRequirements = new ArrayList<>();
SecurityRequirement sr = new SecurityRequirement();
sr.requirement("auth");
securityRequirements.add(sr);
_swagger.setSecurity(securityRequirements);
}
if (apiContext.getInfo() != null)
_swagger.setInfo(apiContext.getInfo());
swagger = _swagger;
return _swagger;
}
private Scheme convertScheme(io.swagger.annotations.SwaggerDefinition.Scheme annotationScheme) {
if (SwaggerDefinition.Scheme.DEFAULT.equals(annotationScheme)) {
return Scheme.HTTP;
}
return Scheme.forValue(annotationScheme.name());
}
public void populateTable(Swagger swagger) {
DefaultTableModel defaultTableModel = (DefaultTableModel) this.table.getModel();
List<Scheme> schemes = swagger.getSchemes();
for (Scheme scheme : schemes) {
for (Map.Entry<String, Path> path : swagger.getPaths().entrySet()) {
for (Map.Entry<HttpMethod, Operation> operation : path.getValue().getOperationMap()
.entrySet()) {
StringBuilder stringBuilder = new StringBuilder();
for (Parameter parameter : operation.getValue().getParameters()) {
stringBuilder.append(parameter.getName()).append(", ");
}
if (stringBuilder.length() > 0) {
stringBuilder.setLength(stringBuilder.length() - 2);
}
this.httpRequestResponses.add(
new HttpRequestResponse(
this.extensionHelper.getBurpExtensionHelpers().buildHttpService(
swagger.getHost().split(":")[0],
this.extensionHelper
.getPort(
swagger,
scheme
),
this.extensionHelper
.isUseHttps(
scheme)
),
this.extensionHelper.isUseHttps(scheme),
this.extensionHelper
.buildRequest(swagger, path,
operation
)
));
defaultTableModel.addRow(new Object[]{
defaultTableModel.getRowCount(),
operation.getKey().toString(),
swagger.getHost().split(":")[0],
scheme.toValue().toUpperCase(),
swagger.getBasePath(),
path.getKey(),
stringBuilder.toString()
});
}
}
}
}
public SwaggerContext setScheme(String scheme) {
this.scheme = "http".equals(scheme) ? Scheme.HTTP : Scheme.HTTPS;
return this;
}
/**
* Gets a new Swagger metadata.
*
* @return the Swagger metadata.
* @throws MojoExecutionException if any problems were encountered.
*/
private Swagger getSwagger() throws MojoExecutionException
{
getLog().debug("Creating Swagger Metadata");
// Set up initial Swagger metadata.
Swagger swagger = new Swagger();
swagger.setInfo(new Info().title(title).version(version));
swagger.setBasePath(basePath);
// Set the schemes.
if (!CollectionUtils.isEmpty(schemeParameters))
{
List<Scheme> schemes = new ArrayList<>();
for (String schemeParameter : schemeParameters)
{
Scheme scheme = Scheme.forValue(schemeParameter);
if (scheme == null)
{
throw new MojoExecutionException("Invalid scheme specified: " + schemeParameter);
}
schemes.add(scheme);
}
swagger.setSchemes(schemes);
}
// Add authorization support if specified.
if (authType != null)
{
// Find the definition for the user specified type.
SecuritySchemeDefinition securitySchemeDefinition = null;
for (SecuritySchemeDefinition possibleDefinition : SECURITY_SCHEME_DEFINITIONS)
{
if (possibleDefinition.getType().equalsIgnoreCase(authType))
{
securitySchemeDefinition = possibleDefinition;
break;
}
}
// If we found a match, set it on the swagger object.
if (securitySchemeDefinition != null)
{
// Come up with an authentication name for easy identification (e.g. basicAuthentication, etc.).
String securityName = securitySchemeDefinition.getType() + "Authentication";
// Add the security definition.
swagger.addSecurityDefinition(securityName, securitySchemeDefinition);
// Add the security for everything based on the name of the definition.
SecurityRequirement securityRequirement = new SecurityRequirement();
securityRequirement.requirement(securityName);
swagger.addSecurity(securityRequirement);
}
}
// Use default paths and definitions.
swagger.setPaths(new TreeMap<>());
swagger.setDefinitions(new TreeMap<>());
return swagger;
}
public List<Scheme> schemes() {
return Collections.unmodifiableList(this.schemes);
}
public List<Scheme> getSchemes() {
return schemes;
}
public void setSchemes(List<Scheme> schemes) {
this.schemes = schemes;
}