Search in sources :

Example 21 with CompiledMangoJavaScript

use of com.infiniteautomation.mango.util.script.CompiledMangoJavaScript in project ma-core-public by MangoAutomation.

the class ScriptingTest method testScriptContextWriter.

@Test
public void testScriptContextWriter() {
    String script = "print('testing context writer');";
    try {
        Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
        final StringWriter scriptOut = new StringWriter();
        final PrintWriter scriptWriter = new PrintWriter(scriptOut);
        try (ScriptLog scriptLog = new ScriptLog("testContextWriter-", LogLevel.TRACE, scriptWriter)) {
            ScriptPointValueSetter setter = null;
            CompiledMangoJavaScript compiled = new CompiledMangoJavaScript(setter, scriptLog, new ArrayList<>(), admin);
            compiled.compile(script, true);
            compiled.initialize(context);
            compiled.execute(Common.timer.currentTimeMillis(), Common.timer.currentTimeMillis(), DataType.NUMERIC);
            String result = scriptOut.toString();
            Assert.assertEquals("testing context writer" + System.lineSeparator(), result);
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : StringWriter(java.io.StringWriter) HashMap(java.util.HashMap) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) CompiledMangoJavaScript(com.infiniteautomation.mango.util.script.CompiledMangoJavaScript) IOException(java.io.IOException) PrintWriter(java.io.PrintWriter) Test(org.junit.Test)

Example 22 with CompiledMangoJavaScript

use of com.infiniteautomation.mango.util.script.CompiledMangoJavaScript in project ma-core-public by MangoAutomation.

the class ScriptingTest method testScriptLog.

@Test
public void testScriptLog() {
    String script = "LOG.trace('Trace message');";
    script += "LOG.debug('Debug message');";
    script += "LOG.info('Info message');";
    script += "LOG.warn('Warn message');";
    script += "LOG.error('Error message');";
    script += "LOG.fatal('Fatal message');";
    try {
        Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
        final StringWriter scriptOut = new StringWriter();
        final PrintWriter scriptWriter = new PrintWriter(scriptOut);
        try (ScriptLog scriptLog = new ScriptLog("testScriptLogger", LogLevel.TRACE, scriptWriter)) {
            ScriptPointValueSetter setter = null;
            CompiledMangoJavaScript compiled = new CompiledMangoJavaScript(setter, scriptLog, new ArrayList<>(), admin);
            compiled.compile(script, true);
            compiled.initialize(context);
            compiled.execute(Common.timer.currentTimeMillis(), Common.timer.currentTimeMillis(), DataType.NUMERIC);
            String result = scriptOut.toString();
            String[] messages = result.split(System.lineSeparator());
            Assert.assertEquals(6, messages.length);
            for (int i = 0; i < messages.length; i++) {
                Pattern p = Pattern.compile(logRegex);
                Matcher m = p.matcher(messages[i]);
                Assert.assertEquals(true, m.matches());
                String level = m.group(1);
                String message = m.group(2);
                switch(level) {
                    case "TRACE":
                        Assert.assertEquals("Trace message", message);
                        break;
                    case "DEBUG":
                        Assert.assertEquals("Debug message", message);
                        break;
                    case "INFO":
                        Assert.assertEquals("Info message", message);
                        break;
                    case "WARN":
                        Assert.assertEquals("Warn message", message);
                        break;
                    case "ERROR":
                        Assert.assertEquals("Error message", message);
                        break;
                    case "FATAL":
                        Assert.assertEquals("Fatal message", message);
                        break;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : Pattern(java.util.regex.Pattern) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) IDataPoint(com.serotonin.m2m2.vo.IDataPoint) IOException(java.io.IOException) StringWriter(java.io.StringWriter) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) CompiledMangoJavaScript(com.infiniteautomation.mango.util.script.CompiledMangoJavaScript) PrintWriter(java.io.PrintWriter) Test(org.junit.Test)

Example 23 with CompiledMangoJavaScript

use of com.infiniteautomation.mango.util.script.CompiledMangoJavaScript in project ma-core-public by MangoAutomation.

the class ScriptingTest method testScriptLogNullWriter.

@Test
public void testScriptLogNullWriter() {
    String script = "LOG.trace('Trace message');";
    script += "LOG.debug('Debug message');";
    script += "LOG.info('Info message');";
    script += "LOG.warn('Warn message');";
    script += "LOG.error('Error message');";
    script += "LOG.fatal('Fatal message');";
    try {
        Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
        try (ScriptLog scriptLog = new ScriptLog("testNullWriter")) {
            ScriptPointValueSetter setter = null;
            CompiledMangoJavaScript compiled = new CompiledMangoJavaScript(setter, scriptLog, new ArrayList<>(), admin);
            compiled.compile(script, true);
            compiled.initialize(context);
            compiled.execute(Common.timer.currentTimeMillis(), Common.timer.currentTimeMillis(), DataType.NUMERIC);
            Assert.assertTrue(!scriptLog.getFile().exists());
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : HashMap(java.util.HashMap) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) CompiledMangoJavaScript(com.infiniteautomation.mango.util.script.CompiledMangoJavaScript) IOException(java.io.IOException) Test(org.junit.Test)

Example 24 with CompiledMangoJavaScript

use of com.infiniteautomation.mango.util.script.CompiledMangoJavaScript in project ma-core-public by MangoAutomation.

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;
    }
    DataType targetDataType = targetPoint.getVO().getPointLocator().getDataType();
    DataValue value = null;
    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 (valueTime.getValue().getDataType() != 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) {
        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(SetPointEventHandlerVO.TARGET_CONTEXT_KEY, 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 activeScript = new CompiledMangoJavaScript(new SetCallback(vo.getScriptRoles()), scriptLog, additionalContext, null, importExclusions, false, service, vo.getScriptRoles());
            activeScript.compile(vo.getActiveScript(), true);
            activeScript.initialize(context);
            MangoJavaScriptResult result = activeScript.execute(Common.timer.currentTimeMillis(), evt.getActiveTimestamp(), 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.invalidActiveScriptError", e.getTranslatableMessage()), 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 (MangoJavaScriptService.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) 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 25 with CompiledMangoJavaScript

use of com.infiniteautomation.mango.util.script.CompiledMangoJavaScript in project ma-core-public by MangoAutomation.

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)

Aggregations

CompiledMangoJavaScript (com.infiniteautomation.mango.util.script.CompiledMangoJavaScript)28 IDataPointValueSource (com.serotonin.m2m2.rt.dataImage.IDataPointValueSource)24 HashMap (java.util.HashMap)24 IOException (java.io.IOException)20 Test (org.junit.Test)18 MangoJavaScriptResult (com.infiniteautomation.mango.util.script.MangoJavaScriptResult)13 PrintWriter (java.io.PrintWriter)13 StringWriter (java.io.StringWriter)13 IDataPoint (com.serotonin.m2m2.vo.IDataPoint)12 PointValueTime (com.serotonin.m2m2.rt.dataImage.PointValueTime)11 ResultTypeException (com.serotonin.m2m2.rt.script.ResultTypeException)10 ScriptError (com.serotonin.m2m2.rt.script.ScriptError)10 Matcher (java.util.regex.Matcher)9 Pattern (java.util.regex.Pattern)9 ShouldNeverHappenException (com.serotonin.ShouldNeverHappenException)8 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)8 ScriptLog (com.serotonin.m2m2.rt.script.ScriptLog)8 ScriptPermissionsException (com.serotonin.m2m2.rt.script.ScriptPermissionsException)8 File (java.io.File)8 IntStringPair (com.serotonin.db.pair.IntStringPair)6