List of usage examples for java.io File setExecutable
public boolean setExecutable(boolean executable)
From source file:com.github.nethad.clustermeister.integration.JPPFTestNode.java
private void startNode() throws RuntimeException { File startNodeScript = new File(targetDir, "jppf-node/startNode.sh"); startNodeScript.setExecutable(true); try {//from ww w. j a va 2 s. c o m // String jppfNodePath = startNodeScript.getParentFile().getAbsolutePath(); final String command = String.format("%s %s %s", "./" + startNodeScript.getName(), currentNodeConfig, "true"); logger.info("Start node with {}", command); nodeProcess = Runtime.getRuntime().exec(command, new String[] {}, startNodeScript.getParentFile()); // Process exec = Runtime.getRuntime().exec(command); InputStream stdOutInputStream = nodeProcess.getInputStream(); InputStream stdErrInputStream = nodeProcess.getErrorStream(); // CharStreams.class; BufferedReader stdOutReader = new BufferedReader(new InputStreamReader(stdOutInputStream)); BufferedReader stdErrReader = new BufferedReader(new InputStreamReader(stdErrInputStream)); nodeProcessOutputterStdOut = new NodeProcessOutputter(stdOutReader, "STDOUT"); nodeProcessOutputterStdOut.start(); nodeProcessOutputterStdErr = new NodeProcessOutputter(stdErrReader, "STDERR"); nodeProcessOutputterStdErr.start(); } catch (IOException ex) { throw new RuntimeException(ex); } }
From source file:com.urswolfer.intellij.plugin.gerrit.extension.GerritCheckoutProvider.java
private void setupCommitMsgHook(String parentDirectory, String directoryName, Project project) { try {/*from w ww. j a v a 2 s . c o m*/ HttpResponse response = gerritApiUtil.doREST("/tools/hooks/commit-msg", null, Collections.<Header>emptyList(), GerritApiUtil.HttpVerb.GET); if (response.getStatusLine().getStatusCode() != 200) { throw new HttpStatusException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), response.getStatusLine().getReasonPhrase()); } File targetFile = new File(parentDirectory + '/' + directoryName + "/.git/hooks/commit-msg"); Files.write(EntityUtils.toString(response.getEntity(), Consts.UTF_8).getBytes(), targetFile); targetFile.setExecutable(true); } catch (Exception e) { log.info(e); NotificationBuilder notification = new NotificationBuilder(project, "Couldn't set up Gerrit Commit-Message Hook. Please do it manually.", gerritUtil.getErrorTextFromException(e)); notificationService.notifyError(notification); } }
From source file:edu.stolaf.cs.wmrserver.testjob.TestJobTask.java
protected TestJobResult.TransformResult runTransform(long id, File executable, File workingDir, InputStream input) throws IOException { // Create the result object TestJobResult.TransformResult result = new TestJobResult.TransformResult(); CountingOutputStream output = null;//from ww w . j a v a 2s. co m CountingOutputStream error = null; try { // Create and open temporary file for standard output File outputFile = File.createTempFile("job-" + Long.toString(_id), "-output", _tempDir); output = new CountingOutputStream(new FileOutputStream(outputFile)); // Create and open temporary file for standard error File errorFile = File.createTempFile("job-" + Long.toString(_id), "-error", _tempDir); error = new CountingOutputStream(new FileOutputStream(errorFile)); // If executable is relative, try to resolve in working directory // (This emulates the behavior of Streaming) if (!executable.isAbsolute()) { File resolvedExecutable = new File(workingDir, executable.toString()); if (resolvedExecutable.isFile()) { resolvedExecutable.setExecutable(true); executable = resolvedExecutable.getAbsoluteFile(); } } // Run the transform CommandLine command; if (_switchUserCommand == null) command = new CommandLine(executable); else { command = CommandLine.parse(_switchUserCommand); HashMap<String, String> substitutionMap = new HashMap<String, String>(); substitutionMap.put("cmd", executable.toString()); command.setSubstitutionMap(substitutionMap); } DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog dog = new ExecuteWatchdog(EXECUTABLE_TIMEOUT); PumpStreamHandler pump = new PumpStreamHandler(output, error, input); executor.setWorkingDirectory(workingDir); executor.setWatchdog(dog); executor.setStreamHandler(pump); executor.setExitValues(null); int exitCode = executor.execute(command); result.setExitCode(exitCode); // Check whether it produced any output if (output.getByteCount() == 0) { output.close(); outputFile.delete(); } else result.setOutputFile(outputFile); // Check whether it produced any error output if (error.getByteCount() == 0) { error.close(); errorFile.delete(); } else result.setErrorFile(errorFile); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(error); } return result; }
From source file:org.apache.hadoop.hdfs.server.datanode.TestDataNodeVolumeFailureToleration.java
/** * Test the dfs.datanode.failed.volumes.tolerated configuration * option, ie the DN shuts itself down when the number of failures * experienced drops below the tolerated amount. *//*www.ja v a 2 s . com*/ @Test public void testConfigureMinValidVolumes() throws Exception { assumeTrue(!System.getProperty("os.name").startsWith("Windows")); // Bring up two additional datanodes that need both of their volumes // functioning in order to stay up conf.setInt("dfs.datanode.failed.volumes.tolerated", 0); cluster.startDataNodes(conf, 2, true, null, null); cluster.waitActive(); // Fail a volume on the 2nd DN File dn2Vol1 = new File(new File(dataDir, "data" + (2 * 1 + 1)), "current"); try { assertTrue("Couldn't chmod local vol", dn2Vol1.setExecutable(false)); // Should only get two replicas (the first DN and the 3rd) Path file1 = new Path("/test1"); DFSTestUtil.createFile(fs, file1, 1024, (short) 3, 1L); DFSTestUtil.waitReplication(fs, file1, (short) 2); DFSTestUtil.waitNSecond(2); assertFalse("2nd DN should be dead", cluster.getDataNodes().get(1).isDatanodeUp()); // If we restore the volume we should still only be able to get // two replicas since the DN is still considered dead. assertTrue("Couldn't chmod local vol", dn2Vol1.setExecutable(true)); Path file2 = new Path("/test2"); DFSTestUtil.createFile(fs, file2, 1024, (short) 3, 1L); DFSTestUtil.waitReplication(fs, file2, (short) 2); DFSTestUtil.waitNSecond(2); assertFalse("2nd DN should be dead", cluster.getDataNodes().get(1).isDatanodeUp()); } finally { dn2Vol1.setExecutable(true); } }
From source file:com.thoughtworks.go.util.command.CommandLineTest.java
@BeforeEach void setUp() throws Exception { // Have to call this as it uses another Junit runner which overrides the rule temporaryFolder.create();/*w w w . j a v a 2 s . c om*/ subFolder = temporaryFolder.newFolder("subFolder"); File file = temporaryFolder.newFile("./originalCommand"); file.setExecutable(true); }
From source file:com.jpmorgan.cakeshop.bean.QuorumConfigBean.java
private void initQuorumBean() { // setup needed paths String baseResourcePath = System.getProperty("eth.geth.dir"); if (StringUtils.isBlank(baseResourcePath)) { baseResourcePath = FileUtils.getClasspathName("geth"); }// w w w. j a va2s.c o m if (SystemUtils.IS_OS_LINUX) { LOG.debug("Using quorum for linux"); setQuorumPath(expandPath(baseResourcePath, QUORUM_LINUX_COMMAND)); setConstellationPath(expandPath(baseResourcePath, CONSTELLATION_LINUX_COMMAND)); setKeyGen(expandPath(baseResourcePath, CONSTELLATION_LINUX_KEYGEN)); } else if (SystemUtils.IS_OS_MAC_OSX) { LOG.debug("Using quorum for mac"); setQuorumPath(expandPath(baseResourcePath, QUORUM_MAC_COMMAND)); setConstellationPath(expandPath(baseResourcePath, CONSTELLATION_MAC_COMMAND)); setKeyGen(expandPath(baseResourcePath, CONSTELLATION_MAC_KEYGEN)); } else { LOG.error("Running on unsupported OS! Only Linux and Mac OS X are currently supported"); throw new IllegalArgumentException( "Running on unsupported OS! Only Linux and Mac OS X are currently supported"); } File quorumExec = new File(getQuorumPath()); if (!quorumExec.canExecute()) { quorumExec.setExecutable(true); } File constExec = new File(getConstellationPath()); if (!constExec.canExecute()) { constExec.setExecutable(true); } File keyGenExec = new File(getKeyGen()); if (!keyGenExec.canExecute()) { keyGenExec.setExecutable(true); } }
From source file:com.blackducksoftware.integration.hub.cli.CLILocation.java
public File getOneJarFile() { final File cliHomeFile = getCLIHome(); if (cliHomeFile == null) { return null; }//from ww w.ja va2s . co m File oneJarFile = new File(cliHomeFile, "lib"); oneJarFile = new File(oneJarFile, "cache"); oneJarFile = new File(oneJarFile, "scan.cli.impl-standalone.jar"); oneJarFile.setExecutable(true); return oneJarFile; }
From source file:com.intel.chimera.utils.NativeCodeLoader.java
/** * Extracts the specified library file to the target folder. * // ww w . j a v a 2 s .co m * @param libFolderForCurrentOS the library in chimera.lib.path. * @param libraryFileName the library name. * @param targetFolder Target folder for the native lib. Use the value of * chimera.tempdir or java.io.tmpdir. * @return the library file. */ 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 libchimera multiple times. String uuid = UUID.randomUUID().toString(); String extractedLibFileName = String.format("chimera-%s-%s-%s", getVersion(), uuid, libraryFileName); File extractedLibFile = new File(targetFolder, extractedLibFileName); InputStream reader = null; try { // Extract a native library file into the target directory reader = NativeCodeLoader.class.getResourceAsStream(nativeLibraryFilePath); FileOutputStream writer = new FileOutputStream(extractedLibFile); try { byte[] buffer = new byte[8192]; int bytesRead; 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(); reader = null; } } // Set executable (x) flag to enable Java to load the native library if (!extractedLibFile.setReadable(true) || !extractedLibFile.setExecutable(true) || !extractedLibFile.setWritable(true, true)) { throw new RuntimeException("Invalid path for library path"); } // Check whether the contents are properly copied from the resource folder { InputStream nativeIn = null; InputStream extractedLibIn = null; try { nativeIn = NativeCodeLoader.class.getResourceAsStream(nativeLibraryFilePath); extractedLibIn = new FileInputStream(extractedLibFile); 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; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:com.google.dart.tools.update.core.internal.UpdateUtils.java
/** * Unzip a zip file, notifying the given monitor along the way. *///ww w . j ava 2 s .c o m public static void unzip(File zipFile, File destination, String taskName, IProgressMonitor monitor) throws IOException { ZipFile zip = new ZipFile(zipFile); //TODO (pquitslund): add real progress units if (monitor != null) { monitor.beginTask(taskName, 1); } 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) { file.setExecutable(true); } } } //TODO (pquitslund): fix progress units if (monitor != null) { monitor.worked(1); monitor.done(); } }
From source file:org.silverpeas.core.security.encryption.ContentEncryptionServiceTest.java
private void createSecurityDirectoryAndSetupJCEProviders() throws IOException { ACTUAL_KEY_FILE_PATH = FileRepositoryManager.getSecurityDirPath() + ".aid_key"; DEPRECATED_KEY_FILE_PATH = FileRepositoryManager.getSecurityDirPath() + ".did_key"; try {// ww w . j av a2s. c o m CIPHER_KEY = CipherKey.aKeyFromHexText("06277d1ce530c94bd9a13a72a58342be"); } catch (ParseException e) { throw new RuntimeException("Cannot create the cryptographic key!", e); } String securityPath = FileRepositoryManager.getSecurityDirPath(); File securityDir = new File(securityPath); if (!securityDir.exists()) { FileUtils.forceMkdir(securityDir); } securityDir.setWritable(true); securityDir.setExecutable(true); securityDir.setReadable(true); if (System.getProperty("os.name").toLowerCase().contains("windows")) { Runtime.getRuntime().exec("attrib +H " + securityPath); } Security.addProvider(new BouncyCastleProvider()); }