Copy folder and file nodes to file system.
authorMathieu Baudier <mbaudier@argeo.org>
Mon, 25 Jan 2021 10:51:50 +0000 (11:51 +0100)
committerMathieu Baudier <mbaudier@argeo.org>
Mon, 25 Jan 2021 10:51:50 +0000 (11:51 +0100)
org.argeo.jcr/src/org/argeo/jcr/JcrUtils.java

index cb9fe6e471797a9289a7ff945c53d4530221ff33..56d959e08579c2306e662173227ae1a926c69e02 100644 (file)
@@ -6,10 +6,13 @@ import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import java.io.OutputStream;
 import java.io.PipedInputStream;
 import java.io.PipedOutputStream;
 import java.net.MalformedURLException;
 import java.net.URL;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
 import java.security.Principal;
@@ -1577,6 +1580,7 @@ public class JcrUtils {
         * 
         * @return the created file node
         */
+       @Deprecated
        public static Node copyFile(Node folderNode, File file) {
                try (InputStream in = new FileInputStream(file)) {
                        return copyStreamAsFile(folderNode, file.getName(), in);
@@ -1648,6 +1652,28 @@ public class JcrUtils {
                // TODO remove properties if args are null?
        }
 
+       public static void copyFilesToFs(Node baseNode, Path targetDir, boolean recursive) {
+               try {
+                       Files.createDirectories(targetDir);
+                       for (NodeIterator nit = baseNode.getNodes(); nit.hasNext();) {
+                               Node node = nit.nextNode();
+                               if (node.isNodeType(NodeType.NT_FILE)) {
+                                       Path filePath = targetDir.resolve(node.getName());
+                                       try (OutputStream out = Files.newOutputStream(filePath); InputStream in = getFileAsStream(node)) {
+                                               IOUtils.copy(in, out);
+                                       }
+                               } else if (recursive && node.isNodeType(NodeType.NT_FOLDER)) {
+                                       Path dirPath = targetDir.resolve(node.getName());
+                                       copyFilesToFs(node, dirPath, true);
+                               }
+                       }
+               } catch (RepositoryException e) {
+                       throw new JcrException("Cannot copy " + baseNode + " to " + targetDir, e);
+               } catch (IOException e) {
+                       throw new RuntimeException("Cannot copy " + baseNode + " to " + targetDir, e);
+               }
+       }
+
        /**
         * Computes the checksum of an nt:file.
         *