Example usage for java.lang Runtime exec

List of usage examples for java.lang Runtime exec

Introduction

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

Prototype

public Process exec(String cmdarray[]) throws IOException 

Source Link

Document

Executes the specified command and arguments in a separate process.

Usage

From source file:com.impetus.kundera.ycsb.runner.YCSBRunner.java

public void run(final String workLoad, final int threadCount) throws IOException {
    int runCounter = crudUtils.getMaxRunSequence(new Date(), runType);
    runCounter = runCounter + 1;/*from   ww  w .  j a v a  2s  .  c o m*/
    noOfThreads = threadCount;
    // id column of performanceNoInfo table
    Date id = new Date();

    int counter = 1;
    for (String client : clients) {
        currentClient = client;
        if (clientjarlocation != null && ycsbJarLocation != null && client != null && runType != null
                && host != null && schema != null && columnFamilyOrTable != null) {
            Runtime runtime = Runtime.getRuntime();
            counter++;
            String runCommand = getCommandString(client, workLoad);

            logger.info(runCommand);
            double totalTime = 0.0;
            long noOfOperations = 0;

            Process process = runtime.exec(runCommand);
            process.getErrorStream();
            InputStream is = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            BigDecimal avgLatency = null;
            BigDecimal throughput = null;

            boolean processed = false;
            while ((line = br.readLine()) != null) {
                processed = true;
                if (line.contains("RunTime")) {
                    totalTime = Double.parseDouble(line.substring(line.lastIndexOf(", ") + 2));
                    logger.info("Total time taken " + totalTime);
                }
                if (line.contains("Operations") && noOfOperations == 0) {
                    noOfOperations = Long.parseLong(line.substring(line.lastIndexOf(", ") + 2));
                    logger.info("Total no of oprations " + noOfOperations);
                }
                if (line.contains("Throughput")) {

                    throughput = new BigDecimal(line.substring(line.lastIndexOf(", ") + 2));
                    logger.info("Throughput(ops/sec) " + line);
                }
                if (line.contains("AverageLatency")) {
                    if (avgLatency == null) {
                        avgLatency = new BigDecimal(line.substring(line.lastIndexOf(", ") + 2));
                        logger.info("AverageLatency " + line);
                    }
                }
                /*
                 * if(line.contains("MinLatency")) {
                 * logger.info("MinLatency " + line); }
                 * if(line.contains("MaxLatency")) {
                 * logger.info("MaxLatency " + line); }
                 */
                // if(!(line.contains("CLEANUP") || line.contains("UPDATE")
                // || line.contains("INSERT") )){
                //                     logger.info(line);
                // }
            }

            if (!processed) {
                is = process.getErrorStream();
                isr = new InputStreamReader(is);
                br = new BufferedReader(isr);
                line = null;
                while ((line = br.readLine()) != null) {
                    logger.info(line);

                }
                throw new RuntimeException("Error while processing");
            }

            PerformanceNoInfo info = new PerformanceNoInfo(id, releaseNo,
                    client.substring(client.lastIndexOf(".") + 1), runType, noOfThreads, noOfOperations,
                    totalTime, runCounter);

            if (avgLatency != null) {
                info.setAvgLatency(avgLatency.round(MathContext.DECIMAL32));
            }

            if (throughput != null) {
                info.setThroughput(throughput.round(MathContext.DECIMAL32));
            }
            crudUtils.persistInfo(info);
            timeTakenByClient.put(client, throughput);
        }
    }

    sendMail();
}

From source file:com.hp.avmon.home.service.LicenseService.java

public void callLinuxCpuId() {
    Runtime rt = Runtime.getRuntime();
    Process p = null;/*from www  . ja v  a 2s .  c  om*/
    try {
        String vbexepath = getLicensePath() + "/getcpusn";
        p = rt.exec(vbexepath);

        InputStreamReader isr_normal = new InputStreamReader(p.getInputStream());
        int ch = 0;
        StringBuffer strbuf = new StringBuffer();
        while ((ch = isr_normal.read()) != -1) {
            strbuf.append((char) ch);
        }
        p.waitFor();

    } catch (Exception e) {
        // e.printStackTrace();
    }
}

From source file:org.jitsi.meet.test.PSNRTest.java

/**
 * A test where we read some configurations or fallback to default values
 * and we expect a conference to be already established (by SetupConference)
 * and we keep checking whether this is still the case, and if something
 * is not working we fail.// w w  w  .j  av a2  s .c o  m
 */
public void testPSNR() {
    File inputFrameDir = new File(INPUT_FRAME_DIR);
    if (!inputFrameDir.exists()) {
        // Skip the PSNR tests because we don't have any PSNR
        // resources.
        return;
    }
    // Create the output directory for captured frames.
    File outputFrameDir = new File(OUTPUT_FRAME_DIR);
    if (!outputFrameDir.exists()) {
        outputFrameDir.mkdirs();
    }

    String timeToRunInMin = System.getProperty("psnr.duration");

    // default is 1 minute
    if (timeToRunInMin == null || timeToRunInMin.length() == 0)
        timeToRunInMin = "1";

    final int minutesToRun = Integer.valueOf(timeToRunInMin);

    final CountDownLatch waitSignal = new CountDownLatch(1);

    // execute every 1 sec.
    final Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        long lastRun = System.currentTimeMillis();

        int millsToRun = minutesToRun * 60 * 1000;

        CountDownLatch ownerDownloadSignal = new CountDownLatch(3);
        CountDownLatch secondPDownloadSignal = new CountDownLatch(3);

        @Override
        public void run() {
            try {
                System.err.println("Checking at " + new Date() + " / to finish: " + millsToRun + " ms.");

                if (!ConferenceFixture.isIceConnected(ConferenceFixture.getOwner())) {
                    assertAndQuit("Owner ice is not connected.");
                    return;
                }

                if (!ConferenceFixture.isInMuc(ConferenceFixture.getOwner())) {
                    assertAndQuit("Owner is not in the muc.");
                    return;
                }

                if (!ConferenceFixture.isIceConnected(ConferenceFixture.getSecondParticipant())) {
                    assertAndQuit("Second participant ice is not connected.");
                    return;
                }

                if (!ConferenceFixture.isInMuc(ConferenceFixture.getSecondParticipant())) {
                    assertAndQuit("The second participant is not in the muc.");
                    return;
                }

                long downloadOwner = ConferenceFixture.getDownloadBitrate(ConferenceFixture.getOwner());
                long downloadParticipant = ConferenceFixture
                        .getDownloadBitrate(ConferenceFixture.getSecondParticipant());

                if (downloadOwner <= 0) {
                    System.err.println("Owner no download bitrate");
                    ownerDownloadSignal.countDown();
                } else
                    ownerDownloadSignal = new CountDownLatch(3);

                if (ownerDownloadSignal.getCount() <= 0) {
                    assertAndQuit("Owner download bitrate less than 0");
                    return;
                }

                if (downloadParticipant <= 0) {
                    System.err.println("Second participant no download bitrate");
                    secondPDownloadSignal.countDown();
                } else
                    secondPDownloadSignal = new CountDownLatch(3);

                if (secondPDownloadSignal.getCount() <= 0) {
                    assertAndQuit("Second participant download rate less than 0");
                    return;
                }

                if (!ConferenceFixture.isXmppConnected(ConferenceFixture.getOwner())) {
                    assertAndQuit("Owner xmpp connection is not connected");
                    return;
                }

                if (!ConferenceFixture.isXmppConnected(ConferenceFixture.getSecondParticipant())) {
                    assertAndQuit("The second participant xmpp " + "connection is not connected");
                    return;
                }

                WebDriver driver = ConferenceFixture.getOwner();
                if (driver instanceof JavascriptExecutor) {
                    JavascriptExecutor js = ((JavascriptExecutor) driver);

                    List<WebElement> remoteThumb = driver
                            .findElements(By.xpath("//video[starts-with(@id, 'remoteVideo_')]"));

                    for (WebElement webElement : remoteThumb) {
                        //FIXME This needs to be optimized. We run this
                        // every second. It encodes an image in base64 and
                        // it transfers it over the network (that's how
                        // selenium communicates with the debugger). So this
                        // might work with a few images per second.. But this
                        // will fail miserably if we want to capture 30fps.
                        // The proper solution would be to store the images
                        // in the sandboxed HTML filesystem that modern
                        // browsers provide. And transfer them at the end
                        // of the test. We could follow the same approach
                        // if we want to grab the whole webm/vp8 stream using
                        // the Recorder API.
                        String elmId = webElement.getAttribute("id");
                        Object pngUrl = js.executeScript("var video = document.getElementById(\"" + elmId
                                + "\");" + "var canvasId = 'canvas-capture';"
                                + "var canvas = document.getElementById(canvasId);" + "if (canvas == null) {"
                                + "    canvas = document.createElement('canvas');" + "    canvas.id = canvasId;"
                                + "    document.body.appendChild(canvas);" + "}"
                                + "canvas.width = video.videoWidth;" + "canvas.height = video.videoHeight;"
                                + "var ctx = canvas.getContext('2d');" + "ctx.drawImage(video, 0, 0);"
                                + "return canvas.toDataURL(\"image/png\");");

                        // Parse the URI to get only the base64 part
                        String strBase64 = pngUrl.toString().substring("data:image/png;base64,".length());

                        // Convert it to binary
                        // Java 8 has a Base64 class.
                        byte[] data = org.apache.commons.codec.binary.Base64.decodeBase64(strBase64);

                        try (OutputStream stream = new FileOutputStream(
                                OUTPUT_FRAME_DIR + elmId + "-" + lastRun + ".png")) {
                            stream.write(data);
                        }
                    }
                }

                long currentTime = System.currentTimeMillis();
                millsToRun -= (currentTime - lastRun);
                lastRun = currentTime;

                if (millsToRun <= 0) {
                    timer.cancel();
                }
            } catch (Exception e) {
                e.printStackTrace();

                assertAndQuit("Unexpected error occurred.");
            }
        }

        /**
         * Clears what is needed and lowers the assert countdown.
         * @param msg
         */
        private void assertAndQuit(String msg) {
            System.err.println(msg);
            waitSignal.countDown();
            timer.cancel();
        }

    }, /* delay */ 1000, /* period */ 1000);

    try {
        waitSignal.await(minutesToRun, TimeUnit.MINUTES);

        if (waitSignal.getCount() == 0)
            assertTrue("A problem with the conf occurred", false);
        else {
            Runtime rt = Runtime.getRuntime();
            String[] commands = { PSNR_SCRIPT, OUTPUT_FRAME_DIR, INPUT_FRAME_DIR, RESIZED_FRAME_DIR };
            Process proc = rt.exec(commands);

            BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));

            BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

            // read the output from the command
            String s = null;
            while ((s = stdInput.readLine()) != null) {
                assertTrue(s == null || Float.parseFloat(s.split(" ")[1]) > MIN_PSNR);
            }

            // read any errors from the attempted command
            while ((s = stdError.readLine()) != null) {
                System.err.println(s);
            }
        }
    } catch (Exception e) {
        assertTrue("An error occurred", false);
    }
}

From source file:org.mnsoft.pdfocr.Wrapper.java

/**
 * Call an external program./*from  w ww. j a  va 2s .co m*/
 *
 * @param cmd
 * @throws IOException
 * @throws InterruptedException
 */
private void callOCREngine(String[] cmd) throws IOException, InterruptedException {
    Runtime run = Runtime.getRuntime();
    Process pr = run.exec(cmd);
    pr.waitFor();

    BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    String line = "";
    while ((line = buf.readLine()) != null) {
        log.info(line);
    }
}

From source file:com.panet.imeta.trans.steps.monetdbbulkloader.MonetDBBulkLoader.java

public boolean execute(MonetDBBulkLoaderMeta meta, boolean wait) throws KettleException {
    Runtime rt = Runtime.getRuntime();

    try {/*  w w w  .j  av a2s.  com*/
        String cmd = createCommandLine(meta, true);

        logBasic("Executing command: " + cmd);
        data.mClientlProcess = rt.exec(cmd);

        // any error message?
        //
        data.errorLogger = new StreamLogger(data.mClientlProcess.getErrorStream(), "ERROR");

        // any output?
        data.outputLogger = new StreamLogger(data.mClientlProcess.getInputStream(), "OUTPUT");

        // Where do we send the data to?  --> To STDIN of the mclient process
        //
        data.monetOutputStream = data.mClientlProcess.getOutputStream();

        // kick them off
        new Thread(data.errorLogger).start();
        new Thread(data.outputLogger).start();

        // OK, from here on, we need to feed the COPY INTO command followed by the data into the monetOutputStream
        //
    } catch (Exception ex) {
        throw new KettleException("Error while executing mclient : " + createCommandLine(meta, false), ex);
    }

    return true;
}

From source file:org.estatio.dscm.services.SyncService.java

@Programmatic
public void syncPlaylist(Display display, String path) {
    Runtime rt = Runtime.getRuntime();
    String[] syncCommand = createSyncSchedulePath(path, "sync", display);
    String[] scheduleCommand = createSyncSchedulePath(path, "schedule", display);

    try {/*ww w. java 2s .c o  m*/
        Process p = rt.exec(syncCommand);
        p.waitFor();
        rt.exec(scheduleCommand);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:fish.payara.maven.plugins.micro.StopMojo.java

private void killProcess(String processId) throws MojoExecutionException {
    String command = null;/*  w  ww.  ja  v  a 2s .  com*/
    try {
        final Runtime re = Runtime.getRuntime();
        if (isUnix()) {
            command = "kill " + processId;
        } else if (isWindows()) {
            command = "taskkill /PID " + processId + " /F";
        }
        if (command == null) {
            throw new MojoExecutionException("Operation system not supported!");
        }
        Process killProcess = re.exec(command);
        int result = killProcess.waitFor();
        if (result != 0) {
            getLog().error(ERROR_MESSAGE);
        }
    } catch (IOException | InterruptedException e) {
        getLog().error(ERROR_MESSAGE, e);
    }
}

From source file:com.eucalyptus.storage.ISCSIManager.java

/**
 * Executes the specified command in a separate process. A {@link DirectStorageInfo#timeoutInMillis timeout} is enforced on the process using
 * {@link java.util.concurrent.ExecutorService ExecutorService} framework. If the process does not complete with in the timeout, it is cancelled.
 * /*from   w w  w.ja  v a2s .  c  o m*/
 * @param command
 * @param timeout
 * @return CommandOutput
 * @throws EucalyptusCloudException
 */
private CommandOutput execute(String[] command, Long timeout) throws EucalyptusCloudException {
    try {
        Integer returnValue = -999999;
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(command);
        StreamConsumer error = new StreamConsumer(process.getErrorStream());
        StreamConsumer output = new StreamConsumer(process.getInputStream());
        error.start();
        output.start();
        Callable<Integer> processMonitor = new ProcessMonitor(process);
        Future<Integer> processController = service.submit(processMonitor);
        try {
            returnValue = processController.get(timeout, TimeUnit.MILLISECONDS);
        } catch (TimeoutException tex) {
            String commandStr = buildCommand(command);
            LOG.error(commandStr + " timed out. Cancelling the process, logging a fault and exceptioning out");
            processController.cancel(true);
            Faults.forComponent(Storage.class).havingId(TGT_HOSED).withVar("component", "Storage Controller")
                    .withVar("timeout", Long.toString(timeout)).log();
            throw new EucalyptusCloudException("No response from the command " + commandStr
                    + ". Process timed out after waiting for " + timeout + " milliseconds");
        }
        output.join();
        error.join();
        LOG.debug("ISCSIManager executed: " + JOINER.join(command) + "\n return=" + returnValue + "\n stdout="
                + output.getReturnValue() + "\n stderr=" + error.getReturnValue());
        return new CommandOutput(returnValue, output.getReturnValue(), error.getReturnValue());
    } catch (Exception ex) {
        if (ex instanceof EucalyptusCloudException) {
            throw (EucalyptusCloudException) ex;
        } else {
            throw new EucalyptusCloudException(ex);
        }
    }
}

From source file:coral.service.ExpTemplateUtil.java

public String runZtree(String template, ExpData data, ErrorFlag error, final ExpServiceImpl service) {
    if (ztreeProcess == null) {
        Runtime rt = Runtime.getRuntime();
        try {/*  ww  w .j  a v  a2s . co m*/
            ztreeProcess = rt.exec("ztree.exe /treatment " + template);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        new Thread() {
            public void run() {
                File f = new File(basepath + "ztree_end.txt");
                while (!f.exists()) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                // TODO read f and post to database

                ztreeProcess.destroy();
                ztreeProcess = null;

                // TODO delete file
                f.delete();

                // TODO progress client
                for (Integer id : service.dataMap.keySet()) {
                    // todo add table comps as args
                    service.process(id, "zleaf");
                }
            };
        }.start();
    }

    return null;
}