Java Code Examples for java.io.File#setReadable()

The following examples show how to use java.io.File#setReadable() . 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
Source File: StorageUtils.java    From XposedSmsCode with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
        }
    }
}
 
Example 2
Source File: H3CoreLoader.java    From h3-java with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 3
Source File: ExternalTableIT.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
@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());
    }
}
 
Example 4
Source File: GetUserProfile.java    From rides-java-sdk with MIT License 6 votes vote down vote up
/**
 * 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();
}
 
Example 5
Source File: TestCoreDiscovery.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@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);

}
 
Example 6
Source File: IOUtil.java    From cwlexec with Apache License 2.0 6 votes vote down vote up
/**
 * 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");
        }
    }
}
 
Example 7
Source File: TestShellClusterProvider.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 8
Source File: JobPlanner.java    From samza with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
  }
}
 
Example 9
Source File: LocalFileUtils.java    From systemds with Apache License 2.0 5 votes vote down vote up
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 );
}
 
Example 10
Source File: BrooklynPropertiesFactoryHelperTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example 11
Source File: JavaIoFileSystem.java    From bazel with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 12
Source File: Preferences.java    From XInstaller with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@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);
    }
}
 
Example 13
Source File: BrooklynPropertiesFactoryHelperTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example 14
Source File: BasePreferenceFragment.java    From mhzs with MIT License 5 votes vote down vote up
/**
 * 设置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);
        }
    }
}
 
Example 15
Source File: FileUtil.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 16
Source File: ExecutionStatisticsCollectorTest.java    From tlaplus with MIT License 5 votes vote down vote up
@Test
public void testUnreadableFile() throws IOException {
	File tempFile = File.createTempFile("esc", "txt");
	tempFile.setReadable(false);
	tempFile.deleteOnExit();
	
	assertNull(new ExecutionStatisticsCollector(tempFile.getAbsolutePath()).getIdentifier());
}
 
Example 17
Source File: JsonDataValidationReducer.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
	 * 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);	
}
 
Example 18
Source File: RNSoundPlayerModule.java    From react-native-sound-player with MIT License 5 votes vote down vote up
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);
}
 
Example 19
Source File: ZipResourceExtractor.java    From brailleback with Apache License 2.0 4 votes vote down vote up
private static void makeReadable(File file) {
    if (!file.canRead()) {
        file.setReadable(true);
    }
}
 
Example 20
Source File: FileUtilTest.java    From recheck with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
public void readableCanonicalFileOrNull_dont_return_unreadable_file() throws Exception {
	final File file = temp.newFile();
	file.setReadable( false );
	assertThat( FileUtil.readableCanonicalFileOrNull( file ) ).isNull();
}