Java Code Examples for net.schmizz.sshj.sftp.FileAttributes

The following examples show how to use net.schmizz.sshj.sftp.FileAttributes. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cyberduck   Source File: SFTPTouchFeature.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public Path touch(final Path file, final TransferStatus status) throws BackgroundException {
    if(file.isFile()) {
        try {
            final FileAttributes attrs;
            if(Permission.EMPTY != status.getPermission()) {
                attrs = new FileAttributes.Builder().withPermissions(Integer.parseInt(status.getPermission().getMode(), 8)).build();
            }
            else {
                attrs = FileAttributes.EMPTY;
            }
            final RemoteFile handle = session.sftp().open(file.getAbsolute(),
                EnumSet.of(OpenMode.CREAT, OpenMode.TRUNC, OpenMode.WRITE), attrs);
            handle.close();
        }
        catch(IOException e) {
            throw new SFTPExceptionMappingService().map("Cannot create file {0}", e, file);
        }
    }
    return new Path(file.getParent(), file.getName(), file.getType(), new SFTPAttributesFinderFeature(session).find(file));
}
 
Example 2
@Override
public Path mkdir(final Path folder, final String region, final TransferStatus status) throws BackgroundException {
    try {
        final FileAttributes attrs;
        if(Permission.EMPTY != status.getPermission()) {
            attrs = new FileAttributes.Builder().withPermissions(Integer.parseInt(status.getPermission().getMode(), 8)).build();
        }
        else {
            attrs = FileAttributes.EMPTY;
        }
        session.sftp().makeDir(folder.getAbsolute(), attrs);
    }
    catch(IOException e) {
        throw new SFTPExceptionMappingService().map("Cannot create folder {0}", e, folder);
    }
    return new Path(folder.getParent(), folder.getName(), folder.getType(), new SFTPAttributesFinderFeature(session).find(folder));
}
 
Example 3
public PathAttributes toAttributes(final FileAttributes stat) {
    final PathAttributes attributes = new PathAttributes();
    switch(stat.getType()) {
        case REGULAR:
        case UNKNOWN:
            attributes.setSize(stat.getSize());
    }
    if(0 != stat.getMode().getPermissionsMask()) {
        attributes.setPermission(new Permission(Integer.toString(stat.getMode().getPermissionsMask(), 8)));
    }
    if(0 != stat.getUID()) {
        attributes.setOwner(String.valueOf(stat.getUID()));
    }
    if(0 != stat.getGID()) {
        attributes.setGroup(String.valueOf(stat.getGID()));
    }
    if(0 != stat.getMtime()) {
        attributes.setModificationDate(stat.getMtime() * 1000L);
    }
    if(0 != stat.getAtime()) {
        attributes.setAccessedDate(stat.getAtime() * 1000L);
    }
    return attributes;
}
 
Example 4
Source Project: datacollector   Source File: TestChrootSFTPClient.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRootConcatRelativeSeparator() throws Exception {
  // Can't use SSHD because we need to access the root of the disk for these tests, which we might not have permission
  // so we'll need to mock things instead
  String[] values = getConcatRelativeSeparatorValues();
  for (int i = 0; i < getConcatRelativeSeparatorValues().length; i+=3) {
    String userDir = values[i];
    String root = values[i+1];
    String expected = values[i+2];

    SFTPClient sftpClient = Mockito.mock(SFTPClient.class);
    Mockito.when(sftpClient.canonicalize(".")).thenReturn(userDir);
    Mockito.when(sftpClient.statExistence(Mockito.anyString())).thenReturn(FileAttributes.EMPTY);

    new ChrootSFTPClient(sftpClient, root, true, false, false);
    Mockito.verify(sftpClient).statExistence(expected);
  }
}
 
Example 5
Source Project: datacollector   Source File: TestChrootSFTPClient.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testArchiveConcatRelativeSeparator() throws Exception {
  // Can't use SSHD because we need to access the root of the disk for these tests, which we might not have permission
  // so we'll need to mock things instead
  String[] values = getConcatRelativeSeparatorValues();
  for (int i = 0; i < getConcatRelativeSeparatorValues().length; i+=3) {
    String userDir = values[i];
    String archiveDir = values[i+1];
    String expected = values[i+2];

    SFTPClient sftpClient = Mockito.mock(SFTPClient.class);
    Mockito.when(sftpClient.canonicalize(".")).thenReturn(userDir);
    Mockito.when(sftpClient.statExistence(Mockito.anyString())).thenReturn(FileAttributes.EMPTY);

    ChrootSFTPClient chrootSFTPClient = new ChrootSFTPClient(sftpClient, "/root", true, false, false);
    chrootSFTPClient.setArchiveDir(archiveDir, true);
    chrootSFTPClient.archive("/path");
    Mockito.verify(sftpClient).rename(Mockito.anyString(), Mockito.eq(Paths.get(expected, "/path").toString()));
  }
}
 
Example 6
@Override
public PathAttributes find(final Path file) throws BackgroundException {
    if(file.isRoot()) {
        return PathAttributes.EMPTY;
    }
    try {
        final FileAttributes stat;
        if(file.isSymbolicLink()) {
            stat = session.sftp().lstat(file.getAbsolute());
        }
        else {
            stat = session.sftp().stat(file.getAbsolute());
        }
        switch(stat.getType()) {
            case BLOCK_SPECIAL:
            case CHAR_SPECIAL:
            case FIFO_SPECIAL:
            case SOCKET_SPECIAL:
            case REGULAR:
            case SYMLINK:
                if(!file.getType().contains(Path.Type.file)) {
                    throw new NotfoundException(String.format("Path %s is file", file.getAbsolute()));
                }
                break;
            case DIRECTORY:
                if(!file.getType().contains(Path.Type.directory)) {
                    throw new NotfoundException(String.format("Path %s is directory", file.getAbsolute()));
                }
                break;
        }
        return this.toAttributes(stat);
    }
    catch(IOException e) {
        throw new SFTPExceptionMappingService().map("Failure to read attributes of {0}", e, file);
    }
}
 
Example 7
@Override
public void setUnixOwner(final Path file, final String owner) throws BackgroundException {
    final FileAttributes attr = new FileAttributes.Builder()
            .withUIDGID(new Integer(owner), 0)
            .build();
    try {
        session.sftp().setAttributes(file.getAbsolute(), attr);
    }
    catch(IOException e) {
        throw new SFTPExceptionMappingService().map("Failure to write attributes of {0}", e, file);
    }
}
 
Example 8
@Override
public void setUnixGroup(final Path file, final String group) throws BackgroundException {
    final FileAttributes attr = new FileAttributes.Builder()
            .withUIDGID(0, new Integer(group))
            .build();
    try {
        session.sftp().setAttributes(file.getAbsolute(), attr);
    }
    catch(IOException e) {
        throw new SFTPExceptionMappingService().map("Failure to write attributes of {0}", e, file);
    }
}
 
Example 9
@Override
public void setUnixPermission(final Path file, final Permission permission) throws BackgroundException {
    final FileAttributes attr = new FileAttributes.Builder()
            .withPermissions(Integer.parseInt(permission.getMode(), 8))
            .build();
    try {
        session.sftp().setAttributes(file.getAbsolute(), attr);
    }
    catch(IOException e) {
        throw new SFTPExceptionMappingService().map("Failure to write attributes of {0}", e, file);
    }
}
 
Example 10
@Override
public void setTimestamp(final Path file, final TransferStatus status) throws BackgroundException {
    try {
        // We must both set the accessed and modified time. See AttribFlags.SSH_FILEXFER_ATTR_V3_ACMODTIME
        // All times are represented as seconds from Jan 1, 1970 in UTC.
        final FileAttributes attrs = new FileAttributes.Builder().withAtimeMtime(
            System.currentTimeMillis() / 1000, status.getTimestamp() / 1000
        ).build();
        session.sftp().setAttributes(file.getAbsolute(), attrs);
    }
    catch(IOException e) {
        throw new SFTPExceptionMappingService().map("Cannot change timestamp of {0}", e, file);
    }

}
 
Example 11
Source Project: datacollector   Source File: ChrootSFTPClient.java    License: Apache License 2.0 5 votes vote down vote up
public OutputStream openForWriting(String path) throws IOException {
  String toPath = prependRoot(path);
  // Create the toPath's parent dir(s) if they don't exist
  String toDir = Paths.get(toPath).getParent().toString();
  sftpClient.mkdirs(toDir);
  RemoteFile remoteFile = sftpClient.open(
      toPath,
      EnumSet.of(OpenMode.WRITE, OpenMode.CREAT, OpenMode.TRUNC),
      FileAttributes.EMPTY
  );
  return SFTPStreamFactory.createOutputStream(remoteFile);
}
 
Example 12
@Override
public Offset createOffset(String file) throws IOException {
  FileAttributes attributes = sftpClient.stat(file);
  Offset offset =
      new Offset(slashify(file),
      convertSecsToMillis(attributes.getMtime()),
      ZERO
  );
  return offset;
}
 
Example 13
@Override
public long populateMetadata(String remotePath, Map<String, Object> metadata) throws IOException {
  FileAttributes remoteAttributes = sftpClient.stat(remotePath);
  long size = remoteAttributes.getSize();
  metadata.put(HeaderAttributeConstants.SIZE, size);
  metadata.put(HeaderAttributeConstants.LAST_MODIFIED_TIME, convertSecsToMillis(remoteAttributes.getMtime()));
  metadata.put(RemoteDownloadSource.CONTENT_TYPE, determineContentType(remotePath));
  metadata.put(RemoteDownloadSource.CONTENT_ENCODING, null);  // VFS hardcodes this in FileContentInfoFilenameFactory
  return size;
}
 
Example 14
Source Project: brooklyn-server   Source File: SshjTool.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Void create() throws Exception {
    final AtomicReference<InputStream> inputStreamRef = new AtomicReference<InputStream>();
    sftp = acquire(sftpConnection);
    try {
        sftp.put(new InMemorySourceFile() {
            @Override public String getName() {
                return path;
            }
            @Override public long getLength() {
                return length;
            }
            @Override public InputStream getInputStream() throws IOException {
                InputStream contents = contentsSupplier.get();
                inputStreamRef.set(contents);
                return contents;
            }
        }, path);
        sftp.chmod(path, permissionsMask);
        if (uid != -1) {
            sftp.chown(path, uid);
        }
        if (lastAccessDate > 0) {
            sftp.setattr(path, new FileAttributes.Builder()
                    .withAtimeMtime(lastAccessDate, lastModificationDate)
                    .build());
        }
    } finally {
        closeWhispering(inputStreamRef.get(), this);
    }
    return null;
}
 
Example 15
Source Project: datacollector   Source File: ChrootSFTPClient.java    License: Apache License 2.0 4 votes vote down vote up
public FileAttributes stat(String path) throws IOException {
  return sftpClient.stat(prependRoot(path));
}
 
Example 16
private RemoteResourceInfo createRemoteResourceInfo(long mtime) {
	PathComponents comps = new PathComponents("parent", "name" + mtime, "/");
	FileAttributes attrs = new FileAttributes(0, 0, 0, 0, null, 0L, mtime, new HashMap<String, String>());
	return new RemoteResourceInfo(comps, attrs);
}