-
Notifications
You must be signed in to change notification settings - Fork 167
Validator: Support for JSON Schema versions 2019-09 and 2020-12 #2225
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
ae65d4b
feat: validator Support for JSON Schema versions 2019-09 and 2020-12
predic8 71c61d9
refactor: minor
predic8 4e1b13e
refactor: minor
predic8 becd94e
refactor: minor
predic8 69e9de5
Merge branch 'master' into validator-json-schema-parser-migration
predic8 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
41 changes: 41 additions & 0 deletions
41
.../com/predic8/membrane/core/interceptor/schemavalidation/json/JSONSchemaVersionParser.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| /* Copyright 2025 predic8 GmbH, www.predic8.com | ||
|
|
||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
| you may not use this file except in compliance with the License. | ||
| You may obtain a copy of the License at | ||
|
|
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. */ | ||
|
|
||
| package com.predic8.membrane.core.interceptor.schemavalidation.json; | ||
|
|
||
| import com.networknt.schema.*; | ||
| import com.predic8.membrane.core.util.*; | ||
| import org.jetbrains.annotations.*; | ||
|
|
||
| import static com.networknt.schema.SchemaId.*; | ||
|
|
||
| public class JSONSchemaVersionParser { | ||
|
|
||
| public static SpecVersion.VersionFlag parse(String version) { | ||
| return SpecVersion.VersionFlag.fromId(aliasToSpecId(version)).get(); | ||
| } | ||
|
predic8 marked this conversation as resolved.
|
||
|
|
||
| static @NotNull String aliasToSpecId(String alias) { | ||
| if (alias == null) | ||
| throw new ConfigurationException("Unknown JSON Schema version: " + alias); | ||
| return switch (alias) { | ||
| case "04","draft-04" -> V4; | ||
| case "06","draft-06" -> V6; | ||
| case "07","draft-07" -> V7; | ||
| case "2019-09" -> V201909; | ||
| case "2020-12" -> V202012; | ||
| default -> throw new ConfigurationException("Unknown JSON Schema version: " + alias); | ||
| }; | ||
| } | ||
| } | ||
181 changes: 181 additions & 0 deletions
181
.../com/predic8/membrane/core/interceptor/schemavalidation/json/JSONYAMLSchemaValidator.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,181 @@ | ||
| /* Copyright 2012 predic8 GmbH, www.predic8.com | ||
|
|
||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
| you may not use this file except in compliance with the License. | ||
| You may obtain a copy of the License at | ||
|
|
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. */ | ||
|
|
||
| package com.predic8.membrane.core.interceptor.schemavalidation.json; | ||
|
|
||
| import com.github.fge.jsonschema.*; | ||
| import com.networknt.schema.*; | ||
| import com.predic8.membrane.core.exchange.*; | ||
| import com.predic8.membrane.core.http.*; | ||
| import com.predic8.membrane.core.interceptor.Interceptor.*; | ||
| import com.predic8.membrane.core.interceptor.*; | ||
| import com.predic8.membrane.core.interceptor.schemavalidation.*; | ||
| import com.predic8.membrane.core.interceptor.schemavalidation.ValidatorInterceptor.*; | ||
| import com.predic8.membrane.core.resolver.*; | ||
| import org.jetbrains.annotations.*; | ||
| import org.slf4j.*; | ||
|
|
||
| import java.nio.charset.*; | ||
| import java.util.*; | ||
| import java.util.concurrent.atomic.*; | ||
|
|
||
| import static com.networknt.schema.InputFormat.JSON; | ||
| import static com.predic8.membrane.core.exceptions.ProblemDetails.*; | ||
| import static com.predic8.membrane.core.interceptor.Outcome.*; | ||
| import static java.nio.charset.StandardCharsets.*; | ||
|
|
||
| public class JSONYAMLSchemaValidator extends AbstractMessageValidator { | ||
|
|
||
| private static final Logger log = LoggerFactory.getLogger(JSONYAMLSchemaValidator.class); | ||
|
|
||
| private final Resolver resolver; | ||
| private final String jsonSchema; | ||
| private final FailureHandler failureHandler; | ||
|
|
||
| private final AtomicLong valid = new AtomicLong(); | ||
| private final AtomicLong invalid = new AtomicLong(); | ||
| private final SpecVersion.VersionFlag schemaId; | ||
|
|
||
| /** | ||
| * JsonSchemaFactory instances are thread-safe provided its configuration is not modified. | ||
| */ | ||
| JsonSchemaFactory jsonSchemaFactory; | ||
|
|
||
| SchemaValidatorsConfig config; | ||
|
|
||
| /** | ||
| * JsonSchema instances are thread-safe provided its configuration is not modified. | ||
| */ | ||
| JsonSchema schema; | ||
|
|
||
| public JSONYAMLSchemaValidator(Resolver resolver, String jsonSchema, FailureHandler failureHandler, String schemaVersion) { | ||
| this.resolver = resolver; | ||
| this.jsonSchema = jsonSchema; | ||
| this.failureHandler = failureHandler; | ||
| this.schemaId = JSONSchemaVersionParser.parse( schemaVersion); | ||
| } | ||
|
|
||
| public JSONYAMLSchemaValidator(Resolver resolver, String jsonSchema, FailureHandler failureHandler) { | ||
| this(resolver, jsonSchema, failureHandler, "2020-12"); | ||
| } | ||
|
|
||
| @Override | ||
| public String getName() { | ||
| return "JSON Schema Validator"; | ||
| } | ||
|
|
||
| @Override | ||
| public void init() { | ||
| super.init(); | ||
|
|
||
| jsonSchemaFactory = JsonSchemaFactory.getInstance(schemaId, builder -> | ||
| builder.schemaLoaders(loaders -> loaders.add(new MembraneSchemaLoader(resolver))) | ||
| // builder.schemaMappers(schemaMappers -> schemaMappers.mapPrefix("https://www.example.org/", "classpath:/")) | ||
| ); | ||
|
|
||
| SchemaValidatorsConfig.Builder builder = SchemaValidatorsConfig.builder(); | ||
| // By default the JDK regular expression implementation which is not ECMA 262 compliant is used | ||
| // Note that setting this requires including optional dependencies | ||
| // builder.regularExpressionFactory(GraalJSRegularExpressionFactory.getInstance()); | ||
| // builder.regularExpressionFactory(JoniRegularExpressionFactory.getInstance()); | ||
| config = builder.build(); | ||
|
|
||
| // If the schema data does not specify an $id the absolute IRI of the schema location will be used as the $id. | ||
| schema= jsonSchemaFactory.getSchema(SchemaLocation.of( jsonSchema), config); | ||
| schema.initializeValidators(); | ||
|
|
||
| } | ||
|
|
||
| public Outcome validateMessage(Exchange exc, Flow flow) throws Exception { | ||
| return validateMessage(exc, flow, UTF_8); | ||
| } | ||
|
|
||
| public Outcome validateMessage(Exchange exc, Flow flow, Charset ignored) throws Exception { | ||
|
|
||
| Set<ValidationMessage> assertions = schema.validate(exc.getMessage(flow).getBodyAsStringDecoded(), JSON); | ||
|
|
||
| if (assertions.isEmpty()) { | ||
| valid.incrementAndGet(); | ||
| return CONTINUE; | ||
| } | ||
| invalid.incrementAndGet(); | ||
|
|
||
|
|
||
| log.debug("Validation failed: {}", assertions); | ||
|
|
||
| List<Map<String, Object>> mapForProblemDetails = getMapForProblemDetails(assertions); | ||
| failureHandler.handleFailure(mapForProblemDetails.toString(), exc); | ||
|
|
||
| user(false, getName()) | ||
| .title(getErrorTitle()) | ||
| .addSubType("validation") | ||
| .component(getName()) | ||
| .internal("flow", flow.name()) | ||
| .internal("errors", mapForProblemDetails) | ||
| .buildAndSetResponse(exc); | ||
|
|
||
| return ABORT; | ||
| } | ||
|
|
||
| private @NotNull List<Map<String, Object>> getMapForProblemDetails(Set<ValidationMessage> assertions) { | ||
| return assertions.stream().map(this::validationMessageToProblemDetailsMap).toList(); | ||
| } | ||
|
|
||
| private @NotNull Map<String, Object> validationMessageToProblemDetailsMap(ValidationMessage vm) { | ||
| Map<String, Object> m = new LinkedHashMap<>(); | ||
| m.put("message", vm.getMessage()); | ||
| m.put("code", vm.getCode()); | ||
| m.put("key", vm.getMessageKey()); | ||
| if (vm.getDetails() != null) | ||
| m.put("details", vm.getDetails()); | ||
| m.put("type", vm.getType()); | ||
| m.put("error", vm.getError()); | ||
| m.put("pointer", getPointer(vm.getEvaluationPath())); | ||
| m.put("node", vm.getInstanceNode()); | ||
| return m; | ||
| } | ||
|
|
||
| private String getPointer(JsonNodePath evaluationPath) { | ||
| if (evaluationPath == null || evaluationPath.getNameCount() == 0) { | ||
| return ""; | ||
| } | ||
|
|
||
| StringBuilder sb = new StringBuilder(); | ||
| for (int i = 0; i < evaluationPath.getNameCount(); i++) { | ||
| sb.append('/'); | ||
| String part = evaluationPath.getName(i); | ||
|
|
||
| // escape according to RFC 6901 | ||
| part = part.replace("~", "~0").replace("/", "~1"); | ||
|
|
||
| sb.append(part); | ||
| } | ||
| return sb.toString(); | ||
| } | ||
|
|
||
| @Override | ||
| public long getValid() { | ||
| return valid.get(); | ||
| } | ||
|
|
||
| @Override | ||
| public long getInvalid() { | ||
| return invalid.get(); | ||
| } | ||
|
|
||
| @Override | ||
| public String getErrorTitle() { | ||
| return "JSON validation failed"; | ||
| } | ||
| } |
33 changes: 33 additions & 0 deletions
33
...ava/com/predic8/membrane/core/interceptor/schemavalidation/json/MembraneSchemaLoader.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| /* Copyright 2025 predic8 GmbH, www.predic8.com | ||
|
|
||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
| you may not use this file except in compliance with the License. | ||
| You may obtain a copy of the License at | ||
|
|
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. */ | ||
|
|
||
| package com.predic8.membrane.core.interceptor.schemavalidation.json; | ||
|
|
||
| import com.networknt.schema.*; | ||
| import com.networknt.schema.resource.*; | ||
| import com.predic8.membrane.core.resolver.*; | ||
|
|
||
| public class MembraneSchemaLoader implements SchemaLoader { | ||
|
|
||
| private final Resolver resolver; | ||
|
|
||
| public MembraneSchemaLoader(Resolver resolver) { | ||
| this.resolver = resolver; | ||
| } | ||
|
|
||
| @Override | ||
| public InputStreamSource getSchema(AbsoluteIri absoluteIri) { | ||
| return () -> resolver.resolve(absoluteIri.toString()); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.