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:annis.visualizers.component.AbstractDotVisualizer.java

public void writeOutput(VisualizerInput input, OutputStream outstream) {

    StringBuilder dot = new StringBuilder();

    try {/*from w w  w . j  av  a  2  s .  c  o m*/
        File tmpInput = File.createTempFile("annis-dot-input", ".dot");
        tmpInput.deleteOnExit();

        // write out input file
        StringBuilder dotContent = new StringBuilder();
        createDotContent(input, dotContent);
        FileUtils.writeStringToFile(tmpInput, dotContent.toString());

        // execute dot
        String dotPath = input.getMappings().getProperty("dotpath", "dot");
        ProcessBuilder pBuilder = new ProcessBuilder(dotPath, "-Tpng", tmpInput.getCanonicalPath());

        pBuilder.redirectErrorStream(false);
        Process process = pBuilder.start();

        InputStream inputFromProcess = process.getInputStream();
        for (int chr = inputFromProcess.read(); chr != -1; chr = inputFromProcess.read()) {
            outstream.write(chr);
        }

        inputFromProcess.close();

        int resultCode = process.waitFor();

        if (resultCode != 0) {
            InputStream stderr = process.getErrorStream();
            StringBuilder errorMessage = new StringBuilder();

            for (int chr = stderr.read(); chr != -1; chr = stderr.read()) {
                errorMessage.append((char) chr);
            }
            if (!"".equals(errorMessage.toString())) {
                log.error(
                        "Could not execute dot graph-layouter.\ncommand line:\n{}\n\nstderr:\n{}\n\nstdin:\n{}",
                        new Object[] { StringUtils.join(pBuilder.command(), " "), errorMessage.toString(),
                                dot.toString() });
            }
        }

        // cleanup
        if (!tmpInput.delete()) {
            log.warn("Cannot delete " + tmpInput.getAbsolutePath());
        }

    } catch (Exception ex) {
        log.error(null, ex);
    }
}

From source file:com.novartis.pcs.ontology.service.graph.DOTProcessImpl.java

@PostConstruct
protected void init() {
    ProcessBuilder processBuilder = new ProcessBuilder(Arrays.asList(dotPath, "-Tsvg"));

    try {/* w ww  . j a v  a  2 s .  c  o  m*/
        process = processBuilder.start();
        buffer = new byte[262144];
        count = 0;
        skip = new int[256];
    } catch (IOException e) {
        String msg = "Failed to start dot process";
        logger.log(Level.WARNING, msg, e);
        throw new RuntimeException(msg, e);
    }
}

From source file:frk.gpssimulator.service.impl.DefaultGpsdService.java

/**
 * Start given process./* w ww .j a  v  a  2  s  . c  om*/
 * @param command
 * @param wait for process to exit
 * @return
 */
int startProc(String command, Boolean wait) throws IOException, InterruptedException {
    String[] commandArray = command.split(" ");
    ProcessBuilder pb = new ProcessBuilder(commandArray);
    pb.redirectErrorStream(true); //redirect errorstream and outputstream to single stream
    Process proc = pb.start();
    BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    String line;
    //empty the output buff of the proc
    while ((line = in.readLine()) != null) {
        LOGGER.info(line);
    }

    if (wait) {
        return proc.waitFor();
    } else {
        return 0;
    }

}

From source file:ape.NetworkSlowCommand.java

/**
 * This method implements the event//from  ww  w  .j  a  v a 2s . c  o  m
 * @param time The amount of time to delay all network traffic in milliseconds
 * @param period How long the delay should last in seconds
 * @return True if successful execution, false if an error occurred
 * @throws IOException
 */
private boolean executecommand(double time, double period) throws IOException {
    String cmd = "tc qdisc add dev eth0 root netem delay " + time + "ms && sleep " + period
            + " && tc qdisc del dev eth0 root netem";
    ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(true);
    Process p = null;

    try {
        p = pb.start();
    } catch (IOException e) {
        System.err.println(
                "Executing network connection simulation catches IOException, enter VERBOSE mode to see the Stack Trace");
        e.printStackTrace();
        return false;
    }

    try {
        int retVal = p.waitFor();
        System.out.println("The return value for '" + cmd + "' was " + retVal);
        if (retVal != 0) {
            System.err.println("Non-zero return code (" + p.exitValue() + ") when executing: '" + cmd + "'");

            ProcessBuilder tmp2 = new ProcessBuilder("bash", "-c", "tc qdisc del dev eth0 root netem");
            Process ptmp = tmp2.start();
            try {
                if (ptmp.waitFor() == 0)
                    System.out.println("Connection Resumed");
                else {
                    System.out.println("Connection Resumed Failed");
                    return false;
                }
            } catch (InterruptedException e1) {
                e1.printStackTrace();
                System.err.println("Catches an exception when trying to recover the network");
                return false;
            }

            return false;

        }
    } catch (InterruptedException e) {
        System.err.println("Executing Command catches an Interrupt, resume connection");
        ProcessBuilder tmp2 = new ProcessBuilder("bash", "-c", "tc qdisc del dev eth0 root netem");
        Process ptmp = tmp2.start();
        try {
            if (ptmp.waitFor() == 0)
                System.out.println("Connection Resumed");
            else {
                System.out.println("Connection Resumed Failed");
                return false;
            }
        } catch (InterruptedException e1) {
            e1.printStackTrace();
            System.err.println("Catches an exception when trying to recover the network");
            e.printStackTrace();
            return false;
        }
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:alluxio.cli.AlluxioFrameworkIntegrationTest.java

private void startAlluxioFramework(Map<String, String> extraEnv) {
    String startScript = PathUtils.concatPath(Configuration.get(PropertyKey.HOME), "integration", "mesos",
            "bin", "alluxio-mesos-start.sh");
    ProcessBuilder pb = new ProcessBuilder(startScript, mMesosAddress);
    Map<String, String> env = pb.environment();
    env.putAll(extraEnv);//from w  w  w  .j  av a  2  s .  c  om
    try {
        pb.start().waitFor();
    } catch (Exception e) {
        LOG.info("Failed to launch Alluxio on Mesos. Note that this test requires that "
                + "Mesos is currently running.");
        throw new RuntimeException(e);
    }
}

From source file:com.web.searchlocal.flashpaper.thread.Covnert2SwfTask.java

/** 
 * /*from w w w .j  a  v  a 2s .com*/
 */
public void excute() {
    String tmpOutFile = outFile.getPath().concat(File.separator)
            .concat(inFile.getName().replaceAll("[.]{1}.*$", ".swf"));
    List<String> commandArray = new ArrayList<String>();
    commandArray.add(defaultCommand);
    commandArray.add(inFile.getPath());
    commandArray.add("-o");
    commandArray.add(tmpOutFile);
    ProcessBuilder pbObj = new ProcessBuilder();
    pbObj.command(commandArray);
    pbObj.directory(outFile);
    pbObj.redirectErrorStream(true);
    try {
        Process proObj = pbObj.start();
        final InputStream ins = proObj.getInputStream();
        final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        Thread th = new Thread() {
            public void run() {
                ReadableByteChannel rbcObj = Channels.newChannel(ins);
                try {
                    while (rbcObj.read(byteBuffer) != -1) {
                        byteBuffer.flip();
                        logger.info(java.nio.charset.Charset.defaultCharset().decode(byteBuffer));
                        byteBuffer.clear();
                    }
                } catch (IOException e) {
                    logger.error(e);
                }
            }
        };
        th.setDaemon(true);
        th.start();
        try {
            proObj.waitFor();
            logger.error("??." + tmpOutFile);
        } catch (InterruptedException e) {
            logger.error(e);
        }
    } catch (IOException e) {
        logger.error(e);
    }
}

From source file:gda.device.detector.mythen.client.TextClientMythenClient.java

private MythenTextClientExecResult execProcess(String... args) throws DeviceException {

    if (!EXEC_LOCK.tryLock()) {
        throw new DeviceException("Cannot acquire: client is already running");
    }//from www. ja v a2  s  .co  m

    try {
        MythenTextClientExecResult result = new MythenTextClientExecResult();

        // Build argument list
        List<String> argList = new Vector<String>();
        argList.add(host);
        argList.addAll(Arrays.asList(args));
        logger.info("Starting acquisition");
        logger.debug("Executing Mythen client with args " + argList);

        // Prepend executable name to argument list
        argList.add(0, mythenClientCommand);

        ProcessBuilder pb = new ProcessBuilder(argList);
        try {
            Process p = pb.start();
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            try {
                logger.debug("wait for TextClient to complete data acquisition ...");
                p.waitFor();
                logger.debug("TextClient returned.");
            } catch (InterruptedException e) {
                throw new DeviceException("Unable to wait for text client to finish", e);
            }

            result.output = FileCopyUtils.copyToString(br);

            result.exitValue = p.exitValue();
            if (result.exitValue != 0) {
                throw new DeviceException(
                        String.format("Client exited with non-zero status: %d", result.exitValue));
            }
            InterfaceProvider.getTerminalPrinter().print("Save to file " + this.params.getFilename());
            logger.info("Acquisition completed successfully");
            logger.debug("Client successfully exited with status code " + result.exitValue);

            return result;

        } catch (IOException e) {
            throw new DeviceException("Client operation failed", e);
        }
    } finally {
        EXEC_LOCK.unlock();
    }
}

From source file:com.twosigma.beakerx.kernel.MagicKernelManager.java

private void initPythonProcess() throws NoSuchKernelException {
    //cleanup communication resources if already in use
    exit();/*  w  w  w . j  av  a 2s  .co m*/

    port = findFreePort();
    pythonPort = findFreePort();

    try {
        ProcessBuilder pb = new ProcessBuilder(getPy4jCommand());
        pb.redirectError(ProcessBuilder.Redirect.INHERIT);
        pythonProcess = pb.start();
        BufferedReader br = new BufferedReader(new InputStreamReader(pythonProcess.getInputStream()));
        while (!PY4J_INIT_MESSAGE.equals(br.readLine()) && pythonProcess.isAlive()) {
            //wait for python process to initialize properly
        }
        if (!pythonProcess.isAlive() && pythonProcess.exitValue() == NO_SUCH_KERNEL_CODE) {
            throw new NoSuchKernelException(kernelName);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.palantir.tslint.Linter.java

public void lint(IResource resource, String configurationPath) throws IOException {
    String resourceName = resource.getName();
    if (resource instanceof IFile && resourceName.endsWith(".ts") && !resourceName.endsWith(".d.ts")) {
        IFile file = (IFile) resource;/* w  w  w  . j  a v  a2 s  .  com*/
        String linterPath = TSLintPlugin.getLinterPath();
        String resourcePath = resource.getRawLocation().toOSString();

        // remove any pre-existing markers for the given file
        deleteMarkers(file);

        // start tslint and get its output
        ProcessBuilder processBuilder = new ProcessBuilder(this.nodePath, linterPath, "-f", resourcePath, "-t",
                "json", "-c", configurationPath);

        Process process = processBuilder.start();
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream(), Charsets.UTF_8));
        String jsonString = reader.readLine();

        // now that we have the complete output, terminate the process
        process.destroy();

        if (jsonString != null) {
            ObjectMapper objectMapper = new ObjectMapper();
            RuleFailure[] ruleFailures = objectMapper.readValue(jsonString, RuleFailure[].class);
            for (RuleFailure ruleFailure : ruleFailures) {
                addMarker(ruleFailure);
            }
        }
    }
}

From source file:postenergy.PostEnergy.java

private void initUI() {

    /* Definitions */
    JPanel panel = new JPanel();
    getContentPane().add(panel);// w  ww .j a v  a  2  s. c om

    panel.setLayout(null);

    /* Basic elements */

    JButton getBatteryInfo = new JButton("Get Battery Info");
    getBatteryInfo.setBounds(0, 60, 180, 30);
    getBatteryInfo.setToolTipText("Get Battery Info");
    getBatteryInfo.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            System.out.println("getBatteryInfo button pressed!");

            ProcessBuilder pbs = new ProcessBuilder("/Users/thomas/Development/script.sh");

            try {
                Process p = pbs.start();
                BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                StringBuilder builder = new StringBuilder();
                String line = null;
                try {
                    while ((line = br.readLine()) != null) {
                        builder.append(line);
                        builder.append(System.getProperty("line.separator"));
                    }
                } catch (IOException ex) {
                    Logger.getLogger(PostEnergy.class.getName()).log(Level.SEVERE, null, ex);
                }
                String result = builder.toString();
                System.out.println("Result: " + result);

                // Send as POST request
                String[] paramNames = new String[] { "t", "h" };
                String[] paramVals = new String[] { result, result + 100 };

                PostHttpClient("mindass", paramNames, paramVals);
            } catch (IOException ex) {
                System.out.println("Error with the processbuilder!");
                Logger.getLogger(PostEnergy.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    });

    panel.add(getBatteryInfo);

    JButton sendPost = new JButton("Send Post");
    sendPost.setBounds(0, 30, 180, 30);
    sendPost.setToolTipText("Send Post");

    sendPost.addActionListener(new ActionListener() {
        @Override

        public void actionPerformed(ActionEvent event) {
            System.out.println("sendPost button pressed!");

            PostHttpClient("mindass", new String[] { "t", "h" }, new String[] { "23", "44" });

        }

    });

    panel.add(sendPost);

    JButton quitButton = new JButton("Quit");
    quitButton.setBounds(0, 0, 80, 30);
    quitButton.setToolTipText("Quit iPower");

    quitButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            System.out.println("Quit button pressed!");
            System.exit(0);
        }
    });

    panel.add(quitButton);

    /* Set init */
    setTitle("iPower");
    setSize(300, 200);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
}