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.jini.commands.files.FindFiles.java

/**
 * Find Files with a wild card pattern/*from   w w  w.j a  v  a2  s  .  c  o  m*/
 *
 * @param dirName
 * @param wildCardPattern
 * @param recursive
 */
void findFilesWithWildCard(String dirName, String wildCardPattern, boolean recursive) {

    PrintChar printChar = new PrintChar();
    printChar.setOutPutChar(">");

    if ((this.getJcError() == false) && (this.isDir(dirName) == false)) {
        this.setJcError(true);
        this.addErrorMessages("Error : Directory [" + dirName + "] does not exsist.");
    }

    if (this.getJcError() == false) {
        printChar.start();

        try {
            File root = new File(dirName);

            Collection files = FileUtils.listFiles(root, null, recursive);

            TablePrinter tableF = new TablePrinter("Name", "Type", "Readable", "Writable", "Executable",
                    "Size KB", "Size MB", "Last Modified");

            for (Iterator iterator = files.iterator(); iterator.hasNext();) {

                File file = (File) iterator.next();

                if (file.getName().matches(wildCardPattern)) {

                    if (this.withDetails == false) {
                        System.out.println(file.getAbsolutePath());
                    } else {

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

                        String type = "";

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

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

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

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

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

            if (this.withDetails == true) {
                if (files.isEmpty() == false) {
                    tableF.print();
                }
            }

            printChar.setStopPrinting(true);
        } catch (Exception e) {

            this.setJcError(true);
            this.addErrorMessages("Error : " + e.toString());
        }

    }

    printChar.setStopPrinting(true);
    this.done = true;
}

From source file:com.ah.ui.actions.hiveap.HiveApFileAction.java

/**
 * Upload the file to appoint location.//w  w  w. ja v a2s.co m
 *
 *@return result
 */
private String saveFile() {
    FileOutputStream fos = null;
    FileInputStream fis = null;
    String strPath = AhDirTools.getImageDir(HmDomain.HOME_DOMAIN);

    // for log message
    String result = "Upload " + NmsUtil.getOEMCustomer().getAccessPointOS() + " image";

    // the file is Captive Web Page
    if ("cwpFile".equals(fileType)) {
        strPath = AhDirTools.getCwpWebPageDir(domainName, cwpDir);
        result = "Upload CWP web page";
    } else if ("cwpPageCustom".equals(fileType)) {
        strPath = AhDirTools.getPageResourcesDir(domainName);
        result = "Upload CWP web page resource";
    } else if (FILE_TYPE_L7_SIGNATURE.equals(fileType)) {
        strPath = AhDirTools.getL7SignatureDir(HmDomain.HOME_DOMAIN);
        result = "Upload L7 signature file";
    }

    /*
     * create the direct which saved the file if it does not exist
     */
    try {
        HmBeOsUtil.getFileAndSubdirectoryNames(strPath, BeOsLayerModule.ONLYFILE, false);
    } catch (Exception e) {
        HmBeOsUtil.createDirectory(strPath);
    }

    String oldName = "";
    AhScpMgmt fileTranser = null;

    try {
        /*
         * upload the file from local host
         */
        if ("local".equals(selectType)) {
            oldName = getUploadFileName();
            if (null != upload && !"".equals(oldName)) {

                /*
                 * check the format of the file
                 */
                // Linklater security of upload execute file
                if (upload.canExecute()) {
                    addActionError(MgrUtil.getUserMessage("error.formatInvalid", oldName));
                    return ERROR;
                }
                if (!checkFileFormat(oldName)) {
                    return ERROR;
                }

                /*
                 * read the message to the output file
                 */
                fis = new FileInputStream(upload);
                byte[] buffer = new byte[2048];
                int len;

                /*
                 * generate the stream of file output
                 */
                fos = new FileOutputStream(strPath + oldName);

                boolean firstRun = true;
                boolean parseImageHeadError = false;
                HiveApImageInfo imgInfo = null;
                while ((len = fis.read(buffer)) > 0) {
                    if ("image".equals(fileType) && oldName.endsWith(".hm")) {
                        // the first read buffer
                        if (firstRun) {
                            String lineStr = new String(buffer, "UTF8");
                            // check script and xml format
                            imgInfo = getImageInfoHead(lineStr);
                            if (null == imgInfo) {
                                addActionError(MgrUtil.getUserMessage("error.licenseFailed.file.invalid"));
                                HmBeOsUtil.deletefile(strPath + oldName);
                                parseImageHeadError = true;
                                break;
                            }
                            firstRun = false;
                        }
                    }
                    fos.write(buffer, 0, len);
                }
                if (parseImageHeadError) {
                    return ERROR;
                }

                if ("image".equals(fileType)) {
                    if (!generateImageFileInfo(strPath, oldName, HiveApImageInfo.SOURCE_TYPE_LOCAL)) {
                        return ERROR;
                    }

                    // update image to download server
                    saveImageDS(new File(strPath + oldName));

                    // run the script in the file
                    if (oldName.endsWith(".hm")) {
                        if (!checkVersionExist(imgInfo, strPath, oldName)) {
                            return ERROR;
                        }
                    }
                } else if (FILE_TYPE_L7_SIGNATURE.equals(fileType)) {
                    // parse signature meta info
                    try {
                        new L7SignatureMng().l7SaveOne(oldName);
                        /*- for testing
                        LSevenSignatures l = new LSevenSignatures();
                        l.setFileName(oldName+(int)(Math.random()*10));
                        l.setAhVersion("1.0.0."+(int)(Math.random()*10));
                        l.setDateReleased("01022013");
                        l.setOwner(BoMgmt.getDomainMgmt().getHomeDomain());
                        l.setPackageType((short)((Math.random()*2)+1));
                        l.setPlatformId((short)((Math.random()*4)+1));
                        l.setVendorVersion((int)(Math.random()*10) + ".2.2.2");
                        QueryUtil.createBo(l);*/
                    } catch (Exception e) {
                        //remove file from disk
                        HmBeOsUtil.deletefile(strPath + oldName);
                        throw e;
                    }
                }
            } else {
                addActionError(MgrUtil.getUserMessage("error.fileNotExist"));
                return ERROR;
            }

            /*
             * upload the file from remote server
             */
        } else if ("remote".equals(selectType)) {
            File oldFile = new File(filePath);
            oldName = oldFile.getName();

            /*
             * check the format of the file
             */
            // Linklater security of upload execute file
            if (oldFile.canExecute()) {
                addActionError(MgrUtil.getUserMessage("error.formatInvalid", oldName));
                return ERROR;
            }
            if (!checkFileFormat(oldName)) {
                return ERROR;
            }

            // get the file by scp
            fileTranser = new AhScpMgmtImpl(ipAddress, Integer.valueOf(port), scpUser, scpPass);
            fileTranser.scpGet(filePath, strPath);

            if (!generateImageFileInfo(strPath, oldName, HiveApImageInfo.SOURCE_TYPE_SCP)) {
                return ERROR;
            }

            if ("image".equals(fileType) && oldName.endsWith(".hm")) {
                fis = new FileInputStream(strPath + oldName);
                byte[] buffer = new byte[2048];
                boolean firstRun = true;
                boolean parseImageHeadError = false;
                HiveApImageInfo imgInfo = null;
                while (fis.read(buffer) > 0 && firstRun) {
                    // the first read buffer
                    String lineStr = new String(buffer, "UTF8");
                    // check the script and xml format
                    imgInfo = getImageInfoHead(lineStr);
                    if (null == imgInfo) {
                        addActionError(MgrUtil.getUserMessage("error.licenseFailed.file.invalid"));
                        HmBeOsUtil.deletefile(strPath + oldName);
                        parseImageHeadError = true;
                        break;
                    }
                    firstRun = false;
                }
                if (parseImageHeadError) {
                    return ERROR;
                }

                saveImageDS(new File(strPath + oldName));
                // run the script in the file
                if (!checkVersionExist(imgInfo, strPath, oldName)) {
                    return ERROR;
                }
            }
            /*
             * download from license server
             */
        } else {
            //            Map<String, Integer> hardwareList = getHardwareList();
            //            if (null == hardwareList || downloadInfo.size() > 0) {
            //               addActionMessage(MgrUtil.getUserMessage("license.server.available.software.update.hiveos"));
            //               return ERROR;
            //            }
            //            downloadInfo = DownloadManager.downloadHiveApSoftware(hardwareList);
            //            if (downloadInfo.size() == 0) {
            //               addActionMessage(MgrUtil.getUserMessage("license.server.available.software.update.hiveos"));
            //               return ERROR;
            //            }
            //            for (DownloadImageInfo image : downloadInfo) {
            //               oldName += image.getImageName()+" ";
            //            }
            //            oldName = oldName.substring(0, oldName.length()-1);
            //            while (DownloadManager.getHiveOSDownloadList().size() > 0) {
            //               Thread.sleep(1000);
            //            }
            AhAppContainer.getBeConfigModule().getImageSynupLS().downloadImageManual();
        }
        if ("license".equals(selectType)) {
            addActionMessage(MgrUtil.getUserMessage("info.ls.fileUploaded"));
        } else {
            addActionMessage(MgrUtil.getUserMessage("info.fileUploaded", oldName));
        }
        generateAuditLog(HmAuditLog.STATUS_SUCCESS, result + " (" + oldName + ")");
        return SUCCESS;
    } catch (HmException e) {
        AhAppContainer.HmBe.setSystemLog(HmSystemLog.LEVEL_MAJOR, HmSystemLog.FEATURE_HIVEAPS,
                result + " : " + MgrUtil.getUserMessage(e));
        addActionError(MgrUtil.getUserMessage(e));
        generateAuditLog(HmAuditLog.STATUS_FAILURE, result + " (" + oldName + ")");
        return ERROR;
    } catch (Exception e) {
        AhAppContainer.HmBe.setSystemLog(HmSystemLog.LEVEL_MAJOR, HmSystemLog.FEATURE_HIVEAPS,
                result + " : " + e.getMessage());
        addActionError(MgrUtil.getUserMessage("error.file.upload.fail", oldName));
        generateAuditLog(HmAuditLog.STATUS_FAILURE, result + " (" + oldName + ")");
        return ERROR;
    } finally {
        if (fileTranser != null) {
            fileTranser.close();
        }
        if (null != fos) {
            IOUtils.closeQuietly(fos);
        }
        if (null != fis) {
            IOUtils.closeQuietly(fis);
        }
    }
}

From source file:org.apache.nifi.minifi.bootstrap.RunMiNiFi.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public Tuple<ProcessBuilder, Process> startMiNiFi() throws IOException, InterruptedException {
    final Integer port = getCurrentPort(cmdLogger);
    if (port != null) {
        cmdLogger.info("Apache MiNiFi is already running, listening to Bootstrap on port " + port);
        return null;
    }/*from  w  w  w. j  av  a 2s  . c  om*/

    final File prevLockFile = getLockFile(cmdLogger);
    if (prevLockFile.exists() && !prevLockFile.delete()) {
        cmdLogger.warn("Failed to delete previous lock file {}; this file should be cleaned up manually",
                prevLockFile);
    }

    final ProcessBuilder builder = new ProcessBuilder();

    final Map<String, String> props = readProperties();

    final String specifiedWorkingDir = props.get("working.dir");
    if (specifiedWorkingDir != null) {
        builder.directory(new File(specifiedWorkingDir));
    }

    final File bootstrapConfigAbsoluteFile = bootstrapConfigFile.getAbsoluteFile();
    final File binDir = bootstrapConfigAbsoluteFile.getParentFile();
    final File workingDir = binDir.getParentFile();

    if (specifiedWorkingDir == null) {
        builder.directory(workingDir);
    }

    final String minifiLogDir = replaceNull(
            System.getProperty("org.apache.nifi.minifi.bootstrap.config.log.dir"), DEFAULT_LOG_DIR).trim();

    final String libFilename = replaceNull(props.get("lib.dir"), "./lib").trim();
    File libDir = getFile(libFilename, workingDir);

    final String confFilename = replaceNull(props.get(CONF_DIR_KEY), "./conf").trim();
    File confDir = getFile(confFilename, workingDir);

    String minifiPropsFilename = props.get("props.file");
    if (minifiPropsFilename == null) {
        if (confDir.exists()) {
            minifiPropsFilename = new File(confDir, "nifi.properties").getAbsolutePath();
        } else {
            minifiPropsFilename = DEFAULT_CONFIG_FILE;
        }
    }

    minifiPropsFilename = minifiPropsFilename.trim();

    final List<String> javaAdditionalArgs = new ArrayList<>();
    for (final Entry<String, String> entry : props.entrySet()) {
        final String key = entry.getKey();
        final String value = entry.getValue();

        if (key.startsWith("java.arg")) {
            javaAdditionalArgs.add(value);
        }
    }

    final File[] libFiles = libDir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(final File dir, final String filename) {
            return filename.toLowerCase().endsWith(".jar");
        }
    });

    if (libFiles == null || libFiles.length == 0) {
        throw new RuntimeException("Could not find lib directory at " + libDir.getAbsolutePath());
    }

    final File[] confFiles = confDir.listFiles();
    if (confFiles == null || confFiles.length == 0) {
        throw new RuntimeException("Could not find conf directory at " + confDir.getAbsolutePath());
    }

    final List<String> cpFiles = new ArrayList<>(confFiles.length + libFiles.length);
    cpFiles.add(confDir.getAbsolutePath());
    for (final File file : libFiles) {
        cpFiles.add(file.getAbsolutePath());
    }

    final StringBuilder classPathBuilder = new StringBuilder();
    for (int i = 0; i < cpFiles.size(); i++) {
        final String filename = cpFiles.get(i);
        classPathBuilder.append(filename);
        if (i < cpFiles.size() - 1) {
            classPathBuilder.append(File.pathSeparatorChar);
        }
    }

    final String classPath = classPathBuilder.toString();
    String javaCmd = props.get("java");
    if (javaCmd == null) {
        javaCmd = DEFAULT_JAVA_CMD;
    }
    if (javaCmd.equals(DEFAULT_JAVA_CMD)) {
        String javaHome = System.getenv("JAVA_HOME");
        if (javaHome != null) {
            String fileExtension = isWindows() ? ".exe" : "";
            File javaFile = new File(
                    javaHome + File.separatorChar + "bin" + File.separatorChar + "java" + fileExtension);
            if (javaFile.exists() && javaFile.canExecute()) {
                javaCmd = javaFile.getAbsolutePath();
            }
        }
    }

    final MiNiFiListener listener = new MiNiFiListener();
    final int listenPort = listener.start(this);

    final List<String> cmd = new ArrayList<>();

    cmd.add(javaCmd);
    cmd.add("-classpath");
    cmd.add(classPath);
    cmd.addAll(javaAdditionalArgs);
    cmd.add("-Dnifi.properties.file.path=" + minifiPropsFilename);
    cmd.add("-Dnifi.bootstrap.listen.port=" + listenPort);
    cmd.add("-Dapp=MiNiFi");
    cmd.add("-Dorg.apache.nifi.minifi.bootstrap.config.log.dir=" + minifiLogDir);
    cmd.add("org.apache.nifi.minifi.MiNiFi");

    builder.command(cmd);

    final StringBuilder cmdBuilder = new StringBuilder();
    for (final String s : cmd) {
        cmdBuilder.append(s).append(" ");
    }

    cmdLogger.info("Starting Apache MiNiFi...");
    cmdLogger.info("Working Directory: {}", workingDir.getAbsolutePath());
    cmdLogger.info("Command: {}", cmdBuilder.toString());

    Process process = builder.start();
    handleLogging(process);
    Long pid = getPid(process, cmdLogger);
    if (pid != null) {
        minifiPid = pid;
        final Properties minifiProps = new Properties();
        minifiProps.setProperty(PID_KEY, String.valueOf(minifiPid));
        saveProperties(minifiProps, cmdLogger);
    }

    gracefulShutdownSeconds = getGracefulShutdownSeconds(props, bootstrapConfigAbsoluteFile);
    shutdownHook = new ShutdownHook(process, this, secretKey, gracefulShutdownSeconds, loggingExecutor);
    final Runtime runtime = Runtime.getRuntime();
    runtime.addShutdownHook(shutdownHook);

    return new Tuple<ProcessBuilder, Process>(builder, process);
}

From source file:org.apache.hadoop.hdfs.MiniDFSCluster.java

/**
 * @return a debug string which can help diagnose an error of why
 * a given directory might have a permissions error in the context
 * of a test case/*from  w w w .j  a v a2 s  .c om*/
 */
private String createPermissionsDiagnosisString(File path) {
    StringBuilder sb = new StringBuilder();
    while (path != null) {
        sb.append("path '" + path + "': ").append("\n");
        sb.append("\tabsolute:").append(path.getAbsolutePath()).append("\n");
        sb.append("\tpermissions: ");
        sb.append(path.isDirectory() ? "d" : "-");
        sb.append(path.canRead() ? "r" : "-");
        sb.append(path.canWrite() ? "w" : "-");
        sb.append(path.canExecute() ? "x" : "-");
        sb.append("\n");
        path = path.getParentFile();
    }
    return sb.toString();
}

From source file:org.computeforcancer.android.client.Monitor.java

/**
 * Copies given file from APK assets to internal storage.
 * @param file name of file as it appears in assets directory
 * @param override define override, if already present in internal storage
 * @param executable set executable flag of file in internal storage
 * @return Boolean success//w  ww .  j a v a2  s  .c om
 */
private Boolean installFile(String file, Boolean override, Boolean executable) {
    Boolean success = false;
    byte[] b = new byte[1024];
    int count;

    // If file is executable, cpu architecture has to be evaluated
    // and assets directory select accordingly
    String source = "";
    if (executable)
        source = getAssestsDirForCpuArchitecture() + file;
    else
        source = file;

    try {
        if (Logging.ERROR)
            Log.d(Logging.TAG, "installing: " + source);

        File target = new File(boincWorkingDir + file);

        // Check path and create it
        File installDir = new File(boincWorkingDir);
        if (!installDir.exists()) {
            installDir.mkdir();
            installDir.setWritable(true);
        }

        if (target.exists()) {
            if (override)
                target.delete();
            else {
                if (Logging.DEBUG)
                    Log.d(Logging.TAG, "skipped file, exists and ovverride is false");
                return true;
            }
        }

        // Copy file from the asset manager to clientPath
        InputStream asset = getApplicationContext().getAssets().open(source);
        OutputStream targetData = new FileOutputStream(target);
        while ((count = asset.read(b)) != -1) {
            targetData.write(b, 0, count);
        }
        asset.close();
        targetData.flush();
        targetData.close();

        success = true; //copy succeeded without exception

        // Set executable, if requested
        Boolean isExecutable = false;
        if (executable) {
            target.setExecutable(executable);
            isExecutable = target.canExecute();
            success = isExecutable; // return false, if not executable
        }

        if (Logging.ERROR)
            Log.d(Logging.TAG,
                    "install of " + source + " successfull. executable: " + executable + "/" + isExecutable);

    } catch (IOException e) {
        if (Logging.ERROR)
            Log.e(Logging.TAG, "IOException: " + e.getMessage());
        if (Logging.ERROR)
            Log.d(Logging.TAG, "install of " + source + " failed.");
    }

    return success;
}

From source file:com.filemanager.free.activities.MainActivity.java

@SuppressLint("SdCardPath")
public File getUsbDrive() {
    File parent;/* ww  w  .  j av a2  s  .  co  m*/
    parent = new File("/storage");

    try {
        for (File f : parent.listFiles()) {
            if (f.exists() && f.getName().toLowerCase().contains("usb") && f.canExecute()) {
                return f;
            }
        }
    } catch (Exception ignored) {
    }
    parent = new File("/mnt/sdcard/usbStorage");
    if (parent.exists() && parent.canExecute())
        return (parent);
    parent = new File("/mnt/sdcard/usb_storage");
    if (parent.exists() && parent.canExecute())
        return parent;

    return null;
}

From source file:com.amaze.filemanager.activities.MainActivity.java

public File getUsbDrive() {
    File parent;/* w  ww. j a va 2 s. co m*/
    parent = new File("/storage");

    try {
        for (File f : parent.listFiles()) {
            if (f.exists() && f.getName().toLowerCase().contains("usb") && f.canExecute()) {
                return f;
            }
        }
    } catch (Exception e) {
    }
    parent = new File("/mnt/sdcard/usbStorage");
    if (parent.exists() && parent.canExecute())
        return (parent);
    parent = new File("/mnt/sdcard/usb_storage");
    if (parent.exists() && parent.canExecute())
        return parent;

    return null;
}

From source file:edu.stolaf.cs.wmrserver.TransformProcessor.java

private File compile(SubnodeConfiguration languageConf, String transformTypeString, File srcTransformFile,
        File jobTransformDir) throws CompilationException, IOException {
    // Determine correct compiler, returning if none specified
    String compiler = languageConf.getString("compiler-" + transformTypeString, "");
    if (compiler.isEmpty())
        compiler = languageConf.getString("compiler", "");
    if (compiler.isEmpty())
        return srcTransformFile;

    // Determine destination filename
    File compiledTransformFile = new File(jobTransformDir, "compiled-job-" + transformTypeString);

    // Create map to replace ${wmr:...} variables.
    // NOTE: Commons Configuration's built-in interpolator does not work here
    //  for some reason.
    File jobTempDir = getJobTempDir();
    Hashtable<String, String> variableMap = new Hashtable<String, String>();
    File libDir = getLibraryDirectory(languageConf);
    variableMap.put("wmr:lib.dir", (libDir != null) ? libDir.toString() : "");
    variableMap.put("wmr:src.dir", relativizeFile(srcTransformFile.getParentFile(), jobTempDir).toString());
    variableMap.put("wmr:src.file", relativizeFile(srcTransformFile, jobTempDir).toString());
    variableMap.put("wmr:dest.dir", relativizeFile(jobTransformDir, jobTempDir).toString());
    variableMap.put("wmr:dest.file", relativizeFile(compiledTransformFile, jobTempDir).toString());

    // Replace variables in compiler string
    compiler = StrSubstitutor.replace(compiler, variableMap);

    // Run the compiler

    CommandLine compilerCommand = CommandLine.parse(compiler);
    DefaultExecutor exec = new DefaultExecutor();
    ExecuteWatchdog dog = new ExecuteWatchdog(60000); // 1 minute
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler pump = new PumpStreamHandler(output);
    exec.setWorkingDirectory(jobTempDir);
    exec.setWatchdog(dog);//w w  w . ja  v  a  2  s.  c  om
    exec.setStreamHandler(pump);
    exec.setExitValues(null); // Can't get the exit code if it throws exception

    int exitStatus = -1;
    try {
        exitStatus = exec.execute(compilerCommand);
    } catch (IOException ex) {
        // NOTE: Exit status is still -1 in this case, since exception was thrown
        throw new CompilationException("Compiling failed for " + transformTypeString, exitStatus,
                new String(output.toByteArray()));
    }

    // Check for successful exit

    if (exitStatus != 0)
        throw new CompilationException("Compiling failed for " + transformTypeString, exitStatus,
                new String(output.toByteArray()));

    // Check that output exists and is readable, and make it executable

    if (!compiledTransformFile.isFile())
        throw new CompilationException(
                "Compiler did not output a " + transformTypeString
                        + " executable (or it was not a regular file).",
                exitStatus, new String(output.toByteArray()));

    if (!compiledTransformFile.canRead())
        throw new IOException(StringUtils.capitalize(transformTypeString)
                + " executable output from compiler was not readable: " + compiledTransformFile.toString());

    if (!compiledTransformFile.canExecute())
        compiledTransformFile.setExecutable(true, false);

    return compiledTransformFile;
}

From source file:de.unibi.techfak.bibiserv.BiBiTools.java

/**
 * Generate a cmdline string according to execinfo and
 * paramANDInputOutputOrder description with switch for check if executable
 * exists or not. Should only used for test purpose!
 *
 * See getExecCmd to optain the strategy about the executable path to
 * generation.// w w  w  .  java2 s. c o  m
 *
 * @param id - function id
 * @param paramhash - a hash containing the parameter/ id as key and "real"
 * cmdline as value
 * @param prefix - string that would put at the front the generated string
 * @param postfix - String that would put at the end of the generated string
 * @param testexec - Check if executable is available and can be executed
 * @return string representation of the cmdline call
 */
public String generateCmdLineString(String id, Map<String, String> hash, String prefix, String postfix,
        boolean testexec) throws BiBiToolsException, DBConnectionException, IdNotFoundException {
    Tfunction function = search_for_function(id);

    if (function == null) {
        status.setStatuscode(701, "Did not found any function matching id = '" + id + "!");
        log.error(status);
        throw new BiBiToolsException(status.toString());
    }

    StringBuffer cmdline = new StringBuffer(getExecCmd());

    // test if cmdline describe a valid executable (only if 'UseDocker' is unset)
    if (!getToolDescription().getExecutable().getExecInfo().getExecutableType().equalsIgnoreCase("docker")) {

        File test = new File(cmdline.toString());
        if (testexec && !(test.exists() && test.isFile() && test.canExecute())) {
            status.setStatuscode(720, "Internal Server Error (Executable)",
                    "Executable '" + cmdline + "' does not exists or is not executable!");
            log.fatal(status.toString());
            throw new BiBiToolsException(status);
        }
    }

    String DELIMITER = " ";

    /* iterate over every  paramAndInputOutputOrder list */
    for (JAXBElement<?> e : function.getParamAndInputOutputOrder().getReferenceOrAdditionalString()) {

        if (e.getValue() instanceof Tparam) {
            String key = ((Tparam) e.getValue()).getId();
            if (hash.containsKey(key)) {
                cmdline.append(DELIMITER).append(hash.get(key));
            }
        } else if (e.getValue() instanceof TenumParam) {
            String key = ((TenumParam) e.getValue()).getId();
            if (hash.containsKey(key)) {
                cmdline.append(DELIMITER).append(hash.get(key));
            }
        } else if (e.getValue() instanceof TinputOutput) {
            String key = ((TinputOutput) e.getValue()).getId();
            if (hash.containsKey(key)) {
                // must be an input type
                cmdline.append(DELIMITER).append(hash.get(key));
            } else {
                //can be an output type
                TinputOutput output = (TinputOutput) function.getOutputref().getRef();
                if (output.getId().equals(key)) {
                    // use getOutputFile function to get an outputfilename
                    cmdline.append(DELIMITER).append((output.isSetOption() ? output.getOption() : ""));
                    if (output.getHandling().equalsIgnoreCase("STDOUT")) {
                        postfix = postfix + DELIMITER + ">" + getOutputFile(id, true);
                    } else {
                        cmdline.append(
                                (getOutputFile(id, true) == null ? "" : getOutputFile(id, true).toString()));
                    }
                }
            }
        } else if (e.getValue() instanceof String) {
            cmdline.append(DELIMITER).append((String) e.getValue());
        } else {
            status.setStatuscode(701, "Unsupported type '" + e.getValue().getClass().getName()
                    + "' in list of paramAndInputOutputOrder.");
            throw new BiBiToolsException(status.toString()); //@TODO : search for a better error code
        }
    }
    return prefix + DELIMITER + cmdline.toString() + DELIMITER + postfix;
}

From source file:com.amaze.carbonfilemanager.activities.MainActivity.java

public File getUsbDrive() {
    File parent = new File("/storage");

    try {/*  w  w w .  j  av  a  2  s  . co m*/
        for (File f : parent.listFiles())
            if (f.exists() && f.getName().toLowerCase().contains("usb") && f.canExecute())
                return f;
    } catch (Exception e) {
    }

    parent = new File("/mnt/sdcard/usbStorage");
    if (parent.exists() && parent.canExecute())
        return (parent);
    parent = new File("/mnt/sdcard/usb_storage");
    if (parent.exists() && parent.canExecute())
        return parent;

    return null;
}