Search in sources :

Example 1 with DateTimeUtility

use of com.serotonin.m2m2.rt.script.DateTimeUtility in project ma-core-public by infiniteautomation.

the class MangoJavaScriptService method compile.

/**
 * Compile a script to be run and add global bindings
 */
public CompiledScript compile(String script, boolean wrapInFunction) throws ScriptError {
    try {
        final ScriptEngine engine = newEngine();
        // Add constants to the context
        Bindings globalBindings = new SimpleBindings();
        // left here for legacy compatibility
        globalBindings.put("SECOND", Common.TimePeriods.SECONDS);
        globalBindings.put("MINUTE", Common.TimePeriods.MINUTES);
        globalBindings.put("HOUR", Common.TimePeriods.HOURS);
        globalBindings.put("DAY", Common.TimePeriods.DAYS);
        globalBindings.put("WEEK", Common.TimePeriods.WEEKS);
        globalBindings.put("MONTH", Common.TimePeriods.MONTHS);
        globalBindings.put("YEAR", Common.TimePeriods.YEARS);
        for (IntStringPair isp : Common.TIME_PERIOD_CODES.getIdKeys()) globalBindings.put(Common.TIME_PERIOD_CODES.getCode(isp.getKey()), isp.getKey());
        for (IntStringPair isp : Common.ROLLUP_CODES.getIdKeys(Common.Rollups.NONE)) globalBindings.put(Common.ROLLUP_CODES.getCode(isp.getKey()), isp.getKey());
        // Add in Additional Utilities with Global Scope
        globalBindings.put(DateTimeUtility.CONTEXT_KEY, new DateTimeUtility());
        globalBindings.put(UnitUtility.CONTEXT_KEY, new UnitUtility());
        engine.setBindings(globalBindings, ScriptContext.GLOBAL_SCOPE);
        String toCompile;
        if (wrapInFunction) {
            toCompile = SCRIPT_PREFIX + script + SCRIPT_SUFFIX;
        } else {
            toCompile = script;
        }
        return ((Compilable) engine).compile(toCompile);
    } catch (ScriptException e) {
        throw ScriptError.create(e, wrapInFunction);
    }
}
Also used : ScriptException(javax.script.ScriptException) IntStringPair(com.serotonin.db.pair.IntStringPair) SimpleBindings(javax.script.SimpleBindings) Compilable(javax.script.Compilable) DateTimeUtility(com.serotonin.m2m2.rt.script.DateTimeUtility) SimpleBindings(javax.script.SimpleBindings) Bindings(javax.script.Bindings) UnitUtility(com.serotonin.m2m2.rt.script.UnitUtility) ScriptEngine(javax.script.ScriptEngine)

Aggregations

IntStringPair (com.serotonin.db.pair.IntStringPair)1 DateTimeUtility (com.serotonin.m2m2.rt.script.DateTimeUtility)1 UnitUtility (com.serotonin.m2m2.rt.script.UnitUtility)1 Bindings (javax.script.Bindings)1 Compilable (javax.script.Compilable)1 ScriptEngine (javax.script.ScriptEngine)1 ScriptException (javax.script.ScriptException)1 SimpleBindings (javax.script.SimpleBindings)1