org.openqa.selenium.NoSuchSessionException Java Examples

The following examples show how to use org.openqa.selenium.NoSuchSessionException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LocalNode.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse executeWebDriverCommand(HttpRequest req) {
  // True enough to be good enough
  SessionId id = getSessionId(req.getUri()).map(SessionId::new)
    .orElseThrow(() -> new NoSuchSessionException("Cannot find session: " + req));

  SessionSlot slot = currentSessions.getIfPresent(id);
  if (slot == null) {
    throw new NoSuchSessionException("Cannot find session with id: " + id);
  }

  HttpResponse toReturn = slot.execute(req);
  if (req.getMethod() == DELETE && req.getUri().equals("/session/" + id)) {
    stop(id);
  }
  return toReturn;
}
 
Example #2
Source File: LocalSessionMap.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public Session get(SessionId id) {
  Require.nonNull("Session ID", id);

  Lock readLock = lock.readLock();
  readLock.lock();
  try {
    Session session = knownSessions.get(id);
    if (session == null) {
      throw new NoSuchSessionException("Unable to find session with ID: " + id);
    }

    return session;
  } finally {
    readLock.unlock();
  }
}
 
Example #3
Source File: ProxyCdpIntoGrid.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<Consumer<Message>> apply(String uri, Consumer<Message> downstream) {
  Objects.requireNonNull(uri);
  Objects.requireNonNull(downstream);

  Optional<SessionId> sessionId = HttpSessionId.getSessionId(uri).map(SessionId::new);
  if (!sessionId.isPresent()) {
    return Optional.empty();
  }

  try {
    Session session = sessions.get(sessionId.get());

    HttpClient client = clientFactory.createClient(ClientConfig.defaultConfig().baseUri(session.getUri()));
    WebSocket upstream = client.openSocket(new HttpRequest(GET, uri), new ForwardingListener(downstream));

    return Optional.of(upstream::send);

  } catch (NoSuchSessionException e) {
    LOG.info("Attempt to connect to non-existant session: " + uri);
    return Optional.empty();
  }
}
 
Example #4
Source File: RedisBackedSessionMap.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public URI getUri(SessionId id) throws NoSuchSessionException {
  Require.nonNull("Session ID", id);

  RedisCommands<String, String> commands = connection.sync();

  List<KeyValue<String, String>> rawValues = commands.mget(uriKey(id), capabilitiesKey(id));

  String rawUri = rawValues.get(0).getValueOrElse(null);
  if (rawUri == null) {
    throw new NoSuchSessionException("Unable to find URI for session " + id);
  }

  try {
    return new URI(rawUri);
  } catch (URISyntaxException e) {
    throw new NoSuchSessionException(String.format("Unable to convert session id (%s) to uri: %s", id, rawUri), e);
  }
}
 
Example #5
Source File: FluentLeniumAdapter.java    From sahagin-java with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] captureScreen() {
    if (fluent == null) {
        return null;
    }
    WebDriver driver = fluent.getDriver();
    if (driver == null) {
        return null;
    }
    if (!(driver instanceof TakesScreenshot)) {
        return null;
    }
    try {
        return ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.BYTES);
    } catch (NoSuchSessionException e) {
        // just do nothing if WebDriver instance is in invalid state
        return null;
    }
}
 
Example #6
Source File: WebDriverScreenCaptureAdapter.java    From sahagin-java with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] captureScreen() {
    if (driver == null) {
        return null;
    }
    if (!(driver instanceof TakesScreenshot)) {
        return null;
    }
    try {
        return ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.BYTES);
    } catch (NoSuchSessionException e) {
        // just do nothing if WebDriver instance is in invalid state
        return null;
    }
    // TODO test should not fail when taking screen capture fails?
}
 
Example #7
Source File: OneShotNode.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public void stop(SessionId id) throws NoSuchSessionException {
  LOG.info("Stop has been called: " + id);
  Require.nonNull("Session ID", id);

  if (!isSessionOwner(id)) {
    throw new NoSuchSessionException("Unable to find session " + id);
  }

  LOG.info("Quitting session " + id);
  try {
    driver.quit();
  } catch (Exception e) {
    // It's possible that the driver has already quit.
  }

  events.fire(new SessionClosedEvent(id));
  LOG.info("Firing node drain complete message");
  events.fire(new NodeDrainComplete(getId()));
}
 
Example #8
Source File: SessionMapTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAllowEntriesToBeRemovedByAMessage() {
  local.add(expected);

  bus.fire(new SessionClosedEvent(expected.getId()));

  Wait<SessionMap> wait = new FluentWait<>(local).withTimeout(ofSeconds(2));
  wait.until(sessions -> {
    try {
      sessions.get(expected.getId());
      return false;
    } catch (NoSuchSessionException e) {
      return true;
    }
  });
}
 
Example #9
Source File: JdbcBackedSessionMapTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeAbleToRemoveSessions() throws URISyntaxException {
  SessionMap sessions = getSessionMap();

  Session expected = new Session(
      new SessionId(UUID.randomUUID()),
      new URI("http://example.com/foo"),
      new ImmutableCapabilities("key", "value"));
  sessions.add(expected);

  SessionMap reader = getSessionMap();

  reader.remove(expected.getId());

  try {
    reader.get(expected.getId());
    fail("Oh noes!");
  } catch (NoSuchSessionException ignored) {
    // This is expected
  }
}
 
Example #10
Source File: RedisBackedSessionMapTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeAbleToRemoveSessions() throws URISyntaxException {
  SessionMap sessions = new RedisBackedSessionMap(tracer, uri);

  Session expected = new Session(
    new SessionId(UUID.randomUUID()),
    new URI("http://example.com/foo"),
    new ImmutableCapabilities("cheese", "beyaz peynir"));
  sessions.add(expected);

  SessionMap reader = new RedisBackedSessionMap(tracer, uri);

  reader.remove(expected.getId());

  try {
    reader.get(expected.getId());
    fail("Oh noes!");
  } catch (NoSuchSessionException ignored) {
    // This is expected
  }
}
 
Example #11
Source File: NodeTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void aSessionThatTimesOutWillBeStoppedAndRemovedFromTheSessionMap() {
  AtomicReference<Instant> now = new AtomicReference<>(Instant.now());

  Clock clock = new MyClock(now);
  Node node = LocalNode.builder(tracer, bus, uri, uri, null)
      .add(caps, new TestSessionFactory((id, c) -> new Session(id, uri, c)))
      .sessionTimeout(Duration.ofMinutes(3))
      .advanced()
      .clock(clock)
      .build();
  Session session = node.newSession(createSessionRequest(caps))
      .map(CreateSessionResponse::getSession)
      .orElseThrow(() -> new RuntimeException("Session not created"));

  now.set(now.get().plus(Duration.ofMinutes(5)));

  assertThatExceptionOfType(NoSuchSessionException.class)
      .isThrownBy(() -> node.getSession(session.getId()));
}
 
Example #12
Source File: OneShotNode.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public Session getSession(SessionId id) throws NoSuchSessionException {
  if (!isSessionOwner(id)) {
    throw new NoSuchSessionException("Unable to find session with id: " + id);
  }

  return new Session(
    sessionId,
    getUri(),
    capabilities);
}
 
Example #13
Source File: SessionSlot.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse execute(HttpRequest req) throws UncheckedIOException {
  if (currentSession == null) {
    throw new NoSuchSessionException("No session currently running: " + req.getUri());
  }

  return currentSession.execute(req);
}
 
Example #14
Source File: WebDriverTestCase.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Same as {@link #loadPageWithAlerts2(String)}... but doesn't verify the alerts.
 * @param html the HTML to use
 * @param url the url to use to load the page
 * @param contentType the content type to return
 * @param charset the charset
 * @param serverCharset the charset at the server side.
 * @return the web driver
 * @throws Exception if something goes wrong
 */
protected final WebDriver loadPage2(String html, final URL url,
        final String contentType, final Charset charset, final Charset serverCharset) throws Exception {
    if (useStandards_ != null) {
        if (html.startsWith(HtmlPageTest.STANDARDS_MODE_PREFIX_)) {
            fail("HTML must not be prefixed with Standards Mode.");
        }
        if (useStandards_) {
            html = HtmlPageTest.STANDARDS_MODE_PREFIX_ + html;
        }
    }
    final MockWebConnection mockWebConnection = getMockWebConnection();
    mockWebConnection.setResponse(url, html, contentType, charset);
    startWebServer(mockWebConnection, serverCharset);

    WebDriver driver = getWebDriver();
    if (!(driver instanceof HtmlUnitDriver)) {
        try {
            resizeIfNeeded(driver);
        }
        catch (final NoSuchSessionException e) {
            // maybe the driver was killed by the test before; setup a new one
            shutDownRealBrowsers();

            driver = getWebDriver();
            resizeIfNeeded(driver);
        }
    }
    driver.get(url.toExternalForm());

    return driver;
}
 
Example #15
Source File: RemoteNode.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public Session getSession(SessionId id) throws NoSuchSessionException {
  Require.nonNull("Session ID", id);

  HttpRequest req = new HttpRequest(GET, "/se/grid/node/session/" + id);
  HttpTracing.inject(tracer, tracer.getCurrentContext(), req);

  HttpResponse res = client.execute(req);

  return Values.get(res, Session.class);
}
 
Example #16
Source File: LocalNode.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public void stop(SessionId id) throws NoSuchSessionException {
  Require.nonNull("Session ID", id);

  SessionSlot slot = currentSessions.getIfPresent(id);
  if (slot == null) {
    throw new NoSuchSessionException("Cannot find session with id: " + id);
  }

  killSession(slot);
  tempFileSystems.invalidate(id);
}
 
Example #17
Source File: RemoteNode.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public void stop(SessionId id) throws NoSuchSessionException {
  Require.nonNull("Session ID", id);
  HttpRequest req = new HttpRequest(DELETE, "/se/grid/node/session/" + id);
  HttpTracing.inject(tracer, tracer.getCurrentContext(), req);

  HttpResponse res = client.execute(req);

  Values.get(res, Void.class);
}
 
Example #18
Source File: AddingNodesTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public Session getSession(SessionId id) throws NoSuchSessionException {
  if (running == null || !running.getId().equals(id)) {
    throw new NoSuchSessionException();
  }

  return running;
}
 
Example #19
Source File: HandleSession.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse execute(HttpRequest req) {
  try (Span span = HttpTracing.newSpanAsChildOf(tracer, req, "router.handle_session")) {
    HTTP_REQUEST.accept(span, req);

    SessionId id = getSessionId(req.getUri()).map(SessionId::new)
      .orElseThrow(() -> new NoSuchSessionException("Cannot find session: " + req));

    SESSION_ID.accept(span, id);

    try {
      HttpTracing.inject(tracer, span, req);
      HttpResponse res = knownSessions.get(id, loadSessionId(tracer, span, id)).execute(req);

      HTTP_RESPONSE.accept(span, res);

      return res;
    } catch (ExecutionException e) {
      span.setAttribute("error", true);
      span.setAttribute("error.message", e.getMessage());

      Throwable cause = e.getCause();
      if (cause instanceof RuntimeException) {
        throw (RuntimeException) cause;
      }
      throw new RuntimeException(cause);
    }
  }
}
 
Example #20
Source File: ResultConfig.java    From selenium with Apache License 2.0 5 votes vote down vote up
private void throwUpIfSessionTerminated(SessionId sessId) throws NoSuchSessionException {
  if (sessId == null) return;
  Session session = sessions.get(sessId);
  final boolean isTerminated = session == null;
  if (isTerminated) {
    throw new NoSuchSessionException();
  }
}
 
Example #21
Source File: SessionSlot.java    From selenium with Apache License 2.0 5 votes vote down vote up
public ActiveSession getSession() {
  if (isAvailable()) {
    throw new NoSuchSessionException("Session is not running");
  }

  return currentSession;
}
 
Example #22
Source File: AddingNodesTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public void stop(SessionId id) throws NoSuchSessionException {
  getSession(id);
  running = null;

  bus.fire(new SessionClosedEvent(id));
}
 
Example #23
Source File: SessionMapTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAllowSessionsToBeRemoved() {
  local.add(expected);

  assertEquals(expected, remote.get(id));

  remote.remove(id);

  assertThatExceptionOfType(NoSuchSessionException.class).isThrownBy(() -> local.get(id));
  assertThatExceptionOfType(NoSuchSessionException.class).isThrownBy(() -> remote.get(id));
}
 
Example #24
Source File: NodeTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void sessionsThatAreStoppedWillNotBeReturned() {
  Session expected = node.newSession(createSessionRequest(caps))
      .map(CreateSessionResponse::getSession)
      .orElseThrow(() -> new RuntimeException("Session not created"));

  node.stop(expected.getId());

  assertThatExceptionOfType(NoSuchSessionException.class)
      .isThrownBy(() -> local.getSession(expected.getId()));

  assertThatExceptionOfType(NoSuchSessionException.class)
      .isThrownBy(() -> node.getSession(expected.getId()));
}
 
Example #25
Source File: NodeTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void stoppingASessionThatDoesNotExistWillThrowAnException() {
  assertThatExceptionOfType(NoSuchSessionException.class)
      .isThrownBy(() -> local.stop(new SessionId(UUID.randomUUID())));

  assertThatExceptionOfType(NoSuchSessionException.class)
      .isThrownBy(() -> node.stop(new SessionId(UUID.randomUUID())));
}
 
Example #26
Source File: NodeTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void attemptingToGetASessionThatDoesNotExistWillCauseAnExceptionToBeThrown() {
  assertThatExceptionOfType(NoSuchSessionException.class)
      .isThrownBy(() -> local.getSession(new SessionId(UUID.randomUUID())));

  assertThatExceptionOfType(NoSuchSessionException.class)
      .isThrownBy(() -> node.getSession(new SessionId(UUID.randomUUID())));
}
 
Example #27
Source File: ExceptionHandlerTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSetErrorCodeForJsonWireProtocol() {
  Exception e = new NoSuchSessionException("This does not exist");
  HttpResponse response = new ExceptionHandler(e).execute(new HttpRequest(HttpMethod.POST, "/session"));

  assertEquals(HTTP_INTERNAL_ERROR, response.getStatus());

  Map<String, Object> err = new Json().toType(string(response), MAP_TYPE);
  assertEquals(ErrorCodes.NO_SUCH_SESSION, ((Number) err.get("status")).intValue());
}
 
Example #28
Source File: WebDriverTestCase.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Same as {@link #loadPage2(String, URL)}, but with additional servlet configuration.
 * @param html the HTML to use for the default page
 * @param url the URL to use to load the page
 * @param servlets the additional servlets to configure with their mapping
 * @return the web driver
 * @throws Exception if something goes wrong
 */
protected final WebDriver loadPage2(final String html, final URL url,
        final Map<String, Class<? extends Servlet>> servlets) throws Exception {

    servlets.put("/*", MockWebConnectionServlet.class);
    getMockWebConnection().setResponse(url, html);
    MockWebConnectionServlet.MockConnection_ = getMockWebConnection();

    startWebServer("./", null, servlets);

    WebDriver driver = getWebDriver();
    if (!(driver instanceof HtmlUnitDriver)) {
        try {
            resizeIfNeeded(driver);
        }
        catch (final NoSuchSessionException e) {
            // maybe the driver was killed by the test before; setup a new one
            shutDownRealBrowsers();

            driver = getWebDriver();
            resizeIfNeeded(driver);
        }
    }
    driver.get(url.toExternalForm());

    return driver;
}
 
Example #29
Source File: IOSDeviceActions.java    From coteafs-appium with Apache License 2.0 5 votes vote down vote up
/**
 * @param strategy
 * @param keyName
 * @author wasiq.bhamla
 * @since 08-May-2017 3:21:20 PM
 */
public void hideKeyboard(final String strategy, final String keyName) {
    log.info("Hiding keyboard on device using %s strategy for key {}...", strategy, keyName);
    try {
        if (this.driver.isKeyboardShown()) {
            this.driver.hideKeyboard(strategy, keyName);
        }
    } catch (final NoSuchSessionException e) {
        fail(AppiumServerStoppedError.class, SERVER_STOPPED, e);
    }
}
 
Example #30
Source File: AndroidDeviceActions.java    From coteafs-appium with Apache License 2.0 5 votes vote down vote up
private void perform(final String message, final Consumer<AndroidDriver<MobileElement>> action,
    final Object... args) {
    LOG.info(message, args);
    try {
        action.accept(this.driver);
    } catch (final NoSuchSessionException e) {
        fail(AppiumServerStoppedError.class, SERVER_STOPPED, e);
    }
}