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

The following examples show how to use io.swagger.v3.oas.models.media.Schema. 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
Source Project: openapi-diff   Source File: SchemaDiffResult.java    License: 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 2
Source Project: swagger-inflector   Source File: ExtensionsUtilTest.java    License: 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 3
@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 4
Source Project: swagger-parser   Source File: InlineModelResolverTest.java    License: 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 5
Source Project: crnk-framework   Source File: PostResourceDataTest.java    License: 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 6
/**
 * 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 7
Source Project: openapi-generator   Source File: RubyClientCodegen.java    License: 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 8
Source Project: swagger-inflector   Source File: ExampleBuilderTest.java    License: 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 9
Source Project: swagger-parser   Source File: OpenAPIV3ParserTest.java    License: 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 10
Source Project: openapi-generator   Source File: AbstractJavaCodegen.java    License: 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 11
Source Project: openapi-generator   Source File: PhpSilexServerCodegen.java    License: 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 Project: spring-openapi   Source File: OpenApiClientGenerator.java    License: 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 Project: flow   Source File: AbstractEndpointGenerationTest.java    License: 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 Project: swagger-parser   Source File: OpenAPIDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
public Map<String, Schema> getSchemas(ObjectNode obj, String location, ParseResult result, boolean underComponents) {
    if (obj == null) {
        return null;
    }
    Map<String, Schema> schemas = new LinkedHashMap<>();

    Set<String> schemaKeys = getKeys(obj);
    for (String schemaName : schemaKeys) {
        if(underComponents) {
            if (!Pattern.matches("^[a-zA-Z0-9\\.\\-_]+$",
                    schemaName)) {
                result.warning(location, "Schema name " + schemaName + " doesn't adhere to regular expression ^[a-zA-Z0-9\\.\\-_]+$");
            }
        }
        JsonNode schemaValue = obj.get(schemaName);
            if (!schemaValue.getNodeType().equals(JsonNodeType.OBJECT)) {
                result.invalidType(location, schemaName, "object", schemaValue);
            } else {
                ObjectNode schema = (ObjectNode) schemaValue;
                Schema schemaObj = getSchema(schema, String.format("%s.%s", location, schemaName), result);
                if(schemaObj != null) {
                    schemas.put(schemaName, schemaObj);
                }
            }
    }

    return schemas;
}
 
Example 15
Source Project: tcases   Source File: InputModeller.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the enumerated number values defined by the given schema.
 */
private Set<BigDecimal> getNumberEnum( Schema<?> schema)
  {
  return
    schema instanceof NumberSchema
    ? asOrderedSet( ((NumberSchema) schema).getEnum())
    : getNumberEnum( schema.getEnum());
  }
 
Example 16
Source Project: openapi-generator   Source File: AbstractPhpCodegen.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return the default value of the property
 * @param p OpenAPI property object
 * @return string presentation of the default value of the property
 */
@Override
public String toDefaultValue(Schema p) {
    if (ModelUtils.isBooleanSchema(p)) {
        if (p.getDefault() != null) {
            return p.getDefault().toString();
        }
    } else if (ModelUtils.isDateSchema(p)) {
        // TODO
    } else if (ModelUtils.isDateTimeSchema(p)) {
        // TODO
    } else if (ModelUtils.isNumberSchema(p)) {
        if (p.getDefault() != null) {
            return p.getDefault().toString();
        }
    } else if (ModelUtils.isIntegerSchema(p)) {
        if (p.getDefault() != null) {
            return p.getDefault().toString();
        }
    } else if (ModelUtils.isStringSchema(p)) {
        if (p.getDefault() != null) {
            return "'" + p.getDefault() + "'";
        }
    }

    return null;
}
 
Example 17
Source Project: flow   Source File: OpenApiObjectGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private List<Schema> createSchemasFromQualifiedNameAndType(
        String qualifiedName, ResolvedReferenceType resolvedReferenceType) {
    List<Schema> list = parseNonEndpointClassAsSchema(qualifiedName);
    if (list.isEmpty()) {
        return parseReferencedTypeAsSchema(resolvedReferenceType);
    } else {
        return list;
    }
}
 
Example 18
Source Project: tcases   Source File: InputModeller.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the type-specific {@link IVarDef input variables} defined by the given alternative schemas for the given instance.
 */
private Stream<IVarDef> alternativeSchemaVars( String instanceVarTag, boolean instanceOptional, List<Schema<?>> alternatives, boolean instanceItem)
  {
  return
    Stream.of(
      combinedAlternativesVar(
        VarSetBuilder.with( "Alternative")
        .members(
          VarDefBuilder.with( "Used")
          .values(
            IntStream.range( 0, alternatives.size())
            .mapToObj(
              i ->
              VarValueDefBuilder.with( String.valueOf( i))
              .properties( alternativeProperty( instanceVarTag, i))
              .build()))
          .build())

        .members(
          IntStream.range( 0, alternatives.size())
          .mapToObj(
            i->
            VarSetBuilder.with( String.valueOf( i))
            .when( has( alternativeProperty( instanceVarTag, i)))
            .members( typeSchemaVars( instanceVarTag, instanceOptional, alternatives.get(i), instanceItem))
            .build()))
      
        .build()));
  }
 
Example 19
Source Project: tcases   Source File: InputModeller.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the type-specific {@link IVarDef input variables} defined by the schema for the given instance.
 */
private Stream<IVarDef> typeSchemaVars( String instanceType, String instanceVarTag, boolean instanceOptional, Schema<?> instanceSchema, boolean instanceItem)
  {
  Stream.Builder<IVarDef> typeVars = Stream.builder();

  typeVars.add( instanceTypeVar( instanceVarTag, instanceOptional, instanceSchema, instanceItem));
  if( instanceType != null)
    {
    typeVars.add( typeValueVar( instanceType, instanceVarTag, instanceSchema, instanceItem));
    }

  return typeVars.build();
  }
 
Example 20
Source Project: swagger-parser   Source File: InlineModelResolver.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This function fix models that are string (mostly enum). Before this fix, the example
 * would look something like that in the doc: "\"example from def\""
 * @param m Model implementation
 */
private void fixStringModel(Schema m) {
    if (m.getType() != null && m.getType().equals("string") && m.getExample() != null) {
        String example = m.getExample().toString();
        if (example.substring(0, 1).equals("\"") &&
                example.substring(example.length() - 1).equals("\"")) {
            m.setExample(example.substring(1, example.length() - 1));
        }
    }
}
 
Example 21
@Test
void response() {
  ApiResponse apiResponse = new ResourceReferencesResponse(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/ResourceTypeResourceReferencesResponseSchema",
      schema.get$ref()
  );
}
 
Example 22
Source Project: tcases   Source File: InputModeller.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the {@link IVarDef input variable definitions} for the given media type content.
 */
private Stream<IVarDef> mediaTypeContentVars( OpenAPI api, String contentVarTag, Map<String,MediaType> mediaTypes)
  {
  return
    mediaTypes.entrySet().stream()
    .map(
      contentDef ->
      {
      String mediaType = contentDef.getKey();

      return
        resultFor( mediaType,
          () ->
          {
          String mediaTypeVarName = mediaTypeVarName( mediaType);
          String mediaTypeVarTag = mediaTypeVarTag( contentVarTag, mediaType);
          
          VarSetBuilder contentVar =
            VarSetBuilder.with( mediaTypeVarName)
            .when( has( mediaTypeVarTag));

          // Schema defined for this media type?
          Schema<?> mediaTypeSchema = contentDef.getValue().getSchema();
          if( mediaTypeSchema == null)
            {
            // No, use perfunctory "must be defined" input model for contents
            notifyWarning( String.format( "No schema defined for media type=%s", mediaType));
            contentVar.members( instanceDefinedVar( mediaTypeVarTag, false));
            }
          else
            {
            // Yes, use schema input model for contents
            contentVar.members( instanceSchemaVars( mediaTypeVarTag, false, analyzeSchema( api, mediaTypeSchema)));
            }

          return contentVar.build();
          });
      });
  }
 
Example 23
Source Project: tcases   Source File: SchemaExtensions.java    License: MIT License 5 votes vote down vote up
/**
 * Adds to the composed set of properties that must not be required when validating the given object schema.
 */
public static void addNotRequired( Schema<?> schema, Iterable<String> notRequired)
  {
  if( notRequired != null)
    {
    for( String property : notRequired)
      {
      addNotRequired( schema, property);
      }
    }
  }
 
Example 24
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);
}
 
Example 25
Source Project: swagger-inflector   Source File: ExampleBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue126Inline() throws Exception {
    String schema =
        "{\n" +
        "  \"type\": \"object\",\n" +
        "  \"properties\": {\n" +
        "    \"id\": {\n" +
        "      \"type\": \"integer\",\n" +
        "      \"format\": \"int32\",\n" +
        "      \"example\": 999\n" +
        "    },\n" +
        "    \"inline\": {\n" +
        "      \"type\": \"object\",\n" +
        "      \"properties\": {\n" +
        "        \"first\": {\n" +
        "          \"type\": \"string\"\n" +
        "        },\n" +
        "        \"last\": {\n" +
        "          \"type\": \"string\"\n" +
        "        }\n" +
        "      }\n" +
        "    }\n" +
        "  }\n" +
        "}";
    Schema model = Json.mapper().readValue(schema, Schema.class);

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

    Example rep = ExampleBuilder.fromSchema(new Schema().$ref("InlineModel"), definitions);

    assertEqualsIgnoreLineEnding(Json.pretty(rep), "{\n" +
        "  \"id\" : 999,\n" +
        "  \"inline\" : {\n" +
        "    \"first\" : \"string\",\n" +
        "    \"last\" : \"string\"\n" +
        "  }\n" +
        "}");
}
 
Example 26
Source Project: crnk-framework   Source File: Pagination.java    License: Apache License 2.0 5 votes vote down vote up
public Schema schema() {
  return new ObjectSchema()
      .addProperties(
          "first",
          new StringSchema()
              .description("The first page of data")
              .format("uri")
              .nullable(true))
      .addProperties(
          "last",
          new StringSchema()
              .description("The last page of data")
              .format("uri")
              .nullable(true))
      .addProperties(
          "prev",
          new StringSchema()
              .description("The previous page of data")
              .format("uri")
              .nullable(true))
      .addProperties(
          "next",
          new StringSchema()
              .description("The next page of data")
              .format("uri")
              .nullable(true));
}
 
Example 27
Source Project: tcases   Source File: CombineStringSchemaTest.java    License: MIT License 5 votes vote down vote up
/**
 * Tests {@link SchemaUtils#combineStringSchemas combineStringSchemas()} using the following inputs.
 * <P>
 * <TABLE border="1" cellpadding="8">
 * <TR align="left"><TH colspan=2> 7. Combine (<FONT color="red">Failure</FONT>) </TH></TR>
 * <TR align="left"><TH> Input Choice </TH> <TH> Value </TH></TR>
 * <TR><TD> base.format </TD> <TD> Non-null </TD> </TR>
 * <TR><TD> base.enum </TD> <TD> Non-null </TD> </TR>
 * <TR><TD> base.maxLength </TD> <TD> Non-null </TD> </TR>
 * <TR><TD> base.minLength </TD> <TD> Non-null </TD> </TR>
 * <TR><TD> base.pattern </TD> <TD> null </TD> </TR>
 * <TR><TD> additional.format </TD> <TD> null </TD> </TR>
 * <TR><TD> additional.enum </TD> <TD> <FONT color="red"> Disjoint from base  </FONT> </TD> </TR>
 * <TR><TD> additional.maxLength </TD> <TD> null </TD> </TR>
 * <TR><TD> additional.minLength </TD> <TD> > base </TD> </TR>
 * <TR><TD> additional.pattern </TD> <TD> Non-null </TD> </TR>
 * </TABLE>
 * </P>
 */
@Test
public void Combine_7()
  {
  // Given...
  Schema<?> base =
    SchemaBuilder.ofType( "string")
    .format( "password")
    .enums( "Alpha", "Bravo", "Charlie")
    .maxLength( 128)
    .minLength( 127)
    .patterns()
    .build();

  Schema<?> additional =
    SchemaBuilder.ofType( "string")
    .format( null)
    .enums( "Delta", "Easy", "Foxtrot")
    .maxLength( null)
    .minLength( 128)
    .patterns( "[A-Z]*")
    .build();

  OpenApiContext context = new OpenApiContext();
  
  expectFailure( IllegalStateException.class)
    .when( () -> combineSchemas( context, base, additional))
    .then( failure -> {
      assertThat(
        "Failure",
        failure.getMessage(),
        is( "Can't combine schema requiring {enum: [Delta, Easy, Foxtrot]} with schema requiring {enum: [Alpha, Bravo, Charlie]}"));
      });
  }
 
Example 28
Source Project: tcases   Source File: SchemaAnalyzer.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the disjunctive normal form of the given schema.
 */
private Dnf toDnf( Schema<?> schema, Set<String> validTypes)
  {
  return
    allOf(
      withSubSchemas( schema),

      getNotDnf( schema, validTypes),

      resultFor(
        "allOf",
        () ->
        withWarningIf(
          allOf( getAllOfDnfs( schema, validTypes)),
          Dnf::unsatisfiable,
          "This combination of schemas can't be satisfied")),

      resultFor(
        "oneOf",
        () ->
        withWarningIf(
          oneOf( getOneOfDnfs( schema, validTypes)),
          Dnf::unsatisfiable,
          "This combination of schemas can't be satisfied")),

      resultFor(
        "anyOf",
        () ->
        withWarningIf(
          anyOf( getAnyOfDnfs( schema, validTypes)),
          Dnf::unsatisfiable,
          "This combination of schemas can't be satisfied")));
  }
 
Example 29
Source Project: openapi-generator   Source File: ExampleGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private List<Map<String, String>> generateFromResponseSchema(Schema responseSchema, Set<String> producesInfo) {
    if (responseSchema.getExample() == null && StringUtils.isEmpty(responseSchema.get$ref()) && !ModelUtils.isArraySchema(responseSchema)) {
        // no example provided
        return null;
    }

    if (responseSchema.getExample() != null && !(responseSchema.getExample() instanceof Map)) {
        return generate(responseSchema.getExample(), new ArrayList<>(producesInfo));
    }

    if (ModelUtils.isArraySchema(responseSchema)) { // array of schema
        ArraySchema as = (ArraySchema) responseSchema;
        if (as.getItems() != null && StringUtils.isEmpty(as.getItems().get$ref())) { // arary of primtive types
            return generate((Map<String, Object>) responseSchema.getExample(),
                    new ArrayList<String>(producesInfo), as.getItems());
        } else if (as.getItems() != null && !StringUtils.isEmpty(as.getItems().get$ref())) { // array of model
            return generate((Map<String, Object>) responseSchema.getExample(),
                    new ArrayList<String>(producesInfo), ModelUtils.getSimpleRef(as.getItems().get$ref()));
        } else {
            // TODO log warning message as such case is not handled at the moment
            return null;
        }
    } else if (StringUtils.isEmpty(responseSchema.get$ref())) { // primtiive type (e.g. integer, string)
        return generate((Map<String, Object>) responseSchema.getExample(),
                new ArrayList<String>(producesInfo), responseSchema);
    } else { // model
        return generate((Map<String, Object>) responseSchema.getExample(),
                new ArrayList<String>(producesInfo), ModelUtils.getSimpleRef(responseSchema.get$ref()));
    }
}
 
Example 30
/**
 * Resolve schema from type schema.
 *
 * @param schemaImplementation the schema implementation
 * @param components the components
 * @param jsonView the json view
 * @param annotations the annotations
 * @return the schema
 */
public static Schema resolveSchemaFromType(Class<?> schemaImplementation, Components components,
		JsonView jsonView, Annotation[] annotations) {
	Schema schemaObject = extractSchema(components, schemaImplementation, jsonView, annotations);
	if (schemaObject != null && StringUtils.isBlank(schemaObject.get$ref())
			&& StringUtils.isBlank(schemaObject.getType()) && !(schemaObject instanceof ComposedSchema)) {
		// default to string
		schemaObject.setType("string");
	}
	return schemaObject;
}