org.openqa.selenium.remote.Response Java Examples

The following examples show how to use org.openqa.selenium.remote.Response. 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: HasSessionDetails.java    From java-client with Apache License 2.0 6 votes vote down vote up
/**
 * The current session details.
 *
 * @return a map with values that hold session details.
 */
@SuppressWarnings("unchecked")
default Map<String, Object> getSessionDetails() {
    Response response = execute(GET_SESSION);
    Map<String, Object> resultMap = Map.class.cast(response.getValue());

    //this filtering was added to clear returned result.
    //results of further operations should be simply interpreted by users
    return  ImmutableMap.<String, Object>builder()
            .putAll(resultMap.entrySet()
                    .stream().filter(entry -> {
                        String key = entry.getKey();
                        Object value = entry.getValue();
                        return !isBlank(key)
                            && value != null
                            && !isBlank(String.valueOf(value));
                    }).collect(toMap(Map.Entry::getKey, Map.Entry::getValue))).build();
}
 
Example #2
Source File: QAFExtendedWebElement.java    From qaf with MIT License 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void onFailure(QAFExtendedWebElement element, CommandTracker commandTracker) {
	commandTracker.setStage(Stage.executingOnFailure);
	commandTracker.setEndTime(System.currentTimeMillis());

	if (commandTracker.getException() instanceof StaleElementReferenceException) {
		logger.warn(commandTracker.getException().getMessage());
		element.setId("-1");
		Map parameters = commandTracker.getParameters();
		parameters.put("id", element.getId());
		commandTracker.setException(null);
		commandTracker.setStage(Stage.executingMethod);
		Response response = element.execute(commandTracker.command, parameters);
		commandTracker.setEndTime(System.currentTimeMillis());
		commandTracker.setResponce(response);
	}
	for (QAFWebElementCommandListener listener : listners) {
		// whether handled previous listener
		if (!commandTracker.hasException()) {
			break;
		}
		logger.debug("Executing listener " + listener.getClass().getName());
		listener.onFailure(element, commandTracker);
	}
}
 
Example #3
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 #4
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 #5
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 #6
Source File: W3CHttpResponseCodecTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void decodingAnErrorWithoutAStacktraceIsDecodedProperlyForConformingImplementations() {
  Map<String, Object> error = new HashMap<>();
  error.put("error", "unsupported operation");  // 500
  error.put("message", "I like peas");
  error.put("stacktrace", "");
  Map<String, Object> data = new HashMap<>();
  data.put("value", error);

  HttpResponse response = createValidResponse(HTTP_INTERNAL_ERROR, data);

  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 #7
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 #8
Source File: WebDriverWaitTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldIncludeRemoteInfoForWrappedDriverTimeout() throws IOException {
  Capabilities caps = new MutableCapabilities();
  Response response = new Response(new SessionId("foo"));
  response.setValue(caps.asMap());
  CommandExecutor executor = mock(CommandExecutor.class);
  when(executor.execute(any(Command.class))).thenReturn(response);

  RemoteWebDriver driver = new RemoteWebDriver(executor, caps);
  WebDriver testDriver = mock(WebDriver.class, withSettings().extraInterfaces(WrapsDriver.class));
  when(((WrapsDriver) testDriver).getWrappedDriver()).thenReturn(driver);

  TickingClock clock = new TickingClock();
  WebDriverWait wait =
      new WebDriverWait(testDriver, Duration.ofSeconds(1), Duration.ofMillis(200), clock, clock);

  assertThatExceptionOfType(TimeoutException.class)
      .isThrownBy(() -> wait.until(d -> false))
      .withMessageContaining("Capabilities {javascriptEnabled: true, platform: ANY, platformName: ANY}")
      .withMessageContaining("Session ID: foo");
}
 
Example #9
Source File: Status.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public Response handle() {
  Response response = new Response();
  response.setStatus(ErrorCodes.SUCCESS);
  response.setState(ErrorCodes.SUCCESS_STRING);

  BuildInfo buildInfo = new BuildInfo();

  Object info = ImmutableMap.of(
      "ready", true,
      "message", "Server is running",
      "build", ImmutableMap.of(
          "version", buildInfo.getReleaseLabel(),
          "revision", buildInfo.getBuildRevision()),
      "os", ImmutableMap.of(
          "name", System.getProperty("os.name"),
          "arch", System.getProperty("os.arch"),
          "version", System.getProperty("os.version")),
      "java", ImmutableMap.of("version", System.getProperty("java.version")));

  response.setValue(info);
  return response;
}
 
Example #10
Source File: GetLogTypes.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse execute(HttpRequest req) throws UncheckedIOException {
  // Try going upstream first. It's okay if this fails.
  HttpRequest upReq = new HttpRequest(GET, String.format("/session/%s/log/types", session.getId()));
  HttpResponse upRes = session.execute(upReq);

  ImmutableSet.Builder<String> types = ImmutableSet.builder();
  types.add(LogType.SERVER);

  if (upRes.getStatus() == HTTP_OK) {
    Map<String, Object> upstream = json.toType(string(upRes), Json.MAP_TYPE);
    Object raw = upstream.get("value");
    if (raw instanceof Collection) {
      ((Collection<?>) raw).stream().map(String::valueOf).forEach(types::add);
    }
  }

  Response response = new Response(session.getId());
  response.setValue(types.build());
  response.setStatus(ErrorCodes.SUCCESS);

  HttpResponse resp = new HttpResponse();
  session.getDownstreamDialect().getResponseCodec().encode(() -> resp, response);
  return resp;
}
 
Example #11
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAttemptToConvertAnExceptionIntoAnActualExceptionInstance() {
  Response response = new Response();
  response.setStatus(ErrorCodes.ASYNC_SCRIPT_TIMEOUT);
  WebDriverException exception = new ScriptTimeoutException("I timed out");
  response.setValue(exception);

  HttpResponse httpResponse = new HttpResponse();
  httpResponse.setStatus(HTTP_CLIENT_TIMEOUT);
  httpResponse.setContent(asJson(response));

  Response decoded = codec.decode(httpResponse);
  assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.ASYNC_SCRIPT_TIMEOUT);

  WebDriverException seenException = (WebDriverException) decoded.getValue();
  assertThat(seenException.getClass()).isEqualTo(exception.getClass());
  assertThat(seenException.getMessage().startsWith(exception.getMessage())).isTrue();
}
 
Example #12
Source File: AbstractHttpResponseCodec.java    From selenium with Apache License 2.0 6 votes vote down vote up
/**
 * Encodes the given response as a HTTP response message. This method is guaranteed not to throw.
 *
 * @param response The response to encode.
 * @return The encoded response.
 */
@Override
public HttpResponse encode(Supplier<HttpResponse> factory, Response response) {
  int status = response.getStatus() == ErrorCodes.SUCCESS
               ? HTTP_OK
               : HTTP_INTERNAL_ERROR;

  byte[] data = json.toJson(getValueToEncode(response)).getBytes(UTF_8);

  HttpResponse httpResponse = factory.get();
  httpResponse.setStatus(status);
  httpResponse.setHeader(CACHE_CONTROL, "no-cache");
  httpResponse.setHeader(EXPIRES, "Thu, 01 Jan 1970 00:00:00 GMT");
  httpResponse.setHeader(CONTENT_LENGTH, String.valueOf(data.length));
  httpResponse.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());
  httpResponse.setContent(bytes(data));

  return httpResponse;
}
 
Example #13
Source File: W3CHttpResponseCodec.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
protected Object getValueToEncode(Response response) {
  HashMap<Object, Object> toReturn = new HashMap<>();
  Object value = response.getValue();
  if (value instanceof WebDriverException) {
    HashMap<Object, Object> exception = new HashMap<>();
    exception.put(
        "error",
        response.getState() != null ?
        response.getState() :
        errorCodes.toState(response.getStatus()));
    exception.put("message", ((WebDriverException) value).getMessage());
    exception.put("stacktrace", Throwables.getStackTraceAsString((WebDriverException) value));
    if (value instanceof UnhandledAlertException) {
      HashMap<String, Object> data = new HashMap<>();
      data.put("text", ((UnhandledAlertException) value).getAlertText());
      exception.put("data", data);
    }

    value = exception;
  }
  toReturn.put("value", value);
  return toReturn;
}
 
Example #14
Source File: JsonTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void canHandleValueBeingAnArray() {
  String[] value = {"Cheese", "Peas"};

  Response response = new Response();
  response.setSessionId("bar");
  response.setValue(value);
  response.setStatus(1512);

  String json = new Json().toJson(response);
  Response converted = new Json().toType(json, Response.class);

  assertThat(response.getSessionId()).isEqualTo("bar");
  assertThat(((List<?>) converted.getValue())).hasSize(2);
  assertThat(response.getStatus().intValue()).isEqualTo(1512);
}
 
Example #15
Source File: DriverCommandExecutor.java    From selenium with Apache License 2.0 6 votes vote down vote up
/**
 * Sends the {@code command} to the driver server for execution. The server will be started
 * if requesting a new session. Likewise, if terminating a session, the server will be shutdown
 * once a response is received.
 *
 * @param command The command to execute.
 * @return The command response.
 * @throws IOException If an I/O error occurs while sending the command.
 */
@Override
public Response execute(Command command) throws IOException {
  if (DriverCommand.NEW_SESSION.equals(command.getName())) {
    service.start();
  }

  try {
    return super.execute(command);
  } catch (Throwable t) {
    Throwable rootCause = Throwables.getRootCause(t);
    if (rootCause instanceof ConnectException &&
        "Connection refused".equals(rootCause.getMessage()) &&
        !service.isRunning()) {
      throw new WebDriverException("The driver server has unexpectedly died!", t);
    }
    Throwables.throwIfUnchecked(t);
    throw new WebDriverException(t);
  } finally {
    if (DriverCommand.QUIT.equals(command.getName())) {
      service.stop();
    }
  }
}
 
Example #16
Source File: AndroidTest.java    From java-client with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    startsActivity = new StartsActivity() {
        @Override
        public Response execute(String driverCommand, Map<String, ?> parameters) {
            return driver.execute(driverCommand, parameters);
        }

        @Override
        public Response execute(String driverCommand) {
            return driver.execute(driverCommand);
        }
    };
    Activity activity = new Activity("io.appium.android.apis", ".ApiDemos");
    startsActivity.startActivity(activity);
}
 
Example #17
Source File: ExecuteCommand.java    From opentest with MIT License 6 votes vote down vote up
@Override
public void run() {
    String command = this.readStringArgument("command");
    Map<String, Object> commandArgs = this.readMapArgument("commandArgs", null);

    Response response = this.driver.execute(command, commandArgs);
    
    String sessionId = response.getSessionId();
    String state = response.getState();
    int status = response.getStatus();
    Object value = response.getValue();
    
    this.writeOutput("sessionId", sessionId);
    this.writeOutput("state", state);
    this.writeOutput("status", status);
    this.writeOutput("value", value);
}
 
Example #18
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 #19
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeNonJsonResponse_200() {
  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(utf8String("{\"foobar\"}"));

  Response decoded = codec.decode(response);
  assertThat(decoded.getStatus().longValue()).isEqualTo(0);
  assertThat(decoded.getValue()).isEqualTo("{\"foobar\"}");
}
 
Example #20
Source File: JsonTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConvertInvalidSelectorError() {
  Response response = new Json().toType(
      "{\"state\":\"invalid selector\",\"message\":\"invalid xpath selector\"}",
      Response.class);
  assertThat(response.getStatus().intValue()).isEqualTo(32);
  assertThat(response.getState()).isEqualTo(new ErrorCodes().toState(32));
}
 
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: JsonTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConvertAResponseWithAnElementInIt() {
  String json =
      "{\"value\":{\"value\":\"\",\"text\":\"\",\"selected\":false,\"enabled\":true,\"id\":\"three\"},\"context\":\"con\",\"sessionId\":\"sess\"}";
  Response converted = new Json().toType(json, Response.class);

  Map<String, Object> value = (Map<String, Object>) converted.getValue();
  assertThat(value).containsEntry("id", "three");
}
 
Example #23
Source File: JsonHttpResponseCodec.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
protected Response reconstructValue(Response response) {
  try {
    errorHandler.throwIfResponseFailed(response, 0);
  } catch (Exception e) {
    response.setValue(e);
  }

  response.setValue(elementConverter.apply(response.getValue()));

  return response;
}
 
Example #24
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeJsonResponseMissingContentType() {
  Response response = new Response();
  response.setStatus(ErrorCodes.SUCCESS);
  response.setValue(ImmutableMap.of("color", "red"));

  HttpResponse httpResponse = new HttpResponse();
  httpResponse.setStatus(HTTP_OK);
  httpResponse.setContent(asJson(response));

  Response decoded = codec.decode(httpResponse);
  assertThat(decoded.getStatus()).isEqualTo(response.getStatus());
  assertThat(decoded.getSessionId()).isEqualTo(response.getSessionId());
  assertThat(decoded.getValue()).isEqualTo(response.getValue());
}
 
Example #25
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeUtf16EncodedResponse() {
  HttpResponse httpResponse = new HttpResponse();
  httpResponse.setStatus(200);
  httpResponse.setHeader(CONTENT_TYPE, JSON_UTF_8.withCharset(UTF_16).toString());
  httpResponse.setContent(string("{\"status\":0,\"value\":\"水\"}", UTF_16));

  Response response = codec.decode(httpResponse);
  assertThat(response.getValue()).isEqualTo("水");
}
 
Example #26
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeJsonResponseWithTrailingNullBytes() {
  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(utf8String("{\"status\":0,\"value\":\"foo\"}\0\0"));

  Response decoded = codec.decode(response);
  assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.SUCCESS);
  assertThat(decoded.getValue()).isEqualTo("foo");
}
 
Example #27
Source File: JavaDriverCommandExecutor.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
@Override
public Response execute(Command command) throws IOException {
    if (!this.started) {
        start();
        this.started = true;
    }
    if (QUIT.equals(command.getName())) {
        stop();
    }
    return super.execute(command);
}
 
Example #28
Source File: HasSessionDetails.java    From java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Get All Sessions details.
 * 
 * @return List of Map objects with All Session Details.
 */
@SuppressWarnings("unchecked")
default List<Map<String, Object>> getAllSessionDetails() {
    Response response = execute(GET_ALLSESSION);
    List<Map<String,Object>> resultSet = List.class.cast(response.getValue());
    return ImmutableList.<Map<String,Object>>builder().addAll(resultSet).build();
}
 
Example #29
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConvertElementReferenceToRemoteWebElement() {
  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(asJson(ImmutableMap.of(
      "status", 0,
      "value", ImmutableMap.of(Dialect.OSS.getEncodedElementKey(), "345678"))));

  Response decoded = codec.decode(response);
  assertThat(((RemoteWebElement) decoded.getValue()).getId()).isEqualTo("345678");
}
 
Example #30
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
  }
}