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:com.playonlinux.wine.WineInstallationTest.java

@Test
public void testRun_RunWineVersionWithArgument_ProcessDoesNotReturnHepMessage() throws IOException {
    List<String> arguments = new ArrayList<>();
    arguments.add("--help");

    Process wineProcess = this.wineInstallationToTest.run(new File("/tmp"), "/tmp/unexisting", null, arguments);

    InputStream inputStream = wineProcess.getInputStream();
    String processOutput = IOUtils.toString(inputStream);

    assertNotEquals(//from  w w w  . ja v  a2  s  . c o  m
            "Usage: wine PROGRAM [ARGUMENTS...]   Run the specified program\n"
                    + "       wine --help                   Display this help and exit\n"
                    + "       wine --version                Output version information and exit\n",
            processOutput);
}

From source file:edu.northwestern.bioinformatics.studycalendar.utility.osgimosis.BidirectionalObjectStoreTest.java

private Process performMemoryTest(String refType) throws IOException, InterruptedException {
    ProcessBuilder builder = new ProcessBuilder("java", "-Xmx16M", "-cp", "target/classes:target/test/classes",
            MemTest.class.getName(), refType);
    builder.redirectErrorStream(true);/*from w  w  w .  j a  v  a 2s .c o m*/
    builder.directory(detectBaseDirectory());
    Process p = builder.start();
    p.waitFor();
    IOUtils.copy(p.getInputStream(), System.out);
    return p;
}

From source file:com.googlecode.flyway.ant.AntLargeTest.java

/**
 * Runs Ant 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 .j a  v a2s  .c o  m
 * @throws Exception When the execution failed.
 */
private String runAnt(int expectedReturnCode, String dir, String... extraArgs) throws Exception {
    String antHome = System.getenv("ANT_HOME");

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

    List<String> args = new ArrayList<String>();
    args.add(antHome + "/bin/ant" + extension);
    args.add("-DlibDir=" + System.getProperty("libDir"));
    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;
}

From source file:com.antonjohansson.svncommit.core.utils.Bash.java

/** {@inheritDoc} */
@Override/*from   ww w. j a  v a 2  s  .  c  o  m*/
public void executeAndPipeOutput(Consumer<String> onData, Consumer<String> onError,
        Consumer<Boolean> onComplete, String... commandLines) {
    File scriptFile = getTemporaryScriptFile(asList(commandLines));
    Process process = execute(path, scriptFile);

    try (InputStream logStream = process.getInputStream(); InputStream errorStream = process.getErrorStream()) {
        while (isAvailable(process, logStream, errorStream)) {
            if (logStream.available() > 0) {
                accept(onData, logStream);
            }
            if (errorStream.available() > 0) {
                accept(onError, errorStream);
            }
        }
        int exitValue = process.exitValue();
        onComplete.accept(exitValue == 0);
    } catch (IOException e) {
        throw new RuntimeException("Could not execute temporary bash script", e);
    }
}

From source file:com.excella.deploy.agent.core.UnixShellCommand.java

/**
 * {@inheritDoc}/*from w w  w. ja v a  2 s .c o  m*/
 */
public String execute(String argument) throws FailedCommandException {
    String line = "";
    StringBuffer buffer = new StringBuffer();
    String command = getJBossHome() + "/bin/appdeploy.sh " + argument + " 2>/dev/null";
    InputStreamReader inputStream = null;
    BufferedReader input = null;

    log.info("Running an RSM Deployment using the following command: " + command);
    try {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(command);
        int exitValue = process.waitFor();
        inputStream = new InputStreamReader(process.getInputStream());
        input = new BufferedReader(inputStream);
        while ((line = input.readLine()) != null) {
            log.debug("> " + line);
            buffer.append(line);
            buffer.append("<br/>");
        }

        log.info("RSM Deployment Kicked off.  Exited with [" + exitValue + "]");
    } catch (Exception e) {
        throw new FailedCommandException("Unable to execute the command.", e);
    } finally {
        close(inputStream);
        close(input);
    }
    return buffer.toString();
}

From source file:com.antonjohansson.svncommit.core.utils.Bash.java

/** {@inheritDoc} */
@Override/*w  w  w. jav  a2 s  .  c o  m*/
public <R> R execute(ThrowingFunction<InputStream, R, IOException> function, String... commandLines) {
    File scriptFile = getTemporaryScriptFile(asList(commandLines));
    Process process = execute(path, scriptFile);

    try {
        return function.apply(process.getInputStream());
    } catch (IOException e) {
        throw new RuntimeException("Could not execute temporary bash script", e);
    }
}

From source file:com.kylinolap.common.util.OSCommandExecutor.java

private void runNativeCommand() throws IOException {
    String[] cmd = new String[3];
    String osName = System.getProperty("os.name");
    if (osName.startsWith("Windows")) {
        cmd[0] = "cmd.exe";
        cmd[1] = "/C";
    } else {//  ww w . j  a  va 2s  . co  m
        cmd[0] = "/bin/bash";
        cmd[1] = "-c";
    }
    cmd[2] = command;

    ProcessBuilder builder = new ProcessBuilder(cmd);
    builder.redirectErrorStream(true);
    Process proc = builder.start();

    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    IOUtils.copy(proc.getInputStream(), buf);
    output = buf.toString("UTF-8");

    try {
        exitCode = proc.waitFor();
    } catch (InterruptedException e) {
        throw new IOException(e);
    }
}

From source file:com.salsaw.msalsa.clustal.ClustalOmegaManager.java

@Override
public void callClustal(String clustalPath, ClustalFileMapper clustalFileMapper)
        throws IOException, InterruptedException, SALSAException {
    // Get program path to execute
    List<String> clustalProcessCommands = new ArrayList<String>();
    clustalProcessCommands.add(clustalPath);

    // Create the name of output files
    String inputFileName = FilenameUtils.getBaseName(clustalFileMapper.getInputFilePath());
    String inputFileFolderPath = FilenameUtils.getFullPath(clustalFileMapper.getInputFilePath());
    Path alignmentFilePath = Paths.get(inputFileFolderPath, inputFileName + "-aln.fasta");
    Path guideTreeFilePath = Paths.get(inputFileFolderPath, inputFileName + "-tree.dnd");

    // Set inside file mapper
    clustalFileMapper.setAlignmentFilePath(alignmentFilePath.toString());
    clustalFileMapper.setGuideTreeFilePath(guideTreeFilePath.toString());
    setClustalFileMapper(clustalFileMapper);

    // Create clustal omega data
    generateClustalArguments(clustalProcessCommands);

    // http://www.rgagnon.com/javadetails/java-0014.html
    ProcessBuilder builder = new ProcessBuilder(clustalProcessCommands);
    builder.redirectErrorStream(true);// w  ww.  j  a v a  2 s .  com
    System.out.println(builder.command());
    final Process process = builder.start();
    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    process.waitFor();

    if (process.exitValue() != 0) {
        throw new SALSAException("Failed clustal omega call");
    }
}

From source file:de.fhg.iais.asc.xslt.binaries.scale.ImageMagickScaler.java

private boolean scale(File source, File target, List<String> command) {
    File incomplete = target;//  w w w.java  2s.c o  m

    // Execute convert
    try {
        ParentDirectoryUtils.forceCreateParentDirectoryOf(target);

        Process process = new ProcessBuilder(command).redirectErrorStream(true).start();

        IOUtils.copyLarge(process.getInputStream(), NULL_OUTPUT_STREAM);

        if (process.waitFor() == 0) {
            incomplete = null;
            if (target.isFile()) {
                return true;
            } else {
                System.out.println(target);
            }
        }

        LOG.error(createErrorPrefix(source, target) + ": convert failed");
    } catch (IOException e) {
        LOG.error(createErrorPrefix(source, target), e);
    } catch (InterruptedException e) {
        throw new RuntimeException();
    } finally {
        if (incomplete != null) {
            incomplete.delete();
        }
    }

    return false;
}

From source file:de.fhg.igd.mapviewer.server.file.FileTiler.java

/**
 * Tries to exec the command, waits for it to finsih, logs errors if exit
 * status is nonzero, and returns true if exit status is 0 (success).
 *
 * @param command Description of the Parameter
 * @param output a list that will be cleared and the output lines added (if
 *            the list is not null)//from  ww w .ja v  a  2 s. c  o  m
 * @return Description of the Return Value
 */
public static boolean exec(String[] command, List<String> output) {
    Process proc;

    try {
        // System.out.println("Trying to execute command " +
        // Arrays.asList(command));
        proc = Runtime.getRuntime().exec(command);
    } catch (IOException e) {
        log.error("IOException while trying to execute " + Arrays.toString(command), e);
        return false;
    }

    if (output == null)
        output = new ArrayList<String>();

    output.clear();
    BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));

    String currentLine;
    try {
        while ((currentLine = reader.readLine()) != null) {
            output.add(currentLine);
        }
    } catch (IOException e) {
        log.error("Error reading process output", e);
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            log.error("Error closing input stream", e);
        }
    }

    int exitStatus;

    while (true) {
        try {
            exitStatus = proc.waitFor();
            break;
        } catch (java.lang.InterruptedException e) {
            log.warn("Interrupted: Ignoring and waiting");
        }
    }

    if (exitStatus != 0) {
        /*
         * StringBuilder cmdString = new StringBuilder(); for (int i = 0; i
         * < command.length; i++) cmdString.append(command[i]);
         */
        log.warn("Error executing command: " + exitStatus + " (" + output + ")");
    }

    return (exitStatus == 0);
}