Example usage for java.io File setReadable

List of usage examples for java.io File setReadable

Introduction

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

Prototype

public boolean setReadable(boolean readable) 

Source Link

Document

A convenience method to set the owner's read permission for this abstract pathname.

Usage

From source file:org.apache.slider.server.services.security.SecurityUtils.java

private static String getKeystorePassword(File secDirFile, boolean persistPassword) {
    File passFile = new File(secDirFile, SliderKeys.CRT_PASS_FILE_NAME);
    String password = null;//from ww  w.  ja  v  a  2 s . com
    if (!passFile.exists()) {
        LOG.info("Generating keystore password");
        password = RandomStringUtils.randomAlphanumeric(Integer.valueOf(SliderKeys.PASS_LEN));
        if (persistPassword) {
            try {
                FileUtils.writeStringToFile(passFile, password);
                passFile.setWritable(true);
                passFile.setReadable(true);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("Error creating certificate password file");
            }
        }
    } else {
        LOG.info("Reading password from existing file");
        try {
            password = FileUtils.readFileToString(passFile);
            password = password.replaceAll("\\p{Cntrl}", "");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return password;
}

From source file:edu.uw.apl.nativelibloader.NativeLoader.java

static private File extractLibraryFile(String resourceName, File outDir) throws IOException {
    /*// w ww  .j ava  2s . c o m
    Attach UUID to the native library file to essentially
    randomize its name.  This ensures multiple class loaders can
    read it multiple times.
    */
    String uuid = UUID.randomUUID().toString();
    String extractedLibFileName = resourceName.substring(1).replaceAll("/", ".");
    // In Maven terms, the uuid acts like a 'classifier'
    extractedLibFileName += "-" + uuid;
    File extractedLibFile = new File(outDir, extractedLibFileName);
    log.debug("Extracting " + resourceName + " to " + extractedLibFile);

    InputStream is = NativeLoader.class.getResourceAsStream(resourceName);
    FileUtils.copyInputStreamToFile(is, extractedLibFile);
    is.close();
    extractedLibFile.deleteOnExit();

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

    return extractedLibFile;
}

From source file:org.jboss.tools.openshift.reddeer.utils.FileHelper.java

public static void extractTarGz(File archive, File outputDirectory) {
    InputStream inputStream = null;
    try {/*  w w w  .  ja v  a 2s  . co m*/
        logger.info("Opening stream to gzip archive");
        inputStream = new GzipCompressorInputStream(new FileInputStream(archive));
    } catch (IOException ex) {
        throw new OpenShiftToolsException(
                "Exception occured while processing tar.gz file.\n" + ex.getMessage());
    }

    logger.info("Opening stream to tar archive");
    BufferedOutputStream outputStream = null;
    TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(inputStream);
    TarArchiveEntry currentEntry = null;
    try {
        while ((currentEntry = tarArchiveInputStream.getNextTarEntry()) != null) {
            if (currentEntry.isDirectory()) {
                logger.info("Creating directory: " + currentEntry.getName());
                createDirectory(new File(outputDirectory, currentEntry.getName()));
            } else {
                File outputFile = new File(outputDirectory, currentEntry.getName());
                if (!outputFile.getParentFile().exists()) {
                    logger.info("Creating directory: " + outputFile.getParentFile());
                    createDirectory(outputFile.getParentFile());
                }

                outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

                logger.info("Extracting file: " + currentEntry.getName());
                copy(tarArchiveInputStream, outputStream, (int) currentEntry.getSize());
                outputStream.close();

                outputFile.setExecutable(true);
                outputFile.setReadable(true);
                outputFile.setWritable(true);
            }
        }
    } catch (IOException e) {
        throw new OpenShiftToolsException("Exception occured while processing tar.gz file.\n" + e.getMessage());
    } finally {
        try {
            tarArchiveInputStream.close();
        } catch (Exception ex) {
        }
        try {
            outputStream.close();
        } catch (Exception ex) {
        }
    }
}

From source file:org.cytoscape.app.internal.manager.App.java

public static boolean delete(File f) {
    if (!f.exists()) {
        System.err.println("Cannot delete, file does not exist: " + f.getPath());
        return false;
    }/*from w  ww .j  ava  2  s. c  o  m*/
    f.setReadable(true);
    f.setWritable(true);
    if (!f.canWrite()) {
        System.err.println("Cannot delete, file is read-only: " + f.getPath());
        return false;
    }

    // Hack attempt  
    File parent = f.getParentFile();
    parent.setReadable(true);
    parent.setWritable(true);
    if (!parent.canWrite()) {
        System.err.println("Cannot delete, parent folder read-only: " + parent.getPath());
        return false;
    }

    try {
        (new SecurityManager()).checkDelete(f.getPath());
    } catch (Exception ex) {
        System.err.println("Cannot delete file, " + ex.getMessage());
        return false;
    }

    boolean ret = f.delete();
    if (!ret)
        System.err.println("Delete failed: " + f.getPath());
    return ret;
}

From source file:org.jboss.tools.openshift.reddeer.utils.FileHelper.java

private static void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDirectory) {

    if (entry.isDirectory()) {
        createDirectory(new File(outputDirectory, entry.getName()));
        return;// w  w w.  j  av a2  s. c o  m
    }

    File outputFile = new File(outputDirectory, entry.getName());
    if (!outputFile.getParentFile().exists()) {
        createDirectory(outputFile.getParentFile());
    }

    BufferedInputStream inputStream = null;
    BufferedOutputStream outputStream = null;
    try {
        inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
        outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
        copy(inputStream, outputStream, 1024);
    } catch (IOException ex) {
    } finally {
        try {
            outputStream.close();
        } catch (Exception ex) {
        }
        try {
            inputStream.close();
        } catch (Exception ex) {
        }
    }
    outputFile.setExecutable(true);
    outputFile.setReadable(true);
    outputFile.setWritable(true);
}

From source file:org.trellisldp.rosid.file.CachedResourceTest.java

@Test
public void testReadError() {
    final Optional<Resource> res = CachedResource.find(readonly2, rdf.createIRI("trellis:repository/ldpnr"));
    assertTrue(res.isPresent());//from  w w  w  .  j a v a 2  s  .co m

    final File quads = new File(readonly2, RESOURCE_QUADS);
    assumeTrue(quads.setReadable(false));
    assertEquals(0L, res.get().stream().count());
    quads.setReadable(true);
}

From source file:org.pdfsam.ui.JsonWorkspaceServiceTest.java

@Test(expected = RuntimeException.class)
public void cannotAccessWorkspace() throws IOException {
    File file = folder.newFile();
    FileUtils.copyInputStreamToFile(getClass().getResourceAsStream("/workspace.json"), file);
    if (!file.setReadable(false)) {
        throw new RuntimeException("OS does not implement read pemissions");
    }//  w w w .ja  va 2  s .c  o m
    victim.loadWorkspace(file);
}

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

/**
 * Extract the specified library file to the target folder
 * //from   ww w  .j av a2 s . c om
 * @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.falcon.security.AuthenticationInitializationServiceTest.java

@Test
public void testKerberosAuthenticationWithKeytabFileNotReadable() {
    /* Return if OS is Windows because of JDK issue for setReadable */
    if (SystemUtils.IS_OS_WINDOWS) {
        return;/*from w  w  w.  j  a  v  a 2 s.c o  m*/
    }
    File tempFile = new File(".keytabFile");
    try {
        assert tempFile.createNewFile();
        assert tempFile.setReadable(false);

        StartupProperties.get().setProperty(SecurityUtil.AUTHENTICATION_TYPE,
                KerberosAuthenticationHandler.TYPE);
        StartupProperties.get().setProperty(AuthenticationInitializationService.KERBEROS_KEYTAB,
                tempFile.toString());
        authenticationService.init();
        Assert.fail("The keytab file is not readable! must have been thrown.");
    } catch (Exception e) {
        Assert.assertEquals(e.getCause().getClass(), IllegalArgumentException.class);
    } finally {
        assert tempFile.delete();
    }
}

From source file:org.finra.herd.core.HerdFileUtilsTest.java

@Test
public void testVerifyFileExistsAndReadableFileNotReadable() throws IOException {
    File testFile = createLocalFile(localTempPath.toString(), "SOME_FILE", FILE_SIZE_1_KB);

    if (testFile.setReadable(false)) {
        try {/*  ww  w  .  j  a  v a 2 s . c o  m*/
            HerdFileUtils.verifyFileExistsAndReadable(testFile);
            fail("Should throw an IllegalArgumentException when file is not readable.");
        } catch (IllegalArgumentException e) {
            assertEquals(String.format("Unable to read file \"%s\". Check permissions.", testFile.getName()),
                    e.getMessage());
        }
    }
}