java.nio.file.attribute.GroupPrincipal Java Examples

The following examples show how to use java.nio.file.attribute.GroupPrincipal. 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: PosixAttributeProvider.java    From jimfs with Apache License 2.0 6 votes vote down vote up
@Override
public void set(File file, String view, String attribute, Object value, boolean create) {
  switch (attribute) {
    case "group":
      checkNotCreate(view, attribute, create);

      GroupPrincipal group = checkType(view, attribute, value, GroupPrincipal.class);
      if (!(group instanceof UserLookupService.JimfsGroupPrincipal)) {
        group = createGroupPrincipal(group.getName());
      }
      file.setAttribute("posix", "group", group);
      break;
    case "permissions":
      file.setAttribute(
          "posix", "permissions", toPermissions(checkType(view, attribute, value, Set.class)));
      break;
    default:
  }
}
 
Example #3
Source File: PosixFileAttributeViewTest.java    From ParallelGit with Apache License 2.0 6 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void setGroupOfFile_shouldThrowUnsupportedOperationException() throws IOException {
  writeToCache("/file.txt");
  commitToMaster();
  initGitFileSystem();

  GfsFileAttributeView.Posix view = provider.getFileAttributeView(gfs.getPath("/file.txt"), GfsFileAttributeView.Posix.class);
  assertNotNull(view);
  view.setGroup(new GroupPrincipal() {
    @Nonnull
    @Override
    public String getName() {
      return "some_group";
    }
  });
}
 
Example #4
Source File: PosixFileAttributeManager.java    From yajsync with GNU General Public License v3.0 6 votes vote down vote up
@Override
public RsyncFileAttributes stat(Path path) throws IOException
{
    PosixFileAttributes attrs = Files.readAttributes(path, PosixFileAttributes.class,
                                                     LinkOption.NOFOLLOW_LINKS);
    UserPrincipal userPrincipal = attrs.owner();
    String userName = userPrincipal.getName();
    GroupPrincipal groupPrincipal = attrs.group();
    String groupName = groupPrincipal.getName();
    _nameToUserPrincipal.putIfAbsent(userName, userPrincipal);
    _nameToGroupPrincipal.putIfAbsent(groupName, groupPrincipal);
    return new RsyncFileAttributes(toMode(attrs),
                                   attrs.size(),
                                   attrs.lastModifiedTime().to(TimeUnit.SECONDS),
                                   new User(userName, _defaultUserId),
                                   new Group(groupName, _defaultGroupId));
}
 
Example #5
Source File: UnixFileAttributeManager.java    From yajsync with GNU General Public License v3.0 6 votes vote down vote up
private RsyncFileAttributes fullStat(Path path) throws IOException
{
    String toStat = "unix:mode,lastModifiedTime,size,uid,gid,owner,group";
    Map<String, Object> attrs = Files.readAttributes(path, toStat, LinkOption.NOFOLLOW_LINKS);
    int mode = (int) attrs.get("mode");
    long mtime = ((FileTime) attrs.get("lastModifiedTime")).to(TimeUnit.SECONDS);
    long size = (long) attrs.get("size");
    int uid = (int) attrs.get("uid");
    int gid = (int) attrs.get("gid");
    String userName = ((UserPrincipal ) attrs.get("owner")).getName();
    String groupName = ((GroupPrincipal) attrs.get("group")).getName();
    User user = new User(userName, uid);
    Group group = new Group(groupName, gid);

    return new RsyncFileAttributes(mode, size, mtime, user, group);
}
 
Example #6
Source File: PosixFileAttributeViewTest.java    From ParallelGit with Apache License 2.0 6 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void setGroupOfFile_shouldThrowUnsupportedOperationException() throws IOException {
  writeToCache("/file.txt");
  commitToMaster();
  initGitFileSystem();

  GfsFileAttributeView.Posix view = provider.getFileAttributeView(gfs.getPath("/file.txt"), GfsFileAttributeView.Posix.class);
  assertNotNull(view);
  view.setGroup(new GroupPrincipal() {
    @Nonnull
    @Override
    public String getName() {
      return "some_group";
    }
  });
}
 
Example #7
Source File: UnixPath.java    From vespa with Apache License 2.0 5 votes vote down vote up
public UnixPath setGroup(String group) {
    UserPrincipalLookupService service = path.getFileSystem().getUserPrincipalLookupService();
    GroupPrincipal principal = uncheck(
            () -> service.lookupPrincipalByGroupName(group),
            "while looking up group %s", group);
    uncheck(() -> Files.getFileAttributeView(path, PosixFileAttributeView.class).setGroup(principal));
    return this;
}
 
Example #8
Source File: UnixSshPosixFileAttributeView.java    From jsch-nio with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
void setAttribute( String attributeName, Object value ) throws IOException {
    if ( attributeName.equals( "group" ) ) {
        setGroup( (GroupPrincipal)value );
    }
    else if ( attributeName.equals( "owner" ) ) {
        setOwner( (UserPrincipal)value );
    }
    else if ( attributeName.equals( "permissions" ) ) {
        setPermissions( (Set<PosixFilePermission>)value );
    }
    else {
        super.setAttribute( attributeName, value );
    }
}
 
Example #9
Source File: PosixFileAttributeManager.java    From yajsync with GNU General Public License v3.0 5 votes vote down vote up
private GroupPrincipal getGroupPrincipalFrom(String groupName) throws IOException
{
    try {
        GroupPrincipal principal = _nameToGroupPrincipal.get(groupName);
        if (principal == null) {
            UserPrincipalLookupService service =
                    FileSystems.getDefault().getUserPrincipalLookupService();
            principal = service.lookupPrincipalByGroupName(groupName);
            _nameToGroupPrincipal.put(groupName, principal);
        }
        return principal;
    } catch (UnsupportedOperationException e) {
        throw new IOException(e);
    }
}
 
Example #10
Source File: UnixFileAttributeManager.java    From yajsync with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setGroup(Path path, Group group, LinkOption... linkOption) throws IOException
{
    GroupPrincipal principal = getGroupPrincipalFrom(group.name());
    if (principal == null) {
        setGroupId(path, group.id(), linkOption);
    }
    Files.setAttribute(path, "unix:group", principal, linkOption);
}
 
Example #11
Source File: UnixFileAttributeManager.java    From yajsync with GNU General Public License v3.0 5 votes vote down vote up
private GroupPrincipal getGroupPrincipalFrom(String groupName) throws IOException
{
    try {
        if (_isCacheEnabled) {
            return _nameToGroupPrincipal.get(groupName);
        }
        UserPrincipalLookupService service =
                FileSystems.getDefault().getUserPrincipalLookupService();
        return service.lookupPrincipalByGroupName(groupName);
    } catch (IOException | UnsupportedOperationException e) {
        return null;
    }
}
 
Example #12
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 #13
Source File: SFTPFileSystem.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
void setAttribute(SFTPPath path, String attribute, Object value, LinkOption... options) throws IOException {
    String view;
    int pos = attribute.indexOf(':');
    if (pos == -1) {
        view = "basic"; //$NON-NLS-1$
        attribute = "basic:" + attribute; //$NON-NLS-1$
    } else {
        view = attribute.substring(0, pos);
    }
    if (!"basic".equals(view) && !"owner".equals(view) && !"posix".equals(view)) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        throw Messages.fileSystemProvider().unsupportedFileAttributeView(view);
    }

    boolean followLinks = LinkOptionSupport.followLinks(options);

    switch (attribute) {
    case "basic:lastModifiedTime": //$NON-NLS-1$
    case "posix:lastModifiedTime": //$NON-NLS-1$
        setLastModifiedTime(path, (FileTime) value, followLinks);
        break;
    case "owner:owner": //$NON-NLS-1$
    case "posix:owner": //$NON-NLS-1$
        setOwner(path, (UserPrincipal) value, followLinks);
        break;
    case "posix:group": //$NON-NLS-1$
        setGroup(path, (GroupPrincipal) value, followLinks);
        break;
    case "posix:permissions": //$NON-NLS-1$
        @SuppressWarnings("unchecked")
        Set<PosixFilePermission> permissions = (Set<PosixFilePermission>) value;
        setPermissions(path, permissions, followLinks);
        break;
    default:
        throw Messages.fileSystemProvider().unsupportedFileAttribute(attribute);
    }
}
 
Example #14
Source File: SFTPFileSystem.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
private void setGroup(SFTPPath path, GroupPrincipal group, boolean followLinks) throws IOException {
    try {
        int gid = Integer.parseInt(group.getName());
        try (Channel channel = channelPool.get()) {
            if (followLinks) {
                path = toRealPath(channel, path, followLinks).path;
            }
            channel.chgrp(path.path(), gid);
        }
    } catch (NumberFormatException e) {
        throw new IOException(e);
    }
}
 
Example #15
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 #16
Source File: UserLookupService.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@Override
public GroupPrincipal lookupPrincipalByGroupName(String group) throws IOException {
  if (!supportsGroups) {
    throw new UserPrincipalNotFoundException(group); // required by spec
  }
  return createGroupPrincipal(group);
}
 
Example #17
Source File: LocalUnixPermissionFeature.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setUnixGroup(final Path file, final String group) throws BackgroundException {
    try {
        final GroupPrincipal principal = session.getClient().getUserPrincipalLookupService().lookupPrincipalByGroupName(group);
        Files.getFileAttributeView(session.toPath(file),
            PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS).setGroup(principal);
    }
    catch(IOException e) {
        throw new LocalExceptionMappingService().map("Failure to write attributes of {0}", e, file);
    }
}
 
Example #18
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 group name
 * @throws FileSystemOperationException
 */
private String getGroup(
        String filename ) {

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

    } catch (Exception e) {
        throw new FileSystemOperationException("Could not get group for '" + filename + "'", e);
    }
}
 
Example #19
Source File: FileUtils.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Define file posix attribute view on a path/file.
 *
 * @param path Target path
 * @param filePermissions Permissions to apply
 * @param fileOwner File owner
 * @param fileGroup File group
 * @throws IOException If IO error during definition of file attribute view
 */
public static void defineFilePosixAttributeView(final Path path,
        final Set<PosixFilePermission> filePermissions,
        final String fileOwner,
        final String fileGroup) throws IOException {
    final PosixFileAttributeView view = Files.getFileAttributeView(path, PosixFileAttributeView.class);
    if (view != null) {
        final UserPrincipalLookupService lookupService = FileSystems.getDefault()
                .getUserPrincipalLookupService();
        if (fileOwner != null) {
            final UserPrincipal userPrincipal = lookupService.lookupPrincipalByName(fileOwner);
            if (userPrincipal != null) {
                // If not sudoers member, it will throw Operation not permitted
                // Only processes with an effective user ID equal to the user ID
                // of the file or with appropriate privileges may change the ownership of a file.
                // If _POSIX_CHOWN_RESTRICTED is in effect for path
                view.setOwner(userPrincipal);
            }
        }
        if (fileGroup != null) {
            final GroupPrincipal groupPrincipal = lookupService.lookupPrincipalByGroupName(fileGroup);
            if (groupPrincipal != null) {
                // The current user id should be members of this group,
                // if not will raise Operation not permitted
                view.setGroup(groupPrincipal);
            }
        }
        if (filePermissions != null) {
            view.setPermissions(filePermissions);
        }
    }
}
 
Example #20
Source File: PosixFileAttributeManager.java    From yajsync with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void setGroup(Path path, Group group, LinkOption... linkOption) throws IOException
{
    GroupPrincipal principal = getGroupPrincipalFrom(group.name());
    Files.setAttribute(path, "posix:group", principal, linkOption);
}
 
Example #21
Source File: PosixAttributeProvider.java    From jimfs with Apache License 2.0 4 votes vote down vote up
@Override
public GroupPrincipal group() {
  return group;
}
 
Example #22
Source File: UserLookupService.java    From jimfs with Apache License 2.0 4 votes vote down vote up
/** Creates a {@link GroupPrincipal} for the given group name. */
static GroupPrincipal createGroupPrincipal(String name) {
  return new JimfsGroupPrincipal(name);
}
 
Example #23
Source File: PosixAttributeProvider.java    From jimfs with Apache License 2.0 4 votes vote down vote up
@Override
public void setGroup(GroupPrincipal group) throws IOException {
  lookupFile().setAttribute("posix", "group", checkNotNull(group));
}
 
Example #24
Source File: PosixAttributeProvider.java    From jimfs with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public ImmutableMap<String, ?> defaultValues(Map<String, ?> userProvidedDefaults) {
  Object userProvidedGroup = userProvidedDefaults.get("posix:group");

  UserPrincipal group = DEFAULT_GROUP;
  if (userProvidedGroup != null) {
    if (userProvidedGroup instanceof String) {
      group = createGroupPrincipal((String) userProvidedGroup);
    } else {
      throw new IllegalArgumentException(
          "invalid type "
              + userProvidedGroup.getClass().getName()
              + " for attribute 'posix:group': should be one of "
              + String.class
              + " or "
              + GroupPrincipal.class);
    }
  }

  Object userProvidedPermissions = userProvidedDefaults.get("posix:permissions");

  Set<PosixFilePermission> permissions = DEFAULT_PERMISSIONS;
  if (userProvidedPermissions != null) {
    if (userProvidedPermissions instanceof String) {
      permissions =
          Sets.immutableEnumSet(
              PosixFilePermissions.fromString((String) userProvidedPermissions));
    } else if (userProvidedPermissions instanceof Set) {
      permissions = toPermissions((Set<?>) userProvidedPermissions);
    } else {
      throw new IllegalArgumentException(
          "invalid type "
              + userProvidedPermissions.getClass().getName()
              + " for attribute 'posix:permissions': should be one of "
              + String.class
              + " or "
              + Set.class);
    }
  }

  return ImmutableMap.of(
      "posix:group", group,
      "posix:permissions", permissions);
}
 
Example #25
Source File: UnixSshPosixFileAttributeView.java    From jsch-nio with MIT License 4 votes vote down vote up
@Override
public void setGroup( GroupPrincipal group ) throws IOException {
    getPath().getFileSystem().provider().setGroup( getPath(), group );
}
 
Example #26
Source File: UnixSshFileSystemProvider.java    From jsch-nio with MIT License 4 votes vote down vote up
public GroupPrincipal group() {
    return (GroupPrincipal)map.get( SupportedAttribute.group.toString() );
}
 
Example #27
Source File: UnixSshFileSystemProvider.java    From jsch-nio with MIT License 4 votes vote down vote up
void setGroup( UnixSshPath path, GroupPrincipal group ) throws IOException {
    String command = path.getFileSystem().getCommand( "chgrp" )
            + " " + group.getName() + " " + path.toAbsolutePath().quotedString();
    executeForStdout( path, command );
}
 
Example #28
Source File: HadoopPosixFileAttributeView.java    From jsr203-hadoop with Apache License 2.0 4 votes vote down vote up
@Override
public void setGroup(GroupPrincipal group) throws IOException {
  FileSystem fs = path.getFileSystem().getHDFS();
  fs.setOwner(path.getRawResolvedPath(), null, group.getName());
}
 
Example #29
Source File: HadoopPosixFileAttributes.java    From jsr203-hadoop with Apache License 2.0 4 votes vote down vote up
@Override
public GroupPrincipal group() {
  return group;
}
 
Example #30
Source File: HadoopUserPrincipalLookupService.java    From jsr203-hadoop with Apache License 2.0 4 votes vote down vote up
@Override
public GroupPrincipal lookupPrincipalByGroupName(String group)
    throws IOException {
  return new HadoopGroupPrincipal(this.hdfs, group);
}