use of com.serotonin.m2m2.rt.script.ScriptPermissions in project ma-modules-public by infiniteautomation.
the class PointLinksDwr method validateScript.
@DwrPermission(user = true)
public ProcessResult validateScript(String script, int sourcePointId, int targetPointId, ScriptPermissions permissions, int logLevel) {
ProcessResult response = new ProcessResult();
TranslatableMessage message;
DataPointRT source = Common.runtimeManager.getDataPoint(sourcePointId);
if (source == null) {
DataPointVO sourceVo = DataPointDao.instance.getDataPoint(sourcePointId, false);
if (sourceVo == null) {
message = new TranslatableMessage("pointLinks.validate.sourceRequired");
response.addMessage("script", message);
return response;
}
if (sourceVo.getDefaultCacheSize() == 0)
sourceVo.setDefaultCacheSize(1);
source = new DataPointRT(sourceVo, sourceVo.getPointLocator().createRuntime(), DataSourceDao.instance.getDataSource(sourceVo.getDataSourceId()), null);
source.resetValues();
}
DataPointRT target = Common.runtimeManager.getDataPoint(targetPointId);
if (target == null) {
DataPointVO targetVo = DataPointDao.instance.getDataPoint(targetPointId, false);
if (targetVo == null) {
message = new TranslatableMessage("pointLinks.validate.targetRequired");
response.addMessage("script", message);
return response;
}
if (targetVo.getDefaultCacheSize() == 0)
targetVo.setDefaultCacheSize(1);
target = new DataPointRT(targetVo, targetVo.getPointLocator().createRuntime(), DataSourceDao.instance.getDataSource(targetVo.getDataSourceId()), null);
target.resetValues();
}
Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
context.put(PointLinkRT.CONTEXT_SOURCE_VAR_NAME, source);
context.put(PointLinkRT.CONTEXT_TARGET_VAR_NAME, target);
int targetDataType = target.getDataTypeId();
final StringWriter scriptOut = new StringWriter();
final PrintWriter scriptWriter = new PrintWriter(scriptOut);
ScriptLog scriptLog = new ScriptLog(scriptWriter, logLevel);
final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYY HH:mm:ss");
ScriptPointValueSetter loggingSetter = new ScriptPointValueSetter(permissions) {
@Override
public void set(IDataPointValueSource point, Object value, long timestamp, String annotation) {
DataPointRT dprt = (DataPointRT) point;
if (!dprt.getVO().getPointLocator().isSettable()) {
scriptOut.append("Point " + dprt.getVO().getExtendedName() + " not settable.");
return;
}
if (!Permissions.hasPermission(dprt.getVO().getSetPermission(), permissions.getDataPointSetPermissions())) {
scriptOut.write(new TranslatableMessage("pointLinks.setTest.permissionDenied", dprt.getVO().getXid()).translate(Common.getTranslations()));
return;
}
scriptOut.append("Setting point " + dprt.getVO().getName() + " to " + value + " @" + sdf.format(new Date(timestamp)) + "\r\n");
}
@Override
protected void setImpl(IDataPointValueSource point, Object value, long timestamp, String annotation) {
// not really setting
}
};
try {
CompiledScript compiledScript = CompiledScriptExecutor.compile(script);
PointValueTime pvt = CompiledScriptExecutor.execute(compiledScript, context, null, System.currentTimeMillis(), targetDataType, -1, permissions, scriptWriter, scriptLog, loggingSetter, null, true);
if (pvt.getValue() == null)
message = new TranslatableMessage("event.pointLink.nullResult");
else if (pvt.getValue() == CompiledScriptExecutor.UNCHANGED)
message = new TranslatableMessage("pointLinks.validate.successNoValue");
else if (pvt.getTime() == -1)
message = new TranslatableMessage("pointLinks.validate.success", pvt.getValue());
else
message = new TranslatableMessage("pointLinks.validate.successTs", pvt.getValue(), Functions.getTime(pvt.getTime()));
// Add the script logging output
response.addData("out", scriptOut.toString().replaceAll("\n", "<br/>"));
} catch (ScriptException e) {
message = new TranslatableMessage("pointLinks.validate.scriptError", e.getMessage());
} catch (ResultTypeException e) {
message = e.getTranslatableMessage();
}
response.addMessage("script", message);
return response;
}
use of com.serotonin.m2m2.rt.script.ScriptPermissions in project ma-modules-public by infiniteautomation.
the class ScriptUtilRestController method testScript.
@PreAuthorize("isAdmin()")
@ApiOperation(value = "Test a script")
@ApiResponses({ @ApiResponse(code = 401, message = "Unauthorized user access", response = ResponseEntity.class), @ApiResponse(code = 500, message = "Error processing request", response = ResponseEntity.class) })
@RequestMapping(method = RequestMethod.POST, value = { "/test" }, consumes = { "application/json" }, produces = { "application/json" })
public ResponseEntity<ScriptRestResult> testScript(@AuthenticationPrincipal User user, @RequestBody ScriptRestModel scriptModel) {
if (LOG.isDebugEnabled())
LOG.debug("Testing script for: " + user.getName());
Map<String, IDataPointValueSource> context = convertContextModel(scriptModel.getContext(), true);
try {
CompiledScript script = CompiledScriptExecutor.compile(scriptModel.getScript());
final StringWriter scriptOut = new StringWriter();
final PrintWriter scriptWriter = new PrintWriter(scriptOut);
int logLevel = ScriptLog.LogLevel.FATAL;
if (StringUtils.isEmpty(scriptModel.getLogLevel())) {
int levelId = ScriptLog.LOG_LEVEL_CODES.getId(scriptModel.getLogLevel());
if (levelId == -1)
throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, new TranslatableMessage("rest.script.error.unknownLogLevel", scriptModel.getLogLevel()));
else
logLevel = levelId;
}
ScriptLog scriptLog = new ScriptLog(scriptWriter, logLevel);
final ScriptPermissions permissions = scriptModel.getPermissions().toPermissions();
final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYY HH:mm:ss");
ScriptPointValueSetter loggingSetter = new ScriptPointValueSetter(permissions) {
@Override
public void set(IDataPointValueSource point, Object value, long timestamp, String annotation) {
DataPointRT dprt = (DataPointRT) point;
if (!dprt.getVO().getPointLocator().isSettable()) {
scriptOut.append("Point " + dprt.getVO().getExtendedName() + " not settable.");
return;
}
if (!Permissions.hasPermission(dprt.getVO().getSetPermission(), permissions.getDataPointSetPermissions())) {
scriptOut.write(new TranslatableMessage("pointLinks.setTest.permissionDenied", dprt.getVO().getXid()).translate(Common.getTranslations()));
return;
}
scriptOut.append("Setting point " + dprt.getVO().getName() + " to " + value + " @" + sdf.format(new Date(timestamp)) + "\r\n");
}
@Override
protected void setImpl(IDataPointValueSource point, Object value, long timestamp, String annotation) {
// not really setting
}
};
try {
PointValueTime pvt = CompiledScriptExecutor.execute(script, context, new HashMap<String, Object>(), Common.timer.currentTimeMillis(), DataTypes.ALPHANUMERIC, Common.timer.currentTimeMillis(), permissions, scriptWriter, scriptLog, loggingSetter, null, true);
if (LOG.isDebugEnabled())
LOG.debug("Script output: " + scriptOut.toString());
return new ResponseEntity<>(new ScriptRestResult(scriptOut.toString(), new PointValueTimeModel(pvt)), HttpStatus.OK);
} catch (ResultTypeException e) {
throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, e);
}
} catch (ScriptException e) {
throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, e);
}
}
use of com.serotonin.m2m2.rt.script.ScriptPermissions in project ma-modules-public by infiniteautomation.
the class ScriptUtilRestController method runScript.
@PreAuthorize("isAdmin()")
@ApiOperation(value = "Run a script")
@ApiResponses({ @ApiResponse(code = 401, message = "Unauthorized user access", response = ResponseEntity.class), @ApiResponse(code = 500, message = "Error processing request", response = ResponseEntity.class) })
@RequestMapping(method = RequestMethod.POST, value = { "/run" }, consumes = { "application/json" }, produces = { "application/json" })
public ResponseEntity<ScriptRestResult> runScript(@AuthenticationPrincipal User user, @RequestBody ScriptRestModel scriptModel) {
if (LOG.isDebugEnabled())
LOG.debug("Running script for: " + user.getName());
Map<String, IDataPointValueSource> context = convertContextModel(scriptModel.getContext(), false);
try {
CompiledScript script = CompiledScriptExecutor.compile(scriptModel.getScript());
final StringWriter scriptOut = new StringWriter();
final PrintWriter scriptWriter = new PrintWriter(scriptOut);
int logLevel = ScriptLog.LogLevel.FATAL;
if (StringUtils.isEmpty(scriptModel.getLogLevel())) {
int levelId = ScriptLog.LOG_LEVEL_CODES.getId(scriptModel.getLogLevel());
if (levelId == -1)
throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, new TranslatableMessage("rest.script.error.unknownLogLevel", scriptModel.getLogLevel()));
else
logLevel = levelId;
}
ScriptLog scriptLog = new ScriptLog(scriptWriter, logLevel);
ScriptPermissions permissions = scriptModel.getPermissions().toPermissions();
try {
PointValueTime pvt = CompiledScriptExecutor.execute(script, context, new HashMap<String, Object>(), Common.timer.currentTimeMillis(), DataTypes.ALPHANUMERIC, Common.timer.currentTimeMillis(), permissions, scriptWriter, scriptLog, new SetCallback(permissions, user), null, false);
if (LOG.isDebugEnabled())
LOG.debug("Script output: " + scriptOut.toString());
return new ResponseEntity<>(new ScriptRestResult(scriptOut.toString(), new PointValueTimeModel(pvt)), HttpStatus.OK);
} catch (ResultTypeException | ScriptPermissionsException e) {
throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, e);
}
} catch (ScriptException e) {
throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, e);
}
}
use of com.serotonin.m2m2.rt.script.ScriptPermissions in project ma-core-public by infiniteautomation.
the class EmailEventHandlerVO method jsonWrite.
@Override
public void jsonWrite(ObjectWriter writer) throws IOException, JsonException {
super.jsonWrite(writer);
writer.writeEntry("activeRecipients", activeRecipients);
writer.writeEntry("sendEscalation", sendEscalation);
if (sendEscalation) {
writer.writeEntry("escalationDelayType", Common.TIME_PERIOD_CODES.getCode(escalationDelayType));
writer.writeEntry("escalationDelay", escalationDelay);
writer.writeEntry("escalationRecipients", escalationRecipients);
writer.writeEntry("keepSendingEscalations", repeatEscalations);
}
writer.writeEntry("sendInactive", sendInactive);
if (sendInactive) {
writer.writeEntry("inactiveOverride", inactiveOverride);
if (inactiveOverride)
writer.writeEntry("inactiveRecipients", inactiveRecipients);
}
writer.writeEntry("includeSystemInformation", includeSystemInfo);
writer.writeEntry("includePointValueCount", includePointValueCount);
writer.writeEntry("includeLogfile", includeLogfile);
writer.writeEntry("customTemplate", customTemplate);
JsonArray context = new JsonArray();
for (IntStringPair pnt : additionalContext) {
DataPointVO dpvo = DataPointDao.instance.get(pnt.getKey());
if (dpvo != null) {
JsonObject point = new JsonObject();
point.put("dataPointXid", dpvo.getXid());
point.put("contextKey", pnt.getValue());
context.add(point);
}
}
writer.writeEntry("additionalContext", context);
writer.writeEntry("script", script);
if (scriptPermissions != null) {
JsonObject permissions = new JsonObject();
permissions.put(ScriptPermissions.DATA_SOURCE, scriptPermissions.getDataSourcePermissions());
permissions.put(ScriptPermissions.DATA_POINT_READ, scriptPermissions.getDataPointReadPermissions());
permissions.put(ScriptPermissions.DATA_POINT_SET, scriptPermissions.getDataPointSetPermissions());
writer.writeEntry("scriptPermissions", permissions);
} else {
writer.writeEntry("scriptPermissions", null);
}
}
use of com.serotonin.m2m2.rt.script.ScriptPermissions in project ma-core-public by infiniteautomation.
the class EmailEventHandlerVO method jsonRead.
@SuppressWarnings("unchecked")
@Override
public void jsonRead(JsonReader reader, JsonObject jsonObject) throws JsonException {
super.jsonRead(reader, jsonObject);
String text = null;
TypeDefinition recipType = new TypeDefinition(List.class, RecipientListEntryBean.class);
JsonArray jsonActiveRecipients = jsonObject.getJsonArray("activeRecipients");
if (jsonActiveRecipients != null)
activeRecipients = (List<RecipientListEntryBean>) reader.read(recipType, jsonActiveRecipients);
JsonBoolean b = jsonObject.getJsonBoolean("sendEscalation");
if (b != null)
sendEscalation = b.booleanValue();
if (sendEscalation) {
text = jsonObject.getString("escalationDelayType");
if (text != null) {
escalationDelayType = Common.TIME_PERIOD_CODES.getId(text);
if (escalationDelayType == -1)
throw new TranslatableJsonException("emport.error.invalid", "escalationDelayType", text, Common.TIME_PERIOD_CODES.getCodeList());
}
Integer i = jsonObject.getInt("escalationDelay", 1);
if (i != null)
escalationDelay = i;
JsonArray jsonEscalationRecipients = jsonObject.getJsonArray("escalationRecipients");
if (jsonEscalationRecipients != null)
escalationRecipients = (List<RecipientListEntryBean>) reader.read(recipType, jsonEscalationRecipients);
b = jsonObject.getJsonBoolean("keepSendingEscalations");
if (b != null)
repeatEscalations = b.booleanValue();
}
b = jsonObject.getJsonBoolean("sendInactive");
if (b != null)
sendInactive = b.booleanValue();
if (sendInactive) {
b = jsonObject.getJsonBoolean("inactiveOverride");
if (b != null)
inactiveOverride = b.booleanValue();
if (inactiveOverride) {
JsonArray jsonInactiveRecipients = jsonObject.getJsonArray("inactiveRecipients");
if (jsonInactiveRecipients != null)
inactiveRecipients = (List<RecipientListEntryBean>) reader.read(recipType, jsonInactiveRecipients);
}
}
b = jsonObject.getJsonBoolean("includeSystemInformation");
if (b != null)
includeSystemInfo = b.booleanValue();
includePointValueCount = jsonObject.getInt("includePointValueCount", 0);
b = jsonObject.getJsonBoolean("includeLogfile");
if (b != null)
includeSystemInfo = b.booleanValue();
customTemplate = jsonObject.getString("customTemplate");
JsonArray context = jsonObject.getJsonArray("additionalContext");
if (context != null) {
List<IntStringPair> additionalContext = new ArrayList<>();
for (JsonValue jv : context) {
JsonObject jo = jv.toJsonObject();
String dataPointXid = jo.getString("dataPointXid");
if (dataPointXid == null)
throw new TranslatableJsonException("emport.error.context.missing", "dataPointXid");
DataPointVO dpvo = DataPointDao.instance.getByXid(dataPointXid);
if (dpvo == null)
throw new TranslatableJsonException("emport.error.missingPoint", dataPointXid);
String contextKey = jo.getString("contextKey");
if (contextKey == null)
throw new TranslatableJsonException("emport.error.context.missing", "contextKey");
additionalContext.add(new IntStringPair(dpvo.getId(), contextKey));
}
this.additionalContext = additionalContext;
} else
this.additionalContext = new ArrayList<>();
script = jsonObject.getString("script");
JsonObject permissions = jsonObject.getJsonObject("scriptPermissions");
ScriptPermissions scriptPermissions = new ScriptPermissions();
if (permissions != null) {
String perm = permissions.getString(ScriptPermissions.DATA_SOURCE);
if (perm != null)
scriptPermissions.setDataSourcePermissions(perm);
perm = permissions.getString(ScriptPermissions.DATA_POINT_READ);
if (perm != null)
scriptPermissions.setDataPointReadPermissions(perm);
perm = permissions.getString(ScriptPermissions.DATA_POINT_SET);
if (perm != null)
scriptPermissions.setDataPointSetPermissions(perm);
}
this.scriptPermissions = scriptPermissions;
}
Aggregations