Search in sources :

Example 1 with GenericRestException

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);
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) GenericRestException(com.infiniteautomation.mango.rest.v2.exception.GenericRestException) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with GenericRestException

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);
    }
}
Also used : CompiledScript(javax.script.CompiledScript) ScriptPointValueSetter(com.serotonin.m2m2.rt.script.ScriptPointValueSetter) PointValueTimeModel(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.PointValueTimeModel) ScriptLog(com.serotonin.m2m2.rt.script.ScriptLog) ScriptPermissions(com.serotonin.m2m2.rt.script.ScriptPermissions) Date(java.util.Date) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptException(javax.script.ScriptException) ResponseEntity(org.springframework.http.ResponseEntity) StringWriter(java.io.StringWriter) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) SimpleDateFormat(java.text.SimpleDateFormat) GenericRestException(com.infiniteautomation.mango.rest.v2.exception.GenericRestException) PrintWriter(java.io.PrintWriter) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) ApiResponses(com.wordnik.swagger.annotations.ApiResponses) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 3 with GenericRestException

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);
    }
}
Also used : CompiledScript(javax.script.CompiledScript) PointValueTimeModel(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.PointValueTimeModel) ScriptLog(com.serotonin.m2m2.rt.script.ScriptLog) ScriptPermissions(com.serotonin.m2m2.rt.script.ScriptPermissions) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptException(javax.script.ScriptException) ResponseEntity(org.springframework.http.ResponseEntity) StringWriter(java.io.StringWriter) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) GenericRestException(com.infiniteautomation.mango.rest.v2.exception.GenericRestException) PrintWriter(java.io.PrintWriter) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) ApiResponses(com.wordnik.swagger.annotations.ApiResponses) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 4 with GenericRestException

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);
    }
}
Also used : NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) File(java.io.File) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) FileStoreDefinition(com.serotonin.m2m2.module.FileStoreDefinition) GenericRestException(com.infiniteautomation.mango.rest.v2.exception.GenericRestException) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 5 with GenericRestException

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);
}
Also used : Path(java.nio.file.Path) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) FileModel(com.infiniteautomation.mango.rest.v2.model.filestore.FileModel) FileItem(org.apache.commons.fileupload.FileItem) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) ResponseEntity(org.springframework.http.ResponseEntity) FileOutputStream(java.io.FileOutputStream) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) File(java.io.File) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) FileStoreDefinition(com.serotonin.m2m2.module.FileStoreDefinition) GenericRestException(com.infiniteautomation.mango.rest.v2.exception.GenericRestException) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

GenericRestException (com.infiniteautomation.mango.rest.v2.exception.GenericRestException)13 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)11 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)9 ResponseEntity (org.springframework.http.ResponseEntity)9 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)9 NotFoundRestException (com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException)8 File (java.io.File)6 MultipartFile (org.springframework.web.multipart.MultipartFile)6 CommonsMultipartFile (org.springframework.web.multipart.commons.CommonsMultipartFile)6 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)5 FileModel (com.infiniteautomation.mango.rest.v2.model.filestore.FileModel)3 FileStoreDefinition (com.serotonin.m2m2.module.FileStoreDefinition)3 IOException (java.io.IOException)3 Path (java.nio.file.Path)3 ResourceNotFoundException (com.infiniteautomation.mango.rest.v2.exception.ResourceNotFoundException)2 DataPointRT (com.serotonin.m2m2.rt.dataImage.DataPointRT)2 IDataPointValueSource (com.serotonin.m2m2.rt.dataImage.IDataPointValueSource)2 PointValueTime (com.serotonin.m2m2.rt.dataImage.PointValueTime)2 ResultTypeException (com.serotonin.m2m2.rt.script.ResultTypeException)2 ScriptLog (com.serotonin.m2m2.rt.script.ScriptLog)2