下面列出了io.swagger.annotations.SwaggerDefinition#io.swagger.models.Path 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Updates BasePath and Paths in Swagger
*
* @param swagger the API doc
* @param serviceId the unique service id
* @param apiDocInfo the service information
* @param hidden do not set Paths for automatically generated API doc
*/
protected void updatePaths(Swagger swagger, String serviceId, ApiDocInfo apiDocInfo, boolean hidden) {
ApiDocPath<Path> apiDocPath = new ApiDocPath<>();
String basePath = swagger.getBasePath();
if (swagger.getPaths() != null && !swagger.getPaths().isEmpty()) {
swagger.getPaths()
.forEach((originalEndpoint, path)
-> preparePath(path, apiDocPath, apiDocInfo, basePath, originalEndpoint, serviceId));
}
Map<String, Path> updatedPaths;
if (apiDocPath.getPrefixes().size() == 1) {
swagger.setBasePath(OpenApiUtil.SEPARATOR + apiDocPath.getPrefixes().iterator().next() + OpenApiUtil.SEPARATOR + serviceId);
updatedPaths = apiDocPath.getShortPaths();
} else {
swagger.setBasePath("");
updatedPaths = apiDocPath.getLongPaths();
}
if (!hidden) {
swagger.setPaths(updatedPaths);
}
}
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;
}
};
}
private void mapRequestMapping(RequestMapping requestMapping, Method method, Map<String, Path> operationsMap, String controllerClassName,
String baseControllerPath) {
List<HttpMethod> httpMethods = Arrays.stream(requestMapping.method())
.map(this::getSpringMethod)
.collect(toList());
httpMethods.forEach(httpMethod -> {
Operation operation = mapOperation(requestMapping.name(), httpMethod, method, requestMapping.produces(),
requestMapping.consumes(), controllerClassName);
String path = ObjectUtils.defaultIfNull(getFirstFromArray(requestMapping.value()), getFirstFromArray(requestMapping.path()));
updateOperationsMap(prepareUrl(baseControllerPath, "/", path), operationsMap,
pathItem -> setContentBasedOnHttpMethod(pathItem, httpMethod, operation)
);
});
}
private void validatePaths(Map<String, Path> actualPaths, Map<String, Path> expectedPaths) {
if (MapUtils.isNotEmpty(expectedPaths)) {
softAssertions.assertThat(actualPaths).as("Checking Paths").isNotEmpty();
if (MapUtils.isNotEmpty(actualPaths)) {
softAssertions.assertThat(actualPaths.keySet()).as("Checking Paths").containsAll(expectedPaths.keySet());
for (Map.Entry<String, Path> actualPathEntry : actualPaths.entrySet()) {
Path expectedPath = expectedPaths.get(actualPathEntry.getKey());
Path actualPath = actualPathEntry.getValue();
String pathName = actualPathEntry.getKey();
validatePath(pathName, actualPath, expectedPath);
}
}
} else {
softAssertions.assertThat(actualPaths).as("Checking Paths").isNullOrEmpty();
}
}
public SwaggerOperations(Swagger swagger) {
this.swagger = swagger;
Map<String, Path> paths = swagger.getPaths();
if (paths == null) {
return;
}
for (Entry<String, Path> pathEntry : paths.entrySet()) {
for (Entry<HttpMethod, Operation> operationEntry : pathEntry.getValue().getOperationMap().entrySet()) {
Operation operation = operationEntry.getValue();
if (StringUtils.isEmpty(operation.getOperationId())) {
throw new IllegalStateException(String
.format("OperationId can not be empty, path=%s, httpMethod=%s.",
pathEntry.getKey(), operationEntry.getKey()));
}
SwaggerOperation swaggerOperation = new SwaggerOperation(swagger, pathEntry.getKey(), operationEntry.getKey(),
operation);
if (operations.putIfAbsent(operation.getOperationId(), swaggerOperation) != null) {
throw new IllegalStateException(
"please make sure operationId is unique, duplicated operationId is " + operation.getOperationId());
}
}
}
}
/**
* Provide a method to validate swagger. This method is now implemented to check common errors, and the logic
* will be changed when necessary. For internal use only.
*/
public static void validateSwagger(Swagger swagger) {
Map<String, Path> paths = swagger.getPaths();
if (paths == null) {
return;
}
for (Path path : paths.values()) {
Operation operation = path.getPost();
if (operation == null) {
continue;
}
for (Parameter parameter : operation.getParameters()) {
if (BodyParameter.class.isInstance(parameter) &&
((BodyParameter) parameter).getSchema() == null) {
throw new ServiceCombException("swagger validator: body parameter schema is empty.");
}
}
}
}
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();
}
public void process(Path path) {
this.paths.add(path);
Iterator var2;
if(path.getParameters() != null) {
var2 = path.getParameters().iterator();
while(var2.hasNext()) {
Parameter operation = (Parameter)var2.next();
this.process(operation);
}
}
if(path.getOperations() != null) {
var2 = path.getOperations().iterator();
while(var2.hasNext()) {
Operation operation1 = (Operation)var2.next();
this.process(operation1);
}
}
}
@Test
public void shouldReturnPathsPrefixedIfPrefixConfigured() {
// given
Swagger swagger = buildSwaggerFrom("/swagger.json");
Properties properties = new Properties();
String configuredPathPrefix = "/foo";
properties.put("assertj.swagger.pathsPrependExpected", configuredPathPrefix);
SwaggerAssertionConfig swaggerAssertionConfig = new SwaggerAssertionConfig(properties);
// when
Map<String, Path> paths = new DummyValidator().findExpectedPaths(swagger, swaggerAssertionConfig);
// then configured prefix takes precedence over base path
paths.entrySet().forEach(e -> {
assertThat(e.getKey(), startsWith(configuredPathPrefix));
assertThat(e.getKey(), not(containsString(swagger.getBasePath())));
});
}
protected Class<?> getSubResourceWithJaxRsSubresourceLocatorSpecs(Method method) {
final Class<?> rawType = method.getReturnType();
final Class<?> type;
if (Class.class.equals(rawType)) {
type = getClassArgument(method.getGenericReturnType());
if (type == null) {
return null;
}
} else {
type = rawType;
}
if (method.getAnnotation(javax.ws.rs.Path.class) != null) {
if (extractOperationMethod(null, method, null) == null) {
return type;
}
}
return null;
}
/**
* Builds a path operation depending on generation mode.
*
* @param operation operation
*/
private void buildOperation(MarkupDocBuilder markupDocBuilder, SwaggerPathOperation operation, Swagger2MarkupConfig config) {
if (config.isSeparatedOperationsEnabled()) {
MarkupDocBuilder pathDocBuilder = copyMarkupDocBuilder(markupDocBuilder);
applyPathOperationComponent(pathDocBuilder, operation);
java.nio.file.Path operationFile = context.getOutputPath().resolve(operationDocumentNameResolver.apply(operation));
pathDocBuilder.writeToFileWithoutExtension(operationFile, StandardCharsets.UTF_8);
if (logger.isDebugEnabled()) {
logger.debug("Separate operation file produced : '{}'", operationFile);
}
buildOperationRef(markupDocBuilder, operation);
} else {
applyPathOperationComponent(markupDocBuilder, operation);
}
if (logger.isDebugEnabled()) {
logger.debug("Operation processed : '{}' (normalized id = '{}')", operation, normalizeName(operation.getId()));
}
}
@Override
public void path(ListSchemaNode lN, PathSegment pathCtx) {
final Path operationalPath = operationalOperations(lN, pathCtx);
ODLRestconfPathPrinter operationalPathPrinter = new ODLRestconfPathPrinter(pathCtx, useModuleName);
swagger.path(operational + operationalPathPrinter.path(), operationalPath);
if (!pathCtx.isReadOnly()) {
final Path configPath = operations(lN, pathCtx);
ODLRestconfPathPrinter configPathPrinter = new ODLRestconfPathPrinter(pathCtx, useModuleName);
swagger.path(data + configPathPrinter.path(), configPath);
if(fullCrud) {
//referencing list path
final Path list = new Path();
list.post(new PostOperationGenerator(pathCtx, dataObjectBuilder, true).execute(lN));
ODLRestconfPathPrinter postPrinter = new ODLRestconfPathPrinter(pathCtx, useModuleName, true);
swagger.path(data + postPrinter.path(), list);
}
}
}
@Test
public void test_3() throws Exception
{
Swagger swagger = new Swagger();
String restJavaPackage = "org.finra.herd.swaggergen.test.restControllerProcessor.case3";
String tagPatternTemplate = "(?<tag>.+?)RestController";
Class<?> modelErrorClass = null;
new RestControllerProcessor(LOG, swagger, restJavaPackage, tagPatternTemplate, modelErrorClass);
List<String> operationIds = new ArrayList<>();
for (Path path : swagger.getPaths().values())
{
for (Operation operation : path.getOperations())
{
operationIds.add(operation.getOperationId());
}
}
assertEquals(2, operationIds.size());
assertTrue(operationIds.contains("Test3.duplicate"));
assertTrue(operationIds.contains("Test3.duplicate1"));
}
@org.junit.Test
public void testGenerateReadOnlyModule() {
final Consumer<Path> onlyGetOperationExists = p -> {
assertEquals(1, p.getOperations().size());
assertNotNull(p.getGet());
};
//when
swaggerFor("read-only.yang");
//then
// for read only operations only one get operation
swagger.getPaths().entrySet().stream().filter(e -> e.getKey().contains("c2")).map(Map.Entry::getValue)
.forEach(onlyGetOperationExists);
}
@Override
public void run(ApplicationConfiguration configuration, Environment environment) throws Exception {
environment.jersey().register(new UriConnegFilter(new MediaTypeMappings(), Collections.<String, String>emptyMap()));
Map<String, Object> props = new HashMap<>();
props.put(MessageProperties.LEGACY_WORKERS_ORDERING, true);
environment.jersey().getResourceConfig().addProperties(props);
addWriters(environment.jersey());
configureCors(environment);
//TODO: This path should not be hard coded.
configureSwagger(environment, "scigraph");
environment.servlets().
addFilter("Swagger Filter", factory.getInjector().getInstance(SwaggerFilter.class))
.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/swagger.json", "/swagger");
environment.servlets().addFilter("swaggerDocResolver", new SwaggerDocUrlFilter())
.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*");
DynamicCypherResourceFactory cypherFactory = factory.getInjector().getInstance(DynamicCypherResourceFactory.class);
for (Map.Entry<String,Path> config: configuration.getCypherResources().entrySet()) {
environment.jersey().getResourceConfig().registerResources(cypherFactory.create(config.getKey(), config.getValue()).getBuilder().build());
}
}
private void validatePaths(Map<String, Path> actualPaths, Map<String, Path> expectedPaths) {
if (MapUtils.isNotEmpty(expectedPaths)) {
softAssertions.assertThat(actualPaths).as("Checking Paths").isNotEmpty();
if (MapUtils.isNotEmpty(actualPaths)) {
softAssertions.assertThat(actualPaths.keySet()).as("Checking Paths").hasSameElementsAs(expectedPaths.keySet());
for (Map.Entry<String, Path> actualPathEntry : actualPaths.entrySet()) {
Path expectedPath = expectedPaths.get(actualPathEntry.getKey());
Path actualPath = actualPathEntry.getValue();
String pathName = actualPathEntry.getKey();
validatePath(pathName, actualPath, expectedPath);
}
}
} else {
softAssertions.assertThat(actualPaths).as("Checking Paths").isNullOrEmpty();
}
}
/**
*
* @param swagger
* @return
*/
private List<InterfaceDiagram> processSwaggerPaths(Swagger swagger) {
LOGGER.entering(LOGGER.getName(), "processSwaggerPaths");
List<InterfaceDiagram> interfaceDiagrams = new ArrayList<InterfaceDiagram>();
Map<String, Path> paths = swagger.getPaths();
for (Map.Entry<String, Path> entry : paths.entrySet()) {
Path pathObject = entry.getValue();
LOGGER.info("Processing Path --> " + entry.getKey());
List<Operation> operations = pathObject.getOperations();
String uri = entry.getKey();
for (Operation operation : operations) {
interfaceDiagrams.add(getInterfaceDiagram(operation, uri));
}
}
LOGGER.exiting(LOGGER.getName(), "processSwaggerPaths");
return interfaceDiagrams;
}
@Any
public void execute(HttpServletResponse response) throws IOException {
Swagger swagger = new Swagger();
swagger.setBasePath("/127.0.0.1");
//
Operation operation = new Operation();
Path apiPath = new Path();
apiPath.setPost(operation);
// apiPath.setPost();
swagger.setPaths(new LinkedHashMap<String, Path>() {{
put("/aaa", apiPath);
}});
//
//
String asString = Json.pretty().writeValueAsString(swagger);
PrintWriter writer = response.getWriter();
writer.write(asString);
writer.flush();
}
private Path getNewWildCardPathObject(Path userDefinedWildCardPathObject) {
Preconditions.checkNotNull(
userDefinedWildCardPathObject, "userDefinedWildCardPathObject cannot be null");
Path path = new Path();
if (userDefinedWildCardPathObject.getGet() == null) {
path.set("get", constructReservedOperation("Get"));
}
if (userDefinedWildCardPathObject.getDelete() == null) {
path.set("delete", constructReservedOperation("Delete"));
}
if (userDefinedWildCardPathObject.getPatch() == null) {
path.set("patch", constructReservedOperation("Patch"));
}
if (userDefinedWildCardPathObject.getPost() == null) {
path.set("post", constructReservedOperation("Post"));
}
if (userDefinedWildCardPathObject.getPut() == null) {
path.set("put", constructReservedOperation("Put"));
}
return path;
}
private void checkDuplicateOperations(Swagger actual) {
Multimap<String, String> operationIds = HashMultimap.create();
for (Entry<String, Path> pathEntry : actual.getPaths().entrySet()) {
for (Entry<HttpMethod, Operation> opEntry : pathEntry.getValue().getOperationMap()
.entrySet()) {
operationIds
.put(opEntry.getValue().getOperationId(), pathEntry.getKey() + "|" + opEntry.getKey());
}
}
int duplicateOperationIdCount = 0;
for (Entry<String, Collection<String>> entry : operationIds.asMap().entrySet()) {
if (entry.getValue().size() > 1) {
System.out.println("Duplicate operation id: " + entry);
duplicateOperationIdCount++;
}
}
assertThat(duplicateOperationIdCount).named("Duplicate operation ids").isEqualTo(0);
}
private Map<String, Path> createPaths(OpenApiV2GeneratorConfig config) {
ClassPathScanningCandidateComponentProvider scanner = createClassPathScanningCandidateComponentProvider();
scanner.addIncludeFilter(new AnnotationTypeFilter(RestController.class));
List<Class<?>> controllerClasses = new ArrayList<>();
List<String> packagesWithoutRegex = removeRegexFormatFromPackages(controllerBasePackages);
for (String controllerPackage : packagesWithoutRegex) {
logger.debug("Scanning controller package=[{}]", controllerPackage);
for (BeanDefinition beanDefinition : scanner.findCandidateComponents(controllerPackage)) {
logger.debug("Scanning controller class=[{}]", beanDefinition.getBeanClassName());
controllerClasses.add(getClass(beanDefinition));
}
}
return operationsTransformer.transformOperations(controllerClasses, config);
}
private void fixDuplicateOperationIds(Map<String, Path> operationsMap) {
Map<String, Integer> operationIdCount = new HashMap<>();
operationsMap.values().forEach(pathItem -> {
handleOperation(pathItem.getHead(), operationIdCount);
handleOperation(pathItem.getOptions(), operationIdCount);
handleOperation(pathItem.getPost(), operationIdCount);
handleOperation(pathItem.getPatch(), operationIdCount);
handleOperation(pathItem.getPut(), operationIdCount);
handleOperation(pathItem.getGet(), operationIdCount);
handleOperation(pathItem.getDelete(), operationIdCount);
});
}
private void createOperation(Method method, String baseControllerPath, Map<String, Path> operationsMap, String controllerClassName) {
logger.debug("Transforming {} controller method", method.getName());
getAnnotation(method, PostMapping.class).ifPresent(postMapping -> mapPost(postMapping, method, operationsMap, controllerClassName, baseControllerPath));
getAnnotation(method, PutMapping.class).ifPresent(putMapping -> mapPut(putMapping, method, operationsMap, controllerClassName, baseControllerPath));
getAnnotation(method, PatchMapping.class).ifPresent(patchMapping -> mapPatch(patchMapping, method, operationsMap, controllerClassName,
baseControllerPath));
getAnnotation(method, GetMapping.class).ifPresent(getMapping -> mapGet(getMapping, method, operationsMap, controllerClassName, baseControllerPath));
getAnnotation(method, DeleteMapping.class).ifPresent(deleteMapping -> mapDelete(deleteMapping, method, operationsMap, controllerClassName,
baseControllerPath));
getAnnotation(method, RequestMapping.class).ifPresent(requestMapping -> mapRequestMapping(requestMapping, method, operationsMap, controllerClassName,
baseControllerPath));
}
private void setContentBasedOnHttpMethod(Path pathItem, HttpMethod method, Operation operation) {
if (method == null) {
throw new IllegalArgumentException("RequestMethod in RequestMapping must have at least one value");
}
switch (method) {
case GET:
pathItem.setGet(operation);
return;
case PUT:
pathItem.setPut(operation);
return;
case POST:
pathItem.setPost(operation);
return;
case PATCH:
pathItem.setPatch(operation);
return;
case HEAD:
pathItem.setHead(operation);
return;
case OPTIONS:
pathItem.setOptions(operation);
return;
case DELETE:
pathItem.setDelete(operation);
}
}
private void mapDelete(DeleteMapping deleteMapping, Method method, Map<String, Path> operationsMap, String controllerClassName,
String baseControllerPath) {
Operation operation = mapOperation(deleteMapping.name(), HttpMethod.DELETE, method, deleteMapping.produces(), deleteMapping.consumes(), controllerClassName);
String path = ObjectUtils.defaultIfNull(getFirstFromArray(deleteMapping.value()), getFirstFromArray(deleteMapping.path()));
updateOperationsMap(prepareUrl(baseControllerPath, "/", path), operationsMap, pathItem -> pathItem.setDelete(operation));
}
@Test
public void shouldReturnPathsPrefixedIfBasePathSet() {
// given
Swagger swagger = buildSwaggerFrom("/swagger.json");
// when
Map<String, Path> paths = new DummyValidator().getPathsIncludingBasePath(swagger);
// then
paths.entrySet().forEach(e -> assertThat(e.getKey(), startsWith(swagger.getBasePath())));
}
@Test
public void shouldReturnPlainPathsIfNoBasePathSet() {
// given
Swagger swagger = buildSwaggerFrom("/swagger_with_path_prefixes.json");
// when
Map<String, Path> paths = new DummyValidator().getPathsIncludingBasePath(swagger);
// then
paths.entrySet().forEach(e -> assertThat(e.getKey(), startsWith("/v2")));
}
@Before
public void setup() {
when(swagger.getPaths()).thenReturn(ImmutableMap.of(
TEST_PATH_1, new Path().get(getOperationPath1).post(postOperationPath1),
TEST_PATH_2, new Path().get(getOperationPath2).post(postOperationPath2)));
underTest = new TestParameterContributor(HTTP_METHODS, PATHS, PARAMS);
}
String getPath(javax.ws.rs.Path classLevelPath, javax.ws.rs.Path methodLevelPath, String parentPath)
{
if (classLevelPath == null && methodLevelPath == null) {
return null;
}
StringBuilder b = new StringBuilder();
if (parentPath != null && !"".equals(parentPath) && !"/".equals(parentPath)) {
if (!parentPath.startsWith("/")) {
parentPath = "/" + parentPath;
}
if (parentPath.endsWith("/")) {
parentPath = parentPath.substring(0, parentPath.length() - 1);
}
b.append(parentPath);
}
if (classLevelPath != null) {
b.append(classLevelPath.value());
}
if (methodLevelPath != null && !"/".equals(methodLevelPath.value())) {
String methodPath = methodLevelPath.value();
if (!methodPath.startsWith("/") && !b.toString().endsWith("/")) {
b.append("/");
}
if (methodPath.endsWith("/")) {
methodPath = methodPath.substring(0, methodPath.length() - 1);
}
b.append(methodPath);
}
String output = b.toString();
if (!output.startsWith("/")) {
output = "/" + output;
}
if (output.endsWith("/") && output.length() > 1) {
return output.substring(0, output.length() - 1);
}
else {
return output;
}
}
@Test
public void shouldReturnPathsPrefixedIfBasePathSet() {
// given
Swagger swagger = buildSwaggerFrom("/swagger.json");
SwaggerAssertionConfig swaggerAssertionConfig = new SwaggerAssertionConfig(new Properties());
// when
Map<String, Path> paths = new DummyValidator().findExpectedPaths(swagger, swaggerAssertionConfig);
// then
paths.entrySet().forEach(e -> assertThat(e.getKey(), startsWith(swagger.getBasePath())));
}