Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for prefixItems keyword #23

Merged
merged 2 commits into from
Oct 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,12 @@
*/
package io.github.sebastiantoepfer.jsonschema;

import io.github.sebastiantoepfer.jsonschema.keyword.Keyword;
import jakarta.json.JsonValue;
import java.util.Optional;

public interface JsonSchema extends JsonValue {
public Validator validator();

Optional<Keyword> keywordByName(String name);
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@
*/
package io.github.sebastiantoepfer.jsonschema;

import io.github.sebastiantoepfer.jsonschema.keyword.Keyword;
import io.github.sebastiantoepfer.jsonschema.spi.JsonSchemaFactory;
import jakarta.json.JsonValue;
import java.util.Optional;

public final class FakeJsonSchemaFactory implements JsonSchemaFactory {

Expand All @@ -40,6 +42,11 @@ public Validator validator() {
public JsonValue.ValueType getValueType() {
throw new UnsupportedOperationException("Not supported yet.");
}

@Override
public Optional<Keyword> keywordByName(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
};
}
}
1 change: 1 addition & 0 deletions core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@
<inculde>**/tests/draft2020-12/maximum.json</inculde>
<inculde>**/tests/draft2020-12/exclusiveMaximum.json</inculde>
<inculde>**/tests/draft2020-12/multipleOf.json</inculde>
<inculde>**/tests/draft2020-12/prefixItems.json</inculde>
<!-- more than items keyword needed :(
<inculde>**/tests/draft2020-12/items.json</inculde>
-->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@
import jakarta.json.JsonValue;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;

final class DefaultJsonSchema extends AbstractJsonValueSchema {

Expand All @@ -55,16 +55,19 @@ public DefaultJsonSchema(final JsonObject value) {

@Override
public Validator validator() {
return asJsonObject()
.entrySet()
.stream()
return keywords()
.map(this::asContraint)
.flatMap(Optional::stream)
.collect(
collectingAndThen(toList(), constraints -> new DefaultValidator(new AllOfConstraint<>(constraints)))
);
}

@Override
public Optional<Keyword> keywordByName(final String name) {
return keywords().filter(k -> k.hasName(name)).findFirst();
}

private Collection<VocabularyDefinition> vocabulary() {
return new KeywordSearch(new VocabularyKeywordType())
.searchForKeywordIn(this)
Expand All @@ -75,8 +78,11 @@ private Collection<VocabularyDefinition> vocabulary() {
.toList();
}

private Optional<Constraint<JsonValue>> asContraint(final Entry<String, JsonValue> property) {
final Keyword keyword = keywords.createKeywordFor(this, property);
private Stream<Keyword> keywords() {
return asJsonObject().entrySet().stream().map(property -> keywords.createKeywordFor(this, property));
}

private Optional<Constraint<JsonValue>> asContraint(final Keyword keyword) {
final Constraint<JsonValue> result;
if (keyword.hasCategory(Keyword.KeywordCategory.ASSERTION)) {
result = new AssertionConstraint(keyword.asAssertion());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@

import io.github.sebastiantoepfer.jsonschema.Validator;
import io.github.sebastiantoepfer.jsonschema.core.constraint.NoConstraint;
import io.github.sebastiantoepfer.jsonschema.keyword.Keyword;
import jakarta.json.JsonValue;
import java.util.Optional;

final class EmptyJsonSchema extends AbstractJsonValueSchema {

Expand All @@ -37,4 +39,9 @@ public EmptyJsonSchema() {
public Validator validator() {
return new DefaultValidator(new NoConstraint<>());
}

@Override
public Optional<Keyword> keywordByName(final String name) {
return Optional.empty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@

import io.github.sebastiantoepfer.jsonschema.Validator;
import io.github.sebastiantoepfer.jsonschema.core.constraint.UnfulfillableConstraint;
import io.github.sebastiantoepfer.jsonschema.keyword.Keyword;
import jakarta.json.JsonValue;
import java.util.Optional;

final class FalseJsonSchema extends AbstractJsonValueSchema {

Expand All @@ -37,4 +39,9 @@ public FalseJsonSchema() {
public Validator validator() {
return new DefaultValidator(new UnfulfillableConstraint<>());
}

@Override
public Optional<Keyword> keywordByName(final String name) {
return Optional.empty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@

import io.github.sebastiantoepfer.jsonschema.Validator;
import io.github.sebastiantoepfer.jsonschema.core.constraint.NoConstraint;
import io.github.sebastiantoepfer.jsonschema.keyword.Keyword;
import jakarta.json.JsonValue;
import java.util.Optional;

final class TrueJsonSchema extends AbstractJsonValueSchema {

Expand All @@ -37,4 +39,9 @@ public TrueJsonSchema() {
public Validator validator() {
return new DefaultValidator(new NoConstraint<>());
}

@Override
public Optional<Keyword> keywordByName(final String name) {
return Optional.empty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public ApplicatorVocabulary() {
this.vocab =
new DefaultVocabulary(
URI.create("https://json-schema.org/draft/2020-12/vocab/applicator"),
new PrefixItemsKeywordType(),
new ItemsKeywordType()
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,12 @@
import io.github.sebastiantoepfer.jsonschema.keyword.Keyword;
import io.github.sebastiantoepfer.jsonschema.keyword.KeywordType;
import jakarta.json.JsonArray;
import jakarta.json.JsonNumber;
import jakarta.json.JsonValue;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

final class ItemsKeywordType implements KeywordType {

Expand Down Expand Up @@ -75,6 +77,11 @@ public ValueType getValueType() {
return schema.getValueType();
}

@Override
public Optional<Keyword> keywordByName(final String name) {
return schema.keywordByName(name);
}

@Override
public boolean hasName(final String name) {
return Objects.equals(name(), name);
Expand All @@ -87,7 +94,17 @@ public Collection<KeywordCategory> categories() {

@Override
public JsonValue value() {
return JsonValue.TRUE;
final JsonValue result;
if (appliesToAny()) {
result = JsonValue.TRUE;
} else {
result = JsonValue.FALSE;
}
return result;
}

private boolean appliesToAny() {
return startIndex() < 0;
}

@Override
Expand All @@ -97,7 +114,18 @@ public boolean applyTo(final JsonValue instance) {

private boolean matchesSchema(final JsonArray items) {
final Validator itemValidator = validator();
return items.stream().map(itemValidator::validate).allMatch(Collection::isEmpty);
return items.stream().skip(startIndex() + 1).map(itemValidator::validate).allMatch(Collection::isEmpty);
}

private long startIndex() {
return owner()
.keywordByName("prefixItems")
.map(Keyword::asAnnotation)
.map(Annotation::value)
.filter(InstanceType.INTEGER::isInstance)
.map(JsonNumber.class::cast)
.map(JsonNumber::longValue)
.orElse(-1L);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* The MIT License
*
* Copyright 2023 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.applicator;

import io.github.sebastiantoepfer.jsonschema.InstanceType;
import io.github.sebastiantoepfer.jsonschema.JsonSchema;
import io.github.sebastiantoepfer.jsonschema.JsonSchemas;
import io.github.sebastiantoepfer.jsonschema.keyword.Annotation;
import io.github.sebastiantoepfer.jsonschema.keyword.Applicator;
import io.github.sebastiantoepfer.jsonschema.keyword.Keyword;
import io.github.sebastiantoepfer.jsonschema.keyword.KeywordType;
import jakarta.json.Json;
import jakarta.json.JsonArray;
import jakarta.json.JsonValue;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
* https://json-schema.org/draft/2020-12/json-schema-core#section-10.3.1.1
* https://www.learnjsonschema.com/2020-12/applicator/prefixitems/
*/
final class PrefixItemsKeywordType implements KeywordType {

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

@Override
public Keyword createKeyword(final JsonSchema schema, final JsonValue value) {
if (InstanceType.ARRAY.isInstance(value)) {
return new PrefixItemsKeyword(value.asJsonArray());
} else {
throw new IllegalArgumentException("must be a non empty array!");
}
}

private class PrefixItemsKeyword implements Annotation, Applicator {

private final List<JsonSchema> schemas;

public PrefixItemsKeyword(final JsonArray schemas) {
this.schemas = schemas.stream().map(JsonSchemas::load).toList();
}

@Override
public Collection<KeywordCategory> categories() {
return List.of(KeywordCategory.ANNOTATION, KeywordCategory.APPLICATOR);
}

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

@Override
public JsonValue value() {
return Json.createValue(schemas.size() - 1);
}

@Override
public boolean applyTo(final JsonValue instance) {
return !InstanceType.ARRAY.isInstance(instance) || matchesSchemas(instance.asJsonArray());
}

private boolean matchesSchemas(final JsonArray instance) {
boolean result = true;
for (int i = 0; i < Math.min(schemas.size(), instance.size()); i++) {
result &= schemas.get(i).validator().validate(instance.get(i)).isEmpty();
if (!result) {
break;
}
}
return result;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,11 @@
import static org.hamcrest.Matchers.is;

import io.github.sebastiantoepfer.jsonschema.Validator;
import io.github.sebastiantoepfer.jsonschema.keyword.Keyword;
import jakarta.json.JsonArray;
import jakarta.json.JsonObject;
import jakarta.json.JsonValue;
import java.util.Optional;
import org.junit.jupiter.api.Test;

class AbstractJsonValueSchemaTest {
Expand Down Expand Up @@ -65,5 +67,10 @@ public MyJsonValueSchema(JsonValue value) {
public Validator validator() {
throw new UnsupportedOperationException("Not supported yet.");
}

@Override
public Optional<Keyword> keywordByName(final String name) {
return Optional.empty();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
*/
package io.github.sebastiantoepfer.jsonschema.core;

import static com.github.npathai.hamcrestopt.OptionalMatchers.isEmpty;
import static com.github.npathai.hamcrestopt.OptionalMatchers.isPresent;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
Expand Down Expand Up @@ -76,4 +78,38 @@ void should_not_be_loadable_without_mandantory_core_vocabulary() {

Assertions.assertThrows(Exception.class, () -> new DefaultJsonSchema(invalidSchema));
}

@Test
void should_find_keyword_by_name() {
assertThat(
new DefaultJsonSchema(
Json
.createObjectBuilder()
.add(
"$vocabulary",
Json.createObjectBuilder().add("https://json-schema.org/draft/2020-12/vocab/core", true)
)
.build()
)
.keywordByName("$vocabulary"),
isPresent()
);
}

@Test
void should_return_empty_for_non_existing_keyword() {
assertThat(
new DefaultJsonSchema(
Json
.createObjectBuilder()
.add(
"$vocabulary",
Json.createObjectBuilder().add("https://json-schema.org/draft/2020-12/vocab/core", true)
)
.build()
)
.keywordByName("type"),
isEmpty()
);
}
}
Loading