public void onEvent(List<RemoteException> events, RemoteException lastInserted) {
   for (RemoteException e : events) {
     if (e instanceof RemoteNotReachableException) {
       log.warning(e.getMessage());
       down = true;
       this.errors.clear();
     }
     if (e instanceof RemoteUnregisterException) {
       log.warning(e.getMessage());
       Registry registry = this.getRegistry();
       registry.removeIfPresent(this);
     }
   }
 }
  @Test
  public void proxyTimeout() throws InterruptedException {
    Registry registry = Registry.newInstance();
    registry.getConfiguration().getAllParams().put(RegistrationRequest.TIME_OUT, 1);
    RegistrationRequest req = RegistrationRequest.build("-role", "webdriver", "-A", "valueA");
    req.getConfiguration().put(ID, "abc");
    req.getConfiguration().put(RegistrationRequest.PROXY_CLASS, DefaultRemoteProxy.class.getName());

    BaseRemoteProxy p = BaseRemoteProxy.getNewInstance(req, registry);
    TestSession newSession = p.getNewSession(new HashMap<String, Object>());
    assertNotNull(newSession);
    Thread.sleep(2);
    p.forceSlotCleanerRun();
    assertTrue(p.getRegistry().getActiveSessions().isEmpty());
  }
  @Test(expected = IllegalArgumentException.class)
  public void invalidNodePollingValue() {
    Map<String, Object> config = new HashMap<String, Object>();
    config.put(ID, "abc");
    config.put(RegistrationRequest.NODE_POLLING, "abc");

    RegistrationRequest req = new RegistrationRequest();
    req.setConfiguration(config);

    new DefaultRemoteProxy(req, Registry.newInstance());
  }
  @Test(expected = IllegalArgumentException.class)
  public void invalidUnregisterIfStillDownValue() {
    Map<String, Object> config = new HashMap<String, Object>();
    config.put(ID, "abc");
    config.put(RegistrationRequest.NODE_POLLING, 100);
    config.put(RegistrationRequest.UNREGISTER_IF_STILL_DOWN_AFTER, "abc");

    RegistrationRequest req = new RegistrationRequest();
    req.setConfiguration(config);

    new DefaultRemoteProxy(req, Registry.newInstance());
  }
  @BeforeClass
  public static void prepare() throws Exception {

    hub = GridTestHelper.getHub();
    registry = hub.getRegistry();
    registry.setThrowOnCapabilityNotPresent(false);

    remote = GridTestHelper.getRemoteWithoutCapabilities(hub.getUrl(), GridRole.NODE);
    remote.setMaxConcurrent(100);

    DesiredCapabilities caps = null;

    // firefox

    caps = DesiredCapabilities.firefox();
    caps.setCapability(FirefoxDriver.BINARY, locationFF7);
    caps.setVersion("7");
    remote.addBrowser(caps, 1);
    caps = DesiredCapabilities.firefox();
    caps.setCapability(FirefoxDriver.BINARY, locationFF3);
    caps.setVersion("3");
    remote.addBrowser(caps, 1);
    caps = DesiredCapabilities.firefox();
    caps.setCapability(FirefoxDriver.BINARY, "should be overwritten");
    caps.setVersion("20");
    remote.addBrowser(caps, 1);

    // chrome

    caps = DesiredCapabilities.chrome();
    caps.setCapability("chrome_binary", locationChrome27);
    caps.setVersion("27");
    remote.addBrowser(caps, 1);
    caps = DesiredCapabilities.chrome();
    caps.setCapability("chrome_binary", locationChrome29);
    caps.setVersion("29");
    remote.addBrowser(caps, 2);
    caps = DesiredCapabilities.chrome();
    caps.setCapability("chrome_binary", "should be overwritten");
    caps.setVersion("30");
    remote.addBrowser(caps, 1);

    remote.setRemoteServer(new SeleniumServer(remote.getConfiguration()));
    remote.startRemoteServer();
    remote.sendRegistrationRequest();
    RegistryTestHelper.waitForNode(registry, 1);
  }
/** how to setup a grid that does not use FIFO for the requests. */
public class WebDriverPriorityDemo {

  private Hub hub =
      Hub.getNewInstanceForTest(PortProber.findFreePort(), Registry.getNewInstanceForTestOnly());
  private URL hubURL = hub.getUrl();

  // start a small grid that only has 1 testing slot : firefox
  @BeforeClass(alwaysRun = true)
  public void prepare() throws Exception {

    hub.start();
    hubURL = new URL("http://" + hub.getHost() + ":" + hub.getPort());

    SelfRegisteringRemote remote =
        SelfRegisteringRemote.create(
            SeleniumProtocol.WebDriver, PortProber.findFreePort(), hub.getRegistrationURL());
    remote.addFirefoxSupport(null);
    remote.setMaxConcurrentSession(1);
    remote.setTimeout(-1, -1);
    remote.launchRemoteServer();
    remote.registerToHub();

    // assigning a priority rule where requests with the flag "important"
    // go first.
    hub.getRegistry()
        .setPrioritizer(
            new Prioritizer() {
              public int compareTo(Map<String, Object> a, Map<String, Object> b) {
                boolean aImportant =
                    a.get("important") == null
                        ? false
                        : Boolean.parseBoolean(a.get("important").toString());
                boolean bImportant =
                    b.get("important") == null
                        ? false
                        : Boolean.parseBoolean(b.get("important").toString());
                if (aImportant == bImportant) {
                  return 0;
                }
                if (aImportant && !bImportant) {
                  return -1;
                } else {
                  return 1;
                }
              }
            });
  }

  WebDriver runningOne;

  // mark the grid 100% busy = having 1 firefox test running.
  @Test
  public void test() throws MalformedURLException, InterruptedException {
    DesiredCapabilities ff = DesiredCapabilities.firefox();
    runningOne = new RemoteWebDriver(new URL(hubURL + "/grid/driver"), ff);
    runningOne.get(hubURL + "/grid/console");
    Assert.assertEquals(runningOne.getTitle(), "Grid overview");
  }

  // queuing 5 requests on the grid.
  @Test(dependsOnMethods = "test")
  public void sendMoreRequests() throws MalformedURLException {
    for (int i = 0; i < 5; i++) {
      new Thread(
              new Runnable() {
                public void run() {
                  DesiredCapabilities ff = DesiredCapabilities.firefox();
                  try {
                    new RemoteWebDriver(new URL(hubURL + "/grid/driver"), ff);
                  } catch (MalformedURLException e) {
                    e.printStackTrace();
                  }
                }
              })
          .start();
    }
  }

  WebDriver importantOne;
  boolean importantOneStarted = false;

  // adding a request with high priority at the end of the queue
  @Test(dependsOnMethods = "sendMoreRequests", timeOut = 30000)
  public void sendTheImportantOne() throws MalformedURLException, InterruptedException {
    while (hub.getRegistry().getNewSessionRequests().size() != 5) {
      Thread.sleep(250);
    }
    Assert.assertEquals(hub.getRegistry().getNewSessionRequests().size(), 5);
    Assert.assertEquals(hub.getRegistry().getActiveSessions().size(), 1);

    final DesiredCapabilities ff = DesiredCapabilities.firefox();
    ff.setCapability("important", true);

    new Thread(
            new Runnable() {
              public void run() {
                try {
                  importantOne = new RemoteWebDriver(new URL(hubURL + "/grid/driver"), ff);
                  importantOneStarted = true;
                } catch (MalformedURLException e) {
                  throw new RuntimeException("bug", e);
                }
              }
            })
        .start();
  }

  // then 5 more non-important requests
  @Test(dependsOnMethods = "sendTheImportantOne")
  public void sendMoreRequests2() throws MalformedURLException {
    for (int i = 0; i < 5; i++) {
      new Thread(
              new Runnable() {
                public void run() {
                  DesiredCapabilities ff = DesiredCapabilities.firefox();
                  try {
                    new RemoteWebDriver(new URL(hubURL + "/grid/driver"), ff);
                  } catch (MalformedURLException e) {
                    e.printStackTrace();
                  }
                }
              })
          .start();
    }
  }

  @Test(dependsOnMethods = "sendMoreRequests2", timeOut = 20000)
  public void validateStateAndPickTheImportantOne() throws InterruptedException {
    try {
      while (hub.getRegistry().getNewSessionRequests().size() != 11) {
        Thread.sleep(500);
      }
      // queue = 5 + 1 important + 5.
      Assert.assertEquals(hub.getRegistry().getNewSessionRequests().size(), 11);

      // 1 firefox still running
      Assert.assertEquals(hub.getRegistry().getActiveSessions().size(), 1);

      // closing the running test.
      runningOne.quit();

      // validating new expected state
      while (!(hub.getRegistry().getActiveSessions().size() == 1
          && hub.getRegistry().getNewSessionRequests().size() == 10)) {
        Thread.sleep(250);
        Reporter.log("waiting for correct state.");
      }

      // TODO freynaud : sometines does not start. FF pops up, but address bar remains empty.
      while (!importantOneStarted) {
        Thread.sleep(250);
        Reporter.log("waiting for browser to start");
      }
      importantOne.get(hubURL + "/grid/console");
      Assert.assertEquals(importantOne.getTitle(), "Grid overview");
    } finally {
      // cleaning the queue to avoid having some browsers left over after
      // the test
      hub.getRegistry().getNewSessionRequests().clear();
      importantOne.quit();
    }
  }

  @AfterClass(alwaysRun = true)
  public void stop() throws Exception {
    hub.stop();
  }
}
public class RemoteProxyInheritanceTest {
  private Registry registry = Registry.newInstance();

  @Test
  public void defaultToRemoteProxy() {
    GridNodeConfiguration nodeConfiguration = new GridNodeConfiguration();
    new JCommander(nodeConfiguration, "-role", "webdriver", "-host", "localhost");
    RegistrationRequest res = RegistrationRequest.build(nodeConfiguration);
    res.getCapabilities().clear();
    RegistrationRequest req = res;

    Map<String, Object> app1 = new HashMap<>();
    GridNodeConfiguration config = new GridNodeConfiguration();
    app1.put(CapabilityType.APPLICATION_NAME, "app1");

    req.addDesiredCapability(app1);
    req.setConfiguration(config);

    // requires Custom1 & Custom1 set in config to work.
    RemoteProxy p = BaseRemoteProxy.getNewInstance(req, registry);
    assertEquals(BaseRemoteProxy.class, p.getClass());
  }

  @Test
  public void existing() {
    Map<String, Object> app1 = new HashMap<>();
    GridNodeConfiguration config = new GridNodeConfiguration();
    app1.put(CapabilityType.APPLICATION_NAME, "app1");
    config.proxy = "org.openqa.grid.plugin.MyRemoteProxy";

    config.custom.put("Custom1", "A");
    config.custom.put("Custom2", "B");

    RegistrationRequest req = new RegistrationRequest();
    req.addDesiredCapability(app1);
    req.setConfiguration(config);

    RemoteProxy p = BaseRemoteProxy.getNewInstance(req, registry);

    assertEquals(p.getClass(), MyRemoteProxy.class);
    MyRemoteProxy myRemoteProxy = (MyRemoteProxy) p;
    assertEquals("A", myRemoteProxy.getCustom1());
    assertEquals("B", myRemoteProxy.getCustom2());
    assertEquals("A", myRemoteProxy.getConfig().custom.get("Custom1"));
    assertEquals("B", myRemoteProxy.getConfig().custom.get("Custom2"));
  }

  @Test(expected = InvalidParameterException.class)
  public void notExisting() {
    Map<String, Object> app1 = new HashMap<>();
    GridNodeConfiguration config = new GridNodeConfiguration();
    app1.put(CapabilityType.APPLICATION_NAME, "app1");
    config.proxy = "I Don't exist";

    RegistrationRequest req = new RegistrationRequest();
    req.addDesiredCapability(app1);
    req.setConfiguration(config);

    BaseRemoteProxy.getNewInstance(req, registry);
  }

  @Test(expected = InvalidParameterException.class)
  public void notExtendingProxyExisting() {
    Map<String, Object> app1 = new HashMap<>();
    GridNodeConfiguration config = new GridNodeConfiguration();
    app1.put(CapabilityType.APPLICATION_NAME, "app1");
    config.proxy = "java.lang.String";

    RegistrationRequest req = new RegistrationRequest();
    req.addDesiredCapability(app1);
    req.setConfiguration(config);

    BaseRemoteProxy.getNewInstance(req, registry);
  }

  // when some mandatory param are missing -> InvalidParameterException
  @Test(expected = InvalidParameterException.class)
  public void badConfig() {
    Map<String, Object> app1 = new HashMap<>();
    GridNodeConfiguration config = new GridNodeConfiguration();
    app1.put(CapabilityType.APPLICATION_NAME, "app1");
    config.proxy = "I Don't exist";

    RegistrationRequest req = new RegistrationRequest();
    req.addDesiredCapability(app1);
    req.setConfiguration(config);

    // requires Custom1 & Custom1 set in config to work.
    BaseRemoteProxy.getNewInstance(req, registry);
  }

  @After
  public void tearDown() {
    registry.stop();
  }
}
 @After
 public void tearDown() {
   registry.stop();
 }