Example usage for java.util Timer cancel

List of usage examples for java.util Timer cancel

Introduction

In this page you can find the example usage for java.util Timer cancel.

Prototype

public void cancel() 

Source Link

Document

Terminates this timer, discarding any currently scheduled tasks.

Usage

From source file:org.pbccrc.zsls.utils.Shell.java

/** Run a command */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }//  w  ww  . ja  v a2  s . c  om
    if (dir != null) {
        builder.directory(this.dir);
    }

    builder.redirectErrorStream(redirectErrorStream);

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        //One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            boolean overErrMsg = false;
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    if (!overErrMsg) {
                        if (line.length() + errMsg.length() > ERR_MSG_BUFF_SIZE)
                            overErrMsg = true;
                        else {
                            errMsg.append(line);
                            errMsg.append(System.getProperty("line.separator"));
                        }
                    }
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        // make sure that the error thread exits
        joinThread(errThread);
        completed.set(true);
        //the timeout thread handling
        //taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            // JDK 7 tries to automatically drain the input streams for us
            // when the process exits, but since close is not synchronized,
            // it creates a race if we close the stream first and the same
            // fd is recycled.  the stream draining thread will attempt to
            // drain that fd!!  it may block, OOM, or cause bizarre behavior
            // see: https://bugs.openjdk.java.net/browse/JDK-8024521
            //      issue is fixed in build 7u60
            InputStream stdout = process.getInputStream();
            synchronized (stdout) {
                inReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
            joinThread(errThread);
        }
        try {
            InputStream stderr = process.getErrorStream();
            synchronized (stderr) {
                errReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = clock.getTime();
    }
}

From source file:org.apache.hadoop.chukwa.inputtools.mdl.TorqueInfoProcessor.java

private boolean loadQstatData(String hodId) throws IOException, SQLException {
    TreeMap<String, String> aJobData = currentHodJobs.get(hodId);
    String userId = aJobData.get("userId");

    StringBuffer sb = new StringBuffer();
    sb.append(torqueBinDir).append("/qstat -f -1 ").append(hodId);
    String[] qstatCommand = new String[3];
    qstatCommand[0] = "ssh";
    qstatCommand[1] = torqueServer;/* w  w  w.j a v a 2s. c om*/
    qstatCommand[2] = sb.toString();

    String command = qstatCommand[0] + " " + qstatCommand[1] + " " + qstatCommand[2];
    ProcessBuilder pb = new ProcessBuilder(qstatCommand);
    Process p = pb.start();

    Timer timeout = new Timer();
    TorqueTimerTask torqueTimerTask = new TorqueTimerTask(p, command);
    timeout.schedule(torqueTimerTask, TorqueTimerTask.timeoutInterval * 1000);

    BufferedReader result = new BufferedReader(new InputStreamReader(p.getInputStream()));
    ErStreamHandler errorHandler = new ErStreamHandler(p.getErrorStream(), command, false);
    errorHandler.start();
    String line = null;
    String hosts = null;
    long startTimeValue = -1;
    long endTimeValue = Calendar.getInstance().getTimeInMillis();
    long executeTimeValue = Calendar.getInstance().getTimeInMillis();
    boolean qstatfinished;

    while ((line = result.readLine()) != null) {
        if (line.indexOf("ctime") >= 0) {
            String startTime = line.split("=")[1].trim();
            // Tue Sep 9 23:44:29 2008
            SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy");
            Date startTimeDate;
            try {
                startTimeDate = sdf.parse(startTime);
                startTimeValue = startTimeDate.getTime();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        if (line.indexOf("mtime") >= 0) {
            String endTime = line.split("=")[1].trim();
            SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy");
            Date endTimeDate;
            try {
                endTimeDate = sdf.parse(endTime);
                endTimeValue = endTimeDate.getTime();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        if (line.indexOf("etime") >= 0) {
            String executeTime = line.split("=")[1].trim();
            SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy");
            Date executeTimeDate;
            try {
                executeTimeDate = sdf.parse(executeTime);
                executeTimeValue = executeTimeDate.getTime();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        if (line.indexOf("exec_host") >= 0) {
            hosts = line.split("=")[1].trim();
        }
    }

    if (hosts != null && startTimeValue >= 0) {
        String[] items2 = hosts.split("[+]");
        int num = 0;
        for (int i = 0; i < items2.length; i++) {
            String machinetmp = items2[i];
            if (machinetmp.length() > 3) {
                String machine = items2[i].substring(0, items2[i].length() - 2);
                StringBuffer data = new StringBuffer();
                data.append("HodId=").append(hodId);
                data.append(", Machine=").append(machine);
                if (domain != null) {
                    data.append(".").append(domain);
                }
                log.info(data);
                num++;
            }
        }
        Timestamp startTimedb = new Timestamp(startTimeValue);
        Timestamp endTimedb = new Timestamp(endTimeValue);
        StringBuffer data = new StringBuffer();
        long timeQueued = executeTimeValue - startTimeValue;
        data.append("HodID=").append(hodId);
        data.append(", UserId=").append(userId);
        data.append(", StartTime=").append(startTimedb);
        data.append(", TimeQueued=").append(timeQueued);
        data.append(", NumOfMachines=").append(num);
        data.append(", EndTime=").append(endTimedb);
        log.info(data);
        qstatfinished = true;

    } else {

        qstatfinished = false;
    }

    try {
        errorHandler.join();
    } catch (InterruptedException ie) {
        log.error(ie.getMessage());
    }
    result.close();
    timeout.cancel();

    return qstatfinished;
}

From source file:com.lenovo.tensorhusky.common.utils.Shell.java

/**
 * Run a command//from   www  .  ja  va  2s  .c  om
 */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    builder.redirectErrorStream(redirectErrorStream);

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        // One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(
            new InputStreamReader(process.getErrorStream(), Charset.defaultCharset()));
    final BufferedReader inReader = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charset.defaultCharset()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    } catch (OutOfMemoryError oe) {
        LOG.error("Caught " + oe + ". One possible reason is that ulimit"
                + " setting of 'max user processes' is too low. If so, do"
                + " 'ulimit -u <largerNum>' and try again.");
        throw oe;
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        // make sure that the error thread exits
        joinThread(errThread);
        completed.set(true);
        // the timeout thread handling
        // taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            // JDK 7 tries to automatically drain the input streams for us
            // when the process exits, but since close is not synchronized,
            // it creates a race if we close the stream first and the same
            // fd is recycled. the stream draining thread will attempt to
            // drain that fd!! it may block, OOM, or cause bizarre behavior
            // see: https://bugs.openjdk.java.net/browse/JDK-8024521
            // issue is fixed in build 7u60
            InputStream stdout = process.getInputStream();
            synchronized (stdout) {
                inReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
            joinThread(errThread);
        }
        try {
            InputStream stderr = process.getErrorStream();
            synchronized (stderr) {
                errReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = Time.monotonicNow();
    }
}

From source file:at.gv.egovernment.moa.id.configuration.validation.oa.OAPVP2ConfigValidation.java

public List<String> validate(OAPVP2Config form, String oaID, HttpServletRequest request) {

    Timer timer = null;
    MOAHttpClient httpClient = null;/*from   www . j a  v a2 s. c  om*/
    HTTPMetadataProvider httpProvider = null;

    List<String> errors = new ArrayList<String>();
    try {
        byte[] certSerialized = null;
        if (form.getFileUpload() != null)
            certSerialized = form.getCertificate();
        else {
            OnlineApplication oa = ConfigurationDBRead.getOnlineApplication(oaID);
            if (oa != null && oa.getAuthComponentOA() != null && oa.getAuthComponentOA().getOAPVP2() != null) {
                certSerialized = oa.getAuthComponentOA().getOAPVP2().getCertificate();
            }
        }

        String check = form.getMetaDataURL();
        if (MiscUtil.isNotEmpty(check)) {

            if (!ValidationHelper.validateURL(check)) {
                log.info("MetaDataURL has no valid form.");
                errors.add(LanguageHelper.getErrorString("validation.pvp2.metadataurl.valid", request));

            } else {

                if (certSerialized == null) {
                    log.info("No certificate for metadata validation");
                    errors.add(LanguageHelper.getErrorString("validation.pvp2.certificate.notfound", request));

                } else {

                    X509Certificate cert = new X509Certificate(certSerialized);
                    BasicX509Credential credential = new BasicX509Credential();
                    credential.setEntityCertificate(cert);

                    timer = new Timer();
                    httpClient = new MOAHttpClient();

                    if (form.getMetaDataURL().startsWith("https:"))
                        try {
                            MOAHttpProtocolSocketFactory protoSocketFactory = new MOAHttpProtocolSocketFactory(
                                    "MOAMetaDataProvider",
                                    ConfigurationProvider.getInstance().getCertStoreDirectory(),
                                    ConfigurationProvider.getInstance().getTrustStoreDirectory(), null,
                                    ChainingModeType.PKIX, true);

                            httpClient.setCustomSSLTrustStore(form.getMetaDataURL(), protoSocketFactory);

                        } catch (MOAHttpProtocolSocketFactoryException e) {
                            log.warn("MOA SSL-TrustStore can not initialized. Use default Java TrustStore.", e);

                        } catch (ConfigurationException e) {
                            log.info("No MOA specific SSL-TrustStore configured. Use default Java TrustStore.",
                                    e);

                        }

                    List<MetadataFilter> filterList = new ArrayList<MetadataFilter>();
                    filterList.add(new MetaDataVerificationFilter(credential));
                    filterList.add(new SchemaValidationFilter());
                    MetadataFilterChain filter = new MetadataFilterChain();
                    filter.setFilters(filterList);

                    httpProvider = new HTTPMetadataProvider(timer, httpClient, form.getMetaDataURL());
                    httpProvider.setParserPool(new BasicParserPool());
                    httpProvider.setRequireValidMetadata(true);
                    httpProvider.setMetadataFilter(filter);
                    httpProvider.setMinRefreshDelay(1000 * 60 * 15); //15 minutes
                    httpProvider.setMaxRefreshDelay(1000 * 60 * 60 * 24); //24 hours

                    httpProvider.setRequireValidMetadata(true);

                    httpProvider.initialize();

                    if (httpProvider.getMetadata() == null) {
                        log.info("Metadata could be received but validation FAILED.");
                        errors.add(
                                LanguageHelper.getErrorString("validation.pvp2.metadata.validation", request));
                    }

                }
            }
        }

    } catch (CertificateException e) {
        log.info("Uploaded Certificate can not be found", e);
        errors.add(LanguageHelper.getErrorString("validation.pvp2.certificate.notfound", request));

    } catch (IOException e) {
        log.info("Metadata can not be loaded from URL", e);
        errors.add(LanguageHelper.getErrorString("validation.pvp2.metadataurl.read", request));

    } catch (MetadataProviderException e) {

        //TODO: check exception handling
        if (e.getCause() != null && e.getCause().getCause() instanceof SSLHandshakeException) {
            log.info("SSL Server certificate not trusted.", e);
            errors.add(LanguageHelper.getErrorString("validation.pvp2.metadata.ssl", request));

        } else {
            log.info("MetaDate verification failed", e);
            errors.add(LanguageHelper.getErrorString("validation.pvp2.metadata.verify", request));
        }

    } finally {
        if (httpProvider != null)
            httpProvider.destroy();

        if (timer != null)
            timer.cancel();

    }

    return errors;
}

From source file:org.pentaho.di.trans.Trans.java

/**
 * Begin processing. Also handle logging operations related to the start of the transformation
 *
 * @throws KettleTransException//  w  w w . j  a  v  a  2s  .  com
 *           the kettle trans exception
 */
public void beginProcessing() throws KettleTransException {
    TransLogTable transLogTable = transMeta.getTransLogTable();
    int intervalInSeconds = Const.toInt(environmentSubstitute(transLogTable.getLogInterval()), -1);

    try {
        String logTable = transLogTable.getActualTableName();

        SimpleDateFormat df = new SimpleDateFormat(REPLAY_DATE_FORMAT);
        log.logDetailed(
                BaseMessages.getString(PKG, "Trans.Log.TransformationCanBeReplayed") + df.format(currentDate));

        try {
            if (transLogTableDatabaseConnection != null && !Const.isEmpty(logTable)
                    && !Const.isEmpty(transMeta.getName())) {
                transLogTableDatabaseConnection.writeLogRecord(transLogTable, LogStatus.START, this, null);

                // Pass in a commit to release transaction locks and to allow a user to actually see the log record.
                //
                if (!transLogTableDatabaseConnection.isAutoCommit()) {
                    transLogTableDatabaseConnection.commitLog(true, transLogTable);
                }

                // If we need to do periodic logging, make sure to install a timer for this...
                //
                if (intervalInSeconds > 0) {
                    final Timer timer = new Timer(getName() + " - interval logging timer");
                    TimerTask timerTask = new TimerTask() {
                        public void run() {
                            try {
                                endProcessing();
                            } catch (Exception e) {
                                log.logError(BaseMessages.getString(PKG,
                                        "Trans.Exception.UnableToPerformIntervalLogging"), e);
                                // Also stop the show...
                                //
                                errors.incrementAndGet();
                                stopAll();
                            }
                        }
                    };
                    timer.schedule(timerTask, intervalInSeconds * 1000, intervalInSeconds * 1000);

                    addTransListener(new TransAdapter() {
                        public void transFinished(Trans trans) {
                            timer.cancel();
                        }
                    });
                }

                // Add a listener to make sure that the last record is also written when transformation finishes...
                //
                addTransListener(new TransAdapter() {
                    public void transFinished(Trans trans) throws KettleException {
                        try {
                            endProcessing();

                            lastWrittenStepPerformanceSequenceNr = writeStepPerformanceLogRecords(
                                    lastWrittenStepPerformanceSequenceNr, LogStatus.END);

                        } catch (KettleException e) {
                            throw new KettleException(BaseMessages.getString(PKG,
                                    "Trans.Exception.UnableToPerformLoggingAtTransEnd"), e);
                        }
                    }
                });

            }

            // If we need to write out the step logging information, do so at the end of the transformation too...
            //
            StepLogTable stepLogTable = transMeta.getStepLogTable();
            if (stepLogTable.isDefined()) {
                addTransListener(new TransAdapter() {
                    public void transFinished(Trans trans) throws KettleException {
                        try {
                            writeStepLogInformation();
                        } catch (KettleException e) {
                            throw new KettleException(BaseMessages.getString(PKG,
                                    "Trans.Exception.UnableToPerformLoggingAtTransEnd"), e);
                        }
                    }
                });
            }

            // If we need to write the log channel hierarchy and lineage information, add a listener for that too...
            //
            ChannelLogTable channelLogTable = transMeta.getChannelLogTable();
            if (channelLogTable.isDefined()) {
                addTransListener(new TransAdapter() {
                    public void transFinished(Trans trans) throws KettleException {
                        try {
                            writeLogChannelInformation();
                        } catch (KettleException e) {
                            throw new KettleException(BaseMessages.getString(PKG,
                                    "Trans.Exception.UnableToPerformLoggingAtTransEnd"), e);
                        }
                    }
                });
            }

            // See if we need to write the step performance records at intervals too...
            //
            PerformanceLogTable performanceLogTable = transMeta.getPerformanceLogTable();
            int perfLogInterval = Const.toInt(environmentSubstitute(performanceLogTable.getLogInterval()), -1);
            if (performanceLogTable.isDefined() && perfLogInterval > 0) {
                final Timer timer = new Timer(getName() + " - step performance log interval timer");
                TimerTask timerTask = new TimerTask() {
                    public void run() {
                        try {
                            lastWrittenStepPerformanceSequenceNr = writeStepPerformanceLogRecords(
                                    lastWrittenStepPerformanceSequenceNr, LogStatus.RUNNING);
                        } catch (Exception e) {
                            log.logError(BaseMessages.getString(PKG,
                                    "Trans.Exception.UnableToPerformIntervalPerformanceLogging"), e);
                            // Also stop the show...
                            //
                            errors.incrementAndGet();
                            stopAll();
                        }
                    }
                };
                timer.schedule(timerTask, perfLogInterval * 1000, perfLogInterval * 1000);

                addTransListener(new TransAdapter() {
                    public void transFinished(Trans trans) {
                        timer.cancel();
                    }
                });
            }
        } catch (KettleException e) {
            throw new KettleTransException(
                    BaseMessages.getString(PKG, "Trans.Exception.ErrorWritingLogRecordToTable", logTable), e);
        } finally {
            // If we use interval logging, we keep the connection open for performance reasons...
            //
            if (transLogTableDatabaseConnection != null && (intervalInSeconds <= 0)) {
                transLogTableDatabaseConnection.disconnect();
                transLogTableDatabaseConnection = null;
            }
        }
    } catch (KettleException e) {
        throw new KettleTransException(
                BaseMessages.getString(PKG, "Trans.Exception.UnableToBeginProcessingTransformation"), e);
    }
}

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.//from w ww .  j  av a  2 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);
    }
}