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:com.gnuroot.debian.GNURootMain.java

private void exec(String command, boolean setError) {
    Runtime runtime = Runtime.getRuntime();
    Process process;
    try {//from   w ww. ja va  2  s .  co m
        process = runtime.exec(command);
        try {
            String str;
            process.waitFor();
            BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            while ((str = stdError.readLine()) != null) {
                Log.e("Exec", str);
                if (setError)
                    errOcc = true;
            }
            process.getInputStream().close();
            process.getOutputStream().close();
            process.getErrorStream().close();
        } catch (InterruptedException e) {
            if (setError)
                errOcc = true;
        }
    } catch (IOException e1) {
        errOcc = true;
    }
}

From source file:org.neo4j.server.enterprise.ArbiterBootstrapperIT.java

private boolean startArbiter(File configDir, CountDownLatch latch) throws Exception {
    Process process = null;
    ProcessStreamHandler handler = null;
    try {/* w  ww  .j a  v  a  2 s . c o  m*/
        process = startArbiterProcess(configDir);
        new InputStreamAwaiter(process.getInputStream()).awaitLine(START_SIGNAL, 20, SECONDS);
        handler = new ProcessStreamHandler(process, false, "", IGNORE_FAILURES);
        handler.launch();

        // Latch is triggered when the arbiter we just spawned joins the cluster,
        // or rather when the first client sees it as joined. If the latch awaiting times out it
        // (most likely) means that the arbiter couldn't be started. The reason for not
        // being able to start is assumed in this test to be that the specified port already is in use.
        return latch.await(10, SECONDS);
    } finally {
        if (process != null) {
            // Tell it to leave the cluster and shut down now
            try (OutputStream inputToOtherProcess = process.getOutputStream()) {
                inputToOtherProcess.write(0);
                inputToOtherProcess.flush();
            }
            if (!process.waitFor(10, SECONDS)) {
                kill(process);
            }
        }
        if (handler != null) {
            handler.done();
        }
    }
}

From source file:org.pentaho.di.job.entries.spark.JobEntrySparkSubmit.java

private void prepareProcessThreadsToStop(Process proc, Thread errorLoggerThread, Thread outputLoggerThread)
        throws Exception {
    if (blockExecution) {
        waitForThreadsFinishToRead(errorLoggerThread, outputLoggerThread);
    } else {//from ww  w  . j a v  a 2s .co m
        killChildProcesses();
    }
    // close the streams
    // otherwise you get "Too many open files, java.io.IOException" after a lot of iterations
    proc.getErrorStream().close();
    proc.getOutputStream().close();
}

From source file:com.ah.ui.actions.admin.UsersAction.java

/**
 * synchronize shell admin password with HM admin password
 *///  w w  w  . j  a va 2s. c o m
private void updateShellAdminPwd() {
    try {
        String password = adminPassword;

        String[] cmd = { "bash", "-c", "passwd admin" };
        Process proc = Runtime.getRuntime().exec(cmd);

        PrintWriter out = new PrintWriter(new OutputStreamWriter(proc.getOutputStream()));
        // new password
        out.println(password);
        out.flush();

        // confirm password
        out.println(password);
        out.flush();
    } catch (Exception e) {
        log.error("updateAdminShellPwd", "catch exception", e);
    }
}

From source file:org.fusesource.meshkeeper.distribution.provisioner.embedded.Execute.java

/**
 * Runs a process defined by the command line and returns its exit status.
 *
 * @return the exit status of the subprocess or <code>INVALID</code>.
 * @exception java.io.IOException The exception is thrown, if launching
 *            of the subprocess failed./* w w  w.j av a  2 s .  co  m*/
 */
public int execute() throws IOException {
    if (workingDirectory != null && !workingDirectory.exists()) {
        throw new ProvisionerException(workingDirectory + " doesn't exist.");
    }
    final Process process = launch(getCommandline(), getEnvironment(), workingDirectory, useVMLauncher);
    try {
        streamHandler.setProcessInputStream(process.getOutputStream());
        streamHandler.setProcessOutputStream(process.getInputStream());
        streamHandler.setProcessErrorStream(process.getErrorStream());
    } catch (IOException e) {
        process.destroy();
        throw e;
    }
    streamHandler.start();

    try {

        waitFor(process);

        streamHandler.stop();
        closeStreams(process);

        return getExitValue();
    } catch (ThreadDeath t) {
        // #31928: forcibly kill it before continuing.
        process.destroy();
        throw t;
    } finally {
    }
}

From source file:org.pshdl.model.simulation.codegenerator.GoCodeGenerator.java

public IHDLInterpreterFactory<NativeRunner> createInterpreter(final File tempDir) {
    try {/*from   ww  w. ja  va2 s .  com*/
        IHDLInterpreterFactory<NativeRunner> _xblockexpression = null;
        {
            final CharSequence dartCode = this.generateMainCode();
            final File dutFile = new File(tempDir, "TestUnit.go");
            Files.createParentDirs(dutFile);
            Files.write(dartCode, dutFile, StandardCharsets.UTF_8);
            final File testRunner = new File(tempDir, "runner.go");
            final InputStream runnerStream = CCodeGenerator.class
                    .getResourceAsStream("/org/pshdl/model/simulation/includes/runner.go");
            final FileOutputStream fos = new FileOutputStream(testRunner);
            try {
                ByteStreams.copy(runnerStream, fos);
            } finally {
                fos.close();
            }
            String _absolutePath = testRunner.getAbsolutePath();
            String _absolutePath_1 = dutFile.getAbsolutePath();
            ProcessBuilder _processBuilder = new ProcessBuilder("/usr/local/go/bin/go", "build", _absolutePath,
                    _absolutePath_1);
            ProcessBuilder _directory = _processBuilder.directory(tempDir);
            ProcessBuilder _redirectErrorStream = _directory.redirectErrorStream(true);
            final ProcessBuilder goBuilder = _redirectErrorStream.inheritIO();
            final Process goCompiler = goBuilder.start();
            int _waitFor = goCompiler.waitFor();
            boolean _notEquals = (_waitFor != 0);
            if (_notEquals) {
                throw new RuntimeException("Compilation of Go Program failed");
            }
            _xblockexpression = new IHDLInterpreterFactory<NativeRunner>() {
                public NativeRunner newInstance() {
                    try {
                        final File runnerExecutable = new File(tempDir, "runner");
                        String _absolutePath = runnerExecutable.getAbsolutePath();
                        ProcessBuilder _processBuilder = new ProcessBuilder(_absolutePath);
                        ProcessBuilder _directory = _processBuilder.directory(tempDir);
                        final ProcessBuilder goBuilder = _directory.redirectErrorStream(true);
                        final Process goRunner = goBuilder.start();
                        InputStream _inputStream = goRunner.getInputStream();
                        OutputStream _outputStream = goRunner.getOutputStream();
                        String _absolutePath_1 = runnerExecutable.getAbsolutePath();
                        return new NativeRunner(_inputStream, _outputStream, GoCodeGenerator.this.em, goRunner,
                                5, _absolutePath_1);
                    } catch (Throwable _e) {
                        throw Exceptions.sneakyThrow(_e);
                    }
                }
            };
        }
        return _xblockexpression;
    } catch (Throwable _e) {
        throw Exceptions.sneakyThrow(_e);
    }
}

From source file:org.intermine.install.swing.CreateDatabaseWorker.java

/**
 * Create a database using the Postgres <code>createdb</code> program.
 * /*from  w ww. j a v  a 2  s  .c om*/
 * @param server The database server.
 * @param databaseName The database name.
 * @param userName The database user name.
 * @param password The user password.
 * @param encoding The encoding for the database.
 * 
 * @throws IOException if there is a problem running <code>createdb</code>.
 *  
 * @throws InterruptedException if the thread is interrupted while running
 * the <code>createdb</code>.
 * 
 * @throws DatabaseCreationException if the process completes but failed
 * to create the database.
 */
protected void createDatabaseWithCreatedb(String server, String databaseName, String userName, String password,
        String encoding) throws IOException, InterruptedException, DatabaseCreationException {

    String[] commands = { "/usr/bin/createdb", "-h", server, "-E", encoding, "-O", userName, "-W", "-T",
            "template0", databaseName };

    if (logger.isDebugEnabled()) {
        StringBuilder command = new StringBuilder();
        for (int i = 0; i < commands.length; i++) {
            if (i > 0) {
                command.append(' ');
            }
            command.append(commands[i]);
        }
        logger.debug(command);
    }

    StringBuilder output = new StringBuilder();
    StringBuilder errorOutput = new StringBuilder();

    Integer exitCode = null;
    Process p = Runtime.getRuntime().exec(commands);
    try {
        BufferedReader stdin = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        boolean passwordSet = false;
        while (true) {
            try {
                while (stdin.ready()) {
                    char c = (char) stdin.read();
                    output.append(c);
                }
                while (stderr.ready()) {
                    char c = (char) stderr.read();
                    errorOutput.append(c);
                }

                if (!passwordSet && errorOutput.indexOf("Password:") >= 0) {
                    PrintStream out = new PrintStream(p.getOutputStream(), true);
                    out.println(password);
                    passwordSet = true;
                }

                exitCode = p.exitValue();
                // If this succeeds, we're done.
                break;
            } catch (IllegalThreadStateException e) {
                // Process not done, so wait and continue.
                Thread.sleep(250);
            }
        }
    } finally {
        try {
            p.exitValue();
        } catch (IllegalThreadStateException e) {
            // Not finished, but something has failed.
            p.destroy();
        }
    }

    if (errorOutput.length() > 0) {
        throw new DatabaseCreationException(exitCode, output.toString(), errorOutput.toString());
    }

    if (exitCode != 0) {
        throw new DatabaseCreationException("Return code from createdb = " + exitCode, exitCode,
                output.toString(), errorOutput.toString());
    }
}

From source file:com.hijacker.MainActivity.java

static boolean createReport(File out, String filesDir, String stackTrace, Process shell) {
    if (!out.exists()) {
        try {//w  ww .ja va  2  s  . co m
            if (!out.createNewFile())
                return false;
        } catch (IOException e) {
            Log.e("HIJACKER/createReport", e.toString());
            return false;
        }
    }
    String busybox_tmp = filesDir + "/bin/busybox";
    PrintWriter shell_in = new PrintWriter(shell.getOutputStream());
    BufferedReader shell_out = new BufferedReader(new InputStreamReader(shell.getInputStream()));

    FileWriter writer = null;
    try {
        writer = new FileWriter(out, true);
        writer.write("\n--------------------------------------------------------------------------------\n");
        writer.write("Hijacker report - " + new Date().toString() + "\n\n");
        writer.write("Android version: " + Build.VERSION.SDK_INT + '\n');
        writer.write("Device: " + deviceModel + '\n');
        writer.write("App version: " + versionName + " (" + versionCode + ")\n");
        writer.write("App data path: " + filesDir + '\n');
        if (stackTrace != null)
            writer.write("\nStack trace:\n" + stackTrace + '\n');

        String cmd = "echo pref_file--------------------------------------; cat /data/data/com.hijacker/shared_prefs/com.hijacker_preferences.xml;";
        cmd += " echo app directory----------------------------------; " + busybox_tmp + " ls -lR " + filesDir
                + ';';
        cmd += " echo fw_bcmdhd--------------------------------------; strings /vendor/firmware/fw_bcmdhd.bin | grep \"FWID:\";";
        cmd += " echo ps---------------------------------------------; ps | " + busybox_tmp
                + " grep -e air -e mdk -e reaver;";
        cmd += " echo busybox----------------------------------------; " + busybox_tmp + ";";
        cmd += " echo logcat-----------------------------------------; logcat -d -v time | " + busybox_tmp
                + " grep HIJACKER;";
        cmd += " exit\n";
        Log.d("HIJACKER/createReport", cmd);
        shell_in.print(cmd);
        shell_in.flush();

        String buffer = shell_out.readLine();
        while (buffer != null) {
            writer.write(buffer + '\n');
            buffer = shell_out.readLine();
        }

        writer.close();
    } catch (IOException e) {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException ignored) {
            }
        }
        return false;
    }
    return true;
}

From source file:net.firejack.platform.model.service.reverse.ReverseEngineeringService.java

private File generate(String wsdl, String domain) throws IOException, InterruptedException {
    String name = SecurityHelper.generateRandomSequence(16);
    File temp = new File(FileUtils.getTempDirectory(), name);
    FileUtils.forceMkdir(temp);//from w w w .j ava 2  s . c  om

    Process exec = Runtime.getRuntime().exec(new String[] { "wsimport", "-d", temp.getPath(), "-p",
            "wsdl." + domain, "-target", "2.1", "-extension", wsdl });
    exec.getInputStream().close();
    exec.getErrorStream().close();
    exec.getOutputStream().close();
    exec.waitFor();

    return temp;
}

From source file:mitm.common.util.ProcessRunner.java

public int run(List<String> cmd) throws IOException {
    if (cmd == null || cmd.size() == 0) {
        throw new IllegalArgumentException("cmd is invalid.");
    }/*from   w ww .j  a  v  a  2s .c  o m*/

    /*
     * Used to show which command was executed
     */
    String cmdLine = logArguments ? StringUtils.join(cmd, ",") : cmd.get(0);

    logger.debug("Starting application. cmdLine: " + cmdLine);

    /*
     * Watchdog that will be used to destroy the process on a timeout
     */
    TaskScheduler watchdog = new TaskScheduler(ProcessRunner.class.getCanonicalName() + "#" + cmdLine);

    try {
        ProcessBuilder processBuilder = new ProcessBuilder(cmd);

        Process process = processBuilder.start();

        if (timeout > 0) {
            /*
             * Task that will destroy the process on a timeout
             */
            Task processWatchdogTask = new DestroyProcessTimeoutTask(process, watchdog.getName());

            watchdog.addTask(processWatchdogTask, timeout);

            /*
             * Task that will interrupt the current thread on a timeout
             */
            Task threadInterruptTimeoutTask = new ThreadInterruptTimeoutTask(Thread.currentThread(),
                    watchdog.getName());

            watchdog.addTask(threadInterruptTimeoutTask, timeout);
        }

        Thread inputThread = null;
        Thread outputThread = null;
        Thread errorThread = null;

        if (input != null) {
            inputThread = new StreamCopier(input, process.getOutputStream(), "input", false, true);
            inputThread.start();
        }

        if (output != null) {
            outputThread = new StreamCopier(process.getInputStream(), output, "output", true, false);
            outputThread.start();
        }

        if (error != null) {
            errorThread = new StreamCopier(process.getErrorStream(), error, "error", true, false);
            errorThread.start();
        }

        try {
            exitCode = process.waitFor();

            /*
             * We need to wait for the threads to finish because otherwise there is
             * a chance we will start using the output before all the output has been
             * written/read.
             */
            if (inputThread != null) {
                inputThread.join();
            }

            if (outputThread != null) {
                outputThread.join();
            }

            if (errorThread != null) {
                errorThread.join();
            }

            /*
             * We MUST close the standard streams otherwise some "FIFO pipes" won't be closed until
             * the garbage collector is run. If there are too many open "FIFO pipes", the following
             * exception might occur:
             * 
             * java.io.IOException: error=24, Too many open files
             * 
             * Closing the standard streams makes sure that the pipes are closed.
             * 
             * Note: The Javadoc for Process does not mention that you should close the standard streams
             * even if not used. Perhaps they rely on the GC?
             * 
             * Note2: The number of FIFI pipes can be counted with:
             * 
             * lsof | grep java | grep pipe | wc -l
             */
            IOUtils.closeQuietly(process.getInputStream());
            IOUtils.closeQuietly(process.getOutputStream());
            IOUtils.closeQuietly(process.getErrorStream());
        } catch (InterruptedException e) {
            throw new IOException("Error running [" + cmdLine + "]", e);
        }

        if (exitCode != successExitCode) {
            throw new ProcessException("Error running [" + cmdLine + "]. exit value: " + exitCode, exitCode);
        }
    } finally {
        logger.debug("Application finished. cmdLine: " + cmdLine);

        /*
         * Need to cancel any pending watchdog tasks
         */
        watchdog.cancel();
    }

    return exitCode;
}