io.swagger.models.properties.Property Java Examples

The following examples show how to use io.swagger.models.properties.Property. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TypeBuilder.java    From api-compiler with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #2
Source File: DubboReaderExtension.java    From swagger-dubbo with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: DocumentationDrivenValidator.java    From assertj-swagger with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #4
Source File: JaxrsParameterExtension.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #5
Source File: SwaggerRefHelper.java    From yang2swagger with Eclipse Public License 1.0 6 votes vote down vote up
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();
}
 
Example #6
Source File: SpringSwaggerExtension.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #7
Source File: TypeBuilder.java    From api-compiler with Apache License 2.0 6 votes vote down vote up
/** 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;
}
 
Example #8
Source File: SwaggerInventory.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
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);
            }
        }
    }

}
 
Example #9
Source File: AndroidClientCodegen.java    From TypeScript-Microservices with MIT License 6 votes vote down vote up
@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);
}
 
Example #10
Source File: AbstractOperationGenerator.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #11
Source File: AbstractKotlinCodegen.java    From TypeScript-Microservices with MIT License 6 votes vote down vote up
/**
 * 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);
}
 
Example #12
Source File: PlantUMLCodegen.java    From swagger2puml with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @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();
}
 
Example #13
Source File: SwaggerUtils.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #14
Source File: RpcReaderExtension.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #15
Source File: RpcReaderExtension.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #16
Source File: ConverterMgr.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #17
Source File: ValidatorTestUtil.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #18
Source File: PerlClientCodegen.java    From TypeScript-Microservices with MIT License 6 votes vote down vote up
@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);
}
 
Example #19
Source File: SilexServerCodegen.java    From TypeScript-Microservices with MIT License 6 votes vote down vote up
@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);
}
 
Example #20
Source File: JaxRs2Extension.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Property enforcePrimitive(final Property in, final int level) {
    if (in instanceof RefProperty) {
        return new StringProperty();
    }
    if (in instanceof ArrayProperty) {
        if (level == 0) {
            final ArrayProperty array = (ArrayProperty) in;
            array.setItems(enforcePrimitive(array.getItems(), level + 1));
        } else {
            return new StringProperty();
        }
    }
    return in;
}
 
Example #21
Source File: Reader.java    From dorado with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #22
Source File: PetIdToStringModelConverter.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public Property resolveProperty(Type type, ModelConverterContext modelConverterContext, Annotation[] annotations, Iterator<ModelConverter> iterator) {
    try {
        Type expectedType = _mapper.constructType(Class.forName("com.wordnik.sample.model.PetId"));
        if (type.equals(expectedType)) {
            return super.resolveProperty(_mapper.constructType(Class.forName("java.lang.String")), modelConverterContext, annotations, iterator);
        }
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
    return super.resolveProperty(type, modelConverterContext, annotations, iterator);
}
 
Example #23
Source File: NancyFXServerCodegen.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
private static Predicate<Property> timeProperty() {
    return new Predicate<Property>() {
        @Override
        public boolean apply(Property property) {
            return property instanceof StringProperty && "time".equalsIgnoreCase(property.getFormat());
        }
    };
}
 
Example #24
Source File: WSDL11SOAPOperationExtractor.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private Property getPropertyFromDataType(String dataType) {

        switch (dataType) {
        case "string":
            return new StringProperty();
        case "boolean":
            return new BooleanProperty();
        case "int":
            return new IntegerProperty();
        case "nonNegativeInteger":
            return new IntegerProperty();
        case "integer":
            return new IntegerProperty();
        case "positiveInteger":
            return new IntegerProperty();
        case "double":
            return new DoubleProperty();
        case "float":
            return new FloatProperty();
        case "long":
            return new LongProperty();
        case "date":
            return new DateProperty();
        case "dateTime":
            return new DateTimeProperty();
        default:
            return new RefProperty();
        }
    }
 
Example #25
Source File: ArrayPropertyConverter.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public static JavaType findJavaType(Swagger swagger, Property itemProperty, Boolean uniqueItems) {
  JavaType itemJavaType = ConverterMgr.findJavaType(swagger, itemProperty);

  @SuppressWarnings("rawtypes")
  Class<? extends Collection> collectionClass = List.class;
  if (Boolean.TRUE.equals(uniqueItems)) {
    collectionClass = Set.class;
  }
  return TypeFactory.defaultInstance().constructCollectionType(collectionClass, itemJavaType);
}
 
Example #26
Source File: ElmClientCodegen.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
@Override
public String toInstantiationType(Property p) {
    if (p instanceof ArrayProperty) {
        ArrayProperty ap = (ArrayProperty) p;
        String inner = getSwaggerType(ap.getItems());
        return instantiationTypes.get("array") + " " + inner;
    } else {
        return null;
    }
}
 
Example #27
Source File: FlashClientCodegen.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
@Override
public String getTypeDeclaration(Property p) {
    if (p instanceof ArrayProperty || p instanceof MapProperty) {
        return getSwaggerType(p);
    }
    return super.getTypeDeclaration(p);
}
 
Example #28
Source File: TestApiResponse.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void checkApiResponseHeader() {
  SwaggerOperation swaggerOperation = swaggerOperations.findOperation("testApiResponseHeader");
  Assert.assertEquals("/testApiResponseHeader", swaggerOperation.getPath());

  Response response = swaggerOperation.getOperation().getResponses().get("200");
  Property property = response.getHeaders().get("k1");
  Assert.assertEquals("integer", property.getType());
  Assert.assertEquals("int32", property.getFormat());

  property = response.getHeaders().get("k2");
  Assert.assertEquals("string", property.getType());
  Assert.assertNull(property.getFormat());
}
 
Example #29
Source File: SchemaObjectResolver.java    From assertj-swagger with Apache License 2.0 5 votes vote down vote up
private Map<String, Property> resolveProperties(Model definition, Swagger owningSchema, Set<String> seenRefs) {
    Map<String, Property> result;

    // if the definition does not contain any property, then the model will return null instead of an empty map
    final Map<String, Property> definitionProperties = definition.getProperties() != null ? definition.getProperties() : Collections.emptyMap();

    if (definition instanceof RefModel) {
        // Don't navigate ref-def cycles infinitely
        final RefModel refDef = (RefModel) definition;

        if (seenRefs.contains(refDef.getSimpleRef())) {
            return Collections.emptyMap();
        } else {
            seenRefs.add(refDef.getSimpleRef());
        }
        result = resolveProperties(findDefinition(owningSchema.getDefinitions(), refDef), owningSchema, seenRefs);
    } else if (definition instanceof ComposedModel) {
        Map<String, Property> allProperties = new HashMap<>();
        if (definitionProperties != null) {
            allProperties.putAll(definitionProperties);
        }
        for (final Model childDefinition : ((ComposedModel) definition).getAllOf()) {
            allProperties.putAll(resolveProperties(childDefinition, owningSchema, seenRefs));
        }
        result = allProperties;
    } else {
        result = definitionProperties;
    }

    return result;
}
 
Example #30
Source File: ResponseHeaderProcessor.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public void process(SwaggerGenerator swaggerGenerator, OperationGenerator operationGenerator,
    ResponseHeader responseHeader) {
  ResponseHeaderConfig config = AnnotationUtils.convert(responseHeader);
  if (config != null) {
    Property property =
        AnnotationUtils.generateResponseHeaderProperty(swaggerGenerator.getSwagger(), config);
    operationGenerator.addMethodResponseHeader(config.getName(), property);
  }
}