Java Code Examples for java.nio.file.Files#isExecutable()

The following examples show how to use java.nio.file.Files#isExecutable() . These examples are extracted from open source projects. 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 Project: XHAIL   File: Finder.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
	Objects.nonNull(file);
	Objects.nonNull(attrs);
	Path found = file.getFileName();
	for (String name : matchers.keySet())
		if (!results.containsKey(name)) {
			PathMatcher matcher = matchers.get(name);
			if (null != found && matcher.matches(found) && Files.isExecutable(file) && check(file, name, version)) {
				results.put(name, file);
				if (results.size() == matchers.size())
					return FileVisitResult.TERMINATE;
			}
		}
	return FileVisitResult.CONTINUE;
}
 
Example 2
Source Project: java-debug   File: DebugUtility.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private static boolean isValidJavaExec(String javaExec) {
    if (StringUtils.isBlank(javaExec)) {
        return false;
    }

    File file = new File(javaExec);
    if (!file.exists() || !file.isFile()) {
        return false;
    }

    return Files.isExecutable(file.toPath())
        && Objects.equals(file.getParentFile().getName(), "bin");
}
 
Example 3
private static String getJavaBinaryPath() {
    boolean isWindows = System.getProperty("os.name").startsWith("Windows");
    String executable = isWindows ? "java.exe" : "java";
    Path path = Paths.get(System.getProperty("java.home"), "bin", executable);
    if (!Files.isExecutable(path)) {
        throw new IllegalStateException("unable to find java path");
    }
    return path.toAbsolutePath().toString();
}
 
Example 4
private static String getJavaBinaryPath() {
    boolean isWindows = System.getProperty("os.name").startsWith("Windows");
    String executable = isWindows ? "java.exe" : "java";
    Path path = Paths.get(System.getProperty("java.home"), "bin", executable);
    if (!Files.isExecutable(path)) {
        throw new IllegalStateException("unable to find java path");
    }
    return path.toAbsolutePath().toString();
}
 
Example 5
private static String[] getLauncher() throws IOException {
    String platform = getPlatform();
    if (platform == null) {
        return null;
    }

    String launcher = TEST_SRC + File.separator + platform + "-" + ARCH +
                      File.separator + "launcher";

    final FileSystem FS = FileSystems.getDefault();
    Path launcherPath = FS.getPath(launcher);

    final boolean hasLauncher = Files.isRegularFile(launcherPath, LinkOption.NOFOLLOW_LINKS)&&
                                Files.isReadable(launcherPath);
    if (!hasLauncher) {
        System.out.println("Launcher [" + launcher + "] does not exist. Skipping the test.");
        return null;
    }

    // It is impossible to store an executable file in the source control
    // We need to copy the launcher to the working directory
    // and set the executable flag
    Path localLauncherPath = FS.getPath(WORK_DIR, "launcher");
    Files.copy(launcherPath, localLauncherPath,
               StandardCopyOption.REPLACE_EXISTING,
               StandardCopyOption.COPY_ATTRIBUTES);
    if (!Files.isExecutable(localLauncherPath)) {
        Set<PosixFilePermission> perms = new HashSet<>(
            Files.getPosixFilePermissions(
                localLauncherPath,
                LinkOption.NOFOLLOW_LINKS
            )
        );
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(localLauncherPath, perms);
    }
    return new String[] {launcher, localLauncherPath.toAbsolutePath().toString()};
}
 
Example 6
/**
 * Returns whether the given file is executable. Depending on the platform
 * we might not get this right.
 * 
 * TODO find a better home for this function
 */
public static boolean isExecutable(File file) {
    if (!file.isFile())
        return false;
    if (Platform.getOS().equals(Platform.OS_WIN32))
        // executable attribute is a *ix thing, on Windows all files are
        // executable
        return true;
    return Files.isExecutable(file.toPath());
}
 
Example 7
private static Path toMavenExecutable(String mavenHomeEnvVar) {
    Path mavenHome = envVarPath(mavenHomeEnvVar);
    if (mavenHome != null) {
        if (Files.isDirectory(mavenHome)) {
            Path executable = mavenHome.resolve("bin").resolve(MAVEN_BINARY_NAME);
            if (Files.isExecutable(executable)) {
                return executable;
            }
        }
    }
    return null;
}
 
Example 8
private String determineDotExecutable() throws IOException {
  if (this.dotExecutable == null) {
    return "dot";
  }

  Path dotExecutablePath = this.dotExecutable.toPath();
  if (!Files.exists(dotExecutablePath)) {
    throw new NoSuchFileException("The dot executable '" + this.dotExecutable + "' does not exist.");
  } else if (Files.isDirectory(dotExecutablePath) || !Files.isExecutable(dotExecutablePath)) {
    throw new IOException("The dot executable '" + this.dotExecutable + "' is not a file or cannot be executed.");
  }

  return dotExecutablePath.toAbsolutePath().toString();
}
 
Example 9
private Path testNativeXz() {
    final String[] paths = {"/usr/bin/xz", "/opt/local/bin/xz", "/usr/local/bin/xz"};

    Path xz = null;

    for (String path : paths) {
        xz = Paths.get(path);
        if (Files.isExecutable(xz)) {
            break;
        }
    }

    return xz;
}
 
Example 10
private Consumer<Path> isNotExecutable() {
	return (path) -> {
		if (supportsExecutableFlag() && Files.isExecutable(path)) {
			throw Failures.instance().failure(String.format("%nExpecting:%n  <%s>%nto not be executable.", path));
		}
	};
}
 
Example 11
private static String[] getLauncher() throws IOException {
    String platform = getPlatform();
    if (platform == null) {
        return null;
    }

    String launcher = TEST_SRC + File.separator + platform + "-" + ARCH +
                      File.separator + "launcher";

    final FileSystem FS = FileSystems.getDefault();
    Path launcherPath = FS.getPath(launcher);

    final boolean hasLauncher = Files.isRegularFile(launcherPath, LinkOption.NOFOLLOW_LINKS)&&
                                Files.isReadable(launcherPath);
    if (!hasLauncher) {
        System.out.println("Launcher [" + launcher + "] does not exist. Skipping the test.");
        return null;
    }

    // It is impossible to store an executable file in the source control
    // We need to copy the launcher to the working directory
    // and set the executable flag
    Path localLauncherPath = FS.getPath(WORK_DIR, "launcher");
    Files.copy(launcherPath, localLauncherPath,
               StandardCopyOption.REPLACE_EXISTING,
               StandardCopyOption.COPY_ATTRIBUTES);
    if (!Files.isExecutable(localLauncherPath)) {
        Set<PosixFilePermission> perms = new HashSet<>(
            Files.getPosixFilePermissions(
                localLauncherPath,
                LinkOption.NOFOLLOW_LINKS
            )
        );
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(localLauncherPath, perms);
    }
    return new String[] {launcher, localLauncherPath.toAbsolutePath().toString()};
}
 
Example 12
public static boolean isExecutable(String commandName)
{
    for (String dirName : System.getenv("PATH").split(":")) {
        Path p = Paths.get(dirName).resolve(commandName);
        if (Files.isRegularFile(p) && Files.isExecutable(p)) {
            return true;
        }
    }
    return false;
}
 
Example 13
private static String[] getLauncher() throws IOException {
    String platform = getPlatform();
    if (platform == null) {
        return null;
    }

    String launcher = TEST_SRC + File.separator + platform + "-" + ARCH +
                      File.separator + "launcher";

    final FileSystem FS = FileSystems.getDefault();
    Path launcherPath = FS.getPath(launcher);

    final boolean hasLauncher = Files.isRegularFile(launcherPath, LinkOption.NOFOLLOW_LINKS)&&
                                Files.isReadable(launcherPath);
    if (!hasLauncher) {
        System.out.println("Launcher [" + launcher + "] does not exist. Skipping the test.");
        return null;
    }

    // It is impossible to store an executable file in the source control
    // We need to copy the launcher to the working directory
    // and set the executable flag
    Path localLauncherPath = FS.getPath(WORK_DIR, "launcher");
    Files.copy(launcherPath, localLauncherPath,
               StandardCopyOption.REPLACE_EXISTING);
    if (!Files.isExecutable(localLauncherPath)) {
        Set<PosixFilePermission> perms = new HashSet<>(
            Files.getPosixFilePermissions(
                localLauncherPath,
                LinkOption.NOFOLLOW_LINKS
            )
        );
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(localLauncherPath, perms);
    }
    return new String[] {launcher, localLauncherPath.toAbsolutePath().toString()};
}
 
Example 14
private static String[] getLauncher() throws IOException {
    String platform = getPlatform();
    if (platform == null) {
        return null;
    }

    String launcher = TEST_SRC + File.separator + platform + "-" + ARCH +
                      File.separator + "launcher";

    final FileSystem FS = FileSystems.getDefault();
    Path launcherPath = FS.getPath(launcher);

    final boolean hasLauncher = Files.isRegularFile(launcherPath, LinkOption.NOFOLLOW_LINKS)&&
                                Files.isReadable(launcherPath);
    if (!hasLauncher) {
        System.out.println("Launcher [" + launcher + "] does not exist. Skipping the test.");
        return null;
    }

    // It is impossible to store an executable file in the source control
    // We need to copy the launcher to the working directory
    // and set the executable flag
    Path localLauncherPath = FS.getPath(WORK_DIR, "launcher");
    Files.copy(launcherPath, localLauncherPath,
               StandardCopyOption.REPLACE_EXISTING,
               StandardCopyOption.COPY_ATTRIBUTES);
    if (!Files.isExecutable(localLauncherPath)) {
        Set<PosixFilePermission> perms = new HashSet<>(
            Files.getPosixFilePermissions(
                localLauncherPath,
                LinkOption.NOFOLLOW_LINKS
            )
        );
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(localLauncherPath, perms);
    }
    return new String[] {launcher, localLauncherPath.toAbsolutePath().toString()};
}
 
Example 15
Source Project: XHAIL   File: Finder.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static boolean check(Path executable, String... match) {
	if (null == executable || Files.notExists(executable) || !Files.isExecutable(executable))
		return false;
	if (null == match || String.join(" ", match).trim().isEmpty())
		return false;
	try {
		String[] command = combine(executable, "--version");
		ProcessBuilder builder = new ProcessBuilder(command);
		Process process = builder.start();
		process.waitFor();

		String line;
		BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
		while (null != (line = reader.readLine())) {
			line = line.toLowerCase();
			int pos = 0;
			for (String pattern : match) {
				pos = line.indexOf(pattern, pos);
				if (pos > -1)
					pos += pattern.length();
			}
			if (pos > -1)
				return true;
		}
		return false;
	} catch (IOException | InterruptedException e) {
		return false;
	}
}
 
Example 16
Source Project: ParallelGit   File: FilesCreateFileTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void createFileWithExecutableOption_fileShouldBeExcutable() throws IOException {
  Path newFile = gfs.getPath("/new_file.txt");
  createFile(newFile, PosixFilePermissions.asFileAttribute(singleton(OWNER_EXECUTE)));
  Files.isExecutable(newFile);
}
 
Example 17
@Override
public Boolean canExecute() {
	return Files.isExecutable(path);
}
 
Example 18
@Test
public void testIsExecutable() {
  PowerMock.mockStatic(Paths.class);
  PowerMock.mockStatic(Files.class);

  final Path path = mock(Path.class);

  Paths.get("test-file");
  PowerMock.expectLastCall().andReturn(path);

  Files.isRegularFile(path);
  PowerMock.expectLastCall().andReturn(false);

  PowerMock.replayAll();
  assertFalse(processLauncher.isExecutable("test-file"));
  PowerMock.verifyAll();
  PowerMock.resetAll();

  // --

  Paths.get("test-file");
  PowerMock.expectLastCall().andReturn(path);

  Files.isRegularFile(path);
  PowerMock.expectLastCall().andReturn(true);

  Files.isReadable(path);
  PowerMock.expectLastCall().andReturn(false);

  PowerMock.replayAll();
  assertFalse(processLauncher.isExecutable("test-file"));
  PowerMock.verifyAll();
  PowerMock.resetAll();

  // --

  Paths.get("test-file");
  PowerMock.expectLastCall().andReturn(path);

  Files.isRegularFile(path);
  PowerMock.expectLastCall().andReturn(true);

  Files.isReadable(path);
  PowerMock.expectLastCall().andReturn(true);

  Files.isExecutable(path);
  PowerMock.expectLastCall().andReturn(false);

  PowerMock.replayAll();
  assertFalse(processLauncher.isExecutable("test-file"));
  PowerMock.verifyAll();
  PowerMock.resetAll();

  // --

  Paths.get("test-file");
  PowerMock.expectLastCall().andReturn(path);

  Files.isRegularFile(path);
  PowerMock.expectLastCall().andReturn(true);

  Files.isReadable(path);
  PowerMock.expectLastCall().andReturn(true);

  Files.isExecutable(path);
  PowerMock.expectLastCall().andReturn(true);

  PowerMock.replayAll();
  assertTrue(processLauncher.isExecutable("test-file"));
  PowerMock.verifyAll();
}
 
Example 19
Source Project: eplmp   File: ConverterBean.java    License: Eclipse Public License 1.0 4 votes vote down vote up
private boolean decimate(Path file, Path tempDir, float[] ratio) {

        LOGGER.log(Level.INFO, "Decimate file in progress : {0}", ratio);

        // sanity checks
        String decimater = CONF.getProperty("decimater");
        Path executable = Paths.get(decimater);
        if (!executable.toFile().exists()) {
            LOGGER.log(Level.WARNING, "Cannot decimate file \"{0}\", decimater \"{1}\" is not available",
                    new Object[]{file.getFileName(), decimater});
            return false;
        }
        if (!Files.isExecutable(executable)) {
            LOGGER.log(Level.WARNING, "Cannot decimate file \"{0}\", decimater \"{1}\" has no execution rights",
                    new Object[]{file.getFileName(), decimater});
            return false;
        }

        boolean decimateSucceed = false;

        try {
            String[] args = {decimater, "-i", file.toAbsolutePath().toString(), "-o",
                    tempDir.toAbsolutePath().toString(), String.valueOf(ratio[0]), String.valueOf(ratio[1]),
                    String.valueOf(ratio[2])};

            LOGGER.log(Level.INFO, "Decimate command\n{0}", args);

            // Add redirectErrorStream, fix process hang up
            ProcessBuilder pb = new ProcessBuilder(args).redirectErrorStream(true);

            Process proc = pb.start();

            String stdOutput = ConverterUtils.inputStreamToString(proc.getInputStream());

            proc.waitFor();

            if (proc.exitValue() == 0) {
                LOGGER.log(Level.INFO, "Decimation done");
                decimateSucceed = true;
            } else {
                LOGGER.log(Level.SEVERE, "Decimation failed with code = {0} {1}", new Object[]{proc.exitValue(), stdOutput});
            }

        } catch (IOException | InterruptedException e) {
            LOGGER.log(Level.SEVERE, "Decimation failed for " + file.toAbsolutePath(), e);
        }
        return decimateSucceed;
    }
 
Example 20
/**
 * Returns the path to python interpreter. If python is specified in the 'python_interpreter' key
 * of the 'parser' section that is used and an error reported if invalid.
 *
 * <p>If none has been specified, consult the PythonBuckConfig for an interpreter.
 *
 * @return The found python interpreter.
 */
public String getOrFail() {
  Path path = getPythonInterpreter(parserConfig.getParserPythonInterpreterPath());
  if (!(Files.isExecutable(path) && !Files.isDirectory(path))) {
    throw new HumanReadableException("Not a python executable: " + path);
  }
  return path.toString();
}