Search in sources :

Example 6 with ScriptError

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

the class EmailHandlerRT method sendEmail.

private static void sendEmail(EventInstance evt, NotificationType notificationType, Set<String> addresses, String baseSubject, boolean includeSystemInfo, int pointValueCount, boolean includeLogs, String handlerXid, String customTemplate, List<IntStringPair> additionalContext, String script, SetCallback setCallback, ScriptPermissions permissions) {
    if (evt.getEventType().isSystemMessage()) {
        if (((SystemEventType) evt.getEventType()).getSystemEventType().equals(SystemEventType.TYPE_EMAIL_SEND_FAILURE)) {
            // Don't send email notifications about email send failures.
            LOG.info("Not sending email for event raised due to email failure");
            return;
        }
    }
    Translations translations = Common.getTranslations();
    if (StringUtils.isBlank(baseSubject)) {
        // Just set the subject to the message
        baseSubject = evt.getMessage().translate(translations);
        // Strip out the HTML and the &nbsp
        baseSubject = StringEscapeUtils.unescapeHtml4(baseSubject);
        // Since we have <br/> in the code and that isn't proper HTML we need to remove it by hand
        baseSubject = baseSubject.replace("<br/>", "\n");
    }
    // end if alias was blank
    // Determine the subject to use.
    TranslatableMessage subjectMsg;
    TranslatableMessage notifTypeMsg = new TranslatableMessage(notificationType.getKey());
    if (StringUtils.isBlank(baseSubject)) {
        // Make these more descriptive
        if (evt.getId() == Common.NEW_ID)
            subjectMsg = new TranslatableMessage("ftl.subject.default", notifTypeMsg);
        else
            subjectMsg = new TranslatableMessage("ftl.subject.default.id", notifTypeMsg, evt.getId());
    } else {
        if (evt.getId() == Common.NEW_ID)
            subjectMsg = new TranslatableMessage("ftl.subject.alias", baseSubject, notifTypeMsg);
        else
            subjectMsg = new TranslatableMessage("ftl.subject.alias.id", baseSubject, notifTypeMsg, evt.getId());
    }
    String alarmLevel = evt.getAlarmLevel().getDescription().translate(translations);
    String subject = alarmLevel + " - " + subjectMsg.translate(translations);
    // Trim the subject if its too long
    if (subject.length() > 200)
        subject = subject.substring(0, 200);
    try {
        String[] toAddrs;
        if (addresses == null)
            toAddrs = new String[0];
        else
            toAddrs = addresses.toArray(new String[0]);
        UsedImagesDirective inlineImages = new UsedImagesDirective();
        // Send the email.
        Map<String, Object> model = new HashMap<String, Object>();
        model.put(EventInstance.CONTEXT_KEY, evt);
        model.put(EventInstanceWrapper.CONTEXT_KEY, new EventInstanceWrapper(evt));
        if (evt.getContext() != null)
            model.putAll(evt.getContext());
        model.put("img", inlineImages);
        model.put("instanceDescription", SystemSettingsDao.getInstance().getValue(SystemSettingsDao.INSTANCE_DESCRIPTION));
        if (includeSystemInfo) {
            // Get the Work Items
            List<WorkItemInfo> highPriorityWorkItems = Common.backgroundProcessing.getHighPriorityServiceItems();
            model.put("highPriorityWorkItems", highPriorityWorkItems);
            List<WorkItemInfo> mediumPriorityWorkItems = Common.backgroundProcessing.getMediumPriorityServiceQueueItems();
            model.put("mediumPriorityWorkItems", mediumPriorityWorkItems);
            List<WorkItemInfo> lowPriorityWorkItems = Common.backgroundProcessing.getLowPriorityServiceQueueItems();
            model.put("lowPriorityWorkItems", lowPriorityWorkItems);
            model.put("threadList", getThreadsList());
        }
        int type = SystemSettingsDao.getInstance().getIntValue(SystemSettingsDao.EMAIL_CONTENT_TYPE);
        // If we are a point event then add the value
        if (evt.getEventType() instanceof DataPointEventType) {
            DataPointVO dp = (DataPointVO) evt.getContext().get("point");
            if (dp != null) {
                DataPointRT rt = Common.runtimeManager.getDataPoint(dp.getId());
                if (rt != null) {
                    List<PointValueTime> pointValues = null;
                    if (pointValueCount > 0)
                        pointValues = rt.getLatestPointValues(pointValueCount);
                    if ((pointValues != null) && (pointValues.size() > 0)) {
                        if (type == MangoEmailContent.CONTENT_TYPE_HTML || type == MangoEmailContent.CONTENT_TYPE_BOTH) {
                            List<RenderedPointValueTime> renderedPointValues = new ArrayList<RenderedPointValueTime>();
                            for (PointValueTime pvt : pointValues) {
                                RenderedPointValueTime rpvt = new RenderedPointValueTime();
                                rpvt.setValue(Functions.getHtmlText(rt.getVO(), pvt));
                                rpvt.setTime(Functions.getFullSecondTime(pvt.getTime()));
                                renderedPointValues.add(rpvt);
                            }
                            model.put("renderedHtmlPointValues", renderedPointValues);
                        }
                        if (type == MangoEmailContent.CONTENT_TYPE_TEXT || type == MangoEmailContent.CONTENT_TYPE_BOTH) {
                            List<RenderedPointValueTime> renderedPointValues = new ArrayList<RenderedPointValueTime>();
                            for (PointValueTime pvt : pointValues) {
                                RenderedPointValueTime rpvt = new RenderedPointValueTime();
                                rpvt.setValue(Functions.getRenderedText(rt.getVO(), pvt));
                                rpvt.setTime(Functions.getFullSecondTime(pvt.getTime()));
                                renderedPointValues.add(rpvt);
                            }
                            model.put("renderedPointValues", renderedPointValues);
                        }
                    }
                }
            }
        }
        // Build the additional context for the email model
        if (additionalContext == null || pointValueCount <= 0)
            model.put("additionalContext", new HashMap<>(0));
        else {
            Map<String, EmailPointWrapper> context = new HashMap<>();
            for (IntStringPair pair : additionalContext) {
                EmailPointWrapper point;
                DataPointRT rt = Common.runtimeManager.getDataPoint(pair.getKey());
                List<PointValueTime> pointValues;
                List<RenderedPointValueTime> renderedPointValues;
                DataPointVO dpvo;
                if (rt != null) {
                    dpvo = rt.getVO();
                    point = new EmailPointWrapper(dpvo);
                    pointValues = rt.getLatestPointValues(pointValueCount);
                    renderedPointValues = new ArrayList<RenderedPointValueTime>();
                    if (pointValues != null && pointValues.size() > 0)
                        for (PointValueTime pvt : pointValues) {
                            RenderedPointValueTime rpvt = new RenderedPointValueTime();
                            rpvt.setValue(Functions.getRenderedText(rt.getVO(), pvt));
                            rpvt.setTime(Functions.getFullSecondTime(pvt.getTime()));
                            renderedPointValues.add(rpvt);
                        }
                } else {
                    dpvo = DataPointDao.getInstance().get(pair.getKey());
                    if (dpvo == null)
                        continue;
                    point = new EmailPointWrapper(dpvo);
                    pointValues = Common.getBean(PointValueDao.class).getLatestPointValues(dpvo, pointValueCount);
                    renderedPointValues = new ArrayList<RenderedPointValueTime>();
                    for (PointValueTime pvt : pointValues) {
                        RenderedPointValueTime rpvt = new RenderedPointValueTime();
                        rpvt.setValue(Functions.getRenderedText(dpvo, pvt));
                        rpvt.setTime(Functions.getFullSecondTime(pvt.getTime()));
                        renderedPointValues.add(rpvt);
                    }
                }
                point.setRawValues(pointValues);
                point.setValues(renderedPointValues);
                point.setContextKey(pair.getValue());
                context.put(pair.getValue(), point);
            }
            model.put("additionalContext", context);
        }
        if (!StringUtils.isEmpty(script)) {
            // Okay, a script is defined, let's pass it the model so that it may add to it
            Map<String, Object> modelContext = new HashMap<String, Object>();
            modelContext.put("model", model);
            Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
            for (IntStringPair pair : additionalContext) {
                DataPointRT dprt = Common.runtimeManager.getDataPoint(pair.getKey());
                if (dprt == null) {
                    DataPointVO targetVo = DataPointDao.getInstance().get(pair.getKey());
                    if (targetVo == null) {
                        LOG.warn("Additional context point with ID: " + pair.getKey() + " and context name " + pair.getValue() + " could not be found.");
                        // Not worth aborting the email, just warn it
                        continue;
                    }
                    if (targetVo.getDefaultCacheSize() == 0)
                        targetVo.setDefaultCacheSize(1);
                    DataPointWithEventDetectors dp = new DataPointWithEventDetectors(targetVo, new ArrayList<>());
                    DataSourceRT<? extends DataSourceVO> dataSource = DataSourceDao.getInstance().get(targetVo.getDataSourceId()).createDataSourceRT();
                    dprt = new DataPointRT(dp, targetVo.getPointLocator().createRuntime(), dataSource, null, Common.getBean(PointValueDao.class), Common.getBean(PointValueCache.class));
                }
                context.put(pair.getValue(), dprt);
            }
            modelContext.put(DO_NOT_SEND_KEY, MangoJavaScriptService.UNCHANGED);
            List<JsonImportExclusion> importExclusions = new ArrayList<JsonImportExclusion>(1);
            importExclusions.add(new JsonImportExclusion("xid", handlerXid) {

                @Override
                public String getImporterType() {
                    return ConfigurationExportData.EVENT_HANDLERS;
                }
            });
            try (ScriptLog scriptLog = new ScriptLog("emailScript-" + evt.getId())) {
                MangoJavaScriptService service = Common.getBean(MangoJavaScriptService.class);
                long time = evt.isActive() || !evt.isRtnApplicable() ? evt.getActiveTimestamp() : evt.getRtnTimestamp();
                CompiledMangoJavaScript compiledScript = new CompiledMangoJavaScript(setCallback, scriptLog, modelContext, null, importExclusions, false, service, permissions);
                compiledScript.compile(script, true);
                compiledScript.initialize(context);
                MangoJavaScriptResult r = compiledScript.execute(Common.timer.currentTimeMillis(), time, DataType.ALPHANUMERIC);
                PointValueTime result = (PointValueTime) r.getResult();
                if (// The script cancelled the email
                result != null && result.getValue() == MangoJavaScriptService.UNCHANGED)
                    return;
            } catch (ScriptError | ResultTypeException e) {
                LOG.error("Exception running email handler script: " + e.getTranslatableMessage(), e);
            }
        }
        MangoEmailContent content;
        if (StringUtils.isEmpty(customTemplate))
            content = new MangoEmailContent(notificationType.getFile(), model, translations, subject, StandardCharsets.UTF_8);
        else
            content = new MangoEmailContent(handlerXid, customTemplate, model, translations, subject);
        PostEmailRunnable[] postEmail = null;
        if (includeLogs) {
            final File logZip = getZippedLogfile(content, new File(Common.getLogsDir(), "ma.log"));
            // Setup To delete the temp files from zip
            if (logZip != null) {
                // See that the temp file(s) gets deleted after the email is sent.
                PostEmailRunnable deleteTempFile = new PostEmailRunnable() {

                    @Override
                    public void run() {
                        if (!logZip.delete())
                            LOG.warn("Temp file " + logZip.getPath() + " not deleted");
                    // Set our state to email failed if necessary
                    // TODO Create an Event to notify of Failed Emails...
                    // if(!this.isSuccess()){}
                    }
                };
                postEmail = new PostEmailRunnable[] { deleteTempFile };
            }
        }
        for (Entry<Path, UUID> entry : inlineImages.getImageList().entrySet()) {
            content.addInline(new FileInline(entry.getValue().toString(), entry.getKey().toFile()));
        }
        if (toAddrs.length > 0)
            EmailWorkItem.queueEmail(toAddrs, content, postEmail);
    } catch (Exception e) {
        LOG.error("Error sending email", e);
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) JsonImportExclusion(com.serotonin.m2m2.rt.script.JsonImportExclusion) ScriptLog(com.serotonin.m2m2.rt.script.ScriptLog) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) RenderedPointValueTime(com.serotonin.m2m2.rt.dataImage.RenderedPointValueTime) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) FileInline(com.serotonin.web.mail.EmailInline.FileInline) UsedImagesDirective(com.serotonin.m2m2.email.UsedImagesDirective) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) DataPointEventType(com.serotonin.m2m2.rt.event.type.DataPointEventType) UUID(java.util.UUID) DataPointVO(com.serotonin.m2m2.vo.DataPointVO) MangoJavaScriptResult(com.infiniteautomation.mango.util.script.MangoJavaScriptResult) DataPointWithEventDetectors(com.serotonin.m2m2.vo.dataPoint.DataPointWithEventDetectors) PostEmailRunnable(com.serotonin.m2m2.email.PostEmailRunnable) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) MangoEmailContent(com.serotonin.m2m2.email.MangoEmailContent) CompiledMangoJavaScript(com.infiniteautomation.mango.util.script.CompiledMangoJavaScript) Translations(com.serotonin.m2m2.i18n.Translations) File(java.io.File) EventInstanceWrapper(com.serotonin.m2m2.rt.script.EventInstanceWrapper) MangoJavaScriptService(com.infiniteautomation.mango.spring.service.MangoJavaScriptService) ScriptError(com.serotonin.m2m2.rt.script.ScriptError) Path(java.nio.file.Path) IntStringPair(com.serotonin.db.pair.IntStringPair) WorkItemInfo(com.infiniteautomation.mango.util.WorkItemInfo) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) IOException(java.io.IOException) RenderedPointValueTime(com.serotonin.m2m2.rt.dataImage.RenderedPointValueTime)

Example 7 with ScriptError

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

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 8 with ScriptError

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

the class SetPointHandlerRT method eventInactive.

@Override
public void eventInactive(EventInstance evt) {
    if (vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_NONE)
        return;
    // Validate that the target point is available.
    DataPointRT targetPoint = Common.runtimeManager.getDataPoint(vo.getTargetPointId());
    if (targetPoint == null) {
        raiseFailureEvent(new TranslatableMessage("event.setPoint.targetPointMissing"), evt.getEventType());
        return;
    }
    if (!targetPoint.getPointLocator().isSettable()) {
        raiseFailureEvent(new TranslatableMessage("event.setPoint.targetNotSettable"), evt.getEventType());
        return;
    }
    DataType targetDataType = targetPoint.getVO().getPointLocator().getDataType();
    DataValue value = null;
    if (vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_POINT_VALUE) {
        // Get the source data point.
        DataPointRT sourcePoint = Common.runtimeManager.getDataPoint(vo.getInactivePointId());
        if (sourcePoint == null) {
            raiseFailureEvent(new TranslatableMessage("event.setPoint.inactivePointMissing"), evt.getEventType());
            return;
        }
        PointValueTime valueTime = sourcePoint.getPointValue();
        if (valueTime == null) {
            raiseFailureEvent(new TranslatableMessage("event.setPoint.inactivePointValue"), evt.getEventType());
            return;
        }
        if (valueTime.getValue().getDataType() != targetDataType) {
            raiseFailureEvent(new TranslatableMessage("event.setPoint.inactivePointDataType"), evt.getEventType());
            return;
        }
        value = valueTime.getValue();
    } else if (vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_STATIC_VALUE)
        value = DataValue.stringToValue(vo.getInactiveValueToSet(), targetDataType);
    else if (vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_SCRIPT_VALUE) {
        ArrayList<JsonImportExclusion> importExclusions = new ArrayList<JsonImportExclusion>();
        importExclusions.add(new JsonImportExclusion("xid", vo.getXid()) {

            @Override
            public String getImporterType() {
                return ConfigurationExportData.EVENT_HANDLERS;
            }
        });
        Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
        context.put("target", targetPoint);
        Map<String, Object> additionalContext = new HashMap<String, Object>();
        additionalContext.put(EventInstance.CONTEXT_KEY, evt);
        additionalContext.put(EventInstanceWrapper.CONTEXT_KEY, new EventInstanceWrapper(evt));
        try (ScriptLog scriptLog = new ScriptLog("setPointHandler-" + evt.getId())) {
            for (IntStringPair cxt : vo.getAdditionalContext()) {
                DataPointRT dprt = Common.runtimeManager.getDataPoint(cxt.getKey());
                if (dprt != null)
                    context.put(cxt.getValue(), dprt);
            }
            CompiledMangoJavaScript inactiveScript = new CompiledMangoJavaScript(new SetCallback(vo.getScriptRoles()), scriptLog, additionalContext, null, importExclusions, false, service, vo.getScriptRoles());
            inactiveScript.compile(vo.getInactiveScript(), true);
            inactiveScript.initialize(context);
            MangoJavaScriptResult result = inactiveScript.execute(Common.timer.currentTimeMillis(), evt.getRtnTimestamp(), targetPoint.getDataType());
            PointValueTime pvt = (PointValueTime) result.getResult();
            if (pvt != null)
                value = pvt.getValue();
        } catch (ScriptPermissionsException e) {
            raiseFailureEvent(e.getTranslatableMessage(), evt.getEventType());
            return;
        } catch (ScriptError e) {
            raiseFailureEvent(new TranslatableMessage("eventHandlers.invalidInactiveScriptError", e.getTranslatableMessage()), evt.getEventType());
            return;
        } catch (ResultTypeException e) {
            raiseFailureEvent(new TranslatableMessage("eventHandlers.invalidInactiveScriptError", e.getMessage()), evt.getEventType());
            return;
        }
    } else
        throw new ShouldNeverHappenException("Unknown active action: " + vo.getInactiveAction());
    if (MangoJavaScriptService.UNCHANGED != value)
        Common.backgroundProcessing.addWorkItem(new SetPointWorkItem(vo.getTargetPointId(), new PointValueTime(value, evt.getRtnTimestamp()), this));
}
Also used : DataValue(com.serotonin.m2m2.rt.dataImage.types.DataValue) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SetPointWorkItem(com.serotonin.m2m2.rt.maint.work.SetPointWorkItem) JsonImportExclusion(com.serotonin.m2m2.rt.script.JsonImportExclusion) ScriptLog(com.serotonin.m2m2.rt.script.ScriptLog) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptError(com.serotonin.m2m2.rt.script.ScriptError) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) DataType(com.serotonin.m2m2.DataType) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) IntStringPair(com.serotonin.db.pair.IntStringPair) MangoJavaScriptResult(com.infiniteautomation.mango.util.script.MangoJavaScriptResult) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) CompiledMangoJavaScript(com.infiniteautomation.mango.util.script.CompiledMangoJavaScript) EventInstanceWrapper(com.serotonin.m2m2.rt.script.EventInstanceWrapper)

Example 9 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 10 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)

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