下面列出了io.swagger.annotations.AuthorizationScope#io.swagger.models.properties.Property 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void initConverters() {
// inner converters
for (Class<? extends Property> propertyCls : PROPERTY_MAP.keySet()) {
addInnerConverter(propertyCls);
}
converterMap.put(RefProperty.class, new RefPropertyConverter());
converterMap.put(ArrayProperty.class, new ArrayPropertyConverter());
converterMap.put(MapProperty.class, new MapPropertyConverter());
converterMap.put(StringProperty.class, new StringPropertyConverter());
converterMap.put(ObjectProperty.class, new ObjectPropertyConverter());
converterMap.put(ModelImpl.class, new ModelImplConverter());
converterMap.put(RefModel.class, new RefModelConverter());
converterMap.put(ArrayModel.class, new ArrayModelConverter());
}
public static SerializableParameter arrayParam(final boolean required,
final String collectionFormat,
final Integer minItems,
final Integer maxItems,
final Boolean unique,
final Property items) {
final SerializableParameter result = mock(SerializableParameter.class);
when(result.getName()).thenReturn("Test Parameter");
when(result.getType()).thenReturn("array");
when(result.getCollectionFormat()).thenReturn(collectionFormat);
when(result.getRequired()).thenReturn(required);
when(result.getMinItems()).thenReturn(minItems);
when(result.getMaxItems()).thenReturn(maxItems);
when(result.isUniqueItems()).thenReturn(unique);
when(result.getItems()).thenReturn(items);
return result;
}
/**
*
* @param operation
* @return
*/
private String getErrorClassName(Operation operation) {
StringBuilder errorClass = new StringBuilder();
Map<String, Response> responses = operation.getResponses();
for (Map.Entry<String, Response> responsesEntry : responses.entrySet()) {
String responseCode = responsesEntry.getKey();
if (responseCode.equalsIgnoreCase("default") || Integer.parseInt(responseCode) >= 300) {
Property responseProperty = responsesEntry.getValue().getSchema();
if (responseProperty instanceof RefProperty) {
String errorClassName = ((RefProperty) responseProperty).getSimpleRef();
if (!errorClass.toString().contains(errorClassName)) {
if (StringUtils.isNotEmpty(errorClass)) {
errorClass.append(",");
}
errorClass.append(errorClassName);
}
}
}
}
return errorClass.toString();
}
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 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 void validateDefinitionProperties(Map<String, Property> actualDefinitionProperties, Map<String, Property> expectedDefinitionProperties, String definitionName) {
if (MapUtils.isNotEmpty(expectedDefinitionProperties)) {
softAssertions.assertThat(actualDefinitionProperties).as("Checking properties of definition '%s", definitionName).isNotEmpty();
if (MapUtils.isNotEmpty(actualDefinitionProperties)) {
final Set<String> filteredExpectedProperties = filterWhitelistedPropertyNames(definitionName, expectedDefinitionProperties.keySet());
softAssertions.assertThat(actualDefinitionProperties.keySet()).as("Checking properties of definition '%s'", definitionName).hasSameElementsAs(filteredExpectedProperties);
for (Map.Entry<String, Property> actualDefinitionPropertyEntry : actualDefinitionProperties.entrySet()) {
Property expectedDefinitionProperty = expectedDefinitionProperties.get(actualDefinitionPropertyEntry.getKey());
Property actualDefinitionProperty = actualDefinitionPropertyEntry.getValue();
String propertyName = actualDefinitionPropertyEntry.getKey();
validateProperty(actualDefinitionProperty, expectedDefinitionProperty, String.format("Checking property '%s' of definition '%s'", propertyName, definitionName));
}
}
} else {
softAssertions.assertThat(actualDefinitionProperties).as("Checking properties of definition '%s", definitionName).isNullOrEmpty();
}
}
public static String getFromResponse(Operation oper, String responseCode) {
Response response = oper.getResponses().get(responseCode);
if(response == null) return null;
Property prop = response.getSchema();
if(prop instanceof ObjectProperty) {
prop = ((ObjectProperty) prop).getProperties().get("output");
}
if(prop instanceof RefProperty) {
return ((RefProperty)prop).getSimpleRef();
}
if(prop == null) return null;
RefProperty schema = (RefProperty) prop;
return schema.getSimpleRef();
}
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;
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type) || type.indexOf(".") >= 0 ||
type.equals("Map") || type.equals("List") ||
type.equals("File") || type.equals("Date")) {
return type;
}
} else {
type = swaggerType;
}
return toModelName(type);
}
public static Map<String, Property> getBodyProperties(Swagger swagger, Parameter parameter) {
if (!(parameter instanceof BodyParameter)) {
return null;
}
Model model = ((BodyParameter) parameter).getSchema();
if (model instanceof RefModel) {
model = swagger.getDefinitions().get(((RefModel) model).getSimpleRef());
}
if (model instanceof ModelImpl) {
return model.getProperties();
}
return null;
}
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;
}
/**
* Returns list of {@link com.google.protobuf.Field.Builder} created using the properties of a
* {@link ModelImpl} object.
*/
private ImmutableList.Builder<Field> createFields(
Service.Builder serviceBuilder, ModelImpl modelImpl) {
ImmutableList.Builder<Field> fieldsBuilder = ImmutableList.builder();
int count = 1;
if (modelImpl.getProperties() != null) {
for (String propertyName : modelImpl.getProperties().keySet()) {
Property prop = modelImpl.getProperties().get(propertyName);
TypeInfo typeInfo =
ensureNamed(
serviceBuilder,
getTypeInfo(serviceBuilder, prop),
NameConverter.propertyNameToMessageName(propertyName));
fieldsBuilder.add(createField(propertyName, count++, typeInfo).build());
}
}
return fieldsBuilder;
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return type;
}
} else {
type = swaggerType;
}
if (type == null) {
return null;
}
return toModelName(type);
}
/**
* returns the swagger type for the property
*
* @param p Swagger property object
* @return string presentation of the type
**/
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type;
// This maps, for example, long -> kotlin.Long based on hashes in this type's constructor
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
} else {
type = swaggerType;
}
return toModelName(type);
}
public void process(Property property) {
this.properties.add(property);
if(property instanceof ArrayProperty) {
ArrayProperty p = (ArrayProperty)property;
Property ap = p.getItems();
this.process(ap);
} else if(property instanceof MapProperty) {
MapProperty p1 = (MapProperty)property;
} else if(property instanceof ObjectProperty) {
ObjectProperty p2 = (ObjectProperty)property;
if(p2.getProperties() != null) {
Iterator ap1 = p2.getProperties().keySet().iterator();
while(ap1.hasNext()) {
String name = (String)ap1.next();
Property ip = (Property)p2.getProperties().get(name);
this.process(ip);
}
}
}
}
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;
}
/** Returns {@link TypeInfo} for the arrayItems. */
private TypeInfo getArrayModelTypeInfo(Service.Builder serviceBuilder, Property arrayItems) {
TypeInfo resultTypeInfo;
TypeInfo arrayItemTypeInfo =
ensureNamed(serviceBuilder, getTypeInfo(serviceBuilder, arrayItems), "ArrayEntry");
// Check if the type is unspecified. If so, we represent this array as a generic List
if (arrayItemTypeInfo == null) {
resultTypeInfo =
WellKnownType.LIST.toTypeInfo().withCardinality(Cardinality.CARDINALITY_OPTIONAL);
// Check if this is a repeated of repeated. Since repeated of repeated is not allowed, we will
// represent this as {@link com.google.protobuf.ListValue} type.
} else if (arrayItemTypeInfo.cardinality() == Cardinality.CARDINALITY_REPEATED) {
resultTypeInfo =
WellKnownType.LIST.toTypeInfo().withCardinality(Cardinality.CARDINALITY_REPEATED);
} else {
resultTypeInfo = arrayItemTypeInfo.withCardinality(Cardinality.CARDINALITY_REPEATED);
}
return resultTypeInfo;
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return type;
} else if (instantiationTypes.containsKey(type)) {
return type;
}
} else {
type = swaggerType;
}
if (type == null) {
return null;
}
return toModelName(type);
}
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;
}
@Override
public Property convert(TypeDefinition<?> type, SchemaNode parent) {
Property prop = super.convert(type, parent);
if(prop instanceof AbstractProperty) {
if(type instanceof LeafrefTypeDefinition) {
String leafRef = ((LeafrefTypeDefinition) type).getPathStatement().toString();
((AbstractProperty) prop).setVendorExtension("x-path", leafRef);
}
}
return prop;
}
@SuppressWarnings("squid:S1192") // better in-place defined for better readability
protected Property createStringProperty(String format, Annotation[] annotations) {
StringProperty schema = new StringProperty();
if (StringUtils.isNotBlank(format)) {
schema.setFormat(format);
}
if (annotations != null) {
asList(annotations).forEach(annotation -> applyStringAnnotationDetails(schema, annotation));
}
return schema;
}
public static boolean isComplexProperty(Property property) {
if (property instanceof RefProperty || property instanceof ObjectProperty || property instanceof MapProperty) {
return true;
}
if (ArrayProperty.class.isInstance(property)) {
return isComplexProperty(((ArrayProperty) property).getItems());
}
return false;
}
public static Stream<String> toUses(Property p) {
if(p instanceof RefProperty) return Stream.of(((RefProperty)p).getSimpleRef());
if(p instanceof ArrayProperty) return toUses(((ArrayProperty)p).getItems());
if(p instanceof ObjectProperty) {
return ((ObjectProperty)p).getProperties().values().stream()
.flatMap(SwaggerRefHelper::toUses);
}
return Stream.empty();
}
private Map<String, Property> getClassProperties(Class<?> clazz, GenerationContext generationContext) {
Map<String, Property> classPropertyMap = new HashMap<>();
ReflectionUtils.doWithLocalFields(clazz,
field -> getFieldSchema(field, generationContext).ifPresent(schema -> {
schemaFieldInterceptors
.forEach(modelClassFieldInterceptor -> modelClassFieldInterceptor.intercept(clazz, field, schema));
classPropertyMap.put(field.getName(), schema);
})
);
return classPropertyMap;
}
private static Property getResponseProperty(Operation operation) {
Map<String, Response> responses = operation.getResponses();
// temporary workaround for missing response messages
if (responses == null) return null;
Response response = responses.get("200");
return null == response ? null : response.getSchema();
}
@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);
}
@Override
protected Property createRefProperty(Class<?> typeSignature, GenerationContext generationContext) {
RefProperty schema = new RefProperty();
if (isInPackagesToBeScanned(typeSignature, generationContext)) {
schema.set$ref(CommonConstants.COMPONENT_REF_PREFIX + typeSignature.getSimpleName());
return schema;
}
UntypedProperty fallBack = new UntypedProperty();
fallBack.setType("object");
return fallBack;
}
private Map<String, Property> createHeaderResponse(com.github.jrcodeza.Header[] headers) {
Map<String, Property> responseHeaders = new HashMap<>();
for (com.github.jrcodeza.Header headerAnnotation : headers) {
StringProperty header = new StringProperty();
header.setDescription(headerAnnotation.description());
responseHeaders.put(headerAnnotation.name(), header);
}
return responseHeaders;
}
public static Property wrapContainer(String container, Property property, ContainerWrapper... allowed) {
final Set<ContainerWrapper> tmp = allowed.length > 0 ? EnumSet.copyOf(Arrays.asList(allowed)) : EnumSet.allOf(ContainerWrapper.class);
for (ContainerWrapper wrapper : tmp) {
final Property prop = wrapper.wrap(container, property);
if (prop != null) {
return prop;
}
}
return property;
}
private io.swagger.models.parameters.Parameter createStandardRequestBody(Method method, ParameterNamePair requestBodyParameter, ModelImpl content,
Property property) {
BodyParameter requestBody = new BodyParameter();
requestBody.setSchema(content);
requestBody.setRequired(true);
requestBody.setName(resolveRequestBodyName(property, requestBodyParameter.getName()));
requestBody.setDescription(requestBody.getName());
requestBodyInterceptors.forEach(interceptor ->
interceptor.intercept(method, requestBodyParameter.getParameter(), requestBodyParameter.getName(), requestBody)
);
return requestBody;
}