Search in sources :

Example 1 with ScriptError

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

the class MangoJavaScriptService method execute.

/**
 * Reset the result and execute for PointValueTime result
 */
public void execute(CompiledMangoJavaScript script, long runtime, long timestamp, DataType resultDataType) throws ScriptError, ResultTypeException, ScriptPermissionsException {
    try {
        runAs.runAsCallable(script.getPermissionHolder(), () -> {
            execute(script, runtime, timestamp);
            Object ts = script.getEngine().getBindings(ScriptContext.ENGINE_SCOPE).get(MangoJavaScriptService.TIMESTAMP_CONTEXT_KEY);
            long scriptRuntime;
            if (ts != null) {
                // Check the type of the object.
                if (ts instanceof Number) {
                    // Convert to long
                    scriptRuntime = ((Number) ts).longValue();
                } else {
                    scriptRuntime = timestamp;
                }
            } else {
                scriptRuntime = timestamp;
            }
            Object resultObject = script.getResult().getResult();
            DataValue value = coerce(resultObject, resultDataType);
            script.getResult().setResult(new PointValueTime(value, scriptRuntime));
            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) {
        if (e instanceof ResultTypeException) {
            throw (ResultTypeException) e;
        }
        throw new ShouldNeverHappenException(e);
    }
}
Also used : ScriptException(javax.script.ScriptException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) DataValue(com.serotonin.m2m2.rt.dataImage.types.DataValue) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) 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)

Example 2 with ScriptError

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

the class MangoJavaScriptService method initialize.

/**
 * Reset the engine scope of a script and initialize for running
 * @param context - if provided points will be wrapped with script's setter (alternatively use script.addToContext()
 */
public void initialize(CompiledMangoJavaScript script, Map<String, IDataPointValueSource> context) throws ScriptError {
    if (context == null) {
        context = new HashMap<>();
    }
    Bindings engineScope = script.getEngine().getBindings(ScriptContext.ENGINE_SCOPE);
    // TODO Clear engine scope completely?
    engineScope.put(MangoJavaScriptService.UNCHANGED_KEY, MangoJavaScriptService.UNCHANGED);
    Set<String> points = new HashSet<>();
    engineScope.put(MangoJavaScriptService.POINTS_CONTEXT_KEY, points);
    // Holder for modifying timestamps of meta points, in Engine Scope so it can be modified by all
    engineScope.put(MangoJavaScriptService.TIMESTAMP_CONTEXT_KEY, null);
    if (script.getPermissionHolder() != null) {
        script.getUtilities().clear();
        for (MangoJavascriptContextObjectDefinition def : ModuleRegistry.getMangoJavascriptContextObjectDefinitions()) {
            ScriptUtility util = def.initializeContextObject(script);
            util.setScriptLog(script.getLog());
            util.setResult(script.getResult());
            util.takeContext(script.getEngine(), engineScope, script.getSetter(), script.getImportExclusions(), script.isTestRun());
            engineScope.put(util.getContextKey(), util);
            script.getUtilities().add(util);
        }
        // Initialize additional utilities
        for (ScriptUtility util : script.getAdditionalUtilities()) {
            util.setScriptLog(script.getLog());
            util.setResult(script.getResult());
            util.takeContext(script.getEngine(), engineScope, script.getSetter(), script.getImportExclusions(), script.isTestRun());
            engineScope.put(util.getContextKey(), util);
        }
    }
    Set<Entry<String, Object>> entries = script.getAdditionalContext().entrySet();
    for (Entry<String, Object> entry : entries) engineScope.put(entry.getKey(), entry.getValue());
    String selfPointXid = (String) script.getAdditionalContext().get(SELF_POINT_XID_KEY);
    Map<String, AbstractPointWrapper> external = new HashMap<>();
    for (String varName : context.keySet()) {
        IDataPointValueSource point = context.get(varName);
        AbstractPointWrapper wrapped = wrapPoint(script.getEngine(), point, script.getSetter());
        engineScope.put(varName, wrapped);
        points.add(varName);
        if (!point.getVO().getXid().equals(selfPointXid)) {
            external.put(varName, wrapped);
        }
    }
    engineScope.put(EXTERNAL_POINTS_KEY, external);
    engineScope.put(EXTERNAL_POINTS_ARRAY_KEY, external.values());
    engineScope.put(POINTS_MAP_KEY, context);
    // Set the print writer and log
    script.getEngine().getContext().setWriter(script.getLog().getStdOutWriter());
    engineScope.put(ScriptLog.CONTEXT_KEY, script.getLog());
    try {
        script.getEngine().eval(getGlobalFunctions());
    } 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 if (e.getCause() != null)
            throw ScriptError.createFromThrowable(e.getCause());
        else
            throw new ShouldNeverHappenException(e);
    }
}
Also used : MangoJavascriptContextObjectDefinition(com.serotonin.m2m2.module.MangoJavascriptContextObjectDefinition) HashMap(java.util.HashMap) SimpleBindings(javax.script.SimpleBindings) Bindings(javax.script.Bindings) ScriptException(javax.script.ScriptException) Entry(java.util.Map.Entry) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) AbstractPointWrapper(com.serotonin.m2m2.rt.script.AbstractPointWrapper) ScriptUtility(com.infiniteautomation.mango.util.script.ScriptUtility) HashSet(java.util.HashSet)

Example 3 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 4 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 5 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)

Aggregations

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