下面列出了io.swagger.annotations.SwaggerDefinition#io.swagger.models.Tag 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public Swagger handle(Swagger swagger) {
if (swagger.getTags() == null) return swagger;
for (Tag tag : swagger.getTags())
{
String newTagName = TextUtils.getFirstLine(tag.getDescription());
swagger.getPaths().values().forEach(path -> {
handleOperation(tag, newTagName, path.getGet());
handleOperation(tag, newTagName, path.getPost());
handleOperation(tag, newTagName, path.getPut());
handleOperation(tag, newTagName, path.getDelete());
handleOperation(tag, newTagName, path.getHead());
handleOperation(tag, newTagName, path.getOptions());
handleOperation(tag, newTagName, path.getPatch());
});
tag.setName(newTagName);
}
return swagger;
}
@Override
public TagStatisticsBuilder configure(Swagger swagger, List<ConditionRule> rules) {
OperationsHolder operations = SwaggerSpecificationProcessor.extractOperation(swagger);
tagCoverageMap = swagger.getTags().stream()
.collect(toMap(Tag::getName, TagCoverage::new));
operationToTag = operations.getOperations()
.entrySet()
.stream()
.collect(toMap(Map.Entry::getKey, entry -> entry.getValue().getTags()));
operationToTag.forEach((key, value) -> value.forEach(tag -> tagCoverageMap.get(tag).addOperation(key)));
return this;
}
private void readOperation(String valuePath, String basePath, io.swagger.models.Operation verb, HttpMethod method, List<Resource> resources, Long apiId) {
verb.getTags().forEach(tagName -> {
Tag tag = new Tag().name(tagName);
Resource resource = findResourceByTagOrCreate(tag, resources);
if (resourceThisTagNotExist(tag, resources)) {
resource = resourceService.save(apiId, resource);
resources.add(resource);
}
List<Operation> operations = resource.getOperations();
if (Objects.isNull(operations)) {
operations = new ArrayList<>();
}
String path = valuePath.replace(basePath, "");
Operation operation = findOperationByOperationSwaggerOrCreate(verb, method, path, operations);
if (operationNotExist(method, path, operations)) {
operation = operationService.save(apiId, resource.getId(), operation);
operations.add(operation);
}
});
}
@Test
public void testTagsComponent() throws URISyntaxException {
List<Tag> tags = new ArrayList<>();
tags.add(new Tag().name("Tag1").description("description"));
tags.add(new Tag().name("Tag2"));
Swagger2MarkupConverter.SwaggerContext context = createContext();
MarkupDocBuilder markupDocBuilder = context.createMarkupDocBuilder();
markupDocBuilder = new TagsComponent(context).apply(markupDocBuilder, TagsComponent.parameters(tags, OverviewDocument.SECTION_TITLE_LEVEL));
markupDocBuilder.writeToFileWithoutExtension(outputDirectory, StandardCharsets.UTF_8);
Path expectedFile = getExpectedFile(COMPONENT_NAME);
DiffUtils.assertThatFileIsEqual(expectedFile, outputDirectory, getReportName(COMPONENT_NAME));
}
private byte[] writeDynamicResource(InputStream is) throws IOException {
String str = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8));
Swagger swagger = new SwaggerParser().parse(str);
// set the resource listing tag
Tag dynamic = new Tag();
dynamic.setName("dynamic");
dynamic.setDescription("Dynamic Cypher resources");
swagger.addTag(dynamic);
// add resources to the path
Map<String,Path> paths = swagger.getPaths();
paths.putAll(configuration.getCypherResources());
Map<String,Path> sorted = new LinkedHashMap<>();
List<String> keys = new ArrayList<>();
keys.addAll(paths.keySet());
Collections.sort(keys);
for (String key : keys) {
sorted.put(key, paths.get(key));
}
swagger.setPaths(sorted);
// return updated swagger JSON
return Json.pretty(swagger).getBytes();
}
private Map<String, Tag> scanClasspathForTags() {
Map<String, Tag> tags = new HashMap<>();
for (Class<?> aClass: new Reflections("").getTypesAnnotatedWith(SwaggerDefinition.class)) {
SwaggerDefinition swaggerDefinition = AnnotationUtils.findAnnotation(aClass, SwaggerDefinition.class);
for (io.swagger.annotations.Tag tag : swaggerDefinition.tags()) {
String tagName = tag.name();
if (!tagName.isEmpty()) {
tags.put(tag.name(), new Tag().name(tag.name()).description(tag.description()));
}
}
}
return tags;
}
private void handleOperation(Tag tag, String newTagName, Operation operation) {
if (operation == null) return;
if (operation.getTags().contains(tag.getName()))
{
operation.getTags().remove(tag.getName());
operation.getTags().add(newTagName);
}
}
/**
* Scans a single class for Swagger annotations - does not invoke
* ReaderListeners
*/
public Swagger read(Class<?> cls) {
SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);
if (swaggerDefinition != null) {
readSwaggerConfig(cls, swaggerDefinition);
}
return read(cls, new LinkedHashMap<String, Tag>(), new ArrayList<Parameter>(), new HashSet<Class<?>>());
}
private void readTags(List<Tag> tags, List<Resource> resources, Long apiId) {
tags.forEach(tag -> {
if (resourceThisTagNotExist(tag, resources)) {
Resource resourceCreated = findResourceByTagOrCreate(tag, resources);
resourceCreated = resourceService.save(apiId, resourceCreated);
resources.add(resourceCreated);
}
});
}
private Resource createResourceByTag(Tag tag) {
Resource resource = new Resource();
resource.setName(tag.getName());
resource.setDescription(tag.getDescription());
resource.setOperations(new ArrayList<>());
return resource;
}
private Tag convertTag(io.swagger.annotations.Tag tagAnnotation) {
Tag tag = new Tag();
tag.setName(tagAnnotation.name());
tag.setDescription(tagAnnotation.description());
tag.setExternalDocs(convertExternalDocs(tagAnnotation.externalDocs()));
tag.getVendorExtensions().putAll(BaseReaderUtils.parseExtensions(tagAnnotation.extensions()));
return tag;
}
@Override
protected Tag mapTag(springfox.documentation.service.Tag from)
{
if (from == null)
{
return null;
}
Tag tag = new Tag();
tag.setVendorExtensions(vendorExtensionsMapper.mapExtensions(from.getVendorExtensions()));
tag.setName(from.getName());
tag.setDescription(from.getDescription());
return tag;
}
protected List<Tag> tagSetToTagList(Set<springfox.documentation.service.Tag> set)
{
if (set == null)
{
return null;
}
List<Tag> list = new ArrayList<Tag>(set.size());
for (springfox.documentation.service.Tag tag : set)
{
list.add(mapTag(tag));
}
return list;
}
/**
* Converts the global Tag list into a Map where the tag name is the key and the Tag the value.
* Either ordered or as-is, if the comparator is null.
*
* @param tags the List of tags
* @param comparator the comparator to use.
* @return the Map of tags. Either ordered or as-is, if the comparator is null.
*/
public static Map<String, Tag> toSortedMap(List<Tag> tags, Comparator<String> comparator) {
Map<String, Tag> sortedMap;
if (comparator == null)
sortedMap = new LinkedHashMap<>();
else
sortedMap = new TreeMap<>(comparator);
tags.forEach(tag -> sortedMap.put(tag.getName(), tag));
return sortedMap;
}
private String mapToString(Tag tag) {
String name = tag.getName();
String description = tag.getDescription();
if (isNotBlank(description)) {
return name + COLON + description;
} else {
return name;
}
}
/**
* Builds the paths section. Groups the paths either as-is, by tags or using regex.
*
* @param paths the Swagger paths
*/
private void buildsPathsSection(MarkupDocBuilder markupDocBuilder, Map<String, Path> paths) {
List<SwaggerPathOperation> pathOperations = PathUtils.toPathOperationsList(paths, getHostname(), getBasePath(), config.getOperationOrdering());
if (CollectionUtils.isNotEmpty(pathOperations)) {
if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
pathOperations.forEach(operation -> buildOperation(markupDocBuilder, operation, config));
} else if (config.getPathsGroupedBy() == GroupBy.TAGS) {
Validate.notEmpty(context.getSchema().getTags(), "Tags must not be empty, when operations are grouped by tags");
// Group operations by tag
Multimap<String, SwaggerPathOperation> operationsGroupedByTag = TagUtils.groupOperationsByTag(pathOperations, config.getOperationOrdering());
Map<String, Tag> tagsMap = TagUtils.toSortedMap(context.getSchema().getTags(), config.getTagOrdering());
tagsMap.forEach((String tagName, Tag tag) -> {
markupDocBuilder.sectionTitleWithAnchorLevel2(WordUtils.capitalize(tagName), tagName + "_resource");
String description = tag.getDescription();
if (StringUtils.isNotBlank(description)) {
markupDocBuilder.paragraph(description);
}
operationsGroupedByTag.get(tagName).forEach(operation -> buildOperation(markupDocBuilder, operation, config));
});
} else if (config.getPathsGroupedBy() == GroupBy.REGEX) {
Validate.notNull(config.getHeaderPattern(), "Header regex pattern must not be empty when operations are grouped using regex");
Pattern headerPattern = config.getHeaderPattern();
Multimap<String, SwaggerPathOperation> operationsGroupedByRegex = RegexUtils.groupOperationsByRegex(pathOperations, headerPattern);
Set<String> keys = operationsGroupedByRegex.keySet();
String[] sortedHeaders = RegexUtils.toSortedArray(keys);
for (String header : sortedHeaders) {
markupDocBuilder.sectionTitleWithAnchorLevel2(WordUtils.capitalize(header), header + "_resource");
operationsGroupedByRegex.get(header).forEach(operation -> buildOperation(markupDocBuilder, operation, config));
}
}
}
}
public SwaggerInventory process(Swagger swagger) {
Iterator var2;
if(swagger.getTags() != null) {
var2 = swagger.getTags().iterator();
while(var2.hasNext()) {
Tag key = (Tag)var2.next();
this.process(key);
}
}
String key1;
if(swagger.getPaths() != null) {
var2 = swagger.getPaths().keySet().iterator();
while(var2.hasNext()) {
key1 = (String)var2.next();
Path model = swagger.getPath(key1);
this.process(model);
}
}
if(swagger.getDefinitions() != null) {
var2 = swagger.getDefinitions().keySet().iterator();
while(var2.hasNext()) {
key1 = (String)var2.next();
Model model1 = (Model)swagger.getDefinitions().get(key1);
this.process(model1);
}
}
return this;
}
private void updateTagDescriptions(Map<String, Tag> discoveredTags) {
if (swagger.getTags() != null) {
for (Tag tag : swagger.getTags()) {
Tag rightTag = discoveredTags.get(tag.getName());
if (rightTag != null && rightTag.getDescription() != null) {
tag.setDescription(rightTag.getDescription());
}
}
}
}
private void handleSubResource(String[] apiConsumes, String httpMethod, String[] apiProduces, Map<String, Tag> tags, Method method, ApiOperation apiOperation, String operationPath, Operation operation) {
if (isSubResource(httpMethod, method)) {
Class<?> responseClass = method.getReturnType();
if (apiOperation != null && !apiOperation.response().equals(Void.class) && !apiOperation.response().equals(void.class)) {
responseClass = apiOperation.response();
}
LOGGER.debug("handling sub-resource method " + method.toString() + " -> " + responseClass);
read(responseClass, operationPath, httpMethod, true, apiConsumes, apiProduces, tags, operation.getParameters());
}
}
protected void updateTagsForOperation(Operation operation, ApiOperation apiOperation) {
if (apiOperation == null) {
return;
}
for (String tag : apiOperation.tags()) {
if (!tag.isEmpty()) {
operation.tag(tag);
swagger.tag(new Tag().name(tag));
}
}
}
public static void sortSwagger(Swagger swagger) throws GenerateException {
if (swagger == null || swagger.getPaths() == null) {
return;
}
TreeMap<String, Path> sortedMap = new TreeMap<String, Path>();
if (swagger.getPaths() == null) {
return;
}
sortedMap.putAll(swagger.getPaths());
swagger.paths(sortedMap);
for (Path path : swagger.getPaths().values()) {
String methods[] = {"Get", "Delete", "Post", "Put", "Options", "Patch"};
for (String m : methods) {
sortResponses(path, m);
}
}
//reorder definitions
if (swagger.getDefinitions() != null) {
TreeMap<String, Model> defs = new TreeMap<String, Model>();
defs.putAll(swagger.getDefinitions());
swagger.setDefinitions(defs);
}
// order the tags
if (swagger.getTags() != null) {
Collections.sort(swagger.getTags(), new Comparator<Tag>() {
public int compare(final Tag a, final Tag b) {
return a.toString().toLowerCase().compareTo(b.toString().toLowerCase());
}
});
}
}
@Test
public void includeApiIfHiddenParameterIsTrueAndApiHiddenAttributeIsTrue() {
Swagger result = reader.read(HiddenApi.class, "", null, true, new String[0], new String[0], new HashMap<String, Tag>(), new ArrayList<Parameter>());
assertNotNull(result, "No Swagger object created");
assertFalse(result.getTags().isEmpty(), "Should contain api tags");
assertFalse(result.getPaths().isEmpty(), "Should contain operation paths");
}
@Test
public void discoverApiOperation() {
Tag expectedTag = new Tag();
expectedTag.name("atag");
Swagger result = reader.read(AnApi.class);
assertSwaggerResponseContents(expectedTag, result);
}
@Test
public void createNewSwaggerInstanceIfNoneProvided() {
JaxrsReader nullReader = new JaxrsReader(null, log);
Tag expectedTag = new Tag();
expectedTag.name("atag");
Swagger result = nullReader.read(AnApi.class);
assertSwaggerResponseContents(expectedTag, result);
}
private void assertSwaggerResponseContents(Tag expectedTag, Swagger result) {
assertNotNull(result, "No Swagger object created");
assertFalse(result.getTags().isEmpty(), "Should contain api tags");
assertTrue(result.getTags().contains(expectedTag), "Expected tag missing");
assertFalse(result.getPaths().isEmpty(), "Should contain operation paths");
assertTrue(result.getPaths().containsKey("/apath"), "Path missing from paths map");
io.swagger.models.Path path = result.getPaths().get("/apath");
assertFalse(path.getOperations().isEmpty(), "Should be a get operation");
}
public TagCoverage(Tag tag) {
this.tag = tag;
}
public Tag getTag() {
return tag;
}
public TagCoverage setTag(Tag tag) {
this.tag = tag;
return this;
}
protected Swagger read(Class<?> cls, Map<String, Tag> parentTags, List<Parameter> parentParameters) {
return read(cls, parentTags, parentParameters, new HashSet<Class<?>>());
}
private boolean resourceThisTagNotExist(Tag tag, List<Resource> resources) {
return resources.stream().noneMatch(resource -> tag.getName().equalsIgnoreCase(resource.getName()));
}