Java Code Examples for io.swagger.v3.oas.models.media.ArraySchema

The following examples show how to use io.swagger.v3.oas.models.media.ArraySchema. These examples are extracted from open source projects. 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
@Override
public final List<OasViolation> validate(OasValidationContext context, OasObjectPropertyLocation location,
  Schema oasObject) {

  if (StringUtils.isNotBlank(oasObject.get$ref())) {
    return emptyList();
  }
  if (oasObject instanceof ComposedSchema) {
    return validateComposedSchema(context, (ComposedSchema) oasObject, location);
  }
  if (oasObject instanceof ArraySchema) {
    return validateArraySchema(context, (ArraySchema) oasObject, location);
  }
  return validateOrdinarySchema(context, oasObject, location);

}
 
Example 2
Source Project: spring-openapi   Source File: OpenApiClientGenerator.java    License: MIT License 6 votes vote down vote up
private FieldSpec.Builder parseTypeBasedSchema(String fieldName, Schema innerSchema, String targetPackage,
									   TypeSpec.Builder typeSpecBuilder) {
	if (innerSchema.getEnum() != null) {
		typeSpecBuilder.addType(createEnumClass(StringUtils.capitalize(fieldName), innerSchema).build());
		return createSimpleFieldSpec(null, StringUtils.capitalize(fieldName), fieldName, typeSpecBuilder);
	}
	if (equalsIgnoreCase(innerSchema.getType(), "string")) {
		return getStringBasedSchemaField(fieldName, innerSchema, typeSpecBuilder);
	} else if (equalsIgnoreCase(innerSchema.getType(), "integer") || equalsIgnoreCase(innerSchema.getType(), "number")) {
		return getNumberBasedSchemaField(fieldName, innerSchema, typeSpecBuilder);
	} else if (equalsIgnoreCase(innerSchema.getType(), "boolean")) {
		return createSimpleFieldSpec(JAVA_LANG_PKG, "Boolean", fieldName, typeSpecBuilder);
	} else if (equalsIgnoreCase(innerSchema.getType(), "array") && innerSchema instanceof ArraySchema) {
		ArraySchema arraySchema = (ArraySchema) innerSchema;
		ParameterizedTypeName listParameterizedTypeName = ParameterizedTypeName.get(
				ClassName.get("java.util", "List"),
				determineTypeName(arraySchema.getItems(), targetPackage)
		);
		enrichWithGetSetList(typeSpecBuilder, listParameterizedTypeName, fieldName);
		return FieldSpec.builder(listParameterizedTypeName, fieldName, Modifier.PRIVATE);
	}
	return createSimpleFieldSpec(JAVA_LANG_PKG, "Object", fieldName, typeSpecBuilder);
}
 
Example 3
Source Project: spring-openapi   Source File: ResourceInterfaceGenerator.java    License: MIT License 6 votes vote down vote up
private ParameterSpec.Builder parseTypeBasedSchema(String parameterName, Schema innerSchema) {
	if (equalsIgnoreCase(innerSchema.getType(), "string")) {
		return ParameterSpec.builder(getStringGenericClassName(innerSchema), parameterName);
	} else if (equalsIgnoreCase(innerSchema.getType(), "integer") || equalsIgnoreCase(innerSchema.getType(), "number")) {
		return getNumberBasedSchemaParameter(parameterName, innerSchema);
	} else if (equalsIgnoreCase(innerSchema.getType(), "boolean")) {
		return createSimpleParameterSpec(JAVA_LANG_PKG, "Boolean", parameterName);
	} else if (equalsIgnoreCase(innerSchema.getType(), "array") && innerSchema instanceof ArraySchema) {
		ArraySchema arraySchema = (ArraySchema) innerSchema;
		ParameterizedTypeName listParameterizedTypeName = ParameterizedTypeName.get(
				ClassName.get("java.util", "List"),
				determineTypeName(arraySchema.getItems())
		);
		return ParameterSpec.builder(listParameterizedTypeName, parameterName);
	} else if (equalsIgnoreCase(innerSchema.getType(), "object") && isFile(innerSchema.getProperties())) {
		return ParameterSpec.builder(ClassName.get(File.class), parameterName);
	}
	return createSimpleParameterSpec(JAVA_LANG_PKG, "Object", parameterName);
}
 
Example 4
@Override
public Schema<?> resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {
	if (chain.hasNext() && type != null && type.getType() instanceof CollectionType
			&& "_embedded".equalsIgnoreCase(type.getPropertyName())) {
		Schema<?> schema = chain.next().resolve(type, context, chain);
		if (schema instanceof ArraySchema) {
			Class<?> entityType = getEntityType(type);
			String entityClassName = linkRelationProvider.getCollectionResourceRelFor(entityType).value();

			return new ObjectSchema()
					.name("_embedded")
					.addProperties(entityClassName, schema);
		}
	}
	return chain.hasNext() ? chain.next().resolve(type, context, chain) : null;
}
 
Example 5
Source Project: springdoc-openapi   Source File: GenericParameterBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Calculate request body schema schema.
 *
 * @param components the components
 * @param parameterInfo the parameter info
 * @param requestBodyInfo the request body info
 * @param schemaN the schema n
 * @param paramName the param name
 * @return the schema
 */
private Schema calculateRequestBodySchema(Components components, ParameterInfo parameterInfo, RequestBodyInfo requestBodyInfo, Schema schemaN, String paramName) {
	if (schemaN != null && StringUtils.isEmpty(schemaN.getDescription()) && parameterInfo.getParameterModel() != null) {
		String description = parameterInfo.getParameterModel().getDescription();
		if (schemaN.get$ref() != null && schemaN.get$ref().contains(AnnotationsUtils.COMPONENTS_REF)) {
			String key = schemaN.get$ref().substring(21);
			Schema existingSchema = components.getSchemas().get(key);
			existingSchema.setDescription(description);
		}
		else
			schemaN.setDescription(description);
	}

	if (requestBodyInfo.getMergedSchema() != null) {
		requestBodyInfo.getMergedSchema().addProperties(paramName, schemaN);
		schemaN = requestBodyInfo.getMergedSchema();
	}
	else if (schemaN instanceof FileSchema || schemaN instanceof ArraySchema && ((ArraySchema) schemaN).getItems() instanceof FileSchema) {
		schemaN = new ObjectSchema().addProperties(paramName, schemaN);
		requestBodyInfo.setMergedSchema(schemaN);
	}
	else
		requestBodyInfo.addProperties(paramName, schemaN);
	return schemaN;
}
 
Example 6
/**
 * Gets media type.
 *
 * @param schema the schema
 * @param components the components
 * @param jsonViewAnnotation the json view annotation
 * @param annotationContent the annotation content
 * @return the media type
 */
private static MediaType getMediaType(Schema schema, Components components, JsonView jsonViewAnnotation,
		io.swagger.v3.oas.annotations.media.Content annotationContent) {
	MediaType mediaType = new MediaType();
	if (!annotationContent.schema().hidden()) {
		if (components != null) {
			try {
				getSchema(annotationContent, components, jsonViewAnnotation).ifPresent(mediaType::setSchema);
			}
			catch (Exception e) {
				if (isArray(annotationContent))
					mediaType.setSchema(new ArraySchema().items(new StringSchema()));
				else
					mediaType.setSchema(new StringSchema());
			}
		}
		else {
			mediaType.setSchema(schema);
		}
	}
	return mediaType;
}
 
Example 7
@Override
public String toInstantiationType(Schema p) {
    if (ModelUtils.isMapSchema(p)) {
        Schema additionalProperties2 = getAdditionalProperties(p);
        String type = additionalProperties2.getType();
        if (null == type) {
            LOGGER.error("No Type defined for Additional Schema " + additionalProperties2 + "\n" //
                    + "\tIn Schema: " + p);
        }
        String inner = getSchemaType(additionalProperties2);
        return "(Map.Map Text " + inner + ")";
    } else if (ModelUtils.isArraySchema(p)) {
        ArraySchema ap = (ArraySchema) p;
        return getSchemaType(ap.getItems());
    } else {
        return null;
    }
}
 
Example 8
Source Project: openapi-generator   Source File: AbstractKotlinCodegen.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Provides a strongly typed declaration for simple arrays of some type and arrays of arrays of some type.
 *
 * @param arr Array schema
 * @return type declaration of array
 */
private String getArrayTypeDeclaration(ArraySchema arr) {
    // TODO: collection type here should be fully qualified namespace to avoid model conflicts
    // This supports arrays of arrays.
    String arrayType;
    if (ModelUtils.isSet(arr)) {
        arrayType = typeMapping.get("set");
    } else {
        arrayType = typeMapping.get("array");
    }
    StringBuilder instantiationType = new StringBuilder(arrayType);
    Schema items = arr.getItems();
    String nestedType = getTypeDeclaration(items);
    additionalProperties.put("nestedType", nestedType);
    // TODO: We may want to differentiate here between generics and primitive arrays.
    instantiationType.append("<").append(nestedType).append(">");
    return instantiationType.toString();
}
 
Example 9
Source Project: swagger-parser   Source File: InlineModelResolver.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("static-method")
public Schema modelFromProperty(Schema object, @SuppressWarnings("unused") String path) {
    String description = object.getDescription();
    String example = null;

    Object obj = object.getExample();
    if (obj != null) {
        example = obj.toString();
    }
    ArraySchema model = new ArraySchema();
    model.setDescription(description);
    model.setExample(example);
    if (object.getAdditionalProperties() != null && !(object.getAdditionalProperties() instanceof Boolean)) {
        model.setItems((Schema)  object.getAdditionalProperties());
    }
    return model;
}
 
Example 10
@Test
public void testConvertStringArrayCSV() throws Exception {
    List<String> values = Arrays.asList("a,b");

    Parameter parameter = new QueryParameter()
            .style(Parameter.StyleEnum.FORM)
            .explode(false)//("csv")
            .schema(new ArraySchema()
                    .items(new StringSchema()));

    Object o = utils.cast(values, parameter, tf.constructArrayType(String.class), null);

    assertTrue(o instanceof List);

    @SuppressWarnings("unchecked")
    List<String> objs = (List<String>) o;

    assertTrue(objs.size() == 2);
    assertEquals(objs.get(0), "a");
    assertEquals(objs.get(1), "b");
}
 
Example 11
/**
 * Extracts the list of type names from a list of schemas.
 * Excludes `AnyType` if there are other valid types extracted.
 *
 * @param schemas list of schemas
 * @return list of types
 */
protected List<String> getTypesFromSchemas(List<Schema> schemas) {
    List<Schema> filteredSchemas = schemas.size() > 1
        ? schemas.stream().filter(schema -> super.getSchemaType(schema) != "AnyType").collect(Collectors.toList())
        : schemas;

    return filteredSchemas.stream().map(schema -> {
        String schemaType = getSchemaType(schema);
        if (ModelUtils.isArraySchema(schema)) {
            ArraySchema ap = (ArraySchema) schema;
            Schema inner = ap.getItems();
            schemaType = schemaType + "<" + getSchemaType(inner) + ">";
        }
        return schemaType;
    }).distinct().collect(Collectors.toList());
}
 
Example 12
@Test
public void addsImportForSetArgument() throws IOException {
    File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
    output.deleteOnExit();
    String outputPath = output.getAbsolutePath().replace('\\', '/');

    OpenAPI openAPI = new OpenAPIParser()
        .readLocation("src/test/resources/3_0/arrayParameter.yaml", null, new ParseOptions()).getOpenAPI();

    openAPI.getComponents().getParameters().get("operationsQueryParam").setSchema(new ArraySchema().uniqueItems(true));
    codegen.setOutputDir(output.getAbsolutePath());

    codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true");

    ClientOptInput input = new ClientOptInput()
        .openAPI(openAPI)
        .config(codegen);

    DefaultGenerator generator = new DefaultGenerator(false);
    generator.opts(input).generate();

    Path path = Paths.get(outputPath + "/src/gen/java/org/openapitools/api/ExamplesApi.java");

    assertFileContains(path, "\nimport java.util.Set;\n");
}
 
Example 13
@Test
public void testConvertIntegerArraySSVValue() throws Exception {
    List<String> values = Arrays.asList("1 2 3");

    Parameter parameter = new QueryParameter()
            .style(Parameter.StyleEnum.SPACEDELIMITED)
            .explode(false)//("csv")
            .schema(new ArraySchema()
                    .items(new IntegerSchema()));

    Object o = utils.cast(values, parameter, tf.constructArrayType(Integer.class), null);

    assertTrue(o instanceof List);

    @SuppressWarnings("unchecked")
    List<Integer> objs = (List<Integer>) o;

    assertTrue(objs.size() == 3);
    assertEquals(objs.get(0), new Integer(1));
    assertEquals(objs.get(1), new Integer(2));
    assertEquals(objs.get(2), new Integer(3));
}
 
Example 14
Source Project: openapi-generator   Source File: DartDioModelTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(description = "convert a model with complex list property")
public void complexListProperty() {
    final Schema model = new Schema()
            .description("a sample model")
            .addProperties("children", new ArraySchema()
                    .items(new Schema().$ref("#/definitions/Children")));
    final DefaultCodegen codegen = new DartDioClientCodegen();
    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
    codegen.setOpenAPI(openAPI);
    final CodegenModel cm = codegen.fromModel("sample", model);

    Assert.assertEquals(cm.name, "sample");
    Assert.assertEquals(cm.classname, "Sample");
    Assert.assertEquals(cm.description, "a sample model");
    Assert.assertEquals(cm.vars.size(), 1);

    final CodegenProperty property1 = cm.vars.get(0);
    Assert.assertEquals(property1.baseName, "children");
    Assert.assertEquals(property1.dataType, "BuiltList<Children>");
    Assert.assertEquals(property1.name, "children");
    Assert.assertEquals(property1.baseType, "BuiltList");
    Assert.assertEquals(property1.containerType, "array");
    Assert.assertFalse(property1.required);
    Assert.assertTrue(property1.isContainer);
}
 
Example 15
Source Project: openapi-generator   Source File: DartDioModelTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(description = "convert an array model")
public void arrayModelTest() {
    final Schema model = new ArraySchema()
            .items(new Schema().$ref("#/definitions/Children"))
            .description("an array model");
    final DefaultCodegen codegen = new DartDioClientCodegen();
    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
    codegen.setOpenAPI(openAPI);
    final CodegenModel cm = codegen.fromModel("sample", model);

    Assert.assertEquals(model.getDescription(), "an array model");

    Assert.assertEquals(cm.name, "sample");
    Assert.assertEquals(cm.classname, "Sample");
    Assert.assertTrue(cm.isArrayModel);
    Assert.assertEquals(cm.description, "an array model");
    Assert.assertEquals(cm.vars.size(), 0);
    // skip import test as import is not used by PHP codegen
}
 
Example 16
Source Project: raptor   Source File: RefHelper.java    License: Apache License 2.0 6 votes vote down vote up
private Map<String, Schema> buildProperties(MessageType protoType) {
    Map<String, Schema> properties = new LinkedHashMap<>();
    // 不处理oneof
    ImmutableList<Field> fields = protoType.fields();
    for (Field field : fields) {
        ProtoType fieldType = field.type();
        String fieldName = field.name();


        Schema property = getSchemaByType(fieldType);
        if (field.isRepeated()) {
            property = new ArraySchema().items(property);
        }
        property.description(field.documentation());
        properties.put(fieldName, property);
    }
    return properties;
}
 
Example 17
Source Project: carbon-apimgt   Source File: OASParserUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static void extractReferenceFromSchema(Schema schema, SwaggerUpdateContext context) {
    if (schema != null) {
        String ref = schema.get$ref();
        if (ref == null) {
            if (ARRAY_DATA_TYPE.equalsIgnoreCase(schema.getType())) {
                ArraySchema arraySchema = (ArraySchema) schema;
                ref = arraySchema.getItems().get$ref();
            }
        }

        if (ref != null) {
            addToReferenceObjectMap(ref, context);
        }

        // Process schema properties if present
        Map properties = schema.getProperties();

        if (properties != null) {
            for (Object propertySchema : properties.values()) {
                extractReferenceFromSchema((Schema) propertySchema, context);
            }
        }
    }
}
 
Example 18
Source Project: crnk-framework   Source File: Failure.java    License: Apache License 2.0 6 votes vote down vote up
public Schema schema() {
  return new ObjectSchema()
      .addProperties("jsonapi", new JsonApi().$ref())
      .addProperties(
          "errors",
          new ArraySchema()
              .items(new ApiError().$ref())
              .uniqueItems(true))
      .addProperties(
          "meta",
          new Meta().$ref())
      .addProperties(
          "links",
          new Links().$ref())
      .required(Collections.singletonList("errors"))
      .additionalProperties(false);
}
 
Example 19
Source Project: openapi-diff   Source File: ArraySchemaDiffResult.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T extends Schema<X>, X> Optional<ChangedSchema> diff(
    HashSet<String> refSet,
    Components leftComponents,
    Components rightComponents,
    T left,
    T right,
    DiffContext context) {
  ArraySchema leftArraySchema = (ArraySchema) left;
  ArraySchema rightArraySchema = (ArraySchema) right;
  super.diff(refSet, leftComponents, rightComponents, left, right, context);
  openApiDiff
      .getSchemaDiff()
      .diff(
          refSet,
          leftArraySchema.getItems(),
          rightArraySchema.getItems(),
          context.copyWithRequired(true))
      .ifPresent(changedSchema::setItems);
  return isApplicable(context);
}
 
Example 20
Source Project: zap-extensions   Source File: ArrayGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public String generate(
        String name, ArraySchema property, String collectionType, boolean isPath) {

    if (property == null) {
        return "";
    }
    if (collectionType.isEmpty()) {
        collectionType = "csv";
    }
    String valueType = property.getItems().getType();
    if (dataGenerator.isArray(valueType)) {
        if (property.getItems() instanceof ArraySchema) {
            return generate(name, (ArraySchema) property.getItems(), collectionType, isPath);
        } else {
            return "";
        }
    }
    String value = dataGenerator.generateValue(name, property.getItems(), isPath);
    return ARRAY_BEGIN + value + ARRAY_END;
}
 
Example 21
Source Project: zap-extensions   Source File: BodyGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private String generateFromArraySchema(ArraySchema schema) {
    if (schema.getExample() instanceof String) {
        return (String) schema.getExample();
    }

    if (schema.getExample() instanceof Iterable) {
        try {
            return Json.mapper().writeValueAsString(schema.getExample());
        } catch (JsonProcessingException e) {
            LOG.warn(
                    "Failed to encode Example Object. Falling back to default example generation",
                    e);
        }
    }

    return createJsonArrayWith(generate(schema.getItems()));
}
 
Example 22
Source Project: swagger-parser   Source File: InlineModelResolver.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("static-method")
public Schema modelFromProperty(ArraySchema object, @SuppressWarnings("unused") String path) {
    String description = object.getDescription();
    String example = null;

    Object obj = object.getExample();
    if (obj != null) {
        example = obj.toString();
    }

    Schema inner = object.getItems();
    if (inner instanceof ObjectSchema) {
        ArraySchema model = new ArraySchema();
        model.setDescription(description);
        model.setExample(example);
        model.setItems(object.getItems());
        return model;
    }

    return null;
}
 
Example 23
Source Project: flow   Source File: SchemaResolverTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void should_ReturnArraySchema_When_GivenTypeIsAnArray() {
    ResolvedType arrayType = mock(ResolvedType.class);
    ResolvedArrayType arrayResolvedType = mock(ResolvedArrayType.class);
    ResolvedType stringType = mockReferencedTypeOf(String.class);

    when(arrayType.isArray()).thenReturn(true);
    when(arrayType.asArrayType()).thenReturn(arrayResolvedType);
    when(arrayResolvedType.getComponentType()).thenReturn(stringType);

    Schema schema = schemaResolver.parseResolvedTypeToSchema(arrayType);
    Assert.assertTrue(schema instanceof ArraySchema);
    Assert.assertNull(schema.getNullable());
    Assert.assertTrue(
            ((ArraySchema) schema).getItems() instanceof StringSchema);
    Assert.assertTrue(schemaResolver.getFoundTypes().isEmpty());
}
 
Example 24
Source Project: flow   Source File: SchemaResolverTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void should_ReturnNotNullableArray_When_GivenTypeIsAListString() {
    ResolvedType resolvedType = mockReferencedTypeOf(Collection.class);
    ResolvedReferenceType resolvedReferenceType = resolvedType
            .asReferenceType();

    List<Pair<ResolvedTypeParameterDeclaration, ResolvedType>> pairs = Collections
            .singletonList(
                    new Pair<>(null, mockReferencedTypeOf(String.class)));
    when(resolvedReferenceType.getTypeParametersMap()).thenReturn(pairs);

    Schema schema = schemaResolver.parseResolvedTypeToSchema(resolvedType);

    Assert.assertTrue(schema instanceof ArraySchema);
    Assert.assertNull(schema.getNullable());
    Assert.assertTrue(
            ((ArraySchema) schema).getItems() instanceof StringSchema);
    Assert.assertTrue(schemaResolver.getFoundTypes().isEmpty());
}
 
Example 25
Source Project: swagger-parser   Source File: InlineModelResolverTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testArbitraryObjectModelWithArrayInlineWithTitle() {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setComponents(new Components());

    Schema items = new ObjectSchema();
    items.setTitle("InnerUserTitle");
    items.setDefault("default");
    items.setReadOnly(false);
    items.setDescription("description");
    items.setName("name");
    items.addProperties("arbitrary", new ObjectSchema());

    openAPI.getComponents().addSchemas("User", new ArraySchema().items(items).addRequiredItem("name"));

    new InlineModelResolver().flatten(openAPI);

    Schema model = openAPI.getComponents().getSchemas().get("User");
    assertTrue(model instanceof ArraySchema);
    ArraySchema am = (ArraySchema) model;
    Schema inner = am.getItems();
    assertTrue(inner.get$ref() != null);

    Schema userInner = openAPI.getComponents().getSchemas().get("InnerUserTitle");
    assertNotNull(userInner);
    Schema inlineProp = (Schema) userInner.getProperties().get("arbitrary");
    assertTrue(inlineProp instanceof ObjectSchema);
    ObjectSchema op = (ObjectSchema) inlineProp;
    assertNull(op.getProperties());
}
 
Example 26
Source Project: openapi-generator   Source File: AbstractJavaCodegen.java    License: 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 27
Source Project: openapi-generator   Source File: AbstractKotlinCodegen.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Output the type declaration of the property
 *
 * @param p OpenAPI Property object
 * @return a string presentation of the property type
 */
@Override
public String getTypeDeclaration(Schema p) {
    if (ModelUtils.isArraySchema(p)) {
        return getArrayTypeDeclaration((ArraySchema) p);
    } else if (ModelUtils.isMapSchema(p)) {
        Schema inner = getAdditionalProperties(p);

        // Maps will be keyed only by primitive Kotlin string
        return getSchemaType(p) + "<kotlin.String, " + getTypeDeclaration(inner) + ">";
    }
    return super.getTypeDeclaration(p);
}
 
Example 28
Source Project: swagger-parser   Source File: V2ConverterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(description = "Request Body Completions")
public void testIssue19() throws Exception {
    OpenAPI oas = getConvertedOpenAPIFromJsonFile(ISSUE_19_JSON);
    RequestBody requestBody = oas.getPaths().get(POST_PATH).getPost().getRequestBody();
    assertNotNull(requestBody);
    Schema schema = requestBody.getContent().get(URLENCODED_CONTENT).getSchema();
    assertNotNull(schema);
    Map properties = schema.getProperties();
    assertEquals(PROPERTIES_SIZE, properties.size());
    ArraySchema ids = (ArraySchema) properties.get("ids");
    assertEquals(new Integer(MIN_ITEMS), ids.getMinItems());
    assertEquals(new Integer(MAXIMUM), ids.getMaxItems());
    //Fixed from Issue 19
    assertEquals(Boolean.TRUE, ids.getUniqueItems());

    Schema login = (Schema) properties.get("login");
    assertEquals(new Integer(MIN_LENGTH), login.getMinLength());
    assertEquals(new Integer(MAX_LENGTH), login.getMaxLength());
    assertEquals(PATTERN, login.getPattern());
    Schema favNumber = (Schema) properties.get("favNumber");
    assertEquals(new BigDecimal(MAXIMUM), favNumber.getMinimum());
    assertEquals(new BigDecimal(MAXIMUM), favNumber.getMaximum());
    assertEquals(Boolean.TRUE, favNumber.getExclusiveMinimum());
    assertEquals(Boolean.TRUE, favNumber.getExclusiveMaximum());
    assertEquals(new BigDecimal(MULTIPLE_OF_VALUE), new BigDecimal(favNumber.getMultipleOf().doubleValue()));

    Schema dayOfWeek = (Schema) properties.get("dayOfWeek");
    assertEquals(MONDAY_TUESDAY_VALUE, dayOfWeek.getDefault());
    assertEquals(MONDAY_TUESDAY_VALUE, dayOfWeek.getEnum().get(0));
    assertEquals(TUESDAY_WEDNESDAY_VALUE, dayOfWeek.getEnum().get(1));
    assertEquals(WEDNESDAY_THURSDAY_VALUE, dayOfWeek.getEnum().get(2));
}
 
Example 29
Source Project: openapi-generator   Source File: AbstractCSharpCodegen.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Provides C# strongly typed declaration for simple arrays of some type and arrays of arrays of some type.
 *
 * @param arr The input array property
 * @return The type declaration when the type is an array of arrays.
 */
private String getArrayTypeDeclaration(ArraySchema arr) {
    // TODO: collection type here should be fully qualified namespace to avoid model conflicts
    // This supports arrays of arrays.
    String arrayType = typeMapping.get("array");
    StringBuilder instantiationType = new StringBuilder(arrayType);
    Schema items = arr.getItems();
    String nestedType = getTypeDeclaration(items);
    // TODO: We may want to differentiate here between generics and primitive arrays.
    instantiationType.append("<").append(nestedType).append(">");
    return instantiationType.toString();
}
 
Example 30
Source Project: openapi-generator   Source File: AbstractCSharpCodegen.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String toInstantiationType(Schema p) {
    if (ModelUtils.isArraySchema(p)) {
        return getArrayTypeDeclaration((ArraySchema) p);
    }
    return super.toInstantiationType(p);
}