Example usage for java.io File canExecute

List of usage examples for java.io File canExecute

Introduction

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

Prototype

public boolean canExecute() 

Source Link

Document

Tests whether the application can execute the file denoted by this abstract pathname.

Usage

From source file:edu.ucsd.crbs.cws.cluster.submission.TestJobCmdScriptCreatorImpl.java

@Test
public void testCreateAndRunScriptWithFakeKeplerThatSucceedsWithPreExistingWorkflowFailedFile()
        throws Exception {
    assumeTrue(SystemUtils.IS_OS_UNIX);/*www . j ava  2s  .  com*/
    File baseDirectory = Folder.newFolder();
    File tempDirectory = new File(baseDirectory + File.separator + "subdir");
    File outputsDir = new File(tempDirectory + File.separator + Constants.OUTPUTS_DIR_NAME);
    assertTrue(outputsDir.mkdirs());

    JobEmailNotificationData emailNotifyData = createJobEmailNotificationData();

    JobBinaries jb = new JobBinaries();
    jb.setKeplerScript(getAndCheckForTrueBinaryFile().getAbsolutePath());
    jb.setRegisterUpdateJar("register.jar");
    jb.setJavaCommand("/bin/echo");
    jb.setRetryCount(1);

    JobCmdScriptCreatorImpl scriptCreator = new JobCmdScriptCreatorImpl("/workflowsdir", jb, emailNotifyData);

    Job j = new Job();
    Workflow w = new Workflow();
    w.setId(new Long(5));
    j.setWorkflow(w);

    FileWriter fw = new FileWriter(outputsDir.getAbsoluteFile() + File.separator + "WORKFLOW.FAILED.txt");
    fw.write("simple.error.message=simple\n");
    fw.write("detailed.error.message=detailed\n");
    fw.flush();
    fw.close();

    String jobCmd = scriptCreator.create(tempDirectory.getAbsolutePath(), j, new Long(2345));

    assertTrue(jobCmd != null);
    assertTrue(
            jobCmd.equals(outputsDir.getAbsolutePath() + File.separator + JobCmdScriptCreatorImpl.JOB_CMD_SH));
    File checkCmdFile = new File(jobCmd);
    assertTrue(checkCmdFile.canExecute());

    RunCommandLineProcessImpl rclpi = new RunCommandLineProcessImpl();
    rclpi.setWorkingDirectory(tempDirectory.getAbsolutePath());

    String result = rclpi.runCommandLineProcess(jobCmd);

    List<String> yos = IOUtils.readLines(new FileReader(jobCmd));

    String logFile = baseDirectory.getAbsoluteFile() + File.separator + "job...log";
    File checkLogFile = new File(logFile);
    assertTrue(logFile + " and we ran " + jobCmd, checkLogFile.exists());
    List<String> lines = IOUtils.readLines(new FileReader(logFile));
    for (String line : lines) {
        if (line.startsWith("exitcode: ")) {
            assertTrue(line, line.equals("exitcode: 0"));
        }
    }

    String updateFile = tempDirectory.getAbsoluteFile() + File.separator + "updateworkspacefile.out";

    lines = IOUtils.readLines(new FileReader(updateFile));
    for (String line : lines) {
        if (line.startsWith("-jar")) {
            assertTrue(line, line.startsWith(
                    "-jar register.jar --updatepath 2345 --path " + outputsDir.getAbsolutePath() + " --size "));
            assertTrue(line, line.endsWith(" --workspacefilefailed false"));
        }
    }
}

From source file:edu.ucsd.crbs.cws.cluster.submission.TestJobCmdScriptCreatorImpl.java

@Test
public void testCreateAndRunScriptWithKeplerThatHasExceptionInStdErrFile() throws Exception {
    assumeTrue(SystemUtils.IS_OS_UNIX);/*from  ww w  . j av a  2s.com*/
    File baseDirectory = Folder.newFolder();
    File tempDirectory = new File(baseDirectory + File.separator + "subdir");
    File outputsDir = new File(tempDirectory + File.separator + Constants.OUTPUTS_DIR_NAME);
    assertTrue(outputsDir.mkdirs());

    JobEmailNotificationData emailNotifyData = createJobEmailNotificationData();

    JobBinaries jb = new JobBinaries();
    jb.setKeplerScript(getAndCheckForTrueBinaryFile().getAbsolutePath());
    jb.setRegisterUpdateJar("register.jar");
    jb.setJavaCommand("/bin/echo");
    jb.setRetryCount(1);

    JobCmdScriptCreatorImpl scriptCreator = new JobCmdScriptCreatorImpl("/workflowsdir", jb, emailNotifyData);

    Job j = new Job();
    Workflow w = new Workflow();
    w.setId(new Long(5));
    j.setWorkflow(w);

    FileWriter fw = new FileWriter(outputsDir.getAbsoluteFile() + File.separator + "stderr");
    fw.write("Exception in thread \"main\" Java returned: 1\n"
            + "   at org.kepler.build.modules.ModulesTask.execute(ModulesTask.java:106)\n"
            + "   at org.kepler.build.runner.Kepler.main(Kepler.java:109)\n" + "Caused by: Java returned: 1\n"
            + "   at org.kepler.build.modules.ModulesTask.execute(ModulesTask.java:106)\n"
            + "   at org.kepler.build.runner.Kepler.run(Kepler.java:266)\n"
            + "   at org.kepler.build.modules.ModulesTask.execute(ModulesTask.java:102)\n" + "   ... 1 more\n"
            + "Caused by: Java returned: 1\n"
            + "   at org.apache.tools.ant.taskdefs.Java.execute(Java.java:111)\n"
            + "   at org.kepler.build.Run.runSuite(Run.java:379)\n"
            + "   at org.kepler.build.Run.run(Run.java:240)\n"
            + "   at org.kepler.build.modules.ModulesTask.execute(ModulesTask.java:102)\n" + "   ... 3 more");
    fw.flush();
    fw.close();

    String jobCmd = scriptCreator.create(tempDirectory.getAbsolutePath(), j, new Long(10));

    assertTrue(jobCmd != null);
    assertTrue(
            jobCmd.equals(outputsDir.getAbsolutePath() + File.separator + JobCmdScriptCreatorImpl.JOB_CMD_SH));
    File checkCmdFile = new File(jobCmd);
    assertTrue(checkCmdFile.canExecute());

    RunCommandLineProcessImpl rclpi = new RunCommandLineProcessImpl();
    rclpi.setWorkingDirectory(outputsDir.getAbsolutePath());
    String result;
    try {
        result = rclpi.runCommandLineProcess(jobCmd);
    } catch (Exception ex) {
        assertTrue(ex.getMessage(), ex.getMessage().startsWith("Non zero exit code (101)"));
    }

    String logFile = tempDirectory.getAbsoluteFile() + File.separator + "job...log";
    File checkLogFile = new File(logFile);
    assertTrue(logFile + " and we ran " + jobCmd, checkLogFile.exists());
    List<String> lines = IOUtils.readLines(new FileReader(logFile));
    for (String line : lines) {
        if (line.startsWith("exitcode: ")) {
            assertTrue(line, line.equals("exitcode: 101"));
        }
    }

    checkWorkflowFailed(outputsDir.getAbsolutePath(), "Error running Kepler",
            "Found Exception in thread main Java returned: 1 in the stderr file for Kepler");
}

From source file:edu.ucsd.crbs.cws.cluster.submission.TestJobCmdScriptCreatorImpl.java

@Test
public void testCreateAndRunScriptWithFakeKeplerThatSimulatesUSR2SignalButAlreadyHasWorkFlowFailedFile()
        throws Exception {
    assumeTrue(SystemUtils.IS_OS_UNIX);/*from  w w w  .j  a v  a  2  s. co m*/
    File baseDirectory = Folder.newFolder();
    File tempDirectory = new File(baseDirectory + File.separator + "subdir");
    File outputsDir = new File(tempDirectory + File.separator + Constants.OUTPUTS_DIR_NAME);
    assertTrue(outputsDir.mkdirs());

    JobEmailNotificationData emailNotifyData = createJobEmailNotificationData();

    JobBinaries jb = new JobBinaries();
    jb.setKeplerScript("mv " + outputsDir.getAbsoluteFile() + File.separator + "WORKFLOW.FAILED.txt2 "
            + outputsDir.getAbsoluteFile() + File.separator + "WORKFLOW.FAILED.txt; kill -s USR2 $$;sleep 100");
    jb.setRegisterUpdateJar("register.jar");
    jb.setJavaCommand("/bin/echo");
    jb.setRetryCount(1);

    JobCmdScriptCreatorImpl scriptCreator = new JobCmdScriptCreatorImpl("/workflowsdir", jb, emailNotifyData);

    Job j = new Job();
    Workflow w = new Workflow();
    w.setId(new Long(5));
    j.setWorkflow(w);

    FileWriter fw = new FileWriter(outputsDir.getAbsoluteFile() + File.separator + "WORKFLOW.FAILED.txt2");
    fw.write("simple.error.message=simple\n");
    fw.write("detailed.error.message=detailed\n");
    fw.flush();
    fw.close();

    String jobCmd = scriptCreator.create(tempDirectory.getAbsolutePath(), j, new Long(10));

    assertTrue(jobCmd != null);
    assertTrue(
            jobCmd.equals(outputsDir.getAbsolutePath() + File.separator + JobCmdScriptCreatorImpl.JOB_CMD_SH));
    File checkCmdFile = new File(jobCmd);
    assertTrue(checkCmdFile.canExecute());

    RunCommandLineProcessImpl rclpi = new RunCommandLineProcessImpl();
    rclpi.setWorkingDirectory(outputsDir.getAbsolutePath());
    String result;
    try {
        result = rclpi.runCommandLineProcess(jobCmd);
    } catch (Exception ex) {
        assertTrue(ex.getMessage(), ex.getMessage().startsWith("Non zero exit code (100)"));
    }

    String logFile = tempDirectory.getAbsoluteFile() + File.separator + "job...log";
    File checkLogFile = new File(logFile);
    assertTrue(logFile + " and we ran " + jobCmd, checkLogFile.exists());
    List<String> lines = IOUtils.readLines(new FileReader(logFile));
    for (String line : lines) {
        if (line.startsWith("exitcode: ")) {
            assertTrue(line, line.equals("exitcode: 100"));
        }
    }

    File failedFile = checkWorkflowFailed(outputsDir.getAbsolutePath(), "simple", "detailed");

    lines = IOUtils.readLines(new FileReader(failedFile));
    boolean jobFound = false;
    for (String line : lines) {
        if (line.startsWith(" Job received")) {
            assertTrue(line,
                    line.equals(" Job received USR2 signal which in SGE meant it is about to be killed"));
            jobFound = true;
        }
    }
    assertTrue(jobFound);
}

From source file:edu.ucsd.crbs.cws.cluster.submission.TestJobCmdScriptCreatorImpl.java

@Test
public void testCreateAndRunScriptWhereUpdateFailsWithThreeRetries() throws Exception {
    assumeTrue(SystemUtils.IS_OS_UNIX);/*from w  ww .java 2s.c  om*/
    File baseDirectory = Folder.newFolder();
    File tempDirectory = new File(baseDirectory + File.separator + "subdir");
    File outputsDir = new File(tempDirectory + File.separator + Constants.OUTPUTS_DIR_NAME);
    assertTrue(outputsDir.mkdirs());

    JobEmailNotificationData emailNotifyData = createJobEmailNotificationData();
    emailNotifyData.setErrorEmail("error@error.com > emailargs");
    JobBinaries jb = new JobBinaries();
    jb.setKeplerScript(getAndCheckForTrueBinaryFile().getAbsolutePath());
    jb.setRegisterUpdateJar("register.jar");
    jb.setMailCommand("cat > email.${finishedMessage};/bin/echo");
    jb.setJavaCommand(getAndCheckForFalseBinaryFile().getAbsolutePath());
    jb.setRetryCount(3);

    JobCmdScriptCreatorImpl scriptCreator = new JobCmdScriptCreatorImpl("/workflowsdir", jb, emailNotifyData);

    Job j = new Job();
    Workflow w = new Workflow();
    w.setId(new Long(5));
    j.setWorkflow(w);

    String jobCmd = scriptCreator.create(tempDirectory.getAbsolutePath(), j, new Long(10));

    assertTrue(jobCmd != null);
    assertTrue(
            jobCmd.equals(outputsDir.getAbsolutePath() + File.separator + JobCmdScriptCreatorImpl.JOB_CMD_SH));
    File checkCmdFile = new File(jobCmd);
    assertTrue(checkCmdFile.canExecute());

    RunCommandLineProcessImpl rclpi = new RunCommandLineProcessImpl();
    rclpi.setWorkingDirectory(outputsDir.getAbsolutePath());
    String result;
    try {
        result = rclpi.runCommandLineProcess(jobCmd);
    } catch (Exception ex) {
        assertTrue(ex.getMessage(), ex.getMessage().startsWith("Non zero exit code (102)"));
    }

    String logFile = tempDirectory.getAbsoluteFile() + File.separator + "job...log";
    File checkLogFile = new File(logFile);
    assertTrue(logFile + " and we ran " + jobCmd, checkLogFile.exists());
    List<String> lines = IOUtils.readLines(new FileReader(logFile));
    for (String line : lines) {
        if (line.startsWith("exitcode: ")) {
            assertTrue(line, line.equals("exitcode: 102"));
        }
    }

    lines = IOUtils
            .readLines(new FileReader(outputsDir.getAbsoluteFile() + File.separator + "WORKFLOW.FAILED.txt"));
    for (String line : lines) {
        if (line.startsWith("simple.error.message")) {
            assertTrue(line, line.equals("simple.error.message=Unable to update WorkspaceFile"));
        }
        if (line.startsWith("detailed.error.message")) {
            assertTrue(line, line.equals(
                    "detailed.error.message=Received non zero exit code (1) when trying to update WorkspaceFile"));
        }
    }

    File emailFailedFile = new File(outputsDir.getAbsolutePath() + File.separator + "email.failed");

    assertTrue(emailFailedFile.exists());

    lines = IOUtils.readLines(new FileReader(emailFailedFile));
    boolean yourFound = false;
    boolean unableFound = false;
    for (String line : lines) {
        if (line.startsWith("Your Unknown job: ")) {
            assertTrue(line.contains(" has failed"));
            yourFound = true;
        }
        if (line.contains("WORKFLOW.FAILED.txt:")) {
            assertTrue(line.contains("Unable to update WorkspaceFile"));
            unableFound = true;
        }
    }
    assertTrue(yourFound);
    assertTrue(unableFound);

}

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

/**
 * Copies the installer to a location.//from  ww  w . j  a v a2  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.opennms.install.Installer.java

/**
 * <p>install</p>// w w w. ja v a 2 s .  co m
 *
 * @param argv an array of {@link java.lang.String} objects.
 * @throws java.lang.Exception if any.
 */
public void install(final String[] argv) throws Exception {
    printHeader();
    loadProperties();
    parseArguments(argv);

    final boolean doDatabase = (m_update_database || m_do_inserts || m_update_iplike || m_update_unicode
            || m_fix_constraint);

    if (!doDatabase && m_tomcat_conf == null && !m_install_webapp && m_library_search_path == null) {
        usage(options, m_commandLine, "Nothing to do.  Use -h for help.", null);
        System.exit(1);
    }

    if (doDatabase) {
        final File cfgFile = ConfigFileConstants
                .getFile(ConfigFileConstants.OPENNMS_DATASOURCE_CONFIG_FILE_NAME);

        InputStream is = new FileInputStream(cfgFile);
        final JdbcDataSource adminDsConfig = new DataSourceConfigurationFactory(is)
                .getJdbcDataSource(ADMIN_DATA_SOURCE_NAME);
        final DataSource adminDs = new SimpleDataSource(adminDsConfig);
        is.close();

        is = new FileInputStream(cfgFile);
        final JdbcDataSource dsConfig = new DataSourceConfigurationFactory(is)
                .getJdbcDataSource(OPENNMS_DATA_SOURCE_NAME);
        final DataSource ds = new SimpleDataSource(dsConfig);
        is.close();

        m_installerDb.setForce(m_force);
        m_installerDb.setIgnoreNotNull(m_ignore_not_null);
        m_installerDb.setNoRevert(m_do_not_revert);
        m_installerDb.setAdminDataSource(adminDs);
        m_installerDb.setPostgresOpennmsUser(dsConfig.getUserName());
        m_installerDb.setDataSource(ds);
        m_installerDb.setDatabaseName(dsConfig.getDatabaseName());

        m_migrator.setDataSource(ds);
        m_migrator.setAdminDataSource(adminDs);
        m_migrator.setValidateDatabaseVersion(!m_ignore_database_version);

        m_migration.setDatabaseName(dsConfig.getDatabaseName());
        m_migration.setSchemaName(dsConfig.getSchemaName());
        m_migration.setAdminUser(adminDsConfig.getUserName());
        m_migration.setAdminPassword(adminDsConfig.getPassword());
        m_migration.setDatabaseUser(dsConfig.getUserName());
        m_migration.setDatabasePassword(dsConfig.getPassword());
        m_migration.setChangeLog("changelog.xml");
    }

    checkIPv6();

    /*
     * Make sure we can execute the rrdtool binary when the
     * JniRrdStrategy is enabled.
     */

    boolean using_jni_rrd_strategy = System.getProperty("org.opennms.rrd.strategyClass", "")
            .contains("JniRrdStrategy");

    if (using_jni_rrd_strategy) {
        File rrd_binary = new File(System.getProperty("rrd.binary"));
        if (!rrd_binary.canExecute()) {
            throw new Exception("Cannot execute the rrdtool binary '" + rrd_binary.getAbsolutePath()
                    + "' required by the current RRD strategy. Update the rrd.binary field in opennms.properties appropriately.");
        }
    }

    /*
     * make sure we can load the ICMP library before we go any farther
     */

    if (!Boolean.getBoolean("skip-native")) {
        String icmp_path = findLibrary("jicmp", m_library_search_path, false);
        String icmp6_path = findLibrary("jicmp6", m_library_search_path, false);
        String jrrd_path = findLibrary("jrrd", m_library_search_path, false);
        String jrrd2_path = findLibrary("jrrd2", m_library_search_path, false);
        writeLibraryConfig(icmp_path, icmp6_path, jrrd_path, jrrd2_path);
    }

    /*
     * Everything needs to use the administrative data source until we
     * verify that the opennms database is created below (and where we
     * create it if it doesn't already exist).
     */

    verifyFilesAndDirectories();

    if (m_install_webapp) {
        checkWebappOldOpennmsDir();
        checkServerXmlOldOpennmsContext();
    }

    if (m_update_database || m_fix_constraint) {
        // OLDINSTALL m_installerDb.readTables();
    }

    m_installerDb.disconnect();
    if (doDatabase) {
        m_migrator.validateDatabaseVersion();

        System.out.println(
                String.format("* using '%s' as the PostgreSQL user for OpenNMS", m_migration.getAdminUser()));
        System.out.println(String.format("* using '%s' as the PostgreSQL database name for OpenNMS",
                m_migration.getDatabaseName()));
        if (m_migration.getSchemaName() != null) {
            System.out.println(String.format("* using '%s' as the PostgreSQL schema name for OpenNMS",
                    m_migration.getSchemaName()));
        }
    }

    if (m_update_database) {
        m_migrator.prepareDatabase(m_migration);
    }

    if (doDatabase) {
        m_installerDb.checkUnicode();
    }

    handleConfigurationChanges();

    final GenericApplicationContext context = new GenericApplicationContext();
    context.setClassLoader(Bootstrap.loadClasses(new File(m_opennms_home), true));

    if (m_update_database) {
        m_installerDb.databaseSetUser();
        m_installerDb.disconnect();

        for (final Resource resource : context.getResources("classpath*:/changelog.xml")) {
            System.out.println("- Running migration for changelog: " + resource.getDescription());
            m_migration.setAccessor(new ExistingResourceAccessor(resource));
            m_migrator.migrate(m_migration);
        }
    }

    if (m_update_unicode) {
        System.out.println("WARNING: the -U option is deprecated, it does nothing now");
    }

    if (m_do_vacuum) {
        m_installerDb.vacuumDatabase(m_do_full_vacuum);
    }

    if (m_install_webapp) {
        installWebApp();
    }

    if (m_tomcat_conf != null) {
        updateTomcatConf();
    }

    if (m_update_iplike) {
        m_installerDb.updateIplike();
    }

    if (m_update_database && m_remove_database) {
        m_installerDb.disconnect();
        m_installerDb.databaseRemoveDB();
    }

    if (doDatabase) {
        m_installerDb.disconnect();
    }

    if (m_update_database) {
        createConfiguredFile();
    }

    System.out.println();
    System.out.println("Installer completed successfully!");

    if (!m_skip_upgrade_tools) {
        System.setProperty("opennms.manager.class", "org.opennms.upgrade.support.Upgrade");
        Bootstrap.main(new String[] {});
    }

    context.close();
}

From source file:org.jini.commands.files.List.java

/**
 * Print the results//from  w w  w.  j  a  v  a 2  s . c  o m
 *
 * @param withDetails
 * @param fileList
 * @return
 */
private boolean printResults(boolean withDetails, ArrayList<File> fileList) {

    if (this.getJcError() == false) {
        if (withDetails == true) {
            TablePrinter tableF = new TablePrinter("Name", "Type", "Readable", "Writable", "Executable",
                    "Size KB", "Size MB", "Last Modified");
            for (File v : fileList) {

                java.util.Date lastModified = new java.util.Date(v.lastModified());
                long filesizeInKB = v.length() / 1024;
                double bytes = v.length();
                double kilobytes = (bytes / 1024);
                double megabytes = (kilobytes / 1024);

                String type = "";

                DecimalFormat df = new DecimalFormat("####.####");

                if (v.isDirectory()) {
                    type = "Dir";
                }
                if (v.isFile()) {
                    type = "File";
                }

                if (v.isFile() && v.isHidden()) {
                    type = "File (Hidden)";
                }
                if (v.isDirectory() && (v.isHidden())) {
                    type = "Dir (Hidden)";
                }

                String canExec = "" + v.canExecute();
                String canRead = "" + v.canRead();
                String canWrite = "" + v.canWrite();
                String filesizeInKBStr = Long.toString(filesizeInKB);
                String filesizeInMBStr = df.format(megabytes);

                tableF.addRow(v.getName(), type, canRead, canWrite, canExec, filesizeInKBStr, filesizeInMBStr,
                        lastModified.toString());
            }

            tableF.print();
        } else {
            for (File v : fileList) {
                System.out.println(v.getName());
            }
        }
    }

    return true;
}

From source file:org.voltdb.utils.CatalogUtil.java

private static void validateDirectory(String type, File path) {
    String error = null;//  w  ww.  j ava 2 s. c om
    do {
        if (!path.exists()) {
            error = "Specified " + type + " \"" + path + "\" does not exist";
            break;
        }
        if (!path.isDirectory()) {
            error = "Specified " + type + " \"" + path + "\" is not a directory";
            break;
        }
        if (!path.canRead()) {
            error = "Specified " + type + " \"" + path + "\" is not readable";
            break;
        }
        if (!path.canWrite()) {
            error = "Specified " + type + " \"" + path + "\" is not writable";
            break;
        }
        if (!path.canExecute()) {
            error = "Specified " + type + " \"" + path + "\" is not executable";
            break;
        }
    } while (false);
    if (error != null) {
        throw new RuntimeException(error);
    }
}

From source file:com.linkedin.harisekhon.Utils.java

public static final String which(String bin) throws IOException {
    if (bin == null || bin.trim().isEmpty()) {
        throw new IllegalArgumentException("no bin passed to which()");
    }/*w  w w  .  j  ava  2s  .  c om*/
    // TODO: should probably consider switching this to os path sep instead of unix biased /
    if (bin.matches("^(?:/|\\./).*")) {
        File f = new File(bin);
        if (f.isFile()) {
            if (f.canExecute()) {
                return bin;
            } else {
                throw new IOException(String.format("'%s' is not executable!", bin));
            }
        } else {
            throw new IOException(String.format("couldn't find executable '%s'", bin));
        }
    } else {
        for (String path : System.getenv("PATH").split(":")) {
            String fullpath = path + "/" + bin;
            File f = new File(fullpath);
            //                if(f.exists() && ! f.isDirectory()){
            //                    if(! f.canExecute()){
            //                        throw new IOException(String.format("'%s' is not executable!", bin);
            //                    }
            if (f.isFile() && f.canExecute()) {
                return fullpath;
            }
        }
        throw new IOException(String.format("couldn't find '%s' in PATH (%s)", bin, System.getenv("PATH")));
    }
}

From source file:org.yamj.core.service.mediainfo.MediaInfoService.java

@Override
public void afterPropertiesSet() {
    String OS_NAME = System.getProperty("os.name");
    LOG.debug("Operating System Name   : {}", OS_NAME);
    LOG.debug("Operating System Version: {}", System.getProperty("os.version"));
    LOG.debug("Operating System Type   : {}", System.getProperty("os.arch"));
    LOG.debug("Media Info Path         : {}", MEDIAINFO_PATH);

    File mediaInfoFile;
    if (OS_NAME.contains("Windows")) {
        mediaInfoFile = new File(MEDIAINFO_PATH.getAbsolutePath() + File.separator + MI_RAR_FILENAME_WINDOWS);
        if (!mediaInfoFile.exists()) {
            //  fall back to the normal filename
            mediaInfoFile = new File(MEDIAINFO_PATH.getAbsolutePath() + File.separator + MI_FILENAME_WINDOWS);
        } else {/*from   ww  w .  j  ava2  s  .  com*/
            // enable the extra mediainfo-rar features
            isMediaInfoRar = Boolean.TRUE;
        }
    } else {
        mediaInfoFile = new File(MEDIAINFO_PATH.getAbsolutePath() + File.separator + MI_RAR_FILENAME_LINUX);
        if (!mediaInfoFile.exists()) {
            // Fall back to the normal filename
            mediaInfoFile = new File(MEDIAINFO_PATH.getAbsolutePath() + File.separator + MI_FILENAME_LINUX);
        } else {
            // enable the extra mediainfo-rar features
            isMediaInfoRar = Boolean.TRUE;
        }
    }

    if (!mediaInfoFile.canExecute()) {
        LOG.info("Couldn't find CLI mediaInfo executable tool: Media file data won't be extracted");
        isActivated = Boolean.FALSE;
    } else {
        if (OS_NAME.contains("Windows")) {
            execMediaInfo.add("cmd.exe");
            execMediaInfo.add("/E:1900");
            execMediaInfo.add("/C");
            execMediaInfo.add(mediaInfoFile.getName());
            execMediaInfo.add("-f");
        } else {
            execMediaInfo.add("./" + mediaInfoFile.getName());
            execMediaInfo.add("-f");
        }

        if (isMediaInfoRar) {
            LOG.info("MediaInfo-rar tool found, additional scanning functions enabled.");
        } else {
            LOG.info("MediaInfo tool will be used to extract video data. But not RAR and ISO formats");
        }
        isActivated = Boolean.TRUE;
    }

    // Add a list of supported extensions
    for (String ext : PropertyTools.getProperty("mediainfo.rar.diskExtensions", "iso,img,rar,001").split(",")) {
        RAR_DISK_IMAGES.add(ext.toLowerCase());
    }
}