List of usage examples for java.lang Process getErrorStream
public abstract InputStream getErrorStream();
From source file:com.sap.prd.mobile.ios.mios.PListAccessor.java
public String printValue(String key) throws IOException { try {// w w w. j a v a2 s. co m String command = "/usr/libexec/PlistBuddy -c \"Print :" + key + "\" \"" + plist.getAbsolutePath() + "\""; System.out.println("[INFO] PlistBuddy Add command is: '" + command + "'."); String[] args = new String[] { "bash", "-c", command }; Process p = Runtime.getRuntime().exec(args); InputStream is = p.getInputStream(); p.waitFor(); int exitValue = p.exitValue(); if (exitValue != 0) { String errorMessage = "n/a"; try { errorMessage = new Scanner(p.getErrorStream(), Charset.defaultCharset().name()) .useDelimiter("\\Z").next(); } catch (Exception ex) { System.out.println("[ERROR] Exception caught during retrieving error message of command '" + command + "': " + ex); } throw new IllegalStateException("Execution of \"" + StringUtils.join(args, " ") + "\" command failed: " + errorMessage + ". Exit code was: " + exitValue); } byte[] buff = new byte[64]; StringBuilder sb = new StringBuilder(); for (int i = 0; (i = is.read(buff)) != -1;) { sb.append(new String(buff, 0, i, Charset.defaultCharset().name())); } BufferedReader reader = new BufferedReader(new StringReader(sb.toString())); try { return reader.readLine(); } finally { IOUtils.closeQuietly(reader); } } catch (InterruptedException e) { throw new RuntimeException(e); } }
From source file:com.hi.datacleaner.ExternalCommandTransformer.java
private String[] getResult(List<String> commandTokens) throws IOException, InterruptedException { Process process = new ProcessBuilder(commandTokens).start(); if (!process.waitFor(_timeout, TimeUnit.MILLISECONDS)) { process.destroy();// ww w . j av a2 s. com throw new InterruptedException( "Process has been interrupted because of timeout (" + _timeout + "ms). "); } BufferedReader stdin = new BufferedReader(new InputStreamReader(process.getInputStream())); BufferedReader stderr = new BufferedReader(new InputStreamReader(process.getErrorStream())); StringBuilder result = new StringBuilder(); String line; int linesCount = 0; while ((line = stdin.readLine()) != null) { linesCount++; result.append(line).append(_separator); } if (linesCount == 0) { result.append(ERROR); while ((line = stderr.readLine()) != null) { result.append(line).append(_separator); } } return new String[] { result.toString() }; }
From source file:com.redhat.jenkins.plugins.ci.integration.FedMsgMessagingPluginIntegrationTest.java
private Process logProcessBuilderIssues(ProcessBuilder pb, String commandName) throws InterruptedException, IOException { String dir = ""; if (pb.directory() != null) { dir = pb.directory().getAbsolutePath(); }//from w ww . jav a 2s . com System.out.println("Running : " + pb.command() + " => directory: " + dir); Process processToRun = pb.start(); int result = processToRun.waitFor(); if (result != 0) { StringWriter writer = new StringWriter(); IOUtils.copy(processToRun.getErrorStream(), writer); System.out.println("Issue occurred during command \"" + commandName + "\":\n" + writer.toString()); writer.close(); } return processToRun; }
From source file:com.googlecode.jmxtrans.model.output.RRDToolWriter.java
/** * Check to see if there was an error processing an rrdtool command *//*w w w . ja va 2 s .c o m*/ private void checkErrorStream(Process process) throws Exception { // rrdtool should use platform encoding (unless you did something // very strange with your installation of rrdtool). So let's be // explicit and use the presumed correct encoding to read errors. try (InputStream is = process.getErrorStream(); InputStreamReader isr = new InputStreamReader(is, Charset.defaultCharset()); BufferedReader br = new BufferedReader(isr)) { StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } if (sb.length() > 0) { throw new RuntimeException(sb.toString()); } } }
From source file:com.openshift.internal.restclient.capability.resources.OpenShiftBinaryRSync.java
private void waitForExit(String source, String destination, Process process) { try {//from w w w .ja v a 2 s.c om if (process == null) { throw new OpenShiftException("Could not sync %s to %s, no process was launched.", destination); } if (!process.waitFor(WAIT_FOR_EXIT_TIMEOUT, TimeUnit.MINUTES)) { throw new OpenShiftException("Syncing %s to %s did not terminate within %d minutes.", source, destination, WAIT_FOR_EXIT_TIMEOUT); } if (process.exitValue() != 0) { String errorMessage = getErrorMessage(process.getErrorStream()); throw new OpenShiftException( "Syncing %s to %s failed" + (StringUtil.isBlank(errorMessage) ? "" : ":%s"), source, destination, errorMessage); } } catch (InterruptedException e) { throw new OpenShiftException(e, "Syncing %s to %s was interrupted.", source, destination); } }
From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.algorithm.pisa.PISAAlgorithm.java
@Override public void initialize() { super.initialize(); try {//from w w w . jav a 2 s .com configure(); state.set(0); state0(); state.set(1); Process process = selector.start(); RedirectStream.redirect(process.getInputStream(), System.out); RedirectStream.redirect(process.getErrorStream(), System.err); } catch (Exception e) { throw new AlgorithmException(this, e); } }
From source file:com.datatorrent.stram.StramLocalClusterTest.java
private String generatejar(String pojoClassName) throws IOException, InterruptedException { String sourceDir = "src/test/resources/dynamicJar/"; String destDir = testMeta.getPath(); // The compiled java class should be loadable by the current java runtime hence setting the compile target version // to be the same String binLocation = getJavaBinLocation(); Process p = Runtime.getRuntime().exec( new String[] { binLocation + "javac", "-d", destDir, sourceDir + pojoClassName + ".java" }, null, null);//ww w. ja v a 2s .c o m IOUtils.copy(p.getInputStream(), System.out); IOUtils.copy(p.getErrorStream(), System.err); Assert.assertEquals(0, p.waitFor()); p = Runtime.getRuntime().exec( new String[] { binLocation + "jar", "-cf", pojoClassName + ".jar", pojoClassName + ".class" }, null, new File(destDir)); IOUtils.copy(p.getInputStream(), System.out); IOUtils.copy(p.getErrorStream(), System.err); Assert.assertEquals(0, p.waitFor()); return new File(destDir, pojoClassName + ".jar").getAbsolutePath(); }
From source file:de.mpg.escidoc.services.extraction.ExtractionChain.java
public ExtractionResult doExtract(String infileName, String outfileName) { File outfile = new File(outfileName); Date stepStart = new Date(); Date current;//from w w w . ja v a 2 s . co m logger.info("Extracting PDF content ----------------------------------------"); logger.info("Infile: " + infileName); logger.info("Outfile: " + outfileName); logger.info(stepStart + " -- started"); // xPDF try { logger.info("Extracting with xPDF"); StringBuffer command = new StringBuffer(2048); command.append(System.getProperty("os.name").contains("Windows") ? pdftotext + " -enc UTF-8 " : "/usr/bin/pdftotext -enc UTF-8 "); command.append(infileName); command.append(" "); command.append(outfileName); Process proc = Runtime.getRuntime().exec(command.toString()); StreamGobbler inputGobbler = new StreamGobbler(proc.getInputStream(), "xPDF"); StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "xPDF"); inputGobbler.start(); errorGobbler.start(); int exitCode = proc.waitFor(); if (proc.exitValue() == 0) { if (verbose) { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(outfile), "UTF-8")); String line; while ((line = bufferedReader.readLine()) != null) { logger.info(line); } bufferedReader.close(); } current = new Date(); logger.info(current + " -- finished successfully"); logger.info("Extraction took " + (current.getTime() - stepStart.getTime())); return ExtractionResult.OK; } } catch (Exception e) { logger.warn("Error extracting PDF with xPDF:"); logger.warn(e.getStackTrace()); } current = new Date(); logger.info(current + " -- finished unsuccessfully"); logger.info("Extraction attempt took " + (current.getTime() - stepStart.getTime())); // PDFBox try { logger.info("Extracting with PDFBox"); stepStart = new Date(); StringBuffer command = new StringBuffer(1024); command.append(System.getProperty("os.name").contains("Windows") ? "java -Dfile.encoding=UTF-8 -jar " + pdfboxAppJar + " ExtractText " : "/usr/bin/java -Dfile.encoding=UTF-8 -jar " + pdfboxAppJar + " ExtractText "); command.append(infileName); command.append(" "); command.append(outfileName); Process proc = Runtime.getRuntime().exec(command.toString()); StreamGobbler inputGobbler = new StreamGobbler(proc.getInputStream(), "PDFBox"); StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "PDFBox"); inputGobbler.start(); errorGobbler.start(); int exitCode = proc.waitFor(); if (exitCode == 0) { if (verbose) { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(outfile), "UTF-8")); String line; while ((line = bufferedReader.readLine()) != null) { logger.info(line); } bufferedReader.close(); } current = new Date(); logger.info(current + " -- finished successfully"); logger.info("Extraction took " + (current.getTime() - stepStart.getTime())); return ExtractionResult.OK; } } catch (Exception e) { logger.warn("Error extracting PDF with PDFBox:"); logger.warn(e.getStackTrace()); } current = new Date(); logger.info(current + " -- finished unsuccessfully"); logger.info("Extraction attempt took " + (current.getTime() - stepStart.getTime())); // iText try { logger.info("Extracting with iText"); stepStart = new Date(); PdfReader reader = new PdfReader(infileName); int numberOfPages = reader.getNumberOfPages(); outputStreamWriter = new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8"); for (int i = 0; i < numberOfPages; i++) { outputStreamWriter.write(PdfTextExtractor.getTextFromPage(reader, i + 1)); } if (verbose) { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(outfile), "UTF-8")); String line; while ((line = bufferedReader.readLine()) != null) { logger.info(line); } bufferedReader.close(); } current = new Date(); logger.info(current + " -- finished successfully"); logger.info("Extraction took " + (current.getTime() - stepStart.getTime())); return ExtractionResult.OK; } catch (Exception e) { logger.warn("Error extracting PDF with iText:", e); } // tika InputStream stream = null; try { logger.info("Extracting with Tika"); stepStart = new Date(); stream = TikaInputStream.get(new File(infileName)); ContentHandler handler = new BodyContentHandler(TIKA_CONTENT_SIZE); new AutoDetectParser().parse(stream, handler, new Metadata(), new ParseContext()); String content = handler.toString(); FileUtils.writeStringToFile(outfile, content); stream.close(); if (verbose) { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(outfile), "UTF-8")); String line; while ((line = bufferedReader.readLine()) != null) { logger.info(line); } bufferedReader.close(); } current = new Date(); logger.info(current + " -- finished successfully"); logger.info("Extraction took " + (current.getTime() - stepStart.getTime())); return ExtractionResult.OK; } catch (Exception e) { logger.warn("Error extracting Tika:", e); try { stream.close(); } catch (IOException e1) { e1.printStackTrace(); } } current = new Date(); logger.warn(current + " -- finished unsuccessfully"); logger.info("Extraction attempt took " + (current.getTime() - stepStart.getTime())); logger.info("... giving up"); return ExtractionResult.FAILURE; }
From source file:net.sf.mavenjython.test.PythonTestMojo.java
public void execute() throws MojoExecutionException { // all we have to do is to run nose on the source directory List<String> l = new ArrayList<String>(); if (program.equals("nose")) { l.add("nosetests.bat"); l.add("--failure-detail"); l.add("--verbose"); } else {// w w w . j av a 2s .c om l.add(program); } ProcessBuilder pb = new ProcessBuilder(l); pb.directory(testOutputDirectory); pb.environment().put("JYTHONPATH", ".;" + outputDirectory.getAbsolutePath()); final Process p; getLog().info("starting python tests"); getLog().info("executing " + pb.command()); getLog().info("in directory " + testOutputDirectory); getLog().info("and also including " + outputDirectory); try { p = pb.start(); } catch (IOException e) { throw new MojoExecutionException( "Python tests execution failed. Provide the executable '" + program + "' in the path", e); } copyIO(p.getInputStream(), System.out); copyIO(p.getErrorStream(), System.err); copyIO(System.in, p.getOutputStream()); try { if (p.waitFor() != 0) { throw new MojoExecutionException("Python tests failed with return code: " + p.exitValue()); } else { getLog().info("Python tests (" + program + ") succeeded."); } } catch (InterruptedException e) { throw new MojoExecutionException("Python tests were interrupted", e); } }
From source file:com.sssemil.advancedsettings.MainService.java
@Override public void onDisplayChanged(int displayId) { try {/*from ww w . j a v a2 s. com*/ mDisplayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE); mDisplayManager.registerDisplayListener(MainService.this, null); switch (mDisplayManager.getDisplay(displayId).getState()) { case Display.STATE_DOZE_SUSPEND: case Display.STATE_DOZE: try { //TODO: Need to fix screen_saver_brightness_settings. SELinux problems? Thread.sleep(3); int brightness = Integer .parseInt(mSharedPreferences.getString("screen_saver_brightness_settings", String.valueOf(Utils.getDeviceCfg(MainService.this).brightnessDefault))); boolean do_brightness = mSharedPreferences.getBoolean("manage_screen_saver_brightness_settings", false); if (do_brightness) { Log.i(TAG, "echo \"" + brightness + "\" > " + Utils.getDeviceCfg(MainService.this).brightnessPath); Runtime rt = Runtime.getRuntime(); String[] commands = { "su", "-c", "echo \"" + brightness + "\" > " + Utils.getDeviceCfg(MainService.this).brightnessPath }; Process proc = rt.exec(commands); BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream())); String s; while ((s = stdInput.readLine()) != null) { System.out.println(s); } while ((s = stdError.readLine()) != null) { System.out.println(s); } } } catch (IOException | InterruptedException e) { if (BuildConfig.DEBUG) { Log.d(TAG, "catch " + e.toString() + " hit in run", e); } } /*PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "WakeLock"); wakeLock.acquire();*/ break; default: break; } } catch (NullPointerException e) { e.printStackTrace(); } }