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

The following examples show how to use io.swagger.v3.oas.models.media.ComposedSchema. 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: SchemaAnalyzer.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Resolves the members of a ComposedSchema.
 */
private void resolveMembers( OpenAPI api, ComposedSchema composed)
  {
  // Resolve "allOf" schemas
  composed.setAllOf(
    Optional.ofNullable( composed.getAllOf()).orElse( emptyList())
    .stream()
    .map( member -> resultFor( "allOf", () -> resolve( api, member)))
    .collect( toList()));
    
  // Resolve "anyOf" schemas
  composed.setAnyOf(
    Optional.ofNullable( composed.getAnyOf()).orElse( emptyList())
    .stream()
    .map( member -> resultFor( "anyOf", () -> resolve( api, member)))
    .collect( toList()));
    
  // Resolve "oneOf" schemas
  composed.setOneOf(
    Optional.ofNullable( composed.getOneOf()).orElse( emptyList())
    .stream()
    .map( member -> resultFor( "oneOf", () -> resolve( api, member)))
    .collect( toList()));
  }
 
Example #2
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void resolveComposedSchema(@Injectable final List<AuthorizationValue> auths){

    ParseOptions options = new ParseOptions();
    options.setResolveCombinators(false);
    options.setResolveFully(true);
    OpenAPI openAPI = new OpenAPIV3Parser().readLocation("src/test/resources/oneof-anyof.yaml",auths,options).getOpenAPI();


    assertTrue(openAPI.getPaths().get("/mixed-array").getGet().getResponses().get("200").getContent().get("application/json").getSchema() instanceof ArraySchema);
    ArraySchema arraySchema = (ArraySchema) openAPI.getPaths().get("/mixed-array").getGet().getResponses().get("200").getContent().get("application/json").getSchema();
    assertTrue(arraySchema.getItems() instanceof ComposedSchema);
    ComposedSchema oneOf = (ComposedSchema) arraySchema.getItems();
    assertEquals(oneOf.getOneOf().get(0).getType(), "string");

    //System.out.println(openAPI.getPaths().get("/oneOf").getGet().getResponses().get("200").getContent().get("application/json").getSchema() );
    assertTrue(openAPI.getPaths().get("/oneOf").getGet().getResponses().get("200").getContent().get("application/json").getSchema() instanceof ComposedSchema);
    ComposedSchema oneOfSchema = (ComposedSchema) openAPI.getPaths().get("/oneOf").getGet().getResponses().get("200").getContent().get("application/json").getSchema();
    assertEquals(oneOfSchema.getOneOf().get(0).getType(), "object");

}
 
Example #3
Source File: SchemaProcessor.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
public void processSchemaType(Schema schema){

        if (schema instanceof ArraySchema) {
            processArraySchema((ArraySchema) schema);
        }
        if (schema instanceof ComposedSchema) {
            processComposedSchema((ComposedSchema) schema);
        }

        if(schema.getProperties() != null && schema.getProperties().size() > 0){
            processPropertySchema(schema);
        }

        if(schema.getNot() != null){
            processNotSchema(schema);
        }
        if(schema.getAdditionalProperties() != null){
            processAdditionalProperties(schema);
            
        }
        if (schema.getDiscriminator() != null) {
            processDiscriminatorSchema(schema);
        }

    }
 
Example #4
Source File: ExternalRefProcessor.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
private void processSchema(Schema property, String file) {
    if (property != null) {
        if (StringUtils.isNotBlank(property.get$ref())) {
            processRefSchema(property, file);
        }
        if (property.getProperties() != null) {
            processProperties(property.getProperties(), file);
        }
        if (property instanceof ArraySchema) {
            processSchema(((ArraySchema) property).getItems(), file);
        }
        if (property.getAdditionalProperties() instanceof Schema) {
            processSchema(((Schema) property.getAdditionalProperties()), file);
        }
        if (property instanceof ComposedSchema) {
            ComposedSchema composed = (ComposedSchema) property;
            processProperties(composed.getAllOf(), file);
            processProperties(composed.getAnyOf(), file);
            processProperties(composed.getOneOf(), file);
        }
    }
}
 
Example #5
Source File: InfluxJavaGenerator.java    From influxdb-client-java with MIT License 6 votes vote down vote up
private List<Schema> getOneOf(final Schema schema, final Map<String, Schema> allDefinitions) {

        List<Schema> schemas = new ArrayList<>();

        if (schema instanceof ComposedSchema) {

            ComposedSchema composedSchema = (ComposedSchema) schema;
            for (Schema oneOfSchema : composedSchema.getOneOf()) {

                if (oneOfSchema.get$ref() != null) {

                    Schema refSchema = allDefinitions.get(ModelUtils.getSimpleRef(oneOfSchema.get$ref()));
                    if (refSchema instanceof ComposedSchema && ((ComposedSchema) refSchema).getOneOf() != null) {
                        schemas.addAll(((ComposedSchema) refSchema).getOneOf());
                    } else {
                        schemas.add(oneOfSchema);
                    }
                }
            }
        }

        return schemas;
    }
 
Example #6
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssueFlattenAdditionalPropertiesSchemaInlineModelTrue() {
    OpenAPIV3Parser openApiParser = new OpenAPIV3Parser();
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setFlatten(true);
    options.setFlattenComposedSchemas(true);
    options.setCamelCaseFlattenNaming(true);
    SwaggerParseResult parseResult = openApiParser.readLocation("additionalPropertiesFlatten.yaml", null, options);
    OpenAPI openAPI = parseResult.getOpenAPI();

    //responses
    assertNotNull(openAPI.getComponents().getSchemas().get("Inline_response_map200"));
    assertEquals(((ComposedSchema)openAPI.getComponents().getSchemas().get("Inline_response_map200")).getOneOf().get(0).get$ref(),"#/components/schemas/Macaw1");
    assertNotNull(openAPI.getComponents().getSchemas().get("Inline_response_map_items404"));
    assertEquals(((ComposedSchema)openAPI.getComponents().getSchemas().get("Inline_response_map_items404")).getAnyOf().get(0).get$ref(),"#/components/schemas/Macaw2");
}
 
Example #7
Source File: PolymorphicModelConverter.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Compose polymorphic schema schema.
 *
 * @param type the type
 * @param schema the schema
 * @param schemas the schemas
 * @return the schema
 */
private Schema composePolymorphicSchema(AnnotatedType type, Schema schema, Collection<Schema> schemas) {
	String ref = schema.get$ref();
	List<Schema> composedSchemas = schemas.stream()
			.filter(s -> s instanceof ComposedSchema)
			.map(s -> (ComposedSchema) s)
			.filter(s -> s.getAllOf() != null)
			.filter(s -> s.getAllOf().stream().anyMatch(s2 -> ref.equals(s2.get$ref())))
			.map(s -> new Schema().$ref(AnnotationsUtils.COMPONENTS_REF + s.getName()))
			.collect(Collectors.toList());
	if (composedSchemas.isEmpty()) return schema;

	ComposedSchema result = new ComposedSchema();
	if (isConcreteClass(type)) result.addOneOfItem(schema);
	composedSchemas.forEach(result::addOneOfItem);
	return result;
}
 
Example #8
Source File: OpenApiClientGenerator.java    From spring-openapi with MIT License 6 votes vote down vote up
private ClassName determineTypeName(Schema<?> arrayItemsSchema, String targetPackage) {
	if (equalsIgnoreCase(arrayItemsSchema.getType(), "string")) {
		return getStringGenericClassName(arrayItemsSchema);
	} else if (equalsIgnoreCase(arrayItemsSchema.getType(), "integer") || equalsIgnoreCase(arrayItemsSchema.getType(), "number")) {
		return getNumberGenericClassName(arrayItemsSchema);
	} else if (equalsIgnoreCase(arrayItemsSchema.getType(), "boolean")) {
		return ClassName.get(JAVA_LANG_PKG, "Boolean");
	} else if (arrayItemsSchema.get$ref() != null) {
		return ClassName.get(targetPackage, getNameFromRef(arrayItemsSchema.get$ref()));
	} else if (arrayItemsSchema instanceof ComposedSchema && CollectionUtils.isNotEmpty(((ComposedSchema) arrayItemsSchema).getAllOf())) {
		return ClassName.get(targetPackage, determineParentClassNameUsingOneOf(arrayItemsSchema, "innerArray", allComponents));
	} else if (arrayItemsSchema.getDiscriminator() != null) {
		return ClassName.get(targetPackage, determineParentClassNameUsingDiscriminator(arrayItemsSchema, "innerArray", allComponents));
	}
	return ClassName.get(JAVA_LANG_PKG, "Object");
}
 
Example #9
Source File: OpenApi3Utils.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
public static Map<String, ObjectField> solveObjectParameters(Schema schema) {
  if (OpenApi3Utils.isSchemaObjectOrAllOfType(schema)) {
    if (OpenApi3Utils.isAllOfSchema(schema)) {
      // allOf case
      ComposedSchema composedSchema = (ComposedSchema) schema;
      return resolveAllOfArrays(new ArrayList<>(composedSchema.getAllOf()));
    } else {
      // type object case
      Map<String, ObjectField> properties = new HashMap<>();
      if (schema.getProperties() == null) return new HashMap<>();
      for (Map.Entry<String, ? extends Schema> entry : ((Map<String, Schema>) schema.getProperties()).entrySet()) {
        properties.put(entry.getKey(), new OpenApi3Utils.ObjectField(entry.getValue(), entry.getKey(), schema));
      }
      return properties;
    }
  } else return null;
}
 
Example #10
Source File: SchemaRecursiveValidatorTemplate.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: OpenAPIResolverTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue1161(@Injectable final List<AuthorizationValue> auths) {
    String path = "/issue-1161/swagger.yaml";

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

    OpenAPI openAPI = new OpenAPIV3Parser().readLocation(path, auths, options).getOpenAPI();

    Schema petsSchema = openAPI.getComponents().getSchemas().get("Pets");
    Schema colouringsSchema = openAPI.getComponents().getSchemas().get("Colouring");

    assertNotNull(petsSchema);
    assertNotNull(colouringsSchema);

    assertTrue(petsSchema instanceof ComposedSchema);
    assertTrue(petsSchema.getProperties() != null);
    assertTrue(((ComposedSchema) petsSchema).getOneOf() != null);

    Schema petsColouringProperty = (Schema) petsSchema.getProperties().get("colouring");
    assertTrue(petsColouringProperty.get$ref() == null);
    assertTrue(petsColouringProperty == colouringsSchema);
}
 
Example #12
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 #13
Source File: JavaInheritanceTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test(description = "convert a composed model with discriminator")
public void javaInheritanceWithDiscriminatorTest() {
    final Schema base = new Schema().name("Base");
    Discriminator discriminator = new Discriminator().mapping("name", StringUtils.EMPTY);
    discriminator.setPropertyName("model_type");
    base.setDiscriminator(discriminator);

    final Schema schema = new ComposedSchema()
            .addAllOfItem(new Schema().$ref("Base"));

    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("Base", base);

    final JavaClientCodegen codegen = new JavaClientCodegen();
    codegen.setOpenAPI(openAPI);
    final CodegenModel cm = codegen.fromModel("sample", schema);

    Assert.assertEquals(cm.name, "sample");
    Assert.assertEquals(cm.classname, "Sample");
    Assert.assertEquals(cm.parent, "Base");
    Assert.assertEquals(cm.imports, Sets.newHashSet("Base"));
}
 
Example #14
Source File: VaadinConnectTsGenerator.java    From flow with Apache License 2.0 6 votes vote down vote up
private Set<String> collectImportsFromSchema(Schema schema) {
    Set<String> imports = new HashSet<>();
    if (GeneratorUtils.isNotBlank(schema.get$ref())) {
        imports.add(getSimpleRef(schema.get$ref()));
    }
    if (schema instanceof ArraySchema) {
        imports.addAll(collectImportsFromSchema(
                ((ArraySchema) schema).getItems()));
    } else if (schema instanceof MapSchema
            || schema.getAdditionalProperties() instanceof Schema) {
        imports.addAll(collectImportsFromSchema(
                (Schema) schema.getAdditionalProperties()));
    } else if (schema instanceof ComposedSchema) {
        for (Schema child : ((ComposedSchema) schema).getAllOf()) {
            imports.addAll(collectImportsFromSchema(child));
        }
    }
    if (schema.getProperties() != null) {
        schema.getProperties().values().forEach(
                o -> imports.addAll(collectImportsFromSchema((Schema) o)));
    }
    return imports;
}
 
Example #15
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 #16
Source File: SchemaAnalyzer.java    From tcases with MIT License 6 votes vote down vote up
/**
 * The given ComposedSchema, if it consists solely of "allOf" members, may be equivalent to a single leaf schema.
 * If so, returns the equivalent schema. Otherwise, returns <CODE>Optional.empty()</CODE>.
 */
@SuppressWarnings({ "rawtypes" })
private Optional<Schema> combinedAllOf( ComposedSchema schema)
  {
  return
    // Does this schema define only "allOf" members?
    schema.getAllOf().isEmpty() || !schema.getAnyOf().isEmpty() || !schema.getOneOf().isEmpty() || schema.getNot() != null?
    Optional.empty() :
    
    // Yes, does its consolidated "allOf" list consist of a single member?
    Optional.of( combinedAllOf( schema.getAllOf()))
    .filter( members -> members.size() == 1)

    // ...which is a leaf schema?
    .map( members -> members.get(0))
    .filter( SchemaUtils::isLeafSchema)

    // If so, return the equivalent combined leaf schema
    .map( member -> combineSchemas( getContext(), schema, member));
  }
 
Example #17
Source File: ResourcePatchRelationshipsTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
void isUpdatable() {
	final Schema relationshipsSchema = checkRelationshipsSchema(true);
	assertIterableEquals(singleton("resourceRelation"), relationshipsSchema.getProperties().keySet());

	Schema resourceRelationSchema = ((ObjectSchema) relationshipsSchema).getProperties().get("resourceRelation");
	assertNotNull(resourceRelationSchema);
	assertEquals(ObjectSchema.class, resourceRelationSchema.getClass());
	Map<String, Schema> resourceRelationProps = ((ObjectSchema) resourceRelationSchema).getProperties();
	assertIterableEquals(singleton("data"), resourceRelationProps.keySet());

	Schema dataSchema = resourceRelationProps.get("data");
	assertNotNull(dataSchema);
	assertEquals(ComposedSchema.class, dataSchema.getClass());
	List<Schema> dataOneOfSchema = ((ComposedSchema) dataSchema).getOneOf();
	assertNotNull(dataOneOfSchema);
	assertEquals(2, dataOneOfSchema.size());
	assertEquals("#/components/schemas/RelatedResourceTypeResourceReference", dataOneOfSchema.get(1).get$ref());
}
 
Example #18
Source File: ResourceSchemaTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
void schema() {
	Schema resourceSchema = new ResourceSchema(metaResource).schema();
	assertNotNull(resourceSchema);
	assertEquals(ComposedSchema.class, resourceSchema.getClass());
	assertIterableEquals(singletonList("attributes"), resourceSchema.getRequired());

	List<Schema> allOf = ((ComposedSchema) resourceSchema).getAllOf();
	assertNotNull(allOf);
	List<String> allOfItems = allOf.stream().map(Schema::get$ref).collect(toList());
	assertIterableEquals(Stream.of(
			"#/components/schemas/ResourceTypeResourceReference",
			"#/components/schemas/ResourceTypeResourceAttributes",
			"#/components/schemas/ResourceTypeResourceRelationships",
			"#/components/schemas/ResourceTypeResourceLinks"
	).collect(toList()), allOfItems);
}
 
Example #19
Source File: ResourcePostRelationshipsTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
void isInsertable() {
	final Schema relationshipsSchema = checkRelationshipsSchema(true);
	assertIterableEquals(singleton("resourceRelation"), relationshipsSchema.getProperties().keySet());

	Schema resourceRelationSchema = ((ObjectSchema) relationshipsSchema).getProperties().get("resourceRelation");
	assertNotNull(resourceRelationSchema);
	assertEquals(ObjectSchema.class, resourceRelationSchema.getClass());
	Map<String, Schema> resourceRelationProps = ((ObjectSchema) resourceRelationSchema).getProperties();
	assertIterableEquals(singleton("data"), resourceRelationProps.keySet());

	Schema dataSchema = resourceRelationProps.get("data");
	assertNotNull(dataSchema);
	assertEquals(ComposedSchema.class, dataSchema.getClass());
	List<Schema> dataOneOfSchema = ((ComposedSchema) dataSchema).getOneOf();
	assertNotNull(dataOneOfSchema);
	assertEquals(2, dataOneOfSchema.size());
	assertEquals("#/components/schemas/RelatedResourceTypeResourceReference", dataOneOfSchema.get(1).get$ref());
}
 
Example #20
Source File: OpenApiUtils.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Returns the given schema after resolving schemas referenced by any "allOf", "anyOf", or "oneOf" members.
 */
public static ComposedSchema resolveSchemaMembers( OpenAPI api, ComposedSchema composed)
  {
  // Resolve "allOf" schemas
  composed.setAllOf(
    Optional.ofNullable( composed.getAllOf()).orElse( emptyList())
    .stream()
    .map( member -> resolveSchema( api, member))
    .collect( toList()));
    
  // Resolve "anyOf" schemas
  composed.setAnyOf(
    Optional.ofNullable( composed.getAnyOf()).orElse( emptyList())
    .stream()
    .map( member -> resolveSchema( api, member))
    .collect( toList()));
    
  // Resolve "oneOf" schemas
  composed.setOneOf(
    Optional.ofNullable( composed.getOneOf()).orElse( emptyList())
    .stream()
    .map( member -> resolveSchema( api, member))
    .collect( toList()));

  return composed;
  }
 
Example #21
Source File: SchemaTransformer.java    From swagger-brake with Apache License 2.0 6 votes vote down vote up
private Schema transformComposedSchema(ComposedSchema swSchema) {
    Function<ComposedSchema, List<io.swagger.v3.oas.models.media.Schema>> schemaFunc;
    if (CollectionUtils.isNotEmpty(swSchema.getAllOf())) {
        schemaFunc = ComposedSchema::getAllOf;
    } else if (CollectionUtils.isNotEmpty(swSchema.getOneOf())) {
        schemaFunc = ComposedSchema::getOneOf;
    } else if (CollectionUtils.isNotEmpty(swSchema.getAnyOf())) {
        schemaFunc = ComposedSchema::getAnyOf;
    } else {
        throw new IllegalStateException("Composed schema is used that is not allOf, oneOf nor anyOf.");
    }
    List<SchemaAttribute> objectAttributes = schemaFunc.apply(swSchema)
        .stream()
        .map(this::transformSchema)
        .map(Schema::getSchemaAttributes)
        .flatMap(Collection::stream)
        .collect(toList());
    return new Schema.Builder(SchemaTypeUtil.OBJECT_TYPE).schemaAttributes(objectAttributes).build();
}
 
Example #22
Source File: TypeScriptAngularClientCodegenTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void testSchema() {
    TypeScriptAngularClientCodegen codegen = new TypeScriptAngularClientCodegen();

    ComposedSchema composedSchema = new ComposedSchema();

    Schema<Object> schema1 = new Schema<>();
    schema1.set$ref("SchemaOne");
    Schema<Object> schema2 = new Schema<>();
    schema2.set$ref("SchemaTwo");
    Schema<Object> schema3 = new Schema<>();
    schema3.set$ref("SchemaThree");

    composedSchema.addAnyOfItem(schema1);
    composedSchema.addAnyOfItem(schema2);
    composedSchema.addAnyOfItem(schema3);

    String schemaType = codegen.getSchemaType(composedSchema);
    Assert.assertEquals(schemaType, "SchemaOne | SchemaTwo | SchemaThree");
}
 
Example #23
Source File: JavaInheritanceTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Test(description = "convert a composed model with parent")
public void javaInheritanceTest() {
    final Schema parentModel = new Schema().name("Base");

    final Schema schema = new ComposedSchema()
            .addAllOfItem(new Schema().$ref("Base"))
            .name("composed");

    OpenAPI openAPI = TestUtils.createOpenAPI();
    openAPI.setComponents(new Components()
            .addSchemas(parentModel.getName(),parentModel)
            .addSchemas(schema.getName(), schema)
    );

    final JavaClientCodegen codegen = new JavaClientCodegen();
    codegen.setOpenAPI(openAPI);
    final CodegenModel cm = codegen.fromModel("sample", schema);

    Assert.assertEquals(cm.name, "sample");
    Assert.assertEquals(cm.classname, "Sample");
    Assert.assertEquals(cm.parent, "Base");
    Assert.assertEquals(cm.imports, Sets.newHashSet("Base"));
}
 
Example #24
Source File: SchemaResolver.java    From flow with Apache License 2.0 5 votes vote down vote up
Schema createNullableWrapper(Schema nestedTypeSchema) {
    if (nestedTypeSchema.get$ref() == null) {
        nestedTypeSchema.setNullable(true);
        return nestedTypeSchema;
    } else {
        ComposedSchema nullableSchema = new ComposedSchema();
        nullableSchema.setNullable(true);
        nullableSchema.setAllOf(Collections.singletonList(nestedTypeSchema));
        return nullableSchema;
    }
}
 
Example #25
Source File: SchemaBuilder.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns this ComposedSchema.
 */
private ComposedSchema asComposed()
  {
  return
    Optional.of( schema_)
    .filter( schema -> schema instanceof ComposedSchema)
    .map( schema -> (ComposedSchema) schema)
    .orElseThrow( () -> new IllegalStateException( "This is not a ComposedSchema"));
  }
 
Example #26
Source File: SchemaMatcher.java    From tcases with MIT License 5 votes vote down vote up
/**
 * If the given schema is a ComposedSchema, returns it. Otherwise, returns null.
 */
private ComposedSchema asComposedSchema( Schema schema)
  {
  return
    schema instanceof ComposedSchema
    ? (ComposedSchema) schema
    : null;
  }
 
Example #27
Source File: SchemaProcessor.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
private void changeDiscriminatorMapping(ComposedSchema composedSchema, String oldRef, String newRef) {
    Discriminator discriminator = composedSchema.getDiscriminator();
    if (!oldRef.equals(newRef) && discriminator != null) {
        String oldName = RefUtils.computeDefinitionName(oldRef);
        String newName = RefUtils.computeDefinitionName(newRef);

        String mappingName = null;
        if (discriminator.getMapping() != null) {
            for (String name : discriminator.getMapping().keySet()) {
                if (oldRef.equals(discriminator.getMapping().get(name))) {
                    mappingName = name;
                    break;
                }
            }
            if (mappingName != null) {
                discriminator.getMapping().put(mappingName, newRef);
            }
        }

        if (mappingName == null && !oldName.equals(newName)) {
            if (discriminator.getMapping() == null) {
                discriminator.setMapping(new HashMap());
            }
            discriminator.getMapping().put(oldName, newRef);
        }

    }
}
 
Example #28
Source File: InlineModelResolver.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
private void flattenComposedSchema(Schema inner, String key) {

        ComposedSchema composedSchema = (ComposedSchema) inner;
        String inlineModelName = "";

        List<Schema> list = null;
        if (composedSchema.getAllOf() != null) {
            list  = composedSchema.getAllOf();
            inlineModelName = "AllOf";
        }else if (composedSchema.getAnyOf() != null) {
            list  = composedSchema.getAnyOf();
            inlineModelName = "AnyOf";
        }else if (composedSchema.getOneOf() != null) {
            list  = composedSchema.getOneOf();
            inlineModelName = "OneOf";
        }

        for(int i= 0; i<list.size();i++){
            if (list.get(i).get$ref() == null){
                Schema inline = list.get(i);
                if (inline.getProperties()!= null){
                    flattenProperties(inline.getProperties(), key);
                }
                if (this.flattenComposedSchemas) {
                    int position = i+1;
                    inlineModelName = resolveModelName(inline.getTitle(),  key + inlineModelName + "_" + position);
                    list.set(i,new Schema().$ref(inlineModelName));
                    addGenerated(inlineModelName, inline);
                    openAPI.getComponents().addSchemas(inlineModelName, inline);
                }
            }
        }
    }
 
Example #29
Source File: SchemaBuilder.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Creates a new builder for a ComposedSchema with the given type.
 */
public static SchemaBuilder composed( String type)
  {
  ComposedSchema schema = new ComposedSchema();
  schema.setType( type);
  return new SchemaBuilder( schema);
  }
 
Example #30
Source File: SchemaUtils.java    From tcases with MIT License 5 votes vote down vote up
/**
 * If the given schema is a ComposedSchema instance, returns the casting result.
 * Otherwise, returns null.
 */
public static ComposedSchema asComposedSchema( Schema<?> schema)
  {
  return
    schema instanceof ComposedSchema
    ? (ComposedSchema) schema
    : null;
  }