Example usage for java.lang ProcessBuilder redirectErrorStream

List of usage examples for java.lang ProcessBuilder redirectErrorStream

Introduction

In this page you can find the example usage for java.lang ProcessBuilder redirectErrorStream.

Prototype

boolean redirectErrorStream

To view the source code for java.lang ProcessBuilder redirectErrorStream.

Click Source Link

Usage

From source file:com.netflix.dynomitemanager.defaultimpl.StorageProcessManager.java

public void start() throws IOException {
    logger.info(String.format("Starting Storage process"));

    List<String> command = Lists.newArrayList();
    if (!"root".equals(System.getProperty("user.name"))) {
        command.add(SUDO_STRING);/*  w w w  .  j  a va  2s.com*/
        command.add("-n");
        command.add("-E");
    }
    command.addAll(getStartCommand());

    ProcessBuilder startStorage = new ProcessBuilder(command);

    startStorage.directory(new File("/"));
    startStorage.redirectErrorStream(true);
    Process starter = startStorage.start();

    try {
        sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS);
        int code = starter.exitValue();
        if (code == 0) {
            logger.info("Storage process has been started");
            instanceState.setStorageProxyAlive(true);
        } else {
            logger.error("Unable to start Storage process. Error code: {}", code);
        }

        logProcessOutput(starter);
    } catch (Exception e) {
        logger.warn("Starting Storage process has an error", e);
    }
}

From source file:annis.visualizers.component.AbstractDotVisualizer.java

public void writeOutput(VisualizerInput input, OutputStream outstream) {

    StringBuilder dot = new StringBuilder();

    try {/*ww w.  java2s .  c  om*/
        File tmpInput = File.createTempFile("annis-dot-input", ".dot");
        tmpInput.deleteOnExit();

        // write out input file
        StringBuilder dotContent = new StringBuilder();
        createDotContent(input, dotContent);
        FileUtils.writeStringToFile(tmpInput, dotContent.toString());

        // execute dot
        String dotPath = input.getMappings().getProperty("dotpath", "dot");
        ProcessBuilder pBuilder = new ProcessBuilder(dotPath, "-Tpng", tmpInput.getCanonicalPath());

        pBuilder.redirectErrorStream(false);
        Process process = pBuilder.start();

        InputStream inputFromProcess = process.getInputStream();
        for (int chr = inputFromProcess.read(); chr != -1; chr = inputFromProcess.read()) {
            outstream.write(chr);
        }

        inputFromProcess.close();

        int resultCode = process.waitFor();

        if (resultCode != 0) {
            InputStream stderr = process.getErrorStream();
            StringBuilder errorMessage = new StringBuilder();

            for (int chr = stderr.read(); chr != -1; chr = stderr.read()) {
                errorMessage.append((char) chr);
            }
            if (!"".equals(errorMessage.toString())) {
                log.error(
                        "Could not execute dot graph-layouter.\ncommand line:\n{}\n\nstderr:\n{}\n\nstdin:\n{}",
                        new Object[] { StringUtils.join(pBuilder.command(), " "), errorMessage.toString(),
                                dot.toString() });
            }
        }

        // cleanup
        if (!tmpInput.delete()) {
            log.warn("Cannot delete " + tmpInput.getAbsolutePath());
        }

    } catch (Exception ex) {
        log.error(null, ex);
    }
}

From source file:org.apache.metron.rest.service.impl.StormCLIWrapper.java

protected String stormClientVersionInstalled() throws RestException {
    String stormClientVersionInstalled = "Storm client is not installed";
    ProcessBuilder pb = getProcessBuilder("storm", "version");
    pb.redirectErrorStream(true);
    Process p;/*w w  w  .ja  v a 2 s.  c o m*/
    try {
        p = pb.start();
    } catch (IOException e) {
        throw new RestException(e);
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    List<String> lines = reader.lines().collect(toList());
    lines.forEach(System.out::println);
    if (lines.size() > 1) {
        stormClientVersionInstalled = lines.get(1).replaceFirst("Storm ", "");
    }
    return stormClientVersionInstalled;
}

From source file:com.temetra.vroomapi.RouteController.java

@RequestMapping(value = "/route", produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public JsonNode route(@RequestParam(value = "loc") String[] locs,
        @RequestParam(value = "startAtFirst", defaultValue = "true") boolean startAtFirst,
        @RequestParam(value = "endAtLast", defaultValue = "false") boolean endAtLast,
        @RequestParam(value = "includeGeometry", defaultValue = "false") boolean includeGeometry)
        throws Exception {
    long millis = System.currentTimeMillis();

    File vroomBinFile = new File(vroomBinary);
    if (!vroomBinFile.exists()) {
        log.error("Vroom binary file doesn't exist");
        throw new Exception("Vroom binary file doesn't exist");
    }//from www  .  j ava  2  s.c o m

    if (!vroomBinFile.canExecute()) {
        log.error("Cannot execute Vroom binary file");
        throw new Exception("Cannot execute Vroom binary file");
    }

    if (locs.length < 2) {
        log.error("Zero or one location sent");
        throw new Exception("Must send more than one location");
    }

    List<String> progArgs = new ArrayList<>();
    progArgs.add("./" + vroomBinFile.getName());
    if (startAtFirst) {
        progArgs.add("-s");
    }
    if (endAtLast) {
        progArgs.add("-e");
    }
    if (includeGeometry) {
        progArgs.add("-g");
    }

    progArgs.add("loc=" + Joiner.on("&loc=").join(locs) + "");
    log.info("Run (" + millis + "): " + Joiner.on(' ').join(progArgs));

    StringBuilder output = new StringBuilder();
    ProcessBuilder builder = new ProcessBuilder(progArgs);
    builder.directory(vroomBinFile.getParentFile());
    builder.redirectErrorStream(true);
    Process process = builder.start();

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
        String line;
        while ((line = reader.readLine()) != null) {
            output.append(line);
        }
        process.waitFor();
    }

    log.info("Output (" + millis + "): " + output.toString());
    return jsonMapper.readTree(output.toString());
}

From source file:org.wso2.msf4j.ballerina.BallerinaService.java

@POST
@Consumes(MediaType.APPLICATION_JSON)//w w  w  .j  a v  a 2 s .  c  o m
@Produces(MediaType.TEXT_PLAIN)
@Path("/executeAsProcess")
public Response executeBallerinaWithArgsAsProcess(BallerinaContent ballerinaContent) {
    UUID requestId = UUID.randomUUID();
    log.info(requestId.toString() + " <<< " + new Gson().toJson(ballerinaContent));
    String result;
    try {
        java.nio.file.Path path = Paths.get(Application.ballerinaTmp.toString(), requestId.toString() + ".bal");
        Files.write(path, ballerinaContent.getContent().getBytes());
        fileCleaningTracker.track(path.toFile(), ballerinaContent);
        List<String> processArgs = new ArrayList<>();
        processArgs.add(Application.ballerinaPath.toString());
        processArgs.add("run");
        processArgs.add(path.toString());
        processArgs.addAll(Arrays.asList(ballerinaContent.getArguments().split(";")));
        ProcessBuilder processBuilder = new ProcessBuilder(processArgs);
        processBuilder.environment().put("JAVA_HOME", System.getProperty("java.home"));
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();

        if (!process.waitFor(8, TimeUnit.SECONDS)) {
            // Run the psfinder script which will get the pid of started ballerina process and kill that.
            Process exec = Runtime.getRuntime().exec(
                    new String[] { Application.psFinder.toFile().getAbsolutePath(), requestId.toString() });
            exec.waitFor();
            process.destroyForcibly();
            result = "Process took too long\nSystem will exit";
        } else {
            result = IOUtils.toString(process.getInputStream());
        }
    } catch (Exception e) {
        result = "Something went wrong. Try again";
        log.error(e);
    }
    log.info(requestId.toString() + " >>> " + result);
    return Response.ok().entity(result).header("Access-Control-Allow-Origin", "*").build();
}

From source file:ape.NetworkDisconnectCommand.java

/**
 * This method actually executes the command that would disconnect the network
 *///  ww  w  . ja  v a2  s.  co  m
private boolean executecommand(double time) throws IOException {
    String cmd = "ifdown eth0 && sleep " + time + " && /etc/init.d/network restart";
    ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(true);
    Process p = null;

    try {
        p = pb.start();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    try {
        if (p.waitFor() != 0) {
            System.out.println(
                    "ERROR: Non-zero return code (" + p.exitValue() + ") when executing: '" + cmd + "'");
            Main.logger
                    .info("ERROR: Non-zero return code (" + p.exitValue() + ") when executing: '" + cmd + "'");

            ProcessBuilder tmp2 = new ProcessBuilder("bash", "-c", "/etc/init.d/network restart");
            Process ptmp = tmp2.start();
            try {
                if (ptmp.waitFor() == 0)
                    System.out.println("Connection resumed");
                else {
                    System.out.println("Connection resume failed");
                    return false;
                }
            } catch (InterruptedException e1) {
                e1.printStackTrace();
                System.err.println("Catches an exception when trying to recover the network");
                return false;
            }

            return false;
        }
    } catch (InterruptedException e) {
        System.err.println("Executing Command catches an Interrupt, resume connection");
        ProcessBuilder tmp2 = new ProcessBuilder("bash", "-c", "/etc/init.d/network restart");
        Process ptmp = tmp2.start();
        try {
            if (ptmp.waitFor() == 0)
                System.out.println("Connection Resumed");
            else {
                System.out.println("Connection Resumed Failed");
                return false;
            }
        } catch (InterruptedException e1) {
            e1.printStackTrace();
            System.err.println("Catches an exception when trying to recover the network");
            return false;

        }
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:net.urlgrey.mythpodcaster.transcode.SegmentedVodTranscoderImpl.java

public void transcode(File workingDirectory, GenericTranscoderConfigurationItem genericConfig, File inputFile,
        File outputFile) throws Exception {
    LOG.info("transcode started: inputFile [" + inputFile.getAbsolutePath() + "], outputFile ["
            + outputFile.getAbsolutePath() + "]");

    SegmenterTranscoderConfigurationItem config = (SegmenterTranscoderConfigurationItem) genericConfig;
    List<String> commandList = new ArrayList<String>();
    commandList.add(niceLocation);/*from   w  w w .j av a2 s  .c o m*/
    commandList.add("-n");
    commandList.add(Integer.toString(config.getNiceness()));
    commandList.add(segmenterLocation);
    commandList.add(inputFile.getAbsolutePath());
    commandList.add(config.getSegmentDuration());
    commandList.add(config.getSegmentFilePrefix());
    commandList.add(config.getPlaylistFileName());
    commandList.add(config.getHttpPrefix());
    ProcessBuilder pb = new ProcessBuilder(commandList);

    pb.environment().put("LD_LIBRARY_PATH", "/usr/local/lib:");
    pb.redirectErrorStream(true);
    pb.directory(outputFile.getParentFile());
    Process process = null;

    try {
        // Get the segmenter process
        process = pb.start();
        // We give a couple of secs to complete task if needed
        Future<List<String>> stdout = pool.submit(new OutputMonitor(process.getInputStream()));
        List<String> result = stdout.get(config.getTimeout(), TimeUnit.SECONDS);
        process.waitFor();
        final int exitValue = process.exitValue();
        LOG.info("Segmenter exit value: " + exitValue);
        if (exitValue != 0) {
            for (String line : result) {
                LOG.error(line);
            }
            throw new Exception("Segmenter return code indicated failure: " + exitValue);
        }
    } catch (InterruptedException e) {
        throw new Exception("Segmenter process interrupted by another thread", e);
    } catch (ExecutionException ee) {
        throw new Exception("Something went wrong parsing Segmenter output", ee);
    } catch (TimeoutException te) {
        // We could not get the result before timeout
        throw new Exception("Segmenter process timed out", te);
    } catch (RuntimeException re) {
        // Unexpected output from Segmenter
        throw new Exception("Something went wrong parsing Segmenter output", re);
    } finally {
        if (process != null) {
            process.destroy();
        }
    }

    LOG.debug("transcoding finished");
}

From source file:npm.modules.java

public void excutecmdwindow(String[] command, String workfolder) throws Exception {
    ProcessBuilder builder = new ProcessBuilder(command);
    builder.directory(new File(workfolder).getAbsoluteFile());
    builder.redirectErrorStream(true);
    builder.start();//  www.  j a va  2 s.  co m
}

From source file:es.amplia.research.maven.protodocbook.cmd.Factory.java

private void execute(File directory, String... cmd) throws Exception {
    ProcessBuilder pb = new ProcessBuilder(cmd);
    Map<String, String> env = pb.environment();
    pb.directory(directory);/*from  w  w w  .j  a  v  a 2s  . c  o m*/
    pb.redirectErrorStream(true);
    Process p = pb.start();
    p.waitFor();
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = null;
    while ((line = br.readLine()) != null) {
        if (this.log.isInfoEnabled())
            this.log.info(line);
    }
}

From source file:org.kie.workbench.common.services.backend.compiler.offprocess.impl.CompilerIPCCoordinatorImpl.java

private void invokeServerBuild(String mavenRepo, String projectPath, String uuid, String classpath,
        String alternateSettingsAbsPath, String queueName) throws Exception {
    String[] commandArrayServer = { javaBin, "-cp", getClasspathIncludedCurrentModuleDep(mavenRepo, classpath),
            "-Dorg.uberfire.nio.git.daemon.enabled=false", "-Dorg.uberfire.nio.ssh.daemon.enabled=false",
            ServerIPCImpl.class.getCanonicalName(), uuid, projectPath, mavenRepo, alternateSettingsAbsPath,
            queueName };//from w  w w  . jav  a 2  s . c om
    if (logger.isDebugEnabled()) {
        logger.debug(
                "************************** \n Invoking server in a separate process with args: \n{} \n{} \n{} \n{} \n{} \n{} \n{} \n{} \n**************************",
                commandArrayServer);
    }
    ProcessBuilder serverPb = new ProcessBuilder(commandArrayServer);
    serverPb.directory(new File(projectPath));
    serverPb.redirectErrorStream(true);
    serverPb.inheritIO();
    writeStdOut(serverPb);
}