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 Project: jimfs   Author: google   File: UserLookupServiceTest.java    License: 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 Project: wildfly-core   Author: wildfly   File: FilePermissionTestCase.java    License: 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 #3
Source Project: uyuni   Author: uyuni-project   File: SaltActionChainGeneratorService.java    License: 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 #4
Source Project: jsr203-hadoop   Author: damiencarol   File: TestUserPrincipalLookupService.java    License: 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 #5
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: TestVMOptionsFile.java    License: 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 #6
Source Project: helm-maven-plugin   Author: kiwigrid   File: InitMojo.java    License: 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 #7
Source Project: bazel-buildfarm   Author: bazelbuild   File: CFCExecFileSystem.java    License: 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 #8
Source Project: hashicorp-vault-plugin   Author: jenkinsci   File: WindowsFilePermissionHelper.java    License: 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 #9
Source Project: git-client-plugin   Author: jenkinsci   File: CliGitAPIImpl.java    License: 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 #10
Source Project: dragonwell8_jdk   Author: alibaba   File: CheckLockLocationTest.java    License: 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 #11
Source Project: jsr203-hadoop   Author: damiencarol   File: TestUserPrincipalLookupService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Try to get user and set the same user in the root.
 * 
 * @throws IOException
 */
@Test
public void testGetSetUGI() throws IOException {
  Path rootPath = Paths.get(clusterUri);

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

  Files.setOwner(rootPath, user);
}
 
Example #12
Source Project: uyuni   Author: uyuni-project   File: SCCRefreshLock.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * tries to obtain the lock or throws an exception
 */
public static void tryGetLock() {
    try {
        f = new File(REFRESH_FILE_LOCKED_PATH);
        synchronized (f) {
            // create the lock file
            channel = new RandomAccessFile(f, "rw").getChannel();
            // create it with correct user
            FileSystem fileSystem = FileSystems.getDefault();
            UserPrincipalLookupService service = fileSystem.getUserPrincipalLookupService();
            UserPrincipal rootUser = service.lookupPrincipalByName("root");
            UserPrincipal tomcatUser = service.lookupPrincipalByName("tomcat");
            if (Files.getOwner(f.toPath(), LinkOption.NOFOLLOW_LINKS).equals(rootUser)) {
                Files.setOwner(f.toPath(), tomcatUser);
            }
            lock = channel.tryLock();
            if (lock == null) {
                // File is lock by other application
                channel.close();
                log.warn("SCC refresh is already running.");
                throw new OverlappingFileLockException();
            }
            log.info("Got the Lock for scc refresh");
            // Add on exit handler to release lock when application shutdown
            OnExitHandler onExitHandler = new OnExitHandler();
            Runtime.getRuntime().addShutdownHook(onExitHandler);
        }
    }
    catch (IOException e) {
        throw new RuntimeException("Could not start process.", e);
    }
}
 
Example #13
Source Project: uyuni   Author: uyuni-project   File: SaltServerActionService.java    License: 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 #14
Source Project: jdk8u60   Author: chenghanpeng   File: CheckLockLocationTest.java    License: 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 Project: cwlexec   Author: IBMSpectrumComputing   File: CWLParser.java    License: 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 #16
Source Project: ats-framework   Author: Axway   File: LocalFileSystemOperations.java    License: 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 #17
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: CheckLockLocationTest.java    License: 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 Project: yajsync   Author: perlundq   File: PosixFileAttributeManager.java    License: 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 #19
Source Project: jdk8u-jdk   Author: lambdalab-mirror   File: CheckLockLocationTest.java    License: 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 #20
Source Project: bazel-buildfarm   Author: bazelbuild   File: EvenMoreFiles.java    License: 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 #21
Source Project: jsr203-hadoop   Author: damiencarol   File: HadoopFileOwnerAttributeView.java    License: 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 #22
Source Project: bazel-buildfarm   Author: bazelbuild   File: Worker.java    License: 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 #23
Source Project: bazel-buildfarm   Author: bazelbuild   File: Worker.java    License: 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);
}
 
Example #24
Source Project: yajsync   Author: perlundq   File: UnixFileAttributeManager.java    License: 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 #25
Source Project: yajsync   Author: perlundq   File: UnixFileAttributeManager.java    License: 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 #26
Source Project: jsr203-hadoop   Author: damiencarol   File: TestFiles.java    License: 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 #27
Source Project: jimfs   Author: google   File: PosixAttributeProvider.java    License: 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 #28
Source Project: openjdk-8   Author: bpupadhyaya   File: CheckLockLocationTest.java    License: 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 #29
Source Project: jimfs   Author: google   File: UnixAttributeProvider.java    License: 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 #30
Source Project: jdk8u_jdk   Author: JetBrains   File: CheckLockLocationTest.java    License: 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();
}