Example usage for java.lang Process getInputStream

List of usage examples for java.lang Process getInputStream

Introduction

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

Prototype

public abstract InputStream getInputStream();

Source Link

Document

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

Usage

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

public static boolean dcmsnd(File inputDirFile, boolean throwException) throws Exception {
    InputStream is = null;//from   w ww. j  av  a  2  s. c o  m
    InputStreamReader isr = null;
    BufferedReader br = null;
    FileWriter tagFileWriter = null;
    boolean success = false;
    try {
        String aeTitle = EPADConfig.aeTitle;
        String dicomServerIP = EPADConfig.dicomServerIP;
        String dicomServerPort = EPADConfig.dicomServerPort;
        String dicomServerTitleAndPort = aeTitle + "@" + dicomServerIP + ":" + dicomServerPort;

        dicomServerTitleAndPort = dicomServerTitleAndPort.trim();

        String dirPath = inputDirFile.getAbsolutePath();
        if (pathContainsSpaces(dirPath))
            dirPath = escapeSpacesInDirPath(dirPath);

        File dir = new File(dirPath);
        int nbFiles = -1;
        if (dir != null) {
            String[] filePaths = dir.list();
            if (filePaths != null)
                nbFiles = filePaths.length;
        }
        log.info("./dcmsnd: sending " + nbFiles + " file(s) - command: ./dcmsnd " + dicomServerTitleAndPort
                + " " + dirPath);

        String[] command = { "./dcmsnd", dicomServerTitleAndPort, dirPath };
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        String dicomScriptsDir = EPADConfig.getEPADWebServerDICOMScriptsDir() + "bin/";
        File script = new File(dicomScriptsDir, "dcmsnd");
        if (!script.exists())
            dicomScriptsDir = EPADConfig.getEPADWebServerDICOMBinDir();
        script = new File(dicomScriptsDir, "dcmsnd");
        if (!script.exists())
            throw new Exception("No script found:" + script.getAbsolutePath());
        // 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();
        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("./dcmsend output: " + line);
        }

        try {
            int exitValue = process.waitFor();
            log.info("DICOM send exit value is: " + exitValue);
            if (exitValue == 0)
                success = true;
        } catch (InterruptedException e) {
            log.warning("Didn't send DICOM files in: " + inputDirFile.getAbsolutePath(), e);
        }
        String cmdLineOutput = sb.toString();

        if (cmdLineOutput.toLowerCase().contains("error"))
            throw new IllegalStateException("Failed for: " + parseError(cmdLineOutput));
        return success;
    } catch (Exception e) {
        log.warning("DicomSendTask failed to send DICOM files", e);
        if (e instanceof IllegalStateException && throwException) {
            throw e;
        }
        if (throwException) {
            throw new IllegalStateException("DicomSendTask failed to send DICOM files", e);
        }
        return success;
    } catch (OutOfMemoryError oome) {
        log.warning("DicomSendTask out of memory: ", oome);
        if (throwException) {
            throw new IllegalStateException("DicomSendTask out of memory: ", oome);
        }
        return success;
    } finally {
        IOUtils.closeQuietly(tagFileWriter);
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(is);
    }
}

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
 *//*from  w ww.j  a va2s.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.loy.MicroServiceConsole.java

@SuppressWarnings("rawtypes")
static void init() {

    ClassPathResource classPathResource = new ClassPathResource("application.yml");
    Yaml yaml = new Yaml();
    Map result = null;/*from   w ww.  ja  va2s  . co  m*/
    try {
        result = (Map) yaml.load(classPathResource.getInputStream());
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    String platformStr = result.get("platform").toString();
    String version = result.get("version").toString();
    String jvmOption = result.get("jvmOption").toString();
    @SuppressWarnings("unchecked")
    List<String> projects = (List<String>) result.get("projects");
    platform = Platform.valueOf(platformStr);

    final Runtime runtime = Runtime.getRuntime();
    File pidsForder = new File("./pids");
    if (!pidsForder.exists()) {
        pidsForder.mkdir();
    } else {
        File[] files = pidsForder.listFiles();
        if (files != null) {
            for (File f : files) {
                f.deleteOnExit();
                String pidStr = f.getName();
                try {
                    Long pid = new Long(pidStr);
                    if (Processes.isProcessRunning(platform, pid)) {
                        if (Platform.Windows == platform) {
                            Processes.tryKillProcess(null, platform, new NullProcessor(), pid);
                        } else {
                            Processes.killProcess(null, platform, new NullProcessor(), pid);
                        }

                    }
                } catch (Exception ex) {
                }
            }
        }
    }

    File currentForder = new File("");
    String root = currentForder.getAbsolutePath();
    root = root.replace(File.separator + "build" + File.separator + "libs", "");
    root = root.replace(File.separator + "e-example-ms-start", "");
    final String rootPath = root;
    new Thread(new Runnable() {
        @Override
        public void run() {
            int size = projects.size();
            int index = 1;
            for (String value : projects) {
                String path = value;
                String[] values = value.split("/");
                value = values[values.length - 1];
                value = rootPath + "/" + path + "/build/libs/" + value + "-" + version + ".jar";
                final String command = value;
                try {
                    Process process = runtime
                            .exec("java " + jvmOption + " -Dfile.encoding=UTF-8 -jar " + command);
                    Long pid = Processes.processId(process);
                    pids.add(pid);
                    File pidsFile = new File("./pids", pid.toString());
                    pidsFile.createNewFile();
                    new WriteLogThread(process.getInputStream()).start();

                } catch (IOException e) {
                    e.printStackTrace();
                }
                synchronized (lock) {
                    try {
                        if (index < size) {
                            lock.wait();
                        } else {
                            index++;
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }).start();
}

From source file:cn.schina.dbfw.service.SystemLicenseSrever.java

private static String runCmd(String[] cmd) throws IOException {
    Process ps = Runtime.getRuntime().exec(cmd);

    BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
    StringBuffer sb = new StringBuffer();
    String line;//www. j  a  va2 s.c  om
    while ((line = br.readLine()) != null) {
        sb.append(line).append("\n");
    }
    String result = sb.toString();
    return result;
}

From source file:org.zenoss.zep.dao.impl.DaoUtils.java

public static int executeCommand(String command) {
    String response = "";

    ProcessBuilder pb = new ProcessBuilder("bash", "-c", command);
    pb.redirectErrorStream(true);/*from  w w w .  j  a v a 2 s  .  c om*/

    int shellExitStatus = -1;
    InputStream shellIn = null;

    try {
        Process shell = pb.start();
        // To capture output from the shell
        shellIn = shell.getInputStream();

        // Wait for the shell to finish and get the return code
        shellExitStatus = shell.waitFor();
        if (shellExitStatus != 0) {
            response = DaoUtils.convertStreamToStr(shellIn);
            logger.error("Error (return code: " + shellExitStatus + ") from \"" + command + "\": \nOutput: "
                    + response);
        }
        shellIn.close();
    } catch (IOException e) {
        logger.error("Error occured while executing Linux command. Error Description: " + e.getMessage());
    } catch (InterruptedException e) {
        logger.error("Error occured while executing Linux command. Error Description: " + e.getMessage());
    }

    return shellExitStatus;
}

From source file:TestFuseDFS.java

/**
 * Run a fuse-dfs process to mount the given DFS
 *//*  ww w. j  a va2  s .  co m*/
private static Process establishMount(URI uri) throws IOException {
    Runtime r = Runtime.getRuntime();
    String cp = System.getProperty("java.class.path");

    String buildTestDir = System.getProperty("build.test");
    String fuseCmd = buildTestDir + "/../fuse_dfs";
    String libHdfs = buildTestDir + "/../../../c++/lib";

    String arch = System.getProperty("os.arch");
    String jvm = System.getProperty("java.home") + "/lib/" + arch + "/server";
    String lp = System.getProperty("LD_LIBRARY_PATH") + ":" + libHdfs + ":" + jvm;
    LOG.debug("LD_LIBRARY_PATH=" + lp);

    String nameNode = "dfs://" + uri.getHost() + ":" + String.valueOf(uri.getPort());

    // NB: We're mounting via an unprivileged user, therefore
    // user_allow_other needs to be set in /etc/fuse.conf, which also
    // needs to be world readable.
    String mountCmd[] = { fuseCmd, nameNode, mountPoint,
            // "-odebug",              // Don't daemonize
            "-obig_writes", // Allow >4kb writes
            "-oentry_timeout=0.1", // Don't cache dents long
            "-oattribute_timeout=0.1", // Don't cache attributes long
            "-ononempty", // Don't complain about junk in mount point
            "-f", // Don't background the process
            "-ordbuffer=32768", // Read buffer size in kb
            "rw" };

    String[] env = { "CLASSPATH=" + cp, "LD_LIBRARY_PATH=" + lp, "PATH=/usr/bin:/bin" };

    execWaitRet("fusermount -u " + mountPoint);
    execAssertSucceeds("rm -rf " + mountPoint);
    execAssertSucceeds("mkdir -p " + mountPoint);

    // Mount the mini cluster
    String cmdStr = "";
    for (String c : mountCmd) {
        cmdStr += (" " + c);
    }
    LOG.info("now mounting with:" + cmdStr);
    Process fuseProcess = r.exec(mountCmd, env);
    RedirectToStdoutThread stdoutThread = new RedirectToStdoutThread(fuseProcess.getInputStream());
    RedirectToStdoutThread stderrThread = new RedirectToStdoutThread(fuseProcess.getErrorStream());
    stdoutThread.start();
    stderrThread.start();
    // Wait for fusermount to start up, so that we know we're operating on the
    // FUSE FS when we run the tests.
    try {
        Thread.sleep(50000);
    } catch (InterruptedException e) {
    }
    return fuseProcess;
}

From source file:com.vaadin.addon.charts.util.SVGGenerator.java

protected static Process startPhantomJS() {
    try {//from  w ww . ja  v a  2s  . c o  m
        ArrayList<String> commands = new ArrayList<String>();
        commands.add(PHANTOM_EXEC);
        // comment out for debugging
        // commands.add("--remote-debugger-port=9001");

        ensureTemporaryFiles();

        commands.add(JS_CONVERTER.getAbsolutePath());

        commands.add("-jsstuff");
        commands.add(JS_STUFF.getAbsolutePath());

        final Process process = new ProcessBuilder(commands).start();
        final BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));
        String readLine = bufferedReader.readLine();
        if (!readLine.contains("ready")) {
            throw new RuntimeException("PHANTOM JS NOT READY");
        }
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                super.run();
                if (process != null) {
                    System.out.println("Shutting down PhantomJS instance");
                    process.destroy();
                }
            }
        });

        return process;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.fabric8.maven.core.util.ProcessUtil.java

private static Thread startOutputLoggingThread(final Process process, final Logger log,
        final String commandDesc, final boolean useStandardLoggingLevel) {
    Thread logThread = new Thread("[OUT] " + commandDesc) {
        @Override/*w  w w . ja v  a  2s  .  com*/
        public void run() {
            try {
                processOutput(process.getInputStream(), createOutputHandler(log, useStandardLoggingLevel));
            } catch (IOException e) {
                log.error("Failed to read output stream from %s : %s", commandDesc, e.getMessage());
            }
        }
    };
    logThread.setDaemon(true);
    logThread.start();
    return logThread;
}

From source file:net.pickapack.io.cmd.CommandLineHelper.java

/**
 *
 * @param cmd/*  www.j  a v  a 2 s  . c  om*/
 * @param waitFor
 * @return
 */
public static int invokeNativeCommand(String[] cmd, boolean waitFor) {
    try {
        Runtime r = Runtime.getRuntime();
        final Process ps = r.exec(cmd);
        //            ProcessBuilder pb = new ProcessBuilder(cmd);
        //            Process ps = pb.start();

        new Thread() {
            {
                setDaemon(true);
            }

            @Override
            public void run() {
                try {
                    IOUtils.copy(ps.getInputStream(), System.out);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread() {
            {
                setDaemon(true);
            }

            @Override
            public void run() {
                try {
                    IOUtils.copy(ps.getErrorStream(), System.out);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        if (waitFor) {
            int exitValue = ps.waitFor();
            if (exitValue != 0) {
                System.out.println("WARN: Process exits with non-zero code: " + exitValue);
            }

            ps.destroy();

            return exitValue;
        }

        return 0;
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
}

From source file:edu.cornell.med.icb.R.RUtils.java

/**
 * Can be used to start a rserve instance.
 * @param threadPool The ExecutorService used to start the Rserve process
 * @param rServeCommand Full path to command used to start Rserve process
 * @param host Host where the command should be sent
 * @param port Port number where the command should be sent
 * @param username Username to send to the server if authentication is required
 * @param password Password to send to the server if authentication is required
 * @return The return value from the Rserve instance
 *//*from   www  .  ja  va2  s  . com*/
static Future<Integer> startup(final ExecutorService threadPool, final String rServeCommand, final String host,
        final int port, final String username, final String password) {
    if (LOG.isInfoEnabled()) {
        LOG.info("Attempting to start Rserve on " + host + ":" + port);
    }

    return threadPool.submit(new Callable<Integer>() {
        public Integer call() throws IOException {
            final List<String> commands = new ArrayList<String>();

            // if the host is not local, use ssh to exec the command
            if (!"localhost".equals(host) && !"127.0.0.1".equals(host)
                    && !InetAddress.getLocalHost().equals(InetAddress.getByName(host))) {
                commands.add("ssh");
                commands.add(host);
            }

            // TODO - this will fail when spaces are in the the path to the executable
            CollectionUtils.addAll(commands, rServeCommand.split(" "));
            commands.add("--RS-port");
            commands.add(Integer.toString(port));

            final String[] command = commands.toArray(new String[commands.size()]);
            LOG.debug(ArrayUtils.toString(commands));

            final ProcessBuilder builder = new ProcessBuilder(command);
            builder.redirectErrorStream(true);
            final Process process = builder.start();
            BufferedReader br = null;
            try {
                final InputStream is = process.getInputStream();
                final InputStreamReader isr = new InputStreamReader(is);
                br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(host + ":" + port + "> " + line);
                    }
                }

                process.waitFor();
                if (LOG.isInfoEnabled()) {
                    LOG.info("Rserve on " + host + ":" + port + " terminated");
                }
            } catch (InterruptedException e) {
                LOG.error("Interrupted!", e);
                process.destroy();
                Thread.currentThread().interrupt();
            } finally {
                IOUtils.closeQuietly(br);
            }

            final int exitValue = process.exitValue();
            if (LOG.isInfoEnabled()) {
                LOG.info("Rserve on " + host + ":" + port + " returned " + exitValue);
            }
            return exitValue;
        }
    });
}