io.swagger.v3.oas.models.media.Schema Java Examples

The following examples show how to use io.swagger.v3.oas.models.media.Schema. 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: AbstractJavaCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Override
protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) {
    if (!supportsAdditionalPropertiesWithComposedSchema) {
        // The additional (undeclared) propertiees are modeled in Java as a HashMap.
        // 
        // 1. supportsAdditionalPropertiesWithComposedSchema is set to false:
        //    The generated model class extends from the HashMap. That does not work
        //    with composed schemas that also use a discriminator because the model class
        //    is supposed to extend from the generated parent model class.
        // 2. supportsAdditionalPropertiesWithComposedSchema is set to true:
        //    The HashMap is a field.
        super.addAdditionPropertiesToCodeGenModel(codegenModel, schema);
    }

    // See https://github.com/OpenAPITools/openapi-generator/pull/1729#issuecomment-449937728
    Schema s = getAdditionalProperties(schema);
    // 's' may be null if 'additionalProperties: false' in the OpenAPI schema.
    if (s != null) {
        codegenModel.additionalPropertiesType = getSchemaType(s);
        addImport(codegenModel, codegenModel.additionalPropertiesType);
    }
}
 
Example #2
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldParseExternalSchemaModelHavingReferenceToItsLocalModel() {
    // given
    String location = "src/test/resources/issue-1040/api.yaml";
    OpenAPIV3Parser tested = new OpenAPIV3Parser();

    // when
    OpenAPI result = tested.read(location);

    // then
    Components components = result.getComponents();
    Schema modelSchema = components.getSchemas().get("Value");

    assertThat(modelSchema, notNullValue());
    assertThat(modelSchema.getProperties().get("id"), instanceOf(Schema.class));
    assertThat(((Schema) modelSchema.getProperties().get("id")).get$ref(), equalTo("#/components/schemas/ValueId"));
}
 
Example #3
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testArbitraryObjectResponseMapInline() {
    OpenAPI openAPI = new OpenAPI();

    Schema schema = new Schema();
    schema.setAdditionalProperties(new ObjectSchema());

    openAPI.path("/foo/baz", new PathItem()
            .get(new Operation()
                    .responses(new ApiResponses().addApiResponse("200", new ApiResponse()
                            .description("it works!")
                            .content(new Content().addMediaType("*/*", new MediaType().schema(schema)))))));

    new InlineModelResolver().flatten(openAPI);

    ApiResponse response = openAPI.getPaths().get("/foo/baz").getGet().getResponses().get("200");

    Schema property = response.getContent().get("*/*").getSchema();
    assertTrue(property.getAdditionalProperties() != null);
    assertTrue(property.getAdditionalProperties() instanceof  Schema);
    assertTrue(openAPI.getComponents().getSchemas() == null);
    Schema inlineProp = (Schema)property.getAdditionalProperties();
    assertTrue(inlineProp instanceof ObjectSchema);
    ObjectSchema op = (ObjectSchema) inlineProp;
    assertNull(op.getProperties());
}
 
Example #4
Source File: SchemaPropertiesKeysValidator.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
@Override
protected List<OasViolation> validateCurrentSchemaObject(OasValidationContext context, Schema oasObject,
  OasObjectPropertyLocation location) {

  Map<String, Schema> properties = oasObject.getProperties();

  if (MapUtils.isEmpty(properties)) {
    return emptyList();
  }

  return
    OasObjectValidatorUtils.doValidateMapPropertyKeys(
      location,
      "properties",
      properties,
      keyPredicate,
      errorFunction
    );

}
 
Example #5
Source File: ExampleBuilderTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
public void testInvalidExample(Schema property, String invalidValue, Object defaultValue, Object sampleValue ) throws Exception {
    property.setExample( invalidValue);

    Schema model = new Schema();
    model.addProperties("test", property);


    Map<String, Schema> definitions = new HashMap<>();
    definitions.put("Test", model);

    // validate that the internal default value is returned if an invalid value is set
    ObjectExample rep = (ObjectExample) ExampleBuilder.fromSchema(new Schema().$ref("Test"), definitions);
    AbstractExample example = (AbstractExample) rep.get( "test" );
    System.out.println(example);
    assertEquals( example.asString(), String.valueOf(defaultValue) );

    // validate that a specified default value is returned if an invalid value is set
    if( sampleValue != null ) {
        property.setDefault(String.valueOf(sampleValue));
        rep = (ObjectExample) ExampleBuilder.fromSchema(new Schema().$ref("Test"), definitions);
        example = (AbstractExample) rep.get("test");
        assertEquals(String.valueOf(sampleValue), example.asString());
    }
}
 
Example #6
Source File: RubyClientCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Override
public String getSchemaType(Schema schema) {
    String openAPIType = super.getSchemaType(schema);
    String type = null;
    if (typeMapping.containsKey(openAPIType)) {
        type = typeMapping.get(openAPIType);
        if (languageSpecificPrimitives.contains(type)) {
            return type;
        }
    } else {
        type = openAPIType;
    }

    if (type == null) {
        return null;
    }

    return toModelName(type);
}
 
Example #7
Source File: PostResourceDataTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void schema() {
	additionalMetaResourceField.setInsertable(true);
	final Schema dataSchema = new PostResourceData(metaResource).schema();

	assertNotNull(dataSchema);
	assertEquals(ComposedSchema.class, dataSchema.getClass());
	final List<Schema> allOf = ((ComposedSchema) dataSchema).getAllOf();
	assertNotNull(allOf);
	assertEquals(2, allOf.size());
	assertEquals(
			"#/components/schemas/ResourceTypePostResourceReference",
			allOf.get(0).get$ref(),
			"Post resource uses a special <Type>PostResourceReference in which the id is optional");
	assertEquals("#/components/schemas/ResourceTypeResourcePostAttributes", allOf.get(1).get$ref());
}
 
Example #8
Source File: ExtensionsUtilTest.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Test
public void allowBooleanAdditionalProperties(@Injectable final List<AuthorizationValue> auths) {

    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setResolveFully(true);

    SwaggerParseResult result = new OpenAPIV3Parser().readLocation("./src/test/swagger/additionalProperties.yaml", auths, options);

    assertNotNull(result);
    assertNotNull(result.getOpenAPI());
    OpenAPI openAPI = result.getOpenAPI();
    Assert.assertEquals(result.getOpenAPI().getOpenapi(), "3.0.0");
    List<String> messages = result.getMessages();

    Assert.assertTrue(openAPI.getComponents().getSchemas().get("someObject").getAdditionalProperties() instanceof Schema);
    Assert.assertTrue(((Schema)(openAPI.getComponents().getSchemas().get("someObject").getProperties().get("innerObject"))).getAdditionalProperties() instanceof Boolean);

}
 
Example #9
Source File: SchemaDiffResult.java    From openapi-diff with Apache License 2.0 6 votes vote down vote up
private void compareAdditionalProperties(
    HashSet<String> refSet, Schema leftSchema, Schema rightSchema, DiffContext context) {
  Object left = leftSchema.getAdditionalProperties();
  Object right = rightSchema.getAdditionalProperties();
  if ((left != null && left instanceof Schema) || (right != null && right instanceof Schema)) {
    Schema leftAdditionalSchema = (Schema) left;
    Schema rightAdditionalSchema = (Schema) right;
    ChangedSchema apChangedSchema =
        new ChangedSchema()
            .setContext(context)
            .setOldSchema(leftAdditionalSchema)
            .setNewSchema(rightAdditionalSchema);
    if (left != null && right != null) {
      Optional<ChangedSchema> addPropChangedSchemaOP =
          openApiDiff
              .getSchemaDiff()
              .diff(
                  refSet,
                  leftAdditionalSchema,
                  rightAdditionalSchema,
                  context.copyWithRequired(false));
      apChangedSchema = addPropChangedSchemaOP.orElse(apChangedSchema);
    }
    isChanged(apChangedSchema).ifPresent(changedSchema::setAddProp);
  }
}
 
Example #10
Source File: OpenApiSchemaValidations.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * JSON Schema defines oneOf as a validation property which can be applied to any schema.
 * <p>
 * OpenAPI Specification is a variant of JSON Schema for which oneOf is defined as:
 * "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema."
 * <p>
 * Where the only examples of oneOf in OpenAPI Specification are used to define either/or type structures rather than validations.
 * Because of this ambiguity in the spec about what is non-standard about oneOf support, we'll warn as a recommendation that
 * properties on the schema defining oneOf relationships may not be intentional in the OpenAPI Specification.
 *
 * @param schemaWrapper An input schema, regardless of the type of schema
 * @return {@link ValidationRule.Pass} if the check succeeds, otherwise {@link ValidationRule.Fail}
 */
private static ValidationRule.Result checkOneOfWithProperties(SchemaWrapper schemaWrapper) {
    Schema schema = schemaWrapper.getSchema();
    ValidationRule.Result result = ValidationRule.Pass.empty();

    if (schema instanceof ComposedSchema) {
        final ComposedSchema composed = (ComposedSchema) schema;
        // check for loosely defined oneOf extension requirements.
        // This is a recommendation because the 3.0.x spec is not clear enough on usage of oneOf.
        // see https://json-schema.org/draft/2019-09/json-schema-core.html#rfc.section.9.2.1.3 and the OAS section on 'Composition and Inheritance'.
        if (composed.getOneOf() != null && composed.getOneOf().size() > 0) {
            if (composed.getProperties() != null && composed.getProperties().size() >= 1 && composed.getProperties().get("discriminator") == null) {
                // not necessarily "invalid" here, but we trigger the recommendation which requires the method to return false.
                result = ValidationRule.Fail.empty();
            }
        }
    }
    return result;
}
 
Example #11
Source File: PhpSilexServerCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Override
public String getSchemaType(Schema p) {
    String openAPIType = super.getSchemaType(p);
    String type = null;
    if (typeMapping.containsKey(openAPIType)) {
        type = typeMapping.get(openAPIType);
        if (languageSpecificPrimitives.contains(type)) {
            return type;
        } else if (instantiationTypes.containsKey(type)) {
            return type;
        }
    } else {
        type = openAPIType;
    }
    if (type == null) {
        return null;
    }
    return toModelName(type);
}
 
Example #12
Source File: OpenApiClientGenerator.java    From spring-openapi with MIT License 6 votes vote down vote up
private FieldSpec.Builder getNumberBasedSchemaField(String fieldName, Schema innerSchema, TypeSpec.Builder typeSpecBuilder) {
	FieldSpec.Builder fieldBuilder = createNumberBasedFieldWithFormat(fieldName, innerSchema, typeSpecBuilder);
	if (innerSchema.getMinimum() != null) {
		fieldBuilder.addAnnotation(AnnotationSpec.builder(DecimalMin.class)
				.addMember("value", "$S", innerSchema.getMinimum().toString())
				.build()
		);
	}
	if (innerSchema.getMaximum() != null) {
		fieldBuilder.addAnnotation(AnnotationSpec.builder(DecimalMax.class)
				.addMember("value", "$S", innerSchema.getMaximum().toString())
				.build()
		);
	}
	return fieldBuilder;
}
 
Example #13
Source File: AbstractEndpointGenerationTest.java    From flow with Apache License 2.0 6 votes vote down vote up
private void assertRequestSchema(Schema requestSchema,
        Class<?>[] parameterTypes, Parameter[] parameters) {
    Map<String, Schema> properties = requestSchema.getProperties();
    assertEquals(
            "Request schema should have the same amount of properties as the corresponding endpoint method parameters number",
            parameterTypes.length, properties.size());
    int index = 0;
    for (Map.Entry<String, Schema> stringSchemaEntry : properties
            .entrySet()) {
        assertSchema(stringSchemaEntry.getValue(), parameterTypes[index]);
        List requiredList = requestSchema.getRequired();
        if (parameters[index].isAnnotationPresent(Nullable.class) ||
                Optional.class.isAssignableFrom(parameters[index].getType())) {
            boolean notRequired = requiredList == null ||
                    !requiredList.contains(stringSchemaEntry.getKey());
            assertTrue("@Nullable or Optional request parameter " +
                    "should not be required", notRequired);

        } else {
            assertTrue(requiredList.contains(stringSchemaEntry.getKey()));
        }
        index++;
    }
}
 
Example #14
Source File: AbstractCSharpCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public String getTypeDeclaration(Schema p) {
    if (ModelUtils.isArraySchema(p)) {
        return getArrayTypeDeclaration((ArraySchema) p);
    } else if (ModelUtils.isMapSchema(p)) {
        // Should we also support maps of maps?
        Schema inner = getAdditionalProperties(p);
        return getSchemaType(p) + "<string, " + getTypeDeclaration(inner) + ">";
    }
    return super.getTypeDeclaration(p);
}
 
Example #15
Source File: AbstractJavaCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public String getTypeDeclaration(Schema p) {
    if (ModelUtils.isArraySchema(p)) {
        Schema<?> items = getSchemaItems((ArraySchema) p);
        return getSchemaType(p) + "<" + getTypeDeclaration(ModelUtils.unaliasSchema(this.openAPI, items)) + ">";
    } else if (ModelUtils.isMapSchema(p) && !ModelUtils.isComposedSchema(p)) {
        // Note: ModelUtils.isMapSchema(p) returns true when p is a composed schema that also defines
        // additionalproperties: true
        Schema<?> inner = getSchemaAdditionalProperties(p);
        return getSchemaType(p) + "<String, " + getTypeDeclaration(ModelUtils.unaliasSchema(this.openAPI, inner)) + ">";
    }
    return super.getTypeDeclaration(p);
}
 
Example #16
Source File: JavascriptApolloClientCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public String toDefaultValueWithParam(String name, Schema p) {
    String type = normalizeType(getTypeDeclaration(p));
    if (!StringUtils.isEmpty(p.get$ref())) {
        return " = " + type + ".constructFromObject(data['" + name + "']);";
    } else {
        return " = ApiClient.convertToType(data['" + name + "'], " + type + ");";
    }
}
 
Example #17
Source File: SchemaProcessor.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
public void processSchema(Schema schema) {
    if (schema == null) {
        return;
    }
    if (schema.get$ref() != null) {
        processReferenceSchema(schema);
    } else {
        processSchemaType(schema);
    }

}
 
Example #18
Source File: ComponentSchemaTransformer.java    From spring-openapi with MIT License 5 votes vote down vote up
private Optional<Schema> getFieldSchema(Class<?> clazz, Field field, List<String> requiredFields) {
    if (shouldIgnoreField(clazz, field)) {
        return Optional.empty();
    }

    Class<?> typeSignature = field.getType();
    Annotation[] annotations = field.getAnnotations();
    if (isRequired(annotations)) {
        requiredFields.add(field.getName());
    }

    if (typeSignature.isPrimitive()) {
        return createBaseTypeSchema(field, requiredFields, annotations);
    } else if (typeSignature.isArray()) {
        return createArrayTypeSchema(typeSignature, annotations);
    } else if (StringUtils.equalsIgnoreCase(typeSignature.getName(), "java.lang.Object")) {
        ObjectSchema objectSchema = new ObjectSchema();
        objectSchema.setName(field.getName());
        return Optional.of(objectSchema);
    } else if (typeSignature.isAssignableFrom(List.class)) {
        if (field.getGenericType() instanceof ParameterizedType) {
            Class<?> listGenericParameter = (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
            return Optional.of(schemaGeneratorHelper.parseArraySignature(listGenericParameter, annotations));
        }
        return Optional.empty();
    } else {
        return createClassRefSchema(typeSignature, annotations);
    }
}
 
Example #19
Source File: StringTypeValidator.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
public boolean validateFormat(Object argument, Schema schema) throws ValidationException{
    if (argument != null && schema != null) {
        if ("string".equals(schema.getType()) && ("date".equals(schema.getFormat()) || "date-time".equals(schema.getFormat()))) {
            if (argument instanceof DateTime) {

            } else if (argument instanceof LocalDate) {

            } else {
                return true;
            }
        }

    }
    return false;
}
 
Example #20
Source File: RefUtilsTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
private Map<String, Schema> createMap(String... keys) {
    Map<String, Schema> definitionMap = new HashMap<>();

    for (String key : keys) {
        definitionMap.put(key, new Schema());
    }

    return definitionMap;
}
 
Example #21
Source File: OpenApiClientGenerator.java    From spring-openapi with MIT License 5 votes vote down vote up
private FieldSpec.Builder getStringBasedSchemaField(String fieldName, Schema innerSchema, TypeSpec.Builder typeSpecBuilder) {
	if (innerSchema.getFormat() == null) {
		ClassName stringClassName = ClassName.get(JAVA_LANG_PKG, "String");
		FieldSpec.Builder fieldBuilder = FieldSpec.builder(stringClassName, fieldName, Modifier.PRIVATE);
		if (innerSchema.getPattern() != null) {
			fieldBuilder.addAnnotation(AnnotationSpec.builder(Pattern.class)
					.addMember("regexp", "$S", innerSchema.getPattern())
					.build()
			);
		}
		if (innerSchema.getMinLength() != null || innerSchema.getMaxLength() != null) {
			AnnotationSpec.Builder sizeAnnotationBuilder = AnnotationSpec.builder(Size.class);
			if (innerSchema.getMinLength() != null) {
				sizeAnnotationBuilder.addMember("min", "$L", innerSchema.getMinLength());
			}
			if (innerSchema.getMaxLength() != null) {
				sizeAnnotationBuilder.addMember("max", "$L", innerSchema.getMaxLength());
			}
			fieldBuilder.addAnnotation(sizeAnnotationBuilder.build());
		}
		enrichWithGetSet(typeSpecBuilder, stringClassName, fieldName);
		return fieldBuilder;
	} else if (equalsIgnoreCase(innerSchema.getFormat(), "date")) {
		ClassName localDateClassName = ClassName.get(JAVA_TIME_PKG, "LocalDate");
		enrichWithGetSet(typeSpecBuilder, localDateClassName, fieldName);
		return FieldSpec.builder(localDateClassName, fieldName, Modifier.PRIVATE);
	} else if (equalsIgnoreCase(innerSchema.getFormat(), "date-time")) {
		ClassName localDateTimeClassName = ClassName.get(JAVA_TIME_PKG, "LocalDateTime");
		enrichWithGetSet(typeSpecBuilder, localDateTimeClassName, fieldName);
		return FieldSpec.builder(localDateTimeClassName, fieldName, Modifier.PRIVATE);
	}
	throw new IllegalArgumentException(String.format("Error parsing string based property [%s]", fieldName));
}
 
Example #22
Source File: ResourcePatchRelationshipsTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
private Schema checkRelationshipsSchema(boolean updatable) {
	relationshipMetaResourceField.setUpdatable(updatable);
	Schema schema = new ResourcePatchRelationships(metaResource).schema();

	assertNotNull(schema);
	assertEquals(ObjectSchema.class, schema.getClass());
	assertIterableEquals(singleton("relationships"), schema.getProperties().keySet());

	Schema relationshipsSchema = ((ObjectSchema) schema).getProperties().get("relationships");
	assertNotNull(relationshipsSchema);
	assertEquals(ObjectSchema.class, relationshipsSchema.getClass());

	return relationshipsSchema;
}
 
Example #23
Source File: FileSupportConverter.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {
	JavaType javaType = Json.mapper().constructType(type.getType());
	if (javaType != null) {
		Class<?> cls = javaType.getRawClass();
		if (isFile(cls))
			return new FileSchema();
	}
	return (chain.hasNext()) ? chain.next().resolve(type, context, chain) : null;
}
 
Example #24
Source File: ResourcesResponseTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Test
void response() {
  ApiResponse apiResponse = new ResourcesResponse(metaResource).response();
  Assert.assertNotNull(apiResponse);
  Assert.assertEquals("OK", apiResponse.getDescription());
  Content content = apiResponse.getContent();
  Assert.assertEquals(1, content.size());
  Schema schema = content.get("application/vnd.api+json").getSchema();
  Assert.assertEquals(
      "#/components/schemas/ResourceTypeResourcesResponseSchema",
      schema.get$ref()
  );
}
 
Example #25
Source File: ClientGeneratorUtils.java    From spring-openapi with MIT License 5 votes vote down vote up
public static String determineParentClassName(String childClassToFind, Map<String, Schema> allComponents) {
	Schema childClass = allComponents.get(childClassToFind);
	if (childClass instanceof ComposedSchema) {
		ComposedSchema childClassComposed = (ComposedSchema) childClass;
		if (CollectionUtils.isNotEmpty(childClassComposed.getAllOf())) {
			String parentClassRef = childClassComposed.getAllOf().get(0).get$ref();
			if (parentClassRef == null) {
				throw new IllegalArgumentException("Unsupported inheritance model. AllOf $ref for parent class has to be defined");
			}
			return getNameFromRef(parentClassRef);
		}
	}
	throw new IllegalArgumentException("Unsupported inheritance model for " + (childClass == null ? "null" : childClass.getName()));
}
 
Example #26
Source File: CombineGenericSchemaTest.java    From tcases with MIT License 5 votes vote down vote up
@Test
public void whenNotTypesCombined()
  {
  // Given...
  Schema<?> base =
    SchemaBuilder.ofType( null)
    .notTypes( "object", "string")
    .build();

  OpenApiContext context = new OpenApiContext();

  // Then...
  assertThat( "With empty", copySchema( base), matches( new SchemaMatcher( base)));
  assertThat( "With self", combineSchemas( context, base, base), matches( new SchemaMatcher( base)));

  // Given...
  Schema<?> additional =
    SchemaBuilder.ofType( null)
    .notTypes( "object", "boolean")
    .build();

  // When...
  Schema<?> combined = combineSchemas( context, base, additional);

  // Then...
  Schema<?> expected =
    SchemaBuilder.ofType( null)
    .notTypes( "object", "boolean", "string")
    .build();
  
  assertThat( "Generic schema", combined, matches( new SchemaMatcher( expected)));
  }
 
Example #27
Source File: PythonClientExperimentalCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public CodegenParameter fromRequestBody(RequestBody body, Set<String> imports, String bodyParameterName) {
    CodegenParameter result = super.fromRequestBody(body, imports, bodyParameterName);
    // if we generated a model with a non-object type because it has validations or enums,
    // make sure that the datatype of that body parameter refers to our model class
    Content content = body.getContent();
    Set<String> keySet = content.keySet();
    Object[] keyArray = (Object[]) keySet.toArray();
    MediaType mediaType = content.get(keyArray[0]);
    Schema schema = mediaType.getSchema();
    String ref = schema.get$ref();
    if (ref == null) {
        return result;
    }
    String modelName = ModelUtils.getSimpleRef(ref);
    // the result lacks validation info so we need to make a CodegenProperty from the schema to check
    // if we have validation and enum info exists
    Schema realSchema = ModelUtils.getSchema(this.openAPI, modelName);
    CodegenProperty modelProp = fromProperty("body", realSchema);
    if (modelProp.isPrimitiveType && (modelProp.hasValidation || modelProp.isEnum)) {
        String simpleDataType = result.dataType;
        result.dataType = toModelName(modelName);
        result.baseType = getPythonClassName(result.dataType);
        imports.remove(modelName);
        imports.add(result.dataType);
        // set the example value
        if (modelProp.isEnum) {
            String value = modelProp._enum.get(0).toString();
            result.example = result.dataType + "(" + toEnumValue(value, simpleDataType) + ")";
        } else {
            result.example = result.dataType + "(" + result.example + ")";
        }
    } else if (!result.isPrimitiveType) {
        // fix the baseType for the api docs so the .md link to the class's documentation file is correct
        result.baseType = getPythonClassName(result.baseType);
    }
    return result;
}
 
Example #28
Source File: RustServerCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public String toDefaultValue(Schema p) {
    String defaultValue = null;
    if ((ModelUtils.isNullable(p)) && (p.getDefault() != null) && (p.getDefault().toString().equalsIgnoreCase("null")))
        return "swagger::Nullable::Null";
    else if (ModelUtils.isBooleanSchema(p)) {
        if (p.getDefault() != null) {
            if (p.getDefault().toString().equalsIgnoreCase("false"))
                defaultValue = "false";
            else
                defaultValue = "true";
        }
    } else if (ModelUtils.isNumberSchema(p)) {
        if (p.getDefault() != null) {
            defaultValue = p.getDefault().toString();
        }
    } else if (ModelUtils.isIntegerSchema(p)) {
        if (p.getDefault() != null) {
            defaultValue = p.getDefault().toString();
        }
    } else if (ModelUtils.isStringSchema(p)) {
        if (p.getDefault() != null) {
            defaultValue = "\"" + (String) p.getDefault() + "\".to_string()";
        }
    }
    if ((defaultValue != null) && (ModelUtils.isNullable(p)))
        defaultValue = "swagger::Nullable::Present(" + defaultValue + ")";
    return defaultValue;
}
 
Example #29
Source File: InputModeller.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the {@link IVarDef input variable} representing the additional properties of an object instance.
 */
private IVarDef objectAdditionalVar( String instanceVarTag, Schema<?> instanceSchema, PropertyCountConstraints constraints)
  {
  boolean allowed =
    constraints.hasAdditional()
    &&
    Optional.ofNullable( instanceSchema.getMaxProperties()).orElse( Integer.MAX_VALUE) > 0;

  boolean required =
    allowed
    &&
    Optional.ofNullable( instanceSchema.getMinProperties())
    .map( min -> min > constraints.getTotalCount())
    .orElse( false);

  Schema<?> propertySchema = additionalPropertiesSchema( instanceSchema);

  return
    propertySchema != null?
    objectPropertyVar( instanceVarTag, "Additional", required, propertySchema) :

    VarDefBuilder.with( "Additional")
    .values(
      VarValueDefBuilder.with( "Yes")
      .type( allowed? VarValueDef.Type.VALID : VarValueDef.Type.FAILURE)
      .properties( Optional.ofNullable( allowed? objectPropertiesProperty( instanceVarTag) : null))
      .build(),

      VarValueDefBuilder.with( "No")
      .type( required? VarValueDef.Type.FAILURE : VarValueDef.Type.VALID)
      .build())
    .build();
  }
 
Example #30
Source File: CSharpNancyFXServerCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
private static Predicate<Schema> timeProperty() {
    return new Predicate<Schema>() {
        @Override
        public boolean apply(Schema property) {
            return ModelUtils.isStringSchema(property) && "time".equalsIgnoreCase(property.getFormat());
        }
    };
}