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:org.jvnet.hudson.update_center.Main.java

/**
 * Generates symlink to the latest version.
 *//*from w ww. j a v a 2s.com*/
protected void createLatestSymlink(PluginHistory hpi, HPI latest) throws InterruptedException, IOException {
    File dir = new File(download, "plugins/" + hpi.artifactId);
    new File(dir, "latest").delete();

    ProcessBuilder pb = new ProcessBuilder();
    pb.command("ln", "-s", latest.version, "latest");
    pb.directory(dir);
    int r = pb.start().waitFor();
    if (r != 0)
        throw new IOException("ln failed: " + r);
}

From source file:org.taverna.server.master.localworker.ForkRunFactory.java

/**
 * Makes the subprocess that manufactures runs.
 * /*from  w w  w  .j a  va 2 s.c  o m*/
 * @throws Exception
 *             If anything goes wrong.
 */
public void initFactory() throws Exception {
    if (factory != null)
        return;
    // Generate the arguments to use when spawning the subprocess
    factoryProcessName = state.getFactoryProcessNamePrefix() + randomUUID();
    ProcessBuilder p = new ProcessBuilder(getJavaBinary());
    p.command().addAll(asList(getExtraArguments()));
    p.command().add("-jar");
    p.command().add(getServerWorkerJar());
    p.command().add(getExecuteWorkflowScript());
    p.command().add(factoryProcessName);
    p.redirectErrorStream(true);
    p.directory(new File(getProperty("javax.servlet.context.tempdir", getProperty("java.io.tmpdir"))));

    // Spawn the subprocess
    log.info("about to create subprocess: " + p.command());
    factoryProcess = p.start();
    Thread logger = new Thread(new OutputLogger(factoryProcessName, factoryProcess),
            factoryProcessName + ".Logger");
    logger.setDaemon(true);
    logger.start();

    // Wait for the subprocess to register itself in the RMI registry
    Calendar deadline = Calendar.getInstance();
    deadline.add(SECOND, state.getWaitSeconds());
    Exception lastException = null;
    lastStartupCheckCount = 0;
    while (deadline.after(Calendar.getInstance())) {
        try {
            sleep(state.getSleepMS());
            lastStartupCheckCount++;
            log.info("about to look up resource called " + factoryProcessName);
            try {
                // Validate registry connection first
                getTheRegistry().list();
            } catch (ConnectException ce) {
                log.warn("connection problems with registry", ce);
            } catch (ConnectIOException e) {
                log.warn("connection problems with registry", e);
            }
            factory = (RemoteRunFactory) getTheRegistry().lookup(factoryProcessName);
            log.info("successfully connected to factory subprocess " + factoryProcessName);
            if (interhost != null)
                factory.setInteractionServiceDetails(interhost, interport, interwebdav, interfeed);
            return;
        } catch (InterruptedException ie) {
            continue;
        } catch (NotBoundException nbe) {
            lastException = nbe;
            log.info("resource \"" + factoryProcessName + "\" not yet registered...");
            continue;
        } catch (RemoteException re) {
            // Unpack a remote exception if we can
            lastException = re;
            try {
                if (re.getCause() != null)
                    lastException = (Exception) re.getCause();
            } catch (Throwable t) {
                // Ignore!
            }
        } catch (Exception e) {
            lastException = e;
        }
    }
    throw lastException;
}

From source file:org.jvnet.hudson.update_center.Main.java

/**
 * Stages an artifact into the specified location.
 *//*w ww  . j  ava2  s.  co m*/
protected void stage(MavenArtifact a, File dst) throws IOException, InterruptedException {
    File src = a.resolve();
    if (dst.exists() && dst.lastModified() == src.lastModified() && dst.length() == src.length())
        return; // already up to date

    //        dst.getParentFile().mkdirs();
    //        FileUtils.copyFile(src,dst);

    // TODO: directory and the war file should have the release timestamp
    dst.getParentFile().mkdirs();

    ProcessBuilder pb = new ProcessBuilder();
    pb.command("ln", "-f", src.getAbsolutePath(), dst.getAbsolutePath());
    if (pb.start().waitFor() != 0)
        throw new IOException("ln failed");

}

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

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    getLog().info("Instrumentation command" + command);

    try {/*from  www. j  a  v a  2s .  com*/
        outputFolder = project.getBasedir().getAbsolutePath();
        File f = new File(outputFolder);
        File files[] = f.listFiles();
        for (File file : files) {
            if (file.getName().startsWith("Run 1") || file.getName().endsWith(".trace")) {
                FileUtils.deleteDirectory(file);
            }
        }
    } catch (IOException e) {
        getLog().error(e);
    }

    Runnable runnable = new Runnable() {
        public void run() {
            ProcessBuilder pb = new ProcessBuilder(command);
            //device takes the highest priority
            if (StringUtils.isNotBlank(deviceid)) {
                pb.command().add("-w");
                pb.command().add(deviceid);
            }
            pb.command().add("-t");
            pb.command().add(template);

            if (StringUtils.isNotBlank(appPath)) {
                pb.command().add(appPath);
            } else {
                getLog().error("Application should not be empty");
            }
            if (StringUtils.isNotBlank(script)) {
                pb.command().add("-e");
                pb.command().add("UIASCRIPT");
                String scriptPath = project.getBasedir().getAbsolutePath() + File.separator + script;
                pb.command().add(scriptPath);
            } else {
                getLog().error("script is empty");
            }

            pb.command().add("-e");
            pb.command().add("UIARESULTSPATH");
            pb.command().add(outputFolder);

            // Include errors in output
            pb.redirectErrorStream(true);

            getLog().info("List of commands" + pb.command());
            Process child;
            try {
                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) {
                    System.out.write(singleByte);
                }
            } catch (IOException e) {
                getLog().error(e);
            }

        }

    };

    Thread t = new Thread(runnable, "iPhoneSimulator");
    t.start();
    getLog().info("Thread started");
    try {
        //Thread.sleep(5000);
        t.join();
        t.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    preparePlistResult();
    generateXMLReport(project.getBasedir().getAbsolutePath() + File.separator + plistResult);
}

From source file:com.appcel.core.encoder.executor.FfmpegEncoderExecutor.java

public void execute(MediaRecord record, File directory) throws EncoderException {

    LOGGER.info(" ffmpeg ?  video ...  Ffmpeg  ===>>> " + args);

    final ProcessBuilder pb = new ProcessBuilder().directory(directory);
    pb.redirectErrorStream(true);/*from   ww w  . j  a  v a  2s  .c o  m*/
    if (null != directory) {
        LOGGER.info("ffmpeg ??==========>>>" + directory.toString());
    }

    pb.command(args);

    try {
        final Process process = pb.start();
        inputStream = process.getInputStream();

        MediaInputStreamParser.parseMediaRecord(inputStream, record);

        outputStream = process.getOutputStream();
        errorStream = process.getErrorStream();
        // ???????.
        //         BufferedInputStream in = new BufferedInputStream(inputStream);
        //         BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
        //         String lineStr;
        //         while ((lineStr = inBr.readLine()) != null)
        //            LOGGER.info("process.getInputStream() ===>>> " + lineStr);

        int waitfor = process.waitFor();
        if (waitfor != 0) {
            //p.exitValue()==0?1??
            if (process.exitValue() == 1) {
                LOGGER.info("===>>> ffmpeg ? Failed!");
                throw new EncoderException("ffmpeg ? Failed!");
            } else {
                LOGGER.info("==========>>> ffmpeg ??.");
            }
        } else {
            LOGGER.info("==========>>> ffmpeg ??.");
        }

    } catch (IOException e) {
        LOGGER.error("==========>>> ffmpeg ? Message: " + e.getMessage());
        LOGGER.error("==========>>> ffmpeg ? Cause: " + e.getCause());
        e.printStackTrace();
    } catch (InterruptedException e) {
        LOGGER.error("==========>>> ffmpeg ? Message: " + e.getMessage());
        LOGGER.error("==========>>> ffmpeg ? Cause: " + e.getCause());
        e.printStackTrace();
        Thread.currentThread().interrupt();
    } finally {
        destroy();
    }
}

From source file:com.att.aro.datacollector.ioscollector.utilities.AppSigningHelper.java

public void executeCmd(String cmd) {
    System.out.println(cmd);//from   w w  w  . j a  v a  2s .  c  o  m
    ProcessBuilder pbldr = new ProcessBuilder();
    if (!Util.isWindowsOS()) {
        pbldr.command(new String[] { "bash", "-c", cmd });
    } else {
        pbldr.command(new String[] { "CMD", "/C", cmd });
    }
    try {
        Process proc = pbldr.start();
        try {
            Thread.sleep(1000 * 2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        proc.destroy();
    } catch (IOException e) {
        //Do nothing
    }
}

From source file:org.pepstock.jem.node.tasks.JobTask.java

/**
 * Internal method which creates the process, preparing environment
 * variables, creating directories, setting listener of output and error
 * log, and wait for end of job execution.
 * /*from  ww w  .j  a  v a2  s . co  m*/
 * @return return code of execution
 * @throws NodeMessageException 
 * @throws InterruptedException 
 * @throws Exception occurs if there is any error
 */

private int launchProcess() throws IOException, NodeMessageException, InterruptedException {
    int returnCode = 0;
    Process process = null;
    try {
        String user = job.isUserSurrogated() ? job.getJcl().getUser() : job.getUser();
        AbstractFactory currFactory = (AbstractFactory) getFactory();
        boolean useSudo = currFactory.isUseSudo() && !user.equalsIgnoreCase(Main.getNode().getUser());

        // create a process builder
        ProcessBuilder builder = new ProcessBuilder();
        Shell shell = CurrentPlatform.getInstance().getShell();
        String command = CurrentPlatform.getInstance().getCommand(job, getCommand(), useSudo);
        builder.command(shell.getName(), shell.getParameters(), command);

        // set directory where execute process
        if (getStartDir() != null) {
            builder.directory(new File(getStartDir()));
        }

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

        // writes JEM log with headers
        JobLogManager.printHeader(job);

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

        // check if cancelled, setting the return code 222
        if (isCancelled) {
            returnCode = Result.CANCELED;
        }
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
    return returnCode;
}

From source file:com.rogue.simpleclient.SimpleClient.java

/**
 * Opens the minecraft client.//ww  w.jav a2  s .co m
 *
 * @since 1.0.0
 * @version 1.0.0
 *
 * @throws SecurityException Lack of permissions to execute a process
 * @throws IOException Unobserved I/O Error
 */
public void openMinecraft() throws SecurityException, IOException {
    MCProc mc = new MCProc(this.natives, this.minecraftDir, this.gameDir, this.version);
    JSONObject prof = (JSONObject) this.response.get("selectedProfile");
    mc.appendTag("username", (String) prof.get("name"), "=");
    mc.appendTag("version", this.version, " ");
    mc.appendTag("gameDir", this.minecraftDir.getAbsolutePath(), " ");
    mc.appendTag("assetsDir", new File(this.minecraftDir, "assets").getAbsolutePath(), " ");
    mc.appendTag("userProperties", "{}", " ");
    mc.appendTag("accessToken", (String) this.response.get("accessToken"), " ");
    mc.appendTag("uuid", (String) prof.get("id"), " ");
    try {
        ProcessBuilder pb = new ProcessBuilder();
        pb.redirectErrorStream(true);
        pb.command(mc.getExec());
        Process p = Runtime.getRuntime().exec(mc.getExec());
        p.waitFor();
        try (BufferedReader bf = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            String line;
            while ((line = bf.readLine()) != null) {
                System.out.println(line);
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.RSTAnnotator.java

/**
 * Runs the parser on the given text/* w  w w . ja  v  a  2 s  . c o m*/
 *
 * @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:org.ow2.proactive.scheduler.ext.matlab.worker.MatlabConnectionRImpl.java

protected Process createMatlabProcess(String runArg) throws Exception {
    // Attempt to run MATLAB
    final ArrayList<String> commandList = new ArrayList<String>();
    commandList.add(this.matlabLocation);
    commandList.addAll(Arrays.asList(this.startUpOptions));
    commandList.add("-logfile");
    commandList.add(this.taskOutputFile.toString());
    commandList.add("-r");
    commandList.add(runArg);// w w w.j  ava 2 s . c  o m

    String[] command = (String[]) commandList.toArray(new String[commandList.size()]);

    ProcessBuilder b = new ProcessBuilder();
    // invalid on windows, it affects the starter only
    b.directory(this.workingDirectory);
    b.command(command);

    // Fix for SCHEDULING-1309: If MATLAB client uses RunAsMe option the MATLAB
    // worker jvm can crash if the client user has never started any MATLAB
    // session on the worker host

    // Since the user profile can be missing on Windows with RunAsMe, by setting
    // the MATLAB_PREFDIR variable to a writable dir (can be non-writable on Windows with RunAsMe)
    // the MATLAB doesn't crash no more

    Map<String, String> env = b.environment();

    // Transmit the prefdir as env variable
    String matlabPrefdir = System.getProperty(MATLAB_PREFDIR);
    if (matlabPrefdir != null) {
        env.put("MATLAB_PREFDIR", matlabPrefdir);
    }
    // Transmit the tmpdir as env variable
    String matlabTmpvar = System.getProperty(MATLAB_TASK_TMPDIR);
    if (matlabTmpvar != null) {
        env.put("TEMP", matlabTmpvar);
        env.put("TMP", matlabTmpvar);
    }

    return b.start();
}