下面列出了怎么用org.openqa.selenium.remote.Response的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
@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);
}
@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);
}
}
@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;
}
@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;
}
/**
* 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();
}
@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()));
}
@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);
}
/**
* 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();
}
}
}
@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;
}
/**
* 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;
}
@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();
}
@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);
}
@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");
}
@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");
}
@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");
}
@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());
}
@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());
}
@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);
}
private SessionId createSession() throws IOException, ServletException {
Map<String, Object> caps = ImmutableMap.of("desiredCapabilities", ImmutableMap.of());
FakeHttpServletResponse response = sendCommand("POST", "/session", caps);
assertEquals(HttpServletResponse.SC_OK, response.getStatus());
Response resp = json.toType(response.getBody(), Response.class);
String sessionId = resp.getSessionId();
assertNotNull(sessionId);
assertFalse(sessionId.isEmpty());
return new SessionId(sessionId);
}
@Override
protected Response execute(String driverCommand, Map<String, ?> parameters) {
if (driverCommand.equalsIgnoreCase(DriverCommand.QUIT)) {
return new Response();
}
return super.execute(driverCommand, parameters);
}
@Override
protected Response execute(String driverCommand, Map<String, ?> parameters) {
CommandTracker commandTracker = new CommandTracker(driverCommand, parameters);
try {
beforeCommand(this, commandTracker);
// already handled in before command?
if (commandTracker.getResponce() == null) {
commandTracker.setStartTime(System.currentTimeMillis());
commandTracker.setResponce(super.execute(commandTracker.getCommand(), commandTracker.getParameters()));
commandTracker.setEndTime(System.currentTimeMillis());
}
afterCommand(this, commandTracker);
} catch (RuntimeException wde) {
commandTracker.setException(wde);
onFailure(this, commandTracker);
}
if (commandTracker.hasException()) {
if (commandTracker.retry) {
commandTracker.setResponce(super.execute(commandTracker.getCommand(), commandTracker.getParameters()));
commandTracker.setException(null);
commandTracker.setEndTime(System.currentTimeMillis());
} else {
throw commandTracker.getException();
}
}
return commandTracker.getResponce();
}
public Object sendCommand(String cmd, Object params) {
try {
Method execute = RemoteWebDriver.class.getDeclaredMethod("execute", String.class, Map.class);
execute.setAccessible(true);
Response res = (Response) execute.invoke(driver, "sendCommand", ImmutableMap.of("cmd", cmd, "params", params));
return res.getValue();
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public Object executeCustomCommand(String commandName) {
try {
Method execute = RemoteWebDriver.class.getDeclaredMethod("execute", String.class);
execute.setAccessible(true);
Response res = (Response) execute.invoke(this.driver, commandName);
return res.getValue();
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Override
protected Response execute(final String command, final Map<String, ?> parameters) {
PtlWebElement parent = getFrameParent();
if (parent == null) {
return super.execute(command, parameters);
}
// in frame
return executeInFrame(parent, new Supplier<Response>() {
@Override
public Response get() {
return PtlWebElement.super.execute(command, parameters);
}
});
}
/**
* This method executes a command supported by Appium JSONWP.
*
* @param commandName a JSONWP command
* @param parameters is a map which contains parameter names as keys and parameter values
* @return a command execution result
*/
public Object execute(String commandName, Map<String, ?> parameters) {
Response response;
if (parameters == null || parameters.isEmpty()) {
response = driver.execute(commandName, ImmutableMap.of());
} else {
response = driver.execute(commandName, parameters);
}
return response.getValue();
}
@Override
public HttpResponse execute(HttpRequest req) throws UncheckedIOException {
String originalPayload = string(req);
Map<String, Object> args = json.toType(originalPayload, Json.MAP_TYPE);
String type = (String) args.get("type");
if (!LogType.SERVER.equals(type)) {
HttpRequest upReq = new HttpRequest(POST, String.format("/session/%s/log", session.getId()));
upReq.setContent(utf8String(originalPayload));
return session.execute(upReq);
}
LogEntries entries = null;
try {
entries = LoggingManager.perSessionLogHandler().getSessionLog(session.getId());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
Response response = new Response(session.getId());
response.setStatus(ErrorCodes.SUCCESS);
response.setValue(entries);
HttpResponse resp = new HttpResponse();
session.getDownstreamDialect().getResponseCodec().encode(() -> resp, response);
return resp;
}
@Override
public Set<String> getContextHandles() {
Response response = execute(DriverCommand.GET_CONTEXT_HANDLES);
Object value = response.getValue();
try {
List<String> returnedValues = (List<String>) value;
return new LinkedHashSet<>(returnedValues);
} catch (ClassCastException ex) {
throw new WebDriverException(
"Returned value cannot be converted to List<String>: " + value, ex);
}
}
@Override
public DeviceRotation rotation() {
Response response = execute(DriverCommand.GET_SCREEN_ROTATION);
DeviceRotation deviceRotation =
new DeviceRotation((Map<String, Number>) response.getValue());
if (deviceRotation.getX() < 0 || deviceRotation.getY() < 0 || deviceRotation.getZ() < 0) {
throw new WebDriverException("Unexpected orientation returned: " + deviceRotation);
}
return deviceRotation;
}
@Override
public ScreenOrientation getOrientation() {
Response response = execute(DriverCommand.GET_SCREEN_ORIENTATION);
String orientation = response.getValue().toString().toLowerCase();
if (orientation.equals(ScreenOrientation.LANDSCAPE.value())) {
return ScreenOrientation.LANDSCAPE;
} else if (orientation.equals(ScreenOrientation.PORTRAIT.value())) {
return ScreenOrientation.PORTRAIT;
} else {
throw new WebDriverException("Unexpected orientation returned: " + orientation);
}
}