001/*
002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.nuxeo.functionaltests;
017
018import com.google.common.base.Function;
019import org.openqa.selenium.JavascriptExecutor;
020import org.openqa.selenium.NoSuchElementException;
021import org.openqa.selenium.WebDriver;
022import org.openqa.selenium.support.ui.FluentWait;
023import org.openqa.selenium.support.ui.Wait;
024
025import java.util.concurrent.TimeUnit;
026
027/**
028 * @since 7.10
029 */
030public class EventListener {
031
032    private static int COUNT = 0;
033
034    private final String id = "evt_listener_" + COUNT++;
035
036    private final String event;
037
038    private final String selector;
039
040    private final JavascriptExecutor js;
041
042    public EventListener(WebDriver driver, String event, String selector) {
043        super();
044        this.event = event;
045        this.selector = selector;
046        js = (JavascriptExecutor) driver;
047        listen();
048    }
049
050    public void listen() {
051        StringBuilder sb = new StringBuilder();
052        sb.append("window."+ id + " = 0;");
053        sb.append("var els = document.querySelectorAll('" + selector +"');");
054        sb.append("for (var i=0; i<els.length; i++) {");
055        sb.append("  els[i].addEventListener('" + event + "', function(e) { window."+ id + "++; });");
056        sb.append("}");
057        js.executeScript(sb.toString());
058    }
059
060    public void waitCalled() {
061        waitCalled(1);
062    }
063
064    public void waitCalled(int times) {
065        waitUntil(driver -> (Boolean) js.executeScript("return window." + id + " == " + times + ";"));
066    }
067
068    public void reset() {
069        js.executeScript("window." + id + " = 0;");
070    }
071
072    private void waitUntil(Function<WebDriver, Boolean> function) {
073        Wait<WebDriver> wait = new FluentWait<WebDriver>(AbstractTest.driver).withTimeout(
074            AbstractTest.LOAD_TIMEOUT_SECONDS, TimeUnit.SECONDS).pollingEvery(
075            AbstractTest.POLLING_FREQUENCY_MILLISECONDS, TimeUnit.MILLISECONDS).ignoring(
076            NoSuchElementException.class);
077        wait.until(function);
078    }
079
080}