Example usage for java.lang ProcessBuilder ProcessBuilder

List of usage examples for java.lang ProcessBuilder ProcessBuilder

Introduction

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

Prototype

public ProcessBuilder(String... command) 

Source Link

Document

Constructs a process builder with the specified operating system program and arguments.

Usage

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   w ww.  j a v  a 2s  .  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:org.mashupmedia.encode.ProcessManager.java

public String callProcess(List<String> commands) throws IOException {

    logger.info("Starting process...");

    ProcessBuilder processBuilder = new ProcessBuilder(commands);
    processBuilder.redirectErrorStream(true);
    Process process = processBuilder.start();

    InputStream inputStream = process.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    String line;/*from   www .j a va  2  s.co  m*/

    StringBuilder outputBuilder = new StringBuilder();

    while ((line = bufferedReader.readLine()) != null) {
        logger.info(line);
        outputBuilder.append(line);
    }
    IOUtils.closeQuietly(inputStream);

    try {
        int waitForValue = process.waitFor();
        logger.info("Process waitFor value = " + waitForValue);
    } catch (InterruptedException e) {
        logger.error("Error waiting for waitFor.", e);
    }

    int exitValue = process.exitValue();
    logger.info("Process exit value = " + exitValue);

    return outputBuilder.toString();

}

From source file:com.hi.datacleaner.ExternalCommandTransformer.java

private String[] getResult(List<String> commandTokens) throws IOException, InterruptedException {
    Process process = new ProcessBuilder(commandTokens).start();

    if (!process.waitFor(_timeout, TimeUnit.MILLISECONDS)) {
        process.destroy();//from www  . j  a v  a  2s.  co m
        throw new InterruptedException(
                "Process has been interrupted because of timeout (" + _timeout + "ms). ");
    }

    BufferedReader stdin = new BufferedReader(new InputStreamReader(process.getInputStream()));
    BufferedReader stderr = new BufferedReader(new InputStreamReader(process.getErrorStream()));

    StringBuilder result = new StringBuilder();
    String line;
    int linesCount = 0;

    while ((line = stdin.readLine()) != null) {
        linesCount++;
        result.append(line).append(_separator);
    }

    if (linesCount == 0) {
        result.append(ERROR);

        while ((line = stderr.readLine()) != null) {
            result.append(line).append(_separator);
        }
    }

    return new String[] { result.toString() };
}

From source file:edu.uci.ics.asterix.event.management.EventExecutor.java

public void executeEvent(Node node, String script, List<String> args, boolean isDaemon, Cluster cluster,
        Pattern pattern, IOutputHandler outputHandler, AsterixEventServiceClient client) throws IOException {
    List<String> pargs = new ArrayList<String>();
    pargs.add("/bin/bash");
    pargs.add(client.getEventsHomeDir() + File.separator + AsterixEventServiceUtil.EVENT_DIR + File.separator
            + EXECUTE_SCRIPT);/*w w w  .ja v a2 s  . c  o  m*/
    StringBuffer envBuffer = new StringBuffer(IP_LOCATION + "=" + node.getClusterIp() + " ");
    boolean isMasterNode = node.getId().equals(cluster.getMasterNode().getId());

    if (!node.getId().equals(EventDriver.CLIENT_NODE_ID) && cluster.getEnv() != null) {
        for (Property p : cluster.getEnv().getProperty()) {
            if (p.getKey().equals("JAVA_HOME")) {
                String val = node.getJavaHome() == null ? p.getValue() : node.getJavaHome();
                envBuffer.append(p.getKey() + "=" + val + " ");
            } else if (p.getKey().equals(EventUtil.NC_JAVA_OPTS)) {
                if (!isMasterNode) {
                    StringBuilder builder = new StringBuilder();
                    builder.append("\"");
                    String javaOpts = p.getValue();
                    if (javaOpts != null) {
                        builder.append(javaOpts);
                    }
                    if (node.getDebugPort() != null) {
                        int debugPort = node.getDebugPort().intValue();
                        if (!javaOpts.contains("-Xdebug")) {
                            builder.append(
                                    (" " + "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address="
                                            + debugPort));
                        }
                    }
                    builder.append("\"");
                    envBuffer.append("JAVA_OPTS" + "=" + builder + " ");
                }
            } else if (p.getKey().equals(EventUtil.CC_JAVA_OPTS)) {
                if (isMasterNode) {
                    StringBuilder builder = new StringBuilder();
                    builder.append("\"");
                    String javaOpts = p.getValue();
                    if (javaOpts != null) {
                        builder.append(javaOpts);
                    }
                    if (node.getDebugPort() != null) {
                        int debugPort = node.getDebugPort().intValue();
                        if (!javaOpts.contains("-Xdebug")) {
                            builder.append(
                                    (" " + "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address="
                                            + debugPort));
                        }
                    }
                    builder.append("\"");
                    envBuffer.append("JAVA_OPTS" + "=" + builder + " ");
                }
            } else if (p.getKey().equals("LOG_DIR")) {
                String val = node.getLogDir() == null ? p.getValue() : node.getLogDir();
                envBuffer.append(p.getKey() + "=" + val + " ");
            } else {
                envBuffer.append(p.getKey() + "=" + p.getValue() + " ");
            }

        }
        pargs.add(cluster.getUsername() == null ? System.getProperty("user.name") : cluster.getUsername());
    }

    StringBuffer argBuffer = new StringBuffer();
    if (args != null && args.size() > 0) {
        for (String arg : args) {
            argBuffer.append(arg + " ");
        }
    }

    ProcessBuilder pb = new ProcessBuilder(pargs);
    pb.environment().put(IP_LOCATION, node.getClusterIp());
    pb.environment().put(CLUSTER_ENV, envBuffer.toString());
    pb.environment().put(SCRIPT, script);
    pb.environment().put(ARGS, argBuffer.toString());
    pb.environment().put(DAEMON, isDaemon ? "true" : "false");

    Process p = pb.start();
    if (!isDaemon) {
        BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
        StringWriter writer = new StringWriter();
        IOUtils.copy(bis, writer, "UTF-8");
        String result = writer.getBuffer().toString();
        OutputAnalysis analysis = outputHandler.reportEventOutput(pattern.getEvent(), result);
        if (!analysis.isExpected()) {
            throw new IOException(analysis.getErrorMessage() + result);
        }
    }
}

From source file:com.opentable.etcd.EtcdInstance.java

@SuppressFBWarnings("SWL_SLEEP_WITH_LOCK_HELD")
public synchronized void start() throws IOException {
    if (etcdServer != null) {
        throw new IllegalStateException("already started");
    }/*www  .j a  v  a  2  s .  c  o m*/

    if (clientPort == 0) {
        clientPort = findPort(configuration.getClientPort());
    }
    if (peerPort == 0) {
        peerPort = findPort(configuration.getPeerPort());
    }

    final String hostname = configuration.getHostname() != null ? configuration.getHostname() : findHostname();

    final String clientAddr = hostname + ':' + clientPort;
    final String peerAddr = hostname + ':' + peerPort;

    final List<String> arguments = new ArrayList<>();
    arguments.addAll(Arrays.asList(ETCD_LOCATION, "-data-dir", configuration.getDataDirectory().toString(),
            "-name", id, "-max-wals", "1", "-max-snapshots", "1", "-listen-client-urls",
            "http://0.0.0.0:" + clientPort, "-advertise-client-urls", "http://" + clientAddr,
            "-initial-advertise-peer-urls", "http://" + peerAddr, "-listen-peer-urls",
            "http://0.0.0.0:" + peerPort));

    if (configuration.getInitialCluster() != null) {
        arguments.add("-initial-cluster");
        arguments.add(configuration.getInitialCluster());
    }

    if (configuration.isVerbose()) {
        arguments.add("-v");
    }

    if (configuration.getDiscoveryUri() != null) {
        arguments.add("-discovery");
        arguments.add(configuration.getDiscoveryUri());
    }

    if (configuration.getSnapshotCount() != null) {
        arguments.add("-snapshot-count=" + configuration.getSnapshotCount());
    }

    LOGGER.info("Launching etcd: {}", arguments);

    etcdServer = new ProcessBuilder(arguments).redirectOutput(Redirect.INHERIT).redirectError(Redirect.INHERIT)
            .start();

    try {
        Thread.sleep(200);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
    }

    LOGGER.info("etcd server launched: {}", etcdServer);
}

From source file:org.jellycastle.maven.Maven.java

/**
 * Get Java process builder with basic command line execution based on
 * given os nature./*w w w . j a v  a 2s .  com*/
 * @return
 */
private ProcessBuilder getProcessBuilder() {
    List<String> commands = new ArrayList<String>();
    if (SystemUtils.IS_OS_UNIX) {
        commands.add(BASH);
        commands.add(BASH_OPTION_C);
    } else {
        commands.add(CMD);
        commands.add(CMD_OPTION_C);
    }

    commands.add(buildCommand());

    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.directory(Paths.get("").toFile().getAbsoluteFile());

    log.trace("Returning ProcessBuilder for command:" + commands);
    return pb;
}

From source file:com.hivemq.maven.HiveMQMojo.java

/**
 * Starts the HiveMQ process with the given parameters
 *
 * @param commandParameters the parameters
 * @return the running HiveMQ process// ww  w.  jav a2s  . c o  m
 * @throws MojoExecutionException if the execution of HiveMQ did not work
 */
private Process startHiveMQ(final List<String> commandParameters) throws MojoExecutionException {
    final ProcessBuilder processBuilder = new ProcessBuilder(commandParameters);

    processBuilder.directory(hiveMQDir);
    processBuilder.redirectErrorStream(true);

    Process p;
    try {
        p = processBuilder.start();
    } catch (IOException e) {
        log.error("An error occured while starting HiveMQ:", e);
        throw new MojoExecutionException("An error occured while starting HiveMQ", e);
    }
    return p;
}

From source file:com.palantir.tslint.services.Bridge.java

private void start() {
    File nodeFile = Bridge.findNode();
    String nodePath = nodeFile.getAbsolutePath();

    // get the path to the bridge.js file
    File bundleFile;//from   w w  w.j  a v  a2 s  . c  o m
    try {
        bundleFile = FileLocator.getBundleFile(TSLintPlugin.getDefault().getBundle());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    File bridgeFile = new File(bundleFile, "bin/bridge.js");
    String bridgePath = bridgeFile.getAbsolutePath();

    // construct the arguments
    ImmutableList.Builder<String> argsBuilder = ImmutableList.builder();
    argsBuilder.add(nodePath);
    argsBuilder.add(bridgePath);

    // start the node process and create a reader/writer for its stdin/stdout
    List<String> args = argsBuilder.build();
    ProcessBuilder processBuilder = new ProcessBuilder(args.toArray(new String[args.size()]));
    try {
        this.nodeProcess = processBuilder.start();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    this.nodeStdout = new BufferedReader(
            new InputStreamReader(this.nodeProcess.getInputStream(), Charsets.UTF_8));
    this.nodeStdin = new PrintWriter(new OutputStreamWriter(this.nodeProcess.getOutputStream(), Charsets.UTF_8),
            true);

    // add a shutdown hook to destroy the node process in case its not properly disposed
    Runtime.getRuntime().addShutdownHook(new ShutdownHookThread());
}