org.openqa.selenium.remote.http.HttpResponse Java Examples

The following examples show how to use org.openqa.selenium.remote.http.HttpResponse. 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: ProtocolHandshakeTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void requestShouldIncludeJsonWireProtocolCapabilities() throws IOException {
  Map<String, Object> params = singletonMap("desiredCapabilities", new ImmutableCapabilities());
  Command command = new Command(null, DriverCommand.NEW_SESSION, params);

  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(utf8String(
      "{\"value\": {\"sessionId\": \"23456789\", \"capabilities\": {}}}"));
  RecordingHttpClient client = new RecordingHttpClient(response);

  new ProtocolHandshake().createSession(client, command);

  Map<String, Object> json = getRequestPayloadAsMap(client);

  assertThat(json.get("desiredCapabilities")).isEqualTo(EMPTY_MAP);
}
 
Example #2
Source File: ContainerExists.java    From selenium with Apache License 2.0 6 votes vote down vote up
boolean apply(ContainerId id) {
  Require.nonNull("Container id", id);

  Map<String, Object> filters = ImmutableMap.of("id", ImmutableSet.of(id));

  HttpResponse res = throwIfNecessary(
    client.execute(
      new HttpRequest(GET, "/v1.40/containers/json")
        .addHeader("Content-Length", "0")
        .addHeader("Content-Type", JSON_UTF_8)
        .addQueryParameter("filters", JSON.toJson(filters))
    ),
    "Unable to list container %s",
    id);

  List<?> allContainers = JSON.toType(Contents.string(res), List.class);
  return !allContainers.isEmpty();
}
 
Example #3
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 #4
Source File: DriverServiceSessionFactoryTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInstantiateSessionIfEverythingIsOK() throws IOException {
  HttpClient httpClient = mock(HttpClient.class);
  when(httpClient.execute(any(HttpRequest.class))).thenReturn(
      new HttpResponse().setStatus(200).setContent(() -> new ByteArrayInputStream(
          "{ \"value\": { \"sessionId\": \"1\", \"capabilities\": {} } }".getBytes())));
  when(clientFactory.createClient(any(URL.class))).thenReturn(httpClient);

  DriverServiceSessionFactory factory = factoryFor("chrome", builder);

  Optional<ActiveSession> session = factory.apply(new CreateSessionRequest(
      ImmutableSet.of(Dialect.W3C), toPayload("chrome"), ImmutableMap.of()));

  assertThat(session).isNotEmpty();

  verify(builder, times(1)).build();
  verifyNoMoreInteractions(builder);
  verify(driverService, times(1)).start();
  verify(driverService, atLeastOnce()).getUrl();
  verifyNoMoreInteractions(driverService);
}
 
Example #5
Source File: OneShotNode.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse executeWebDriverCommand(HttpRequest req) {
  LOG.info("Executing " + req);

  HttpResponse res = client.execute(req);

  if (DELETE.equals(req.getMethod()) && req.getUri().equals("/session/" + sessionId)) {
    // Ensure the response is sent before we viciously kill the node

    new Thread(
      () -> {
        try {
          Thread.sleep(500);
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
          throw new RuntimeException(e);
        }
        LOG.info("Stopping session: " + sessionId);
        stop(sessionId);
      },
      "Node clean up: " + getId())
    .start();
  }

  return res;
}
 
Example #6
Source File: JettyServerTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void exceptionsThrownByHandlersAreConvertedToAProperPayload() {
  Server<?> server = new JettyServer(
    emptyOptions,
    req -> {
      throw new UnableToSetCookieException("Yowza");
    });

  server.start();
  URL url = server.getUrl();
  HttpClient client = HttpClient.Factory.createDefault().createClient(url);
  HttpResponse response = client.execute(new HttpRequest(GET, "/status"));

  assertThat(response.getStatus()).isEqualTo(HTTP_INTERNAL_ERROR);

  Throwable thrown = null;
  try {
    thrown = ErrorCodec.createDefault().decode(new Json().toType(string(response), MAP_TYPE));
  } catch (IllegalArgumentException ignored) {
    fail("Apparently the command succeeded" + string(response));
  }

  assertThat(thrown).isInstanceOf(UnableToSetCookieException.class);
  assertThat(thrown.getMessage()).startsWith("Yowza");
}
 
Example #7
Source File: NoSessionHandler.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse execute(HttpRequest req) throws UncheckedIOException {
  // We're not using ImmutableMap for the outer map because it disallows null values.
  Map<String, Object> responseMap = new HashMap<>();
  responseMap.put("sessionId", sessionId.toString());
  responseMap.put("status", NO_SUCH_SESSION);
  responseMap.put("value", ImmutableMap.of(
      "error", "invalid session id",
      "message", String.format("No active session with ID %s", sessionId),
      "stacktrace", ""));
  responseMap = Collections.unmodifiableMap(responseMap);

  byte[] payload = json.toJson(responseMap).getBytes(UTF_8);

  return new HttpResponse().setStatus(HTTP_NOT_FOUND)
    .setHeader("Content-Type", JSON_UTF_8.toString())
    .setContent(bytes(payload));
}
 
Example #8
Source File: EndToEndTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAllowPassthroughForW3CMode() {
  HttpRequest request = new HttpRequest(POST, "/session");
  request.setContent(asJson(
      ImmutableMap.of(
          "capabilities", ImmutableMap.of(
              "alwaysMatch", ImmutableMap.of("browserName", "cheese")))));

  HttpClient client = clientFactory.createClient(server.getUrl());
  HttpResponse response = client.execute(request);

  assertEquals(200, response.getStatus());

  Map<String, Object> topLevel = json.toType(string(response), MAP_TYPE);

  // There should not be a numeric status field
  assertFalse(string(request), topLevel.containsKey("status"));

  // And the value should have all the good stuff in it: the session id and the capabilities
  Map<?, ?> value = (Map<?, ?>) topLevel.get("value");
  assertThat(value.get("sessionId")).isInstanceOf(String.class);

  Map<?, ?> caps = (Map<?, ?>) value.get("capabilities");
  assertEquals("cheese", caps.get("browserName"));
}
 
Example #9
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void convertsResponses_failure() {
  Response response = new Response();
  response.setStatus(ErrorCodes.NO_SUCH_ELEMENT);
  response.setValue(ImmutableMap.of("color", "red"));

  HttpResponse converted = codec.encode(HttpResponse::new, response);
  assertThat(converted.getStatus()).isEqualTo(HTTP_INTERNAL_ERROR);
  assertThat(converted.getHeader(CONTENT_TYPE)).isEqualTo(JSON_UTF_8.toString());

  Response rebuilt = new Json().toType(string(converted), Response.class);

  assertThat(rebuilt.getStatus()).isEqualTo(response.getStatus());
  assertThat(rebuilt.getState()).isEqualTo(new ErrorCodes().toState(response.getStatus()));
  assertThat(rebuilt.getSessionId()).isEqualTo(response.getSessionId());
  assertThat(rebuilt.getValue()).isEqualTo(response.getValue());
}
 
Example #10
Source File: SessionMapServer.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
protected void execute(Config config) {
  SessionMapOptions sessionMapOptions = new SessionMapOptions(config);
  SessionMap sessions = sessionMapOptions.getSessionMap();

  BaseServerOptions serverOptions = new BaseServerOptions(config);

  Server<?> server = new NettyServer(serverOptions, Route.combine(
    sessions,
    get("/status").to(() -> req ->
      new HttpResponse()
        .addHeader("Content-Type", JSON_UTF_8)
        .setContent(asJson(
          ImmutableMap.of("value", ImmutableMap.of(
            "ready", true,
            "message", "Session map is ready."))))),
    get("/readyz").to(() -> req -> new HttpResponse().setStatus(HTTP_NO_CONTENT))));
  server.start();

  BuildInfo info = new BuildInfo();
  LOG.info(String.format(
    "Started Selenium session map %s (revision %s): %s",
    info.getReleaseLabel(),
    info.getBuildRevision(),
    server.getUrl()));
}
 
Example #11
Source File: ActiveSessionCommandExecutor.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public Response execute(Command command) throws IOException {
  if (DriverCommand.NEW_SESSION.equals(command.getName())) {
    if (active) {
      throw new WebDriverException("Cannot start session twice! " + session);
    }

    active = true;

    // We already have a running session.
    Response response = new Response(session.getId());
    response.setValue(session.getCapabilities());
    return response;
  }

  // The command is about to be sent to the session, which expects it to be
  // encoded as if it has come from the downstream end, not the upstream end.
  HttpRequest request = session.getDownstreamDialect().getCommandCodec().encode(command);

  HttpResponse httpResponse = session.execute(request);

  return session.getDownstreamDialect().getResponseCodec().decode(httpResponse);
}
 
Example #12
Source File: HttpClientTestBase.java    From selenium with Apache License 2.0 6 votes vote down vote up
private HttpResponse getQueryParameterResponse(HttpRequest request) throws Exception {
  return executeWithinServer(
      request,
      new HttpServlet() {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
          try (Writer writer = resp.getWriter()) {
            JsonOutput json = new Json().newOutput(writer);
            json.beginObject();
            req.getParameterMap()
                .forEach((key, value) -> {
                  json.name(key);
                  json.beginArray();
                  Stream.of(value).forEach(json::write);
                  json.endArray();
                });
            json.endObject();
          }
        }
      });
}
 
Example #13
Source File: HttpClientTestBase.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldIncludeAUserAgentHeader() throws Exception {
  HttpResponse response = executeWithinServer(
      new HttpRequest(GET, "/foo"),
      new HttpServlet() {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
          try (Writer writer = resp.getWriter()) {
            writer.write(req.getHeader("user-agent"));
          }
        }
      });


  String label = new BuildInfo().getReleaseLabel();
  Platform platform = Platform.getCurrent();
  Platform family = platform.family() == null ? platform : platform.family();

  assertThat(string(response)).isEqualTo(String.format(
      "selenium/%s (java %s)",
      label,
      family.toString().toLowerCase()));
}
 
Example #14
Source File: WebSocketServingTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldStillBeAbleToServeHttpTraffic() {
  server = new NettyServer(
    defaultOptions(),
    req -> new HttpResponse().setContent(utf8String("Brie!")),
    (uri, sink) -> {
      if ("/foo".equals(uri)) {
        return Optional.of(msg -> sink.accept(new TextMessage("Peas!")));
      }
      return Optional.empty();
    }).start();

  HttpClient client = HttpClient.Factory.createDefault().createClient(server.getUrl());
  HttpResponse res = client.execute(new HttpRequest(GET, "/cheese"));

  assertThat(Contents.string(res)).isEqualTo("Brie!");
}
 
Example #15
Source File: W3CHttpResponseCodecTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void decodingAnErrorWithoutAStacktraceIsDecodedProperlyForNonCompliantImplementations() {
  Map<String, Object> error = new HashMap<>();
  error.put("error", "unsupported operation");  // 500
  error.put("message", "I like peas");
  error.put("stacktrace", "");

  HttpResponse response = createValidResponse(HTTP_INTERNAL_ERROR, error);

  Response decoded = new W3CHttpResponseCodec().decode(response);

  assertThat(decoded.getState()).isEqualTo("unsupported operation");
  assertThat(decoded.getStatus().intValue()).isEqualTo(METHOD_NOT_ALLOWED);

  assertThat(decoded.getValue()).isInstanceOf(UnsupportedCommandException.class);
  assertThat(((WebDriverException) decoded.getValue()).getMessage()).contains("I like peas");
}
 
Example #16
Source File: ReactorHandlerTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
protected HttpClient.Factory createFactory() {
  return config -> {
    ReactorHandler reactorHandler = new ReactorHandler(config, httpClient);

    return new HttpClient() {
      @Override
      public WebSocket openSocket(HttpRequest request, WebSocket.Listener listener) {
        throw new UnsupportedOperationException("openSocket");
      }

      @Override
      public HttpResponse execute(HttpRequest req) throws UncheckedIOException {
        return reactorHandler.execute(req);
      }
    };
  };
}
 
Example #17
Source File: WebSocketServingTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void webSocketHandlersShouldBeAbleToFireMoreThanOneMessage() {
  server = new NettyServer(
    defaultOptions(),
    req -> new HttpResponse(),
    (uri, sink) -> Optional.of(msg -> {
      sink.accept(new TextMessage("beyaz peynir"));
      sink.accept(new TextMessage("cheddar"));
    })).start();

  HttpClient client = HttpClient.Factory.createDefault().createClient(server.getUrl());
  List<String> messages = new LinkedList<>();
  WebSocket socket = client.openSocket(new HttpRequest(GET, "/cheese"), new WebSocket.Listener() {
    @Override
    public void onText(CharSequence data) {
      messages.add(data.toString());
    }
  });

  socket.send(new TextMessage("Hello"));

  new FluentWait<>(messages).until(msgs -> msgs.size() == 2);
}
 
Example #18
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void convertsResponses_success() {
  Response response = new Response();
  response.setStatus(ErrorCodes.SUCCESS);
  response.setValue(ImmutableMap.of("color", "red"));

  HttpResponse converted = codec.encode(HttpResponse::new, response);
  assertThat(converted.getStatus()).isEqualTo(HTTP_OK);
  assertThat(converted.getHeader(CONTENT_TYPE)).isEqualTo(JSON_UTF_8.toString());

  Response rebuilt = new Json().toType(string(converted), Response.class);

  assertThat(rebuilt.getStatus()).isEqualTo(response.getStatus());
  assertThat(rebuilt.getState()).isEqualTo(new ErrorCodes().toState(response.getStatus()));
  assertThat(rebuilt.getSessionId()).isEqualTo(response.getSessionId());
  assertThat(rebuilt.getValue()).isEqualTo(response.getValue());
}
 
Example #19
Source File: ProtocolConverter.java    From selenium with Apache License 2.0 5 votes vote down vote up
private ResponseCodec<HttpResponse> getResponseCodec(Dialect dialect) {
  switch (dialect) {
    case OSS:
      return new JsonHttpResponseCodec();

    case W3C:
      return new W3CHttpResponseCodec();

    default:
      throw new IllegalStateException("Unknown dialect: " + dialect);
  }
}
 
Example #20
Source File: VersionCommand.java    From selenium with Apache License 2.0 5 votes vote down vote up
public Optional<DockerProtocol> getDockerProtocol() {
  try {
    HttpResponse res = handler.execute(new HttpRequest(GET, "/version"));

    if (!res.isSuccessful()) {
      return Optional.empty();
    }

    Map<String, Object> raw = JSON.toType(Contents.string(res), MAP_TYPE);

    Version maxVersion = new Version((String) raw.get("ApiVersion"));
    Version minVersion = new Version((String) raw.get("MinAPIVersion"));

    return SUPPORTED_VERSIONS.entrySet().stream()
      .filter(entry -> {
        Version version = entry.getKey();
        if (version.equalTo(maxVersion) || version.equalTo(minVersion)) {
          return true;
        }
        return version.isLessThan(maxVersion) && version.isGreaterThan(minVersion);
      })
      .map(Map.Entry::getValue)
      .map(func -> func.apply(handler))
      .findFirst();
  } catch (ClassCastException | JsonException | NullPointerException | UncheckedIOException e) {
    return Optional.empty();
  }
}
 
Example #21
Source File: W3CHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void noErrorNoCry() {
  Map<String, Object> data = new HashMap<>();
  data.put("value", "cheese");

  HttpResponse response = createValidResponse(HTTP_OK, data);

  Response decoded = new W3CHttpResponseCodec().decode(response);

  assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.SUCCESS);
  assertThat(decoded.getState()).isEqualTo("success");
  assertThat(decoded.getValue()).isEqualTo("cheese");
}
 
Example #22
Source File: RemoteDistributor.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public RemoteDistributor add(Node node) {
  HttpRequest request = new HttpRequest(POST, "/se/grid/distributor/node");
  HttpTracing.inject(tracer, tracer.getCurrentContext(), request);
  request.setContent(asJson(node.getStatus()));

  HttpResponse response = client.execute(request);

  Values.get(response, Void.class);

  LOG.info(String.format("Added node %s.", node.getId()));

  return this;
}
 
Example #23
Source File: ResponseConverter.java    From selenium with Apache License 2.0 5 votes vote down vote up
private void copyHeaders(HttpResponse seResponse, DefaultHttpResponse first) {
  for (String name : seResponse.getHeaderNames()) {
    if (CONTENT_LENGTH.contentEqualsIgnoreCase(name) || TRANSFER_ENCODING.contentEqualsIgnoreCase(name)) {
      continue;
    }
    for (String value : seResponse.getHeaders(name)) {
      if (value == null) {
        continue;
      }
      first.headers().add(name, value);
    }
  }
}
 
Example #24
Source File: NettyServerTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
/**
 * There is a bug between an OkHttp client and the Netty server where a TCP
 * RST causes the same HTTP request to be generated twice. This is clearly
 * less than desirable behaviour, so this test attempts to ensure the problem
 * does not occur. I suspect the problem is to do with OkHttp's connection
 * pool, but it seems cruel to make our users deal with this. Better to have
 * it be something the server handles.
 */
@Test
public void ensureMultipleCallsWorkAsExpected() {
  System.out.println("\n\n\n\nNetty!");

  AtomicInteger count = new AtomicInteger(0);

  Server<?> server = new NettyServer(
    new BaseServerOptions(
      new MapConfig(
        ImmutableMap.of("server", ImmutableMap.of("port", PortProber.findFreePort())))),
    req -> {
      count.incrementAndGet();
      return new HttpResponse().setContent(utf8String("Count is " + count.get()));
    }
  ).start();

    // TODO: avoid using netty for this
    HttpClient client = HttpClient.Factory.createDefault().createClient(server.getUrl());

  HttpResponse res = client.execute(new HttpRequest(GET, "/does-not-matter"));
  outputHeaders(res);
  assertThat(count.get()).isEqualTo(1);

  client.execute(new HttpRequest(GET, "/does-not-matter"));
  outputHeaders(res);
  assertThat(count.get()).isEqualTo(2);
}
 
Example #25
Source File: ProtocolHandshakeTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldParseW3CNewSessionResponse() throws IOException {
  Map<String, Object> params = singletonMap("desiredCapabilities", new ImmutableCapabilities());
  Command command = new Command(null, DriverCommand.NEW_SESSION, params);

  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(utf8String(
      "{\"value\": {\"sessionId\": \"23456789\", \"capabilities\": {}}}"));
  RecordingHttpClient client = new RecordingHttpClient(response);

  ProtocolHandshake.Result result = new ProtocolHandshake().createSession(client, command);
  assertThat(result.getDialect()).isEqualTo(Dialect.W3C);
}
 
Example #26
Source File: RemoteDistributor.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public CreateSessionResponse newSession(HttpRequest request)
    throws SessionNotCreatedException {
  HttpRequest upstream = new HttpRequest(POST, "/se/grid/distributor/session");
  HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);
  upstream.setContent(request.getContent());

  HttpResponse response = client.execute(upstream);

  return Values.get(response, CreateSessionResponse.class);
}
 
Example #27
Source File: BootstrapTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReportDockerIsUnsupportedIfServerReturns500() {
  HttpHandler client = req -> new HttpResponse().setStatus(HTTP_INTERNAL_ERROR);

  boolean isSupported = new Docker(client).isSupported();

  assertThat(isSupported).isFalse();
}
 
Example #28
Source File: ProtocolConverter.java    From selenium with Apache License 2.0 5 votes vote down vote up
private HttpResponse createResponse(ImmutableMap<String, Object> toSend) {
  byte[] bytes = JSON.toJson(toSend).getBytes(UTF_8);

  return new HttpResponse()
    .setHeader("Content-Type", MediaType.JSON_UTF_8.toString())
    .setHeader("Content-Length", String.valueOf(bytes.length))
    .setContent(bytes(bytes));
}
 
Example #29
Source File: VersionCommandTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnEmptyIfServerReturnsAnUnsuccessfulResponseStatus() {
  HttpHandler handler = req -> new HttpResponse().setStatus(HTTP_INTERNAL_ERROR);

  Optional<DockerProtocol> maybeDocker = new VersionCommand(handler).getDockerProtocol();

  assertThat(maybeDocker).isEqualTo(Optional.empty());
}
 
Example #30
Source File: ProtocolConverter.java    From selenium with Apache License 2.0 5 votes vote down vote up
private HttpResponse createW3CNewSessionResponse(HttpResponse response) {
  Map<String, Object> value = JSON.toType(string(response), MAP_TYPE);

  Require.state("Session id", value.get("sessionId")).nonNull();
  Require.state("Response payload", value.get("value")).instanceOf(Map.class);

  return createResponse(ImmutableMap.of(
    "value", ImmutableMap.of(
      "sessionId", value.get("sessionId"),
      "capabilities", value.get("value"))));
}