List of usage examples for java.nio.file.attribute PosixFilePermissions fromString
public static Set<PosixFilePermission> fromString(String perms)
From source file:com.facebook.buck.util.unarchive.UnzipTest.java
@Test public void testExtractZipFilePreservesExecutePermissionsAndModificationTime() throws InterruptedException, IOException { // getFakeTime returs time with some non-zero millis. By doing division and multiplication by // 1000 we get rid of that. long time = ZipConstants.getFakeTime() / 1000 * 1000; // Create a simple zip archive using apache's commons-compress to store executable info. try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) { ZipArchiveEntry entry = new ZipArchiveEntry("test.exe"); entry.setUnixMode((int) MorePosixFilePermissions.toMode(PosixFilePermissions.fromString("r-x------"))); entry.setSize(DUMMY_FILE_CONTENTS.length); entry.setMethod(ZipEntry.STORED); entry.setTime(time);/*w w w. ja v a 2s. co m*/ zip.putArchiveEntry(entry); zip.write(DUMMY_FILE_CONTENTS); zip.closeArchiveEntry(); } // Now run `Unzip.extractZipFile` on our test zip and verify that the file is executable. Path extractFolder = tmpFolder.newFolder(); ImmutableList<Path> result = ArchiveFormat.ZIP.getUnarchiver().extractArchive( new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), ExistingFileMode.OVERWRITE); Path exe = extractFolder.toAbsolutePath().resolve("test.exe"); assertTrue(Files.exists(exe)); assertThat(Files.getLastModifiedTime(exe).toMillis(), Matchers.equalTo(time)); assertTrue(Files.isExecutable(exe)); assertEquals(ImmutableList.of(extractFolder.resolve("test.exe")), result); }
From source file:org.fim.tooling.RepositoryTool.java
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 {//from w w w . j a va 2s. co m Set<PosixFilePermission> permissionSet = PosixFilePermissions.fromString(posixPermissions); Files.getFileAttributeView(file, PosixFileAttributeView.class).setPermissions(permissionSet); } }
From source file:RestoreService.java
public static void setAdvancedAttributes(final VOBackupFile voBackupFile, final File file) throws IOException { // advanced attributes // owner//w w w. j a v a 2 s.c o m 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:com.dangdang.ddframe.job.example.JavaMain.java
private static String buildScriptCommandLine() throws IOException { if (System.getProperties().getProperty("os.name").contains("Windows")) { return Paths.get(JavaMain.class.getResource("/script/demo.bat").getPath().substring(1)).toString(); }/*from w ww . j a v a 2 s. c o m*/ Path result = Paths.get(JavaMain.class.getResource("/script/demo.sh").getPath()); Files.setPosixFilePermissions(result, PosixFilePermissions.fromString("rwxr-xr-x")); return result.toString(); }
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 ww. j a va 2 s . co 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:de.unirostock.sems.cbarchive.web.VcImporter.java
private static File cloneHg(String link, ArchiveFromHg archive) throws IOException, TransformerException, JDOMException, ParseException, CombineArchiveException, CombineArchiveWebException { // create new temp dir File tempDir = Files//from w w w . j a v a 2 s . c o m .createTempDirectory(Fields.TEMP_FILE_PREFIX, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))) .toFile(); if (!tempDir.isDirectory() && !tempDir.mkdirs()) throw new CombineArchiveWebException( "The temporary directories could not be created: " + tempDir.getAbsolutePath()); // temp file for CombineArchive File archiveFile = File.createTempFile(Fields.TEMP_FILE_PREFIX, "ca-imported"); archiveFile.delete(); // delete the tmp file, so the CombineArchive Lib will create a new file // create the archive CombineArchive ca = new CombineArchive(archiveFile); Repository repo = Repository.clone(tempDir, link); if (repo == null) { ca.close(); LOGGER.error("Cannot clone Mercurial Repository ", link, " into ", tempDir); throw new CombineArchiveWebException("Cannot clone Mercurial Repository " + link + " into " + tempDir); } List<File> relevantFiles = scanRepository(tempDir, repo); System.out.println("before LogCommand"); LogCommand logCmd = new LogCommand(repo); System.out.println("after LogCommand"); for (File cur : relevantFiles) { List<Changeset> relevantVersions = logCmd.execute(cur.getAbsolutePath()); ArchiveEntry caFile = ca.addEntry(tempDir, cur, Formatizer.guessFormat(cur)); // lets create meta! List<Date> modified = new ArrayList<Date>(); List<VCard> creators = new ArrayList<VCard>(); HashMap<String, VCard> users = new HashMap<String, VCard>(); for (Changeset cs : relevantVersions) { LOGGER.debug("cs: " + cs.getTimestamp().getDate() + " -- " + cs.getUser()); modified.add(cs.getTimestamp().getDate()); String vcuser = cs.getUser(); String firstName = ""; String lastName = ""; String mail = ""; String[] tokens = vcuser.split(" "); int lastNameToken = tokens.length - 1; // is there a mail address? if (tokens[lastNameToken].contains("@")) { mail = tokens[lastNameToken]; if (mail.startsWith("<") && mail.endsWith(">")) mail = mail.substring(1, mail.length() - 1); lastNameToken--; } // search for a non-empty last name while (lastNameToken >= 0) { if (tokens[lastNameToken].length() > 0) { lastName = tokens[lastNameToken]; break; } lastNameToken--; } // and first name of course... for (int i = 0; i < lastNameToken; i++) { if (tokens[i].length() > 0) firstName += tokens[i] + " "; } firstName = firstName.trim(); String userid = "[" + firstName + "] -- [" + lastName + "] -- [" + mail + "]"; LOGGER.debug("this is user: " + userid); if (users.get(userid) == null) { users.put(userid, new VCard(lastName, firstName, mail, null)); } } for (VCard vc : users.values()) creators.add(vc); caFile.addDescription(new OmexMetaDataObject( new OmexDescription(creators, modified, modified.get(modified.size() - 1)))); } ca.pack(); ca.close(); repo.close(); // clean up the directory FileUtils.deleteDirectory(tempDir); // add the combine archive to the dataholder if (archive != null) { //TODO ugly workaround with the lock. archive.setArchiveFile(archiveFile, null); archive.getArchive().close(); } return archiveFile; }
From source file:org.syncany.tests.integration.scenarios.ChangedAttributesScenarioTest.java
@Test public void testNewFileWithDifferingAttributes() throws Exception { // Setup /*from w w w. j av a 2 s . c o m*/ TransferSettings testConnection = TestConfigUtil.createTestLocalConnection(); TestClient clientA = new TestClient("A", testConnection); TestClient clientB = new TestClient("B", testConnection); // Create new file with differing attributes clientA.createNewFile("file1.jpg"); FileUtils.copyFile(clientA.getLocalFile("file1.jpg"), clientB.getLocalFile("file1.jpg")); File aFile = clientA.getLocalFile("file1.jpg"); // Client B's attributes differ! Path aFilePath = Paths.get(aFile.getAbsolutePath()); Object aReadOnlyAttribute = null; Set<PosixFilePermission> aPosixFilePermissions = null; File bFile = clientB.getLocalFile("file1.jpg"); // Client B's attributes differ! Path bFilePath = Paths.get(bFile.getAbsolutePath()); if (EnvironmentUtil.isWindows()) { aReadOnlyAttribute = Files.getAttribute(aFilePath, "dos:readonly"); Files.setAttribute(bFilePath, "dos:readonly", true); } else if (EnvironmentUtil.isUnixLikeOperatingSystem()) { aPosixFilePermissions = Files.getPosixFilePermissions(aFilePath); Files.setPosixFilePermissions(bFilePath, PosixFilePermissions.fromString("rwxrwxrwx")); } clientA.upWithForceChecksum(); DownOperationResult downResult = clientB.down(); // This is the key operation // Test 1: Check result sets for inconsistencies assertTrue("File should be downloaded.", downResult.getChangeSet().hasChanges()); // Test 2: file1.jpg permissions (again! if (EnvironmentUtil.isWindows()) { Object bReadOnlyAttribute = Files.getAttribute(aFilePath, "dos:readonly"); assertEquals("Read-only should be true.", aReadOnlyAttribute, bReadOnlyAttribute); } else if (EnvironmentUtil.isUnixLikeOperatingSystem()) { Set<PosixFilePermission> bPosixFilePermissions = Files.getPosixFilePermissions(aFilePath); assertEquals("Should be rwxrwxrwx.", PosixFilePermissions.toString(aPosixFilePermissions), PosixFilePermissions.toString(bPosixFilePermissions)); } // Test 3: The rest assertFileListEquals(clientA.getLocalFilesExcludeLockedAndNoRead(), clientB.getLocalFilesExcludeLockedAndNoRead()); assertSqlDatabaseEquals(clientA.getDatabaseFile(), clientB.getDatabaseFile()); // Tear down clientA.deleteTestData(); clientB.deleteTestData(); }
From source file:org.fim.command.ResetFileAttributesCommand.java
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); System.out.printf("Set permissions: %s \t%s -> %s%n", fileState.getFileName(), permissions, previousPermissions);/*from w w w. j a v a2 s . c o m*/ return true; } return false; }
From source file:de.huberlin.wbi.cuneiform.core.cre.LocalThread.java
@Override public void run() { Path scriptFile, location, successMarker, reportFile, callLocation, stdErrFile, stdOutFile; // Path lockMarker; Process process;//from ww w .jav a2 s .com int exitValue; Set<JsonReportEntry> report; JsonReportEntry entry; String line; StringBuffer buf; Path srcPath, destPath; ProcessBuilder processBuilder; Ticket ticket; String script, stdOut, stdErr; long tic, toc; JSONObject obj; Message msg; Charset cs; int trial; boolean suc; Exception ex; if (log.isDebugEnabled()) log.debug("Starting up local thread for ticket " + invoc.getTicketId() + "."); if (invoc == null) throw new NullPointerException("Invocation must not be null."); ticket = invoc.getTicket(); process = null; stdOut = null; stdErr = null; // lockMarker = null; script = null; successMarker = null; cs = Charset.forName("UTF-8"); try { callLocation = Paths.get(System.getProperty("user.dir")); location = buildDir.resolve(String.valueOf(invoc.getTicketId())); // lockMarker = location.resolve( Invocation.LOCK_FILENAME ); successMarker = location.resolve(Invocation.SUCCESS_FILENAME); reportFile = location.resolve(Invocation.REPORT_FILENAME); script = invoc.toScript(); // if( Files.exists( lockMarker ) ) // throw new IOException( "Lock held on ticket "+invoc.getTicketId() ); if (!Files.exists(successMarker)) { deleteIfExists(location); Files.createDirectories(location); // Files.createFile( lockMarker ); scriptFile = invoc.getExecutablePath(location); Files.createFile(scriptFile, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxr-x---"))); // write executable script try (BufferedWriter writer = Files.newBufferedWriter(scriptFile, cs, StandardOpenOption.CREATE)) { writer.write(script); } // write executable log entry try (BufferedWriter writer = Files.newBufferedWriter(reportFile, cs, StandardOpenOption.CREATE)) { writer.write(ticket.getExecutableLogEntry().toString()); writer.write('\n'); } for (String filename : invoc.getStageInList()) { if (filename.charAt(0) == '/') throw new UnsupportedOperationException("Absolute path encountered '" + filename + "'."); srcPath = centralRepo.resolve(filename); destPath = location.resolve(filename); if (!Files.exists(srcPath)) { srcPath = callLocation.resolve(filename); if (log.isTraceEnabled()) log.trace("Resolving relative path '" + srcPath + "'."); } else if (log.isTraceEnabled()) log.trace("Resolving path to central repository '" + srcPath + "'."); if (log.isTraceEnabled()) log.trace("Trying to create symbolic link from '" + srcPath + "' to '" + destPath + "'."); if (!Files.exists(destPath.getParent())) Files.createDirectories(destPath.getParent()); Files.createSymbolicLink(destPath, srcPath); } // run script processBuilder = new ProcessBuilder(invoc.getCmd()); processBuilder.directory(location.toFile()); stdOutFile = location.resolve(Invocation.STDOUT_FILENAME); stdErrFile = location.resolve(Invocation.STDERR_FILENAME); processBuilder.redirectOutput(stdOutFile.toFile()); processBuilder.redirectError(stdErrFile.toFile()); trial = 1; suc = false; ex = null; tic = System.currentTimeMillis(); do { try { process = processBuilder.start(); suc = true; } catch (IOException e) { ex = e; if (log.isWarnEnabled()) log.warn("Unable to start process on trial " + (trial++) + " Waiting " + WAIT_INTERVAL + "ms: " + e.getMessage()); Thread.sleep(WAIT_INTERVAL); } } while (suc == false && trial <= MAX_TRIALS); if (process == null) { ticketSrc.sendMsg(new TicketFailedMsg(cre, ticket, ex, script, null, null)); // Files.delete( lockMarker ); return; } exitValue = process.waitFor(); toc = System.currentTimeMillis(); try (BufferedWriter writer = Files.newBufferedWriter(reportFile, cs, StandardOpenOption.APPEND)) { obj = new JSONObject(); obj.put(JsonReportEntry.LABEL_REALTIME, toc - tic); entry = invoc.createJsonReportEntry(tic, JsonReportEntry.KEY_INVOC_TIME, obj); writer.write(entry.toString()); writer.write('\n'); try (BufferedReader reader = Files.newBufferedReader(stdOutFile, cs)) { buf = new StringBuffer(); while ((line = reader.readLine()) != null) buf.append(line).append('\n'); stdOut = buf.toString(); if (!stdOut.isEmpty()) { entry = invoc.createJsonReportEntry(JsonReportEntry.KEY_INVOC_STDOUT, stdOut); writer.write(entry.toString()); writer.write('\n'); } } try (BufferedReader reader = Files.newBufferedReader(stdErrFile, cs)) { buf = new StringBuffer(); while ((line = reader.readLine()) != null) buf.append(line).append('\n'); stdErr = buf.toString(); if (!stdErr.isEmpty()) { entry = invoc.createJsonReportEntry(JsonReportEntry.KEY_INVOC_STDERR, stdErr); writer.write(entry.toString()); writer.write('\n'); } } if (exitValue == 0) Files.createFile(successMarker); else { ticketSrc.sendMsg(new TicketFailedMsg(cre, ticket, null, script, stdOut, stdErr)); // Files.delete( lockMarker ); return; } } } // gather report report = new HashSet<>(); try (BufferedReader reader = Files.newBufferedReader(reportFile, cs)) { while ((line = reader.readLine()) != null) { line = line.trim(); if (line.isEmpty()) continue; entry = new JsonReportEntry(line); // If the report comes from the hard cache then the run id // is different from the run id of this invocation. This is // corrected here. entry.setRunId(invoc.getRunId()); report.add(entry); } } invoc.evalReport(report); // create link in central data repository for (String f : invoc.getStageOutList()) { srcPath = location.resolve(f); destPath = centralRepo.resolve(f); if (Files.exists(destPath)) continue; if (log.isTraceEnabled()) log.trace("Creating link from " + srcPath + " to " + destPath + "."); Files.createSymbolicLink(destPath, srcPath); } ticketSrc.sendMsg(new TicketFinishedMsg(cre, invoc.getTicket(), report)); if (log.isTraceEnabled()) log.trace("Local thread ran through without exception."); // Files.deleteIfExists( lockMarker ); } catch (InterruptedException e) { if (log.isTraceEnabled()) log.trace("Local thread has been interrupted."); } catch (Exception e) { if (log.isTraceEnabled()) log.trace("Something went wrong. Deleting success marker if present."); if (successMarker != null) try { Files.deleteIfExists(successMarker); } catch (IOException e1) { e1.printStackTrace(); } msg = new TicketFailedMsg(cre, ticket, e, script, stdOut, stdErr); ticketSrc.sendMsg(msg); } finally { if (process != null) { if (log.isDebugEnabled()) log.debug("Stopping local thread for ticket " + invoc.getTicketId() + "."); process.destroy(); } } }
From source file:net.sourceforge.jencrypt.FileEncrypter.java
/** * Encrypt file [inputFile] relative to [pathToEncrypt] into the archive * specified by [outputFile].//from w w w . j av a 2 s. c o m * * @param pathToEncrypt * @param inputFile * @param outputFile * @throws Exception */ private void encryptAndArchivePath(String folderToEncryptString, String inputFileRelativePath, OutputStream os) throws Exception { // Full path to file to encrypt String fullSourcePath = folderToEncryptString + File.separator + inputFileRelativePath; // Path to encrypt is a folder if it ends with a file separator boolean pathIsFolder = (inputFileRelativePath .charAt(inputFileRelativePath.length() - 1) == File.separatorChar); // Use a Unix separator for storing file paths inputFileRelativePath = FilenameUtils.normalize(inputFileRelativePath, true); // To indicate a folder add a Unix file separator at the end if (pathIsFolder) inputFileRelativePath += Utils.UNIX_SEPARATOR; File inputFile = new File(fullSourcePath); Set<PosixFilePermission> perms = null; // Get the "Encrypting [file] ... " message String message = getCipherMessage(inputFile.getName(), commandline.getCipherMode()); // Instantiate ProgressInfo ProgressInfo progress = new FileProgressInfo(message, inputFile.length(), config.getReadBufferSize()); assert (inputFileRelativePath.length() > 0); byte[] pathLength = ByteBuffer.allocate(4).putInt(inputFileRelativePath.length()).array(); byte[] pathLengthEnc = cryptoWrapperFileNamesAndSizes.cipherBytes(pathLength, Cipher.ENCRYPT_MODE); // write 4 bytes path size os.write(pathLengthEnc); byte[] fullPath = inputFileRelativePath.getBytes(); byte[] fullPathEnc = cryptoWrapperFileNamesAndSizes.cipherBytes(fullPath, Cipher.ENCRYPT_MODE); // write full path of encrypted file os.write(fullPathEnc); // Retain file permissions on Unix flavours if (fileSystemIsPosixCompliant()) { perms = Files.getPosixFilePermissions(Paths.get(fullSourcePath), LinkOption.NOFOLLOW_LINKS); } else { /* * On non-POSIX file systems use default Unix (umask 022) file and * directory permissions */ if (pathIsFolder) perms = PosixFilePermissions.fromString("rwxr-xr-x"); else perms = PosixFilePermissions.fromString("rw-r--r--"); } byte[] permBytes = Utils.permsToByte(perms); byte[] permBytesEnc = cryptoWrapperFileNamesAndSizes.cipherBytes(permBytes, Cipher.ENCRYPT_MODE); // write 2 bytes with the file's permissions os.write(permBytesEnc); // Start file encryption if the supplied relative path is not a folder if (!pathIsFolder) { long l = inputFile.length(); byte[] fileSize = ByteBuffer.allocate(8).putLong(l).array(); byte[] fileSizeEnc = cryptoWrapperFileNamesAndSizes.cipherBytes(fileSize, Cipher.ENCRYPT_MODE); // write 8 bytes filesize os.write(fileSizeEnc); cryptoWrapperFileContent.doCipherOperation(getInputFileStream(fullSourcePath), os, new File(fullSourcePath).length(), Cipher.ENCRYPT_MODE, progress); } }