Java Code Examples for org.openqa.selenium.remote.http.HttpClient

The following examples show how to use org.openqa.selenium.remote.http.HttpClient. These examples are extracted from open source projects. 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 Project: selenium   Source File: AddingNodesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUpDistributor() throws MalformedURLException {
  tracer = DefaultTestTracer.createTracer();
  bus = new GuavaEventBus();

  handler = new CombinedHandler();
  externalUrl = new URL("http://example.com");
  HttpClient.Factory clientFactory = new RoutableHttpClientFactory(
    externalUrl,
    handler,
    HttpClient.Factory.createDefault());

  LocalSessionMap sessions = new LocalSessionMap(tracer, bus);
  Distributor local = new LocalDistributor(tracer, bus, clientFactory, sessions, null);
  handler.addHandler(local);
  distributor = new RemoteDistributor(tracer, clientFactory, externalUrl);

  wait = new FluentWait<>(new Object()).withTimeout(Duration.ofSeconds(2));
}
 
Example 2
Source Project: selenium   Source File: ProxyCdpIntoGrid.java    License: 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 3
Source Project: selenium   Source File: Router.java    License: Apache License 2.0 6 votes vote down vote up
public Router(
  Tracer tracer,
  HttpClient.Factory clientFactory,
  SessionMap sessions,
  Distributor distributor) {
  Require.nonNull("Tracer to use", tracer);
  Require.nonNull("HTTP client factory", clientFactory);

  this.sessions = Require.nonNull("Session map", sessions);
  this.distributor = Require.nonNull("Distributor", distributor);

  routes =
    combine(
      get("/status")
        .to(() -> new GridStatusHandler(new Json(), tracer, clientFactory, distributor)),
      sessions.with(new SpanDecorator(tracer, req -> "session_map")),
      distributor.with(new SpanDecorator(tracer, req -> "distributor")),
      matching(req -> req.getUri().startsWith("/session/"))
        .to(() -> new HandleSession(tracer, clientFactory, sessions)));
}
 
Example 4
Source Project: selenium   Source File: ProtocolConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void newW3CSessionResponseShouldBeCorrectlyConvertedToJwp() {
  Map<String, Object> w3cNewSession = ImmutableMap.of(
    "capabilities", ImmutableMap.of());

  Map<String, Object> jwpResponse = ImmutableMap.of(
    "status", 0,
    "sessionId", "i like cheese very much",
    "value", ImmutableMap.of("cheese", "brie"));

  HttpClient client = mock(HttpClient.class);
  Mockito.when(client.execute(any())).thenReturn(new HttpResponse().setContent(asJson(jwpResponse)));

  ProtocolConverter converter = new ProtocolConverter(tracer, client, W3C, OSS);

  HttpResponse response = converter.execute(new HttpRequest(POST, "/session").setContent(asJson(w3cNewSession)));

  Map<String, Object> convertedResponse = json.toType(string(response), MAP_TYPE);
  Map<?, ?> value = (Map<?, ?>) convertedResponse.get("value");
  assertThat(value.get("capabilities"))
    .as("capabilities: " + convertedResponse)
    .isEqualTo(jwpResponse.get("value"));
  assertThat(value.get("sessionId"))
    .as("session id: " + convertedResponse)
    .isEqualTo(jwpResponse.get("sessionId"));
}
 
Example 5
Source Project: selenium   Source File: DriverServiceSessionFactoryTest.java    License: 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 6
Source Project: selenium   Source File: HttpCommandExecutor.java    License: Apache License 2.0 6 votes vote down vote up
public HttpCommandExecutor(
    Map<String, CommandInfo> additionalCommands,
    URL addressOfRemoteServer,
    HttpClient.Factory httpClientFactory) {
  try {
    remoteServer = addressOfRemoteServer == null
        ? new URL(System.getProperty("webdriver.remote.server", "http://localhost:4444/"))
        : addressOfRemoteServer;
  } catch (MalformedURLException e) {
    throw new WebDriverException(e);
  }

  this.additionalCommands = additionalCommands;
  this.httpClientFactory = httpClientFactory;
  this.client = httpClientFactory.createClient(remoteServer);
}
 
Example 7
Source Project: selenium   Source File: EndToEndTest.java    License: 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 8
Source Project: selenium   Source File: JreAppServer.java    License: 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 9
Source Project: selenium   Source File: ReactorHandlerTest.java    License: 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 10
Source Project: selenium   Source File: ProtocolConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void newJwpSessionResponseShouldBeConvertedToW3CCorrectly() {
  Map<String, Object> w3cResponse = ImmutableMap.of(
    "value", ImmutableMap.of(
      "capabilities", ImmutableMap.of("cheese", "brie"),
      "sessionId", "i like cheese very much"));

  Map<String, Object> jwpNewSession = ImmutableMap.of(
    "desiredCapabilities", ImmutableMap.of());

  HttpClient client = mock(HttpClient.class);
  Mockito.when(client.execute(any())).thenReturn(new HttpResponse().setContent(asJson(w3cResponse)));

  ProtocolConverter converter = new ProtocolConverter(tracer, client, OSS, W3C);

  HttpResponse response = converter.execute(new HttpRequest(POST, "/session").setContent(asJson(jwpNewSession)));

  Map<String, Object> convertedResponse = json.toType(string(response), MAP_TYPE);
  assertThat(convertedResponse.get("status")).isEqualTo(0L);
  assertThat(convertedResponse.get("sessionId")).isEqualTo("i like cheese very much");
  assertThat(convertedResponse.get("value")).isEqualTo(ImmutableMap.of("cheese", "brie"));
}
 
Example 11
Source Project: selenium   Source File: ProtocolConverter.java    License: Apache License 2.0 6 votes vote down vote up
public ProtocolConverter(
  Tracer tracer,
  HttpClient client,
  Dialect downstream,
  Dialect upstream) {
  this.tracer = Require.nonNull("Tracer", tracer);
  this.client = Require.nonNull("HTTP client", client);

  this.downstream = getCommandCodec(Require.nonNull("Downstream dialect", downstream));
  this.downstreamResponse = getResponseCodec(downstream);

  this.upstream = getCommandCodec(Require.nonNull("Upstream dialect", upstream));
  this.upstreamResponse = getResponseCodec(upstream);

  converter = new JsonToWebElementConverter(null);

  newSessionConverter = downstream == W3C ? this::createW3CNewSessionResponse : this::createJwpNewSessionResponse;
}
 
Example 12
Source Project: selenium   Source File: ProtocolConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void newJwpSessionResponseShouldBeCorrectlyConvertedToW3C() {
  Map<String, Object> jwpNewSession = ImmutableMap.of("desiredCapabilities", ImmutableMap.of("cheese", "brie"));

  Map<String, Object> w3cResponse = ImmutableMap.of(
    "value", ImmutableMap.of(
      "sessionId", "i like cheese very much",
      "capabilities", ImmutableMap.of("cheese", "brie")));

  HttpClient client = mock(HttpClient.class);
  Mockito.when(client.execute(any())).thenReturn(new HttpResponse().setContent(asJson(w3cResponse)));

  ProtocolConverter converter = new ProtocolConverter(tracer, client, OSS, W3C);

  HttpResponse response = converter.execute(new HttpRequest(POST, "/session").setContent(asJson(jwpNewSession)));

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

  assertThat(convertedResponse.get("sessionId")).isEqualTo("i like cheese very much");
  assertThat(convertedResponse.get("status")).isEqualTo(0L);
  assertThat(convertedResponse.get("value")).isEqualTo(ImmutableMap.of("cheese", "brie"));
}
 
Example 13
Source Project: selenium   Source File: LocalDistributor.java    License: Apache License 2.0 6 votes vote down vote up
public LocalDistributor(
    Tracer tracer,
    EventBus bus,
    HttpClient.Factory clientFactory,
    SessionMap sessions,
    String registrationSecret) {
  super(tracer, clientFactory);
  this.tracer = Require.nonNull("Tracer", tracer);
  this.bus = Require.nonNull("Event bus", bus);
  this.clientFactory = Require.nonNull("HTTP client factory", clientFactory);
  this.sessions = Require.nonNull("Session map", sessions);
  this.registrationSecret = registrationSecret;

  bus.addListener(NODE_STATUS, event -> refresh(event.getData(NodeStatus.class)));
  bus.addListener(NODE_DRAIN_COMPLETE, event -> remove(event.getData(UUID.class)));
}
 
Example 14
Source Project: selenium   Source File: DriverServiceSessionFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotInstantiateSessionIfRemoteEndReturnsInvalidResponse() throws IOException {
  HttpClient httpClient = mock(HttpClient.class);
  when(httpClient.execute(any(HttpRequest.class))).thenReturn(
      new HttpResponse().setStatus(200).setContent(() -> new ByteArrayInputStream(
          "Hello, world!".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).isEmpty();

  verify(builder, times(1)).build();
  verifyNoMoreInteractions(builder);
  verify(driverService, times(1)).start();
  verify(driverService, atLeastOnce()).getUrl();
  verify(driverService, times(1)).stop();
  verifyNoMoreInteractions(driverService);
}
 
Example 15
Source Project: selenium   Source File: RouterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  tracer = DefaultTestTracer.createTracer();
  bus = new GuavaEventBus();

  handler = new CombinedHandler();
  HttpClient.Factory clientFactory = new PassthroughHttpClient.Factory(handler);

  sessions = new LocalSessionMap(tracer, bus);
  handler.addHandler(sessions);

  distributor = new LocalDistributor(tracer, bus, clientFactory, sessions, null);
  handler.addHandler(distributor);

  router = new Router(tracer, clientFactory, sessions, distributor);
}
 
Example 16
Source Project: selenium   Source File: JettyServerTest.java    License: 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 17
Source Project: selenium   Source File: EndToEndTest.java    License: 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 18
Source Project: selenium   Source File: LocalNodeFactory.java    License: Apache License 2.0 6 votes vote down vote up
private static Collection<SessionFactory> createSessionFactory(
  Tracer tracer,
  HttpClient.Factory clientFactory,
  List<DriverService.Builder<?, ?>> builders,
  WebDriverInfo info) {
  ImmutableList.Builder<SessionFactory> toReturn = ImmutableList.builder();

  Capabilities caps = info.getCanonicalCapabilities();

  builders.stream()
    .filter(builder -> builder.score(caps) > 0)
    .forEach(builder -> {
      DriverService.Builder<?, ?> freePortBuilder = builder.usingAnyFreePort();
      toReturn.add(new DriverServiceSessionFactory(
        tracer,
        clientFactory,
        c -> freePortBuilder.score(c) > 0,
        freePortBuilder));
    });

  return toReturn.build();
}
 
Example 19
Source Project: carina   Source File: EventFiringAppiumCommandExecutor.java    License: Apache License 2.0 5 votes vote down vote up
private EventFiringAppiumCommandExecutor(Map<String, CommandInfo> additionalCommands, DriverService service,
        URL addressOfRemoteServer,
        HttpClient.Factory httpClientFactory) {
    super(additionalCommands,
            ofNullable(service)
                    .map(DriverService::getUrl)
                    .orElse(addressOfRemoteServer),
            httpClientFactory);
    serviceOptional = ofNullable(service);
}
 
Example 20
Source Project: selenium   Source File: JettyServerTest.java    License: 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 21
Source Project: hifive-pitalium   Source File: CustomHttpCommandExecutor.java    License: Apache License 2.0 5 votes vote down vote up
public CustomHttpCommandExecutor(Map<String, CommandInfo> additionalCommands, URL addressOfRemoteServer,
		HttpClient.Factory httpClientFactory) {
	try {
		remoteServer = addressOfRemoteServer == null
				? new URL(System.getProperty("webdriver.remote.server", "http://localhost:4444/wd/hub"))
				: addressOfRemoteServer;
	} catch (MalformedURLException e) {
		throw new WebDriverException(e);
	}

	this.additionalCommands = additionalCommands;
	this.client = httpClientFactory.createClient(remoteServer);
}
 
Example 22
Source Project: selenium   Source File: NettyServerTest.java    License: 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 23
Source Project: selenium   Source File: WebSocketServingTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUseUriToChooseWhichWebSocketHandlerToUse() throws InterruptedException {
  AtomicBoolean foo = new AtomicBoolean(false);
  AtomicBoolean bar = new AtomicBoolean(false);

  BiFunction<String, Consumer<Message>, Optional<Consumer<Message>>> factory = (str, sink) -> {
    if ("/foo".equals(str)) {
      return Optional.of(msg -> {
        foo.set(true);
        sink.accept(new TextMessage("Foo called"));
      });
    } else {
      return Optional.of(msg -> {
        bar.set(true);
        sink.accept(new TextMessage("Bar called"));
      });
    }
  };

  server = new NettyServer(
    defaultOptions(),
    req -> new HttpResponse(),
    factory
  ).start();

  CountDownLatch latch = new CountDownLatch(1);
  HttpClient client = HttpClient.Factory.createDefault().createClient(server.getUrl());
  WebSocket fooSocket = client.openSocket(new HttpRequest(GET, "/foo"), new WebSocket.Listener() {
    @Override
    public void onText(CharSequence data) {
      System.out.println("Called!");
      latch.countDown();
    }
  });
  fooSocket.sendText("Hello, World!");

  latch.await(2, SECONDS);
  assertThat(foo.get()).isTrue();
  assertThat(bar.get()).isFalse();
}
 
Example 24
Source Project: java-client   Source File: AppiumCommandExecutor.java    License: Apache License 2.0 5 votes vote down vote up
private AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands, DriverService service,
                              URL addressOfRemoteServer,
                              HttpClient.Factory httpClientFactory) {
    super(additionalCommands,
            ofNullable(service)
                    .map(DriverService::getUrl)
                    .orElse(addressOfRemoteServer), httpClientFactory);
    serviceOptional = ofNullable(service);
}
 
Example 25
Source Project: selenium   Source File: DriverServiceSessionFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws MalformedURLException {
  tracer = DefaultTestTracer.createTracer();

  clientFactory = mock(HttpClient.Factory.class);

  driverService = mock(DriverService.class);
  when(driverService.getUrl()).thenReturn(new URL("http://localhost:1234/"));

  builder = mock(DriverService.Builder.class);
  when(builder.build()).thenReturn(driverService);
}
 
Example 26
Source Project: selenium   Source File: ProxyCdpTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  Tracer tracer = DefaultTestTracer.createTracer();
  EventBus events = new GuavaEventBus();

  sessions = new LocalSessionMap(tracer, events);

  // Set up the proxy we'll be using
  HttpClient.Factory clientFactory = HttpClient.Factory.createDefault();
  ProxyCdpIntoGrid proxy = new ProxyCdpIntoGrid(clientFactory, sessions);
  proxyServer = new NettyServer(new BaseServerOptions(emptyConfig), nullHandler, proxy).start();
}
 
Example 27
Source Project: selenium   Source File: ChromiumDriver.java    License: Apache License 2.0 5 votes vote down vote up
protected ChromiumDriver(CommandExecutor commandExecutor, Capabilities capabilities, String capabilityKey) {
  super(commandExecutor, capabilities);
  locationContext = new RemoteLocationContext(getExecuteMethod());
  webStorage = new RemoteWebStorage(getExecuteMethod());
  touchScreen = new RemoteTouchScreen(getExecuteMethod());
  networkConnection = new RemoteNetworkConnection(getExecuteMethod());

  HttpClient.Factory factory = HttpClient.Factory.createDefault();
  connection = ChromiumDevToolsLocator.getChromeConnector(
      factory,
      getCapabilities(),
      capabilityKey);
  devTools = connection.map(DevTools::new);
}
 
Example 28
Source Project: selenium   Source File: ChromiumDevToolsLocator.java    License: 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 29
Source Project: selenium   Source File: DistributorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  tracer = DefaultTestTracer.createTracer();
  bus = new GuavaEventBus();
  LocalSessionMap sessions = new LocalSessionMap(tracer, bus);
  local = new LocalDistributor(tracer, bus, HttpClient.Factory.createDefault(), sessions, null);

  caps = new ImmutableCapabilities("browserName", "cheese");
}
 
Example 30
Source Project: selenium   Source File: ProtocolHandshake.java    License: Apache License 2.0 5 votes vote down vote up
public Result createSession(HttpClient client, Command command)
    throws IOException {
  Capabilities desired = (Capabilities) command.getParameters().get("desiredCapabilities");
  desired = desired == null ? new ImmutableCapabilities() : desired;

  int threshold = (int) Math.min(Runtime.getRuntime().freeMemory() / 10, Integer.MAX_VALUE);
  FileBackedOutputStream os = new FileBackedOutputStream(threshold);
  try (
      CountingOutputStream counter = new CountingOutputStream(os);
      Writer writer = new OutputStreamWriter(counter, UTF_8);
      NewSessionPayload payload = NewSessionPayload.create(desired)) {

    payload.writeTo(writer);

    try (InputStream rawIn = os.asByteSource().openBufferedStream();
         BufferedInputStream contentStream = new BufferedInputStream(rawIn)) {
      Optional<Result> result = createSession(client, contentStream, counter.getCount());

      if (result.isPresent()) {
        Result toReturn = result.get();
        LOG.info(String.format("Detected dialect: %s", toReturn.dialect));
        return toReturn;
      }
    }
  } finally {
    os.reset();
  }

  throw new SessionNotCreatedException(
      String.format(
          "Unable to create new remote session. " +
          "desired capabilities = %s",
          desired));
}