下面列出了io.swagger.annotations.AuthorizationScope#io.swagger.converter.ModelConverters 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
}
}
private static Map<String, Property> parseResponseHeaders(ReaderContext context,
ResponseHeader[] headers) {
Map<String, Property> responseHeaders = null;
for (ResponseHeader header : headers) {
final String name = header.name();
if (StringUtils.isNotEmpty(name)) {
if (responseHeaders == null) {
responseHeaders = new HashMap<String, Property>();
}
final Class<?> cls = header.response();
if (!ReflectionUtils.isVoid(cls)) {
final Property property = ModelConverters.getInstance().readAsProperty(cls);
if (property != null) {
final Property responseProperty = ContainerWrapper.wrapContainer(
header.responseContainer(), property, ContainerWrapper.ARRAY,
ContainerWrapper.LIST, ContainerWrapper.SET);
responseProperty.setDescription(header.description());
responseHeaders.put(name, responseProperty);
appendModels(context.getSwagger(), cls);
}
}
}
}
return responseHeaders;
}
private Parameter readParam(Swagger swagger, Type type, Class<?> cls, ApiParam param) {
PrimitiveType fromType = PrimitiveType.fromType(type);
final Parameter para = null == fromType ? new BodyParameter() : new QueryParameter();
Parameter parameter = ParameterProcessor.applyAnnotations(swagger, para, type,
null == param ? new ArrayList<Annotation>()
: Collections.<Annotation> singletonList(param));
if (parameter instanceof AbstractSerializableParameter) {
final AbstractSerializableParameter<?> p = (AbstractSerializableParameter<?>) parameter;
if (p.getType() == null) {
p.setType(null == fromType ? "string" : fromType.getCommonName());
}
p.setRequired(p.getRequired() || cls.isPrimitive());
} else {
//hack: Get the from data model paramter from BodyParameter
BodyParameter bp = (BodyParameter) parameter;
bp.setIn("body");
Property property = ModelConverters.getInstance().readAsProperty(type);
final Map<PropertyBuilder.PropertyId, Object> args = new EnumMap<PropertyBuilder.PropertyId, Object>(
PropertyBuilder.PropertyId.class);
bp.setSchema(PropertyBuilder.toModel(PropertyBuilder.merge(property, args)));
}
return parameter;
}
public static void main(String[] args) throws JsonProcessingException {
final var read = ModelConverters.getInstance().read(User.class);
final var elepy_model = new OpenAPI()
.info(new Info()
.title("Elepy Model")
.version("3.0")
)
.paths(new Paths())
.paths(createPathsFromModel(ModelUtils.createDeepSchema(User.class)))
;
read.forEach(elepy_model::schema);
final var objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
System.out.println(objectMapper.writeValueAsString(elepy_model).replaceAll("SIMPLE", "simple"));
}
private void addResponse(Operation operation, ApiResponse apiResponse) {
Map<String, Property> responseHeaders = parseResponseHeaders(apiResponse.responseHeaders());
Response response = new Response().description(apiResponse.message()).headers(responseHeaders);
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);
if (property != null) {
response.schema(ContainerWrapper.wrapContainer(apiResponse.responseContainer(), property));
appendModels(responseType);
}
}
}
private static Map<String, Property> parseResponseHeaders(ReaderContext context,
ResponseHeader[] headers) {
Map<String, Property> responseHeaders = null;
for (ResponseHeader header : headers) {
final String name = header.name();
if (StringUtils.isNotEmpty(name)) {
if (responseHeaders == null) {
responseHeaders = new HashMap<String, Property>();
}
final Class<?> cls = header.response();
if (!ReflectionUtils.isVoid(cls)) {
final Property property = ModelConverters.getInstance().readAsProperty(cls);
if (property != null) {
final Property responseProperty = ContainerWrapper.wrapContainer(
header.responseContainer(), property, ContainerWrapper.ARRAY,
ContainerWrapper.LIST, ContainerWrapper.SET);
responseProperty.setDescription(header.description());
responseHeaders.put(name, responseProperty);
appendModels(context.getSwagger(), cls);
}
}
}
}
return responseHeaders;
}
private static Map<String, Property> parseResponseHeaders(Swagger swagger, ReaderContext context, ResponseHeader[] headers) {
Map<String, Property> responseHeaders = null;
for (ResponseHeader header : headers) {
final String name = header.name();
if (StringUtils.isNotEmpty(name)) {
if (responseHeaders == null) {
responseHeaders = new HashMap<String, Property>();
}
final Class<?> cls = header.response();
if (!ReflectionUtils.isVoid(cls)) {
final Property property = ModelConverters.getInstance().readAsProperty(cls);
if (property != null) {
final Property responseProperty = ContainerWrapper.wrapContainer(header.responseContainer(),
property, ContainerWrapper.ARRAY, ContainerWrapper.LIST, ContainerWrapper.SET);
responseProperty.setDescription(header.description());
responseHeaders.put(name, responseProperty);
appendModels(swagger, cls);
}
}
}
}
return responseHeaders;
}
protected void fillBodyParameter(Swagger swagger, Parameter parameter, Type type, List<Annotation> annotations) {
// so strange, for bodyParameter, swagger return a new instance
// that will cause lost some information
// so we must merge them
BodyParameter newBodyParameter = (BodyParameter) io.swagger.util.ParameterProcessor.applyAnnotations(
swagger, parameter, type, annotations);
// swagger missed enum data, fix it
ModelImpl model = SwaggerUtils.getModelImpl(swagger, newBodyParameter);
if (model != null) {
Property property = ModelConverters.getInstance().readAsProperty(type);
if (property instanceof StringProperty) {
model.setEnum(((StringProperty) property).getEnum());
}
}
mergeBodyParameter((BodyParameter) parameter, newBodyParameter);
}
private void addResponse(Operation operation, ApiResponse apiResponse) {
Map<String, Property> responseHeaders = parseResponseHeaders(apiResponse.responseHeaders());
Response response = new Response().description(apiResponse.message()).headers(responseHeaders);
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);
if (property != null) {
response.schema(ContainerWrapper.wrapContainer(apiResponse.responseContainer(), property));
appendModels(responseType);
}
}
}
private Property readAsPropertyIfPrimitive(Type type) {
if (com.github.kongchen.swagger.docgen.util.TypeUtils.isPrimitive(type)) {
return ModelConverters.getInstance().readAsProperty(type);
} else {
String msg = String.format("Non-primitive type: %s used as request/path/cookie parameter", type);
log.warn(msg);
// fallback to string if type is simple wrapper for String to support legacy code
JavaType ct = constructType(type);
if (isSimpleWrapperForString(ct.getRawClass())) {
log.warn(String.format("Non-primitive type: %s used as string for request/path/cookie parameter", type));
return new StringProperty();
}
}
return null;
}
private QueryParameter extractQueryParam(Type type, String defaultValue, QueryParam param) {
QueryParameter queryParameter = new QueryParameter().name(param.value());
if (!Strings.isNullOrEmpty(defaultValue)) {
queryParameter.setDefaultValue(defaultValue);
}
Property schema = ModelConverters.getInstance().readAsProperty(type);
if (schema != null) {
queryParameter.setProperty(schema);
}
String parameterType = queryParameter.getType();
if (parameterType == null || parameterType.equals("ref")) {
queryParameter.setType("string");
}
return queryParameter;
}
private PathParameter extractPathParam(Type type, String defaultValue, PathParam param) {
PathParameter pathParameter = new PathParameter().name(param.value());
if (!Strings.isNullOrEmpty(defaultValue)) {
pathParameter.setDefaultValue(defaultValue);
}
Property schema = ModelConverters.getInstance().readAsProperty(type);
if (schema != null) {
pathParameter.setProperty(schema);
}
String parameterType = pathParameter.getType();
if (parameterType == null || parameterType.equals("ref")) {
pathParameter.setType("string");
}
return pathParameter;
}
private HeaderParameter extractHeaderParam(Type type, String defaultValue, HeaderParam param) {
HeaderParameter headerParameter = new HeaderParameter().name(param.value());
if (!Strings.isNullOrEmpty(defaultValue)) {
headerParameter.setDefaultValue(defaultValue);
}
Property schema = ModelConverters.getInstance().readAsProperty(type);
if (schema != null) {
headerParameter.setProperty(schema);
}
String parameterType = headerParameter.getType();
if (parameterType == null || parameterType.equals("ref") || parameterType.equals("array")) {
headerParameter.setType("string");
}
return headerParameter;
}
private CookieParameter extractCookieParameter(Type type, String defaultValue, CookieParam param) {
CookieParameter cookieParameter = new CookieParameter().name(param.value());
if (!Strings.isNullOrEmpty(defaultValue)) {
cookieParameter.setDefaultValue(defaultValue);
}
Property schema = ModelConverters.getInstance().readAsProperty(type);
if (schema != null) {
cookieParameter.setProperty(schema);
}
String parameterType = cookieParameter.getType();
if (parameterType == null || parameterType.equals("ref") || parameterType.equals("array")) {
cookieParameter.setType("string");
}
return cookieParameter;
}
private FormParameter extractFormParameter(Type type, String defaultValue, FormParam param) {
FormParameter formParameter = new FormParameter().name(param.value());
if (!Strings.isNullOrEmpty(defaultValue)) {
formParameter.setDefaultValue(defaultValue);
}
Property schema = ModelConverters.getInstance().readAsProperty(type);
if (schema != null) {
formParameter.setProperty(schema);
}
String parameterType = formParameter.getType();
if (parameterType == null || parameterType.equals("ref") || parameterType.equals("array")) {
formParameter.setType("string");
}
return formParameter;
}
private Map<String, Property> parseResponseHeaders(ResponseHeader[] headers, JsonView jsonView) {
Map<String, Property> responseHeaders = null;
if (headers != null) {
for (ResponseHeader header : headers) {
String name = header.name();
if (!"".equals(name)) {
if (responseHeaders == null) {
responseHeaders = new LinkedHashMap<String, Property>();
}
String description = header.description();
Class<?> cls = header.response();
if (!isVoid(cls)) {
final Property property = ModelConverters.getInstance().readAsProperty(cls, jsonView);
if (property != null) {
Property responseProperty = ContainerWrapper.wrapContainer(header.responseContainer(),
property, ContainerWrapper.ARRAY, ContainerWrapper.LIST, ContainerWrapper.SET);
responseProperty.setDescription(description);
responseHeaders.put(name, responseProperty);
appendModels(cls);
}
}
}
}
}
return responseHeaders;
}
private Map<String, Property> parseResponseHeaders(ResponseHeader[] headers) {
Map<String, Property> responseHeaders = null;
if (headers != null) {
for (ResponseHeader header : headers) {
String name = header.name();
if (!"".equals(name)) {
if (responseHeaders == null) {
responseHeaders = new LinkedHashMap<>();
}
String description = header.description();
Class<?> cls = header.response();
if (!isVoid(cls)) {
final Property property = ModelConverters.getInstance().readAsProperty(cls);
if (property != null) {
Property responseProperty = ContainerWrapper.wrapContainer(header.responseContainer(), property,
ContainerWrapper.ARRAY, ContainerWrapper.LIST, ContainerWrapper.SET);
responseProperty.setDescription(description);
responseHeaders.put(name, responseProperty);
appendModels(cls);
}
}
}
}
}
return responseHeaders;
}
private void appendModels(Type type) {
final Map<String, Model> models = ModelConverters.getInstance().readAll(type);
for (Map.Entry<String, Model> entry : models.entrySet()) {
swagger.model(entry.getKey(), entry.getValue());
}
}
@Override
public Model process(SwaggerGenerator swaggerGenerator, OperationGenerator operationGenerator,
Type genericResponseType) {
Type responseType = extractResponseType(swaggerGenerator, operationGenerator, genericResponseType);
if (responseType == null || ReflectionUtils.isVoid(responseType)) {
return null;
}
if (responseType instanceof Class && Part.class.isAssignableFrom((Class<?>) responseType)) {
responseType = Part.class;
}
SwaggerUtils.addDefinitions(swaggerGenerator.getSwagger(), responseType);
Property property = ModelConverters.getInstance().readAsProperty(responseType);
return new PropertyModelConverter().propertyToModel(property);
}
public static void addDefinitions(Swagger swagger, Type paramType) {
Map<String, Model> models = ModelConverters.getInstance().readAll(paramType);
for (Entry<String, Model> entry : models.entrySet()) {
if (null != swagger.getDefinitions()) {
Model tempModel = swagger.getDefinitions().get(entry.getKey());
if (null != tempModel && !tempModel.equals(entry.getValue())) {
LOGGER.warn("duplicate param model: " + entry.getKey());
throw new IllegalArgumentException("duplicate param model: " + entry.getKey());
}
}
swagger.addDefinition(entry.getKey(), entry.getValue());
}
}
public static void setParameterType(Swagger swagger, Type type, AbstractSerializableParameter<?> parameter) {
addDefinitions(swagger, type);
Property property = ModelConverters.getInstance().readAsProperty(type);
if (isComplexProperty(property)) {
// cannot set a simple parameter(header, query, etc.) as complex type
String msg = String
.format("not allow complex type for %s parameter, type=%s.", parameter.getIn(), type.getTypeName());
throw new IllegalStateException(msg);
}
parameter.setProperty(property);
}
private SwaggerAnnotationsReader(Swagger swagger) {
this.swagger = swagger;
ModelConverters.getInstance().addConverter(new SwaggerModelConverter() {
protected boolean shouldIgnoreClass(Type type) {
if (type instanceof SimpleType && JSONObject.class.equals(((SimpleType)type).getRawClass())) {
return true;
}
return super.shouldIgnoreClass(type);
}
});
}
@Inject
public SwaggerModel(final ApplicationVersion applicationVersion,
final List<SwaggerContributor> contributors)
{
this.applicationVersion = checkNotNull(applicationVersion);
this.contributors = checkNotNull(contributors);
// filter banned types from model, such as Groovy's MetaClass
ModelConverters.getInstance().addConverter(new ModelFilter());
this.reader = new Reader(createSwagger());
}
private Map<String, Property> parseResponseHeaders(ResponseHeader[] headers) {
Map<String, Property> responseHeaders = null;
if (headers != null && headers.length > 0) {
for (ResponseHeader header : headers) {
String name = header.name();
if (!"".equals(name)) {
if (responseHeaders == null) {
responseHeaders = new HashMap<>();
}
String description = header.description();
Class<?> cls = header.response();
if (!isVoid(cls)) {
final Property property = ModelConverters.getInstance().readAsProperty(cls);
if (property != null) {
Property responseProperty = ContainerWrapper
.wrapContainer(header.responseContainer(), property, ContainerWrapper.ARRAY,
ContainerWrapper.LIST, ContainerWrapper.SET);
responseProperty.setDescription(description);
responseHeaders.put(name, responseProperty);
appendModels(cls);
}
}
}
}
}
return responseHeaders;
}
@Test
public void testAllTypes() {
Map<String, Model> modelMap = ModelConverters.getInstance()
.read(TypeToken.of(RAllTypes.class).getType());
Model rAllTypes = modelMap.get(RAllTypes.class.getSimpleName());
Assert.assertNotNull(rAllTypes);
Map<String, Class<? extends Property>> expectedProperties = ImmutableMap.<String, Class<? extends Property>>builder()
.put("id", StringProperty.class)
.put("rChar", StringProperty.class)
.put("rDate", LongProperty.class)
.put("rTime", LongProperty.class)
.put("rDatetime", LongProperty.class)
.put("rLong", LongProperty.class)
.put("rDouble", DoubleProperty.class)
.put("rDecimal", DecimalProperty.class)
.put("rEnum", StringProperty.class)
.put("rSubBean", RefProperty.class)
.put("rSubBeanList", ArrayProperty.class)
.build();
Assert.assertEquals(expectedProperties.size(), rAllTypes.getProperties().size());
expectedProperties.forEach(
(k, v) -> Assert.assertEquals(v, rAllTypes.getProperties().get(k).getClass())
);
StringProperty rEnumProperty = ((StringProperty)rAllTypes.getProperties().get("rEnum"));
Assert.assertTrue(
new HashSet<>(rEnumProperty.getEnum())
.containsAll(Arrays.stream(Alphabet.values()).map(Enum::name).collect(Collectors.toSet()))
);
RefProperty refProperty = (RefProperty) rAllTypes.getProperties().get("rSubBean");
Assert.assertEquals(refProperty.getSimpleRef(), RSubBean.class.getSimpleName());
ArrayProperty arrayProperty = (ArrayProperty) rAllTypes.getProperties().get("rSubBeanList");
Assert.assertEquals(((RefProperty)arrayProperty.getItems()).getSimpleRef(), RSubBean.class.getSimpleName());
}
private Map<String, Property> parseResponseHeaders(ResponseHeader[] headers) {
Map<String, Property> responseHeaders = null;
if (headers != null && headers.length > 0) {
for (ResponseHeader header : headers) {
String name = header.name();
if (!"".equals(name)) {
if (responseHeaders == null) {
responseHeaders = new HashMap<>();
}
String description = header.description();
Class<?> cls = header.response();
if (!isVoid(cls)) {
final Property property = ModelConverters.getInstance().readAsProperty(cls);
if (property != null) {
Property responseProperty = ContainerWrapper.wrapContainer(header.responseContainer(),
property, ContainerWrapper.ARRAY, ContainerWrapper.LIST, ContainerWrapper.SET);
responseProperty.setDescription(description);
responseHeaders.put(name, responseProperty);
appendModels(cls);
}
}
}
}
}
return responseHeaders;
}
public SwaggerFilter() {
ModelConverters modelConverters = ModelConverters.getInstance();
modelConverters.addConverter(new ParamModelConverter(Tags.class, () -> {
return new StringFormatProperty("tag-list");
}));
modelConverters.addConverter(new ParamModelConverter(Duration.class, () -> {
return new StringFormatProperty("duration");
}));
}
private Map<String, Model> readAllModels(Type responseClassType) {
Map<String, Model> modelMap = ModelConverters.getInstance().readAll(responseClassType);
if (modelMap != null) {
handleJsonTypeInfo(responseClassType, modelMap);
}
return modelMap;
}
private void appendModels(Type type) {
final Map<String, Model> models = ModelConverters.getInstance().readAll(type);
for (Map.Entry<String, Model> entry : models.entrySet()) {
swagger.model(entry.getKey(), entry.getValue());
}
}
private void appendModelsWithJsonView(Type type, JsonView annotation) {
final Map<String, Model> models = ModelConverters.getInstance().readAll(type, annotation);
for (Map.Entry<String, Model> entry : models.entrySet()) {
swagger.model(entry.getKey(), entry.getValue());
}
}