Skip to content

Commit

Permalink
add support for dependentRequired keyword
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastian-toepfer committed May 29, 2024
1 parent 9b66593 commit 5624806
Show file tree
Hide file tree
Showing 5 changed files with 308 additions and 0 deletions.
1 change: 1 addition & 0 deletions core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@
<include>**/tests/draft2020-12/additionalProperties.json</include>
<include>**/tests/draft2020-12/boolean_schema.json</include>
<include>**/tests/draft2020-12/const.json</include>
<include>**/tests/draft2020-12/dependentRequired.json</include>
<include>**/tests/draft2020-12/enum.json</include>
<include>**/tests/draft2020-12/exclusiveMaximum.json</include>
<include>**/tests/draft2020-12/exclusiveMinimum.json</include>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* The MIT License
*
* Copyright 2024 sebastian.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.github.sebastiantoepfer.jsonschema.core.keyword.type;

import io.github.sebastiantoepfer.jsonschema.JsonSchema;
import io.github.sebastiantoepfer.jsonschema.keyword.Keyword;
import io.github.sebastiantoepfer.jsonschema.keyword.KeywordType;
import jakarta.json.JsonObject;
import java.util.Objects;
import java.util.function.Function;

public final class ObjectKeywordType implements KeywordType {

private final String name;
private final Function<JsonObject, Keyword> keywordCreator;

public ObjectKeywordType(final String name, final Function<JsonObject, Keyword> keywordCreator) {
this.name = Objects.requireNonNull(name);
this.keywordCreator = Objects.requireNonNull(keywordCreator);
}

@Override
public String name() {
return name;
}

@Override
public Keyword createKeyword(final JsonSchema schema) {
return keywordCreator.apply(schema.asJsonObject().getJsonObject(name));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*
* The MIT License
*
* Copyright 2024 sebastian.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.github.sebastiantoepfer.jsonschema.core.vocab.validation;

import io.github.sebastiantoepfer.common.condition4j.Fulfilable;
import io.github.sebastiantoepfer.common.condition4j.core.ContainsOnlyItemsWhichFulfilThe;
import io.github.sebastiantoepfer.common.condition4j.json.JsonValueOfType;
import io.github.sebastiantoepfer.ddd.common.Media;
import io.github.sebastiantoepfer.ddd.media.json.JsonObjectPrintable;
import io.github.sebastiantoepfer.jsonschema.InstanceType;
import io.github.sebastiantoepfer.jsonschema.keyword.Assertion;
import jakarta.json.JsonObject;
import jakarta.json.JsonString;
import jakarta.json.JsonValue;
import java.util.Collection;
import java.util.Objects;

/**
* <b>dependentRequired</b> : <i>Object<String, Array<String>></i><br/>
* Validation succeeds if, for each name that appears in both the instance and as a name within this keyword’s value,
* every item in the corresponding array is also the name of a property in the instance.<br/>
* <br/>
* <ul>
* <li>assertion</li>
* </ul>
*
* source: https://www.learnjsonschema.com/2020-12/validation/const/
* spec: https://json-schema.org/draft/2020-12/json-schema-validation.html#section-6.1.3
*/
final class DependentRequiredKeyword implements Assertion {

static final String NAME = "dependentRequired";
private final JsonObject dependentRequired;

public DependentRequiredKeyword(final JsonObject dependentRequired) {
new AllPropertiesAreArraysOfString()
.asVerification("objects must contains only string array props.")
.check(dependentRequired);
this.dependentRequired = dependentRequired;
}

@Override
public boolean isValidFor(final JsonValue instance) {
return !InstanceType.OBJECT.isInstance(instance) || isValidFor(instance.asJsonObject());
}

private boolean isValidFor(final JsonObject instance) {
return instance
.keySet()
.stream()
.filter(dependentRequired::containsKey)
.map(dependentRequired::getJsonArray)
.flatMap(Collection::stream)
.map(JsonString.class::cast)
.map(JsonString::getString)
.allMatch(instance::containsKey);
}

@Override
public boolean hasName(final String name) {
return Objects.equals(NAME, name);
}

@Override
public <T extends Media<T>> T printOn(final T media) {
return media.withValue(NAME, new JsonObjectPrintable(dependentRequired));
}

private static class AllPropertiesAreArraysOfString implements Fulfilable<JsonObject> {

private final JsonValueOfType isArray;
private final ContainsOnlyItemsWhichFulfilThe<JsonValue> values;

public AllPropertiesAreArraysOfString() {
this.isArray = new JsonValueOfType(JsonValue.ValueType.ARRAY);
this.values = new ContainsOnlyItemsWhichFulfilThe<>(new JsonValueOfType(JsonValue.ValueType.STRING));
}

@Override
public boolean isFulfilledBy(final JsonObject value) {
return (
value.values().stream().allMatch(v -> isArray.isFulfilledBy(v) && values.isFulfilledBy(v.asJsonArray()))
);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import io.github.sebastiantoepfer.jsonschema.core.keyword.type.BooleanKeywordType;
import io.github.sebastiantoepfer.jsonschema.core.keyword.type.IntegerKeywordType;
import io.github.sebastiantoepfer.jsonschema.core.keyword.type.NumberKeywordType;
import io.github.sebastiantoepfer.jsonschema.core.keyword.type.ObjectKeywordType;
import io.github.sebastiantoepfer.jsonschema.core.keyword.type.StringArrayKeywordType;
import io.github.sebastiantoepfer.jsonschema.core.keyword.type.StringKeywordType;
import io.github.sebastiantoepfer.jsonschema.keyword.KeywordType;
Expand All @@ -47,6 +48,7 @@ public ValidationVocabulary(final JsonProvider jsonContext) {
new TypeKeywordType(),
new AnyKeywordType(ConstKeyword.NAME, ConstKeyword::new),
new ArrayKeywordType(EnumKeyword.NAME, EnumKeyword::new),
new ObjectKeywordType(DependentRequiredKeyword.NAME, DependentRequiredKeyword::new),
new StringKeywordType(jsonContext, PatternKeyword.NAME, PatternKeyword::new),
new IntegerKeywordType(jsonContext, MinLengthKeyword.NAME, MinLengthKeyword::new),
new IntegerKeywordType(jsonContext, MaxLengthKeyword.NAME, MaxLengthKeyword::new),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
/*
* The MIT License
*
* Copyright 2024 sebastian.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.github.sebastiantoepfer.jsonschema.core.vocab.validation;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows;

import io.github.sebastiantoepfer.ddd.media.core.HashMapMedia;
import io.github.sebastiantoepfer.jsonschema.core.DefaultJsonSchemaFactory;
import io.github.sebastiantoepfer.jsonschema.core.keyword.type.ObjectKeywordType;
import io.github.sebastiantoepfer.jsonschema.keyword.Keyword;
import jakarta.json.Json;
import jakarta.json.JsonObject;
import jakarta.json.JsonValue;
import java.math.BigDecimal;
import org.hamcrest.Matcher;
import org.junit.jupiter.api.Test;

class DependentRequiredKeywordTest {

@Test
void should_not_be_createable_with_object_contains_non_string_array_property() {
final JsonObject obj = Json.createObjectBuilder()
.add("totalCost", Json.createArrayBuilder().add("units"))
.add("trackingId", BigDecimal.ONE)
.build();
assertThrows(IllegalArgumentException.class, () -> new DependentRequiredKeyword(obj));
}

@Test
void should_not_be_createable_with_object_contains_only_non_string_array_property() {
final JsonObject obj = Json.createObjectBuilder()
.add("totalCost", 12.7)
.add("trackingId", BigDecimal.ONE)
.build();
assertThrows(IllegalArgumentException.class, () -> new DependentRequiredKeyword(obj));
}

@Test
void should_know_his_name() {
final Keyword enumKeyword = createKeywordFrom(
Json.createObjectBuilder().add("dependentRequired", JsonValue.EMPTY_JSON_OBJECT).build()
);

assertThat(enumKeyword.hasName("dependentRequired"), is(true));
assertThat(enumKeyword.hasName("test"), is(false));
}

@Test
void should_be_valid_if_both_properties_available() {
assertThat(
createKeywordFrom(
Json.createObjectBuilder()
.add(
"dependentRequired",
Json.createObjectBuilder().add("license", Json.createArrayBuilder().add("age"))
)
.build()
)
.asAssertion()
.isValidFor(
Json.createObjectBuilder().add("name", "John").add("age", 25).add("license", "XYZ123").build()
),
is(true)
);
}

@Test
void should_be_valid_if_required_properties_is_missing() {
assertThat(
createKeywordFrom(
Json.createObjectBuilder()
.add(
"dependentRequired",
Json.createObjectBuilder().add("license", Json.createArrayBuilder().add("age"))
)
.build()
)
.asAssertion()
.isValidFor(Json.createObjectBuilder().add("name", "John").add("license", "XYZ123").build()),
is(false)
);
}

@Test
void should_be_valid_if_both_properties_are_missing() {
assertThat(
createKeywordFrom(
Json.createObjectBuilder()
.add(
"dependentRequired",
Json.createObjectBuilder().add("license", Json.createArrayBuilder().add("age"))
)
.build()
)
.asAssertion()
.isValidFor(Json.createObjectBuilder().add("name", "John").build()),
is(true)
);
}

@Test
void should_be_printable() {
assertThat(
createKeywordFrom(
Json.createObjectBuilder()
.add(
"dependentRequired",
Json.createObjectBuilder().add("license", Json.createArrayBuilder().add("age"))
)
.build()
).printOn(new HashMapMedia()),
(Matcher) hasEntry(is("dependentRequired"), hasEntry(is("license"), contains("age")))
);
}

private static Keyword createKeywordFrom(final JsonObject json) {
return new ObjectKeywordType("dependentRequired", DependentRequiredKeyword::new).createKeyword(
new DefaultJsonSchemaFactory().create(json)
);
}
}

0 comments on commit 5624806

Please sign in to comment.