下面列出了怎么用java.nio.file.AccessMode的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
void and_and_and_match_any_and_and() throws IOException {
result = when(enumField.eq(AccessMode.WRITE)
.and(booleanField1.isFalse())
.and(matchAny(booleanField1.isTrue(),
booleanField2.not()
.and(zeroField.between(0, 1))))
.and(zeroField.eq(1)))
.validate().withShortCircuit(false).executeOn(model);
ruleTs = jestExtension.toTS(result);
TypeScriptAssertionContext script = parseAs(ruleTs, TypeScriptParser::script);
assertFalse(result.value());
assertThat(script).numberOfSyntaxErrors().isEqualTo(0);
assertThat(script).identifierNamesText().containsExactly("when", "eq", "WRITE", "and", "eq", "and", "matchAny", "eq", "not",
"and", "greaterOrEquals", "and", "lesserThan", "and", "eq", "validate");
assertThat(script).identifierReferencesText().containsExactly("DOOV", "enumField", "boolean1", "DOOV", "boolean1",
"boolean2", "zero", "zero", "zero");
assertThat(script).identifierExpressionsText().containsExactly("AccessMode");
assertThat(script).literalsText().containsExactly("false", "true", "0", "1", "1");
assertThat(script).arrayLiteralsText().isEmpty();
}
/**
* Ensures configured directory {@code path} exists.
* @throws IOException if {@code path} exists, but is not a directory, not accessible, or broken symbolic link.
*/
static void ensureDirectoryExists(Path path) throws IOException {
// this isn't atomic, but neither is createDirectories.
if (Files.isDirectory(path)) {
// verify access, following links (throws exception if something is wrong)
// we only check READ as a sanity test
path.getFileSystem().provider().checkAccess(path.toRealPath(), AccessMode.READ);
} else {
// doesn't exist, or not a directory
try {
Files.createDirectories(path);
} catch (FileAlreadyExistsException e) {
// convert optional specific exception so the context is clear
IOException e2 = new NotDirectoryException(path.toString());
e2.addSuppressed(e);
throw e2;
}
}
}
@VisibleForTesting
static FsAction toFsAction(Set<AccessMode> mode) {
final char[] perms = new char[]{'-', '-', '-'};
for (AccessMode m : mode) {
switch (m) {
case READ:
perms[0] = 'r';
break;
case WRITE:
perms[1] = 'w';
break;
case EXECUTE:
perms[2] = 'x';
break;
}
}
return FsAction.getFsAction(new String(perms));
}
@VisibleForTesting
static FsAction toFsAction(Set<AccessMode> mode) {
final char[] perms = new char[] { '-', '-', '-'};
for(AccessMode m: mode) {
switch(m) {
case READ:
perms[0] = 'r';
break;
case WRITE:
perms[1] = 'w';
break;
case EXECUTE:
perms[2] = 'x';
break;
}
}
return FsAction.getFsAction(new String(perms));
}
@VisibleForTesting
static FsAction toFsAction(Set<AccessMode> mode) {
final char[] perms = new char[] { '-', '-', '-'};
for(AccessMode m: mode) {
switch(m) {
case READ:
perms[0] = 'r';
break;
case WRITE:
perms[1] = 'w';
break;
case EXECUTE:
perms[2] = 'x';
break;
}
}
return FsAction.getFsAction(new String(perms));
}
@Override
public void checkAccess(Path path, AccessMode... modes) throws IOException
{
JPath jPath = (JPath) path;
Status status;
try {
status = jPath.getBfsFile().getStatus();
}
catch (Exception e) {
throw createIOException(e);
}
if (status.getType() == Status.FileType.FILE) {
// do nothing
}
else if (status.getType() == Status.FileType.DIRECTORY) {
// do nothing
}
else {
throw new NoSuchFileException(path.toUri().toString());
}
}
void checkAccess(HadoopPath path, AccessMode... modes) throws IOException {
// Get Raw path
org.apache.hadoop.fs.Path hdfs_path = path.getRawResolvedPath();
// First check if the path exists
if (!path.getFileSystem().getHDFS().exists(hdfs_path))
throw new NoSuchFileException(toString());
// Check if ACL is enabled
if (!path.getFileSystem().getHDFS().getConf().getBoolean("dfs.namenode.acls.enabled", false)) {
return;
}
// TODO implement check access
}
@Override
public void checkAccess(Path file, AccessMode... modes)
throws IOException
{
triggerEx(file, "checkAccess");
// hack
if (modes.length == 0) {
if (Files.exists(unwrap(file)))
return;
else
throw new NoSuchFileException(file.toString());
}
throw new RuntimeException("not implemented yet");
}
@Override
public void checkAccess(Path file, AccessMode... modes) throws IOException {
if (modes.length == 0) {
if (Files.exists(EncryptedFileSystem.dismantle(file)))
return;
else
throw new NoSuchFileException(file.toString());
}
// see
// https://docs.oracle.com/javase/7/docs/api/java/nio/file/spi/FileSystemProvider.html#checkAccess%28java.nio.file.Path,%20java.nio.file.AccessMode...%29
throw new UnsupportedOperationException("not implemented");
}
@BeforeEach
void beforeEach() {
this.model = new GenericModel();
this.enumField = model.enumField(AccessMode.READ, "enumField");
this.dateField1 = model.localDateField(LocalDate.now(), "date 1");
this.dateField2 = model.localDateField(LocalDate.now(), "date 2");
this.booleanField1 = model.booleanField(false, "boolean 1");
this.booleanField2 = model.booleanField(false, "boolean 2");
this.zeroField = model.intField(0, "zero");
}
@BeforeEach
void beforeEach() {
this.model = new GenericModel();
this.enumField = model.enumField(AccessMode.READ, "enum");
this.dateField1 = model.localDateField(LocalDate.now(), "date 1");
this.dateField2 = model.localDateField(LocalDate.now(), "date 2");
this.booleanField1 = model.booleanField(false, "boolean 1");
this.booleanField2 = model.booleanField(false, "boolean 2");
this.zeroField = model.intField(0, "zero");
}
@Test
void and_and_and_match_any_and_and() {
rule = when(enumField.eq(AccessMode.WRITE)
.and(booleanField1.isFalse())
.and(matchAny(booleanField1.isTrue(),
booleanField2.not()
.and(zeroField.between(0, 1))))
.and(zeroField.eq(1))).validate();
assertThat(rule.readable(LOCALE)).isEqualTo(
"rule when (((enum = WRITE and boolean 1 is false) and match any [boolean 1 is true, (boolean 2 not and (zero >= 0 and zero < 1))]) and zero = 1) validate");
}
@BeforeEach
void beforeEach() {
this.model = new GenericModel();
this.enumField = model.enumField(AccessMode.READ, "enum");
this.dateField1 = model.localDateField(LocalDate.now(), "date 1");
this.dateField2 = model.localDateField(LocalDate.now(), "date 2");
this.booleanField1 = model.booleanField(false, "boolean 1");
this.booleanField2 = model.booleanField(false, "boolean 2");
this.zeroField = model.intField(0, "zero");
}
@Test
void and_and_and_match_any_and_and() {
result = when(enumField.eq(AccessMode.WRITE)
.and(booleanField1.isFalse())
.and(matchAny(booleanField1.isTrue(),
booleanField2.not()
.and(zeroField.between(0, 1))))
.and(zeroField.eq(1)))
.validate().withShortCircuit(false).executeOn(model);
doc = documentOf(result);
assertFalse(result.value());
assertThat(doc).nary_OL().hasSize(1);
assertThat(doc).binary_LI().hasSize(3);
assertThat(doc).nary_LI().isEmpty();
assertThat(doc).leaf_LI().isEmpty();
assertThat(doc).when_UL().isEmpty();
assertThat(doc).binary_UL().isEmpty();
assertThat(doc).binaryChild_UL().isEmpty();
assertThat(doc).unary_UL().isEmpty();
assertThat(doc).percentageValue_DIV()
.containsExactly("0 %", "100 %", "100 %", "0 %", "100 %", "100 %", "100 %", "0 %");
assertThat(doc).tokenOperator_SPAN()
.containsExactly("=", "and", "is", "and", "is", "not", "and", ">=", "and", "<", "and", "=");
assertThat(doc).tokenValue_SPAN().containsExactly("WRITE", "false", "true", "0", "1", "1");
assertThat(doc).tokenNary_SPAN().containsExactly("match any");
}
@Override
public void checkAccess(Path file, AccessMode... modes)
throws IOException
{
triggerEx(file, "checkAccess");
// hack
if (modes.length == 0) {
if (Files.exists(unwrap(file)))
return;
else
throw new NoSuchFileException(file.toString());
}
throw new RuntimeException("not implemented yet");
}
@Override
public void checkAccess(Path file, AccessMode... modes)
throws IOException
{
triggerEx(file, "checkAccess");
// hack
if (modes.length == 0) {
if (Files.exists(unwrap(file)))
return;
else
throw new NoSuchFileException(file.toString());
}
throw new RuntimeException("not implemented yet");
}
@Override
public void checkAccess(Path file, AccessMode... modes)
throws IOException
{
triggerEx(file, "checkAccess");
// hack
if (modes.length == 0) {
if (Files.exists(unwrap(file)))
return;
else
throw new NoSuchFileException(file.toString());
}
throw new RuntimeException("not implemented yet");
}
private Collection<FsPermissionTask> getUpdateKeyPermissionTasks(DatasetConfig datasetConfig, FileSystem userFs) {
FileUpdateKey fileUpdateKey;
try {
fileUpdateKey = LegacyProtobufSerializer.parseFrom(FileUpdateKey.PARSER, datasetConfig.getReadDefinition().getReadSignature().toByteArray());
} catch (InvalidProtocolBufferException e) {
throw new RuntimeException("Cannot read file update key", e);
}
if (fileUpdateKey.getCachedEntitiesList().isEmpty()) {
return Collections.emptyList();
}
final List<FsPermissionTask> fsPermissionTasks = Lists.newArrayList();
final Set<AccessMode> access;
final List<Path> batch = Lists.newArrayList();
//DX-7850 : remove once solution for maprfs is found
if (userFs.isMapRfs()) {
access = EnumSet.of(AccessMode.READ);
} else {
access = EnumSet.of(AccessMode.READ, AccessMode.EXECUTE);
}
for (FileSystemCachedEntity cachedEntity : fileUpdateKey.getCachedEntitiesList()) {
batch.add(Path.of(cachedEntity.getPath()));
if (batch.size() == PERMISSION_CHECK_TASK_BATCH_SIZE) {
// make a copy of batch
fsPermissionTasks.add(new FsPermissionTask(userFs, Lists.newArrayList(batch), access));
batch.clear();
}
}
if (!batch.isEmpty()) {
fsPermissionTasks.add(new FsPermissionTask(userFs, batch, access));
}
return fsPermissionTasks;
}
private Collection<FsPermissionTask> getSplitPermissionTasks(DatasetConfig datasetConfig, FileSystem userFs, String user) {
final SplitsPointer splitsPointer = DatasetSplitsPointer.of(context.getNamespaceService(user), datasetConfig);
final boolean isParquet = DatasetHelper.hasParquetDataFiles(datasetConfig.getPhysicalDataset().getFormatSettings());
final List<FsPermissionTask> fsPermissionTasks = Lists.newArrayList();
final List<Path> batch = Lists.newArrayList();
for (PartitionChunkMetadata partitionChunkMetadata: splitsPointer.getPartitionChunks()) {
for (DatasetSplit split : partitionChunkMetadata.getDatasetSplits()) {
final Path filePath;
try {
if (isParquet) {
filePath = Path.of(LegacyProtobufSerializer.parseFrom(ParquetDatasetSplitXAttr.PARSER, split.getSplitExtendedProperty().toByteArray()).getPath());
} else {
filePath = Path.of(LegacyProtobufSerializer.parseFrom(EasyDatasetSplitXAttr.PARSER, split.getSplitExtendedProperty().toByteArray()).getPath());
}
} catch (InvalidProtocolBufferException e) {
throw new RuntimeException("Could not deserialize split info", e);
}
batch.add(filePath);
if (batch.size() == PERMISSION_CHECK_TASK_BATCH_SIZE) {
// make a copy of batch
fsPermissionTasks.add(new FsPermissionTask(userFs, new ArrayList<>(batch), EnumSet.of(AccessMode.READ)));
batch.clear();
}
}
}
if (!batch.isEmpty()) {
fsPermissionTasks.add(new FsPermissionTask(userFs, batch, EnumSet.of(AccessMode.READ)));
}
return fsPermissionTasks;
}
@Override
public void access(final Path path, final Set<AccessMode> mode) throws AccessControlException, FileNotFoundException, IOException {
try (WaitRecorder recorder = OperatorStats.getWaitRecorder(operatorStats)) {
checkAccessAllowed(toHadoopPath(path), toFsAction(mode));
} catch(FSError e) {
throw propagateFSError(e);
}
}
@Override
public void checkAccess(Path file, AccessMode... modes)
throws IOException
{
triggerEx(file, "checkAccess");
// hack
if (modes.length == 0) {
if (Files.exists(unwrap(file)))
return;
else
throw new NoSuchFileException(file.toString());
}
throw new RuntimeException("not implemented yet");
}
@Override
public void checkAccess(Path file, AccessMode... modes)
throws IOException
{
triggerEx(file, "checkAccess");
// hack
if (modes.length == 0) {
if (Files.exists(unwrap(file)))
return;
else
throw new NoSuchFileException(file.toString());
}
throw new RuntimeException("not implemented yet");
}
@Override
public void checkAccess(Path path, AccessMode... modes) throws IOException {
MCRPath mcrPath = MCRFileSystemUtils.checkPathAbsolute(path);
MCRStoredNode node = MCRFileSystemUtils.resolvePath(mcrPath);
if (node == null) {
throw new NoSuchFileException(mcrPath.toString());
}
if (node instanceof MCRDirectory) {
checkDirectory((MCRDirectory) node, modes);
} else {
checkFile((MCRFile) node, modes);
}
}
private void checkFile(MCRFile file, AccessMode... modes) throws AccessDeniedException {
for (AccessMode mode : modes) {
switch (mode) {
case READ:
case WRITE:
break;
case EXECUTE:
throw new AccessDeniedException(MCRFileSystemUtils.toPath(file).toString(), null,
"Unsupported AccessMode: " + mode);
default:
throw new UnsupportedOperationException("Unsupported AccessMode: " + mode);
}
}
}
@Override
public void checkAccess(Path path, AccessMode... modes) throws IOException {
MCRPath mcrPath = MCRFileSystemUtils.checkPathAbsolute(path);
MCRFilesystemNode node = resolvePath(mcrPath);
if (node == null) {
throw new NoSuchFileException(mcrPath.toString());
}
if (node instanceof MCRDirectory) {
checkDirectory((MCRDirectory) node, modes);
} else {
checkFile((MCRFile) node, modes);
}
}
private void checkFile(MCRFile file, AccessMode... modes) throws AccessDeniedException {
for (AccessMode mode : modes) {
switch (mode) {
case READ:
case WRITE:
break;
case EXECUTE:
throw new AccessDeniedException(file.toPath().toString(), null, "Unsupported AccessMode: " + mode);
default:
throw new UnsupportedOperationException("Unsupported AccessMode: " + mode);
}
}
}
@Override
public void checkAccess(Path path, AccessMode... modes) throws IOException
{
BootJar jar = jar(path);
if (jar == null) {
throw new FileNotFoundException(L.l("{0} does not exist", path));
}
}
@Override
public void checkAccess(Path path, AccessMode... modes) throws IOException
{
URL url = getURL(path);
if (url == null) {
throw new IOException(L.l("{0} does not exist", path));
}
}
void checkAccess(SFTPPath path, AccessMode... modes) throws IOException {
try (Channel channel = channelPool.get()) {
SftpATTRS attributes = getAttributes(channel, path, true);
for (AccessMode mode : modes) {
if (!hasAccess(attributes, mode)) {
throw new AccessDeniedException(path.path());
}
}
}
}
private boolean hasAccess(SftpATTRS attrs, AccessMode mode) {
switch (mode) {
case READ:
return PosixFilePermissionSupport.hasPermission(attrs.getPermissions(), PosixFilePermission.OWNER_READ);
case WRITE:
return PosixFilePermissionSupport.hasPermission(attrs.getPermissions(), PosixFilePermission.OWNER_WRITE);
case EXECUTE:
return PosixFilePermissionSupport.hasPermission(attrs.getPermissions(), PosixFilePermission.OWNER_EXECUTE);
default:
return false;
}
}