package org.simantics.fileimport.scl;\r
\r
import java.io.IOException;\r
+import java.nio.file.DirectoryStream;\r
+import java.nio.file.Files;\r
import java.nio.file.Path;\r
import java.util.HashMap;\r
+import java.util.Iterator;\r
import java.util.Map;\r
import java.util.Optional;\r
\r
public static void watchDropinsFolder() {\r
FileImportDropins.watchDropinsFolder();\r
}\r
- \r
+\r
public static void unwatchDropinsFolder() {\r
FileImportDropins.unwatchDropinsFolder();\r
}\r
- \r
+\r
public static void uploadToDropinsBase64(String base64, String fileName) {\r
// ensure that watcher is awake\r
FileImportDropins.watchDropinsFolder();\r
try {\r
Path rootFolder = Activator.getDropinsFolder();\r
+ Path newFile = rootFolder.resolve(fileName);\r
+ if (Files.exists(newFile)) {\r
+ newFile = findFreshFileName(rootFolder, fileName);\r
+ }\r
byte[] bytes = Base64.decode(base64);\r
- FileUtils.writeFile(rootFolder.resolve(fileName).toFile(), bytes);\r
- \r
+ FileUtils.writeFile(newFile.toFile(), bytes);\r
} catch (IOException e) {\r
e.printStackTrace();\r
}\r
}\r
- \r
+\r
+ private static Path findFreshFileName(Path root, String fileName) throws IOException {\r
+ int ending = fileName.lastIndexOf('.');\r
+ String glob = fileName;\r
+ String suffix = "";\r
+ if (ending > -1) {\r
+ glob = fileName.substring(0, ending);\r
+ suffix = fileName.substring(ending);\r
+ }\r
+ int i = 0;\r
+ try (DirectoryStream<Path> stream = Files.newDirectoryStream(root, glob)) {\r
+ Iterator<Path> iter = stream.iterator();\r
+ while (iter.hasNext()) {\r
+ iter.next();\r
+ i++;\r
+ }\r
+ }\r
+ String newFileName = glob + "_" + i + suffix;\r
+ return root.resolve(newFileName);\r
+ }\r
+\r
public static Map<String, Long> getUploadedFiles() throws DatabaseException {\r
Map<String, String> results = FileImportService.getPathsAndResources();\r
Map<String, Long> result = Simantics.getSession().syncRequest(new UniqueRead<Map<String, Long>>() {\r
});\r
return result;\r
}\r
- \r
+\r
public static void removeFileForId(long id) {\r
FileImportService.removeFileForResource(id, Optional.empty());\r
}\r
- \r
+\r
}\r