Java Code Examples for io.swagger.v3.oas.models.media.Schema#setRequired()

The following examples show how to use io.swagger.v3.oas.models.media.Schema#setRequired() . 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: OpenApiObjectGenerator.java    From flow with Apache License 2.0 6 votes vote down vote up
private Schema createSingleSchema(String fullQualifiedName,
        TypeDeclaration<?> typeDeclaration) {
    Optional<String> description = typeDeclaration.getJavadoc()
            .map(javadoc -> javadoc.getDescription().toText());
    Schema schema = new ObjectSchema();
    schema.setName(fullQualifiedName);
    description.ifPresent(schema::setDescription);
    Map<String, Schema> properties = getPropertiesFromClassDeclaration(
            typeDeclaration);
    schema.properties(properties);
    List<String> requiredList = properties.entrySet().stream()
            .filter(stringSchemaEntry -> GeneratorUtils
                    .isNotTrue(stringSchemaEntry.getValue().getNullable()))
            .map(Map.Entry::getKey).collect(Collectors.toList());
    // Nullable is represented in requiredList instead.
    properties.values()
            .forEach(propertySchema -> propertySchema.nullable(null));
    schema.setRequired(requiredList);
    return schema;
}
 
Example 2
Source File: ComponentSchemaTransformer.java    From spring-openapi with MIT License 5 votes vote down vote up
private void updateRequiredFields(Schema schema, List<String> requiredFields) {
    if (requiredFields == null || requiredFields.isEmpty()) {
        return;
    }
    if (schema.getRequired() == null) {
        schema.setRequired(requiredFields);
        return;
    }
    schema.getRequired().addAll(requiredFields);
}
 
Example 3
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveInlineModelTestWithoutTitle() throws Exception {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setComponents(new Components());


    Schema objectSchema = new ObjectSchema();
    objectSchema.setDefault("default");
    objectSchema.setReadOnly(false);
    objectSchema.setDescription("description");
    objectSchema.setName("name");
    objectSchema.addProperties("street", new StringSchema());
    objectSchema.addProperties("city", new StringSchema());

    Schema schema =  new Schema();
    schema.setName("user");
    schema.setDescription("a common user");
    List<String> required = new ArrayList<>();
    required.add("address");
    schema.setRequired(required);
    schema.addProperties("name", new StringSchema());
    schema.addProperties("address", objectSchema);


    openAPI.getComponents().addSchemas("User", schema);

    new InlineModelResolver().flatten(openAPI);

    Schema user = openAPI.getComponents().getSchemas().get("User");

    assertNotNull(user);
    Schema address = (Schema)user.getProperties().get("address");
    assertTrue((address.get$ref()!= null));
    Schema userAddress = openAPI.getComponents().getSchemas().get("User_address");
    assertNotNull(userAddress);
    assertNotNull(userAddress.getProperties().get("city"));
    assertNotNull(userAddress.getProperties().get("street"));
}
 
Example 4
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void resolveInlineModelTestWithTitle() throws Exception {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setComponents(new Components());


    Schema objectSchema = new ObjectSchema();
    objectSchema.setTitle("UserAddressTitle");
    objectSchema.setDefault("default");
    objectSchema.setReadOnly(false);
    objectSchema.setDescription("description");
    objectSchema.setName("name");
    objectSchema.addProperties("street", new StringSchema());
    objectSchema.addProperties("city", new StringSchema());

    Schema schema =  new Schema();
    schema.setName("user");
    schema.setDescription("a common user");
    List<String> required = new ArrayList<>();
    required.add("address");
    schema.setRequired(required);
    schema.addProperties("name", new StringSchema());
    schema.addProperties("address", objectSchema);


    openAPI.getComponents().addSchemas("User", schema);

    new InlineModelResolver().flatten(openAPI);

    Schema user = openAPI.getComponents().getSchemas().get("User");

    assertNotNull(user);
    Schema address = (Schema)user.getProperties().get("address");
    assertTrue( address.get$ref() != null);

    Schema userAddressTitle = openAPI.getComponents().getSchemas().get("UserAddressTitle");
    assertNotNull(userAddressTitle);
    assertNotNull(userAddressTitle.getProperties().get("city"));
    assertNotNull(userAddressTitle.getProperties().get("street"));
}
 
Example 5
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testArbitraryObjectModelInline() {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setComponents(new Components());

    Schema userSchema = new Schema();
    userSchema.setName("user");
    userSchema.setDescription("a common user");
    userSchema.addProperties("name", new StringSchema());

    ObjectSchema objectSchema = new ObjectSchema();
    objectSchema.setTitle("title");
    objectSchema.setDefault("default");
    objectSchema.setReadOnly(false);
    objectSchema.setDescription("description");
    objectSchema.setName("name");

    userSchema.addProperties("arbitrary", objectSchema);
    List required = new ArrayList();
    required.add("arbitrary");
    userSchema.setRequired(required);


    openAPI.getComponents().addSchemas("User", userSchema);

    new InlineModelResolver().flatten(openAPI);

    Schema user = openAPI.getComponents().getSchemas().get("User");
    assertNotNull(user);
    Schema inlineProp = (Schema) user.getProperties().get("arbitrary");
    assertTrue(inlineProp instanceof ObjectSchema);
    assertNull(inlineProp.getProperties());
}
 
Example 6
Source File: OASMergeUtil.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
public static Schema mergeSchema(Schema thisSchema, Schema thatSchema) {
  if (thatSchema == null) {
    return thisSchema;
  }
  // Overwriting `implementation` is explicitly disallowed
  // Overwriting `not` is explicitly disallowed
  // Overwriting `oneOf` is explicitly disallowed
  // Overwriting `anyOf` is explicitly disallowed
  // Overwriting `allOf` is explicitly disallowed
  // Overwriting `name` is explicitly disallowed
  if (thatSchema.getTitle() != null) {
    thisSchema.setTitle(thatSchema.getTitle());
  }
  // Overwriting `multipleOf` is explicitly disallowed
  if (thatSchema.getMaximum() != null) {
    thisSchema.setMaximum(thatSchema.getMaximum());
  }
  if (thatSchema.getExclusiveMaximum() != null) {
    thisSchema.setExclusiveMaximum(thatSchema.getExclusiveMaximum());
  }

  if (thatSchema.getMinimum() != null) {
    thisSchema.setMinimum(thatSchema.getMinimum());
  }
  if (thatSchema.getExclusiveMinimum() != null) {
    thisSchema.setExclusiveMinimum(thatSchema.getExclusiveMinimum());
  }
  if (thatSchema.getMaxLength() != null) {
    thisSchema.setMaxLength(thatSchema.getMaxLength());
  }
  if (thatSchema.getMinLength() != null) {
    thisSchema.setMinLength(thatSchema.getMinLength());
  }
  if (thatSchema.getPattern() != null) {
    thisSchema.setPattern(thatSchema.getPattern());
  }
  if (thatSchema.getMaxProperties() != null) {
    thisSchema.setMaxProperties(thatSchema.getMaxProperties());
  }
  if (thatSchema.getMinProperties() != null) {
    thisSchema.setMinProperties(thatSchema.getMinProperties());
  }
  // RequiredProperties
  if (thatSchema.getRequired() != null) {
    thisSchema.setRequired(thatSchema.getRequired());
  }
  // Overwriting `name` is explicitly disallowed
  if (thatSchema.getDescription() != null) {
    thisSchema.setDescription(thatSchema.getDescription());
  }
  if (thatSchema.getFormat() != null) {
    thisSchema.setFormat(thatSchema.getFormat());
  }
  // Overwriting `ref` is explicitly disallowed
  if (thatSchema.getNullable() != null) {
    thisSchema.setNullable(thatSchema.getNullable());
  }
  // Overwriting `AccessMode` is explicitly disallowed
  if (thatSchema.getExample() != null) {
    thisSchema.setExample(thatSchema.getExample());
  }
  if (thatSchema.getExternalDocs() != null) {
    thisSchema.setExternalDocs(thatSchema.getExternalDocs());
  }
  if (thatSchema.getDeprecated() != null) {
    thisSchema.setDeprecated(thatSchema.getDeprecated());
  }
  if (thatSchema.getType() != null) {
    thisSchema.setType(thatSchema.getType());
  }
  if (thatSchema.getEnum() != null) {
    thisSchema.setEnum(thatSchema.getEnum());
  }
  if (thatSchema.getDefault() != null) {
    thisSchema.setDefault(thatSchema.getDefault());
  }
  // Overwriting `discriminator` is explicitly disallowed
  // Overwriting `hidden` is explicitly disallowed
  // Overwriting `subTypes` is explicitly disallowed
  if (thatSchema.getExtensions() != null) {
    thisSchema.setExtensions(thatSchema.getExtensions());
  }
  return thisSchema;
}
 
Example 7
Source File: InputModeller.java    From tcases with MIT License 4 votes vote down vote up
/**
 * Returns the {@link IVarDef input variable} representing the values for an object instance.
 */
@SuppressWarnings("rawtypes")
private IVarDef objectValueVar( String instanceVarTag, Schema<?> instanceSchema, boolean instanceItem)
  {
  // Ensure schema defined for all required properties, using a default empty schema if necessary.
  Map<String,Schema> propertyDefs = Optional.ofNullable( instanceSchema.getProperties()).orElse( new LinkedHashMap<String,Schema>());
  Optional.ofNullable( instanceSchema.getRequired())
    .map( required -> required.stream().filter( property -> !propertyDefs.containsKey( property)).collect( toList()))
    .filter( undefined -> !undefined.isEmpty())
    .ifPresent( undefined -> {
      undefined.stream().forEach( required -> propertyDefs.put( required, emptySchema()));
      instanceSchema.setProperties( propertyDefs);
      });

  // Reconcile any "required" constraints for read/WriteOnly properties.
  instanceSchema.setRequired(
    Optional.ofNullable( instanceSchema.getRequired()).orElse( emptyList())
    .stream()
    .filter( property -> expectedInView( propertyDefs.get( property)))
    .collect( toList()));

  // Accumulate constraints on the number of properties expected.
  PropertyCountConstraints constraints = new PropertyCountConstraints();
  constraints.setRequiredCount( Optional.ofNullable( instanceSchema.getRequired()).orElse( emptyList()).size());
  constraints.setTotalCount( objectTotalProperties( instanceSchema));

  constraints.setHasAdditional(
    // additionalProperties keyword is not false...
    Optional.ofNullable( instanceSchema.getAdditionalProperties())
    .map( additional -> additional.getClass().equals( Boolean.class)? (Boolean) additional : true)
    .orElse( true)
    &&
    // maxProperties not already satisfied by required properties
    Optional.ofNullable( instanceSchema.getMaxProperties())
    .map( max -> max > constraints.getRequiredCount())
    .orElse( true));

  // Ensure min/max range is feasible
  instanceSchema.setMinProperties(
    Optional.ofNullable( instanceSchema.getMinProperties())
    .map( min -> Optional.ofNullable( instanceSchema.getMaxProperties()).map( max -> adjustedMinOf( "Properties", min, max)).orElse( min))
    .orElse( null));

  // Ensure minimum is a usable constraint
  instanceSchema.setMinProperties(
    Optional.ofNullable( instanceSchema.getMinProperties())
    .filter( min -> isUsablePropertyLimit( "minProperties", min, constraints))
    .orElse( null));

  // Ensure maximum is a usable constraint
  instanceSchema.setMaxProperties(
    Optional.ofNullable( instanceSchema.getMaxProperties())
    .filter( max -> isUsablePropertyMax( "maxProperties", max, constraints))
    .orElse( null));

  // Are additional properties are required to satisfy the minimum?
  Integer minProperties = instanceSchema.getMinProperties();
  constraints.setRequiresAdditional(
    Optional.ofNullable( minProperties)
    .map( min -> min > constraints.getTotalCount() && constraints.hasAdditional())
    .orElse( false));

  // Are all properties effectively required to satisfy the minimum?
  constraints.setAllRequired(
    Optional.ofNullable( minProperties)
    .map( min -> min == constraints.getTotalCount() && !constraints.hasAdditional())
    .orElse( false));

  return
    VarSetBuilder.with( "Value")
    .when( has( instanceValueProperty( instanceVarTag)))
    .members( iterableOf( objectPropertyCountVar( instanceVarTag, instanceSchema, constraints)))
    .members( objectPropertiesVar( instanceVarTag, instanceSchema, constraints))
    .build();
  }
 
Example 8
Source File: OpenApiObjectGenerator.java    From flow with Apache License 2.0 4 votes vote down vote up
private RequestBody createRequestBody(MethodDeclaration methodDeclaration) {
    Map<String, String> paramsDescription = new HashMap<>();
    methodDeclaration.getJavadoc().ifPresent(javadoc -> {
        for (JavadocBlockTag blockTag : javadoc.getBlockTags()) {
            if (blockTag.getType() == JavadocBlockTag.Type.PARAM) {
                paramsDescription.put(blockTag.getName().orElse(""),
                        blockTag.getContent().toText());
            }
        }
    });

    RequestBody requestBody = new RequestBody();
    Content requestBodyContent = new Content();
    requestBody.content(requestBodyContent);
    MediaType requestBodyObject = new MediaType();
    requestBodyContent.addMediaType("application/json", requestBodyObject);
    Schema requestSchema = new ObjectSchema();
    requestSchema.setRequired(new ArrayList<>());
    requestBodyObject.schema(requestSchema);
    methodDeclaration.getParameters().forEach(parameter -> {
        Schema paramSchema = parseTypeToSchema(parameter.getType(), "");
        usedTypes.putAll(collectUsedTypesFromSchema(paramSchema));
        String name = (isReservedWord(parameter.getNameAsString()) ? "_"
                : "").concat(parameter.getNameAsString());
        if (GeneratorUtils.isBlank(paramSchema.get$ref())) {
            paramSchema.description(
                    paramsDescription.remove(parameter.getNameAsString()));
        }
        requestSchema.addProperties(name, paramSchema);
        if (GeneratorUtils.isNotTrue(paramSchema.getNullable())
                && !parameter.isAnnotationPresent(Nullable.class)) {
            requestSchema.addRequiredItem(name);
        }
        paramSchema.setNullable(null);
    });
    if (!paramsDescription.isEmpty()) {
        requestSchema.addExtension(
                EXTENSION_VAADIN_CONNECT_PARAMETERS_DESCRIPTION,
                new LinkedHashMap<>(paramsDescription));
    }
    return requestBody;
}
 
Example 9
Source File: InlineModelResolver.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
public Schema createModelFromProperty(Schema schema, String path) {
    String description = schema.getDescription();
    String example = null;
    List<String> requiredList = schema.getRequired();


    Object obj = schema.getExample();
    if (obj != null) {
        example = obj.toString();
    }
    String name = schema.getName();
    XML xml = schema.getXml();
    Map<String, Schema> properties = schema.getProperties();


    if (schema instanceof ComposedSchema && this.flattenComposedSchemas){
        ComposedSchema composedModel = (ComposedSchema) schema;

        composedModel.setDescription(description);
        composedModel.setExample(example);
        composedModel.setName(name);
        composedModel.setXml(xml);
        composedModel.setType(schema.getType());
        composedModel.setRequired(requiredList);

        return composedModel;


    } else {
        Schema model = new Schema();//TODO Verify this!
        model.setDescription(description);
        model.setExample(example);
        model.setName(name);
        model.setXml(xml);
        model.setType(schema.getType());
        model.setRequired(requiredList);

        if (properties != null) {
            flattenProperties(properties, path);
            model.setProperties(properties);
        }

        return model;
    }
}
 
Example 10
Source File: ExternalRefProcessorTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
  public void testNestedExternalRefs(@Injectable final Schema mockedModel){
  	final RefFormat refFormat = RefFormat.URL;

  	//Swagger test instance
  	OpenAPI testedOpenAPI = new OpenAPI();

  	//Start with customer, add address property to it
  	final String customerURL = "http://my.company.com/path/to/customer.json#/definitions/Customer";

  	final Schema customerModel = new Schema();
  	Map<String,Schema> custProps = new HashMap<>();
  	Schema address = new Schema();
  	final String addressURL = "http://my.company.com/path/to/address.json#/definitions/Address";
  	address.set$ref(addressURL);
  	custProps.put("Address", address);

  	//Create a 'local' reference to something in #/definitions, this should be ignored a no longer result in a null pointer exception
  	final String loyaltyURL = "#/definitions/LoyaltyScheme";

  	Schema loyaltyProp = new Schema();
  	loyaltyProp.set$ref(loyaltyURL);
  	loyaltyProp.setName("LoyaltyCardNumber");
  	List<String> required = new ArrayList<>();
  	required.add("LoyaltyCardNumber");
  	loyaltyProp.setRequired(required);

  	custProps.put("Loyalty", loyaltyProp);
  	customerModel.setProperties(custProps);

  	//create address model, add Contact Ref Property to it
  	final Schema addressModel = new Schema();
  	Map<String, Schema> addressProps = new HashMap<>();
  	Schema contact = new Schema();
  	final String contactURL = "http://my.company.com/path/to/Contact.json#/definitions/Contact";
  	contact.set$ref(contactURL);
  	addressProps.put("Contact", contact);
  	addressModel.setProperties(addressProps);


  	//Create contact model, with basic type property
  	final Schema contactModel = new Schema();
  	Schema contactProp = new StringSchema();
  	contactProp.setName("PhoneNumber");
List<String> requiredList = new ArrayList<>();
requiredList.add("PhoneNumber");
  	contactProp.setRequired(requiredList);
  	Map<String, Schema> contactProps = new HashMap<>();
  	contactProps.put("PhoneNumber", contactProp);
  	contactModel.setProperties(contactProps);

  	new Expectations(){{
  		cache.loadRef(customerURL, refFormat, Schema.class);
  		result = customerModel;
  		times = 1;

  		cache.loadRef(addressURL, refFormat, Schema.class);
  		result = addressModel;
  		times = 1;

  		cache.loadRef(contactURL, refFormat, Schema.class);
  		result = contactModel;
  		times = 1;
	}};

new ExternalRefProcessor(cache, testedOpenAPI).processRefToExternalSchema(customerURL, refFormat);

assertThat(testedOpenAPI.getComponents().getSchemas().get("Customer"), notNullValue());
assertThat(testedOpenAPI.getComponents().getSchemas().get("Contact"), notNullValue());
assertThat(testedOpenAPI.getComponents().getSchemas().get("Address"), notNullValue());
  }
 
Example 11
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void resolveInlineModel2EqualInnerModels() throws Exception {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setComponents(new Components());


    Schema objectSchema = new ObjectSchema();
    objectSchema.setTitle("UserAddressTitle");
    objectSchema.setDefault("default");
    objectSchema.setReadOnly(false);
    objectSchema.setDescription("description");
    objectSchema.setName("name");
    objectSchema.addProperties("street", new StringSchema());
    objectSchema.addProperties("city", new StringSchema());

    Schema schema =  new Schema();
    schema.setName("user");
    schema.setDescription("a common user");
    List<String> required = new ArrayList<>();
    required.add("address");
    schema.setRequired(required);
    schema.addProperties("name", new StringSchema());
    schema.addProperties("address", objectSchema);


    openAPI.getComponents().addSchemas("User", schema);

    Schema addressSchema = new ObjectSchema();
    addressSchema.setTitle("UserAddressTitle");
    addressSchema.setDefault("default");
    addressSchema.setReadOnly(false);
    addressSchema.setDescription("description");
    addressSchema.setName("name");
    addressSchema.addProperties("street", new StringSchema());
    addressSchema.addProperties("city", new StringSchema());

    Schema anotherSchema =  new Schema();
    anotherSchema.setName("user");
    anotherSchema.setDescription("a common user");
    List<String> requiredFields = new ArrayList<>();
    requiredFields.add("address");
    anotherSchema.setRequired(requiredFields);
    anotherSchema.addProperties("name", new StringSchema());
    anotherSchema.addProperties("lastName", new StringSchema());
    anotherSchema.addProperties("address", addressSchema);

    openAPI.getComponents().addSchemas("AnotherUser", anotherSchema);

    new InlineModelResolver().flatten(openAPI);

    Schema user = openAPI.getComponents().getSchemas().get("User");

    assertNotNull(user);
    Schema addressSchema1 = (Schema) user.getProperties().get("address");
    assertTrue(addressSchema1.get$ref() != null);

    Schema address = openAPI.getComponents().getSchemas().get("UserAddressTitle");
    assertNotNull(address);
    assertNotNull(address.getProperties().get("city"));
    assertNotNull(address.getProperties().get("street"));
    Schema duplicateAddress = openAPI.getComponents().getSchemas().get("UserAddressTitle_0");
    assertNull(duplicateAddress);
}
 
Example 12
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void resolveInlineModel2DifferentInnerModelsWIthSameTitle() throws Exception {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setComponents(new Components());

    Schema objectSchema = new ObjectSchema();
    objectSchema.setTitle("UserAddressTitle");
    objectSchema.setDefault("default");
    objectSchema.setReadOnly(false);
    objectSchema.setDescription("description");
    objectSchema.setName("name");
    objectSchema.addProperties("street", new StringSchema());
    objectSchema.addProperties("city", new StringSchema());

    Schema schema =  new Schema();
    schema.setName("user");
    schema.setDescription("a common user");
    List<String> required = new ArrayList<>();
    required.add("address");
    schema.setRequired(required);
    schema.addProperties("name", new StringSchema());
    schema.addProperties("address", objectSchema);


    openAPI.getComponents().addSchemas("User", schema);

    Schema addressSchema = new ObjectSchema();
    addressSchema.setTitle("UserAddressTitle");
    addressSchema.setDefault("default");
    addressSchema.setReadOnly(false);
    addressSchema.setDescription("description");
    addressSchema.setName("name");
    addressSchema.addProperties("street", new StringSchema());
    addressSchema.addProperties("city", new StringSchema());
    addressSchema.addProperties("apartment", new StringSchema());


    Schema anotherSchema =  new Schema();
    anotherSchema.setName("AnotherUser");
    anotherSchema.setDescription("a common user");
    List<String> requiredFields = new ArrayList<>();
    requiredFields.add("address");
    anotherSchema.setRequired(requiredFields);
    anotherSchema.addProperties("name", new StringSchema());
    anotherSchema.addProperties("lastName", new StringSchema());
    anotherSchema.addProperties("address", addressSchema);


    openAPI.getComponents().addSchemas("AnotherUser", anotherSchema);

    new InlineModelResolver().flatten(openAPI);

    Schema user = openAPI.getComponents().getSchemas().get("User");

    assertNotNull(user);
    Schema userAddress = (Schema) user.getProperties().get("address");
    assertTrue( userAddress.get$ref()!= null);

    Schema address = openAPI.getComponents().getSchemas().get("UserAddressTitle");
    assertNotNull(address);
    assertNotNull(address.getProperties().get("city"));
    assertNotNull(address.getProperties().get("street"));
    Schema duplicateAddress = openAPI.getComponents().getSchemas().get("UserAddressTitle_1");
    assertNotNull(duplicateAddress);
    assertNotNull(duplicateAddress.getProperties().get("city"));
    assertNotNull(duplicateAddress.getProperties().get("street"));
    assertNotNull(duplicateAddress.getProperties().get("apartment"));
}