List of usage examples for java.nio.file Files setPosixFilePermissions
public static Path setPosixFilePermissions(Path path, Set<PosixFilePermission> perms) throws IOException
From source file:Main.java
public static void main(String[] args) throws Exception { Path path = Paths.get("c:/home/tutorial/Java/JavaFX/Topic.txt"); Path new_path = Paths.get("/home/tutorial/Java/JavaFX/new_Topic.txt"); //use of fromString Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("rw-r--r--"); try {//from w w w. j a v a 2s .com Files.setPosixFilePermissions(new_path, permissions); } catch (IOException e) { System.err.println(e); } }
From source file:Test.java
public static void main(String[] args) throws Exception { Path profile = Paths.get("/user/Admin/.profile"); PosixFileAttributes attrs = Files.readAttributes(profile, PosixFileAttributes.class); Set<PosixFilePermission> posixPermissions = attrs.permissions(); posixPermissions.clear();/*from w w w. j ava2 s .co m*/ String owner = attrs.owner().getName(); String perms = PosixFilePermissions.toString(posixPermissions); System.out.format("%s %s%n", owner, perms); posixPermissions.add(OWNER_READ); posixPermissions.add(GROUP_READ); posixPermissions.add(OWNER_READ); posixPermissions.add(OWNER_WRITE); Files.setPosixFilePermissions(profile, posixPermissions); }
From source file:com.ignorelist.kassandra.steam.scraper.TaggerCli.java
/** * @param args the command line arguments * @throws java.io.IOException// w w w.j ava2 s. com * @throws org.antlr.runtime.RecognitionException * @throws org.apache.commons.cli.ParseException */ public static void main(String[] args) throws IOException, RecognitionException, ParseException { Options options = buildOptions(); CommandLineParser parser = new DefaultParser(); CommandLine commandLine; try { commandLine = parser.parse(options, args); } catch (ParseException pe) { System.out.println(pe.getMessage()); System.out.println(); printHelp(options); System.exit(0); return; } if (commandLine.hasOption("h")) { printHelp(options); System.exit(0); } final PathResolver pathResolver = new PathResolver(); Configuration configuration; Path configurationFile = pathResolver.findConfiguration(); if (Files.isRegularFile(configurationFile)) { configuration = Configuration.fromPropertiesFile(configurationFile); } else { configuration = new Configuration(); } configuration = toConfiguration(configuration, commandLine); //configuration.toProperties().store(System.err, null); if (!Files.isRegularFile(configurationFile)) { configuration.writeProperties(configurationFile); System.err.println( "no configuration file present, write based on CLI options: " + configurationFile.toString()); configuration.toProperties().store(System.err, null); } Set<Path> sharedConfigPaths = configuration.getSharedConfigPaths(); if (sharedConfigPaths.size() > 1 && !commandLine.hasOption("w")) { System.err.println("multiple sharedconfig.vdf available:\n" + Joiner.on("\n").join(sharedConfigPaths) + "\n, can not write to stdout. Need to specify -w or -f with a single sharedconfig.vdf"); System.exit(1); } Tagger.Options taggerOptions = Tagger.Options.fromConfiguration(configuration); final String[] removeTagsValues = commandLine.getOptionValues("remove"); if (null != removeTagsValues) { taggerOptions.setRemoveTags(Sets.newHashSet(removeTagsValues)); } Set<TagType> tagTypes = configuration.getTagTypes(); if (null == tagTypes) { System.err.println("no tag types!"); System.exit(1); } final boolean printTags = commandLine.hasOption("p"); final HtmlTagLoader htmlTagLoader = new HtmlTagLoader(pathResolver.findCachePath("html"), null == configuration.getCacheExpiryDays() ? 7 : configuration.getCacheExpiryDays()); final BatchTagLoader tagLoader = new BatchTagLoader(htmlTagLoader, configuration.getDownloadThreads()); if (true || commandLine.hasOption("v")) { tagLoader.registerEventListener(new CliEventLoggerLoaded()); } Tagger tagger = new Tagger(tagLoader); if (printTags) { Set<String> availableTags = tagger.getAvailableTags(sharedConfigPaths, taggerOptions); Joiner.on("\n").appendTo(System.out, availableTags); } else { for (Path path : sharedConfigPaths) { VdfNode tagged = tagger.tag(path, taggerOptions); if (commandLine.hasOption("w")) { Path backup = path.getParent() .resolve(path.getFileName().toString() + ".bak" + new Date().getTime()); Files.copy(path, backup, StandardCopyOption.REPLACE_EXISTING); System.err.println("backup up " + path + " to " + backup); Files.copy(new ByteArrayInputStream(tagged.toPrettyString().getBytes(StandardCharsets.UTF_8)), path, StandardCopyOption.REPLACE_EXISTING); try { Files.setPosixFilePermissions(path, SHARED_CONFIG_POSIX_PERMS); } catch (Exception e) { System.err.println(e); } System.err.println("wrote " + path); } else { System.out.println(tagged.toPrettyString()); System.err.println("pipe to file and copy to: " + path.toString()); } } } }
From source file:com.android.tradefed.util.ZipUtil2.java
/** * A util method to apply unix mode from {@link ZipArchiveEntry} to the created local file * system entry if necessary/*from w w w. j a v a2 s . c o m*/ * @param entry the entry inside zipfile (potentially contains mode info) * @param localFile the extracted local file entry * @throws IOException */ private static void applyUnixModeIfNecessary(ZipArchiveEntry entry, File localFile) throws IOException { if (entry.getPlatform() == ZipArchiveEntry.PLATFORM_UNIX) { Files.setPosixFilePermissions(localFile.toPath(), FileUtil.unixModeToPosix(entry.getUnixMode())); } else { CLog.i("Entry does not contain Unix mode info: %s", entry.getName()); } }
From source file:com.vmware.bdd.utils.CommonUtil.java
public static void setOwnerOnlyReadWrite(String filename) throws IOException { try {/*from ww w.j a v a2 s . c o m*/ Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); Files.setPosixFilePermissions(Paths.get(filename), perms); } catch (UnsupportedOperationException uoe) { logger.error("we are probably on windows! failed to set PosixFilePermission to: " + filename, uoe); } }
From source file:org.savantbuild.io.tar.TarTools.java
/** * Untars a TAR file. This also handles tar.gz files by checking the file extension. If the file extension ends in .gz * it will read the tarball through a GZIPInputStream. * * @param file The TAR file.//ww w. j a v a 2 s . c o m * @param to The directory to untar to. * @param useGroup Determines if the group name in the archive is used. * @param useOwner Determines if the owner name in the archive is used. * @throws IOException If the untar fails. */ public static void untar(Path file, Path to, boolean useGroup, boolean useOwner) throws IOException { if (Files.notExists(to)) { Files.createDirectories(to); } InputStream is = Files.newInputStream(file); if (file.toString().endsWith(".gz")) { is = new GZIPInputStream(is); } try (TarArchiveInputStream tis = new TarArchiveInputStream(is)) { TarArchiveEntry entry; while ((entry = tis.getNextTarEntry()) != null) { Path entryPath = to.resolve(entry.getName()); if (entry.isDirectory()) { // Skip directory entries that don't add any value if (entry.getMode() == 0 && entry.getGroupName() == null && entry.getUserName() == null) { continue; } if (Files.notExists(entryPath)) { Files.createDirectories(entryPath); } if (entry.getMode() != 0) { Set<PosixFilePermission> permissions = FileTools.toPosixPermissions(entry.getMode()); Files.setPosixFilePermissions(entryPath, permissions); } if (useGroup && entry.getGroupName() != null && !entry.getGroupName().trim().isEmpty()) { GroupPrincipal group = FileSystems.getDefault().getUserPrincipalLookupService() .lookupPrincipalByGroupName(entry.getGroupName()); Files.getFileAttributeView(entryPath, PosixFileAttributeView.class).setGroup(group); } if (useOwner && entry.getUserName() != null && !entry.getUserName().trim().isEmpty()) { UserPrincipal user = FileSystems.getDefault().getUserPrincipalLookupService() .lookupPrincipalByName(entry.getUserName()); Files.getFileAttributeView(entryPath, PosixFileAttributeView.class).setOwner(user); } } else { if (Files.notExists(entryPath.getParent())) { Files.createDirectories(entryPath.getParent()); } if (Files.isRegularFile(entryPath)) { if (Files.size(entryPath) == entry.getSize()) { continue; } else { Files.delete(entryPath); } } Files.createFile(entryPath); try (OutputStream os = Files.newOutputStream(entryPath)) { byte[] ba = new byte[1024]; int read; while ((read = tis.read(ba)) != -1) { if (read > 0) { os.write(ba, 0, read); } } } if (entry.getMode() != 0) { Set<PosixFilePermission> permissions = FileTools.toPosixPermissions(entry.getMode()); Files.setPosixFilePermissions(entryPath, permissions); } if (useGroup && entry.getGroupName() != null && !entry.getGroupName().trim().isEmpty()) { GroupPrincipal group = FileSystems.getDefault().getUserPrincipalLookupService() .lookupPrincipalByGroupName(entry.getGroupName()); Files.getFileAttributeView(entryPath, PosixFileAttributeView.class).setGroup(group); } if (useOwner && entry.getUserName() != null && !entry.getUserName().trim().isEmpty()) { UserPrincipal user = FileSystems.getDefault().getUserPrincipalLookupService() .lookupPrincipalByName(entry.getUserName()); Files.getFileAttributeView(entryPath, PosixFileAttributeView.class).setOwner(user); } } } } }
From source file:com.geewhiz.pacify.utils.FileUtils.java
public static void setPosixPermissions(Set<PosixFilePermission> permissions, File forFile) { if (!IS_POSIX) { return;// w w w .ja v a2 s . c om } try { Files.setPosixFilePermissions(Paths.get(forFile.toURI()), permissions); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.esa.s2tbx.dataio.openjpeg.OpenJPEGActivator.java
private static void setExecutablePermissions(Path executablePathName) { if (IS_OS_UNIX) { Set<PosixFilePermission> permissions = new HashSet<>(Arrays.asList(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_EXECUTE, PosixFilePermission.OTHERS_READ, PosixFilePermission.OTHERS_EXECUTE)); try {/*w w w . jav a2s . c om*/ Files.setPosixFilePermissions(executablePathName, permissions); } catch (IOException e) { // can't set the permissions for this file, eg. the file was installed as root // send a warning message, user will have to do that by hand. SystemUtils.LOG .severe("Can't set execution permissions for executable " + executablePathName.toString() + ". If required, please ask an authorised user to make the file executable."); } } }
From source file:org.jenkinsci.sshd.SshdTest.java
/** * Get plaintext Private Key File/*from w w w. ja va 2 s . co m*/ */ private File getPrivateKey() { if (privateKey == null) { try { privateKey = File.createTempFile("ssh", "key"); privateKey.deleteOnExit(); FileUtils.copyURLToFile(SshdTest.class.getResource("/sshd/unsafe"), privateKey); Files.setPosixFilePermissions(privateKey.toPath(), EnumSet.of(OWNER_READ)); } catch (IOException e) { throw new RuntimeException( "Not able to get the plaintext SSH key file. Missing file, wrong file permissions?!"); } } return privateKey; }
From source file:it.sonarlint.cli.tools.CommandExecutor.java
public int execute(String[] args, @Nullable Path workingDir, Map<String, String> addEnv) throws IOException { if (!Files.isExecutable(file)) { Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_EXECUTE); Files.setPosixFilePermissions(file, perms); }//from w ww. j a v a2 s . c o m ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT); CommandLine cmd = new CommandLine(file.toFile()); cmd.addArguments(args); DefaultExecutor exec = new DefaultExecutor(); exec.setWatchdog(watchdog); exec.setStreamHandler(createStreamHandler()); exec.setExitValues(null); if (workingDir != null) { exec.setWorkingDirectory(workingDir.toFile()); } in.close(); LOG.info("Executing: {}", cmd.toString()); Map<String, String> env = new HashMap<>(System.getenv()); env.putAll(addEnv); return exec.execute(cmd, env); }