All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.fibanez.jsonschema.content.generator.NumberSchemaGenerator Maven / Gradle / Ivy

package com.fibanez.jsonschema.content.generator;

import com.fibanez.jsonschema.content.Context;
import com.fibanez.jsonschema.content.generator.abstraction.MultipleOfGenerator;
import com.fibanez.jsonschema.content.generator.abstraction.RangeGenerator;
import com.fibanez.jsonschema.content.generator.javaType.JavaTypeGenerator;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import org.everit.json.schema.NumberSchema;

import java.util.Collections;
import java.util.Optional;
import java.util.Set;

import static java.util.Optional.ofNullable;

@NoArgsConstructor(access = AccessLevel.PACKAGE)
public final class NumberSchemaGenerator implements SchemaGenerator {

    @Override
    public Number generate(@NonNull NumberSchema schema, JsonNode jsonNode) {
        JavaTypeGenerator generator = Context.getJavaTypeGenerator(Integer.class);

        Number minValue = getMinValue(schema).orElse(Context.current().getNumberMin());
        Number maxValue = getMaxValue(schema).orElse(Context.current().getNumberMax());

        if (generator instanceof MultipleOfGenerator) {
            MultipleOfGenerator numberTypeGenerator = (MultipleOfGenerator) generator;
            Number multipleOf = getMultipleOfValue(schema).orElse(Context.DEFAULT_NUMBER_MULTIPLE_OF);

            // Check for non-multipleOf
            Set negatedMultipleOf = getNegatedMultipleOfValue(schema);
            if (negatedMultipleOf.isEmpty()) {
                return numberTypeGenerator.get(minValue.intValue(), maxValue.intValue(), multipleOf.intValue());
            } else {
                return numberTypeGenerator.get(minValue.intValue(), maxValue.intValue(), multipleOf.intValue(), negatedMultipleOf);
            }

        } else if (generator instanceof RangeGenerator) {
            RangeGenerator numberTypeGenerator = (RangeGenerator) generator;
            return numberTypeGenerator.get(minValue.intValue(), maxValue.intValue());
        }

        return generator.get();
    }

    private Optional getMinValue(NumberSchema schema) {
        Number value = getOrDefault(schema.getMinimum(), schema.getExclusiveMinimumLimit());
        return ofNullable(value);
    }

    private Optional getMaxValue(NumberSchema schema) {
        Number value = getOrDefault(schema.getMaximum(), schema.getExclusiveMaximumLimit());
        return ofNullable(value);
    }

    private Optional getMultipleOfValue(NumberSchema schema) {
        return ofNullable(schema.getMultipleOf());
    }

    @SuppressWarnings("unchecked")
    private Set getNegatedMultipleOfValue(NumberSchema schema) {
        return (Set) schema.getUnprocessedProperties().getOrDefault(Context.UNPROCESSED_NOT_MULTIPLE_OF, Collections.emptySet());
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy