List of usage examples for java.lang Process exitValue
public abstract int exitValue();
From source file:com.orange.clara.cloud.servicedbdumper.integrations.AbstractIntegrationTest.java
protected void runCommand(String[] command, boolean showStdout) throws IOException, InterruptedException { Process process = null; if (showStdout) { process = this.runCommandLineWithStdoutShowed(command); } else {/* w w w . ja v a2s . c o m*/ process = this.runCommandLine(command); } process.waitFor(); if (process.exitValue() != 0) { throw this.generateInterruptedExceptionFromProcess(process); } }
From source file:org.gbif.ocurrence.index.solr.SolrRecordWriter.java
private Path findSolrConfig(Configuration conf) throws IOException { Path solrHome = null;//from ww w.ja va 2 s.com Path[] localArchives = DistributedCache.getLocalCacheArchives(conf); if (localArchives.length == 0) { throw new IOException(String.format("No local cache archives, where is %s:%s", SolrOutputFormat.getSetupOk(), SolrOutputFormat.getZipName(conf))); } for (Path unpackedDir : localArchives) { // Only logged if debugging if (LOG.isDebugEnabled()) { LOG.debug(String.format("Examining unpack directory %s for %s", unpackedDir, SolrOutputFormat.getZipName(conf))); ProcessBuilder lsCmd = new ProcessBuilder( new String[] { "/bin/ls", "-lR", unpackedDir.toString() }); lsCmd.redirectErrorStream(); Process ls = lsCmd.start(); try { byte[] buf = new byte[16 * 1024]; InputStream all = ls.getInputStream(); int count; while ((count = all.read(buf)) > 0) { System.err.write(buf, 0, count); } } catch (IOException ignore) { } System.err.format("Exit value is %d%n", ls.exitValue()); } if (unpackedDir.getName().equals(SolrOutputFormat.getZipName(conf))) { solrHome = unpackedDir; break; } } return solrHome; }
From source file:org.mashupmedia.encode.ProcessManager.java
public String callProcess(List<String> commands) throws IOException { logger.info("Starting process..."); ProcessBuilder processBuilder = new ProcessBuilder(commands); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); InputStream inputStream = process.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line;// w w w .ja v a2s . c o m StringBuilder outputBuilder = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { logger.info(line); outputBuilder.append(line); } IOUtils.closeQuietly(inputStream); try { int waitForValue = process.waitFor(); logger.info("Process waitFor value = " + waitForValue); } catch (InterruptedException e) { logger.error("Error waiting for waitFor.", e); } int exitValue = process.exitValue(); logger.info("Process exit value = " + exitValue); return outputBuilder.toString(); }
From source file:org.ednovo.gooru.converter.service.ConversionServiceImpl.java
@Override public void resizeImage(String command, String logFile) { logger.info("Runtime Executor .... Initializing..."); try {// ww w . j av a2 s. c om command = StringUtils.replace(command, "/usr/bin/convert", "/usr/bin/gm@convert"); String cmdArgs[] = applyTemporaryFixForPath(command.split("@")); Process thumsProcess = Runtime.getRuntime().exec(cmdArgs); thumsProcess.waitFor(); String line; StringBuffer sb = new StringBuffer(); BufferedReader in = new BufferedReader(new InputStreamReader(thumsProcess.getInputStream())); while ((line = in.readLine()) != null) { sb.append(line).append("\n"); } in.close(); logger.info("output : {} - Status : {} - Command : " + StringUtils.join(cmdArgs, " "), sb.toString(), thumsProcess.exitValue() + ""); if (logFile != null) { FileUtils.writeStringToFile(new File(logFile), "Completed"); } } catch (Exception e) { logger.error("something went wrong while converting image", e); } }
From source file:org.atemsource.dojo.build.DojoBuildMojo.java
private void execute(List<String> params) throws IOException, MojoExecutionException, InterruptedException { ProcessBuilder processBuilder = new ProcessBuilder(); processBuilder.directory(workDir);//from w w w . j a v a2 s . c o m processBuilder.command(params); Process process = processBuilder.start(); InputStream in = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); InputStream ein = process.getErrorStream(); BufferedReader ereader = new BufferedReader(new InputStreamReader(ein)); boolean finished = false; do { if (reader.ready()) { String line = reader.readLine(); if (line != null) { System.out.println(line); } } else if (ereader.ready()) { String line = ereader.readLine(); if (line != null) { System.err.println(line); } } else { try { int exit = process.exitValue(); if (exit != 0) { throw new MojoExecutionException("dojo build ended with exit code " + exit); } else { finished = true; } } catch (IllegalThreadStateException e) { } Thread.sleep(100); } } while (!finished); }
From source file:de.berg.systeme.jenkins.wix.WixCommand.java
/** * executes command and parses the output checking for errors. * @return true if execution was successful otherwise false. * @throws Exception//from w ww.java 2s. c o m * @throws ToolsetException */ public boolean execute() throws Exception, ToolsetException { // false berschreibt immer true boolean success = true; String line = null; this.createCommand(); Process p = Runtime.getRuntime().exec(cmd.toString()); BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream())); // Log stdout of executable while ((line = stdout.readLine()) != null) { lg.log(line); success &= checkForErrors(line); } stdout.close(); // Log stderr of executable while ((line = stderr.readLine()) != null) { lg.log(line); success &= checkForErrors(line); } stderr.close(); // Wait for the process to end p.waitFor(); success &= (p.exitValue() > 0); return !success; // inverted logic at this point }
From source file:jeplus.EPlusWinTools.java
public static boolean runVersionTransition(String fromVer, String toVer, String binfolder, String listfile, PrintStream logstream) {//from w w w.j a v a 2s . c o m boolean ok = true; try { Process EPProc; // Run EnergyPlus ExpandObjects String CmdLine = binfolder + File.separator + "Transition-" + fromVer + "-to-" + toVer + " \"" + listfile + "\""; EPProc = Runtime.getRuntime().exec(CmdLine, null, new File(binfolder)); try (BufferedReader ins = new BufferedReader(new InputStreamReader(EPProc.getInputStream()))) { if (logstream != null) { logstream.println("Calling VersionTransition with Command line: " + binfolder + ">" + CmdLine); String res = ins.readLine(); while (res != null) { logstream.println(res); res = ins.readLine(); } } else { int res = ins.read(); while (res != -1) { res = ins.read(); } } } EPProc.waitFor(); int ExitValue = EPProc.exitValue(); if (logstream != null) { logstream.println("Exit value = " + ExitValue); logstream.println(); } } catch (IOException | InterruptedException ex) { logger.error("", ex); ok = false; } return ok; }
From source file:com.photon.phresco.plugins.xcode.XcodeBuild.java
/** * Execute the xcode command line utility. */// w w w . j a v a2 s . c o m public void execute() throws MojoExecutionException { if (!xcodeCommandLine.exists()) { throw new MojoExecutionException( "Invalid path, invalid xcodebuild file: " + xcodeCommandLine.getAbsolutePath()); } /* * // Compute archive name String archiveName = * project.getBuild().getFinalName() + ".cust"; File finalDir = new * File(buildDirectory, archiveName); * * // Configure archiver MavenArchiver archiver = new MavenArchiver(); * archiver.setArchiver(jarArchiver); archiver.setOutputFile(finalDir); */ try { if (!SdkVerifier.isAvailable(sdk)) { throw new MojoExecutionException("Selected version " + sdk + " is not available!"); } } catch (IOException e2) { throw new MojoExecutionException("SDK verification failed!"); } catch (InterruptedException e2) { throw new MojoExecutionException("SDK verification interrupted!"); } try { init(); configure(); ProcessBuilder pb = new ProcessBuilder(xcodeCommandLine.getAbsolutePath()); // Include errors in output pb.redirectErrorStream(true); List<String> commands = pb.command(); if (xcodeProject != null) { commands.add("-project"); commands.add(xcodeProject); } if (StringUtils.isNotBlank(configuration)) { commands.add("-configuration"); commands.add(configuration); } if (StringUtils.isNotBlank(sdk)) { commands.add("-sdk"); commands.add(sdk); } commands.add("OBJROOT=" + buildDirectory); commands.add("SYMROOT=" + buildDirectory); commands.add("DSTROOT=" + buildDirectory); if (StringUtils.isNotBlank(xcodeTarget)) { commands.add("-target"); commands.add(xcodeTarget); } if (StringUtils.isNotBlank(gccpreprocessor)) { commands.add("GCC_PREPROCESSOR_DEFINITIONS=" + gccpreprocessor); } if (unittest) { commands.add("clean"); commands.add("build"); } getLog().info("List of commands" + pb.command()); // pb.command().add("install"); pb.directory(new File(basedir)); Process child = pb.start(); // Consume subprocess output and write to stdout for debugging InputStream is = new BufferedInputStream(child.getInputStream()); int singleByte = 0; while ((singleByte = is.read()) != -1) { // output.write(buffer, 0, bytesRead); System.out.write(singleByte); } child.waitFor(); int exitValue = child.exitValue(); getLog().info("Exit Value: " + exitValue); if (exitValue != 0) { throw new MojoExecutionException("Compilation error occured. Resolve the error(s) and try again!"); } if (!unittest) { //In case of unit testcases run, the APP files will not be generated. createdSYM(); createApp(); } /* * child.waitFor(); * * InputStream in = child.getInputStream(); InputStream err = * child.getErrorStream(); getLog().error(sb.toString()); */ } catch (IOException e) { getLog().error("An IOException occured."); throw new MojoExecutionException("An IOException occured", e); } catch (InterruptedException e) { getLog().error("The clean process was been interrupted."); throw new MojoExecutionException("The clean process was been interrupted", e); } catch (MojoFailureException e) { // TODO Auto-generated catch block e.printStackTrace(); } File directory = new File(this.basedir + "/pom.xml"); this.project.getArtifact().setFile(directory); }
From source file:gui.sqlmap.SqlmapUi.java
private void startSqlmap() { String python = textfieldPython.getText(); String workingDir = textfieldWorkingdir.getText(); String sqlmap = textfieldSqlmap.getText(); // Do some basic tests File f;// www . j a v a 2 s . co m f = new File(python); if (!f.exists()) { JOptionPane.showMessageDialog(this, "Python path does not exist: " + python); return; } f = new File(workingDir); if (!f.exists()) { JOptionPane.showMessageDialog(this, "workingDir path does not exist: " + workingDir); return; } f = new File(sqlmap); if (!f.exists()) { JOptionPane.showMessageDialog(this, "sqlmap path does not exist: " + sqlmap); return; } // Write request file String requestFile = workingDir + "request.txt"; try { FileOutputStream fos = new FileOutputStream(requestFile); fos.write(httpMessage.getRequest()); fos.close(); } catch (IOException e) { JOptionPane.showMessageDialog(this, "could not write request: " + workingDir + "request.txt"); BurpCallbacks.getInstance().print("Error: " + e.getMessage()); } // Start sqlmap args = new ArrayList<String>(); args.add(python); args.add(sqlmap); args.add("-r"); args.add(requestFile); args.add("--batch"); args.add("-p"); args.add(attackParam.getName()); String sessionFile = workingDir + "sessionlog.txt"; args.add("-s"); args.add(sessionFile); args.add("--flush-session"); String traceFile = workingDir + "tracelog.txt"; args.add("-t"); args.add(traceFile); args.add("--disable-coloring"); args.add("--cleanup"); textareaCommand.setText(StringUtils.join(args, " ")); SwingWorker worker = new SwingWorker<String, Void>() { @Override public String doInBackground() { ProcessBuilder pb = new ProcessBuilder(args); //BurpCallbacks.getInstance().print(pb.command().toString()); pb.redirectErrorStream(true); Process proc; try { proc = pb.start(); InputStream is = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; int exit = -1; while ((line = br.readLine()) != null) { // Outputs your process execution addLine(line); try { exit = proc.exitValue(); if (exit == 0) { // Process finished } } catch (IllegalThreadStateException t) { // The process has not yet finished. // Should we stop it? //if (processMustStop()) // processMustStop can return true // after time out, for example. //{ // proc.destroy(); //} } } } catch (IOException ex) { BurpCallbacks.getInstance().print(ex.getLocalizedMessage()); } return ""; } @Override public void done() { } }; worker.execute(); }
From source file:dk.netarkivet.common.utils.ProcessUtils.java
/** Wait for the end of a process, but only for a limited time. This * method takes care of the ways waitFor can get interrupted. * * @param p Process to wait for/*from w ww. j a v a2 s . c om*/ * @param maxWait The maximum number of milliseconds to wait for the * process to exit. * @return Exit value for process, or null if the process didn't exit * within the expected time. */ public static Integer waitFor(final Process p, long maxWait) { ArgumentNotValid.checkNotNull(p, "Process p"); ArgumentNotValid.checkPositive(maxWait, "long maxWait"); long startTime = System.currentTimeMillis(); Timer timer = new Timer(true); final Thread waitThread = Thread.currentThread(); boolean wakeupScheduled = false; final AtomicBoolean doneWaiting = new AtomicBoolean(false); while (System.currentTimeMillis() < startTime + maxWait) { try { if (!wakeupScheduled) { // First time in here, we need to start the wakup thread, // but be sure it doesn't notify us too early or too late. synchronized (waitThread) { timer.schedule(new TimerTask() { public void run() { synchronized (waitThread) { if (!doneWaiting.get()) { waitThread.interrupt(); } } } }, maxWait); wakeupScheduled = true; } } p.waitFor(); break; } catch (InterruptedException e) { // May happen for a number of reasons. We just check if we've // timed out yet when we go through the loop again. } } synchronized (waitThread) { timer.cancel(); doneWaiting.set(true); Thread.interrupted(); // In case the timer task interrupted. } try { return p.exitValue(); } catch (IllegalThreadStateException e) { log.warn("Process '" + p + "' did not exit within " + (System.currentTimeMillis() - startTime) + " milliseconds"); return null; } }