java.nio.file.attribute.PosixFilePermissions Java Examples

The following examples show how to use java.nio.file.attribute.PosixFilePermissions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LocalAttributesFinderFeatureTest.java    From cyberduck with GNU General Public License v3.0 8 votes vote down vote up
@Test
public void testConvert() throws Exception {
    final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
    if(session.isPosixFilesystem()) {
        session.open(Proxy.DIRECT, new DisabledHostKeyCallback(), new DisabledLoginCallback());
        session.login(Proxy.DIRECT, 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());
    }
}
 
Example #2
Source File: KafkaConsumerGroupClientImpl.java    From ksql-fork-with-deep-learning-function with Apache License 2.0 7 votes vote down vote up
private File flushPropertiesToTempFile(Map<String, Object> configProps) throws IOException {
  FileAttribute<Set<PosixFilePermission>> attributes
      = PosixFilePermissions.asFileAttribute(new HashSet<>(
          Arrays.asList(PosixFilePermission.OWNER_WRITE,
                        PosixFilePermission.OWNER_READ)));
  File configFile = Files.createTempFile("ksqlclient", "properties", attributes).toFile();
  configFile.deleteOnExit();

  try (FileOutputStream outputStream = new FileOutputStream(configFile)) {
    Properties clientProps = new Properties();
    for (Map.Entry<String, Object> property
        : configProps.entrySet()) {
      clientProps.put(property.getKey(), property.getValue());
    }
    clientProps.store(outputStream, "Configuration properties of KSQL AdminClient");
  }
  return configFile;
}
 
Example #3
Source File: Standard.java    From presto with Apache License 2.0 6 votes vote down vote up
public static void enablePrestoJavaDebugger(DockerContainer container, int debugPort)
{
    try {
        FileAttribute<Set<PosixFilePermission>> rwx = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxrwxrwx"));
        Path script = Files.createTempFile("enable-java-debugger", ".sh", rwx);
        Files.writeString(
                script,
                format(
                        "#!/bin/bash\n" +
                                "printf '%%s\\n' '%s' >> '%s'\n",
                        "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=0.0.0.0:" + debugPort,
                        CONTAINER_PRESTO_JVM_CONFIG),
                UTF_8);
        container.withCopyFileToContainer(MountableFile.forHostPath(script), "/docker/presto-init.d/enable-java-debugger.sh");

        // expose debug port unconditionally when debug is enabled
        exposePort(container, debugPort);
    }
    catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #4
Source File: LocalJavaKeyStoreProvider.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Override
protected void stashOriginalFilePermissions() throws IOException {
  // save off permissions in case we need to
  // rewrite the keystore in flush()
  if (!Shell.WINDOWS) {
    Path path = Paths.get(file.getCanonicalPath());
    permissions = Files.getPosixFilePermissions(path);
  } else {
    // On Windows, the JDK does not support the POSIX file permission APIs.
    // Instead, we can do a winutils call and translate.
    String[] cmd = Shell.getGetPermissionCommand();
    String[] args = new String[cmd.length + 1];
    System.arraycopy(cmd, 0, args, 0, cmd.length);
    args[cmd.length] = file.getCanonicalPath();
    String out = Shell.execCommand(args);
    StringTokenizer t = new StringTokenizer(out, Shell.TOKEN_SEPARATOR_REGEX);
    // The winutils output consists of 10 characters because of the leading
    // directory indicator, i.e. "drwx------".  The JDK parsing method expects
    // a 9-character string, so remove the leading character.
    String permString = t.nextToken().substring(1);
    permissions = PosixFilePermissions.fromString(permString);
  }
}
 
Example #5
Source File: FileSystemStorage.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
public void writeFile(final String content, final Path file, boolean writeTempFileFirst, Set<PosixFilePermission> permissions)
    throws IOException {
  FsPermission fsPermission;
  if (permissions == null || permissions.isEmpty()) {
    fsPermission = FsPermission.getFileDefault();
  } else {
    // FsPermission expects a 10-character string because of the leading
    // directory indicator, i.e. "drwx------". The JDK toString method returns
    // a 9-character string, so prepend a leading character.
    fsPermission = FsPermission.valueOf("-" + PosixFilePermissions.toString(permissions));
  }
  callHdfsOperation(new HdfsOperation<Void>() {
    @Override
    public Void call() throws IOException {
      InputStream in = new ByteArrayInputStream(content.getBytes(
          zConf.getString(ZeppelinConfiguration.ConfVars.ZEPPELIN_ENCODING)));
      Path tmpFile = new Path(file.toString() + ".tmp");
      IOUtils.copyBytes(in, fs.create(tmpFile), hadoopConf);
      fs.setPermission(tmpFile, fsPermission);
      fs.delete(file, true);
      fs.rename(tmpFile, file);
      return null;
    }
  });
}
 
Example #6
Source File: PasswordFile.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Create password file to be written with access permissions to read
 * and write by user only.
 * <p/>
 * @return Value of <code>true</code> if new file was created
 *         or <code>false</code> otherwise
 */
private boolean createFilePosix() {
    final String METHOD = "createFilePosix";
    boolean success = false;
    try {
        if (Files.notExists(file, new LinkOption[0])) {
            Files.createFile(file, PosixFilePermissions
                    .asFileAttribute(CREATE_FILE_PERMISSIONS));
            success = true;
        } else {
            Files.setPosixFilePermissions(file, CREATE_FILE_PERMISSIONS);
            LOGGER.log(Level.INFO, METHOD, "exists", file.toString());
        }
    } catch (UnsupportedOperationException uoe) {
        LOGGER.log(Level.INFO, METHOD, "unsupported", file.toString());
    } catch (FileAlreadyExistsException faee) {
        LOGGER.log(Level.INFO, METHOD, "exists", file.toString());
    } catch (IOException ioe) {
        LOGGER.log(Level.INFO, METHOD, "ioException", ioe);
    }
    return success;
}
 
Example #7
Source File: LocalJavaKeyStoreProvider.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Override
protected void stashOriginalFilePermissions() throws IOException {
  // save off permissions in case we need to
  // rewrite the keystore in flush()
  if (!Shell.WINDOWS) {
    Path path = Paths.get(file.getCanonicalPath());
    permissions = Files.getPosixFilePermissions(path);
  } else {
    // On Windows, the JDK does not support the POSIX file permission APIs.
    // Instead, we can do a winutils call and translate.
    String[] cmd = Shell.getGetPermissionCommand();
    String[] args = new String[cmd.length + 1];
    System.arraycopy(cmd, 0, args, 0, cmd.length);
    args[cmd.length] = file.getCanonicalPath();
    String out = Shell.execCommand(args);
    StringTokenizer t = new StringTokenizer(out, Shell.TOKEN_SEPARATOR_REGEX);
    // The winutils output consists of 10 characters because of the leading
    // directory indicator, i.e. "drwx------".  The JDK parsing method expects
    // a 9-character string, so remove the leading character.
    String permString = t.nextToken().substring(1);
    permissions = PosixFilePermissions.fromString(permString);
  }
}
 
Example #8
Source File: XcodeToolFinderTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void picksFirstMatchingEntry() throws Exception {
  Path searchRoot1 = tempPath.newFolder("SEARCH_ROOT1");
  Files.createFile(
      searchRoot1.resolve("clang"),
      PosixFilePermissions.asFileAttribute(
          EnumSet.of(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ)));
  Path searchRoot2 = tempPath.newFolder("SEARCH_ROOT2");
  Files.createFile(
      searchRoot2.resolve("clang"),
      PosixFilePermissions.asFileAttribute(
          EnumSet.of(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ)));

  XcodeToolFinder finder =
      new XcodeToolFinder(FakeBuckConfig.builder().build().getView(AppleConfig.class));
  assertEquals(
      Optional.of(searchRoot1.resolve("clang")),
      finder.getToolPath(ImmutableList.of(searchRoot1, searchRoot2), "clang"));
  assertEquals(
      Optional.of(searchRoot2.resolve("clang")),
      finder.getToolPath(ImmutableList.of(searchRoot2, searchRoot1), "clang"));
}
 
Example #9
Source File: LogSegmentTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Test that the file permissions are correctly set based on permissions specified in {@link StoreConfig}.
 * @throws Exception
 */
@Test
public void setFilePermissionsTest() throws Exception {
  Properties props = new Properties();
  props.setProperty("store.set.file.permission.enabled", Boolean.toString(true));
  props.setProperty("store.data.file.permission", "rw-rw-r--");
  StoreConfig initialConfig = new StoreConfig(new VerifiableProperties(props));
  File segmentFile = new File(tempDir, "test_segment");
  assertTrue("Fail to create segment file", segmentFile.createNewFile());
  segmentFile.deleteOnExit();
  // create log segment instance by writing into brand new file (using initialConfig, file permission = "rw-rw-r--")
  new LogSegment(segmentFile.getName(), segmentFile, STANDARD_SEGMENT_SIZE, initialConfig, metrics, true);
  Set<PosixFilePermission> filePerm = Files.getPosixFilePermissions(segmentFile.toPath());
  assertEquals("File permissions are not expected", "rw-rw-r--", PosixFilePermissions.toString(filePerm));
  // create log segment instance by reading from existing file (using default store config, file permission = "rw-rw----")
  new LogSegment(segmentFile.getName(), segmentFile, config, metrics);
  filePerm = Files.getPosixFilePermissions(segmentFile.toPath());
  assertEquals("File permissions are not expected", "rw-rw----", PosixFilePermissions.toString(filePerm));
}
 
Example #10
Source File: XcodeToolFinderTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void matchesRenamedToolName() throws Exception {
  Path searchRoot = tempPath.newFolder("SEARCH_ROOT");
  Files.createFile(
      searchRoot.resolve("clang"),
      PosixFilePermissions.asFileAttribute(
          EnumSet.of(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ)));
  Files.createFile(
      searchRoot.resolve("my_clang"),
      PosixFilePermissions.asFileAttribute(
          EnumSet.of(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ)));
  assertEquals(
      Optional.of(searchRoot.resolve("clang")),
      new XcodeToolFinder(FakeBuckConfig.builder().build().getView(AppleConfig.class))
          .getToolPath(ImmutableList.of(searchRoot), "clang"));
  assertEquals(
      Optional.of(searchRoot.resolve("my_clang")),
      new XcodeToolFinder(
              FakeBuckConfig.builder()
                  .setSections("[apple]", "clang_xcode_tool_name_override=my_clang")
                  .build()
                  .getView(AppleConfig.class))
          .getToolPath(ImmutableList.of(searchRoot), "clang"));
}
 
Example #11
Source File: TrustOnFirstUseManagerTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddFingerPrintFailedToWrite() throws CertificateException, IOException {

    Path notWritable = Paths.get(tmpDir.getRoot().getPath(), "notWritable");

    Files.createFile(notWritable);
    Files.setPosixFilePermissions(notWritable, PosixFilePermissions.fromString("r--------"));

    trustManager = new TrustOnFirstUseManager(notWritable);

    X509Certificate certificate = mock(X509Certificate.class);
    when(certificate.getEncoded()).thenReturn("certificate".getBytes(UTF_8));
    X500Principal cn = new X500Principal("CN=localhost");
    when(certificate.getSubjectX500Principal()).thenReturn(cn);

    try {
        trustManager.checkServerTrusted(new X509Certificate[]{certificate}, "s");
        trustManager.checkClientTrusted(new X509Certificate[]{certificate}, "s");

        failBecauseExceptionWasNotThrown(CertificateException.class);
    } catch (Exception ex) {
        assertThat(ex).isInstanceOf(CertificateException.class);
    }
}
 
Example #12
Source File: Utils.java    From CodeCheckerEclipsePlugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Copies into the specified directory, and sets runnable permission to Codechecker.
 * The path to the runnable CodeChecker will be tmp/<tempTestFolder>/<into>/bin/CodeChecker
 * @param into This will be the name of the CodeChecker root folder.
 * @return The path to To the CodeChecker root directory. 
 *      Will point to tmp/<tempTestFolder>/<into> .
 */
public static Path prepareCodeChecker(String into) {
    if (into.isEmpty() || into == null) throw new IllegalArgumentException();
    
    Path testDir = null;
    Path ccRoot = null;
    try {
        testDir = Files.createTempDirectory("CCTest");
        testDir.toFile().deleteOnExit();
        testDir = Files.createDirectory(Paths.get(testDir.toString(), into));
        ccRoot = Utils.loadFileFromBundle("org.codechecker.eclipse.rcp.shared",
                Utils.RES + CODECHECKER);
    } catch (IOException | URISyntaxException e1) {
        e1.printStackTrace(System.out);
    }
    // Get the CodeChecker stub from the test resources, and copy it to a temporary folder.
    Path ccDir = Utils.copyFolder(ccRoot, testDir);
    Path ccBinDir = Paths.get( testDir.toAbsolutePath().toString(), CODECHECKER, BIN, CODECHECKER);
    try {
        // CodeChecker must be runnable.
        Files.setPosixFilePermissions(ccBinDir, PosixFilePermissions.fromString("rwxrwxrwx"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return ccDir;
}
 
Example #13
Source File: PosixViewAttributeAction.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public PosixViewAttributeAction build() {
    if (Strings.isEmpty(basePath)) {
        LOGGER.error("Posix file attribute view action not valid because base path is empty.");
        return null;
    }

    if (filePermissions == null && Strings.isEmpty(filePermissionsString)
                && Strings.isEmpty(fileOwner) && Strings.isEmpty(fileGroup)) {
        LOGGER.error("Posix file attribute view not valid because nor permissions, user or group defined.");
        return null;
    }

    if (!FileUtils.isFilePosixAttributeViewSupported()) {
        LOGGER.warn("Posix file attribute view defined but it is not supported by this files system.");
        return null;
    }

    return new PosixViewAttributeAction(basePath, followLinks, maxDepth, pathConditions,
            subst != null ? subst : configuration.getStrSubstitutor(),
            filePermissions != null ? filePermissions :
                        filePermissionsString != null ? PosixFilePermissions.fromString(filePermissionsString) : null,
            fileOwner,
            fileGroup);
}
 
Example #14
Source File: LocalFile.java    From datacollector with Apache License 2.0 6 votes vote down vote up
public Map<String, Object> getFileMetadata() throws IOException {
  Map<String, Object>  metadata;
  if (filePath.toFile().exists()) {
    boolean isPosix = filePath.getFileSystem().supportedFileAttributeViews().contains("posix");
    metadata = new ConcurrentHashMap<>(Files.readAttributes(filePath, isPosix ? "posix:*" : "*"));
    metadata.put(HeaderAttributeConstants.FILE_NAME, filePath.getFileName().toString());
    metadata.put(HeaderAttributeConstants.FILE, filePath);
    if (isPosix && metadata.containsKey(PERMISSIONS) && Set.class.isAssignableFrom(metadata.get(PERMISSIONS).getClass())) {
      Set<PosixFilePermission> posixFilePermissions = (Set<PosixFilePermission>)(metadata.get(PERMISSIONS));
      //converts permission to rwx- format and replace it in permissions field.
      // (totally containing 9 characters 3 for user 3 for group and 3 for others)
      metadata.put(PERMISSIONS, PosixFilePermissions.toString(posixFilePermissions));
    }
    metadata.put(HeaderAttributeConstants.LAST_CHANGE_TIME, Files.getAttribute(filePath, "unix:ctime"));
  } else {
    metadata = new ConcurrentHashMap<>();
    metadata.put(HeaderAttributeConstants.LAST_CHANGE_TIME, 0L);
    metadata.put(HeaderAttributeConstants.LAST_MODIFIED_TIME, 0L);
    metadata.put(LAST_MODIFIED_TIMESTAMP_KEY, 0L);
  }
  return metadata;
}
 
Example #15
Source File: LocalLocation.java    From twill with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the given permission to a set of {@link PosixFilePermission}.
 *
 * @param permission the permission as passed to the {@link #createNew(String)} or {@link #getOutputStream(String)}
 *                   methods.
 * @return a new set of {@link PosixFilePermission}.
 */
private Set<PosixFilePermission> parsePermissions(String permission) {
  Set<PosixFilePermission> permissions;
  if (permission.length() == 3) {
    permissions = parseNumericPermissions(permission);
  } else if (permission.length() == 9) {
    permissions = PosixFilePermissions.fromString(permission);
  } else {
    throw new IllegalArgumentException("Invalid permission " + permission +
                                         ". Permission should either be a three digit or nine character string.");
  }

  return permissions;
}
 
Example #16
Source File: IOUtils.java    From signal-cli with GNU General Public License v3.0 5 votes vote down vote up
public static void createPrivateDirectories(String directoryPath) throws IOException {
    final File file = new File(directoryPath);
    if (file.exists()) {
        return;
    }

    final Path path = file.toPath();
    try {
        Set<PosixFilePermission> perms = EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE);
        Files.createDirectories(path, PosixFilePermissions.asFileAttribute(perms));
    } catch (UnsupportedOperationException e) {
        Files.createDirectories(path);
    }
}
 
Example #17
Source File: FilePermissionTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testWriteFileIntoDirWithoutWritePermission() throws Exception {

    // This is unix test only
    if (!Util.isWindows()) {

        Set<PosixFilePermission> permsBefore =
                EnumSet.of(OWNER_READ, OWNER_EXECUTE);

        Path dir = Files.createTempDirectory("tmpDir", PosixFilePermissions.asFileAttribute(permsBefore));
        String dirFullStringPath = dir.toString();
        String filePath = dirFullStringPath + "/test";

        String cmd = "echo \"aaa\" >>" + filePath;

        expectedException.expect(CommandLineException.class);
        expectedException.expectMessage(filePath + " (Access denied)");

        cliOut.reset();
        final CommandContext ctx = CLITestUtil.getCommandContext(cliOut);
        try {
            ctx.handle(cmd);
        } finally {
            ctx.terminateSession();
            cliOut.reset();
            Files.delete(dir);
        }
    }
}
 
Example #18
Source File: PathParameterTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testInputFileValidate_unreadableFile_throws() throws Exception {
  Path file = Paths.get(folder.newFile().toString());
  Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("-w-------"));
  ParameterException thrown =
      assertThrows(ParameterException.class, () -> inputFile.validate("input", file.toString()));
  assertThat(thrown).hasMessageThat().contains("not readable");
}
 
Example #19
Source File: UnixPath.java    From vespa with Apache License 2.0 5 votes vote down vote up
private Set<PosixFilePermission> getPosixFilePermissionsFromString(String permissions) {
    try {
        return PosixFilePermissions.fromString(permissions);
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException("Failed to set permissions '" +
                permissions + "' on path " + path, e);
    }
}
 
Example #20
Source File: XcodeToolFinderTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void matchesReplacementTool() throws Exception {
  Path searchRoot = tempPath.newFolder("SEARCH_ROOT");
  Path outsideRoot = tempPath.newFolder("OUTSIDE_ROOT");
  Files.createFile(
      searchRoot.resolve("clang"),
      PosixFilePermissions.asFileAttribute(
          EnumSet.of(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ)));
  Files.createFile(
      searchRoot.resolve("my_clang"),
      PosixFilePermissions.asFileAttribute(
          EnumSet.of(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ)));
  Files.createFile(
      outsideRoot.resolve("clang"),
      PosixFilePermissions.asFileAttribute(
          EnumSet.of(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ)));
  assertEquals(
      Optional.of(searchRoot.resolve("clang")),
      new XcodeToolFinder(FakeBuckConfig.builder().build().getView(AppleConfig.class))
          .getToolPath(ImmutableList.of(searchRoot), "clang"));
  assertEquals(
      Optional.of(outsideRoot.resolve("clang")),
      new XcodeToolFinder(
              FakeBuckConfig.builder()
                  .setSections(
                      "[apple]",
                      "clang_xcode_tool_name_override=my_clang",
                      "clang_replacement=" + outsideRoot.resolve("clang"))
                  .build()
                  .getView(AppleConfig.class))
          .getToolPath(ImmutableList.of(searchRoot), "clang"));
}
 
Example #21
Source File: UnzipTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@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);
    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);
}
 
Example #22
Source File: TestRemoteNodeFileSystemE2E.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetFileStatus() throws IOException {
  File subFolder = temporaryFolder.newFolder();

  java.nio.file.Path nativePath = Files.createFile(
      new File(subFolder, "foo").toPath(),
      PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("r-xr--r--")));

  FileStatus status = sabotFS.getFileStatus(new Path(toPathString(nativePath)));
  assertEquals(toPathString(nativePath), toPathString(status.getPath()));
  assertEquals(FsPermission.createImmutable((short) 0544), status.getPermission());
}
 
Example #23
Source File: FileType.java    From skara with GNU General Public License v2.0 5 votes vote down vote up
public Optional<Set<PosixFilePermission>> permissions() {
    switch (type) {
        case REGULAR_NON_EXECUTABLE:
            return Optional.of(PosixFilePermissions.fromString("rw-r--r--"));
        case REGULAR_NON_EXECUTABLE_GROUP_WRITABLE:
            return Optional.of(PosixFilePermissions.fromString("rw-rw-r--"));
        case REGULAR_EXECUTABLE:
            return Optional.of(PosixFilePermissions.fromString("rwxr-xr-x"));
        default:
            return Optional.empty();
    }
}
 
Example #24
Source File: LocalLocation.java    From twill with Apache License 2.0 5 votes vote down vote up
/**
 * Parses a three digit UNIX numeric permission representation to a set of {@link PosixFilePermission}.
 */
private Set<PosixFilePermission> parseNumericPermissions(String permission) {
  String posixPermission = "";
  for (int i = 0; i < 3; i++) {
    int digit = permission.charAt(i) - '0';
    if (digit < 0 || digit > 7) {
      throw new IllegalArgumentException("Invalid permission " + permission +
                                           ". Only digits between 0-7 are allowed.");
    }
    posixPermission += ((digit & 4) != 0) ? "r" : "-";
    posixPermission += ((digit & 2) != 0) ? "w" : "-";
    posixPermission += ((digit & 1) != 0) ? "x" : "-";
  }
  return PosixFilePermissions.fromString(posixPermission);
}
 
Example #25
Source File: PosixAttributeProviderTest.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@Test
public void testView() throws IOException {
  file.setAttribute("owner", "owner", createUserPrincipal("user"));

  PosixFileAttributeView view =
      provider.view(
          fileLookup(),
          ImmutableMap.of(
              "basic", new BasicAttributeProvider().view(fileLookup(), NO_INHERITED_VIEWS),
              "owner", new OwnerAttributeProvider().view(fileLookup(), NO_INHERITED_VIEWS)));
  assertNotNull(view);

  assertThat(view.name()).isEqualTo("posix");
  assertThat(view.getOwner()).isEqualTo(createUserPrincipal("user"));

  PosixFileAttributes attrs = view.readAttributes();
  assertThat(attrs.fileKey()).isEqualTo(0);
  assertThat(attrs.owner()).isEqualTo(createUserPrincipal("user"));
  assertThat(attrs.group()).isEqualTo(createGroupPrincipal("group"));
  assertThat(attrs.permissions()).isEqualTo(PosixFilePermissions.fromString("rw-r--r--"));

  view.setOwner(createUserPrincipal("root"));
  assertThat(view.getOwner()).isEqualTo(createUserPrincipal("root"));
  assertThat(file.getAttribute("owner", "owner")).isEqualTo(createUserPrincipal("root"));

  view.setGroup(createGroupPrincipal("root"));
  assertThat(view.readAttributes().group()).isEqualTo(createGroupPrincipal("root"));
  assertThat(file.getAttribute("posix", "group")).isEqualTo(createGroupPrincipal("root"));

  view.setPermissions(PosixFilePermissions.fromString("rwx------"));
  assertThat(view.readAttributes().permissions())
      .isEqualTo(PosixFilePermissions.fromString("rwx------"));
  assertThat(file.getAttribute("posix", "permissions"))
      .isEqualTo(PosixFilePermissions.fromString("rwx------"));
}
 
Example #26
Source File: FilePersistenceUtils.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static List<FileAttribute<Set<PosixFilePermission>>> getPosixAttributes(Path file) throws IOException {
    if (Files.exists(file) && supportsFileOwnerAttributeView(file, PosixFileAttributeView.class)) {
        PosixFileAttributeView posixView = Files.getFileAttributeView(file, PosixFileAttributeView.class);
        if (posixView != null) {
            return Collections.singletonList(PosixFilePermissions.asFileAttribute(posixView.readAttributes().permissions()));
        }
    }
    return Collections.emptyList();
}
 
Example #27
Source File: ValidFileWritableTest.java    From connect-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void notWritable() throws IOException {
  final FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(EnumSet.of(
      PosixFilePermission.OWNER_READ
  ));
  final Path path = createTempFile(attr);

  assertThrows(ConfigException.class, () -> {
    this.validator.ensureValid("testing", path.toString());
  });
}
 
Example #28
Source File: TestCacheUtil.java    From rubix with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void initializeCacheDirectories() throws IOException
{
  Set<PosixFilePermission> perms =
          PosixFilePermissions.fromString("rwx------");
  FileAttribute<Set<PosixFilePermission>> attr =
          PosixFilePermissions.asFileAttribute(perms);
  Files.createDirectories(Paths.get(cacheTestDirPrefix), attr);
  for (int i = 0; i < maxDisks; i++) {
    Files.createDirectories(Paths.get(cacheTestDirPrefix, String.valueOf(i)));
  }
}
 
Example #29
Source File: Put.java    From bt with Apache License 2.0 5 votes vote down vote up
void loadKey() throws IOException, NoSuchAlgorithmException {
	if(!mutable)
		return;
	
	if(keyFile == null) {
		keyFile = Paths.get(".", ".keys", "default.priv");
	}
	
	keyFile = keyFile.toAbsolutePath().normalize();
	
	Path dir = keyFile.getParent();
	
	Files.createDirectories(dir);
	
	// TODO: platform detection
	try {
		Files.setPosixFilePermissions(dir, PosixFilePermissions.fromString("rwx------"));
	} catch (UnsupportedOperationException ex) {
		printErr("Warning: could not restrict access for private key storage directory (filesystem does not support posix permissions?). " + dir.toString() + "\n");
	}
	
	byte[] seed;
	

	if(!Files.exists(keyFile)) {
		seed = SecureRandom.getInstanceStrong().generateSeed(32);
		Files.write(keyFile, Base64.getEncoder().encode(seed), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
		println("Key does not exist, creating... saving at " + keyFile.toString());
	} else {
		seed = Base64.getDecoder().decode(Files.readAllBytes(keyFile));
		if(seed.length != 32) {
			throw new IllegalArgumentException("failed to decode private key, expected 32bytes after base64 decoding");
		}
	}
	
	key = new EdDSAPrivateKey(new EdDSAPrivateKeySpec(seed, GenericStorage.StorageItem.spec));
}
 
Example #30
Source File: LocalLocation.java    From twill with Apache License 2.0 5 votes vote down vote up
@Override
public OutputStream getOutputStream(String permission) throws IOException {
  Set<PosixFilePermission> permissions = parsePermissions(permission);
  ensureDirectory(file.getParentFile(), permissions);
  Path path = file.toPath();
  WritableByteChannel channel = Files.newByteChannel(path,
                                                     EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE),
                                                     PosixFilePermissions.asFileAttribute(permissions));
  // Set the permission explicitly again to skip the umask
  Files.setPosixFilePermissions(path, permissions);
  return Channels.newOutputStream(channel);
}