java.nio.file.attribute.UserPrincipal Java Examples

The following examples show how to use java.nio.file.attribute.UserPrincipal. 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: UserLookupServiceTest.java    From jimfs with Apache License 2.0 7 votes vote down vote up
@Test
public void testUserLookupService() throws IOException {
  UserPrincipalLookupService service = new UserLookupService(true);
  UserPrincipal bob1 = service.lookupPrincipalByName("bob");
  UserPrincipal bob2 = service.lookupPrincipalByName("bob");
  UserPrincipal alice = service.lookupPrincipalByName("alice");

  assertThat(bob1).isEqualTo(bob2);
  assertThat(bob1).isNotEqualTo(alice);

  GroupPrincipal group1 = service.lookupPrincipalByGroupName("group");
  GroupPrincipal group2 = service.lookupPrincipalByGroupName("group");
  GroupPrincipal foo = service.lookupPrincipalByGroupName("foo");

  assertThat(group1).isEqualTo(group2);
  assertThat(group1).isNotEqualTo(foo);
}
 
Example #2
Source File: TestUserPrincipalLookupService.java    From jsr203-hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testUsersEquals() throws IOException {
  Path rootPath = Paths.get(clusterUri);

  UserPrincipal user = Files.getOwner(rootPath);
  assertNotNull(user);

  // Get the same user
  UserPrincipal user2 = Files.getOwner(rootPath);
  assertNotNull(user2);

  Assert.assertTrue(user.equals(user));
  Assert.assertTrue(user.equals(user2) && user2.equals(user));

  Assert.assertFalse(user.equals(null));
  Assert.assertFalse(user.equals(new Double(-1)));

  UserPrincipal userTest = rootPath.getFileSystem()
      .getUserPrincipalLookupService().lookupPrincipalByName("test");
  Assert.assertFalse(user.equals(userTest));
}
 
Example #3
Source File: TestVMOptionsFile.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void makeFileNonReadable(String file) throws IOException {
    Path filePath = Paths.get(file);
    Set<String> supportedAttr = filePath.getFileSystem().supportedFileAttributeViews();

    if (supportedAttr.contains("posix")) {
        Files.setPosixFilePermissions(filePath, PosixFilePermissions.fromString("-w--w----"));
    } else if (supportedAttr.contains("acl")) {
        UserPrincipal fileOwner = Files.getOwner(filePath);

        AclFileAttributeView view = Files.getFileAttributeView(filePath, AclFileAttributeView.class);

        AclEntry entry = AclEntry.newBuilder()
                .setType(AclEntryType.DENY)
                .setPrincipal(fileOwner)
                .setPermissions(AclEntryPermission.READ_DATA)
                .build();

        List<AclEntry> acl = view.getAcl();
        acl.add(0, entry);
        view.setAcl(acl);
    }
}
 
Example #4
Source File: InitMojo.java    From helm-maven-plugin with MIT License 6 votes vote down vote up
private void addExecPermission(final Path helm) throws IOException {
	Set<String> fileAttributeView = FileSystems.getDefault().supportedFileAttributeViews();

	if (fileAttributeView.contains("posix")) {
		final Set<PosixFilePermission> permissions;
		try {
			permissions = Files.getPosixFilePermissions(helm);
		} catch (UnsupportedOperationException e) {
			getLog().debug("Exec file permission is not set", e);
			return;
		}
		permissions.add(PosixFilePermission.OWNER_EXECUTE);
		Files.setPosixFilePermissions(helm, permissions);

	} else if (fileAttributeView.contains("acl")) {
		String username = System.getProperty("user.name");
		UserPrincipal userPrincipal = FileSystems.getDefault().getUserPrincipalLookupService().lookupPrincipalByName(username);
		AclEntry aclEntry = AclEntry.newBuilder().setPermissions(AclEntryPermission.EXECUTE).setType(AclEntryType.ALLOW).setPrincipal(userPrincipal).build();

		AclFileAttributeView acl = Files.getFileAttributeView(helm, AclFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
		List<AclEntry> aclEntries = acl.getAcl();
		aclEntries.add(aclEntry);
		acl.setAcl(aclEntries);
	}
}
 
Example #5
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
void fixSshKeyOnWindows(File key) throws GitException {
    if (launcher.isUnix()) return;

    Path file = Paths.get(key.toURI());

    AclFileAttributeView fileAttributeView = Files.getFileAttributeView(file, AclFileAttributeView.class);
    if (fileAttributeView == null) return;

    try {
        UserPrincipal userPrincipal = fileAttributeView.getOwner();
        AclEntry aclEntry = AclEntry.newBuilder()
            .setType(AclEntryType.ALLOW)
            .setPrincipal(userPrincipal)
            .setPermissions(ACL_ENTRY_PERMISSIONS)
            .build();
        fileAttributeView.setAcl(Collections.singletonList(aclEntry));
    } catch (IOException | UnsupportedOperationException e) {
        throw new GitException("Error updating file permission for \"" + key.getAbsolutePath() + "\"", e);
    }
}
 
Example #6
Source File: WindowsFilePermissionHelper.java    From hashicorp-vault-plugin with MIT License 6 votes vote down vote up
public static void fixSshKeyOnWindows(Path file) {
    AclFileAttributeView fileAttributeView = Files
        .getFileAttributeView(file, AclFileAttributeView.class);
    if (fileAttributeView == null) return;

    try {
        UserPrincipal userPrincipal = fileAttributeView.getOwner();
        AclEntry aclEntry = AclEntry.newBuilder()
            .setType(AclEntryType.ALLOW)
            .setPrincipal(userPrincipal)
            .setPermissions(ACL_ENTRY_PERMISSIONS)
            .build();
        fileAttributeView.setAcl(Collections.singletonList(aclEntry));
    } catch (IOException | UnsupportedOperationException e) {
        throw new IllegalStateException("Error updating file permission for \"" + file + "\"", e);
    }
}
 
Example #7
Source File: SaltActionChainGeneratorService.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Make sure the {@literal actionchains} subdir exists.
 * @return the {@link Path} of the {@literal} actionchains directory
 */
private Path createActionChainsDir() {
    Path targetDir = getTargetDir();
    if (!Files.exists(targetDir)) {
        try {
            Files.createDirectories(targetDir);
            if (!skipSetOwner) {
                FileSystem fileSystem = FileSystems.getDefault();
                UserPrincipalLookupService service = fileSystem.getUserPrincipalLookupService();
                UserPrincipal tomcatUser = service.lookupPrincipalByName("tomcat");
                Files.setOwner(targetDir, tomcatUser);
            }
        }
        catch (IOException e) {
            LOG.error("Could not create action chain directory " + targetDir, e);
            throw new RuntimeException(e);
        }
    }
    return targetDir;
}
 
Example #8
Source File: FilePermissionTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testDefaultOwnership() throws Exception {
    // This is unix test only
    if (!Util.isWindows()) {
        CommandContext ctx = CLITestUtil.getCommandContext(TestSuiteEnvironment.getServerAddress(),
                TestSuiteEnvironment.getServerPort(), System.in, System.out);

        String tmpFile = "tmpFile";
        Path path = Paths.get(tmpFile);

        try {
            ctx.handle("echo \"aaa\" >> " + tmpFile);

            UserPrincipal userPrincipal = Files.getOwner(path);
            assertThat("The test file has unexpected ownership: " + userPrincipal.toString(),
                    userPrincipal.toString(), CoreMatchers.is(CoreMatchers.equalTo(System.getProperty("user.name"))));
        } finally {
            ctx.terminateSession();
            Files.delete(path);
        }
    }
}
 
Example #9
Source File: CFCExecFileSystem.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
CFCExecFileSystem(
    Path root,
    CASFileCache fileCache,
    @Nullable UserPrincipal owner,
    boolean linkInputDirectories,
    ExecutorService removeDirectoryService,
    ExecutorService accessRecorder,
    long deadlineAfter,
    TimeUnit deadlineAfterUnits) {
  this.root = root;
  this.fileCache = fileCache;
  this.owner = owner;
  this.linkInputDirectories = linkInputDirectories;
  this.removeDirectoryService = removeDirectoryService;
  this.accessRecorder = accessRecorder;
  this.deadlineAfter = deadlineAfter;
  this.deadlineAfterUnits = deadlineAfterUnits;
}
 
Example #10
Source File: OwnerAttributeProvider.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@Override
public ImmutableMap<String, ?> defaultValues(Map<String, ?> userProvidedDefaults) {
  Object userProvidedOwner = userProvidedDefaults.get("owner:owner");

  UserPrincipal owner = DEFAULT_OWNER;
  if (userProvidedOwner != null) {
    if (userProvidedOwner instanceof String) {
      owner = createUserPrincipal((String) userProvidedOwner);
    } else {
      throw invalidType("owner", "owner", userProvidedOwner, String.class, UserPrincipal.class);
    }
  }

  return ImmutableMap.of("owner:owner", owner);
}
 
Example #11
Source File: CheckLockLocationTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private static String getOwner(Path path) {
    UserPrincipal user = null;
    try {
        user = Files.getOwner(path);
    } catch (Exception x) {
        System.err.println("Failed to get owner of: " + path);
        System.err.println("\terror is: " + x);
    }
    return user == null ? "???" : user.getName();
}
 
Example #12
Source File: SaltServerActionService.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
private void setFileOwner(Path path) throws IOException {
    FileSystem fileSystem = FileSystems.getDefault();
    UserPrincipalLookupService service = fileSystem.getUserPrincipalLookupService();
    UserPrincipal tomcatUser = service.lookupPrincipalByName("tomcat");

    Files.setOwner(path, tomcatUser);
}
 
Example #13
Source File: CWLParser.java    From cwlexec with Apache License 2.0 5 votes vote down vote up
private static String getFileOwner(File file) {
    String owner = null;
    if (file != null) {
        Path path = Paths.get(file.getAbsolutePath());
        try {
            UserPrincipal user = Files.getFileAttributeView(path, FileOwnerAttributeView.class).getOwner();
            return user.getName();
        } catch (IOException e) {
            logger.warn("Fail to get the owner of {}, ({})", path, e.getMessage());
        }
    }
    return owner;
}
 
Example #14
Source File: CheckLockLocationTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static String getOwner(Path path) {
    UserPrincipal user = null;
    try {
        user = Files.getOwner(path);
    } catch (Exception x) {
        System.err.println("Failed to get owner of: " + path);
        System.err.println("\terror is: " + x);
    }
    return user == null ? "???" : user.getName();
}
 
Example #15
Source File: CheckLockLocationTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private static String getOwner(Path path) {
    UserPrincipal user = null;
    try {
        user = Files.getOwner(path);
    } catch (Exception x) {
        System.err.println("Failed to get owner of: " + path);
        System.err.println("\terror is: " + x);
    }
    return user == null ? "???" : user.getName();
}
 
Example #16
Source File: UnixPath.java    From vespa with Apache License 2.0 5 votes vote down vote up
public UnixPath setOwner(String owner) {
    UserPrincipalLookupService service = path.getFileSystem().getUserPrincipalLookupService();
    UserPrincipal principal = uncheck(
            () -> service.lookupPrincipalByName(owner),
            "While looking up user %s", owner);
    uncheck(() -> Files.setOwner(path, principal));
    return this;
}
 
Example #17
Source File: CheckLockLocationTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static String getOwner(Path path) {
    UserPrincipal user = null;
    try {
        user = Files.getOwner(path);
    } catch (Exception x) {
        System.err.println("Failed to get owner of: " + path);
        System.err.println("\terror is: " + x);
    }
    return user == null ? "???" : user.getName();
}
 
Example #18
Source File: UnixAttributeProvider.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object get(File file, String attribute) {
  switch (attribute) {
    case "uid":
      UserPrincipal user = (UserPrincipal) file.getAttribute("owner", "owner");
      return getUniqueId(user);
    case "gid":
      GroupPrincipal group = (GroupPrincipal) file.getAttribute("posix", "group");
      return getUniqueId(group);
    case "mode":
      Set<PosixFilePermission> permissions =
          (Set<PosixFilePermission>) file.getAttribute("posix", "permissions");
      return toMode(permissions);
    case "ctime":
      return FileTime.fromMillis(file.getCreationTime());
    case "rdev":
      return 0L;
    case "dev":
      return 1L;
    case "ino":
      return file.id();
    case "nlink":
      return file.links();
    default:
      return null;
  }
}
 
Example #19
Source File: LocalFileSystemOperations.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param filename the file name
 * @return the file owner
 * @throws FileSystemOperationException
 */
private String getOwner(
        String filename ) {

    try {
        UserPrincipal owner = Files.readAttributes(new File(filename).toPath(),
                                                   PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS)
                                   .owner();
        return owner.getName();

    } catch (Exception e) {
        throw new FileSystemOperationException("Could not get owner for '" + filename + "'", e);
    }
}
 
Example #20
Source File: CheckLockLocationTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static String getOwner(Path path) {
    UserPrincipal user = null;
    try {
        user = Files.getOwner(path);
    } catch (Exception x) {
        System.err.println("Failed to get owner of: " + path);
        System.err.println("\terror is: " + x);
    }
    return user == null ? "???" : user.getName();
}
 
Example #21
Source File: PosixFileAttributeManager.java    From yajsync with GNU General Public License v3.0 5 votes vote down vote up
private UserPrincipal getUserPrincipalFrom(String userName) throws IOException
{
    try {
        UserPrincipal principal = _nameToUserPrincipal.get(userName);
        if (principal == null) {
            UserPrincipalLookupService service =
                    FileSystems.getDefault().getUserPrincipalLookupService();
            principal = service.lookupPrincipalByName(userName);
            _nameToUserPrincipal.put(userName, principal);
        }
        return principal;
    } catch (UnsupportedOperationException e) {
        throw new IOException(e);
    }
}
 
Example #22
Source File: PosixAttributeProvider.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected Attributes(File file) {
  super(file);
  this.owner = (UserPrincipal) file.getAttribute("owner", "owner");
  this.group = (GroupPrincipal) file.getAttribute("posix", "group");
  this.permissions =
      (ImmutableSet<PosixFilePermission>) file.getAttribute("posix", "permissions");
}
 
Example #23
Source File: TestFiles.java    From jsr203-hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Test owner in posix file view support.
 * 
 * @throws IOException
 */
@Test
public void testGetPosixView() throws IOException {
  Path rootPath = Paths.get(clusterUri);

  assertTrue(rootPath.getFileSystem().supportedFileAttributeViews()
      .contains("posix"));
  PosixFileAttributeView view = Files.getFileAttributeView(rootPath,
      PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
  assertNotNull(view);
  UserPrincipal user = view.getOwner();
  assertNotNull(user);
  assertNotNull(user.getName());
}
 
Example #24
Source File: UnixFileAttributeManager.java    From yajsync with GNU General Public License v3.0 5 votes vote down vote up
private UserPrincipal getUserPrincipalFrom(String userName) throws IOException
{
    try {
        if (_isCacheEnabled) {
            return _nameToUserPrincipal.get(userName);
        }
        UserPrincipalLookupService service =
                FileSystems.getDefault().getUserPrincipalLookupService();
        return service.lookupPrincipalByName(userName);
    } catch (IOException | UnsupportedOperationException e) {
        return null;
    }
}
 
Example #25
Source File: CheckLockLocationTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static String getOwner(Path path) {
    UserPrincipal user = null;
    try {
        user = Files.getOwner(path);
    } catch (Exception x) {
        System.err.println("Failed to get owner of: " + path);
        System.err.println("\terror is: " + x);
    }
    return user == null ? "???" : user.getName();
}
 
Example #26
Source File: UnixFileAttributeManager.java    From yajsync with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setOwner(Path path, User user, LinkOption... linkOption) throws IOException
{
    UserPrincipal principal = getUserPrincipalFrom(user.name());
    if (principal == null) {
        setUserId(path, user.id(), linkOption);
    }
    Files.setAttribute(path, "unix:owner", principal, linkOption);
}
 
Example #27
Source File: EvenMoreFiles.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
public static void setReadOnlyPerms(Path path, boolean executable) throws IOException {
  FileStore fileStore = Files.getFileStore(path);
  if (fileStore.supportsFileAttributeView("posix")) {
    if (executable) {
      Files.setPosixFilePermissions(path, readOnlyExecPerms);
    } else {
      Files.setPosixFilePermissions(path, readOnlyPerms);
    }
  } else if (fileStore.supportsFileAttributeView("acl")) {
    // windows, we hope
    UserPrincipal authenticatedUsers =
        path.getFileSystem()
            .getUserPrincipalLookupService()
            .lookupPrincipalByName("Authenticated Users");
    AclEntry denyWriteEntry =
        AclEntry.newBuilder()
            .setType(AclEntryType.DENY)
            .setPrincipal(authenticatedUsers)
            .setPermissions(AclEntryPermission.APPEND_DATA, AclEntryPermission.WRITE_DATA)
            .build();
    AclEntry execEntry =
        AclEntry.newBuilder()
            .setType(executable ? AclEntryType.ALLOW : AclEntryType.DENY)
            .setPrincipal(authenticatedUsers)
            .setPermissions(AclEntryPermission.EXECUTE)
            .build();

    AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class);
    List<AclEntry> acl = view.getAcl();
    acl.add(0, execEntry);
    acl.add(0, denyWriteEntry);
    view.setAcl(acl);
  } else {
    throw new UnsupportedOperationException("no recognized attribute view");
  }
}
 
Example #28
Source File: HadoopFileOwnerAttributeView.java    From jsr203-hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public UserPrincipal getOwner() throws IOException {
  UserPrincipalLookupService ls = this.path.getFileSystem()
      .getUserPrincipalLookupService();
  FileStatus fileStatus = path.getFileSystem().getHDFS()
      .getFileStatus(path.getRawResolvedPath());
  return ls.lookupPrincipalByName(fileStatus.getOwner());
}
 
Example #29
Source File: Worker.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
private ExecFileSystem createExecFileSystem(
    InputStreamFactory remoteInputStreamFactory,
    ExecutorService removeDirectoryService,
    ExecutorService accessRecorder,
    ContentAddressableStorage storage)
    throws ConfigurationException {
  checkState(storage != null, "no exec fs cas specified");
  if (storage instanceof CASFileCache) {
    CASFileCache cfc = (CASFileCache) storage;
    final @Nullable UserPrincipal owner;
    if (!config.getExecOwner().isEmpty()) {
      try {
        owner =
            cfc.getRoot()
                .getFileSystem()
                .getUserPrincipalLookupService()
                .lookupPrincipalByName(config.getExecOwner());
      } catch (IOException e) {
        ConfigurationException configException =
            new ConfigurationException("Could not locate exec_owner");
        configException.initCause(e);
        throw configException;
      }
    } else {
      owner = null;
    }
    return createCFCExecFileSystem(removeDirectoryService, accessRecorder, cfc, owner);
  } else {
    // FIXME not the only fuse backing capacity...
    return createFuseExecFileSystem(remoteInputStreamFactory, storage);
  }
}
 
Example #30
Source File: Worker.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
private ExecFileSystem createCFCExecFileSystem(
    ExecutorService removeDirectoryService,
    ExecutorService accessRecorder,
    CASFileCache fileCache,
    @Nullable UserPrincipal owner) {
  return new CFCExecFileSystem(
      root,
      fileCache,
      owner,
      config.getLinkInputDirectories(),
      removeDirectoryService,
      accessRecorder,
      /* deadlineAfter=*/ 1,
      /* deadlineAfterUnits=*/ DAYS);
}