List of usage examples for java.nio.file Files setPosixFilePermissions
public static Path setPosixFilePermissions(Path path, Set<PosixFilePermission> perms) throws IOException
From source file:RestoreService.java
public static void setAdvancedAttributes(final VOBackupFile voBackupFile, final File file) throws IOException { // advanced attributes // owner//from w w w .j a v a 2 s . c om if (StringUtils.isNotBlank(voBackupFile.getOwner())) { try { UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService(); UserPrincipal userPrincipal = lookupService.lookupPrincipalByName(voBackupFile.getOwner()); Files.setOwner(file.toPath(), userPrincipal); } catch (UserPrincipalNotFoundException e) { logger.warn("Cannot set owner {}", voBackupFile.getOwner()); } } if (Files.getFileStore(file.toPath()).supportsFileAttributeView(DosFileAttributeView.class) && BooleanUtils.isTrue(voBackupFile.getDosAttr())) { Files.setAttribute(file.toPath(), "dos:hidden", BooleanUtils.isTrue(voBackupFile.getDosHidden())); Files.setAttribute(file.toPath(), "dos:archive", BooleanUtils.isTrue(voBackupFile.getDosArchive())); Files.setAttribute(file.toPath(), "dos:readonly", BooleanUtils.isTrue(voBackupFile.getDosReadOnly())); Files.setAttribute(file.toPath(), "dos:system", BooleanUtils.isTrue(voBackupFile.getDosSystem())); } if (Files.getFileStore(file.toPath()).supportsFileAttributeView(PosixFileAttributeView.class) && BooleanUtils.isTrue(voBackupFile.getPosixAttr())) { try { UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService(); GroupPrincipal groupPrincipal = lookupService .lookupPrincipalByGroupName(voBackupFile.getPosixGroup()); Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS) .setGroup(groupPrincipal); } catch (UserPrincipalNotFoundException e) { logger.warn("Cannot set group {}", voBackupFile.getOwner()); } if (StringUtils.isNotBlank(voBackupFile.getPosixPermitions())) { Set<PosixFilePermission> perms = PosixFilePermissions.fromString(voBackupFile.getPosixPermitions()); Files.setPosixFilePermissions(file.toPath(), perms); } } }
From source file:org.kitodo.command.CommandTest.java
private static void setFileExecuteable(File file) throws IOException { Set<PosixFilePermission> perms = new HashSet<>(); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); perms.add(PosixFilePermission.OTHERS_READ); perms.add(PosixFilePermission.OTHERS_WRITE); perms.add(PosixFilePermission.OTHERS_EXECUTE); perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); Files.setPosixFilePermissions(file.toPath(), perms); }
From source file:com.dangdang.ddframe.job.example.JavaLiteJobMain.java
private static String buildScriptCommandLine() throws IOException { if (System.getProperties().getProperty("os.name").contains("Windows")) { return Paths.get(JavaLiteJobMain.class.getResource("/script/demo.bat").getPath().substring(1)) .toString();// w w w. j ava 2 s . c o m } Path result = Paths.get(JavaLiteJobMain.class.getResource("/script/demo.sh").getPath()); Files.setPosixFilePermissions(result, PosixFilePermissions.fromString("rwxr-xr-x")); return result.toString(); }
From source file:net.krotscheck.util.ResourceUtilTest.java
/** * Assert that we can read a resource as a stream. * * @throws Exception Should not be thrown. *//* w w w. j av a 2 s.co m*/ @Test public void testGetResourceAsStream() throws Exception { String name = "/valid-resource-file.txt"; InputStream stream = ResourceUtil.getResourceAsStream(name); Assert.assertTrue(stream.available() > 0); String invalidName = "/invalid-resource-file.txt"; InputStream invalidContent = ResourceUtil.getResourceAsStream(invalidName); Assert.assertTrue(invalidContent instanceof NullInputStream); Assert.assertTrue(invalidContent.available() == 0); // Make the file write only File resource = ResourceUtil.getFileForResource(name); Set<PosixFilePermission> oldPerms = Files.getPosixFilePermissions(resource.toPath()); Set<PosixFilePermission> perms = new HashSet<>(); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); perms.add(PosixFilePermission.OTHERS_WRITE); perms.add(PosixFilePermission.OTHERS_EXECUTE); // Write only... Files.setPosixFilePermissions(resource.toPath(), perms); String writeOnlyName = "/valid-resource-file.txt"; InputStream writeOnlyContent = ResourceUtil.getResourceAsStream(writeOnlyName); Assert.assertTrue(writeOnlyContent instanceof NullInputStream); Assert.assertTrue(writeOnlyContent.available() == 0); Files.setPosixFilePermissions(resource.toPath(), oldPerms); }
From source file:org.assertj.examples.PathAssertionsExamples.java
@Test public void path_rwx_assertion() throws Exception { assumeTrue(SystemUtils.IS_OS_UNIX);/*ww w . jav a 2s.co m*/ // Create a file and set permissions to be readable by all. write(rwxFile, "rwx file".getBytes()); // using PosixFilePermission to set file permissions 777 Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); // add owners permission perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); // add group permissions perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); // add others permissions perms.add(PosixFilePermission.OTHERS_READ); perms.add(PosixFilePermission.OTHERS_WRITE); perms.add(PosixFilePermission.OTHERS_EXECUTE); Files.setPosixFilePermissions(rwxFile, perms); final Path symlinkToRwxFile = FileSystems.getDefault().getPath("symlink-to-rwxFile"); if (!Files.exists(symlinkToRwxFile)) { createSymbolicLink(symlinkToRwxFile, rwxFile); } // The following assertions succeed: assertThat(rwxFile).isReadable().isWritable().isExecutable(); assertThat(symlinkToRwxFile).isReadable().isWritable().isExecutable(); }
From source file:org.gradle.caching.internal.tasks.ChmodBenchmark.java
@Benchmark public void createFileJava7SetMixedPermission(Blackhole blackhole) throws IOException { int incrementAndGet = counter.incrementAndGet(); Path file = Files.createFile(tempDirPath.resolve("file-" + incrementAndGet)); Set<PosixFilePermission> permissionsToSet; if (incrementAndGet % 2 == 0) { permissionsToSet = DEFAULT_JAVA7_FILE_PERMISSIONS; } else {//from ww w. j av a2 s. c om permissionsToSet = WEIRD_JAVA7_FILE_PERMISSIONS; } Files.setPosixFilePermissions(file, permissionsToSet); blackhole.consume(file); }
From source file:com.streamsets.datacollector.restapi.TestRestApiAuthorization.java
private String startServer(boolean authzEnabled) throws Exception { int port = getRandomPort(); Configuration conf = new Configuration(); conf.set(WebServerTask.HTTP_PORT_KEY, port); conf.set(WebServerTask.AUTHENTICATION_KEY, (authzEnabled) ? "basic" : "none"); Writer writer = new FileWriter(new File( System.getProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.CONFIG_DIR), "sdc.properties")); conf.save(writer);// w ww .ja va 2 s. c o m writer.close(); File realmFile = new File(System.getProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.CONFIG_DIR), "basic-realm.properties"); writer = new FileWriter(realmFile); IOUtils.copy( new InputStreamReader(getClass().getClassLoader().getResourceAsStream("basic-realm.properties")), writer); writer.close(); Files.setPosixFilePermissions(realmFile.toPath(), WebServerTask.OWNER_PERMISSIONS); ObjectGraph dagger = ObjectGraph.create(MainStandalonePipelineManagerModule.class); RuntimeInfo runtimeInfo = dagger.get(RuntimeInfo.class); runtimeInfo.setAttribute(RuntimeInfo.LOG4J_CONFIGURATION_URL_ATTR, new URL("file://" + baseDir + "/log4j.properties")); server = dagger.get(TaskWrapper.class); server.init(); server.run(); return "http://127.0.0.1:" + port; }
From source file:com.facebook.buck.artifact_cache.ArtifactUploaderTest.java
/** compressSavesExecutableBit asserts that compress()-ing an executable file stores the x bit. */ @Test/* w w w .j a v a 2 s . c om*/ public void compressSavesExecutableBit() throws Exception { ProjectFilesystem fs = FakeProjectFilesystem.createJavaOnlyFilesystem("/"); Path out = fs.getRootPath().resolve("out"); Path file = fs.getRootPath().resolve("file"); fs.writeContentsToPath("foo", file); Files.setPosixFilePermissions(fs.getPathForRelativePath(file), ImmutableSet.of(PosixFilePermission.OWNER_EXECUTE)); // Compress ArtifactUploader.compress(fs, ImmutableList.of(file), out); // Decompress+unarchive, and check that the only file is an executable. try (TarArchiveInputStream fin = new TarArchiveInputStream( new ZstdCompressorInputStream(Files.newInputStream(out)))) { ArrayList<TarArchiveEntry> entries = new ArrayList<>(); TarArchiveEntry entry; while ((entry = fin.getNextTarEntry()) != null) { entries.add(entry); } assertThat(entries, Matchers.hasSize(1)); assertThat(MorePosixFilePermissions.fromMode(entries.get(0).getMode()), Matchers.contains(PosixFilePermission.OWNER_EXECUTE)); } }
From source file:com.streamsets.datacollector.el.TestRuntimeEL.java
@Test public void testLoadResource() throws Exception { Path fooFile = Paths.get(resourcesDir.getPath(), "foo.txt"); try {//ww w. j av a2s . c o m Files.write(fooFile, "Hello".getBytes(StandardCharsets.UTF_8)); RuntimeEL.loadRuntimeConfiguration(runtimeInfo); Assert.assertNull(RuntimeEL.loadResource("bar.txt", false)); Assert.assertNull(RuntimeEL.loadResource("bar.txt", true)); Assert.assertEquals("Hello", RuntimeEL.loadResource("foo.txt", false)); try { RuntimeEL.loadResource("foo.txt", true); Assert.fail(); } catch (IllegalArgumentException ex) { //nop } catch (Exception ex) { Assert.fail(); } Files.setPosixFilePermissions(fooFile, ImmutableSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)); Assert.assertEquals("Hello", RuntimeEL.loadResource("foo.txt", true)); try { Files.setPosixFilePermissions(fooFile, ImmutableSet.of(PosixFilePermission.OTHERS_READ)); Assert.assertEquals("Hello", RuntimeEL.loadResource("foo.txt", true)); Assert.fail(); } catch (IllegalArgumentException ex) { //NOP } try { Files.setPosixFilePermissions(fooFile, ImmutableSet.of(PosixFilePermission.OTHERS_WRITE)); Assert.assertEquals("Hello", RuntimeEL.loadResource("foo.txt", true)); Assert.fail(); } catch (IllegalArgumentException ex) { //NOP } } finally { Files.setPosixFilePermissions(fooFile, ImmutableSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)); } }
From source file:org.ng200.openolympus.cerberus.executors.JavaExecutor.java
@Override public ExecutionResult execute(final Path program) throws IOException { final Path chrootRoot = this.storage.getPath().resolve("chroot"); final Path chrootedProgram = chrootRoot.resolve(program.getFileName().toString()); FileAccess.createDirectories(chrootedProgram); FileAccess.copyDirectory(program, chrootedProgram, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); final Path outOfMemoryFile = chrootRoot.resolve("outOfMemory"); final Path policyFile = this.storage.getPath().resolve("olymp.policy"); try (Stream<Path> paths = FileAccess.walkPaths(storage.getPath())) { paths.forEach(path -> {// ww w .jav a 2 s .c o m try { Files.setPosixFilePermissions(path, new HashSet<PosixFilePermission>( Lists.from(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.GROUP_EXECUTE, PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_WRITE, PosixFilePermission.OTHERS_EXECUTE, PosixFilePermission.OTHERS_READ))); } catch (Exception e) { throw new RuntimeException(e); } }); } this.buildPolicy(chrootRoot, policyFile); final CommandLine commandLine = new CommandLine("sudo"); commandLine.addArgument("olympus_watchdog"); this.setUpOlrunnerLimits(commandLine); commandLine.addArgument("--security=0"); commandLine.addArgument("--jail=/"); commandLine.addArgument("--"); commandLine.addArgument("/usr/bin/java"); commandLine.addArgument("-classpath"); commandLine.addArgument(chrootedProgram.toAbsolutePath().toString()); commandLine.addArgument("-Djava.security.manager"); commandLine.addArgument("-Djava.security.policy=" + policyFile.toAbsolutePath().toString()); commandLine.addArgument("-Xmx" + this.getMemoryLimit()); commandLine.addArgument("-Xms" + this.getMemoryLimit()); commandLine.addArgument(MessageFormat.format("-XX:OnOutOfMemoryError=touch {0}; echo \"\" > {0}", outOfMemoryFile.toAbsolutePath().toString()), false); commandLine.addArgument("Main"); final DefaultExecutor executor = new DefaultExecutor(); executor.setWatchdog(new ExecuteWatchdog(20000)); // 20 seconds for the // sandbox to // complete executor.setWorkingDirectory(chrootRoot.toFile()); executor.setStreamHandler(new PumpStreamHandler(this.outputStream, this.errorStream, this.inputStream)); try { executor.execute(commandLine); } catch (final IOException e) { if (!e.getMessage().toLowerCase().equals("stream closed")) { throw e; } } final ExecutionResult readOlrunnerVerdict = this.readOlrunnerVerdict(chrootRoot.resolve("verdict.txt")); if (FileAccess.exists(outOfMemoryFile)) { readOlrunnerVerdict.setResultType(ExecutionResultType.MEMORY_LIMIT); } readOlrunnerVerdict.setMemoryPeak(this.getMemoryLimit()); return readOlrunnerVerdict; }