Example usage for java.io File setExecutable

List of usage examples for java.io File setExecutable

Introduction

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

Prototype

public boolean setExecutable(boolean executable) 

Source Link

Document

A convenience method to set the owner's execute permission for this abstract pathname.

Usage

From source file:org.tinymediamanager.TmmOsUtils.java

/**
 * create a .desktop file for linux and unix (not osx)
 * //from   w  ww .  j  a v  a  2 s  . c  o  m
 * @param desktop
 *          .desktop file
 */
public static void createDesktopFileForLinux(File desktop) {
    if (SystemUtils.IS_OS_WINDOWS || SystemUtils.IS_OS_MAC) {
        return;
    }

    // get the path in a safe way
    String path = new File(TinyMediaManager.class.getProtectionDomain().getCodeSource().getLocation().getPath())
            .getParent();
    try {
        path = URLDecoder.decode(path, "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        path = URLDecoder.decode(path);
    }
    StringBuilder sb = new StringBuilder(60);
    sb.append("[Desktop Entry]\n");
    sb.append("Type=Application\n");
    sb.append("Name=tinyMediaManager\n");
    sb.append("Path=");
    sb.append(path);
    sb.append('\n');
    sb.append("Exec=/bin/sh \"");
    sb.append(path);
    sb.append("/tinyMediaManager.sh\"\n");
    sb.append("Icon=");
    sb.append(path);
    sb.append("/tmm.png\n");
    sb.append("Categories=AudioVideo;Video;Database;Java;");
    sb.append("\n");
    FileWriterWithEncoding writer;
    try {
        writer = new FileWriterWithEncoding(desktop, "UTF-8");
        writer.write(sb.toString());
        writer.close();
        desktop.setExecutable(true);
    } catch (IOException e) {
        LOGGER.warn(e.getMessage());
    }
}

From source file:org.nanoko.playframework.mojo.Play2InstallPlayMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (StringUtils.isEmpty(play2version)) {
        throw new MojoExecutionException("play2version configuration parameter is not set");
    }/*from   w  w  w.  ja v  a  2  s  .co m*/
    String debugLogPrefix = "AutoInstall - Play! " + play2version + ' ';
    File play2basedirFile = new File(play2basedir);
    File play2home = new File(play2basedirFile, "play-" + play2version);
    File play2 = new File(play2home, AbstractPlay2Mojo.isWindows() ? "play.bat" : "play");

    // Is the requested Play! version already installed?
    if (play2.isFile() && play2.canExecute()) {

        getLog().info(debugLogPrefix + "is already installed in " + play2home);
        return;

    }

    getLog().info("Play! " + play2version + " download and installation, please be patient ...");
    File zipFile = new File(play2basedirFile, "play-" + play2version + ".zip");

    try {

        // New download URL pattern starting from 2.1.0, the 2.1-RC* versions use the old URL pattern.
        // See https://groups.google.com/forum/#!topic/play-framework/SKOXG1YRKa8
        URL zipUrl;
        if (play2version.startsWith("2.0") || play2version.startsWith("2.1-RC")) {
            zipUrl = new URL("http://downloads.typesafe.com/releases/play-" + play2version + ".zip");
        } else {
            zipUrl = new URL(
                    "http://downloads.typesafe.com/play/" + play2version + "/play-" + play2version + ".zip");
        }
        FileUtils.forceMkdir(play2basedirFile);

        // Download
        getLog().debug(debugLogPrefix + "is downloading to " + zipFile);
        FileUtils.copyURLToFile(zipUrl, zipFile);

        // Extract
        getLog().debug(debugLogPrefix + "is extracting to " + play2basedir);
        UnArchiver unarchiver = archiverManager.getUnArchiver(zipFile);
        unarchiver.setSourceFile(zipFile);
        unarchiver.setDestDirectory(play2basedirFile);
        unarchiver.extract();

        // Prepare
        File framework = new File(play2home, "framework");
        File build = new File(framework, AbstractPlay2Mojo.isWindows() ? "build.bat" : "build");
        if (!build.canExecute() && !build.setExecutable(true)) {
            throw new MojoExecutionException("Can't set " + build + " execution bit");
        }
        if (!play2.canExecute() && !play2.setExecutable(true)) {
            throw new MojoExecutionException("Can't set " + play2 + " execution bit");
        }

        getLog().debug(debugLogPrefix + "is now installed in " + play2home);

    } catch (NoSuchArchiverException ex) {
        throw new MojoExecutionException("Can't auto install Play! " + play2version + " in " + play2basedir,
                ex);
    } catch (IOException ex) {
        try {
            if (play2home.exists()) {
                // Clean extracted data
                FileUtils.forceDelete(play2home);
            }
        } catch (IOException ignored) {
            getLog().warn("Unable to delete extracted Play! distribution after error: " + play2home);
        }
        throw new MojoExecutionException("Can't auto install Play! " + play2version + " in " + play2basedir,
                ex);
    } catch (ArchiverException e) {
        throw new MojoExecutionException("Cannot unzip Play " + play2version + " in " + play2basedir, e);
    } finally {
        try {
            if (zipFile.exists()) {
                // Clean downloaded data
                FileUtils.forceDelete(zipFile);
            }
        } catch (IOException ignored) {
            getLog().warn("Unable to delete downloaded Play! distribution: " + zipFile);
        }
    }
}

From source file:com.intel.cryptostream.utils.NativeCodeLoader.java

/**
 * Extract the specified library file to the target folder
 * //from w  w w .j  a  v  a2  s .c  om
 * @param libFolderForCurrentOS
 * @param libraryFileName
 * @param targetFolder
 * @return
 */
private static File extractLibraryFile(String libFolderForCurrentOS, String libraryFileName,
        String targetFolder) {
    String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;

    // Attach UUID to the native library file to ensure multiple class loaders
    // can read the libcryptostream multiple times.
    String uuid = UUID.randomUUID().toString();
    String extractedLibFileName = String.format("cryptostream-%s-%s-%s", getVersion(), uuid, libraryFileName);
    File extractedLibFile = new File(targetFolder, extractedLibFileName);

    try {
        // Extract a native library file into the target directory
        InputStream reader = NativeCodeLoader.class.getResourceAsStream(nativeLibraryFilePath);
        FileOutputStream writer = new FileOutputStream(extractedLibFile);
        try {
            byte[] buffer = new byte[8192];
            int bytesRead = 0;
            while ((bytesRead = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, bytesRead);
            }
        } finally {
            // Delete the extracted lib file on JVM exit.
            extractedLibFile.deleteOnExit();

            if (writer != null)
                writer.close();
            if (reader != null)
                reader.close();
        }

        // Set executable (x) flag to enable Java to load the native library
        extractedLibFile.setReadable(true);
        extractedLibFile.setWritable(true, true);
        extractedLibFile.setExecutable(true);

        // Check whether the contents are properly copied from the resource folder
        {
            InputStream nativeIn = NativeCodeLoader.class.getResourceAsStream(nativeLibraryFilePath);
            InputStream extractedLibIn = new FileInputStream(extractedLibFile);
            try {
                if (!contentsEquals(nativeIn, extractedLibIn))
                    throw new RuntimeException(
                            String.format("Failed to write a native library file at %s", extractedLibFile));
            } finally {
                if (nativeIn != null)
                    nativeIn.close();
                if (extractedLibIn != null)
                    extractedLibIn.close();
            }
        }

        return new File(targetFolder, extractedLibFileName);
    } catch (IOException e) {
        e.printStackTrace(System.err);
        return null;
    }
}

From source file:de.tudarmstadt.ukp.csniper.webapp.search.tgrep.TgrepQuery.java

@Override
public List<EvaluationItem> execute() {
    BufferedReader brInput = null;
    BufferedReader brError = null;
    List<String> output = new ArrayList<String>();
    List<String> error = new ArrayList<String>();

    try {/*from w  w w .  j a  v a  2 s .com*/
        List<String> cmd = new ArrayList<String>();

        File exe = engine.getTgrepExecutable();
        if (!exe.canExecute()) {
            exe.setExecutable(true);
        }

        cmd.add(exe.getAbsolutePath());
        // specify corpus
        cmd.add("-c");
        cmd.add(engine.getCorpusPath(corpus));
        // only one match per sentence
        cmd.add("-f");
        // print options
        cmd.add("-m");
        // comment
        // full sentence
        // match begin token index
        // match end token index
        cmd.add("%c\\n%tw\\n%ym\\n%zm\\n");
        // pattern to search for
        cmd.add(query);
        if (log.isTraceEnabled()) {
            log.trace("Invoking [" + StringUtils.join(cmd, " ") + "]");
        }

        final ProcessBuilder pb = new ProcessBuilder(cmd);
        tgrep = pb.start();

        brInput = new BufferedReader(new InputStreamReader(tgrep.getInputStream(), "UTF-8"));
        brError = new BufferedReader(new InputStreamReader(tgrep.getErrorStream(), "UTF-8"));

        String line;
        while ((line = brInput.readLine()) != null) {
            if (log.isTraceEnabled()) {
                log.trace("<< " + line);
            }
            output.add(line);
        }

        while ((line = brError.readLine()) != null) {
            if (log.isErrorEnabled()) {
                log.error(line);
            }
            error.add(line);
        }

        if (!error.isEmpty()) {
            throw new IOException(StringUtils.join(error, " "));
        }
    } catch (IOException e) {
        throw new DataAccessResourceFailureException("Unable to start Tgrep process.", e);
    } finally {
        IOUtils.closeQuietly(brInput);
        IOUtils.closeQuietly(brError);
    }

    size = output.size() / LINES_PER_MATCH;
    if (maxResults >= 0 && size > maxResults) {
        return parseOutput(output.subList(0, LINES_PER_MATCH * maxResults));
    } else {
        return parseOutput(output);
    }
}

From source file:com.yahoo.parsec.gradle.utils.FileUtils.java

/**
 * Write resource as executable./*from w  w w. j  ava  2 s  .  c o m*/
 *
 * @param inputStream input stream
 * @param outputFile  output file
 * @throws IOException IOException
 */
public void writeResourceAsExecutable(InputStream inputStream, String outputFile) throws IOException {
    writeResourceToFile(inputStream, outputFile, true);
    File file = new File(outputFile);
    file.setExecutable(true);
}

From source file:abs.backend.erlang.ErlangTestDriver.java

/**
* Executes mainModule//from   w w w . j  av a2s  .c  o  m
* 
* We replace the run script by a new version, which will write the Result
* to STDOUT Furthermore to detect faults, we have a Timeout process, which
* will kill the runtime system after 2 seconds
*/
private String run(File workDir, String mainModule) throws Exception {
    String val = null;
    File runFile = new File(workDir, "run");
    Files.write(RUN_SCRIPT, runFile, Charset.forName("UTF-8"));
    runFile.setExecutable(true);
    ProcessBuilder pb = new ProcessBuilder(runFile.getAbsolutePath(), mainModule);
    pb.directory(workDir);
    pb.redirectErrorStream(true);
    Process p = pb.start();

    Thread t = new Thread(new TimeoutThread(p));
    t.start();
    // Search for result
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    while (true) {
        String line = br.readLine();
        if (line == null)
            break;
        if (line.startsWith("RES="))
            val = line.split("=")[1];
    }
    int res = p.waitFor();
    t.interrupt();
    if (res != 0)
        return null;
    return val;

}

From source file:io.wcm.maven.plugins.nodejs.installation.TarUnArchiver.java

/**
 * Unarchives the arvive into the pBaseDir
 * @param baseDir//w ww  .  j a  v a2s .  c  o m
 * @throws MojoExecutionException
 */
public void unarchive(String baseDir) throws MojoExecutionException {
    try {
        FileInputStream fis = new FileInputStream(archive);

        // TarArchiveInputStream can be constructed with a normal FileInputStream if
        // we ever need to extract regular '.tar' files.
        final TarArchiveInputStream tarIn = new TarArchiveInputStream(new GzipCompressorInputStream(fis));

        TarArchiveEntry tarEntry = tarIn.getNextTarEntry();
        while (tarEntry != null) {
            // Create a file for this tarEntry
            final File destPath = new File(baseDir + File.separator + tarEntry.getName());
            if (tarEntry.isDirectory()) {
                destPath.mkdirs();
            } else {
                destPath.createNewFile();
                destPath.setExecutable(true);
                //byte [] btoRead = new byte[(int)tarEntry.getSize()];
                byte[] btoRead = new byte[8024];
                final BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath));
                int len = 0;

                while ((len = tarIn.read(btoRead)) != -1) {
                    bout.write(btoRead, 0, len);
                }

                bout.close();
            }
            tarEntry = tarIn.getNextTarEntry();
        }
        tarIn.close();
    } catch (IOException e) {
        throw new MojoExecutionException("Could not extract archive: '" + archive.getAbsolutePath() + "'", e);
    }

}

From source file:io.schultz.dustin.runner.VideoDownloaderLatestRunner.java

@Override
public void run(final ApplicationArguments args) throws Exception {
    final String filename = downloaderProperties.getDownloaderFilename();
    final File fileAbsolute = new File(downloaderProperties.getRootDir(), filename);

    log.info("Downloading latest video downloader to {}", downloaderProperties.getRootDir());
    try {/*www.j  a v  a  2 s  .  c om*/
        FileUtils.copyURLToFile(new URL(downloaderProperties.getLatestUrl(), filename), fileAbsolute);
        fileAbsolute.setExecutable(true);
    } catch (IOException e) {
        log.error("Unable to download latest video downloader", e);
    }
    log.info("Finished downloading latest video downloader");
}

From source file:eu.excitementproject.eop.distsim.redisinjar.EmbeddedRedisServerRunner.java

private File extractExecutableFromJar(String scriptName) throws IOException {
    File tmpDir = Files.createTempDir();
    tmpDir.deleteOnExit();//from  w w w.  j a  v a 2  s .co  m

    File command = new File(tmpDir, scriptName);
    FileUtils.copyURLToFile(Resources.getResource(scriptName), command);
    command.deleteOnExit();
    command.setExecutable(true);

    return command;
}

From source file:io.covert.binary.analysis.BinaryAnalysisMapper.java

protected void setup(Context context) throws java.io.IOException, InterruptedException {
    Configuration conf = context.getConfiguration();
    try {/*w ww  .j  av  a2s .  c  om*/
        parser = (OutputParser<K, V>) Class.forName(conf.get("binary.analysis.output.parser")).newInstance();
    } catch (Exception e) {
        throw new IOException("Could create parser", e);
    }

    fileExtention = conf.get("binary.analysis.file.extention", ".dat");
    timeoutMS = conf.getLong("binary.analysis.execution.timeoutMS", Long.MAX_VALUE);
    program = conf.get("binary.analysis.program");
    args = conf.get("binary.analysis.program.args").split(conf.get("binary.analysis.program.args.delim", ","));
    String[] codes = conf.get("binary.analysis.program.exit.codes").split(",");
    exitCodes = new int[codes.length];
    for (int i = 0; i < codes.length; ++i) {
        exitCodes[i] = Integer.parseInt(codes[i]);
    }

    workingDir = new File(".").getAbsoluteFile();
    dataDir = new File(workingDir, "_data");
    dataDir.mkdir();
    logDirContents(workingDir);

    File programFile = new File(workingDir, program);
    if (programFile.exists()) {
        LOG.info("Program file exists in working directory, ensuring executable and readable");
        programFile.setExecutable(true);
        programFile.setReadable(true);
    }
}