Search in sources :

Example 6 with ResultTypeException

use of com.serotonin.m2m2.rt.script.ResultTypeException 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;
    }
    int targetDataType = targetPoint.getVO().getPointLocator().getDataTypeId();
    DataValue value;
    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 (DataTypes.getDataType(valueTime.getValue()) != 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) {
        if (inactiveScript == null) {
            raiseFailureEvent(new TranslatableMessage("eventHandlers.invalidInactiveScript"), evt.getEventType());
            return;
        }
        Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
        context.put("target", targetPoint);
        try {
            PointValueTime pvt = CompiledScriptExecutor.execute(inactiveScript, context, new HashMap<String, Object>(), evt.getRtnTimestamp(), targetPoint.getDataTypeId(), evt.getRtnTimestamp(), vo.getScriptPermissions(), NULL_WRITER, new ScriptLog(NULL_WRITER, LogLevel.FATAL), setCallback, importExclusions, false);
            value = pvt.getValue();
        } catch (ScriptPermissionsException e) {
            raiseFailureEvent(e.getTranslatableMessage(), evt.getEventType());
            return;
        } catch (ScriptException e) {
            raiseFailureEvent(new TranslatableMessage("eventHandlers.invalidInactiveScriptError", e.getCause().getMessage()), 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());
    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) SetPointWorkItem(com.serotonin.m2m2.rt.maint.work.SetPointWorkItem) ScriptLog(com.serotonin.m2m2.rt.script.ScriptLog) ScriptException(javax.script.ScriptException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage)

Example 7 with ResultTypeException

use of com.serotonin.m2m2.rt.script.ResultTypeException in project ma-modules-public by infiniteautomation.

the class PointLinkRT method execute.

private void execute(PointValueTime newValue) {
    // Bail out if already running a point link operation
    synchronized (ready) {
        if (!ready) {
            SystemEventType.raiseEvent(alreadyRunningEvent, newValue.getTime(), true, new TranslatableMessage("event.pointLink.duplicateRuns"));
            return;
        } else {
            // Stop anyone else from using this
            ready = false;
            SystemEventType.returnToNormal(alreadyRunningEvent, System.currentTimeMillis());
        }
    }
    // Propagate the update to the target point. Validate that the target point is available.
    DataPointRT targetPoint = Common.runtimeManager.getDataPoint(vo.getTargetPointId());
    if (targetPoint == null) {
        raiseFailureEvent(newValue.getTime(), new TranslatableMessage("event.pointLink.targetUnavailable"));
        ready = true;
        return;
    }
    if (!targetPoint.getPointLocator().isSettable()) {
        raiseFailureEvent(newValue.getTime(), new TranslatableMessage("event.pointLink.targetNotSettable"));
        ready = true;
        return;
    }
    int targetDataType = targetPoint.getVO().getPointLocator().getDataTypeId();
    if (!StringUtils.isBlank(vo.getScript())) {
        Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
        context.put(CONTEXT_SOURCE_VAR_NAME, Common.runtimeManager.getDataPoint(vo.getSourcePointId()));
        context.put(CONTEXT_TARGET_VAR_NAME, Common.runtimeManager.getDataPoint(vo.getTargetPointId()));
        try {
            if (!compiled) {
                compiledScript = CompiledScriptExecutor.compile(vo.getScript());
                compiled = true;
            }
            PointValueTime pvt = CompiledScriptExecutor.execute(compiledScript, context, null, newValue.getTime(), targetDataType, newValue.getTime(), vo.getScriptPermissions(), new PrintWriter(new NullWriter()), scriptLog, setCallback, importExclusions, false);
            if (pvt.getValue() == null) {
                raiseFailureEvent(newValue.getTime(), new TranslatableMessage("event.pointLink.nullResult"));
                ready = true;
                return;
            } else if (pvt.getValue() == CompiledScriptExecutor.UNCHANGED) {
                ready = true;
                return;
            }
            newValue = pvt;
        } catch (ScriptException e) {
            raiseFailureEvent(newValue.getTime(), new TranslatableMessage("pointLinks.validate.scriptError", e.getMessage()));
            ready = true;
            return;
        } catch (ScriptPermissionsException e) {
            raiseFailureEvent(newValue.getTime(), e.getTranslatableMessage());
            ready = true;
            return;
        } catch (ResultTypeException e) {
            raiseFailureEvent(newValue.getTime(), e.getTranslatableMessage());
            ready = true;
            return;
        }
    }
    if (DataTypes.getDataType(newValue.getValue()) != targetDataType) {
        raiseFailureEvent(newValue.getTime(), new TranslatableMessage("event.pointLink.convertError"));
        ready = true;
        return;
    }
    // Queue a work item to perform the update.
    Common.backgroundProcessing.addWorkItem(new PointLinkSetPointWorkItem(vo.getTargetPointId(), newValue, this));
    returnToNormal();
}
Also used : HashMap(java.util.HashMap) NullWriter(org.apache.commons.io.output.NullWriter) ScriptException(javax.script.ScriptException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) PrintWriter(java.io.PrintWriter)

Example 8 with ResultTypeException

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

the class SetPointHandlerRT method eventRaised.

@Override
public void eventRaised(EventInstance evt) {
    if (vo.getActiveAction() == 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;
    }
    int targetDataType = targetPoint.getVO().getPointLocator().getDataTypeId();
    DataValue value;
    if (vo.getActiveAction() == SetPointEventHandlerVO.SET_ACTION_POINT_VALUE) {
        // Get the source data point.
        DataPointRT sourcePoint = Common.runtimeManager.getDataPoint(vo.getActivePointId());
        if (sourcePoint == null) {
            raiseFailureEvent(new TranslatableMessage("event.setPoint.activePointMissing"), evt.getEventType());
            return;
        }
        PointValueTime valueTime = sourcePoint.getPointValue();
        if (valueTime == null) {
            raiseFailureEvent(new TranslatableMessage("event.setPoint.activePointValue"), evt.getEventType());
            return;
        }
        if (DataTypes.getDataType(valueTime.getValue()) != targetDataType) {
            raiseFailureEvent(new TranslatableMessage("event.setPoint.activePointDataType"), evt.getEventType());
            return;
        }
        value = valueTime.getValue();
    } else if (vo.getActiveAction() == SetPointEventHandlerVO.SET_ACTION_STATIC_VALUE) {
        value = DataValue.stringToValue(vo.getActiveValueToSet(), targetDataType);
    } else if (vo.getActiveAction() == SetPointEventHandlerVO.SET_ACTION_SCRIPT_VALUE) {
        if (activeScript == null) {
            raiseFailureEvent(new TranslatableMessage("eventHandlers.invalidActiveScript"), evt.getEventType());
            return;
        }
        Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
        context.put(SetPointEventHandlerVO.TARGET_CONTEXT_KEY, targetPoint);
        Map<String, Object> additionalContext = new HashMap<String, Object>();
        additionalContext.put(SetPointEventHandlerVO.EVENT_CONTEXT_KEY, new EventInstanceWrapper(evt));
        try {
            for (IntStringPair cxt : vo.getAdditionalContext()) {
                DataPointRT dprt = Common.runtimeManager.getDataPoint(cxt.getKey());
                if (dprt != null)
                    context.put(cxt.getValue(), dprt);
            }
            PointValueTime pvt = CompiledScriptExecutor.execute(activeScript, context, additionalContext, evt.getActiveTimestamp(), targetPoint.getDataTypeId(), evt.getActiveTimestamp(), vo.getScriptPermissions(), NULL_WRITER, new ScriptLog(NULL_WRITER, LogLevel.FATAL), setCallback, importExclusions, false);
            value = pvt.getValue();
        } catch (ScriptPermissionsException e) {
            raiseFailureEvent(e.getTranslatableMessage(), evt.getEventType());
            return;
        } catch (ScriptException e) {
            raiseFailureEvent(new TranslatableMessage("eventHandlers.invalidActiveScriptError", e.getCause().getMessage()), evt.getEventType());
            return;
        } catch (ResultTypeException e) {
            raiseFailureEvent(new TranslatableMessage("eventHandlers.invalidActiveScriptError", e.getMessage()), evt.getEventType());
            return;
        }
    } else
        throw new ShouldNeverHappenException("Unknown active action: " + vo.getActiveAction());
    // Queue a work item to perform the set point.
    if (CompiledScriptExecutor.UNCHANGED != value)
        Common.backgroundProcessing.addWorkItem(new SetPointWorkItem(vo.getTargetPointId(), new PointValueTime(value, evt.getActiveTimestamp()), this));
}
Also used : DataValue(com.serotonin.m2m2.rt.dataImage.types.DataValue) HashMap(java.util.HashMap) IntStringPair(com.serotonin.db.pair.IntStringPair) SetPointWorkItem(com.serotonin.m2m2.rt.maint.work.SetPointWorkItem) ScriptLog(com.serotonin.m2m2.rt.script.ScriptLog) ScriptException(javax.script.ScriptException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) EventInstanceWrapper(com.serotonin.m2m2.rt.script.EventInstanceWrapper)

Example 9 with ResultTypeException

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

the class EmailHandlerRT method sendEmail.

private static void sendEmail(EventInstance evt, NotificationType notificationType, Set<String> addresses, String alias, 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(alias)) {
        // Just set the subject to the message
        alias = evt.getMessage().translate(translations);
        // Strip out the HTML and the &nbsp
        alias = StringEscapeUtils.unescapeHtml4(alias);
        // Since we have <br/> in the code and that isn't proper HTML we need to remove it by hand
        alias = alias.replace("<br/>", "\n");
    }
    // end if alias was blank
    // Determine the subject to use.
    TranslatableMessage subjectMsg;
    TranslatableMessage notifTypeMsg = new TranslatableMessage(notificationType.getKey());
    if (StringUtils.isBlank(alias)) {
        // 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", alias, notifTypeMsg);
        else
            subjectMsg = new TranslatableMessage("ftl.subject.alias.id", alias, notifTypeMsg, evt.getId());
    }
    String alarmLevel = AlarmLevels.getAlarmLevelMessage(evt.getAlarmLevel()).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 = addresses.toArray(new String[0]);
        UsedImagesDirective inlineImages = new UsedImagesDirective();
        // Send the email.
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("evt", evt);
        if (evt.getContext() != null)
            model.putAll(evt.getContext());
        model.put("img", inlineImages);
        model.put("instanceDescription", SystemSettingsDao.getValue(SystemSettingsDao.INSTANCE_DESCRIPTION));
        if (includeSystemInfo) {
            // Get the Work Items
            List<WorkItemModel> highPriorityWorkItems = Common.backgroundProcessing.getHighPriorityServiceItems();
            model.put("highPriorityWorkItems", highPriorityWorkItems);
            List<WorkItemModel> mediumPriorityWorkItems = Common.backgroundProcessing.getMediumPriorityServiceQueueItems();
            model.put("mediumPriorityWorkItems", mediumPriorityWorkItems);
            List<WorkItemModel> lowPriorityWorkItems = Common.backgroundProcessing.getLowPriorityServiceQueueItems();
            model.put("lowPriorityWorkItems", lowPriorityWorkItems);
            model.put("threadList", getThreadsList());
        }
        int type = SystemSettingsDao.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, Map<String, Object>> context = new HashMap<>();
            for (IntStringPair pair : additionalContext) {
                Map<String, Object> point = new HashMap<String, Object>();
                DataPointRT rt = Common.runtimeManager.getDataPoint(pair.getKey());
                List<PointValueTime> pointValues;
                List<RenderedPointValueTime> renderedPointValues;
                DataPointVO dpvo;
                if (rt != null) {
                    dpvo = rt.getVO();
                    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.instance.get(pair.getKey());
                    if (dpvo == null)
                        continue;
                    pointValues = Common.databaseProxy.newPointValueDao().getLatestPointValues(pair.getKey(), 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.put("values", renderedPointValues);
                point.put("deviceName", dpvo.getDeviceName());
                point.put("name", dpvo.getName());
                point.put("contextKey", 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.instance.getDataPoint(pair.getKey(), false);
                    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);
                    dprt = new DataPointRT(targetVo, targetVo.getPointLocator().createRuntime(), DataSourceDao.instance.getDataSource(targetVo.getDataSourceId()), null);
                    dprt.resetValues();
                }
                context.put(pair.getValue(), dprt);
            }
            List<JsonImportExclusion> importExclusions = new ArrayList<JsonImportExclusion>(1);
            importExclusions.add(new JsonImportExclusion("xid", handlerXid) {

                @Override
                public String getImporterType() {
                    return ConfigurationExportData.EVENT_HANDLERS;
                }
            });
            try {
                CompiledScript compiledScript = CompiledScriptExecutor.compile(script);
                CompiledScriptExecutor.execute(compiledScript, context, modelContext, Common.timer.currentTimeMillis(), DataTypes.ALPHANUMERIC, evt.isActive() || !evt.isRtnApplicable() ? evt.getActiveTimestamp() : evt.getRtnTimestamp(), permissions, SetPointHandlerRT.NULL_WRITER, new ScriptLog(SetPointHandlerRT.NULL_WRITER, LogLevel.FATAL), setCallback, importExclusions, false);
            } catch (ScriptPermissionsException | ScriptException | ResultTypeException e) {
                LOG.error("Exception running email handler script: " + e.getMessage(), e);
            }
        }
        MangoEmailContent content;
        if (StringUtils.isEmpty(customTemplate))
            content = new MangoEmailContent(notificationType.getFile(), model, translations, subject, Common.UTF8);
        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 (String s : inlineImages.getImageList()) content.addInline(new EmailInline.FileInline(s, Common.getWebPath(s)));
        EmailWorkItem.queueEmail(toAddrs, content, postEmail);
    } catch (Exception e) {
        LOG.error("", e);
    }
}
Also used : CompiledScript(javax.script.CompiledScript) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) JsonImportExclusion(com.serotonin.m2m2.rt.script.JsonImportExclusion) ScriptLog(com.serotonin.m2m2.rt.script.ScriptLog) WorkItemModel(com.serotonin.m2m2.web.mvc.rest.v1.model.workitem.WorkItemModel) ScriptException(javax.script.ScriptException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) RenderedPointValueTime(com.serotonin.m2m2.web.dwr.beans.RenderedPointValueTime) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) UsedImagesDirective(com.serotonin.m2m2.email.UsedImagesDirective) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) DataPointEventType(com.serotonin.m2m2.rt.event.type.DataPointEventType) DataPointVO(com.serotonin.m2m2.vo.DataPointVO) IntStringPair(com.serotonin.db.pair.IntStringPair) ScriptException(javax.script.ScriptException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) IOException(java.io.IOException) PostEmailRunnable(com.serotonin.m2m2.email.PostEmailRunnable) RenderedPointValueTime(com.serotonin.m2m2.web.dwr.beans.RenderedPointValueTime) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) MangoEmailContent(com.serotonin.m2m2.email.MangoEmailContent) Translations(com.serotonin.m2m2.i18n.Translations) Map(java.util.Map) HashMap(java.util.HashMap) File(java.io.File)

Example 10 with ResultTypeException

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

the class ScriptExecutor method getResult.

/**
 * Common method to extract the result
 * @param engine
 * @param result
 * @param dataTypeId
 * @param timestamp
 * @return
 * @throws ResultTypeException
 */
protected static PointValueTime getResult(ScriptEngine engine, Object result, int dataTypeId, long timestamp) throws ResultTypeException {
    // Check if a timestamp was set
    Object ts = engine.getBindings(ScriptContext.ENGINE_SCOPE).get(ScriptUtils.TIMESTAMP_CONTEXT_KEY);
    if (ts != null) {
        // Check the type of the object.
        if (ts instanceof Number)
            // Convert to long
            timestamp = ((Number) ts).longValue();
    // else if (ts instanceof ScriptableObject && "Date".equals(((ScriptableObject)ts).getClassName())) {
    // // A native date
    // // It turns out to be a crazy hack to try and get the value from a native date, and the Rhino source
    // // code FTP server is not responding, so, going to have to leave this for now.
    // }
    }
    DataValue value = ScriptUtils.coerce(result, dataTypeId);
    return new PointValueTime(value, timestamp);
}
Also used : DataValue(com.serotonin.m2m2.rt.dataImage.types.DataValue) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime)

Aggregations

PointValueTime (com.serotonin.m2m2.rt.dataImage.PointValueTime)10 ScriptException (javax.script.ScriptException)9 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)8 IDataPointValueSource (com.serotonin.m2m2.rt.dataImage.IDataPointValueSource)8 ResultTypeException (com.serotonin.m2m2.rt.script.ResultTypeException)8 DataPointRT (com.serotonin.m2m2.rt.dataImage.DataPointRT)7 ScriptLog (com.serotonin.m2m2.rt.script.ScriptLog)7 ScriptPermissionsException (com.serotonin.m2m2.rt.script.ScriptPermissionsException)6 HashMap (java.util.HashMap)6 PrintWriter (java.io.PrintWriter)5 CompiledScript (javax.script.CompiledScript)5 DataValue (com.serotonin.m2m2.rt.dataImage.types.DataValue)4 StringWriter (java.io.StringWriter)4 IntStringPair (com.serotonin.db.pair.IntStringPair)3 ScriptPointValueSetter (com.serotonin.m2m2.rt.script.ScriptPointValueSetter)3 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)3 SimpleDateFormat (java.text.SimpleDateFormat)3 Date (java.util.Date)3 GenericRestException (com.infiniteautomation.mango.rest.v2.exception.GenericRestException)2 ShouldNeverHappenException (com.serotonin.ShouldNeverHappenException)2