List of usage examples for java.lang Process getInputStream
public abstract InputStream getInputStream();
From source file:com.qmetry.qaf.automation.testng.report.ReporterUtil.java
public static String execHostName(String execCommand) { InputStream stream;/*from w w w. j a v a 2s . c om*/ Scanner s; try { Process proc = Runtime.getRuntime().exec(execCommand); stream = proc.getInputStream(); if (stream != null) { s = new Scanner(stream); s.useDelimiter("\\A"); String val = s.hasNext() ? s.next() : ""; stream.close(); s.close(); return val; } } catch (IOException ioException) { ioException.printStackTrace(); } return ""; }
From source file:com.floragunn.searchguard.util.SecurityUtil.java
public static boolean isRootUser() { boolean isRoot = false; int exitValue = -1; String result = null;// w w w . j a v a2s . co m try { final Process p = Runtime.getRuntime().exec("id -u"); result = IOUtils.toString(p.getInputStream()); exitValue = p.waitFor(); p.destroy(); } catch (final Exception e) { //ignore } if (exitValue == 0 && result != null) { isRoot = "0".equals(result.trim()); } if (!isRoot) { return isWindowsAdmin(); } else { return true; } }
From source file:com.ibm.jaql.JaqlBaseTestCase.java
/** * Compares the tmp file and gold file using unix diff. whitespace is ignored * for the diff.// w w w .j a v a 2s .co m * * * @param tmpFileName tmp file name * @param goldFileName gold file name * @return <tt>true</tt> if the tmp file and gold file are the same; * <tt>false</tt> otherwise. * @throws IOException */ public static boolean compareResults(String tmpFileName, String goldFileName) throws IOException { // use unix 'diff', ignoring whitespace ProcessBuilder pb = new ProcessBuilder("diff", "-w", tmpFileName, goldFileName); /* * Two input file for diff are the same only if nothing is printed to stdout * and stderr. Redirect stderr to stdout so that only stdout needs to * checked. */ pb.redirectErrorStream(true); Process p = pb.start(); InputStream str = p.getInputStream(); byte[] b = new byte[1024]; int numRead = 0; StringBuilder sb = new StringBuilder(); while ((numRead = str.read(b)) > 0) { sb.append(new String(b, 0, numRead, "US-ASCII")); } if (sb.length() > 0) System.err.println("\ndiff -w " + tmpFileName + " " + goldFileName + "\n" + sb); return sb.length() == 0; }
From source file:com.modeln.build.common.tool.CMnCmdLineTool.java
/** * Wait for the executing process to complete. * * @param process Process to monitor/*ww w . j ava 2 s. c o m*/ * @param profile Enable or disable execution profiling */ public static int wait(Process process, boolean profile) throws InterruptedException { Date startDate = null; if (profile) { startDate = new Date(); } // Use a separate thread to relay the process output to the user CMnProcessOutput stdout = new CMnProcessOutput(process, process.getInputStream()); CMnProcessOutput stderr = new CMnProcessOutput(process, process.getErrorStream()); Thread out = new Thread(stdout); Thread err = new Thread(stderr); out.start(); err.start(); // Wait for the process to complete int result = process.waitFor(); // Display the elapsed time for this operation if (profile) { displayElapsedTime(startDate, new Date(), "Execution complete: "); } return result; }
From source file:Main.java
public static String RunExecCmd(StringBuilder sb, Boolean su) { String shell;//from w ww .j av a2 s . co m if (su) { shell = "su"; } else { shell = "sh"; } Process process = null; DataOutputStream processOutput = null; InputStream processInput = null; String outmsg = new String(); try { process = Runtime.getRuntime().exec(shell); processOutput = new DataOutputStream(process.getOutputStream()); processOutput.writeBytes(sb.toString() + "\n"); processOutput.writeBytes("exit\n"); processOutput.flush(); processInput = process.getInputStream(); outmsg = inputStream2String(processInput, "UTF-8"); process.waitFor(); } catch (Exception e) { //Log.d("*** DEBUG ***", "ROOT REE" + e.getMessage()); //return; } finally { try { if (processOutput != null) { processOutput.close(); } process.destroy(); } catch (Exception e) { } } return outmsg; }
From source file:ExifUtils.ExifReadWrite.java
public static ArrayList<String> exifTool(String[] parameters, File directory) { // final String command[] = "exiftool " + parameters; ArrayList<String> lines = new ArrayList<>(); try {//from ww w .java 2 s.c om Runtime runtime = Runtime.getRuntime(); Process p = runtime.exec(parameters, null, directory); final BufferedReader stdinReader = new BufferedReader( new InputStreamReader(p.getInputStream(), "ISO-8859-1")); final BufferedReader stderrReader = new BufferedReader( new InputStreamReader(p.getErrorStream(), "ISO-8859-1")); new Thread(new Runnable() { @Override public void run() { try { String s; while ((s = stdinReader.readLine()) != null) { lines.add(s); } } catch (IOException e) { } } }).start(); new Thread(new Runnable() { @Override public void run() { try { String s; while ((s = stderrReader.readLine()) != null) { lines.add(s); } } catch (IOException e) { } } }).start(); int returnVal = p.waitFor(); } catch (Exception e) { errorOut("xmp", e); } return lines; }
From source file:com.utdallas.s3lab.smvhunter.monkey.MonkeyMe.java
/** * Process to execute commands in command line * @param command/*from w w w .j av a 2 s .c o m*/ * @return * @throws IOException */ public static String execCommand(String command) throws IOException { if (logDebug) logger.debug(String.format("Executing command %s", command)); System.out.println(String.format("Executing command %s", command)); Process pr = Runtime.getRuntime().exec(command); String result = IOUtils.toString(pr.getInputStream()); pr.destroy(); return result; }
From source file:edu.stanford.epad.epadws.dcm4chee.Dcm4CheeOperations.java
public static boolean deleteStudy(String studyUID) { InputStream is = null;// w ww . j a v a2 s. c om InputStreamReader isr = null; BufferedReader br = null; boolean success = false; try { log.info("Deleting study " + studyUID + " files - command: ./dcmdeleteStudy " + studyUID); String[] command = { "./dcmdeleteStudy", studyUID }; ProcessBuilder pb = new ProcessBuilder(command); String dicomScriptsDir = EPADConfig.getEPADWebServerDICOMScriptsDir() + "bin/"; File script = new File(dicomScriptsDir, "dcmdeleteStudy"); if (!script.exists()) dicomScriptsDir = EPADConfig.getEPADWebServerMyScriptsDir(); script = new File(dicomScriptsDir, "dcmdeleteStudy"); // Java 6 - Runtime.getRuntime().exec("chmod u+x "+script.getAbsolutePath()); script.setExecutable(true); pb.directory(new File(dicomScriptsDir)); Process process = pb.start(); process.getOutputStream(); is = process.getInputStream(); isr = new InputStreamReader(is); br = new BufferedReader(isr); String line; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { log.info("./dcmdeleteStudy: " + line); sb.append(line).append("\n"); } try { int exitValue = process.waitFor(); log.info("DICOM delete study exit value is: " + exitValue); if (exitValue == 0) success = true; } catch (Exception e) { log.warning("Failed to delete DICOM study " + studyUID, e); } String cmdLineOutput = sb.toString(); if (cmdLineOutput.toLowerCase().contains("error")) { throw new IllegalStateException("Failed for: " + parseError(cmdLineOutput)); } } catch (Exception e) { log.warning("Failed to delete DICOM study " + studyUID, e); } return success; }
From source file:edu.kit.dama.util.SystemUtils.java
/** * Lock a folder in a Unix system. Therefor, the script previously generated * by generateScript() is used to lock the provided folder 'pLocalFolder'. * * @param pLocalScriptFile The lock script. * @param pLocalFolder The folder to lock. * * @return TRUE if the locking succeeded. */// ww w . j a v a2 s .co m private static boolean applyScriptToFolder(String pLocalScriptFile, String... pArguments) { BufferedReader brStdOut = null; BufferedReader brStdErr = null; try { String line; StringBuilder stdOut = new StringBuilder(); StringBuilder stdErr = new StringBuilder(); List<String> cmdArrayList = new ArrayList<>(); cmdArrayList.add("sh"); cmdArrayList.add(pLocalScriptFile); if (pArguments != null) { cmdArrayList.addAll(Arrays.asList(pArguments)); } Process p = Runtime.getRuntime().exec(cmdArrayList.toArray(new String[cmdArrayList.size()])); brStdOut = new BufferedReader(new InputStreamReader(p.getInputStream())); brStdErr = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((line = brStdOut.readLine()) != null) { stdOut.append(line).append("\n"); } brStdOut.close(); while ((line = brStdErr.readLine()) != null) { stdErr.append(line).append("\n"); } brStdErr.close(); int result = p.waitFor(); LOGGER.debug("Script finished execution with return code {}", result); LOGGER.debug("StdOut: {}", stdOut.toString()); LOGGER.warn("StdErr: {}", stdErr.toString()); } catch (IOException err) { LOGGER.error("Script execution failed", err); return false; } catch (InterruptedException err) { LOGGER.error("Script execution might have failed", err); return false; } finally { if (brStdErr != null) { try { brStdErr.close(); } catch (IOException ex) { } } if (brStdOut != null) { try { brStdOut.close(); } catch (IOException ex) { } } } return true; }
From source file:com.cprassoc.solr.auth.SolrAuthActionController.java
public static String doPushConfigToSolrAction(SecurityJson json) { String result = ""; try {/* w w w . j av a 2 s . com*/ String mime = "sh"; if (Utils.isWindows()) { mime = "bat"; } String pathToScript = System.getProperty("user.dir") + File.separator + "solrAuth." + mime; String jsonstr = json.export(); String filePath = SolrAuthManager.getProperties().getProperty("solr.install.path") + File.separator + "security.json"; File backup = new File("backup"); if (!backup.exists()) { backup.mkdirs(); } File file = new File(filePath); if (file.exists()) { // String newFilePath = SolrAuthManager.getProperties().getProperty("solr.install.path") + File.separator + System.currentTimeMillis() + "_security.json"; // File newFile = new File(newFilePath); // file.renameTo(newFile); FileUtils.copyFileToDirectory(file, backup); } FileUtils.writeByteArrayToFile(file, jsonstr.getBytes()); Thread.sleep(500); ProcessBuilder pb = new ProcessBuilder(pathToScript); Log.log("Run PUSH command"); Process process = pb.start(); if (process.waitFor() == 0) { result = ""; } else { result = Utils.streamToString(process.getErrorStream()); result += "\n" + Utils.streamToString(process.getInputStream()); Log.log(result); } } catch (Exception e) { e.printStackTrace(); result = e.getLocalizedMessage(); } return result; }