Example usage for java.nio.file Files isExecutable

List of usage examples for java.nio.file Files isExecutable

Introduction

In this page you can find the example usage for java.nio.file Files isExecutable.

Prototype

public static boolean isExecutable(Path path) 

Source Link

Document

Tests whether a file is executable.

Usage

From source file:com.facebook.buck.util.unarchive.UnzipTest.java

@Test
public void testExtractZipFilePreservesExecutePermissionsAndModificationTime()
        throws InterruptedException, IOException {

    // getFakeTime returs time with some non-zero millis. By doing division and multiplication by
    // 1000 we get rid of that.
    long time = ZipConstants.getFakeTime() / 1000 * 1000;

    // Create a simple zip archive using apache's commons-compress to store executable info.
    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        ZipArchiveEntry entry = new ZipArchiveEntry("test.exe");
        entry.setUnixMode((int) MorePosixFilePermissions.toMode(PosixFilePermissions.fromString("r-x------")));
        entry.setSize(DUMMY_FILE_CONTENTS.length);
        entry.setMethod(ZipEntry.STORED);
        entry.setTime(time);//  w w  w. ja v a 2  s . c om
        zip.putArchiveEntry(entry);
        zip.write(DUMMY_FILE_CONTENTS);
        zip.closeArchiveEntry();
    }

    // Now run `Unzip.extractZipFile` on our test zip and verify that the file is executable.
    Path extractFolder = tmpFolder.newFolder();
    ImmutableList<Path> result = ArchiveFormat.ZIP.getUnarchiver().extractArchive(
            new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            ExistingFileMode.OVERWRITE);
    Path exe = extractFolder.toAbsolutePath().resolve("test.exe");
    assertTrue(Files.exists(exe));
    assertThat(Files.getLastModifiedTime(exe).toMillis(), Matchers.equalTo(time));
    assertTrue(Files.isExecutable(exe));
    assertEquals(ImmutableList.of(extractFolder.resolve("test.exe")), result);
}

From source file:com.fizzed.stork.deploy.Archive.java

static public void packEntry(ArchiveOutputStream aos, Path dirOrFile, String base, boolean appendName)
        throws IOException {
    String entryName = base;//  w ww .  j  av a 2  s .  c  o  m

    if (appendName) {
        if (!entryName.equals("")) {
            if (!entryName.endsWith("/")) {
                entryName += "/" + dirOrFile.getFileName();
            } else {
                entryName += dirOrFile.getFileName();
            }
        } else {
            entryName += dirOrFile.getFileName();
        }
    }

    ArchiveEntry entry = aos.createArchiveEntry(dirOrFile.toFile(), entryName);

    if (Files.isRegularFile(dirOrFile)) {
        if (entry instanceof TarArchiveEntry && Files.isExecutable(dirOrFile)) {
            // -rwxr-xr-x
            ((TarArchiveEntry) entry).setMode(493);
        } else {
            // keep default mode
        }
    }

    aos.putArchiveEntry(entry);

    if (Files.isRegularFile(dirOrFile)) {
        Files.copy(dirOrFile, aos);
        aos.closeArchiveEntry();
    } else {
        aos.closeArchiveEntry();
        List<Path> children = Files.list(dirOrFile).collect(Collectors.toList());
        if (children != null) {
            for (Path childFile : children) {
                packEntry(aos, childFile, entryName + "/", true);
            }
        }
    }
}

From source file:com.facebook.buck.zip.ZipStepTest.java

@Test
public void zipMaintainsExecutablePermissions() throws IOException {
    assumeTrue(Platform.detect() != Platform.WINDOWS);

    Path parent = tmp.newFolder("zipstep");
    Path toZip = tmp.newFolder("zipdir");
    Path file = toZip.resolve("foo.sh");
    ImmutableSet<PosixFilePermission> filePermissions = ImmutableSet.of(PosixFilePermission.OWNER_READ,
            PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.GROUP_READ,
            PosixFilePermission.OTHERS_READ);
    Files.createFile(file, PosixFilePermissions.asFileAttribute(filePermissions));
    Path outputZip = parent.resolve("output.zip");
    ZipStep step = new ZipStep(filesystem, outputZip, ImmutableSet.of(), false,
            ZipCompressionLevel.MIN_COMPRESSION_LEVEL, Paths.get("zipdir"));
    assertEquals(0, step.execute(TestExecutionContext.newInstance()).getExitCode());

    Path destination = tmp.newFolder("output");
    Unzip.extractZipFile(outputZip, destination, Unzip.ExistingFileMode.OVERWRITE);
    assertTrue(Files.isExecutable(destination.resolve("foo.sh")));
}

From source file:at.tfr.securefs.ui.CopyFilesServiceBean.java

private Path validateFromPath(String fromPathName) throws IOException {
    Path from = Paths.get(fromPathName);
    if (!Files.isDirectory(from, LinkOption.NOFOLLOW_LINKS)) {
        throw new IOException("Path " + from + " is no directory");
    }/*from w w  w  .  j  a  v a2 s . co m*/
    if (!Files.isReadable(from)) {
        throw new IOException("Path " + from + " is not readable");
    }
    if (!Files.isExecutable(from)) {
        throw new IOException("Path " + from + " is not executable");
    }
    return from;
}

From source file:com.github.ferstl.depgraph.AbstractGraphMojo.java

private String determineDotExecutable() throws IOException {
    if (this.dotExecutable == null) {
        return "dot";
    }/*from w w  w  .ja  v a2s  . c o  m*/

    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();
}

From source file:at.tfr.securefs.ui.CopyFilesServiceBean.java

private Path validateToPath(String toPathName, ProcessFilesData pfd) throws IOException {
    Path to = Paths.get(toPathName);
    if (Files.exists(to, LinkOption.NOFOLLOW_LINKS)) {
        if (Files.isSameFile(to, Paths.get(pfd.getFromRootPath()))) {
            throw new IOException("Path " + to + " may not be same as FromPath: " + pfd.getFromRootPath());
        }/*from  w ww.j a  va2 s .co  m*/
        if (!Files.isDirectory(to, LinkOption.NOFOLLOW_LINKS)) {
            throw new IOException("Path " + to + " is no directory");
        }
        if (!Files.isWritable(to)) {
            throw new IOException("Path " + to + " is not writable");
        }
        if (!Files.isExecutable(to)) {
            throw new IOException("Path " + to + " is not executable");
        }
        if (!pfd.isAllowOverwriteExisting()) {
            if (Files.newDirectoryStream(to).iterator().hasNext()) {
                throw new IOException("Path " + to + " is not empty, delete content copy.");
            }
        }
    }
    return to;
}

From source file:org.exist.launcher.LauncherWrapper.java

protected String getJavaCmd() {
    final File javaHome = SystemUtils.getJavaHome();
    if (SystemUtils.IS_OS_WINDOWS) {
        Path javaBin = Paths.get(javaHome.getAbsolutePath(), "bin", "javaw.exe");
        if (Files.isExecutable(javaBin)) {
            return '"' + javaBin.toString() + '"';
        }/*from   www .j  a va2s. c  o m*/
        javaBin = Paths.get(javaHome.getAbsolutePath(), "bin", "java.exe");
        if (Files.isExecutable(javaBin)) {
            return '"' + javaBin.toString() + '"';
        }
    } else {
        Path javaBin = Paths.get(javaHome.getAbsolutePath(), "bin", "java");
        if (Files.isExecutable(javaBin)) {
            return javaBin.toString();
        }
    }
    return "java";
}

From source file:org.ng200.openolympus.FileAccess.java

public static boolean isExecutable(final Path path) {
    return Files.isExecutable(path);
}

From source file:org.opennms.features.newts.converter.NewtsConverter.java

private NewtsConverter(final String... args) {
    final Options options = new Options();

    final Option helpOption = new Option("h", "help", false, "Print this help");
    options.addOption(helpOption);//from  w w  w  . ja v  a2 s  .  com

    final Option opennmsHomeOption = new Option("o", "onms-home", true,
            "OpenNMS Home Directory (defaults to /opt/opennms)");
    options.addOption(opennmsHomeOption);

    final Option rrdPathOption = new Option("r", "rrd-dir", true,
            "The path to the RRD data (defaults to ONMS-HOME/share/rrd)");
    options.addOption(rrdPathOption);

    final Option rrdToolOption = new Option("t", "rrd-tool", true,
            "Whether to use rrdtool or JRobin (defaults to use rrdtool)");
    options.addOption(rrdToolOption);

    final Option rrdBinaryOption = new Option("T", "rrd-binary", true,
            "The binary path to the rrdtool command (defaults to /usr/bin/rrdtool, only used if rrd-tool is set)");
    options.addOption(rrdBinaryOption);

    final Option storeByGroupOption = new Option("s", "storage-strategy", true,
            "Whether store by group was enabled or not");
    storeByGroupOption.setRequired(true);
    options.addOption(storeByGroupOption);

    final Option threadsOption = new Option("n", "threads", true,
            "Number of conversion threads (defaults to number of CPUs)");
    options.addOption(threadsOption);

    final CommandLineParser parser = new PosixParser();

    final CommandLine cmd;
    try {
        cmd = parser.parse(options, args);

    } catch (ParseException e) {
        new HelpFormatter().printHelp(80, CMD_SYNTAX, String.format("ERROR: %s%n", e.getMessage()), options,
                null);
        System.exit(1);
        throw null;
    }

    // Processing Options
    if (cmd.hasOption('h')) {
        new HelpFormatter().printHelp(80, CMD_SYNTAX, null, options, null);
        System.exit(0);
    }

    this.onmsHome = cmd.hasOption('o') ? Paths.get(cmd.getOptionValue('o')) : Paths.get("/opt/opennms");
    if (!Files.exists(this.onmsHome) || !Files.isDirectory(this.onmsHome)) {
        new HelpFormatter().printHelp(80, CMD_SYNTAX,
                String.format("ERROR: Directory %s doesn't exist%n", this.onmsHome.toAbsolutePath()), options,
                null);
        System.exit(1);
        throw null;
    }
    System.setProperty("opennms.home", onmsHome.toAbsolutePath().toString());

    this.rrdDir = cmd.hasOption('r') ? Paths.get(cmd.getOptionValue('r'))
            : this.onmsHome.resolve("share").resolve("rrd");
    if (!Files.exists(this.rrdDir) || !Files.isDirectory(this.rrdDir)) {
        new HelpFormatter().printHelp(80, CMD_SYNTAX,
                String.format("ERROR: Directory %s doesn't exist%n", this.rrdDir.toAbsolutePath()), options,
                null);
        System.exit(1);
        throw null;
    }

    if (!cmd.hasOption('s')) {
        new HelpFormatter().printHelp(80, CMD_SYNTAX,
                String.format("ERROR: Option for storage-strategy must be spcified%n"), options, null);
        System.exit(1);
        throw null;
    }

    switch (cmd.getOptionValue('s').toLowerCase()) {
    case "storeByMetric":
    case "sbm":
    case "false":
        storageStrategy = StorageStrategy.STORE_BY_METRIC;
        break;

    case "storeByGroup":
    case "sbg":
    case "true":
        storageStrategy = StorageStrategy.STORE_BY_GROUP;
        break;

    default:
        new HelpFormatter().printHelp(80, CMD_SYNTAX,
                String.format("ERROR: Invalid value for storage-strategy%n"), options, null);
        System.exit(1);
        throw null;
    }

    if (!cmd.hasOption('t')) {
        new HelpFormatter().printHelp(80, CMD_SYNTAX,
                String.format("ERROR: Option rrd-tool must be specified%n"), options, null);
        System.exit(1);
        throw null;
    }

    switch (cmd.getOptionValue('t').toLowerCase()) {
    case "rrdtool":
    case "rrd":
    case "true":
        storageTool = StorageTool.RRDTOOL;
        break;

    case "jrobin":
    case "jrb":
    case "false":
        storageTool = StorageTool.JROBIN;
        break;

    default:
        new HelpFormatter().printHelp(80, CMD_SYNTAX, String.format("ERROR: Invalid value for rrd-tool%n"),
                options, null);
        System.exit(1);
        throw null;
    }

    this.rrdBinary = cmd.hasOption('T') ? Paths.get(cmd.getOptionValue('T')) : Paths.get("/usr/bin/rrdtool");
    if (!Files.exists(this.rrdBinary) || !Files.isExecutable(this.rrdBinary)) {
        new HelpFormatter().printHelp(80, CMD_SYNTAX,
                String.format("ERROR: RRDtool command %s doesn't exist%n", this.rrdBinary.toAbsolutePath()),
                options, null);
        System.exit(1);
        throw null;
    }
    System.setProperty("rrd.binary", this.rrdBinary.toString());

    final int threads;
    try {
        threads = cmd.hasOption('n') ? Integer.parseInt(cmd.getOptionValue('n'))
                : Runtime.getRuntime().availableProcessors();
        this.executor = new ForkJoinPool(threads, ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true);

    } catch (Exception e) {
        new HelpFormatter().printHelp(80, CMD_SYNTAX,
                String.format("ERROR: Invalid number of threads: %s%n", e.getMessage()), options, null);
        System.exit(1);
        throw null;
    }

    // Initialize OpenNMS
    OnmsProperties.initialize();

    final String host = System.getProperty("org.opennms.newts.config.hostname", "localhost");
    final String keyspace = System.getProperty("org.opennms.newts.config.keyspace", "newts");
    int ttl = Integer.parseInt(System.getProperty("org.opennms.newts.config.ttl", "31540000"));
    int port = Integer.parseInt(System.getProperty("org.opennms.newts.config.port", "9042"));

    batchSize = Integer.parseInt(System.getProperty("org.opennms.newts.config.max_batch_size", "16"));

    LOG.info("OpenNMS Home: {}", this.onmsHome);
    LOG.info("RRD Directory: {}", this.rrdDir);
    LOG.info("Use RRDtool Tool: {}", this.storageTool);
    LOG.info("RRDtool CLI: {}", this.rrdBinary);
    LOG.info("StoreByGroup: {}", this.storageStrategy);
    LOG.info("Conversion Threads: {}", threads);
    LOG.info("Cassandra Host: {}", host);
    LOG.info("Cassandra Port: {}", port);
    LOG.info("Cassandra Keyspace: {}", keyspace);
    LOG.info("Newts Max Batch Size: {}", this.batchSize);
    LOG.info("Newts TTL: {}", ttl);

    if (!"newts".equals(System.getProperty("org.opennms.timeseries.strategy", "rrd"))) {
        throw NewtsConverterError.create(
                "The configured timeseries strategy must be 'newts' on opennms.properties (org.opennms.timeseries.strategy)");
    }

    if (!"true".equals(System.getProperty("org.opennms.rrd.storeByForeignSource", "false"))) {
        throw NewtsConverterError.create(
                "The option storeByForeignSource must be enabled in opennms.properties (org.opennms.rrd.storeByForeignSource)");
    }

    try {
        this.context = new ClassPathXmlApplicationContext(
                new String[] { "classpath:/META-INF/opennms/applicationContext-soa.xml",
                        "classpath:/META-INF/opennms/applicationContext-newts.xml" });

        this.repository = context.getBean(SampleRepository.class);
        this.indexer = context.getBean(Indexer.class);

    } catch (final Exception e) {
        throw NewtsConverterError.create(e, "Cannot connect to the Cassandra/Newts backend: {}",
                e.getMessage());
    }

    // Initialize node ID to foreign ID mapping
    try (final Connection conn = DataSourceFactory.getInstance().getConnection();
            final Statement st = conn.createStatement();
            final ResultSet rs = st.executeQuery("SELECT nodeid, foreignsource, foreignid from node n")) {
        while (rs.next()) {
            foreignIds.put(rs.getInt("nodeid"),
                    new ForeignId(rs.getString("foreignsource"), rs.getString("foreignid")));
        }

    } catch (final Exception e) {
        throw NewtsConverterError.create(e, "Failed to connect to database: {}", e.getMessage());
    }

    LOG.trace("Found {} nodes on the database", foreignIds.size());
}

From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalUtils.java

public static void checkPrivilegesOnDirectory(Path location) {
    log.debug("Check the Location {}", location);
    Validate.isTrue(Files.exists(location));
    Validate.isTrue(Files.isDirectory(location));
    Validate.isTrue(Files.isReadable(location)); // List Files within Directory
    Validate.isTrue(Files.isExecutable(location)); // can change into Directory
    Validate.isTrue(Files.isWritable(location)); // can create or delete Files within Directory
}