SchemaCatalogAwareJsonSchemaValidator { public void validate(final String envelopeJson, final String actionName, final Optional<MediaType> mediaTypeOptional) { mediaTypeOptional.ifPresent(mediaType -> doValidate(envelopeJson, actionName, mediaType)); }  void validate(final String envelopeJson, final String actionName, final Optional<MediaType> mediaTypeOptional);  }
@Test public void shouldLoadTheCorrectSchemaUsingTheCatalogServiceAndValidate() throws Exception { final String uri = "http: 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); schemaCatalogAwareJsonSchemaValidator.validate(envelopeJson, actionName, of(mediaType)); verify(schema).validate(payload); verifyZeroInteractions(fileBasedJsonSchemaValidator); }
@Test public void shouldFallBackToFileBasedSchemaValidationIfNoSchemaFoundInTheCatalogCache() throws Exception { final String uri = "http: 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\"}"; when(schemaIdMappingCache.schemaIdFor(mediaType)).thenReturn(schemaId); when(schemaCatalogService.findSchema(uri)).thenReturn(empty()); schemaCatalogAwareJsonSchemaValidator.validate(envelopeJson, actionName, of(mediaType)); verify(fileBasedJsonSchemaValidator).validateWithoutSchemaCatalog(envelopeJson, actionName); verifyZeroInteractions(payloadExtractor); }
@Test public void shouldThrowExceptionIfSchemaValidationFails() { final String uri = "http: 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))); } }