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 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");
}
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 MangoJavaScriptService method compile.
/**
* Compile a script to be run and add global bindings
*/
public CompiledScript compile(String script, boolean wrapInFunction) throws ScriptError {
try {
final ScriptEngine engine = newEngine();
// Add constants to the context
Bindings globalBindings = new SimpleBindings();
// left here for legacy compatibility
globalBindings.put("SECOND", Common.TimePeriods.SECONDS);
globalBindings.put("MINUTE", Common.TimePeriods.MINUTES);
globalBindings.put("HOUR", Common.TimePeriods.HOURS);
globalBindings.put("DAY", Common.TimePeriods.DAYS);
globalBindings.put("WEEK", Common.TimePeriods.WEEKS);
globalBindings.put("MONTH", Common.TimePeriods.MONTHS);
globalBindings.put("YEAR", Common.TimePeriods.YEARS);
for (IntStringPair isp : Common.TIME_PERIOD_CODES.getIdKeys()) globalBindings.put(Common.TIME_PERIOD_CODES.getCode(isp.getKey()), isp.getKey());
for (IntStringPair isp : Common.ROLLUP_CODES.getIdKeys(Common.Rollups.NONE)) globalBindings.put(Common.ROLLUP_CODES.getCode(isp.getKey()), isp.getKey());
// Add in Additional Utilities with Global Scope
globalBindings.put(DateTimeUtility.CONTEXT_KEY, new DateTimeUtility());
globalBindings.put(UnitUtility.CONTEXT_KEY, new UnitUtility());
engine.setBindings(globalBindings, ScriptContext.GLOBAL_SCOPE);
String toCompile;
if (wrapInFunction) {
toCompile = SCRIPT_PREFIX + script + SCRIPT_SUFFIX;
} else {
toCompile = script;
}
return ((Compilable) engine).compile(toCompile);
} catch (ScriptException e) {
throw ScriptError.create(e, wrapInFunction);
}
}
use of com.serotonin.m2m2.rt.script.ScriptError in project ma-core-public by infiniteautomation.
the class MangoJavaScriptService method execute.
/**
* Reset result and execute script for any type of result
*/
public void execute(CompiledMangoJavaScript script, long runtime, long timestamp) throws ScriptError, ScriptPermissionsException {
try {
runAs.runAsCallable(script.getPermissionHolder(), () -> {
script.getResult().reset();
// Setup the wrapper context
Bindings engineScope = script.getEngine().getBindings(ScriptContext.ENGINE_SCOPE);
engineScope.put(MangoJavaScriptService.WRAPPER_CONTEXT_KEY, new WrapperContext(runtime, timestamp));
// Ensure the result is available to the utilities
for (ScriptUtility util : script.getUtilities()) {
util.setResult(script.getResult());
}
// Initialize additional utilities
for (ScriptUtility util : script.getAdditionalUtilities()) util.setResult(script.getResult());
Object resultObject = script.getCompiledScript().eval();
script.getResult().setResult(resultObject);
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) {
throw new ShouldNeverHappenException(e);
}
}
Aggregations