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:edu.stanford.epad.epadws.dcm4chee.Dcm4CheeOperations.java

public static boolean deleteStudy(String studyUID) {
    InputStream is = null;//www  . j  a  v  a 2s  . c om
    InputStreamReader isr = null;
    BufferedReader br = null;
    boolean success = false;
    try {
        log.info("Deleting study " + studyUID + " files - command: ./dcmdeleteStudy " + studyUID);

        String[] command = { "./dcmdeleteStudy", studyUID };

        ProcessBuilder pb = new ProcessBuilder(command);
        String dicomScriptsDir = EPADConfig.getEPADWebServerDICOMScriptsDir() + "bin/";
        File script = new File(dicomScriptsDir, "dcmdeleteStudy");
        if (!script.exists())
            dicomScriptsDir = EPADConfig.getEPADWebServerMyScriptsDir();
        script = new File(dicomScriptsDir, "dcmdeleteStudy");
        // Java 6 - Runtime.getRuntime().exec("chmod u+x "+script.getAbsolutePath());
        script.setExecutable(true);
        pb.directory(new File(dicomScriptsDir));

        Process process = pb.start();
        process.getOutputStream();
        is = process.getInputStream();
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            log.info("./dcmdeleteStudy: " + line);
            sb.append(line).append("\n");
        }

        try {
            int exitValue = process.waitFor();
            log.info("DICOM delete study exit value is: " + exitValue);
            if (exitValue == 0)
                success = true;
        } catch (Exception e) {
            log.warning("Failed to delete DICOM study " + studyUID, e);
        }
        String cmdLineOutput = sb.toString();

        if (cmdLineOutput.toLowerCase().contains("error")) {
            throw new IllegalStateException("Failed for: " + parseError(cmdLineOutput));
        }
    } catch (Exception e) {
        log.warning("Failed to delete DICOM study " + studyUID, e);
    }
    return success;
}

From source file:com.github.pemapmodder.pocketminegui.utils.Utils.java

private static File installLinuxPHP(File home, InstallProgressReporter progress) {
    progress.report(0.0);/*  ww  w.  j  a v a  2s  . co  m*/
    File bin = new File(home, ".pmgui_tmp_pm_linux_installer");
    bin.mkdirs();
    try {
        InputStream get = new URL("http", "get.pocketmine.net", "").openStream();
        Process bash = new ProcessBuilder("bash -s - -v development").directory(bin)
                .redirectOutput(ProcessBuilder.Redirect.INHERIT).redirectError(ProcessBuilder.Redirect.INHERIT)
                .start();
        progress.report(0.25);
        byte[] bytes = IOUtils.toByteArray(get);
        progress.report(0.5);
        bash.getOutputStream().write(bytes);
        int result = bash.waitFor();
        progress.report(0.75);
        if (result == 0) {
            File out = new File(bin, "bin");
            FileUtils.copyDirectory(out, new File(home, "bin"));
            FileUtils.deleteDirectory(bin);
            File output = new File(out, "php7/bin/php");
            progress.completed(output);
            return output;
        } else {
            FileUtils.deleteDirectory(bin);
            return null;
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
        try {
            FileUtils.deleteDirectory(bin);
        } catch (IOException e1) {
        }
        return null;
    }
}

From source file:edu.stanford.epad.epadws.dcm4chee.Dcm4CheeOperations.java

/**
 * TODO This does not work. The ./dcmdeleteSeries script invoked the dcm4chee twiddle command but it appears that the
 * moveSeriesToTrash operation it calls has no effect in this version of dcm4chee. See:
 * http://www.dcm4che.org/jira/browse/WEB-955
 *//*w  w w.  j a  v a 2s  . c  o m*/
public static boolean deleteSeries(String seriesUID, String seriesPk) {
    InputStream is = null;
    InputStreamReader isr = null;
    BufferedReader br = null;
    boolean success = false;

    try {
        log.info("Deleting series " + seriesUID + " seriesPK:" + seriesPk);

        String[] command = { "./dcmdeleteSeries", seriesPk, EPADConfig.xnatUploadProjectPassword };
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        String dicomScriptsDir = EPADConfig.getEPADWebServerDICOMScriptsDir() + "bin/";
        File script = new File(dicomScriptsDir, "dcmdeleteSeries");
        if (!script.exists())
            dicomScriptsDir = EPADConfig.getEPADWebServerMyScriptsDir();
        script = new File(dicomScriptsDir, "dcmdeleteSeries");
        // Java 6 - Runtime.getRuntime().exec("chmod u+x "+script.getAbsolutePath());
        script.setExecutable(true);
        processBuilder.directory(new File(dicomScriptsDir));
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        process.getOutputStream();
        is = process.getInputStream();
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);

        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
            log.info("./dcmdeleteSeries: " + line);
        }
        try {
            int exitValue = process.waitFor();
            if (exitValue == 0) {
                log.info("Deleted DICOM series " + seriesUID + " pk:" + seriesPk);
                success = true;
            } else {
                log.warning("Failed to delete DICOM series " + seriesUID + " pk=" + seriesPk + "; exitValue="
                        + exitValue + "\n" + sb.toString());
            }
        } catch (Exception e) {
            log.warning("Failed to delete DICOM series " + seriesUID, e);
        }

        String cmdLineOutput = sb.toString();

        if (cmdLineOutput.toLowerCase().contains("error")) {
            throw new IllegalStateException("Failed for: " + parseError(cmdLineOutput));
        }
    } catch (IOException e) {
        log.warning("Failed to delete DICOM series " + seriesUID, e);
    } finally {
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(is);
    }
    return success;
}

From source file:com.sshtools.common.util.X11Util.java

public static X11Cookie getCookie(XDisplay xdisplay) {
    if (System.getProperty("os.name").startsWith("Windows"))
        return getRNDCookie();
    log.debug("Getting X11 cookie using xauth");
    try {/*ww w  .  ja v  a  2s.  c om*/
        String host = xdisplay.getHost();
        String display = host + ":" + xdisplay.getDisplay();
        String cmd = "xauth list " + display + " 2>/dev/null";
        if (host == null || host.equals("localhost") || host.equals("unix")) {
            cmd = "xauth list :" + xdisplay.getDisplay() + " 2>/dev/null";
        }

        Process process = null;
        InputStream in = null;
        OutputStream out = null;
        try {
            log.debug("Executing " + cmd);
            process = Runtime.getRuntime().exec(cmd);
            BufferedReader reader = new BufferedReader(new InputStreamReader(in = process.getInputStream()));
            out = process.getOutputStream();
            String line = null;
            String cookie = null;
            while ((line = reader.readLine()) != null) {
                log.debug(line);
                StringTokenizer t = new StringTokenizer(line);
                try {
                    String fhost = t.nextToken();
                    String type = t.nextToken();
                    String value = t.nextToken();
                    if (cookie == null) {
                        cookie = value;
                        log.debug("Using cookie " + cookie);
                    }
                    return expand(type, cookie);
                } catch (Exception e) {
                    log.error("Unexpected response from xauth.", e);
                    log.warn("Trying random data.");
                    return getRNDCookie();
                }
            }
        } finally {
            IOUtil.closeStream(in);
            IOUtil.closeStream(out);
        }
        return getRNDCookie();
    } catch (Exception e) {
        log.warn("Had problem finding xauth data (" + e + ") trying random data.");
        return getRNDCookie();
    }
}

From source file:com.sinpo.xnfc.nfc.Util.java

/**
 * ??? Root??(ROOT??)/*from   w  w  w  .  ja v a 2s.  c  o  m*/
 *
 * @return ?/??Root??
 */
public static boolean upgradeRootPermission(String pkgCodePath) {
    Process process = null;
    DataOutputStream os = null;
    try {
        String cmd = "chmod 777 " + pkgCodePath;
        process = Runtime.getRuntime().exec("su"); //?root??
        os = new DataOutputStream(process.getOutputStream());
        os.writeBytes(cmd + "\n");
        os.writeBytes("exit\n");
        os.flush();
        process.waitFor();
    } catch (Exception e) {
        return false;
    } finally {
        try {
            if (os != null) {
                os.close();
            }
            process.destroy();
        } catch (Exception e) {
        }
    }
    return true;
}

From source file:com.dtolabs.rundeck.core.utils.ScriptExecUtil.java

/**
 * Run a command with environment variables in a working dir, and copy the streams
 *
 * @param command      the command array to run
 * @param envMap       the environment variables to pass in
 * @param workingdir   optional working dir location (or null)
 * @param outputStream stream for stdout
 * @param errorStream  stream for stderr
 *
 * @return the exit code of the command/*from w  ww . j  a va2  s.  c  o m*/
 *
 * @throws IOException          if any IO exception occurs
 * @throws InterruptedException if interrupted while waiting for the command to finish
 */
public static int runLocalCommand(final String[] command, final Map<String, String> envMap,
        final File workingdir, final OutputStream outputStream, final OutputStream errorStream)
        throws IOException, InterruptedException {
    final String[] envarr = createEnvironmentArray(envMap);

    final Runtime runtime = Runtime.getRuntime();
    final Process exec = runtime.exec(command, envarr, workingdir);
    final Streams.StreamCopyThread errthread = Streams.copyStreamThread(exec.getErrorStream(), errorStream);
    final Streams.StreamCopyThread outthread = Streams.copyStreamThread(exec.getInputStream(), outputStream);
    errthread.start();
    outthread.start();
    exec.getOutputStream().close();
    final int result = exec.waitFor();
    errthread.join();
    outthread.join();
    if (null != outthread.getException()) {
        throw outthread.getException();
    }
    if (null != errthread.getException()) {
        throw errthread.getException();
    }
    return result;
}

From source file:com.theonespy.util.Util.java

public static void disableMobileData() {
    Util.Log("Disable mobile data");

    try {//from w w  w  .j  a  va2 s.c om
        Process su = Runtime.getRuntime().exec("su");
        DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

        outputStream.writeBytes("svc data disable\n ");
        outputStream.flush();

        outputStream.writeBytes("exit\n");
        outputStream.flush();
        try {
            su.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.doctoror.surprise.SurpriseService.java

private static Result execute(final List<String> commands, final boolean surpriseBinary) {
    final Result result = new Result();
    Process process = null;
    DataOutputStream os = null;/* w w  w.j a v a 2 s.  co m*/
    BufferedReader is = null;
    try {
        process = new ProcessBuilder().command(surpriseBinary ? COMMAND_SURPRISE : COMMAND_SU)
                .redirectErrorStream(true).start();
        os = new DataOutputStream(process.getOutputStream());
        is = new BufferedReader(new InputStreamReader(process.getInputStream()));
        for (final String command : commands) {
            os.writeBytes(command + "\n");
        }
        os.flush();

        os.writeBytes("exit\n");
        os.flush();

        final StringBuilder output = new StringBuilder();
        String line;
        try {
            while ((line = is.readLine()) != null) {
                if (output.length() != 0) {
                    output.append('\n');
                }
                output.append(line);
            }
        } catch (EOFException ignored) {
        }

        result.output = output.toString();
        result.exitCode = process.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
        result.exitCode = -666;
        result.output = e.getMessage();
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (Exception ignored) {
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (Exception ignored) {
            }
        }
        if (process != null) {
            try {
                process.destroy();
            } catch (Exception ignored) {
            }
        }
    }
    return result;
}

From source file:opendap.aws.glacier.BesMetadataExtractor.java

private static String runSysCommand(String sysCmd) throws IOException {

    Process p = null;

    try {//from   w  w  w.j a v  a  2  s  .c  o  m
        System.out.println("COMMAND: " + sysCmd);

        Runtime rt = Runtime.getRuntime();
        p = rt.exec(sysCmd.toString());
        InputStream in = p.getInputStream();
        OutputStream out = p.getOutputStream();
        InputStream err = p.getErrorStream();

        CharArrayWriter caw = new CharArrayWriter();

        IOUtils.copy(in, caw);
        IOUtils.copy(err, System.err);

        return caw.toString();
    } finally {
        if (p != null)
            p.destroy();
    }

}

From source file:org.stanwood.podcaster.util.AbstractExecutable.java

/**
 * Used to execute a process and capture the output. This method will return when the process has finished
 * @param proc The process/*w  w  w  .  j a va  2s  .  c  o m*/
 * @param outputGobbler The standard output gobbler
 * @param errorGobbler The standard error gobbler
 * @return The exit code of the process
 * @throws IOException Thrown if their are any problems
 * @throws InterruptedException Thrown if the threads are intruppted
 */
public static int execute(Process proc, IStreamGobbler outputGobbler, IStreamGobbler errorGobbler)
        throws IOException, InterruptedException {
    outputGobbler.start();
    errorGobbler.start();
    int exitCode = proc.waitFor();
    while (!errorGobbler.isDone() || !outputGobbler.isDone()) {
    }

    errorGobbler.done();
    outputGobbler.done();

    proc.getErrorStream().close();
    proc.getInputStream().close();
    proc.getOutputStream().close();

    return exitCode;
}