Skip to content

Commit

Permalink
Make JSON key for the record ID value configurable (#443)
Browse files Browse the repository at this point in the history
  • Loading branch information
fsteeg committed Sep 22, 2022
1 parent f182204 commit 8a1ceb5
Showing 1 changed file with 12 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -45,21 +45,24 @@
*/
@Description("Validate JSON against a given schema, send only valid input to the receiver. Pass the schema location to validate against. " +
"Set 'schemaRoot' for resolving sub-schemas referenced in '$id' or '$ref' (defaults to the classpath root: '/'). " +
"Write valid and/or invalid output to locations specified with 'writeValid' and 'writeInvalid'.")
"Write valid and/or invalid output to locations specified with 'writeValid' and 'writeInvalid'." +
"Set the JSON key for the record ID value with 'idKey' (for logging output, defaults to 'id').")
@In(String.class)
@Out(String.class)
@FluxCommand("validate-json")
public final class JsonValidator extends DefaultObjectPipe<String, ObjectReceiver<String>> {

private static final Logger LOG = LoggerFactory.getLogger(JsonValidator.class);
private static final String DEFAULT_SCHEMA_ROOT = "/";
private static final String DEFAULT_ID_KEY = "id";
private String schemaUrl;
private Schema schema;
private long fail;
private long success;
private FileWriter writeInvalid;
private FileWriter writeValid;
private String schemaRoot = DEFAULT_SCHEMA_ROOT;
private String idKey = DEFAULT_ID_KEY;

/**
* @param url The URL of the schema to validate against.
Expand Down Expand Up @@ -89,6 +92,13 @@ public void setWriteInvalid(final String writeInvalid) {
this.writeInvalid = fileWriter(writeInvalid);
}

/**
* @param idKey The JSON key for the record ID value.
*/
public void setIdKey(final String idKey) {
this.idKey = idKey;
}

@Override
public void process(final String json) {
final JSONObject object;
Expand Down Expand Up @@ -149,7 +159,7 @@ private FileWriter fileWriter(final String fileLocation) {

private void handleInvalid(final String json, final JSONObject object,
final String errorMessage) {
LOG.info("Invalid JSON: {} in {}", errorMessage, object != null ? object.opt("id") : json);
LOG.info("Invalid JSON: {} in {}", errorMessage, object != null ? object.opt(idKey) : json);
++fail;
write(json, writeInvalid);
}
Expand Down

0 comments on commit 8a1ceb5

Please sign in to comment.