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.freedesktop.icons.DConf.java

private void load() throws IOException {
    if (loaded) {
        return;/*from ww w.  j a va  2s  .  co  m*/
    }

    try {
        ProcessBuilder pb = new ProcessBuilder("dconf", "list", path);
        pb.redirectErrorStream();
        Process p = pb.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        try {
            String line = null;
            while ((line = r.readLine()) != null) {
                if (line.endsWith("/")) {
                    DConf d = new DConf(path + line);
                    children.put(line, d);
                } else {
                    values.put(line, null);
                }
            }
        } finally {
            r.close();
            p.waitFor();
        }

        for (Map.Entry<String, Entry<?>> en : values.entrySet()) {
            pb = new ProcessBuilder("dconf", "read", path + en.getKey());
            pb.redirectErrorStream();
            p = pb.start();
            r = new BufferedReader(new InputStreamReader(p.getInputStream()));
            try {
                en.setValue(new Entry<Object>(en.getKey(), r.readLine()));
            } finally {
                r.close();
                p.waitFor();
            }
        }
    } catch (InterruptedException ie) {
        throw new RuntimeException(ie);
    }

    loaded = true;
}

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

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

    FFMpegTranscoderConfigurationItem config = (FFMpegTranscoderConfigurationItem) genericConfig;
    List<String> commandList = new ArrayList<String>();
    commandList.add(niceLocation);/*from w  ww. j av  a  2 s  . c o  m*/
    commandList.add("-n");
    commandList.add(Integer.toString(config.getNiceness()));
    commandList.add(ffmpegLocation);
    commandList.add("-i");
    commandList.add(inputFile.getAbsolutePath());
    commandList.addAll(config.getParsedEncoderArguments());
    commandList.add(outputFile.getAbsolutePath());
    ProcessBuilder pb = new ProcessBuilder(commandList);

    // Needed for ffmpeg
    pb.environment().put("LD_LIBRARY_PATH", "/usr/local/lib:");
    pb.redirectErrorStream(true);
    pb.directory(workingDirectory);
    Process process = null;

    try {
        // Get the ffmpeg 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("FFMPEG exit value: " + exitValue);
        if (exitValue != 0) {
            for (String line : result) {
                LOG.error(line);
            }
            throw new Exception("FFMpeg return code indicated failure: " + exitValue);
        }
    } catch (InterruptedException e) {
        throw new Exception("FFMpeg process interrupted by another thread", e);
    } catch (ExecutionException ee) {
        throw new Exception("Something went wrong parsing FFMpeg output", ee);
    } catch (TimeoutException te) {
        // We could not get the result before timeout
        throw new Exception("FFMpeg process timed out", te);
    } catch (RuntimeException re) {
        // Unexpected output from FFMpeg
        throw new Exception("Something went wrong parsing FFMpeg output", re);
    } finally {
        if (process != null) {
            process.destroy();
        }
    }

    LOG.debug("transcoding finished");
}

From source file:org.kepler.util.sql.HSQL.java

/** Start the HSQL Server */
private static int _launchDBServer(String dbNamePath, String dbAlias, String dbPort) {

    if (_forkServers) {
        System.out.println("spawning HSQL server for " + dbNamePath);

        // find the hsql jar
        String classpath = System.getProperty("java.class.path");
        String[] jars = classpath.split(File.pathSeparator);
        String hsqlJar = null;//from  www  .j  av  a  2 s .com
        for (String jar : jars) {
            if (jar.matches(".*hsqldb-[\\d\\.]+\\.jar$")) {
                hsqlJar = jar;
                break;
            }
        }

        if (hsqlJar == null) {
            MessageHandler.error("Unable to find HSQL jar in class path.");
            return ServerConstants.SERVER_STATE_SHUTDOWN;
        }

        // NOTE: the database argument must include the file name of
        // the database. when using the Server API to start the server
        // (see below), the database argument does NOT include the file
        // name, but uses the alias as the file name.

        ProcessBuilder procBuilder = new ProcessBuilder("java", "-cp", hsqlJar, "org.hsqldb.Server", "-address",
                "localhost", "-port", dbPort, "-dbname.0", dbAlias, "-database.0",
                dbNamePath + File.separator + dbAlias);
        procBuilder.redirectErrorStream(true);

        //for(String str : procBuilder.command())
        //System.out.print(str + " ");
        //System.out.println();

        try {
            /*Process proc =*/ procBuilder.start();

            // sleep a few seconds so that it has time to start before we
            // try to connect
            // XXX this may not be long enough
            Thread.sleep(3000);
            return ServerConstants.SERVER_STATE_ONLINE;
        } catch (Exception e) {
            MessageHandler.error("Error starting HSQL server.", e);
            return ServerConstants.SERVER_STATE_SHUTDOWN;
        }
    } else {
        Server server = new Server();

        if (!_isDebugging) {
            server.setLogWriter(null);
            server.setErrWriter(null);
        } else {
            _log.debug("starting server for " + dbNamePath);
        }

        // the file name is full path and alias.
        String dbFileName = dbNamePath + File.separator + dbAlias;

        server.setDatabasePath(0, dbFileName);
        server.setDatabaseName(0, dbAlias);

        if (dbPort != null && dbPort.length() > 0) {
            try {
                int port = Integer.parseInt(dbPort);
                server.setPort(port);
            } catch (NumberFormatException e) {
                System.out.print("ERROR: bad port " + dbPort + ": " + e.getMessage());
            }
        }

        server.setSilent(true);
        server.setTrace(false);
        server.setNoSystemExit(true);
        server.start();

        _servers.add(server);

        return server.getState();
    }
}

From source file:org.auraframework.archetype.AuraArchetypeSimpleTestMANUAL.java

private Process startProcess(File workingDir, List<String> command) throws Exception {
    ProcessBuilder builder = new ProcessBuilder(command);
    builder.directory(workingDir);//from  w  ww  .j  a v  a 2 s.  c  o m
    builder.redirectErrorStream(true);
    return builder.start();
}

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);
    builder.directory(detectBaseDirectory());
    Process p = builder.start();/* w  w w.  j  a  v  a  2s.  c om*/
    p.waitFor();
    IOUtils.copy(p.getInputStream(), System.out);
    return p;
}

From source file:org.zaproxy.zap.extension.ascanrules.wpscan.java

@Override
public void scan() {
    try {/*from   www . java 2  s .c o  m*/
        URI originalURI = this.getBaseMsg().getRequestHeader().getURI();
        String target = originalURI.getScheme() + "://" + originalURI.getAuthority();
        log.info("Starting wpscan... Target is " + target);
        log.info(target);
        ProcessBuilder builder = new ProcessBuilder("/usr/bin/wpscan", "--url", target);
        builder.redirectErrorStream(true);
        Process process = builder.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String fileExistsPatternString = "^\\[31m\\[!\\]\\[0m The WordPress '(.*)' file exists$";
        Pattern fileExistsPattern = Pattern.compile(fileExistsPatternString, Pattern.MULTILINE);

        String backupExistsPatternString = "^\\[31m\\[!\\]\\[0m A (.*) backup file has been found in: '(.*)'$";
        Pattern backupExistsPattern = Pattern.compile(backupExistsPatternString, Pattern.MULTILINE);

        String vulnWithReferencePatternString = "^\\[31m\\[!\\]\\[0m(?:Title:)? (.*)\n    Reference: (.*)";
        Pattern vulnWithReferencePattern = Pattern.compile(vulnWithReferencePatternString, Pattern.MULTILINE);

        String vulnPatternString = "^\\[31m\\[!\\]\\[0m(?: Title\\:)? (.*)";
        Pattern vulnPattern = Pattern.compile(vulnPatternString);

        String blockDelimiterPatternString = ".*\n\n.*";
        Pattern blockDelimiterPattern = Pattern.compile(blockDelimiterPatternString, Pattern.MULTILINE);

        String line;
        String buffer = "";
        while ((line = reader.readLine()) != null) {
            buffer += line + "\n";

            Matcher blockDelimiterMatcher = blockDelimiterPattern.matcher(buffer);

            if (blockDelimiterMatcher.find()) { // new block, process it.
                Matcher fileExistsMatcher = fileExistsPattern.matcher(buffer);
                Matcher backupExistsMatcher = backupExistsPattern.matcher(buffer);
                Matcher vulnWithReferenceMatcher = vulnWithReferencePattern.matcher(buffer);
                Matcher vulnMatcher = vulnPattern.matcher(buffer);

                while (fileExistsMatcher.find()) {
                    bingo(Alert.RISK_INFO, Alert.WARNING, "WordPress installation file",
                            "A WordPress installation is present on the server.", fileExistsMatcher.group(1),
                            "", fileExistsMatcher.group(1), "",
                            "These files should be removed from the server upon installation.",
                            "Remove installation files.", getNewMsg());
                }
                while (backupExistsMatcher.find()) {
                    bingo(Alert.RISK_HIGH, Alert.WARNING,
                            "WordPress " + backupExistsMatcher.group(1) + " backup file",
                            "A WordPress configuration back file is present on the server.",
                            backupExistsMatcher.group(2), "", backupExistsMatcher.group(2), "",
                            "Backup files should not be accessible from the web server.",
                            "Backup your files at a safe place that is not acessible from the web server.",
                            getNewMsg());
                }
                if (vulnWithReferenceMatcher.find()) {
                    bingo(Alert.RISK_HIGH, Alert.WARNING, vulnWithReferenceMatcher.group(1),
                            "Wordpress Vulnerability.", vulnWithReferenceMatcher.group(1), "",
                            vulnWithReferenceMatcher.group(1), vulnWithReferenceMatcher.group(2), "", ".",
                            getNewMsg());
                } else if (vulnMatcher.find()) {
                    bingo(Alert.RISK_HIGH, Alert.WARNING, vulnMatcher.group(1), "Wordpress Vulnerability.",
                            vulnMatcher.group(1), "", vulnMatcher.group(1), "", "", ".", getNewMsg());
                }

                buffer = ""; //clear buffer
            }
        }

    } catch (Exception e) {
        log.info("Error" + e.getMessage());
    }
}

From source file:com.asakusafw.testdriver.DefaultJobExecutor.java

private int runCommand(List<String> commandLine, Map<String, String> environmentVariables) throws IOException {
    LOG.info(MessageFormat.format(Messages.getString("DefaultJobExecutor.infoEchoCommandLine"), //$NON-NLS-1$
            toCommandLineString(commandLine)));

    ProcessBuilder builder = new ProcessBuilder(commandLine);
    builder.redirectErrorStream(true);
    builder.environment().putAll(environmentVariables);
    File hadoopCommand = configurations.getHadoopCommand();
    if (hadoopCommand != null) {
        builder.environment().put("HADOOP_CMD", hadoopCommand.getAbsolutePath()); //$NON-NLS-1$
    }/*from   www .  j  a  v  a  2s .c  o  m*/
    builder.directory(new File(System.getProperty("user.home", "."))); //$NON-NLS-1$ //$NON-NLS-2$

    int exitCode;
    Process process = builder.start();
    try (InputStream is = process.getInputStream()) {
        InputStreamThread it = new InputStreamThread(is);
        it.start();
        exitCode = process.waitFor();
        it.join();
    } catch (InterruptedException e) {
        throw new IOException(
                MessageFormat.format(Messages.getString("DefaultJobExecutor.errorExecutionInterrupted"), //$NON-NLS-1$
                        toCommandLineString(commandLine)),
                e);
    } finally {
        process.getOutputStream().close();
        process.getErrorStream().close();
        process.destroy();
    }
    return exitCode;
}

From source file:org.geoserver.wfs.response.OGRWrapper.java

/**
 * Runs the specified command appending the output to the string builder and
 * returning the exit code//from w  w w.j a v  a  2  s  . c  o  m
 * 
 * @param cmd
 * @param sb
 * @return
 * @throws IOException
 * @throws InterruptedException
 */
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 (gdalData != null)
        builder.environment().put("GDAL_DATA", gdalData);
    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:de.tudarmstadt.ukp.dkpro.core.RSTAnnotator.java

/**
 * Runs the parser on the given text// w w  w.  j av a 2 s.c  om
 *
 * @param originalText text
 * @return parse tree
 * @throws IOException exception
 */
public String parseWithRST(String originalText) throws IOException {
    // temporary file in
    File tmpFileIn = File.createTempFile("rst_tmp", ".txt");
    // output of RST parser is a .tree file
    File tmpFileOut = new File(tmpFileIn.getAbsolutePath() + ".tree");
    // tmp log
    File tmpFileLog = new File(tmpFileIn.getAbsolutePath() + ".log");

    try {
        // write the text into a temporary file
        FileUtils.writeStringToFile(tmpFileIn, originalText);

        String tmpDirName = System.getProperty("java.io.tmpdir");

        File rstParserSrcDir = new File(rstParserSrcDirPath);

        // create process
        ProcessBuilder processBuilder = new ProcessBuilder().inheritIO();

        // log to file
        processBuilder.redirectErrorStream(true);
        processBuilder.redirectOutput(ProcessBuilder.Redirect.to(tmpFileLog));

        // working dir must be set to the src dir of RST parser
        processBuilder.directory(rstParserSrcDir);

        // run the command
        processBuilder.command("python", new File(rstParserSrcDir, "parse.py").getAbsolutePath(), "-t",
                tmpDirName, tmpFileIn.getAbsolutePath(), "-g");
        Process process = processBuilder.start();

        // and wait
        int returnValue = process.waitFor();

        if (returnValue != 0) {
            throw new RuntimeException("Process exited with code " + returnValue);
        }

        // read the log
        if (this.debugRSTOutput) {
            getLogger().debug(FileUtils.readFileToString(tmpFileLog));
        }

        // read the output
        if (tmpFileOut.exists()) {
            return FileUtils.readFileToString(tmpFileOut);
        }
    } catch (InterruptedException e) {
        throw new IOException(e);
    } finally {
        // clean up
        if (!keepTmpFiles) {
            FileUtils.deleteQuietly(tmpFileIn);
            FileUtils.deleteQuietly(tmpFileOut);
            FileUtils.deleteQuietly(tmpFileLog);
        }
    }

    return null;
}

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

public void stop() throws IOException {
    logger.info("Stopping Dynomite server ....");
    List<String> command = Lists.newArrayList();
    if (!"root".equals(System.getProperty("user.name"))) {
        command.add(SUDO_STRING);/*from w  ww  . j  av  a 2  s .  c  o m*/
        command.add("-n");
        command.add("-E");
    }
    for (String param : config.getDynomiteStopScript().split(" ")) {
        if (StringUtils.isNotBlank(param))
            command.add(param);
    }
    ProcessBuilder stopCass = new ProcessBuilder(command);
    stopCass.directory(new File("/"));
    stopCass.redirectErrorStream(true);
    Process stopper = stopCass.start();

    sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS);
    try {
        int code = stopper.exitValue();
        if (code == 0) {
            logger.info("Dynomite server has been stopped");
            instanceState.setStorageProxyAlive(false);
        } else {
            logger.error("Unable to stop Dynomite server. Error code: {}", code);
            logProcessOutput(stopper);
        }
    } catch (Exception e) {
        logger.warn("couldn't shut down Dynomite correctly", e);
    }
}