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:org.eclipse.cbi.maven.plugins.macsigner.SignMojo.java

/**
 * Creates a zip file.//ww w .ja  va 2  s.co m
 * @param dir                   The Directory of the files to be zipped.
 * @param zip                   An output stream to write the file
 * @throws IOException
 */
private void createZip(File dir, ZipArchiveOutputStream zip) throws IOException {
    Deque<File> dir_stack = new LinkedList<File>();
    dir_stack.push(dir);

    // base path is the parent of the "Application.app" folder
    // it will be used to make "Application.app" the top-level folder in the zip
    String base_path = getParentDirAbsolutePath(dir);

    // verify that "dir" actually id the ".app" folder
    if (!dir.getName().endsWith(".app"))
        throw new IOException("Please verify the configuration. Directory does not end with '.app': " + dir);

    while (!dir_stack.isEmpty()) {

        File file = dir_stack.pop();
        File[] files = file.listFiles();

        for (File f : files) {
            String name = f.getAbsolutePath().substring(base_path.length());
            getLog().debug("Found: " + name);

            if (f.isFile() && isInContentsFolder(name)) {
                getLog().debug("Adding to zip file for signing: " + f);

                ZipArchiveEntry entry = new ZipArchiveEntry(name);
                zip.putArchiveEntry(entry);

                if (f.canExecute()) {
                    //work around to track the relative file names
                    // of those that need to be set as executable on unZip
                    executableFiles.add(name);
                }
                InputStream is = new FileInputStream(f);
                copyInputStreamToOutputStream(is, zip);

                is.close();
                zip.closeArchiveEntry();
            } else if (f.isDirectory() && isInContentsFolder(name)) { //add directory entry
                dir_stack.push(f);
            } else {
                getLog().debug(f + " was not included in the zip file to be signed.");
            }
        }
    }
}

From source file:org.apache.geode.internal.cache.BackupDUnitTest.java

private void verifyUserFileRestored(VM vm, final long lm) {
    vm.invoke(new SerializableRunnable() {
        public void run() {
            final int pid = DUnitEnv.get().getPid();
            File vmdir = new File("userbackup_" + pid);
            File mytext = new File(vmdir, "test1/test2/my.txt");
            assertTrue(mytext.exists());
            if (System.getProperty("java.specification.version").equals("1.6")) {
                assertTrue(mytext.canExecute());
            } else {
                System.out.println(
                        "java.specification.version is " + System.getProperty("java.specification.version")
                                + ", canExecute is" + mytext.canExecute());
            }//w  ww. j  a  v a  2s .c  o m
            assertEquals(lm, mytext.lastModified());

            try {
                FileReader fr = new FileReader(mytext);
                BufferedReader bin = new BufferedReader(fr);
                String content = bin.readLine();
                assertTrue(content.equals("" + pid));
            } catch (IOException e) {
                fail(e.getMessage());
            }
        }
    });
}

From source file:com.xse.optstack.persconftool.base.persistence.PersConfImport.java

/**
 * Actually starts the import of the persconf configuration at the location specified on construction of this
 * importer instance./*ww w  . ja va2  s. com*/
 *
 * @return OK_STATUS if the import did fully succeed, any other {@link IStatus} instance if there have been errors
 *         or warnings or the import had to be cancelled due to serious problems.
 */
public IStatus importConfig() {
    final File resourceFolder = new File(
            this.rootFolder.getAbsolutePath() + File.separator + PersConfDefinitions.RESOURCE_FOLDER_NAME);
    if (resourceFolder.exists() && resourceFolder.canExecute()) {
        final Resource resource = this.configResource.getResource();

        final Map<String, EApplication> applicationMap = new HashMap<>();

        boolean hasRootItems = false;
        boolean hasWarnings = false;
        boolean hasErrors = false;
        for (final EGroupType groupType : EGroupType.values()) {
            final File groupFile = new File(
                    resourceFolder.getAbsolutePath() + File.separator + groupType.getLiteral().toLowerCase());
            if (groupFile.exists() && groupFile.canExecute()) {
                hasRootItems = true;

                final EApplicationGroup applicationGroup = PersconfFactory.eINSTANCE.createEApplicationGroup();
                applicationGroup.setType(groupType);
                resource.getContents().add(applicationGroup);

                final Map<String, EInstallRule> installRulesMapping = new HashMap<>();
                final File installRulesFile = new File(
                        groupFile + File.separator + PersConfDefinitions.INSTALL_RULES_FILE);
                if (installRulesFile.exists() && installRulesFile.canRead()) {
                    final GsonBuilder gsonBuilder = new GsonBuilder();
                    final Gson gson = gsonBuilder.create();
                    try (final FileReader reader = new FileReader(installRulesFile.getAbsolutePath())) {
                        final JsonObject fromJson = gson.fromJson(reader, JsonObject.class);
                        for (final Entry<String, JsonElement> entry : fromJson.entrySet()) {
                            final EInstallRule installRule = EInstallRule.get(entry.getValue().getAsString()
                                    .substring(PersConfDefinitions.INSTALL_RULE_PREFIX.length()));
                            if (installRule != null) {
                                installRulesMapping.put(entry.getKey(), installRule);
                            } else {
                                Logger.warn(Activator.PLUGIN_ID,
                                        "Invalid installation rule definition '"
                                                + entry.getValue().getAsString() + "' in group " + groupType
                                                + " group.");
                                hasWarnings = true;
                            }
                        }
                    } catch (final Exception e) {
                        Logger.error(Activator.PLUGIN_ID, "Error parsing " + installRulesFile.getName() + " of "
                                + groupType
                                + " group. Does that file contain valid JSON (e.g. no trailing commas)?", e);
                        hasErrors = true;
                    }
                }

                final File[] groupFiles = groupFile.listFiles((FileFilter) DirectoryFileFilter.INSTANCE);
                if (groupFiles != null) {
                    for (final File appFolder : groupFiles) {
                        if (appFolder.exists() && appFolder.canExecute()) {
                            final EApplication application = PersconfFactory.eINSTANCE.createEApplication();
                            application.setName(appFolder.getName());
                            applicationMap.put(application.getName(), application);
                            if (installRulesMapping.containsKey(appFolder.getName())) {
                                application.setInstallRule(installRulesMapping.get(appFolder.getName()));
                            }
                            applicationGroup.getApplications().add(application);

                            final Map<String, EResource> resources = new HashMap<>();

                            final File installExceptionsFile = new File(appFolder.getAbsolutePath()
                                    + File.separator + PersConfDefinitions.INSTALL_EXCEPTIONS_FILE);
                            if (installExceptionsFile.exists() && installExceptionsFile.canRead()) {
                                final GsonBuilder gsonBuilder = new GsonBuilder();
                                final Gson gson = gsonBuilder.create();
                                try (final FileReader reader = new FileReader(
                                        installExceptionsFile.getAbsolutePath())) {
                                    final JsonObject fromJson = gson.fromJson(reader, JsonObject.class);
                                    for (final Entry<String, JsonElement> entry : fromJson.entrySet()) {
                                        final EInstallException installException = EInstallException
                                                .get(entry.getValue().getAsString().substring(
                                                        PersConfDefinitions.INSTALL_EXCEPTION_PREFIX.length()));
                                        if (installException != null) {
                                            final EResource res = createResource(entry.getKey());
                                            res.setInstallException(installException);
                                            application.getResources().add(res);
                                            resources.put(entry.getKey(), res);
                                        } else {
                                            Logger.warn(Activator.PLUGIN_ID,
                                                    "Invalid installation exception definition: "
                                                            + entry.getValue().getAsString()
                                                            + " of application '" + application.getName()
                                                            + "'.");
                                            hasWarnings = true;
                                        }
                                    }
                                } catch (final Exception e) {
                                    Logger.error(Activator.PLUGIN_ID, "Error parsing install exceptions file '"
                                            + installExceptionsFile.getName() + "' of application '"
                                            + application.getName()
                                            + "'. Does that file contain valid JSON (e.g. no trailing commas)?",
                                            e);
                                    hasErrors = true;
                                }
                            }

                            final File resouceConfigurationFile = new File(appFolder.getAbsolutePath()
                                    + File.separator + PersConfDefinitions.RESOURCE_CONFIGURATION_FILE);
                            if (resouceConfigurationFile.exists() && resouceConfigurationFile.canRead()) {
                                final GsonBuilder gsonBuilder = new GsonBuilder();
                                final Gson gson = gsonBuilder.create();
                                try (final FileReader reader = new FileReader(
                                        resouceConfigurationFile.getAbsolutePath())) {
                                    final JsonObject fromJson = gson.fromJson(reader, JsonObject.class);
                                    final JsonElement resourcesNode = fromJson
                                            .get(PersConfDefinitions.RESOURCES_KEY_NAME);
                                    final JsonElement versionElement = fromJson
                                            .get(PersConfDefinitions.VERSION_KEY_NAME);
                                    if (versionElement != null) {
                                        application.setVersion(versionElement.getAsString());
                                    }
                                    if (resourcesNode != null) {
                                        for (final Entry<String, JsonElement> entry : resourcesNode
                                                .getAsJsonObject().entrySet()) {
                                            if (!resources.containsKey(entry.getKey())) {
                                                final EResource res = createResource(entry.getKey());
                                                resources.put(entry.getKey(), res);
                                                application.getResources().add(res);
                                            }
                                            final EResource res = resources.get(entry.getKey());

                                            if (PersConfImport.handleConfigEntries(entry, res)) {
                                                hasWarnings = true;
                                            }
                                        }
                                    }
                                } catch (final Exception e) {
                                    Logger.error(Activator.PLUGIN_ID,
                                            "Error parsing resource configuration file of application '"
                                                    + application.getName()
                                                    + "'. Does that file contain valid JSON (e.g. no trailing commas)?",
                                            e);
                                    hasErrors = true;
                                }
                            } else {
                                Logger.warn(Activator.PLUGIN_ID, "Unable to read resource configuration file: "
                                        + resouceConfigurationFile.getName());
                                hasWarnings = true;
                            }

                            final File configDefaultFile = new File(appFolder.getAbsolutePath() + File.separator
                                    + PersConfDefinitions.KEY_FOLDER + File.separator
                                    + PersConfDefinitions.CONFIGURABLE_DEFAULTS_FILE);
                            if (PersConfImport.handleDefaultDataEntry(configDefaultFile,
                                    PersconfPackage.ECONFIGURATION__CONFIG_DEFAULT, resources, application)) {
                                hasWarnings = true;
                            }

                            final File factoryDefaultFile = new File(appFolder.getAbsolutePath()
                                    + File.separator + PersConfDefinitions.KEY_FOLDER + File.separator
                                    + PersConfDefinitions.FACTORY_DEFAULTS_FILE);
                            if (PersConfImport.handleDefaultDataEntry(factoryDefaultFile,
                                    PersconfPackage.ECONFIGURATION__FACTORY_DEFAULT, resources, application)) {
                                hasWarnings = true;
                            }
                        }
                    }
                }

                final File ownershipConfigurationFile = new File(
                        groupFile + File.separator + PersConfDefinitions.OWNERSHIP_CONFIGURATION_FILE);
                if (ownershipConfigurationFile.exists() && ownershipConfigurationFile.canRead()) {
                    final GsonBuilder gsonBuilder = new GsonBuilder();
                    final Gson gson = gsonBuilder.create();

                    try (final FileReader reader = new FileReader(
                            ownershipConfigurationFile.getAbsolutePath())) {
                        final JsonObject fromJson = gson.fromJson(reader, JsonObject.class);

                        for (final Entry<String, JsonElement> applicationEntry : fromJson.entrySet()) {
                            final String applicationName = applicationEntry.getKey();

                            // Find application by name:
                            final EApplication application = applicationMap.get(applicationName);
                            if (application == null)
                                continue;

                            try {
                                for (final Entry<String, JsonElement> ownershipEntry : applicationEntry
                                        .getValue().getAsJsonObject().entrySet()) {
                                    final String ownershipTypeName = ownershipEntry.getKey();
                                    final String ownershipValueString = String
                                            .valueOf(ownershipEntry.getValue()).replaceAll("\"", "");

                                    switch (ownershipTypeName) {
                                    case PersConfDefinitions.USERNAME_KEY_NAME:
                                        application.setUserName(ownershipValueString);
                                        break;
                                    case PersConfDefinitions.GROUPNAME_KEY_NAME:
                                        application.setGroupName(ownershipValueString);
                                        break;
                                    case PersConfDefinitions.USERID_KEY_NAME:
                                        if (ownershipValueString.equals(""))
                                            application.setUserId(null);
                                        else {
                                            try {
                                                final Integer ownerShipValue = Integer
                                                        .valueOf(ownershipValueString);
                                                application.setUserId(ownerShipValue);
                                            } catch (NumberFormatException e) {
                                                Logger.warn(Activator.PLUGIN_ID,
                                                        "Cannot read ownership configuration entry: Value for UserID cannot be parsed as integer: "
                                                                + ownershipValueString);
                                                hasWarnings = true;
                                            }
                                        }
                                        break;
                                    case PersConfDefinitions.GROUPID_KEY_NAME:
                                        if (ownershipValueString.equals(""))
                                            application.setGroupId(null);
                                        else {
                                            try {
                                                final Integer ownerShipValue = Integer
                                                        .valueOf(ownershipValueString);
                                                application.setGroupId(ownerShipValue);
                                            } catch (NumberFormatException e) {
                                                Logger.warn(Activator.PLUGIN_ID,
                                                        "Cannot read ownership configuration entry: Value for GroupID cannot be parsed as integer: "
                                                                + ownershipValueString);
                                                hasWarnings = true;
                                            }
                                        }
                                        break;
                                    default:
                                        Logger.warn(Activator.PLUGIN_ID,
                                                "Unknown identifier in ownership configuration file: "
                                                        + ownershipTypeName);
                                        hasWarnings = true;
                                        break;
                                    }
                                }
                            } catch (IllegalStateException e) {
                                Logger.warn(Activator.PLUGIN_ID,
                                        "Error while parsing the ownership configuration file: Cannot read sub-entries of application "
                                                + applicationName);
                            }
                        }
                    } catch (final Exception e) {
                        Logger.error(Activator.PLUGIN_ID,
                                "Error parsing ownership configuration file. Does that file contain valid JSON (e.g. no trailing commas)?",
                                e);
                        hasErrors = true;
                    }
                } else {
                    Logger.warn(Activator.PLUGIN_ID, "Unable to read resource configuration file: "
                            + ownershipConfigurationFile.getName());
                    hasWarnings = true;
                }
            } else {
                // add missing application groups
                final EApplicationGroup applicationGroup = PersconfFactory.eINSTANCE.createEApplicationGroup();
                applicationGroup.setType(groupType);
                resource.getContents().add(applicationGroup);
                Logger.warn(Activator.PLUGIN_ID, "No configuration items for " + groupType + ".");
                hasWarnings = true;
            }
        }

        if (!hasRootItems) {
            return new Status(IStatus.CANCEL, Activator.PLUGIN_ID,
                    "Directory does not contain a valid persistency configuration structure.");
        }

        this.importAppSizes(applicationMap);

        if (hasErrors) {
            return new Status(IStatus.ERROR, Activator.PLUGIN_ID,
                    "The configuration " + this.rootFolder + " contains errors.");
        } else if (hasWarnings) {
            return new Status(IStatus.WARNING, Activator.PLUGIN_ID,
                    "The configuration " + this.rootFolder + " contains warnings.");
        } else {
            return Status.OK_STATUS;
        }
    } else {
        return new Status(IStatus.CANCEL, Activator.PLUGIN_ID,
                "Directory does not contain a '" + PersConfDefinitions.RESOURCE_FOLDER_NAME + "' folder.");
    }
}

From source file:display.containers.FileManager.java

public static boolean copyFile(File from, File to) throws IOException {

    boolean created = to.createNewFile();

    if (created) {
        FileChannel fromChannel = null;
        FileChannel toChannel = null;
        try {//from w w w . j a v  a2  s.c  o  m
            fromChannel = new FileInputStream(from).getChannel();
            toChannel = new FileOutputStream(to).getChannel();

            toChannel.transferFrom(fromChannel, 0, fromChannel.size());

            // set the flags of the to the same as the from
            to.setReadable(from.canRead());
            to.setWritable(from.canWrite());
            to.setExecutable(from.canExecute());
        } finally {
            if (fromChannel != null) {
                fromChannel.close();
            }
            if (toChannel != null) {
                toChannel.close();
            }
            return false;
        }
    }
    return created;
}

From source file:org.kepler.ddp.director.DDPEngine.java

/** Check if the DDP engine server is running. If not, try to start it.
 *  @param socketAddress Host and port of the server to check.
 *  @param startScriptStr The script to start the server if not running.
 *  @return True if a server was started, false if could connect to already running server. 
 *///ww  w  . ja  v  a2 s  .  c  o  m
protected boolean _checkServer(InetSocketAddress socketAddress, String startScriptStr)
        throws IllegalActionException {

    boolean startedServer = false;

    synchronized (_serverStartStopLock) {
        Socket socket = null;
        try {
            socket = new Socket();
            boolean connected = false;
            try {
                socket.connect(socketAddress, _CONNECT_TIMEOUT);
                connected = true;
            } catch (IOException e) {

                System.out.println(_engineName + " server " + socketAddress
                        + " does not appear to be running. Starting...");

                // start the server

                if (!_checkFilesBeforeStartingServer()) {
                    throw new IllegalActionException(_director,
                            "One or more files required to start the server were not found.");
                }

                // see if the script is executable. kepler modules are zipped,
                // which does not preserve the permissions.
                File startScriptFile = new File(startScriptStr);
                if (!startScriptFile.canExecute()) {
                    throw new IllegalActionException(_director,
                            "The script " + startScriptFile + " is not executable.\n"
                                    + "You must change the permissions so that " + startScriptFile.getName()
                                    + " and all the other scripts in \n" + startScriptFile.getParent()
                                    + " are executable.");
                }

                ProcessBuilder builder = new ProcessBuilder(startScriptStr);

                // make sure JAVA_HOME is set
                java.util.Map<String, String> env = builder.environment();
                if (env.get("JAVA_HOME") == null) {
                    env.put("JAVA_HOME", System.getProperty("java.home"));
                }

                builder.redirectErrorStream(true);

                try {
                    Process process = builder.start();
                    InetSocketAddress newAddress = _parseOutputFromStartingServer(process.getInputStream());
                    if (newAddress != null) {
                        socketAddress = newAddress;
                    }
                    process.waitFor();
                    startedServer = true;
                } catch (Exception e1) {
                    throw new IllegalActionException(_director, e1,
                            "Unable to start " + _engineName + " server.");
                }

                int tries = 0;
                while (tries < 5) {
                    // wait for the server to start
                    try {
                        Thread.sleep(5000);
                        tries++;
                        System.out.print("Connecting to " + _engineName + " server port try #" + tries + ": ");
                        try {
                            socket.close();
                            socket = new Socket();
                            socket.connect(socketAddress, _CONNECT_TIMEOUT);
                            connected = true;
                            System.out.println("connected.");
                            break;
                        } catch (IOException e1) {
                            // do nothing
                            System.out.println(e1);
                        }
                    } catch (InterruptedException e2) {
                        throw new IllegalActionException(_director, e2, "Error while sleeping.");
                    }
                }

                // if we get here, we were able to connect to the master/job manager port.
                // however, the server may not be completely initialized, so wait a few more seconds
                System.out.println("Waiting 15 seconds for " + _engineName + " server to initialize.");
                try {
                    Thread.sleep(15000);
                } catch (InterruptedException e2) {
                    throw new IllegalActionException(_director, e2,
                            "Error while waiting " + " for " + _engineName + " server to initialize.");
                }

            }

            if (connected) {
                try {
                    socket.close();
                    socket = null;
                } catch (IOException e) {
                    throw new IllegalActionException(_director, e, "Error closing socket.");
                }
            } else {
                throw new IllegalActionException(_director,
                        "Could not connect to " + _engineName + " server: " + socketAddress);
            }
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new IllegalActionException(_director, e, "Error closing socket.");
                }
            }
        }
    }

    return startedServer;
}

From source file:org.jboss.tools.openshift.internal.ui.wizard.connection.AdvancedConnectionEditor.java

private IStatus validateOCLocation(String location, boolean override) {
    IStatus validity = ValidationStatus.ok();
    if (StringUtils.isBlank(location)) {
        if (override)
            validity = ValidationStatus.error("Please provide a location for the OC binary.");
        else {//from w w w.  j av a 2s  . c o  m
            validity = ValidationStatus.error(
                    "The workspace setting for the OC binary is not set. Please update the workspace setting or override the location here in the 'Advanced' section.");
        }
    } else {
        File file = new File(location);
        // Error messages have to be set to field editor, not directly to
        // the page.
        if (override) {
            if (!file.exists()) {
                validity = ValidationStatus.error((NLS.bind("{0} was not found.", file)));
            } else if (file.isDirectory()) {
                validity = ValidationStatus.error((NLS.bind("OC Location must be a file.", file)));
            } else if (!file.canExecute()) {
                validity = ValidationStatus.error(NLS.bind("{0} does not have execute permissions.", file));
            }
        } else {
            if (!file.exists()) {
                validity = ValidationStatus
                        .error((NLS.bind("Workspace setting for OC binary location was not found: {0}", file)));
            } else if (file.isDirectory()) {
                validity = ValidationStatus
                        .error((NLS.bind("Workspace setting for OC binary location is not a file: {0}", file)));
            } else if (!file.canExecute()) {
                validity = ValidationStatus.error(NLS.bind(
                        "Workspace setting for OC binary location does not have execute permissions: {0}",
                        file));
            }
        }
    }
    return validity;
}

From source file:com.cloudera.impala.service.JniFrontend.java

/**
 * Return an empty string if short circuit read is properly enabled. If not, return an
 * error string describing the issues./*from   www .j av a2s  .  c  om*/
 */
private String checkShortCircuitRead(Configuration conf) {
    StringBuilder output = new StringBuilder();
    String errorMessage = "ERROR: short-circuit local reads is disabled because\n";
    String prefix = "  - ";
    StringBuilder errorCause = new StringBuilder();

    // dfs.domain.socket.path must be set properly
    String domainSocketPath = conf.getTrimmed(DFSConfigKeys.DFS_DOMAIN_SOCKET_PATH_KEY,
            DFSConfigKeys.DFS_DOMAIN_SOCKET_PATH_DEFAULT);
    if (domainSocketPath.isEmpty()) {
        errorCause.append(prefix);
        errorCause.append(DFSConfigKeys.DFS_DOMAIN_SOCKET_PATH_KEY);
        errorCause.append(" is not configured.\n");
    } else {
        // The socket path parent directory must be readable and executable.
        File socketFile = new File(domainSocketPath);
        File socketDir = socketFile.getParentFile();
        if (socketDir == null || !socketDir.canRead() || !socketDir.canExecute()) {
            errorCause.append(prefix);
            errorCause.append("Impala cannot read or execute the parent directory of ");
            errorCause.append(DFSConfigKeys.DFS_DOMAIN_SOCKET_PATH_KEY);
            errorCause.append("\n");
        }
    }

    // dfs.client.read.shortcircuit must be set to true.
    if (!conf.getBoolean(DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_KEY,
            DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_DEFAULT)) {
        errorCause.append(prefix);
        errorCause.append(DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_KEY);
        errorCause.append(" is not enabled.\n");
    }

    // dfs.client.use.legacy.blockreader.local must be set to false
    if (conf.getBoolean(DFSConfigKeys.DFS_CLIENT_USE_LEGACY_BLOCKREADERLOCAL,
            DFSConfigKeys.DFS_CLIENT_USE_LEGACY_BLOCKREADERLOCAL_DEFAULT)) {
        errorCause.append(prefix);
        errorCause.append(DFSConfigKeys.DFS_CLIENT_USE_LEGACY_BLOCKREADERLOCAL);
        errorCause.append(" should not be enabled.\n");
    }

    if (errorCause.length() > 0) {
        output.append(errorMessage);
        output.append(errorCause);
    }

    return output.toString();
}

From source file:org.moe.gradle.MoeSDK.java

private void validate(int type, @NotNull Path path, @NotNull String sub) throws IOException {
    Require.nonNull(path);// w  w w . j a va 2  s . c om
    Require.nonNull(sub);

    final Path fullPath = sub.length() == 0 ? path : path.resolve(sub);
    final File file = fullPath.toFile();
    if (!file.exists()) {
        throw new IOException("no filesystem entry exists at " + file.getAbsolutePath());
    }
    if ((type & DIR) != 0 && !file.isDirectory()) {
        throw new IOException("expected a directory at " + file.getAbsolutePath());
    }
    if ((type & FIL) != 0 && !file.isFile()) {
        throw new IOException("expected a file at " + file.getAbsolutePath());
    }
    if ((type & EXE) != 0 && !file.canExecute() && !file.setExecutable(true)) {
        throw new IOException("file is not executable at " + file.getAbsolutePath());
    }
}

From source file:org.mitre.mpf.nms.BaseServiceLauncher.java

/**
 *
 * @param minServiceTimeupMillis the minimum amount of time a service must be running to allow more than one restart
 * @return/*from ww w  . j  a  va 2 s . c  o m*/
 */
public boolean startup(int minServiceTimeupMillis) {
    this.minTimeUpMilliSeconds = minServiceTimeupMillis;

    // Until shown otherwise, we have had a problem starting up
    m_fatalProblemFlag = true;

    File tester = new File(this.getCommandPath());
    String fullPath = null;

    // get fully qualified path to executable, completing any relative paths used.
    try {
        fullPath = tester.getCanonicalPath();
    } catch (IOException e) {
        LOG.error("Exception", e);
    }

    if (!tester.exists()) {
        LOG.error("Node service command '{}' for '{}' does not exist or is not reachable.", fullPath,
                this.mServiceDesc.getName());
        mRunToCompletion = true;
        return false;
    } else if (!tester.canExecute()) {
        LOG.error("Node service command '{}' for '{}' exists but is not executable.  Check permissions!",
                fullPath, this.mServiceDesc.getName());
        mRunToCompletion = true;
        return false;
    }

    thread = new Thread(this);
    thread.start();

    return true;
}

From source file:org.apache.slider.common.tools.SliderUtils.java

/**
 * Verify that a Unix exe works//from w w  w .  j a  v a  2s . c om
 * @param program program name for errors
 * @param exe executable
 * @throws IOException IOE
        
 */
public static void verifyUnixExe(String program, File exe) throws IOException {
    verifyIsFile(program, exe);

    // read flag
    if (!exe.canRead()) {
        throw new IOException("Cannot read " + program + " at " + exe);
    }
    // exe flag
    if (!exe.canExecute()) {
        throw new IOException("Cannot execute " + program + " at " + exe);
    }
}