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);
}
}
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);
}
}
use of com.serotonin.m2m2.rt.script.ScriptError in project ma-core-public by infiniteautomation.
the class MangoJavaScriptService method executeScript.
/**
* The preferred way to execute a script
*/
public MangoJavaScriptResult executeScript(MangoJavaScript vo, ScriptPointValueSetter setter) throws ValidationException, PermissionException {
PermissionHolder user = Common.getUser();
ensureValid(vo);
MangoJavaScriptResult result = new MangoJavaScriptResult();
final Writer scriptOut;
final PrintWriter scriptWriter;
if (vo.isReturnLogOutput()) {
scriptOut = new StringWriter();
scriptWriter = new PrintWriter(scriptOut);
} else {
NullWriter writer = new NullWriter();
scriptWriter = new NullPrintWriter(writer);
scriptOut = writer;
}
try {
try (ScriptLogExtender scriptLog = new ScriptLogExtender("scriptTest-" + user.getPermissionHolderName(), vo.getLogLevel(), scriptWriter, vo.getLog(), vo.isCloseLog())) {
CompiledMangoJavaScript script = new CompiledMangoJavaScript(vo, setter, scriptLog, result, this, pointValueDao, pointValueCache);
script.compile(vo.getScript(), vo.isWrapInFunction());
script.initialize(vo.getContext());
long time = Common.timer.currentTimeMillis();
runAs.runAsCallable(script.getPermissionHolder(), () -> {
if (vo.getResultDataType() != null) {
script.execute(time, time, vo.getResultDataType());
} else {
script.execute(time, time);
}
return null;
});
}
} catch (ScriptError e) {
// The script exception should be clean as both compile() and execute() clean it
result.addError(new MangoJavaScriptError(e.getTranslatableMessage(), e.getLineNumber(), e.getColumnNumber()));
} catch (ResultTypeException | DataPointStateException e) {
result.addError(new MangoJavaScriptError(e.getTranslatableMessage()));
} catch (Exception e) {
result.addError(new MangoJavaScriptError(e.getMessage()));
} finally {
if (vo.isReturnLogOutput())
result.setScriptOutput(scriptOut.toString());
}
return result;
}
use of com.serotonin.m2m2.rt.script.ScriptError in project ma-core-public by infiniteautomation.
the class SetPointEventHandlerDefinition method commonValidation.
private void commonValidation(ProcessResult response, SetPointEventHandlerVO vo) {
DataPointVO dp = DataPointDao.getInstance().get(vo.getTargetPointId());
DataType dataType = null;
if (dp == null)
response.addContextualMessage("targetPointId", "eventHandlers.noTargetPoint");
else {
dataType = dp.getPointLocator().getDataType();
if (!dp.getPointLocator().isSettable())
response.addContextualMessage("targetPointId", "event.setPoint.targetNotSettable");
}
if (vo.getActiveAction() == SetPointEventHandlerVO.SET_ACTION_NONE && vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_NONE) {
response.addContextualMessage("activeAction", "eventHandlers.noSetPointAction");
response.addContextualMessage("inactiveAction", "eventHandlers.noSetPointAction");
}
MangoJavaScriptService javaScriptService = Common.getBean(MangoJavaScriptService.class);
// Active
if (vo.getActiveAction() == SetPointEventHandlerVO.SET_ACTION_STATIC_VALUE && dataType == DataType.MULTISTATE) {
try {
Integer.parseInt(vo.getActiveValueToSet());
} catch (NumberFormatException e) {
response.addContextualMessage("activeValueToSet", "eventHandlers.invalidActiveValue");
}
} else if (vo.getActiveAction() == SetPointEventHandlerVO.SET_ACTION_STATIC_VALUE && dataType == DataType.NUMERIC) {
try {
Double.parseDouble(vo.getActiveValueToSet());
} catch (NumberFormatException e) {
response.addContextualMessage("activeValueToSet", "eventHandlers.invalidActiveValue");
}
} else if (vo.getActiveAction() == SetPointEventHandlerVO.SET_ACTION_POINT_VALUE) {
DataPointVO dpActive = DataPointDao.getInstance().get(vo.getActivePointId());
if (dpActive == null)
response.addContextualMessage("activePointId", "eventHandlers.invalidActiveSource");
else if (dataType != dpActive.getPointLocator().getDataType())
response.addContextualMessage("activeDataPointId", "eventHandlers.invalidActiveSourceType");
} else if (vo.getActiveAction() == SetPointEventHandlerVO.SET_ACTION_SCRIPT_VALUE) {
if (StringUtils.isEmpty(vo.getActiveScript())) {
response.addContextualMessage("activeScript", "eventHandlers.invalidActiveScript");
} else {
try {
javaScriptService.compile(vo.getActiveScript(), true);
} catch (ScriptError e) {
response.addContextualMessage("activeScript", "eventHandlers.invalidActiveScriptError", e.getTranslatableMessage());
}
}
}
// Inactive
if (vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_STATIC_VALUE && dataType == DataType.MULTISTATE) {
try {
Integer.parseInt(vo.getInactiveValueToSet());
} catch (NumberFormatException e) {
response.addContextualMessage("inactiveValueToSet", "eventHandlers.invalidInactiveValue");
}
} else if (vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_STATIC_VALUE && dataType == DataType.NUMERIC) {
try {
Double.parseDouble(vo.getInactiveValueToSet());
} catch (NumberFormatException e) {
response.addContextualMessage("inactiveValueToSet", "eventHandlers.invalidInactiveValue");
}
} else if (vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_POINT_VALUE) {
DataPointVO dpInactive = DataPointDao.getInstance().get(vo.getInactivePointId());
if (dpInactive == null)
response.addContextualMessage("inactivePointId", "eventHandlers.invalidInactiveSource");
else if (dataType != dpInactive.getPointLocator().getDataType())
response.addContextualMessage("inactivePointId", "eventHandlers.invalidInactiveSourceType");
} else if (vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_SCRIPT_VALUE) {
if (StringUtils.isEmpty(vo.getInactiveScript())) {
response.addContextualMessage("inactiveScript", "eventHandlers.invalidInactiveScript");
} else {
try {
javaScriptService.compile(vo.getInactiveScript(), true);
} catch (ScriptError e) {
response.addContextualMessage("inactiveScript", "eventHandlers.invalidActiveScriptError", e.getTranslatableMessage());
}
}
}
if (vo.getAdditionalContext() != null)
validateScriptContext(vo.getAdditionalContext(), response);
else
vo.setAdditionalContext(new ArrayList<>());
}
use of com.serotonin.m2m2.rt.script.ScriptError in project ma-core-public by infiniteautomation.
the class EmailEventHandlerDefinition method commonValidation.
private void commonValidation(ProcessResult result, EmailEventHandlerVO vo) {
if (vo.getActiveRecipients() != null) {
int pos = 0;
for (MailingListRecipient b : vo.getActiveRecipients()) {
mailingListService.validateRecipient("activeRecipients[" + pos + "]", b, result, RecipientListEntryType.ADDRESS, RecipientListEntryType.MAILING_LIST, RecipientListEntryType.USER);
pos++;
}
}
if (vo.isSendEscalation()) {
if (vo.getEscalationDelay() <= 0)
result.addContextualMessage("escalationDelay", "eventHandlers.escalDelayError");
if (!Common.TIME_PERIOD_CODES.isValidId(vo.getEscalationDelayType()))
result.addContextualMessage("escalationDelayType", "validate.invalidValue");
if (vo.getEscalationRecipients() != null) {
int pos = 0;
for (MailingListRecipient b : vo.getEscalationRecipients()) {
mailingListService.validateRecipient("escalationRecipients[" + pos + "]", b, result, RecipientListEntryType.ADDRESS, RecipientListEntryType.MAILING_LIST, RecipientListEntryType.USER);
pos++;
}
}
} else if (vo.isRepeatEscalations()) {
vo.setRepeatEscalations(false);
}
if (StringUtils.isNotEmpty(vo.getCustomTemplate())) {
try {
new Template("customTemplate", new StringReader(vo.getCustomTemplate()), Common.freemarkerConfiguration);
} catch (Exception e) {
result.addContextualMessage("customTemplate", "common.default", e.getMessage());
}
}
if (vo.getAdditionalContext() != null)
validateScriptContext(vo.getAdditionalContext(), result);
else {
vo.setAdditionalContext(new ArrayList<>());
}
if (!StringUtils.isEmpty(vo.getScript())) {
MangoJavaScriptService service = Common.getBean(MangoJavaScriptService.class);
try {
service.compile(vo.getScript(), true);
} catch (ScriptError e) {
result.addContextualMessage("script", "eventHandlers.invalidActiveScriptError", e.getTranslatableMessage());
}
}
if (!EmailEventHandlerVO.SUBJECT_INCLUDE_CODES.isValidId(vo.getSubject()))
result.addContextualMessage("subject", "validate.invalidValue");
}
Aggregations