JsonSchemaChecker implements ConditionChecker { @Override public boolean checkCondition(final WilmaHttpRequest request, final ParameterList parameters) { boolean result = true; String schemaString = parameters.get(SCHEMA); String isSchemaVolatileString = parameters.get(IS_SCHEMA_VOLATILE); boolean isSchemaVolatile = isSchemaVolatileString == null || isSchemaVolatileString.compareToIgnoreCase("true") == 0; Schema jsonSchema; try { if (!isSchemaVolatile && schemaMap.containsKey(schemaString)) { jsonSchema = schemaMap.get(schemaString); } else { jsonSchema = readTemplateAsJsonSchemaFromFileSystem(schemaString); if (!isSchemaVolatile) { schemaMap.put(schemaString, jsonSchema); } } } catch (Exception e) { throw new StubConfigJsonSchemaException("Cannot load: " + schemaString + " as Json Schema to check the messages, pls fix the configuration."); } JSONObject jsonToBeValidated = null; try { InputStream stream = new ByteArrayInputStream(request.getBody().getBytes(StandardCharsets.UTF_8.name())); jsonToBeValidated = new JSONObject(new JSONTokener(stream)); } catch (JSONException | IOException e) { result = false; } if (result) { try { jsonSchema.validate(jsonToBeValidated); } catch (ValidationException e) { result = false; } } return result; }  @Override boolean checkCondition(final WilmaHttpRequest request, final ParameterList parameters);  }
@Test public void testCheckConditionShouldPassWhenJsonHasProperParameter() { givenExpectations("JsonSchemaCheckerTestSchema.json", "false"); givenWilmaRequest("{\"person\":{\"name\":\"Wilma\",\"age\":20}}"); boolean matches = underTest.checkCondition(request, parameters); assertTrue(matches); }
@Test public void testCheckConditionShouldFailWhenJsonHasNoSuchParameter() { givenExpectations("JsonSchemaCheckerTestSchema.json", "false"); givenWilmaRequest("{\"person\":{\"name\":\"Wilma\",\"birthDate\":20}}"); boolean matches = underTest.checkCondition(request, parameters); assertFalse(matches); }
@Test public void testCheckConditionShouldFailWhenJsonHasMoreParameters() { givenExpectations("JsonSchemaCheckerTestSchema.json", "false"); givenWilmaRequest("{\"person\":{\"name\":\"Wilma\",\"age\":20,\"birthDate\":\"2018-08-23\"}}"); boolean matches = underTest.checkCondition(request, parameters); assertFalse(matches); }
@Test public void testCheckConditionShouldFailWhenRequestIsNotJson() { givenExpectations("JsonSchemaCheckerTestSchema.json", "false"); givenWilmaRequest("<request><name>Wilma</name><age>2></age></request>"); boolean matches = underTest.checkCondition(request, parameters); assertFalse(matches); }