Java Code Examples for java.io.File#setExecutable()

The following examples show how to use java.io.File#setExecutable() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Build.java    From APDE with GNU General Public License v2.0 6 votes vote down vote up
static public void copyFile(File sourceFile, File targetFile) throws IOException {
	BufferedInputStream from = new BufferedInputStream(new FileInputStream(sourceFile));
	BufferedOutputStream to = new BufferedOutputStream(new FileOutputStream(targetFile));
	byte[] buffer = new byte[16 * 1024];
	int bytesRead;
	while((bytesRead = from.read(buffer)) != -1)
		to.write(buffer, 0, bytesRead);
	from.close();
	from = null;

	to.flush();
	to.close();
	to = null;

	targetFile.setLastModified(sourceFile.lastModified());
	targetFile.setExecutable(sourceFile.canExecute());
}
 
Example 2
Source File: TestReify.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static File makedir(String name, boolean clear) throws IOException {
  File dir = new File(name);
  dir.mkdirs(); // ensure existence
  // Change permissions to allow read/write by anyone
  dir.setExecutable(true, false);
  dir.setReadable(true, false);
  dir.setWritable(true, false);
  if (!dir.canRead())
    throw new IOException(name + ": cannot read");
  if (!dir.canWrite())
    throw new IOException(name + ": cannot write");
  // optionally clear out the dir
  if (clear)
    deleteTree(name, false);
  return dir;
}
 
Example 3
Source File: FileUtil.java    From copybara with Apache License 2.0 6 votes vote down vote up
/**
 * Tries to add the Posix permissions if the file belongs to a Posix filesystem. This is an
 * addition, which means that no permissions are removed.
 *
 * <p>For Windows type filesystems, it uses setReadable/setWritable/setExecutable, which is only
 * supported for the owner, and ignores the rest of permissions.
 */
public static void addPermissions(Path path, Set<PosixFilePermission> permissionsToAdd)
    throws IOException {
  if (path.getFileSystem().supportedFileAttributeViews().contains("posix")) {
    Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(path);
    permissions.addAll(permissionsToAdd);
    Files.setPosixFilePermissions(path, permissions);
  } else {
    File file = path.toFile();
    if (permissionsToAdd.contains(PosixFilePermission.OWNER_READ)) {
      if (!file.setReadable(true)) {
        throw new IOException("Could not set 'readable' permission for file: " + path);
      }
    }
    if (permissionsToAdd.contains(PosixFilePermission.OWNER_WRITE)) {
      if (!file.setWritable(true)) {
        throw new IOException("Could not set 'writable' permission for file: " + path);
      }
    }
    if (permissionsToAdd.contains(PosixFilePermission.OWNER_EXECUTE)) {
      if (!file.setExecutable(true)) {
        throw new IOException("Could not set 'executable' permission for file: " + path);
      }
    }
  }
}
 
Example 4
Source File: TestExecuteStreamCommand.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoggingToStdErr() throws IOException {
    File exJar = new File("src/test/resources/ExecuteCommand/TestLogStdErr.jar");
    File dummy = new File("src/test/resources/ExecuteCommand/1mb.txt");
    String jarPath = exJar.getAbsolutePath();
    exJar.setExecutable(true);
    final TestRunner controller = TestRunners.newTestRunner(ExecuteStreamCommand.class);
    controller.setValidateExpressionUsage(false);
    controller.enqueue(dummy.toPath());
    controller.setProperty(ExecuteStreamCommand.EXECUTION_COMMAND, "java");
    controller.setProperty(ExecuteStreamCommand.EXECUTION_ARGUMENTS, "-jar;" + jarPath);
    controller.run(1);
    controller.assertTransferCount(ExecuteStreamCommand.ORIGINAL_RELATIONSHIP, 1);
    controller.assertTransferCount(ExecuteStreamCommand.OUTPUT_STREAM_RELATIONSHIP, 1);
    List<MockFlowFile> flowFiles = controller.getFlowFilesForRelationship(ExecuteStreamCommand.OUTPUT_STREAM_RELATIONSHIP);
    MockFlowFile flowFile = flowFiles.get(0);
    assertEquals(0, flowFile.getSize());
    assertEquals("fffffffffffffffffffffffffffffff", flowFile.getAttribute("execution.error").substring(0, 31));
}
 
Example 5
Source File: GlslReduceTest.java    From graphicsfuzz with Apache License 2.0 6 votes vote down vote up
@Test
public void testAlwaysReduceJudgeMaximallyReduces() throws Exception {
  final File jsonFile = getShaderJobReady();
  // We make this a .bat file to avoid a "what application would you like to use to open this
  // file?" pop-up on Windows.  (On other platforms the fact that it has the .bat extension does
  // not matter.)
  final File emptyFile = temporaryFolder.newFile("judge.bat");
  emptyFile.setExecutable(true);
  GlslReduce.mainHelper(new String[]{
      jsonFile.getAbsolutePath(),
      "--reduction-kind",
      "CUSTOM",
      emptyFile.getAbsolutePath(),
      "--output",
      temporaryFolder.getRoot().getAbsolutePath()}, null);
  final File[] reducedFinal = temporaryFolder.getRoot().listFiles((dir, name) -> name.contains(
      "reduced_final.frag"));
  assertEquals(1, reducedFinal.length);
  CompareAsts.assertEqualAsts("#version 100\nvoid main() { }",
      ParseHelper.parse(reducedFinal[0]));
}
 
Example 6
Source File: KubeConfigTest.java    From java with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecCredentialsBasedir() throws Exception {
  File basedir = folder.newFolder();
  File config = new File(basedir, ".kubeconfig");
  try (FileWriter writer = new FileWriter(config)) {
    writer.write(KUBECONFIG_EXEC_BASEDIR);
    writer.flush();
  }
  File bindir = new File(basedir, "bin");
  bindir.mkdir();
  File script = new File(bindir, "authenticate");
  try (FileWriter writer = new FileWriter(script)) {
    writer.write(AUTH_SCRIPT);
    writer.flush();
  }
  script.setExecutable(true);
  try (FileReader reader = new FileReader(config)) {
    KubeConfig kc = KubeConfig.loadKubeConfig(reader);
    kc.setFile(config);
    assertEquals("abc123", kc.getAccessToken());
  }
}
 
Example 7
Source File: TestExecuteStreamCommand.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteJarWithBadPath() throws Exception {
    File exJar = new File("src/test/resources/ExecuteCommand/noSuchFile.jar");
    File dummy = new File("src/test/resources/ExecuteCommand/1000bytes.txt");
    String jarPath = exJar.getAbsolutePath();
    exJar.setExecutable(true);
    final TestRunner controller = TestRunners.newTestRunner(ExecuteStreamCommand.class);
    controller.enqueue(dummy.toPath());
    controller.setProperty(ExecuteStreamCommand.EXECUTION_COMMAND, "java");
    controller.setProperty(ExecuteStreamCommand.EXECUTION_ARGUMENTS, "-jar;" + jarPath);
    controller.run(1);
    controller.assertTransferCount(ExecuteStreamCommand.ORIGINAL_RELATIONSHIP, 1);
    controller.assertTransferCount(ExecuteStreamCommand.OUTPUT_STREAM_RELATIONSHIP, 0);
    controller.assertTransferCount(ExecuteStreamCommand.NONZERO_STATUS_RELATIONSHIP, 1);
    List<MockFlowFile> flowFiles = controller.getFlowFilesForRelationship(ExecuteStreamCommand.NONZERO_STATUS_RELATIONSHIP);
    MockFlowFile flowFile = flowFiles.get(0);
    assertEquals(0, flowFile.getSize());
    assertEquals("Error: Unable to access jarfile", flowFile.getAttribute("execution.error").substring(0, 31));
    assertTrue(flowFile.isPenalized());
}
 
Example 8
Source File: BatchEvaluator.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@Override
public EvaluationResult evaluate(File input, File output) throws EvaluationException {
    if (!sandbox.containsFile(executableFilename)) {
        sandbox.addFile(new File(compilationDir, executableFilename));
        File executableFile = sandbox.getFile(executableFilename);
        if (!executableFile.setExecutable(true)) {
            throw new EvaluationException("Cannot set " + executableFile.getAbsolutePath() + " as executable");
        }
    }

    TestCaseVerdict verdict;

    GenerationResult generationResult = generate(input, output);
    if (generationResult.getVerdict().isPresent()) {
        verdict = generationResult.getVerdict().get();
    } else {
        ScoringResult scoringResult = score(input, output);
        verdict = scoringResult.getVerdict();
    }

    return new EvaluationResult.Builder()
            .verdict(verdict)
            .executionResult(generationResult.getExecutionResult())
            .build();
}
 
Example 9
Source File: MacOSTerminalOpener.java    From phoenicis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void openTerminal(String workingDirectory, Map<String, String> environmentVariables) {
    try {
        final File temporaryScript = File.createTempFile("terminal", "sh");
        if (temporaryScript.setExecutable(true)) {
            temporaryScript.deleteOnExit();
            try (FileOutputStream fileOutputStream = new FileOutputStream(temporaryScript)) {
                IOUtils.write(createScript(workingDirectory, environmentVariables), fileOutputStream, "UTF-8");
                fileOutputStream.flush();
            }

            final ProcessBuilder processBuilder = new ProcessBuilder().command("/usr/bin/open", "-b",
                    "com.apple.terminal", temporaryScript.getAbsolutePath());

            processBuilder.start();
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 10
Source File: Tools.java    From m2g_android_miner with GNU General Public License v3.0 6 votes vote down vote up
public static void copyFile(Context context, String assetFilePath, String localFilePath) {
    try {
        InputStream in = context.getAssets().open(assetFilePath);
        FileOutputStream out = new FileOutputStream(localFilePath);
        int read;
        byte[] buffer = new byte[4096];
        while ((read = in.read(buffer)) > 0) {
            out.write(buffer, 0, read);
        }
        out.close();
        in.close();

        File bin = new File(localFilePath);
        bin.setExecutable(true);

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 11
Source File: DecompilationBugTest.java    From securify with Apache License 2.0 5 votes vote down vote up
private void processWithoutException(String filesol) throws IOException, InterruptedException {
    File tmpFile = File.createTempFile("solc-0.5", "");
    String tmpPath = tmpFile.getPath();
    URL website = new URL("https://github.com/ethereum/solidity/releases/download/v0.5.0/solc-static-linux");
    try (InputStream in = website.openStream()) {
        Files.copy(in, tmpFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }
    File f = new File(tmpPath);
    f.setExecutable(true, true);
    String livestatusfile = File.createTempFile("securify_livestatusfile", "").getPath();
    TreeMap<String, SolidityResult> output = processSolidityFile(tmpPath, filesol, livestatusfile);
    output.values().forEach(s -> TestCase.assertTrue(s.securifyErrors.isEmpty()));
}
 
Example 12
Source File: TestRSGroupMappingScript.java    From hbase with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  script = new File(UTIL.getConfiguration().get(RSGroupMappingScript.RS_GROUP_MAPPING_SCRIPT));
  if (!script.createNewFile()) {
    throw new IOException("Can't create script");
  }

  PrintWriter pw = new PrintWriter(new FileOutputStream(script));
  try {
    pw.println("#!/bin/bash");
    pw.println("namespace=$1");
    pw.println("tablename=$2");
    pw.println("if [[ $namespace == test ]]; then");
    pw.println("  echo test");
    pw.println("elif [[ $tablename == *foo* ]]; then");
    pw.println("  echo other");
    pw.println("else");
    pw.println("  echo default");
    pw.println("fi");
    pw.flush();
  } finally {
    pw.close();
  }
  boolean executable = script.setExecutable(true);
  LOG.info("Created " + script  + ", executable=" + executable);
  verifyScriptContent(script);
}
 
Example 13
Source File: TestExecuteStreamCommand.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testExecuteJarToAttributeConfiguration() throws Exception {
    File exJar = new File("src/test/resources/ExecuteCommand/TestSuccess.jar");
    String jarPath = exJar.getAbsolutePath();
    exJar.setExecutable(true);
    final TestRunner controller = TestRunners.newTestRunner(ExecuteStreamCommand.class);
    controller.enqueue("small test".getBytes());
    controller.setProperty(ExecuteStreamCommand.EXECUTION_COMMAND, "java");
    controller.setProperty(ExecuteStreamCommand.EXECUTION_ARGUMENTS, "-jar;" + jarPath);
    controller.setProperty(ExecuteStreamCommand.PUT_ATTRIBUTE_MAX_LENGTH, "10");
    controller.setProperty(ExecuteStreamCommand.PUT_OUTPUT_IN_ATTRIBUTE, "outputDest");
    assertEquals(1, controller.getProcessContext().getAvailableRelationships().size());
    controller.run(1);
    controller.assertTransferCount(ExecuteStreamCommand.ORIGINAL_RELATIONSHIP, 1);
    controller.assertTransferCount(ExecuteStreamCommand.OUTPUT_STREAM_RELATIONSHIP, 0);
    controller.assertTransferCount(ExecuteStreamCommand.NONZERO_STATUS_RELATIONSHIP, 0);

    List<MockFlowFile> flowFiles = controller.getFlowFilesForRelationship(ExecuteStreamCommand.ORIGINAL_RELATIONSHIP);
    MockFlowFile outputFlowFile = flowFiles.get(0);
    outputFlowFile.assertContentEquals("small test".getBytes());
    String result = outputFlowFile.getAttribute("outputDest");
    assertTrue(Pattern.compile("Test was a").matcher(result).find());
    assertEquals("0", outputFlowFile.getAttribute("execution.status"));
    assertEquals("java", outputFlowFile.getAttribute("execution.command"));
    assertEquals("-jar;", outputFlowFile.getAttribute("execution.command.args").substring(0, 5));
    String attribute = outputFlowFile.getAttribute("execution.command.args");
    String expected = "src" + File.separator + "test" + File.separator + "resources" + File.separator + "ExecuteCommand" + File.separator + "TestSuccess.jar";
    assertEquals(expected, attribute.substring(attribute.length() - expected.length()));
}
 
Example 14
Source File: MonitorUtilsTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
private Process createDumpingProcess(boolean writeToErr) throws IOException {
    String errSuffix = writeToErr ? " >&2" : "";
    //Windows limits the length of the arguments so echo multiple times instead
    String bigstr = Strings.repeat("a", 8000);
    String bigcmd = getExecPrefix() + Strings.repeat(getSilentPrefix() + "echo " + bigstr + errSuffix + Os.LINE_SEPARATOR, 15);
    File file = Os.newTempFile("test-consume", ".bat");
    file.setExecutable(true);
    Files.write(bigcmd, file, Charsets.UTF_8);
    Process process = MonitorUtils.exec(file.getAbsolutePath());
    return process;
}
 
Example 15
Source File: DefaultBubbleHook.java    From QNotified with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setEnabled(boolean enabled) {
    try {
        File dir = new File(getApplication().getFilesDir().getAbsolutePath() + "/bubble_info");
        boolean curr = !dir.exists() || !dir.canRead();
        if (dir.exists()) {
            if (enabled && !curr) {
                dir.setWritable(false);
                dir.setReadable(false);
                dir.setExecutable(false);
            }
            if (!enabled && curr) {
                dir.setWritable(true);
                dir.setReadable(true);
                dir.setExecutable(true);
            }
        }
    } catch (final Exception e) {
        Utils.log(e);
        if (Looper.myLooper() == Looper.getMainLooper()) {
            Utils.showToast(getApplication(), TOAST_TYPE_ERROR, e + "", Toast.LENGTH_SHORT);
        } else {
            SyncUtils.post(new Runnable() {
                @Override
                public void run() {
                    Utils.showToast(getApplication(), TOAST_TYPE_ERROR, e + "", Toast.LENGTH_SHORT);
                }
            });
        }
    }
}
 
Example 16
Source File: ForkedProcessBuilderCreator.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private void addExecutionPermissionToScripts() throws IOException {
    //Add execution permissions to scripts except for windows OS
    if (!StandardSystemProperty.OS_NAME.value().toLowerCase().contains("windows")) {
        String schedulerHome = ClasspathUtils.findSchedulerHome();
        File scriptsDirectory = new File(schedulerHome, "dist/scripts/processbuilder/linux");
        if (scriptsDirectory != null) {
            for (File script : scriptsDirectory.listFiles()) {
                script.setExecutable(true, false);
            }
        } else {
            throw new IOException("The directory that contains scripts required for the runAsMe mode does not exist");
        }
    }
}
 
Example 17
Source File: CMDInstaller.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
private static void writeOut(String resName, boolean executable) throws IOException {
    File self = new File(CMDInstaller.class.getProtectionDomain().getCodeSource().getLocation().getFile());
    File src = new File(resName);
    String home = self.getParentFile().getParentFile().getParent();
    File dest = new File(home + File.separator + "bin" + File.separator + src.getName());

    InputStream is = CMDInstaller.class.getResourceAsStream(resName);
    Files.copy(is, dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
    dest.setExecutable(executable);
}
 
Example 18
Source File: EnvUtils.java    From busybox with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Update env directory
 *
 * @param c context
 * @return false if error
 */
static boolean update(Context c) {
    if (isLatestVersion(c)) return true;

    // prepare env directory
    String envDir = PrefStore.getEnvDir(c);
    File fEnvDir = new File(envDir);
    fEnvDir.mkdirs();
    if (!fEnvDir.exists()) {
        return false;
    }
    cleanDirectory(fEnvDir);

    // extract assets
    if (!extractDir(c, "all", "")) {
        return false;
    }
    String mArch = PrefStore.getArch();
    switch (mArch) {
        case "arm":
            if (!extractDir(c, "arm", "")) {
                return false;
            }
            break;
        case "arm64":
            if (!extractDir(c, "arm", "")) {
                return false;
            }
            if (!extractDir(c, "arm64", "")) {
                return false;
            }
            break;
        case "x86":
            if (!extractDir(c, "x86", "")) {
                return false;
            }
            break;
        case "x86_64":
            if (!extractDir(c, "x86", "")) {
                return false;
            }
            if (!extractDir(c,  "x86_64", "")) {
                return false;
            }
            break;
    }

    // set executable app directory
    File appDir = new File(PrefStore.getEnvDir(c) + "/..");
    appDir.setExecutable(true, false);

    // set permissions
    setPermissions(fEnvDir);

    // install applets
    List<String> params = new ArrayList<>();
    params.add("busybox --install -s " + envDir + "/bin");
    exec(c, "sh", params);

    // update version
    return setVersion(c);
}
 
Example 19
Source File: CommandAsObjectResponserHA.java    From jumbune with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Prepares command to be executed in a different JVM. It writes the command in the form of 
 * bash script which is then executed in its own JVM by method <code> spawnNewJVMForCommand(CommandWritable commandWritable, Command command, String methodName)</code>. 
 *
 * @param commandWritable the command writable
 * @param command the command
 * @param methodName the method name
 * @return the string[]
 * @throws IOException Signals that an I/O exception has occurred.
 */
private String[] prepareCommand(CommandWritable commandWritable, Command command, String methodName) throws IOException {
	String javaHome = System.getProperty(RemotingConstants.JAVA_HOME_PROP_KEY);
	// path of jdk
	javaHome = javaHome.substring(0, javaHome.lastIndexOf(File.separator));
	Gson gson = new Gson();
	StringBuilder libEntriesBuilder = new StringBuilder();
       String libEntries = null;
	for(String libEntry : JumbuneAgent.getAgentLibEntries()) {
		libEntriesBuilder.append(RemotingConstants.COLON).append(libEntry);
	}		
	libEntries = libEntriesBuilder.toString().replaceFirst(RemotingConstants.COLON, "");
	
	String commandDir = JumbuneAgent.getHAProps().getProperty(RemotingConstants.COMMAND_LOG_DIR);
	if(commandDir == null || commandDir.isEmpty()) {
		commandDir = JumbuneAgent.getAgentDirPath();
	}
	
	File commandLogsDir = new File(commandDir + File.separator + command.getCommandId());
	commandLogsDir.mkdirs();
	commandLogsDir.setReadable(true, false);
	commandLogsDir.setWritable(true, false);
	String[] cmd = {EXEC, RemotingConstants.SINGLE_SPACE, 			
			NOHUP + RemotingConstants.SINGLE_SPACE + javaHome + BIN_JAVA + RemotingConstants.SINGLE_SPACE
			+ RemotingConstants.CLASSPATH_ARG + RemotingConstants.SINGLE_SPACE + libEntries
			+ RemotingConstants.SINGLE_SPACE + RemotingConstants.COMMAND_EXEC_DRIVER
			+ " '" + gson.toJson(commandWritable) + "'  '"
			+ gson.toJson(command) + "'  '" + gson.toJson(methodName)
			+ "'  '"+ gson.toJson(JumbuneAgent.getZKHosts())
			 +"' > "+commandLogsDir.getAbsolutePath()+CMD_OUT+commandLogsDir.getAbsolutePath()+CMD_ERR+ RemotingConstants.AMPERSAND };
	
	String scriptFilePath =commandLogsDir.getAbsolutePath() + File.separator + CMD + command.getCommandId() + SH_EXTENSION;
	try (BufferedWriter bw = Files.newBufferedWriter(
			Paths.get(scriptFilePath), Charset.defaultCharset(),
			StandardOpenOption.CREATE)) {
		bw.write(HASH_BANG);
		bw.write(System.lineSeparator());
		for (String token : cmd) {
			bw.write(token);
		}
		bw.write(System.lineSeparator());
		bw.flush();
	}
	File f = new File(scriptFilePath);		
	f.setExecutable(true, false);
	
	String[] scriptCmd = { SUDO, U_ARG, command.getSwitchedIdentity().getWorkingUser(), RemotingConstants.BASH,
			scriptFilePath };
	return scriptCmd;
}
 
Example 20
Source File: PackrFileUtils.java    From packr with Apache License 2.0 4 votes vote down vote up
static void chmodX(File path) {
	if (!path.setExecutable(true)) {
		System.err.println("Warning! Failed setting executable flag for: " + path);
	}
}