0

The title might be "wrong" as I'm unsure how to summarize what I'm trying to achieve.

Let's imagine that (in a JAVA context), I have a DTO Document

public class Document {
    private String title;
    private List<Field> fields;
    // Omitting constructor/getters/setters

}

public class Field {
    private String name;
    private String value;
}

Now, I would like my users to be able to write simple conditions on this Document. Example:

${document.fields[0].value} > 10000

(assuming here that the first field has an integer value, let's keep types out for now).

So I'm thinking of having an evaluator:

public class Evaluator {
    public Object eval(Document document, String expression) {
        // 1. "put" the document values in the expression, i.e. replace the ${} with proper attirbutes
        // 2. Eval the expression
    }
}

Since many operators would be asked (numerical, dates, custom ones), I'm also thinking of having a Clojure evaluation happen here so I can harness macros to define said operators. Or use a Javascript script engine (cf. Evaluate String as a condition Java)

But that may be beside the point as my first goal here would be "map" the ${document.fields[0].value} to the Document's getters (the 1. in the comments).

Is there anything existing on the matter? Or do I have to manually parse my expression to map to the Document afterwards?

Justmaker
  • 1,261
  • 2
  • 11
  • 20
  • 1
    This one is an obvious candidate for some tamplating engine, like velocity, freemarker, pebble and so forth.. most of them are quality power tools to solve this class of tasks, you don't have to reinvent the wheel here. https://en.m.wikipedia.org/wiki/Comparison_of_web_template_engines – leetwinski Dec 15 '19 at 20:27
  • It sounds like what you want to do is similar to [JsonPath](https://github.com/json-path/JsonPath), but it aims to parse a JSON string instead. – LHCHIN Dec 16 '19 at 00:29
  • Thanks, indeed templating does the job! – Justmaker Dec 18 '19 at 05:40
  • Templating is built into Java (as a preview feature) as of Java 21. See [JEP 430](https://openjdk.org/jeps/430). – mernst Aug 04 '23 at 22:46

0 Answers0