Skip to content

[Question] How to make my custom Java POJOs known to CelCompiler? #786

@antimatter84

Description

@antimatter84

Hi all,
I am trying to run expressions against my Java data structure. I find it rather difficult to make my Java objects known to the CelCompiler and documentation seems to be sparse. Here's some code as an exampe:

abstract class MagicalCreature {
  String name;
}

class Dragon extends MagicalCreature {
  String color;
}

class Niffler extends MagicalCreature {
  int pouchVolume;
}

class Suitcase {
  List<MagicalCreature> creatures;
}

class CreatureEvaluator {
  public void evaluate() {
    Suitcase suitcase = ...
    String rule = "suitecase.creatures.exists(c, c.color == 'green')";

    CelCompiler cel = CelCompilerFactory
        .standardCelCompilerBuilder()
        .setStandardMacros(CelStandardMacro.STANDARD_MACROS)
        .setContainer(...)  // required?
        .addVar("suitcase", StructTypeReference.create(Suitcase.class.getName()))
        .setResultType(SimpleType.BOOL)
        .build();


    CelValidationResult compileResult = cel.compile(rule);
    CelRuntime celRuntime = CelRuntimeFactory.standardCelRuntimeBuilder().build();
    CelRuntime.Program program = celRuntime.createProgram(compileResult.getAst());
    Object result = program.eval(Map.of("suitcase", suitcase));
    
    // ...
  }
}

This attempt won't run because with this setup, the compiler doesn't know the "creatures" attribute in the suitcase and it also has no idea about the MagicalCreature subclasses and their members.

I problably need to do something with CelVarDecl, Decl and/or Types.

In my real use case, my input object has deep nesting with lists and maps, containing dozens of such polymorphic objects.

Can someone provide a few tips please, how to properly tell the CelCompiler, what my actual types are? Any help is very much appreciated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions