]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.core/src/org/argeo/sync/fs/SyncFileVisitor.java
Start using FreeMarker
[lgpl/argeo-commons.git] / org.argeo.core / src / org / argeo / sync / fs / SyncFileVisitor.java
1 package org.argeo.sync.fs;
2
3 import java.io.IOException;
4 import java.nio.file.FileVisitResult;
5 import java.nio.file.Files;
6 import java.nio.file.Path;
7 import java.nio.file.SimpleFileVisitor;
8 import java.nio.file.attribute.BasicFileAttributes;
9
10 import org.apache.commons.logging.Log;
11 import org.apache.commons.logging.LogFactory;
12
13 /** Synchronises two directory structures. */
14 public class SyncFileVisitor extends SimpleFileVisitor<Path> {
15 private final static Log log = LogFactory.getLog(SyncFileVisitor.class);
16
17 private final Path sourceBasePath;
18 private final Path targetBasePath;
19
20 public SyncFileVisitor(Path sourceBasePath, Path targetBasePath) {
21 this.sourceBasePath = sourceBasePath;
22 this.targetBasePath = targetBasePath;
23 }
24
25 @Override
26 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
27 Path targetPath = toTargetPath(dir);
28 Files.createDirectories(targetPath);
29 return FileVisitResult.CONTINUE;
30 }
31
32 @Override
33 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
34 Path targetPath = toTargetPath(file);
35 try {
36 Files.copy(file, targetPath);
37 if (log.isDebugEnabled())
38 log.debug("Copied " + targetPath);
39 } catch (Exception e) {
40 log.error("Cannot copy " + file + " to " + targetPath, e);
41 }
42 return FileVisitResult.CONTINUE;
43 }
44
45 @Override
46 public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
47 log.error("Cannot sync " + file, exc);
48 return FileVisitResult.CONTINUE;
49 }
50
51 private Path toTargetPath(Path sourcePath) {
52 Path relativePath = sourceBasePath.relativize(sourcePath);
53 Path targetPath = targetBasePath.resolve(relativePath.toString());
54 return targetPath;
55 }
56 }