Search in sources :

Example 1 with FileModel

use of com.infiniteautomation.mango.rest.v2.model.filestore.FileModel in project ma-modules-public by infiniteautomation.

the class LoggingRestController method list.

@PreAuthorize("isAdmin()")
@ApiOperation(value = "List Log Files", notes = "Returns a list of logfile metadata")
@RequestMapping(method = RequestMethod.GET, produces = { "application/json" }, value = "/files")
public ResponseEntity<List<FileModel>> list(@RequestParam(value = "limit", required = false) Integer limit, HttpServletRequest request) throws IOException {
    List<FileModel> modelList = new ArrayList<FileModel>();
    File logsDir = Common.getLogsDir();
    int count = 0;
    for (File file : logsDir.listFiles()) {
        if ((limit != null) && (count >= limit.intValue()))
            break;
        if (!file.getName().startsWith(".")) {
            FileModel model = FileStoreRestV2Controller.fileToModel(file, logsDir, request.getServletContext());
            model.setMimeType("text/plain");
            modelList.add(model);
            count++;
        }
    }
    return ResponseEntity.ok(modelList);
}
Also used : FileModel(com.infiniteautomation.mango.rest.v2.model.filestore.FileModel) ArrayList(java.util.ArrayList) File(java.io.File) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with FileModel

use of com.infiniteautomation.mango.rest.v2.model.filestore.FileModel in project ma-modules-public by infiniteautomation.

the class FileStoreRestV2Controller method fileToModel.

public static FileModel fileToModel(File file, File root, ServletContext context) throws UnsupportedEncodingException {
    FileModel model = new FileModel();
    model.setFilename(file.getName());
    model.setFolderPath(relativePath(root, file.getParentFile()));
    model.setDirectory(file.isDirectory());
    model.setLastModified(new Date(file.lastModified()));
    model.setMimeType(context.getMimeType(file.getName()));
    if (!file.isDirectory())
        model.setSize(file.length());
    return model;
}
Also used : FileModel(com.infiniteautomation.mango.rest.v2.model.filestore.FileModel) Date(java.util.Date)

Example 3 with FileModel

use of com.infiniteautomation.mango.rest.v2.model.filestore.FileModel 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 4 with FileModel

use of com.infiniteautomation.mango.rest.v2.model.filestore.FileModel 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)

Example 5 with FileModel

use of com.infiniteautomation.mango.rest.v2.model.filestore.FileModel in project ma-modules-public by infiniteautomation.

the class FileStoreRestV2Controller method moveFileOrFolder.

private ResponseEntity<FileModel> moveFileOrFolder(HttpServletRequest request, String fileStoreName, File root, File fileOrFolder, String moveTo) throws IOException, URISyntaxException {
    if (!fileOrFolder.exists()) {
        throw new NotFoundRestException();
    }
    Path srcPath = fileOrFolder.toPath();
    File dstFile = new File(fileOrFolder.getParentFile(), moveTo).getCanonicalFile();
    Path dstPath = dstFile.toPath();
    if (!dstPath.startsWith(root.toPath())) {
        throw new GenericRestException(HttpStatus.FORBIDDEN, new TranslatableMessage("filestore.belowRoot", moveTo));
    }
    if (dstFile.isDirectory()) {
        dstPath = dstPath.resolve(srcPath.getFileName());
    }
    Path movedPath;
    try {
        movedPath = java.nio.file.Files.move(srcPath, dstPath);
    } catch (FileAlreadyExistsException e) {
        throw new GenericRestException(HttpStatus.CONFLICT, new TranslatableMessage("filestore.fileExists", dstPath.getFileName()));
    }
    File movedFile = new File(movedPath.toUri());
    FileModel fileModel = fileToModel(movedFile, root, request.getServletContext());
    return new ResponseEntity<>(fileModel, HttpStatus.OK);
}
Also used : Path(java.nio.file.Path) FileModel(com.infiniteautomation.mango.rest.v2.model.filestore.FileModel) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) ResponseEntity(org.springframework.http.ResponseEntity) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) File(java.io.File) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) GenericRestException(com.infiniteautomation.mango.rest.v2.exception.GenericRestException)

Aggregations

FileModel (com.infiniteautomation.mango.rest.v2.model.filestore.FileModel)6 File (java.io.File)6 MultipartFile (org.springframework.web.multipart.MultipartFile)5 CommonsMultipartFile (org.springframework.web.multipart.commons.CommonsMultipartFile)5 GenericRestException (com.infiniteautomation.mango.rest.v2.exception.GenericRestException)4 NotFoundRestException (com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException)4 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)4 ResponseEntity (org.springframework.http.ResponseEntity)4 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)3 Path (java.nio.file.Path)3 ArrayList (java.util.ArrayList)3 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)3 FileStoreDefinition (com.serotonin.m2m2.module.FileStoreDefinition)2 FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)2 ResourceNotFoundException (com.infiniteautomation.mango.rest.v2.exception.ResourceNotFoundException)1 FileOutputStream (java.io.FileOutputStream)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 Date (java.util.Date)1 FileItem (org.apache.commons.fileupload.FileItem)1