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.dcache.xrootd.standalone.DataServerHandler.java

private int getFileStatusFlagsOf(File file) {
    int flags = 0;
    if (file.isDirectory()) {
        flags |= kXR_isDir;/*w  ww  . j av  a 2  s  .c o  m*/
    }
    if (!file.isFile() && !file.isDirectory()) {
        flags |= kXR_other;
    }
    if (file.canExecute()) {
        flags |= kXR_xset;
    }
    if (file.canRead()) {
        flags |= kXR_readable;
    }
    if (file.canWrite()) {
        flags |= kXR_writable;
    }
    return flags;
}

From source file:org.opennms.smoketest.OpenNMSSeleniumTestCase.java

private File findPhantomJS() {
    final String os = System.getProperty("os.name").toLowerCase();
    final String extension = (os.indexOf("win") >= 0) ? ".exe" : "";

    final String path = System.getenv("PATH");
    if (path == null) {
        LOG.debug("findPhantomJS(): Unable to get PATH.");
        final File phantomFile = new File("/usr/local/bin/phantomjs" + extension);
        LOG.debug("findPhantomJS(): trying {}", phantomFile);
        if (phantomFile.exists() && phantomFile.canExecute()) {
            return phantomFile;
        }/*from www  . j  av  a2s.c  om*/
    } else {
        final List<String> paths = new ArrayList<String>(Arrays.asList(path.split(File.pathSeparator)));
        paths.add("/usr/local/bin");
        paths.add("/usr/local/sbin");
        LOG.debug("findPhantomJS(): paths = {}", paths);
        for (final String directory : paths) {
            final File phantomFile = new File(directory + File.separator + "phantomjs" + extension);
            LOG.debug("findPhantomJS(): trying {}", phantomFile);
            if (phantomFile.exists() && phantomFile.canExecute()) {
                return phantomFile;
            }
        }
    }
    return null;
}

From source file:org.geotools.coverage.io.util.Utilities.java

/**
 * Creates a human readable message that describe the provided {@link File} object in terms of its properties.
 * //from  w  w  w  . ja  va 2  s .  co  m
 * <p>
 * Useful for creating meaningful log messages.
 * 
 * @param file the {@link File} object to create a descriptive message for
 * @return a {@link String} containing a descriptive message about the provided {@link File}.
 * 
 */
public static String getFileInfo(final File file) {
    final StringBuilder builder = new StringBuilder();
    builder.append("Checking file:").append(FilenameUtils.getFullPath(file.getAbsolutePath())).append("\n");
    builder.append("isHidden:").append(file.isHidden()).append("\n");
    builder.append("exists:").append(file.exists()).append("\n");
    builder.append("isFile").append(file.isFile()).append("\n");
    builder.append("canRead:").append(file.canRead()).append("\n");
    builder.append("canWrite").append(file.canWrite()).append("\n");
    builder.append("canExecute:").append(file.canExecute()).append("\n");
    builder.append("isAbsolute:").append(file.isAbsolute()).append("\n");
    builder.append("lastModified:").append(file.lastModified()).append("\n");
    builder.append("length:").append(file.length());
    final String message = builder.toString();
    return message;
}

From source file:com.cws.esolutions.agent.processors.impl.ApplicationManagerProcessorImpl.java

/**
 * @see com.cws.esolutions.agent.processors.interfaces.IApplicationManagerProcessor#installApplication(com.cws.esolutions.agent.processors.dto.ApplicationManagerRequest)
 *///from   w w  w  .  j  ava 2  s  . co m
public ApplicationManagerResponse installApplication(final ApplicationManagerRequest request)
        throws ApplicationManagerException {
    final String methodName = IApplicationManagerProcessor.CNAME
            + "#installApplication(final ApplicationManagerRequest request) throws ApplicationManagerException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ApplicationManagerRequest: {}", request);
    }

    BufferedWriter writer = null;
    ApplicationManagerResponse response = new ApplicationManagerResponse();

    final double version = request.getVersion();
    final DefaultExecutor executor = new DefaultExecutor();
    final String installerOptions = request.getInstallerOptions();
    final File installPath = FileUtils.getFile(request.getInstallPath());
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(CONNECT_TIMEOUT * 1000);
    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    final File packageInstaller = FileUtils.getFile(request.getPackageInstaller());

    if (DEBUG) {
        DEBUGGER.debug("double: {}", version);
        DEBUGGER.debug("DefaultExecutor: {}", executor);
        DEBUGGER.debug("String: {}", installerOptions);
        DEBUGGER.debug("File: {}", installPath);
        DEBUGGER.debug("ExecuteWatchdog: {}", watchdog);
        DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler);
        DEBUGGER.debug("File:{}", packageInstaller);
    }

    try {
        if (!(packageInstaller.canExecute())) {
            throw new ApplicationManagerException("Unable to execute package installer. Cannot continue.");
        }

        if (!(installPath.canWrite()) && (!(installPath.mkdirs()))) {
            throw new ApplicationManagerException("Unable to create installation target. Cannot continue.");
        }

        CommandLine command = CommandLine.parse(packageInstaller.getAbsolutePath());
        command.addArgument(installerOptions, false);
        command.addArgument(request.getPackageLocation(), false);

        if (DEBUG) {
            DEBUGGER.debug("CommandLine: {}", command);
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ExecuteStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        streamHandler.start();

        executor.setWatchdog(watchdog);
        executor.setStreamHandler(streamHandler);

        if (DEBUG) {
            DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler);
            DEBUGGER.debug("ExecuteWatchdog: {}", watchdog);
            DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler);
            DEBUGGER.debug("DefaultExecutor: {}", executor);
        }

        executor.execute(command, resultHandler);

        resultHandler.waitFor();
        int exitCode = resultHandler.getExitValue();

        writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + request.getPackageName() + ".log"));
        writer.write(outputStream.toString());
        writer.flush();

        if (DEBUG) {
            DEBUGGER.debug("exitCode: {}", exitCode);
        }

        if (executor.isFailure(exitCode)) {
            throw new ApplicationManagerException("Application installation failed: Result Code: " + exitCode);
        }

        response.setResponse(outputStream.toString());
        response.setRequestStatus(AgentStatus.SUCCESS);
    } catch (ExecuteException eex) {
        ERROR_RECORDER.error(eex.getMessage(), eex);

        throw new ApplicationManagerException(eex.getMessage(), eex);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new ApplicationManagerException(iox.getMessage(), iox);
    } catch (InterruptedException ix) {
        ERROR_RECORDER.error(ix.getMessage(), ix);

        throw new ApplicationManagerException(ix.getMessage(), ix);
    } finally {
        try {
            writer.close();
        } catch (IOException iox) {
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }

    return response;
}

From source file:com.hughes.android.dictionary.DictionaryManagerActivity.java

public void readableCheckAndError(boolean requestPermission) {
    final File dictDir = application.getDictDir();
    if (dictDir.canRead() && dictDir.canExecute())
        return;//w ww  .ja v  a 2  s.  c o  m
    blockAutoLaunch = true;
    if (requestPermission && ContextCompat.checkSelfPermission(getApplicationContext(),
            Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
        return;
    }
    blockAutoLaunch = true;

    AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
    builder.setTitle(getString(R.string.error));
    builder.setMessage(getString(R.string.unableToReadDictionaryDir, dictDir.getAbsolutePath(),
            Environment.getExternalStorageDirectory()));
    builder.setNeutralButton("Close", null);
    builder.create().show();
}

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

private void exportCHeader(final EApplication application) {
    if (application.getResources().size() > 0) {
        final File headerFolder = new File(this.rootFolder + File.separator + "header");
        try {/*from   w  ww.j a  v a  2s. c o m*/
            headerFolder.mkdir();
        } catch (final SecurityException e) {
            Logger.error(Activator.PLUGIN_ID,
                    "Not allowed to create header folder: " + headerFolder.getAbsolutePath(), e);
        }
        if (headerFolder.exists() && headerFolder.canExecute()) {
            final String lineSeparator = System.getProperty("line.separator");
            try (final FileWriter fileWriter = new FileWriter(
                    headerFolder + File.separator + application.getName() + ".h")) {
                for (final EResource eResource : application.getResources()) {
                    fileWriter.write("#define ");
                    fileWriter.write(
                            application.getName().toUpperCase() + "_" + eResource.getName().toUpperCase());
                    fileWriter.write(" " + eResource.getName() + lineSeparator);
                }
            } catch (final IOException e) {
                Logger.error(Activator.PLUGIN_ID,
                        "Unable to create header file for " + application.getName() + ".", e);
            }
        } else {
            Logger.error(Activator.PLUGIN_ID,
                    "Unable to read header folder: " + headerFolder.getAbsolutePath());
        }
    }
}

From source file:dk.statsbiblioteket.util.Files.java

/**
 * Copies a file (not a folder).//from  ww w  .  j  av a  2 s. c om
 *
 * @param source      the file to copy.
 * @param destination where to copy the file to. If this is an existing
 *                    directory, {@code source} will be copied into it,
 *                    otherwise {@code source} will copied to this file.
 * @param overwrite   whether or not to overwrite if the destination
 *                    already exists.
 * @throws IOException                thrown if there was an error writing to the
 *                                    destination file, or if the input file doidn't exist
 *                                    or if the source was a directory.
 * @throws FileNotFoundException      thrown if the source file did not exist.
 * @throws FileAlreadyExistsException if there's already a file at
 *                                    {@code destination} and {@code overwrite} was
 *                                    {@code false}.
 */
private static void copyFile(File source, File destination, boolean overwrite) throws IOException {
    log.trace("copyFile(" + source + ", " + destination + ", " + overwrite + ") called");
    source = source.getAbsoluteFile();
    destination = destination.getAbsoluteFile();
    if (!source.exists()) {
        throw new FileNotFoundException("The source '" + source + "' does not exist");
    }
    if (destination.isDirectory()) {
        throw new IOException("The destination '" + destination + "' is a directory");
    }

    if (destination.exists() && destination.isDirectory()) {
        destination = new File(destination, source.getName());
    }

    if (!overwrite && destination.exists()) {
        throw new FileAlreadyExistsException(destination.toString());
    }

    // BufferedInputStream is not used, as it chokes > 2GB
    InputStream in = new FileInputStream(source);
    OutputStream out = new FileOutputStream(destination);

    try {
        byte[] buf = new byte[2028];
        int count = 0;
        while ((count = in.read(buf)) != -1) {
            out.write(buf, 0, count);
        }
    } finally {
        in.close();
        out.close();
    }
    destination.setExecutable(source.canExecute());
}

From source file:edu.kit.dama.dataworkflow.impl.LocalExecutionHandler.java

/**
 * Execute the user application. This method will start a new process running
 * the prepared user application locally. The method will return as soon as
 * the application has terminated. An asnychronous monitoring task my check
 * whether the process is still running or not via {@link #getTaskStatus(edu.kit.dama.mdm.dataworkflow.DataWorkflowTask)
 * } This method will check the runningIndicator file '.RUNNING', which only
 * exists as long as the application is running.
 *
 * @param pTask The task whose application should be executed.
 *
 * @throws DataWorkflowProcessingException If either the startup or the
 * processing fails for any reason, or if the user application returns an exit
 * code != 0./*from   w  w w  .  j a  v  a 2  s  . c  o m*/
 */
@Override
public void startUserApplication(DataWorkflowTask pTask) throws DataWorkflowProcessingException {
    //simply start the process...monitoring will be connected later
    File runningIndicator = getRunningIndicator(pTask);
    FileOutputStream fout = null;
    FileOutputStream ferr = null;
    File executablePath;

    try {
        executablePath = DataWorkflowHelper.getTaskMainExecutable(pTask);
        File executionBasePath = DataWorkflowHelper.getExecutionBasePath(pTask);
        File workingDirectory = DataWorkflowHelper.getTaskWorkingDirectory(executionBasePath);
        File tempDirectory = DataWorkflowHelper.getTaskTempDirectory(executionBasePath);
        File inputDirectory = DataWorkflowHelper.getTaskInputDirectory(executionBasePath);
        File outputDirectory = DataWorkflowHelper.getTaskOutputDirectory(executionBasePath);

        if (!executablePath.canExecute()) {
            LOGGER.debug("Executable at location {} seems not to be executable. Taking care of this...");
            if (executablePath.setExecutable(true)) {
                LOGGER.debug("Executable was successfully set to be executable.");
            } else {
                LOGGER.warn("Failed to set executable to be executable. Trying to continue.");
            }
        }

        String cmdLineString = executablePath.getAbsolutePath() + " "
                + pTask.getConfiguration().getApplicationArguments() + " " + pTask.getApplicationArguments();
        LOGGER.debug("Building up command array from string '{}'", cmdLineString);

        CommandLine cmdLine = CommandLine.parse(cmdLineString);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        Map<String, String> env = new HashMap<>();
        env.put("WORKING_DIR", workingDirectory.getAbsolutePath());
        env.put("TEMP_DIR", tempDirectory.getAbsolutePath());
        env.put("INPUT_DIR", inputDirectory.getAbsolutePath());
        env.put("OUTPUT_DIR", outputDirectory.getAbsolutePath());

        fout = new FileOutputStream(new File(tempDirectory, "stdout.log"));
        ferr = new FileOutputStream(new File(tempDirectory, "stderr.log"));
        LOGGER.debug("Setting stream handler for stdout and stderr.");
        executor.setStreamHandler(new PumpStreamHandler(fout, ferr));
        LOGGER.debug("Creating .RUNNING file for monitoring.");
        FileUtils.touch(runningIndicator);
        LOGGER.debug("Executing process.");
        int exitCode = executor.execute(cmdLine);
        if (exitCode != 0) {
            throw new DataWorkflowProcessingException(
                    "Execution returned exit code " + exitCode + ". See logfiles for details.");
        } else {
            LOGGER.debug("Process successfully finished with exit code {}", exitCode);
        }
    } catch (IOException | UnsupportedOperatingSystemException e) {
        throw new DataWorkflowProcessingException("Failed to start executable for task " + pTask.getId(), e);
    } finally {
        LOGGER.debug("Removing running indicator file {}", runningIndicator);
        FileUtils.deleteQuietly(runningIndicator);
        if (fout != null) {
            try {
                fout.close();
            } catch (IOException ex) {
            }
        }

        if (ferr != null) {
            try {
                ferr.close();
            } catch (IOException ex) {
            }
        }
    }
}

From source file:com.cloud.hypervisor.kvm.storage.LibvirtStorageAdaptor.java

public StoragePool createFileBasedStoragePool(Connect conn, String localStoragePath, String uuid) {
    if (!(_storageLayer.exists(localStoragePath) && _storageLayer.isDirectory(localStoragePath))) {
        return null;
    }// www  . j av  a  2  s  .c  o  m

    File path = new File(localStoragePath);
    if (!(path.canWrite() && path.canRead() && path.canExecute())) {
        return null;
    }

    StoragePool pool = null;

    try {
        pool = conn.storagePoolLookupByUUIDString(uuid);
    } catch (LibvirtException e) {

    }

    if (pool == null) {
        LibvirtStoragePoolDef spd = new LibvirtStoragePoolDef(poolType.DIR, uuid, uuid, null, null,
                localStoragePath);
        try {
            pool = conn.storagePoolDefineXML(spd.toString(), 0);
            pool.create(0);
        } catch (LibvirtException e) {
            if (pool != null) {
                try {
                    pool.destroy();
                    pool.undefine();
                } catch (LibvirtException e1) {
                }
                pool = null;
            }
            throw new CloudRuntimeException(e.toString());
        }
    }

    try {
        StoragePoolInfo spi = pool.getInfo();
        if (spi.state != StoragePoolState.VIR_STORAGE_POOL_RUNNING) {
            pool.create(0);
        }

    } catch (LibvirtException e) {
        throw new CloudRuntimeException(e.toString());
    }

    return pool;
}

From source file:eu.stratosphere.client.web.WebInterfaceServer.java

/**
 * Checks and creates the directory described by the abstract directory path. This function checks
 * if the directory exists and creates it if necessary. It also checks read permissions and
 * write permission, if necessary./*from   ww  w  .j  a  va2s  .  c  o  m*/
 * 
 * @param dir
 *        The String describing the directory path.
 * @param needWritePermission
 *        A flag indicating whether to check write access.
 * @throws IOException
 *         Thrown, if the directory could not be created, or if one of the checks failed.
 */
private final void checkAndCreateDirectories(File f, boolean needWritePermission) throws IOException {
    String dir = f.getAbsolutePath();

    // check if it exists and it is not a directory
    if (f.exists() && !f.isDirectory()) {
        throw new IOException("A none directory file with the same name as the configured directory '" + dir
                + "' already exists.");
    }

    // try to create the directory
    if (!f.exists()) {
        if (!f.mkdirs()) {
            throw new IOException("Could not create the directory '" + dir + "'.");
        }
    }

    // check the read and execute permission
    if (!(f.canRead() && f.canExecute())) {
        throw new IOException("The directory '" + dir + "' cannot be read and listed.");
    }

    // check the write permission
    if (needWritePermission && !f.canWrite()) {
        throw new IOException("No write access could be obtained on directory '" + dir + "'.");
    }
}