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

The following examples show how to use org.openqa.selenium.remote.http.HttpMethod. 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: Browser.java    From selenium-shutterbug with MIT License 6 votes vote down vote up
public BufferedImage takeScreenshotEntirePageUsingGeckoDriver() {
    // Check geckodriver version (>= 0.24.0 is requried)
    String version = (String) ((RemoteWebDriver) driver).getCapabilities().getCapability("moz:geckodriverVersion");
    if (version == null || Version.valueOf(version).satisfies("<0.24.0")) {
        return takeScreenshotEntirePageDefault();
    }
    defineCustomCommand("mozFullPageScreenshot", new CommandInfo("/session/:sessionId/moz/screenshot/full", HttpMethod.GET));
    Object result = this.executeCustomCommand("mozFullPageScreenshot");
    String base64EncodedPng;
    if (result instanceof String) {
        base64EncodedPng = (String) result;
    } else if (result instanceof byte[]) {
        base64EncodedPng = new String((byte[]) result);
    } else {
        throw new RuntimeException(String.format("Unexpected result for /moz/screenshot/full command: %s",
            result == null ? "null" : result.getClass().getName() + "instance"));
    }
    return decodeBase64EncodedPng(base64EncodedPng);
}
 
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: AbstractHttpCommandCodec.java    From selenium with Apache License 2.0 6 votes vote down vote up
/**
 * Returns whether this instance matches the provided HTTP request.
 *
 * @param method The request method.
 * @param parts The parsed request path segments.
 * @return Whether this instance matches the request.
 */
boolean isFor(HttpMethod method, ImmutableList<String> parts) {
  if (!this.method.equals(method)) {
    return false;
  }

  if (parts.size() != this.pathSegments.size()) {
    return false;
  }

  for (int i = 0; i < parts.size(); ++i) {
    String reqPart = parts.get(i);
    String specPart = pathSegments.get(i);
    if (!(specPart.startsWith(":") || specPart.equals(reqPart))) {
      return false;
    }
  }

  return true;
}
 
Example #4
Source File: JreMessages.java    From selenium with Apache License 2.0 6 votes vote down vote up
static HttpRequest asRequest(HttpExchange exchange) {
  HttpRequest request = new HttpRequest(
    HttpMethod.valueOf(exchange.getRequestMethod()),
    exchange.getRequestURI().getPath());

  String query = exchange.getRequestURI().getQuery();
  if (query != null) {
    Arrays.stream(query.split("&"))
      .map(q -> {
        int i = q.indexOf("=");
        if (i == -1) {
          return new AbstractMap.SimpleImmutableEntry<>(q, "");
        }
        return new AbstractMap.SimpleImmutableEntry<>(q.substring(0, i), q.substring(i + 1));
      })
      .forEach(entry -> request.addQueryParameter(entry.getKey(), entry.getValue()));
  }

  exchange.getRequestHeaders().forEach((name, values) -> values.forEach(value -> request.addHeader(name, value)));

  request.setContent(memoize(exchange::getRequestBody));

  return request;
}
 
Example #5
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 #6
Source File: UploadFileTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldWriteABase64EncodedZippedFileToDiskAndKeepName() 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 tempFile = touch(null, "foo");
  String encoded = Zip.zip(tempFile);

  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);

  Response res = new Json().toType(string(response), Response.class);
  String path = (String) res.getValue();
  assertTrue(new File(path).exists());
  assertTrue(path.endsWith(tempFile.getName()));
}
 
Example #7
Source File: Browser.java    From selenium-shutterbug with MIT License 6 votes vote down vote up
public BufferedImage takeScreenshotEntirePageUsingChromeCommand() {
    //should use devicePixelRatio by default as chrome command executor makes screenshot account for that
    Object devicePixelRatio = executeJsScript(DEVICE_PIXEL_RATIO);
    this.devicePixelRatio = devicePixelRatio instanceof Double ? (Double) devicePixelRatio : (Long) devicePixelRatio * 1.0;

    defineCustomCommand("sendCommand", new CommandInfo("/session/:sessionId/chromium/send_command_and_get_result", HttpMethod.POST));

    int verticalIterations = (int) Math.ceil(((double) this.getDocHeight()) / this.getViewportHeight());
    for (int j = 0; j < verticalIterations; j++) {
        this.scrollTo(0, j * this.getViewportHeight());
        wait(betweenScrollTimeout);
    }
    Object metrics = this.evaluate(FileUtil.getJsScript(ALL_METRICS));
    this.sendCommand("Emulation.setDeviceMetricsOverride", metrics);
    wait(beforeShootCondition,beforeShootTimeout);
    Object result = this.sendCommand("Page.captureScreenshot", ImmutableMap.of("format", "png", "fromSurface", true));
    this.sendCommand("Emulation.clearDeviceMetricsOverride", ImmutableMap.of());
    return decodeBase64EncodedPng((String) ((Map<String, ?>) result).get("data"));
}
 
Example #8
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 #9
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 #10
Source File: ReverseProxyHandlerTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
public Server() throws IOException {
  int port = PortProber.findFreePort();
  String address = new NetworkUtils().getPrivateLocalAddress();
  url = new URL("http", address, port, "/ok");

  server = HttpServer.create(new InetSocketAddress(address, port), 0);
  server.createContext("/ok", ex -> {
    lastRequest = new HttpRequest(
        HttpMethod.valueOf(ex.getRequestMethod()),
        ex.getRequestURI().getPath());
    Headers headers = ex.getRequestHeaders();
    for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
      for (String value : entry.getValue()) {
        lastRequest.addHeader(entry.getKey().toLowerCase(), value);
      }
    }
    try (InputStream in = ex.getRequestBody()) {
      lastRequest.setContent(bytes(ByteStreams.toByteArray(in)));
    }

    byte[] payload = "I like cheese".getBytes(UTF_8);
    ex.sendResponseHeaders(HTTP_OK, payload.length);
    try (OutputStream out = ex.getResponseBody()) {
      out.write(payload);
    }
  });
  server.start();
}
 
Example #11
Source File: ReverseProxyHandlerTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldForwardRequestsToEndPoint() {
  HttpHandler handler = new ReverseProxyHandler(tracer, factory.createClient(server.url));
  HttpRequest req = new HttpRequest(HttpMethod.GET, "/ok");
  req.addHeader("X-Cheese", "Cake");
  handler.execute(req);

  // HTTP headers are case insensitive. This is how the HttpUrlConnection likes to encode things
  assertEquals("Cake", server.lastRequest.getHeader("x-cheese"));
}
 
Example #12
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 #13
Source File: RequestConverter.java    From selenium with Apache License 2.0 5 votes vote down vote up
private HttpRequest createRequest(io.netty.handler.codec.http.HttpRequest nettyRequest) {
  HttpRequest req = new HttpRequest(
      HttpMethod.valueOf(nettyRequest.method().name()),
      nettyRequest.uri());

  nettyRequest.headers().entries().stream()
      .filter(entry -> entry.getKey() != null)
      .forEach(entry -> req.addHeader(entry.getKey(), entry.getValue()));

  return req;
}
 
Example #14
Source File: ExceptionHandlerTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSetErrorCodeForW3cSpec() {
  Exception e = new NoAlertPresentException("This does not exist");
  HttpResponse response = new ExceptionHandler(e).execute(new HttpRequest(HttpMethod.POST, "/session"));

  Map<String, Object> err = new Json().toType(string(response), MAP_TYPE);
  Map<?, ?> value = (Map<?, ?>) err.get("value");
  assertEquals(value.toString(), "no such alert", value.get("error"));
}
 
Example #15
Source File: ServicedSession.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public void stop() {
  // Try and kill the running session. Both W3C and OSS use the same quit endpoint
  try {
    HttpRequest request = new HttpRequest(HttpMethod.DELETE, "/session/" + getId());
    execute(request);
  } catch (UncheckedIOException e) {
    // This is fine.
  }

  service.stop();
}
 
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: ExceptionHandlerTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUnwrapAnExecutionException() {
  Exception noSession = new SessionNotCreatedException("This does not exist");
  Exception e = new ExecutionException(noSession);
  HttpResponse response = new ExceptionHandler(e).execute(new HttpRequest(HttpMethod.POST, "/session"));

  Map<String, Object> err = new Json().toType(string(response), MAP_TYPE);
  Map<?, ?> value = (Map<?, ?>) err.get("value");

  assertEquals(ErrorCodes.SESSION_NOT_CREATED, ((Number) err.get("status")).intValue());
  assertEquals("session not created", value.get("error"));
}
 
Example #19
Source File: AbstractHttpCommandCodec.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public HttpRequest encode(Command command) {
  String name = aliases.getOrDefault(command.getName(), command.getName());
  CommandSpec spec = nameToSpec.get(name);
  if (spec == null) {
    throw new UnsupportedCommandException(command.getName());
  }
  Map<String, ?> parameters = amendParameters(command.getName(), command.getParameters());
  String uri = buildUri(name, command.getSessionId(), parameters, spec);

  HttpRequest request = new HttpRequest(spec.method, uri);

  if (HttpMethod.POST == spec.method) {

    String content = json.toJson(parameters);
    byte[] data = content.getBytes(UTF_8);

    request.setHeader(CONTENT_LENGTH, String.valueOf(data.length));
    request.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());
    request.setContent(bytes(data));
  }

  if (HttpMethod.GET == spec.method) {
    request.setHeader(CACHE_CONTROL, "no-cache");
  }

  return request;
}
 
Example #20
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 #21
Source File: ChromiumDriverCommandExecutor.java    From selenium with Apache License 2.0 5 votes vote down vote up
private static Map<String, CommandInfo> buildChromiumCommandMappings(String vendorKeyword) {
  String sessionPrefix = "/session/:sessionId/";
  String chromiumPrefix = sessionPrefix + "chromium";
  String vendorPrefix = sessionPrefix + vendorKeyword;

  HashMap<String, CommandInfo> mappings = new HashMap<>();

  mappings.put(ChromiumDriverCommand.LAUNCH_APP,
    new CommandInfo(chromiumPrefix + "/launch_app", HttpMethod.POST));

  String networkConditions = chromiumPrefix + "/network_conditions";
  mappings.put(ChromiumDriverCommand.GET_NETWORK_CONDITIONS,
    new CommandInfo(networkConditions, HttpMethod.GET));
  mappings.put(ChromiumDriverCommand.SET_NETWORK_CONDITIONS,
    new CommandInfo(networkConditions, HttpMethod.POST));
  mappings.put(ChromiumDriverCommand.DELETE_NETWORK_CONDITIONS,
    new CommandInfo(networkConditions, HttpMethod.DELETE));

  mappings.put( ChromiumDriverCommand.EXECUTE_CDP_COMMAND,
    new CommandInfo(vendorPrefix + "/cdp/execute", HttpMethod.POST));

  // Cast / Media Router APIs
  String cast = vendorPrefix + "/cast";
  mappings.put(ChromiumDriverCommand.GET_CAST_SINKS,
    new CommandInfo(cast + "/get_sinks", HttpMethod.GET));
  mappings.put(ChromiumDriverCommand.SET_CAST_SINK_TO_USE,
    new CommandInfo(cast + "/set_sink_to_use", HttpMethod.POST));
  mappings.put(ChromiumDriverCommand.START_CAST_TAB_MIRRORING,
    new CommandInfo(cast + "/start_tab_mirroring", HttpMethod.POST));
  mappings.put(ChromiumDriverCommand.GET_CAST_ISSUE_MESSAGE,
    new CommandInfo(cast + "/get_issue_message", HttpMethod.GET));
  mappings.put(ChromiumDriverCommand.STOP_CASTING,
    new CommandInfo(cast + "/stop_casting", HttpMethod.POST));

  mappings.put(ChromiumDriverCommand.SET_PERMISSION,
    new CommandInfo(sessionPrefix + "/permissions", HttpMethod.POST));

  return unmodifiableMap(mappings);
}
 
Example #22
Source File: CommandInfo.java    From hifive-pitalium with Apache License 2.0 4 votes vote down vote up
public CommandInfo(String url, HttpMethod method) {
	this.url = url;
	this.method = method;
}
 
Example #23
Source File: ChromeDevToolsNetworkTest.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Test
public void verifyRequestPostData() {

  devTools.send(enable(Optional.empty(), Optional.empty(), Optional.empty()));

  final RequestId[] requestIds = new RequestId[1];

  devTools.addListener(requestWillBeSent(), requestWillBeSent -> {
    Assert.assertNotNull(requestWillBeSent);
    if (requestWillBeSent.getRequest().getMethod().equalsIgnoreCase(HttpMethod.POST.name())) {
      requestIds[0] = requestWillBeSent.getRequestId();
    }
  });

  driver.get(appServer.whereIs("postForm.html"));

  driver.findElement(By.xpath("/html/body/form/input")).click();

  Assert.assertNotNull(devTools.send(getRequestPostData(requestIds[0])));

}
 
Example #24
Source File: CommandInfo.java    From selenium with Apache License 2.0 4 votes vote down vote up
public CommandInfo(String url, HttpMethod method) {
  this.url = url;
  this.method = method;
}
 
Example #25
Source File: AbstractHttpCommandCodec.java    From selenium with Apache License 2.0 4 votes vote down vote up
private CommandSpec(HttpMethod method, String path) {
  this.method = Require.nonNull("HTTP method", method);
  this.path = path;
  this.pathSegments = ImmutableList.copyOf(PATH_SPLITTER.split(path));
}
 
Example #26
Source File: AbstractHttpCommandCodec.java    From selenium with Apache License 2.0 4 votes vote down vote up
protected static CommandSpec post(String path) {
  return new CommandSpec(HttpMethod.POST, path);
}
 
Example #27
Source File: StatusBasedReadinessCheck.java    From selenium with Apache License 2.0 4 votes vote down vote up
public StatusBasedReadinessCheck(HttpHandler handler, HttpMethod method, String url) {
  this.handler = Require.nonNull("handler", handler);
  this.method = Require.nonNull("HTTP method", method);
  this.url = Require.nonNull("URL for status", url);
}
 
Example #28
Source File: AbstractHttpCommandCodec.java    From selenium with Apache License 2.0 4 votes vote down vote up
protected static CommandSpec get(String path) {
  return new CommandSpec(HttpMethod.GET, path);
}
 
Example #29
Source File: ServletRequestWrappingHttpRequest.java    From selenium with Apache License 2.0 4 votes vote down vote up
ServletRequestWrappingHttpRequest(HttpServletRequest req) {
  super(HttpMethod.valueOf(req.getMethod()), req.getPathInfo() == null ? "/" : req.getPathInfo());

  this.req = req;
}
 
Example #30
Source File: AbstractHttpCommandCodec.java    From selenium with Apache License 2.0 4 votes vote down vote up
protected static CommandSpec delete(String path) {
  return new CommandSpec(HttpMethod.DELETE, path);
}