Search in sources :

Example 6 with ValidationException

use of org.everit.json.schema.ValidationException in project mule by mulesoft.

the class GlobalConfigLoader method initialiseGlobalConfig.

/**
 * Initialise the global config if not yet initialised.
 * <p>
 * Validates the provided configuration against a JSON schema
 */
private static void initialiseGlobalConfig() {
    Config config = ConfigFactory.load(GlobalConfigLoader.class.getClassLoader(), "mule-config", ConfigParseOptions.defaults().setSyntax(JSON), ConfigResolveOptions.defaults());
    Config muleRuntimeConfig = config.hasPath(CONFIG_ROOT_ELEMENT_NAME) ? config.getConfig(CONFIG_ROOT_ELEMENT_NAME) : null;
    if (muleRuntimeConfig == null) {
        mavenConfig = buildNullMavenConfig();
    } else {
        String effectiveConfigAsJson = muleRuntimeConfig.root().render(ConfigRenderOptions.concise().setJson(true).setComments(false));
        String prettyPrintConfig = muleRuntimeConfig.root().render(ConfigRenderOptions.defaults().setComments(true).setJson(true).setFormatted(true));
        try (InputStream schemaStream = GlobalConfigLoader.class.getClassLoader().getResourceAsStream(MULE_SCHEMA_JSON_LOCATION)) {
            JSONObject rawSchema = new JSONObject(new JSONTokener(schemaStream));
            Schema schema = SchemaLoader.load(rawSchema);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Using effective mule-config.json configuration: \n" + prettyPrintConfig);
            }
            schema.validate(new JSONObject(effectiveConfigAsJson));
            Config mavenConfig = muleRuntimeConfig.getConfig("maven");
            if (mavenConfig != null) {
                GlobalConfigLoader.mavenConfig = buildMavenConfig(mavenConfig);
            } else {
                GlobalConfigLoader.mavenConfig = buildNullMavenConfig();
            }
        } catch (ValidationException e) {
            LOGGER.info("Mule global config exception. Effective configuration is (config is a merge of MULE_HOME/conf/mule-config.json and system properties): \n " + prettyPrintConfig);
            throw new RuntimeGlobalConfigException(e);
        } catch (IOException e) {
            throw new RuntimeGlobalConfigException(createStaticMessage(format("resources %s missing from the runtime classpath", MULE_SCHEMA_JSON_LOCATION)), e);
        }
    }
}
Also used : JSONTokener(org.json.JSONTokener) RuntimeGlobalConfigException(org.mule.runtime.globalconfig.api.exception.RuntimeGlobalConfigException) ValidationException(org.everit.json.schema.ValidationException) JSONObject(org.json.JSONObject) Config(com.typesafe.config.Config) MavenConfigBuilder.buildMavenConfig(org.mule.runtime.globalconfig.internal.MavenConfigBuilder.buildMavenConfig) MavenConfigBuilder.buildNullMavenConfig(org.mule.runtime.globalconfig.internal.MavenConfigBuilder.buildNullMavenConfig) InputStream(java.io.InputStream) Schema(org.everit.json.schema.Schema) IOException(java.io.IOException)

Example 7 with ValidationException

use of org.everit.json.schema.ValidationException in project microservice_framework by CJSCommonPlatform.

the class FileBasedJsonSchemaValidatorTest method shouldThrowExceptionIfSchemaValidationFails.

@Test
public void shouldThrowExceptionIfSchemaValidationFails() throws Exception {
    final String actionName = "example.action-name";
    final String envelopeJson = "{\"envelope\": \"json\"}";
    final JSONObject payload = mock(JSONObject.class);
    final Schema schema = mock(Schema.class);
    when(payloadExtractor.extractPayloadFrom(envelopeJson)).thenReturn(payload);
    when(jsonSchemaLoader.loadSchema(actionName)).thenReturn(schema);
    doThrow(new ValidationException(schema, "", "", "")).when(schema).validate(payload);
    try {
        fileBasedJsonSchemaValidator.validateWithoutSchemaCatalog(envelopeJson, actionName);
        fail();
    } catch (final JsonSchemaValidationException e) {
        assertThat(e.getCause(), is(instanceOf(ValidationException.class)));
    }
}
Also used : ValidationException(org.everit.json.schema.ValidationException) JSONObject(org.json.JSONObject) Schema(org.everit.json.schema.Schema) Test(org.junit.Test)

Example 8 with ValidationException

use of org.everit.json.schema.ValidationException in project microservice_framework by CJSCommonPlatform.

the class SchemaCatalogAwareJsonSchemaValidatorTest method shouldThrowExceptionIfSchemaValidationFails.

@Test
public void shouldThrowExceptionIfSchemaValidationFails() {
    final String uri = "http://space.time.gov.uk/mind/command/api/initiate-warp-speed.json";
    final String actionName = "command.api.initiate-warp-speed";
    final Optional<String> schemaId = of(uri);
    final MediaType mediaType = new MediaType("application", "vnd.mind.command.initiate-warp-speed+json");
    final String envelopeJson = "{\"envelope\": \"json\"}";
    final Schema schema = mock(Schema.class);
    final JSONObject payload = mock(JSONObject.class);
    when(schemaIdMappingCache.schemaIdFor(mediaType)).thenReturn(schemaId);
    when(schemaCatalogService.findSchema(uri)).thenReturn(of(schema));
    when(payloadExtractor.extractPayloadFrom(envelopeJson)).thenReturn(payload);
    doThrow(new ValidationException(schema, "", "", "")).when(schema).validate(payload);
    try {
        schemaCatalogAwareJsonSchemaValidator.validate(envelopeJson, actionName, of(mediaType));
        fail();
    } catch (final JsonSchemaValidationException e) {
        assertThat(e.getCause(), is(instanceOf(ValidationException.class)));
    }
}
Also used : ValidationException(org.everit.json.schema.ValidationException) JSONObject(org.json.JSONObject) Schema(org.everit.json.schema.Schema) MediaType(uk.gov.justice.services.core.mapping.MediaType) Test(org.junit.Test)

Example 9 with ValidationException

use of org.everit.json.schema.ValidationException in project microservice_framework by CJSCommonPlatform.

the class EnvelopeValidatorTest method shouldHandleAValidationException.

@SuppressWarnings("deprecation")
@Test
public void shouldHandleAValidationException() throws Exception {
    final ValidationException validationException = new ValidationException("Ooops");
    final String actionName = "exaple.action-name";
    final String payloadJson = "{\"some\": \"json\"}";
    final Optional<MediaType> mediaType = of(new MediaType("application/vnd.example.action-name+json"));
    final JsonEnvelope jsonEnvelope = mock(JsonEnvelope.class);
    final JsonValue payload = mock(JsonValue.class);
    when(jsonEnvelope.payload()).thenReturn(payload);
    when(objectMapper.writeValueAsString(payload)).thenReturn(payloadJson);
    when(jsonEnvelope.toObfuscatedDebugString()).thenReturn("debug-json");
    doThrow(validationException).when(jsonSchemaValidator).validate(payloadJson, actionName, mediaType);
    envelopeValidator.validate(jsonEnvelope, actionName, mediaType);
    verify(envelopeValidationExceptionHandler).handle(exceptionArgumentCaptor.capture());
    final EnvelopeValidationException envelopeValidationException = exceptionArgumentCaptor.getValue();
    assertThat(envelopeValidationException.getMessage(), is("Message not valid against schema: \ndebug-json"));
    assertThat(envelopeValidationException.getCause(), is(validationException));
}
Also used : ValidationException(org.everit.json.schema.ValidationException) JsonValue(javax.json.JsonValue) MediaType(uk.gov.justice.services.core.mapping.MediaType) JsonEnvelope(uk.gov.justice.services.messaging.JsonEnvelope) Test(org.junit.Test)

Example 10 with ValidationException

use of org.everit.json.schema.ValidationException in project microservice_framework by CJSCommonPlatform.

the class SubscriptionDescriptorFileValidatorTest method shouldThrowExceptionOnInCorrectSubscriptionYaml.

@Test
public void shouldThrowExceptionOnInCorrectSubscriptionYaml() {
    try {
        final SubscriptionDescriptorFileValidator subscriptionDescriptorFileValidator = new SubscriptionDescriptorFileValidator(new YamlFileToJsonObjectConverter());
        subscriptionDescriptorFileValidator.validate(getFromClasspath("incorrect-subscription.yaml"));
        fail();
    } catch (ValidationException e) {
        assertThat(e, is(instanceOf(ValidationException.class)));
        assertThat(e.getMessage(), is("#/subscription_descriptor: required key [spec_version] not found"));
    }
}
Also used : ValidationException(org.everit.json.schema.ValidationException) SubscriptionDescriptorFileValidator(uk.gov.justice.subscription.file.read.SubscriptionDescriptorFileValidator) YamlFileToJsonObjectConverter(uk.gov.justice.subscription.file.read.YamlFileToJsonObjectConverter) Test(org.junit.Test)

Aggregations

ValidationException (org.everit.json.schema.ValidationException)12 JSONObject (org.json.JSONObject)7 Test (org.junit.Test)6 Schema (org.everit.json.schema.Schema)5 IOException (java.io.IOException)3 MediaType (uk.gov.justice.services.core.mapping.MediaType)2 JsonEnvelope (uk.gov.justice.services.messaging.JsonEnvelope)2 SubscriptionDescriptorFileValidator (uk.gov.justice.subscription.file.read.SubscriptionDescriptorFileValidator)2 YamlFileToJsonObjectConverter (uk.gov.justice.subscription.file.read.YamlFileToJsonObjectConverter)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 YAMLFactory (com.fasterxml.jackson.dataformat.yaml.YAMLFactory)1 Jdk8Module (com.fasterxml.jackson.datatype.jdk8.Jdk8Module)1 ParameterNamesModule (com.fasterxml.jackson.module.paramnames.ParameterNamesModule)1 Config (com.typesafe.config.Config)1 InputStream (java.io.InputStream)1 NoSuchFileException (java.nio.file.NoSuchFileException)1 JsonValue (javax.json.JsonValue)1 Response (javax.ws.rs.core.Response)1 ModelId (org.eclipse.vorto.repository.api.ModelId)1 Description (org.hamcrest.Description)1