Best Selenium code snippet using org.openqa.selenium.remote.Response.setStatus
Source:GridStatusHandler.java
...90 try {91 status = EXECUTOR_SERVICE.submit(span.wrap(distributor::getStatus)).get(2, SECONDS);92 } catch (ExecutionException | TimeoutException e) {93 span.setAttribute("error", true);94 span.setStatus(Status.CANCELLED);95 EXCEPTION.accept(attributeMap, e);96 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),97 EventAttribute.setValue("Unable to get distributor status due to execution error or timeout: " + e.getMessage()));98 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);99 return new HttpResponse().setContent(asJson(100 ImmutableMap.of("value", ImmutableMap.of(101 "ready", false,102 "message", "Unable to read distributor status."))));103 } catch (InterruptedException e) {104 span.setAttribute("error", true);105 span.setStatus(Status.ABORTED);106 EXCEPTION.accept(attributeMap, e);107 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),108 EventAttribute.setValue("Interruption while getting distributor status: " + e.getMessage()));109 Thread.currentThread().interrupt();110 return new HttpResponse().setContent(asJson(111 ImmutableMap.of("value", ImmutableMap.of(112 "ready", false,113 "message", "Reading distributor status was interrupted."))));114 }115 boolean ready = status.hasCapacity();116 long remaining = System.currentTimeMillis() + 2000 - start;117 List<Future<Map<String, Object>>> nodeResults = status.getNodes().stream()118 .map(node -> {119 ImmutableMap<String, Object> defaultResponse = ImmutableMap.of(120 "id", node.getId(),121 "uri", node.getUri(),122 "maxSessions", node.getMaxSessionCount(),123 "slots", node.getSlots(),124 "warning", "Unable to read data from node.");125 CompletableFuture<Map<String, Object>> toReturn = new CompletableFuture<>();126 Future<?> future = EXECUTOR_SERVICE.submit(127 () -> {128 try {129 HttpClient client = clientFactory.createClient(node.getUri().toURL());130 HttpRequest nodeStatusReq = new HttpRequest(GET, "/se/grid/node/status");131 HttpTracing.inject(tracer, span, nodeStatusReq);132 HttpResponse res = client.execute(nodeStatusReq);133 toReturn.complete(res.getStatus() == 200134 ? json.toType(string(res), MAP_TYPE)135 : defaultResponse);136 } catch (IOException e) {137 toReturn.complete(defaultResponse);138 }139 });140 SCHEDULED_SERVICE.schedule(141 () -> {142 if (!toReturn.isDone()) {143 toReturn.complete(defaultResponse);144 future.cancel(true);145 }146 },147 remaining,148 MILLISECONDS);149 return toReturn;150 })151 .collect(toList());152 ImmutableMap.Builder<String, Object> value = ImmutableMap.builder();153 value.put("ready", ready);154 value.put("message", ready ? "Selenium Grid ready." : "Selenium Grid not ready.");155 value.put("nodes", nodeResults.stream()156 .map(summary -> {157 try {158 return summary.get();159 } catch (ExecutionException e) {160 span.setAttribute("error", true);161 span.setStatus(Status.NOT_FOUND);162 EXCEPTION.accept(attributeMap, e);163 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),164 EventAttribute.setValue("Unable to get Node information: " + e.getMessage()));165 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);166 throw wrap(e);167 } catch (InterruptedException e) {168 span.setAttribute("error", true);169 span.setStatus(Status.NOT_FOUND);170 EXCEPTION.accept(attributeMap, e);171 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),172 EventAttribute.setValue("Unable to get Node information: " + e.getMessage()));173 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);174 Thread.currentThread().interrupt();175 throw wrap(e);176 }177 })178 .collect(toList()));179 HttpResponse res = new HttpResponse().setContent(asJson(ImmutableMap.of("value", value.build())));180 HTTP_RESPONSE.accept(span, res);181 HTTP_RESPONSE_EVENT.accept(attributeMap, res);182 attributeMap.put("grid.status", EventAttribute.setValue(ready));183 span.setStatus(Status.OK);184 span.addEvent("Computed grid status", attributeMap);185 return res;186 }187 }188 private RuntimeException wrap(Exception e) {189 if (e instanceof InterruptedException) {190 Thread.currentThread().interrupt();191 return new RuntimeException(e);192 }193 Throwable cause = e.getCause();194 if (cause == null) {195 return e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);196 }197 return cause instanceof RuntimeException ? (RuntimeException) cause...
Source:AppiumProtocolHandShake.java
...124 // session, create an exception and throw it.125 Response tempResponse = null;126 if ("session not created".equals(w3cError)) {127 tempResponse = new Response(null);128 tempResponse.setStatus(SESSION_NOT_CREATED);129 tempResponse.setValue(jsonBlob);130 } else if (131 ossStatus instanceof Number132 && ((Number) ossStatus).intValue() == SESSION_NOT_CREATED) {133 tempResponse = new Response(null);134 tempResponse.setStatus(SESSION_NOT_CREATED);135 tempResponse.setValue(jsonBlob);136 }137 if (tempResponse != null) {138 new ErrorHandler().throwIfResponseFailed(tempResponse, 0);139 }140 // Otherwise, just return empty.141 return Optional.empty();142 }143 private void amendW3CParameters(JsonObject jsonObject, JsonElement desired,144 JsonElement required) {145 JsonArray result = new JsonArray();146 JsonObject desiredJson = new JsonObject();147 JsonObject requiredJson = new JsonObject();148 desiredJson.add("desiredCapabilities", desired);149 requiredJson.add("requiredCapabilities", required);150 result.add(desiredJson);151 result.add(requiredJson);152 jsonObject.add("capabilities", result);153 }154 private void amendOssParamters(155 JsonObject jsonObject, JsonElement desired,156 JsonElement required) {157 jsonObject.add("desiredCapabilities", desired);158 jsonObject.add("requiredCapabilities", required);159 }160 public class Result {161 private final Dialect dialect;162 private final Map<String, ?> capabilities;163 private final SessionId sessionId;164 private Result(Dialect dialect, String sessionId, Map<String, ?> capabilities) {165 this.dialect = dialect;166 this.sessionId = new SessionId(Preconditions.checkNotNull(sessionId));167 this.capabilities = capabilities;168 }169 public Dialect getDialect() {170 return dialect;171 }172 public Response createResponse() {173 Response response = new Response(sessionId);174 response.setValue(capabilities);175 response.setStatus(SUCCESS);176 return response;177 }178 @Override179 public String toString() {180 return String.format("%s: %s", dialect, capabilities);181 }182 }183}...
Source:JsonHttpResponseCodecTest.java
...41 private final JsonHttpResponseCodec codec = new JsonHttpResponseCodec();42 @Test43 public void convertsResponses_success() {44 Response response = new Response();45 response.setStatus(ErrorCodes.SUCCESS);46 response.setValue(ImmutableMap.of("color", "red"));47 HttpResponse converted = codec.encode(HttpResponse::new, response);48 assertThat(converted.getStatus()).isEqualTo(HTTP_OK);49 assertThat(converted.getHeader(CONTENT_TYPE)).isEqualTo(JSON_UTF_8.toString());50 Response rebuilt = new Json().toType(string(converted), Response.class);51 assertThat(rebuilt.getStatus()).isEqualTo(response.getStatus());52 assertThat(rebuilt.getState()).isEqualTo(new ErrorCodes().toState(response.getStatus()));53 assertThat(rebuilt.getSessionId()).isEqualTo(response.getSessionId());54 assertThat(rebuilt.getValue()).isEqualTo(response.getValue());55 }56 @Test57 public void convertsResponses_failure() {58 Response response = new Response();59 response.setStatus(ErrorCodes.NO_SUCH_ELEMENT);60 response.setValue(ImmutableMap.of("color", "red"));61 HttpResponse converted = codec.encode(HttpResponse::new, response);62 assertThat(converted.getStatus()).isEqualTo(HTTP_INTERNAL_ERROR);63 assertThat(converted.getHeader(CONTENT_TYPE)).isEqualTo(JSON_UTF_8.toString());64 Response rebuilt = new Json().toType(string(converted), Response.class);65 assertThat(rebuilt.getStatus()).isEqualTo(response.getStatus());66 assertThat(rebuilt.getState()).isEqualTo(new ErrorCodes().toState(response.getStatus()));67 assertThat(rebuilt.getSessionId()).isEqualTo(response.getSessionId());68 assertThat(rebuilt.getValue()).isEqualTo(response.getValue());69 }70 @Test71 public void roundTrip() {72 Response response = new Response();73 response.setStatus(ErrorCodes.SUCCESS);74 response.setValue(ImmutableMap.of("color", "red"));75 HttpResponse httpResponse = codec.encode(HttpResponse::new, response);76 Response decoded = codec.decode(httpResponse);77 assertThat(decoded.getStatus()).isEqualTo(response.getStatus());78 assertThat(decoded.getSessionId()).isEqualTo(response.getSessionId());79 assertThat(decoded.getValue()).isEqualTo(response.getValue());80 }81 @Test82 public void decodeNonJsonResponse_200() {83 HttpResponse response = new HttpResponse();84 response.setStatus(HTTP_OK);85 response.setContent(utf8String("{\"foobar\"}"));86 Response decoded = codec.decode(response);87 assertThat(decoded.getStatus().longValue()).isEqualTo(0);88 assertThat(decoded.getValue()).isEqualTo("{\"foobar\"}");89 }90 @Test91 public void decodeNonJsonResponse_204() {92 HttpResponse response = new HttpResponse();93 response.setStatus(HTTP_NO_CONTENT);94 Response decoded = codec.decode(response);95 assertThat(decoded.getStatus()).isNull();96 assertThat(decoded.getValue()).isNull();97 }98 @Test99 public void decodeNonJsonResponse_4xx() {100 HttpResponse response = new HttpResponse();101 response.setStatus(HTTP_BAD_REQUEST);102 response.setContent(utf8String("{\"foobar\"}"));103 Response decoded = codec.decode(response);104 assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.UNKNOWN_COMMAND);105 assertThat(decoded.getValue()).isEqualTo("{\"foobar\"}");106 }107 @Test108 public void decodeNonJsonResponse_5xx() {109 HttpResponse response = new HttpResponse();110 response.setStatus(HTTP_INTERNAL_ERROR);111 response.setContent(utf8String("{\"foobar\"}"));112 Response decoded = codec.decode(response);113 assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.UNHANDLED_ERROR);114 assertThat(decoded.getValue()).isEqualTo("{\"foobar\"}");115 }116 @Test117 public void decodeJsonResponseMissingContentType() {118 Response response = new Response();119 response.setStatus(ErrorCodes.SUCCESS);120 response.setValue(ImmutableMap.of("color", "red"));121 HttpResponse httpResponse = new HttpResponse();122 httpResponse.setStatus(HTTP_OK);123 httpResponse.setContent(asJson(response));124 Response decoded = codec.decode(httpResponse);125 assertThat(decoded.getStatus()).isEqualTo(response.getStatus());126 assertThat(decoded.getSessionId()).isEqualTo(response.getSessionId());127 assertThat(decoded.getValue()).isEqualTo(response.getValue());128 }129 @Test130 public void decodeUtf16EncodedResponse() {131 HttpResponse httpResponse = new HttpResponse();132 httpResponse.setStatus(200);133 httpResponse.setHeader(CONTENT_TYPE, JSON_UTF_8.withCharset(UTF_16).toString());134 httpResponse.setContent(string("{\"status\":0,\"value\":\"æ°´\"}", UTF_16));135 Response response = codec.decode(httpResponse);136 assertThat(response.getValue()).isEqualTo("æ°´");137 }138 @Test139 public void decodeJsonResponseWithTrailingNullBytes() {140 HttpResponse response = new HttpResponse();141 response.setStatus(HTTP_OK);142 response.setContent(utf8String("{\"status\":0,\"value\":\"foo\"}\0\0"));143 Response decoded = codec.decode(response);144 assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.SUCCESS);145 assertThat(decoded.getValue()).isEqualTo("foo");146 }147 @Test148 public void shouldConvertElementReferenceToRemoteWebElement() {149 HttpResponse response = new HttpResponse();150 response.setStatus(HTTP_OK);151 response.setContent(asJson(ImmutableMap.of(152 "status", 0,153 "value", ImmutableMap.of(Dialect.OSS.getEncodedElementKey(), "345678"))));154 Response decoded = codec.decode(response);155 assertThat(((RemoteWebElement) decoded.getValue()).getId()).isEqualTo("345678");156 }157 @Test158 public void shouldAttemptToConvertAnExceptionIntoAnActualExceptionInstance() {159 Response response = new Response();160 response.setStatus(ErrorCodes.ASYNC_SCRIPT_TIMEOUT);161 WebDriverException exception = new ScriptTimeoutException("I timed out");162 response.setValue(exception);163 HttpResponse httpResponse = new HttpResponse();164 httpResponse.setStatus(HTTP_CLIENT_TIMEOUT);165 httpResponse.setContent(asJson(response));166 Response decoded = codec.decode(httpResponse);167 assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.ASYNC_SCRIPT_TIMEOUT);168 WebDriverException seenException = (WebDriverException) decoded.getValue();169 assertThat(seenException.getClass()).isEqualTo(exception.getClass());170 assertThat(seenException.getMessage().startsWith(exception.getMessage())).isTrue();171 }172}...
Source:JsonHttpResponseCodec.java
...36 ? HTTP_OK37 : HTTP_INTERNAL_ERROR;38 byte[] data = beanToJsonConverter.convert(response).getBytes(UTF_8);39 HttpResponse httpResponse = new HttpResponse();40 httpResponse.setStatus(status);41 httpResponse.setHeader(CACHE_CONTROL, "no-cache");42 httpResponse.setHeader(EXPIRES, "Thu, 01 Jan 1970 00:00:00 GMT");43 httpResponse.setHeader(CONTENT_LENGTH, String.valueOf(data.length));44 httpResponse.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());45 httpResponse.setContent(data);46 return httpResponse;47 }48 @Override49 public Response decode(HttpResponse encodedResponse) {50 String contentType = nullToEmpty(encodedResponse.getHeader(CONTENT_TYPE));51 String content = encodedResponse.getContentString();52 try {53 return jsonToBeanConverter.convert(Response.class, content);54 } catch (JsonException e) {55 if (contentType.startsWith("application/json")) {56 throw new IllegalArgumentException(57 "Cannot decode response content: " + content, e);58 }59 } catch (ClassCastException e) {60 if (contentType.startsWith("application/json")) {61 if (content.isEmpty()) {62 // The remote server has died, but has already set some headers.63 // Normally this occurs when the final window of the firefox driver64 // is closed on OS X. Return null, as the return value _should_ be65 // being ignored. This is not an elegant solution.66 return new Response();67 }68 throw new IllegalArgumentException(69 "Cannot decode response content: " + content, e);70 }71 }72 Response response = new Response();73 int statusCode = encodedResponse.getStatus();74 if (statusCode < 200 || statusCode > 299) {75 // 4xx represents an unknown command or a bad request.76 if (statusCode > 399 && statusCode < 500) {77 response.setStatus(ErrorCodes.UNKNOWN_COMMAND);78 } else {79 response.setStatus(ErrorCodes.UNHANDLED_ERROR);80 }81 }82 if (encodedResponse.getContent().length > 0) {83 response.setValue(content);84 }85 if (response.getValue() instanceof String) {86 // We normalise to \n because Java will translate this to \r\n87 // if this is suitable on our platform, and if we have \r\n, java will88 // turn this into \r\r\n, which would be Bad!89 response.setValue(((String) response.getValue()).replace("\r\n", "\n"));90 }91 response.setState(errorCodes.toState(response.getStatus()));92 return response;93 }...
Source:AbstractHttpResponseCodec.java
...24 25 byte[] data = beanToJsonConverter.convert(response).getBytes(Charsets.UTF_8);26 27 HttpResponse httpResponse = new HttpResponse();28 httpResponse.setStatus(status);29 httpResponse.setHeader("Cache-Control", "no-cache");30 httpResponse.setHeader("Expires", "Thu, 01 Jan 1970 00:00:00 GMT");31 httpResponse.setHeader("Content-Length", String.valueOf(data.length));32 httpResponse.setHeader("Content-Type", MediaType.JSON_UTF_8.toString());33 httpResponse.setContent(data);34 35 return httpResponse;36 }37 38 public Response decode(HttpResponse encodedResponse)39 {40 String contentType = Strings.nullToEmpty(encodedResponse.getHeader("Content-Type"));41 String content = encodedResponse.getContentString().trim();42 try {43 return (Response)jsonToBeanConverter.convert(Response.class, content);44 } catch (JsonException e) {45 if (contentType.startsWith("application/json")) {46 throw new IllegalArgumentException("Cannot decode response content: " + content, e);47 }48 }49 catch (ClassCastException e) {50 if (contentType.startsWith("application/json")) {51 if (content.isEmpty())52 {53 return new Response();54 }55 throw new IllegalArgumentException("Cannot decode response content: " + content, e);56 }57 }58 59 Response response = new Response();60 int statusCode = encodedResponse.getStatus();61 if ((statusCode < 200) || (statusCode > 299))62 {63 if ((statusCode > 399) && (statusCode < 500)) {64 response.setStatus(Integer.valueOf(9));65 } else {66 response.setStatus(Integer.valueOf(13));67 }68 }69 70 if (encodedResponse.getContent().length > 0) {71 response.setValue(content);72 }73 74 if ((response.getValue() instanceof String))75 {76 response.setValue(((String)response.getValue()).replace("\r\n", "\n"));77 }78 79 if ((response.getStatus() != null) && (response.getState() == null)) {80 response.setState(errorCodes.toState(response.getStatus()));81 } else if ((response.getStatus() == null) && (response.getState() != null)) {82 response.setStatus(83 Integer.valueOf(errorCodes.toStatus(response.getState(), 84 Optional.of(Integer.valueOf(encodedResponse.getStatus())))));85 } else if (statusCode == 200) {86 response.setStatus(Integer.valueOf(0));87 response.setState(errorCodes.toState(Integer.valueOf(0)));88 }89 90 if (response.getStatus() != null) {91 response.setState(errorCodes.toState(response.getStatus()));92 } else if (statusCode == 200) {93 response.setState(errorCodes.toState(Integer.valueOf(0)));94 }95 return response;96 }97}...
Source:UploadFile.java
...44 // Select the first file45 File[] allFiles = tempDir.listFiles();46 Response response = new Response(session.getId());47 if (allFiles == null || allFiles.length != 1) {48 response.setStatus(ErrorCodes.UNHANDLED_ERROR);49 response.setValue(new WebDriverException(50 "Expected there to be only 1 file. There were: " +51 (allFiles == null ? 0 : allFiles.length)));52 } else {53 response.setStatus(ErrorCodes.SUCCESS);54 response.setValue(allFiles[0].getAbsolutePath());55 }56 session.getDownstreamDialect().getResponseCodec().encode(() -> resp, response);57 }58}...
Source:NewSession.java
...52 Response response = new Response();53 response.setSessionId(sessionId.toString());54 response.setValue(capabilities);55 56 response.setStatus(Integer.valueOf(0));57 return response;58 }59 60 public String getSessionId() {61 return sessionId.toString();62 }63 64 public String toString()65 {66 return String.format("[new session: %s]", new Object[] { desiredCapabilities });67 }68}...
Source:Responses.java
...16 {17 Response response = new Response();18 response.setSessionId(sessionId != null ? sessionId.toString() : null);19 response.setValue(value);20 response.setStatus(Integer.valueOf(0));21 response.setState("success");22 return response;23 }24 25 public static Response failure(SessionId sessionId, Throwable reason)26 {27 Response response = new Response();28 response.setSessionId(sessionId != null ? sessionId.toString() : null);29 response.setValue(reason);30 response.setStatus(Integer.valueOf(ERROR_CODES.toStatusCode(reason)));31 response.setState(ERROR_CODES.toState(response.getStatus()));32 return response;33 }34 35 public static Response failure(SessionId sessionId, Throwable reason, Optional<String> screenshot)36 {37 Response response = new Response();38 response.setSessionId(sessionId != null ? sessionId.toString() : null);39 response.setStatus(Integer.valueOf(ERROR_CODES.toStatusCode(reason)));40 response.setState(ERROR_CODES.toState(response.getStatus()));41 42 if (reason != null) {43 JsonObject json = new BeanToJsonConverter().convertObject(reason).getAsJsonObject();44 json.addProperty("screen", (String)screenshot.orNull());45 response.setValue(json);46 }47 return response;48 }49}...
setStatus
Using AI Code Generation
1import org.openqa.selenium.remote.Response;2import org.openqa.selenium.remote.server.DriverServlet;3public class MyDriverServlet extends DriverServlet {4 protected Response createResponse(String sessionId) {5 Response response = super.createResponse(sessionId);6 response.setStatus(500);7 return response;8 }9}10import org.openqa.selenium.remote.RemoteWebDriver;11import org.openqa.selenium.remote.DesiredCapabilities;12import org.testng.annotations.Test;13public class MyTest {14 public void test() {15 DesiredCapabilities capabilities = new DesiredCapabilities();16 capabilities.setCapability("browserName", "chrome");17 RemoteWebDriver driver = new RemoteWebDriver(capabilities);18 driver.quit();19 }20}
LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.
Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.
What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.
Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.
Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.
How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.
Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.
Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!