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

The following examples show how to use io.swagger.v3.oas.models.media.Schema#setProperties() . 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: ComponentSchemaTransformer.java    From spring-openapi with MIT License 6 votes vote down vote up
public Schema transformSimpleSchema(Class<?> clazz, Map<String, InheritanceInfo> inheritanceMap) {
      if (clazz.isEnum()) {
          return schemaGeneratorHelper.createEnumSchema(clazz.getEnumConstants());
      }
      List<String> requiredFields = new ArrayList<>();

      Schema<?> schema = new Schema<>();
      schema.setType("object");
      schema.setProperties(getClassProperties(clazz, requiredFields));
schemaGeneratorHelper.enrichWithTypeAnnotations(schema, clazz.getDeclaredAnnotations());

      updateRequiredFields(schema, requiredFields);

      if (inheritanceMap.containsKey(clazz.getName())) {
          Discriminator discriminator = createDiscriminator(inheritanceMap.get(clazz.getName()));
          schema.setDiscriminator(discriminator);
          enrichWithDiscriminatorProperty(schema, discriminator);
      }
      if (clazz.getSuperclass() != null) {
          return traverseAndAddProperties(schema, inheritanceMap, clazz.getSuperclass(), clazz);
      }
      return schema;
  }
 
Example 2
Source File: OpenAPIBuilder.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Resolve properties schema.
 *
 * @param schema the schema
 * @param propertyResolverUtils the property resolver utils
 * @return the schema
 */
public Schema resolveProperties(Schema schema, PropertyResolverUtils propertyResolverUtils) {
	resolveProperty(schema::getName, schema::name, propertyResolverUtils);
	resolveProperty(schema::getTitle, schema::title, propertyResolverUtils);
	resolveProperty(schema::getDescription, schema::description, propertyResolverUtils);

	Map<String, Schema> properties = schema.getProperties();
	if (!CollectionUtils.isEmpty(properties)) {
		Map<String, Schema> resolvedSchemas = properties.entrySet().stream().map(es -> {
			es.setValue(resolveProperties(es.getValue(), propertyResolverUtils));
			return es;
		}).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
		schema.setProperties(resolvedSchemas);
	}

	return schema;
}
 
Example 3
Source File: SchemaGeneratorHelper.java    From spring-openapi with MIT License 5 votes vote down vote up
public MediaType createMediaType(Class<?> requestBodyParameter,
                                 String parameterName,
                                 List<Class<?>> genericParams) {
    Schema<?> rootMediaSchema = new Schema<>();
    if (isFile(requestBodyParameter)) {
        Schema<?> fileSchema = new Schema<>();
        fileSchema.setType("string");
        fileSchema.setFormat("binary");

        if (parameterName == null) {
            rootMediaSchema = fileSchema;
        } else {
            Map<String, Schema> properties = new HashMap<>();
            properties.put(parameterName, fileSchema);
            rootMediaSchema.setType("object");
            rootMediaSchema.setProperties(properties);
        }
    } else if (isList(requestBodyParameter, genericParams)) {
        rootMediaSchema = parseArraySignature(getFirstOrNull(genericParams), null, new Annotation[]{});
    } else if (!StringUtils.equalsIgnoreCase(requestBodyParameter.getSimpleName(), "void")) {
        if (isInPackagesToBeScanned(requestBodyParameter, modelPackages)) {
            rootMediaSchema.set$ref(COMPONENT_REF_PREFIX + requestBodyParameter.getSimpleName());
        } else if (requestBodyParameter.isAssignableFrom(ResponseEntity.class) && !CollectionUtils.isEmpty(genericParams)
                && !genericParams.get(0).isAssignableFrom(Void.class)) {
            rootMediaSchema.set$ref(COMPONENT_REF_PREFIX + genericParams.get(0).getSimpleName());
        } else {
            return null;
        }
    } else {
        return null;
    }

    MediaType mediaType = new MediaType();
    mediaType.setSchema(rootMediaSchema);
    return mediaType;
}
 
Example 4
Source File: ComponentSchemaTransformer.java    From spring-openapi with MIT License 5 votes vote down vote up
private void updateSchemaProperties(Schema schema, String propertyName, Schema propertyValue) {
    if (StringUtils.isBlank(propertyName) || propertyValue == null) {
        return;
    }
    if (schema.getProperties() == null) {
        schema.setProperties(new HashMap<>());
    }
    schema.getProperties().put(propertyName, propertyValue);
}
 
Example 5
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Construct openAPI definition for graphQL. Add get and post operations
 *
 * @param openAPI OpenAPI
 * @return modified openAPI for GraphQL
 */
private void modifyGraphQLSwagger(OpenAPI openAPI) {
    SwaggerData.Resource resource = new SwaggerData.Resource();
    resource.setAuthType(APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN);
    resource.setPolicy(APIConstants.DEFAULT_SUB_POLICY_UNLIMITED);
    resource.setPath("/");
    resource.setVerb(APIConstants.HTTP_POST);
    Operation postOperation = createOperation(resource);

    //post operation
    RequestBody requestBody = new RequestBody();
    requestBody.setDescription("Query or mutation to be passed to graphQL API");
    requestBody.setRequired(true);

    JSONObject typeOfPayload = new JSONObject();
    JSONObject payload = new JSONObject();
    typeOfPayload.put(APIConstants.TYPE, APIConstants.STRING);
    payload.put(APIConstants.OperationParameter.PAYLOAD_PARAM_NAME, typeOfPayload);

    Schema postSchema = new Schema();
    postSchema.setType(APIConstants.OBJECT);
    postSchema.setProperties(payload);

    MediaType mediaType = new MediaType();
    mediaType.setSchema(postSchema);

    Content content = new Content();
    content.addMediaType(APPLICATION_JSON_MEDIA_TYPE, mediaType);
    requestBody.setContent(content);
    postOperation.setRequestBody(requestBody);

    //add post and get operations to path /*
    PathItem pathItem = new PathItem();
    pathItem.setPost(postOperation);
    Paths paths = new Paths();
    paths.put("/", pathItem);

    openAPI.setPaths(paths);
}
 
Example 6
Source File: CsharpModelEnumTest.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Test(description = "not override identical parent enums", enabled = false)
public void overrideEnumTest() {
    final StringSchema identicalEnumProperty = new StringSchema();
    identicalEnumProperty.setEnum(Arrays.asList("VALUE1", "VALUE2", "VALUE3"));

    final StringSchema subEnumProperty = new StringSchema();
    subEnumProperty.setEnum(Arrays.asList("SUB1", "SUB2", "SUB3"));

    // Add one enum property to the parent
    final Map<String, Schema> parentProperties = new HashMap<String, Schema>();
    parentProperties.put("sharedThing", identicalEnumProperty);

    // Add TWO enums to the subType model; one of which is identical to the one in parent class
    final Map<String, Schema> subProperties = new HashMap<String, Schema>();
    subProperties.put("sharedThing", identicalEnumProperty);
    subProperties.put("unsharedThing", identicalEnumProperty);

    final Schema parentModel = new Schema()
            .description("parentModel");
    parentModel.setProperties(parentProperties);
    parentModel.name("parentModel");

    final Schema subModel = new Schema()
            .description("subModel");
    subModel.setProperties(subProperties);
    subModel.name("subModel");

    /* TODO revise the following as there's parent/child method
    final ComposedSchema model = new ComposedSchema().
            .parent(new RefModel(parentModel.getName()))
            .child(subModel)
            .interfaces(new ArrayList<RefModel>());
            */
    final DefaultCodegen codegen = new CSharpClientCodegen();
    final Map<String, Schema> allModels = new HashMap<>();
    allModels.put("ParentModel", parentModel);
    allModels.put("SubModel", subModel);

    /*
    codegen.setOpenAPI(allModels);
    final CodegenModel cm = codegen.fromModel("sample", model);

    Assert.assertEquals(cm.name, "sample");
    Assert.assertEquals(cm.classname, "Sample");
    Assert.assertEquals(cm.parent, "ParentModel");
    Assert.assertTrue(cm.imports.contains("ParentModel"));

    // Assert that only the unshared/uninherited enum remains
    Assert.assertEquals(cm.vars.size(), 1);
    final CodegenProperty enumVar = cm.vars.get(0);
    Assert.assertEquals(enumVar.baseName, "unsharedThing");
    Assert.assertEquals(enumVar.datatype, "string");
    Assert.assertEquals(enumVar.datatypeWithEnum, "UnsharedThingEnum");
    Assert.assertTrue(enumVar.isEnum);
    */
}
 
Example 7
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 8
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());
  }