@Test public void testConvert() throws Exception { final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname())); if(session.isPosixFilesystem()) { session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback()); session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback()); final Path file = new Path(new LocalHomeFinderFeature(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); new LocalTouchFeature(session).touch(file, new TransferStatus()); final java.nio.file.Path local = session.toPath(file); final PosixFileAttributes posixAttributes = Files.readAttributes(local, PosixFileAttributes.class); final LocalAttributesFinderFeature finder = new LocalAttributesFinderFeature(session); assertEquals(PosixFilePermissions.toString(posixAttributes.permissions()), finder.find(file).getPermission().getSymbol()); Files.setPosixFilePermissions(local, PosixFilePermissions.fromString("rw-------")); assertEquals("rw-------", finder.find(file).getPermission().getSymbol()); Files.setPosixFilePermissions(local, PosixFilePermissions.fromString("rwxrwxrwx")); assertEquals("rwxrwxrwx", finder.find(file).getPermission().getSymbol()); Files.setPosixFilePermissions(local, PosixFilePermissions.fromString("rw-rw----")); assertEquals("rw-rw----", finder.find(file).getPermission().getSymbol()); assertEquals(posixAttributes.size(), finder.find(file).getSize()); assertEquals(posixAttributes.lastModifiedTime().toMillis(), finder.find(file).getModificationDate()); assertEquals(posixAttributes.creationTime().toMillis(), finder.find(file).getCreationDate()); assertEquals(posixAttributes.lastAccessTime().toMillis(), finder.find(file).getAccessedDate()); new LocalDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback()); } }
private static String getFileListEntry(File fileInDir) { StringBuilder sb = new StringBuilder(); try { PosixFileAttributes fa = Files.readAttributes(fileInDir.toPath(), PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS); sb.append(fa.isDirectory() ? "d" : fa.isSymbolicLink() ? "l" : fa.isRegularFile() ? "f" : "-"); sb.append(fileInDir.canRead() ? "r" : "-"); sb.append(fileInDir.canWrite() ? "w" : "-"); sb.append(fileInDir.canExecute() ? "x" : "-"); sb.append("\t"); sb.append(fa.owner()); sb.append(fa.owner().getName().length() < 4 ? "\t\t" : "\t"); sb.append(fa.group()); sb.append(fa.group().getName().length() < 4 ? "\t\t" : "\t"); sb.append(fa.size()); sb.append(String.valueOf(fa.size()).length() < 4 ? "\t\t" : "\t"); sb.append(fa.lastModifiedTime().toString()); sb.append("\t"); sb.append(fa.isDirectory() ? fileInDir.getName() + "/" : fileInDir.getName()); } catch (IOException e) { logger.log(Level.WARNING, "Failed to get file attributes", e); } logger.info(sb.toString()); return sb.toString(); }
private int resetFileAttributes(Context context, FileState fileState, Path file) throws IOException { boolean attributesModified = false; try { BasicFileAttributes attributes; if (SystemUtils.IS_OS_WINDOWS) { DosFileAttributes dosFileAttributes = Files.readAttributes(file, DosFileAttributes.class); attributes = dosFileAttributes; attributesModified = resetDosPermissions(context, file, fileState, dosFileAttributes) || attributesModified; } else { PosixFileAttributes posixFileAttributes = Files.readAttributes(file, PosixFileAttributes.class); attributes = posixFileAttributes; attributesModified = resetPosixPermissions(file, fileState, posixFileAttributes) || attributesModified; } attributesModified = resetCreationTime(file, fileState, attributes) || attributesModified; attributesModified = resetLastModified(file, fileState, attributes) || attributesModified; attributesModified = resetSELinux(context, file, fileState) || attributesModified; } catch (Exception ex) { Logger.error(ex.getMessage()); } return attributesModified ? 1 : 0; }
/** {@inheritDoc} */ @Override public IgfsFile info(final IgfsPath path) { File file = fileForPath(path); if (!file.exists()) return null; boolean isDir = file.isDirectory(); PosixFileAttributes attrs = LocalFileSystemUtils.posixAttributes(file); Map<String, String> props = LocalFileSystemUtils.posixAttributesToMap(attrs); BasicFileAttributes basicAttrs = LocalFileSystemUtils.basicAttributes(file); if (isDir) { return new LocalFileSystemIgfsFile(path, false, true, 0, basicAttrs.lastAccessTime().toMillis(), basicAttrs.lastModifiedTime().toMillis(), 0, props); } else { return new LocalFileSystemIgfsFile(path, file.isFile(), false, 0, basicAttrs.lastAccessTime().toMillis(), basicAttrs.lastModifiedTime().toMillis(), file.length(), props); } }
/** * Get POSIX attributes for file. * * @param file File. * @return PosixFileAttributes. */ @Nullable public static PosixFileAttributes posixAttributes(File file) { PosixFileAttributes attrs = null; try { PosixFileAttributeView view = Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class); if (view != null) attrs = view.readAttributes(); } catch (IOException e) { throw new IgfsException("Failed to read POSIX attributes: " + file.getAbsolutePath(), e); } return attrs; }
private void constructCrawlBundle(Path src, Path dest) throws IOException { Path zipFile = dest.resolve("crawl-bundle.zip"); try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(zipFile))) { Files.walk(src) .filter(ImportJob::shouldIncludeInCrawlBundle) .forEachOrdered((path) -> { ZipEntry entry = new ZipEntry(src.relativize(path).toString()); try { PosixFileAttributes attr = Files.readAttributes(path, PosixFileAttributes.class); entry.setCreationTime(attr.creationTime()); entry.setLastModifiedTime(attr.lastModifiedTime()); entry.setLastAccessTime(attr.lastAccessTime()); entry.setSize(attr.size()); zip.putNextEntry(entry); Files.copy(path, zip); } catch (IOException e) { throw new UncheckedIOException(e); } }); } }
@Override public RsyncFileAttributes stat(Path path) throws IOException { PosixFileAttributes attrs = Files.readAttributes(path, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS); UserPrincipal userPrincipal = attrs.owner(); String userName = userPrincipal.getName(); GroupPrincipal groupPrincipal = attrs.group(); String groupName = groupPrincipal.getName(); _nameToUserPrincipal.putIfAbsent(userName, userPrincipal); _nameToGroupPrincipal.putIfAbsent(groupName, groupPrincipal); return new RsyncFileAttributes(toMode(attrs), attrs.size(), attrs.lastModifiedTime().to(TimeUnit.SECONDS), new User(userName, _defaultUserId), new Group(groupName, _defaultGroupId)); }
/** * @param path * @return */ public static String getPosixAttributesString(Path path) { PosixFileAttributeView posixView = Files.getFileAttributeView(path, PosixFileAttributeView.class); StringBuilder attrs = new StringBuilder(); try { // + all basic attributes PosixFileAttributes posixAttrs = posixView.readAttributes(); if (posixAttrs != null) { attrs.append(PosixFilePermissions.toString(posixAttrs.permissions())); } } catch (IOException e) { log.warn("unable to read Posix file attributes.", e); //$NON-NLS-1$ } return attrs.toString(); }
@Override public Map<String, Object> readAttributes(String attributes, LinkOption[] options) throws IOException { PosixFileAttributes zfas = readAttributes(); LinkedHashMap<String, Object> map = new LinkedHashMap<>(); if ("*".equals(attributes)) { for (AttrID id : AttrID.values()) { map.put(id.name(), attribute(id, zfas)); } } else { String[] as = attributes.split(","); for (String a : as) { map.put(a, attribute(AttrID.valueOf(a), zfas)); } } return map; }
@SuppressWarnings("unchecked") @Override public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options) throws IOException { if (type == BasicFileAttributes.class || type == HadoopBasicFileAttributes.class) { return (A) toHadoopPath(path).getAttributes(); } if (type == PosixFileAttributes.class) { return (A) toHadoopPath(path).getPosixAttributes(); } throw new UnsupportedOperationException("readAttributes:" + type.getName()); }
public UnixBuilder( FSDescription descr, T t ) { super( descr, t ); PathLimits pathLimits = new PathLimits( OS.UNIX ); PathSpec pathSpec = new PathSpecUnix(); descr.props.put( Tests10PathWithContent.ONE_CHAR_COUNT, pathLimits.getBigChar() ); descr.props.put( Tests10PathWithContent.MAX_FILENAME_LENGTH, pathSpec.getMaxFilenameLength() ); descr.props.put( Tests10PathWithContent.MAX_PATH_LENGTH, pathSpec.getMaxPathLength() ); descr.props.put( Tests10PathWithContent.GET_FILENAME_LENGTH, (Function<String,Integer>)pathSpec::getFilenameLength ); descr.props.put( Tests10PathWithContent.GET_PATH_LENGTH, (Function<String,Integer>)pathSpec::getPathLength ); // descr.removeTopic( LimitedPath.class ); theory but linux c limits descr.removeTopic( Windows.class ); descr.removeTopic( DosAttributesT.class ); descr.removeTopic( CaseInsensitive.class ); descr.removeTopic( NonCasePreserving.class ); descr.attributeDescriptions.put( "posix", attributeBuilding( Posix.class, "posix", PosixFileAttributeView.class, PosixFileAttributes.class ). addAttribute( "owner", PosixFileAttributes::owner ). addAttribute( "permissions", PosixFileAttributes::permissions ). addAttribute( "group", PosixFileAttributes::group ). build()); }
@Test public void testCreateReadOnlyFileSetsPermissions() throws IOException { Path path = Paths.get("hello.txt"); ImmutableSet<PosixFilePermission> permissions = ImmutableSet.<PosixFilePermission>of( PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ, PosixFilePermission.OTHERS_READ); filesystem.writeContentsToPath( "hello world", path, PosixFilePermissions.asFileAttribute(permissions)); // The umask may restrict the actual permissions on the filesystem: // https://fburl.com/26569549 // So the best we can do is to check that the actual permissions are a // strict subset of the expected permissions. PosixFileAttributes attrs = filesystem.readAttributes(path, PosixFileAttributes.class); assertTrue(permissions.containsAll(attrs.permissions())); }
@Test public void testCreateReadOnlyFileSetsPermissions() throws IOException { Assume.assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")); Path path = Paths.get("hello.txt"); ImmutableSet<PosixFilePermission> permissions = ImmutableSet.of( PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ, PosixFilePermission.OTHERS_READ); filesystem.writeContentsToPath( "hello world", path, PosixFilePermissions.asFileAttribute(permissions)); // The umask may restrict the actual permissions on the filesystem: // https://fburl.com/26569549 // So the best we can do is to check that the actual permissions are a // strict subset of the expected permissions. PosixFileAttributes attrs = filesystem.readAttributes(path, PosixFileAttributes.class); assertTrue(permissions.containsAll(attrs.permissions())); }
/** * 设置文件权限。前提:必须支持PosixFileAttributeView. */ public static void setFilePerm(File file, String perm) { if (filePermSupported()) { try { Set<PosixFilePermission> perms = PosixFilePermissions.fromString(perm); PosixFileAttributes attr = Files.readAttributes(file.toPath(), PosixFileAttributes.class); attr.permissions().clear(); Files.setPosixFilePermissions(file.toPath(), perms); } catch (IOException e) { throw new IllegalStateException(e); } } }
/** * Copies the files from {@code tmpConfigDir} into {@code destConfigDir}. * Any files existing in both the source and destination will be skipped. */ private void installConfig(PluginInfo info, Path tmpConfigDir, Path destConfigDir) throws Exception { if (Files.isDirectory(tmpConfigDir) == false) { throw new UserException(ExitCodes.IO_ERROR, "config in plugin " + info.getName() + " is not a directory"); } Files.createDirectories(destConfigDir); setFileAttributes(destConfigDir, CONFIG_DIR_PERMS); final PosixFileAttributeView destConfigDirAttributesView = Files.getFileAttributeView(destConfigDir.getParent(), PosixFileAttributeView.class); final PosixFileAttributes destConfigDirAttributes = destConfigDirAttributesView != null ? destConfigDirAttributesView.readAttributes() : null; if (destConfigDirAttributes != null) { setOwnerGroup(destConfigDir, destConfigDirAttributes); } try (DirectoryStream<Path> stream = Files.newDirectoryStream(tmpConfigDir)) { for (Path srcFile : stream) { if (Files.isDirectory(srcFile)) { throw new UserException(ExitCodes.DATA_ERROR, "Directories not allowed in config dir for plugin " + info.getName()); } Path destFile = destConfigDir.resolve(tmpConfigDir.relativize(srcFile)); if (Files.exists(destFile) == false) { Files.copy(srcFile, destFile); setFileAttributes(destFile, CONFIG_FILES_PERMS); if (destConfigDirAttributes != null) { setOwnerGroup(destFile, destConfigDirAttributes); } } } } IOUtils.rm(tmpConfigDir); // clean up what we just copied }
private static void setOwnerGroup(final Path path, final PosixFileAttributes attributes) throws IOException { Objects.requireNonNull(attributes); PosixFileAttributeView fileAttributeView = Files.getFileAttributeView(path, PosixFileAttributeView.class); assert fileAttributeView != null; fileAttributeView.setOwner(attributes.owner()); fileAttributeView.setGroup(attributes.group()); }
/** * * @param filename the file name * @return the file owner * @throws FileSystemOperationException */ private String getOwner( String filename ) { try { UserPrincipal owner = Files.readAttributes( new File( filename ).toPath(), PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS ) .owner(); return owner.getName(); } catch( Exception e ) { throw new FileSystemOperationException( "Could not get owner for '" + filename + "'", e ); } }
/** * * @param filename the file name * @return the file group name * @throws FileSystemOperationException */ private String getGroup( String filename ) { try { GroupPrincipal group = Files.readAttributes( new File( filename ).toPath(), PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS ) .group(); return group.getName(); } catch( Exception e ) { throw new FileSystemOperationException( "Could not get group for '" + filename + "'", e ); } }
protected PathAttributes convert(final java.nio.file.Path file) throws IOException { final boolean isPosix = session.isPosixFilesystem(); final PathAttributes attributes = new PathAttributes(); final Class<? extends BasicFileAttributes> provider = isPosix ? PosixFileAttributes.class : DosFileAttributes.class; final BasicFileAttributes a = Files.readAttributes(file, provider, LinkOption.NOFOLLOW_LINKS); if(Files.isRegularFile(file)) { attributes.setSize(a.size()); } attributes.setModificationDate(a.lastModifiedTime().toMillis()); attributes.setCreationDate(a.creationTime().toMillis()); attributes.setAccessedDate(a.lastAccessTime().toMillis()); if(isPosix) { attributes.setOwner(((PosixFileAttributes) a).owner().getName()); attributes.setGroup(((PosixFileAttributes) a).group().getName()); attributes.setPermission(new Permission(PosixFilePermissions.toString(((PosixFileAttributes) a).permissions()))); } else { Permission.Action actions = Permission.Action.none; if(Files.isReadable(file)) { actions = actions.or(Permission.Action.read); } if(Files.isWritable(file)) { actions = actions.or(Permission.Action.write); } if(Files.isExecutable(file)) { actions = actions.or(Permission.Action.execute); } attributes.setPermission(new Permission( actions, Permission.Action.none, Permission.Action.none )); } return attributes; }
@Override public Permission getPermission() { if(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) { final BasicFileAttributes attributes; try { return new LocalPermission(PosixFilePermissions.toString(Files.readAttributes(Paths.get(path), PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS).permissions())); } catch(IOException e) { return Permission.EMPTY; } } return Permission.EMPTY; }
static final boolean isFileReadOnly(final File file) { if (System.getProperty("os.name").startsWith("Windows")) { return !file.canWrite(); } //All Unix-like OSes final Path path = Paths.get(file.getAbsolutePath()); PosixFileAttributes attributes = null; try { attributes = Files.getFileAttributeView(path, PosixFileAttributeView.class).readAttributes(); } catch (final IOException e) { // File presence is guaranteed. Ignore e.printStackTrace(); } if (attributes == null) { return false; } // A file is read-only in Linux-derived OSes only when it has 0444 permissions. final Set<PosixFilePermission> permissions = attributes.permissions(); int bits = 0; bits |= ((permissions.contains(PosixFilePermission.OWNER_READ)) ? 1 << 8 : 0); bits |= ((permissions.contains(PosixFilePermission.OWNER_WRITE)) ? 1 << 7 : 0); bits |= ((permissions.contains(PosixFilePermission.OWNER_EXECUTE)) ? 1 << 6 : 0); bits |= ((permissions.contains(PosixFilePermission.GROUP_READ)) ? 1 << 5 : 0); bits |= ((permissions.contains(PosixFilePermission.GROUP_WRITE)) ? 1 << 4 : 0); bits |= ((permissions.contains(PosixFilePermission.GROUP_EXECUTE)) ? 1 << 3 : 0); bits |= ((permissions.contains(PosixFilePermission.OTHERS_READ)) ? 1 << 2 : 0); bits |= ((permissions.contains(PosixFilePermission.OTHERS_WRITE)) ? 1 << 1 : 0); bits |= ((permissions.contains(PosixFilePermission.OTHERS_EXECUTE)) ? 1 : 0); //System.out.println(Util.zeroPad(Integer.toBinaryString(bits), 32)); //System.out.println(Util.zeroPad(Integer.toOctalString(bits), 4)); // Here we are going to ignore the Owner Write & Execute bits to allow root/owner testing. return ((bits & 0477) == 0444); }
public static boolean isUnixStickyBit(Path path) throws IOException, InvalidFileSystemException { PosixFileAttributes attr = Files.readAttributes(path, PosixFileAttributes.class); try { Field st_modeField = attr.getClass().getDeclaredField("st_mode"); st_modeField.setAccessible(true); int st_mode = st_modeField.getInt(attr); return (st_mode & S_ISVTX) > 0; } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { throw new InvalidFileSystemException("File is not on a Unix file system: " + e.getMessage(), e); } }
/** * * @param fileLoc * @return */ public static Map<String, String> getFileMetadata(Path fileLoc) { Map<String, String> linkedHashMap = new LinkedHashMap<>(); try { DosFileAttributes dosFileAttr = Files.readAttributes(fileLoc, DosFileAttributes.class); linkedHashMap.put("File Name", fileLoc.getFileName().toString()); linkedHashMap.put("File Location", fileLoc.toString()); linkedHashMap.put("File Size", readableFileSize(dosFileAttr.size())); linkedHashMap.put("Creation Time", getDateTime(dosFileAttr.creationTime())); linkedHashMap.put("Last Accessed Time", getDateTime(dosFileAttr.lastAccessTime())); linkedHashMap.put("Last Modified Time", getDateTime(dosFileAttr.lastModifiedTime())); linkedHashMap.put("Is Directory?", dosFileAttr.isDirectory() ? "True" : "False"); linkedHashMap.put("Is Regular File?", dosFileAttr.isRegularFile() ? "True" : "False"); linkedHashMap.put("Is Symbolic Link?", dosFileAttr.isSymbolicLink() ? "True" : "False"); linkedHashMap.put("Is Archive?", dosFileAttr.isArchive() ? "True" : "False"); linkedHashMap.put("Is Hidden File?", dosFileAttr.isHidden() ? "True" : "False"); linkedHashMap.put("Is ReadOnly?", dosFileAttr.isReadOnly() ? "True" : "False"); linkedHashMap.put("Is System File?", dosFileAttr.isSystem() ? "True" : "False"); if (getOsName().equals("Linux")) { PosixFileAttributes attr = Files.readAttributes(fileLoc, PosixFileAttributes.class); String posixPerm = String.format("%s %s %s%n", attr.owner().getName(), attr.group().getName(), PosixFilePermissions.toString(attr.permissions())); linkedHashMap.put("Posix", posixPerm); } } catch (UnsupportedOperationException | IOException ex) { System.err.println(ex.getMessage()); } return linkedHashMap; }
private SegmentProperties doGetStreamSegmentInfo(String streamSegmentName) throws IOException { long traceId = LoggerHelpers.traceEnter(log, "getStreamSegmentInfo", streamSegmentName); PosixFileAttributes attrs = Files.readAttributes(Paths.get(config.getRoot(), streamSegmentName), PosixFileAttributes.class); StreamSegmentInformation information = StreamSegmentInformation.builder() .name(streamSegmentName) .length(attrs.size()) .sealed(!(attrs.permissions().contains(OWNER_WRITE))) .lastModified(new ImmutableDate(attrs.creationTime().toMillis())) .build(); LoggerHelpers.traceLeave(log, "getStreamSegmentInfo", traceId, streamSegmentName); return information; }
/** * Helper method to rwx stringify POSIX permissions. * @param path path of object * @param attrs POSIX attributes object * @return rwx permissions as string */ private String stringifyPermissions(Path path, PosixFileAttributes attrs) { String permissions = ""; //Type descriptor if (Files.isDirectory(path)) { permissions += "d"; } else if (Files.isSymbolicLink(path)) { permissions += "l"; } else if (Files.isRegularFile(path)) { permissions += "-"; } else { permissions += " "; } //Permissions permissions += attrs.permissions().contains(PosixFilePermission.OWNER_READ) ? "r" : "-"; permissions += attrs.permissions().contains(PosixFilePermission.OWNER_WRITE) ? "w" : "-"; permissions += attrs.permissions().contains(PosixFilePermission.OWNER_EXECUTE) ? "x" : "-"; permissions += attrs.permissions().contains(PosixFilePermission.GROUP_READ) ? "r" : "-"; permissions += attrs.permissions().contains(PosixFilePermission.GROUP_WRITE) ? "w" : "-"; permissions += attrs.permissions().contains(PosixFilePermission.GROUP_EXECUTE) ? "x" : "-"; permissions += attrs.permissions().contains(PosixFilePermission.OTHERS_READ) ? "r" : "-"; permissions += attrs.permissions().contains(PosixFilePermission.OTHERS_WRITE) ? "w" : "-"; permissions += attrs.permissions().contains(PosixFilePermission.OTHERS_EXECUTE) ? "x" : "-"; return permissions; }
public static void main(String[] args) { try { Path path = Paths.get("metadata.txt"); Files.deleteIfExists(path); Files.createFile(path); BasicFileAttributeView basicView = Files.getFileAttributeView(path, BasicFileAttributeView.class); BasicFileAttributes basicAttributes = basicView.readAttributes(); boolean isDirectory = basicAttributes.isDirectory(); FileTime lastModifiedTime = basicAttributes.lastModifiedTime(); System.out.println(isDirectory); System.out.println(lastModifiedTime); PosixFileAttributeView posixView = Files.getFileAttributeView(path, PosixFileAttributeView.class); PosixFileAttributes posixAttributes = posixView.readAttributes(); GroupPrincipal group = posixAttributes.group(); Set<PosixFilePermission> permissions = posixAttributes.permissions(); permissions.add(PosixFilePermission.OWNER_EXECUTE); posixView.setPermissions(permissions); System.out.println(group); } catch (IOException e) { // Log and Handle exception e.printStackTrace(); } }
private void hashFilesInQueue() throws InterruptedException { Path file; while ((file = filesToHashQueue.poll(100, TimeUnit.MILLISECONDS)) != null) { try { BasicFileAttributes attributes; List<Attribute> fileAttributes = null; if (SystemUtils.IS_OS_WINDOWS) { DosFileAttributes dosFileAttributes = Files.readAttributes(file, DosFileAttributes.class); fileAttributes = addAttribute(fileAttributes, FileAttribute.DosFilePermissions, DosFilePermissions.toString(dosFileAttributes)); attributes = dosFileAttributes; } else { PosixFileAttributes posixFileAttributes = Files.readAttributes(file, PosixFileAttributes.class); fileAttributes = addAttribute(fileAttributes, FileAttribute.PosixFilePermissions, PosixFilePermissions.toString(posixFileAttributes.permissions())); if (SELinux.ENABLED) { fileAttributes = addAttribute(fileAttributes, FileAttribute.SELinuxLabel, SELinux.getLabel(context, file)); } attributes = posixFileAttributes; } hashProgress.updateOutput(attributes.size()); FileHash fileHash = hashFile(file, attributes.size()); String normalizedFileName = FileUtil.getNormalizedFileName(file); String relativeFileName = FileUtil.getRelativeFileName(rootDir, normalizedFileName); fileStates.add(new FileState(relativeFileName, attributes, fileHash, fileAttributes)); } catch (Exception ex) { Logger.newLine(); Logger.error("Skipping - Error hashing file '" + file + "'", ex, context.isDisplayStackTrace()); } } }
private boolean resetPosixPermissions(Path file, FileState fileState, PosixFileAttributes posixFileAttributes) throws IOException { String permissions = PosixFilePermissions.toString(posixFileAttributes.permissions()); String previousPermissions = getAttribute(fileState, FileAttribute.PosixFilePermissions); if (previousPermissions != null && !Objects.equals(permissions, previousPermissions)) { Set<PosixFilePermission> permissionSet = PosixFilePermissions.fromString(previousPermissions); Files.getFileAttributeView(file, PosixFileAttributeView.class).setPermissions(permissionSet); Logger.out.printf("Set permissions: %s \t%s -> %s%n", fileState.getFileName(), permissions, previousPermissions); return true; } return false; }
@Test public void getPermissionOfFile_shouldReturnNotNull() throws IOException { writeToCache("/file.txt"); commitToMaster(); initGitFileSystem(); PosixFileAttributes attributes = readPosixAttributes("/file.txt"); assertNotNull(attributes.permissions()); }
@Test public void getPermissionOfFile_shouldContainOwnerRead() throws IOException { writeToCache("/file.txt"); commitToMaster(); initGitFileSystem(); PosixFileAttributes attributes = readPosixAttributes("/file.txt"); Collection permissions = (Collection) attributes.permissions(); assertTrue(permissions.contains(PosixFilePermission.OWNER_READ)); }
@Test public void getPermissionOfFile_shouldContainOwnerWrite() throws IOException { writeToCache("/file.txt"); commitToMaster(); initGitFileSystem(); PosixFileAttributes attributes = readPosixAttributes("/file.txt"); Collection permissions = (Collection) attributes.permissions(); assertTrue(permissions.contains(PosixFilePermission.OWNER_WRITE)); }
@Test public void getPermissionOfFile_shouldNotContainOwnerExecute() throws IOException { writeToCache("/file.txt"); commitToMaster(); initGitFileSystem(); PosixFileAttributes attributes = readPosixAttributes("/file.txt"); Collection permissions = (Collection) attributes.permissions(); assertFalse(permissions.contains(OWNER_EXECUTE)); }
@Test public void getPermissionOfExecutableFile_shouldContainOwnerExecute() throws IOException { writeToCache("/file.txt", someBytes(), EXECUTABLE_FILE); commitToMaster(); initGitFileSystem(); PosixFileAttributes attributes = readPosixAttributes("/file.txt"); Collection permissions = (Collection) attributes.permissions(); assertTrue(permissions.contains(OWNER_EXECUTE)); }
@Test public void getOwnerOfFile_shouldReturnNull() throws IOException { writeToCache("/file.txt"); commitToMaster(); initGitFileSystem(); PosixFileAttributes attributes = readPosixAttributes("/file.txt"); assertNull(attributes.owner()); }
@Test public void getGroupOfFile_shouldReturnNull() throws IOException { writeToCache("/file.txt"); commitToMaster(); initGitFileSystem(); PosixFileAttributes attributes = readPosixAttributes("/file.txt"); assertNull(attributes.group()); }
public int getUnixMode(File file) { try { final PosixFileAttributes posixFileAttributes = Files.readAttributes(file.toPath(), PosixFileAttributes.class); return convertToInt(posixFileAttributes.permissions()); }catch (Exception e) { throw new NativeIntegrationException(String.format("Failed to read File permissions for %s", file.getAbsolutePath()), e); } }
/** {@inheritDoc} */ @Override public Map<String, String> properties(final String path) throws IOException { Path p = path(path); PosixFileAttributes attrs = Files.getFileAttributeView(p, PosixFileAttributeView.class).readAttributes(); Map<String, String> props = new HashMap<>(); props.put(IgfsUtils.PROP_USER_NAME, attrs.owner().getName()); props.put(IgfsUtils.PROP_GROUP_NAME, attrs.group().getName()); props.put(IgfsUtils.PROP_PERMISSION, permissions(path)); return props; }
public <V extends BasicFileAttributes> V cast(Class<V> type) { if(type == BasicFileAttributes.class) { return (V) new EphemeralFsBasicFileAttributes(); } else if(type == PosixFileAttributes.class) { return (V) new EphemeralFsPosixFileAttributes(); } else if(type == DosFileAttributes.class) { return (V) new EphemeralFsDosFileAttributes(); } //there is no FileOwnerAttributes ? else { throw new UnsupportedOperationException("type:" + type + " is not supported"); } }
private Class<? extends BasicFileAttributeView> viewClassFor( Class<? extends BasicFileAttributes> attributeClass) { if (attributeClass == BasicFileAttributes.class) { return BasicFileAttributeView.class; } else if (attributeClass == PosixFileAttributes.class) { return PosixFileAttributeView.class; } else if (attributeClass == DosFileAttributes.class) { return DosFileAttributeView.class; } else { throw new IllegalArgumentException("unrecognized view class:" + attributeClass); } }
@IgnoreIf(FsType.WINDOWS) @Test public void testReadPosix() throws Exception { PosixFileAttributes attributes = Files.readAttributes(root, PosixFileAttributes.class); assertNotNull(attributes); assertNotNull(attributes.creationTime()); }