org.everit.json.schema.ValidationException Java Examples

The following examples show how to use org.everit.json.schema.ValidationException. 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: ExceptionMap.java    From daq with Apache License 2.0 7 votes vote down vote up
private static ErrorTree format(Throwable e, final String prefix, final String indent) {
  final ErrorTree errorTree = new ErrorTree();
  errorTree.prefix = prefix;
  errorTree.message = e.getMessage();
  final String newPrefix = prefix + indent;
  if (e instanceof ExceptionMap) {
    if (e.getCause() != null) {
      errorTree.child = format(e.getCause(), newPrefix, indent);
    }
    ((ExceptionMap) e).forEach(
        (key, sub) -> errorTree.children.put(key, format(sub, newPrefix, indent)));
  } else if (e instanceof ValidationException) {
    ((ValidationException) e).getCausingExceptions().forEach(
        sub -> errorTree.children.put(sub.getMessage(), format(sub, newPrefix, indent)));
  } else if (e.getCause() != null) {
    errorTree.child = format(e.getCause(), newPrefix, indent);
  }
  if (errorTree.children.isEmpty()) {
    errorTree.children = null;
  }
  if (errorTree.child == null && errorTree.children == null && errorTree.message == null) {
    errorTree.message = e.toString();
  }
  return errorTree;
}
 
Example #2
Source File: ParsePayload.java    From gcp-ingestion with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public Result<PCollection<PubsubMessage>, PubsubMessage> expand(
    PCollection<PubsubMessage> messages) {
  return messages.apply(FlatMapElements.into(TypeDescriptor.of(PubsubMessage.class)) //
      .via(new Fn()) //
      .exceptionsInto(TypeDescriptor.of(PubsubMessage.class)) //
      .exceptionsVia((WithFailures.ExceptionElement<PubsubMessage> ee) -> {
        try {
          throw ee.exception();
        } catch (IOException | SchemaNotFoundException | ValidationException
            | MessageScrubberException e) {
          return FailureMessage.of(ParsePayload.class.getSimpleName(), //
              ee.element(), //
              ee.exception());
        }
      }));
}
 
Example #3
Source File: DecryptPioneerPayloads.java    From gcp-ingestion with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public Result<PCollection<PubsubMessage>, PubsubMessage> expand(
    PCollection<PubsubMessage> messages) {
  return messages.apply(FlatMapElements.into(TypeDescriptor.of(PubsubMessage.class)) //
      .via(new Fn()) //
      .exceptionsInto(TypeDescriptor.of(PubsubMessage.class)) //
      .exceptionsVia((WithFailures.ExceptionElement<PubsubMessage> ee) -> {
        try {
          throw ee.exception();
        } catch (IOException | JoseException | ValidationException e) {
          return FailureMessage.of(DecryptPioneerPayloads.class.getSimpleName(), //
              ee.element(), //
              ee.exception());
        }
      }));
}
 
Example #4
Source File: CommonGTest.java    From bdt with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatchJsonToSchema() throws Exception {
    ThreadProperty.set("class", this.getClass().getCanonicalName());
    CommonG commong = new CommonG();
    String schema = "{\"type\": \"object\",\"additionalProperties\": false,\"properties\": {\"serviceId\": {\"description\": \"Service ID of the Service\",\"type\": \"string\",\"readOnly\": false,\"pattern\": \"(.*)(jumanji-)(.+)+$\",\"examples\": [\"jumanji-\"],\"title\": \"Service ID of the Service\",\"default\": \"jumanji-\"}},\"taskcfgAllKafkaReplicaLagTimeMaxMs\": {\"description\": \"If a follower hasn't sent any fetch requests or hasn't consumed up to the leaders log end offset for at least this time, the leader will remove the follower from isr\",\"readOnly\": false,\"default\": 10000,\"type\": \"number\",\"title\": \"Lag time max (ms)\",\"level\": 1}}";
    String json = "{\"serviceId\":\"jumanji-\"}";

    JSONObject jsonschema = new JSONObject(schema);
    JSONObject jsondeploy = new JSONObject(json);

    try {
        boolean matches = commong.matchJsonToSchema(jsonschema,jsondeploy);
        assertThat(matches).as("Unexpected situation, exception should have been triggered").isTrue();
    } catch (ValidationException valEx){
        assertThat(valEx.getClass().toString()).as("Unexpected exception").isEqualTo(ValidationException.class.toString());
    }
}
 
Example #5
Source File: CapabilitySchemaValidator.java    From AppiumTestDistribution with GNU General Public License v3.0 6 votes vote down vote up
public void validateCapabilitySchema(JSONObject capability) {
    try {
        isPlatformInEnv();
        InputStream inputStream = getClass().getResourceAsStream(getPlatform());
        JSONObject rawSchema = new JSONObject(new JSONTokener(inputStream));
        Schema schema = SchemaLoader.load(rawSchema);
        schema.validate(new JSONObject(capability.toString()));
        validateRemoteHosts();
    } catch (ValidationException e) {
        if (e.getCausingExceptions().size() > 1) {
            e.getCausingExceptions().stream()
                .map(ValidationException::getMessage)
                .forEach(System.out::println);
        } else {
            LOGGER.info(e.getErrorMessage());
        }

        throw new ValidationException("Capability json provided is missing the above schema");
    }
}
 
Example #6
Source File: ConfigurationPropagationTest.java    From json-schema with Apache License 2.0 6 votes vote down vote up
@Test
public void configurationPropagationTest() throws URISyntaxException {
    SchemaLoader loader = SchemaLoader.builder()
            .schemaClient(SchemaClient.classPathAwareClient())
            .nullableSupport(true)
            .useDefaults(true)
            .registerSchemaByURI(new URI("urn:uuid:85946d9c-b896-496c-a7ac-6835f4b59f63"), LOADER.readObj("schema-by-urn.json"))
            .addFormatValidator(new CustomFormatValidatorTest.EvenCharNumValidator())
            .schemaJson(LOADER.readObj("schema.json"))
            .build();
    Schema actual = loader.load().build();
    JSONObject instance = LOADER.readObj("instance.json");
    try {
        actual.validate(instance);
        fail("did not throw validation exception");
    } catch (ValidationException e) {
        assertThat(e.toJSON(), sameJsonAs(LOADER.readObj("expected-exception.json")));
    }
    assertEquals(42, instance.get("propWithDefault"));
}
 
Example #7
Source File: Validator.java    From daq with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  Validator validator = new Validator();
  try {
    System.out.println(ServiceOptions.CREDENTIAL_ENV_NAME + "=" +
        System.getenv(ServiceOptions.CREDENTIAL_ENV_NAME));
    if (args.length < 3 || args.length > 4) {
      throw new IllegalArgumentException("Args: schema target inst_name [site]");
    }
    validator.setSchemaSpec(args[0]);
    String targetSpec = args[1];
    String instName = args[2];
    if (args.length >= 4) {
      validator.setSiteDir(args[3]);
    }
    if (targetSpec.startsWith(PUBSUB_PREFIX)) {
      String topicName = targetSpec.substring(PUBSUB_PREFIX.length());
      validator.validatePubSub(instName, topicName);
    } else {
      validator.validateFilesOutput(targetSpec);
    }
  } catch (ExceptionMap | ValidationException processingException) {
    System.exit(2);
  } catch (Exception e) {
    e.printStackTrace();
    System.err.flush();
    System.exit(-1);
  }
  System.exit(0);
}
 
Example #8
Source File: JSONSchemaUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test(expected = ValidationException.class)
public void givenInvalidInput_whenValidating_thenInvalid() {

    JSONObject jsonSchema = new JSONObject(new JSONTokener(JSONSchemaUnitTest.class.getResourceAsStream("/schema.json")));
    JSONObject jsonSubject = new JSONObject(new JSONTokener(JSONSchemaUnitTest.class.getResourceAsStream("/product_invalid.json")));

    Schema schema = SchemaLoader.load(jsonSchema);
    schema.validate(jsonSubject);
}
 
Example #9
Source File: JsonValidator.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Validates that a JSON string conforms to a {@link Schema}.
 *
 * @param json the JSON string to check
 * @param schema the {@link Schema} that the JSON string should conform to
 * @throws JsonValidationException if the JSON doesn't conform to the schema, containing a {@link
 *     ConstraintViolation} for each message
 */
public void validate(String json, Schema schema) {
  try {
    schema.validate(new JSONObject(json));
  } catch (ValidationException validationException) {
    throw new JsonValidationException(
        validationException.getAllMessages().stream()
            .map(ConstraintViolation::new)
            .collect(toSet()));
  }
}
 
Example #10
Source File: ConditionalSchemaMismatchEventTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void equalsVerifier() {
    ValidationException exc1 = new ValidationException(TrueSchema.INSTANCE, "message", "keyword", "#/location");
    ValidationException exc2 = new ValidationException(FalseSchema.INSTANCE, "message", "keyword", "#/loca/tion");
    EqualsVerifier.forClass(ConditionalSchemaMismatchEvent.class)
            .withNonnullFields("keyword", "schema", "instance", "failure")
            .withRedefinedSuperclass()
            .withPrefabValues(ValidationException.class, exc1, exc2)
            .suppress(Warning.STRICT_INHERITANCE)
            .verify();
}
 
Example #11
Source File: EventToStringTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void combinedSchemaMismatchEventToString() {
    JSONObject expected = LOADER.readObj("combined-schema-mismatch.json");
    ValidationException exc = new ValidationException(COMBINED_SCHEMA, "message", "anyOf", "#/schema/location");
    CombinedSchemaMismatchEvent subject = new CombinedSchemaMismatchEvent(COMBINED_SCHEMA, FalseSchema.INSTANCE, INSTANCE, exc);

    JSONObject actual = new JSONObject(subject.toJSON(true, true).toString());

    assertThat(actual, sameJsonAs(expected));
}
 
Example #12
Source File: EventToStringTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void conditionalSchemaMismatchEvent() {
    JSONObject expected = LOADER.readObj("conditional-mismatch-if.json");
    ValidationException exc = new ValidationException(CONDITIONAL_SCHEMA, "message", "if", "#/schema/location");
    ConditionalSchemaMismatchEvent subject = new ConditionalSchemaMismatchEvent(CONDITIONAL_SCHEMA, INSTANCE, IF, exc);

    JSONObject actual = new JSONObject(subject.toString());
    assertThat(actual, sameJsonAs(expected));
}
 
Example #13
Source File: CombinedSchemaMismatchEventTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void equalsVerifier() {
    ValidationException exc1 = new ValidationException(TrueSchema.INSTANCE, "message", "keyword", "#/location");
    ValidationException exc2 = new ValidationException(FalseSchema.INSTANCE, "message", "keyword", "#/loca/tion");
    EqualsVerifier.forClass(CombinedSchemaMismatchEvent.class)
            .withNonnullFields("subSchema", "schema", "instance", "failure")
            .withRedefinedSuperclass()
            .withPrefabValues(ValidationException.class, exc1, exc2)
            .suppress(Warning.STRICT_INHERITANCE)
            .verify();
}
 
Example #14
Source File: DefinesPropertyTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void definesPropertyIfSubschemaMatchCountIsAcceptedByCriterion() {
    CombinedSchema subject = CombinedSchema.builder()
            .subschema(ObjectSchema.builder().addPropertySchema("a", BooleanSchema.INSTANCE).build())
            .subschema(ObjectSchema.builder().addPropertySchema("b", BooleanSchema.INSTANCE).build())
            .criterion((subschemaCount, matchingSubschemaCount) -> {
                if (matchingSubschemaCount == 1 && subschemaCount == 2) {
                    // dummy exception
                    throw new ValidationException(Object.class, new Object());
                }
            })
            .build();
    assertFalse(subject.definesProperty("a"));
}
 
Example #15
Source File: CustomFormatValidatorTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    SchemaLoader schemaLoader = SchemaLoader.builder()
            .schemaJson(baseSchemaJson())
            .addFormatValidator("evenlength", new EvenCharNumValidator())
            .build();
    try {
        schemaLoader.load().build().validate(loader.readObj("customformat-data.json"));
        Assert.fail("did not throw exception");
    } catch (ValidationException ve) {
    }
}
 
Example #16
Source File: SchemaEvolutionService.java    From nakadi with MIT License 5 votes vote down vote up
private void collectErrorMessages(final ValidationException e,
                                  final List<SchemaIncompatibility> incompatibilities) {
    if (e.getCausingExceptions().isEmpty()) {
        incompatibilities.add(
                new ForbiddenAttributeIncompatibility(e.getPointerToViolation(), e.getErrorMessage()));
    } else {
        e.getCausingExceptions()
                .forEach(causingException -> collectErrorMessages(causingException, incompatibilities));
    }
}
 
Example #17
Source File: SchemaEvolutionService.java    From nakadi with MIT License 5 votes vote down vote up
public List<SchemaIncompatibility> collectIncompatibilities(final JSONObject schemaJson) {
    final List<SchemaIncompatibility> incompatibilities = new ArrayList<>();

    try {
        metaSchema.validate(schemaJson);
    } catch (final ValidationException e) {
        collectErrorMessages(e, incompatibilities);
    }

    return incompatibilities;
}
 
Example #18
Source File: EventValidatorBuilder.java    From nakadi with MIT License 5 votes vote down vote up
private static void recursiveCollectErrors(final ValidationException e, final StringBuilder builder) {
    builder.append(e.getMessage());

    e.getCausingExceptions().forEach(causingException -> {
        builder.append("\n");
        recursiveCollectErrors(causingException, builder);
    });
}
 
Example #19
Source File: EventValidatorBuilder.java    From nakadi with MIT License 5 votes vote down vote up
private Optional<ValidationError> validateSchemaConformance(final Schema schema, final JSONObject evt) {
    try {
        schema.validate(evt);
        return Optional.empty();
    } catch (final ValidationException e) {
        final StringBuilder builder = new StringBuilder();
        recursiveCollectErrors(e, builder);
        return Optional.of(new ValidationError(builder.toString()));
    }
}
 
Example #20
Source File: JsonSchemaValidator.java    From yare with MIT License 5 votes vote down vote up
private SchemaValidationResults mapAsSchemaValidationResults(ValidationException e) {
    Set<SchemaValidationError> results = e.getCausingExceptions().stream()
            .map(ValidationException::getMessage)
            .map(SchemaValidationError::of)
            .collect(Collectors.toSet());
    return results.isEmpty()
            ? SchemaValidationResults.ofError(SchemaValidationError.of(e.getMessage()))
            : SchemaValidationResults.ofErrors(results);
}
 
Example #21
Source File: KeyStoreTest.java    From gcp-ingestion with Mozilla Public License 2.0 5 votes vote down vote up
@Test(expected = ValidationException.class)
public void testMetadataInvalidFormat() {
  String metadataLocation = Resources.getResource("pioneer/metadata-invalid.json").getPath();
  KeyStore store = KeyStore.of(metadataLocation, false);
  // force the store to load
  store.getKey("*");
}
 
Example #22
Source File: DecryptAetIdentifiersTest.java    From gcp-ingestion with Mozilla Public License 2.0 5 votes vote down vote up
@Test(expected = ValidationException.class)
public void testForbiddenFieldsStructured() throws Exception {
  JsonValidator validator = new JsonValidator();
  byte[] data = Resources
      .toByteArray(Resources.getResource("account-ecosystem/structured.schema.json"));
  Schema fxaSchema = JSONSchemaStore.readSchema(data);
  ObjectNode json = Json.asObjectNode(ImmutableMap.<String, Object>builder()
      .put("ecosystem_client_id", "3ed15efab7e94757bf9e9ef5e844ada2")
      .put("ecosystem_device_id", "7ab4e373ce434b848a9d0946e388fee9")
      .put("ecosystem_user_id", "aab4e373ce434b848a9d0946e388fdd3").build());
  validator.validate(fxaSchema, json);
}
 
Example #23
Source File: Validator.java    From daq with Apache License 2.0 5 votes vote down vote up
private void validateFilesOutput(String targetSpec) {
  try {
    validateFiles(schemaSpec, targetSpec);
  } catch (ExceptionMap | ValidationException processingException) {
    ErrorTree errorTree = ExceptionMap.format(processingException, ERROR_FORMAT_INDENT);
    errorTree.write(System.err);
    throw processingException;
  }
}
 
Example #24
Source File: JsonSchemaTests.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private boolean validateJson(String source, Schema schema) throws FileNotFoundException, IOException {
    JSONObject jo = new JSONObject(source); // jo = (JsonObject) new com.google.gson.JsonParser().parse(source);
    try {
      schema.validate(jo);
      return true;
    } catch (ValidationException e) {
      System.out.println(e.getMessage());
      return false;
    }
//        e.getCausingExceptions().stream()
////            .map(ValidationException::getMessage)
////            .forEach(System.out::println);
  }
 
Example #25
Source File: ConditionalSchemaMismatchEvent.java    From json-schema with Apache License 2.0 4 votes vote down vote up
public ConditionalSchemaMismatchEvent(ConditionalSchema schema, Object instance, Keyword keyword, ValidationException failure) {
    super(schema, instance, keyword);
    this.failure = failure;
}
 
Example #26
Source File: ConditionalSchemaMismatchEvent.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Override public ValidationException getFailure() {
    return failure;
}
 
Example #27
Source File: CombinedSchemaMismatchEvent.java    From json-schema with Apache License 2.0 4 votes vote down vote up
public CombinedSchemaMismatchEvent(CombinedSchema schema, Schema subSchema, Object instance, ValidationException failure) {
    super(schema, subSchema, instance);
    this.failure = failure;
}
 
Example #28
Source File: CombinedSchemaMismatchEvent.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Override public ValidationException getFailure() {
    return failure;
}
 
Example #29
Source File: DecryptPioneerPayloads.java    From gcp-ingestion with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public Iterable<PubsubMessage> apply(PubsubMessage message)
    throws IOException, JoseException, ValidationException {
  message = PubsubConstraints.ensureNonNull(message);

  if (keyStore == null) {
    // If configured resources aren't available, this throws UncheckedIOException;
    // this is unretryable so we allow it to bubble up and kill the worker and eventually fail
    // the pipeline.
    keyStore = KeyStore.of(metadataLocation.get(), kmsEnabled.get());
  }

  if (validator == null) {
    validator = new JsonValidator();
    byte[] data = Resources
        .toByteArray(Resources.getResource("telemetry.pioneer-study.4.schema.json"));
    envelopeSchema = JSONSchemaStore.readSchema(data);
  }

  ObjectNode json = Json.readObjectNode(message.getPayload());
  validator.validate(envelopeSchema, json);
  JsonNode payload = json.get(FieldName.PAYLOAD);

  String encryptionKeyId = payload.get(ENCRYPTION_KEY_ID).asText();
  PrivateKey key = keyStore.getKey(encryptionKeyId);
  if (key == null) {
    // Is this really an IOException?
    throw new IOException(String.format("encryptionKeyId not found: %s", encryptionKeyId));
  }

  final byte[] decrypted = decrypt(key, payload.get(ENCRYPTED_DATA).asText());

  byte[] payloadData;
  if (decompressPayload.get()) {
    payloadData = GzipUtil.maybeDecompress(decrypted);
  } else {
    // don't bother decompressing
    payloadData = decrypted;
  }

  // insert top-level metadata into the payload
  ObjectNode metadata = Json.createObjectNode();
  metadata.put(PIONEER_ID, payload.get(PIONEER_ID).asText());
  metadata.put(STUDY_NAME, payload.get(STUDY_NAME).asText());
  final byte[] merged = AddMetadata.mergedPayload(payloadData, Json.asBytes(metadata));

  // Redirect messages via attributes
  Map<String, String> attributes = new HashMap<String, String>(message.getAttributeMap());
  attributes.put(Attribute.DOCUMENT_NAMESPACE, payload.get(SCHEMA_NAMESPACE).asText());
  attributes.put(Attribute.DOCUMENT_TYPE, payload.get(SCHEMA_NAME).asText());
  attributes.put(Attribute.DOCUMENT_VERSION, payload.get(SCHEMA_VERSION).asText());
  return Collections.singletonList(new PubsubMessage(merged, attributes));
}
 
Example #30
Source File: Util.java    From configuration-as-code-plugin with MIT License 3 votes vote down vote up
/**
 * Validates a given jsonObject against the schema generated for the current live jenkins
 * instance.
 *
 * <p>Example Usage:</p>
 *  <pre>{@code
 *   assertThat(validateSchema(convertYamlFileToJson(this, "invalidSchemaConfig.yml")),
 *             contains("#/jenkins/numExecutors: expected type: Number, found: String"));
 *  }</pre>
 *
 *  <pre>{@code
 *   assertThat(validateSchema(convertYamlFileToJson(this, "validConfig.yml")),
 *             empty());
 *  }</pre>
 *
 * @param jsonSubject the json object that needs to be validated
 * @return a list of validation errors, empty list if no errors
 */
public static List<String> validateSchema(JSONObject jsonSubject) {
    try {
        returnSchema().validate(jsonSubject);
    } catch (ValidationException e) {
        return e.getAllMessages();
    } catch (Exception ie) {
        LOGGER.log(Level.WARNING, failureMessage, ie);
        return singletonList("Exception during test" + ie.getMessage());
    }
    return emptyList();
}