List of usage examples for java.lang Process getOutputStream
public abstract OutputStream getOutputStream();
From source file:org.dbflute.maven.plugin.command.CommandExecutor.java
public void execute(String cmd) throws MojoExecutionException, MojoFailureException { File dbfluteClientDir = plugin.getDbfluteClientDir(); if (!dbfluteClientDir.isDirectory()) { LogUtil.getLog()/* www. j a va 2 s. c o m*/ .info("Create dbflute client directory. " + "Try to run \'mvn dbflute:create-client\'."); return; } List<String> cmds = new ArrayList<String>(); if (SystemUtil.isWindows()) { cmds.add("cmd.exe"); cmds.add("/c"); cmds.add(cmd + ".bat"); environment.put("pause_at_end", "n"); } else { cmds.add("/bin/bash"); cmds.add(cmd + ".sh"); } // TODO Mac? plugin.updateArgs(cmds); LogUtil.getLog().info("Running " + StringUtils.join(cmds.toArray(), " ")); ProcessBuilder builder = new ProcessBuilder(cmds); if (environment.size() > 0) { builder.environment().putAll(environment); } Process process; try { process = builder.directory(dbfluteClientDir).redirectErrorStream(true).start(); } catch (IOException e) { throw new MojoExecutionException("Could not run the command.", e); } try (InputStream stdin = process.getInputStream(); OutputStream stdout = process.getOutputStream()) { InputStreamThread ist = new InputStreamThread(stdin); OutputStreamThread ost = new OutputStreamThread(System.in, stdout); ist.start(); ost.start(); int exitValue = process.waitFor(); ist.join(); //ost.join(); if (exitValue != 0) { throw new MojoFailureException("Build Failed. The exit value is " + exitValue + "."); } } catch (InterruptedException e) { throw new MojoExecutionException("Could not wait a process.", e); } catch (IOException e) { throw new MojoExecutionException("I/O error.", e); } }
From source file:org.ops4j.pax.runner.platform.DefaultJavaRunner.java
/** * Create helper thread to safely shutdown the external framework process * * @param process framework process// w ww.jav a2 s. c om * * @return stream handler */ private Thread createShutdownHook(final Process process) { LOG.debug("Wrapping stream I/O."); final Pipe errPipe = new Pipe(process.getErrorStream(), System.err).start("Error pipe"); final Pipe outPipe = new Pipe(process.getInputStream(), System.out).start("Out pipe"); final Pipe inPipe = new Pipe(process.getOutputStream(), System.in).start("In pipe"); return new Thread(new Runnable() { public void run() { Info.println(); // print an empty line LOG.debug("Unwrapping stream I/O."); inPipe.stop(); outPipe.stop(); errPipe.stop(); try { process.destroy(); } catch (Exception e) { // ignore if already shutting down } } }, "Pax-Runner shutdown hook"); }
From source file:net.unicon.academus.spell.SpellCheckerServlet.java
/** * Perform the actual spellcheck operation using the aspell process. *///from w w w . j a v a 2 s . com private synchronized void performSpellCheck(PrintWriter out, String[] chk) throws Exception { ArrayList cmdline = new ArrayList(); cmdline.add(aspell_loc); cmdline.add("-a"); cmdline.add("--lang=" + lang); if (hasHTMLFilter) cmdline.add("--mode=html"); if (log.isDebugEnabled()) { StringBuffer cmd = new StringBuffer(); Iterator it = cmdline.iterator(); while (it.hasNext()) { cmd.append(it.next()).append(' '); } log.debug("Running aspell command: " + cmd.toString()); } Process p = Runtime.getRuntime().exec((String[]) cmdline.toArray(new String[0])); PrintWriter pout = new PrintWriter(p.getOutputStream()); // Start the reader thread. This is threaded so that we do not run into // problems with the input stream buffer running out prior to // processing the results. Thread inThread = new InReader(p.getInputStream(), chk, out); inThread.start(); for (int i = 0; i < chk.length; i++) { // Decode the input string if necessary. chk[i] = URLDecoder.decode(chk[i], ENCODING); // Force a line containing '*' to signal the input switch pout.println("%"); // Exit terse mode pout.println("^" + known_good); // Emit a known-good word pout.println("!"); // Enter terse mode String[] lines = chk[i].split("\n"); for (int k = 0; k < lines.length; k++) { pout.println(lines[k]); } pout.flush(); } // Close the input stream to signal completion to aspell pout.flush(); pout.close(); // Wait for input reader thread to finish. inThread.join(); // Kill the aspell process p.destroy(); log.debug("SpellCheckerServlet completed processing with aspell."); }
From source file:org.apache.tika.parser.ocr.TesseractOCRParser.java
/** * Run external tesseract-ocr process.//from w w w . j a v a 2 s . c om * * @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:org.nuxeo.ecm.platform.commandline.executor.service.executors.ShellExecutor.java
protected ExecResult exec1(CommandLineDescriptor cmdDesc, CmdParameters params, EnvironmentDescriptor env) throws IOException { // split the configured parameters while keeping quoted parts intact List<String> list = new ArrayList<>(); list.add(cmdDesc.getCommand());/*w ww. j ava 2 s. c o m*/ Matcher m = COMMAND_SPLIT.matcher(cmdDesc.getParametersString()); while (m.find()) { String word; if (m.group(1) != null) { word = m.group(1); // double-quoted } else if (m.group(2) != null) { word = m.group(2); // single-quoted } else { word = m.group(); // word } List<String> words = replaceParams(word, params); list.addAll(words); } List<Process> processes = new LinkedList<>(); List<Thread> pipes = new LinkedList<>(); List<String> command = new LinkedList<>(); Process process = null; for (Iterator<String> it = list.iterator(); it.hasNext();) { String word = it.next(); boolean build; if (word.equals("|")) { build = true; } else { // on Windows, look up the command in the PATH first if (command.isEmpty() && SystemUtils.IS_OS_WINDOWS) { command.add(getCommandAbsolutePath(word)); } else { command.add(word); } build = !it.hasNext(); } if (!build) { continue; } ProcessBuilder processBuilder = new ProcessBuilder(command); command = new LinkedList<>(); // reset for next loop processBuilder.directory(new File(env.getWorkingDirectory())); processBuilder.environment().putAll(env.getParameters()); processBuilder.redirectErrorStream(true); Process newProcess = processBuilder.start(); processes.add(newProcess); if (process == null) { // first process, nothing to input IOUtils.closeQuietly(newProcess.getOutputStream()); } else { // pipe previous process output into new process input // needs a thread doing the piping because Java has no way to connect two children processes directly // except through a filesystem named pipe but that can't be created in a portable manner Thread pipe = pipe(process.getInputStream(), newProcess.getOutputStream()); pipes.add(pipe); } process = newProcess; } // get result from last process @SuppressWarnings("null") BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; List<String> output = new ArrayList<>(); while ((line = reader.readLine()) != null) { output.add(line); } reader.close(); // wait for all processes, get first non-0 exit status int returnCode = 0; for (Process p : processes) { try { int exitCode = p.waitFor(); if (returnCode == 0) { returnCode = exitCode; } } catch (InterruptedException e) { ExceptionUtils.checkInterrupt(e); } } // wait for all pipes for (Thread t : pipes) { try { t.join(); } catch (InterruptedException e) { ExceptionUtils.checkInterrupt(e); } } return new ExecResult(null, output, 0, returnCode); }
From source file:com.doomy.padlock.MainFragment.java
public void superUserReboot(String mCommand) { Runtime mRuntime = Runtime.getRuntime(); Process mProcess = null; OutputStreamWriter mWrite = null; try {/*from www . ja v a2 s . c o m*/ mProcess = mRuntime.exec("su"); mWrite = new OutputStreamWriter(mProcess.getOutputStream()); mWrite.write(mCommand + "\n"); mWrite.flush(); mWrite.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.thoughtworks.go.agent.AgentProcessParentImplTest.java
private Process mockProcess(final InputStream outputStream, final InputStream errorStream, final OutputStream inputStream) throws InterruptedException { final Process subProcess = mock(Process.class); when(subProcess.waitFor()).thenReturn(42); when(subProcess.getInputStream()).thenReturn(outputStream); when(subProcess.getErrorStream()).thenReturn(errorStream); when(subProcess.getOutputStream()).thenReturn(inputStream); return subProcess; }
From source file:net.sourceforge.vulcan.maven.MavenBuildTool.java
@Override protected void preparePipes(final Process process) throws IOException { process.getOutputStream().close(); stdErrThread = new PipeThread("Maven stderr l [" + projectName + "]", process.getErrorStream(), stdErrStream);// w w w . j av a 2s .c om stdErrThread.start(); if (logFile == null) { process.getInputStream().close(); return; } final OutputStream logOutputStream = new FileOutputStream(logFile); logThread = new PipeThread("Maven Build Logger [" + projectName + "]", process.getInputStream(), logOutputStream); logThread.start(); }
From source file:org.opencastproject.dictionary.hunspell.DictionaryServiceImpl.java
/** * Run hunspell with text as input.// ww w .j a v a 2 s. co m **/ public LinkedList<String> runHunspell(String text) throws Throwable { // create a new list of arguments for our process String commandLine = binary + ' ' + command; String[] commandList = commandLine.split("\\s+"); InputStream stdout = null; InputStream stderr = null; OutputStream stdin = null; Process p = null; BufferedReader bufr = null; LinkedList<String> words = new LinkedList<String>(); logger.info("Executing hunspell command '{}'", StringUtils.join(commandList, " ")); p = new ProcessBuilder(commandList).start(); stderr = p.getErrorStream(); stdout = p.getInputStream(); stdin = p.getOutputStream(); /* Pipe text through hunspell for filtering */ stdin.write(text.getBytes("UTF-8")); stdin.flush(); stdin.close(); /* Get output of hunspell */ String line; bufr = new BufferedReader(new InputStreamReader(stdout, "UTF-8")); while ((line = bufr.readLine()) != null) { words.add(line); } bufr.close(); /* Get error messages */ bufr = new BufferedReader(new InputStreamReader(stderr)); while ((line = bufr.readLine()) != null) { logger.warn(line); } bufr.close(); if (p.waitFor() != 0) { logger.error("Hunspell reported an error (Missing dictionaries?)"); throw new IllegalStateException("Hunspell returned error code"); } return words; }
From source file:com.SecUpwN.AIMSICD.smsdetection.SmsDetector.java
@Override public void run() { setSmsDetectionState(true);/*from www .j av a2s . co m*/ try { try { new Thread().sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } try { String MODE = "logcat -b radio\n";// default Runtime r = Runtime.getRuntime(); Process process = r.exec("su"); dos = new DataOutputStream(process.getOutputStream()); dos.writeBytes(MODE); dos.flush(); dis = new DataInputStream(process.getInputStream()); } catch (IOException e) { e.printStackTrace(); } while (getSmsDetectionState()) { try { int bufferlen = dis.available(); //System.out.println("DEBUG>> Buff Len " +bufferlen); if (bufferlen != 0) { byte[] b = new byte[bufferlen]; dis.read(b); String split[] = new String(b).split("\n"); checkForSilentSms(split); } else { Thread.sleep(1000); } } catch (IOException e) { if (e.getMessage() != null) System.out.println(e.getMessage()); e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } finally { } }