Skip to content

fugerit-org/fj-script-helper

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Fugerit Language Script Helper

This project provides just a convenient interface for evaluating scripts with java script engine.

Keep a Changelog v1.1.0 badge Maven Central javadoc license code of conduct Quality Gate Status Coverage

Java runtime version Java build version Apache Maven Fugerit Github Project Conventions

Quickstart

1. Add dependency

<dependency>
    <groupId>org.fugerit.java</groupId>
    <artifactId>fj-script-helper</artifactId>
    <version>${fj-script-helper-version}</version>
</dependency>

2. Usage

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}}