Java Code Examples for org.openqa.selenium.remote.http.HttpClient#execute()

The following examples show how to use org.openqa.selenium.remote.http.HttpClient#execute() . 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: 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 2
Source File: JreAppServer.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public String create(Page page) {
  try {
    byte[] data = new Json()
        .toJson(ImmutableMap.of("content", page.toString()))
        .getBytes(UTF_8);

    HttpClient client = HttpClient.Factory.createDefault().createClient(new URL(whereIs("/")));
    HttpRequest request = new HttpRequest(HttpMethod.POST, "/common/createPage");
    request.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());
    request.setContent(bytes(data));
    HttpResponse response = client.execute(request);
    return string(response);
  } catch (IOException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example 3
Source File: EndToEndTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAllowPassthroughForJWPMode() {
  HttpRequest request = new HttpRequest(POST, "/session");
  request.setContent(asJson(
      ImmutableMap.of(
          "desiredCapabilities", 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 be a numeric status field
  assertEquals(topLevel.toString(), 0L, topLevel.get("status"));
  // The session id
  assertTrue(string(request), topLevel.containsKey("sessionId"));

  // And the value should be the capabilities.
  Map<?, ?> value = (Map<?, ?>) topLevel.get("value");
  assertEquals(string(request), "cheese", value.get("browserName"));
}
 
Example 4
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 5
Source File: HttpClientTestBase.java    From selenium with Apache License 2.0 6 votes vote down vote up
private HttpResponse executeWithinServer(HttpRequest request, HttpServlet servlet)
    throws Exception {
  Server server = new Server(PortProber.findFreePort());
  ServletContextHandler handler = new ServletContextHandler();
  handler.setContextPath("");
  ServletHolder holder = new ServletHolder(servlet);
  handler.addServlet(holder, "/*");

  server.setHandler(handler);

  server.start();
  try {
    HttpClient client = createFactory().createClient(fromUri(server.getURI()));
    return client.execute(request);
  } finally {
    server.stop();
  }
}
 
Example 6
Source File: JettyServerTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAllowCORS() {
  // TODO: Server setup
  Config cfg = new CompoundConfig(
      new MapConfig(ImmutableMap.of("server", ImmutableMap.of("allow-cors", "true"))));
  BaseServerOptions options = new BaseServerOptions(cfg);
  assertTrue("Allow CORS should be enabled", options.getAllowCORS());
  Server<?> server = new JettyServer(options, req -> new HttpResponse()).start();

  // TODO: Client setup
  URL url = server.getUrl();
  HttpClient client = HttpClient.Factory.createDefault().createClient(url);
  HttpRequest request = new HttpRequest(DELETE, "/session");
  String exampleUrl = "http://www.example.com";
  request.setHeader("Origin", exampleUrl);
  request.setHeader("Accept", "*/*");
  HttpResponse response = client.execute(request);

  // TODO: Assertion
  assertEquals("Access-Control-Allow-Credentials should be true", "true",
               response.getHeader("Access-Control-Allow-Credentials"));

  assertEquals("Access-Control-Allow-Origin should be equal to origin in request header",
               exampleUrl,
               response.getHeader("Access-Control-Allow-Origin"));
}
 
Example 7
Source File: JettyServerTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDisableAllowOrigin() {
  // TODO: Server setup
  Server<?> server = new JettyServer(emptyOptions, req -> new HttpResponse()).start();

  // TODO: Client setup
  URL url = server.getUrl();
  HttpClient client = HttpClient.Factory.createDefault().createClient(url);
  HttpRequest request = new HttpRequest(DELETE, "/session");
  String exampleUrl = "http://www.example.com";
  request.setHeader("Origin", exampleUrl);
  request.setHeader("Accept", "*/*");
  HttpResponse response = client.execute(request);

  // TODO: Assertion
  assertEquals("Access-Control-Allow-Credentials should be null", null,
               response.getHeader("Access-Control-Allow-Credentials"));

  assertEquals("Access-Control-Allow-Origin should be null",
               null,
               response.getHeader("Access-Control-Allow-Origin"));
}
 
Example 8
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 9
Source File: JettyServerTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAllowAHandlerToBeRegistered() {
  Server<?> server = new JettyServer(
    emptyOptions,
    get("/cheese").to(() -> req -> new HttpResponse().setContent(utf8String("cheddar"))));

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

  assertEquals("cheddar", string(response));
}
 
Example 10
Source File: SessionLogsTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
private static Map<String, Object> getValueForPostRequest(URL serverUrl) throws Exception {
  String url = serverUrl + "/logs";
  HttpClient.Factory factory = HttpClient.Factory.createDefault();
  HttpClient client = factory.createClient(new URL(url));
  HttpResponse response = client.execute(new HttpRequest(HttpMethod.POST, url));
  Map<String, Object> map = new Json().toType(string(response), MAP_TYPE);
  return (Map<String, Object>) map.get("value");
}
 
Example 11
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 12
Source File: NetworkOptionsTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
/**
 * An initial version of our wrapper around OpenTracing caused exceptions
 * to be thrown when spans were closed prematurely and out of order. This
 * test was written to both demonstrate that problem and to resolve it.
 */
@Test
public void triggerFailureInTracing() {
  // I better explain this. The only hint that we have that our use of
  // OpenTelemetry is wrong is found in the log message that the
  // io.grpc.Context generates when `Context.detach` is called in an
  // "unbalanced" way. So, what we'll do is add a new log handler that
  // will record all messages during the test (filtered by logger name)
  // and after the fact make sure that the list of warnings at the
  // appropriate level is empty.
  //
  // This means this test is remarkably brittle and fragile. If there
  // were a way to replace the storage engine in `Context`, I'd have done
  // that for this test run, but of course there is not.

  Logger rootLogger = LogManager.getLogManager().getLogger("");

  CapturingHandler handler = new CapturingHandler("io.grpc");
  rootLogger.addHandler(handler);

  try {
    Config config = new MapConfig(emptyMap());
    Tracer tracer = DefaultTestTracer.createTracer();
    HttpClient.Factory clientFactory = new NetworkOptions(config).getHttpClientFactory(tracer);

    Server<?> server = new JreServer(new BaseServerOptions(config), req -> new HttpResponse()).start();
    HttpClient client = clientFactory.createClient(server.getUrl());

    client.execute(new HttpRequest(GET, "/version"));
  } finally {
    rootLogger.removeHandler(handler);
  }

  List<String> messages = handler.getMessages(Level.SEVERE);
  assertThat(messages).isEmpty();
}
 
Example 13
Source File: JettyServerTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void baseServerStartsAndDoesNothing() {
  Server<?> server = new JettyServer(emptyOptions, req -> new HttpResponse()).start();

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

  // Although we don't expect the server to be ready, we do expect the request to succeed.
  assertEquals(HTTP_OK, response.getStatus());

  // And we expect the content to be UTF-8 encoded JSON.
  assertEquals(MediaType.JSON_UTF_8, MediaType.parse(response.getHeader("Content-Type")));
}
 
Example 14
Source File: HttpClientTestBase.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAllowUrlsWithSchemesToBeUsed() throws Exception {
  Server server = new Server(PortProber.findFreePort());
  ServletContextHandler handler = new ServletContextHandler();
  handler.setContextPath("");

  class Canned extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
      try (PrintWriter writer = resp.getWriter()) {
        writer.append("Hello, World!");
      }
    }
  }
  ServletHolder holder = new ServletHolder(new Canned());
  handler.addServlet(holder, "/*");
  server.setHandler(handler);

  server.start();
  try {
    // This is a terrible choice of URL
    HttpClient client = createFactory().createClient(new URL("http://example.com"));

    URI uri = server.getURI();
    HttpRequest request = new HttpRequest(
        GET,
        String.format("http://%s:%s/hello", uri.getHost(), uri.getPort()));

    HttpResponse response = client.execute(request);

    assertThat(string(response)).isEqualTo("Hello, World!");
  } finally {
    server.stop();
  }
}
 
Example 15
Source File: NettyClientTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBeAbleToConnectToAUnixDomainSocketUrl() {
  ClientConfig config = ClientConfig.defaultConfig().baseUri(socket);
  HttpClient client = new NettyClient.Factory().createClient(config);

  String emphaticCheeseEnjoyment = "I like cheese!";
  responseText.set(emphaticCheeseEnjoyment);

  HttpResponse res = client.execute(new HttpRequest(GET, "/do-you-like-cheese"));

  assertThat(Contents.string(res)).isEqualTo(emphaticCheeseEnjoyment);
}
 
Example 16
Source File: JettyAppServer.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public String create(Page page) {
  try {
    byte[] data = new Json().toJson(singletonMap("content", page.toString())).getBytes(UTF_8);

    HttpClient client = HttpClient.Factory.createDefault().createClient(new URL(whereIs("/")));
    HttpRequest request = new HttpRequest(HttpMethod.POST, "/common/createPage");
    request.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());
    request.setContent(bytes(data));
    HttpResponse response = client.execute(request);
    return string(response);
  } catch (IOException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example 17
Source File: AppServerTestBase.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void manifestHasCorrectMimeType() throws IOException {
  String url = server.whereIs("html5/test.appcache");
  HttpClient.Factory factory = HttpClient.Factory.createDefault();
  HttpClient client = factory.createClient(new URL(url));
  HttpResponse response = client.execute(new HttpRequest(HttpMethod.GET, url));

  System.out.printf("Content for %s was %s\n", url, string(response));

  assertTrue(StreamSupport.stream(response.getHeaders("Content-Type").spliterator(), false)
      .anyMatch(header -> header.contains(APPCACHE_MIME_TYPE)));
}
 
Example 18
Source File: ProtocolHandshake.java    From selenium with Apache License 2.0 5 votes vote down vote up
private Optional<Result> createSession(HttpClient client, InputStream newSessionBlob, long size) {
  // Create the http request and send it
  HttpRequest request = new HttpRequest(HttpMethod.POST, "/session");

  HttpResponse response;
  long start = System.currentTimeMillis();

  request.setHeader(CONTENT_LENGTH, String.valueOf(size));
  request.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());
  request.setContent(() -> newSessionBlob);

  response = client.execute(request);
  long time = System.currentTimeMillis() - start;

  // Ignore the content type. It may not have been set. Strictly speaking we're not following the
  // W3C spec properly. Oh well.
  Map<?, ?> blob;
  try {
    blob = new Json().toType(string(response), Map.class);
  } catch (JsonException e) {
    throw new WebDriverException(
        "Unable to parse remote response: " + string(response), e);
  }

  InitialHandshakeResponse initialResponse = new InitialHandshakeResponse(
      time,
      response.getStatus(),
      blob);

  return Stream.of(
      new W3CHandshakeResponse().getResponseFunction(),
      new JsonWireProtocolResponse().getResponseFunction())
      .map(func -> func.apply(initialResponse))
      .filter(Objects::nonNull)
      .findFirst();
}
 
Example 19
Source File: ChromiumDevToolsLocator.java    From selenium with Apache License 2.0 5 votes vote down vote up
public static Optional<URI> getCdpEndPoint(
  HttpClient.Factory clientFactory,
  URI reportedUri) {
  Require.nonNull("HTTP client factory", clientFactory);
  Require.nonNull("DevTools URI", reportedUri);

  ClientConfig config = ClientConfig.defaultConfig().baseUri(reportedUri);
  HttpClient client = clientFactory.createClient(config);

  HttpResponse res = client.execute(new HttpRequest(GET, "/json/version"));
  if (res.getStatus() != HTTP_OK) {
    return Optional.empty();
  }

  Map<String, Object> versionData = JSON.toType(string(res), MAP_TYPE);
  Object raw = versionData.get("webSocketDebuggerUrl");

  if (!(raw instanceof String)) {
    return Optional.empty();
  }

  String debuggerUrl = (String) raw;
  try {
    return Optional.of(new URI(debuggerUrl));
  } catch (URISyntaxException e) {
    LOG.warning("Invalid URI for endpoint " + raw);
    return Optional.empty();
  }
}
 
Example 20
Source File: AppiumCommandExecutor.java    From java-client with Apache License 2.0 4 votes vote down vote up
protected HttpClient withRequestsPatchedByIdempotencyKey(HttpClient httpClient) {
    return (request) -> {
        request.setHeader(IDEMPOTENCY_KEY_HEADER, UUID.randomUUID().toString().toLowerCase());
        return httpClient.execute(request);
    };
}