Example usage for java.nio.file Files setOwner

List of usage examples for java.nio.file Files setOwner

Introduction

In this page you can find the example usage for java.nio.file Files setOwner.

Prototype

public static Path setOwner(Path path, UserPrincipal owner) throws IOException 

Source Link

Document

Updates the file owner.

Usage

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

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:RestoreService.java

public static void setAdvancedAttributes(final VOBackupFile voBackupFile, final File file) throws IOException {
    // advanced attributes
    // owner/*  w w  w . j  ava  2  s . co 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)/*w w w .  ja  v a2s.c o 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// ww w .jav a  2  s. c om
 */
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:ch.psi.zmq.receiver.FileReceiver.java

/**
 * Recursively create directories for given user
 * /*from ww  w  .j  av a2 s .  c o  m*/
 * @param f
 * @param user
 * @param perms
 * @throws IOException
 */
public void mkdir(File f, UserPrincipal user, GroupPrincipal group, Set<PosixFilePermission> perms)
        throws IOException {
    if (!f.getParentFile().exists()) {
        mkdir(f.getParentFile(), user, group, perms);
    }

    logger.info("Create directory: " + f.getPath());
    f.mkdir();
    Files.setOwner(f.toPath(), user);
    Files.getFileAttributeView(f.toPath(), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS)
            .setGroup(group);
    Files.setPosixFilePermissions(f.toPath(), perms);
}

From source file:configuration.Util.java

/**
 * Change owner of a directory//from w ww. j a v a2  s  .c o m
 * @param filepath
 * @return true if dir owner is changed
 */
public static boolean changeOwnerDir(String filepath) {
    Path jpath = Paths.get(currentPath());
    Path dpath = Paths.get(filepath);
    UserPrincipal owner;
    try {
        owner = Files.getOwner(jpath);
        Files.setOwner(dpath, owner);
        return true;
    } catch (IOException ex) {
        Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Directory Owner change Failed!");
        System.out.println(ex);
        return false;
    }
}

From source file:configuration.Util.java

/**
 * Change owner of a file//from  w  ww .  ja  v a2s  .c  o m
 * @param filepath
 * @return true if file is changed
 */
public static boolean changeOwnerFile(String filepath) {
    Path jpath = Paths.get(currentPath());
    Path fpath = Paths.get(filepath);
    UserPrincipal owner;
    try {
        owner = Files.getOwner(jpath);
        Files.setOwner(fpath, owner);
        return true;
    } catch (IOException ex) {
        Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("File Owner change Failed!");
        System.out.println(ex);
        return false;
    }
}