use of com.serotonin.m2m2.rt.script.ScriptError in project ma-core-public by infiniteautomation.
the class MangoJavaScriptService method testScript.
/**
*/
public MangoJavaScriptResult testScript(MangoJavaScript vo, BiFunction<MangoJavaScriptResult, PermissionHolder, ScriptPointValueSetter> createSetter, String noChangeKey) {
PermissionHolder user = Common.getUser();
ensureValid(vo);
final StringWriter scriptOut = new StringWriter();
MangoJavaScriptResult result = new MangoJavaScriptResult();
try {
final PrintWriter scriptWriter = new PrintWriter(scriptOut);
try (ScriptLog scriptLog = new ScriptLog("scriptTest-" + user.getPermissionHolderName(), vo.getLogLevel(), scriptWriter)) {
CompiledMangoJavaScript script = new CompiledMangoJavaScript(vo, createSetter.apply(result, vo.getPermissions()), scriptLog, result, this, pointValueDao, pointValueCache);
script.compile(vo.getScript(), vo.isWrapInFunction());
script.initialize(vo.getContext());
long time = Common.timer.currentTimeMillis();
runAs.runAsCallable(vo.getPermissions(), () -> {
if (vo.getResultDataType() != null) {
script.execute(time, time, vo.getResultDataType());
// Convert the UNCHANGED value
Object o = script.getResult().getResult();
if (o instanceof PointValueTime && ((PointValueTime) o).getValue() == UNCHANGED) {
// TODO fix this display hack:
String unchanged = new TranslatableMessage(noChangeKey).translate(Translations.getTranslations(user.getLocaleObject()));
script.getResult().setResult(new PointValueTime(unchanged, ((PointValueTime) o).getTime()));
}
} 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 e) {
result.addError(new MangoJavaScriptError(e.getTranslatableMessage()));
} catch (Exception e) {
result.addError(new MangoJavaScriptError(e.getMessage()));
} finally {
result.setScriptOutput(scriptOut.toString());
}
return result;
}
use of com.serotonin.m2m2.rt.script.ScriptError in project ma-core-public by infiniteautomation.
the class EmailHandlerRT method sendEmail.
private static void sendEmail(EventInstance evt, NotificationType notificationType, Set<String> addresses, String baseSubject, 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(baseSubject)) {
// Just set the subject to the message
baseSubject = evt.getMessage().translate(translations);
// Strip out the HTML and the  
baseSubject = StringEscapeUtils.unescapeHtml4(baseSubject);
// Since we have <br/> in the code and that isn't proper HTML we need to remove it by hand
baseSubject = baseSubject.replace("<br/>", "\n");
}
// end if alias was blank
// Determine the subject to use.
TranslatableMessage subjectMsg;
TranslatableMessage notifTypeMsg = new TranslatableMessage(notificationType.getKey());
if (StringUtils.isBlank(baseSubject)) {
// 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", baseSubject, notifTypeMsg);
else
subjectMsg = new TranslatableMessage("ftl.subject.alias.id", baseSubject, notifTypeMsg, evt.getId());
}
String alarmLevel = evt.getAlarmLevel().getDescription().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;
if (addresses == null)
toAddrs = new String[0];
else
toAddrs = addresses.toArray(new String[0]);
UsedImagesDirective inlineImages = new UsedImagesDirective();
// Send the email.
Map<String, Object> model = new HashMap<String, Object>();
model.put(EventInstance.CONTEXT_KEY, evt);
model.put(EventInstanceWrapper.CONTEXT_KEY, new EventInstanceWrapper(evt));
if (evt.getContext() != null)
model.putAll(evt.getContext());
model.put("img", inlineImages);
model.put("instanceDescription", SystemSettingsDao.getInstance().getValue(SystemSettingsDao.INSTANCE_DESCRIPTION));
if (includeSystemInfo) {
// Get the Work Items
List<WorkItemInfo> highPriorityWorkItems = Common.backgroundProcessing.getHighPriorityServiceItems();
model.put("highPriorityWorkItems", highPriorityWorkItems);
List<WorkItemInfo> mediumPriorityWorkItems = Common.backgroundProcessing.getMediumPriorityServiceQueueItems();
model.put("mediumPriorityWorkItems", mediumPriorityWorkItems);
List<WorkItemInfo> lowPriorityWorkItems = Common.backgroundProcessing.getLowPriorityServiceQueueItems();
model.put("lowPriorityWorkItems", lowPriorityWorkItems);
model.put("threadList", getThreadsList());
}
int type = SystemSettingsDao.getInstance().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, EmailPointWrapper> context = new HashMap<>();
for (IntStringPair pair : additionalContext) {
EmailPointWrapper point;
DataPointRT rt = Common.runtimeManager.getDataPoint(pair.getKey());
List<PointValueTime> pointValues;
List<RenderedPointValueTime> renderedPointValues;
DataPointVO dpvo;
if (rt != null) {
dpvo = rt.getVO();
point = new EmailPointWrapper(dpvo);
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.getInstance().get(pair.getKey());
if (dpvo == null)
continue;
point = new EmailPointWrapper(dpvo);
pointValues = Common.getBean(PointValueDao.class).getLatestPointValues(dpvo, 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.setRawValues(pointValues);
point.setValues(renderedPointValues);
point.setContextKey(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.getInstance().get(pair.getKey());
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);
DataPointWithEventDetectors dp = new DataPointWithEventDetectors(targetVo, new ArrayList<>());
DataSourceRT<? extends DataSourceVO> dataSource = DataSourceDao.getInstance().get(targetVo.getDataSourceId()).createDataSourceRT();
dprt = new DataPointRT(dp, targetVo.getPointLocator().createRuntime(), dataSource, null, Common.getBean(PointValueDao.class), Common.getBean(PointValueCache.class));
}
context.put(pair.getValue(), dprt);
}
modelContext.put(DO_NOT_SEND_KEY, MangoJavaScriptService.UNCHANGED);
List<JsonImportExclusion> importExclusions = new ArrayList<JsonImportExclusion>(1);
importExclusions.add(new JsonImportExclusion("xid", handlerXid) {
@Override
public String getImporterType() {
return ConfigurationExportData.EVENT_HANDLERS;
}
});
try (ScriptLog scriptLog = new ScriptLog("emailScript-" + evt.getId())) {
MangoJavaScriptService service = Common.getBean(MangoJavaScriptService.class);
long time = evt.isActive() || !evt.isRtnApplicable() ? evt.getActiveTimestamp() : evt.getRtnTimestamp();
CompiledMangoJavaScript compiledScript = new CompiledMangoJavaScript(setCallback, scriptLog, modelContext, null, importExclusions, false, service, permissions);
compiledScript.compile(script, true);
compiledScript.initialize(context);
MangoJavaScriptResult r = compiledScript.execute(Common.timer.currentTimeMillis(), time, DataType.ALPHANUMERIC);
PointValueTime result = (PointValueTime) r.getResult();
if (// The script cancelled the email
result != null && result.getValue() == MangoJavaScriptService.UNCHANGED)
return;
} catch (ScriptError | ResultTypeException e) {
LOG.error("Exception running email handler script: " + e.getTranslatableMessage(), e);
}
}
MangoEmailContent content;
if (StringUtils.isEmpty(customTemplate))
content = new MangoEmailContent(notificationType.getFile(), model, translations, subject, StandardCharsets.UTF_8);
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 (Entry<Path, UUID> entry : inlineImages.getImageList().entrySet()) {
content.addInline(new FileInline(entry.getValue().toString(), entry.getKey().toFile()));
}
if (toAddrs.length > 0)
EmailWorkItem.queueEmail(toAddrs, content, postEmail);
} catch (Exception e) {
LOG.error("Error sending email", e);
}
}
use of com.serotonin.m2m2.rt.script.ScriptError 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;
}
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));
}
use of com.serotonin.m2m2.rt.script.ScriptError in project ma-core-public by infiniteautomation.
the class CompiledMangoJavaScript method initialize.
/**
* Clear the engine scope and initialize it with an expandable context which is filled with the ScriptContextVariables and returned
*
* @throws ScriptPermissionsException - permission denied executing a command
* @throws ScriptError - Execution failure, generally will have line and column number with message
* @throws DataPointStateException - If a point is not enabled or missing (unless testRun is true, then a dummy point is created)
*/
public Map<String, IDataPointValueSource> initialize(List<ScriptContextVariable> variables) throws ScriptPermissionsException, ScriptError, DataPointStateException {
Map<String, IDataPointValueSource> context = new HashMap<>();
if (variables != null) {
for (ScriptContextVariable variable : variables) {
DataPointVO dpvo = DataPointDao.getInstance().get(variable.getDataPointId());
if (dpvo != null) {
DataPointRT dprt = Common.runtimeManager.getDataPoint(dpvo.getId());
// So we can test with points disabled
if (dprt == null) {
if (testRun) {
if (dpvo.getDefaultCacheSize() == 0) {
dpvo.setDefaultCacheSize(1);
}
// Generate some fake event detectors
DataPointWithEventDetectors dp = new DataPointWithEventDetectors(dpvo, new ArrayList<>());
DataSourceRT<? extends DataSourceVO> dataSource = DataSourceDao.getInstance().get(dpvo.getDataSourceId()).createDataSourceRT();
dprt = new DataPointRT(dp, dpvo.getPointLocator().createRuntime(), dataSource, null, pointValueDao, pointValueCache);
} else {
throw new DataPointStateException(variable.getDataPointId(), new TranslatableMessage("event.script.contextPointDisabled", variable.getVariableName(), dpvo.getXid()));
}
}
if (dprt != null)
context.put(variable.getVariableName(), dprt);
} else {
throw new DataPointStateException(variable.getDataPointId(), new TranslatableMessage("event.script.contextPointMissing", variable.getVariableName(), variable.getDataPointId()));
}
}
}
this.initialize(context);
return context;
}
use of com.serotonin.m2m2.rt.script.ScriptError in project ma-core-public by MangoAutomation.
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