Example usage for java.lang Process getOutputStream

List of usage examples for java.lang Process getOutputStream

Introduction

In this page you can find the example usage for java.lang Process getOutputStream.

Prototype

public abstract OutputStream getOutputStream();

Source Link

Document

Returns the output stream connected to the normal input of the process.

Usage

From source file:de.tarent.maven.plugins.pkg.Utils.java

/**
 * A method which makes executing programs easier.
 * //from  ww w.j a  va  2 s  .  c o m
 * @param args
 * @param failureMsg
 * @param ioExceptionMsg
 * @throws MojoExecutionException
 */
public static InputStream exec(String[] args, File workingDir, String failureMsg, String ioExceptionMsg,
        String userInput) throws MojoExecutionException {
    /*
     * debug code which prints out the execution command-line. Enable if
     * neccessary. for(int i=0;i<args.length;i++) { System.err.print(args[i]
     * + " "); } System.err.println();
     */

    // Creates process with the defined language setting of LC_ALL=C
    // That way the textual output of certain commands is predictable.
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(workingDir);
    Map<String, String> env = pb.environment();
    env.put("LC_ALL", "C");

    Process p = null;

    try {

        p = pb.start();

        if (userInput != null) {
            PrintWriter writer = new PrintWriter(
                    new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
            writer.println(userInput);
            writer.flush();
            writer.close();
        }
        int exitValue = p.waitFor();
        if (exitValue != 0) {
            print(p);
            throw new MojoExecutionException(
                    String.format("(Subprocess exit value = %s) %s", exitValue, failureMsg));
        }
    } catch (IOException ioe) {
        throw new MojoExecutionException(ioExceptionMsg + " :" + ioe.getMessage(), ioe);
    } catch (InterruptedException ie) {
        // Cannot happen.
        throw new MojoExecutionException("InterruptedException", ie);
    }
    return p.getInputStream();
}

From source file:com.doomy.padlock.MainActivity.java

public void androidDebugBridge(String mPort) {
    Runtime mRuntime = Runtime.getRuntime();
    Process mProcess = null;
    OutputStreamWriter mWrite = null;

    try {//  w w w  .  j  a v a2 s .c  o  m
        mProcess = mRuntime.exec("su");
        mWrite = new OutputStreamWriter(mProcess.getOutputStream());
        mWrite.write("setprop service.adb.tcp.port " + mPort + "\n");
        mWrite.flush();
        mWrite.write("stop adbd\n");
        mWrite.flush();
        mWrite.write("start adbd\n");
        mWrite.flush();
        mWrite.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:io.syndesis.verifier.LocalProcessVerifier.java

private Properties runValidator(String classpath, Verifier.Scope scope, String camelPrefix, Properties request)
        throws IOException, InterruptedException {
    Process java = new ProcessBuilder().command("java", "-classpath", classpath,
            "io.syndesis.connector.ConnectorVerifier", scope.toString(), camelPrefix)
            .redirectError(ProcessBuilder.Redirect.INHERIT).start();

    try (OutputStream os = java.getOutputStream()) {
        request.store(os, null);/*  w ww .jav a 2  s.co m*/
    }
    Properties result = new Properties();
    try (InputStream is = java.getInputStream()) {
        result.load(is);
    }

    if (java.waitFor() != 0) {
        throw new IOException("Verifier failed with exit code: " + java.exitValue());
    }
    return result;
}

From source file:com.otaupdater.DownloadsActivity.java

private void flashFiles(String[] files, boolean backup, boolean wipeCache, boolean wipeData) {
    try {/* w  w  w .ja  va2s  . c  om*/
        Process p = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(p.getOutputStream());
        os.writeBytes("mkdir -p /cache/recovery/\n");
        os.writeBytes("rm -f /cache/recovery/command\n");
        os.writeBytes("rm -f /cache/recovery/extendedcommand\n");
        os.writeBytes("echo 'boot-recovery' >> /cache/recovery/command\n");

        //no official cwm for sony, so use extendedcommand. sony devices cannot use regular command file
        if (Build.MANUFACTURER.toLowerCase(Locale.US).contains("sony")) {
            if (backup) {
                os.writeBytes("echo 'backup_rom /sdcard/clockworkmod/backup/ota_"
                        + new SimpleDateFormat("yyyy-MM-dd_HH.mm", Locale.US).format(new Date())
                        + "' >> /cache/recovery/extendedcommand\n");
            }
            if (wipeData) {
                os.writeBytes("echo 'format(\"/data\");' >> /cache/recovery/extendedcommand\n");
            }
            if (wipeCache) {
                os.writeBytes("echo 'format(\"/cache\");' >> /cache/recovery/extendedcommand\n");
            }

            for (String file : files) {
                os.writeBytes("echo 'install_zip(\"" + file + "\");' >> /cache/recovery/extendedcommand\n");
            }
        } else {
            if (backup) {
                os.writeBytes("echo '--nandroid' >> /cache/recovery/command\n");
            }
            if (wipeData) {
                os.writeBytes("echo '--wipe_data' >> /cache/recovery/command\n");
            }
            if (wipeCache) {
                os.writeBytes("echo '--wipe_cache' >> /cache/recovery/command\n");
            }

            for (String file : files) {
                os.writeBytes("echo '--update_package=" + file + "' >> /cache/recovery/command\n");
            }
        }

        String rebootCmd = PropUtils.getRebootCmd();
        if (!rebootCmd.equals("$$NULL$$")) {
            os.writeBytes("sync\n");
            if (rebootCmd.endsWith(".sh")) {
                os.writeBytes("sh " + rebootCmd + "\n");
            } else {
                os.writeBytes(rebootCmd + "\n");
            }
        }

        os.writeBytes("sync\n");
        os.writeBytes("exit\n");
        os.flush();
        p.waitFor();
        ((PowerManager) getSystemService(POWER_SERVICE)).reboot("recovery");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.github.horrorho.inflatabledonkey.RawProtoDecoder.java

public String decodeProto(InputStream protoBytes) throws IOException, InterruptedException {
    try {//from  w  w w . ja v  a2s  . c o  m
        Process exec;

        try {
            exec = Runtime.getRuntime().exec(protocPath + " --decode_raw");

        } catch (IOException ex) {
            logger.warn("-- decodeProto() - protoc exec error: {}", ex.getMessage());
            return "error";
        }

        try (OutputStream execOut = exec.getOutputStream()) {
            IOUtils.copy(protoBytes, execOut);
        }

        boolean completed = exec.waitFor(15, TimeUnit.SECONDS);

        try (BufferedReader br = new BufferedReader(new InputStreamReader(exec.getInputStream()))) {
            StringWriter decoded = new StringWriter();
            PrintWriter print = new PrintWriter(decoded);

            br.lines().forEach(print::println);

            return decoded.toString() + (completed ? "" : "\nIncomplete\n");
        }

    } finally {
        protoBytes.close();
    }
}

From source file:org.ctuning.openme.openme.java

public static String[] openme_run_program(String cmd, String[] env, String path) {
    /*/*from  w w  w. jav  a2  s . c  o m*/
       FGG: TBD - call local cM
            
       Input:  cmd  - command line to run
       env  - list of environment variables
       path - directory where to start program
            
       Output: string list:
         [0] - error text
         [1] - stdout output
         [2] - stderr output
    */

    File dir = null;
    if (path != null)
        dir = new File(path); //getCacheDir();

    Process p = null;
    String output = "";
    String eoutput = "";
    String err = "";

    try {
        p = Runtime.getRuntime().exec(cmd, env, dir);

        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

        BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream()));

        String line = null;
        while ((line = reader.readLine()) != null)
            output += line + '\n';

        while ((line = stderr.readLine()) != null)
            eoutput += line + '\n';

        reader.close();
        stderr.close();
        p.waitFor();
    } catch (Exception e) {
        err = e.toString();
    }

    if (p != null) {
        try {
            p.getOutputStream().close();
            p.getInputStream().close();
            p.getErrorStream().close();
        } catch (IOException e) {
            err = e.toString();
        }
    }

    return new String[] { err, output, eoutput };
}

From source file:CustomSubmitter.java

/**
 * Submits the specified PBS job to the PBS queue using the {@code qsub}
 * program.//  w w w .  java 2s .com
 * 
 * @param job the PBS job to be submitted
 * @throws IOException if an error occurred while invoking {@code qsub}
 */
public void submit(PBSJob job) throws IOException {
    Process process = new ProcessBuilder("qsub").start();

    RedirectStream.redirect(process.getInputStream(), System.out);
    RedirectStream.redirect(process.getErrorStream(), System.err);

    String script = toPBSScript(job);
    System.out.println(script);

    PrintStream ps = new PrintStream(process.getOutputStream());
    ps.print(script);
    ps.close();

    try {
        int exitStatus = process.waitFor();

        if (exitStatus != 0) {
            throw new IOException("qsub terminated with exit status " + exitStatus);
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

From source file:com.nabla.project.application.tool.runner.ServiceInvoker.java

private void invokeInNewJVM(MethodInvocation invocation) {

    try {/*  ww w.jav a2  s  .  c  o m*/

        checkInvocationArgumentsForJVMTransfer(invocation.getArguments());

        String classpath = System.getProperty("java.class.path");

        if (newVMClasspathRoot != null) {

            classpath = generateClassPath(newVMClasspathRoot);

        }

        ProcessBuilder pb = new ProcessBuilder(new String[] { "java", "-classpath", classpath,
                "com.nabla.project.application.tool.runner.ServiceRunner", newVMconfigFileName,
                newVMServiceBeanName, invocation.getMethod().getName() });
        Process p = pb.start();

        ObjectOutputStream oos = new ObjectOutputStream(p.getOutputStream());

        oos.writeObject(invocation.getArguments());
        oos.flush();

    } catch (Exception ioe) {

        throw new RuntimeException(ioe);

    }

}

From source file:org.hyperic.hq.plugin.postgresql.PostgreSQLServerDetector.java

private String getVersion(String exec) {
    String command[] = { exec, "--version" };
    log.debug("[getVersionString] command= '" + Arrays.asList(command) + "'");
    String version = "";
    try {/* ww w.  j ava2  s.  c  o  m*/
        Process cmd = Runtime.getRuntime().exec(command);
        cmd.getOutputStream().close();
        cmd.waitFor();
        String out = inputStreamAsString(cmd.getInputStream());
        String err = inputStreamAsString(cmd.getErrorStream());
        if (log.isDebugEnabled()) {
            if (cmd.exitValue() != 0) {
                log.error("[getVersionString] exit=" + cmd.exitValue());
                log.error("[getVersionString] out=" + out);
                log.error("[getVersionString] err=" + err);
            } else {
                log.debug("[getVersionString] out=" + out);
            }
        }
        version = out;
    } catch (InterruptedException ex) {
        log.debug("[getVersionString] Error:" + ex.getMessage(), ex);
    } catch (IOException ex) {
        log.debug("[getVersionString] Error:" + ex.getMessage(), ex);
    }
    return version;
}

From source file:net.sourceforge.vulcan.ant.AntBuildTool.java

/**
 * Subclasses may override this method to perform custom handling of
 * I/O.  The default behavior is to close all streams.
 *//*from   w  ww . ja v  a 2 s  .c o  m*/
protected void preparePipes(final Process process) throws IOException {
    process.getOutputStream().close();
    process.getInputStream().close();
    process.getErrorStream().close();
}