Example usage for java.io File setWritable

List of usage examples for java.io File setWritable

Introduction

In this page you can find the example usage for java.io File setWritable.

Prototype

public boolean setWritable(boolean writable, boolean ownerOnly) 

Source Link

Document

Sets the owner's or everybody's write permission for this abstract pathname.

Usage

From source file:com.android.tradefed.util.FileUtil.java

/**
 * Performs a best effort attempt to make given file group readable and
 * writable./*  w  ww.j  av a 2s.  c  o m*/
 * <p />
 * Note that the execute permission is required to make directories
 * accessible. See {@link #chmodGroupRWX(File)}.
 * <p/ >
 * If 'chmod' system command is not supported by underlying OS, will set
 * file to writable by all.
 *
 * @param file
 *            the {@link File} to make owner and group writable
 * @return <code>true</code> if file was successfully made group writable,
 *         <code>false</code> otherwise
 */
public static boolean chmodGroupRW(File file) {
    if (chmod(file, "ug+rw")) {
        return true;
    } else {
        Log.d(LOG_TAG, String.format("Failed chmod; attempting to set %s globally RW", file.getAbsolutePath()));
        return file.setWritable(true, false /* false == writable for all */)
                && file.setReadable(true, false /* false == readable for all */);
    }
}

From source file:com.android.tradefed.util.FileUtil.java

public static boolean chmodRWXRecursively(File file) {
    boolean success = true;
    if (!file.setExecutable(true, false)) {
        CLog.w("Failed to set %s executable.", file.getAbsolutePath());
        success = false;/* w  w w. j  a  v a 2 s.  c o m*/
    }
    if (!file.setWritable(true, false)) {
        CLog.w("Failed to set %s writable.", file.getAbsolutePath());
        success = false;
    }
    if (!file.setReadable(true, false)) {
        CLog.w("Failed to set %s readable", file.getAbsolutePath());
        success = false;
    }

    if (file.isDirectory()) {
        File[] childs = file.listFiles();
        for (File child : childs) {
            if (!chmodRWXRecursively(child)) {
                success = false;
            }
        }

    }
    return success;
}

From source file:com.wuba.utils.FileUtil.java

public static boolean chmodRWXRecursively(File file) {
    boolean success = true;
    if (!file.setExecutable(true, false)) {
        LOG.warn(String.format("Failed to set %s executable.", file.getAbsolutePath()));
        success = false;/*from ww w  . ja v  a2 s  .c  om*/
    }
    if (!file.setWritable(true, false)) {
        LOG.warn(String.format("Failed to set %s writable.", file.getAbsolutePath()));
        success = false;
    }
    if (!file.setReadable(true, false)) {
        LOG.warn(String.format("Failed to set %s readable", file.getAbsolutePath()));
        success = false;
    }

    if (file.isDirectory()) {
        File[] childs = file.listFiles();
        for (File child : childs) {
            if (!chmodRWXRecursively(child)) {
                success = false;
            }
        }

    }
    return success;
}

From source file:de.uni_siegen.wineme.come_in.thumbnailer.util.TemporaryFilesManager.java

/**
 * Create a new, read-only temporary file.
 * // ww  w  . j a v  a2s . com
 * @param file         Original file that you need a copy of
 * @param newExtension   The extension that the new file should have
 * @return File (read-only) 
 * @throws IOException
 */
public File createTempfileCopy(File file, String newExtension) throws IOException {
    File destFile = files.get(file);
    if (destFile == null) {
        destFile = File.createTempFile("temp", "." + newExtension);
        createNewCopy(file, destFile);
        destFile.setWritable(false, false);
    } else {
        String newFilename = FilenameUtils.removeExtension(destFile.getAbsolutePath()) + "." + newExtension;
        File newFile = new File(newFilename);
        boolean renameSucces = destFile.renameTo(newFile);
        if (!renameSucces) {
            createNewCopy(file, newFile);
        }
        files.put(file, newFile);
        destFile = newFile;
    }
    return destFile;
}

From source file:io.sloeber.core.managers.InternalPackageManager.java

private static void chmod(File file, int mode) throws IOException, InterruptedException {
    String octal = Integer.toOctalString(mode);
    if (Platform.getOS().equals(Platform.OS_WIN32)) {
        boolean ownerExecute = (((mode / (8 * 8)) & 1) == 1);
        boolean ownerRead = (((mode / (8 * 8)) & 4) == 4);
        boolean ownerWrite = (((mode / (8 * 8)) & 2) == 2);
        boolean everyoneExecute = (((mode / 8) & 1) == 1);
        boolean everyoneRead = (((mode / 8) & 4) == 4);
        boolean everyoneWrite = (((mode / 8) & 2) == 2);
        file.setWritable(true, false);
        file.setExecutable(ownerExecute, !everyoneExecute);
        file.setReadable(ownerRead, !everyoneRead);
        file.setWritable(ownerWrite, !everyoneWrite);
    } else {/*  w  ww .jav a  2s .  c o m*/
        Process process = Runtime.getRuntime().exec(new String[] { "chmod", octal, file.getAbsolutePath() }, //$NON-NLS-1$
                null, null);
        process.waitFor();
    }
}

From source file:org.apache.flink.runtime.taskmanager.TestManagerStartupTest.java

/**
 * Tests that the TaskManager startup fails synchronously when the I/O directories are
 * not writable.//from   w  w w  .  j  a  v  a 2 s . c  o  m
 */
@Test
public void testIODirectoryNotWritable() {
    File tempDir = new File(ConfigConstants.DEFAULT_TASK_MANAGER_TMP_PATH);
    File nonWritable = new File(tempDir, UUID.randomUUID().toString());

    if (!nonWritable.mkdirs() || !nonWritable.setWritable(false, false)) {
        System.err.println("Cannot create non-writable temporary file directory. Skipping test.");
        return;
    }

    try {
        Configuration cfg = new Configuration();
        cfg.setString(ConfigConstants.TASK_MANAGER_TMP_DIR_KEY, nonWritable.getAbsolutePath());
        cfg.setInteger(ConfigConstants.TASK_MANAGER_MEMORY_SIZE_KEY, 4);
        cfg.setString(ConfigConstants.JOB_MANAGER_IPC_ADDRESS_KEY, "localhost");
        cfg.setInteger(ConfigConstants.JOB_MANAGER_IPC_PORT_KEY, 21656);

        try {
            TaskManager.runTaskManager("localhost", 0, cfg, StreamingMode.BATCH_ONLY);
            fail("Should fail synchronously with an exception");
        } catch (IOException e) {
            // splendid!
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    } finally {
        //noinspection ResultOfMethodCallIgnored
        nonWritable.setWritable(true, false);
        try {
            FileUtils.deleteDirectory(nonWritable);
        } catch (IOException e) {
            // best effort
        }
    }
}

From source file:org.jncc.base.file.Fileupload.java

public boolean file_Upload() throws Exception {

    if (null != upload) {
        File saveFile = new File(getPath(), fileName.substring(fileName.indexOf("/") + 1));
        // upload.renameTo(saveFile);
        if (saveFile.exists()) {
            saveFile.setWritable(true, false);
            saveFile.delete();/*from w  w  w .  j av a  2  s .  c  om*/
        }
        FileUtils.moveFile(upload, saveFile);
        // m_filecontent.put("Product1",fileread.readFileByLines(getPath()+"\\"+fileName));
    }
    return true;
}

From source file:com.intel.cryptostream.utils.NativeCodeLoader.java

/**
 * Extract the specified library file to the target folder
 * /*from   w w w  .  ja va  2s .  co m*/
 * @param libFolderForCurrentOS
 * @param libraryFileName
 * @param targetFolder
 * @return
 */
private static File extractLibraryFile(String libFolderForCurrentOS, String libraryFileName,
        String targetFolder) {
    String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;

    // Attach UUID to the native library file to ensure multiple class loaders
    // can read the libcryptostream multiple times.
    String uuid = UUID.randomUUID().toString();
    String extractedLibFileName = String.format("cryptostream-%s-%s-%s", getVersion(), uuid, libraryFileName);
    File extractedLibFile = new File(targetFolder, extractedLibFileName);

    try {
        // Extract a native library file into the target directory
        InputStream reader = NativeCodeLoader.class.getResourceAsStream(nativeLibraryFilePath);
        FileOutputStream writer = new FileOutputStream(extractedLibFile);
        try {
            byte[] buffer = new byte[8192];
            int bytesRead = 0;
            while ((bytesRead = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, bytesRead);
            }
        } finally {
            // Delete the extracted lib file on JVM exit.
            extractedLibFile.deleteOnExit();

            if (writer != null)
                writer.close();
            if (reader != null)
                reader.close();
        }

        // Set executable (x) flag to enable Java to load the native library
        extractedLibFile.setReadable(true);
        extractedLibFile.setWritable(true, true);
        extractedLibFile.setExecutable(true);

        // Check whether the contents are properly copied from the resource folder
        {
            InputStream nativeIn = NativeCodeLoader.class.getResourceAsStream(nativeLibraryFilePath);
            InputStream extractedLibIn = new FileInputStream(extractedLibFile);
            try {
                if (!contentsEquals(nativeIn, extractedLibIn))
                    throw new RuntimeException(
                            String.format("Failed to write a native library file at %s", extractedLibFile));
            } finally {
                if (nativeIn != null)
                    nativeIn.close();
                if (extractedLibIn != null)
                    extractedLibIn.close();
            }
        }

        return new File(targetFolder, extractedLibFileName);
    } catch (IOException e) {
        e.printStackTrace(System.err);
        return null;
    }
}

From source file:org.apache.flink.runtime.taskmanager.TaskManagerStartupTest.java

/**
 * Tests that the TaskManager startup fails synchronously when the I/O
 * directories are not writable.//from w  w w .j  a va  2  s .c om
 */
@Test
public void testIODirectoryNotWritable() {
    File tempDir = new File(ConfigConstants.DEFAULT_TASK_MANAGER_TMP_PATH);
    File nonWritable = new File(tempDir, UUID.randomUUID().toString());

    if (!nonWritable.mkdirs() || !nonWritable.setWritable(false, false)) {
        System.err.println("Cannot create non-writable temporary file directory. Skipping test.");
        return;
    }

    try {
        Configuration cfg = new Configuration();
        cfg.setString(ConfigConstants.TASK_MANAGER_TMP_DIR_KEY, nonWritable.getAbsolutePath());
        cfg.setInteger(ConfigConstants.TASK_MANAGER_MEMORY_SIZE_KEY, 4);
        cfg.setString(ConfigConstants.JOB_MANAGER_IPC_ADDRESS_KEY, "localhost");
        cfg.setInteger(ConfigConstants.JOB_MANAGER_IPC_PORT_KEY, 21656);

        try {
            TaskManager.runTaskManager("localhost", ResourceID.generate(), 0, cfg);
            fail("Should fail synchronously with an exception");
        } catch (IOException e) {
            // splendid!
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    } finally {
        // noinspection ResultOfMethodCallIgnored
        nonWritable.setWritable(true, false);
        try {
            FileUtils.deleteDirectory(nonWritable);
        } catch (IOException e) {
            // best effort
        }
    }
}

From source file:com.android.tradefed.util.FileUtil.java

/**
 * Performs a best effort attempt to make given file group executable,
 * readable, and writable./*  www.j  ava2s .c  om*/
 * <p/ >
 * If 'chmod' system command is not supported by underlying OS, will attempt
 * to set permissions for all users.
 *
 * @param file
 *            the {@link File} to make owner and group writable
 * @return <code>true</code> if permissions were set successfully,
 *         <code>false</code> otherwise
 */
public static boolean chmodGroupRWX(File file) {
    if (chmod(file, "ug+rwx")) {
        return true;
    } else {
        Log.d(LOG_TAG,
                String.format("Failed chmod; attempting to set %s globally RWX", file.getAbsolutePath()));
        return file.setExecutable(true, false /* false == executable for all */)
                && file.setWritable(true, false /* false == writable for all */)
                && file.setReadable(true, false /* false == readable for all */);
    }
}