Java Code Examples for java.nio.file.attribute.GroupPrincipal

The following examples show how to use java.nio.file.attribute.GroupPrincipal. These examples are extracted from open source projects. 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   Source 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: ParallelGit   Source File: PosixFileAttributeViewTest.java    License: 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 3
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 4
@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 Project: ParallelGit   Source File: PosixFileAttributeViewTest.java    License: 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 6
Source Project: jimfs   Source File: PosixAttributeProvider.java    License: 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 7
Source Project: ats-framework   Source File: LocalFileSystemOperations.java    License: 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 8
@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 9
Source Project: sftp-fs   Source File: SFTPFileSystem.java    License: 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 10
Source Project: sftp-fs   Source File: SFTPFileSystem.java    License: 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 11
Source Project: vespa   Source File: UnixPath.java    License: 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 12
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 13
@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 14
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 15
Source Project: jsch-nio   Source File: UnixSshPosixFileAttributeView.java    License: 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 16
Source Project: jimfs   Source 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 17
Source Project: jimfs   Source 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 18
Source Project: jimfs   Source File: UserLookupService.java    License: 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 19
Source Project: logging-log4j2   Source File: FileUtils.java    License: 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 Project: uyuni   Source File: SaltService.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Map<Boolean, String> storeMinionScapFiles(
        MinionServer minion, String uploadDir, Long actionId) {
    String actionPath = ScapFileManager
            .getActionPath(minion.getOrg().getId(),
                    minion.getId(), actionId);
    Path mountPoint = Paths.get(com.redhat.rhn.common.conf.Config.get()
            .getString(ConfigDefaults.MOUNT_POINT));
    try {
        // create dirs
        Path actionDir = Files.createDirectories(mountPoint.resolve(actionPath));

        UserPrincipalLookupService lookupService = FileSystems.getDefault()
                .getUserPrincipalLookupService();
        GroupPrincipal susemanagerGroup = lookupService
                .lookupPrincipalByGroupName("susemanager");
        GroupPrincipal wwwGroup = lookupService
                .lookupPrincipalByGroupName("www");
        // systems/<orgId>/<serverId>/actions/<actionId>
        changeGroupAndPerms(actionDir, susemanagerGroup);
        // systems/<orgId>/<serverId>/actions
        actionDir = actionDir.getParent();
        while (!actionDir.equals(mountPoint)) {
            changeGroupAndPerms(actionDir, wwwGroup);
            actionDir = actionDir.getParent();
        }

    }
    catch (IOException e) {
        LOG.error("Error creating dir " + mountPoint.resolve(actionPath), e);
    }

    RunnerCall<Map<Boolean, String>> call = MgrUtilRunner.moveMinionUploadedFiles(
            minion.getMinionId(),
            uploadDir,
            com.redhat.rhn.common.conf.Config.get()
                    .getString(ConfigDefaults.MOUNT_POINT),
            actionPath);
    Optional<Map<Boolean, String>> result = callSync(call,
            err -> err.fold(
                    e -> {
                        LOG.error("Function [" + e.getFunctionName() +
                                " not available for runner call " +
                                "[mgrutil.move_minion_uploaded_files].");
                        return Optional.of(Collections.singletonMap(false,
                                "Function [" + e.getFunctionName()));
                    },
                    e -> {
                        LOG.error("Module [" + e.getModuleName() +
                                "] not supported for runner call " +
                                "[mgrutil.move_minion_uploaded_files].");
                        return Optional.of(Collections.singletonMap(false,
                                "Module [" + e.getModuleName() + "] not supported"));
                    },
                    e -> {
                        LOG.error("Error parsing json response from " +
                                "runner call [mgrutil.move_minion_uploaded_files]: " +
                                e.getJson());
                        return Optional.of(Collections.singletonMap(false,
                                "Error parsing json response: " + e.getJson()));
                    },
                    e -> {
                        LOG.error("Generic Salt error for runner call " +
                                "[mgrutil.move_minion_uploaded_files]: " +
                                e.getMessage());
                        return Optional.of(Collections.singletonMap(false,
                                "Generic Salt error: " + e.getMessage()));
                    }
            )
    );
    return result.orElseGet(() ->
            Collections.singletonMap(false, "Error moving scap result files." +
                    " Please check the logs.")
    );
}
 
Example 21
Source Project: cloud-search-samples   Source File: FilePermissionSample.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Sample for mapping permissions from a source repository to Cloud Search
 * ACLs. In this example, NFS file system ACls are used as the source
 * permissions.
 *
 * @return Acl
 * @throws IOException if unable to read file permissions
 */
// [START cloud_search_nfs_acl]
static Acl mapNfsAclToCloudSearchAcl(Path pathToFile) throws IOException {
  // Id of the identity source for external user/group IDs. Shown here,
  // but may be omitted in the SDK as it is automatically applied
  // based on the `api.identitySourceId` configuration parameter.
  String identitySourceId = "abcdef12345";

  // Retrieve the file system ACLs
  AclFileAttributeView aclView = Files.getFileAttributeView(
      pathToFile,
      AclFileAttributeView.class,
      LinkOption.NOFOLLOW_LINKS);

  if (aclView == null) {
    // Can't read, return empty ACl
    return new Acl.Builder().build();
  }

  // Owner, for search quality and owner: filters
  // Note that for principals the name is not the primary
  // email address in Cloud Directory, but the local ID defined
  // by the OS. Users and groups must be referred to by their
  // external ID and mapped via an identity source. The SDK
  // will automatically prepend the identity source prefix based on
  // the `api.identitySourceId` configuration parameter.
  List<Principal> owners = Collections.singletonList(
      Acl.getUserPrincipal(aclView.getOwner().getName(), identitySourceId)
  );
  // Principals allowed to access item
  List<Principal> allowedReaders = new ArrayList<>();
  // Principals denied access to item
  List<Principal> deniedReaders = new ArrayList<>();

  for(AclEntry entry: aclView.getAcl()) {
    UserPrincipal fsPrincipal = entry.principal();
    Principal cloudSearchPrincipal = fsPrincipal instanceof GroupPrincipal ?
        Acl.getGroupPrincipal(fsPrincipal.getName(), identitySourceId) :
        Acl.getUserPrincipal(fsPrincipal.getName(), identitySourceId);
    if (entry.type() == AclEntryType.ALLOW) {
      allowedReaders.add(cloudSearchPrincipal);
    } else if (entry.type() == AclEntryType.DENY) {
      deniedReaders.add(cloudSearchPrincipal);
    }
  }

  // Build the Cloud Search ACL. Note that inheritance of permissions
  // from parents is omitted. See `setInheritFrom()` and `setInheritanceType()`
  // methods on the builder if required by your implementation.
  return new Acl.Builder()
      .setReaders(allowedReaders)
      .setDeniedReaders(deniedReaders)
      .setOwners(owners)
      .build();
}
 
Example 22
Source Project: dremio-oss   Source File: FileStatusWrapper.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public GroupPrincipal group() {
  return group;
}
 
Example 23
Source Project: dremio-oss   Source File: HadoopFileStatusWrapper.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public GroupPrincipal group() {
  return group;
}
 
Example 24
Source Project: twill   Source File: LocalLocation.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void setGroup(String group) throws IOException {
  UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService();
  GroupPrincipal groupPrincipal = lookupService.lookupPrincipalByGroupName(group);
  Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class).setGroup(groupPrincipal);
}
 
Example 25
Source Project: sftp-fs   Source File: SFTPPath.java    License: Apache License 2.0 4 votes vote down vote up
void setGroup(GroupPrincipal group) throws IOException {
    fs.setGroup(this, group);
}
 
Example 26
Source Project: sftp-fs   Source File: SFTPFileSystem.java    License: Apache License 2.0 4 votes vote down vote up
void setGroup(SFTPPath path, GroupPrincipal group) throws IOException {
    setGroup(path, group, false);
}
 
Example 27
Source Project: sftp-fs   Source File: SFTPFileSystemProvider.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void setGroup(GroupPrincipal group) throws IOException {
    path.setGroup(group);
}
 
Example 28
@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 29
@Override
public GroupPrincipal lookupPrincipalByGroupName(String group)
    throws IOException {
  return new HadoopGroupPrincipal(this.hdfs, group);
}
 
Example 30
Source Project: jsr203-hadoop   Source File: HadoopPosixFileAttributes.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public GroupPrincipal group() {
  return group;
}