Java Code Examples for java.io.File.setExecutable()

The following are Jave code examples for showing how to use setExecutable() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: react-native-node   File: RNNodeService.java   View Source Code Vote up 6 votes
public void prepareNode(Context context, String dataDir) {
    InputStream nodeBinary = null;
    try {
        nodeBinary = context.getResources().openRawResource(R.raw.bin_node_v710);
        String nodeFilename = String.format("%s/node", dataDir);
        File nodeFile = new File(nodeFilename);
        if (nodeFile.exists()) {
            return;
        }
        nodeFile.createNewFile();
        InputStreamReader reader = new InputStreamReader(nodeBinary);
        FileOutputStream writer = new FileOutputStream(nodeFile);
        byte[] binary = new byte[(int)(nodeBinary.available())];
        nodeBinary.read(binary);
        writer.write(binary);
        writer.flush();
        writer.close();
        nodeFile.setExecutable(true, true);
        nodeBinary.close();
    } catch (Exception e) {
        Log.e(TAG, "Cannot create binary file for \"node\"");
    }
}
 
Example 2
Project: BatteryModPercentage   File: WorldReadablePrefs.java   View Source Code Vote up 6 votes
private void maybePreCreateFile() {
    try {
        File sharedPrefsFolder = new File(mContext.getDataDir().getAbsolutePath() + "/shared_prefs");
        if (!sharedPrefsFolder.exists()) {
            sharedPrefsFolder.mkdir();
            sharedPrefsFolder.setExecutable(true, false);
            sharedPrefsFolder.setReadable(true, false);
        }
        File f = new File(sharedPrefsFolder.getAbsolutePath() + "/" + mPrefsName + ".xml");
        if (!f.exists()) {
            f.createNewFile();
            f.setReadable(true, false);
        }
    } catch (Exception e) {
        Log.e("EffEnhc", "Error pre-creating prefs file " + mPrefsName + ": " + e.getMessage());
    }
}
 
Example 3
Project: alvisnlp   File: TEESClassify.java   View Source Code Vote up 6 votes
private TEESClassifyExternal(ProcessingContext<Corpus> ctx) throws IOException {
	super();
	this.ctx = ctx;
	File tmp = getTempDir(ctx);
	baseDir = tmp;
	this.input = new OutputFile(tmp.getAbsolutePath(), "tees-o" + ".xml");
	this.outputStem = "tees-i";
	
	//
	script = new File(tmp, "classify.sh");
	// same ClassLoader as this class
	try (InputStream is = TEESTrain.class.getResourceAsStream("classify.sh")) {
		Files.copy(is, script, 1024, true);
	}
	script.setExecutable(true);
}
 
Example 4
Project: alvisnlp   File: GeniaTagger.java   View Source Code Vote up 6 votes
public GeniaTaggerExternal(ProcessingContext<Corpus> ctx, Corpus corpus, File tmpDir) throws IOException {
	super();
	this.ctx = ctx;
	this.evalCtx = new EvaluationContext(getLogger(ctx));
	
	script = new File(tmpDir, "genia.sh");
	// same ClassLoader as this class
	try (InputStream is = GeniaTagger.class.getResourceAsStream("genia.sh")) {
		Files.copy(is, script, 1024, true);
	}
	script.setExecutable(true);

	GeniaTaggerResolvedObjects resObj = getResolvedObjects();
	input = new OutputFile(tmpDir, "corpus.txt");
	TargetStream target = new FileTargetStream(geniaCharset, input);
	PrintStream ps = target.getPrintStream();
	for (Annotation sent : Iterators.loop(getSentenceIterator(evalCtx, corpus, resObj.getDocumentFilter(), resObj.getSectionFilter(), resObj.sentenceFilter)))
		writeSentence(sent, ps);
	ps.close();
	
	output = new InputFile(tmpDir, "corpus.genia");
}
 
Example 5
Project: oneops   File: AbstractOrderExecutor.java   View Source Code Vote up 6 votes
/**
 * writes private key
 *
 * @param key String
 */
protected String writePrivateKey(String key) {
  String uuid = UUID.randomUUID().toString();
  String fileName = config.getDataDir() + "/" + uuid;
  try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(fileName))) {
    bw.write(key);
    bw.close();
    File f = new File(fileName);
    f.setExecutable(false, false);
    f.setReadable(false, false);
    f.setWritable(false, false);
    f.setReadable(true, true);
    f.setWritable(true, true);
    logger.debug("file: " + fileName);
  } catch (IOException e) {
    logger.error("could not write file: " + fileName + " msg:"
        + e.getMessage());
  }
  return fileName;
}
 
Example 6
Project: alvisnlp   File: TEESTrain.java   View Source Code Vote up 6 votes
private TEESTrainExternal(ProcessingContext<Corpus> ctx) throws IOException {
	super();
	this.ctx = ctx;
	File tmp = getTempDir(ctx);
	baseDir = tmp;
	this.trainInput = new OutputFile(tmp.getAbsolutePath(), "train-o" + ".xml");
	this.devInput = new OutputFile(tmp.getAbsolutePath(), "devel-o" + ".xml");
	this.testInput = new OutputFile(tmp.getAbsolutePath(), "test-o" + ".xml");
	
	script = new File(tmp, "train.sh");
	// same ClassLoader as this class
	try (InputStream is = TEESTrain.class.getResourceAsStream("train.sh")) {
		Files.copy(is, script, 1024, true);
	}
	script.setExecutable(true);
}
 
Example 7
Project: neoscada   File: Helper.java   View Source Code Vote up 6 votes
public static void createFile ( final File file, final InputStream resource, final IProgressMonitor monitor, final boolean exec ) throws Exception
{
    file.getParentFile ().mkdirs ();

    try
    {
        try ( FileOutputStream fos = new FileOutputStream ( file ) )
        {
            ByteStreams.copy ( resource, fos );
        }
        file.setExecutable ( exec );
    }
    finally
    {
        resource.close ();
    }
}
 
Example 8
Project: alvisnlp   File: Ab3P.java   View Source Code Vote up 6 votes
private Ab3PExternal(ProcessingContext<Corpus> ctx, Corpus corpus) throws IOException {
	logger = getLogger(ctx);
	File tmpDir = getTempDir(ctx);
	scriptFile = new File(tmpDir, "script.sh");
	inputFile = new File(tmpDir, "input.txt");
	outputFile = new File(tmpDir, "output.txt");
	// same ClassLoader as this class
	try (InputStream is = Ab3P.class.getResourceAsStream("script.sh")) {
		Files.copy(is, scriptFile, 1024, true);
		scriptFile.setExecutable(true);
	}
	EvaluationContext evalCtx = new EvaluationContext(logger);
	try (PrintStream ps = new PrintStream(inputFile)) {
		for (Document doc : Iterators.loop(documentIterator(evalCtx, corpus))) {
			for (Section sec : Iterators.loop(sectionIterator(evalCtx, doc))) {
				String rawContents = sec.getContents();
				String lineContents = rawContents.replace('\n', ' ').trim();
				ps.println(lineContents);
				ps.println();
			}
		}
	}
}
 
Example 9
Project: GitHub   File: EnvUtils.java   View Source Code Vote up 5 votes
/**
 * Recursive set permissions to directory
 *
 * @param path path to directory
 */
private static void setPermissions(File path) {
    if (path == null) return;
    if (path.exists()) {
        path.setReadable(true, false);
        path.setExecutable(true, false);
        File[] list = path.listFiles();
        if (list == null) return;
        for (File f : list) {
            if (f.isDirectory()) setPermissions(f);
            f.setReadable(true, false);
            f.setExecutable(true, false);
        }
    }
}
 
Example 10
Project: Accessibility   File: FileUtils.java   View Source Code Vote up 5 votes
public static boolean changeFilePermission755(final File file) {
    try {
        if (file == null || !file.exists()) {
            return false;
        }

        file.setReadable(true, false);
        file.setExecutable(true, false);
        file.setWritable(true, true);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return false;
}
 
Example 11
Project: NBANDROID-V2   File: MavenDownloader.java   View Source Code Vote up 5 votes
public static void unzip(File zipFile, File destination)
        throws IOException {
    ZipFile zip = new ZipFile(zipFile);
    try {
        Enumeration<ZipArchiveEntry> e = zip.getEntries();
        while (e.hasMoreElements()) {
            ZipArchiveEntry entry = e.nextElement();
            File file = new File(destination, entry.getName());
            if (entry.isDirectory()) {
                file.mkdirs();
            } else {
                InputStream is = zip.getInputStream(entry);
                File parent = file.getParentFile();
                if (parent != null && parent.exists() == false) {
                    parent.mkdirs();
                }
                FileOutputStream os = new FileOutputStream(file);
                try {
                    IOUtils.copy(is, os);
                } finally {
                    os.close();
                    is.close();
                }
                file.setLastModified(entry.getTime());
                int mode = entry.getUnixMode();
                if ((mode & EXEC_MASK) != 0) {
                    if (!file.setExecutable(true)) {
                    }
                }
            }
        }
    } finally {
        ZipFile.closeQuietly(zip);
    }
}
 
Example 12
Project: Xndroid   File: LaunchService.java   View Source Code Vote up 5 votes
private static void pythonInit(){
        if(FileUtils.exists(sXndroidFile + "/python/bin/python"))
            return;
        if(!unzipRawFile(R.raw.python, sXndroidFile))
            AppModel.fatalError("prepare python fail");
//        test();
        File[] files = new File(sXndroidFile + "/python/bin").listFiles();
        if(files == null){
            LogUtils.e("fail to list python/bin");
        }else {
            for (File binFile : files) {
                binFile.setExecutable(true, false);
            }
        }
    }
 
Example 13
Project: appinventor-extensions   File: Compiler.java   View Source Code Vote up 5 votes
/**
 * Writes out the given resource as a temp file and returns the absolute path.
 * Caches the location of the files, so we can reuse them.
 *
 * @param resourcePath the name of the resource
 */
static synchronized String getResource(String resourcePath) {
  try {
    File file = resources.get(resourcePath);
    if (file == null) {
      String basename = PathUtil.basename(resourcePath);
      String prefix;
      String suffix;
      int lastDot = basename.lastIndexOf(".");
      if (lastDot != -1) {
        prefix = basename.substring(0, lastDot);
        suffix = basename.substring(lastDot);
      } else {
        prefix = basename;
        suffix = "";
      }
      while (prefix.length() < 3) {
        prefix = prefix + "_";
      }
      file = File.createTempFile(prefix, suffix);
      file.setExecutable(true);
      file.deleteOnExit();
      file.getParentFile().mkdirs();
      Files.copy(Resources.newInputStreamSupplier(Compiler.class.getResource(resourcePath)),
          file);
      resources.put(resourcePath, file);
    }
    return file.getAbsolutePath();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 14
Project: csap-core   File: OsCommandRunner.java   View Source Code Vote up 5 votes
public String runUsingDefaultUser ( String name, String[] lines )
		throws IOException {
	File scriptWithPermissions = Application.getStagingFile(
		"/temp/" + name + "-" + System.currentTimeMillis() + ".sh" );

	scriptWithPermissions.getParentFile().mkdirs();

	List<String> script = Arrays.asList( lines );

	Files.write( scriptWithPermissions.toPath(), script, Charset.forName( "UTF-8" ) );

	boolean ableToSet = scriptWithPermissions.setExecutable( true );
	if ( !ableToSet ) {
		logger.warn( "Unable to set execute permisions on : {}", scriptWithPermissions );
	}
	List<String> parmList = new ArrayList<String>();
	parmList.add( "bash" );
	parmList.add( "-c" );
	parmList.add( scriptWithPermissions.getAbsolutePath() );
	String scriptOutput = "\n" + executeString( null, parmList );
	scriptWithPermissions.delete();

	logger.debug( "Script Output; {}", scriptOutput );
	// strip off script info
	int tokenIndex = scriptOutput.indexOf( OUTPUT_TOKEN );
	if ( tokenIndex == -1 ) {
		tokenIndex = 0;
	} else {
		tokenIndex += OUTPUT_TOKEN.length();
	}
	return scriptOutput.substring( tokenIndex );
}
 
Example 15
Project: csap-core   File: OsCommandRunner.java   View Source Code Vote up 5 votes
public String runUsingRootUser ( String name, String[] lines )
		throws IOException {

	File scriptWithPermissions = Application.getStagingFile(
		"/temp/" + name + "-" + System.currentTimeMillis() + ".sh" );

	scriptWithPermissions.setExecutable( true );
	scriptWithPermissions.getParentFile().mkdirs();

	List<String> script = Arrays.asList( lines );

	Files.write( scriptWithPermissions.toPath(), script, Charset.forName( "UTF-8" ) );

	boolean ableToSet = scriptWithPermissions.setExecutable( true );
	if ( !ableToSet ) {
		logger.warn( "Unable to set execute permisions on : {}", scriptWithPermissions );
	}

	String scriptOutput = runUsingRootUser( scriptWithPermissions, null );
	scriptWithPermissions.delete();

	logger.debug( "Script Output; {}", scriptOutput );
	// strip off script info
	int tokenIndex = scriptOutput.indexOf( OUTPUT_TOKEN );
	if ( tokenIndex == -1 ) {
		tokenIndex = 0;
	} else {
		tokenIndex += OUTPUT_TOKEN.length();
	}
	return scriptOutput.substring( tokenIndex );
}
 
Example 16
Project: gitplex-mit   File: UpgradeCommand.java   View Source Code Vote up 4 votes
private void restoreExecutables(File installDir) {
	for (File file: new File(installDir, "bin").listFiles()) {
		if (file.getName().endsWith(".sh"))
			file.setExecutable(true);
	}
}
 
Example 17
Project: T0rlib4j   File: JavaOnionProxyManager.java   View Source Code Vote up 4 votes
@Override
protected boolean setExecutable(File f) {
    return f.setExecutable(true);
}
 
Example 18
Project: iTAP-controller   File: CryptoUtil.java   View Source Code Vote up 4 votes
public static void writeSharedSecret(String keyStorePath,
                                     String keyStorePassword,
                                     byte[] sharedSecret) 
                                               throws Exception {
    char[] password = keyStorePassword.toCharArray();
    KeyStore ks;
    try {
        ks = readKeyStore(keyStorePath, password);
    } catch (FileNotFoundException e) {
        ks = KeyStore.getInstance("JCEKS");
        ks.load(null, password);
    } 

    KeyStore.ProtectionParameter protParam =
            new KeyStore.PasswordProtection(password);
    SecretKeySpec signingKey = 
            new SecretKeySpec(sharedSecret, "HmacSHA1");
    KeyStore.SecretKeyEntry skEntry =
            new KeyStore.SecretKeyEntry(signingKey);
    ks.setEntry(CHALLENGE_RESPONSE_SECRET, skEntry, protParam);

    // store away the keystore
    java.io.FileOutputStream fos = null;
    File keyStoreFile = new File(keyStorePath);
    File parent = keyStoreFile.getParentFile();
    if (parent != null)
        parent.mkdirs();
    try {
        fos = new java.io.FileOutputStream(keyStoreFile);
        ks.store(fos, password);
        keyStoreFile.setReadable(false, false);
        keyStoreFile.setReadable(true, true);
        keyStoreFile.setWritable(false, false);
        keyStoreFile.setWritable(true, true);
        keyStoreFile.setExecutable(false, false);
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
}
 
Example 19
Project: selenium-toys   File: ChromeWebDriverFactory.java   View Source Code Vote up 4 votes
public ChromeWebDriverFactory() {
  super( //
      BrowserType.CHROME, //
      (targetDirectory) -> {
        final String extension = getExecutableExtension(true);
        final Pattern executablePattern =
            Pattern.compile("chromedriver-(?<version>.*)" + extension);
        final File[] files =
            targetDirectory.listFiles(new PatternFilenameFilter(executablePattern));
        if (files == null || files.length != 1) {
          return Optional.empty();
        }
        final File executable = files[0];
        final Matcher executableMatcher = executablePattern.matcher(executable.getName());
        if (!executableMatcher.find()) {
          throw new IllegalStateException(
              String.format("Unable to determine version of executable %s", executable));
        }
        final String version = executableMatcher.group("version");
        return Optional
            .of(new DownloadWebDriverExecutable.WebDriverExecutable(executable, version));
      }, //
      () -> getString(LATEST_RELEASE_URL), //
      (version, targetDirectory) -> {
        final String system;
        if (SystemUtils.IS_OS_WINDOWS) {
          system = "win32";
        } else if (SystemUtils.IS_OS_MAC) {
          system = "mac64";
        } else if (SystemUtils.IS_OS_LINUX) {
          final StringBuilder linuxBuilder = new StringBuilder("linux");
          // TODO this property does not reflect the OS architecture, it is the VM`s "bitness"
          if (SystemUtils.OS_ARCH.contains("64")) {
            linuxBuilder.append("64");
          } else {
            linuxBuilder.append("32");
          }
          system = linuxBuilder.toString();
        } else {
          throw new UnsupportedOperationException(
              String.format("Unsupported operation system: %s %s", SystemUtils.OS_NAME,
                  SystemUtils.OS_VERSION));
        }
        LOGGER.debug("System '{}' detected.", system);
        final String downloadUrl =
            DOWNLOAD_URL + String.format("/%s/chromedriver_%s.zip", version, system);
        LOGGER.debug("Download chromedriver from {}", downloadUrl);
        downloadZipAndExtract(downloadUrl, targetDirectory);
        final File chromeDriverFile = new File(targetDirectory,
            String.format("chromedriver%s", getExecutableExtension(false)));
        final File chromeDriverFileWithVersion = new File(targetDirectory,
            String.format("chromedriver-%s%s", version, getExecutableExtension(false)));
        if (!chromeDriverFile.renameTo(chromeDriverFileWithVersion)) {
          throw new RuntimeException();
        }
        if (!chromeDriverFileWithVersion.setExecutable(true, false)) {
          throw new RuntimeException();
        }
        return new DownloadWebDriverExecutable.WebDriverExecutable(chromeDriverFileWithVersion,
            version);
      }, //
      ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY //
  );
}
 
Example 20
Project: alvisnlp   File: BioLG.java   View Source Code Vote up 3 votes
/**
 * Gets the parses the script.
 * 
 * @return the parses the script
 * 
 * @throws FileNotFoundException
 *             the file not found exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private static File getParseScript(File tmpDir) throws IOException {
	File result = new File(tmpDir, "parse.sh");
	// same ClassLoader as this class
	try (InputStream is = BioLG.class.getResourceAsStream("parse.sh")) {
		Files.copy(is, result, 1024, true);
	}
	result.setExecutable(true);
	return result;
}