List of usage examples for java.lang ProcessBuilder redirectOutput
public ProcessBuilder redirectOutput(File file)
From source file:husky.server.HuskyMaster.java
@Override public void run() { try {/* ww w .ja va 2 s. c o m*/ LOG.info("Starting husky master process"); ProcessBuilder mHuskyMasterProcess = new ProcessBuilder(getCommands()); if (!mAppMaster.getLdLibraryPath().isEmpty()) { mHuskyMasterProcess.environment().put("LD_LIBRARY_PATH", mAppMaster.getLdLibraryPath()); } mHuskyMasterProcess.redirectOutput(new File(mAppMaster.getAppMasterLogDir() + "/HuskyMaster.stdout")); mHuskyMasterProcess.redirectError(new File(mAppMaster.getAppMasterLogDir() + "/HuskyMaster.stderr")); Process p = mHuskyMasterProcess.start(); p.waitFor(); if (p.exitValue() == 0) { LOG.info("Husky master exits successfully"); } else { LOG.info("Husky master exits with code " + p.exitValue()); } } catch (Exception e) { LOG.log(Level.SEVERE, " Failed to start c++ husky master process: ", e); } finally { if (!mAppMaster.getLogPathToHDFS().isEmpty()) { try { mAppMaster.getFileSystem().copyFromLocalFile(false, true, new Path[] { new Path(mAppMaster.getAppMasterLogDir() + "/HuskyMaster.stdout"), new Path(mAppMaster.getAppMasterLogDir() + "/HuskyMaster.stderr") }, new Path(mAppMaster.getLogPathToHDFS())); } catch (IOException e) { LOG.log(Level.INFO, "Failed to upload logs of husky master to hdfs", e); } } } }
From source file:com.bekwam.resignator.commands.KeytoolCommand.java
public List<KeystoreEntry> findKeystoreEntries(String keytoolExec, String keystore, String storepass) throws CommandExecutionException { List<KeystoreEntry> entries = new ArrayList<>(); Preconditions.checkNotNull(keytoolExec); Preconditions.checkNotNull(keystore); Preconditions.checkNotNull(storepass); File outputFile = null;/*from w w w . j a v a 2s . c o m*/ try { String[] cmdAndArgs = { keytoolExec, "-keystore", keystore, "-storepass", storepass, "-list" }; File resignatorDir = new File(System.getProperty("user.home"), ".resignator"); String outputFileName = OUTPUTFILE_PREFIX + StringUtils.lowerCase(RandomStringUtils.randomAlphabetic(12)) + OUTPUTFILE_SUFFIX; outputFile = new File(resignatorDir, outputFileName); ProcessBuilder pb = new ProcessBuilder(cmdAndArgs); pb.redirectErrorStream(false); pb.redirectOutput(outputFile); Process p = pb.start(); boolean exitted = p.waitFor(TIMEOUT_SECS, TimeUnit.SECONDS); if (exitted) { if (p.exitValue() == 0) { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile))); entries.addAll(parseKeystoreEntries(br)); br.close(); } else { String firstLine = ""; if (outputFile != null && outputFile.exists()) { BufferedReader br = new BufferedReader(new FileReader(outputFile)); firstLine = br.readLine(); br.close(); } if (logger.isErrorEnabled()) { logger.error("error running exec={}; firstLine={}", keytoolExec, firstLine); } throw new CommandExecutionException( "Command '" + keytoolExec + "' failed to run" + newLine + firstLine); } } else { if (logger.isErrorEnabled()) { logger.error("command '" + keytoolExec + "' timed out"); } throw new CommandExecutionException("Command '" + keytoolExec + "' timed out"); } } catch (Exception exc) { // includes interrupted exception if (logger.isErrorEnabled()) { logger.error("error running keytool", exc); } throw new CommandExecutionException("Error running keytool command" + newLine + exc.getMessage()); } finally { if (outputFile != null) { outputFile.delete(); } } return entries; }
From source file:de.tudarmstadt.ukp.dkpro.core.RSTAnnotator.java
/** * Runs the parser on the given text//ww w . java2 s .c o m * * @param originalText text * @return parse tree * @throws IOException exception */ public String parseWithRST(String originalText) throws IOException { // temporary file in File tmpFileIn = File.createTempFile("rst_tmp", ".txt"); // output of RST parser is a .tree file File tmpFileOut = new File(tmpFileIn.getAbsolutePath() + ".tree"); // tmp log File tmpFileLog = new File(tmpFileIn.getAbsolutePath() + ".log"); try { // write the text into a temporary file FileUtils.writeStringToFile(tmpFileIn, originalText); String tmpDirName = System.getProperty("java.io.tmpdir"); File rstParserSrcDir = new File(rstParserSrcDirPath); // create process ProcessBuilder processBuilder = new ProcessBuilder().inheritIO(); // log to file processBuilder.redirectErrorStream(true); processBuilder.redirectOutput(ProcessBuilder.Redirect.to(tmpFileLog)); // working dir must be set to the src dir of RST parser processBuilder.directory(rstParserSrcDir); // run the command processBuilder.command("python", new File(rstParserSrcDir, "parse.py").getAbsolutePath(), "-t", tmpDirName, tmpFileIn.getAbsolutePath(), "-g"); Process process = processBuilder.start(); // and wait int returnValue = process.waitFor(); if (returnValue != 0) { throw new RuntimeException("Process exited with code " + returnValue); } // read the log if (this.debugRSTOutput) { getLogger().debug(FileUtils.readFileToString(tmpFileLog)); } // read the output if (tmpFileOut.exists()) { return FileUtils.readFileToString(tmpFileOut); } } catch (InterruptedException e) { throw new IOException(e); } finally { // clean up if (!keepTmpFiles) { FileUtils.deleteQuietly(tmpFileIn); FileUtils.deleteQuietly(tmpFileOut); FileUtils.deleteQuietly(tmpFileLog); } } return null; }
From source file:fr.amap.lidar.PtgScanConversion.java
public void toLaz(SimpleScan scan, File outputDirectory, boolean laz, boolean exportIntensity) throws IOException, InterruptedException, UnsupportedOperationException, Exception { /***Convert rxp to txt***/ Mat4D transfMatrix = Mat4D.multiply(scan.sopMatrix, scan.popMatrix); Mat3D rotation = new Mat3D(); rotation.mat = new double[] { transfMatrix.mat[0], transfMatrix.mat[1], transfMatrix.mat[2], transfMatrix.mat[4], transfMatrix.mat[5], transfMatrix.mat[6], transfMatrix.mat[8], transfMatrix.mat[9], transfMatrix.mat[10] }; File outputTxtFile = new File( outputDirectory.getAbsolutePath() + File.separator + scan.file.getName() + ".txt"); try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputTxtFile))) { PTGScan ptgScan = new PTGScan(); ptgScan.openScanFile(scan.file); LPointShotExtractor shots = new LPointShotExtractor(ptgScan); Iterator<LShot> iterator = shots.iterator(); while (iterator.hasNext()) { LShot shot = iterator.next(); shot.direction.normalize();// w w w . j a v a2 s. c o m Vec4D origin = Mat4D.multiply(transfMatrix, new Vec4D(shot.origin.x, shot.origin.y, shot.origin.z, 1.0d)); Vec3D direction = Mat3D.multiply(rotation, new Vec3D(shot.direction.x, shot.direction.y, shot.direction.z)); for (int i = 0; i < shot.ranges.length; i++) { double x = origin.x + direction.x * shot.ranges[i]; double y = origin.y + direction.y * shot.ranges[i]; double z = origin.z + direction.z * shot.ranges[i]; if (exportIntensity) { writer.write(x + " " + y + " " + z + " " + (i + 1) + " " + shot.ranges.length + " " + shot.point.intensity + "\n"); } else { writer.write(x + " " + y + " " + z + " " + (i + 1) + " " + shot.ranges.length + "\n"); } } } } /***Convert txt to laz***/ String propertyValue = System.getProperty("user.dir"); System.out.println("Current jar directory : " + propertyValue); String txtToLasPath; String osName = getOSName(); switch (osName) { case "windows": case "linux": txtToLasPath = propertyValue + File.separator + "LASTools" + File.separator + osName + File.separator + "txt2las"; break; default: throw new UnsupportedOperationException("Os architecture not supported"); } if (osName.equals("windows")) { txtToLasPath = txtToLasPath + ".exe"; } File outputLazFile; if (laz) { outputLazFile = new File( outputDirectory.getAbsolutePath() + File.separator + scan.file.getName() + ".laz"); } else { outputLazFile = new File( outputDirectory.getAbsolutePath() + File.separator + scan.file.getName() + ".las"); } String[] commandLine; if (exportIntensity) { commandLine = new String[] { txtToLasPath, "-i", outputTxtFile.getAbsolutePath(), "-o", outputLazFile.getAbsolutePath(), "-parse", "xyzrni" }; } else { commandLine = new String[] { txtToLasPath, "-i", outputTxtFile.getAbsolutePath(), "-o", outputLazFile.getAbsolutePath(), "-parse", "xyzrn" }; } System.out.println("Command line : " + ArrayUtils.toString(commandLine).replaceAll(",", " ").replaceAll("}", "").replace("{", "")); ProcessBuilder pb = new ProcessBuilder(commandLine); pb.redirectOutput(ProcessBuilder.Redirect.INHERIT); pb.redirectError(ProcessBuilder.Redirect.INHERIT); Process p = pb.start(); p.waitFor(); }
From source file:com.smash.revolance.ui.materials.CmdlineHelper.java
public CmdlineHelper exec() throws InterruptedException, IOException { ProcessBuilder pb = new ProcessBuilder(); if (dir != null) { pb.directory(dir);//from w w w . j a va 2 s.c o m } pb.command(cmd); pb.redirectError(ProcessBuilder.Redirect.to(err)); pb.redirectOutput(ProcessBuilder.Redirect.to(out)); pb.redirectInput(ProcessBuilder.Redirect.from(in)); System.out.println("Executing cmd: " + cmd[0] + " from dir: " + dir); System.out.println("Redirecting out to: " + out.getAbsolutePath()); System.out.println("Redirecting err to: " + err.getAbsolutePath()); Process process = pb.start(); if (sync) { process.waitFor(); } this.process = process; return this; }
From source file:org.p_vcd.process.ProcessBase.java
private void runCommandInternal(String command, ProcessArguments commandArgs, File workingDir, StringBuffer sbSaveStdout, StringBuffer sbSaveStderr) throws Exception { commandArgs.insertFirst(command);//from w w w. j a v a 2 s .c o m FileUtils.forceMkdir(workingDir); StringBuffer sbLog = new StringBuffer(); sbLog.append("\n").append(MyUtil.getFormateDate()); commandArgs.addToLog(sbLog); System.out.println(sbLog.toString()); this.status.appendOutputLine(sbLog.toString()); ProcessBuilder pb = new ProcessBuilder(commandArgs.getCommands()); pb.directory(workingDir); pb.redirectInput(Redirect.INHERIT); pb.redirectOutput(Redirect.PIPE); pb.redirectError(Redirect.PIPE); long init = System.currentTimeMillis(); this.currentSystemProcess = pb.start(); PrintThreadWithStatus thStdout = new PrintThreadWithStatus(this.currentSystemProcess.getInputStream(), command, this.status, sbSaveStdout); PrintThreadWithStatus thStderr = new PrintThreadWithStatus(this.currentSystemProcess.getErrorStream(), command, this.status, sbSaveStderr); this.currentSystemProcess.getOutputStream().close(); thStdout.start(); thStderr.start(); int ret = -1; try { this.processRunning = true; ret = this.currentSystemProcess.waitFor(); } catch (InterruptedException ex) { ex.printStackTrace(); } finally { this.processRunning = false; } try { thStderr.join(); } catch (InterruptedException ex) { ex.printStackTrace(); } try { thStdout.join(); } catch (InterruptedException ex) { ex.printStackTrace(); } long milis = System.currentTimeMillis() - init; if (ret != 0) { throw new Exception("command error code=" + ret + " (" + milis + " ms)"); } sbLog = new StringBuffer(); sbLog.append(MyUtil.getFormateDate()).append("command ").append(command).append(" ok (").append(milis) .append(" ms)"); System.out.println(sbLog.toString()); this.status.appendOutputLine(sbLog.toString()); }
From source file:es.amplia.research.maven.protodocbook.cmd.Factory.java
public void executeAll() throws IOException, InterruptedException { File target = new File("target"); target.mkdir();//from w w w. j ava 2s. c o m ProcessBuilder pb = new ProcessBuilder("/usr/bin/make", "clean"); Map<String, String> env = pb.environment(); pb.directory(new File(homeDir, "linux")); File logFile = new File("log"); pb.redirectErrorStream(true); pb.redirectOutput(Redirect.appendTo(logFile)); Process p = pb.start(); p.waitFor(); pb = new ProcessBuilder("/usr/bin/make"); pb.directory(new File(homeDir, "linux")); pb.redirectErrorStream(true); pb.redirectOutput(Redirect.appendTo(logFile)); p = pb.start(); p.waitFor(); pb = new ProcessBuilder("/usr/local/bin/protoc", "-I/usr/include", "--proto_path=src/main/protobuf", "src/main/protobuf/sample.proto", "--plugin=" + this.homeDir.getAbsolutePath() + "/linux/protoc-gen-docbook", "--docbook_out=target"); pb.directory(new File(".")); pb.redirectErrorStream(true); pb.redirectOutput(Redirect.appendTo(logFile)); p = pb.start(); p.waitFor(); pb = new ProcessBuilder("/usr/bin/fop", "-xml", "target/docbook_out.xml", "-xsl", "/usr/share/xml/docbook/stylesheet/docbook-xsl/fo/docbook.xsl", "-pdf", "target/docbook_out.pdf", "-param", "page.orientation", "landscape", "-param", "paper.type", "USletter"); pb.directory(new File(".")); pb.redirectErrorStream(true); pb.redirectOutput(Redirect.appendTo(logFile)); p = pb.start(); p.waitFor(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; while ((line = br.readLine()) != null) { if (this.log.isInfoEnabled()) this.log.info(line); } }
From source file:org.iobserve.mobile.instrument.core.APKToolProxy.java
/** * Adjust the manifest file of the application. * //from ww w. ja v a 2 s . c o m * @param rights * the rights which are mandatory * @param modifiedManifest * the file where the adjusted manifest can be stored * @return true if success - false otherwise */ public boolean adjustManifest(final List<String> rights, final File modifiedManifest) { if (folderName == null) { return false; } // read all rights final File manifestFile = new File(folderName + "/" + MANIFEST_FILE); if (!manifestFile.exists()) { return false; } final Set<String> exRights = new HashSet<String>(); // PARSING XML final Document dom; // Make an instance of the DocumentBuilderFactory final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { final DocumentBuilder db = dbf.newDocumentBuilder(); dom = db.parse(manifestFile); } catch (ParserConfigurationException | SAXException | IOException e) { return false; } final Node manifestNode = dom.getElementsByTagName("manifest").item(0); this.packageName = manifestNode.getAttributes().getNamedItem("package").getTextContent(); final NodeList permissionNodes = manifestNode.getChildNodes(); for (int k = 0; k < permissionNodes.getLength(); k++) { final Node permNode = permissionNodes.item(k); if (permNode.getNodeName().equals("uses-permission")) { exRights.add(permNode.getAttributes().getNamedItem("android:name").getTextContent()); } } // determine which to add for (String right : rights) { if (!exRights.contains(right)) { final Element nNode = dom.createElement("uses-permission"); nNode.setAttribute("android:name", right); manifestNode.appendChild(nNode); } } // write content back to file try { final TransformerFactory transformerFactory = TransformerFactory.newInstance(); final Transformer transformer = transformerFactory.newTransformer(); final DOMSource source = new DOMSource(dom); final StreamResult result = new StreamResult(manifestFile); transformer.transform(source, result); } catch (TransformerException e) { return false; } // RECOMPILE // apktool b bar -o new_bar.apk final File rebuildFile = new File(folderName + "/rebuild.apk"); final ProcessBuilder pb = new ProcessBuilder("java", "-jar", LIB_PATH, "b", folderName, "-o", rebuildFile.getAbsolutePath()); pb.redirectOutput(Redirect.INHERIT); pb.redirectError(Redirect.INHERIT); try { pb.start().waitFor(); } catch (InterruptedException | IOException e) { LOG.error("Failed to rebuild apk with APKTool."); return false; } // UNZIP IT try { final ZipFile rebuildZip = new ZipFile(rebuildFile); rebuildZip.extractFile(MANIFEST_FILE, folderName + "/" + "manifest_new"); Files.copy(new File(folderName + "/" + "manifest_new" + "/" + MANIFEST_FILE).toPath(), modifiedManifest.toPath()); } catch (ZipException | IOException e) { LOG.error("Failed to extract the manifest from the rebuilt application."); return false; } return true; }
From source file:org.jboss.qa.jenkins.test.executor.utils.MavenCli.java
public void run() throws Exception { final List<String> cmd = new ArrayList<>(); // Maven//from ww w . j av a2 s . co m if (OSDetector.isWindows()) { // TODO(mbasovni): Not yet tested! cmd.add("cmd"); cmd.add("/c"); cmd.add(mavenHome + "/bin/mvn.bat"); } else { cmd.add("/bin/bash"); cmd.add(mavenHome + "/bin/mvn"); } // Maven opts if (xms != null) { mavenOpts.add("-Xms" + xms); } if (xmx != null) { mavenOpts.add("-Xmx" + xmx); } if (maxPermSize != null) { mavenOpts.add("-XX:MaxPermSize=" + maxPermSize); } // Path to POM file cmd.add("-f"); cmd.add(pom.getAbsolutePath()); cmd.addAll(goals); // Profiles if (!profiles.isEmpty()) { cmd.add("-P" + StringUtils.join(profiles, ",")); } // Projects if (!projects.isEmpty()) { cmd.add("-pl"); cmd.add(StringUtils.join(projects, ",")); } // If project list is specified, also build projects required by the list if (alsoMake) { cmd.add("-am"); } // Only fail the build afterwards; allow all non-impacted builds to continue if (failAtEnd) { cmd.add("-fae"); } // System properties for (Map.Entry<String, String> entry : sysProps.entrySet()) { cmd.add(String.format("-D%s=%s", entry.getKey(), entry.getValue())); } if (params != null) { cmd.addAll(params); } final ProcessBuilder processBuilder = new ProcessBuilder(cmd); processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT); processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT); processBuilder.environment().put("JAVA_HOME", javaHome.getAbsolutePath()); processBuilder.environment().put("M2_HOME", mavenHome.getAbsolutePath()); processBuilder.environment().put("MAVEN_OTPS", StringUtils.join(mavenOpts, " ")); log.debug("==========="); log.debug("Process arguments: " + cmd.toString()); log.debug("JAVA_HOME={}", processBuilder.environment().get("JAVA_HOME")); log.debug("M2_HOME={}", processBuilder.environment().get("M2_HOME")); log.debug("MAVEN_OTPS={}", processBuilder.environment().get("MAVEN_OTPS")); final Process process = processBuilder.start(); process.waitFor(); if (process.exitValue() != 0) { log.error("Maven execution failed with exit code: " + process.exitValue()); } }
From source file:metadata.etl.dataset.hdfs.HdfsMetadataEtl.java
private void extractLocal() throws Exception { URL localJarUrl = classLoader.getResource("jar/schemaFetch.jar"); String homeDir = System.getProperty("user.home"); String remoteJarFile = homeDir + "/.wherehows/schemaFetch.jar"; File dest = new File(remoteJarFile); try {//from w w w .j a v a2s . c o m FileUtils.copyURLToFile(localJarUrl, dest); } catch (Exception e) { logger.error(e.toString()); } String outputSchemaFile = prop.getProperty(Constant.HDFS_SCHEMA_LOCAL_PATH_KEY); String outputSampleDataFile = prop.getProperty(Constant.HDFS_SAMPLE_LOCAL_PATH_KEY); String cluster = prop.getProperty(Constant.HDFS_CLUSTER_KEY); String whiteList = prop.getProperty(Constant.HDFS_WHITE_LIST_KEY); String numOfThread = prop.getProperty(Constant.HDFS_NUM_OF_THREAD_KEY, String.valueOf(1)); String hdfsUser = prop.getProperty(Constant.HDFS_REMOTE_USER_KEY); // String hdfsKeyTab = prop.getProperty(Constant.HDFS_REMOTE_KEYTAB_LOCATION_KEY); String hdfsExtractLogFile = outputSchemaFile + ".log"; String[] hadoopCmd = { "hadoop", "jar", remoteJarFile, "-D" + Constant.HDFS_SCHEMA_REMOTE_PATH_KEY + "=" + outputSchemaFile, "-D" + Constant.HDFS_SAMPLE_REMOTE_PATH_KEY + "=" + outputSampleDataFile, "-D" + Constant.HDFS_CLUSTER_KEY + "=" + cluster, "-D" + Constant.HDFS_WHITE_LIST_KEY + "=" + whiteList, "-D" + Constant.HDFS_NUM_OF_THREAD_KEY + "=" + numOfThread, "-D" + Constant.HDFS_REMOTE_USER_KEY + "=" + hdfsUser, "-Dlog.file.name=hdfs_schema_fetch" }; // delete the line (no kerberos needed): "-D" + Constant.HDFS_REMOTE_KEYTAB_LOCATION_KEY + "=" + hdfsKeyTab, ProcessBuilder pb = new ProcessBuilder(hadoopCmd); File logFile = new File(hdfsExtractLogFile); pb.redirectErrorStream(true); pb.redirectOutput(ProcessBuilder.Redirect.appendTo(logFile)); Process process = pb.start(); int pid = -1; if (process.getClass().getName().equals("java.lang.UNIXProcess")) { /* get the PID on unix/linux systems */ try { Field f = process.getClass().getDeclaredField("pid"); f.setAccessible(true); pid = f.getInt(process); } catch (Throwable e) { } } logger.info("executue command [PID=" + pid + "]: " + hadoopCmd); // wait until this process finished. int execResult = process.waitFor(); // if the process failed, log the error and throw exception if (execResult > 0) { BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream())); String errString = "HDFS Metadata Extract Error:\n"; String line = ""; while ((line = br.readLine()) != null) errString = errString.concat(line).concat("\n"); logger.error("*** Process failed, status: " + execResult); logger.error(errString); throw new Exception("Process + " + pid + " failed"); } }