View Javadoc
1   package org.argeo.cli.fs;
2   
3   import java.net.URI;
4   import java.nio.file.FileSystems;
5   import java.nio.file.Files;
6   import java.nio.file.Path;
7   import java.nio.file.Paths;
8   import java.nio.file.spi.FileSystemProvider;
9   import java.util.concurrent.Callable;
10  
11  import org.argeo.jackrabbit.fs.DavexFsProvider;
12  import org.argeo.ssh.Sftp;
13  import org.argeo.sync.SyncResult;
14  
15  /** Synchronises two paths. */
16  public class PathSync implements Callable<SyncResult<Path>> {
17  	private final URI sourceUri, targetUri;
18  	private final boolean delete;
19  	private final boolean recursive;
20  
21  	public PathSync(URI sourceUri, URI targetUri) {
22  		this(sourceUri, targetUri, false, false);
23  	}
24  
25  	public PathSync(URI sourceUri, URI targetUri, boolean delete, boolean recursive) {
26  		this.sourceUri = sourceUri;
27  		this.targetUri = targetUri;
28  		this.delete = delete;
29  		this.recursive = recursive;
30  	}
31  
32  	@Override
33  	public SyncResult<Path> call() {
34  		try {
35  			Path sourceBasePath = createPath(sourceUri);
36  			Path targetBasePath = createPath(targetUri);
37  			SyncFileVisitor syncFileVisitor = new SyncFileVisitor(sourceBasePath, targetBasePath, delete, recursive);
38  			Files.walkFileTree(sourceBasePath, syncFileVisitor);
39  			return syncFileVisitor.getSyncResult();
40  		} catch (Exception e) {
41  			throw new IllegalStateException("Cannot sync " + sourceUri + " to " + targetUri, e);
42  		}
43  	}
44  
45  	private Path createPath(URI uri) {
46  		Path path;
47  		if (uri.getScheme() == null) {
48  			path = Paths.get(uri.getPath());
49  		} else if (uri.getScheme().equals("file")) {
50  			FileSystemProvider fsProvider = FileSystems.getDefault().provider();
51  			path = fsProvider.getPath(uri);
52  		} else if (uri.getScheme().equals("davex")) {
53  			FileSystemProvider fsProvider = new DavexFsProvider();
54  			path = fsProvider.getPath(uri);
55  		} else if (uri.getScheme().equals("sftp")) {
56  			Sftp sftp = new Sftp(uri);
57  			path = sftp.getBasePath();
58  		} else
59  			throw new IllegalArgumentException("URI scheme not supported for " + uri);
60  		return path;
61  	}
62  }