Example usage for java.lang ProcessBuilder start

List of usage examples for java.lang ProcessBuilder start

Introduction

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

Prototype

public Process start() throws IOException 

Source Link

Document

Starts a new process using the attributes of this process builder.

Usage

From source file:abs.backend.erlang.ErlangTestDriver.java

/**
* Executes mainModule//from   w  w  w  .  j  a  va  2 s  . co  m
* 
* We replace the run script by a new version, which will write the Result
* to STDOUT Furthermore to detect faults, we have a Timeout process, which
* will kill the runtime system after 2 seconds
*/
private String run(File workDir, String mainModule) throws Exception {
    String val = null;
    File runFile = new File(workDir, "run");
    Files.write(RUN_SCRIPT, runFile, Charset.forName("UTF-8"));
    runFile.setExecutable(true);
    ProcessBuilder pb = new ProcessBuilder(runFile.getAbsolutePath(), mainModule);
    pb.directory(workDir);
    pb.redirectErrorStream(true);
    Process p = pb.start();

    Thread t = new Thread(new TimeoutThread(p));
    t.start();
    // Search for result
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    while (true) {
        String line = br.readLine();
        if (line == null)
            break;
        if (line.startsWith("RES="))
            val = line.split("=")[1];
    }
    int res = p.waitFor();
    t.interrupt();
    if (res != 0)
        return null;
    return val;

}

From source file:com.all.launcher.Launcher.java

private void createApplicationProcess() {
    try {//from w ww.  ja  v a2s .c  o m
        String applicationComand = launcherConfig.applicationComand();

        log.info("Running client with command: " + applicationComand);

        ProcessBuilder processBuilder = new ProcessBuilder(applicationComand);

        setDirectoryIfMac(processBuilder);
        processBuilder.start();
    } catch (Exception err) {
        log.error(err, err);
    }
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        log.error(e, e);
    }
}

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  w w  w. ja va  2s .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:de.saly.es.example.tssl.plugin.test.multijvm.MultiJvmUnitTest.java

public void startCluster() throws Exception {
    final String separator = System.getProperty("file.separator");
    final String classpath = System.getProperty("java.class.path");
    final String path = System.getProperty("java.home") + separator + "bin" + separator + "java";
    final ProcessBuilder processBuilder = new ProcessBuilder(path, "-Xmx1g", "-Xms1g", "-cp", classpath,
            Cluster.class.getCanonicalName());
    processBuilder.redirectErrorStream(true);
    processBuilder.redirectOutput(Redirect.INHERIT);
    processes.add(processBuilder.start());
}

From source file:fr.amap.amapvox.rxptolaz.RxpScanConversion.java

public void toLaz(SimpleScan scan, File outputDirectory, boolean laz)
        throws IOException, InterruptedException, UnsupportedOperationException, Exception {

    /***Convert rxp to txt***/

    Mat4D transfMatrix = Mat4D.multiply(scan.sopMatrix, scan.popMatrix);

    Mat3D rotation = new Mat3D();
    rotation.mat = new double[] { transfMatrix.mat[0], transfMatrix.mat[1], transfMatrix.mat[2],
            transfMatrix.mat[4], transfMatrix.mat[5], transfMatrix.mat[6], transfMatrix.mat[8],
            transfMatrix.mat[9], transfMatrix.mat[10] };

    File outputTxtFile = new File(
            outputDirectory.getAbsolutePath() + File.separator + scan.file.getName() + ".txt");
    BufferedWriter writer = new BufferedWriter(new FileWriter(outputTxtFile));

    RxpExtraction extraction = new RxpExtraction();

    extraction.openRxpFile(scan.file, RxpExtraction.REFLECTANCE);

    Iterator<Shot> iterator = extraction.iterator();

    while (iterator.hasNext()) {

        Shot shot = iterator.next();//from   ww  w  .j  av  a 2  s  .  com

        Vec4D origin = Mat4D.multiply(transfMatrix,
                new Vec4D(shot.origin.x, shot.origin.y, shot.origin.z, 1.0d));
        Vec3D direction = Mat3D.multiply(rotation,
                new Vec3D(shot.direction.x, shot.direction.y, shot.direction.z));

        for (int i = 0; i < shot.nbEchos; i++) {

            double x = origin.x + direction.x * shot.ranges[i];
            double y = origin.y + direction.y * shot.ranges[i];
            double z = origin.z + direction.z * shot.ranges[i];

            writer.write(x + " " + y + " " + z + " " + (i + 1) + " " + shot.nbEchos + " "
                    + reflectanceToIntensity(shot.reflectances[i]) + "\n");
        }

    }

    extraction.close();
    writer.close();

    /***Convert txt to laz***/
    String propertyValue = System.getProperty("user.dir");
    System.out.println("Current jar directory : " + propertyValue);

    String txtToLasPath;

    String osName = getOSName();

    switch (osName) {
    case "windows":
    case "linux":
        txtToLasPath = propertyValue + File.separator + "LASTools" + File.separator + osName + File.separator
                + "txt2las";
        break;
    default:
        throw new UnsupportedOperationException("Os architecture not supported");
    }

    if (osName.equals("windows")) {
        txtToLasPath = txtToLasPath + ".exe";
    }

    File outputLazFile;
    if (laz) {
        outputLazFile = new File(
                outputDirectory.getAbsolutePath() + File.separator + scan.file.getName() + ".laz");
    } else {
        outputLazFile = new File(
                outputDirectory.getAbsolutePath() + File.separator + scan.file.getName() + ".las");
    }

    String[] commandLine = new String[] { txtToLasPath, "-i", outputTxtFile.getAbsolutePath(), "-o",
            outputLazFile.getAbsolutePath(), "-parse", "xyzrni" };

    System.out.println("Command line : "
            + ArrayUtils.toString(commandLine).replaceAll(",", " ").replaceAll("}", "").replace("{", ""));

    ProcessBuilder pb = new ProcessBuilder(commandLine);
    pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    pb.redirectError(ProcessBuilder.Redirect.INHERIT);

    Process p = pb.start();

    p.waitFor();

}

From source file:drm.taskworker.workers.OptimusWorker.java

private TaskResult start(File workdir, Task task) throws IOException, ParameterFoundException {
    String obj = (String) task.getParam(PRM_START_FILE);
    // FIXME only works with the adapted taskworker-client script (not committed)
    byte[] file = Base64.decodeBase64(obj);

    String method = (String) task.getParam(PRM_START_METHOD);

    File f = new File(workdir, "input.zip");
    OutputStream out = new FileOutputStream(f);
    out.write(file);/*from  w  ww . j  a v  a  2s.  com*/
    out.close();

    ProcessBuilder pb = new ProcessBuilder("python", task.getJobOption("optimus.exe"), "input.zip", method);
    pb.directory(workdir);

    Process handle = pb.start();

    (new VoidStreamPump(handle.getInputStream())).start();
    (new VoidStreamPump(handle.getErrorStream())).start();

    handles.put(task.getJobId(), handle);

    // start looking for flag file
    File goFile = new File(workdir, task.getJobOption("optimus.flagfile.go"));
    while (!goFile.exists()) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new Error("should not occur", e);
        }
    }
    goFile.delete();
    return split(workdir, task);
}

From source file:hydrograph.ui.perspective.ApplicationWorkbenchWindowAdvisor.java

public void killPortProcess(Properties properties) throws IOException {
    if (OSValidator.isWindows()) {
        String pid = getServicePortPID(properties.getProperty(PORT_NUMBER));
        if (StringUtils.isNotBlank(pid)) {
            int portPID = Integer.parseInt(pid);
            ProcessBuilder builder = new ProcessBuilder(
                    new String[] { "cmd", "/c", "taskkill /F /PID " + portPID });
            builder.start();
        }/*from  w ww . java  2 s  .c o  m*/
    } else if (OSValidator.isMac()) {
        int portNumber = Integer.parseInt(properties.getProperty(PORT_NUMBER));
        ProcessBuilder builder = new ProcessBuilder(new String[] { "bash", "-c",
                "lsof -P | grep :" + portNumber + " | awk '{print $2}' | xargs kill -9" });
        builder.start();
    }
}

From source file:com.orange.clara.cloud.servicedbdumper.dbdumper.core.AbstractCoreDbAction.java

protected Process runCommandLine(String[] commandLine, boolean inInheritOutput)
        throws IOException, InterruptedException {
    ProcessBuilder pb = this.generateProcessBuilder(commandLine);
    if (inInheritOutput) {
        pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    } else {//from w  w  w. j  a  v a2 s .  co m
        pb.redirectOutput(ProcessBuilder.Redirect.PIPE);
    }
    pb.redirectErrorStream(true);
    Process process = pb.start();

    return process;
}

From source file:com.seyren.core.service.notification.ScriptNotificationService.java

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts)
        throws NotificationFailedException {
    if (check.getState() == AlertType.ERROR) {
        String hostPosition = subscription.getPosition();

        // Check for a valid position
        if (hostPosition == null) {
            LOGGER.info("No hostname position for subscription: {}", subscription.getId());
            throw new NotificationFailedException("Invalid subscription; script has no hostname position");
        }//from ww w . j a v  a2s  .  c o  m

        LOGGER.info("Script Location: {}", seyrenConfig.getScriptPath());
        for (Alert alert : alerts) {
            try {
                String hostname = getHostName(alert, hostPosition);
                String resourceUrl = subscription.getTarget();
                ProcessBuilder pb = new ProcessBuilder(seyrenConfig.getScriptType(),
                        seyrenConfig.getScriptPath(), hostname, new Gson().toJson(check),
                        seyrenConfig.getBaseUrl(), resourceUrl);
                LOGGER.info("Script Start");
                Process p = pb.start();
                BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    LOGGER.info(line);
                    //System.out.println(line);
                }
                LOGGER.info("Script End");
            } catch (Exception e) {
                LOGGER.error("Script could not be sent: {}", e);
                throw new NotificationFailedException("Could not send message through the script");
            }
        }
    }
}

From source file:cn.dreampie.common.plugin.lesscss.compiler.NodeJsLessCssCompiler.java

private String compile(String input) throws LessException, IOException, InterruptedException {
    long start = System.currentTimeMillis();

    File inputFile = File.createTempFile("lessc-input-", ".less");
    FileOutputStream out = new FileOutputStream(inputFile);
    IOUtils.write(input, out);/* ww  w.  j  a  v  a  2 s.  c  o  m*/
    out.close();
    File outputFile = File.createTempFile("lessc-output-", ".css");
    File lesscJsFile = new File(tempDir, "lessc.js");

    ProcessBuilder pb = new ProcessBuilder(nodeExecutablePath, lesscJsFile.getAbsolutePath(),
            inputFile.getAbsolutePath(), outputFile.getAbsolutePath(), String.valueOf(compress));
    pb.redirectErrorStream(true);
    Process process = pb.start();
    IOUtils.copy(process.getInputStream(), System.out);

    int exitStatus = process.waitFor();

    FileInputStream in = new FileInputStream(outputFile);
    String result = IOUtils.toString(in);
    in.close();
    if (!inputFile.delete()) {
        logger.warn("Could not delete temp file: " + inputFile.getAbsolutePath());
    }
    if (!outputFile.delete()) {
        logger.warn("Could not delete temp file: " + outputFile.getAbsolutePath());
    }
    if (exitStatus != 0) {
        throw new LessException(result, null);
    }

    logger.debug("Finished compilation of LESS source in " + (System.currentTimeMillis() - start) + " ms.");

    return result;
}