JAL-4277 --mkdirs with cautious refusal for paths with ..
[jalview.git] / src / jalview / util / FileUtils.java
index 79cac0a..983ba75 100644 (file)
@@ -17,6 +17,8 @@ import java.util.EnumSet;
 import java.util.List;
 import java.util.stream.Collectors;
 
+import jalview.bin.Console;
+
 public class FileUtils
 {
   /*
@@ -226,4 +228,47 @@ public class FileUtils
     }
     return path.toString();
   }
+
+  public static File getParentDir(File file)
+  {
+    if (file == null)
+    {
+      return null;
+    }
+    File parentDir = file.getAbsoluteFile().getParentFile();
+    return parentDir;
+  }
+
+  public static boolean checkParentDir(File file, boolean mkdirs)
+  {
+    if (file == null)
+    {
+      return false;
+    }
+    File parentDir = getParentDir(file);
+    if (parentDir.exists())
+    {
+      // already exists, nothing to do so nothing to worry about!
+      return true;
+    }
+
+    if (!mkdirs)
+    {
+      return false;
+    }
+
+    Path path = file.toPath();
+    for (int i = 0; i < path.getNameCount(); i++)
+    {
+      Path p = path.getName(i);
+      if ("..".equals(p.toString()))
+      {
+        Console.warn("Cautiously not running mkdirs on " + file.toString()
+                + " because the path to be made contains '..'");
+        return false;
+      }
+    }
+
+    return parentDir.mkdirs();
+  }
 }