下面列出了java.io.File#setReadable ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Copy the resource at the given path to the file. File will be made readable,
* writable, and executable.
*
* @param resourcePath Resource to copy
* @param newH3LibFile File to write
* @throws UnsatisfiedLinkError The resource path does not exist
*/
static void copyResource(String resourcePath, File newH3LibFile) throws IOException {
// Set the permissions
newH3LibFile.setReadable(true);
newH3LibFile.setWritable(true, true);
newH3LibFile.setExecutable(true, true);
// Shove the resource into the file and close it
try (InputStream resource = H3CoreLoader.class.getResourceAsStream(resourcePath)) {
if (resource == null) {
throw new UnsatisfiedLinkError(String.format("No native resource found at %s", resourcePath));
}
try (FileOutputStream outFile = new FileOutputStream(newH3LibFile)) {
copyStream(resource, outFile);
}
}
}
@Test @Ignore // failing on mapr5.2.0. Temporary ignoring
public void testReadToNotPermittedLocation() throws Exception{
methodWatcher.executeUpdate(String.format("create external table PARQUET_NO_PERMISSION_READ (col1 int, col2 varchar(24), col3 boolean)" +
" STORED AS PARQUET LOCATION '%s'", getExternalResourceDirectory()+"PARQUET_NO_PERMISSION_READ"));
File file = new File(String.valueOf(getExternalResourceDirectory()+"PARQUET_NO_PERMISSION_READ"));
try{
methodWatcher.executeUpdate(String.format("insert into PARQUET_NO_PERMISSION_READ values (1,'XXXX',true), (2,'YYYY',false), (3,'ZZZZ', true)"));
file.setReadable(false);
methodWatcher.executeQuery(String.format("select * from PARQUET_NO_PERMISSION_READ"));
// we don't want to have a unreadable file in the folder, clean it up
file.setReadable(true);
file.delete();
Assert.fail("Exception not thrown");
} catch (SQLException e) {
// we don't want to have a unreadable file in the folder, clean it up
file.setReadable(true);
file.delete();
Assert.assertEquals("Wrong Exception","EXT11",e.getSQLState());
}
}
@Test
public void testNonCoreDirCantRead() throws Exception {
File coreDir = solrHomeDirectory.toFile();
setMeUp(coreDir.getAbsolutePath());
addCoreWithProps(makeCoreProperties("core1", false, true),
new File(coreDir, "core1" + File.separator + CorePropertiesLocator.PROPERTIES_FILENAME));
addCoreWithProps(makeCoreProperties("core2", false, false, "dataDir=core2"),
new File(coreDir, "core2" + File.separator + CorePropertiesLocator.PROPERTIES_FILENAME));
File toSet = new File(solrHomeDirectory.toFile(), "cantReadDir");
assertTrue("Should have been able to make directory '" + toSet.getAbsolutePath() + "' ", toSet.mkdirs());
assumeTrue("Cannot make " + toSet + " non-readable. Test aborted.", toSet.setReadable(false, false));
assumeFalse("Appears we are a super user, skip test", toSet.canRead());
CoreContainer cc = init();
try (SolrCore core1 = cc.getCore("core1");
SolrCore core2 = cc.getCore("core2")) {
assertNotNull(core1); // Should be able to open the perfectly valid core1 despite a non-readable directory
assertNotNull(core2);
} finally {
cc.shutdown();
}
// So things can be cleaned up by the framework!
toSet.setReadable(true, false);
}
/**
* Write the execution plan JSON to a file
* @param planJson JSON representation of the plan
*/
final void writePlanJsonFile(String planJson) {
try {
String content = "plan='" + planJson + "'";
String planPath = System.getenv(ShellCommandConfig.EXECUTION_PLAN_DIR);
if (planPath != null && !planPath.isEmpty()) {
// Write the plan json to plan path
File file = new File(planPath + "/plan.json");
file.setReadable(true, false);
PrintWriter writer = new PrintWriter(file, "UTF-8");
writer.println(content);
writer.close();
}
} catch (Exception e) {
LOG.warn("Failed to write execution plan json to file", e);
}
}
@Test
public void testCopyDirectory() throws Exception {
File copyTempDir = new File(tempDir, "copy");
File srcDir = new File(copyTempDir, "somedir");
File dstDir = new File(copyTempDir, "dst");
Assert.assertTrue(srcDir.mkdirs());
Assert.assertTrue(dstDir.mkdirs());
File link1 = new File(copyTempDir, "link1");
File link2 = new File(copyTempDir, "link2");
File dir1 = new File(copyTempDir, "dir1");
File file1 = new File(dir1, "f1");
File file2 = new File(dir1, "f2");
Assert.assertTrue(dir1.mkdirs());
Assert.assertTrue(file1.createNewFile());
Assert.assertTrue(file2.createNewFile());
file2.setReadable(false);
file2.setWritable(false);
file2.setExecutable(false);
Files.createSymbolicLink(link1.toPath(), dir1.toPath());
Files.createSymbolicLink(link2.toPath(), link1.toPath());
Files.createSymbolicLink(new File(srcDir, "dir1").toPath(), link2.toPath());
File clone = ShellClusterProvider.createDirectoryClone(srcDir, srcDir.getName(), dstDir);
File cloneF1 = new File(new File(clone, "dir1"), "f1");
Assert.assertTrue(cloneF1.isFile());
}
/**
* Creates an executable shell script
*
* @param scriptPath
* the path of shell script
* @param command
* the execution command
* @throws CWLException
* Failed to create the shell script
*/
public static void createCommandScript(Path scriptPath, String command) throws CWLException {
if (scriptPath != null) {
File scriptFile = scriptPath.toFile();
if (scriptFile.setExecutable(true)) {
logger.trace("Set file executable attribute.");
}
if (scriptFile.setReadable(true)) {
logger.trace("Set file readable attribute.");
}
if (scriptFile.setWritable(true)) {
logger.trace("Set file writable attribute.");
}
if (command != null) {
write(scriptFile, command);
} else {
write(scriptFile, "#!/bin/bash");
}
}
}
/**
* Creates an {@link OAuth2Credentials} object that can be used by any of the servlets.
*/
public static OAuth2Credentials createOAuth2Credentials(SessionConfiguration sessionConfiguration) throws Exception {
// Store the users OAuth2 credentials in their home directory.
File credentialDirectory =
new File(System.getProperty("user.home") + File.separator + ".uber_credentials");
credentialDirectory.setReadable(true, true);
credentialDirectory.setWritable(true, true);
// If you'd like to store them in memory or in a DB, any DataStoreFactory can be used.
AbstractDataStoreFactory dataStoreFactory = new FileDataStoreFactory(credentialDirectory);
// Build an OAuth2Credentials object with your secrets.
return new OAuth2Credentials.Builder()
.setCredentialDataStoreFactory(dataStoreFactory)
.setRedirectUri(sessionConfiguration.getRedirectUri())
.setClientSecrets(sessionConfiguration.getClientId(), sessionConfiguration.getClientSecret())
.build();
}
/**
* Set file world writable
*/
@SuppressLint({"SetWorldWritable", "SetWorldReadable"})
public static void setFileWorldWritable(File file, int parentDepth) {
if (!file.exists()) {
return;
}
parentDepth = parentDepth + 1;
for (int i = 0; i < parentDepth; i++) {
file.setExecutable(true, false);
file.setWritable(true, false);
file.setReadable(true, false);
file = file.getParentFile();
if (file == null) {
break;
}
}
}
@Test(groups="UNIX")
public void testChecksLocalBrooklynPropertiesPermissionsX00() throws Exception {
File propsFile = File.createTempFile("testChecksLocalBrooklynPropertiesPermissionsX00", ".properties");
propsFile.setReadable(true, false);
try {
new BrooklynPropertiesFactoryHelper(propsFile.getAbsolutePath(), null)
.createPropertiesBuilder();
Assert.fail("Should have thrown");
} catch (FatalRuntimeException e) {
if (!e.toString().contains("Invalid permissions for file")) throw e;
} finally {
propsFile.delete();
}
}
private Uri getUriFromFile(String name, String type) {
String folder = getReactApplicationContext().getFilesDir().getAbsolutePath();
String file = name + "." + type;
// http://blog.weston-fl.com/android-mediaplayer-prepare-throws-status0x1-error1-2147483648
// this helps avoid a common error state when mounting the file
File ref = new File(folder + "/" + file);
if (ref.exists()) {
ref.setReadable(true, false);
}
return Uri.parse("file://" + folder + "/" + file);
}
/**
* Creates the directory.
*
* @param key the key
*/
private void createDirectory(Text key) {
File f = new File(dirPath + File.separator + key.toString());
f.mkdirs();
f.setReadable(true, false);
f.setWritable(true, false);
}
@Test
public void testUnreadableFile() throws IOException {
File tempFile = File.createTempFile("esc", "txt");
tempFile.setReadable(false);
tempFile.deleteOnExit();
assertNull(new ExecutionStatisticsCollector(tempFile.getAbsolutePath()).getIdentifier());
}
/**
* Set permissions to the required value. Uses the java primitives instead
* of forking if group == other.
* @param f the file to change
* @param permission the new permissions
* @throws IOException exception on setPermission
*/
public static void setPermission(File f, FsPermission permission
) throws IOException {
FsAction user = permission.getUserAction();
FsAction group = permission.getGroupAction();
FsAction other = permission.getOtherAction();
// use the native/fork if the group/other permissions are different
// or if the native is available or on Windows
if (group != other || NativeIO.isAvailable() || Shell.WINDOWS) {
execSetPermission(f, permission);
return;
}
boolean rv = true;
// read perms
rv = f.setReadable(group.implies(FsAction.READ), false);
checkReturnValue(rv, f, permission);
if (group.implies(FsAction.READ) != user.implies(FsAction.READ)) {
rv = f.setReadable(user.implies(FsAction.READ), true);
checkReturnValue(rv, f, permission);
}
// write perms
rv = f.setWritable(group.implies(FsAction.WRITE), false);
checkReturnValue(rv, f, permission);
if (group.implies(FsAction.WRITE) != user.implies(FsAction.WRITE)) {
rv = f.setWritable(user.implies(FsAction.WRITE), true);
checkReturnValue(rv, f, permission);
}
// exec perms
rv = f.setExecutable(group.implies(FsAction.EXECUTE), false);
checkReturnValue(rv, f, permission);
if (group.implies(FsAction.EXECUTE) != user.implies(FsAction.EXECUTE)) {
rv = f.setExecutable(user.implies(FsAction.EXECUTE), true);
checkReturnValue(rv, f, permission);
}
}
/**
* 设置Pref为可读
*/
@SuppressWarnings({"deprecation", "ResultOfMethodCallIgnored"})
@SuppressLint({"SetWorldReadable", "WorldReadableFiles"})
protected void setWorldReadable() {
if (FileUtils.getDefaultPrefFile(getActivity())
.exists()) {
for (File file : new File[]{FileUtils.getDataDir(getActivity()), FileUtils.getPrefDir(getActivity()), FileUtils.getDefaultPrefFile(getActivity())}) {
file.setReadable(true, false);
file.setExecutable(true, false);
}
}
}
public static void setLocalFilePermissions(File file, String permissions)
{
//note: user and group treated the same way
char[] c = permissions.toCharArray();
short sU = (short)(c[0]-48);
short sO = (short)(c[2]-48);
file.setExecutable( (sU&1)==1, (sO&1)==0 );
file.setWritable( (sU&2)==2, (sO&2)==0 );
file.setReadable( (sU&4)==4, (sO&4)==0 );
}
@Override
public void onPause() {
super.onPause();
// Set preferences file permissions to be world readable
File prefsDir = new File(getActivity().getApplicationInfo().dataDir, "shared_prefs");
File prefsFile = new File(prefsDir, getPreferenceManager().getSharedPreferencesName() + ".xml");
if (prefsFile.exists()) {
prefsFile.setReadable(true, false);
}
}
@Override
protected void setReadable(Path path, boolean readable) throws IOException {
File file = getIoFile(path);
if (!file.exists()) {
throw new FileNotFoundException(path + ERR_NO_SUCH_FILE_OR_DIR);
}
file.setReadable(readable);
}
@Test(groups="UNIX")
public void testChecksGlobalBrooklynPropertiesPermissionsX00() throws Exception {
File propsFile = File.createTempFile("testChecksGlobalBrooklynPropertiesPermissionsX00", ".properties");
propsFile.setReadable(true, false);
try {
new BrooklynPropertiesFactoryHelper(propsFile.getAbsolutePath(), null)
.createPropertiesBuilder();
Assert.fail("Should have thrown");
} catch (FatalRuntimeException e) {
if (!e.toString().contains("Invalid permissions for file")) throw e;
} finally {
propsFile.delete();
}
}
@Test
public void readableCanonicalFileOrNull_dont_return_unreadable_file() throws Exception {
final File file = temp.newFile();
file.setReadable( false );
assertThat( FileUtil.readableCanonicalFileOrNull( file ) ).isNull();
}
private static void makeReadable(File file) {
if (!file.canRead()) {
file.setReadable(true);
}
}