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:org.geoserver.ogr.core.AbstractToolWrapper.java

/**
 * Runs the specified command appending the output to the string builder and
 * returning the exit code.// w w  w.j ava  2s. c  o m
 * 
 * @param cmd the command to run and its arguments
 * @param sb command output is appended here
 * @return the exit code of the invoked command. Usually, 0 indicates normal termination
 * @throws IOException
 * @throws InterruptedException
 */
protected int run(List<String> cmd, StringBuilder sb) throws IOException, InterruptedException {
    // run the process and grab the output for error reporting purposes
    ProcessBuilder builder = new ProcessBuilder(cmd);
    if (environment != null)
        builder.environment().putAll(environment);
    builder.redirectErrorStream(true);
    Process p = builder.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = null;
    while ((line = reader.readLine()) != null) {
        if (sb != null) {
            sb.append("\n");
            sb.append(line);
        }
    }
    return p.waitFor();
}

From source file:com.mesosphere.dcos.cassandra.executor.tasks.RestoreSnapshot.java

@Override
public void run() {
    try {/*from  w  ww . j av a  2 s  .com*/
        // Send TASK_RUNNING
        sendStatus(driver, Protos.TaskState.TASK_RUNNING, "Started restoring snapshot");

        if (Objects.equals(context.getRestoreType(), new String("new"))) {
            final String keyspaceDirectory = context.getLocalLocation() + File.separator + context.getName()
                    + File.separator + context.getNodeId();

            final String ssTableLoaderBinary = CassandraPaths.create(version).bin().resolve("sstableloader")
                    .toString();
            final String cassandraYaml = CassandraPaths.create(version).cassandraConfig().toString();

            final File keyspacesDirectory = new File(keyspaceDirectory);
            LOGGER.info("Keyspace Directory {} exists: {}", keyspaceDirectory, keyspacesDirectory.exists());

            final File[] keyspaces = keyspacesDirectory.listFiles();

            String libProcessAddress = System.getenv("LIBPROCESS_IP");
            libProcessAddress = StringUtils.isBlank(libProcessAddress)
                    ? InetAddress.getLocalHost().getHostAddress()
                    : libProcessAddress;

            for (File keyspace : keyspaces) {
                final File[] columnFamilies = keyspace.listFiles();

                final String keyspaceName = keyspace.getName();
                if (keyspaceName.equals(StorageUtil.SCHEMA_FILE))
                    continue;
                LOGGER.info("Going to bulk load keyspace: {}", keyspaceName);

                for (File columnFamily : columnFamilies) {
                    final String columnFamilyName = columnFamily.getName();
                    if (columnFamilyName.equals(StorageUtil.SCHEMA_FILE))
                        continue;
                    LOGGER.info("Bulk loading... keyspace: {} column family: {}", keyspaceName,
                            columnFamilyName);

                    final String columnFamilyPath = columnFamily.getAbsolutePath();
                    final List<String> command = Arrays.asList(ssTableLoaderBinary, "-d", libProcessAddress,
                            "-u", context.getUsername(), "-pw", context.getPassword(), "-f", cassandraYaml,
                            columnFamilyPath);
                    LOGGER.info("Executing command: {}", command);

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

                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        LOGGER.info(line);
                    }

                    int exitCode = process.waitFor();
                    LOGGER.info("Command exit code: {}", exitCode);

                    // Send TASK_ERROR
                    if (exitCode != 0) {
                        final String errMessage = String.format("Error restoring snapshot. Exit code: %s",
                                (exitCode + ""));
                        LOGGER.error(errMessage);
                        sendStatus(driver, Protos.TaskState.TASK_ERROR, errMessage);
                    }

                    LOGGER.info("Done bulk loading! keyspace: {} column family: {}", keyspaceName,
                            columnFamilyName);
                }
                LOGGER.info("Successfully bulk loaded keyspace: {}", keyspaceName);
            }
            // cleanup downloaded snapshot directory recursively.
            Path rootPath = Paths.get(context.getLocalLocation() + File.separator + context.getName());
            if (rootPath.toFile().exists()) {
                Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder())
                        .map(Path::toFile).forEach(File::delete);
            }
        } else {
            // run nodetool refresh rather than SSTableLoader, as on performance test
            // I/O stream was pretty slow between mesos container processes
            final String localLocation = context.getLocalLocation();
            final List<String> keyspaces = cassandra.getNonSystemKeySpaces();
            for (String keyspace : keyspaces) {
                final String keySpaceDirPath = localLocation + "/" + keyspace;
                File keySpaceDir = new File(keySpaceDirPath);
                File[] cfNames = keySpaceDir
                        .listFiles((current, name) -> new File(current, name).isDirectory());
                for (File cfName : cfNames) {
                    String columnFamily = cfName.getName().substring(0, cfName.getName().indexOf("-"));
                    cassandra.getProbe().loadNewSSTables(keyspace, columnFamily);
                    LOGGER.info("Completed nodetool refresh for keyspace {} & columnfamily {}", keyspace,
                            columnFamily);
                }
            }
        }

        final String message = "Finished restoring snapshot";
        LOGGER.info(message);
        sendStatus(driver, Protos.TaskState.TASK_FINISHED, message);
    } catch (Throwable t) {
        // Send TASK_FAILED
        final String errorMessage = "Failed restoring snapshot. Reason: " + t;
        LOGGER.error(errorMessage, t);
        sendStatus(driver, Protos.TaskState.TASK_FAILED, errorMessage);
    }
}

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

protected Process runCommandLine(String[] commandLine, boolean inInheritOutput)
        throws IOException, InterruptedException {
    ProcessBuilder pb = this.generateProcessBuilder(commandLine);
    if (inInheritOutput) {
        pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    } else {/*from   w  w  w. jav a 2  s.c o m*/
        pb.redirectOutput(ProcessBuilder.Redirect.PIPE);
    }
    pb.redirectErrorStream(true);
    Process process = pb.start();

    return process;
}

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  ava2s.  co 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:org.mashupmedia.encode.ProcessManager.java

public String callProcess(List<String> commands) throws IOException {

    logger.info("Starting process...");

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

    InputStream inputStream = process.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    String line;//  w  w  w .  ja v a2  s .  com

    StringBuilder outputBuilder = new StringBuilder();

    while ((line = bufferedReader.readLine()) != null) {
        logger.info(line);
        outputBuilder.append(line);
    }
    IOUtils.closeQuietly(inputStream);

    try {
        int waitForValue = process.waitFor();
        logger.info("Process waitFor value = " + waitForValue);
    } catch (InterruptedException e) {
        logger.error("Error waiting for waitFor.", e);
    }

    int exitValue = process.exitValue();
    logger.info("Process exit value = " + exitValue);

    return outputBuilder.toString();

}

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);/*w ww  . java  2s .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.netflix.raigad.defaultimpl.ElasticSearchProcessManager.java

public void start(boolean join_ring) throws IOException {
    logger.info("Starting elasticsearch server");

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

    ProcessBuilder startEs = new ProcessBuilder(command);
    Map<String, String> env = startEs.environment();

    env.put("DATA_DIR", config.getDataFileLocation());

    startEs.directory(new File("/"));
    startEs.redirectErrorStream(true);
    Process starter = startEs.start();
    logger.info("Starting Elasticsearch server ....");
    try {
        sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS);
        int code = starter.exitValue();
        if (code == 0)
            logger.info("Elasticsearch server has been started");
        else
            logger.error("Unable to start Elasticsearch server. Error code: {}", code);

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

From source file:org.sonar.process.monitor.JavaProcessLauncher.java

private ProcessBuilder create(JavaCommand javaCommand) {
    List<String> commands = new ArrayList<>();
    commands.add(buildJavaPath());//from  ww  w  . j  av  a 2  s . c o m
    commands.addAll(javaCommand.getJavaOptions());
    // TODO warning - does it work if temp dir contains a whitespace ?
    commands.add(String.format("-Djava.io.tmpdir=%s", tempDir.getAbsolutePath()));
    commands.add(getJmxAgentCommand());
    commands.addAll(buildClasspath(javaCommand));
    commands.add(javaCommand.getClassName());
    commands.add(buildPropertiesFile(javaCommand).getAbsolutePath());

    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.command(commands);
    processBuilder.directory(javaCommand.getWorkDir());
    processBuilder.environment().putAll(javaCommand.getEnvVariables());
    processBuilder.redirectErrorStream(true);
    return processBuilder;
}

From source file:org.trancecode.xproc.step.ExecStepProcessor.java

@Override
protected void execute(final StepInput input, final StepOutput output) throws Exception {
    final String pathSeparator = input.getOptionValue(XProcOptions.PATH_SEPARATOR);
    final String command;
    if (pathSeparator != null) {
        command = input.getOptionValue(XProcOptions.COMMAND).replace(pathSeparator, File.separator);
    } else {/*from   ww  w  . j a va 2s .c  o  m*/
        command = input.getOptionValue(XProcOptions.COMMAND);
    }

    final String argSeparator = input.getOptionValue(XProcOptions.ARG_SEPARATOR, " ");
    final Iterable<String> rawArgs = TcStrings.split(input.getOptionValue(XProcOptions.ARGS), argSeparator);
    final Iterable<String> args = Iterables.transform(rawArgs, arg -> {
        if (pathSeparator != null) {
            return arg.replace(pathSeparator, File.separator);
        }

        return arg;
    });
    final String cwd = input.getOptionValue(XProcOptions.CWD);

    final List<XdmNode> inputDocuments = ImmutableList.copyOf(input.readNodes(XProcPorts.SOURCE));
    if (inputDocuments.size() > 1) {
        throw XProcExceptions.xd0006(input.getStep().getLocation(),
                input.getStep().getPortReference(XProcPorts.SOURCE));
    }
    final boolean sourceIsXml = Boolean.parseBoolean(input.getOptionValue(XProcOptions.SOURCE_IS_XML));
    final boolean resultIsXml = Boolean.parseBoolean(input.getOptionValue(XProcOptions.RESULT_IS_XML));
    final boolean wrapResultLines = Boolean.parseBoolean(input.getOptionValue(XProcOptions.WRAP_RESULT_LINES));
    final boolean errorsIsXml = Boolean.parseBoolean(input.getOptionValue(XProcOptions.ERRORS_IS_XML));
    final boolean wrapErrorLines = Boolean.parseBoolean(input.getOptionValue(XProcOptions.WRAP_ERROR_LINES));
    if ((resultIsXml && wrapResultLines) || (errorsIsXml && wrapErrorLines)) {
        throw XProcExceptions.xc0035(input.getStep().getLocation());
    }

    final List<String> commandLine = Lists.newArrayList();
    commandLine.add(command);
    Iterables.addAll(commandLine, Iterables.filter(args, StringPredicates.isNotEmpty()));
    LOG.trace("  commandLine = {}", commandLine);
    final ProcessBuilder processBuilder = new ProcessBuilder(commandLine.toArray(new String[0]));
    processBuilder.redirectErrorStream(false);
    if (cwd != null) {
        final Path newDirectory = Paths.get(cwd);
        if (!Files.isDirectory(newDirectory)) {
            throw XProcExceptions.xc0034(input.getLocation());
        }
        processBuilder.directory(new File(cwd));
    }
    final Process process;
    try {
        process = processBuilder.start();
    } catch (IOException e) {
        throw XProcExceptions.xc0033(input.getLocation());
    }

    if (!inputDocuments.isEmpty()) {
        final String inputContent;
        if (sourceIsXml) {
            inputContent = inputDocuments.get(0).toString();
        } else {
            inputContent = SaxonAxis.childElement(inputDocuments.get(0)).getStringValue();
        }

        new Thread(() -> {
            try {
                IOUtils.write(inputContent, process.getOutputStream());
            } catch (final IOException e) {
                throw new IllegalStateException(e);
            } finally {
                Closeables.closeQuietly(process.getOutputStream());
            }
        }).start();
    }

    final Supplier<File> stdout = TcByteStreams.copyToTempFile(process.getInputStream());
    final Supplier<File> stderr = TcByteStreams.copyToTempFile(process.getErrorStream());

    final int exitCode = process.waitFor();
    LOG.trace("exitCode = {}", exitCode);
    final String failureThreshold = input.getOptionValue(XProcOptions.FAILURE_THRESHOLD);
    if (failureThreshold != null) {
        LOG.trace("failureThreshold  = {}", failureThreshold);
        final int numericFailureThreshold = Integer.parseInt(failureThreshold);
        if (exitCode > numericFailureThreshold) {
            throw XProcExceptions.xc0064(input.getLocation(), exitCode, numericFailureThreshold);
        }
    }

    final File stdoutFile = stdout.get();
    final File stderrFile = stderr.get();
    process.destroy();

    final Processor processor = input.getPipelineContext().getProcessor();
    output.writeNodes(XProcPorts.RESULT,
            parseOutput(stdoutFile, resultIsXml, wrapResultLines, input.getStep().getNode(), processor));
    output.writeNodes(XProcPorts.ERRORS,
            parseOutput(stderrFile, errorsIsXml, wrapErrorLines, input.getStep().getNode(), processor));
    output.writeNodes(XProcPorts.EXIT_STATUS, input.newResultElement(Integer.toString(exitCode)));
}

From source file:edu.cornell.med.icb.clustering.MCLClusterer.java

/**
 * Groups instances into clusters. Returns the indices of the instances that belong to a cluster
 * as an int array in the list result./*  w ww  . jav a  2  s .  c o  m*/
 *
 * @param calculator The {@link SimilarityDistanceCalculator}
 * that should be used when clustering
 * @param qualityThreshold The QT clustering algorithm quality threshold (d)
 * @return The list of clusters.
 */
public List<int[]> cluster(final SimilarityDistanceCalculator calculator, final double qualityThreshold) {
    if (mclCommand == null) {
        throw new IllegalStateException("mcl command not set!");
    }

    // reset cluster results
    clusterCount = 0;
    for (int i = 0; i < instanceCount; i++) {
        clusters[i].clear();
    }

    BufferedReader br = null;
    try {
        final File mclInputFile = File.createTempFile("mcl-input", ".txt");
        writeMCLInputFile(mclInputFile, calculator, qualityThreshold);

        final File mclOutputFile = File.createTempFile("mcl-output", ".txt");
        final String[] command = { mclCommand, mclInputFile.getAbsolutePath(), "--abc", "-o",
                mclOutputFile.getAbsolutePath() };

        LOGGER.info("Executing: " + ArrayUtils.toString(command));

        final ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectErrorStream(true);
        final Process process = builder.start();
        final InputStream is = process.getInputStream();
        final InputStreamReader isr = new InputStreamReader(is);
        br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
            LOGGER.info(line);
        }
        process.waitFor();

        LOGGER.info("Program terminated!");

        readMCLOutputFile(mclOutputFile);
    } catch (IOException e) {
        LOGGER.error("Counldn't create MCL file", e);
        throw new ClusteringException("Counldn't create MCL file", e);
    } catch (InterruptedException e) {
        LOGGER.error("Interrupted!", e);
        Thread.currentThread().interrupt();
    } finally {
        IOUtils.closeQuietly(br);
    }

    return getClusters();
}