List of usage examples for java.lang Process destroy
public abstract void destroy();
From source file:org.springframework.integration.file.tail.TailRule.java
private boolean tailWorksOnThisMachine() { if (tmpDir.contains(":")) { return false; }/*from ww w .j a v a2 s. co m*/ File testDir = new File(tmpDir, "FileTailingMessageProducerTests"); testDir.mkdir(); final File file = new File(testDir, "foo"); int result = -99; try { OutputStream fos = new FileOutputStream(file); fos.write("foo".getBytes()); fos.close(); final AtomicReference<Integer> c = new AtomicReference<Integer>(); final CountDownLatch latch = new CountDownLatch(1); Future<Process> future = Executors.newSingleThreadExecutor().submit(new Callable<Process>() { @Override public Process call() throws Exception { final Process process = Runtime.getRuntime().exec(commandToTest + " " + file.getAbsolutePath()); Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { try { c.set(process.getInputStream().read()); latch.countDown(); } catch (IOException e) { logger.error("Error reading test stream", e); } } }); return process; } }); try { Process process = future.get(10, TimeUnit.SECONDS); if (latch.await(10, TimeUnit.SECONDS)) { Integer read = c.get(); if (read != null && read == 'f') { result = 0; } } process.destroy(); } catch (ExecutionException e) { result = -999; } file.delete(); } catch (Exception e) { logger.error("failed to test tail", e); } if (result != 0) { logger.warn("tail command is not available on this platform; result:" + result); } return result == 0; }
From source file:org.fusesource.meshkeeper.distribution.provisioner.embedded.Execute.java
/** * Wait for a given process.//w ww . ja va 2s. c o m * * @param process the process one wants to wait for. */ protected void waitFor(Process process) { try { process.waitFor(); setExitValue(process.exitValue()); } catch (InterruptedException e) { process.destroy(); } }
From source file:de.rrze.idmone.utils.jidgen.filter.ShellCmdFilter.java
public String apply(String id) { String cmd = this.cmdTemplate.replace("%s", id); logger.trace("Executing command: " + cmd); Runtime run = Runtime.getRuntime(); try {//w ww.ja va 2 s . com Process proc = run.exec(cmd); /* BufferedWriter commandLine = new BufferedWriter( new OutputStreamWriter(proc.getOutputStream()) ); commandLine.write(cmd); commandLine.flush(); */ // read stdout and log it to the debug level BufferedReader stdOut = new BufferedReader(new InputStreamReader(proc.getInputStream())); String stdOutput = ""; while ((stdOutput = stdOut.readLine()) != null) { logger.debug("STDOUT: " + stdOutput); } stdOut.close(); // read stderr and log it to the error level BufferedReader stdErr = new BufferedReader(new InputStreamReader(proc.getErrorStream())); String errOutput = ""; while ((errOutput = stdErr.readLine()) != null) { logger.error("STDERR: " + errOutput); } stdErr.close(); int exitCode = proc.waitFor(); proc.destroy(); if (exitCode == 0) { logger.trace("Filtered!"); return null; } else { return id; } } catch (IOException e) { logger.fatal(e.toString()); System.exit(120); } catch (InterruptedException e) { logger.fatal(e.toString()); System.exit(121); } return null; }
From source file:org.apache.tika.parser.ocr.TesseractOCRParser.java
/** * Run external tesseract-ocr process.//from ww w . j av a 2s . c o m * * @param input * File to be ocred * @param output * File to collect ocr result * @param config * Configuration of tesseract-ocr engine * @throws TikaException * if the extraction timed out * @throws IOException * if an input error occurred */ private void doOCR(File input, File output, TesseractOCRConfig config) throws IOException, TikaException { String[] cmd = { config.getTesseractPath() + getTesseractProg(), input.getPath(), output.getPath(), "-l", config.getLanguage(), "-psm", config.getPageSegMode() }; ProcessBuilder pb = new ProcessBuilder(cmd); setEnv(config, pb); final Process process = pb.start(); process.getOutputStream().close(); InputStream out = process.getInputStream(); InputStream err = process.getErrorStream(); logStream("OCR MSG", out, input); logStream("OCR ERROR", err, input); FutureTask<Integer> waitTask = new FutureTask<Integer>(new Callable<Integer>() { public Integer call() throws Exception { return process.waitFor(); } }); Thread waitThread = new Thread(waitTask); waitThread.start(); try { waitTask.get(config.getTimeout(), TimeUnit.SECONDS); } catch (InterruptedException e) { waitThread.interrupt(); process.destroy(); Thread.currentThread().interrupt(); throw new TikaException("TesseractOCRParser interrupted", e); } catch (ExecutionException e) { // should not be thrown } catch (TimeoutException e) { waitThread.interrupt(); process.destroy(); throw new TikaException("TesseractOCRParser timeout", e); } }
From source file:com.tascape.qa.th.Utils.java
public static Process cmd(String[] commands, final File file, final File workingDir, final String... ignoreRegex) throws IOException { FileUtils.touch(file);//w w w.j av a 2 s . c om LOG.debug("Saving console output to {}", file.getAbsolutePath()); ProcessBuilder pb = new ProcessBuilder(commands); pb.redirectErrorStream(true); pb.directory(workingDir); LOG.info("Running command {}: {}", workingDir == null ? "" : workingDir.getAbsolutePath(), pb.command().toString().replaceAll(",", "")); final Process p = pb.start(); Thread t = new Thread(Thread.currentThread().getName() + "-" + p.hashCode()) { @Override public void run() { BufferedReader stdIn = new BufferedReader(new InputStreamReader(p.getInputStream())); String console = "console-" + stdIn.hashCode(); try (PrintWriter pw = new PrintWriter(file)) { for (String line = stdIn.readLine(); line != null;) { LOG.trace("{}: {}", console, line); if (null == ignoreRegex || ignoreRegex.length == 0) { pw.println(line); } else { boolean ignore = false; for (String regex : ignoreRegex) { if (!regex.isEmpty() && (line.contains(regex) || line.matches(regex))) { ignore = true; break; } } if (!ignore) { pw.println(line); } } pw.flush(); line = stdIn.readLine(); } } catch (IOException ex) { LOG.warn(ex.getMessage()); } LOG.trace("command is done"); } }; t.setDaemon(true); t.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { if (p != null) { p.destroy(); } } }); return p; }
From source file:jp.co.tis.gsp.tools.dba.dialect.OracleDialect.java
@Override public void exportSchema(ExportParams params) throws MojoExecutionException { BufferedReader reader = null; try {//from w w w. jav a 2 s . com File dumpFile = params.getDumpFile(); String user = params.getUser(); String password = params.getPassword(); String schema = params.getSchema(); createDirectory(user, password, dumpFile.getParentFile()); ProcessBuilder pb = new ProcessBuilder("expdp", user + "/" + password, "directory=exp_dir", "dumpfile=" + dumpFile.getName(), "schemas=" + schema, "reuse_dumpfiles=y", "nologfile=y"); pb.redirectErrorStream(true); Process process = pb.start(); Charset terminalCharset = System.getProperty("os.name").toLowerCase().contains("windows") ? Charset.forName("Shift_JIS") : Charset.forName("UTF-8"); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), terminalCharset)); //??????????????? String line; while ((line = reader.readLine()) != null) { System.out.println(line); } process.waitFor(); if (process.exitValue() != 0) { throw new MojoExecutionException("oracle export error"); } process.destroy(); } catch (Exception e) { throw new MojoExecutionException("oracle export", e); } finally { IOUtils.closeQuietly(reader); } }
From source file:jp.co.tis.gsp.tools.dba.dialect.OracleDialect.java
@Override public void importSchema(ImportParams params) throws MojoExecutionException { BufferedReader reader = null; try {/*from w ww. j ava 2s . co m*/ File dumpFile = params.getDumpFile(); if (!dumpFile.exists()) throw new MojoExecutionException(dumpFile.getName() + " is not found?"); String user = params.getAdminUser(); String password = params.getAdminPassword(); String schema = params.getSchema(); createDirectory(user, password, dumpFile.getParentFile()); // Oracle????? dropAllObjects(user, password, schema); ProcessBuilder pb = new ProcessBuilder("impdp", user + "/" + password, "directory=exp_dir", "dumpfile=" + dumpFile.getName(), "schemas=" + schema, "nologfile=y", "exclude=user"); pb.redirectErrorStream(true); Process process = pb.start(); Charset terminalCharset = System.getProperty("os.name").toLowerCase().contains("windows") ? Charset.forName("Shift_JIS") : Charset.forName("UTF-8"); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), terminalCharset)); //??????????????? String line; while ((line = reader.readLine()) != null) { System.out.println(line); } process.waitFor(); if (process.exitValue() != 0) { throw new MojoExecutionException("oracle import error"); } process.destroy(); } catch (Exception e) { throw new MojoExecutionException("oracle import", e); } finally { IOUtils.closeQuietly(reader); } }
From source file:org.zeroturnaround.exec.ProcessExecutor.java
private WaitForProcess startInternal(Process process, ExecuteStreamHandler streams, ByteArrayOutputStream out) throws IOException { if (streams != null) { try {//from w ww. jav a2 s . c o m streams.setProcessInputStream(process.getOutputStream()); streams.setProcessOutputStream(process.getInputStream()); if (!builder.redirectErrorStream()) streams.setProcessErrorStream(process.getErrorStream()); } catch (IOException e) { process.destroy(); throw e; } streams.start(); } Set<Integer> exitValues = allowedExitValues == null ? null : new HashSet<Integer>(allowedExitValues); WaitForProcess result = new WaitForProcess(process, exitValues, streams, out, listeners.clone()); // Invoke listeners - changing this executor does not affect the started process any more listeners.afterStart(process, this); return result; }
From source file:org.openremote.controller.protocol.shellexe.ShellExeCommand.java
private String executeCommand() { logger.debug("Will start shell command: " + commandPath + " and use params: " + commandParams); String result = ""; Process proc = null; try {//from w w w. ja v a2 s. c om // Use the commons-exec to parse correctly the arguments, respecting quotes and spaces to separate parameters final CommandLine cmdLine = new CommandLine(commandPath); if (commandParams != null) { cmdLine.addArguments(commandParams); } proc = Runtime.getRuntime().exec(cmdLine.toStrings()); final BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream())); final StringBuffer resultBuffer = new StringBuffer(); boolean first = true; for (String tmp = reader.readLine(); tmp != null; tmp = reader.readLine()) { if (!first) resultBuffer.append("\n"); first = false; resultBuffer.append(tmp); } result = resultBuffer.toString(); } catch (IOException e) { logger.error("Could not execute shell command: " + commandPath, e); } finally { if (proc != null) proc.destroy(); } logger.debug("Shell command: " + commandPath + " returned: " + result); return result; }
From source file:org.codelibs.fess.screenshot.impl.CommandGenerator.java
@Override public void generate(final String url, final File outputFile) { if (logger.isDebugEnabled()) { logger.debug("Generate ScreenShot: " + url); }//from www .j av a 2 s . co m if (outputFile.exists()) { if (logger.isDebugEnabled()) { logger.debug("The screenshot file exists: " + outputFile.getAbsolutePath()); } return; } final File parentFile = outputFile.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } if (!parentFile.isDirectory()) { logger.warn("Not found: " + parentFile.getAbsolutePath()); return; } final String outputPath = outputFile.getAbsolutePath(); final List<String> cmdList = new ArrayList<>(); for (final String value : commandList) { cmdList.add(value.replace("${url}", url).replace("${outputFile}", outputPath)); } ProcessBuilder pb = null; Process p = null; if (logger.isDebugEnabled()) { logger.debug("ScreenShot Command: " + cmdList); } TimerTask task = null; try { pb = new ProcessBuilder(cmdList); pb.directory(baseDir); pb.redirectErrorStream(true); p = pb.start(); task = new ProcessDestroyer(p, cmdList); try { destoryTimer.schedule(task, commandTimeout); String line; BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(p.getInputStream(), Charset.defaultCharset())); while ((line = br.readLine()) != null) { if (logger.isDebugEnabled()) { logger.debug(line); } } } finally { IOUtils.closeQuietly(br); } p.waitFor(); } catch (final Exception e) { p.destroy(); } } catch (final Exception e) { logger.warn("Failed to generate a screenshot of " + url, e); } if (task != null) { task.cancel(); task = null; } if (outputFile.isFile() && outputFile.length() == 0) { logger.warn("ScreenShot File is empty. URL is " + url); if (outputFile.delete()) { logger.info("Deleted: " + outputFile.getAbsolutePath()); } } if (logger.isDebugEnabled()) { logger.debug("ScreenShot File: " + outputPath); } }