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:net.landora.video.mediainfo.MediaInfoParser.java

public Video handleFile(File f) {

    try {//from w  w w.  j a  v a  2 s.c om
        //ProcessBuilder process = new ProcessBuilder(Program.MediaInfo.getConfiguredPath(), "-Full", "--Language=raw", f.getAbsolutePath());
        ProcessBuilder process = new ProcessBuilder(
                ProgramsAddon.getInstance().getConfiguredPath(CommonPrograms.MEDIAINFO), "-Full",
                "--Language=raw", f.getAbsolutePath());
        process.redirectErrorStream(true);
        Process p = process.start();

        StringWriter buffer = new StringWriter();
        IOUtils.copy(p.getInputStream(), buffer);
        p.waitFor();

        String reply = buffer.toString();
        buffer = null;

        file = new Video();
        file.setFile(f);

        state = State.EmptyLine;

        BufferedReader reader = new BufferedReader(new StringReader(reply));
        String line;
        while ((line = reader.readLine()) != null) {

            Matcher m = dataPattern.matcher(line);
            if (m.matches()) {
                String field = m.group(1);
                String value = m.group(2);

                switch (state) {
                case General:
                    handleGeneral(field, value);
                    break;

                case Video:
                    handleVideo(field, value);
                    break;

                case Audio:
                    handleAudio(field, value);
                    break;

                case Text:
                    handleSubtitle(field, value);
                    break;

                case Chapters:
                    handleChapter(field, value);
                    break;
                }

            } else if (line.trim().isEmpty()) {
                state = State.EmptyLine;
            } else {
                line = line.trim();
                if (line.equals("General")) {
                    state = State.General;
                } else if (line.equals("Video")) {
                    state = State.Video;
                    curVideo = new VideoStream();
                    file.getVideoStreams().add(curVideo);
                } else if (line.equals("Audio")) {
                    state = State.Audio;
                    curAudio = new AudioStream();
                    curAudio.setStreamId(++audioCount);
                    file.getAudioStreams().add(curAudio);
                } else if (line.equals("Text")) {
                    state = State.Text;
                    curSubtitle = new SubtitleStream();
                    curSubtitle.setStreamId(subtitleCount++);
                    file.getSubtitleStreams().add(curSubtitle);
                } else if (line.equals("Chapters")) {
                    state = State.Chapters;
                }
            }

        }

        cleanupChapters();

        return file;
    } catch (Exception e) {
        return null;
    }
}

From source file:org.opencastproject.gstreamer.service.impl.GStreamerServiceImpl.java

/**
 * Launch the gstreamer pipeline from the gstreamerLine.
 * /*from  w w w . j av  a 2s .  c o  m*/
 * @param gstreamerLine
 *          The gstreamer line to execute.
 * @throws GStreamerLaunchException
 *           Thrown if the pipeline fails to execute.
 */
private void launchGStreamerLine(String gstreamerLine) throws GStreamerLaunchException {
    Process process = null;
    try {
        ArrayList<String> args = new ArrayList<String>();
        args.add(getGStreamerLocation());
        args.addAll(Arrays.asList(gstreamerLine.split(" ")));
        ProcessBuilder pb = new ProcessBuilder(args);
        pb.redirectErrorStream(true); // Unfortunately merges but necessary for deadlock prevention
        process = pb.start();
        BufferedReader inputStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
        process.waitFor();
        StringBuilder sb = new StringBuilder();
        String line = inputStream.readLine();
        while (line != null) {
            sb.append(line);
            line = inputStream.readLine();
        }
        if (process.exitValue() != 0) {
            throw new GStreamerLaunchException(
                    "gstreamer failed with error code: " + process.exitValue() + ". " + sb.toString());
        }
    } catch (IOException e) {
        throw new GStreamerLaunchException(
                "Could not start gstreamer pipeline: " + gstreamerLine + "\n" + e.getMessage());
    } catch (InterruptedException e) {
        throw new GStreamerLaunchException(
                "Could not start gstreamer pipeline: " + gstreamerLine + "\n" + e.getMessage());
    }
    logger.info("Gstreamer process finished");
}

From source file:jenkins.plugins.tanaguru.TanaguruRunner.java

public void callTanaguruService() throws IOException, InterruptedException {
    File logFile = TanaguruRunnerBuilder.createTempFile(contextDir, "log-" + new Random().nextInt() + ".log",
            "");//from  ww  w .  j a va 2s .  c  o  m
    File scenarioFile = TanaguruRunnerBuilder.createTempFile(contextDir, scenarioName + "_#" + buildNumber,
            TanaguruRunnerBuilder.forceVersion1ToScenario(scenario));

    ProcessBuilder pb = new ProcessBuilder(tgScriptName, "-f", firefoxPath, "-r", referential, "-l", level,
            "-d", displayPort, "-x", xmxValue, "-o", logFile.getAbsolutePath(), "-t", "Scenario",
            scenarioFile.getAbsolutePath());

    pb.directory(contextDir);
    pb.redirectErrorStream(true);
    Process p = pb.start();
    p.waitFor();

    extractDataAndPrintOut(logFile, listener.getLogger());

    if (!isDebug) {
        FileUtils.deleteQuietly(logFile);
    }

    FileUtils.deleteQuietly(scenarioFile);
}

From source file:edu.clemson.cs.nestbed.server.management.instrumentation.ProgramCompileManagerImpl.java

private File getMessageFile(File dir, String messageType) throws IOException {
    log.info("getMessageFile():  directory = " + dir.getAbsolutePath() + ", messageType = " + messageType);

    ProcessBuilder processBuilder = new ProcessBuilder(GET_FILE, dir.getAbsolutePath(), messageType);
    processBuilder.redirectErrorStream(true);
    Process process = processBuilder.start();

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

    String line = in.readLine();/*from w w w  .jav a  2  s. co  m*/
    in.close();

    return (line != null) ? new File(line) : null;
}

From source file:archive_v1.Archive_Form.java

public void execArchive(int compress) {
    String execArchiveCommand = null;
    if (compress == 0) {
        execArchiveCommand = "cd /u01 && tar cvf /dev/st0 archive";
    } else {/*  w  w  w.  j av a 2 s . c  o  m*/
        execArchiveCommand = "cd /u01 && tar czf /dev/st0 archive";
    }
    Process proc = null;
    String output = null;
    try {

        ProcessBuilder builder = new ProcessBuilder("/bin/sh", "-c", execArchiveCommand);
        builder.redirectErrorStream(true);
        proc = builder.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));

        output = reader.readLine();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ape.CorruptCommand.java

/**
 * This method is used to fetch the hdfs config file
 * and then fetch the address of where hdfs blk files
 * are stored from the config file//from   w w w  .  j  a  v a 2s .  co m
 * finally, it returns that a random hdfs blk in that address
 */
private String getCorruptAddress() throws IOException {
    String cmd = "cat $HADOOP_HOME/conf/hdfs-site.xml | grep -A1 'dfs.data.dir' | grep 'value'";
    System.out.println(cmd);
    ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(true);
    Process sh = null;
    try {

        sh = pb.start();
        if (sh.waitFor() != 0) {
            System.out.println("Executing '" + cmd + "' returned a nonzero exit code.");
            System.out.println("Unable to find HDFS block files");
            Main.logger.info("Executing '" + cmd + "' returned a nonzero exit code.");
            Main.logger.info("Unable to find HDFS block files");
            return null;
        }
    } catch (IOException e) {
        System.out.println("Failed to acquire block address");
        Main.logger.info("Failed to acquire block address");
        e.printStackTrace();
        Main.logger.info(e);
        return null;

    } catch (InterruptedException e) {
        System.out.println("Caught an Interrupt while runnning");
        Main.logger.info("Caught an Interrupt while runnning");
        e.printStackTrace();
        Main.logger.info(e);
        return null;
    }

    InputStream shIn = sh.getInputStream();
    InputStreamReader isr = new InputStreamReader(shIn);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    try {
        line = br.readLine();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    br.close();
    isr.close();
    line = line.trim();

    int end = line.indexOf("</value>");

    //parse the String and randomly select an address
    String address = line.substring(7, end);

    ArrayList<String> addresses = new ArrayList<String>();

    int idx;

    while ((idx = address.indexOf(',')) != -1) {
        addresses.add(address.substring(0, idx));
        address = address.substring(idx + 1);
    }
    addresses.add(address);

    int index = new Random().nextInt(addresses.size());

    address = addresses.get(index).concat("/current");

    if (Main.VERBOSE) {
        System.out.println("The address of the HDFS data folder is: " + address);
    }
    Main.logger.info("The address of the HDFS data folder is: " + address);

    if (datatype.equalsIgnoreCase("meta")) {
        cmd = "ls " + address + " | grep -i 'blk' |grep -i 'meta' ";
    } else {
        cmd = "ls " + address + " | grep -i 'blk' | grep -v 'meta' ";
    }

    pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(true);

    sh = pb.start();

    try {
        if (sh.waitFor() != 0) {
            System.out.println("Getting address of the list of files failed");
            return null;
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
        return null;
    }

    shIn = sh.getInputStream();

    isr = new InputStreamReader(shIn);
    br = new BufferedReader(isr);

    ArrayList<String> data = new ArrayList<String>();

    while ((line = br.readLine()) != null) {
        data.add(line);
    }

    int length = data.size();
    Random rdm = new Random();

    int random = rdm.nextInt(length);

    address = address.concat("/" + data.get(random));

    if (Main.VERBOSE) {
        System.out.println("The location of the data corrupted is " + address);
    }

    // Log the corrupted block
    Main.logger.info("The location of the data corrupted is " + address);

    br.close();
    isr.close();
    shIn.close();

    return address;
}

From source file:edu.clemson.cs.nestbed.server.management.instrumentation.ProgramCompileManagerImpl.java

private List<String> getMessageList(File dir, String tosPlatform) throws IOException {
    log.info("getMessageList(): directory = " + dir.getAbsolutePath() + ", tosPlatform = " + tosPlatform);
    List<String> messageList = new ArrayList<String>();
    ProcessBuilder processBuilder = new ProcessBuilder(GET_TYPES, dir.getAbsolutePath(), tosPlatform);
    processBuilder.redirectErrorStream(true);
    Process process = processBuilder.start();

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

    String line;//from  w w  w.java2  s . co m
    while ((line = in.readLine()) != null) {
        messageList.add(line);
    }
    in.close();

    return messageList;
}

From source file:org.sonatype.nexus.testsuite.obr.ObrITSupport.java

protected void deployUsingObrIntoFelix(final String repoId) throws Exception {
    final File felixHome = util.resolveFile("target/org.apache.felix.main.distribution-3.2.2");
    final File felixRepo = util.resolveFile("target/felix-local-repository");
    final File felixConfig = testData().resolveFile("felix.properties");

    // ensure we have an obr.xml
    final Content content = content();
    final Location obrLocation = new Location(repoId, ".meta/obr.xml");
    content.download(obrLocation, new File(testIndex().getDirectory("downloads"), repoId + "-obr.xml"));

    FileUtils.deleteDirectory(new File(felixHome, "felix-cache"));
    FileUtils.deleteDirectory(new File(felixRepo, ".meta"));

    final ProcessBuilder pb = new ProcessBuilder("java", "-Dfelix.felix.properties=" + felixConfig.toURI(),
            "-jar", "bin/felix.jar");
    pb.directory(felixHome);//from w ww .j a  v a2 s .  c o  m
    pb.redirectErrorStream(true);
    final Process p = pb.start();

    final Object lock = new Object();

    final Thread t = new Thread(new Runnable() {
        public void run() {
            // just a safeguard, if felix get stuck kill everything
            try {
                synchronized (lock) {
                    lock.wait(5 * 1000 * 60);
                }
            } catch (final InterruptedException e) {
                // ignore
            }
            p.destroy();
        }
    });
    t.setDaemon(true);
    t.start();

    synchronized (lock) {
        final InputStream input = p.getInputStream();
        final OutputStream output = p.getOutputStream();
        waitFor(input, "g!");

        output.write(("obr:repos add " + nexus().getUrl() + "content/" + obrLocation.toContentPath() + "\r\n")
                .getBytes());
        output.flush();
        waitFor(input, "g!");

        output.write(("obr:repos remove http://felix.apache.org/obr/releases.xml\r\n").getBytes());
        output.flush();
        waitFor(input, "g!");

        output.write(("obr:repos list\r\n").getBytes());
        output.flush();
        waitFor(input, "g!");

        output.write("obr:deploy -s org.apache.felix.webconsole\r\n".getBytes());
        output.flush();
        waitFor(input, "done.");

        p.destroy();

        lock.notifyAll();
    }
}

From source file:jp.co.tis.gsp.tools.dba.dialect.PostgresqlDialect.java

@Override
public void exportSchema(ExportParams params) throws MojoExecutionException {
    BufferedInputStream in = null;
    FileOutputStream out = null;//from   ww w.  ja  v a  2s .c  o  m
    try {
        File dumpFile = params.getDumpFile();
        String user = params.getUser();
        String password = params.getPassword();
        String schema = params.getSchema();

        ProcessBuilder pb = new ProcessBuilder("pg_dump", "--host=" + getHost(), "--port=" + getPort(),
                "--username=" + user, "--schema=" + schema, "-c", getDatabase());
        pb.redirectErrorStream(true);
        if (StringUtils.isNotEmpty(password)) {
            // ??????????
            pb.environment().put("PGPASSWORD", password);
        }

        Process process = pb.start();
        in = new BufferedInputStream(process.getInputStream());

        out = FileOutputStreamUtil.create(dumpFile);
        byte[] buf = new byte[4096];
        while (true) {
            int res = in.read(buf);
            if (res <= 0)
                break;
            out.write(buf, 0, res);
        }

    } catch (IOException e) {
        throw new MojoExecutionException("??", e);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:net.landora.video.mkv.MKVParser.java

public Video handleFile(File f) {

    try {//from ww w  .ja  va 2s.  co m
        ProcessBuilder process = new ProcessBuilder(
                ProgramsAddon.getInstance().getConfiguredPath(CommonPrograms.MKVINFO), f.getAbsolutePath());
        process.redirectErrorStream(true);
        Process p = process.start();

        StringWriter buffer = new StringWriter();
        IOUtils.copy(p.getInputStream(), buffer);
        p.waitFor();

        String reply = buffer.toString();
        buffer = null;

        if (reply.contains("No segment/level 0 element found.")) {
            return null;
        }

        Matcher mkvInfoMatcher = dataPattern.matcher(reply);

        file = new MKVFile();
        file.setFile(f);
        state = MKVParserState.Other;

        while (mkvInfoMatcher.find()) {
            depth = mkvInfoMatcher.group(1).length();
            field = mkvInfoMatcher.group(2);
            value = mkvInfoMatcher.group(3);

            switch (state) {
            case Segment_Header:
                handleSegmentHeader();
                break;
            case UnknownTrack:
                handleUnknownTrack();
                break;
            case VideoTrack:
                handleVideo();

                break;
            case AudioTrack:
                handleAudo();

                break;
            case SubtitleTrack:
                handleGeneralStreamFields();

                break;
            case Attachment:
                handleAttachment();
                break;

            case Chapter:
                handleChapter();
                break;

            case Other:
            default:
                handleStateless();
            }
        }
        return file;
    } catch (Exception e) {
        return null;
    }
}