类org.openqa.selenium.remote.http.HttpMethod源码实例Demo

下面列出了怎么用org.openqa.selenium.remote.http.HttpMethod的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: selenium-shutterbug   文件: Browser.java
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"));
}
 
源代码2 项目: selenium-shutterbug   文件: Browser.java
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);
}
 
源代码3 项目: selenium   文件: AbstractHttpCommandCodec.java
/**
 * 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;
}
 
源代码4 项目: selenium   文件: JreAppServer.java
@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);
  }
}
 
源代码5 项目: selenium   文件: JreMessages.java
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;
}
 
源代码6 项目: selenium   文件: AllHandlers.java
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")))))
      ));
}
 
源代码7 项目: selenium   文件: UploadFileTest.java
@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()));
}
 
源代码8 项目: selenium   文件: ChromiumDriverCommandExecutor.java
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);
}
 
源代码9 项目: selenium   文件: ProtocolHandshake.java
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();
}
 
源代码10 项目: selenium   文件: AbstractHttpCommandCodec.java
@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;
}
 
源代码11 项目: selenium   文件: AppServerTestBase.java
@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)));
}
 
源代码12 项目: selenium   文件: JettyAppServer.java
@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);
  }
}
 
源代码13 项目: selenium   文件: ServicedSession.java
@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();
}
 
源代码14 项目: selenium   文件: RequestConverter.java
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;
}
 
源代码15 项目: selenium   文件: ReverseProxyHandlerTest.java
@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"));
}
 
源代码16 项目: selenium   文件: ReverseProxyHandlerTest.java
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();
}
 
源代码17 项目: selenium   文件: SessionLogsTest.java
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");
}
 
源代码18 项目: selenium   文件: UploadFileTest.java
@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
  }
}
 
源代码19 项目: selenium   文件: ExceptionHandlerTest.java
@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());
}
 
源代码20 项目: selenium   文件: ExceptionHandlerTest.java
@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"));
}
 
源代码21 项目: selenium   文件: ExceptionHandlerTest.java
@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"));
}
 
源代码22 项目: hifive-pitalium   文件: CommandInfo.java
public CommandInfo(String url, HttpMethod method) {
	this.url = url;
	this.method = method;
}
 
源代码23 项目: hifive-pitalium   文件: CommandInfo.java
HttpMethod getMethod() {
	return method;
}
 
源代码24 项目: selenium   文件: AbstractHttpCommandCodec.java
protected static CommandSpec delete(String path) {
  return new CommandSpec(HttpMethod.DELETE, path);
}
 
源代码25 项目: selenium   文件: AbstractHttpCommandCodec.java
protected static CommandSpec get(String path) {
  return new CommandSpec(HttpMethod.GET, path);
}
 
源代码26 项目: selenium   文件: AbstractHttpCommandCodec.java
protected static CommandSpec post(String path) {
  return new CommandSpec(HttpMethod.POST, path);
}
 
源代码27 项目: selenium   文件: AbstractHttpCommandCodec.java
private CommandSpec(HttpMethod method, String path) {
  this.method = Require.nonNull("HTTP method", method);
  this.path = path;
  this.pathSegments = ImmutableList.copyOf(PATH_SPLITTER.split(path));
}
 
源代码28 项目: selenium   文件: CommandInfo.java
public CommandInfo(String url, HttpMethod method) {
  this.url = url;
  this.method = method;
}
 
源代码29 项目: selenium   文件: CommandInfo.java
HttpMethod getMethod() {
  return method;
}
 
源代码30 项目: selenium   文件: ChromeDevToolsNetworkTest.java
@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])));

}
 
 类所在包
 类方法
 同包方法