List of usage examples for java.lang Process exitValue
public abstract int exitValue();
From source file:com.netscape.cms.profile.constraint.ExternalProcessConstraint.java
public void validate(IRequest request, X509CertInfo info) throws ERejectException { CMS.debug("About to execute command: " + this.executable); ProcessBuilder pb = new ProcessBuilder(this.executable); // set up process environment Map<String, String> env = pb.environment(); for (String k : envVars.keySet()) { String v = request.getExtDataInString(envVars.get(k)); if (v != null) env.put(k, v);/* ww w . j av a2 s . c o m*/ } for (String k : extraEnvVars.keySet()) { String v = request.getExtDataInString(extraEnvVars.get(k)); if (v != null) env.put(k, v); } Process p; String stdout = ""; String stderr = ""; boolean timedOut; try { p = pb.start(); timedOut = !p.waitFor(timeout, TimeUnit.SECONDS); if (timedOut) p.destroyForcibly(); else stdout = IOUtils.toString(p.getInputStream()); stderr = IOUtils.toString(p.getErrorStream()); } catch (Throwable e) { String msg = "Caught exception while executing command: " + this.executable; CMS.debug(msg); CMS.debug(e); throw new ERejectException(msg, e); } if (timedOut) throw new ERejectException("Request validation timed out"); int exitValue = p.exitValue(); CMS.debug("ExternalProcessConstraint: exit value: " + exitValue); CMS.debug("ExternalProcessConstraint: stdout: " + stdout); CMS.debug("ExternalProcessConstraint: stderr: " + stderr); if (exitValue != 0) throw new ERejectException(stdout); }
From source file:org.apache.hadoop.hive.metastore.dbinstall.DbInstallBase.java
private ProcessResults runCmd(String[] cmd, long secondsToWait) throws IOException, InterruptedException { LOG.info("Going to run: " + StringUtils.join(cmd, " ")); Process proc = Runtime.getRuntime().exec(cmd); if (!proc.waitFor(secondsToWait, TimeUnit.SECONDS)) { throw new RuntimeException("Process " + cmd[0] + " failed to run in " + secondsToWait + " seconds"); }/*from www. ja va 2 s . c o m*/ BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream())); final StringBuilder lines = new StringBuilder(); reader.lines().forEach(s -> lines.append(s).append('\n')); reader = new BufferedReader(new InputStreamReader(proc.getErrorStream())); final StringBuilder errLines = new StringBuilder(); reader.lines().forEach(s -> errLines.append(s).append('\n')); return new ProcessResults(lines.toString(), errLines.toString(), proc.exitValue()); }
From source file:com.netflix.genie.server.jobmanager.impl.JobManagerImpl.java
/** * {@inheritDoc}//from w w w . j a va 2s . co m */ @Override public void kill() throws GenieException { LOG.info("called"); if (!this.initCalled) { throw new GeniePreconditionException("Init wasn't called. Unable to continue."); } // check to ensure that the process id is actually set (which means job // was launched) final int processId = this.job.getProcessHandle(); if (processId > 0) { LOG.info("Attempting to kill the process " + processId); try { final String genieHome = ConfigurationManager.getConfigInstance() .getString("com.netflix.genie.server.sys.home"); if (genieHome == null || genieHome.isEmpty()) { final String msg = "Property com.netflix.genie.server.sys.home is not set correctly"; LOG.error(msg); throw new GenieServerException(msg); } final Process killProcessId = Runtime.getRuntime() .exec(genieHome + File.separator + "jobkill.sh " + processId); int returnCode = 1; int counter = 0; while (counter < 3) { counter++; try { returnCode = killProcessId.exitValue(); LOG.info("Kill script finished"); break; } catch (IllegalThreadStateException e) { LOG.info("Kill script not finished yet. Will retry"); try { Thread.sleep(1000); } catch (InterruptedException e1) { LOG.info("Sleep interrupted. Ignoring."); } } } if (returnCode != 0) { throw new GenieServerException("Failed to kill the job"); } } catch (final GenieException | IOException e) { final String msg = "Failed to kill the job"; LOG.error(msg, e); throw new GenieServerException(msg, e); } } else { final String msg = "Could not get process id"; LOG.error(msg); throw new GenieServerException(msg); } }
From source file:org.apache.oodt.cas.workflow.misc.WingsTask.java
public void run(Metadata metadata, WorkflowTaskConfiguration config) { Properties props = config.getProperties(); // Component Info String compid = props.getProperty("COMPONENT_ID"); String tname = props.getProperty("TASKNAME"); String jobid = props.getProperty("JOBID"); String argstring = props.getProperty("ARGUMENT"); ArrayList<String> inputs = fetchFromProps(props, "INPUT"); ArrayList<String> outputs = fetchFromProps(props, "OUTPUT"); // Following paths should be Shared across the cluster //String script = props.getProperty("SCRIPT_PATH"); String origjobdir = props.getProperty("JOB_DIR"); String jobdir = origjobdir;//from www .j a v a 2s. c om //String datadir = props.getProperty("DATA_DIR"); // File Manager Access String fmurl = props.getProperty("FM_URL"); String fmprefix = props.getProperty("FM_PREFIX"); // Logging specific info String logfile = props.getProperty("LOGFILE"); String wlogfile = props.getProperty("W_LOGFILE"); String tplid = wlogfile.replace(".log", ""); PrintStream wlogout = null; PrintStream logout = null; XmlRpcFileManagerClient fmclient = null; try { fmclient = new XmlRpcFileManagerClient(new URL(fmurl)); DataTransfer dt = new RemoteDataTransferFactory().createDataTransfer(); dt.setFileManagerUrl(new URL(fmurl)); // Check if outputs already exist in the file manager boolean outputs_already_present = true; for (String op : outputs) { String prodid = fmprefix + op; Product prod = null; try { prod = fmclient.getProductById(prodid); } catch (Exception e) { } if (prod == null) { outputs_already_present = false; } } // If outputs already present, no need to execute if (outputs_already_present) return; File tmpdir = File.createTempFile("oodt-run-", ""); if (tmpdir.delete() && tmpdir.mkdirs()) jobdir = tmpdir.getAbsolutePath() + File.separator; argstring = argstring.replace(origjobdir, jobdir); wlogout = new PrintStream(new FileOutputStream(jobdir + wlogfile, true)); logout = new PrintStream(jobdir + logfile); wlogout.println(jobid + " (" + tname + "): RUNNING"); wlogout.close(); this.uploadProduct(wlogfile, wlogfile, "GenericFile", new File(jobdir + wlogfile), new Metadata(), fmclient); wlogout = new PrintStream(new FileOutputStream(jobdir + wlogfile, true)); logout.println("[INFO]: Component Initializing"); logout.println(tname + " " + argstring); // Fetch input files from file manager if not already present in directory for (String ip : inputs) { File f = new File(jobdir + ip); if (!f.exists()) { logout.println("[INFO] Fetching Input from File Manager: " + ip); Product prod = fmclient.getProductById(fmprefix + ip); prod.setProductReferences(fmclient.getProductReferences(prod)); dt.retrieveProduct(prod, new File(jobdir)); } } logout.flush(); // Fetch component from file manager File compdir = new File(jobdir + File.separator + "comp"); compdir.mkdir(); Product cprod = fmclient.getProductById(compid); cprod.setProductReferences(fmclient.getProductReferences(cprod)); dt.retrieveProduct(cprod, compdir); String scriptPath = null; for (File czip : compdir.listFiles()) { if (czip.getName().endsWith(".zip")) { this.unZipIt(czip.getAbsolutePath(), compdir.getAbsolutePath()); File tmpf = new File(compdir.getAbsolutePath() + File.separator + "run"); if (!tmpf.exists()) tmpf = new File(compdir.getAbsolutePath() + File.separator + "run.bat"); scriptPath = tmpf.getAbsolutePath(); } else scriptPath = czip.getAbsolutePath(); } File scriptf = new File(scriptPath); scriptf.setExecutable(true); // Create command execution ArrayList<String> command = new ArrayList<String>(); command.add(scriptf.getAbsolutePath()); for (String s : argstring.split(" ")) { command.add(s); } ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(jobdir)); builder.redirectErrorStream(true); final Process process = builder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { logout.println(line); } process.waitFor(); int exitStatus = process.exitValue(); if (exitStatus != 0) throw new Exception("[ERROR] Component failed with a non-zero exit code"); // Ingest output files to file manager for (String op : outputs) { File f = new File(jobdir + op); File metf = new File(jobdir + op + ".met"); HashMap<String, String> cmeta = new HashMap<String, String>(); if (metf.exists()) { for (Object ln : FileUtils.readLines(metf)) { String metline = (String) ln; String[] kv = metline.split("\\s*=\\s*"); if (kv.length == 2) cmeta.put(kv[0], kv[1]); } } if (!f.exists()) throw new Exception("[ERROR] Missing Output " + op); if (f.exists()) { logout.println("[INFO] Putting Output into File Manager: " + op); // Get Output Metadata & Product Type String typeid = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"; Metadata meta = metadata.getSubMetadata(op); String prodtypeid = meta.getMetadata(typeid); meta.removeMetadata(typeid); // Override metadata with custom metadata (if any) for (String key : meta.getAllKeys()) { String[] nsname = key.split("#"); if (nsname.length == 2) { if (cmeta.containsKey(nsname[1])) { meta.removeMetadata(key); meta.addMetadata(key, cmeta.get(nsname[1])); } } } // Upload output to file manager String prodid = fmprefix + op; this.uploadProduct(prodid, op, prodtypeid, f, meta, fmclient); } if (metf.exists()) { String metname = op + ".met"; String prodid = fmprefix + metname; this.uploadProduct(prodid, metname, "GenericFile", metf, new Metadata(), fmclient); } } logout.println("SUCCESS: Component finished successfully !"); logout.close(); wlogout.println(jobid + " (" + tname + "): SUCCESS"); wlogout.close(); } catch (Exception e) { if (logout != null) { logout.println(e.getMessage()); logout.println("FAILURE: Component Failed"); logout.close(); wlogout.println(jobid + " (" + tname + "): FAILURE"); wlogout.close(); } } try { if (fmclient != null) { this.uploadProduct(wlogfile, wlogfile, "GenericFile", new File(jobdir + wlogfile), new Metadata(), fmclient); String logid = tplid + "-" + logfile; this.uploadProduct(logid, logid, "GenericFile", new File(jobdir + logfile), new Metadata(), fmclient); } } catch (CatalogException e) { e.printStackTrace(); } catch (RepositoryManagerException e) { e.printStackTrace(); } }
From source file:com.liferay.petra.doulos.processor.BaseShellDoulosRequestProcessor.java
protected void execute(ShellStatus shellStatus) throws Exception { shellStatus.status = "executing"; List<String> shellCommandsList = getShellCommands(shellStatus); shellCommandsList.add(0, "/bin/bash"); shellCommandsList.add(1, "-x"); shellCommandsList.add(2, "-c"); String[] shellCommands = shellCommandsList.toArray(new String[shellCommandsList.size()]); shellStatus.shellCommands = StringUtils.join(shellCommands, "\n"); ProcessBuilder processBuilder = new ProcessBuilder(shellCommands); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); StringBuilder sb = new StringBuilder(); String line = null;//from w w w. j av a 2s . com BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); while ((line = bufferedReader.readLine()) != null) { sb.append(line); sb.append("\n"); } bufferedReader.close(); try { if (_log.isDebugEnabled()) { _log.debug("Wait for process to finish"); } process.waitFor(); shellStatus.exitValue = String.valueOf(process.exitValue()); shellStatus.output = sb.toString(); shellStatus.status = "finished"; } catch (Exception e) { Writer writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); e.printStackTrace(printWriter); shellStatus.exception = writer.toString(); shellStatus.status = "exception"; } }
From source file:ch.zhaw.iamp.rct.Controller.java
/** * Starts the simulation by invoking a new process of the physics control * toolbox./*from w w w . ja va 2s .c o m*/ */ public void runSimulation() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { System.out.println("[J] Invoking simulation."); int processExitValue = SIMULATOR_INVOCATION_PROBLEM_EXIT_CODE; try { verifyBinaryState(); Process process = Runtime.getRuntime().exec(getAssembledCommand()); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } process.waitFor(); processExitValue = process.exitValue(); } catch (IOException | InterruptedException ex) { System.out.println("[J] The process led to an exception: " + ex.getMessage()); Dialogs.showErrorPane(mainWindow, "Error", "<html>Could not invoke the Physics Toolbox:<br />" + ex.getMessage() + "</html>"); } System.out.println("[J] Simulation ended with the exit code " + processExitValue + "."); if (processExitValue == SIMULATOR_INVOCATION_PROBLEM_EXIT_CODE) { System.out.println("[J] The exit code is associated with " + "SIMULATOR_INVOCATION_PROBLEM_EXIT_CODE. Please " + "check if there is anything wrong with the " + "environment what could have let to an invocation " + "problem of the mariumapp executable."); } mainWindow.configureGuiForRunningPhase(false); } }); }
From source file:org.apache.sling.testing.serversetup.jarexec.ShutdownHookSingleProcessDestroyer.java
public void destroyProcess(boolean waitForIt) { Process toDestroy = null; synchronized (this) { toDestroy = process;//from w w w. j av a2 s. c om process = null; } if (toDestroy == null) { return; } toDestroy.destroy(); if (waitForIt) { log.info("Waiting for destroyed process {} to exit (timeout={} seconds)", processInfo, timeoutSeconds); final Thread mainThread = Thread.currentThread(); final Timer t = new Timer(true); final TimerTask task = new TimerTask() { @Override public void run() { mainThread.interrupt(); } }; t.schedule(task, timeoutSeconds * 1000L); try { toDestroy.waitFor(); try { final int exit = toDestroy.exitValue(); log.info("Process {} ended with exit code {}", processInfo, exit); } catch (IllegalStateException ise) { log.error("Failed to destroy process " + processInfo); } } catch (InterruptedException e) { log.error("Timeout waiting for process " + processInfo + " to exit"); } finally { t.cancel(); } } }
From source file:org.scantegrity.scanner.ScannerController.java
/** * Return a ballot image from the scanner. The scan is in duplex, so this * will always return an array of size 2. The elements inside *may* be null, * however.// ww w . j av a 2 s. c o m * * @return * @throws IOException */ public BufferedImage[] getImagesFromScanner() throws IOException { Process l_p; int l_pid = 0; String l_cmd = c_binpath + c_scanimgcmd + " " + c_inpath + c_scanopts; //Execute the scan command l_p = Runtime.getRuntime().exec(l_cmd); l_pid = getPid(c_scanimgcmd); if (l_pid == 0) { try { l_p.exitValue(); } catch (IllegalThreadStateException l_e) { c_log.log(Level.WARNING, c_binpath + c_scanimgcmd + " failed to exec." + getErrorMsg(l_p)); } l_pid = -1; } synchronized (this) { //Wait for it to end. int l_hang = 0; do { for (int l_i = 0; l_i < c_timeout; l_i += 200) { if (l_pid != getPid(c_scanimgcmd)) break; try { wait(200); } catch (InterruptedException e) { //do nothing. } } // If it's still alive after 3s send a signal to it // to see if it's still responding. if (l_pid == getPid(c_scanimgcmd)) { // If it doesn't respond and it's still running kill the // process and throw an error (which should cause us to // try again) if (!isAlive(l_pid)) { c_log.log(Level.WARNING, c_scanimgcmd + " did not die."); killPid(l_pid); } else { //Countdown, if it's still going after 12s, do something if (l_hang >= c_hangup) { killPid(l_pid); break; } else { l_hang += c_timeout; } } } } while (l_pid == getPid(c_scanimgcmd)); // Java does not close these streams, so we need to do that here // to prevent too many open files error closeProcess(l_p); } //try to read in the images BufferedImage l_imgs[] = new BufferedImage[2]; for (int l_i = 0; l_i < 2; l_i++) { try { File l_imgFile = new File(c_inpath + String.format(c_scanfmt, l_i + 1)); if (l_imgFile.exists()) { try { RenderedOp l_op = JAI.create("FileLoad", l_imgFile.getAbsolutePath()); l_imgs[l_i] = l_op.createInstance().getAsBufferedImage(); } catch (Exception l_e) { l_imgs[l_i] = null; c_log.log(Level.WARNING, "Read Error: " + l_e.getMessage()); //Handle the error image by moving it } //Delete or move the scanned image after reading. try { if (l_imgs[l_i] == null) { FileUtils.copyFile(l_imgFile, new File(c_outpath + "readerror-" + c_err + ".tiff")); c_err++; } if (c_delete) { FileUtils.forceDelete(l_imgFile); } else { FileUtils.copyFile(l_imgFile, new File(c_outpath)); FileUtils.forceDelete(l_imgFile); } } catch (Exception l_e) { c_log.log(Level.WARNING, "Unable to move or delete the" + " ballot image file.. Changing the" + " scanformat name."); c_suffix++; c_scanopts += "-" + c_suffix; c_scanfmt += "-" + c_suffix; } } else { l_imgs[l_i] = null; c_log.log(Level.FINE, "Could not read " + l_imgFile.getName()); //IT does not exist, so we can't move it. } } catch (Exception l_e) { //Couldn't even open it... l_imgs[l_i] = null; c_log.log(Level.WARNING, "Error: " + l_e.getMessage()); } } //If we failed, check the return value. Log it. if (l_imgs == null || (l_imgs[0] == null && l_imgs[1] == null)) { int l_err = l_p.exitValue(); switch (l_err) { case 0: case 7: //This is the "out of documents" error. break; default: c_log.log(Level.WARNING, "Scanner exited with error code " + l_err + "\n Message: " + getErrorMsg(l_p)); break; } } return l_imgs; }
From source file:org.opencb.cellbase.app.transform.VariationParser.java
private void sortFileByNumericColumn(Path inputFile, Path outputFile, int columnIndex) throws InterruptedException, IOException { this.logger.info("Sorting file " + inputFile + " into " + outputFile + " ..."); // increment column index by 1, beacause Java indexes are 0-based and 'sort' command uses 1-based indexes columnIndex++;/*from ww w .j a va 2s. c o m*/ ProcessBuilder pb = new ProcessBuilder("sort", "-t", "\t", "-k", Integer.toString(columnIndex), "-n", "--stable", inputFile.toAbsolutePath().toString(), "-T", variationDirectoryPath.toString(), "-o", outputFile.toAbsolutePath().toString()); // System.getProperty("java.io.tmpdir") this.logger.debug("Executing '" + StringUtils.join(pb.command(), " ") + "' ..."); Stopwatch stopwatch = Stopwatch.createStarted(); Process process = pb.start(); process.waitFor(); int returnedValue = process.exitValue(); if (returnedValue != 0) { String errorMessage = IOUtils.toString(process.getErrorStream()); logger.error("Error sorting " + inputFile); logger.error(errorMessage); throw new RuntimeException("Error sorting " + inputFile); } this.logger.info("Sorted"); this.logger.debug("Elapsed time sorting file: " + stopwatch); }