Example usage for java.lang ProcessBuilder directory

List of usage examples for java.lang ProcessBuilder directory

Introduction

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

Prototype

File directory

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

Click Source Link

Usage

From source file:com.photon.phresco.framework.param.impl.IosDeviceTypeParameterImpl.java

private String cureentXcodeVersion() throws IOException {
    String version = "";
    ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", "xcodebuild -version");
    pb.redirectErrorStream(true);/*from   w  w  w .j  a v  a  2 s.  co m*/
    pb.directory(new File("/"));
    Process process = pb.start();
    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;
    while ((line = br.readLine()) != null) {
        String[] splited = line.split("\\s");
        version = splited[1];
        break;
    }
    return version;
}

From source file:com.serena.rlc.provider.filesystem.client.FilesystemClient.java

public void localExec(String execScript, String execDir, String execParams, boolean ignoreErrors)
        throws FilesystemClientException {
    Path script = Paths.get(execDir + File.separatorChar + execScript);

    try {//from   w  w  w  . j av  a 2  s. c o m
        if (!Files.exists(script)) {
            if (ignoreErrors) {
                logger.debug("Execution script " + script.toString() + " does not exist, ignoring...");
            } else {
                throw new FilesystemClientException(
                        "Execution script " + script.toString() + " does not exist");
            }
        } else {
            ProcessBuilder pb = new ProcessBuilder(script.toString());
            pb.directory(new File(script.getParent().toString()));
            System.out.println(pb.directory().toString());
            logger.debug("Executing script " + execScript + " in directory " + execDir + " with parameters: "
                    + execParams);
            Process p = pb.start(); // Start the process.
            p.waitFor(); // Wait for the process to finish.
            logger.debug("Executed script " + execScript + " successfully.");
        }
    } catch (Exception e) {
        logger.debug(e.getLocalizedMessage());
        throw new FilesystemClientException(e.getLocalizedMessage());
    }

}

From source file:org.ostara.cmd.BaseCmdLineCmd.java

protected void executeCommand(ICmdResult result, List<String> cmd, String cmdExecDir, boolean wait) {
    Process p = null;//from   w  w  w.ja v  a  2s . c o  m
    ProcessCall processCall = null;
    ProcessCallOutput output = null;

    List<String> cmdLine = new ArrayList<String>();

    // For windows system
    if (SystemUtils.IS_OS_WINDOWS) {
        cmdLine.add("cmd.exe");
        cmdLine.add("/C");
    }

    cmdLine.addAll(cmd);

    int retry = 0;
    Exception error = null;
    while (retry < 3) {
        try {

            ProcessBuilder processBuilder = new ProcessBuilder();
            processBuilder.redirectErrorStream(true);
            processBuilder.directory(new File(cmdExecDir));

            logger.info("Executing process: " + cmdLine);

            p = processBuilder.command(cmdLine).start();
            if (wait) {
                processCall = new ProcessCall(p);
                output = processCall.call();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            error = e;
            retry++;
            continue;
        }
        break;
    }

    if (output == null) {
        result.setException(error);
    } else if (output.exitValue != 0) {
        result.setException(new RuntimeException(
                "Failed to execute command(%" + getClass().getName() + "%), rtn value:" + output.exitValue));
    } else {
        result.setMessage(output.output);
    }
}

From source file:de.uni_potsdam.hpi.asg.common.io.Invoker.java

private ProcessReturn invoke(String[] cmd, List<String> params, File folder, int timeout) {
    List<String> command = new ArrayList<String>();
    command.addAll(Arrays.asList(cmd));
    command.addAll(params);/*from   www. ja  v a 2  s. c o  m*/
    ProcessReturn retVal = new ProcessReturn(Arrays.asList(cmd), params);
    Process process = null;
    try {
        logger.debug("Exec command: " + command.toString());
        //System.out.println(timeout + ": " + command.toString());
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(folder);
        builder.environment(); // bugfix setting env in test-mode (why this works? i dont know..)
        process = builder.start();

        Thread timeoutThread = null;
        if (timeout > 0) {
            timeoutThread = new Thread(new Timeout(Thread.currentThread(), timeout));
            timeoutThread.setName("Timout for " + command.toString());
            timeoutThread.start();
        }
        IOStreamReader ioreader = new IOStreamReader(process);
        Thread streamThread = new Thread(ioreader);
        streamThread.setName("StreamReader for " + command.toString());
        streamThread.start();
        process.waitFor();
        streamThread.join();
        if (timeoutThread != null) {
            timeoutThread.interrupt();
        }
        String out = ioreader.getResult();
        //System.out.println(out);
        if (out == null) {
            //System.out.println("out = null");
            retVal.setStatus(Status.noio);
        }
        retVal.setCode(process.exitValue());
        retVal.setStream(out);
        retVal.setStatus(Status.ok);
    } catch (InterruptedException e) {
        process.destroy();
        retVal.setTimeout(timeout);
        retVal.setStatus(Status.timeout);
    } catch (IOException e) {
        logger.error(e.getLocalizedMessage());
        retVal.setStatus(Status.ioexception);
    }
    return retVal;
}

From source file:nz.co.fortytwo.freeboard.installer.UploadProcessor.java

/**
 * Executes avrdude with relevant params
 * //from  w  w  w .  j  av a2  s .  com
 * @param config2
 * @param hexFile
 * @param argList
 * @param chartName
 * @param list
 * @throws IOException
 * @throws InterruptedException
 */
@SuppressWarnings("static-access")
private void executeAvrdude(File hexFile, List<String> argList) throws IOException, InterruptedException {

    ProcessBuilder pb = new ProcessBuilder(argList);
    pb.directory(hexFile.getParentFile());
    //pb.inheritIO();
    if (manager) {
        ForkWorker fork = new ForkWorker(textArea, pb);
        fork.execute();
        //fork.doInBackground();
        while (!fork.isDone()) {
            Thread.currentThread().sleep(500);
            // System.out.print(".");
        }
        if (fork.getResult() == 0) {
            System.out.print("Avrdude completed normally, and the code has been uploaded\n");
        } else {
            System.out
                    .print("ERROR: avrdude did not complete normally, and the device may not work correctly\n");
        }
    } else {
        Process p = pb.start();
        p.waitFor();
        if (p.exitValue() > 0) {
            if (manager) {
                System.out.print("ERROR: avrdude did not complete normally\n");
            }
            logger.error("avrdude did not complete normally");
            return;
        } else {
            System.out.print("Completed upload\n");
        }
    }

}

From source file:cz.muni.fi.pb138.cvmanager.service.PDFgenerator.java

/**
 * By external calling pdflatex function of laTex generates pdf curriculum vitae document from .tex file
 * @param username name of user whose is the CV
 * @return language to export (sk/en)/* ww w  . j  a va2 s  .co  m*/
 * @throws IOException
 * @throws InterruptedException
 * @throws NullPointerException
 */
public InputStream latexToPdf(String username) throws IOException, InterruptedException, NullPointerException {
    ProcessBuilder pb = new ProcessBuilder("pdflatex", username + "_cv.tex", "--output-directory=");
    File file = new File("cvxml/");
    pb.directory(file);
    Process p = pb.start();

    WatchService watcher = FileSystems.getDefault().newWatchService();
    Path dir = Paths.get("cvxml/");
    dir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY);

    while (true) {
        // wait for a key to be available for 10 seconds
        WatchKey key = watcher.poll(10000L, TimeUnit.MILLISECONDS);
        if (key == null) {
            break;
        }

        for (WatchEvent<?> event : key.pollEvents()) {
            // get event type
            WatchEvent.Kind<?> kind = event.kind();

            // get file name
            @SuppressWarnings("unchecked")
            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path fileName = ev.context();

            System.out.println(kind.name() + ": " + fileName);
        }

        boolean valid = key.reset();
        if (!valid) {
            break;
        }
    }

    System.out.println("end of cycle");

    File pdf = new File("cvxml/" + username + "_cv.pdf");

    return new FileInputStream(pdf);
}

From source file:com.jstar.eclipse.services.JStar.java

public Process executeJStar(final IFolder workingDirectory, final IFolder folder, final String spec,
        final String logic, final String abs, final String jimpleFile, final PrintMode printMode,
        final String debugMode) throws IOException {

    final List<String> command = new ArrayList<String>();
    command.add(PreferenceConstants.getJStarExecutable());
    command.add("-e");
    command.add(printMode.getCmdOption());
    command.add("-l");
    command.add(logic);//from   w  ww . j  av a 2  s  .c  o m
    command.add("-a");
    command.add(abs);
    command.add("-s");
    command.add(spec);
    command.add("-f");
    command.add(jimpleFile);

    if (StringUtils.isNotBlank(debugMode)) {
        command.add("-d");
        command.add(debugMode);
    }

    ProcessBuilder pb = new ProcessBuilder(command);
    pb.directory(new File(workingDirectory.getLocation().toOSString()));

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

    //TODO: jStar accepts only ':' as path separator
    env.put(PreferenceConstants.JSTAR_LOGIC_LIBRARY,
            PreferenceConstants.getJStarLogicLibrary() + ':' + folder.getLocation().toOSString());

    env.put(PreferenceConstants.JSTAR_ABS_LIBRARY,
            PreferenceConstants.getJStarAbsLibrary() + ':' + folder.getLocation().toOSString());

    env.put(PreferenceConstants.JSTAR_SPECS_LIBRARY,
            PreferenceConstants.getJStarSpecLibrary() + ':' + folder.getLocation().toOSString());

    env.put(PreferenceConstants.JSTAR_SMT_PATH, PreferenceConstants.getSmtPath());
    env.put(PreferenceConstants.JSTAR_SMT_ARGUMENTS, PreferenceConstants.getSmtAtguments());

    env.put(TERM, XTERMCOLOR);

    return pb.start();
}

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);
    builder.redirectErrorStream(true);//from  www  . j  ava2  s  . co m
    return builder.start();
}

From source file:de.tarent.maven.plugins.pkg.Utils.java

/**
 * A method which makes executing programs easier.
 * /* www  .java  2s . c  om*/
 * @param args
 * @param failureMsg
 * @param ioExceptionMsg
 * @throws MojoExecutionException
 */
public static InputStream exec(String[] args, File workingDir, String failureMsg, String ioExceptionMsg,
        String userInput) throws MojoExecutionException {
    /*
     * debug code which prints out the execution command-line. Enable if
     * neccessary. for(int i=0;i<args.length;i++) { System.err.print(args[i]
     * + " "); } System.err.println();
     */

    // Creates process with the defined language setting of LC_ALL=C
    // That way the textual output of certain commands is predictable.
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(workingDir);
    Map<String, String> env = pb.environment();
    env.put("LC_ALL", "C");

    Process p = null;

    try {

        p = pb.start();

        if (userInput != null) {
            PrintWriter writer = new PrintWriter(
                    new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
            writer.println(userInput);
            writer.flush();
            writer.close();
        }
        int exitValue = p.waitFor();
        if (exitValue != 0) {
            print(p);
            throw new MojoExecutionException(
                    String.format("(Subprocess exit value = %s) %s", exitValue, failureMsg));
        }
    } catch (IOException ioe) {
        throw new MojoExecutionException(ioExceptionMsg + " :" + ioe.getMessage(), ioe);
    } catch (InterruptedException ie) {
        // Cannot happen.
        throw new MojoExecutionException("InterruptedException", ie);
    }
    return p.getInputStream();
}

From source file:de.zib.gndms.logic.model.gorfx.c3grid.ExternalProviderStageInORQCalculator.java

private ProcessBuilderAction createEstAction(final File estCommandFileParam,
        final TransientContract contParam) {
    final @NotNull ProcessBuilder pb = new ProcessBuilder();
    try {//from ww  w . j  a  v a  2s  .  c o  m
        pb.command(estCommandFileParam.getCanonicalPath());
        pb.directory(new File(getSysInfo().getSystemTempDirName()));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }

    ProcessBuilderAction action;
    // todo add permissions here when delegation is implemented
    action = parmAux.createPBAction(getORQArguments(), contParam, null);
    action.setProcessBuilder(pb);
    action.setOutputReceiver(new StringBuilder(INITIAL_STRING_BUILDER_CAPACITY));
    action.setErrorReceiver(new StringBuilder(INITIAL_STRING_BUILDER_CAPACITY));
    return action;
}