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:ru.anr.cmdline.utils.SimpleOsCommand.java

/**
 * Execute specified command//from w  w  w. jav  a 2s.  co  m
 * 
 * @param command
 *            An os command
 * @return Command result (stdout or stderr)
 * @throws IOException
 *             When error with result processing occures
 */
public String execute(String command) throws IOException {

    StringBuilder sb = new StringBuilder();
    final File root = new File("."); // Starting from a current directory

    try {

        final Process p = Runtime.getRuntime().exec(command, null, root);

        Reader input = new InputStreamReader(p.getInputStream());
        Reader errors = new InputStreamReader(p.getErrorStream());

        for (String s : IOUtils.readLines(input)) { // stdout
            sb.append(s);
            sb.append(OsUtils.LINE_SEPARATOR);
        }

        for (String s : IOUtils.readLines(errors)) { // stderr
            sb.append(s);
            sb.append(OsUtils.LINE_SEPARATOR);
        }

        p.getOutputStream().close();

        if (p.waitFor() != 0) {
            logger.error("The command '{}' did not complete successfully", command);
        }
    } catch (final InterruptedException e) {
        throw new IllegalStateException(e);
    }
    return sb.toString();
}

From source file:com.orange.clara.cloud.servicedbdumper.dbdumper.core.CoreDumper.java

private void runDump(DatabaseDriver databaseDriver, String fileName)
        throws IOException, InterruptedException, RunProcessException {
    String[] commandLine = databaseDriver.getDumpCommandLine();
    int i = 1;//  www .j  av  a2s .c  o  m
    while (true) {
        Process p = this.runCommandLine(commandLine);
        try {
            this.filer.store(p.getInputStream(), fileName);
        } catch (IOException e) {
        } catch (Exception e) {
            if (p.isAlive()) {
                p.destroy();
            }
            throw e;
        }
        p.waitFor();
        if (p.exitValue() == 0) {
            break;
        }
        if (i >= this.dbCommandRetry) {
            this.filer.delete(fileName);
            throw new RunProcessException("\nError during process (exit code is " + p.exitValue() + "): ");
        }
        logger.warn("Retry {}/{}: fail to dump data for file {}.", i, dbCommandRetry, fileName);
        Thread.sleep(10000);
        i++;
    }
}

From source file:org.openlmis.fulfillment.ExportSchemaFlywayCallback.java

@Override
public void afterMigrate(Connection connection) {
    XLOGGER.entry(connection);/*w  w w  .j  a  va  2 s . c o  m*/

    XLOGGER.info("After migrations, exporting db schema");

    int exitCode = 0;
    try {
        schemaName = Optional.ofNullable(schemaName).orElse("fulfillment");

        Process proc = Runtime.getRuntime().exec("/app/export_schema.sh " + schemaName);

        StreamGobbler streamGobbler = new StreamGobbler(proc.getInputStream(), XLOGGER::info);
        Executors.newSingleThreadExecutor().submit(streamGobbler);

        exitCode = proc.waitFor();
    } catch (Exception ex) {
        XLOGGER.warn("Exporting db schema failed with message: " + ex);
    }

    XLOGGER.exit(exitCode);
}

From source file:cz.cas.lib.proarc.common.process.AsyncProcess.java

@Override
public void run() {
    done.set(false);//from  www . j  av a2s . c om
    outputConsumer = null;
    exitCode = -1;
    ProcessBuilder pb = new ProcessBuilder(cmdLine);
    // for now redirect outputs into a single stream to eliminate
    // the need to run multiple threads to read each output
    pb.redirectErrorStream(true);
    pb.environment().putAll(env);
    try {
        Process process = pb.start();
        refProcess.set(process);
        outputConsumer = new OutputConsumer(process.getInputStream());
        outputConsumer.start();
        exitCode = process.waitFor();
        LOG.fine("Done " + cmdLine);
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, cmdLine.toString(), ex);
    } finally {
        done.set(true);
    }
}

From source file:bboss.org.artofsolving.jodconverter.process.LinuxProcessManager.java

private List<String> execute(String... args) throws IOException {
    String[] command;//from  ww w.j a  va2 s.com
    if (runAsArgs != null) {
        command = new String[runAsArgs.length + args.length];
        System.arraycopy(runAsArgs, 0, command, 0, runAsArgs.length);
        System.arraycopy(args, 0, command, runAsArgs.length, args.length);
    } else {
        command = args;
    }
    Process process = new ProcessBuilder(command).start();
    @SuppressWarnings("unchecked")
    List<String> lines = IOUtils.readLines(process.getInputStream());
    return lines;
}

From source file:cn.dreampie.common.plugin.lesscss.compiler.NodeJsLessCssCompiler.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 .  j av a2  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()) {
        logger.warn("Could not delete temp file: " + inputFile.getAbsolutePath());
    }
    if (!outputFile.delete()) {
        logger.warn("Could not delete temp file: " + outputFile.getAbsolutePath());
    }
    if (exitStatus != 0) {
        throw new LessException(result, null);
    }

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

    return result;
}

From source file:com.seyren.core.service.notification.ScriptNotificationService.java

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts)
        throws NotificationFailedException {
    if (check.getState() == AlertType.ERROR) {
        String hostPosition = subscription.getPosition();

        // Check for a valid position
        if (hostPosition == null) {
            LOGGER.info("No hostname position for subscription: {}", subscription.getId());
            throw new NotificationFailedException("Invalid subscription; script has no hostname position");
        }// w  ww  .  ja va 2  s  .  c  o m

        LOGGER.info("Script Location: {}", seyrenConfig.getScriptPath());
        for (Alert alert : alerts) {
            try {
                String hostname = getHostName(alert, hostPosition);
                String resourceUrl = subscription.getTarget();
                ProcessBuilder pb = new ProcessBuilder(seyrenConfig.getScriptType(),
                        seyrenConfig.getScriptPath(), hostname, new Gson().toJson(check),
                        seyrenConfig.getBaseUrl(), resourceUrl);
                LOGGER.info("Script Start");
                Process p = pb.start();
                BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    LOGGER.info(line);
                    //System.out.println(line);
                }
                LOGGER.info("Script End");
            } catch (Exception e) {
                LOGGER.error("Script could not be sent: {}", e);
                throw new NotificationFailedException("Could not send message through the script");
            }
        }
    }
}

From source file:com.playonlinux.wine.WineInstallationTest.java

@Test
public void testRun_RunWineVersionWithArgument_ProcessReturnsHelpMessage() throws IOException {
    List<String> arguments = new ArrayList<>();
    arguments.add("/tmp/unexisting");

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

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

    assertEquals(//  w w  w. j a  v  a  2  s .c om
            "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:mmllabvsdextractfeature.MMllabVSDExtractFeature.java

/**
 * /* ww w. j ava2 s  . c  o  m*/
 * @param tarScriptShFile
 * @param folderForTar
 * @param dirtoSave
 * @return
 * @throws IOException 
 */
Boolean zipFolder(String tarScriptShFile, String folderForZip, String dirtoSave) throws IOException {
    //ProcessBuilder pb = new ProcessBuilder("/home/tiendv/NetBeansProjects/trunk/MMllabVSDExtractFeature/src/mmllabvsdextractfeature/unzip.sh","/home/tiendv/Downloads/tiendv.tar","/home/tiendv");
    Boolean result = false;
    ProcessBuilder pb = new ProcessBuilder(tarScriptShFile, folderForZip, dirtoSave);
    Process process = pb.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line = null;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
    return result;

}

From source file:com.wenzani.maven.mongodb.StartMongoDb.java

public void execute() throws MojoExecutionException {
    port = null == port ? "27017" : port;
    try {/*from   w w  w .  j a  v  a 2  s . co m*/
        chmodMongoD();
        String executable = String.format("%s --dbpath %s --port %s", getMongoD(), mongoDbDir, port);
        Process process = Runtime.getRuntime().exec(executable);
        BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = input.readLine()) != null) {
            getLog().info("Waiting for MongoDB to start...");
            if (StringUtils.contains(line,
                    String.format("waiting for connections on port %s", port).toString())) {
                getLog().info("MongoDB startup complete.");
                break;
            }
        }
        getLog().info(String.format("Started mongod on port %s", port));

    } catch (IOException e) {
        getLog().error(ExceptionUtils.getFullStackTrace(e));
    } catch (InterruptedException ex) {
        getLog().error(ExceptionUtils.getFullStackTrace(ex));
    }
}