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:de.sandroboehme.lesscss.mojo.NodeJsLessCompiler.java

private String compile(String input) throws LessException, IOException, InterruptedException {
    long start = System.currentTimeMillis();

    File inputFile = File.createTempFile("lessc-input-", ".less");
    FileOutputStream out = new FileOutputStream(inputFile);
    IOUtils.write(input, out);//  ww w  .jav  a 2 s  .  c o m
    out.close();
    File outputFile = File.createTempFile("lessc-output-", ".css");
    File lesscJsFile = new File(tempDir, "lessc.js");

    ProcessBuilder pb = new ProcessBuilder(nodeExecutablePath, lesscJsFile.getAbsolutePath(),
            inputFile.getAbsolutePath(), outputFile.getAbsolutePath(), String.valueOf(compress));
    pb.redirectErrorStream(true);
    Process process = pb.start();
    IOUtils.copy(process.getInputStream(), System.out);

    int exitStatus = process.waitFor();

    FileInputStream in = new FileInputStream(outputFile);
    String result = IOUtils.toString(in);
    in.close();
    if (!inputFile.delete()) {
        log.warn("Could not delete temp file: " + inputFile.getAbsolutePath());
    }
    if (!outputFile.delete()) {
        log.warn("Could not delete temp file: " + outputFile.getAbsolutePath());
    }
    if (exitStatus != 0) {
        throw new LessException(result, null);
    }

    log.debug("Finished compilation of LESS source in " + (System.currentTimeMillis() - start) + " ms.");

    return result;
}

From source file:com.emc.ecs.sync.filter.ShellCommandFilter.java

@Override
public void filter(SyncObject obj) {
    getNext().filter(obj);/*from  ww w .  java 2 s  .c om*/

    String[] cmdLine = new String[] { command, obj.getSourceIdentifier(), obj.getTargetIdentifier() };
    try {
        Process p = Runtime.getRuntime().exec(cmdLine);

        InputStream stdout = p.getInputStream();
        InputStream stderr = p.getErrorStream();
        while (true) {
            try {
                int exitCode = p.exitValue();
                if (exitCode != 0) {
                    throw new RuntimeException(
                            "Command: " + Arrays.asList(cmdLine) + "exited with code " + exitCode);
                } else {
                    return;
                }
            } catch (IllegalThreadStateException e) {
                // ignore; process running
            }

            // Drain stdout and stderr.  Many processes will hang if you
            // dont do this.
            drain(stdout, System.out);
            drain(stderr, System.err);
        }
    } catch (IOException e) {
        throw new RuntimeException("Error executing command: " + Arrays.asList(cmdLine) + ": " + e.getMessage(),
                e);
    }
}

From source file:com.synopsys.integration.executable.ProcessBuilderRunner.java

private ExecutableOutput executeProcessBuilder(ProcessBuilder processBuilder) throws ExecutableRunnerException {
    try {//from   ww w.ja va2 s. co m
        final Process process = processBuilder.start();

        try (InputStream standardOutputStream = process.getInputStream();
                InputStream standardErrorStream = process.getErrorStream()) {
            final ExecutableStreamThread standardOutputThread = new ExecutableStreamThread(standardOutputStream,
                    logger::info, logger::trace);
            standardOutputThread.start();

            final ExecutableStreamThread errorOutputThread = new ExecutableStreamThread(standardErrorStream,
                    logger::info, logger::trace);
            errorOutputThread.start();

            final int returnCode = process.waitFor();
            logger.info("process finished: " + returnCode);

            standardOutputThread.join();
            errorOutputThread.join();

            final String standardOutput = standardOutputThread.getExecutableOutput().trim();
            final String errorOutput = errorOutputThread.getExecutableOutput().trim();

            final ExecutableOutput output = new ExecutableOutput(returnCode, standardOutput, errorOutput);
            return output;
        }
    } catch (final Exception e) {
        throw new ExecutableRunnerException(e);
    }
}

From source file:com.esd.vs.interceptor.LoginInterceptor.java

public String getMACAddress(String ip) {
    String str = "";
    String macAddress = "";
    try {//from  w  w  w . j a  va2 s . c  o  m
        Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
        InputStreamReader ir = new InputStreamReader(p.getInputStream());
        LineNumberReader input = new LineNumberReader(ir);
        for (int i = 1; i < 100; i++) {
            str = input.readLine();
            if (str != null) {
                if (str.indexOf("MAC Address") > 1) {
                    macAddress = str.substring(str.indexOf("MAC Address") + 14, str.length());
                    break;
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace(System.out);
    }
    return macAddress;
}

From source file:com.haulmont.yarg.formatters.impl.doc.connector.WinProcessManager.java

@Override
@SuppressWarnings("unchecked")
public List<Long> findPid(String host, int port) {
    try {//from w  ww . j  av  a 2  s  .  com
        if ("localhost".equalsIgnoreCase(host))
            host = LOCAL_HOST;
        Process process = Runtime.getRuntime().exec(String.format(FIND_PID_COMMAND, port));
        List r = IOUtils.readLines(process.getInputStream());
        for (Object output : r) {
            NetStatInfo info = new NetStatInfo((String) output);
            if (info.localPort == port && ObjectUtils.equals(host, info.localAddress))
                return Collections.singletonList(info.pid);
        }
    } catch (IOException e) {
        log.warn(String.format("Unable to find PID for OO process on host:port  %s:%s", host, port), e);
    }
    log.warn(String.format("Unable to find PID for OO process on host:port %s:%s", host, port));
    return Collections.singletonList(PID_UNKNOWN);
}

From source file:edu.ucsd.sbrg.escher.EscherConverter.java

/**
 * Extracts CoBRA from {@link SBMLDocument} if it is FBC compliant. cobrapy must be present for
 * this.//from  ww w . ja  va 2  s .c om
 *
 * @param file Input file.
 * @return Result of extraction.
 * @throws IOException Thrown if there are problems in reading the {@code input} file(s).
 * @throws XMLStreamException Thrown if there are problems in parsing XML file(s).
 */
public static boolean extractCobraModel(File file) throws IOException, XMLStreamException {
    if (false) {
        logger.warning(format(bundle.getString("SBMLFBCNotAvailable"), file.getName()));
        return false;
    } else {
        logger.info(format(bundle.getString("SBMLFBCInit"), file.getName()));
        // Execute: py3 -c "from cobra import io;
        // io.save_json_model(model=io.read_sbml_model('FILENAME'), file_name='FILENAME')"

        String[] command;
        command = new String[] { "python3", "-c",
                "\"print('yo');from cobra import io;" + "io.save_json_model(model=io.read_sbml_model('"
                        + file.getAbsolutePath() + "'), file_name='" + file.getAbsolutePath() + ".json"
                        + "');print('yo')\"",
                "> /temp/log" };
        // command = new String[] {"/usr/local/bin/python3", "-c", "\"print('yo')\""};
        command = new String[] { "python3" };
        Process p;
        try {
            // p = new ProcessBuilder(command).redirectErrorStream(true).start();
            p = Runtime.getRuntime().exec(command);
            p.waitFor();
            if (p.exitValue() == 0) {
                logger.info(format(bundle.getString("SBMLFBCExtractionSuccessful"), file.getAbsolutePath(),
                        file.getAbsolutePath()));
                InputStream is = p.getErrorStream();
                is = p.getInputStream();
                OutputStream os = p.getOutputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String cobrapy_output = "";
                cobrapy_output = reader.readLine();
                while (cobrapy_output != null) {
                    logger.warning(cobrapy_output);
                    cobrapy_output = reader.readLine();
                }
                return true;
            } else {
                logger.info(format(bundle.getString("SBMLFBCExtractionFailed")));
                BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String cobrapy_output = "";
                cobrapy_output = reader.readLine();
                while (cobrapy_output != null) {
                    logger.warning(cobrapy_output);
                    cobrapy_output = reader.readLine();
                }
                return false;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }
}

From source file:edu.uci.ics.asterix.installer.test.AsterixClusterLifeCycleIT.java

@Test
public void StartStopActiveInstance() throws Exception {
    //TODO: is the instance actually live?
    //TODO: is ZK still running?
    try {/* w  w  w .j  a  v  a 2  s  .c o  m*/
        Process start = managixInvoke("start -n vagrant-ssh");
        Assert.assertTrue(checkOutput(start.getInputStream(), "ACTIVE"));
        Process stop = managixInvoke("stop -n vagrant-ssh");
        Assert.assertTrue(checkOutput(stop.getInputStream(), "Stopped Asterix instance"));
        LOGGER.info("Test start/stop active cluster instance PASSED");
    } catch (Exception e) {
        throw new Exception("Test start/stop FAILED!", e);
    }
}

From source file:io.cloudslang.content.utilities.util.ProcessExecutor.java

private void stopProcess(Process process, Future<ProcessResponseEntity> futureResult) {
    futureResult.cancel(true);/*ww  w  .  ja  v  a  2  s . co m*/
    process.destroy();

    closeQuietly(process.getInputStream());
    closeQuietly(process.getErrorStream());
}

From source file:magma.tools.benchmark.model.bench.SinglePlayerLauncher.java

private void runScript(String scriptName, Object[] arguments) {
    File workingDir = new File(path);
    File fullPath = new File(workingDir, scriptName);
    if (!validatePath(fullPath)) {
        return;/*  w  ww . j  a v  a2s .c  o m*/
    }

    Object[] commands = ArrayUtils.addAll(new Object[] { "bash", fullPath.getPath() }, arguments);
    String command = StringUtils.join(commands, " ");
    System.out.println(command);

    Process ps = UnixCommandUtil.launch(command, null, workingDir);
    stdOut = new StreamBufferer(ps.getInputStream(), 5000);
    stdErr = new StreamBufferer(ps.getErrorStream(), 5000);
}

From source file:com.googlecode.flyway.maven.largetest.MavenLargeTest.java

/**
 * Runs Maven in this directory with these extra arguments.
 *
 * @param expectedReturnCode The expected return code for this invocation.
 * @param dir                The directory below src/test/resources to run maven in.
 * @param extraArgs          The extra arguments (if any) for Maven.
 * @return The standard output.//from   www .  ja  v a  2s.co  m
 * @throws Exception When the execution failed.
 */
private String runMaven(int expectedReturnCode, String dir, String... extraArgs) throws Exception {
    String m2Home = System.getenv("M2_HOME");
    String flywayVersion = System.getProperty("flywayVersion");

    String extension = "";
    if (System.getProperty("os.name").startsWith("Windows")) {
        extension = ".bat";
    }

    List<String> args = new ArrayList<String>();
    args.add(m2Home + "/bin/mvn" + extension);
    args.add("-Dflyway.version=" + flywayVersion);
    args.addAll(Arrays.asList(extraArgs));

    ProcessBuilder builder = new ProcessBuilder(args);
    builder.directory(new File(installDir + "/" + dir));
    builder.redirectErrorStream(true);

    Process process = builder.start();
    String stdOut = FileCopyUtils.copyToString(new InputStreamReader(process.getInputStream(), "UTF-8"));
    int returnCode = process.waitFor();

    System.out.print(stdOut);

    assertEquals("Unexpected return code", expectedReturnCode, returnCode);

    return stdOut;
}