@Override public int create(String path, @mode_t long mode, FuseFileInfo fi) { try { Set<OpenFlags> flags = bitMaskUtil.bitMaskToSet(OpenFlags.class, fi.flags.longValue()); LOG.info("createAndOpen {} with openOptions {}", path, flags); Path node = resolvePath(path); if (fileStore.supportsFileAttributeView(PosixFileAttributeView.class)) { FileAttribute<?> attrs = PosixFilePermissions.asFileAttribute(attrUtil.octalModeToPosixPermissions(mode)); return fileHandler.createAndOpen(node, fi, attrs); } else { return fileHandler.createAndOpen(node, fi); } } catch (RuntimeException e) { LOG.error("create failed.", e); return -ErrorCodes.EIO(); } }
public static void assertFilePermissions(Path testRoot) throws IOException { Path file1 = testRoot.resolve(FILE_1); // mode 664 PosixFileAttributeView allAttributesFile1 = Files.getFileAttributeView(file1, PosixFileAttributeView.class); Assert.assertThat( allAttributesFile1.readAttributes().permissions(), Matchers.containsInAnyOrder( PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.GROUP_READ)); Path file2 = testRoot.resolve(FILE_2); // mode 777 PosixFileAttributeView allAttributesFile2 = Files.getFileAttributeView(file2, PosixFileAttributeView.class); Assert.assertThat( allAttributesFile2.readAttributes().permissions(), Matchers.containsInAnyOrder(PosixFilePermission.values())); }
/** * creates and grants permission to daemon files directory */ private static void setupEnvironment() { final File daemonFilePath = new File("/var/run/iofabric"); if (!daemonFilePath.exists()) { try { daemonFilePath.mkdirs(); UserPrincipalLookupService lookupservice = FileSystems.getDefault().getUserPrincipalLookupService(); final GroupPrincipal group = lookupservice.lookupPrincipalByGroupName("iofabric"); Files.getFileAttributeView(daemonFilePath.toPath(), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS).setGroup(group); Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxrwx---"); Files.setPosixFilePermissions(daemonFilePath.toPath(), perms); } catch (Exception e) { } } }
/** * Adds the executable file permission. * * @param file the path to the file */ private void addExecutablePermission(String file) { final Path path = Paths.get(file); if (Files.exists(path)) { try { PosixFileAttributeView attr = Files.getFileAttributeView(path, PosixFileAttributeView.class); Set<PosixFilePermission> permissions = attr.readAttributes().permissions(); if(permissions.add(PosixFilePermission.OWNER_EXECUTE)) { logger.info(String.format("Added +x permission to file: %s", file)); } attr.setPermissions(permissions); } catch (IOException e) { logger.error(String.format("Failed to add the executable permissions to file: %s", file)); } } }
/** * 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 Set<String> getSupportedFileAttributes(FileStore fs) { Set<String> attrs = new HashSet<String>(); if (fs.supportsFileAttributeView(AclFileAttributeView.class)) { attrs.add("acl"); } if (fs.supportsFileAttributeView(BasicFileAttributeView.class)) { attrs.add("basic"); } if (fs.supportsFileAttributeView(FileOwnerAttributeView.class)) { attrs.add("owner"); } if (fs.supportsFileAttributeView(UserDefinedFileAttributeView.class)) { attrs.add("user"); } if (fs.supportsFileAttributeView(DosFileAttributeView.class)) { attrs.add("dos"); } if (fs.supportsFileAttributeView(PosixFileAttributeView.class)) { attrs.add("posix"); } if (fs.supportsFileAttributeView(FileAttributeView.class)) { attrs.add("file"); } return attrs; }
public boolean supportsFileAttributeView( Class<? extends FileAttributeView> type) { String name = "notFound"; if(type == BasicFileAttributeView.class) { name = "basic"; } else if(type == DosFileAttributeView.class) { name = "dos"; } else if(type == PosixFileAttributeView.class) { name = "posix"; } else if(type == FileOwnerAttributeView.class) { name = "owner"; } return attributeSets.containsKey(name); }
/** * Sets permissions on a {@link Resource} - doesn't do anything * for unsupported resource types. * * <p>Supported types are:</p> * <ul> * <li>any {@link FileProvider}</li> * <li>{@link ArchiveResource}</li> * </ul> * * @param r the resource to set permissions for * @param permissions the permissions * @param posixNotSupportedCallback optional callback that is * invoked for a file provider resource if the file-system holding * the file doesn't support PosixFilePermissions. The Path * corresponding to the file is passed to the callback. * @throws IOException if something goes wrong */ public static void setPermissions(Resource r, Set<PosixFilePermission> permissions, Consumer<Path> posixNotSupportedCallback) throws IOException { FileProvider f = r.as(FileProvider.class); if (f != null) { Path p = f.getFile().toPath(); PosixFileAttributeView view = Files.getFileAttributeView(p, PosixFileAttributeView.class); if (view != null) { view.setPermissions(permissions); } else if (posixNotSupportedCallback != null) { posixNotSupportedCallback.accept(p); } } else if (r instanceof ArchiveResource) { ((ArchiveResource) r).setMode(modeFromPermissions(permissions, FileType.of(r))); } }
/** * @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(); }
/** * Test: File and FileStore attributes */ @Test public void testFileStoreAttributes() throws URISyntaxException, IOException { URI uri = clusterUri.resolve("/tmp/testFileStore"); Path path = Paths.get(uri); if (Files.exists(path)) Files.delete(path); assertFalse(Files.exists(path)); Files.createFile(path); assertTrue(Files.exists(path)); FileStore store1 = Files.getFileStore(path); assertNotNull(store1); assertTrue(store1.supportsFileAttributeView("basic")); assertTrue(store1.supportsFileAttributeView(BasicFileAttributeView.class)); assertTrue(store1.supportsFileAttributeView("posix") == store1 .supportsFileAttributeView(PosixFileAttributeView.class)); assertTrue(store1.supportsFileAttributeView("dos") == store1 .supportsFileAttributeView(DosFileAttributeView.class)); assertTrue(store1.supportsFileAttributeView("acl") == store1 .supportsFileAttributeView(AclFileAttributeView.class)); assertTrue(store1.supportsFileAttributeView("user") == store1 .supportsFileAttributeView(UserDefinedFileAttributeView.class)); }
/** * Test {@code posix} file view support. * * @throws IOException */ @Test public void testGetPosixFileAttributeView() throws IOException { Path rootPath = Paths.get(clusterUri); assertTrue(rootPath.getFileSystem().supportedFileAttributeViews() .contains("posix")); // Get root view PosixFileAttributeView view = Files.getFileAttributeView(rootPath, PosixFileAttributeView.class); assertNotNull(view); assertNotNull(view.readAttributes()); assertNotNull(view.readAttributes().lastModifiedTime()); }
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()); }
private void makeWritable(Path file) throws IOException { FileStore fileStore = Files.getFileStore(file); if (IS_WINDOWS && fileStore.supportsFileAttributeView(DosFileAttributeView.class)) { DosFileAttributeView dosAttribs = Files.getFileAttributeView(file, DosFileAttributeView.class); if (dosAttribs != null) { dosAttribs.setReadOnly(false); } } else if (fileStore.supportsFileAttributeView(PosixFileAttributeView.class)) { PosixFileAttributeView posixAttribs = Files.getFileAttributeView(file, PosixFileAttributeView.class); if (posixAttribs != null) { posixAttribs.setPermissions(EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE)); } } }
@Override public void setPosixFilePermissions(Path path, Set<PosixFilePermission> permissions) throws XenonException { if (permissions == null) { throw new IllegalArgumentException("Permissions is null!"); } Path absPath = toAbsolutePath(path); assertPathExists(absPath); try { PosixFileAttributeView view = Files.getFileAttributeView(javaPath(absPath), PosixFileAttributeView.class); view.setPermissions(javaPermissions(permissions)); } catch (IOException e) { throw new XenonException(ADAPTOR_NAME, "Failed to set permissions " + absPath, e); } }
@Override public int getattr(Path node, FileStat stat) { int result = super.getattr(node, stat); if (result == 0 && fileStore.supportsFileAttributeView(PosixFileAttributeView.class)) { stat.st_mode.set(FileStat.S_IFDIR | 0755); } else if (result == 0) { stat.st_mode.set(FileStat.S_IFDIR | 0777); } return result; }
@Override public int getattr(Path node, FileStat stat) { int result = super.getattr(node, stat); if (result == 0 && fileStore.supportsFileAttributeView(PosixFileAttributeView.class)) { stat.st_mode.set(FileStat.S_IFREG | 0644); } else if (result == 0) { stat.st_mode.set(FileStat.S_IFREG | 0777); } return result; }
/** Write the keystore to the given config directory. */ void save(Path configDir) throws Exception { char[] password = this.keystorePassword.get().getPassword(); SimpleFSDirectory directory = new SimpleFSDirectory(configDir); // write to tmp file first, then overwrite String tmpFile = KEYSTORE_FILENAME + ".tmp"; try (IndexOutput output = directory.createOutput(tmpFile, IOContext.DEFAULT)) { CodecUtil.writeHeader(output, KEYSTORE_FILENAME, FORMAT_VERSION); output.writeByte(password.length == 0 ? (byte)0 : (byte)1); output.writeString(type); output.writeString(secretFactory.getAlgorithm()); ByteArrayOutputStream keystoreBytesStream = new ByteArrayOutputStream(); keystore.get().store(keystoreBytesStream, password); byte[] keystoreBytes = keystoreBytesStream.toByteArray(); output.writeInt(keystoreBytes.length); output.writeBytes(keystoreBytes, keystoreBytes.length); CodecUtil.writeFooter(output); } Path keystoreFile = keystorePath(configDir); Files.move(configDir.resolve(tmpFile), keystoreFile, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); PosixFileAttributeView attrs = Files.getFileAttributeView(keystoreFile, PosixFileAttributeView.class); if (attrs != null) { // don't rely on umask: ensure the keystore has minimal permissions attrs.setPermissions(PosixFilePermissions.fromString("rw-------")); } }
/** * 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 }
/** * Sets the attributes for a path iff posix attributes are supported */ private static void setFileAttributes(final Path path, final Set<PosixFilePermission> permissions) throws IOException { PosixFileAttributeView fileAttributeView = Files.getFileAttributeView(path, PosixFileAttributeView.class); if (fileAttributeView != null) { Files.setPosixFilePermissions(path, permissions); } }
@Override public void chown(String path, String username, String groupname) throws IOException { java.nio.file.Path p = FileSystems.getDefault().getPath(path); PosixFileAttributeView view = Files.getFileAttributeView(p, PosixFileAttributeView.class); UserPrincipalLookupService service = p.getFileSystem().getUserPrincipalLookupService(); if(!StringUtils.isBlank(username)) { view.setOwner(service.lookupPrincipalByName(username)); } if(!StringUtils.isBlank(groupname)) { view.setGroup(service.lookupPrincipalByGroupName(groupname)); } }
@Override public void setUnixGroup(final Path file, final String group) throws BackgroundException { try { final GroupPrincipal principal = session.getClient().getUserPrincipalLookupService().lookupPrincipalByGroupName(group); Files.getFileAttributeView(session.toPath(file), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS).setGroup(principal); } catch(IOException e) { throw new LocalExceptionMappingService().map("Failure to write attributes of {0}", e, file); } }
private static void chmod(final Path file, final String perms) throws IOException { final PosixFileAttributeView view = Files.getFileAttributeView(file, PosixFileAttributeView.class); if (view == null) { // OS (Windows) doesn't support POSIX file attributes return; } view.setPermissions(PosixFilePermissions.fromString("rwxr-xr-x")); }
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); }
@Test public void testDumpDirNotWritable() throws IOException { if (! Files.getFileStore(Paths.get(".")) .supportsFileAttributeView(PosixFileAttributeView.class)) { // No easy way to setup readonly directory without POSIX // We would like to skip the test with a cause with // throw new SkipException("Posix not supported"); // but jtreg will report failure so we just pass the test // which we can look at if jtreg changed its behavior return; } Files.createDirectory(Paths.get("readOnly"), asFileAttribute(fromString("r-xr-xr-x"))); TestResult tr = doExec(JAVA_CMD.getAbsolutePath(), "-cp", ".", "-Djdk.internal.lambda.dumpProxyClasses=readOnly", "-Djava.security.manager", "com.example.TestLambda"); assertEquals(tr.testOutput.stream() .filter(s -> s.startsWith("WARNING")) .peek(s -> assertTrue(s.contains("not writable"))) .count(), 1, "only show error once"); tr.assertZero("Should still return 0"); TestUtil.removeAll(Paths.get("readOnly")); }
@Test public void testDumpDirNotWritable() throws IOException { if (!Files.getFileStore(Paths.get(".")) .supportsFileAttributeView(PosixFileAttributeView.class)) { // No easy way to setup readonly directory without POSIX // We would like to skip the test with a cause with // throw new SkipException("Posix not supported"); // but jtreg will report failure so we just pass the test // which we can look at if jtreg changed its behavior System.out.println("WARNING: POSIX is not supported. Skipping testDumpDirNotWritable test."); return; } Files.createDirectory(Paths.get("readOnly"), asFileAttribute(fromString("r-xr-xr-x"))); try { if (isWriteableDirectory(Paths.get("readOnly"))) { // Skipping the test: it's allowed to write into read-only directory // (e.g. current user is super user). System.out.println("WARNING: readOnly directory is writeable. Skipping testDumpDirNotWritable test."); return; } TestResult tr = doExec(JAVA_CMD.getAbsolutePath(), "-cp", ".", "-Djdk.internal.lambda.dumpProxyClasses=readOnly", "com.example.TestLambda"); assertEquals(tr.testOutput.stream() .filter(s -> s.startsWith("WARNING")) .peek(s -> assertTrue(s.contains("not writable"))) .count(), 1, "only show error once"); tr.assertZero("Should still return 0"); } finally { TestUtil.removeAll(Paths.get("readOnly")); } }
@Test public void testDumpDirNotWritable() throws IOException { if (!Files.getFileStore(Paths.get(".")) .supportsFileAttributeView(PosixFileAttributeView.class)) { // No easy way to setup readonly directory without POSIX // We would like to skip the test with a cause with // throw new SkipException("Posix not supported"); // but jtreg will report failure so we just pass the test // which we can look at if jtreg changed its behavior System.out.println("WARNING: POSIX is not supported. Skipping testDumpDirNotWritable test."); return; } Files.createDirectory(Paths.get("readOnly"), asFileAttribute(fromString("r-xr-xr-x"))); try { if (isWriteableDirectory(Paths.get("readOnly"))) { // Skipping the test: it's allowed to write into read-only directory // (e.g. current user is super user). System.out.println("WARNING: readOnly directory is writeable. Skipping testDumpDirNotWritable test."); return; } TestResult tr = doExec(JAVA_CMD.getAbsolutePath(), "-cp", ".", "-Djdk.internal.lambda.dumpProxyClasses=readOnly", "-Djava.security.manager", "com.example.TestLambda"); assertEquals(tr.testOutput.stream() .filter(s -> s.startsWith("WARNING")) .peek(s -> assertTrue(s.contains("not writable"))) .count(), 1, "only show error once"); tr.assertZero("Should still return 0"); } finally { TestUtil.removeAll(Paths.get("readOnly")); } }
public static void unTarGz(Path file, Path target) throws IOException { try (final InputStream is = newInputStream(file)) { final InputStream gzip = new GZIPInputStream(is); final TarArchiveInputStream archive = new TarArchiveInputStream(gzip); TarArchiveEntry entry = archive.getNextTarEntry(); while (entry != null) { final Path entryFile = target.resolve(REMOVE_LEADING_GO_PATH_PATTERN.matcher(entry.getName()).replaceFirst("")).toAbsolutePath(); if (entry.isDirectory()) { createDirectoriesIfRequired(entryFile); } else { ensureParentOf(entryFile); try (final OutputStream os = newOutputStream(entryFile)) { copy(archive, os); } final PosixFileAttributeView view = getFileAttributeView(entryFile, PosixFileAttributeView.class); if (view != null) { final int mode = entry.getMode(); final Set<PosixFilePermission> perms = new HashSet<>(); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.OTHERS_READ); //noinspection OctalInteger,ResultOfMethodCallIgnored,IncompatibleBitwiseMaskOperation if ((mode | 0001) > 0) { perms.add(PosixFilePermission.OWNER_EXECUTE); } //noinspection OctalInteger,ResultOfMethodCallIgnored,IncompatibleBitwiseMaskOperation if ((mode | 0100) > 0) { perms.add(PosixFilePermission.GROUP_EXECUTE); perms.add(PosixFilePermission.OTHERS_EXECUTE); } view.setPermissions(perms); } } entry = archive.getNextTarEntry(); } } }
private static boolean isPosixFileSystem() { if (supportsPosix == null) { supportsPosix = Boolean.FALSE; FileSystem fileSystem = FileSystems.getDefault(); Iterable<FileStore> fileStores = fileSystem.getFileStores(); for (FileStore fs : fileStores) { supportsPosix = fs.supportsFileAttributeView(PosixFileAttributeView.class); if (supportsPosix) { break; } } } return supportsPosix; }
static final void updatePermissions(Path fileOrDir) throws IOException { PosixFileAttributeView posixView = Files.getFileAttributeView(fileOrDir, PosixFileAttributeView.class); if (posixView == null) { LOGGER.log(Level.INFO, "Cannot set file permissions."); return; } if (Files.isDirectory(fileOrDir)) { posixView.setPermissions(DIR_PERMISSIONS); } else { posixView.setPermissions(FILE_PERMISSIONS); } }
@Override public void extract(Path archive, Path destination, MessageListener messageListener) throws IOException { GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(Files.newInputStream(archive)); try (TarArchiveInputStream in = new TarArchiveInputStream(gzipIn)) { TarArchiveEntry entry; while ((entry = in.getNextTarEntry()) != null) { final Path entryTarget = destination.resolve(entry.getName()); if (messageListener != null) { messageListener.message(entryTarget + "\n"); } if (entry.isDirectory()) { if (!Files.exists(entryTarget)) { Files.createDirectories(entryTarget); } } else if (entry.isFile()) { if (!Files.exists(entryTarget.getParent())) { Files.createDirectories(entryTarget.getParent()); } try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(entryTarget))) { IOUtils.copy(in, out); PosixFileAttributeView attributeView = Files.getFileAttributeView(entryTarget, PosixFileAttributeView.class); if (attributeView != null) { attributeView.setPermissions(PosixUtil.getPosixFilePermissions(entry.getMode())); } } } else { // we don't know what kind of entry this is (we only process directories and files). if (messageListener != null) { messageListener.message("Skipping entry (unknown type): " + entry.getName() + "\n"); } } } } }
@Override public void extract(Path archive, Path destination, MessageListener messageListener) throws IOException { // Use ZipFile instead of ZipArchiveInputStream so that we can obtain file permissions // on unix-like systems via getUnixMode(). ZipArchiveInputStream doesn't have access to // all the zip file data and will return "0" for any call to getUnixMode(). try (ZipFile zipFile = new ZipFile(archive.toFile())) { Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries(); while (zipEntries.hasMoreElements()) { ZipArchiveEntry entry = zipEntries.nextElement(); final Path entryTarget = destination.resolve(entry.getName()); if (messageListener != null) { messageListener.message(entryTarget + "\n"); } if (entry.isDirectory()) { if (!Files.exists(entryTarget)) { Files.createDirectories(entryTarget); } } else { if (!Files.exists(entryTarget.getParent())) { Files.createDirectories(entryTarget.getParent()); } try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(entryTarget))) { try (InputStream in = zipFile.getInputStream(entry)) { IOUtils.copy(in, out); PosixFileAttributeView attributeView = Files.getFileAttributeView(entryTarget, PosixFileAttributeView.class); if (attributeView != null) { attributeView.setPermissions( PosixUtil.getPosixFilePermissions(entry.getUnixMode())); } } } } } } }
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 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; }
public void setPermissions(String fileName, String posixPermissions, String dosPermissions) throws IOException { Path file = rootDir.resolve(fileName); if (SystemUtils.IS_OS_WINDOWS) { DosFilePermissions.setPermissions(context, file, dosPermissions); } else { Set<PosixFilePermission> permissionSet = PosixFilePermissions.fromString(posixPermissions); Files.getFileAttributeView(file, PosixFileAttributeView.class).setPermissions(permissionSet); } }
@Test public void getPosixFileAttributeViewFromFile_shouldBeNotNull() throws IOException { initRepository(); writeToCache("/file.txt"); commitToMaster(); initGitFileSystem(); assertNotNull(Files.getFileAttributeView(gfs.getPath("/file.txt"), PosixFileAttributeView.class)); }
/** {@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; }
/** {@inheritDoc} */ @Override public String permissions(String path) throws IOException { Path p = path(path); PosixFileAttributeView attrView = Files.getFileAttributeView(p, PosixFileAttributeView.class); if (attrView == null) throw new UnsupportedOperationException("Posix file attributes not available"); int perm = 0; for(PosixFilePermission pfp : attrView.readAttributes().permissions()) perm |= (1 << 8 - pfp.ordinal()); return '0' + Integer.toOctalString(perm); }
public boolean isInRAF(Path path) { if(!path.getFileSystem().equals(m_FileSystem)) { return false; } try { PosixFileAttributeView a = Files.getFileAttributeView(path, PosixFileAttributeView.class); return a.getOwner() == m_RAFOwnerPrincipal; } catch(IOException e) { return false; } }