Example usage for java.nio.file.attribute UserPrincipalLookupService lookupPrincipalByName

List of usage examples for java.nio.file.attribute UserPrincipalLookupService lookupPrincipalByName

Introduction

In this page you can find the example usage for java.nio.file.attribute UserPrincipalLookupService lookupPrincipalByName.

Prototype

public abstract UserPrincipal lookupPrincipalByName(String name) throws IOException;

Source Link

Document

Lookup a user principal by name.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {

    Path path = Paths.get("C:\\Java_Dev\\test1.txt");

    FileOwnerAttributeView foav = Files.getFileAttributeView(path, FileOwnerAttributeView.class);

    UserPrincipal owner = foav.getOwner();
    System.out.format("Original owner  of  %s  is %s%n", path, owner.getName());

    FileSystem fs = FileSystems.getDefault();
    UserPrincipalLookupService upls = fs.getUserPrincipalLookupService();

    UserPrincipal newOwner = upls.lookupPrincipalByName("brice");
    foav.setOwner(newOwner);//from  w  ww .j a  v a2  s .  c o m

    UserPrincipal changedOwner = foav.getOwner();
    System.out.format("New owner  of  %s  is %s%n", path, changedOwner.getName());

}

From source file:Test.java

public static void main(String[] args) throws Exception {
    Path path = Paths.get("C:/home/docs/users.txt");
    FileOwnerAttributeView view = Files.getFileAttributeView(path, FileOwnerAttributeView.class);
    UserPrincipal userPrincipal = view.getOwner();

    UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService();
    userPrincipal = lookupService.lookupPrincipalByName("users");
    view.setOwner(userPrincipal);/*from  w  w w .  ja va 2s.com*/
    System.out.println("UserPrincipal set: " + userPrincipal.getName());

}

From source file:Test.java

public static void main(String[] args) throws Exception {
    Path path = Paths.get("C:/home/docs/users.txt");
    FileOwnerAttributeView view = Files.getFileAttributeView(path, FileOwnerAttributeView.class);
    UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService();
    UserPrincipal userPrincipal = lookupService.lookupPrincipalByName("mary");

    view.setOwner(userPrincipal);//from www. ja v  a 2 s  .  c om
    System.out.println("Owner: " + view.getOwner().getName());
}

From source file:Test.java

public static void main(String[] args) throws Exception {
    Path path = Paths.get("C:/home/docs/users.txt");
    FileOwnerAttributeView view = Files.getFileAttributeView(path, FileOwnerAttributeView.class);
    UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService();
    UserPrincipal userPrincipal = lookupService.lookupPrincipalByName("mary");

    Files.setOwner(path, userPrincipal);
    System.out.println("Owner: " + view.getOwner().getName());

}

From source file:Main.java

public static void main(String[] args) throws IOException {
    UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService();
    Path path = Paths.get("c:/");
    Files.setOwner(path, lookupService.lookupPrincipalByName("joe"));
}

From source file:Test.java

private static void setGroupPrincipal(Path path, String userName, String groupName) throws Exception {
    System.out.println("Setting owner for " + path.getFileName());
    PosixFileAttributeView view = Files.getFileAttributeView(path, PosixFileAttributeView.class);

    PosixFileAttributes attributes = view.readAttributes();
    System.out.println("Old Group: " + attributes.group().getName());
    System.out.println("Old Owner: " + attributes.owner().getName());

    UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService();
    UserPrincipal userPrincipal = lookupService.lookupPrincipalByName(userName);
    GroupPrincipal groupPrincipal = lookupService.lookupPrincipalByGroupName(groupName);
    view.setGroup(groupPrincipal);//from  w w w . j a  v a2s. c  om
    view.setOwner(userPrincipal);

    attributes = view.readAttributes();
    System.out.println("New Group: " + attributes.group().getName());
    System.out.println("New Owner: " + attributes.owner().getName());
}

From source file:RestoreService.java

public static void setAdvancedAttributes(final VOBackupFile voBackupFile, final File file) throws IOException {
    // advanced attributes
    // owner//from  w  w  w.j a va 2 s  .c  o  m
    if (StringUtils.isNotBlank(voBackupFile.getOwner())) {
        try {
            UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService();
            UserPrincipal userPrincipal = lookupService.lookupPrincipalByName(voBackupFile.getOwner());
            Files.setOwner(file.toPath(), userPrincipal);
        } catch (UserPrincipalNotFoundException e) {
            logger.warn("Cannot set owner {}", voBackupFile.getOwner());
        }
    }
    if (Files.getFileStore(file.toPath()).supportsFileAttributeView(DosFileAttributeView.class)
            && BooleanUtils.isTrue(voBackupFile.getDosAttr())) {
        Files.setAttribute(file.toPath(), "dos:hidden", BooleanUtils.isTrue(voBackupFile.getDosHidden()));
        Files.setAttribute(file.toPath(), "dos:archive", BooleanUtils.isTrue(voBackupFile.getDosArchive()));
        Files.setAttribute(file.toPath(), "dos:readonly", BooleanUtils.isTrue(voBackupFile.getDosReadOnly()));
        Files.setAttribute(file.toPath(), "dos:system", BooleanUtils.isTrue(voBackupFile.getDosSystem()));
    }

    if (Files.getFileStore(file.toPath()).supportsFileAttributeView(PosixFileAttributeView.class)
            && BooleanUtils.isTrue(voBackupFile.getPosixAttr())) {
        try {
            UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService();
            GroupPrincipal groupPrincipal = lookupService
                    .lookupPrincipalByGroupName(voBackupFile.getPosixGroup());
            Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS)
                    .setGroup(groupPrincipal);
        } catch (UserPrincipalNotFoundException e) {
            logger.warn("Cannot set group {}", voBackupFile.getOwner());
        }

        if (StringUtils.isNotBlank(voBackupFile.getPosixPermitions())) {
            Set<PosixFilePermission> perms = PosixFilePermissions.fromString(voBackupFile.getPosixPermitions());
            Files.setPosixFilePermissions(file.toPath(), perms);
        }
    }
}

From source file:com.twosigma.beaker.core.rest.FileIORest.java

@POST
@Consumes("application/x-www-form-urlencoded")
@Path("setPosixFileOwnerAndPermissions")
@Produces(MediaType.TEXT_PLAIN)/*from www  .  java 2 s  . co m*/
public Response setPosixFilePermissions(@FormParam("path") String pathString, @FormParam("owner") String owner,
        @FormParam("group") String group, @FormParam("permissions[]") List<String> permissions)
        throws IOException {
    HashSet<PosixFilePermission> filePermissions = getPosixFilePermissions(permissions);
    try {
        java.nio.file.Path path = Paths.get(pathString);

        Files.setPosixFilePermissions(path, filePermissions);

        UserPrincipalLookupService userPrincipalLookupService = FileSystems.getDefault()
                .getUserPrincipalLookupService();
        if (StringUtils.isNoneBlank(owner)) {
            Files.setOwner(path, userPrincipalLookupService.lookupPrincipalByName(owner));
        }
        if (StringUtils.isNoneBlank(group)) {
            Files.getFileAttributeView(path, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS)
                    .setGroup(userPrincipalLookupService.lookupPrincipalByGroupName(group));
        }
        return status(OK).build();
    } catch (FileSystemException e) {
        return status(INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
}

From source file:ch.psi.zmq.receiver.FileReceiver.java

/**
 * Receive ZMQ messages with pilatus-1.0 header type and write the data part
 * to disk// www  .  j  a  va  2 s  .co  m
 */
public void receive(Integer numImages) {

    try {
        done = false;
        counter = 0;
        counterDropped = 0;
        receive = true;
        context = ZMQ.context(1);
        socket = context.socket(ZMQ.PULL);
        socket.connect("tcp://" + hostname + ":" + port);

        ObjectMapper mapper = new ObjectMapper();
        TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
        };
        String path = "";

        // User lookup service
        UserPrincipalLookupService lookupservice = FileSystems.getDefault().getUserPrincipalLookupService();

        Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_WRITE);
        perms.add(PosixFilePermission.GROUP_READ);
        perms.add(PosixFilePermission.GROUP_WRITE);

        while (receive) {
            try {
                byte[] message = socket.recv();
                byte[] content = null;
                if (socket.hasReceiveMore()) {
                    content = socket.recv();
                }
                logger.info("Message received: " + new String(message));

                Map<String, Object> h = mapper.readValue(message, typeRef);

                if (!"pilatus-1.0".equals(h.get("htype"))) {
                    logger.warning("Message type [" + h.get("htype") + "] not supported - ignore message");
                    continue;
                }

                String username = (String) h.get("username");

                // Save content to file (in basedir)
                String p = (String) h.get("path");
                if (!p.startsWith("/")) {
                    p = basedir + "/" + p;
                }
                File f = new File(p);
                // if(!f.exists()){
                if (!path.equals(p)) {
                    if (username == null) {
                        logger.info("Create directory " + p + "");
                        f.mkdirs();
                    } else {
                        logger.info("Create directory " + p + " for user " + username);
                        try {
                            Set<PosixFilePermission> permissions = new HashSet<PosixFilePermission>();
                            permissions.add(PosixFilePermission.OWNER_READ);
                            permissions.add(PosixFilePermission.OWNER_WRITE);
                            permissions.add(PosixFilePermission.OWNER_EXECUTE);
                            permissions.add(PosixFilePermission.GROUP_READ);
                            permissions.add(PosixFilePermission.GROUP_WRITE);
                            permissions.add(PosixFilePermission.GROUP_EXECUTE);
                            // username and groupname is the same by
                            // convention
                            mkdir(f, lookupservice.lookupPrincipalByName(username),
                                    lookupservice.lookupPrincipalByGroupName(username), permissions);
                        } catch (IOException e) {
                            throw new RuntimeException("Unable to create directory for user " + username + "",
                                    e);
                        }
                    }
                    path = p;
                }

                File file = new File(f, (String) h.get("filename"));
                logger.finest("Write to " + file.getAbsolutePath());

                try (FileOutputStream s = new FileOutputStream(file)) {
                    s.write(content);
                }

                if (username != null) {
                    Files.setOwner(file.toPath(), lookupservice.lookupPrincipalByName(username));
                    // username and groupname is the same by convention
                    Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class,
                            LinkOption.NOFOLLOW_LINKS)
                            .setGroup(lookupservice.lookupPrincipalByGroupName(username));
                    Files.setPosixFilePermissions(file.toPath(), perms);
                }

                counter++;
                if (numImages != null && numImages == counter) {
                    break;
                }
            } catch (IOException e) {
                logger.log(Level.SEVERE, "", e);
                counterDropped++;
            }
        }

    } catch (Exception e) {
        if (receive) {
            e.printStackTrace();
        }
    }
}

From source file:org.apache.rya.api.path.PathUtils.java

/**
 * Indicates whether file lives in a secure directory relative to the
 * program's user./*from w ww. j  av a 2s.  c  o  m*/
 * @param file {@link Path} to test.
 * @param user {@link UserPrincipal} to test. If {@code null}, defaults to
 * current user.
 * @param symlinkDepth Number of symbolic links allowed.
 * @return {@code true} if file's directory is secure.
 */
public static boolean isInSecureDir(Path file, UserPrincipal user, final int symlinkDepth) {
    if (!file.isAbsolute()) {
        file = file.toAbsolutePath();
    }
    if (symlinkDepth <= 0) {
        // Too many levels of symbolic links
        return false;
    }
    // Get UserPrincipal for specified user and superuser
    final Path fileRoot = file.getRoot();
    if (fileRoot == null) {
        return false;
    }
    final FileSystem fileSystem = Paths.get(fileRoot.toString()).getFileSystem();
    final UserPrincipalLookupService upls = fileSystem.getUserPrincipalLookupService();
    UserPrincipal root = null;
    try {
        if (SystemUtils.IS_OS_UNIX) {
            root = upls.lookupPrincipalByName("root");
        } else {
            root = upls.lookupPrincipalByName("Administrators");
        }
        if (user == null) {
            user = upls.lookupPrincipalByName(System.getProperty("user.name"));
        }
        if (root == null || user == null) {
            return false;
        }
    } catch (final IOException x) {
        return false;
    }
    // If any parent dirs (from root on down) are not secure, dir is not secure
    for (int i = 1; i <= file.getNameCount(); i++) {
        final Path partialPath = Paths.get(fileRoot.toString(), file.subpath(0, i).toString());
        try {
            if (Files.isSymbolicLink(partialPath)) {
                if (!isInSecureDir(Files.readSymbolicLink(partialPath), user, symlinkDepth - 1)) {
                    // Symbolic link, linked-to dir not secure
                    return false;
                }
            } else {
                final UserPrincipal owner = Files.getOwner(partialPath);
                if (!user.equals(owner) && !root.equals(owner)) {
                    // dir owned by someone else, not secure
                    return SystemUtils.IS_OS_UNIX ? false : Files.isWritable(partialPath);
                }
            }
        } catch (final IOException x) {
            return false;
        }
    }
    return true;
}