Search in sources :

Example 11 with ScriptError

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

the class MangoJavaScriptService method executeScript.

/**
 * The preferred way to execute a script
 */
public MangoJavaScriptResult executeScript(MangoJavaScript vo, ScriptPointValueSetter setter) throws ValidationException, PermissionException {
    PermissionHolder user = Common.getUser();
    ensureValid(vo);
    MangoJavaScriptResult result = new MangoJavaScriptResult();
    final Writer scriptOut;
    final PrintWriter scriptWriter;
    if (vo.isReturnLogOutput()) {
        scriptOut = new StringWriter();
        scriptWriter = new PrintWriter(scriptOut);
    } else {
        NullWriter writer = new NullWriter();
        scriptWriter = new NullPrintWriter(writer);
        scriptOut = writer;
    }
    try {
        try (ScriptLogExtender scriptLog = new ScriptLogExtender("scriptTest-" + user.getPermissionHolderName(), vo.getLogLevel(), scriptWriter, vo.getLog(), vo.isCloseLog())) {
            CompiledMangoJavaScript script = new CompiledMangoJavaScript(vo, setter, scriptLog, result, this, pointValueDao, pointValueCache);
            script.compile(vo.getScript(), vo.isWrapInFunction());
            script.initialize(vo.getContext());
            long time = Common.timer.currentTimeMillis();
            runAs.runAsCallable(script.getPermissionHolder(), () -> {
                if (vo.getResultDataType() != null) {
                    script.execute(time, time, vo.getResultDataType());
                } else {
                    script.execute(time, time);
                }
                return null;
            });
        }
    } catch (ScriptError e) {
        // The script exception should be clean as both compile() and execute() clean it
        result.addError(new MangoJavaScriptError(e.getTranslatableMessage(), e.getLineNumber(), e.getColumnNumber()));
    } catch (ResultTypeException | DataPointStateException e) {
        result.addError(new MangoJavaScriptError(e.getTranslatableMessage()));
    } catch (Exception e) {
        result.addError(new MangoJavaScriptError(e.getMessage()));
    } finally {
        if (vo.isReturnLogOutput())
            result.setScriptOutput(scriptOut.toString());
    }
    return result;
}
Also used : MangoJavaScriptError(com.infiniteautomation.mango.util.script.MangoJavaScriptError) MangoJavaScriptResult(com.infiniteautomation.mango.util.script.MangoJavaScriptResult) PermissionHolder(com.serotonin.m2m2.vo.permission.PermissionHolder) NullWriter(com.serotonin.io.NullWriter) ScriptException(javax.script.ScriptException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) ValidationException(com.infiniteautomation.mango.util.exception.ValidationException) DataPointStateException(com.serotonin.m2m2.rt.script.DataPointStateException) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) MangoJavaScriptError(com.infiniteautomation.mango.util.script.MangoJavaScriptError) ScriptError(com.serotonin.m2m2.rt.script.ScriptError) StringWriter(java.io.StringWriter) NullPrintWriter(com.serotonin.m2m2.util.log.NullPrintWriter) DataPointStateException(com.serotonin.m2m2.rt.script.DataPointStateException) CompiledMangoJavaScript(com.infiniteautomation.mango.util.script.CompiledMangoJavaScript) NullWriter(com.serotonin.io.NullWriter) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) StringWriter(java.io.StringWriter) NullPrintWriter(com.serotonin.m2m2.util.log.NullPrintWriter) PrintWriter(java.io.PrintWriter) NullPrintWriter(com.serotonin.m2m2.util.log.NullPrintWriter)

Example 12 with ScriptError

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

the class EmailEventHandlerDefinition method commonValidation.

private void commonValidation(ProcessResult result, EmailEventHandlerVO vo) {
    if (vo.getActiveRecipients() != null) {
        int pos = 0;
        for (MailingListRecipient b : vo.getActiveRecipients()) {
            mailingListService.validateRecipient("activeRecipients[" + pos + "]", b, result, RecipientListEntryType.ADDRESS, RecipientListEntryType.MAILING_LIST, RecipientListEntryType.USER);
            pos++;
        }
    }
    if (vo.isSendEscalation()) {
        if (vo.getEscalationDelay() <= 0)
            result.addContextualMessage("escalationDelay", "eventHandlers.escalDelayError");
        if (!Common.TIME_PERIOD_CODES.isValidId(vo.getEscalationDelayType()))
            result.addContextualMessage("escalationDelayType", "validate.invalidValue");
        if (vo.getEscalationRecipients() != null) {
            int pos = 0;
            for (MailingListRecipient b : vo.getEscalationRecipients()) {
                mailingListService.validateRecipient("escalationRecipients[" + pos + "]", b, result, RecipientListEntryType.ADDRESS, RecipientListEntryType.MAILING_LIST, RecipientListEntryType.USER);
                pos++;
            }
        }
    } else if (vo.isRepeatEscalations()) {
        vo.setRepeatEscalations(false);
    }
    if (StringUtils.isNotEmpty(vo.getCustomTemplate())) {
        try {
            new Template("customTemplate", new StringReader(vo.getCustomTemplate()), Common.freemarkerConfiguration);
        } catch (Exception e) {
            result.addContextualMessage("customTemplate", "common.default", e.getMessage());
        }
    }
    if (vo.getAdditionalContext() != null)
        validateScriptContext(vo.getAdditionalContext(), result);
    else {
        vo.setAdditionalContext(new ArrayList<>());
    }
    if (!StringUtils.isEmpty(vo.getScript())) {
        MangoJavaScriptService service = Common.getBean(MangoJavaScriptService.class);
        try {
            service.compile(vo.getScript(), true);
        } catch (ScriptError e) {
            result.addContextualMessage("script", "eventHandlers.invalidActiveScriptError", e.getTranslatableMessage());
        }
    }
    if (!EmailEventHandlerVO.SUBJECT_INCLUDE_CODES.isValidId(vo.getSubject()))
        result.addContextualMessage("subject", "validate.invalidValue");
}
Also used : ScriptError(com.serotonin.m2m2.rt.script.ScriptError) StringReader(java.io.StringReader) MangoJavaScriptService(com.infiniteautomation.mango.spring.service.MangoJavaScriptService) MailingListRecipient(com.serotonin.m2m2.vo.mailingList.MailingListRecipient) Template(freemarker.template.Template)

Example 13 with ScriptError

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

the class SetPointEventHandlerDefinition method commonValidation.

private void commonValidation(ProcessResult response, SetPointEventHandlerVO vo) {
    DataPointVO dp = DataPointDao.getInstance().get(vo.getTargetPointId());
    DataType dataType = null;
    if (dp == null)
        response.addContextualMessage("targetPointId", "eventHandlers.noTargetPoint");
    else {
        dataType = dp.getPointLocator().getDataType();
        if (!dp.getPointLocator().isSettable())
            response.addContextualMessage("targetPointId", "event.setPoint.targetNotSettable");
    }
    if (vo.getActiveAction() == SetPointEventHandlerVO.SET_ACTION_NONE && vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_NONE) {
        response.addContextualMessage("activeAction", "eventHandlers.noSetPointAction");
        response.addContextualMessage("inactiveAction", "eventHandlers.noSetPointAction");
    }
    MangoJavaScriptService javaScriptService = Common.getBean(MangoJavaScriptService.class);
    // Active
    if (vo.getActiveAction() == SetPointEventHandlerVO.SET_ACTION_STATIC_VALUE && dataType == DataType.MULTISTATE) {
        try {
            Integer.parseInt(vo.getActiveValueToSet());
        } catch (NumberFormatException e) {
            response.addContextualMessage("activeValueToSet", "eventHandlers.invalidActiveValue");
        }
    } else if (vo.getActiveAction() == SetPointEventHandlerVO.SET_ACTION_STATIC_VALUE && dataType == DataType.NUMERIC) {
        try {
            Double.parseDouble(vo.getActiveValueToSet());
        } catch (NumberFormatException e) {
            response.addContextualMessage("activeValueToSet", "eventHandlers.invalidActiveValue");
        }
    } else if (vo.getActiveAction() == SetPointEventHandlerVO.SET_ACTION_POINT_VALUE) {
        DataPointVO dpActive = DataPointDao.getInstance().get(vo.getActivePointId());
        if (dpActive == null)
            response.addContextualMessage("activePointId", "eventHandlers.invalidActiveSource");
        else if (dataType != dpActive.getPointLocator().getDataType())
            response.addContextualMessage("activeDataPointId", "eventHandlers.invalidActiveSourceType");
    } else if (vo.getActiveAction() == SetPointEventHandlerVO.SET_ACTION_SCRIPT_VALUE) {
        if (StringUtils.isEmpty(vo.getActiveScript())) {
            response.addContextualMessage("activeScript", "eventHandlers.invalidActiveScript");
        } else {
            try {
                javaScriptService.compile(vo.getActiveScript(), true);
            } catch (ScriptError e) {
                response.addContextualMessage("activeScript", "eventHandlers.invalidActiveScriptError", e.getTranslatableMessage());
            }
        }
    }
    // Inactive
    if (vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_STATIC_VALUE && dataType == DataType.MULTISTATE) {
        try {
            Integer.parseInt(vo.getInactiveValueToSet());
        } catch (NumberFormatException e) {
            response.addContextualMessage("inactiveValueToSet", "eventHandlers.invalidInactiveValue");
        }
    } else if (vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_STATIC_VALUE && dataType == DataType.NUMERIC) {
        try {
            Double.parseDouble(vo.getInactiveValueToSet());
        } catch (NumberFormatException e) {
            response.addContextualMessage("inactiveValueToSet", "eventHandlers.invalidInactiveValue");
        }
    } else if (vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_POINT_VALUE) {
        DataPointVO dpInactive = DataPointDao.getInstance().get(vo.getInactivePointId());
        if (dpInactive == null)
            response.addContextualMessage("inactivePointId", "eventHandlers.invalidInactiveSource");
        else if (dataType != dpInactive.getPointLocator().getDataType())
            response.addContextualMessage("inactivePointId", "eventHandlers.invalidInactiveSourceType");
    } else if (vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_SCRIPT_VALUE) {
        if (StringUtils.isEmpty(vo.getInactiveScript())) {
            response.addContextualMessage("inactiveScript", "eventHandlers.invalidInactiveScript");
        } else {
            try {
                javaScriptService.compile(vo.getInactiveScript(), true);
            } catch (ScriptError e) {
                response.addContextualMessage("inactiveScript", "eventHandlers.invalidActiveScriptError", e.getTranslatableMessage());
            }
        }
    }
    if (vo.getAdditionalContext() != null)
        validateScriptContext(vo.getAdditionalContext(), response);
    else
        vo.setAdditionalContext(new ArrayList<>());
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) ScriptError(com.serotonin.m2m2.rt.script.ScriptError) ArrayList(java.util.ArrayList) DataType(com.serotonin.m2m2.DataType) MangoJavaScriptService(com.infiniteautomation.mango.spring.service.MangoJavaScriptService)

Example 14 with ScriptError

use of com.serotonin.m2m2.rt.script.ScriptError 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)

Example 15 with ScriptError

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

the class MangoJavaScriptService method execute.

/**
 * Reset result and execute script for any type of result
 */
public void execute(CompiledMangoJavaScript script, long runtime, long timestamp) throws ScriptError, ScriptPermissionsException {
    try {
        runAs.runAsCallable(script.getPermissionHolder(), () -> {
            script.getResult().reset();
            // Setup the wrapper context
            Bindings engineScope = script.getEngine().getBindings(ScriptContext.ENGINE_SCOPE);
            engineScope.put(MangoJavaScriptService.WRAPPER_CONTEXT_KEY, new WrapperContext(runtime, timestamp));
            // Ensure the result is available to the utilities
            for (ScriptUtility util : script.getUtilities()) {
                util.setResult(script.getResult());
            }
            // Initialize additional utilities
            for (ScriptUtility util : script.getAdditionalUtilities()) util.setResult(script.getResult());
            Object resultObject = script.getCompiledScript().eval();
            script.getResult().setResult(resultObject);
            return null;
        });
    } catch (ScriptException e) {
        throw ScriptError.create(e, script.isWrapInFunction());
    } catch (RuntimeException e) {
        // Nashorn seems to like to wrap exceptions in RuntimeException
        if (e.getCause() instanceof ScriptPermissionsException)
            throw (ScriptPermissionsException) e.getCause();
        else
            throw new ShouldNeverHappenException(e);
    } catch (Exception e) {
        throw new ShouldNeverHappenException(e);
    }
}
Also used : WrapperContext(com.serotonin.m2m2.rt.script.WrapperContext) ScriptException(javax.script.ScriptException) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) SimpleBindings(javax.script.SimpleBindings) Bindings(javax.script.Bindings) ScriptUtility(com.infiniteautomation.mango.util.script.ScriptUtility) ScriptException(javax.script.ScriptException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) ValidationException(com.infiniteautomation.mango.util.exception.ValidationException) DataPointStateException(com.serotonin.m2m2.rt.script.DataPointStateException) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException)

Aggregations

ShouldNeverHappenException (com.serotonin.ShouldNeverHappenException)14 ResultTypeException (com.serotonin.m2m2.rt.script.ResultTypeException)14 ScriptError (com.serotonin.m2m2.rt.script.ScriptError)14 ScriptPermissionsException (com.serotonin.m2m2.rt.script.ScriptPermissionsException)14 ScriptException (javax.script.ScriptException)12 CompiledMangoJavaScript (com.infiniteautomation.mango.util.script.CompiledMangoJavaScript)10 MangoJavaScriptResult (com.infiniteautomation.mango.util.script.MangoJavaScriptResult)10 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)10 IDataPointValueSource (com.serotonin.m2m2.rt.dataImage.IDataPointValueSource)10 PointValueTime (com.serotonin.m2m2.rt.dataImage.PointValueTime)10 DataPointStateException (com.serotonin.m2m2.rt.script.DataPointStateException)10 HashMap (java.util.HashMap)10 ValidationException (com.infiniteautomation.mango.util.exception.ValidationException)8 IntStringPair (com.serotonin.db.pair.IntStringPair)8 DataPointRT (com.serotonin.m2m2.rt.dataImage.DataPointRT)8 ScriptLog (com.serotonin.m2m2.rt.script.ScriptLog)8 PermissionException (com.serotonin.m2m2.vo.permission.PermissionException)8 ArrayList (java.util.ArrayList)8 MangoJavaScriptService (com.infiniteautomation.mango.spring.service.MangoJavaScriptService)6 DataType (com.serotonin.m2m2.DataType)6