use of com.infiniteautomation.mango.rest.v2.exception.GenericRestException in project ma-modules-public by infiniteautomation.
the class RuntimeManagerRestController method relinquish.
@ApiOperation(value = "Relinquish the value of a data point", notes = "Only BACnet data points allow this", response = Void.class)
@RequestMapping(method = RequestMethod.POST, value = "/relinquish/{xid}")
public void relinquish(@ApiParam(value = "Valid Data Point XID", required = true, allowMultiple = false) @PathVariable String xid, @AuthenticationPrincipal User user, HttpServletRequest request) {
DataPointVO dataPoint = DataPointDao.instance.getByXid(xid);
if (dataPoint == null)
throw new NotFoundRestException();
Permissions.ensureDataPointReadPermission(user, dataPoint);
DataPointRT rt = Common.runtimeManager.getDataPoint(dataPoint.getId());
if (rt == null)
throw new GenericRestException(HttpStatus.BAD_REQUEST, new TranslatableMessage("rest.error.pointNotEnabled", xid));
// Get the Data Source and Relinquish the point
DataSourceRT<?> dsRt = Common.runtimeManager.getRunningDataSource(rt.getDataSourceId());
if (dsRt == null)
throw new GenericRestException(HttpStatus.BAD_REQUEST, new TranslatableMessage("rest.error.dataSourceNotEnabled", xid));
dsRt.relinquish(rt);
}
use of com.infiniteautomation.mango.rest.v2.exception.GenericRestException 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.infiniteautomation.mango.rest.v2.exception.GenericRestException 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.infiniteautomation.mango.rest.v2.exception.GenericRestException in project ma-modules-public by infiniteautomation.
the class FileStoreRestV2Controller method createNewFolder.
@ApiOperation(value = "Create a folder or copy/move/rename an existing file or folder", notes = "Must have write access to the store")
@RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, value = "/{fileStoreName}/**")
public ResponseEntity<FileModel> createNewFolder(@ApiParam(value = "Valid File Store name", required = true, allowMultiple = false) @PathVariable("fileStoreName") String fileStoreName, @ApiParam(value = "Move file/folder to", required = false, allowMultiple = false) @RequestParam(required = false) String moveTo, @ApiParam(value = "Copy file/folder to", required = false, allowMultiple = false) @RequestParam(required = false) String copyTo, @AuthenticationPrincipal User user, HttpServletRequest request) throws IOException, URISyntaxException {
FileStoreDefinition def = ModuleRegistry.getFileStoreDefinition(fileStoreName);
if (def == null)
throw new NotFoundRestException();
// Check Permissions
def.ensureStoreWritePermission(user);
String pathInStore = parsePath(request);
File root = def.getRoot().getCanonicalFile();
File fileOrFolder = new File(root, pathInStore).getCanonicalFile();
if (!fileOrFolder.toPath().startsWith(root.toPath())) {
throw new GenericRestException(HttpStatus.FORBIDDEN, new TranslatableMessage("filestore.belowRoot", pathInStore));
}
if (copyTo != null) {
return copyFileOrFolder(request, fileStoreName, root, fileOrFolder, copyTo);
} else if (moveTo != null) {
return moveFileOrFolder(request, fileStoreName, root, fileOrFolder, moveTo);
} else {
return createFolder(request, fileStoreName, root, fileOrFolder);
}
}
use of com.infiniteautomation.mango.rest.v2.exception.GenericRestException in project ma-modules-public by infiniteautomation.
the class FileStoreRestV2Controller method uploadWithPath.
@ApiOperation(value = "Upload a file to a store with a path", notes = "Must have write access to the store")
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, value = "/{name}/**")
public ResponseEntity<List<FileModel>> uploadWithPath(@ApiParam(value = "Valid File Store name", required = true, allowMultiple = false) @PathVariable("name") String name, @AuthenticationPrincipal User user, @RequestParam(required = false, defaultValue = "false") boolean overwrite, MultipartHttpServletRequest multipartRequest, HttpServletRequest request) throws IOException {
FileStoreDefinition def = ModuleRegistry.getFileStoreDefinition(name);
if (def == null)
throw new NotFoundRestException();
// Check Permissions
def.ensureStoreWritePermission(user);
String pathInStore = parsePath(request);
File root = def.getRoot().getCanonicalFile();
Path rootPath = root.toPath();
File outputDirectory = new File(root, pathInStore).getCanonicalFile();
if (!outputDirectory.toPath().startsWith(rootPath)) {
throw new GenericRestException(HttpStatus.FORBIDDEN, new TranslatableMessage("filestore.belowRoot", pathInStore));
}
if (outputDirectory.exists() && !outputDirectory.isDirectory()) {
throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, new TranslatableMessage("filestore.cannotCreateDir", removeToRoot(root, outputDirectory), name));
}
if (!outputDirectory.exists()) {
if (!outputDirectory.mkdirs())
throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, new TranslatableMessage("filestore.cannotCreateDir", removeToRoot(root, outputDirectory), name));
}
// Put the file where it belongs
List<FileModel> fileModels = new ArrayList<>();
MultiValueMap<String, MultipartFile> filemap = multipartRequest.getMultiFileMap();
for (String nameField : filemap.keySet()) {
for (MultipartFile file : filemap.get(nameField)) {
String filename;
if (file instanceof CommonsMultipartFile) {
FileItem fileItem = ((CommonsMultipartFile) file).getFileItem();
filename = fileItem.getName();
} else {
filename = file.getName();
}
File newFile = findUniqueFileName(outputDirectory, filename, overwrite);
File parent = newFile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
try (OutputStream output = new FileOutputStream(newFile, false)) {
try (InputStream input = file.getInputStream()) {
StreamUtils.copy(input, output);
}
}
fileModels.add(fileToModel(newFile, root, request.getServletContext()));
}
}
return new ResponseEntity<>(fileModels, HttpStatus.OK);
}
Aggregations