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

The following examples show how to use io.swagger.v3.oas.models.media.Schema#getProperties() . 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: SchemaPropertiesKeysValidator.java    From servicecomb-toolkit with Apache License 2.0 6 votes vote down vote up
@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 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: InfluxJavaGenerator.java    From influxdb-client-java with MIT License 6 votes vote down vote up
private String[] getDiscriminatorKeys(final Schema schema, final Schema refSchema) {
    List<String> keys = new ArrayList<>();

    if (refSchema.getProperties() == null) {
        keys.add(schema.getDiscriminator().getPropertyName());
    } else {
        refSchema.getProperties().forEach((BiConsumer<String, Schema>) (property, propertySchema) -> {

            if (keys.isEmpty()) {
                keys.add(property);

            } else if (propertySchema.getEnum() != null && propertySchema.getEnum().size() == 1) {
                keys.add(property);
            }
        });
    }

    return keys.toArray(new String[0]);
}
 
Example 4
Source File: SchemaProcessor.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
public void processPropertySchema(Schema schema) {
    if(schema.get$ref() !=  null){
        processReferenceSchema(schema);
    }

     Map<String, Schema> properties = schema.getProperties();
     if (properties != null) {
         for (Map.Entry<String, Schema> propertyEntry : properties.entrySet()) {
             Schema property = propertyEntry.getValue();
             if(property.get$ref() != null) {
                 processReferenceSchema(property);
             }else {
                 processSchemaType(property);
             }

         }
     }
}
 
Example 5
Source File: ExampleGenerator.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private Object resolveModelToExample(String name, String mediaType, Schema schema, Set<String> processedModels) {
    if (processedModels.contains(name)) {
        return schema.getExample();
    }

    processedModels.add(name);
    Map<String, Object> values = new HashMap<>();
    LOGGER.debug("Resolving model '{}' to example", name);
    if (schema.getExample() != null) {
        LOGGER.debug("Using example from spec: {}", schema.getExample());
        return schema.getExample();
    } else if (schema.getProperties() != null) {
        LOGGER.debug("Creating example from model values");
        for (Object propertyName : schema.getProperties().keySet()) {
            Schema property = (Schema) schema.getProperties().get(propertyName.toString());
            values.put(propertyName.toString(), resolvePropertyToExample(propertyName.toString(), mediaType, property, processedModels));
        }
        schema.setExample(values);
        return schema.getExample();
    } else {
        // TODO log an error message as the model does not have any properties
        return null;
    }
}
 
Example 6
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 7
Source File: OASParserUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
private static void extractReferenceFromSchema(Schema schema, SwaggerUpdateContext context) {
    if (schema != null) {
        String ref = schema.get$ref();
        if (ref == null) {
            if (ARRAY_DATA_TYPE.equalsIgnoreCase(schema.getType())) {
                ArraySchema arraySchema = (ArraySchema) schema;
                ref = arraySchema.getItems().get$ref();
            }
        }

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

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

        if (properties != null) {
            for (Object propertySchema : properties.values()) {
                extractReferenceFromSchema((Schema) propertySchema, context);
            }
        }
    }
}
 
Example 8
Source File: AbstractEndpointGenerationTest.java    From flow with 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 9
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 10
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Map<String, Schema> issue975ExtractPropertiesFromTestResource() {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    OpenAPI openAPI = new OpenAPIV3Parser().readLocation("issue-975/contract/openapi.yaml", null, options).getOpenAPI();
    Schema myResponseSchema = openAPI.getComponents().getSchemas().get("MyResponse");
    return myResponseSchema.getProperties();
}
 
Example 11
Source File: AbstractEndpointGenerationTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private void assertSchemaProperties(Class<?> expectedSchemaClass,
        Schema schema) {
    int expectedFieldsCount = 0;
    Map<String, Schema> properties = schema.getProperties();
    assertNotNull(properties);
    assertTrue(properties.size() > 0);
    for (Field expectedSchemaField : expectedSchemaClass
            .getDeclaredFields()) {
        if (Modifier.isTransient(expectedSchemaField.getModifiers())
                || Modifier.isStatic(expectedSchemaField.getModifiers())
                || expectedSchemaField
                        .isAnnotationPresent(JsonIgnore.class)) {
            continue;
        }

        expectedFieldsCount++;
        Schema propertySchema = properties
                .get(expectedSchemaField.getName());
        assertNotNull(String.format("Property schema is not found %s",
                expectedSchemaField.getName()), propertySchema);
        assertSchema(propertySchema, expectedSchemaField.getType());
        if (Optional.class
                .isAssignableFrom(expectedSchemaField.getType()) ||
                expectedSchemaField.isAnnotationPresent(Nullable.class)) {
            boolean notRequired = schema.getRequired() == null ||
                    !schema.getRequired()
                            .contains(expectedSchemaField.getName());
            assertTrue(notRequired);
        } else {
            assertTrue(schema.getRequired()
                    .contains(expectedSchemaField.getName()));
        }
    }
    assertEquals(expectedFieldsCount, properties.size());

}
 
Example 12
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testEnumType() {
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult result = new OpenAPIV3Parser().readLocation("./src/test/resources/issue-1090.yaml", null, options);
    assertNotNull(result.getOpenAPI());
    OpenAPI openAPI = result.getOpenAPI();

    Schema someObj = openAPI.getComponents().getSchemas().get("SomeObj");
    assertNotNull(someObj);

    Map<String, Schema> properties = someObj.getProperties();
    assertNotNull(properties);

    Schema iprop = properties.get("iprop");
    assertNotNull(iprop);
    assertEquals(iprop.getType(), "integer");
    assertEquals(iprop.getFormat(), "int32");

    Schema lprop = properties.get("lprop");
    assertNotNull(lprop);
    assertEquals(lprop.getType(), "integer");
    assertEquals(lprop.getFormat(), "int64");

    Schema nprop = properties.get("nprop");
    assertNotNull(nprop);
    assertEquals(nprop.getType(), "number");
}
 
Example 13
Source File: OpenApiObjectGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
private Map<String, ResolvedReferenceType> collectUsedTypesFromSchema(
        Schema schema) {
    Map<String, ResolvedReferenceType> map = new HashMap<>();
    if (GeneratorUtils.isNotBlank(schema.getName())
            || GeneratorUtils.isNotBlank(schema.get$ref())) {
        String name = GeneratorUtils.firstNonBlank(schema.getName(),
                schemaResolver.getSimpleRef(schema.get$ref()));
        ResolvedReferenceType resolvedReferenceType = schemaResolver
                .getFoundTypeByQualifiedName(name);
        if (resolvedReferenceType != null) {
            map.put(name, resolvedReferenceType);
        } else {
            getLogger().info(
                    "Can't find the type information of class '{}'. "
                            + "This might result in a missing schema in the generated OpenAPI spec.",
                    name);
        }
    }
    if (schema instanceof ArraySchema) {
        map.putAll(collectUsedTypesFromSchema(
                ((ArraySchema) schema).getItems()));
    } else if (schema instanceof MapSchema
            && schema.getAdditionalProperties() != null) {
        map.putAll(collectUsedTypesFromSchema(
                (Schema) schema.getAdditionalProperties()));
    } else if (schema instanceof ComposedSchema
            && ((ComposedSchema) schema).getAllOf() != null) {
            for (Schema child : ((ComposedSchema) schema).getAllOf()) {
                map.putAll(collectUsedTypesFromSchema(child));
            }
    }
    if (schema.getProperties() != null) {
        schema.getProperties().values().forEach(
                o -> map.putAll(collectUsedTypesFromSchema((Schema) o)));
    }
    return map;
}
 
Example 14
Source File: BodyGenerator.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
public String generate(Schema<?> schema) {
    if (schema == null) {
        return "";
    }

    boolean isArray = schema instanceof ArraySchema;
    if (LOG.isDebugEnabled()) {
        LOG.debug("Generate body for object " + schema.getName());
    }

    if (isArray) {
        return generateFromArraySchema((ArraySchema) schema);
    }

    @SuppressWarnings("rawtypes")
    Map<String, Schema> properties = schema.getProperties();
    if (properties != null) {
        return generateFromObjectSchema(properties);
    } else if (schema.getAdditionalProperties() instanceof Schema) {
        return generate((Schema<?>) schema.getAdditionalProperties());
    }

    if (schema instanceof ComposedSchema) {
        return generateJsonPrimitiveValue(resolveComposedSchema((ComposedSchema) schema));
    }
    if (schema.getNot() != null) {
        resolveNotSchema(schema);
    }

    // primitive type, or schema without properties
    if (schema.getType() == null || schema.getType().equals("object")) {
        schema.setType("string");
    }

    return generateJsonPrimitiveValue(schema);
}
 
Example 15
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 16
Source File: InlineModelResolver.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
private boolean isObjectSchema(Schema schema) {
    return schema instanceof ObjectSchema
            || "object".equalsIgnoreCase(schema.getType())
            || (schema.getType() == null && schema.getProperties() != null && !schema.getProperties().isEmpty()
            || schema instanceof ComposedSchema);
}
 
Example 17
Source File: OpenApi3Utils.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
public static boolean isSchemaObject(Schema schema) {
  return schema != null && ("object".equals(schema.getType()) || schema.getProperties() != null);
}
 
Example 18
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 19
Source File: SchemaComponent.java    From swagger2markup with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public Document apply(StructuralNode parent, SchemaComponent.Parameters parameters) {
    Document schemaDocument = new DocumentImpl(parent);
    Schema schema = parameters.schema;
    if (null == schema) return schemaDocument;

    OpenApiHelpers.appendDescription(schemaDocument, schema.getDescription());

    Map<String, Boolean> schemasBooleanProperties = new HashMap<String, Boolean>() {{
        put(labels.getLabel(LABEL_DEPRECATED), schema.getDeprecated());
        put(labels.getLabel(LABEL_NULLABLE), schema.getNullable());
        put(labels.getLabel(LABEL_READ_ONLY), schema.getReadOnly());
        put(labels.getLabel(LABEL_WRITE_ONLY), schema.getWriteOnly());
        put(labels.getLabel(LABEL_UNIQUE_ITEMS), schema.getUniqueItems());
        put(labels.getLabel(LABEL_EXCLUSIVE_MAXIMUM), schema.getExclusiveMaximum());
        put(labels.getLabel(LABEL_EXCLUSIVE_MINIMUM), schema.getExclusiveMinimum());
    }};

    Map<String, Object> schemasValueProperties = new HashMap<String, Object>() {{
        put(labels.getLabel(LABEL_TITLE), schema.getTitle());
        put(labels.getLabel(LABEL_DEFAULT), schema.getDefault());
        put(labels.getLabel(LABEL_MAXIMUM), schema.getMaximum());
        put(labels.getLabel(LABEL_MINIMUM), schema.getMinimum());
        put(labels.getLabel(LABEL_MAX_LENGTH), schema.getMaxLength());
        put(labels.getLabel(LABEL_MIN_LENGTH), schema.getMinLength());
        put(labels.getLabel(LABEL_MAX_ITEMS), schema.getMaxItems());
        put(labels.getLabel(LABEL_MIN_ITEMS), schema.getMinItems());
        put(labels.getLabel(LABEL_MAX_PROPERTIES), schema.getMaxProperties());
        put(labels.getLabel(LABEL_MIN_PROPERTIES), schema.getMinProperties());
        put(labels.getLabel(LABEL_MULTIPLE_OF), schema.getMultipleOf());
    }};

    Stream<String> schemaBooleanStream = schemasBooleanProperties.entrySet().stream()
            .filter(e -> null != e.getValue() && e.getValue())
            .map(e -> OpenApiHelpers.italicUnconstrained(e.getKey().toLowerCase()));
    Stream<String> schemaValueStream = schemasValueProperties.entrySet().stream()
            .filter(e -> null != e.getValue() && StringUtils.isNotBlank(e.getValue().toString()))
            .map(e -> boldUnconstrained(e.getKey()) + ": " + e.getValue());

    ParagraphBlockImpl paragraphBlock = new ParagraphBlockImpl(schemaDocument);
    String source = Stream.concat(schemaBooleanStream, schemaValueStream).collect(Collectors.joining(" +" + LINE_SEPARATOR));
    paragraphBlock.setSource(source);

    schemaDocument.append(paragraphBlock);

    Map<String, Schema> properties = schema.getProperties();
    if (null != properties && !properties.isEmpty()) {
        PropertiesTableComponent propertiesTableComponent = new PropertiesTableComponent(context);
        propertiesTableComponent.apply(schemaDocument, properties, schema.getRequired());
    }

    return schemaDocument;
}
 
Example 20
Source File: PythonClientExperimentalCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
private void addNullDefaultToOneOfAnyOfReqProps(Schema schema, CodegenModel result){
    // for composed schema models, if the required properties are only from oneOf or anyOf models
    // give them a nulltype.Null so the user can omit including them in python
    ComposedSchema cs = (ComposedSchema) schema;

    // these are the properties that are from properties in self cs or cs allOf
    Map<String, Schema> selfProperties = new LinkedHashMap<String, Schema>();
    List<String> selfRequired = new ArrayList<String>();

    // these are the properties that are from properties in cs oneOf or cs anyOf
    Map<String, Schema> otherProperties = new LinkedHashMap<String, Schema>();
    List<String> otherRequired = new ArrayList<String>();

    List<Schema> oneOfanyOfSchemas = new ArrayList<>();
    List<Schema> oneOf = cs.getOneOf();
    if (oneOf != null) {
        oneOfanyOfSchemas.addAll(oneOf);
    }
    List<Schema> anyOf = cs.getAnyOf();
    if (anyOf != null) {
        oneOfanyOfSchemas.addAll(anyOf);
    }
    for (Schema sc: oneOfanyOfSchemas) {
        Schema refSchema = ModelUtils.getReferencedSchema(this.openAPI, sc);
        addProperties(otherProperties, otherRequired, refSchema);
    }
    Set<String> otherRequiredSet = new HashSet<String>(otherRequired);

    List<Schema> allOf = cs.getAllOf();
    if ((schema.getProperties() != null && !schema.getProperties().isEmpty()) || allOf != null) {
        // NOTE: this function also adds the allOf propesrties inside schema
        addProperties(selfProperties, selfRequired, schema);
    }
    if (result.discriminator != null) {
        selfRequired.add(result.discriminator.getPropertyBaseName());
    }
    Set<String> selfRequiredSet = new HashSet<String>(selfRequired);

    List<CodegenProperty> reqVars = result.getRequiredVars();
    if (reqVars != null) {
        for (CodegenProperty cp: reqVars) {
            String propName = cp.baseName;
            if (otherRequiredSet.contains(propName) && !selfRequiredSet.contains(propName)) {
                // if var is in otherRequiredSet and is not in selfRequiredSet and is in result.requiredVars
                // then set it to nullable because the user doesn't have to give a value for it
                cp.setDefaultValue("nulltype.Null");
            }
        }
    }
}