下面列出了怎么用java.nio.file.attribute.UserPrincipal的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
@Test
public void testDefaultOwnership() throws Exception {
// This is unix test only
if (!Util.isWindows()) {
CommandContext ctx = CLITestUtil.getCommandContext(TestSuiteEnvironment.getServerAddress(),
TestSuiteEnvironment.getServerPort(), System.in, System.out);
String tmpFile = "tmpFile";
Path path = Paths.get(tmpFile);
try {
ctx.handle("echo \"aaa\" >> " + tmpFile);
UserPrincipal userPrincipal = Files.getOwner(path);
assertThat("The test file has unexpected ownership: " + userPrincipal.toString(),
userPrincipal.toString(), CoreMatchers.is(CoreMatchers.equalTo(System.getProperty("user.name"))));
} finally {
ctx.terminateSession();
Files.delete(path);
}
}
}
/**
* 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;
}
@Test
public void testUsersEquals() throws IOException {
Path rootPath = Paths.get(clusterUri);
UserPrincipal user = Files.getOwner(rootPath);
assertNotNull(user);
// Get the same user
UserPrincipal user2 = Files.getOwner(rootPath);
assertNotNull(user2);
Assert.assertTrue(user.equals(user));
Assert.assertTrue(user.equals(user2) && user2.equals(user));
Assert.assertFalse(user.equals(null));
Assert.assertFalse(user.equals(new Double(-1)));
UserPrincipal userTest = rootPath.getFileSystem()
.getUserPrincipalLookupService().lookupPrincipalByName("test");
Assert.assertFalse(user.equals(userTest));
}
private static void makeFileNonReadable(String file) throws IOException {
Path filePath = Paths.get(file);
Set<String> supportedAttr = filePath.getFileSystem().supportedFileAttributeViews();
if (supportedAttr.contains("posix")) {
Files.setPosixFilePermissions(filePath, PosixFilePermissions.fromString("-w--w----"));
} else if (supportedAttr.contains("acl")) {
UserPrincipal fileOwner = Files.getOwner(filePath);
AclFileAttributeView view = Files.getFileAttributeView(filePath, AclFileAttributeView.class);
AclEntry entry = AclEntry.newBuilder()
.setType(AclEntryType.DENY)
.setPrincipal(fileOwner)
.setPermissions(AclEntryPermission.READ_DATA)
.build();
List<AclEntry> acl = view.getAcl();
acl.add(0, entry);
view.setAcl(acl);
}
}
private void addExecPermission(final Path helm) throws IOException {
Set<String> fileAttributeView = FileSystems.getDefault().supportedFileAttributeViews();
if (fileAttributeView.contains("posix")) {
final Set<PosixFilePermission> permissions;
try {
permissions = Files.getPosixFilePermissions(helm);
} catch (UnsupportedOperationException e) {
getLog().debug("Exec file permission is not set", e);
return;
}
permissions.add(PosixFilePermission.OWNER_EXECUTE);
Files.setPosixFilePermissions(helm, permissions);
} else if (fileAttributeView.contains("acl")) {
String username = System.getProperty("user.name");
UserPrincipal userPrincipal = FileSystems.getDefault().getUserPrincipalLookupService().lookupPrincipalByName(username);
AclEntry aclEntry = AclEntry.newBuilder().setPermissions(AclEntryPermission.EXECUTE).setType(AclEntryType.ALLOW).setPrincipal(userPrincipal).build();
AclFileAttributeView acl = Files.getFileAttributeView(helm, AclFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
List<AclEntry> aclEntries = acl.getAcl();
aclEntries.add(aclEntry);
acl.setAcl(aclEntries);
}
}
CFCExecFileSystem(
Path root,
CASFileCache fileCache,
@Nullable UserPrincipal owner,
boolean linkInputDirectories,
ExecutorService removeDirectoryService,
ExecutorService accessRecorder,
long deadlineAfter,
TimeUnit deadlineAfterUnits) {
this.root = root;
this.fileCache = fileCache;
this.owner = owner;
this.linkInputDirectories = linkInputDirectories;
this.removeDirectoryService = removeDirectoryService;
this.accessRecorder = accessRecorder;
this.deadlineAfter = deadlineAfter;
this.deadlineAfterUnits = deadlineAfterUnits;
}
public static void fixSshKeyOnWindows(Path file) {
AclFileAttributeView fileAttributeView = Files
.getFileAttributeView(file, AclFileAttributeView.class);
if (fileAttributeView == null) return;
try {
UserPrincipal userPrincipal = fileAttributeView.getOwner();
AclEntry aclEntry = AclEntry.newBuilder()
.setType(AclEntryType.ALLOW)
.setPrincipal(userPrincipal)
.setPermissions(ACL_ENTRY_PERMISSIONS)
.build();
fileAttributeView.setAcl(Collections.singletonList(aclEntry));
} catch (IOException | UnsupportedOperationException e) {
throw new IllegalStateException("Error updating file permission for \"" + file + "\"", e);
}
}
void fixSshKeyOnWindows(File key) throws GitException {
if (launcher.isUnix()) return;
Path file = Paths.get(key.toURI());
AclFileAttributeView fileAttributeView = Files.getFileAttributeView(file, AclFileAttributeView.class);
if (fileAttributeView == null) return;
try {
UserPrincipal userPrincipal = fileAttributeView.getOwner();
AclEntry aclEntry = AclEntry.newBuilder()
.setType(AclEntryType.ALLOW)
.setPrincipal(userPrincipal)
.setPermissions(ACL_ENTRY_PERMISSIONS)
.build();
fileAttributeView.setAcl(Collections.singletonList(aclEntry));
} catch (IOException | UnsupportedOperationException e) {
throw new GitException("Error updating file permission for \"" + key.getAbsolutePath() + "\"", e);
}
}
private static String getOwner(Path path) {
UserPrincipal user = null;
try {
user = Files.getOwner(path);
} catch (Exception x) {
System.err.println("Failed to get owner of: " + path);
System.err.println("\terror is: " + x);
}
return user == null ? "???" : user.getName();
}
/**
* 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);
}
/**
* 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);
}
}
private void setFileOwner(Path path) throws IOException {
FileSystem fileSystem = FileSystems.getDefault();
UserPrincipalLookupService service = fileSystem.getUserPrincipalLookupService();
UserPrincipal tomcatUser = service.lookupPrincipalByName("tomcat");
Files.setOwner(path, tomcatUser);
}
private static String getOwner(Path path) {
UserPrincipal user = null;
try {
user = Files.getOwner(path);
} catch (Exception x) {
System.err.println("Failed to get owner of: " + path);
System.err.println("\terror is: " + x);
}
return user == null ? "???" : user.getName();
}
private static String getFileOwner(File file) {
String owner = null;
if (file != null) {
Path path = Paths.get(file.getAbsolutePath());
try {
UserPrincipal user = Files.getFileAttributeView(path, FileOwnerAttributeView.class).getOwner();
return user.getName();
} catch (IOException e) {
logger.warn("Fail to get the owner of {}, ({})", path, e.getMessage());
}
}
return owner;
}
/**
*
* @param filename the file name
* @return the file owner
* @throws FileSystemOperationException
*/
private String getOwner(
String filename ) {
try {
UserPrincipal owner = Files.readAttributes(new File(filename).toPath(),
PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS)
.owner();
return owner.getName();
} catch (Exception e) {
throw new FileSystemOperationException("Could not get owner for '" + filename + "'", e);
}
}
private static String getOwner(Path path) {
UserPrincipal user = null;
try {
user = Files.getOwner(path);
} catch (Exception x) {
System.err.println("Failed to get owner of: " + path);
System.err.println("\terror is: " + x);
}
return user == null ? "???" : user.getName();
}
private UserPrincipal getUserPrincipalFrom(String userName) throws IOException
{
try {
UserPrincipal principal = _nameToUserPrincipal.get(userName);
if (principal == null) {
UserPrincipalLookupService service =
FileSystems.getDefault().getUserPrincipalLookupService();
principal = service.lookupPrincipalByName(userName);
_nameToUserPrincipal.put(userName, principal);
}
return principal;
} catch (UnsupportedOperationException e) {
throw new IOException(e);
}
}
private static String getOwner(Path path) {
UserPrincipal user = null;
try {
user = Files.getOwner(path);
} catch (Exception x) {
System.err.println("Failed to get owner of: " + path);
System.err.println("\terror is: " + x);
}
return user == null ? "???" : user.getName();
}
public static void setReadOnlyPerms(Path path, boolean executable) throws IOException {
FileStore fileStore = Files.getFileStore(path);
if (fileStore.supportsFileAttributeView("posix")) {
if (executable) {
Files.setPosixFilePermissions(path, readOnlyExecPerms);
} else {
Files.setPosixFilePermissions(path, readOnlyPerms);
}
} else if (fileStore.supportsFileAttributeView("acl")) {
// windows, we hope
UserPrincipal authenticatedUsers =
path.getFileSystem()
.getUserPrincipalLookupService()
.lookupPrincipalByName("Authenticated Users");
AclEntry denyWriteEntry =
AclEntry.newBuilder()
.setType(AclEntryType.DENY)
.setPrincipal(authenticatedUsers)
.setPermissions(AclEntryPermission.APPEND_DATA, AclEntryPermission.WRITE_DATA)
.build();
AclEntry execEntry =
AclEntry.newBuilder()
.setType(executable ? AclEntryType.ALLOW : AclEntryType.DENY)
.setPrincipal(authenticatedUsers)
.setPermissions(AclEntryPermission.EXECUTE)
.build();
AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class);
List<AclEntry> acl = view.getAcl();
acl.add(0, execEntry);
acl.add(0, denyWriteEntry);
view.setAcl(acl);
} else {
throw new UnsupportedOperationException("no recognized attribute view");
}
}
@Override
public UserPrincipal getOwner() throws IOException {
UserPrincipalLookupService ls = this.path.getFileSystem()
.getUserPrincipalLookupService();
FileStatus fileStatus = path.getFileSystem().getHDFS()
.getFileStatus(path.getRawResolvedPath());
return ls.lookupPrincipalByName(fileStatus.getOwner());
}
private ExecFileSystem createExecFileSystem(
InputStreamFactory remoteInputStreamFactory,
ExecutorService removeDirectoryService,
ExecutorService accessRecorder,
ContentAddressableStorage storage)
throws ConfigurationException {
checkState(storage != null, "no exec fs cas specified");
if (storage instanceof CASFileCache) {
CASFileCache cfc = (CASFileCache) storage;
final @Nullable UserPrincipal owner;
if (!config.getExecOwner().isEmpty()) {
try {
owner =
cfc.getRoot()
.getFileSystem()
.getUserPrincipalLookupService()
.lookupPrincipalByName(config.getExecOwner());
} catch (IOException e) {
ConfigurationException configException =
new ConfigurationException("Could not locate exec_owner");
configException.initCause(e);
throw configException;
}
} else {
owner = null;
}
return createCFCExecFileSystem(removeDirectoryService, accessRecorder, cfc, owner);
} else {
// FIXME not the only fuse backing capacity...
return createFuseExecFileSystem(remoteInputStreamFactory, storage);
}
}
private ExecFileSystem createCFCExecFileSystem(
ExecutorService removeDirectoryService,
ExecutorService accessRecorder,
CASFileCache fileCache,
@Nullable UserPrincipal owner) {
return new CFCExecFileSystem(
root,
fileCache,
owner,
config.getLinkInputDirectories(),
removeDirectoryService,
accessRecorder,
/* deadlineAfter=*/ 1,
/* deadlineAfterUnits=*/ DAYS);
}
@Override
public void setOwner(Path path, User user, LinkOption... linkOption) throws IOException
{
UserPrincipal principal = getUserPrincipalFrom(user.name());
if (principal == null) {
setUserId(path, user.id(), linkOption);
}
Files.setAttribute(path, "unix:owner", principal, linkOption);
}
private UserPrincipal getUserPrincipalFrom(String userName) throws IOException
{
try {
if (_isCacheEnabled) {
return _nameToUserPrincipal.get(userName);
}
UserPrincipalLookupService service =
FileSystems.getDefault().getUserPrincipalLookupService();
return service.lookupPrincipalByName(userName);
} catch (IOException | UnsupportedOperationException e) {
return null;
}
}
/**
* Test owner in posix file view support.
*
* @throws IOException
*/
@Test
public void testGetPosixView() throws IOException {
Path rootPath = Paths.get(clusterUri);
assertTrue(rootPath.getFileSystem().supportedFileAttributeViews()
.contains("posix"));
PosixFileAttributeView view = Files.getFileAttributeView(rootPath,
PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
assertNotNull(view);
UserPrincipal user = view.getOwner();
assertNotNull(user);
assertNotNull(user.getName());
}
@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");
}
private static String getOwner(Path path) {
UserPrincipal user = null;
try {
user = Files.getOwner(path);
} catch (Exception x) {
System.err.println("Failed to get owner of: " + path);
System.err.println("\terror is: " + x);
}
return user == null ? "???" : user.getName();
}
@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;
}
}
private static String getOwner(Path path) {
UserPrincipal user = null;
try {
user = Files.getOwner(path);
} catch (Exception x) {
System.err.println("Failed to get owner of: " + path);
System.err.println("\terror is: " + x);
}
return user == null ? "???" : user.getName();
}