List of usage examples for java.lang Process destroy
public abstract void destroy();
From source file:org.wso2.carbon.integration.tests.carbontools.CarbonServerBasicOperationTestCase.java
@Test(groups = { "carbon.core" }, description = "Testing carbondump.sh execution", dependsOnMethods = { "testStopCommand" }) public void testCarbonDumpCommandOnLinux() throws Exception { String[] cmdArray;/* www . j a va 2 s . c om*/ Process carbonDumpProcess = null; String expectedString = "Copyright"; boolean isFoundTheMessage = false; BufferedReader br = null; String[] zipCmdArray = { "zip", "--help" }; Process process; try { process = Runtime.getRuntime().exec(zipCmdArray, null); } catch (IOException ex) { throw new SkipException(" This test method need zip command to run"); } String line; long startTime = System.currentTimeMillis(); // Wait 1 second to check whether zip command installed or not while (!isFoundTheMessage && (System.currentTimeMillis() - startTime) < 1000) { br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); while ((line = br.readLine()) != null) { log.info(line); if (line.contains(expectedString)) { log.info("found the string expected string " + expectedString + ", in line =>" + line); isFoundTheMessage = true; break; } } } if (!isFoundTheMessage) { throw new SkipException(" This test method need zip command to run"); } try { if ((CarbonCommandToolsUtil.getCurrentOperatingSystem() .contains(OperatingSystems.WINDOWS.name().toLowerCase()))) { //Skipping the test execution on Windows throw new SkipException("--start is not available for windows"); // Since we are skipping --start feature it won } else { cmdArray = new String[] { "sh", "carbondump.sh", "-carbonHome", System.getProperty("carbon.home"), "-pid", getProcessId(System.getProperty("carbon.home")) }; } carbonDumpProcess = CarbonCommandToolsUtil .runScript(System.getProperty("carbon.home") + File.separator + "bin", cmdArray); assertTrue(isDumpFileFound(System.getProperty("carbon.home")), "Couldn't find the dump file"); } finally { if (carbonDumpProcess != null) { carbonDumpProcess.destroy(); } br.close(); } }
From source file:edu.stanford.epad.epadws.processing.pipeline.task.DicomHeadersTask.java
@Override public void run() { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); // Let interactive thread run sooner FileWriter tagFileWriter = null; InputStream is = null;//from w w w. j a v a 2 s . co m InputStreamReader isr = null; BufferedReader br = null; Process process = null; try { String[] command = { "./dcm2txt", "-w", "250", "-l", "250", dicomInputFile.getAbsolutePath() }; ProcessBuilder processBuilder = new ProcessBuilder(command); String dicomBinDir = EPADConfig.getEPADWebServerDICOMScriptsDir() + "bin/"; File script = new File(dicomBinDir, "dcm2txt"); if (!script.exists()) dicomBinDir = EPADConfig.getEPADWebServerDICOMBinDir(); script = new File(dicomBinDir, "dcm2txt"); // Java 6 - Runtime.getRuntime().exec("chmod u+x "+script.getAbsolutePath()); script.setExecutable(true); processBuilder.directory(new File(dicomBinDir)); process = processBuilder.start(); process.getOutputStream(); is = process.getInputStream(); isr = new InputStreamReader(is); br = new BufferedReader(isr); String line; StringBuilder sb = new StringBuilder(); StringBuilder log = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line).append("\n"); log.append("./dcm2txt: " + line).append("\n"); } try { process.waitFor(); } catch (InterruptedException e) { logger.info(log.toString()); logger.warning("Couldn't get tags for series " + seriesUID + "; dicom=" + dicomInputFile.getAbsolutePath() + " tagFile:" + outputFile.getAbsolutePath(), e); } EPADFileUtils.createDirsAndFile(outputFile); File tagFile = outputFile; tagFileWriter = new FileWriter(tagFile); tagFileWriter.write(sb.toString()); } catch (Exception e) { logger.warning("DicomHeadersTask failed to create DICOM tags for series " + seriesUID + " dicom FIle:" + dicomInputFile.getAbsolutePath() + " : " + outputFile.getAbsolutePath(), e); } catch (OutOfMemoryError oome) { logger.warning("DicomHeadersTask for series " + seriesUID + " out of memory: ", oome); } finally { IOUtils.closeQuietly(tagFileWriter); IOUtils.closeQuietly(br); if (process != null) process.destroy(); } }
From source file:org.apache.syncope.fit.cli.CLIITCase.java
@Test public void userRead() { final String userKey1 = "1417acbe-cbf6-4277-9372-e75e04f97000"; final String userKey2 = "74cd8ece-715a-44a4-a736-e17b46c4e7e6"; final String userKey3 = "b3cbc78d-32e6-4bd4-92e0-bbe07566a2ee"; final String userKey4 = "c9b2dec2-00a7-4855-97c0-d854842b4b24"; final String userKey5 = "823074dc-d280-436d-a7dd-07399fae48ec"; Process process1 = null; Process process2 = null;/* w w w .j a va 2 s .c om*/ Process process3 = null; try { PROCESS_BUILDER.command(getCommand(new UserCommand().getClass().getAnnotation(Command.class).name(), UserCommand.UserOptions.READ_BY_KEY.getOptionName(), String.valueOf(userKey1))); process1 = PROCESS_BUILDER.start(); String result = IOUtils.toString(process1.getInputStream(), StandardCharsets.UTF_8); assertTrue(result.contains("username: " + userService.read(userKey1).getUsername())); PROCESS_BUILDER.command(getCommand(new UserCommand().getClass().getAnnotation(Command.class).name(), UserCommand.UserOptions.READ_BY_KEY.getOptionName(), String.valueOf(userKey1), String.valueOf(userKey2), String.valueOf(userKey3), String.valueOf(userKey4), String.valueOf(userKey5))); process2 = PROCESS_BUILDER.start(); long users = IOUtils.readLines(process2.getInputStream(), StandardCharsets.UTF_8).stream() .filter(line -> line.startsWith(" > USER KEY:")).count(); assertEquals(5, users); PROCESS_BUILDER.command(getCommand(new UserCommand().getClass().getAnnotation(Command.class).name(), UserCommand.UserOptions.READ_BY_KEY.getOptionName(), String.valueOf(userKey1), String.valueOf(userKey2), String.valueOf(userKey3), String.valueOf(userKey4), String.valueOf(userKey5))); process3 = PROCESS_BUILDER.start(); String result3 = IOUtils.toString(process3.getInputStream(), StandardCharsets.UTF_8); assertTrue(result3.contains("username: " + userService.read(userKey1).getUsername()) && result3.contains("username: " + userService.read(userKey2).getUsername()) && result3.contains("username: " + userService.read(userKey3).getUsername()) && result3.contains("username: " + userService.read(userKey4).getUsername()) && result3.contains("username: " + userService.read(userKey5).getUsername())); } catch (IOException e) { fail(e.getMessage()); } finally { if (process1 != null) { process1.destroy(); } if (process2 != null) { process2.destroy(); } if (process3 != null) { process3.destroy(); } } }
From source file:com.att.android.arodatacollector.main.AROCollectorService.java
/** * Stops collecting kernel log//w w w . j av a 2 s. c om * * Requires root permission. * * pre: there is only one "cat" process running */ private void stopDmesg() { Process sh = null; DataOutputStream os = null; int pid = 0; try { pid = mAroUtils.getProcessID("cat"); } catch (IOException e1) { Log.e(TAG, "IOException in stopDmesg", e1); } catch (IndexOutOfBoundsException e1) { Log.e(TAG, "IndexOutOfBoundsException in stopDmesg", e1); } catch (InterruptedException e1) { Log.e(TAG, "exception in stopDmesg", e1); } if (DEBUG) { Log.d(TAG, "stopDmesg=" + pid); } if (pid != 0) { try { sh = Runtime.getRuntime().exec("su"); os = new DataOutputStream(sh.getOutputStream()); final String Command = "kill -15 " + pid + "\n"; os.writeBytes(Command); os.flush(); sh.waitFor(); } catch (IOException e) { Log.e(TAG, "exception in stopDmesg", e); } catch (InterruptedException e) { Log.e(TAG, "exception in stopDmesg", e); } finally { try { os.close(); } catch (IOException e) { Log.e(TAG, "exception in stopDmesg DataOutputStream close", e); } if (DEBUG) { Log.d(TAG, "Stopped stopDmesg"); } sh.destroy(); } } }
From source file:org.apache.htrace.impl.HTracedProcess.java
private HTracedProcess(Builder builder) throws Exception { this.htracedPath = Paths.get("target", "..", "go", "build", "htraced").toFile(); if (!this.htracedPath.exists()) { throw new RuntimeException("No htraced binary exists at " + this.htracedPath); }/*from w w w . ja va 2 s . c o m*/ this.dataDir = new DataDir(); // Create a notifier socket bound to a random port. ServerSocket listener = new ServerSocket(0); boolean success = false; Process process = null; HttpClient http = null; try { // Use a random port for the web address. No 'scheme' yet. String random = builder.host + ":0"; String logPath = new File(dataDir.get(), "log.txt").getAbsolutePath(); // Pass cmdline args to htraced to it uses our test dir for data. ProcessBuilder pb = new ProcessBuilder(htracedPath.getAbsolutePath(), "-Dlog.level=TRACE", "-Dlog.path=" + logPath, "-Dweb.address=" + random, "-Dhrpc.address=" + random, "-Ddata.store.clear=true", "-Dstartup.notification.address=localhost:" + listener.getLocalPort(), "-Ddata.store.directories=" + dataDir.get().getAbsolutePath()); // Set HTRACED_CONF_DIR to the temporary directory we just created, to // ensure that it doesn't pull in any other configuration file that might // be on this test machine. Map<String, String> env = pb.environment(); env.put("HTRACED_CONF_DIR", dataDir.get().getAbsolutePath()); // Remove any HTRACED_WEB_DIR variable that might be set, to ensure that // we use the default value (which finds the local web files by relative // path). env.remove("HTRACED_WEB_DIR"); pb.redirectErrorStream(true); // Inherit STDERR/STDOUT i/o; dumps on console for now. Can add logs later. pb.inheritIO(); pb.directory(dataDir.get()); //assert pb.redirectInput() == Redirect.PIPE; //assert pb.redirectOutput().file() == dataDir; process = pb.start(); assert process.getInputStream().read() == -1; StartupNotificationData data = readStartupNotification(listener); httpAddr = data.httpAddr; hrpcAddr = data.hrpcAddr; LOG.info("Started htraced process " + data.processId + " with http " + "address " + data.httpAddr + ", logging to " + logPath); http = RestBufferManager.createHttpClient(60000L, 60000L); http.start(); success = true; } finally { if (!success) { // Clean up after failure if (process != null) { process.destroy(); process = null; } if (http != null) { http.stop(); } } delegate = process; listener.close(); httpClient = http; } }
From source file:org.pentaho.di.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java
public static String execProcess(Context actualContext, Scriptable actualObject, Object[] ArgList, Function FunctionContext) { String retval = null;//from w w w . j av a2 s .c om if (!isNull(ArgList) && !isUndefined(ArgList)) { Process processrun = null; try { String ligne = ""; StringBuffer buffer = new StringBuffer(); processrun = Runtime.getRuntime().exec(Context.toString(ArgList[0])); // Get process response BufferedReader br = new BufferedReader(new InputStreamReader(processrun.getInputStream())); // Read response lines while ((ligne = br.readLine()) != null) { buffer.append(ligne); } // if (processrun.exitValue()!=0) throw Context.reportRuntimeError("Error while running " + ArgList[0]); retval = buffer.toString(); } catch (Exception er) { throw Context.reportRuntimeError(er.toString()); } finally { if (processrun != null) { processrun.destroy(); } } } else { throw Context.reportRuntimeError("The function call execProcess is not valid."); } return retval; }
From source file:com.ah.be.common.NmsUtil.java
/** * <p>/* w w w. j a v a 2 s . c om*/ * Check if the port specified is occupied by some certain process/socket in * the current system. * </p> * * @param port * the number of port to be checked for. * @return <tt>true</tt> if the port given is occupied by a certain * process/socket, <tt>false</tt> otherwise. * @throws IOException If an I/O error occurs. * @throws InterruptedException if the current thread is interrupted by another thread while it is waiting for the result. */ public static boolean checkPortOccupancy(int port) throws IOException, InterruptedException { boolean occupied = false; String cmdForWindows = "netstat -ano|findstr \":" + port + "\\>\""; String cmdForLinux = "netstat -anp|grep \":" + port + " \""; String os = System.getProperty("os.name"); String[] cmdArray = os.toLowerCase().contains("windows") ? new String[] { "cmd.exe", "/C", cmdForWindows } : new String[] { "bash", "-c", cmdForLinux }; Runtime runtime = Runtime.getRuntime(); Process proc = null; BufferedReader reader = null; log.info("checkPortOccupancy", "Executing netstat cmd: " + cmdArray[0] + " " + cmdArray[1] + " " + cmdArray[2]); try { proc = runtime.exec(cmdArray); int exitValue = proc.waitFor(); log.info("checkPortOccupancy", "Netstat cmd was executed and exit value related to the process was " + exitValue); if (exitValue == 0) { InputStream input = proc.getInputStream(); if (input != null) { reader = new BufferedReader(new InputStreamReader(input)); String readLine = reader.readLine(); occupied = readLine != null; } } } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) { log.error("checkPortOccupancy", "I/O Error in closing BufferedReader", ioe); } } if (proc != null) { proc.destroy(); } } return occupied; }
From source file:com.noshufou.android.su.util.Util.java
public static VersionInfo getSuVersionInfo() { VersionInfo info = new VersionInfo(); Process process = null; String inLine = null;// w ww . j av a 2s .com try { process = Runtime.getRuntime().exec("sh"); DataOutputStream os = new DataOutputStream(process.getOutputStream()); BufferedReader is = new BufferedReader( new InputStreamReader(new DataInputStream(process.getInputStream())), 64); os.writeBytes("su -v\n"); // We have to hold up the thread to make sure that we're ready to read // the stream, using increments of 5ms makes it return as quick as // possible, and limiting to 1000ms makes sure that it doesn't hang for // too long if there's a problem. for (int i = 0; i < 400; i++) { if (is.ready()) { break; } try { Thread.sleep(5); } catch (InterruptedException e) { Log.w(TAG, "Sleep timer got interrupted..."); } } if (is.ready()) { inLine = is.readLine(); if (inLine != null) { info.version = inLine; } } else { // If 'su -v' isn't supported, neither is 'su -V'. return legacy info os.writeBytes("exit\n"); info.version = "legacy"; info.versionCode = 0; return info; } os.writeBytes("su -v\n"); // We have to hold up the thread to make sure that we're ready to read // the stream, using increments of 5ms makes it return as quick as // possible, and limiting to 1000ms makes sure that it doesn't hang for // too long if there's a problem. for (int i = 0; i < 400; i++) { if (is.ready()) { break; } try { Thread.sleep(5); } catch (InterruptedException e) { Log.w(TAG, "Sleep timer got interrupted..."); } } if (is.ready()) { inLine = is.readLine(); if (inLine != null && Integer.parseInt(inLine.substring(0, 1)) > 2) { inLine = null; os.writeBytes("su -V\n"); inLine = is.readLine(); if (inLine != null) { info.versionCode = Integer.parseInt(inLine); } } else { info.versionCode = 0; } } else { os.writeBytes("exit\n"); } } catch (IOException e) { Log.e(TAG, "Problems reading current version.", e); } finally { if (process != null) { process.destroy(); } } return info; }
From source file:ExecHelper.java
/** * Take a process, record its standard error and standard out streams, wait for it to finish * * @param process process to watch/* w ww .j av a2s.com*/ * @throws SecurityException if a security manager exists and its checkExec method doesn't allow creation of a subprocess. * @throws IOException - if an I/O error occurs * @throws NullPointerException - if cmdarray is null * @throws IndexOutOfBoundsException - if cmdarray is an empty array (has length 0). * * @since ostermillerutils 1.06.00 */ private ExecHelper(Process process, String charset) throws IOException { StringBuffer output = new StringBuffer(); StringBuffer error = new StringBuffer(); Reader stdout; Reader stderr; if (charset == null) { // This is one time that the system charset is appropriate, // don't specify a character set. stdout = new InputStreamReader(process.getInputStream()); stderr = new InputStreamReader(process.getErrorStream()); } else { stdout = new InputStreamReader(process.getInputStream(), charset); stderr = new InputStreamReader(process.getErrorStream(), charset); } char[] buffer = new char[1024]; boolean done = false; boolean stdoutclosed = false; boolean stderrclosed = false; while (!done) { boolean readSomething = false; // read from the process's standard output if (!stdoutclosed && stdout.ready()) { readSomething = true; int read = stdout.read(buffer, 0, buffer.length); if (read < 0) { readSomething = true; stdoutclosed = true; } else if (read > 0) { readSomething = true; output.append(buffer, 0, read); } } // read from the process's standard error if (!stderrclosed && stderr.ready()) { int read = stderr.read(buffer, 0, buffer.length); if (read < 0) { readSomething = true; stderrclosed = true; } else if (read > 0) { readSomething = true; error.append(buffer, 0, read); } } // Check the exit status only we haven't read anything, // if something has been read, the process is obviously not dead yet. if (!readSomething) { try { this.status = process.exitValue(); done = true; } catch (IllegalThreadStateException itx) { // Exit status not ready yet. // Give the process a little breathing room. try { Thread.sleep(100); } catch (InterruptedException ix) { process.destroy(); throw new IOException("Interrupted - processes killed"); } } } } this.output = output.toString(); this.error = error.toString(); }
From source file:org.pentaho.di.job.entries.pgpencryptfiles.GPG.java
/** * Runs GnuPG external program//from www .j a va 2 s. c o m * * @param commandArgs * command line arguments * @param inputStr * key ID of the key in GnuPG's key database * @param fileMode * @return result * @throws KettleException */ private String execGnuPG(String commandArgs, String inputStr, boolean fileMode) throws KettleException { Process p; String command = getGpgExeFile() + " " + (fileMode ? "" : gnuPGCommand + " ") + commandArgs; if (log.isDebug()) { log.logDebug(BaseMessages.getString(PKG, "GPG.RunningCommand", command)); } String retval; try { if (Const.isWindows()) { p = Runtime.getRuntime().exec(command); } else { ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh", "-c", command); p = processBuilder.start(); } } catch (IOException io) { throw new KettleException(BaseMessages.getString(PKG, "GPG.IOException"), io); } ProcessStreamReader psr_stdout = new ProcessStreamReader(p.getInputStream()); ProcessStreamReader psr_stderr = new ProcessStreamReader(p.getErrorStream()); psr_stdout.start(); psr_stderr.start(); if (inputStr != null) { BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream())); try { out.write(inputStr); } catch (IOException io) { throw new KettleException(BaseMessages.getString(PKG, "GPG.ExceptionWrite"), io); } finally { if (out != null) { try { out.close(); } catch (Exception e) { // Ignore } } } } try { p.waitFor(); psr_stdout.join(); psr_stderr.join(); } catch (InterruptedException i) { throw new KettleException(BaseMessages.getString(PKG, "GPG.ExceptionWait"), i); } try { if (p.exitValue() != 0) { throw new KettleException( BaseMessages.getString(PKG, "GPG.Exception.ExistStatus", psr_stderr.getString())); } } catch (IllegalThreadStateException itse) { throw new KettleException(BaseMessages.getString(PKG, "GPG.ExceptionillegalThreadStateException"), itse); } finally { p.destroy(); } retval = psr_stdout.getString(); return retval; }