Java Code Examples for java.nio.file.Files#setOwner()

The following examples show how to use java.nio.file.Files#setOwner() . 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
/**
 * Make sure the {@literal actionchains} subdir exists.
 * @return the {@link Path} of the {@literal} actionchains directory
 */
private Path createActionChainsDir() {
    Path targetDir = getTargetDir();
    if (!Files.exists(targetDir)) {
        try {
            Files.createDirectories(targetDir);
            if (!skipSetOwner) {
                FileSystem fileSystem = FileSystems.getDefault();
                UserPrincipalLookupService service = fileSystem.getUserPrincipalLookupService();
                UserPrincipal tomcatUser = service.lookupPrincipalByName("tomcat");
                Files.setOwner(targetDir, tomcatUser);
            }
        }
        catch (IOException e) {
            LOG.error("Could not create action chain directory " + targetDir, e);
            throw new RuntimeException(e);
        }
    }
    return targetDir;
}
 
Example 2
/** This method changes the ownership of folder/file to the user provided
 * @param destinationLocation : the location of the path to be owned
 * @param user : the user which needs to own the folder/file
 */
private void changeOwnership(String destinationLocation, String user){
	
	Path path = Paths.get(destinationLocation);
    FileOwnerAttributeView view = Files.getFileAttributeView(path,
        FileOwnerAttributeView.class);
    UserPrincipalLookupService lookupService = FileSystems.getDefault()
        .getUserPrincipalLookupService();
    UserPrincipal userPrincipal;
	try {
		userPrincipal = lookupService.lookupPrincipalByName(user);
		Files.setOwner(path, userPrincipal);
	} catch (IOException e) {
		LOGGER.error("Error while changing ownership of destination location[" + destinationLocation +"]" + "to user[" + user + "]" , e);
	}
}
 
Example 3
/**
 * tries to obtain the lock or throws an exception
 */
public static void tryGetLock() {
    try {
        f = new File(REFRESH_FILE_LOCKED_PATH);
        synchronized (f) {
            // create the lock file
            channel = new RandomAccessFile(f, "rw").getChannel();
            // create it with correct user
            FileSystem fileSystem = FileSystems.getDefault();
            UserPrincipalLookupService service = fileSystem.getUserPrincipalLookupService();
            UserPrincipal rootUser = service.lookupPrincipalByName("root");
            UserPrincipal tomcatUser = service.lookupPrincipalByName("tomcat");
            if (Files.getOwner(f.toPath(), LinkOption.NOFOLLOW_LINKS).equals(rootUser)) {
                Files.setOwner(f.toPath(), tomcatUser);
            }
            lock = channel.tryLock();
            if (lock == null) {
                // File is lock by other application
                channel.close();
                log.warn("SCC refresh is already running.");
                throw new OverlappingFileLockException();
            }
            log.info("Got the Lock for scc refresh");
            // Add on exit handler to release lock when application shutdown
            OnExitHandler onExitHandler = new OnExitHandler();
            Runtime.getRuntime().addShutdownHook(onExitHandler);
        }
    }
    catch (IOException e) {
        throw new RuntimeException("Could not start process.", e);
    }
}
 
Example 4
private void setFileOwner(Path path) throws IOException {
    FileSystem fileSystem = FileSystems.getDefault();
    UserPrincipalLookupService service = fileSystem.getUserPrincipalLookupService();
    UserPrincipal tomcatUser = service.lookupPrincipalByName("tomcat");

    Files.setOwner(path, tomcatUser);
}
 
Example 5
@Override
public void setUnixOwner(final Path file, final String owner) throws BackgroundException {
    try {
        final UserPrincipal principal = session.getClient().getUserPrincipalLookupService().lookupPrincipalByName(owner);
        Files.setOwner(session.toPath(file), principal);
    }
    catch(IOException e) {
        throw new LocalExceptionMappingService().map("Failure to write attributes of {0}", e, file);
    }
}
 
Example 6
Source Project: athenz   File: PolicyUpdater.java    License: Apache License 2.0 5 votes vote down vote up
static void verifyTmpDirSetup(PolicyUpdaterConfiguration configuration) throws IOException {
    // ensure tmp dir exists
    String policyTmpDir = configuration.getPolicyFileTmpDir();
    Path tmpDir = Paths.get(policyTmpDir);
    if (java.nio.file.Files.exists(tmpDir)) {
        return;
    }

    LOG.warn("The temp dir doesnt exist so will create it: " + tmpDir);
    java.nio.file.Files.createDirectory(tmpDir);

    // get the user from config file to perform chown aginst the tmp dir
    // chown -R $zpu_user $ROOT/tmp/zpe
    String user = configuration.getZpuDirOwner();
    if (user == null) {
        LOG.warn("Cannot chown of the temp dir: " + tmpDir + " : no configured user");
        return;
    }

    try {
        java.nio.file.attribute.UserPrincipalLookupService lookupSvc =
            java.nio.file.FileSystems.getDefault().getUserPrincipalLookupService();
        java.nio.file.attribute.UserPrincipal uprinc = lookupSvc.lookupPrincipalByName(user);
        Files.setOwner(tmpDir, uprinc);
    } catch (Exception exc) {
        LOG.warn("Failed to chown of the temp dir: " + tmpDir
                + ", user: " + user + ", exc: " + exc.getMessage());
    }
}
 
Example 7
public void change(Event e, Object[] delta, Changer.ChangeMode mode) {
  if (mode == Changer.ChangeMode.SET) {
    Path pth = Paths.get(skUtilities.getDefaultPath(path.getSingle(e)));
    try {
      UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService();
      Files.setOwner(pth, lookupService.lookupPrincipalByName((String) delta[0]));
    } catch (Exception x) {
      skUtilities.prSysE("File: '" + pth + "' doesn't exist, or is not readable!", getClass().getSimpleName(), x);
    }
  }
}
 
Example 8
/**
 * Try to get user and set the same user in the root.
 * 
 * @throws IOException
 */
@Test
public void testGetSetUGI() throws IOException {
  Path rootPath = Paths.get(clusterUri);

  UserPrincipal user = Files.getOwner(rootPath);
  assertNotNull(user);

  Files.setOwner(rootPath, user);
}
 
Example 9
@Test
public void testCopy_toDifferentFileSystem_copyAttributes() throws IOException {
  try (FileSystem fs2 = Jimfs.newFileSystem(UNIX_CONFIGURATION)) {
    Path foo = fs.getPath("/foo");
    byte[] bytes = {0, 1, 2, 3, 4};
    Files.write(foo, bytes);
    Files.getFileAttributeView(foo, BasicFileAttributeView.class)
        .setTimes(FileTime.fromMillis(0), FileTime.fromMillis(1), FileTime.fromMillis(2));

    UserPrincipal owner = fs.getUserPrincipalLookupService().lookupPrincipalByName("foobar");
    Files.setOwner(foo, owner);

    assertThatPath(foo).attribute("owner:owner").is(owner);

    Path foo2 = fs2.getPath("/foo");
    Files.copy(foo, foo2, COPY_ATTRIBUTES);

    assertThatPath(foo).exists();

    // when copying with COPY_ATTRIBUTES to a different FileSystem, only basic attributes (that
    // is, file times) can actually be copied
    assertThatPath(foo2)
        .exists()
        .and()
        .attribute("lastModifiedTime")
        .is(FileTime.fromMillis(0))
        .and()
        .attribute("lastAccessTime")
        .is(FileTime.fromMillis(1))
        .and()
        .attribute("creationTime")
        .is(FileTime.fromMillis(2))
        .and()
        .attribute("owner:owner")
        .isNot(owner)
        .and()
        .attribute("owner:owner")
        .isNot(fs2.getUserPrincipalLookupService().lookupPrincipalByName("foobar"))
        .and()
        .containsBytes(bytes); // do this last; it updates the access time
  }
}