gchq / koryphe

A flexible library for writing functional operations in Java
Apache License 2.0
20 stars 15 forks source link

Generic predicates and functions should be able to dynamically deserialise JSON fields #67

Open p013570 opened 6 years ago

p013570 commented 6 years ago

Currently if you deserialise:

{
    "class": "uk.gov.gchq.koryphe.impl.predicate.IsMoreThan",
    "value": 1512381090096
}

it will throw an exception saying 1512381090096 is bigger than MAX integer. It should use Long by default.

When used in Gaffer, the Gaffer schema defines the class types for the IsMoreThan value field. We should allow users in Gaffer to write the above json and automatically deserialise the value field into a custom class, like a Date, without requiring the user to provide the class like:

{
    "class": "uk.gov.gchq.koryphe.impl.predicate.IsMoreThan",
    "value": {
       "java.util.Date": 1512381090096
    }
}

We have a method: InputValidator.isInputValid. This takes in classes and checks the predicate's field match the classes. If we pass in a Date class, then we should be able to convert the above long into a Date using JSON serialisation. For example, in the IsMoreThan class:

if (!controlValue.getClass().isAssignableFrom(arguments[0])) {
    final String json;
    try {
        json = JsonSerialiserUtil.serialise(controlValue);
        controlValue = (Comparable) JsonSerialiserUtil.deserialise(json, arguments[0]);
    } catch (final Exception e) {
        result.addError("Control value class " + controlValue.getClass().getName() + " is not compatible with the input type: " + arguments[0]);
    }
}

We could create an interface:

public void TypeResolver {
void resolveTypes(final Class<final Class<?>... arguments);
}

And for any classes that have jsonSubType annotations on fields implement it with something like the above code.

m607123 commented 6 years ago

Added a JsonSerialisiationUtil class in Koryphe core. Created a TypeResolver interface, with method resolveTypes(final Class<?>... args), which should attempt to reserialise the predicate value(s).