org.openqa.selenium.remote.SessionId Java Examples

The following examples show how to use org.openqa.selenium.remote.SessionId. 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: AllHandlers.java    From selenium with Apache License 2.0 6 votes vote down vote up
public AllHandlers(NewSessionPipeline pipeline, ActiveSessions allSessions) {
  this.allSessions = Require.nonNull("Active sessions", allSessions);
  this.json = new Json();

  this.additionalHandlers = ImmutableMap.of(
      HttpMethod.DELETE, ImmutableList.of(),
      HttpMethod.GET, ImmutableList.of(
          handler("/session/{sessionId}/log/types",
                  params -> new GetLogTypes(json, allSessions.get(new SessionId(params.get("sessionId"))))),
          handler("/sessions", params -> new GetAllSessions(allSessions, json)),
          handler("/status", params -> new Status(json))
      ),
      HttpMethod.POST, ImmutableList.of(
          handler("/session", params -> new BeginSession(pipeline, allSessions, json)),
          handler("/session/{sessionId}/file",
                  params -> new UploadFile(json, allSessions.get(new SessionId(params.get("sessionId"))))),
          handler("/session/{sessionId}/log",
                  params -> new GetLogsOfType(json, allSessions.get(new SessionId(params.get("sessionId"))))),
          handler("/session/{sessionId}/se/file",
                  params -> new UploadFile(json, allSessions.get(new SessionId(params.get("sessionId")))))
      ));
}
 
Example #2
Source File: JsonOutputTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeAbleToConvertACommand() {
  SessionId sessionId = new SessionId("some id");
  String commandName = "some command";
  Map<String, Object> parameters = new HashMap<>();
  parameters.put("param1", "value1");
  parameters.put("param2", "value2");
  Command command = new Command(sessionId, commandName, parameters);

  String json = convert(command);

  JsonObject converted = new JsonParser().parse(json).getAsJsonObject();

  assertThat(converted.has("sessionId")).isTrue();
  JsonPrimitive sid = converted.get("sessionId").getAsJsonPrimitive();
  assertThat(sid.getAsString()).isEqualTo(sessionId.toString());

  assertThat(commandName).isEqualTo(converted.get("name").getAsString());

  assertThat(converted.has("parameters")).isTrue();
  JsonObject pars = converted.get("parameters").getAsJsonObject();
  assertThat(pars.entrySet()).hasSize(2);
  assertThat(pars.get("param1").getAsString()).isEqualTo(parameters.get("param1"));
  assertThat(pars.get("param2").getAsString()).isEqualTo(parameters.get("param2"));
}
 
Example #3
Source File: JsonOutputTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldConvertAProxyCorrectly() {
  Proxy proxy = new Proxy();
  proxy.setHttpProxy("localhost:4444");

  MutableCapabilities caps = new DesiredCapabilities("foo", "1", Platform.LINUX);
  caps.setCapability(CapabilityType.PROXY, proxy);
  Map<String, ?> asMap = ImmutableMap.of("desiredCapabilities", caps);
  Command command = new Command(new SessionId("empty"), DriverCommand.NEW_SESSION, asMap);

  String json = convert(command.getParameters());

  JsonObject converted = new JsonParser().parse(json).getAsJsonObject();
  JsonObject capsAsMap = converted.get("desiredCapabilities").getAsJsonObject();

  assertThat(capsAsMap.get(CapabilityType.PROXY).getAsJsonObject().get("httpProxy").getAsString())
      .isEqualTo(proxy.getHttpProxy());
}
 
Example #4
Source File: WebDriverServletTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void handlesWellFormedAndSuccessfulCrossDomainRpcs()
    throws IOException, ServletException {
  final SessionId sessionId = createSession();

  WebDriver driver = testSessions.get(sessionId).getWrappedDriver();

  Map<String, Object> json = ImmutableMap.of(
      "method", "POST",
      "path", String.format("/session/%s/url", sessionId),
      "data", ImmutableMap.of("url", "http://www.google.com"));
  FakeHttpServletResponse response = sendCommand("POST", "/xdrpc", json);

  verify(driver).get("http://www.google.com");
  assertEquals(HttpServletResponse.SC_OK, response.getStatus());
  assertEquals("application/json; charset=utf-8",
               response.getHeader("content-type"));

  Map<String, Object> jsonResponse = this.json.toType(response.getBody(), MAP_TYPE);
  assertEquals(ErrorCodes.SUCCESS, ((Number) jsonResponse.get("status")).intValue());
  assertEquals(sessionId.toString(), jsonResponse.get("sessionId"));
  assertNull(jsonResponse.get("value"));
}
 
Example #5
Source File: AddingNodesTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeAbleToRegisterACustomNode() throws URISyntaxException {
  URI sessionUri = new URI("http://example:1234");
  Node node = new CustomNode(
      bus,
      UUID.randomUUID(),
      externalUrl.toURI(),
      c -> new Session(new SessionId(UUID.randomUUID()), sessionUri, c));
  handler.addHandler(node);

  distributor.add(node);

  wait.until(obj -> distributor.getStatus().hasCapacity());

  DistributorStatus.NodeSummary summary = getOnlyElement(distributor.getStatus().getNodes());
  assertEquals(1, summary.getStereotypes().get(CAPS).intValue());
}
 
Example #6
Source File: JsonTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeAbleToConvertACommand() {
  SessionId sessionId = new SessionId("session id");
  Command original = new Command(
      sessionId,
      DriverCommand.NEW_SESSION,
      ImmutableMap.of("food", "cheese"));
  String raw = new Json().toJson(original);
  Command converted = new Json().toType(raw, Command.class);

  assertThat(converted.getSessionId().toString()).isEqualTo(sessionId.toString());
  assertThat(converted.getName()).isEqualTo(original.getName());

  assertThat(converted.getParameters().keySet()).hasSize(1);
  assertThat(converted.getParameters().get("food")).isEqualTo("cheese");
}
 
Example #7
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 #8
Source File: IDriverPool.java    From carina with Apache License 2.0 6 votes vote down vote up
/**
 * Get driver by WebElement.
 * 
 * @param sessionId
 *            - session id to be used for searching a desired driver
 * 
 * @return default WebDriver
 */
public static WebDriver getDriver(SessionId sessionId) {
    for (CarinaDriver carinaDriver : driversPool) {
        WebDriver drv = carinaDriver.getDriver();
        if (drv instanceof EventFiringWebDriver) {
            EventFiringWebDriver eventFirDriver = (EventFiringWebDriver) drv;
            drv = eventFirDriver.getWrappedDriver();
        }

        SessionId drvSessionId = ((RemoteWebDriver) drv).getSessionId();

        if (drvSessionId != null) {
            if (sessionId.equals(drvSessionId)) {
                return drv;
            }
        }
    }
    throw new DriverPoolException("Unable to find driver using sessionId artifacts. Returning default one!");
}
 
Example #9
Source File: SessionLogsToFileRepository.java    From selenium with Apache License 2.0 6 votes vote down vote up
/**
 * This returns the log records storied in the corresponding log file. This does *NOT* clear the
 * log records in the file.
 *
 * @param sessionId session-id for which the file logs needs to be returned.
 * @return A List of LogRecord objects, which can be <i>null</i>.
 * @throws IOException IO exception can occur with reading the log file
 */
public List<LogRecord> getLogRecords(SessionId sessionId) throws IOException {
  LogFile logFile = sessionToLogFileMap.get(sessionId);
  if (logFile == null) {
    return new ArrayList<>();
  }

  List<LogRecord> logRecords = new ArrayList<>();
  try {
    logFile.openLogReader();
    ObjectInputStream logObjInStream = logFile.getLogReader();
    LogRecord tmpLogRecord;
    while (null != (tmpLogRecord = (LogRecord) logObjInStream
        .readObject())) {
      logRecords.add(tmpLogRecord);
    }
  } catch (IOException | ClassNotFoundException ex) {
    logFile.closeLogReader();
    return logRecords;
  }
  logFile.closeLogReader();
  return logRecords;
}
 
Example #10
Source File: GridInfoExtractor.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
public static String[] getHostNameAndPort(String hostName, int port, SessionId session) {
    String[] hostAndPort = new String[2];
    String errorMsg = "Failed to acquire remote webdriver node and port info. Root cause: \n";

    try {
        HttpHost host = new HttpHost(hostName, port);
        CloseableHttpClient client = HttpClients.createSystem();
        URL sessionURL = new URL("http://" + hostName + ":" + port + "/grid/api/testsession?session=" + session);
        BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm());
        HttpResponse response = client.execute(host, r);
        String url = extractUrlFromResponse(response);
        if (url != null) {
            URL myURL = new URL(url);
            if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {
                hostAndPort[0] = myURL.getHost();
                hostAndPort[1] = Integer.toString(myURL.getPort());
            }
        }
    } catch (Exception e) {
        Logger.getLogger(GridInfoExtractor.class.getName()).log(Level.SEVERE, null, errorMsg + e);
    }
    return hostAndPort;
}
 
Example #11
Source File: ProxyCdpTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldForwardTextMessageToServer() throws URISyntaxException, InterruptedException {
  HttpClient.Factory clientFactory = HttpClient.Factory.createDefault();

  // Create a backend server which will capture any incoming text message
  AtomicReference<String> text = new AtomicReference<>();
  CountDownLatch latch = new CountDownLatch(1);
  Server<?> backend = createBackendServer(latch, text, "");

  // Push a session that resolves to the backend server into the session map
  SessionId id = new SessionId(UUID.randomUUID());
  sessions.add(new Session(id, backend.getUrl().toURI(), new ImmutableCapabilities()));

  // Now! Send a message. We expect it to eventually show up in the backend
  WebSocket socket = clientFactory.createClient(proxyServer.getUrl())
    .openSocket(new HttpRequest(GET, String.format("/session/%s/cdp", id)), new WebSocket.Listener(){});

  socket.sendText("Cheese!");

  assertThat(latch.await(5, SECONDS)).isTrue();
  assertThat(text.get()).isEqualTo("Cheese!");

  socket.close();
}
 
Example #12
Source File: JsonHttpCommandCodecTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void whenDecodingAnHttpRequestDoesNotRecreateWebElements() {
  Command command = new Command(
      new SessionId("1234567"),
      DriverCommand.EXECUTE_SCRIPT,
      ImmutableMap.of(
          "script", "",
          "args", Arrays.asList(ImmutableMap.of(OSS.getEncodedElementKey(), "67890"))));

  HttpRequest request = codec.encode(command);

  Command decoded = codec.decode(request);

  List<?> args = (List<?>) decoded.getParameters().get("args");

  Map<? ,?> element = (Map<?, ?>) args.get(0);
  assertThat(element.get(OSS.getEncodedElementKey())).isEqualTo("67890");
}
 
Example #13
Source File: ServicedSession.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
protected ServicedSession newActiveSession(
    DriverService service,
    Dialect downstream,
    Dialect upstream,
    HttpHandler codec,
    SessionId id,
    Map<String, Object> capabilities) {
  return new ServicedSession(
      service,
      downstream,
      upstream,
      codec,
      id,
      capabilities);
}
 
Example #14
Source File: JdbcBackedSessionMapTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void canCreateAJdbcBackedSessionMap() 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();

  Session seen = reader.get(expected.getId());

  assertThat(seen).isEqualTo(expected);
}
 
Example #15
Source File: NodeStatus.java    From selenium with Apache License 2.0 5 votes vote down vote up
private static Active fromJson(Map<String, Object> raw) {
  SessionId id = new SessionId((String) raw.get("sessionId"));
  Capabilities stereotype = new ImmutableCapabilities((Map<?, ?>) raw.get("stereotype"));
  Capabilities current = new ImmutableCapabilities((Map<?, ?>) raw.get("currentCapabilities"));

  return new Active(stereotype, id, current);
}
 
Example #16
Source File: RemoteSessionMap.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public URI getUri(SessionId id) throws NoSuchSessionException {
  Require.nonNull("Session ID", id);

  URI value = makeRequest(new HttpRequest(GET, "/se/grid/session/" + id + "/uri"), URI.class);
  if (value == null) {
    throw new NoSuchSessionException("Unable to find session with ID: " + id);
  }
  return value;
}
 
Example #17
Source File: LocalSessionMap.java    From selenium with Apache License 2.0 5 votes vote down vote up
public LocalSessionMap(Tracer tracer, EventBus bus) {
  super(tracer);

  this.bus = Require.nonNull("Event bus", bus);

  bus.addListener(SESSION_CLOSED, event -> {
    SessionId id = event.getData(SessionId.class);
    knownSessions.remove(id);
  });
}
 
Example #18
Source File: RemoteSessionMap.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public Session get(SessionId id) {
  Require.nonNull("Session ID", id);

  Session session = makeRequest(new HttpRequest(GET, "/se/grid/session/" + id), Session.class);
  if (session == null) {
    throw new NoSuchSessionException("Unable to find session with ID: " + id);
  }
  return session;
}
 
Example #19
Source File: JdbcBackedSessionMap.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public void remove(SessionId id) {
  Require.nonNull("Session ID", id);

  try (PreparedStatement statement = getDeleteSqlForSession(id)) {
    statement.executeUpdate();
  } catch (SQLException e) {
    throw new JdbcException(e.getMessage());
  }
}
 
Example #20
Source File: JdbcBackedSessionMap.java    From selenium with Apache License 2.0 5 votes vote down vote up
private PreparedStatement readSessionStatement(SessionId sessionId) throws SQLException {
  PreparedStatement getSessionsStatement = connection.prepareStatement(
    String.format("select * from %1$s where %2$s = ?",
      TABLE_NAME,
      SESSION_ID_COL));

  getSessionsStatement.setMaxRows(1);
  getSessionsStatement.setString(1, sessionId.toString());

  return getSessionsStatement;
}
 
Example #21
Source File: ActiveSessionsTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void canAddNewSessionAndRetrieveById() {
  ActiveSessions sessions = new ActiveSessions(10, MINUTES);

  ActiveSession session = Mockito.mock(ActiveSession.class);
  SessionId id = new SessionId("1234567890");
  Mockito.when(session.getId()).thenReturn(id);

  sessions.put(session);

  assertEquals(session, sessions.get(id));
}
 
Example #22
Source File: Responses.java    From selenium with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a response object for a successful command execution.
 *
 * @param sessionId ID of the session that executed the command.
 * @param value the command result value.
 * @return the new response object.
 */
public static Response success(SessionId sessionId, Object value) {
  Response response = new Response();
  response.setSessionId(sessionId != null ? sessionId.toString() : null);
  response.setValue(value);
  response.setStatus(ErrorCodes.SUCCESS);
  response.setState(ErrorCodes.SUCCESS_STRING);
  return response;
}
 
Example #23
Source File: UploadFileTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldThrowAnExceptionIfMoreThanOneFileIsSent() throws Exception {
  ActiveSession session = mock(ActiveSession.class);
  when(session.getId()).thenReturn(new SessionId("1234567"));
  when(session.getFileSystem()).thenReturn(tempFs);
  when(session.getDownstreamDialect()).thenReturn(Dialect.OSS);

  File baseDir = Files.createTempDir();
  touch(baseDir, "example");
  touch(baseDir, "unwanted");
  String encoded = Zip.zip(baseDir);

  UploadFile uploadFile = new UploadFile(new Json(), session);
  Map<String, Object> args = ImmutableMap.of("file", encoded);
  HttpRequest request = new HttpRequest(HttpMethod.POST, "/session/%d/se/file");
  request.setContent(asJson(args));
  HttpResponse response = uploadFile.execute(request);

  try {
    new ErrorHandler(false).throwIfResponseFailed(
        new Json().toType(string(response), Response.class),
        100);
    fail("Should not get this far");
  } catch (WebDriverException ignored) {
    // Expected
  }
}
 
Example #24
Source File: JdbcBackedSessionMap.java    From selenium with Apache License 2.0 5 votes vote down vote up
public JdbcBackedSessionMap(Tracer tracer, Connection jdbcConnection, EventBus bus)  {
  super(tracer);

  Require.nonNull("JDBC Connection Object", jdbcConnection);
  this.bus = Require.nonNull("Event bus", bus);

  this.connection = jdbcConnection;
  this.bus.addListener(SESSION_CLOSED, event -> {
    SessionId id = event.getData(SessionId.class);
    remove(id);
  });
}
 
Example #25
Source File: ServicedSession.java    From selenium with Apache License 2.0 5 votes vote down vote up
public ServicedSession(
    DriverService service,
    Dialect downstream,
    Dialect upstream,
    HttpHandler codec,
    SessionId id,
    Map<String, Object> capabilities) {
  super(downstream, upstream, codec, id, capabilities);

  this.service = service;

  new JMXHelper().register(this);
}
 
Example #26
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 #27
Source File: JdbcBackedSessionMapTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test(expected = JdbcException.class)
public void shouldThrowNoSuchSessionExceptionIfTableDoesNotExist() throws SQLException {
  Connection connection2 = DriverManager.getConnection("jdbc:hsqldb:mem:testdb2", "SA", "");

  SessionMap sessions = new JdbcBackedSessionMap(tracer, connection2, bus);

  sessions.get(new SessionId(UUID.randomUUID()));
}
 
Example #28
Source File: PerSessionLogHandler.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void publish(LogRecord record) {
  ThreadKey threadId = new ThreadKey();
  SessionId sessionId = threadToSessionMap.get(threadId);

  if (sessionId != null) {
    List<LogRecord> records = perSessionRecords.get(sessionId);
    if (records == null) {
      records = new ArrayList<>();
    }
    records.add(record);
    perSessionRecords.put(sessionId, records);

    if (records.size() > capacity) {
      perSessionRecords.put(sessionId, new ArrayList<>());
      // flush records to file;
      try {
        logFileRepository.flushRecordsToLogFile(sessionId, records);
        // clear in memory session records
        records.clear();
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  } else {
    perThreadTempRecords.computeIfAbsent(threadId, k -> new ArrayList<>()).add(record);
  }
}
 
Example #29
Source File: PerSessionLogHandler.java    From selenium with Apache License 2.0 5 votes vote down vote up
/**
 * Removes session logs for the given session id.
 *
 * NB! If the handler has been configured to capture logs on quit no logs will be removed.
 *
 * @param sessionId The session id to use.
 */
public synchronized void removeSessionLogs(SessionId sessionId) {
  if (storeLogsOnSessionQuit) {
    return;
  }
  ThreadKey threadId = sessionToThreadMap.get(sessionId);
  SessionId sessionIdForThread = threadToSessionMap.get(threadId);
  if (threadId != null && sessionIdForThread != null && sessionIdForThread.equals(sessionId)) {
    threadToSessionMap.remove(threadId);
    sessionToThreadMap.remove(sessionId);
  }
  perSessionRecords.remove(sessionId);
  logFileRepository.removeLogFile(sessionId);
}
 
Example #30
Source File: RemoteSession.java    From selenium with Apache License 2.0 5 votes vote down vote up
protected abstract ActiveSession newActiveSession(
X additionalData,
Dialect downstream,
Dialect upstream,
HttpHandler codec,
SessionId id,
Map<String, Object> capabilities);