package org.springblade.mdm.machineback.controller; import org.springblade.mdm.machineback.filewatch.DynamicDirectoryWatcher; import org.springblade.mdm.machineback.filewatch.FileLockChecker; import org.springblade.mdm.machineback.filewatch.FileWatcherService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; @RestController @RequestMapping("/machineback/file") public class DirectoryWatcherController { private final DynamicDirectoryWatcher directoryWatcher; @Autowired public DirectoryWatcherController(DynamicDirectoryWatcher directoryWatcher) { this.directoryWatcher = directoryWatcher; } @PostMapping("/watch") public String watchDirectory(@RequestParam String directoryPath) { try { Path path = Paths.get(directoryPath); directoryWatcher.addDirectory(path, new SimpleFileChangeListener()); return "Started watching directory: " + directoryPath; } catch (Exception e) { return "Error: " + e.getMessage(); } } @PostMapping("/unwatch") public String unwatchDirectory(@RequestParam String directoryPath) { try { Path path = Paths.get(directoryPath); directoryWatcher.removeDirectory(path); return "Stopped watching directory: " + directoryPath; } catch (Exception e) { return "Error: " + e.getMessage(); } } @PostMapping("/canlock") public String canlock(@RequestParam String filePath) { try { Path path = Paths.get(filePath); boolean comp = FileLockChecker.isFileCompletelyWritten(path); return filePath+ " lock: " + comp; } catch (Exception e) { return "Error: " + e.getMessage(); } } private static class SimpleFileChangeListener implements FileWatcherService.FileChangeListener { @Override public void onFileCreated(Path filePath) { System.out.println("File created: " + filePath); } @Override public void onFileModified(Path filePath) { System.out.println("File modified: " + filePath); //boolean comp = FileLockChecker.isFileCompletelyWritten(filePath); boolean comp = false; try { comp = FileLockChecker.isFileComplete(filePath); } catch (Exception e) { throw new RuntimeException(e); } System.out.println("File FINISHED: " + comp); } @Override public void onFileDeleted(Path filePath) { System.out.println("File deleted: " + filePath); } } }