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

The following examples show how to use io.swagger.v3.oas.models.media.Schema#getAdditionalProperties() . 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: SchemaDiffResult.java    From openapi-diff with 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 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 3
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 4
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 5
Source File: InlineModelResolver.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("static-method")
public Schema modelFromProperty(Schema object, @SuppressWarnings("unused") String path) {
    String description = object.getDescription();
    String example = null;

    Object obj = object.getExample();
    if (obj != null) {
        example = obj.toString();
    }
    ArraySchema model = new ArraySchema();
    model.setDescription(description);
    model.setExample(example);
    if (object.getAdditionalProperties() != null && !(object.getAdditionalProperties() instanceof Boolean)) {
        model.setItems((Schema)  object.getAdditionalProperties());
    }
    return model;
}
 
Example 6
Source File: InlineModelResolverTest.java    From swagger-parser with 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 7
Source File: PythonClientExperimentalCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public String toInstantiationType(Schema property) {
    if (ModelUtils.isArraySchema(property) || ModelUtils.isMapSchema(property) || property.getAdditionalProperties() != null) {
        return getSchemaType(property);
    }
    return super.toInstantiationType(property);
}
 
Example 8
Source File: SchemaUtils.java    From tcases with MIT License 5 votes vote down vote up
/**
 * If the given schema asserts a schema for additional properties, returns
 * the additional properties schema. Otherwise, returns null.
 */
public static Schema<?> additionalPropertiesSchema( Schema<?> schema)
  {
  return
    schema.getAdditionalProperties() instanceof Schema
    ? (Schema<?>) schema.getAdditionalProperties()
    : null;
  }
 
Example 9
Source File: SchemaMatcher.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the "additionalProperties" for this schema as a Schema.
 */
public Schema getAdditionalPropertiesSchema( Schema schema)
  {
  Object additional = schema.getAdditionalProperties();
  return
    additional instanceof Schema
    ? (Schema) additional
    : null;
  }
 
Example 10
Source File: SchemaMatcher.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the "additionalProperties" for this schema as a Boolean.
 */
public Boolean getAdditionalPropertiesBoolean( Schema schema)
  {
  return
    getAdditionalPropertiesSchema( schema) == null
    ? (Boolean) schema.getAdditionalProperties()
    : null;
  }
 
Example 11
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 12
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 13
Source File: SchemaProcessor.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
private void processAdditionalProperties(Object additionalProperties) {

        if (additionalProperties instanceof Schema) {
            Schema schema = (Schema) additionalProperties;
            if (schema.getAdditionalProperties() != null && schema.getAdditionalProperties() instanceof Schema) {
                Schema additionalPropertiesSchema = (Schema) schema.getAdditionalProperties();
                if (additionalPropertiesSchema.get$ref() != null) {
                    processReferenceSchema(additionalPropertiesSchema);
                } else {
                    processSchemaType(additionalPropertiesSchema);
                }
            }
        }
    }
 
Example 14
Source File: OpenAPIV3ParserTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
private OpenAPI doRelativeFileTest(String location) {
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult readResult = parser.readLocation(location, null, options);

    if (readResult.getMessages().size() > 0) {
        Json.prettyPrint(readResult.getMessages());
    }
    final OpenAPI openAPI = readResult.getOpenAPI();
    final PathItem path = openAPI.getPaths().get("/health");
    assertEquals(path.getClass(), PathItem.class); //we successfully converted the RefPath to a Path

    final List<Parameter> parameters = path.getParameters();
    assertParamDetails(parameters, 0, QueryParameter.class, "param1", "query");
    assertParamDetails(parameters, 1, HeaderParameter.class, "param2", "header");

    final Operation operation = path.getGet();
    final List<Parameter> operationParams = operation.getParameters();
    assertParamDetails(operationParams, 0, PathParameter.class, "param3", "path");
    assertParamDetails(operationParams, 1, HeaderParameter.class, "param4", "header");

    final Map<String, ApiResponse> responsesMap = operation.getResponses();

    assertResponse(openAPI, responsesMap, "200","application/json", "Health information from the server", "#/components/schemas/health");
    assertResponse(openAPI, responsesMap, "400","*/*", "Your request was not valid", "#/components/schemas/error");
    assertResponse(openAPI, responsesMap, "500","*/*", "An unexpected error occur during processing", "#/components/schemas/error");

    final Map<String, Schema> definitions = openAPI.getComponents().getSchemas();
    final Schema refInDefinitions = definitions.get("refInDefinitions");
    assertEquals(refInDefinitions.getDescription(), "The example model");
    expectedPropertiesInModel(refInDefinitions, "foo", "bar");

    final ArraySchema arrayModel = (ArraySchema) definitions.get("arrayModel");
    final Schema arrayModelItems = arrayModel.getItems();
    assertEquals(arrayModelItems.get$ref(), "#/components/schemas/foo");

    final Schema fooModel = definitions.get("foo");
    assertEquals(fooModel.getDescription(), "Just another model");
    expectedPropertiesInModel(fooModel, "hello", "world");

    final ComposedSchema composedCat = (ComposedSchema) definitions.get("composedCat");
    final Schema child =  composedCat.getAllOf().get(2);
    expectedPropertiesInModel(child, "huntingSkill", "prop2", "reflexes", "reflexMap");
    final ArraySchema reflexes = (ArraySchema) child.getProperties().get("reflexes");
    final Schema reflexItems = reflexes.getItems();
    assertEquals(reflexItems.get$ref(), "#/components/schemas/reflex");
    assertTrue(definitions.containsKey(reflexItems.get$ref().substring(reflexItems.get$ref().lastIndexOf("/")+1)));

    final Schema reflexMap = (Schema) child.getProperties().get("reflexMap");
    final Schema reflexMapAdditionalProperties = (Schema) reflexMap.getAdditionalProperties();
    assertEquals(reflexMapAdditionalProperties.get$ref(), "#/components/schemas/reflex");

    assertEquals(composedCat.getAllOf().size(), 3);
    assertEquals(composedCat.getAllOf().get(0).get$ref(), "#/components/schemas/pet");
    assertEquals(composedCat.getAllOf().get(1).get$ref(), "#/components/schemas/foo_2");

    return openAPI;
}
 
Example 15
Source File: MapGenerator.java    From zap-extensions with Apache License 2.0 3 votes vote down vote up
/**
 * @param types the data types supported with their corresponding default values
 * @param property Can be {@link NumberSchema}, {@link IntegerSchema}, {@link StringSchema} and
 *     {@link BooleanSchema}. For any other schema type, i.g {@link ObjectSchema}, the {@link
 *     BodyGenerator#generate(Schema)} is invoked to start the value generation again.
 * @return a key value JSON structure where the key is default to string as per Swagger/OpenApi
 *     specification.
 */
public String generate(Map<String, String> types, Schema<?> property) {
    Schema<?> schema = (Schema<?>) property.getAdditionalProperties();
    String type = types.get(schema.getType());
    String value = type != null ? type : bodyGenerator.generate(schema);
    String defaultKey = types.get(STRING.type());
    return OBJECT_BEGIN + defaultKey + INNER_SEPARATOR + value + OBJECT_END;
}