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

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

Introduction

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

Prototype

public abstract GroupPrincipal lookupPrincipalByGroupName(String group) throws IOException;

Source Link

Document

Lookup a group principal by group name.

Usage

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 www . ja  va2s .  c o m
    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// w  ww .j  a v a 2  s  .  c  om
    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)//www . ja  v  a 2s  . 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//from w w w.  j  a  va2  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();
        }
    }
}