use of com.infiniteautomation.mango.util.script.CompiledMangoJavaScript 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;
}
use of com.infiniteautomation.mango.util.script.CompiledMangoJavaScript in project ma-core-public by infiniteautomation.
the class ScriptingTest method testScriptLogWriteNullValue.
@Test
public void testScriptLogWriteNullValue() {
String script = "LOG.trace(null);";
script += "LOG.debug(null);";
script += "LOG.info(null);";
script += "LOG.warn(null);";
script += "LOG.error(null);";
script += "LOG.fatal(null);";
script += "print(null);";
try {
Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
// Delete the file
File log = new File(Common.getLogsDir(), "testNullValueWriter-1.log");
if (log.exists()) {
log.delete();
log.createNewFile();
}
try (ScriptLog scriptLog = new ScriptLog("testNullValueWriter-1", LogLevel.TRACE, 100000, 2)) {
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());
String result = readFile(scriptLog.getFile().toPath());
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("null", message);
break;
case "DEBUG":
Assert.assertEquals("null", message);
break;
case "INFO":
Assert.assertEquals("null", message);
break;
case "WARN":
Assert.assertEquals("null", message);
break;
case "ERROR":
Assert.assertEquals("null", message);
break;
case "FATAL":
Assert.assertEquals("null", message);
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
use of com.infiniteautomation.mango.util.script.CompiledMangoJavaScript in project ma-core-public by infiniteautomation.
the class ScriptingTest method testScriptLogFileWriter.
@Test
public void testScriptLogFileWriter() {
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');";
script += "print('Print message');";
try {
Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
// Delete the file
File log = new File(Common.getLogsDir(), "testFileWriter-1.log");
if (log.exists()) {
log.delete();
log.createNewFile();
}
try (ScriptLog scriptLog = new ScriptLog("testFileWriter-1", LogLevel.TRACE, 100000, 2)) {
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());
String result = readFile(scriptLog.getFile().toPath());
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());
}
}
use of com.infiniteautomation.mango.util.script.CompiledMangoJavaScript in project ma-core-public by infiniteautomation.
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());
}
}
use of com.infiniteautomation.mango.util.script.CompiledMangoJavaScript 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));
}
Aggregations