下面列出了org.junit.jupiter.api.condition.EnabledOnOs#java.nio.file.attribute.PosixFilePermissions 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void enablePrestoJavaDebugger(DockerContainer container, int debugPort)
{
try {
FileAttribute<Set<PosixFilePermission>> rwx = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxrwxrwx"));
Path script = Files.createTempFile("enable-java-debugger", ".sh", rwx);
Files.writeString(
script,
format(
"#!/bin/bash\n" +
"printf '%%s\\n' '%s' >> '%s'\n",
"-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=0.0.0.0:" + debugPort,
CONTAINER_PRESTO_JVM_CONFIG),
UTF_8);
container.withCopyFileToContainer(MountableFile.forHostPath(script), "/docker/presto-init.d/enable-java-debugger.sh");
// expose debug port unconditionally when debug is enabled
exposePort(container, debugPort);
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private File flushPropertiesToTempFile(Map<String, Object> configProps) throws IOException {
FileAttribute<Set<PosixFilePermission>> attributes
= PosixFilePermissions.asFileAttribute(new HashSet<>(
Arrays.asList(PosixFilePermission.OWNER_WRITE,
PosixFilePermission.OWNER_READ)));
File configFile = Files.createTempFile("ksqlclient", "properties", attributes).toFile();
configFile.deleteOnExit();
try (FileOutputStream outputStream = new FileOutputStream(configFile)) {
Properties clientProps = new Properties();
for (Map.Entry<String, Object> property
: configProps.entrySet()) {
clientProps.put(property.getKey(), property.getValue());
}
clientProps.store(outputStream, "Configuration properties of KSQL AdminClient");
}
return configFile;
}
public Map<String, Object> getFileMetadata() throws IOException {
Map<String, Object> metadata;
if (filePath.toFile().exists()) {
boolean isPosix = filePath.getFileSystem().supportedFileAttributeViews().contains("posix");
metadata = new ConcurrentHashMap<>(Files.readAttributes(filePath, isPosix ? "posix:*" : "*"));
metadata.put(HeaderAttributeConstants.FILE_NAME, filePath.getFileName().toString());
metadata.put(HeaderAttributeConstants.FILE, filePath);
if (isPosix && metadata.containsKey(PERMISSIONS) && Set.class.isAssignableFrom(metadata.get(PERMISSIONS).getClass())) {
Set<PosixFilePermission> posixFilePermissions = (Set<PosixFilePermission>)(metadata.get(PERMISSIONS));
//converts permission to rwx- format and replace it in permissions field.
// (totally containing 9 characters 3 for user 3 for group and 3 for others)
metadata.put(PERMISSIONS, PosixFilePermissions.toString(posixFilePermissions));
}
metadata.put(HeaderAttributeConstants.LAST_CHANGE_TIME, Files.getAttribute(filePath, "unix:ctime"));
} else {
metadata = new ConcurrentHashMap<>();
metadata.put(HeaderAttributeConstants.LAST_CHANGE_TIME, 0L);
metadata.put(HeaderAttributeConstants.LAST_MODIFIED_TIME, 0L);
metadata.put(LAST_MODIFIED_TIMESTAMP_KEY, 0L);
}
return metadata;
}
@Test
public void testAddFingerPrintFailedToWrite() throws CertificateException, IOException {
Path notWritable = Paths.get(tmpDir.getRoot().getPath(), "notWritable");
Files.createFile(notWritable);
Files.setPosixFilePermissions(notWritable, PosixFilePermissions.fromString("r--------"));
trustManager = new TrustOnFirstUseManager(notWritable);
X509Certificate certificate = mock(X509Certificate.class);
when(certificate.getEncoded()).thenReturn("certificate".getBytes(UTF_8));
X500Principal cn = new X500Principal("CN=localhost");
when(certificate.getSubjectX500Principal()).thenReturn(cn);
try {
trustManager.checkServerTrusted(new X509Certificate[]{certificate}, "s");
trustManager.checkClientTrusted(new X509Certificate[]{certificate}, "s");
failBecauseExceptionWasNotThrown(CertificateException.class);
} catch (Exception ex) {
assertThat(ex).isInstanceOf(CertificateException.class);
}
}
@Test
public void picksFirstMatchingEntry() throws Exception {
Path searchRoot1 = tempPath.newFolder("SEARCH_ROOT1");
Files.createFile(
searchRoot1.resolve("clang"),
PosixFilePermissions.asFileAttribute(
EnumSet.of(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ)));
Path searchRoot2 = tempPath.newFolder("SEARCH_ROOT2");
Files.createFile(
searchRoot2.resolve("clang"),
PosixFilePermissions.asFileAttribute(
EnumSet.of(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ)));
XcodeToolFinder finder =
new XcodeToolFinder(FakeBuckConfig.builder().build().getView(AppleConfig.class));
assertEquals(
Optional.of(searchRoot1.resolve("clang")),
finder.getToolPath(ImmutableList.of(searchRoot1, searchRoot2), "clang"));
assertEquals(
Optional.of(searchRoot2.resolve("clang")),
finder.getToolPath(ImmutableList.of(searchRoot2, searchRoot1), "clang"));
}
/**
* Create password file to be written with access permissions to read
* and write by user only.
* <p/>
* @return Value of <code>true</code> if new file was created
* or <code>false</code> otherwise
*/
private boolean createFilePosix() {
final String METHOD = "createFilePosix";
boolean success = false;
try {
if (Files.notExists(file, new LinkOption[0])) {
Files.createFile(file, PosixFilePermissions
.asFileAttribute(CREATE_FILE_PERMISSIONS));
success = true;
} else {
Files.setPosixFilePermissions(file, CREATE_FILE_PERMISSIONS);
LOGGER.log(Level.INFO, METHOD, "exists", file.toString());
}
} catch (UnsupportedOperationException uoe) {
LOGGER.log(Level.INFO, METHOD, "unsupported", file.toString());
} catch (FileAlreadyExistsException faee) {
LOGGER.log(Level.INFO, METHOD, "exists", file.toString());
} catch (IOException ioe) {
LOGGER.log(Level.INFO, METHOD, "ioException", ioe);
}
return success;
}
@Test
public void testConvert() throws Exception {
final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
if(session.isPosixFilesystem()) {
session.open(Proxy.DIRECT, new DisabledHostKeyCallback(), new DisabledLoginCallback());
session.login(Proxy.DIRECT, new DisabledLoginCallback(), new DisabledCancelCallback());
final Path file = new Path(new LocalHomeFinderFeature(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
new LocalTouchFeature(session).touch(file, new TransferStatus());
final java.nio.file.Path local = session.toPath(file);
final PosixFileAttributes posixAttributes = Files.readAttributes(local, PosixFileAttributes.class);
final LocalAttributesFinderFeature finder = new LocalAttributesFinderFeature(session);
assertEquals(PosixFilePermissions.toString(posixAttributes.permissions()), finder.find(file).getPermission().getSymbol());
Files.setPosixFilePermissions(local, PosixFilePermissions.fromString("rw-------"));
assertEquals("rw-------", finder.find(file).getPermission().getSymbol());
Files.setPosixFilePermissions(local, PosixFilePermissions.fromString("rwxrwxrwx"));
assertEquals("rwxrwxrwx", finder.find(file).getPermission().getSymbol());
Files.setPosixFilePermissions(local, PosixFilePermissions.fromString("rw-rw----"));
assertEquals("rw-rw----", finder.find(file).getPermission().getSymbol());
assertEquals(posixAttributes.size(), finder.find(file).getSize());
assertEquals(posixAttributes.lastModifiedTime().toMillis(), finder.find(file).getModificationDate());
assertEquals(posixAttributes.creationTime().toMillis(), finder.find(file).getCreationDate());
assertEquals(posixAttributes.lastAccessTime().toMillis(), finder.find(file).getAccessedDate());
new LocalDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
}
public void writeFile(final String content, final Path file, boolean writeTempFileFirst, Set<PosixFilePermission> permissions)
throws IOException {
FsPermission fsPermission;
if (permissions == null || permissions.isEmpty()) {
fsPermission = FsPermission.getFileDefault();
} else {
// FsPermission expects a 10-character string because of the leading
// directory indicator, i.e. "drwx------". The JDK toString method returns
// a 9-character string, so prepend a leading character.
fsPermission = FsPermission.valueOf("-" + PosixFilePermissions.toString(permissions));
}
callHdfsOperation(new HdfsOperation<Void>() {
@Override
public Void call() throws IOException {
InputStream in = new ByteArrayInputStream(content.getBytes(
zConf.getString(ZeppelinConfiguration.ConfVars.ZEPPELIN_ENCODING)));
Path tmpFile = new Path(file.toString() + ".tmp");
IOUtils.copyBytes(in, fs.create(tmpFile), hadoopConf);
fs.setPermission(tmpFile, fsPermission);
fs.delete(file, true);
fs.rename(tmpFile, file);
return null;
}
});
}
@Override
protected void stashOriginalFilePermissions() throws IOException {
// save off permissions in case we need to
// rewrite the keystore in flush()
if (!Shell.WINDOWS) {
Path path = Paths.get(file.getCanonicalPath());
permissions = Files.getPosixFilePermissions(path);
} else {
// On Windows, the JDK does not support the POSIX file permission APIs.
// Instead, we can do a winutils call and translate.
String[] cmd = Shell.getGetPermissionCommand();
String[] args = new String[cmd.length + 1];
System.arraycopy(cmd, 0, args, 0, cmd.length);
args[cmd.length] = file.getCanonicalPath();
String out = Shell.execCommand(args);
StringTokenizer t = new StringTokenizer(out, Shell.TOKEN_SEPARATOR_REGEX);
// The winutils output consists of 10 characters because of the leading
// directory indicator, i.e. "drwx------". The JDK parsing method expects
// a 9-character string, so remove the leading character.
String permString = t.nextToken().substring(1);
permissions = PosixFilePermissions.fromString(permString);
}
}
@Override
public PosixViewAttributeAction build() {
if (Strings.isEmpty(basePath)) {
LOGGER.error("Posix file attribute view action not valid because base path is empty.");
return null;
}
if (filePermissions == null && Strings.isEmpty(filePermissionsString)
&& Strings.isEmpty(fileOwner) && Strings.isEmpty(fileGroup)) {
LOGGER.error("Posix file attribute view not valid because nor permissions, user or group defined.");
return null;
}
if (!FileUtils.isFilePosixAttributeViewSupported()) {
LOGGER.warn("Posix file attribute view defined but it is not supported by this files system.");
return null;
}
return new PosixViewAttributeAction(basePath, followLinks, maxDepth, pathConditions,
subst != null ? subst : configuration.getStrSubstitutor(),
filePermissions != null ? filePermissions :
filePermissionsString != null ? PosixFilePermissions.fromString(filePermissionsString) : null,
fileOwner,
fileGroup);
}
@Test
public void matchesRenamedToolName() throws Exception {
Path searchRoot = tempPath.newFolder("SEARCH_ROOT");
Files.createFile(
searchRoot.resolve("clang"),
PosixFilePermissions.asFileAttribute(
EnumSet.of(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ)));
Files.createFile(
searchRoot.resolve("my_clang"),
PosixFilePermissions.asFileAttribute(
EnumSet.of(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ)));
assertEquals(
Optional.of(searchRoot.resolve("clang")),
new XcodeToolFinder(FakeBuckConfig.builder().build().getView(AppleConfig.class))
.getToolPath(ImmutableList.of(searchRoot), "clang"));
assertEquals(
Optional.of(searchRoot.resolve("my_clang")),
new XcodeToolFinder(
FakeBuckConfig.builder()
.setSections("[apple]", "clang_xcode_tool_name_override=my_clang")
.build()
.getView(AppleConfig.class))
.getToolPath(ImmutableList.of(searchRoot), "clang"));
}
@Override
protected void stashOriginalFilePermissions() throws IOException {
// save off permissions in case we need to
// rewrite the keystore in flush()
if (!Shell.WINDOWS) {
Path path = Paths.get(file.getCanonicalPath());
permissions = Files.getPosixFilePermissions(path);
} else {
// On Windows, the JDK does not support the POSIX file permission APIs.
// Instead, we can do a winutils call and translate.
String[] cmd = Shell.getGetPermissionCommand();
String[] args = new String[cmd.length + 1];
System.arraycopy(cmd, 0, args, 0, cmd.length);
args[cmd.length] = file.getCanonicalPath();
String out = Shell.execCommand(args);
StringTokenizer t = new StringTokenizer(out, Shell.TOKEN_SEPARATOR_REGEX);
// The winutils output consists of 10 characters because of the leading
// directory indicator, i.e. "drwx------". The JDK parsing method expects
// a 9-character string, so remove the leading character.
String permString = t.nextToken().substring(1);
permissions = PosixFilePermissions.fromString(permString);
}
}
/**
* Test that the file permissions are correctly set based on permissions specified in {@link StoreConfig}.
* @throws Exception
*/
@Test
public void setFilePermissionsTest() throws Exception {
Properties props = new Properties();
props.setProperty("store.set.file.permission.enabled", Boolean.toString(true));
props.setProperty("store.data.file.permission", "rw-rw-r--");
StoreConfig initialConfig = new StoreConfig(new VerifiableProperties(props));
File segmentFile = new File(tempDir, "test_segment");
assertTrue("Fail to create segment file", segmentFile.createNewFile());
segmentFile.deleteOnExit();
// create log segment instance by writing into brand new file (using initialConfig, file permission = "rw-rw-r--")
new LogSegment(segmentFile.getName(), segmentFile, STANDARD_SEGMENT_SIZE, initialConfig, metrics, true);
Set<PosixFilePermission> filePerm = Files.getPosixFilePermissions(segmentFile.toPath());
assertEquals("File permissions are not expected", "rw-rw-r--", PosixFilePermissions.toString(filePerm));
// create log segment instance by reading from existing file (using default store config, file permission = "rw-rw----")
new LogSegment(segmentFile.getName(), segmentFile, config, metrics);
filePerm = Files.getPosixFilePermissions(segmentFile.toPath());
assertEquals("File permissions are not expected", "rw-rw----", PosixFilePermissions.toString(filePerm));
}
/**
* Copies into the specified directory, and sets runnable permission to Codechecker.
* The path to the runnable CodeChecker will be tmp/<tempTestFolder>/<into>/bin/CodeChecker
* @param into This will be the name of the CodeChecker root folder.
* @return The path to To the CodeChecker root directory.
* Will point to tmp/<tempTestFolder>/<into> .
*/
public static Path prepareCodeChecker(String into) {
if (into.isEmpty() || into == null) throw new IllegalArgumentException();
Path testDir = null;
Path ccRoot = null;
try {
testDir = Files.createTempDirectory("CCTest");
testDir.toFile().deleteOnExit();
testDir = Files.createDirectory(Paths.get(testDir.toString(), into));
ccRoot = Utils.loadFileFromBundle("org.codechecker.eclipse.rcp.shared",
Utils.RES + CODECHECKER);
} catch (IOException | URISyntaxException e1) {
e1.printStackTrace(System.out);
}
// Get the CodeChecker stub from the test resources, and copy it to a temporary folder.
Path ccDir = Utils.copyFolder(ccRoot, testDir);
Path ccBinDir = Paths.get( testDir.toAbsolutePath().toString(), CODECHECKER, BIN, CODECHECKER);
try {
// CodeChecker must be runnable.
Files.setPosixFilePermissions(ccBinDir, PosixFilePermissions.fromString("rwxrwxrwx"));
} catch (IOException e) {
e.printStackTrace();
}
return ccDir;
}
public Optional<Set<PosixFilePermission>> permissions() {
switch (type) {
case REGULAR_NON_EXECUTABLE:
return Optional.of(PosixFilePermissions.fromString("rw-r--r--"));
case REGULAR_NON_EXECUTABLE_GROUP_WRITABLE:
return Optional.of(PosixFilePermissions.fromString("rw-rw-r--"));
case REGULAR_EXECUTABLE:
return Optional.of(PosixFilePermissions.fromString("rwxr-xr-x"));
default:
return Optional.empty();
}
}
public static boolean makeExecutable(File file) {
try {
if (!IS_WINDOWS)
Files.setPosixFilePermissions(file.toPath(), PosixFilePermissions.fromString("rwxr-xr-x"));
return true;
} catch (IOException e) {
return false;
}
}
private static String buildScriptCommandLine() throws IOException {
if (System.getProperties().getProperty("os.name").contains("Windows")) {
return Paths.get(JavaMain.class.getResource("/script/demo.bat").getPath().substring(1)).toString();
}
Path result = Paths.get(JavaMain.class.getResource("/script/demo.sh").getPath());
Files.setPosixFilePermissions(result, PosixFilePermissions.fromString("rwxr-xr-x"));
return result.toString();
}
/**
* @since 2.9
*/
protected FileManager(final LoggerContext loggerContext, final String fileName, final OutputStream os, final boolean append, final boolean locking,
final boolean createOnDemand, final String advertiseURI, final Layout<? extends Serializable> layout,
final String filePermissions, final String fileOwner, final String fileGroup, final boolean writeHeader,
final ByteBuffer buffer) {
super(loggerContext, os, fileName, createOnDemand, layout, writeHeader, buffer);
this.isAppend = append;
this.createOnDemand = createOnDemand;
this.isLocking = locking;
this.advertiseURI = advertiseURI;
this.bufferSize = buffer.capacity();
final Set<String> views = FileSystems.getDefault().supportedFileAttributeViews();
if (views.contains("posix")) {
this.filePermissions = filePermissions != null ? PosixFilePermissions.fromString(filePermissions) : null;
this.fileGroup = fileGroup;
} else {
this.filePermissions = null;
this.fileGroup = null;
if (filePermissions != null) {
LOGGER.warn("Posix file attribute permissions defined but it is not supported by this files system.");
}
if (fileGroup != null) {
LOGGER.warn("Posix file attribute group defined but it is not supported by this files system.");
}
}
if (views.contains("owner")) {
this.fileOwner = fileOwner;
} else {
this.fileOwner = null;
if (fileOwner != null) {
LOGGER.warn("Owner file attribute defined but it is not supported by this files system.");
}
}
// Supported and defined
this.attributeViewEnabled = this.filePermissions != null || this.fileOwner != null || this.fileGroup != null;
}
@SuppressWarnings("resource")
@Test(expected = IllegalAccessError.class)
public void testNonReadible() throws Exception {
// setup
Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
perms.add(PosixFilePermission.OWNER_WRITE);
// test
new JournaledCoalescer(Files.createTempDirectory("tmpdir", PosixFilePermissions.asFileAttribute(perms)), fileNameGenerator);
}
/**
* Display the permissions for the specified Zip file when {@code DEBUG}
* is set to {@code true}
*
* @param msg String to include in the message
* @param zipFile Path to the Zip File
* @throws IOException If an error occurs obtaining the permissions
*/
public void displayPermissions(String msg, Path zipFile) throws IOException {
if (DEBUG) {
PosixFileAttributeView view = Files.getFileAttributeView(zipFile,
PosixFileAttributeView.class);
if (view == null) {
System.out.println("Could not obtain a PosixFileAttributeView!");
return;
}
PosixFileAttributes attrs = view.readAttributes();
System.out.printf("%s: %s, Owner: %s, Group:%s, permissions: %s%n", msg,
zipFile.getFileName(), attrs.owner().getName(),
attrs.group().getName(), PosixFilePermissions.toString(attrs.permissions()));
}
}
private static String buildScriptCommandLine() throws IOException {
if (System.getProperties().getProperty("os.name").contains("Windows")) {
return Paths.get(LocalTaskExecutorTest.class.getResource("/script/TestScriptJob.bat").getPath().substring(1)).toString();
}
Path result = Paths.get(LocalTaskExecutorTest.class.getResource("/script/TestScriptJob.sh").getPath());
Files.setPosixFilePermissions(result, PosixFilePermissions.fromString("rwxr-xr-x"));
return result.toString();
}
private String toMode( Set<PosixFilePermission> permissions ) {
int[] values = new int[] { 4, 2, 1 };
int[] sections = new int[3];
String permissionsString = PosixFilePermissions.toString( permissions );
for ( int i = 0; i < 9; i++ ) {
if ( permissionsString.charAt( i ) != '-' ) {
sections[i / 3] += values[i % 3];
}
}
return "" + sections[0] + sections[1] + sections[2];
}
/**
* 设置文件权限。前提:必须支持PosixFileAttributeView.
*/
public static void setFilePerm(File file, String perm) {
if (filePermSupported()) {
try {
Set<PosixFilePermission> perms = PosixFilePermissions.fromString(perm);
PosixFileAttributes attr = Files.readAttributes(file.toPath(), PosixFileAttributes.class);
attr.permissions().clear();
Files.setPosixFilePermissions(file.toPath(), perms);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
public static void createPrivateFile(String path) throws IOException {
final Path file = new File(path).toPath();
try {
Set<PosixFilePermission> perms = EnumSet.of(OWNER_READ, OWNER_WRITE);
Files.createFile(file, PosixFilePermissions.asFileAttribute(perms));
} catch (UnsupportedOperationException e) {
Files.createFile(file);
}
}
@Test
public void testSet() {
assertSetAndGetSucceeds("group", createGroupPrincipal("foo"));
assertSetAndGetSucceeds("permissions", PosixFilePermissions.fromString("rwxrwxrwx"));
// invalid types
assertSetFails("permissions", ImmutableList.of(PosixFilePermission.GROUP_EXECUTE));
assertSetFails("permissions", ImmutableSet.of("foo"));
}
@Override
public Permission getPermission() {
if(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) {
final BasicFileAttributes attributes;
try {
return new LocalPermission(PosixFilePermissions.toString(Files.readAttributes(Paths.get(path), PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS).permissions()));
}
catch(IOException e) {
return Permission.EMPTY;
}
}
return Permission.EMPTY;
}
@Test
public void testAttributes() {
PosixFileAttributes attrs = provider.readAttributes(file);
assertThat(attrs.permissions()).isEqualTo(PosixFilePermissions.fromString("rw-r--r--"));
assertThat(attrs.group()).isEqualTo(createGroupPrincipal("group"));
assertThat(attrs.fileKey()).isEqualTo(0);
}
@Test
public void createFile() throws IOException {
Path rootPath = Paths.get(clusterUri);
Path path = rootPath.resolve("test");
Set<PosixFilePermission> perms = EnumSet.of(
PosixFilePermission.OWNER_READ,
PosixFilePermission.OWNER_WRITE,
PosixFilePermission.OWNER_EXECUTE,
PosixFilePermission.GROUP_READ);
Files.createFile(path, PosixFilePermissions.asFileAttribute(perms));
}
private static String buildScriptCommandLine() throws IOException {
if (System.getProperties().getProperty("os.name").contains("Windows")) {
return Paths.get(JavaMain.class.getResource("/script/demo.bat").getPath().substring(1)).toString();
}
Path result = Paths.get(JavaMain.class.getResource("/script/demo.sh").getPath());
Files.setPosixFilePermissions(result, PosixFilePermissions.fromString("rwxr-xr-x"));
return result.toString();
}
@Override
public void flush() throws IOException {
super.flush();
if (!Shell.WINDOWS) {
Files.setPosixFilePermissions(Paths.get(file.getCanonicalPath()),
permissions);
} else {
// FsPermission expects a 10-character string because of the leading
// directory indicator, i.e. "drwx------". The JDK toString method returns
// a 9-character string, so prepend a leading character.
FsPermission fsPermission = FsPermission.valueOf(
"-" + PosixFilePermissions.toString(permissions));
FileUtil.setPermission(file, fsPermission);
}
}