org.everit.json.schema.SchemaException Java Examples

The following examples show how to use org.everit.json.schema.SchemaException. 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: SchemaExtractor.java    From json-schema with Apache License 2.0 6 votes vote down vote up
private Schema.Builder<?> loadForExplicitType(String typeString) {
    switch (typeString) {
    case "string":
        return buildStringSchema().requiresString(true);
    case "integer":
        return buildNumberSchema().requiresInteger(true);
    case "number":
        return buildNumberSchema();
    case "boolean":
        return BooleanSchema.builder();
    case "null":
        return NullSchema.builder();
    case "array":
        return buildArraySchema();
    case "object":
        return buildObjectSchema();
    default:
        throw new SchemaException(schemaJson.ls.locationOfCurrentObj(), format("unknown type: [%s]", typeString));
    }
}
 
Example #2
Source File: JSONPointer.java    From json-schema with Apache License 2.0 6 votes vote down vote up
/**
 * Queries from {@code document} based on this pointer.
 *
 * @return a DTO containing the query result and the root document containing the query result.
 * @throws IllegalArgumentException
 *         if the pointer does not start with {@code '#'}.
 */
public QueryResult query() {
    JSONObject document = documentProvider.get();
    if (fragment.isEmpty()) {
        return new QueryResult(document, document);
    }
    String[] path = fragment.split("/");
    if ((path[0] == null) || !path[0].startsWith("#")) {
        throw new IllegalArgumentException("JSON pointers must start with a '#'");
    }
    try {
        JSONObject result = queryFrom(document);
        return new QueryResult(document, result);
    } catch (JSONPointerException e) {
        throw new SchemaException(e.getMessage());
    }
}
 
Example #3
Source File: SchemaLoaderTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void unknownTypeException() {
    try {
        SchemaLoader.load(get("unknownType"));
        fail("did not throw exception for unknown type");
    } catch (SchemaException actual) {
        SchemaException expected = new SchemaException("#/properties/prop", "unknown type: [integgggger]");
        assertEquals(expected, actual);
    }
}
 
Example #4
Source File: JsonPointerEvaluator.java    From json-schema with Apache License 2.0 5 votes vote down vote up
/**
 * Queries from {@code document} based on this pointer.
 *
 * @return a DTO containing the query result and the root document containing the query result.
 * @throws IllegalArgumentException
 *         if the pointer does not start with {@code '#'}.
 */
public QueryResult query() {
    JsonObject document = documentProvider.get();
    if (fragment.isEmpty()) {
        return new QueryResult(document, document);
    }
    JsonObject foundById = ReferenceLookup.lookupObjById(document, fragment);
    if (foundById != null) {
        return new QueryResult(document, foundById);
    }
    String[] path = fragment.split("/");
    if ((path[0] == null) || !path[0].startsWith("#")) {
        throw new IllegalArgumentException("JSON pointers must start with a '#'");
    }
    try {
        JsonValue result;
        LinkedList<String> tokens = new LinkedList<>(asList(path));
        tokens.poll();
        if (tokens.isEmpty()) {
            result = document;
        } else {
            result = queryFrom(document, tokens);
        }
        return new QueryResult(document, result);
    } catch (JSONPointerException e) {
        throw new SchemaException(e.getMessage());
    }
}
 
Example #5
Source File: SchemaLoaderTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void unknownMetaSchemaException() {
    try {
        SchemaLoader.load(get("unknownMetaSchema"));
        fail("did not throw exception");
    } catch (SchemaException e) {
        assertEquals("#", e.getSchemaLocation());
    }
}
 
Example #6
Source File: JsonValueTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void multiplexerFailure() {
    exc.expect(SchemaException.class);
    exc.expectMessage("#: expected type is one of Boolean or String, found: Integer");
    INT.canBe(String.class, str -> {
    })
            .or(Boolean.class, bool -> {
            })
            .requireAny();
}
 
Example #7
Source File: JsonValueTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void multiplexFailureForNullValue() {
    exc.expect(SchemaException.class);
    exc.expectMessage("#: expected type is one of Boolean or String, found: null");
    withLs(JsonValue.of(null)).canBe(String.class, s -> {
    })
            .or(Boolean.class, b -> {
            })
            .requireAny();
}
 
Example #8
Source File: JsonValueTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void booleanCannotBeSchemaIfV4() {
    Consumer<JsonValue> ifSchema = spy(schemaConsumer());
    JsonValue subject = withLs(JsonValue.of(true));
    try {
        subject.canBeSchema(ifSchema).requireAny();
        fail("did not throw exception");
    } catch (SchemaException e) {
        assertEquals("#: expected type is one of JsonObject, found: Boolean", e.getMessage());
        verify(ifSchema, never()).accept(any());
    }
}
 
Example #9
Source File: JsonValueTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void canBeSchemaWithV6hasProperExceptionMessage() {
    Consumer<JsonValue> ifSchema = spy(schemaConsumer());
    JsonValue subject = asV6Value(42);
    try {
        subject.canBeSchema(ifSchema).requireAny();
    } catch (SchemaException e) {
        assertEquals("#: expected type is one of Boolean or JsonObject, found: Integer", e.getMessage());
    }
    verify(ifSchema, never()).accept(subject);
}
 
Example #10
Source File: LoadingStateTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateSchemaException() {
    LoadingState subject = emptySubject();
    SchemaException actual = subject.createSchemaException("message");
    assertEquals("#: message", actual.getMessage());
    assertEquals(JSONPointer.builder().build().toURIFragment(), actual.getSchemaLocation());
}
 
Example #11
Source File: LoadingStateTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void testChildForFailure_NotFound() {
    LoadingState ls = helloWorldObjState();
    try {
        ls.childFor("nonexistent");
        fail("did not throw exception for nonexistent key");
    } catch (SchemaException e) {
        SchemaException expected = new SchemaException("#", "key [nonexistent] not found");
        assertEquals(expected, e);
    }
}
 
Example #12
Source File: LoadingStateTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void testChildForArrayFailure_NotFound() {
    LoadingState subject = singleElemArrayState();
    try {
        subject.childFor(1);
        fail("did not throw exception");
    } catch (SchemaException e) {
        SchemaException expected = new SchemaException("#", "array index [1] is out of bounds");
        assertEquals(expected, e);
    }
}
 
Example #13
Source File: LoadingStateTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidArrayIndex() {
    try {
        singleElemArrayState().childFor("key");
        fail("did not throw exception");
    } catch (SchemaException e) {
        SchemaException expected = new SchemaException("#", "[key] is not an array index");
        assertEquals(expected, e);
    }
}
 
Example #14
Source File: JsonPointerEvaluatorTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test(expected = SchemaException.class)
public void sameDocumentNotFound() {
    JsonPointerEvaluator pointer = JsonPointerEvaluator.forDocument(rootSchemaJson, "#/definitions/NotFound");
    JsonObject actual = pointer.query().getQueryResult().requireObject();
    assertEquals("dummy schema at #/definitions/Bar", actual.require("description").requireString());
    assertEquals("http://localhost:1234/folder/", actual.ls.id.toString());
    assertEquals(new SchemaLocation(asList("definitions", "Bar")), actual.ls.pointerToCurrentObj);
}
 
Example #15
Source File: JsonPointerEvaluatorTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void schemaExceptionForInvalidURI() {
    try {
        SchemaClient schemaClient = mock(SchemaClient.class);
        JsonPointerEvaluator subject = JsonPointerEvaluator.forURL(schemaClient, "||||",
                createLoadingState(schemaClient, "#/definitions/Foo"));
        subject.query();
        fail("did not throw exception");
    } catch (SchemaException e) {
        assertThat(e.toJSON(), sameJsonAs(LOADER.readObj("pointer-eval-non-uri-failure.json")));
    }
}
 
Example #16
Source File: TypeBasedMultiplexerTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test(expected = SchemaException.class)
public void typeBasedMultiplexerFailure() {
    new TypeBasedMultiplexer("foo")
            .ifObject().then(o -> {
    })
            .ifIs(JSONArray.class).then(o -> {
    })
            .requireAny();
}
 
Example #17
Source File: SpecVersionDeductionTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
private void assertSchemaException(SchemaLoader.SchemaLoaderBuilder loaderBuilder) {
    try {
        loaderBuilder.build();
        fail("did not throw exception");
    } catch (SchemaException e) {
        assertEquals("#", e.getSchemaLocation());
    }
}
 
Example #18
Source File: JsonObjectTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void testRequireWithConsumerFailure() {
    expExc.expect(SchemaException.class);
    expExc.expectMessage("#: required key [aaa] not found");
    Consumer<JsonValue> consumer = mockConsumer();
    subject().require("aaa", consumer);
    verify(consumer, never()).accept(any());
}
 
Example #19
Source File: JsonValidator.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Loads JSON schema. The schema may contain remote references.
 *
 * @param schema String containing the JSON schema to load
 * @return loaded {@link Schema}
 * @throws InvalidJsonSchemaException if the schema fails to load
 */
public Schema loadSchema(String schema) {
  try {
    JSONObject rawSchema = new JSONObject(new JSONTokener(schema));
    return SchemaLoader.load(rawSchema);
  } catch (JSONException | SchemaException e) {
    throw new InvalidJsonSchemaException(e);
  }
}
 
Example #20
Source File: SchemaLoader.java    From json-schema with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param builder
 *         the builder containing the properties. Only {@link SchemaLoaderBuilder#id} is
 *         nullable.
 * @throws NullPointerException
 *         if any of the builder properties except {@link SchemaLoaderBuilder#id id} is
 *         {@code null}.
 */
public SchemaLoader(SchemaLoaderBuilder builder) {
    Object effectiveRootSchemaJson = builder.rootSchemaJson == null
            ? builder.schemaJson
            : builder.rootSchemaJson;
    Optional<String> schemaKeywordValue = extractSchemaKeywordValue(effectiveRootSchemaJson);
    SpecificationVersion specVersion;
    if (schemaKeywordValue.isPresent()) {
        try {
            specVersion = SpecificationVersion.getByMetaSchemaUrl(schemaKeywordValue.get());
        } catch (IllegalArgumentException e) {
            if (builder.specVersionIsExplicitlySet) {
                specVersion = builder.specVersion;
            } else {
                throw new SchemaException("#", "could not determine version");
            }
        }
    } else {
        specVersion = builder.specVersion;
    }
    this.config = new LoaderConfig(builder.schemaClient,
            builder.formatValidators,
            builder.schemasByURI,
            specVersion,
            builder.useDefaults,
            builder.nullableSupport,
            builder.regexpFactory);
    this.ls = new LoadingState(config,
            builder.pointerSchemas,
            effectiveRootSchemaJson,
            builder.schemaJson,
            builder.id,
            builder.pointerToCurrentObj,
            builder.subschemaRegistries);
}
 
Example #21
Source File: ProjectedJsonObjectTest.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Test(expected = SchemaException.class)
public void requireMappingFailsForHiddenKey() {
    createSubject().requireMapping("minimum", val -> true);
}
 
Example #22
Source File: JsonObject.java    From json-schema with Apache License 2.0 4 votes vote down vote up
private SchemaException failureOfMissingKey(String key) {
    return ls.createSchemaException(format("required key [%s] not found", key));
}
 
Example #23
Source File: ArraySchemaLoaderTest.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Test(expected = SchemaException.class)
public void invalidItemsArraySchema() {
    SchemaLoader.load(get("invalidItemsArraySchema"));
}
 
Example #24
Source File: ArraySchemaLoaderTest.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Test(expected = SchemaException.class)
public void invalidArrayItemSchema() {
    SchemaLoader.load(get("invalidArrayItemSchema"));
}
 
Example #25
Source File: ArraySchemaLoaderTest.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Test(expected = SchemaException.class)
public void invalidAdditionalItems() {
    SchemaLoader.load(get("invalidAdditionalItems"));
}
 
Example #26
Source File: JsonObjectTest.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Test
public void testRequireWithFunctionFailure() {
    expExc.expect(SchemaException.class);
    expExc.expectMessage("#: required key [aaa] not found");
    subject().requireMapping("aaa", val -> false);
}
 
Example #27
Source File: JsonValue.java    From json-schema with Apache License 2.0 4 votes vote down vote up
protected SchemaException multiplexFailure() {
    return ls.createSchemaException(typeOfValue(), actions.keySet());
}
 
Example #28
Source File: JsonValue.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Override
protected SchemaException multiplexFailure() {
    Set<Class<?>> expectedTypes = new HashSet<>(actions.keySet());
    expectedTypes.add(Boolean.class);
    return ls.createSchemaException(typeOfValue(), expectedTypes);
}
 
Example #29
Source File: TypeBasedMultiplexer.java    From json-schema with Apache License 2.0 4 votes vote down vote up
/**
 * Checks if the {@code obj} is an instance of any previously set classes (by {@link #ifIs(Class)}
 * or {@link #ifObject()}), performs the mapped action of found or throws with a
 * {@link SchemaException}.
 */
public void requireAny() {
    orElse(obj -> {
        throw new SchemaException(keyOfObj, new ArrayList<Class<?>>(actions.keySet()), obj);
    });
}
 
Example #30
Source File: LoadingState.java    From json-schema with Apache License 2.0 4 votes vote down vote up
SchemaException createSchemaException(String message) {
    return new SchemaException(locationOfCurrentObj(), message);
}