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, boolean ownerOnly) 

Source Link

Document

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

Usage

From source file:ezbake.protect.ezca.EzCABootstrap.java

public void ensureDirectory(String path) throws IOException {
    File directory = new File(path);

    if (directory.exists() && !directory.isDirectory()) {
        throw new IOException("Unable to create directory. " + path + " already exists and is not a directory");
    }// w  w  w . j  a v  a  2  s .  c o  m

    if (!directory.mkdirs() && !directory.isDirectory()) {
        throw new IOException("Unable to make directories, mkdirs returned false");
    }

    if (!directory.setExecutable(false, false) || !directory.setExecutable(true, true)) {
        throw new IOException("Created directory, but unable to set executable");
    }
    if (!directory.setReadable(false, false) || !directory.setReadable(true, true)) {
        throw new IOException("Created directory, but unable to set readable");
    }
    if (!directory.setWritable(false, false) || !directory.setWritable(true, true)) {
        throw new IOException("Created directory, but unable to set writable");
    }
}

From source file:hudson.plugins.project_inheritance.projects.view.InheritanceViewAction.java

private boolean dumpBuildSteps(List<Builder> builders, List<File> generatedScripts, File srcDir)
        throws IOException {
    boolean isLinux = true;
    int i = 0;//from  w ww. j a v  a 2  s  .  c om
    for (Builder builder : builders) {
        if (!(builder instanceof CommandInterpreter)) {
            continue;
        }
        CommandInterpreter ci = (CommandInterpreter) builder;
        File builderScript;
        if (builder instanceof BatchFile) {
            isLinux = false;
            builderScript = new File(srcDir, String.format("step_%d.bat", i++));
        } else {
            builderScript = new File(srcDir, String.format("step_%d.sh", i++));
        }

        BufferedWriter out = new BufferedWriter(new FileWriter(builderScript, true));
        String cmd = ci.getCommand();
        if (!isLinux) {
            //Ensure windows line-endings
            cmd = cmd.replaceAll("\r\n", "\n").replaceAll("\n", "\r\n");
        }
        out.write(cmd);
        builderScript.setExecutable(true, false);
        builderScript.setReadable(true, false);
        builderScript.setWritable(true, false);
        out.close();
        generatedScripts.add(builderScript);
    }
    return isLinux;
}

From source file:org.eclipse.acute.OmnisharpStreamConnectionProvider.java

/**
 *
 * @return path to server, unzipping it if necessary. Can be null is fragment is missing.
 *///from   w  ww  .  ja va 2 s.  com
private @Nullable File getServer() throws IOException {
    File serverPath = new File(AcutePlugin.getDefault().getStateLocation().toFile(), "omnisharp-roslyn"); //$NON-NLS-1$
    if (!serverPath.exists()) {
        serverPath.mkdirs();
        try (InputStream stream = FileLocator.openStream(AcutePlugin.getDefault().getBundle(),
                new Path("omnisharp-roslyn.tar"), true); //$NON-NLS-1$
                TarArchiveInputStream tarStream = new TarArchiveInputStream(stream);) {
            TarArchiveEntry entry = null;
            while ((entry = tarStream.getNextTarEntry()) != null) {
                if (!entry.isDirectory()) {
                    File targetFile = new File(serverPath, entry.getName());
                    targetFile.getParentFile().mkdirs();
                    InputStream in = new BoundedInputStream(tarStream, entry.getSize()); // mustn't be closed
                    try (FileOutputStream out = new FileOutputStream(targetFile);) {
                        IOUtils.copy(in, out);
                        if (!Platform.OS_WIN32.equals(Platform.getOS())) {
                            int xDigit = entry.getMode() % 10;
                            targetFile.setExecutable(xDigit > 0, (xDigit & 1) == 1);
                            int wDigit = (entry.getMode() / 10) % 10;
                            targetFile.setWritable(wDigit > 0, (wDigit & 1) == 1);
                            int rDigit = (entry.getMode() / 100) % 10;
                            targetFile.setReadable(rDigit > 0, (rDigit & 1) == 1);
                        }
                    }
                }
            }
        }
    }
    return serverPath;
}

From source file:com.meetme.plugins.jira.gerrit.adminui.AdminServlet.java

private File doUploadPrivateKey(final List<FileItem> items, final String sshHostname) throws IOException {
    File privateKeyPath = null;

    for (FileItem item : items) {
        if (item.getFieldName().equals(GerritConfiguration.FIELD_SSH_PRIVATE_KEY) && item.getSize() > 0) {
            File dataDir = new File(jiraHome.getDataDirectory(),
                    StringUtils.join(PACKAGE_PARTS, File.separatorChar));

            if (!dataDir.exists()) {
                dataDir.mkdirs();//from  w w  w .  ja  va2 s  . c om
            }

            String tempFilePrefix = configurationManager.getSshHostname();
            String tempFileSuffix = ".key";

            try {
                privateKeyPath = File.createTempFile(tempFilePrefix, tempFileSuffix, dataDir);
            } catch (IOException e) {
                log.info("---- Cannot create temporary file: " + e.getMessage() + ": " + dataDir.toString()
                        + tempFilePrefix + tempFileSuffix + " ----");
                break;
            }

            privateKeyPath.setReadable(false, false);
            privateKeyPath.setReadable(true, true);

            InputStream is = item.getInputStream();
            FileOutputStream fos = new FileOutputStream(privateKeyPath);
            IOUtils.copy(is, fos);
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(fos);

            item.delete();
            break;
        }
    }

    return privateKeyPath;
}

From source file:edu.umd.cs.buildServer.BuildServer.java

/**
 * Makes a directory world-readable./*from  www  . j ava  2s.com*/
 * <p>
 * This will not work on Windows!
 *
 * @param dirName
 *            The directory to make world-readable.
 * @throws IOException
 */
private void makeDirectoryWorldReadable(File dir) throws IOException {
    // TODO Make sure that this is a non-Windows machine.

    if (dir.isDirectory()) {
        dir.setReadable(true, false);
        dir.setWritable(true, false);
        dir.setExecutable(true, false);
    }
}

From source file:org.apache.flink.runtime.blob.BlobServerGetTest.java

/**
 * Retrieves a BLOB from the HA store to a {@link BlobServer} which cannot create incoming
 * files. File transfers should fail.// w w  w .j  a v a2 s. c  o m
 */
@Test
public void testGetFailsIncomingForJobHa() throws IOException {
    assumeTrue(!OperatingSystem.isWindows()); //setWritable doesn't work on Windows.

    final JobID jobId = new JobID();

    final Configuration config = new Configuration();
    config.setString(HighAvailabilityOptions.HA_MODE, "ZOOKEEPER");
    config.setString(BlobServerOptions.STORAGE_DIRECTORY, temporaryFolder.newFolder().getAbsolutePath());
    config.setString(HighAvailabilityOptions.HA_STORAGE_PATH, temporaryFolder.newFolder().getPath());

    BlobStoreService blobStore = null;

    try {
        blobStore = BlobUtils.createBlobStoreFromConfig(config);

        File tempFileDir = null;
        try (BlobServer server = new BlobServer(config, blobStore)) {

            server.start();

            // store the data on the server (and blobStore), remove from local store
            byte[] data = new byte[2000000];
            rnd.nextBytes(data);
            BlobKey blobKey = put(server, jobId, data, PERMANENT_BLOB);
            assertTrue(server.getStorageLocation(jobId, blobKey).delete());

            // make sure the blob server cannot create any files in its storage dir
            tempFileDir = server.createTemporaryFilename().getParentFile();
            assertTrue(tempFileDir.setExecutable(true, false));
            assertTrue(tempFileDir.setReadable(true, false));
            assertTrue(tempFileDir.setWritable(false, false));

            // request the file from the BlobStore
            exception.expect(IOException.class);
            exception.expectMessage("Permission denied");

            try {
                get(server, jobId, blobKey);
            } finally {
                HashSet<String> expectedDirs = new HashSet<>();
                expectedDirs.add("incoming");
                expectedDirs.add(JOB_DIR_PREFIX + jobId);
                // only the incoming and job directory should exist (no job directory!)
                File storageDir = tempFileDir.getParentFile();
                String[] actualDirs = storageDir.list();
                assertNotNull(actualDirs);
                assertEquals(expectedDirs, new HashSet<>(Arrays.asList(actualDirs)));

                // job directory should be empty
                File jobDir = new File(tempFileDir.getParentFile(), JOB_DIR_PREFIX + jobId);
                assertArrayEquals(new String[] {}, jobDir.list());
            }
        } finally {
            // set writable again to make sure we can remove the directory
            if (tempFileDir != null) {
                //noinspection ResultOfMethodCallIgnored
                tempFileDir.setWritable(true, false);
            }
        }
    } finally {
        if (blobStore != null) {
            blobStore.closeAndCleanupAllData();
        }
    }
}

From source file:org.apache.flink.runtime.blob.BlobServerGetTest.java

/**
 * Retrieves a BLOB from the HA store to a {@link BlobServer} which cannot create the final
 * storage file. File transfers should fail.
 *///  ww  w  .j  av a2  s . com
@Test
public void testGetFailsStoreForJobHa() throws IOException {
    assumeTrue(!OperatingSystem.isWindows()); //setWritable doesn't work on Windows.

    final JobID jobId = new JobID();

    final Configuration config = new Configuration();
    config.setString(HighAvailabilityOptions.HA_MODE, "ZOOKEEPER");
    config.setString(BlobServerOptions.STORAGE_DIRECTORY, temporaryFolder.newFolder().getAbsolutePath());
    config.setString(HighAvailabilityOptions.HA_STORAGE_PATH, temporaryFolder.newFolder().getPath());

    BlobStoreService blobStore = null;

    try {
        blobStore = BlobUtils.createBlobStoreFromConfig(config);

        File jobStoreDir = null;
        try (BlobServer server = new BlobServer(config, blobStore)) {

            server.start();

            // store the data on the server (and blobStore), remove from local store
            byte[] data = new byte[2000000];
            rnd.nextBytes(data);
            BlobKey blobKey = put(server, jobId, data, PERMANENT_BLOB);
            assertTrue(server.getStorageLocation(jobId, blobKey).delete());

            // make sure the blob cache cannot create any files in its storage dir
            jobStoreDir = server.getStorageLocation(jobId, blobKey).getParentFile();
            assertTrue(jobStoreDir.setExecutable(true, false));
            assertTrue(jobStoreDir.setReadable(true, false));
            assertTrue(jobStoreDir.setWritable(false, false));

            // request the file from the BlobStore
            exception.expect(AccessDeniedException.class);

            try {
                get(server, jobId, blobKey);
            } finally {
                // there should be no remaining incoming files
                File incomingFileDir = new File(jobStoreDir.getParent(), "incoming");
                assertArrayEquals(new String[] {}, incomingFileDir.list());

                // there should be no files in the job directory
                assertArrayEquals(new String[] {}, jobStoreDir.list());
            }
        } finally {
            // set writable again to make sure we can remove the directory
            if (jobStoreDir != null) {
                //noinspection ResultOfMethodCallIgnored
                jobStoreDir.setWritable(true, false);
            }
        }
    } finally {
        if (blobStore != null) {
            blobStore.closeAndCleanupAllData();
        }
    }
}

From source file:com.codesourcery.internal.installer.InstallManager.java

/**
 * Copies the installer to a location.// ww  w .ja  v a 2s . co m
 * 
 * @param location Destination location
 * @param monitor Progress monitor
 * @throws CoreException on failure
 */
private void copyInstaller(IPath destinationLocation, IProgressMonitor monitor) throws CoreException {
    try {
        File uninstallDirectory = destinationLocation.toFile();
        if (!uninstallDirectory.exists()) {
            uninstallDirectory.mkdirs();
        }

        String[] uninstallFiles = getInstallDescription().getUninstallFiles();
        if (uninstallFiles != null) {
            for (String uninstallFile : uninstallFiles) {
                String destinationFileName = uninstallFile;
                String srcFileName = uninstallFile;

                // Parse file name for ":" if renaming of destination file is desired.
                if (uninstallFile.contains(":")) {
                    srcFileName = uninstallFile.substring(0, uninstallFile.indexOf(":"));
                    destinationFileName = uninstallFile.substring(uninstallFile.indexOf(":") + 1);
                }

                IPath destPath = destinationLocation.append(destinationFileName);
                File srcFile = Installer.getDefault().getInstallFile(srcFileName);
                if (srcFile.exists()) {
                    File destFile = destPath.toFile();

                    if (srcFile.isDirectory()) {
                        FileUtils.copyDirectory(srcFile, destFile);
                    } else {
                        FileUtils.copyFile(srcFile, destFile);
                    }

                    // Set permissions
                    destFile.setExecutable(srcFile.canExecute(), false);
                    destFile.setReadable(srcFile.canRead(), false);
                    destFile.setWritable(srcFile.canWrite(), false);
                }
            }
        }
    } catch (Exception e) {
        Installer.log(
                "Failed to copy installer.  This could be because you are running from the Eclipse workbench and the exported RCP binary files are not available.");
    }
}

From source file:org.apache.flink.runtime.blob.BlobServerPutTest.java

/**
 * Uploads a byte array to a server which cannot create incoming files via the {@link
 * BlobServer}. File transfers should fail.
 *
 * @param jobId//from   ww  w.  ja v  a2 s.c  om
 *       job id
 * @param blobType
 *       whether the BLOB should become permanent or transient
 */
private void testPutBufferFailsIncoming(@Nullable final JobID jobId, BlobKey.BlobType blobType)
        throws IOException {
    assumeTrue(!OperatingSystem.isWindows()); //setWritable doesn't work on Windows.

    final Configuration config = new Configuration();
    config.setString(BlobServerOptions.STORAGE_DIRECTORY, temporaryFolder.newFolder().getAbsolutePath());

    File tempFileDir = null;
    try (BlobServer server = new BlobServer(config, new VoidBlobStore())) {

        server.start();

        // make sure the blob server cannot create any files in its storage dir
        tempFileDir = server.createTemporaryFilename().getParentFile();
        assertTrue(tempFileDir.setExecutable(true, false));
        assertTrue(tempFileDir.setReadable(true, false));
        assertTrue(tempFileDir.setWritable(false, false));

        byte[] data = new byte[2000000];
        rnd.nextBytes(data);

        // upload the file to the server directly
        exception.expect(IOException.class);
        exception.expectMessage(" (Permission denied)");

        try {
            put(server, jobId, data, blobType);
        } finally {
            File storageDir = tempFileDir.getParentFile();
            // only the incoming directory should exist (no job directory!)
            assertArrayEquals(new String[] { "incoming" }, storageDir.list());
        }
    } finally {
        // set writable again to make sure we can remove the directory
        if (tempFileDir != null) {
            //noinspection ResultOfMethodCallIgnored
            tempFileDir.setWritable(true, false);
        }
    }
}

From source file:org.apache.flink.runtime.blob.BlobServerPutTest.java

/**
 * Uploads a byte array to a server which cannot create any files via the {@link BlobServer}.
 * File transfers should fail.//from   w  w  w.j a v a  2 s  .  com
 *
 * @param jobId
 *       job id
 * @param blobType
 *       whether the BLOB should become permanent or transient
 */
private void testPutBufferFails(@Nullable final JobID jobId, BlobKey.BlobType blobType) throws IOException {
    assumeTrue(!OperatingSystem.isWindows()); //setWritable doesn't work on Windows.

    final Configuration config = new Configuration();
    config.setString(BlobServerOptions.STORAGE_DIRECTORY, temporaryFolder.newFolder().getAbsolutePath());

    File tempFileDir = null;
    try (BlobServer server = new BlobServer(config, new VoidBlobStore())) {

        server.start();

        // make sure the blob server cannot create any files in its storage dir
        tempFileDir = server.createTemporaryFilename().getParentFile().getParentFile();
        assertTrue(tempFileDir.setExecutable(true, false));
        assertTrue(tempFileDir.setReadable(true, false));
        assertTrue(tempFileDir.setWritable(false, false));

        byte[] data = new byte[2000000];
        rnd.nextBytes(data);

        // upload the file to the server directly
        exception.expect(AccessDeniedException.class);

        put(server, jobId, data, blobType);

    } finally {
        // set writable again to make sure we can remove the directory
        if (tempFileDir != null) {
            //noinspection ResultOfMethodCallIgnored
            tempFileDir.setWritable(true, false);
        }
    }
}