List of usage examples for java.lang Process getOutputStream
public abstract OutputStream getOutputStream();
From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java
@SuppressWarnings("deprecation") public String runAsRoot(String command) { String output = new String(); try {/* w w w . j a v a2s . c o m*/ Process p = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(p.getOutputStream()); DataInputStream is = new DataInputStream(p.getInputStream()); os.writeBytes(command + "\n"); os.flush(); String line = new String(); while ((line = is.readLine()) != null) { output = output + line; } os.writeBytes("exit\n"); os.flush(); } catch (Throwable e) { Log.i(MyApp.TAG, e.getMessage().toString()); } return output; }
From source file:org.apache.tika.parser.ocr.TesseractOCRParser.java
/** * Run external tesseract-ocr process.//from w ww .j av a 2 s . 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(), config.getOutputType().name().toLowerCase(Locale.US), "-c", (config.getPreserveInterwordSpacing()) ? "preserve_interword_spaces=1" : "preserve_interword_spaces=0" }; 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<>(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.jpmorgan.cakeshop.bean.QuorumConfigBean.java
public void createKeys(final String keyName, final String destination) throws IOException, InterruptedException { constellationConfig = destination;/* ww w. j a v a 2s .c o m*/ File dir = new File(destination); Boolean createKeys = true; if (!dir.exists()) { dir.mkdirs(); } else { String[] fileNames = dir.list(); if (fileNames.length >= 4) { for (String fileName : fileNames) { if (fileName.endsWith(".key") || fileName.endsWith(".pub")) { createKeys = false; break; } } } } if (createKeys) { //create keys ProcessBuilder pb = new ProcessBuilder(getKeyGen(), destination.concat(keyName)); Process process = pb.start(); try (Scanner scanner = new Scanner(process.getInputStream())) { boolean flag = scanner.hasNext(); try (BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(process.getOutputStream()))) { while (flag) { String line = scanner.next(); if (line.isEmpty()) { continue; } if (line.contains("[none]:")) { writer.newLine(); writer.flush(); writer.newLine(); writer.flush(); flag = false; } } } } int ret = process.waitFor(); if (ret != 0) { LOG.error( "Failed to generate keys. Please make sure that berkeley db is installed properly. Version of berkeley db is 6.2.23"); } else { //create archive keys pb = new ProcessBuilder(getKeyGen(), destination.concat(keyName.concat("a"))); process = pb.start(); try (Scanner scanner = new Scanner(process.getInputStream())) { boolean flag = scanner.hasNext(); try (BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(process.getOutputStream()))) { while (flag) { String line = scanner.next(); if (line.isEmpty()) { continue; } if (line.contains("[none]:")) { writer.write(" "); writer.flush(); writer.newLine(); writer.flush(); flag = false; } } } } ret = process.waitFor(); if (ret != 0) { LOG.error( "Failed to generate keys. Please make sure that berkeley db is installed properly. Version of berkeley db is 6.2.23"); } } if (process.isAlive()) { process.destroy(); } } }
From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java
@SuppressWarnings("deprecation") public String runAsUser(String command) { String output = new String(); try {//from ww w. ja v a 2s. c o m Process p = Runtime.getRuntime().exec("sh"); DataOutputStream os = new DataOutputStream(p.getOutputStream()); DataInputStream is = new DataInputStream(p.getInputStream()); os.writeBytes("exec " + command + "\n"); os.flush(); String line = new String(); while ((line = is.readLine()) != null) { output = output + line; } // os.writeBytes("exit\n"); os.flush(); p.waitFor(); } catch (Throwable e) { Log.i(MyApp.TAG, e.getMessage().toString()); } return output; }
From source file:eu.eexcess.partnerwizard.webservice.WizardRESTService.java
public String cmdExecute(ArrayList<String> commands) { Process shell = null; DataOutputStream out = null;/*from w w w. j av a 2s. c o m*/ BufferedReader in = null; StringBuilder processOutput = new StringBuilder(); processOutput.append(new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime())) .append("\n"); try { shell = Runtime.getRuntime().exec("cmd");//su if needed out = new DataOutputStream(shell.getOutputStream()); in = new BufferedReader(new InputStreamReader(shell.getInputStream())); // Executing commands for (String command : commands) { LOGGER.info("executing:\n" + command); out.writeBytes(command + "\n"); out.flush(); } out.writeBytes("exit\n"); out.flush(); String line; while ((line = in.readLine()) != null) { processOutput.append(line).append("\n"); } //LOGGER.info("result:\n" + processOutput); processOutput.append(new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime())) .append("\n"); String output = processOutput.toString(); shell.waitFor(); LOGGER.info(processOutput.toString()); LOGGER.info("finished!"); return output; } catch (Exception e) { } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } // shell.destroy(); } catch (Exception e) { // hopeless } } return ""; }
From source file:org.codesearch.commons.plugins.vcs.GitLocalPlugin.java
private void cleanupProcess(Process p) { if (p != null) { try {/*from w w w . j a va2s.c om*/ p.getErrorStream().close(); } catch (IOException ex) { } try { p.getInputStream().close(); } catch (IOException ex) { } try { p.getOutputStream().close(); } catch (IOException ex) { } p.destroy(); } }
From source file:ru.anr.cmdline.utils.SimpleOsCommand.java
/** * Execute specified command//www. j a v a 2s. c o m * * @param command * An os command * @return Command result (stdout or stderr) * @throws IOException * When error with result processing occures */ public String execute(String command) throws IOException { StringBuilder sb = new StringBuilder(); final File root = new File("."); // Starting from a current directory try { final Process p = Runtime.getRuntime().exec(command, null, root); Reader input = new InputStreamReader(p.getInputStream()); Reader errors = new InputStreamReader(p.getErrorStream()); for (String s : IOUtils.readLines(input)) { // stdout sb.append(s); sb.append(OsUtils.LINE_SEPARATOR); } for (String s : IOUtils.readLines(errors)) { // stderr sb.append(s); sb.append(OsUtils.LINE_SEPARATOR); } p.getOutputStream().close(); if (p.waitFor() != 0) { logger.error("The command '{}' did not complete successfully", command); } } catch (final InterruptedException e) { throw new IllegalStateException(e); } return sb.toString(); }
From source file:org.gradle.vcs.fixtures.GitHttpRepository.java
public void expectCloneSomething() { server.expect(server.get(backingRepo.getName() + "/info/refs", getRefsAction())); server.expect(server.post(backingRepo.getName() + "/git-upload-pack", new ErroringAction<HttpExchange>() { @Override//from w w w . j a v a 2s . co m protected void doExecute(HttpExchange httpExchange) throws Exception { httpExchange.getResponseHeaders().add("content-type", "application/x-git-upload-pack-result"); httpExchange.sendResponseHeaders(200, 0); ProcessBuilder builder = new ProcessBuilder(); final Process process = builder.command("git", "upload-pack", "--stateless-rpc", backingRepo.getWorkTree().getAbsolutePath()).redirectErrorStream(true).start(); InputStream instream = new GZIPInputStream(httpExchange.getRequestBody()); ByteArrayOutputStream requestContent = new ByteArrayOutputStream(); IOUtils.copy(instream, requestContent); byte[] bytes = requestContent.toByteArray(); process.getOutputStream().write(bytes); process.getOutputStream().flush(); IOUtils.copy(process.getInputStream(), httpExchange.getResponseBody()); int result = process.waitFor(); if (result != 0) { throw new RuntimeException("Failed to run git upload-pack"); } } })); }
From source file:io.syndesis.verifier.LocalProcessVerifier.java
private String getConnectorClasspath(Connector connector) throws IOException, InterruptedException { byte[] pom = new byte[0]; // TODO: Fix generation to use an Action projectGenerator.generatePom(connector); java.nio.file.Path tmpDir = Files.createTempDirectory("syndesis-connector"); try {/* w w w . j av a 2 s . c o m*/ Files.write(tmpDir.resolve("pom.xml"), pom); ArrayList<String> args = new ArrayList<>(); args.add("mvn"); args.add("org.apache.maven.plugins:maven-dependency-plugin:3.0.0:build-classpath"); if (localMavenRepoLocation != null) { args.add("-Dmaven.repo.local=" + localMavenRepoLocation); } ProcessBuilder builder = new ProcessBuilder().command(args) .redirectError(ProcessBuilder.Redirect.INHERIT).directory(tmpDir.toFile()); Map<String, String> environment = builder.environment(); environment.put("MAVEN_OPTS", "-Xmx64M"); Process mvn = builder.start(); try { String result = parseClasspath(mvn.getInputStream()); if (mvn.waitFor() != 0) { throw new IOException( "Could not get the connector classpath, mvn exit value: " + mvn.exitValue()); } return result; } finally { mvn.getInputStream().close(); mvn.getOutputStream().close(); } } finally { FileSystemUtils.deleteRecursively(tmpDir.toFile()); } }
From source file:org.archive.modules.writer.Kw3WriterProcessor.java
private void chmod(File file, String permissions) { Process proc = null; try {// w ww . java2 s. c o m proc = Runtime.getRuntime().exec("chmod " + permissions + " " + file.getAbsolutePath()); proc.waitFor(); proc.getInputStream().close(); proc.getOutputStream().close(); proc.getErrorStream().close(); } catch (IOException e) { logger.log(Level.WARNING, "chmod failed", e); } catch (InterruptedException e) { logger.log(Level.WARNING, "chmod failed", e); } }