Example usage for java.lang ProcessBuilder command

List of usage examples for java.lang ProcessBuilder command

Introduction

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

Prototype

List command

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

Click Source Link

Usage

From source file:com.smash.revolance.ui.materials.CmdlineHelper.java

public CmdlineHelper exec() throws InterruptedException, IOException {
    ProcessBuilder pb = new ProcessBuilder();

    if (dir != null) {
        pb.directory(dir);//  w  w w .  j  av a 2s  .  co m
    }

    pb.command(cmd);

    pb.redirectError(ProcessBuilder.Redirect.to(err));
    pb.redirectOutput(ProcessBuilder.Redirect.to(out));
    pb.redirectInput(ProcessBuilder.Redirect.from(in));

    System.out.println("Executing cmd: " + cmd[0] + " from dir: " + dir);
    System.out.println("Redirecting out to: " + out.getAbsolutePath());
    System.out.println("Redirecting err to: " + err.getAbsolutePath());

    Process process = pb.start();
    if (sync) {
        process.waitFor();
    }

    this.process = process;

    return this;
}

From source file:com.photon.phresco.plugins.xcode.CodeValidation.java

public void execute() throws MojoExecutionException {

    try {//from  w ww  .ja va2 s . c o m
        ProcessBuilder pb = new ProcessBuilder(check);
        // Include errors in output
        pb.redirectErrorStream(true);

        List<String> commands = pb.command();

        commands.add("-o");
        commands.add("make");
        commands.add("xcodebuild");
        commands.add("-scheme");
        commands.add(scheme);
        commands.add("-project");
        commands.add(xcodeProject);
        commands.add("build");
        getLog().info("List of commands" + pb.command());
        // pb.command().add("install");
        pb.directory(new File(basedir));
        Process child = pb.start();

        // Consume subprocess output and write to stdout for debugging
        InputStream is = new BufferedInputStream(child.getInputStream());
        int singleByte = 0;
        while ((singleByte = is.read()) != -1) {
            // output.write(buffer, 0, bytesRead);
            System.out.write(singleByte);
        }

        child.waitFor();
        int exitValue = child.exitValue();
        getLog().info("Exit Value: " + exitValue);
        if (exitValue != 0) {
            throw new MojoExecutionException("Compilation error occured. Resolve the error(s) and try again!");
        }

    } catch (IOException e) {
        getLog().error("An IOException occured.");
        throw new MojoExecutionException("An IOException occured", e);
    } catch (InterruptedException e) {
        getLog().error("The clean process was been interrupted.");
        throw new MojoExecutionException("The clean process was been interrupted", e);
    }
    createreport();
}

From source file:org.atemsource.dojo.build.DojoBuildMojo.java

private void execute(List<String> params) throws IOException, MojoExecutionException, InterruptedException {
    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.directory(workDir);//from   www.j a  va2 s  .c  o m
    processBuilder.command(params);
    Process process = processBuilder.start();
    InputStream in = process.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    InputStream ein = process.getErrorStream();
    BufferedReader ereader = new BufferedReader(new InputStreamReader(ein));
    boolean finished = false;
    do {
        if (reader.ready()) {
            String line = reader.readLine();
            if (line != null) {
                System.out.println(line);
            }

        } else if (ereader.ready()) {
            String line = ereader.readLine();
            if (line != null) {
                System.err.println(line);
            }

        } else {
            try {
                int exit = process.exitValue();
                if (exit != 0) {
                    throw new MojoExecutionException("dojo build ended with exit code " + exit);
                } else {
                    finished = true;
                }
            } catch (IllegalThreadStateException e) {

            }
            Thread.sleep(100);
        }
    } while (!finished);
}

From source file:net.sourceforge.subsonic.io.TranscodeInputStream.java

/**
 * Creates a transcoded input stream by executing an external process. If <code>in</code> is not null,
 * data from it is copied to the command.
 *
 * @param processBuilder Used to create the external process.
 * @param in Data to feed to the process.  May be {@code null}.
 * @param tmpFile Temporary file to delete when this stream is closed.  May be {@code null}.
 * @throws IOException If an I/O error occurs.
 *///from   www.j  a v a  2 s.  c  o  m
public TranscodeInputStream(ProcessBuilder processBuilder, final InputStream in, File tmpFile)
        throws IOException {
    this.tmpFile = tmpFile;

    StringBuffer buf = new StringBuffer("Starting transcoder: ");
    for (String s : processBuilder.command()) {
        buf.append('[').append(s).append("] ");
    }
    LOG.debug(buf);

    process = processBuilder.start();
    processOutputStream = process.getOutputStream();
    processInputStream = process.getInputStream();

    // Must read stderr from the process, otherwise it may block.
    final String name = processBuilder.command().get(0);
    new InputStreamReaderThread(process.getErrorStream(), name, true).start();

    // Copy data in a separate thread
    if (in != null) {
        new Thread(name + " TranscodedInputStream copy thread") {
            public void run() {
                try {
                    IOUtils.copy(in, processOutputStream);
                } catch (IOException x) {
                    // Intentionally ignored. Will happen if the remote player closes the stream.
                } finally {
                    IOUtils.closeQuietly(in);
                    IOUtils.closeQuietly(processOutputStream);
                }
            }
        }.start();
    }
}

From source file:org.madsonic.io.TranscodeInputStream.java

/**
 * Creates a transcoded input stream by executing an external process. If <code>in</code> is not null,
 * data from it is copied to the command.
 *
 * @param processBuilder Used to create the external process.
 * @param in Data to feed to the process.  May be {@code null}.
 * @param tmpFile Temporary file to delete when this stream is closed.  May be {@code null}.
 * @throws IOException If an I/O error occurs.
 *//*from www  .  j  av a 2s  .  co  m*/
public TranscodeInputStream(ProcessBuilder processBuilder, final InputStream in, File tmpFile)
        throws IOException {
    this.tmpFile = tmpFile;

    StringBuilder buf = new StringBuilder("Starting transcoder: ");
    for (String s : processBuilder.command()) {
        buf.append('[').append(s).append("] ");
    }
    LOG.debug(buf);

    process = processBuilder.start();
    processOutputStream = process.getOutputStream();
    processInputStream = process.getInputStream();

    // Must read stderr from the process, otherwise it may block.
    final String name = processBuilder.command().get(0);
    new InputStreamReaderThread(process.getErrorStream(), name, true).start();

    // Copy data in a separate thread
    if (in != null) {
        new Thread(name + " TranscodedInputStream copy thread") {
            public void run() {
                try {
                    IOUtils.copy(in, processOutputStream);
                } catch (IOException x) {
                    // Intentionally ignored. Will happen if the remote player closes the stream.
                } finally {
                    IOUtils.closeQuietly(in);
                    IOUtils.closeQuietly(processOutputStream);
                }
            }
        }.start();
    }
}

From source file:org.ecocean.ImageProcessor.java

public void run() {
    //        status = Status.INIT;

    if (StringUtils.isBlank(this.command)) {
        log.warn("Can't run processor due to empty command");
        return;//w  w w  . j av  a2 s .  c  om
    }

    if (StringUtils.isBlank(this.imageSourcePath)) {
        log.warn("Can't run processor due to empty source path");
        return;
    }

    if (StringUtils.isBlank(this.imageTargetPath)) {
        log.warn("Can't run processor due to empty target path");
        return;
    }

    String comment = CommonConfiguration.getProperty("imageComment", this.context);
    if (comment == null)
        comment = "%year All rights reserved. | wildbook.org";
    String cname = ContextConfiguration.getNameForContext(this.context);
    if (cname != null)
        comment += " | " + cname;
    String maId = "unknown";
    String rotation = "";
    if (this.parentMA != null) {
        if (this.parentMA.getUUID() != null) {
            maId = this.parentMA.getUUID();
            comment += " | parent " + maId;
        } else {
            maId = this.parentMA.setHashCode();
            comment += " | parent hash " + maId; //a stretch, but maybe should never happen?
        }
        if (this.parentMA.hasLabel("rotate90")) {
            rotation = "-flip -transpose";
        } else if (this.parentMA.hasLabel("rotate180")) {
            rotation = "-flip -flop";
        } else if (this.parentMA.hasLabel("rotate270")) {
            rotation = "-flip -transverse";
        }
    }
    comment += " | v" + Long.toString(System.currentTimeMillis());
    try {
        InetAddress ip = InetAddress.getLocalHost();
        comment += ":" + ip.toString() + ":" + ip.getHostName();
    } catch (UnknownHostException e) {
    }

    int year = Calendar.getInstance().get(Calendar.YEAR);
    comment = comment.replaceAll("%year", Integer.toString(year));
    //TODO should we handle ' better? -- this also assumes command uses '%comment' quoting  :/
    comment = comment.replaceAll("'", "");

    String fullCommand;
    fullCommand = this.command.replaceAll("%width", Integer.toString(this.width))
            .replaceAll("%height", Integer.toString(this.height))
            //.replaceAll("%imagesource", this.imageSourcePath)
            //.replaceAll("%imagetarget", this.imageTargetPath)
            .replaceAll("%maId", maId).replaceAll("%additional", rotation).replaceAll("%arg", this.arg);

    //walk thru transform array and replace "tN" with transform[N]
    if (this.transform.length > 0) {
        for (int i = 0; i < this.transform.length; i++) {
            fullCommand = fullCommand.replaceAll("%t" + Integer.toString(i), Float.toString(this.transform[i]));
        }
    }

    String[] command = fullCommand.split("\\s+");

    //we have to do this *after* the split-on-space cuz files may have spaces!
    for (int i = 0; i < command.length; i++) {
        if (command[i].equals("%imagesource"))
            command[i] = this.imageSourcePath;
        if (command[i].equals("%imagetarget"))
            command[i] = this.imageTargetPath;
        //note this assumes comment stands alone. :/
        if (command[i].equals("%comment"))
            command[i] = comment;
        System.out.println("COMMAND[" + i + "] = (" + command[i] + ")");
    }
    //System.out.println("done run()");
    //System.out.println("command = " + Arrays.asList(command).toString());

    ProcessBuilder pb = new ProcessBuilder();
    pb.command(command);
    /*
            Map<String, String> env = pb.environment();
            env.put("LD_LIBRARY_PATH", "/home/jon/opencv2.4.7");
    */
    //System.out.println("before!");

    try {
        Process proc = pb.start();
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
        String line;
        while ((line = stdInput.readLine()) != null) {
            System.out.println(">>>> " + line);
        }
        while ((line = stdError.readLine()) != null) {
            System.out.println("!!!! " + line);
        }
        proc.waitFor();
        System.out.println("DONE?????");
        ////int returnCode = p.exitValue();
    } catch (Exception ioe) {
        log.error("Trouble running processor [" + command + "]", ioe);
    }
    System.out.println("RETURN");
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

private void applyPatch(Repository envStoreRepo, String site) {
    String tempPath = System.getProperty("java.io.tmpdir");
    if (tempPath == null) {
        tempPath = "temp";
    }//from   w  w  w. j  a  va  2 s .c  o  m
    Path patchPath = Paths.get(tempPath, "patch" + site + ".bin");
    Process p;
    try {
        ProcessBuilder pb = new ProcessBuilder();
        pb.command("git", "apply", patchPath.toAbsolutePath().normalize().toString());
        pb.directory(envStoreRepo.getDirectory().getParentFile());
        p = pb.start();
        p.waitFor();
    } catch (Exception e) {
        logger.error("Error applying patch for site: " + site, e);
    }
}

From source file:org.pepstock.jem.junit.init.submitters.AbstractSubmitter.java

/**
 * /* ww  w .  ja v  a 2 s  .  co m*/
 * @param command
 * @param args
 * @return
 * @throws NodeMessageException
 * @throws IOException
 * @throws InterruptedException
 */
int launch(String command, String[] args) throws NodeMessageException, IOException, InterruptedException {
    String osCommand = null;
    if (SystemUtils.IS_OS_WINDOWS) {
        osCommand = command + ".cmd";
    } else {
        osCommand = command + ".sh";
    }

    Process process = null;
    try {
        File logFile = File.createTempFile("junit", "log");

        String redirect = "> " + FilenameUtils.normalize(logFile.getAbsolutePath(), true) + " 2>&1";
        StringBuilder sb = new StringBuilder(osCommand);
        for (String arg : args) {
            sb.append(" ").append(arg);
        }

        System.err.println(sb.toString());

        sb.append(" ").append(redirect);

        // create a process builder
        ProcessBuilder builder = new ProcessBuilder();
        Shell shell = CurrentPlatform.getInstance().getShell();

        builder.command(shell.getName(), shell.getParameters(), sb.toString());

        // set directory where execute process
        builder.directory(new File(System.getenv("JEM_HOME") + "/bin"));

        // load variable environment from a temporary maps that you can use
        // inside of configure method.
        Map<String, String> env = System.getenv();
        Map<String, String> map = builder.environment();
        for (Map.Entry<String, String> e : env.entrySet()) {
            map.put(e.getKey(), e.getValue());
        }

        // start process and save instance
        process = builder.start();
        // wait for end of job execution
        int rc = process.waitFor();

        FileInputStream fis = new FileInputStream(logFile);
        IOUtils.copy(fis, System.out);
        IOUtils.closeQuietly(fis);
        logFile.delete();
        return rc;

    } finally {
        if (process != null) {
            process.destroy();
        }
    }
}

From source file:org.jajuk.services.players.WebRadioPlayerImpl.java

/**
 * (non-Javadoc)./*from  ww w .j  ava2  s.  com*/
 * 
 * @param radio 
 * @param fVolume 
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws JajukException the jajuk exception
 * 
 * @see org.jajuk.players.IPlayerImpl#play(org.jajuk.base.File, float, long,
 * float)
 */
@Override
public void play(WebRadio radio, float fVolume) throws IOException, JajukException {
    this.fVolume = fVolume;
    this.bOpening = true;
    this.bEOF = false;
    this.bitPerfect = Conf.getBoolean(Const.CONF_BIT_PERFECT);
    // Start
    ProcessBuilder pb = new ProcessBuilder(buildCommand(radio.getUrl(), 0));
    Log.debug("Using this Mplayer command: {{" + pb.command() + "}}");
    // Set all environment variables format: var1=xxx var2=yyy
    try {
        Map<String, String> env = pb.environment();
        StringTokenizer st = new StringTokenizer(Conf.getString(Const.CONF_ENV_VARIABLES), " ");
        while (st.hasMoreTokens()) {
            StringTokenizer st2 = new StringTokenizer(st.nextToken(), "=");
            env.put(st2.nextToken(), st2.nextToken());
        }
        // If needed, set proxy settings in format:
        // http_proxy=http://username:password@proxy.example.org:8080
        if (Conf.getBoolean(Const.CONF_NETWORK_USE_PROXY)) {
            String sLogin = Conf.getString(Const.CONF_NETWORK_PROXY_LOGIN).trim();
            String sHost = Conf.getString(Const.CONF_NETWORK_PROXY_HOSTNAME).trim();
            int port = Conf.getInt(Const.CONF_NETWORK_PROXY_PORT);
            // Non anonymous proxy
            if (!StringUtils.isBlank(sLogin)) {
                String sPwd = UtilString.rot13(Conf.getString(Const.CONF_NETWORK_PROXY_PWD));
                String sProxyConf = "http://" + sLogin + ':' + sPwd + '@' + sHost + ':' + port;
                env.put("http_proxy", sProxyConf);
                Log.debug("Using these proxy settings: " + sProxyConf);
            }
            // Anonymous proxy
            else {
                String sProxyConf = "http://" + sHost + ':' + port;
                env.put("http_proxy", sProxyConf);
                Log.debug("Using these proxy settings: " + sProxyConf);
            }
        }
    } catch (Exception e) {
        Log.error(e);
    }
    // Start mplayer
    proc = pb.start();
    // start mplayer replies reader thread
    new ReaderThread().start();
    // if opening, wait, 30 secs max
    int i = 0;
    while (bOpening && i < 30) {
        try {
            Thread.sleep(1000);
            i++;
        } catch (InterruptedException e) {
            Log.error(e);
        }
    }
    // If end of file already reached, it means that file cannot be read
    if (bEOF) {
        throw new JajukException(7);
    }
    // Get track length
    sendCommand("get_time_length");
}

From source file:org.sonar.application.process.ProcessLauncherImpl.java

private ProcessBuilder create(AbstractCommand<?> javaCommand, List<String> commands) {
    ProcessBuilder processBuilder = processBuilderSupplier.get();
    processBuilder.command(commands);
    processBuilder.directory(javaCommand.getWorkDir());
    Map<String, String> environment = processBuilder.environment();
    environment.putAll(javaCommand.getEnvVariables());
    javaCommand.getSuppressedEnvVariables().forEach(environment::remove);
    processBuilder.redirectErrorStream(true);
    return processBuilder;
}