List of usage examples for java.lang Process exitValue
public abstract int exitValue();
From source file:org.apache.asterix.app.translator.QueryTranslator.java
protected int executeExternalShellProgram(ProcessBuilder pb) throws IOException, AlgebricksException, InterruptedException { Process process = pb.start(); try (BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line;/*from ww w . j a v a 2 s .c o m*/ while ((line = in.readLine()) != null) { LOGGER.info(line); if (line.contains("Exception") || line.contains("Error")) { LOGGER.severe(line); if (line.contains("Connection refused")) { throw new AlgebricksException( "The connection to your Pregelix cluster was refused. Is it running? " + "Is the port in the query correct?"); } if (line.contains("Could not find or load main class")) { throw new AlgebricksException("The main class of your Pregelix query was not found. " + "Is the path to your .jar file correct?"); } if (line.contains("ClassNotFoundException")) { throw new AlgebricksException("The vertex class of your Pregelix query was not found. " + "Does it exist? Is the spelling correct?"); } } } process.waitFor(); } // Gets the exit value of the program. return process.exitValue(); }
From source file:org.sugarcrm.voodoodriver.EventLoop.java
private boolean executeEvent(VDDHash event) { boolean result = false; Process proc = null; int proc_ret = 0; this.report.Log("Execute event starting...\n"); this.resetThreadTime(); if (event.containsKey("args")) { String[] list = (String[]) event.get("args"); int len = list.length - 1; for (int i = 0; i <= len; i++) { System.out.printf("(%s) => '%s'\n", i, list[i]); }/* w w w. j a v a 2 s. c o m*/ try { this.report.Log("Executing process now..."); proc = Runtime.getRuntime().exec(list); this.resetThreadTime(); proc.waitFor(); this.resetThreadTime(); this.report.Log("Process finished executing."); proc_ret = proc.exitValue(); if (proc_ret != 0) { String msg = String.format("Error the command being executed returned a non-zero value: '%s'!", proc_ret); this.report.ReportError(msg); } else { this.report.Log("Execute was successful."); result = true; } } catch (Exception exp) { this.report.ReportException(exp); result = false; } } else { this.report.ReportError("Error no args for Execute Event!"); result = false; this.report.Log("Execute event finished."); return result; } return result; }
From source file:com.ikanow.infinit.e.application.handlers.polls.LogstashTestRequestPollHandler.java
@Override public void performPoll() { if (null == LOGSTASH_DIRECTORY) { // (static memory not yet initialized) try {//w ww.j a v a 2 s.c om Thread.sleep(1000); // (extend the sleep time a bit) } catch (Exception e) { } return; } // 1] Check - does logstash exist on this server: File logstashBinary = new File(LOGSTASH_BINARY); if (!logstashBinary.canExecute()) { try { Thread.sleep(10000); // (extend the sleep time a bit) } catch (Exception e) { } return; } // 2] (Unlike harvester, _don't_ grab an application token, you can run this on as many servers as you want) // 3] Setup if (null == _logHarvesterQ) { _logHarvesterQ = new MongoQueue(DbManager.getIngest().getLogHarvesterQ().getDB().getName(), DbManager.getIngest().getLogHarvesterQ().getName()); } if (null == _testOutputTemplate) { try { File testOutputTemplate = new File(LOGSTASH_TEST_OUTPUT_TEMPLATE); InputStream inStream = null; try { inStream = new FileInputStream(testOutputTemplate); _testOutputTemplate = IOUtils.toString(inStream); } catch (Exception e) {// abandon ship! return; } finally { inStream.close(); } } catch (Exception e) {// abandon ship! //DEBUG //e.printStackTrace(); return; } } //TESTED // 4] Check if any new requests have been made: BasicDBObject queueQuery = new BasicDBObject("logstash", new BasicDBObject(DbManager.exists_, true)); DBObject nextElement = _logHarvesterQ.pop(queueQuery); while (nextElement != null) { //DEBUG //System.out.println("FOUND: " + nextElement.toString()); TestLogstashExtractorPojo testInfo = TestLogstashExtractorPojo.fromDb(nextElement, TestLogstashExtractorPojo.class); if ((null == testInfo.maxDocs) || (null == testInfo.logstash.config) || (null == testInfo.isAdmin) || (null == testInfo.sourceKey)) { TestLogstashExtractorPojo testErr = new TestLogstashExtractorPojo(); testErr._id = testInfo._id; testErr.error = "Internal Logic Error. Missing one of: maxDocs, isAdmin, sourceKey, logstash.config"; _logHarvesterQ.push(testErr.toDb()); return; } //TESTED // Validate/tranform the configuration: StringBuffer errMessage = new StringBuffer(); String logstashConfig = LogstashConfigUtils.validateLogstashInput(testInfo.sourceKey, testInfo.logstash.config, errMessage, testInfo.isAdmin); if (null == logstashConfig) { // Validation error... TestLogstashExtractorPojo testErr = new TestLogstashExtractorPojo(); testErr._id = testInfo._id; testErr.error = "Validation error: " + errMessage.toString(); _logHarvesterQ.push(testErr.toDb()); return; } //TESTED // Replacement for #LOGSTASH{host} - currently only replacement supported (+ #IKANOW{} in main code) try { logstashConfig = logstashConfig.replace("#LOGSTASH{host}", java.net.InetAddress.getLocalHost().getHostName()); } catch (Exception e) { logstashConfig = logstashConfig.replace("#LOGSTASH{host}", "localhost.localdomain"); } //TESTED String outputConf = _testOutputTemplate.replace("_XXX_COLLECTION_XXX_", testInfo._id.toString()); //TESTED String sinceDbPath = LOGSTASH_WD + ".sincedb_" + testInfo._id.toString(); String conf = logstashConfig.replace("_XXX_DOTSINCEDB_XXX_", sinceDbPath) + outputConf.replace("_XXX_SOURCEKEY_XXX_", testInfo.sourceKey); boolean allWorked = false; Process logstashProcess = null; try { // 1] Create the process ArrayList<String> args = new ArrayList<String>(4); args.addAll(Arrays.asList(LOGSTASH_BINARY, "-e", conf)); if (0 == testInfo.maxDocs) { args.add("-t"); // test mode, must faster } //TESTED if ((null != testInfo.logstash.testDebugOutput) && testInfo.logstash.testDebugOutput) { args.add("--debug"); } else { args.add("--verbose"); } ProcessBuilder logstashProcessBuilder = new ProcessBuilder(args); logstashProcessBuilder = logstashProcessBuilder.directory(new File(LOGSTASH_WD)) .redirectErrorStream(true); logstashProcessBuilder.environment().put("JAVA_OPTS", ""); //DEBUG //System.out.println("STARTING: " + ArrayUtils.toString(logstashProcessBuilder.command().toArray())); // 2] Kick off the process logstashProcess = logstashProcessBuilder.start(); StringWriter outputAndError = new StringWriter(); OutputCollector outAndErrorStream = new OutputCollector(logstashProcess.getInputStream(), new PrintWriter(outputAndError)); outAndErrorStream.start(); final int toWait_s = 240; boolean exited = false; // 3] Check the output collection for records int errorVal = 0; long priorCount = 0L; int priorLogCount = 0; int timeOfLastLoggingChange = 0; int timeOfLastDocCountChange = 0; String reasonForExit = ""; int inactivityTimeout_s = 10; // (default) if (null != testInfo.logstash.testInactivityTimeout_secs) { inactivityTimeout_s = testInfo.logstash.testInactivityTimeout_secs; } for (int i = 0; i < toWait_s; i += 5) { try { Thread.sleep(5000); } catch (Exception e) { } long count = DbManager.getCollection("ingest", testInfo._id.toString()).count(); // 3.1] Do we have all the records (or is the number staying static) //DEBUG //System.out.println("FOUND: " + count + " VS " + priorCount + " , " + priorPriorCount); // 3.1a] All done? if ((count >= testInfo.maxDocs) && (count > 0)) { allWorked = true; break; } //TESTED // 3.1b] If not, has anything changes? if (priorCount != count) { timeOfLastDocCountChange = i; } if (priorLogCount != outAndErrorStream.getLines()) { timeOfLastLoggingChange = i; } // 3.1c] Check for inactivity if ((timeOfLastDocCountChange > 0) && (i - timeOfLastDocCountChange) >= inactivityTimeout_s) { // Delay between events: treat as success allWorked = true; break; } //TESTED if ((0 == count) && outAndErrorStream.getPipelineStarted() && ((timeOfLastLoggingChange > 0) && (i - timeOfLastLoggingChange) >= inactivityTimeout_s)) { // Delay between log messages after pipeline started, no documents, treat as failure //DEBUG //System.out.println("LOG LINES! " + i + " NUM = " + outAndErrorStream.getLines()); errorVal = 1; reasonForExit = "No records received and logging inactive.\n"; break; } //TESTED // 3.2] Has the process exited unexpectedly? try { errorVal = logstashProcess.exitValue(); reasonForExit = "Logstash process exited with error: " + errorVal + ".\n"; exited = true; //DEBUG //System.out.println("GOT EXIT VALUE: " + errorVal); break; } //TESTED catch (Exception e) { } // that's OK we're just still going is all... priorCount = count; priorLogCount = outAndErrorStream.getLines(); } //(end loop while waiting for job to complete) // 4] If the process is still running then kill it if (!exited) { //DEBUG //System.out.println("EXITED WITHOUT FINISHING"); logstashProcess.destroy(); } //TESTED // 5] Things to do when the job is done: (worked or not) // Send a message to the harvester outAndErrorStream.join(); // (if we're here then must have closed the process, wait for it to die) TestLogstashExtractorPojo testErr = new TestLogstashExtractorPojo(); testErr._id = testInfo._id; if ((testInfo.maxDocs > 0) || (0 != errorVal)) { testErr.error = reasonForExit + outputAndError.toString(); // (note this is capped at well below the BSON limit in the thread below) } else { // maxDocs==0 (ie pre-publish test) AND no error returned testErr.error = null; } _logHarvesterQ.push(testErr.toDb()); //TESTED } catch (Exception e) { //DEBUG //e.printStackTrace(); TestLogstashExtractorPojo testErr = new TestLogstashExtractorPojo(); testErr._id = testInfo._id; testErr.error = "Internal Logic Error: " + e.getMessage(); _logHarvesterQ.push(testErr.toDb()); } //TOTEST finally { // If we created a sincedb path then remove it: try { new File(sinceDbPath).delete(); } catch (Exception e) { } // (don't care if it fails) if (!allWorked) { // (otherwise up to the harvester to remove these) try { DbManager.getCollection("ingest", testInfo._id.toString()).drop(); } catch (Exception e) { } // doesn't matter if this errors } try { // Really really want to make sure the process isn't running if (null != logstashProcess) { logstashProcess.destroy(); } } catch (Exception e) { } catch (Error ee) { } } //TESTED // (If we actually processed an element, then try again immediate) nextElement = _logHarvesterQ.pop(queueQuery); } }
From source file:com.ah.ui.actions.home.HmSettingsAction.java
private int execCommand(String cmd) { try {// w ww . jav a2 s .co m String string_Path_Array[] = new String[3]; string_Path_Array[0] = "bash"; string_Path_Array[1] = "-c"; string_Path_Array[2] = cmd; Process p = Runtime.getRuntime().exec(string_Path_Array); p.waitFor(); return p.exitValue(); } catch (Exception e) { log.error("execCommand", "catch exception", e); return 255; } }
From source file:br.com.riselabs.cotonet.builder.commands.ExternalGitCommand.java
/** * OBS: this method returns {@code null} when calling ' * {@code git reset --hard}'.//from w w w . j a v a 2 s . c o m * * @return * @throws IOException */ public List<ConflictChunk<CommandLineBlameResult>> call() throws BlameException { Runtime run = Runtime.getRuntime(); Process pr = null; String cmd = null; String[] env = {}; BufferedReader buf; List<ConflictChunk<CommandLineBlameResult>> conflicts = null; int exitCode; try { switch (type) { case RESET: cmd = "git reset --hard"; pr = run.exec(cmd, env, file); break; case BLAME: default: cmd = "git blame -p --line-porcelain"; env = new String[1]; // we need this to disable the pager env[0] = "GIT_PAGER=cat"; pr = run.exec(cmd + " " + file, env, file.getParentFile()); // parse output buf = new BufferedReader(new InputStreamReader(pr.getInputStream())); conflicts = new ArrayList<ConflictChunk<CommandLineBlameResult>>(); final String CONFLICT_START = "<<<<<<<"; final String CONFLICT_SEP = "======="; final String CONFLICT_END = ">>>>>>>"; boolean addBlame = false; ConflictChunk<CommandLineBlameResult> conflict = new ConflictChunk<CommandLineBlameResult>( file.getCanonicalPath()); CommandLineBlameResult bResult; bResult = new CommandLineBlameResult(file.getCanonicalPath()); Blame<CommandLineBlameResult> cBlame; cBlame = new Blame<CommandLineBlameResult>(scenario.getLeft(), bResult); List<String> block; while ((block = readPorcelainBlock(buf)) != null) { String commit = block.get(0).split(" ")[0]; // for (String line : block) // System.out.println(line); Map<PKeys, String> data = getDataFromPorcelainBlock(block); String contentLine = data.get(PKeys.content); int n; if ((n = contentLine.trim().indexOf(" ")) == -1) { // line without blank space contentLine = contentLine.trim(); } else { contentLine = contentLine.trim().substring(0, n); } if (contentLine.equals(CONFLICT_START)) { addBlame = true; continue; } else if (contentLine.equals(CONFLICT_SEP)) { addBlame = true; cBlame.setRevision(scenario.getLeft()); conflict.setBase(scenario.getBase()); conflict.setLeft(cBlame); bResult = new CommandLineBlameResult(file.getCanonicalPath()); cBlame = new Blame<CommandLineBlameResult>(scenario.getRight(), bResult); continue; } else if (contentLine.equals(CONFLICT_END)) { conflict.setRight(cBlame); conflict.setLine(Integer.valueOf(data.get(PKeys.linenumber))); conflicts.add(conflict); addBlame = false; bResult = new CommandLineBlameResult(file.getCanonicalPath()); cBlame = new Blame<CommandLineBlameResult>(scenario.getLeft(), bResult); //@gustavo added this line conflict = new ConflictChunk<CommandLineBlameResult>(file.getCanonicalPath()); } else if (addBlame) { // we are in one of the conflicting chunks Integer linenumber = Integer.valueOf(data.get(PKeys.linenumber)); contentLine = data.get(PKeys.content); String name = data.get(PKeys.authorname); String email = data.get(PKeys.authormail); DeveloperNode dev = new DeveloperNode(name, email); conflict.setLine(linenumber); bResult.addLineAuthor(linenumber, dev); bResult.addLineContent(linenumber, contentLine); bResult.addLineCommit(linenumber, commit); continue; } } buf.close(); break; } /* * already finished to execute the process. now, we should process * the error output. */ buf = new BufferedReader(new InputStreamReader(pr.getErrorStream())); String stdErr = IOUtils.toString(pr.getErrorStream(), StandardCharsets.UTF_8).trim(); IOUtils.closeQuietly(pr.getInputStream()); IOUtils.closeQuietly(pr.getErrorStream()); IOUtils.closeQuietly(pr.getOutputStream()); exitCode = pr.waitFor(); buf.close(); if (!stdErr.isEmpty()) { Logger.log(String.format("Execution of '%s' returned standard error output:%n%s", cmd, stdErr)); throw new RuntimeException( String.format("Error on external call with exit code %d", pr.exitValue())); } } catch (IOException io) { try { throw new BlameException(file.getCanonicalPath(), "IO Exception", io); } catch (IOException e) { } } catch (InterruptedException ie) { // waitFor() exception exitCode = 666; try { throw new BlameException(file.getCanonicalPath(), String.format( "Interrupted while waiting for '%s' to finish. Error code: '%s'", cmd, exitCode), ie); } catch (IOException io) { } } catch (RuntimeException re) { try { throw new BlameException(file.getCanonicalPath(), "Runtime Exception", re); } catch (IOException e) { } } finally { run.freeMemory(); } pr.destroyForcibly(); return conflicts; }
From source file:com.panet.imeta.job.entries.shell.JobEntryShell.java
private void executeShell(Result result, List<RowMetaAndData> cmdRows, String[] args) { LogWriter log = LogWriter.getInstance(); FileObject fileObject = null; String realScript = null;//from w w w .j a va 2 s . co m FileObject tempFile = null; try { // What's the exact command? String base[] = null; List<String> cmds = new ArrayList<String>(); if (log.isBasic()) log.logBasic(toString(), Messages.getString("JobShell.RunningOn", Const.getOS())); if (insertScript) { realScript = environmentSubstitute(script); } else { String realFilename = environmentSubstitute(getFilename()); fileObject = KettleVFS.getFileObject(realFilename); } if (Const.getOS().equals("Windows 95")) { base = new String[] { "command.com", "/C" }; } else if (Const.getOS().startsWith("Windows")) { base = new String[] { "cmd.exe", "/C" }; } else { if (!insertScript) { // Just set the command to the script we need to execute... // base = new String[] { KettleVFS.getFilename(fileObject) }; } else { // Create a unique new temporary filename in the working directory, put the script in there // Set the permissions to execute and then run it... // try { tempFile = KettleVFS.createTempFile("kettle", "shell", workDirectory); tempFile.createFile(); OutputStream outputStream = tempFile.getContent().getOutputStream(); outputStream.write(realScript.getBytes()); outputStream.close(); String tempFilename = KettleVFS.getFilename(tempFile); // Now we have to make this file executable... // On Unix-like systems this is done using the command "/bin/chmod +x filename" // ProcessBuilder procBuilder = new ProcessBuilder("chmod", "+x", tempFilename); Process proc = procBuilder.start(); // Eat/log stderr/stdout all messages in a different thread... StreamLogger errorLogger = new StreamLogger(proc.getErrorStream(), toString() + " (stderr)"); StreamLogger outputLogger = new StreamLogger(proc.getInputStream(), toString() + " (stdout)"); new Thread(errorLogger).start(); new Thread(outputLogger).start(); proc.waitFor(); // Now set this filename as the base command... // base = new String[] { tempFilename }; } catch (Exception e) { throw new Exception("Unable to create temporary file to execute script", e); } } } // Construct the arguments... if (argFromPrevious && cmdRows != null) { // Add the base command... for (int i = 0; i < base.length; i++) cmds.add(base[i]); if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) { // for windows all arguments including the command itself // need to be // included in 1 argument to cmd/command. StringBuffer cmdline = new StringBuffer(300); cmdline.append('"'); if (insertScript) cmdline.append(realScript); else cmdline.append(optionallyQuoteField(KettleVFS.getFilename(fileObject), "\"")); // Add the arguments from previous results... for (int i = 0; i < cmdRows.size(); i++) // Normally just // one row, but // once in a // while to // remain // compatible we // have // multiple. { RowMetaAndData r = (RowMetaAndData) cmdRows.get(i); for (int j = 0; j < r.size(); j++) { cmdline.append(' '); cmdline.append(optionallyQuoteField(r.getString(j, null), "\"")); } } cmdline.append('"'); cmds.add(cmdline.toString()); } else { // Add the arguments from previous results... for (int i = 0; i < cmdRows.size(); i++) // Normally just // one row, but // once in a // while to // remain // compatible we // have // multiple. { RowMetaAndData r = (RowMetaAndData) cmdRows.get(i); for (int j = 0; j < r.size(); j++) { cmds.add(optionallyQuoteField(r.getString(j, null), "\"")); } } } } else if (args != null) { // Add the base command... for (int i = 0; i < base.length; i++) cmds.add(base[i]); if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) { // for windows all arguments including the command itself // need to be // included in 1 argument to cmd/command. StringBuffer cmdline = new StringBuffer(300); cmdline.append('"'); if (insertScript) cmdline.append(realScript); else cmdline.append(optionallyQuoteField(KettleVFS.getFilename(fileObject), "\"")); for (int i = 0; i < args.length; i++) { cmdline.append(' '); cmdline.append(optionallyQuoteField(args[i], "\"")); } cmdline.append('"'); cmds.add(cmdline.toString()); } else { for (int i = 0; i < args.length; i++) { cmds.add(args[i]); } } } StringBuffer command = new StringBuffer(); Iterator<String> it = cmds.iterator(); boolean first = true; while (it.hasNext()) { if (!first) command.append(' '); else first = false; command.append((String) it.next()); } if (log.isBasic()) log.logBasic(toString(), Messages.getString("JobShell.ExecCommand", command.toString())); // Build the environment variable list... ProcessBuilder procBuilder = new ProcessBuilder(cmds); Map<String, String> env = procBuilder.environment(); String[] variables = listVariables(); for (int i = 0; i < variables.length; i++) { env.put(variables[i], getVariable(variables[i])); } if (getWorkDirectory() != null && !Const.isEmpty(Const.rtrim(getWorkDirectory()))) { String vfsFilename = environmentSubstitute(getWorkDirectory()); File file = new File(KettleVFS.getFilename(KettleVFS.getFileObject(vfsFilename))); procBuilder.directory(file); } Process proc = procBuilder.start(); // any error message? StreamLogger errorLogger = new StreamLogger(proc.getErrorStream(), toString() + " (stderr)"); // any output? StreamLogger outputLogger = new StreamLogger(proc.getInputStream(), toString() + " (stdout)"); // kick them off new Thread(errorLogger).start(); new Thread(outputLogger).start(); proc.waitFor(); if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobShell.CommandFinished", command.toString())); // What's the exit status? result.setExitStatus(proc.exitValue()); if (result.getExitStatus() != 0) { if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobShell.ExitStatus", environmentSubstitute(getFilename()), "" + result.getExitStatus())); result.setNrErrors(1); } // close the streams // otherwise you get "Too many open files, java.io.IOException" after a lot of iterations proc.getErrorStream().close(); proc.getOutputStream().close(); } catch (IOException ioe) { log.logError(toString(), Messages.getString("JobShell.ErrorRunningShell", environmentSubstitute(getFilename()), ioe.toString())); result.setNrErrors(1); } catch (InterruptedException ie) { log.logError(toString(), Messages.getString("JobShell.Shellinterupted", environmentSubstitute(getFilename()), ie.toString())); result.setNrErrors(1); } catch (Exception e) { log.logError(toString(), Messages.getString("JobShell.UnexpectedError", environmentSubstitute(getFilename()), e.toString())); result.setNrErrors(1); } finally { // If we created a temporary file, remove it... // if (tempFile != null) { try { tempFile.delete(); } catch (Exception e) { Messages.getString("JobShell.UnexpectedError", tempFile.toString(), e.toString()); } } } if (result.getNrErrors() > 0) { result.setResult(false); } else { result.setResult(true); } }
From source file:org.openTwoFactor.client.util.TwoFactorClientCommonUtils.java
/** * <pre>This will execute a command (with args). Under normal operation, * if the exit code of the command is not zero, an exception will be thrown. * If the parameter exceptionOnExitValueNeZero is set to true, the * results of the call will be returned regardless of the exit status. * Example call: execCommand(new String[]{"/bin/bash", "-c", "cd /someFolder; runSomeScript.sh"}, true); * </pre>// www. j a v a2 s.c om * @param arguments are the commands * @param exceptionOnExitValueNeZero if this is set to false, the * results of the call will be returned regardless of the exit status * @return the output text of the command, and the error and return code if exceptionOnExitValueNeZero is false. */ public static CommandResult execCommand(String[] arguments, boolean exceptionOnExitValueNeZero) { Process process = null; StringBuilder commandBuilder = new StringBuilder(); for (int i = 0; i < arguments.length; i++) { commandBuilder.append(arguments[i]).append(" "); } String command = commandBuilder.toString(); if (LOG.isDebugEnabled()) { LOG.debug("Running command: " + command); } StreamGobbler<Object> outputGobbler = null; StreamGobbler<Object> errorGobbler = null; try { process = Runtime.getRuntime().exec(arguments); outputGobbler = new StreamGobbler<Object>(process.getInputStream(), ".out", command); errorGobbler = new StreamGobbler<Object>(process.getErrorStream(), ".err", command); Future<Object> futureOutput = retrieveExecutorService().submit(outputGobbler); Future<Object> futureError = retrieveExecutorService().submit(errorGobbler); try { process.waitFor(); } finally { //finish running these threads try { futureOutput.get(); } finally { //ignore if cant get } try { futureError.get(); } finally { //ignore if cant get } } } catch (Exception e) { LOG.error("Error running command: " + command, e); throw new RuntimeException("Error running command", e); } finally { try { process.destroy(); } catch (Exception e) { } } //was not successful??? if (process.exitValue() != 0 && exceptionOnExitValueNeZero) { String message = "Process exit status=" + process.exitValue() + ": out: " + (outputGobbler == null ? null : outputGobbler.getResultString()) + ", err: " + (errorGobbler == null ? null : errorGobbler.getResultString()); LOG.error(message + ", on command: " + command); throw new RuntimeException(message); } int exitValue = process.exitValue(); return new CommandResult(outputGobbler.getResultString(), errorGobbler.getResultString(), exitValue); }
From source file:StreamFlusher.java
public Object visit(ASTdraw_statement node, Object data) { // one daughter: regexp // KRB: does this make any sense outside of the GUI??? // KRB: review this whole method node.jjtGetChild(0).jjtAccept(this, data); // Should leave an Fst object on the stack (see Fst.java) Fst fst = (Fst) (stack.pop());// ww w. j av a 2 s .c o m // magic numbers for now; limits on the size of a network // that will be drawn long stateLimit = 400L; long arcLimit = 400L; long nstates = lib.NumStates(fst); long narcs = lib.NumArcs(fst); if (nstates > stateLimit) { // don't try to draw it outputInterpMessage("// Fst contains over " + stateLimit + " states, which is generally too much for the dot application to handle.", data); return data; } if (narcs > arcLimit) { // don't try to draw it outputInterpMessage("// Fst contains over " + arcLimit + " arcs, which is generally too much for the dot application to handle.", data); return data; } String userHomeDir = System.getProperty("user.home"); // to find temp files like ~/.kleene/tmp/last.dot // and ~/.kleene/prefs/prefs.xml String osName = getOsName(); // defaults String tmpdir = ""; String prefsPath = ""; String dotSrcPath = ""; String slashSep = "/"; if (osName.equals("windows")) { slashSep = "\\"; // only really needed for command shell (cmd /c), // else can use "/" } StringBuilder sbhex = new StringBuilder(); StringBuilder sb = new StringBuilder(); getSigmaStrings(fst, sbhex, sb); // On Linux and OS X, the basic Kleene directory is ~/.kleene // On Windows, this maps to C:\Documents and Settings\ // \<username>\.kleene tmpdir = userHomeDir + slashSep + ".kleene" + slashSep + "tmp"; dotSrcPath = tmpdir + slashSep + "last.dot"; prefsPath = userHomeDir + slashSep + ".kleene" + slashSep + "prefs" + slashSep + "prefs.xml"; // an FstDotWriter object knows how to write a GraphViz .dot source file (to a specified // file; here written to last.lot in the user's tmp/ directory) FstDotWriter fstDotWriter = new FstDotWriter(symmap, new File(dotSrcPath), sb.toString(), "UTF-8"); // call Fst2dot traverses an OpenFst Fst directly and generates // dot code (by making callbacks to methods in the Java fstDotWriter) lib.Fst2dot(fst, fstDotWriter); // we should now have tmp/last.dot (a GraphViz dot source file // describing a network diagram) // If the osName is "osx" and a native Graphviz.app is installed // in /Applications, then things are simple. Just call Graphviz directly // on the .dot source file. "open -a Graphviz /path/to/last.lot" // No need to generate PostScript and then call a viewer to see it. File nativeGraphviz = new File("/Applications/Graphviz.app"); if (osName.equals("osx") && nativeGraphviz.exists()) { try { Process proc = Runtime.getRuntime().exec("open -a Graphviz " + dotSrcPath); try { if (proc.waitFor() != 0) { System.err.println("Problem calling native OS X GraphViz: exit value " + proc.exitValue()); } } catch (InterruptedException e) { System.err.println(e); } finally { } } catch (Exception e) { System.err.println(e); } } else { // Need to do it the hard way. // // Take the .dot source file and call 'dot' to generate a graphics file, e.g. .ps // Then take the graphics file and call a viewer application // The location of the 'dot' application, the graphics format, and the view // application are specified in the user-specific pref.xml file // Access the user-specific prefs.xml file // type Document is a Java object representing an XML document (typically // read from an XML file into memory) Document doc = null; try { doc = parseXMLPrefs(prefsPath); // parse the user's prefs/prefs.xml } catch (Exception e) { // KRB: review this System.out.println("Problem reading ~/.kleene/prefs/prefs.xml"); e.printStackTrace(); } // Navigate to platform-specific and user-specific dot, format, // viewer elmts in the prefs.xml file // get the path to the "dot" application String dotpath = getPref(doc, "dot/dotpath"); // get the file format the dot should produce, e.g. ps or pdf String dotflag = getPref(doc, "dot/dotflag"); // get the path to the viewer application String dotview = getPref(doc, "dot/viewer"); // Trouble with generating/displaying PDF directly; // If you generate .ps and 'open' it, the orientation=landscape // and center="true" are reflected correctly in the display (the // ps is converted automatically to pdf) // But if you generate the PDF file directly and 'open' it, the // orientation is wrong and the centering command is ignored. // PostScript seems more reliable right now. // ****************** Call 'dot' from Java ********************** // construct the 'dot' command string to be launched by ProcessBuilder // Command shell prefix needed for ProcessBuilder is opsys-specific. String cmdShell, cmdShellOpts; if (osName.equals("windows")) { cmdShell = "cmd"; cmdShellOpts = "/c"; } else { // for Linux and OS X (valued of osName will be "osx") cmdShell = "/bin/sh"; cmdShellOpts = "-c"; } // Use doublequotes to support filenames with embedded spaces. // Initial blank prevents undesired doublequote removal by // Windows cmd.exe (see "cmd /?"). String cmd = " \"" + dotpath + "\"" + " -T" + dotflag + " \"" + tmpdir + slashSep + "last.dot\"" + " > " + "\"" + tmpdir + slashSep + "last." + dotflag + "\""; // calling 'dot' from Java, from the .dot source file, // it should generate a graphics file, e.g. .ps (PostScript) try { ProcessBuilder pb = new ProcessBuilder(cmdShell, cmdShellOpts, cmd); Process p = pb.start(); StreamFlusher errorFlusher = new StreamFlusher(p.getErrorStream(), "ERROR"); StreamFlusher outputFlusher = new StreamFlusher(p.getInputStream(), "OUTPUT"); errorFlusher.start(); outputFlusher.start(); int exitVal = p.waitFor(); } catch (Exception e) { e.printStackTrace(); } // ******************* Now launch the viewer app from Java //KRB: putting double quotes around dotview currently // works for Linux, at least // with the current default dotview string: /usr/bin/kghostview // which doesn't contain command-line options if (osName.equals("osx")) { // KRB: putting double quotes around dotview breaks // drawing for OS X, // where the dotview string is // /usr/bin/open -a /Applications/Preview.app/Contents/MacOS/Preview // (having three fields and two spaces) cmd = dotview + " \"" + tmpdir + slashSep + "last." + dotflag + "\""; } else { // Phil: fix for Windows (and seems to work for Linux) // Use doublequotes to support filenames with embedded spaces. // Initial blank prevents undesired doublequote removal by Windows cmd.exe (see "cmd /?"). cmd = " \"" + dotview + "\" \"" + tmpdir + slashSep + "last." + dotflag + "\""; } // launching the viewer on the ps, pdf (or whatever) file generated by 'dot' try { ProcessBuilder pb = new ProcessBuilder(cmdShell, cmdShellOpts, cmd); Process p = pb.start(); StreamFlusher errorFlusher = new StreamFlusher(p.getErrorStream(), "ERROR"); StreamFlusher outputFlusher = new StreamFlusher(p.getInputStream(), "OUTPUT"); errorFlusher.start(); outputFlusher.start(); // if active, this stmt causes the viewer window to be 'modal', causing // Kleene to suspend operations until the viewer is closed //int exitVal = p.waitFor() ; } catch (Exception e) { e.printStackTrace(); } // need to drain stdout stderr and inputStream in separate threads? } return data; }
From source file:com.clark.func.Functions.java
/** * Performs the os command.//from w ww . j a v a 2 s . c om * * @param cmdAttribs * the command line parameters * @param max * The maximum limit for the lines returned * @param timeout * The timout amount in milliseconds or no timeout if the value * is zero or less * @return the parsed data * @throws IOException * if an error occurs */ static List<String> performCommand(String[] cmdAttribs, int max, long timeout) throws IOException { // this method does what it can to avoid the 'Too many open files' error // based on trial and error and these links: // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692 // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4801027 // http://forum.java.sun.com/thread.jspa?threadID=533029&messageID=2572018 // however, its still not perfect as the JDK support is so poor // (see commond-exec or ant for a better multi-threaded multi-os // solution) List<String> lines = new ArrayList<String>(20); Process proc = null; InputStream in = null; OutputStream out = null; InputStream err = null; BufferedReader inr = null; try { Thread monitor = ThreadMonitor.start(timeout); proc = openProcess(cmdAttribs); in = proc.getInputStream(); out = proc.getOutputStream(); err = proc.getErrorStream(); inr = new BufferedReader(new InputStreamReader(in)); String line = inr.readLine(); while (line != null && lines.size() < max) { line = line.toLowerCase(Locale.ENGLISH).trim(); lines.add(line); line = inr.readLine(); } proc.waitFor(); ThreadMonitor.stop(monitor); if (proc.exitValue() != 0) { // os command problem, throw exception throw new IOException("Command line returned OS error code '" + proc.exitValue() + "' for command " + Arrays.asList(cmdAttribs)); } if (lines.size() == 0) { // unknown problem, throw exception throw new IOException( "Command line did not return any info " + "for command " + Arrays.asList(cmdAttribs)); } return lines; } catch (InterruptedException ex) { throw new IOExceptionWithCause("Command line threw an InterruptedException " + "for command " + Arrays.asList(cmdAttribs) + " timeout=" + timeout, ex); } finally { closeQuietly(in); closeQuietly(out); closeQuietly(err); closeQuietly(inr); if (proc != null) { proc.destroy(); } } }