use of com.serotonin.m2m2.rt.script.ScriptPointValueSetter in project ma-core-public by infiniteautomation.
the class EventHandlersDwr method validateScript.
@DwrPermission(user = true)
public ProcessResult validateScript(String script, Integer targetPointId, int type, List<IntStringPair> additionalContext, ScriptPermissions scriptPermissions) {
ProcessResult response = new ProcessResult();
TranslatableMessage message;
Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
int targetDataType;
if (type == SetPointEventHandlerDefinition.ACTIVE_SCRIPT_TYPE || type == SetPointEventHandlerDefinition.INACTIVE_SCRIPT_TYPE) {
DataPointRT target = targetPointId == null ? null : Common.runtimeManager.getDataPoint(targetPointId.intValue());
if (target == null) {
DataPointVO targetVo = targetPointId == null ? null : DataPointDao.instance.getDataPoint(targetPointId.intValue(), false);
if (targetVo == null) {
if (// These are passed in the validateScript of eventHandlers.jsp
type == SetPointEventHandlerDefinition.ACTIVE_SCRIPT_TYPE)
response.addMessage("activeScript", new TranslatableMessage("eventHandlers.noTargetPoint"));
else if (type == SetPointEventHandlerDefinition.INACTIVE_SCRIPT_TYPE)
response.addMessage("inactiveScript", new TranslatableMessage("eventHandlers.noTargetPoint"));
return response;
}
if (targetVo.getDefaultCacheSize() == 0)
targetVo.setDefaultCacheSize(1);
target = new DataPointRT(targetVo, targetVo.getPointLocator().createRuntime(), DataSourceDao.instance.getDataSource(targetVo.getDataSourceId()), null);
target.resetValues();
context.put(SetPointEventHandlerVO.TARGET_CONTEXT_KEY, target);
}
targetDataType = target.getDataTypeId();
} else {
targetDataType = DataTypes.ALPHANUMERIC;
}
for (IntStringPair cxt : additionalContext) {
DataPointRT dprt = Common.runtimeManager.getDataPoint(cxt.getKey());
if (dprt == null) {
DataPointVO dpvo = DataPointDao.instance.getDataPoint(cxt.getKey(), false);
if (dpvo == null) {
if (type == SetPointEventHandlerDefinition.ACTIVE_SCRIPT_TYPE)
response.addMessage("activeScript", new TranslatableMessage("event.script.contextPointMissing", cxt.getValue(), cxt.getKey()));
else if (type == SetPointEventHandlerDefinition.INACTIVE_SCRIPT_TYPE)
response.addMessage("inactiveScript", new TranslatableMessage("event.script.contextPointMissing", cxt.getValue(), cxt.getKey()));
else if (type == EmailEventHandlerDefinition.EMAIL_SCRIPT_TYPE)
response.addMessage("emailScript", new TranslatableMessage("event.script.contextPointMissing", cxt.getValue(), cxt.getKey()));
return response;
}
if (dpvo.getDefaultCacheSize() == 0)
dpvo.setDefaultCacheSize(1);
dprt = new DataPointRT(dpvo, dpvo.getPointLocator().createRuntime(), DataSourceDao.instance.getDataSource(dpvo.getDataSourceId()), null);
dprt.resetValues();
}
context.put(cxt.getValue(), dprt);
}
Map<String, Object> otherContext = new HashMap<String, Object>();
otherContext.put(SetPointEventHandlerVO.EVENT_CONTEXT_KEY, getTestEvent());
if (type == EmailEventHandlerDefinition.EMAIL_SCRIPT_TYPE)
otherContext.put("model", new HashMap<String, Object>());
final StringWriter scriptOut = new StringWriter();
final PrintWriter scriptWriter = new PrintWriter(scriptOut);
final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYY HH:mm:ss");
ScriptPointValueSetter loggingSetter = new ScriptPointValueSetter(scriptPermissions) {
@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, otherContext, System.currentTimeMillis(), targetDataType, System.currentTimeMillis(), scriptPermissions, scriptWriter, new ScriptLog(SetPointHandlerRT.NULL_WRITER, LogLevel.FATAL), loggingSetter, null, true);
if (pvt.getValue() == null)
message = new TranslatableMessage("eventHandlers.script.nullResult");
else if (CompiledScriptExecutor.UNCHANGED == pvt.getValue())
message = new TranslatableMessage("eventHandlers.script.successUnchanged");
else
message = new TranslatableMessage("eventHandlers.script.success", pvt.getValue());
// Add the script logging output
response.addData("out", scriptOut.toString().replaceAll("\n", "<br/>"));
} catch (ScriptPermissionsException e) {
message = e.getTranslatableMessage();
} catch (ScriptException e) {
message = new TranslatableMessage("eventHandlers.script.failure", e.getMessage());
} catch (ResultTypeException e) {
message = e.getTranslatableMessage();
}
if (type == SetPointEventHandlerDefinition.ACTIVE_SCRIPT_TYPE)
response.addMessage("activeScript", message);
else if (type == SetPointEventHandlerDefinition.INACTIVE_SCRIPT_TYPE)
response.addMessage("inactiveScript", message);
else if (type == EmailEventHandlerDefinition.EMAIL_SCRIPT_TYPE)
response.addMessage("emailScript", message);
return response;
}
use of com.serotonin.m2m2.rt.script.ScriptPointValueSetter in project ma-core-public by infiniteautomation.
the class CompiledScriptExecutor method execute.
/**
* Execute the script on the common engine
* @param script
* @param context
* @param additionalContext
* @param runtime
* @param dataTypeId
* @param timestamp
* @param permissions
* @param scriptWriter
* @return
* @throws ScriptException
* @throws ResultTypeException
*/
public static PointValueTime execute(CompiledScript script, Map<String, IDataPointValueSource> context, Map<String, Object> additionalContext, long runtime, int dataTypeId, long timestamp, ScriptPermissions permissions, PrintWriter scriptWriter, ScriptLog log, ScriptPointValueSetter setter, List<JsonImportExclusion> importExclusions, boolean testRun) throws ScriptException, ResultTypeException {
// StopWatch stopWatch = new Log4JStopWatch();
// stopWatch.start();
ensureInit();
// Create the wrapper object context.
ScriptEngine engine = script.getEngine();
// Prepare the Engine
Bindings engineScope = prepareEngine(engine, context, additionalContext, runtime, timestamp, permissions, scriptWriter, log, setter, importExclusions, testRun);
// Execute.
Object result;
try {
result = script.eval(engineScope);
} catch (ScriptException e) {
throw prettyScriptMessage(e);
}
PointValueTime value = getResult(engine, result, dataTypeId, timestamp);
// stopWatch.stop("execute()");
return value;
}
use of com.serotonin.m2m2.rt.script.ScriptPointValueSetter 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.ScriptPointValueSetter 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.ScriptPointValueSetter in project ma-core-public by infiniteautomation.
the class ScriptExecutor method prepareEngine.
/**
* Prepare the engine by creating the context
* @param engine
* @param context
* @param additionalContext
* @param runtime
* @param permissions
* @param scriptWriter
* @return
*/
protected static Bindings prepareEngine(ScriptEngine engine, Map<String, IDataPointValueSource> context, Map<String, Object> additionalContext, long runtime, long timestamp, ScriptPermissions permissions, PrintWriter scriptWriter, ScriptLog log, ScriptPointValueSetter setter, List<JsonImportExclusion> importExclusions, boolean testRun) {
ScriptUtils.prepareEngine(engine);
ScriptUtils.wrapperContext(engine, new WrapperContext(runtime, timestamp));
Bindings engineScope = engine.getBindings(ScriptContext.ENGINE_SCOPE);
// TODO Bubble PointValueSetter back up to top
if (permissions != null)
ScriptUtils.prepareUtilities(permissions, engine, engineScope, setter, importExclusions, testRun);
if (additionalContext != null) {
Set<Entry<String, Object>> entries = additionalContext.entrySet();
for (Entry<String, Object> entry : entries) engineScope.put(entry.getKey(), entry.getValue());
}
// Put the context variables into the engine with engine scope.
for (String varName : context.keySet()) {
IDataPointValueSource point = context.get(varName);
engineScope.put(varName, ScriptUtils.wrapPoint(engine, point, setter));
}
engineScope.put(ScriptUtils.POINTS_MAP_KEY, context);
// Set the print writer if necessary
if (scriptWriter != null) {
engine.getContext().setWriter(scriptWriter);
engineScope.put(ScriptLog.CONTEXT_KEY, log);
}
return engineScope;
}
Aggregations