This project provides just a convenient interface for evaluating scripts with java script engine.
<dependency>
<groupId>org.fugerit.java</groupId>
<artifactId>fj-script-helper</artifactId>
<version>${fj-script-helper-version}</version>
</dependency>
Sample code :
// this will create a EvalScript instance for :
// kotlin script engine (kts)
// data model will be bound as "data" (if not provided this is the default binding name)
EvalScript evalKts = new EvalScriptWithDataModel( "kts", "data" );
try (Reader reader = [reader on kotlin script]) {
Map<String, Object> dataModel = new HashMap<>();
dataModel.put( "docTitle", "My custom title" );
Object result = evalKts.evalKts( reader, dataModel );
log.info( "my result : {}", result );
}
It is possible to wrap the EvalScript with some decorators, for instance :
EvalScript evalKts = EvalScriptWithJsonDataModel( new EvalScriptWithDataModel( "kts", "data" ) );
Will wrap the EvalScript with EvalScriptWithJsonDataModel decorator. EvalScriptWithJsonDataModel will transform a Map data model to a json data model style. Only getter and setter will be considered and made into basic types :
- String
- Number
- Boolean
- Object as Map
- Array
For instance this code :
class Vehicle {
private String plate;
private int age;
public Vehicle(int age, String plate) {
this.age = age;
this.plate = plate;
}
public String getPlate() { return plate; }
public int getAge() { return age; }
@Override
public String toString() {
return "Vehicle{age="+age+", plate='"+plate+"'}";
}
}
Map<String, Object> dataModel = new HashMap<>();
dataModel.put( "vehicle", new Vehicle( 10, "AA780BB" ) );
Map<String, Object> jsonStyleDataModel = EvalScriptWithJsonDataModel.defaultDataModelConversion( dataModel );
log.info( "originalDataModel : {}", dataModel );
log.info( "jsonStyleDataModel : {}", jsonStyleDataModel );
would result in this conversion :
originalDataModel : {vehicle=Vehicle{age=10, plate='AA780BB'}}
jsonStyleDataModel : {vehicle={plate=AA780BB, age=10}}