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:hudson.plugins.project_inheritance.projects.view.InheritanceViewAction.java

private void dumpMasterScript(boolean isLinux, List<File> generatedScripts, File srcDir) throws IOException {
    Map<String, String> parameters = getResolvedBuildParameters(this.getBuild());

    String scrFile = (isLinux) ? "build.sh" : "build.bat";
    String scrPreamble = (isLinux) ? "#!/bin/bash" : "@echo off";
    String scrSetCmd = (isLinux) ? "export" : "set";
    String scrInvoke = (isLinux) ? "./" : "CALL ";
    String lineEnd = (isLinux) ? "\n" : "\r\n";

    File mainScript = new File(srcDir, scrFile);
    BufferedWriter out = new BufferedWriter(new FileWriter(mainScript, true));
    out.write(scrPreamble);/*from ww  w. ja va  2  s .com*/
    out.write(lineEnd);

    if (parameters.size() > 0) {
        for (String parameter : parameters.keySet()) {
            out.write(
                    String.format("%s %s=\"%s\"%s", scrSetCmd, parameter, parameters.get(parameter), lineEnd));
        }
    }

    for (File script : generatedScripts) {
        if (isLinux) {
            out.write(String.format("echo 'Will run %s now ...'%s", script.getName(), lineEnd));
        } else {
            out.write(String.format("echo Will run %s now ...%s", script.getName(), lineEnd));
        }
        out.write(String.format("%s%s%s", scrInvoke, script.getName(), lineEnd));
    }
    if (isLinux) {
        mainScript.setExecutable(true, false);
        mainScript.setWritable(true, false);
        mainScript.setReadable(true, false);
    }
    out.close();
    generatedScripts.add(mainScript);
}

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

/**
 * Copies the installer to a location.//  w ww.j a va 2 s .  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.BlobCacheGetTest.java

/**
 * Uploads a byte array for the given job and verifies that a get operation of a transient BLOB
 * (via the {@link BlobCacheService}; also deletes the file on the {@link BlobServer}) does not
 * fail even if the file is not deletable on the {@link BlobServer}, e.g. via restricting the
 * permissions.//ww  w . j ava  2s .co  m
 *
 * @param jobId
 *       job id
 */
private void testGetTransientRemoteDeleteFails(@Nullable final JobID jobId) 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 blobFile = null;
    File directory = null;

    try (BlobServer server = new BlobServer(config, new VoidBlobStore());
            BlobCacheService cache = new BlobCacheService(config, new VoidBlobStore(),
                    new InetSocketAddress("localhost", server.getPort()))) {

        server.start();

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

            // put BLOB
            TransientBlobKey key = (TransientBlobKey) put(server, jobId, data, TRANSIENT_BLOB);
            assertNotNull(key);

            blobFile = server.getStorageLocation(jobId, key);
            directory = blobFile.getParentFile();

            assertTrue(blobFile.setWritable(false, false));
            assertTrue(directory.setWritable(false, false));

            // access from cache once which also deletes the file on the server
            verifyContents(cache, jobId, key, data);
            // delete locally (should not be affected by the server)
            assertTrue(delete(cache, jobId, key));
            File blobFileAtCache = cache.getTransientBlobService().getStorageLocation(jobId, key);
            assertFalse(blobFileAtCache.exists());

            // the file should still be there on the server
            verifyContents(server, jobId, key, data);
            // ... and may be retrieved by the cache
            verifyContents(cache, jobId, key, data);
        } finally {
            if (blobFile != null && directory != null) {
                //noinspection ResultOfMethodCallIgnored
                blobFile.setWritable(true, false);
                //noinspection ResultOfMethodCallIgnored
                directory.setWritable(true, false);
            }
        }
    }
}

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 w  w  w  .  j  a  v a2s .  c  o m
 *       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.ja v a 2s  .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);
        }
    }
}

From source file:org.apache.giraph.zk.ZooKeeperManager.java

/**
 * Whoever is elected to be a ZooKeeper server must generate a config file
 * locally./*from  w  w w  . java2s  .  co  m*/
 *
 * @param serverList List of ZooKeeper servers.
 */
private void generateZooKeeperConfigFile(List<String> serverList) {
    if (LOG.isInfoEnabled()) {
        LOG.info("generateZooKeeperConfigFile: Creating file " + configFilePath + " in " + zkDir
                + " with base port " + zkBasePort);
    }
    try {
        File zkDirFile = new File(this.zkDir);
        boolean mkDirRet = zkDirFile.mkdirs();
        if (LOG.isInfoEnabled()) {
            LOG.info(
                    "generateZooKeeperConfigFile: Make directory of " + zkDirFile.getName() + " = " + mkDirRet);
        }
        File configFile = new File(configFilePath);
        boolean deletedRet = configFile.delete();
        if (LOG.isInfoEnabled()) {
            LOG.info("generateZooKeeperConfigFile: Delete of " + configFile.getName() + " = " + deletedRet);
        }
        if (!configFile.createNewFile()) {
            throw new IllegalStateException(
                    "generateZooKeeperConfigFile: Failed to " + "create config file " + configFile.getName());
        }
        // Make writable by everybody
        if (!configFile.setWritable(true, false)) {
            throw new IllegalStateException(
                    "generateZooKeeperConfigFile: Failed to make writable " + configFile.getName());
        }

        Writer writer = null;
        try {
            writer = new FileWriter(configFilePath);
            writer.write("tickTime=" + GiraphConstants.DEFAULT_ZOOKEEPER_TICK_TIME + "\n");
            writer.write("dataDir=" + this.zkDir + "\n");
            writer.write("clientPort=" + zkBasePort + "\n");
            writer.write("maxClientCnxns=" + GiraphConstants.DEFAULT_ZOOKEEPER_MAX_CLIENT_CNXNS + "\n");
            writer.write("minSessionTimeout=" + conf.getZooKeeperMinSessionTimeout() + "\n");
            writer.write("maxSessionTimeout=" + conf.getZooKeeperMaxSessionTimeout() + "\n");
            writer.write("initLimit=" + GiraphConstants.DEFAULT_ZOOKEEPER_INIT_LIMIT + "\n");
            writer.write("syncLimit=" + GiraphConstants.DEFAULT_ZOOKEEPER_SYNC_LIMIT + "\n");
            writer.write("snapCount=" + GiraphConstants.DEFAULT_ZOOKEEPER_SNAP_COUNT + "\n");
            writer.write("forceSync=" + (conf.getZooKeeperForceSync() ? "yes" : "no") + "\n");
            writer.write("skipACL=" + (conf.getZooKeeperSkipAcl() ? "yes" : "no") + "\n");
            if (serverList.size() != 1) {
                writer.write("electionAlg=0\n");
                for (int i = 0; i < serverList.size(); ++i) {
                    writer.write("server." + i + "=" + serverList.get(i) + ":" + (zkBasePort + 1) + ":"
                            + (zkBasePort + 2) + "\n");
                    if (myHostname.equals(serverList.get(i))) {
                        Writer myidWriter = null;
                        try {
                            myidWriter = new FileWriter(zkDir + "/myid");
                            myidWriter.write(i + "\n");
                        } finally {
                            Closeables.closeQuietly(myidWriter);
                        }
                    }
                }
            }
        } finally {
            Closeables.closeQuietly(writer);
        }
    } catch (IOException e) {
        throw new IllegalStateException("generateZooKeeperConfigFile: Failed to write file", e);
    }
}

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

/**
 * Uploads a byte array to a server which cannot move incoming files to the final blob store via
 * the {@link BlobServer}. File transfers should fail.
 *
 * @param jobId//from   w  w w.  j  a  v  a2 s  .  c  o m
 *       job id
 * @param blobType
 *       whether the BLOB should become permanent or transient
 */
private void testPutBufferFailsStore(@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 jobStoreDir = null;
    try (BlobServer server = new BlobServer(config, new VoidBlobStore())) {

        server.start();

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

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

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

        try {
            put(server, jobId, data, blobType);
        } 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);
        }
    }
}

From source file:com.thoughtworks.go.server.service.GoConfigServiceTest.java

@Test
public void shouldThrowIfCruiseHasNoWritePermissionOnArtifactsDir() throws Exception {
    if (SystemUtils.IS_OS_WINDOWS) {
        return;/*w  ww  .j  a  v  a2s.c o m*/
    }
    File artifactsDir = FileUtil.createTempFolder();
    artifactsDir.setWritable(false, false);
    cruiseConfig.setServerConfig(new ServerConfig(artifactsDir.getAbsolutePath(), new SecurityConfig()));
    expectLoad(cruiseConfig);

    try {
        goConfigService.initialize();
        fail("should throw when cruise has no write permission on artifacts dir "
                + artifactsDir.getAbsolutePath());
    } catch (Exception e) {
        assertThat(e.getMessage(),
                is("Cruise does not have write permission on " + artifactsDir.getAbsolutePath()));
    } finally {
        FileUtils.deleteQuietly(artifactsDir);
    }

}

From source file:com.houghtonassociates.bamboo.plugins.GerritRepositoryAdapter.java

public synchronized File prepareConfigDir(String strRelativePath) {
    String filePath = getBaseBuildWorkingDirectory() + File.separator + strRelativePath;

    File f = new File(filePath);

    f.setReadable(true, true);/* w  w  w.  j a  va2  s  .  com*/
    f.setWritable(true, true);
    f.setExecutable(true, true);

    f.mkdir();

    return f;
}

From source file:com.houghtonassociates.bamboo.plugins.GerritRepositoryAdapter.java

public synchronized File prepareSSHKeyFile(String strRelativePath, String sshKey) {
    String filePath = getBaseBuildWorkingDirectory() + File.separator + strRelativePath;

    File f = new File(filePath);

    f.setReadable(true, true);//www.  j  a  v  a2 s  .  c  o m
    f.setWritable(true, true);
    f.setExecutable(false, false);

    try {
        FileUtils.writeStringToFile(f, sshKey);
    } catch (IOException e) {
        log.error(e.getMessage());
        return null;
    }

    try {
        if (SystemUtils.IS_OS_UNIX || SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_MAC_OSX)
            Runtime.getRuntime().exec("chmod 700 " + filePath);
    } catch (IOException e) {
        log.warn(e.getMessage());
    }

    return f;
}