Search in sources :

Example 11 with FileStore

use of com.serotonin.m2m2.vo.FileStore in project ma-core-public by MangoAutomation.

the class FileStoreService method ensureWriteAccess.

/**
 * @throws IllegalArgumentException if path is not located inside the filestore root
 * @throws NotFoundException        if filestore was not found
 * @throws PermissionException      filestore exists but user does not have write access
 */
public void ensureWriteAccess(Path path) throws IllegalArgumentException, NotFoundException, PermissionException {
    FileStore fileStore = resolveFileStore(path).getFileStore();
    ensureEditPermission(Common.getUser(), fileStore);
}
Also used : FileStore(com.serotonin.m2m2.vo.FileStore)

Example 12 with FileStore

use of com.serotonin.m2m2.vo.FileStore in project ma-core-public by MangoAutomation.

the class FileStoreService method resolveFileStore.

private FileStorePath resolveFileStore(Path path) {
    Path absolutePath = path.toAbsolutePath().normalize();
    if (!absolutePath.startsWith(fileStoreRoot)) {
        throw new TranslatableIllegalArgumentException(new TranslatableMessage("filestore.invalidPath"));
    }
    Path relative = fileStoreRoot.relativize(absolutePath);
    if (relative.getNameCount() == 0) {
        throw new TranslatableIllegalArgumentException(new TranslatableMessage("filestore.invalidPath"));
    }
    String fileStoreName = relative.getName(0).toString();
    FileStore fileStore = getWithoutPermissionCheck(fileStoreName);
    return new FileStorePath(fileStore, absolutePath);
}
Also used : Path(java.nio.file.Path) FileStore(com.serotonin.m2m2.vo.FileStore) TranslatableIllegalArgumentException(com.infiniteautomation.mango.util.exception.TranslatableIllegalArgumentException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage)

Example 13 with FileStore

use of com.serotonin.m2m2.vo.FileStore in project ma-core-public by MangoAutomation.

the class FileStoreService method moveFileOrFolder.

public FileStorePath moveFileOrFolder(String xid, String src, String dst) {
    FileStore fileStore = getWithoutPermissionCheck(xid);
    ensureEditPermission(Common.getUser(), fileStore);
    FileStorePath srcPath = getPathWithinFileStore(fileStore, src);
    if (!Files.exists(srcPath.absolutePath)) {
        throw new NotFoundException();
    }
    FileStorePath dstPath = srcPath.getParent().resolve(Paths.get(dst));
    if (Files.isDirectory(dstPath.absolutePath)) {
        Path pathWithFileName = dstPath.absolutePath.resolve(srcPath.absolutePath.getFileName());
        dstPath = new FileStorePath(fileStore, pathWithFileName);
    }
    try {
        Files.move(srcPath.absolutePath, dstPath.absolutePath);
        return dstPath;
    } catch (FileAlreadyExistsException e) {
        throw new FileStoreException(new TranslatableMessage("filestore.fileExists", dstPath.standardizedPath()));
    } catch (Exception e) {
        throw new FileStoreException(new TranslatableMessage("filestore.errorMovingFile"));
    }
}
Also used : Path(java.nio.file.Path) FileStore(com.serotonin.m2m2.vo.FileStore) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) NoSuchFileException(java.nio.file.NoSuchFileException) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) TranslatableRuntimeException(com.infiniteautomation.mango.util.exception.TranslatableRuntimeException) TranslatableIllegalArgumentException(com.infiniteautomation.mango.util.exception.TranslatableIllegalArgumentException) IOException(java.io.IOException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) ValidationException(com.infiniteautomation.mango.util.exception.ValidationException) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException)

Example 14 with FileStore

use of com.serotonin.m2m2.vo.FileStore in project ma-modules-public by infiniteautomation.

the class ServerRestController method getSystemInfo.

@ApiOperation(value = "System Info", notes = "Provides disk use, db sizes and point, event counts", response = Map.class)
@RequestMapping(method = RequestMethod.GET, produces = { "application/json" }, value = "/system-info")
public ResponseEntity<SystemInfoModel> getSystemInfo(HttpServletRequest request) {
    RestProcessResult<SystemInfoModel> result = new RestProcessResult<SystemInfoModel>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        if (user.isAdmin()) {
            SystemInfoModel model = new SystemInfoModel();
            // Database size
            model.setSqlDbSizeBytes(Common.databaseProxy.getDatabaseSizeInBytes());
            // Do we have any NoSQL Data
            if (Common.databaseProxy.getNoSQLProxy() != null) {
                String pointValueStoreName = Common.envProps.getString("db.nosql.pointValueStoreName", "mangoTSDB");
                model.setNoSqlDbSizeBytes(Common.databaseProxy.getNoSQLProxy().getDatabaseSizeInBytes(pointValueStoreName));
            }
            // Filedata data
            DirectoryInfo fileDatainfo = DirectoryUtils.getSize(new File(Common.getFiledataPath()));
            model.setFileDataSizeBytes(fileDatainfo.getSize());
            // Point history counts.
            model.setTopPoints(DataPointDao.instance.getTopPointHistoryCounts());
            model.setEventCount(EventDao.instance.getEventCount());
            // Disk Info
            FileSystem fs = FileSystems.getDefault();
            List<DiskInfoModel> disks = new ArrayList<DiskInfoModel>();
            model.setDisks(disks);
            for (Path root : fs.getRootDirectories()) {
                try {
                    FileStore store = Files.getFileStore(root);
                    DiskInfoModel disk = new DiskInfoModel();
                    disk.setName(root.getRoot().toString());
                    disk.setTotalSpaceBytes(store.getTotalSpace());
                    disk.setUsableSpaceBytes(store.getUsableSpace());
                    disks.add(disk);
                } catch (IOException e) {
                }
            }
            // CPU Info
            OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
            model.setLoadAverage(osBean.getSystemLoadAverage());
            // OS Info
            model.setArchitecture(osBean.getArch());
            model.setOperatingSystem(osBean.getName());
            model.setOsVersion(osBean.getVersion());
            return result.createResponseEntity(model);
        } else {
            result.addRestMessage(HttpStatus.UNAUTHORIZED, new TranslatableMessage("common.default", "User not admin"));
        }
    }
    return result.createResponseEntity();
}
Also used : Path(java.nio.file.Path) SystemInfoModel(com.serotonin.m2m2.web.mvc.rest.v1.model.system.SystemInfoModel) User(com.serotonin.m2m2.vo.User) ArrayList(java.util.ArrayList) DiskInfoModel(com.serotonin.m2m2.web.mvc.rest.v1.model.system.DiskInfoModel) IOException(java.io.IOException) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) FileStore(java.nio.file.FileStore) FileSystem(java.nio.file.FileSystem) DirectoryInfo(com.serotonin.util.DirectoryInfo) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) File(java.io.File) OperatingSystemMXBean(java.lang.management.OperatingSystemMXBean) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 15 with FileStore

use of com.serotonin.m2m2.vo.FileStore in project ma-modules-public by infiniteautomation.

the class ScriptRestController method evalScript.

@Async
@ApiOperation(value = "Evaluate a filestore file as a script on the backend using a scripting engine")
@RequestMapping(method = RequestMethod.POST, value = "/eval-file-store/{fileStoreName}/**")
public CompletableFuture<Void> evalScript(@ApiParam(value = "File store name", required = true) @PathVariable(required = true) String fileStoreName, @ApiParam(value = "Script engine name", required = false) @RequestParam(required = false) String engineName, @ApiParam(value = "Script file character set", required = false, defaultValue = "UTF-8") @RequestParam(required = false, defaultValue = "UTF-8") String fileCharset, @ApiParam(value = "Script roles", required = false, allowMultiple = true) @RequestParam(required = false) String[] roles, @ApiIgnore @RemainingPath String path, @AuthenticationPrincipal PermissionHolder user, HttpServletRequest request, HttpServletResponse response) throws IOException {
    Path filePath = fileStoreService.getPathForRead(fileStoreName, path);
    if (!Files.exists(filePath)) {
        throw new NotFoundException();
    }
    if (engineName == null) {
        engineName = scriptService.findEngineForFile(filePath);
    }
    Charset fileCharsetParsed = Charset.forName(fileCharset);
    Set<Role> roleSet;
    if (roles != null) {
        roleSet = Arrays.stream(roles).map(xid -> this.roleService.get(xid).getRole()).collect(Collectors.toSet());
    } else {
        roleSet = user.getRoles();
    }
    EvalContext evalContext = new EvalContext();
    Reader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), Charset.forName(request.getCharacterEncoding())));
    Writer writer = new OutputStreamWriter(response.getOutputStream(), Charset.forName(response.getCharacterEncoding()));
    evalContext.setReader(reader);
    evalContext.setWriter(writer);
    evalContext.addBinding("reader", reader);
    evalContext.addBinding("writer", writer);
    if (permissionService.hasPermission(user, requestResponsePermission.getPermission())) {
        evalContext.addBinding("request", request);
        evalContext.addBinding("response", response);
    }
    this.scriptService.eval(new PathMangoScript(engineName, roleSet, filePath, fileCharsetParsed), evalContext);
    return CompletableFuture.completedFuture(null);
}
Also used : Path(java.nio.file.Path) RemainingPath(com.infiniteautomation.mango.rest.latest.resolver.RemainingPath) Role(com.serotonin.m2m2.vo.role.Role) InputStreamReader(java.io.InputStreamReader) EvalContext(com.infiniteautomation.mango.spring.script.EvalContext) BufferedReader(java.io.BufferedReader) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) Charset(java.nio.charset.Charset) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) PathMangoScript(com.infiniteautomation.mango.spring.script.PathMangoScript) OutputStreamWriter(java.io.OutputStreamWriter) OutputStreamWriter(java.io.OutputStreamWriter) Writer(java.io.Writer) Async(org.springframework.scheduling.annotation.Async) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

FileStore (com.serotonin.m2m2.vo.FileStore)38 Path (java.nio.file.Path)18 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)17 IOException (java.io.IOException)15 TranslatableIllegalArgumentException (com.infiniteautomation.mango.util.exception.TranslatableIllegalArgumentException)10 NotFoundException (com.infiniteautomation.mango.util.exception.NotFoundException)7 TranslatableRuntimeException (com.infiniteautomation.mango.util.exception.TranslatableRuntimeException)6 ValidationException (com.infiniteautomation.mango.util.exception.ValidationException)6 PermissionException (com.serotonin.m2m2.vo.permission.PermissionException)6 FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)6 NoSuchFileException (java.nio.file.NoSuchFileException)6 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)5 MangoPermission (com.infiniteautomation.mango.permission.MangoPermission)4 PermissionHolder (com.serotonin.m2m2.vo.permission.PermissionHolder)4 ApiOperation (io.swagger.annotations.ApiOperation)4 ArrayList (java.util.ArrayList)4 FileStoreModel (com.infiniteautomation.mango.rest.latest.model.filestore.FileStoreModel)3 ConditionSortLimit (com.infiniteautomation.mango.db.query.ConditionSortLimit)2 MangoScript (com.infiniteautomation.mango.spring.script.MangoScript)2 LoadFileStorePermission (com.infiniteautomation.mango.spring.script.permissions.LoadFileStorePermission)2