下面列出了io.swagger.annotations.SwaggerDefinition#io.swagger.models.Operation 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* This method will generate path and query parameters in the swagger document.
*
* @param method method of API resource.
* @param operation swagger operation object.
* @param parameterList list of parameters.
*/
private static void generatePathAndQueryParameters(String method, Operation operation,
List<AxisResourceParameter> parameterList) {
if (!parameterList.isEmpty()) {
for (AxisResourceParameter resourceParameter : parameterList) {
AxisResourceParameter.ParameterType resourceParameterType =
resourceParameter.getParameterType();
if (resourceParameterType.equals(AxisResourceParameter.ParameterType.URL_PARAMETER)) {
PathParameter pathParameter = new PathParameter();
pathParameter.setName(resourceParameter.getParameterName());
pathParameter.setType(resourceParameter.getParameterDataType());
pathParameter.required(true);
operation.addParameter(pathParameter);
} else if (resourceParameterType
.equals(AxisResourceParameter.ParameterType.QUERY_PARAMETER) && "GET".equals(method)) {
// Currently handling query parameter only for GET requests.
QueryParameter queryParameter = new QueryParameter();
queryParameter.setName(resourceParameter.getParameterName());
queryParameter.setType(resourceParameter.getParameterDataType());
queryParameter.required(true);
operation.addParameter(queryParameter);
}
}
}
}
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 Operation mapOperation(String operationName, HttpMethod httpMethod, Method method, String[] produces, String[] consumes, String controllerClassName) {
Operation operation = new Operation();
operation.setOperationId(getOperationId(operationName, method, httpMethod));
operation.setSummary(StringUtils.isBlank(operationName) ? operationName : method.getName());
operation.setTags(singletonList(classNameToTag(controllerClassName)));
operation.setResponses(createApiResponses(method));
operation.setParameters(transformParameters(method));
if (isNotEmpty(consumes)) {
operation.setConsumes(asList(consumes));
}
if (isNotEmpty(produces)) {
operation.setProduces(asList(produces));
}
if (isHttpMethodWithRequestBody(httpMethod)) {
io.swagger.models.parameters.Parameter requestBody = createRequestBody(method, getFirstFromArray(consumes));
if (requestBody != null) {
operation.getParameters().add(requestBody);
}
}
applyAnnotationsForOperation(operation, method.getAnnotations());
operationInterceptors.forEach(interceptor -> interceptor.intercept(method, operation));
return operation;
}
@Override
public Operation execute(DataSchemaNode node) {
final Operation put = defaultOperation();
final RefModel definition = new RefModel(getDefinitionId(node));
put.summary("creates or updates " + getName(node));
String description = node.getDescription() == null ? "creates or updates " + getName(node) :
node.getDescription();
put.description(description);
put.parameter(new BodyParameter()
.name(getName(node) + ".body-param")
.schema(definition)
.description(getName(node) + " to be added or updated"));
put.response(201, new Response().description("Object created"));
put.response(204, new Response().description("Object modified"));
return put;
}
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 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());
}
private Boolean isApiKeyRequired(Operation op) {
Optional<Map.Entry<String, SecuritySchemeDefinition>> apiKeySecurityDefinition = Optional.empty();
if (swagger.getSecurityDefinitions() != null) {
apiKeySecurityDefinition = swagger.getSecurityDefinitions().entrySet()
.stream().filter(p -> p.getValue().getType().equals("apiKey")).findFirst();
}
if (!apiKeySecurityDefinition.isPresent()) {
return false;
}
String securityDefinitionName = apiKeySecurityDefinition.get().getKey();
if (op.getSecurity() != null) {
return op.getSecurity().stream().anyMatch(s -> s.containsKey(securityDefinitionName));
}
if (swagger.getSecurityRequirement() != null) {
return swagger.getSecurityRequirement().stream().anyMatch(s -> s.getName().equals(securityDefinitionName));
}
return false;
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation,
Map<String, Model> definitions, Swagger swagger) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger);
if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
Response methodResponse = findMethodResponse(operation.getResponses());
if (methodResponse != null) {
if (methodResponse.getSchema() != null) {
CodegenProperty cm = fromProperty("response", methodResponse.getSchema());
op.vendorExtensions.put("x-codegen-response", cm);
if(cm.datatype == "HttpContent")
{
op.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
}
}
}
}
return op;
}
@Test
public void test() {
Swagger swagger = SwaggerGenerator.generate(ResponseMetaImpl.class);
Operation operation = swagger.getPath("/add").getPost();
ResponsesMeta meta = new ResponsesMeta();
meta.init(swagger, operation);
JavaType resp = meta.findResponseType(200);
Assert.assertEquals(Integer.class, resp.getRawClass());
resp = meta.findResponseType(201);
Assert.assertEquals(Integer.class, resp.getRawClass());
resp = meta.findResponseType(400);
Assert.assertEquals(String.class, resp.getRawClass());
resp = meta.findResponseType(401);
Assert.assertEquals(Long.class, resp.getRawClass());
resp = meta.findResponseType(500);
// changed to Object for new version to keep user defined error data not lose and can be parsed.
Assert.assertEquals(Object.class, resp.getRawClass());
}
private void validateOperation(Operation actualOperation, Operation expectedOperation, String path, String httpMethod) {
String message = String.format("Checking '%s' operation of path '%s'", httpMethod, path);
if (expectedOperation != null) {
softAssertions.assertThat(actualOperation).as(message).isNotNull();
if (actualOperation != null) {
//Validate consumes
validateList(schemaObjectResolver.getActualConsumes(actualOperation),
schemaObjectResolver.getExpectedConsumes(expectedOperation),
String.format("Checking '%s' of '%s' operation of path '%s'", "consumes", httpMethod, path));
//Validate produces
validateList(schemaObjectResolver.getActualProduces(actualOperation),
schemaObjectResolver.getExpectedProduces(expectedOperation),
String.format("Checking '%s' of '%s' operation of path '%s'", "produces", httpMethod, path));
//Validate parameters
validateParameters(actualOperation.getParameters(), expectedOperation.getParameters(), httpMethod, path);
//Validate responses
validateResponses(actualOperation.getResponses(), expectedOperation.getResponses(), httpMethod, path);
}
} else {
softAssertions.assertThat(actualOperation).as(message).isNull();
}
}
public void process(Operation operation) {
this.operations.add(operation);
Iterator var2;
if(operation.getParameters() != null) {
var2 = operation.getParameters().iterator();
while(var2.hasNext()) {
Parameter key = (Parameter)var2.next();
this.process(key);
}
}
if(operation.getResponses() != null) {
var2 = operation.getResponses().keySet().iterator();
while(var2.hasNext()) {
String key1 = (String)var2.next();
Response response = (Response)operation.getResponses().get(key1);
this.process(response);
}
}
}
private static AuthHandler getAuthHandler(SwaggerAuthHandlerFactory authHandlerFactory, Swagger swagger, Operation operation) {
AuthHandler authHandler = null;
if(authHandlerFactory != null) {
if(operation.getSecurity() != null) {
if(!operation.getSecurity().isEmpty()) {
authHandler = authHandlerFactory.createAuthHandler(operation.getSecurity());
}
} else if(swagger.getSecurity() != null && !swagger.getSecurity().isEmpty()) {
List<Map<String, List<String>>> security = swagger.getSecurity().stream()
.map(SecurityRequirement::getRequirements)
.collect(Collectors.toList());
authHandler = authHandlerFactory.createAuthHandler(security);
}
}
return authHandler;
}
/**
* Processes the return value of a RequestMapping annotated method.
*
* @param returnType the return type.
* @param operation the operation.
* @param returnDescription the description of the return value.
*
* @throws MojoExecutionException if the return type isn't an XmlType.
*/
private void processRestMethodReturnValue(Class<?> returnType, Operation operation, String returnDescription) throws MojoExecutionException
{
log.debug("Processing REST method return value \"" + returnType.getName() + "\".");
// Add the class name to the list of classes which we will create an example for.
exampleClassNames.add(returnType.getSimpleName());
// Add the success response
operation.response(200, new Response().description(returnDescription == null ? "Success" : returnDescription)
.schema(new RefProperty(getXmlType(returnType).name().trim())));
// If we have an error class, add that as the default response.
if (modelErrorClass != null)
{
operation.defaultResponse(new Response().description("General Error").schema(new RefProperty(getXmlType(modelErrorClass).name().trim())));
}
}
@Override
public Operation execute(DataSchemaNode node) {
final Operation post = dropLastSegmentParameters ? listOperation() : defaultOperation();
final RefModel definition = new RefModel(getDefinitionId(node));
post.summary("creates " + getName(node));
String description = node.getDescription() == null ? "creates " + getName(node) :
node.getDescription();
post.description(description);
post.parameter(new BodyParameter()
.name(getName(node) + ".body-param")
.schema(definition)
.description(getName(node) + " to be added to list"));
post.response(201, new Response().description("Object created"));
post.response(409, new Response().description("Object already exists"));
return post;
}
@SuppressWarnings("deprecation")
private void addResponse(Operation operation, ApiResponse apiResponse, JsonView jsonView) {
Map<String, Property> responseHeaders = parseResponseHeaders(apiResponse.responseHeaders(), jsonView);
Map<String, Object> examples = parseExamples(apiResponse.examples());
Response response = new Response().description(apiResponse.message()).headers(responseHeaders);
response.setExamples(examples);
if (apiResponse.code() == 0) {
operation.defaultResponse(response);
} else {
operation.response(apiResponse.code(), response);
}
if (StringUtils.isNotEmpty(apiResponse.reference())) {
response.schema(new RefProperty(apiResponse.reference()));
} else if (!isVoid(apiResponse.response())) {
Type responseType = apiResponse.response();
final Property property = ModelConverters.getInstance().readAsProperty(responseType, jsonView);
if (property != null) {
response.schema(ContainerWrapper.wrapContainer(apiResponse.responseContainer(), property));
appendModels(responseType);
}
}
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation,
Map<String, Model> definitions, Swagger swagger) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions,
swagger);
op.imports.add("Map");
op.imports.remove("Request");
op.imports.remove("Response");
if (validateRequest) {
op.imports.remove("Result");
}
if (generatedFlowBasePackage != null) {
ProcessNamer processNamer = new ProcessNamer(generatedFlowBasePackage, path);
String processName = processNamer.getPackage() + "/"
+ processNamer.getName(op.httpMethod);
op.vendorExtensions.put("generatedFlow", processName);
}
return op;
}
/**
*
* @param operation
* @return
*/
private List<ClassRelation> getInterfaceRelations(Operation operation,String errorClassName) {
List<ClassRelation> relations = new ArrayList<ClassRelation>();
relations.addAll(getInterfaceRelatedResponses(operation));
relations.addAll(getInterfaceRelatedInputs(operation));
if(StringUtils.isNotEmpty(errorClassName))
{
relations.add(getErrorClass(errorClassName));
}
return filterUnique(relations,true);
}
/**
* Gets a list of scopes using the security requirements
*
* @param oauth2SchemeKey OAuth2 security element key
* @param operation Swagger path operation
* @return list of scopes using the security requirements
*/
private List<String> getScopeOfOperations(String oauth2SchemeKey, Operation operation) {
List<Map<String, List<String>>> security = operation.getSecurity();
if (security != null) {
for (Map<String, List<String>> requirement : security) {
if (requirement.get(oauth2SchemeKey) != null) {
return requirement.get(oauth2SchemeKey);
}
}
}
return getScopeOfOperationsFromExtensions(operation);
}
@Test
public void testGetMappingKey() {
Operation operation = Mockito.mock(Operation.class);
scenarioMapper.setScenarioList(Arrays.asList(new HttpOperationScenario("/issues/foos", HttpMethod.GET, operation, Collections.emptyMap()),
new HttpOperationScenario("/issues/foos", HttpMethod.POST, operation, Collections.emptyMap()),
new HttpOperationScenario("/issues/foo/{id}", HttpMethod.GET, operation, Collections.emptyMap()),
new HttpOperationScenario("/issues/foo/detail", HttpMethod.GET, operation, Collections.emptyMap()),
new HttpOperationScenario("/issues/bars", HttpMethod.GET, operation, Collections.emptyMap()),
new HttpOperationScenario("/issues/bar/{id}", HttpMethod.GET, operation, Collections.emptyMap()),
new HttpOperationScenario("/issues/bar/detail", HttpMethod.GET, operation, Collections.emptyMap())));
when(operation.getOperationId())
.thenReturn("fooListScenario")
.thenReturn("fooListPostScenario")
.thenReturn("barListScenario")
.thenReturn("fooScenario")
.thenReturn("barScenario")
.thenReturn("fooDetailScenario")
.thenReturn("barDetailScenario");
Assert.assertEquals(scenarioMapper.getMappingKey(new HttpMessage().method(HttpMethod.GET)), "default");
Assert.assertEquals(scenarioMapper.getMappingKey(new HttpMessage().method(HttpMethod.POST)), "default");
Assert.assertEquals(scenarioMapper.getMappingKey(new HttpMessage().method(HttpMethod.GET).path("/issues")), "default");
Assert.assertEquals(scenarioMapper.getMappingKey(new HttpMessage().method(HttpMethod.GET).path("/issues/foos")), "fooListScenario");
Assert.assertEquals(scenarioMapper.getMappingKey(new HttpMessage().method(HttpMethod.POST).path("/issues/foos")), "fooListPostScenario");
Assert.assertEquals(scenarioMapper.getMappingKey(new HttpMessage().method(HttpMethod.PUT).path("/issues/foos")), "default");
Assert.assertEquals(scenarioMapper.getMappingKey(new HttpMessage().method(HttpMethod.GET).path("/issues/bars")), "barListScenario");
Assert.assertEquals(scenarioMapper.getMappingKey(new HttpMessage().method(HttpMethod.DELETE).path("/issues/bars")), "default");
Assert.assertEquals(scenarioMapper.getMappingKey(new HttpMessage().method(HttpMethod.GET).path("/issues/foo/1")), "fooScenario");
Assert.assertEquals(scenarioMapper.getMappingKey(new HttpMessage().method(HttpMethod.GET).path("/issues/bar/1")), "barScenario");
Assert.assertEquals(scenarioMapper.getMappingKey(new HttpMessage().method(HttpMethod.GET).path("/issues/foo/detail")), "fooDetailScenario");
Assert.assertEquals(scenarioMapper.getMappingKey(new HttpMessage().method(HttpMethod.GET).path("/issues/bar/detail")), "barDetailScenario");
scenarioMapper.setUseDefaultMapping(false);
Assert.assertThrows(CitrusRuntimeException.class, () -> scenarioMapper.getMappingKey(new HttpMessage().method(HttpMethod.GET)));
Assert.assertThrows(CitrusRuntimeException.class, () -> scenarioMapper.getMappingKey(new HttpMessage().method(HttpMethod.GET).path("/issues")));
}
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));
}
public static void setCommaConsumes(Operation operation, String commaConsumes) {
if (StringUtils.isEmpty(commaConsumes)) {
return;
}
setConsumes(operation, commaConsumes.split(","));
}
/**
* Returns all parameters for the operation. Note: According to the spec, parameters defined
* inside the operations overrides the parameters defined in the path scope which has the same
* name and location values (example name : 'shelveId' and location : 'query').
*/
public static ImmutableList<Parameter> getAllResolvedParameters(
Operation operation, Path parentPath, final DiagCollector diagCollector, Location location) {
List<Parameter> allResolvedParameters = new ArrayList<>();
// First populate all the parameters defined in the operation.
if (operation.getParameters() != null) {
ImmutableList<Parameter> resolvedParameters =
getResolvedParameters(
diagCollector, ImmutableList.copyOf(operation.getParameters()), location);
allResolvedParameters.addAll(resolvedParameters);
}
FluentIterable<Parameter> fluentAllParameters = FluentIterable.from(allResolvedParameters);
// Now populate shared parameters that were not overridden inside the operation.
if (parentPath.getParameters() != null) {
ImmutableList<Parameter> resolvedSharedParameters =
getResolvedParameters(
diagCollector, ImmutableList.copyOf(parentPath.getParameters()), location);
for (final Parameter sharedParam : resolvedSharedParameters) {
boolean overriddenInOperation =
fluentAllParameters.anyMatch(
new Predicate<Parameter>() {
@Override
public boolean apply(Parameter parameter) {
return parameter.getName().equals(sharedParam.getName())
&& parameter.getIn().equals(sharedParam.getIn());
}
});
if (!overriddenInOperation) {
allResolvedParameters.add(sharedParam);
}
}
}
return ImmutableList.copyOf(allResolvedParameters);
}
private void applyAnnotationsForOperation(Operation operation, Annotation[] annotations) {
asList(annotations).forEach(annotation -> {
if (annotation instanceof Deprecated) {
operation.setVendorExtension("x-deprecated", true);
}
});
}
@Test
public void correctResponsesOperationFixEmptyDescription() {
Response response = new Response();
Operation operation = new Operation();
operation.addResponse("200", response);
SwaggerUtils.correctResponses(operation);
Assert.assertEquals("response of 200", response.getDescription());
}
@Override
public void applyDescription(Operation operation, Method method) {
final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
if (apiOperation != null && StringUtils.isNotBlank(apiOperation.notes())) {
operation.description(apiOperation.notes());
}
operation.description(operation.getDescription() == null ? outputMethod(method)
: (outputMethod(method) + operation.getDescription()));
}
private Operation constructReservedOperation(String suffix) {
Operation getOperation = new Operation();
getOperation.setOperationId(
String.format("Google_Autogenerated_Unrecognized_%s_Method_Call", suffix));
// Clear all the control plane settings that do not apply to the wild card operations.
getOperation.setSecurity(new ArrayList<Map<String, List<String>>>());
return getOperation;
}
@Override
public List<Condition> createCondition(Operation operation) {
ConditionPredicate predicate = new FullStatusConditionPredicate(operation.getResponses().keySet());
Condition condition = new SinglePredicateCondition(
"only declared status",
"",
predicate
);
return Collections.singletonList(condition);
}
protected void doProcess(OperationGenerator operationGenerator, String[] paths, String[] pathValues,
RequestMethod requestMethod, String[] consumes, String[] produces) {
Operation operation = operationGenerator.getOperation();
// paths same to pathValues
this.processPath(operationGenerator, paths);
this.processPath(operationGenerator, pathValues);
if (requestMethod != null) {
operationGenerator.setHttpMethod(requestMethod.name());
}
SwaggerUtils.setConsumes(operation, consumes);
SwaggerUtils.setProduces(operation, produces);
}
/** Creates a map between http verb and operation. */
private Map<String, Operation> getOperationsForPath(Path pathObj) {
Map<String, Operation> hmap = Maps.newLinkedHashMap();
hmap.put("get", pathObj.getGet());
hmap.put("head", pathObj.getHead());
hmap.put("delete", pathObj.getDelete());
hmap.put("patch", pathObj.getPatch());
hmap.put("post", pathObj.getPost());
hmap.put("put", pathObj.getPut());
hmap.put("options", pathObj.getOptions());
return hmap;
}
public static void correctResponses(Operation operation) {
int okCode = Status.OK.getStatusCode();
String strOkCode = String.valueOf(okCode);
Response okResponse = null;
for (Entry<String, Response> responseEntry : operation.getResponses().entrySet()) {
Response response = responseEntry.getValue();
if (StringUtils.isEmpty(response.getDescription())) {
response.setDescription("response of " + responseEntry.getKey());
}
if (operation.getResponses().get(strOkCode) != null) {
continue;
}
int statusCode = NumberUtils.toInt(responseEntry.getKey());
if ("default".equals(responseEntry.getKey())) {
statusCode = okCode;
}
if (Family.SUCCESSFUL.equals(Family.familyOf(statusCode))) {
okResponse = response;
}
}
if (okResponse != null) {
operation.addResponse(strOkCode, okResponse);
}
}