Example usage for java.io File setExecutable

List of usage examples for java.io File setExecutable

Introduction

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

Prototype

public boolean setExecutable(boolean executable, boolean ownerOnly) 

Source Link

Document

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

Usage

From source file:net.technicpack.autoupdate.Relauncher.java

public void replacePackage(Class mainClass, String targetPath) throws UnsupportedEncodingException {
    String currentPath = getRunningPath(mainClass);
    Utils.getLogger().log(Level.INFO, "Moving running package from " + currentPath + " to " + targetPath);

    File source = new File(currentPath);
    File dest = new File(targetPath);

    if (dest.exists()) {
        if (!dest.delete())
            Utils.getLogger().log(Level.SEVERE, "Deletion of existing package failed!");
    }// w  w w . j a va2s  .c  o  m
    FileInputStream sourceStream = null;
    FileOutputStream destStream = null;
    try {
        sourceStream = new FileInputStream(source);
        destStream = new FileOutputStream(dest);
        IOUtils.copy(sourceStream, destStream);
    } catch (IOException ex) {
        Utils.getLogger().log(Level.SEVERE, "Error attempting to copy download package:", ex);
    } finally {
        IOUtils.closeQuietly(sourceStream);
        IOUtils.closeQuietly(destStream);
    }

    dest.setExecutable(true, true);
}

From source file:org.apache.ambari.server.serveraction.kerberos.CreateKeytabFilesServerAction.java

/**
 * Ensures that the owner of the Ambari server process is the only local user account able to
 * read and write to the specified file or read, write to, and execute the specified directory.
 *
 * @param file the file or directory for which to modify access
 */// w ww. j  a  va2s . c o  m
private void ensureAmbariOnlyAccess(File file) {
    if (file.exists()) {
        if (!file.setReadable(false, false) || !file.setReadable(true, true)) {
            LOG.warn(String.format("Failed to set %s readable only by Ambari", file.getAbsolutePath()));
        }

        if (!file.setWritable(false, false) || !file.setWritable(true, true)) {
            LOG.warn(String.format("Failed to set %s writable only by Ambari", file.getAbsolutePath()));
        }

        if (file.isDirectory()) {
            if (!file.setExecutable(false, false) && !file.setExecutable(true, true)) {
                LOG.warn(String.format("Failed to set %s executable by Ambari", file.getAbsolutePath()));
            }
        } else {
            if (!file.setExecutable(false, false)) {
                LOG.warn(String.format("Failed to set %s not executable", file.getAbsolutePath()));
            }
        }
    }
}

From source file:hdfs.FileUtil.java

/**
 * Set permissions to the required value. Uses the java primitives instead
 * of forking if group == other./*from  ww  w . ja va  2 s .  c om*/
 * @param f the file to change
 * @param permission the new permissions
 * @throws IOException
 */
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    
    if (group != other || NativeIO.isAvailable()) {
        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)) {
        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)) {
        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)) {
        f.setExecutable(user.implies(FsAction.EXECUTE), true);
        checkReturnValue(rv, f, permission);
    }
}

From source file:edu.stolaf.cs.wmrserver.TransformProcessor.java

private File writeTransformSource(String transformTypeString, File jobTransformDir, String scriptExtension,
        String transformSource) throws IOException {
    // Write the script to a temporary file
    File scriptFile = new File(jobTransformDir, "job-" + transformTypeString + scriptExtension);
    if (!scriptFile.createNewFile()) {
        throw new IOException("Could not create " + transformTypeString + " file.");
    }/*  w  w  w .  ja va 2s  .  co m*/

    try {
        FileUtils.writeStringToFile(scriptFile, transformSource);
    } catch (IOException ex) {
        throw new IOException("Could not write " + transformTypeString + " code to disk.", ex);
    }

    // Change file permissions on the new file to ensure it is accessible
    try {
        scriptFile.setReadable(true);
        scriptFile.setExecutable(true, false);
    } catch (SecurityException ex) {
        throw new IOException("Could not assign permissions to " + transformTypeString + " file.", ex);
    }

    return scriptFile;
}

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;//ww  w .  j  av  a2s . c o m
    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:de.helmholtz_muenchen.ibis.knime.preferences.KNIMEPreferencePage.java

private void downloadBinaries(String dir) {
    if (dir == null)
        return;//w  ww . ja  v  a2 s .c o m

    try {
        CheckUtils.checkDestinationDirectory(dir);
    } catch (InvalidSettingsException e1) {
        JOptionPane.showMessageDialog(null, "This directory cannot be used: " + e1.getMessage(), "Error",
                JOptionPane.ERROR_MESSAGE);
        return;
    }

    for (String tool : IBISKNIMENodesPlugin.TOOLS.keySet()) {
        if (IBISKNIMENodesPlugin.TOOLS.get(tool)) {
            if (IBISKNIMENodesPlugin.getStringPreference(tool).equals("")) {
                try {
                    File f = new File(dir + File.separatorChar + tool);
                    if (!f.exists()) {
                        FileUtils.copyURLToFile(new URL(DOWNLOAD_PATH + tool), f);
                        f.setExecutable(true, false);
                        IBISKNIMENodesPlugin.setStringPreference(tool, dir + "/" + tool);

                        HashSet<String> deps = DEPENDENCIES.get(tool);
                        if (deps == null)
                            continue;
                        for (String dep : deps) {
                            File f1 = new File(dir + File.separatorChar + dep);
                            if (!f1.exists()) {
                                FileUtils.copyURLToFile(new URL(DOWNLOAD_PATH + dep), f1);
                                f1.setExecutable(true, false);
                            }
                        }
                    }
                } catch (IOException e) {
                    LOGGER.error("Downloading " + tool + " failed! Message: " + e.getMessage());
                }
            }
        }
    }

    for (TableItem i : table.getItems()) {
        i.setText(1, IBISKNIMENodesPlugin.getStringPreference(i.getText(0)));
    }
}

From source file:net.technicpack.autoupdate.tasks.MoveLauncherPackage.java

@Override
public void runTask(InstallTasksQueue queue) throws IOException, InterruptedException {
    String currentPath = relauncher.getRunningPath();
    Utils.getLogger().log(Level.INFO,
            "Moving running package from " + currentPath + " to " + launcher.getAbsolutePath());

    File source = new File(currentPath);
    File dest = new File(launcher.getAbsolutePath());

    if (!source.equals(dest)) {
        if (dest.exists()) {
            if (!dest.delete())
                Utils.getLogger().log(Level.SEVERE, "Deletion of existing package failed!");
        }/*w w w . j av a2 s .  com*/
        FileInputStream sourceStream = null;
        FileOutputStream destStream = null;

        try {
            if (!dest.getParentFile().exists())
                dest.getParentFile().mkdirs();
            dest.createNewFile();
            sourceStream = new FileInputStream(source);
            destStream = new FileOutputStream(dest);
            IOUtils.copy(sourceStream, destStream);
        } catch (IOException ex) {
            Utils.getLogger().log(Level.SEVERE, "Error attempting to copy download package:", ex);
        } finally {
            IOUtils.closeQuietly(sourceStream);
            IOUtils.closeQuietly(destStream);
        }
    }

    dest.setExecutable(true, true);
}

From source file:sh.tak.appbundler.CreateApplicationBundleMojo.java

/**
 * Copies given resources to the build directory.
 *
 * @param fileSets A list of FileSet objects that represent additional
 * resources to copy.//from w  ww  .j  a  v  a  2 s.  c o  m
 * @throws MojoExecutionException In case of a resource copying error.
 */
private List<String> copyResources(File targetDirectory, List<FileSet> fileSets) throws MojoExecutionException {
    ArrayList<String> addedFiles = new ArrayList<String>();
    for (FileSet fileSet : fileSets) {
        // Get the absolute base directory for the FileSet
        File sourceDirectory = new File(fileSet.getDirectory());

        if (!sourceDirectory.isAbsolute()) {
            sourceDirectory = new File(project.getBasedir(), sourceDirectory.getPath());
        }

        if (!sourceDirectory.exists()) {
            // If the requested directory does not exist, log it and carry on
            getLog().warn("Specified source directory " + sourceDirectory.getPath() + " does not exist.");
            continue;
        }

        List<String> includedFiles = scanFileSet(sourceDirectory, fileSet);
        addedFiles.addAll(includedFiles);

        getLog().info("Copying " + includedFiles.size() + " additional resource"
                + (includedFiles.size() > 1 ? "s" : ""));

        for (String destination : includedFiles) {
            File source = new File(sourceDirectory, destination);
            File destinationFile = new File(targetDirectory, destination);

            // Make sure that the directory we are copying into exists
            destinationFile.getParentFile().mkdirs();

            try {
                FileUtils.copyFile(source, destinationFile);
                destinationFile.setExecutable(fileSet.isExecutable(), false);

            } catch (IOException e) {
                throw new MojoExecutionException("Error copying additional resource " + source, e);
            }
        }
    }
    return addedFiles;
}

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.//from  w ww . j  a v a 2 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.
 *///from w  w w  .  ja v a 2 s  .  co m
@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();
        }
    }
}