Source:How can I create a memory leak in Java?
public void perform()
Best Selenium code snippet using org.openqa.selenium.internal.Debug
Source:AndroidDriver.java
1/*2Copyright 2010 WebDriver committers3Copyright 2010 Google Inc.4Licensed under the Apache License, Version 2.0 (the "License");5you may not use this file except in compliance with the License.6You may obtain a copy of the License at7 http://www.apache.org/licenses/LICENSE-2.08Unless required by applicable law or agreed to in writing, software9distributed under the License is distributed on an "AS IS" BASIS,10WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11See the License for the specific language governing permissions and12limitations under the License.13*/14package org.openqa.selenium.android;15import java.util.ArrayList;16import java.util.List;17import java.util.Set;18import java.util.concurrent.TimeUnit;19import org.json.JSONArray;20import org.json.JSONException;21import org.json.JSONObject;22import org.openqa.selenium.Alert;23import org.openqa.selenium.By;24import org.openqa.selenium.Cookie;25import org.openqa.selenium.JavascriptExecutor;26import org.openqa.selenium.NoSuchElementException;27import org.openqa.selenium.NoSuchFrameException;28import org.openqa.selenium.OutputType;29import org.openqa.selenium.Rotatable;30import org.openqa.selenium.ScreenOrientation;31import org.openqa.selenium.SearchContext;32import org.openqa.selenium.TakesScreenshot;33import org.openqa.selenium.TimeoutException;34import org.openqa.selenium.WebDriver;35import org.openqa.selenium.WebDriverException;36import org.openqa.selenium.WebElement;37import org.openqa.selenium.android.intents.IntentReceiverRegistrar;38import org.openqa.selenium.android.util.JsUtil;39import org.openqa.selenium.android.util.SimpleTimer;40import org.openqa.selenium.html5.BrowserConnection;41import org.openqa.selenium.internal.Base64Encoder;42import org.openqa.selenium.internal.FindsById;43import org.openqa.selenium.internal.FindsByLinkText;44import org.openqa.selenium.internal.FindsByName;45import org.openqa.selenium.internal.FindsByTagName;46import org.openqa.selenium.internal.FindsByXPath;47import android.content.Context;48import android.content.Intent;49import android.provider.Settings;50import android.util.Log;51public class AndroidDriver implements WebDriver, SearchContext, FindsByTagName, JavascriptExecutor,52 FindsById, FindsByLinkText, FindsByName, FindsByXPath, TakesScreenshot,53 Rotatable, BrowserConnection {54 public static final String LOG_TAG = AndroidDriver.class.getName();55 56 // Timeouts in milliseconds57 public static final long LOADING_TIMEOUT = 30000L;58 public static final long START_LOADING_TIMEOUT = 800L;59 public static final long WAIT_FOR_RESPONSE_TIMEOUT = 20000L;60 public static final long FOCUS_TIMEOUT = 1000L;61 62 public static final String ERROR = "_ERROR:"; // Prefixes JS result when returning an error63 public static final String TYPE = "_TYPE"; // Prefixes JS result to be converted64 public static final String WEBELEMENT_TYPE = TYPE + "1:"; // Convert to WebElement65 66 private static Context context;67 private final SimpleTimer timer;68 private final IntentReceiverRegistrar intentRegistrar;69 private final AndroidWebElement element;70 private final JavascriptDomAccessor domAccessor;71 72 private String currentFrame;73 private long implicitWait = 0;74 private long asyncScriptTimeout = 0;75 private ActivityController controller = ActivityController.getInstance();76 77 public AndroidDriver() {78 // By default currentFrame is the root, i.e. window79 currentFrame = "window";80 intentRegistrar = new IntentReceiverRegistrar(getContext());81 timer = new SimpleTimer();82 domAccessor = new JavascriptDomAccessor(this);83 element = new AndroidWebElement(this);84 }85 public JavascriptDomAccessor getDomAccessor() {86 return domAccessor;87 }88 89 public String getCurrentUrl() {90 return controller.getCurrentUrl();91 }92 public String getTitle() {93 return controller.getTitle();94 }95 public void get(String url) {96 controller.get(url);97 }98 public String getPageSource() {99 return (String) executeScript(100 "return (new XMLSerializer()).serializeToString(document.documentElement);");101 }102 public void close() {103 quit();104 }105 public void quit() {106 intentRegistrar.unregisterAllReceivers();107 controller.quit();108 }109 public WebElement findElement(By by) {110 timer.start();111 while (true) {112 try {113 return by.findElement(this);114 } catch (NoSuchElementException e) {115 if (timer.getTimeElapsedInMillisSinceStart() > implicitWait) {116 throw e;117 }118 Sleeper.sleepQuietly(100);119 }120 }121 }122 public List<WebElement> findElements(By by) {123 timer.start();124 List<WebElement> found;125 do {126 found = by.findElements(this);127 if (found.isEmpty()) {128 Sleeper.sleepQuietly(100);129 } else {130 break;131 }132 } while (timer.getTimeElapsedInMillisSinceStart() <= implicitWait);133 return found;134 }135 public WebElement findElementByLinkText(String using) {136 return element.findElementByLinkText(using);137 }138 public List<WebElement> findElementsByLinkText(String using) {139 return element.findElementsByLinkText(using);140 }141 public WebElement findElementById(String id) {142 return element.findElementById(id);143 }144 public List<WebElement> findElementsById(String id) {145 return findElementsByXPath("//*[@id='" + id + "']");146 }147 public WebElement findElementByName(String using) {148 return element.findElementByName(using);149 }150 public List<WebElement> findElementsByName(String using) {151 return element.findElementsByName(using);152 }153 public WebElement findElementByTagName(String using) {154 return element.findElementByTagName(using);155 }156 public List<WebElement> findElementsByTagName(String using) {157 return element.findElementsByTagName(using);158 }159 public WebElement findElementByXPath(String using) {160 return element.findElementByXPath(using);161 }162 public List<WebElement> findElementsByXPath(String using) {163 return element.findElementsByXPath(using);164 }165 public WebElement findElementByPartialLinkText(String using) {166 return element.findElementByPartialLinkText(using);167 }168 public List<WebElement> findElementsByPartialLinkText(String using) {169 return element.findElementsByPartialLinkText(using);170 }171 public Set<String> getWindowHandles() {172 return controller.getAllWindowHandles();173 }174 public String getWindowHandle() {175 return controller.getWindowHandle();176 }177 public TargetLocator switchTo() {178 return new AndroidTargetLocator();179 }180 181 private class AndroidTargetLocator implements TargetLocator {182 public WebElement activeElement() {183 Object element = executeScript(184 "try {" +185 "return document.activeElement;" +186 "} catch (err) {" +187 " return 'failed_' + err;" +188 "}");189 if (element == null) {190 return findElementByXPath("//body");191 } else if (element instanceof WebElement) {192 return (WebElement) element;193 }194 return null;195 }196 public WebDriver defaultContent() {197 setCurrentFrame(null);198 return AndroidDriver.this;199 }200 public WebDriver frame(int index) {201 if (isFrameIndexValid(index)) {202 currentFrame += ".frames[" + index + "]"; 203 } else {204 throw new NoSuchFrameException("Frame not found: " + index);205 }206 return AndroidDriver.this;207 }208 public WebDriver frame(String frameNameOrId) {209 setCurrentFrame(frameNameOrId);210 return AndroidDriver.this;211 }212 public WebDriver frame(WebElement frameElement) {213 String tagName = frameElement.getTagName();214 if (!tagName.equalsIgnoreCase("iframe") && !tagName.equalsIgnoreCase("frame")) {215 throw new NoSuchFrameException(216 "Element is not a frame element: " + frameElement.getTagName());217 }218 int index = (Integer) executeScript(219 "var element = arguments[0];" +220 "var targetWindow = element.contentWindow;" +221 "if (!targetWindow) { throw Error('No such window!'); }" +222 // NOTE: this script executes in the context of the current frame, so223 // window === currentFrame224 "var numFrames = window.frames.length;" +225 "for (var i = 0; i < numFrames; i++) {" +226 " if (targetWindow == window.frames[i]) {" +227 " return i;" +228 " }" +229 "}" +230 "return -1;",231 frameElement);232 if (index < 0) {233 throw new NoSuchFrameException("Unable to locate frame: " + tagName234 + "; current window: " + currentFrame);235 }236 currentFrame += ".frames[" + index + "]";237 return AndroidDriver.this;238 }239 public WebDriver window(String nameOrHandle) {240 controller.switchToWindow(nameOrHandle);241 return AndroidDriver.this;242 }243 244 private void setCurrentFrame(String frameNameOrId) {245 if (frameNameOrId == null) {246 currentFrame = "window";247 } else {248 currentFrame += ".frames[" + getIndexForFrameWithNameOrId(frameNameOrId) + "]";249 }250 }251 private int getIndexForFrameWithNameOrId(String name) {252 int index = (Integer) executeScript(253 "try {" +254 " var foundById = null;" +255 // NOTE: this script executes in the context of the current frame, so256 // window === currentFrame257 " var frames = window.frames;" +258 " var numFrames = frames.length;" +259 " for (var i = 0; i < numFrames; i++) {" +260 " if (frames[i].name == arguments[0]) {" +261 " return i;" +262 " } else if (null == foundById && frames[i].frameElement.id == arguments[0]) {" +263 " foundById = i;" +264 " }" +265 " }" +266 " if (foundById != null) {" +267 " return foundById;" +268 " }" +269 "} catch (ignored) {" +270 "}" +271 "return -1;",272 name);273 if (index < 0) {274 throw new NoSuchFrameException("Frame not found: " + name);275 }276 return index;277 }278 private boolean isFrameIndexValid(int index) {279 return (Boolean) executeScript(280 "try {" +281 // NOTE: this script executes in the context of the current frame, so282 // window === currentFrame283 " window.frames[arguments[0]].document;" +284 " return true;" +285 "} catch(err) {" +286 " return false;" +287 "}", index);288 }289 public Alert alert() {290 throw new UnsupportedOperationException("alert()");291 }292 }293 public Navigation navigate() {294 return new AndroidNavigation();295 }296 297 public boolean isJavascriptEnabled() {298 return true;299 }300 public Object executeScript(String script, Object... args) {301 return executeJavascript(script, false, args);302 }303 public Object executeAsyncScript(String script, Object... args) {304 return executeJavascript(script, true, args);305 }306 307 private Object executeJavascript(String script, boolean sync, Object... args) {308 String jsFunction = embedScriptInJsFunction(script, sync, args);309 String jsResult = executeJavascriptInWebView(jsFunction);310 // jsResult is updated by the intent receiver when the JS result is ready. 311 Object res = checkResultAndConvert(jsResult);312 return res;313 }314 private String embedScriptInJsFunction(String script, boolean isAsync, Object... args) {315 String finalScript = new StringBuilder("(function() {")316 .append("var isAsync=").append(isAsync).append(";")317 .append("var timeout=").append(asyncScriptTimeout).append(", timeoutId;")318 .append("var win=").append(currentFrame).append(";")319 .append("function sendResponse(value, isError) {")320 .append(" if (isAsync) {")321 .append(" win.clearTimeout(timeoutId);")322 .append(" win.removeEventListener('unload', onunload, false);")323 .append(" }")324 .append(" if (isError) {")325 .append(" window.webdriver.resultMethod('").append(ERROR).append("'+value);")326 .append(" } else {")327 .append(wrapAndReturnJsResult("value"))328 .append(" }")329 .append("}")330 .append("function onunload() {")331 .append(" sendResponse('Detected a page unload event; async script execution")332 .append(" does not work across page loads', true);")333 .append("}")334 .append("if (isAsync) {")335 .append(" win.addEventListener('unload', onunload, false);")336 .append("}")337 .append("var startTime = new Date().getTime();")338 .append("try {")339 .append(" var result=(function(){with(win){").append(script).append("}})(")340 .append(getArgsString(isAsync, args)).append(");")341 .append(" if (isAsync) {")342 .append(" timeoutId = win.setTimeout(function() {")343 .append(" sendResponse('Timed out waiting for async script after ' +")344 .append("(new Date().getTime() - startTime) + 'ms', true);")345 .append(" }, timeout);")346 .append(" } else {")347 .append(" sendResponse(result, false);")348 .append(" }")349 .append("} catch (e) {")350 .append(" sendResponse(e, true);")351 .append("}")352 .append("})()")353 .toString();354 Logger.log(Log.DEBUG, LOG_TAG, "executeScript executing: " + finalScript);355 return finalScript;356 }357 private String getArgsString(boolean isAsync, Object... args) {358 StringBuilder argsString = new StringBuilder();359 for (int i = 0; i < args.length; i++) {360 argsString.append(JsUtil.convertArgumentToJsObject(args[i]))361 .append((i == args.length - 1) ? "" : ",");362 }363 if (isAsync) {364 if (args.length > 0) {365 argsString.append(",");366 }367 argsString.append("function(value){sendResponse(value,false);}");368 }369 return argsString.toString();370 }371 private String wrapAndReturnJsResult(String objName) {372 // TODO(berrada): Extract this as an atom373 return new StringBuilder()374 .append("if (").append(objName).append(" instanceof HTMLElement) {")375 .append("with(").append(currentFrame).append(") {")376 .append(JavascriptDomAccessor.initCacheJs())377 .append(" var result = []; result.push(").append(objName).append(");")378 .append(JavascriptDomAccessor.ADD_TO_CACHE)379 .append(objName).append("='")380 .append(WEBELEMENT_TYPE)381 .append("'+indices;")382 .append("}")383 .append("} else {")384 .append(objName)385 .append("='{" + TYPE + ":'+JSON.stringify(")386 .append(objName).append(")+'}';")387 .append("}")388 // Callback to get the result passed from JS to Java389 .append("window.webdriver.resultMethod(").append(objName).append(");")390 .toString();391 }392 /**393 * Executes the given Javascript in the WebView and 394 * wait until it is done executing.395 * If the Javascript executed returns a value, the later is updated in the396 * class variable jsResult when the event is broadcasted.397 * 398 * @param args the Javascript to be executed399 */400 private String executeJavascriptInWebView(String script) {401 return controller.executeJavascript(script);402 }403 /**404 * Convert result to java type.405 *406 * @param jsResult JSON format or Error407 * @return java objects like long, double, String, boolean, Array, Map408 */409 protected Object checkResultAndConvert(String jsResult) {410 Logger.log(Log.DEBUG, "WD", "JS RESULR : " + jsResult);411 if (jsResult == null) {412 return null;413 } else if (jsResult.startsWith(ERROR)) {414 if (jsResult.startsWith(ERROR + "Timed out waiting for async script")) {415 throw new TimeoutException(jsResult);416 }417 throw new WebDriverException(jsResult);418 } else if (jsResult.startsWith(WEBELEMENT_TYPE)) {419 return new AndroidWebElement(this, jsResult.substring(7));420 } else if (jsResult.equals("{" + TYPE + ":null}")) {421 return null;422 } else if (jsResult.length() > 0) {423 try {424 JSONObject obj = new JSONObject(jsResult);425 return processJsonObject(obj.opt(TYPE));426 } catch (JSONException e) {427 Logger.log(Log.ERROR, LOG_TAG,428 "checkResultAndConvert JSONException + " + e.getMessage());429 }430 }431 return jsResult;432 }433 protected Object processJsonObject(Object res) throws JSONException {434 if (res instanceof JSONArray) {435 Logger.log(Log.DEBUG, "WD", "JSONARRAY : " + res.toString());436 return convertJsonArray2List((JSONArray) res);437 } else if ("undefined".equals(res)) {438 return null;439 }440 Logger.log(Log.DEBUG, "WD", "NOT JSONARRAY : " + res.toString());441 return res;442 }443 protected List<Object> convertJsonArray2List(JSONArray arr) throws JSONException {444 List<Object> list = new ArrayList<Object>();445 for (int i = 0; i < arr.length(); i++) {446 list.add(processJsonObject(arr.get(i)));447 }448 return list;449 }450 public void setProxy(String host, int port) {451 if ((host != null) && (host.length() > 0)) {452 System.getProperties().put("proxySet", "true");453 System.getProperties().put("proxyHost", host);454 System.getProperties().put("proxyPort", port);455 }456 }457 public static void setContext(Context contentContext) {458 context = contentContext;459 }460 public static Context getContext() {461 return context;462 }463 public Options manage() {464 return new AndroidOptions();465 }466 private class AndroidOptions implements Options {467 468 public void addCookie(Cookie cookie) {469 controller.addCookie(cookie.getName(), cookie.getValue(), cookie.getPath());470 }471 public void deleteCookieNamed(String name) {472 controller.removeCookie(name);473 }474 public void deleteCookie(Cookie cookie) {475 controller.removeCookie(cookie.getName());476 }477 public void deleteAllCookies() {478 controller.removeAllCookies();479 }480 public Set<Cookie> getCookies() {481 return controller.getCookies();482 }483 public Cookie getCookieNamed(String name) {484 return controller.getCookie(name);485 }486 public Timeouts timeouts() {487 return new AndroidTimeouts();488 }489 public ImeHandler ime() {490 throw new UnsupportedOperationException("Not implementing IME input just yet.");491 }492 }493 class AndroidTimeouts implements Timeouts {494 public Timeouts implicitlyWait(long time, TimeUnit unit) {495 implicitWait = TimeUnit.MILLISECONDS.convert(Math.max(0, time), unit);496 return this;497 }498 public Timeouts setScriptTimeout(long time, TimeUnit unit) {499 asyncScriptTimeout = TimeUnit.MILLISECONDS.convert(Math.max(0, time), unit);500 return this;501 }502 }503 public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {504 byte[] rawPng = controller.takeScreenshot();505 String base64Png = new Base64Encoder().encode(rawPng);506 return target.convertFromBase64Png(base64Png);507 }508 public ScreenOrientation getOrientation() {509 return controller.getScreenOrientation();510 }511 public void rotate(ScreenOrientation orientation) {512 controller.rotate(orientation);513 }514 public boolean isOnline() {515 return Settings.System.getInt(getContext().getContentResolver(),516 Settings.System.AIRPLANE_MODE_ON, 0) == 0;517 }518 public void setOnline(boolean online) throws WebDriverException {519 Settings.System.putInt(getContext().getContentResolver(),520 Settings.System.AIRPLANE_MODE_ON, online ? 0 : 1);521 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);522 intent.putExtra("state", !online);523 getContext().sendBroadcast(intent);524 }525}...
Source:Connection.java
...42import java.util.function.Consumer;43import java.util.logging.Level;44import java.util.logging.Logger;45import static java.util.concurrent.TimeUnit.MILLISECONDS;46import static org.openqa.selenium.internal.Debug.getDebugLogLevel;47import static org.openqa.selenium.json.Json.MAP_TYPE;48import static org.openqa.selenium.remote.http.HttpMethod.GET;49public class Connection implements Closeable {50 private static final Logger LOG = Logger.getLogger(Connection.class.getName());51 private static final Json JSON = new Json();52 private static final Executor EXECUTOR = Executors.newCachedThreadPool(r -> {53 Thread thread = new Thread(r, "CDP Connection");54 thread.setDaemon(true);55 return thread;56 });57 private static final AtomicLong NEXT_ID = new AtomicLong(1L);58 private final WebSocket socket;59 private final Map<Long, Consumer<Either<Throwable, JsonInput>>> methodCallbacks = new LinkedHashMap<>();60 private final Multimap<Event<?>, Consumer<?>> eventCallbacks = HashMultimap.create();61 public Connection(HttpClient client, String url) {62 Require.nonNull("HTTP client", client);63 Require.nonNull("URL to connect to", url);64 socket = client.openSocket(new HttpRequest(GET, url), new Listener());65 }66 private static class NamedConsumer<X> implements Consumer<X> {67 private final String name;68 private final Consumer<X> delegate;69 private NamedConsumer(String name, Consumer<X> delegate) {70 this.name = name;71 this.delegate = delegate;72 }73 public static <X> Consumer<X> of(String name, Consumer<X> delegate) {74 return new NamedConsumer<>(name, delegate);75 }76 @Override77 public void accept(X x) {78 delegate.accept(x);79 }80 @Override81 public String toString() {82 return "Consumer for " + name;83 }84 }85 public <X> CompletableFuture<X> send(SessionID sessionId, Command<X> command) {86 long id = NEXT_ID.getAndIncrement();87 CompletableFuture<X> result = new CompletableFuture<>();88 if (command.getSendsResponse()) {89 methodCallbacks.put(id, NamedConsumer.of(command.getMethod(), inputOrException -> {90 if (inputOrException.isRight()) {91 try {92 X value = command.getMapper().apply(inputOrException.right());93 result.complete(value);94 } catch (Throwable e) {95 LOG.log(Level.WARNING, String.format("Unable to map result for %s", command.getMethod()), e);96 result.completeExceptionally(e);97 }98 } else {99 result.completeExceptionally(inputOrException.left());100 }101 }));102 }103 ImmutableMap.Builder<String, Object> serialized = ImmutableMap.builder();104 serialized.put("id", id);105 serialized.put("method", command.getMethod());106 serialized.put("params", command.getParams());107 if (sessionId != null) {108 serialized.put("sessionId", sessionId);109 }110 StringBuilder json = new StringBuilder();111 try (JsonOutput out = JSON.newOutput(json).writeClassName(false)) {112 out.write(serialized.build());113 }114 LOG.log(getDebugLogLevel(), () -> String.format("-> %s", json));115 socket.sendText(json);116 if (!command.getSendsResponse() ) {117 result.complete(null);118 }119 return result;120 }121 public <X> X sendAndWait(SessionID sessionId, Command<X> command, Duration timeout) {122 try {123 CompletableFuture<X> future = send(sessionId, command);124 return future.get(timeout.toMillis(), MILLISECONDS);125 } catch (InterruptedException e) {126 Thread.currentThread().interrupt();127 throw new IllegalStateException("Thread has been interrupted", e);128 } catch (ExecutionException e) {129 Throwable cause = e;130 if (e.getCause() != null) {131 cause = e.getCause();132 }133 throw new DevToolsException(cause);134 } catch (TimeoutException e) {135 throw new org.openqa.selenium.TimeoutException(e);136 }137 }138 public <X> void addListener(Event<X> event, Consumer<X> handler) {139 Require.nonNull("Event to listen for", event);140 Require.nonNull("Handler to call", handler);141 synchronized (eventCallbacks) {142 eventCallbacks.put(event, handler);143 }144 }145 public void clearListeners() {146 synchronized (eventCallbacks) {147 eventCallbacks.clear();148 }149 }150 @Override151 public void close() {152 socket.close();153 }154 private class Listener implements WebSocket.Listener {155 @Override156 public void onText(CharSequence data) {157 EXECUTOR.execute(() -> {158 try {159 handle(data);160 } catch (Throwable t) {161 LOG.log(Level.WARNING, "Unable to process: " + data, t);162 throw new DevToolsException(t);163 }164 });165 }166 }167 private void handle(CharSequence data) {168 // It's kind of gross to decode the data twice, but this lets us get started on something169 // that feels nice to users.170 // TODO: decode once, and once only171 String asString = String.valueOf(data);172 LOG.log(getDebugLogLevel(), () -> String.format("<- %s", asString));173 Map<String, Object> raw = JSON.toType(asString, MAP_TYPE);174 if (raw.get("id") instanceof Number175 && (raw.get("result") != null || raw.get("error") != null)) {176 Consumer<Either<Throwable, JsonInput>> consumer = methodCallbacks.remove(((Number) raw.get("id")).longValue());177 if (consumer == null) {178 return;179 }180 try (StringReader reader = new StringReader(asString);181 JsonInput input = JSON.newInput(reader)) {182 input.beginObject();183 while (input.hasNext()) {184 switch (input.nextName()) {185 case "result":186 consumer.accept(Either.right(input));187 break;188 case "error":189 consumer.accept(Either.left(new WebDriverException(asString)));190 input.skipValue();191 break;192 default:193 input.skipValue();194 }195 }196 input.endObject();197 }198 } else if (raw.get("method") instanceof String && raw.get("params") instanceof Map) {199 LOG.log(200 getDebugLogLevel(),201 String.format("Method %s called with %d callbacks available", raw.get("method"), eventCallbacks.keySet().size()));202 synchronized (eventCallbacks) {203 // TODO: Also only decode once.204 eventCallbacks.keySet().stream()205 .peek(event -> LOG.log(206 getDebugLogLevel(),207 String.format("Matching %s with %s", raw.get("method"), event.getMethod())))208 .filter(event -> raw.get("method").equals(event.getMethod()))209 .forEach(event -> {210 // TODO: This is grossly inefficient. I apologise, and we should fix this.211 try (StringReader reader = new StringReader(asString);212 JsonInput input = JSON.newInput(reader)) {213 Object value = null;214 input.beginObject();215 while (input.hasNext()) {216 switch (input.nextName()) {217 case "params":218 value = event.getMapper().apply(input);219 break;220 default:221 input.skipValue();222 break;223 }224 }225 input.endObject();226 if (value == null) {227 // Do nothing.228 return;229 }230 final Object finalValue = value;231 for (Consumer<?> action : eventCallbacks.get(event)) {232 @SuppressWarnings("unchecked") Consumer<Object> obj = (Consumer<Object>) action;233 LOG.log(234 getDebugLogLevel(),235 String.format("Calling callback for %s using %s being passed %s", event, obj, finalValue));236 obj.accept(finalValue);237 }238 }239 });240 }241 } else {242 LOG.warning("Unhandled type: " + data);243 }244 }245}...
Source:ElementDecorator.java
1package com.wYne.automation.ui.internal;2import com.wYne.automation.ui.elements.SlWebElement;3import com.wYne.automation.ui.elements.WyneLogger;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.internal.Locatable;6import org.openqa.selenium.internal.WrapsElement;7import org.openqa.selenium.support.FindBy;8import org.openqa.selenium.support.FindBys;9import org.openqa.selenium.support.pagefactory.ElementLocator;10import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;11import org.openqa.selenium.support.pagefactory.FieldDecorator;12import org.openqa.selenium.support.pagefactory.internal.LocatingElementListHandler;13import java.lang.reflect.*;14import java.util.List;15/**16 * WrappedElementDecorator recognizes a few things that DefaultFieldDecorator does not.17 * <p/>18 * It is designed to support and return concrete implementations of wrappers for a variety of common html elements.19 */20public class ElementDecorator implements FieldDecorator {21 /**22 * factory to use when generating ElementLocator.23 */24 protected ElementLocatorFactory factory;25 private Field myfield;26 /**27 * Constructor for an ElementLocatorFactory. This class is designed to replace DefaultFieldDecorator.28 *29 * @param factory for locating elements.30 */31 public ElementDecorator(ElementLocatorFactory factory) {32 this.factory = factory;33 }34 public Object decorate(ClassLoader loader, Field field) {35 //EMMLog.entry("Internal Framework methods - decorator");36 myfield = field;37 FindBy findBy = field.getAnnotation(FindBy.class);38 39 String elementName;40 String type;41 String how;42 String using;43 String pageName;44 45 if (field.isAnnotationPresent(FindBy.class)){46 //SnapLogger.LOGGER.debug("-----------------");47 //SnapLogger.LOGGER.debug(findBy);48 //SnapLogger.LOGGER.debug("Identifying the element:[" +field.getName()+"] of type:[" +field.getType().getSimpleName() + "],how:[" + findBy.how()+ "],using:[" + findBy.using() + "]");49 //SnapLogger.LOGGER.debug("Instance of :" + field.getDeclaringClass().getSimpleName());50 pageName = field.getDeclaringClass().getSimpleName();51 elementName = field.getName();52 type = field.getType().getSimpleName();53 how = findBy.how().toString();54 using = findBy.using();55 //SnapLogger.LOGGER.debug("-------END----------");56 WyneLogger.LOGGER.debug("************************Started Identifyin elements of page:" + pageName);57 WyneLogger.LOGGER.debug("IDENTIFYING THE OBJECT -- PAGE NAME:[" + pageName + "],ELEMENT NAME: [" + elementName + "], TYPE: [" + type + "],"58 + " HOW:[" + how + "] , USING:[" + using + "]");59 WyneLogger.LOGGER.debug("************************Completed identifying elements of the page: " + pageName);60 }61 if (!(WebElement.class.isAssignableFrom(field.getType()) || isDecoratableList(field))) {62 return null;63 }64 ElementLocator locator = factory.createLocator(field);65 if (locator == null) {66 return null;67 }68 Class<?> fieldType = field.getType();69 if (WebElement.class.equals(fieldType)) {70 fieldType = SlWebElement.class;71 //SnapLogger.LOGGER.debug(findBy.toString());72 }73 //EMMLog.exit("Internal Framework methods - decorator");74 if (WebElement.class.isAssignableFrom(fieldType)) {75 return proxyForLocator(loader, fieldType, locator);76 } else if (List.class.isAssignableFrom(fieldType)) {77 Class<?> erasureClass = getErasureClass(field);78 return proxyForListLocator(loader, erasureClass, locator);79 } else {80 return null;81 }82 }83 84 private Class<?> getErasureClass(Field field) {85 // Type erasure in Java isn't complete. Attempt to discover the generic86 // interfaceType of the list.87 Type genericType = field.getGenericType();88 if (!(genericType instanceof ParameterizedType)) {89 return null;90 }91 return (Class<?>) ((ParameterizedType) genericType).getActualTypeArguments()[0];92 }93 private boolean isDecoratableList(Field field) {94 if (!List.class.isAssignableFrom(field.getType())) {95 return false;96 }97 Class<?> erasureClass = getErasureClass(field);98 if (erasureClass == null) {99 return false;100 }101 if (!WebElement.class.isAssignableFrom(erasureClass)) {102 return false;103 }104 if (field.getAnnotation(FindBy.class) == null && field.getAnnotation(FindBys.class) == null) {105 return false;106 }107 return true;108 }109 /**110 * Generate a type-parameterized locator proxy for the element in question. We use our customized InvocationHandler111 * here to wrap classes.112 *113 * @param loader ClassLoader of the wrapping class114 * @param interfaceType Interface wrapping the underlying WebElement115 * @param locator ElementLocator pointing at a proxy of the object on the page116 * @param <T> The interface of the proxy.117 * @return a proxy representing the class we need to wrap.118 */119 protected <T> T proxyForLocator(ClassLoader loader, Class<T> interfaceType, ElementLocator locator) {120 InvocationHandler handler = new ElementHandler(interfaceType, myfield, locator);121 122 T proxy;123 proxy = interfaceType.cast(Proxy.newProxyInstance(124 loader, new Class[]{interfaceType, WebElement.class, WrapsElement.class, Locatable.class}, handler));125 //SnapLogger.LOGGER.debug("Locator Info:" + locator.toString() + ", Element:" + interfaceType.toString() );126 return proxy;127 128 }129 /**130 * generates a proxy for a list of elements to be wrapped.131 *132 * @param loader classloader for the class we're presently wrapping with proxies133 * @param interfaceType type of the element to be wrapped134 * @param locator locator for items on the page being wrapped135 * @param <T> class of the interface.136 * @return proxy with the same type as we started with.137 */138 @SuppressWarnings("unchecked")139 protected <T> List<T> proxyForListLocator(ClassLoader loader, Class<T> interfaceType, ElementLocator locator) {140 InvocationHandler handler;141 if (interfaceType.getAnnotation(ImplementedBy.class) != null) {142 handler = new ElementListHandler(interfaceType, locator);143 } else {144 handler = new LocatingElementListHandler(locator);145 }146 List<T> proxy;147 proxy = (List<T>) Proxy.newProxyInstance(148 loader, new Class[]{List.class}, handler);149 return proxy;150 }151}...
Source:InternalSelenseTestBase.java
1/*2Copyright 2012 Selenium committers3Copyright 2012 Software Freedom Conservancy4Licensed under the Apache License, Version 2.0 (the "License");5you may not use this file except in compliance with the License.6You may obtain a copy of the License at7 http://www.apache.org/licenses/LICENSE-2.08Unless required by applicable law or agreed to in writing, software9distributed under the License is distributed on an "AS IS" BASIS,10WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11See the License for the specific language governing permissions and12limitations under the License.13*/14package com.thoughtworks.selenium;15import com.google.common.base.Charsets;16import com.google.common.io.Files;17import com.google.common.io.Resources;18import org.junit.After;19import org.junit.Before;20import org.junit.BeforeClass;21import org.openqa.selenium.Build;22import org.openqa.selenium.JavascriptExecutor;23import org.openqa.selenium.WebDriver;24import org.openqa.selenium.WebDriverBackedSelenium;25import org.openqa.selenium.WebDriverException;26import org.openqa.selenium.environment.GlobalTestEnvironment;27import org.openqa.selenium.internal.WrapsDriver;28import org.openqa.selenium.remote.DesiredCapabilities;29import org.openqa.selenium.testing.DevMode;30import org.openqa.selenium.testing.InProject;31import org.openqa.selenium.testing.drivers.Browser;32import org.openqa.selenium.testing.drivers.WebDriverBuilder;33import org.openqa.selenium.v1.SeleneseBackedWebDriver;34import org.openqa.selenium.v1.SeleniumTestEnvironment;35import org.testng.Assert;36import java.io.File;37import java.io.IOException;38import java.net.URL;39import java.util.logging.Logger;40import static com.thoughtworks.selenium.BrowserConfigurationOptions.MULTI_WINDOW;41import static com.thoughtworks.selenium.BrowserConfigurationOptions.SINGLE_WINDOW;42import static org.openqa.selenium.UnexpectedAlertBehaviour.IGNORE;43import static org.openqa.selenium.remote.CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR;44public class InternalSelenseTestBase extends SeleneseTestBase {45 private static final Logger log = Logger.getLogger(InternalSelenseTestBase.class.getName());46 private static final ThreadLocal<Selenium> instance = new ThreadLocal<Selenium>();47 @BeforeClass48 public static void buildJavascriptLibraries() throws IOException {49 if (!DevMode.isInDevMode()) {50 return;51 }52 log.info("In dev mode. Copying required files in case we're using a WebDriver-backed Selenium");53 try {54 new Build().of(55 "//java/client/src/org/openqa/selenium/internal/seleniumemulation",56 "//third_party/js/sizzle"57 ).go();58 File buildDir = InProject.locate("java/client/build/production/org/openqa/selenium/internal/seleniumemulation");59 buildDir = new File(buildDir, "selenium_atoms");60 if (!buildDir.exists()) {61 assertTrue(buildDir.mkdir());62 }63 File atomsDir = InProject.locate("build/javascript/selenium-atoms");64 for (File file : atomsDir.listFiles()) {65 if (file.getName().endsWith(".js")) {66 File dest = new File(buildDir, file.getName());67 Files.copy(file, dest);68 }69 }70 File sizzle = InProject.locate("third_party/js/sizzle/sizzle.js");71 Files.copy(sizzle, new File(buildDir, "sizzle.js"));72 File seDir = InProject.locate("java/client/test/com/thoughtworks/selenium");73 File destDir = InProject.locate("java/client/build/production/com/thoughtworks/selenium");74 for (File file : seDir.listFiles()) {75 if (file.getName().endsWith(".js")) {76 File dest = new File(destDir, file.getName());77 Files.copy(file, dest);78 }79 }80 } catch (WebDriverException e) {81 System.err.println("Cannot build javascript libraries for selenium emulation: " + e.getMessage());82 }83 }84 @BeforeClass85 public static void initializeServer() {86 GlobalTestEnvironment.get(SeleniumTestEnvironment.class);87 }88 @Before89 public void addNecessaryJavascriptCommands() {90 if (selenium == null || !(selenium instanceof WebDriverBackedSelenium)) {91 return;92 }93 // We need to be a on page where we can execute JS94 WebDriver driver = ((WrapsDriver) selenium).getWrappedDriver();95 driver.get(whereIs("/selenium-server"));96 try {97 URL scriptUrl =98 Resources.getResource(getClass(), "/com/thoughtworks/selenium/testHelpers.js");99 String script = Resources.toString(scriptUrl, Charsets.UTF_8);100 ((JavascriptExecutor) driver).executeScript(script);101 } catch (IOException e) {102 Assert.fail("Cannot read script", e);103 }104 }105 private String whereIs(String location) {106 return GlobalTestEnvironment.get().getAppServer().whereIs(location);107 }108 @Before109 public void focusOnMainWindow() {110 if (selenium == null) {111 return;112 }113 selenium.windowFocus();114 }115 @Before116 public void returnFocusToMainWindow() {117 if (selenium == null) {118 return;119 }120 try {121 selenium.selectWindow("");122 } catch (SeleniumException e) {123 // TODO(simon): Window switching in Opera is picky.124 if (Browser.detect() != Browser.opera) {125 throw e;126 }127 }128 }129 @Before130 public void initializeSelenium() {131 selenium = instance.get();132 if (selenium != null) {133 return;134 }135 DesiredCapabilities caps = new DesiredCapabilities();136 caps.setCapability(UNEXPECTED_ALERT_BEHAVIOUR, IGNORE);137 if (Boolean.getBoolean("singlewindow")) {138 caps.setCapability(SINGLE_WINDOW, true);139 caps.setCapability(MULTI_WINDOW, "");140 }141 if (Boolean.getBoolean("webdriver.debug")) {142 caps.setCapability("browserSideLog", true);143 }144 String baseUrl = whereIs("/selenium-server/tests/");145 caps.setCapability("selenium.server.url", baseUrl);146 WebDriver driver = new WebDriverBuilder().setDesiredCapabilities(caps).get();147 if (driver instanceof SeleneseBackedWebDriver) {148 selenium = ((SeleneseBackedWebDriver) driver).getWrappedSelenium();149 } else {150 selenium = new WebDriverBackedSelenium(driver, baseUrl);151 }152 selenium.setBrowserLogLevel("debug");153 instance.set(selenium);154 }155 @After156 public void checkVerifications() {157 checkForVerificationErrors();158 }159 public static void destroyDriver() {160 Selenium selenium = instance.get();161 if (selenium != null) {162 selenium.stop();163 instance.remove();164 }165 }166}...
Source:ListHandler.java
1package selenium.decorator;2import lombok.extern.slf4j.Slf4j;3import org.openqa.selenium.WebElement;4import org.openqa.selenium.internal.Locatable;5import org.openqa.selenium.internal.WrapsElement;6import org.openqa.selenium.support.pagefactory.ElementLocator;7import selenium.exceptions.ElementException;8import java.lang.reflect.InvocationHandler;9import java.lang.reflect.InvocationTargetException;10import java.lang.reflect.Method;11import java.lang.reflect.Proxy;12import java.util.ArrayList;13import java.util.Arrays;14import java.util.List;15/**16 * Created by Tsovak_Sahakyan.17 */18@SuppressWarnings({"WeakerAccess", "Duplicates"})19@Slf4j20public class ListHandler<T> implements InvocationHandler{21 private final ItemFactory<T> factory;22 private final ClassLoader loader;23 private final Class<T> clazz;24 private final boolean isStatic;25 private final ElementLocator locator;26 private List<WebElement> cachedElements = new ArrayList<>();27 private List<T> cachedObjects = new ArrayList<>();28 public ListHandler(ElementLocator locator, ClassLoader loader, Class<T> clazz, ItemFactory<T> factory, boolean isStatic) {29 this.locator = locator;30 this.loader = loader;31 this.clazz = clazz;32 this.factory = factory;33 this.isStatic = isStatic;34 }35 public Object invoke(Object object, Method method, Object[] objects) throws Throwable {36 final String methodName = method.getName();37 log.debug("[PROXY] The method '{}' is called with the arguments '{}' for the object '{}'", methodName, Arrays38 .toString(objects), locator.toString());39 final List<WebElement> wElements = getElements();40 /* If the new list of items has not changed in size, then immediately return the cached objects */41 if (cachedObjects.size() != wElements.size()) {42 /* else create a new list of objects */43 cachedObjects.clear();44 for (int i = 0; i < wElements.size(); i++) {45 cachedObjects.add(factory.create(clazz, proxyWebElementForList(loader, locator, i)));46 }47 }48 try {49 return method.invoke(cachedObjects, objects);50 } catch (InvocationTargetException e) {51 cachedObjects.clear();52 cachedElements.clear();53 log.warn("[PROXY] An exception is thrown InvocationTargetException '{}'. Locator '{}'. Method '{}'", e.getCause().getClass().getSimpleName(),54 locator.toString(), methodName);55 throw new ElementException(56 String.format("[PROXY] Can not call the method '%s' for the base element with the locator '%s'", method.getName(), locator.toString()),57 e.getCause());58 }59 }60 /**61 * Proxy of one element from the list of elements. Complex logic. Each time the method is invoked,62 * all elements are searched, followed by an element with the specified index and proxy. Its proxy is returned.63 */64 private WebElement proxyWebElementForList(ClassLoader loader, ElementLocator locator, int index) {65 InvocationHandler handler = (proxy, method, args) -> {66 final String methodName = method.getName();67 log.debug("[PROXY] The method '{}' is called with the arguments '{}' for the object '{}'", methodName, Arrays.toString(args), locator.toString());68 try {69 if ("getWrappedElement".equals(method.getName())) {70 return getElements().get(index);71 }72 return method.invoke(getElements().get(index), args);73 } catch (InvocationTargetException e) {74 cachedElements.clear();75 log.warn("[PROXY] An exception is thrown InvocationTargetException '{}'. Locator '{}'. Method '{}'", e.getCause().getClass().getSimpleName(),76 locator.toString(), methodName);77 throw new ElementException(78 String.format("[PROXY] Can not call the method '%s' for the base element with the locator '%s'", method.getName(), locator.toString()),79 e.getCause());80 }81 };82 return (WebElement) Proxy83 .newProxyInstance(loader, new Class[]{WebElement.class, WrapsElement.class, Locatable.class}, handler);84 }85 private List<WebElement> getElements() {86 if (isStatic) {87 if (!cachedElements.isEmpty()) {88 log.debug("[PROXY] Get items from the cache. Count of elements '{}'. Locator '{}'", cachedElements.size(), locator.toString());89 return cachedElements;90 }91 }92 cachedElements = locator.findElements();93 log.debug("[PROXY] Search and get items. Count of elements '{}'. Locator '{}'", cachedElements.size(), locator.toString());94 return cachedElements;95 }96}...
Source:CustomFieldDecorator.java
1/*2 * Copyright (C) 2016 The Selenium Automation Framework Authors3 *4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except5 * in compliance with the License. You may obtain a copy of the License at6 *7 * http://www.apache.org/licenses/LICENSE-2.08 *9 * Unless required by applicable law or agreed to in writing, software distributed under the License10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express11 * or implied. See the License for the specific language governing permissions and limitations under12 * the License.13 *14 * Created by canhua li (licanhua@live.com)15 *16 */17package com.github.licanhua.test.framework.base;18import org.openqa.selenium.support.pagefactory.DefaultFieldDecorator;19import org.openqa.selenium.support.pagefactory.ElementLocator;20import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;21import org.openqa.selenium.support.pagefactory.FieldDecorator;22import java.lang.reflect.*;23import java.util.List;24import org.apache.log4j.Logger;25import org.openqa.selenium.WebElement;26import org.openqa.selenium.internal.Locatable;27import org.openqa.selenium.internal.WrapsElement;28import org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler;29/**30 * @author Canhua Li31 */32public class CustomFieldDecorator implements FieldDecorator {33 private static Logger logger = Logger.getLogger(CustomFieldDecorator.class.getName());34 private ElementLocatorFactory factory;35 private DefaultFieldDecorator decorator;36 private Element parent;37 public CustomFieldDecorator(ElementLocatorFactory factory, Element parent) {38 this.factory = factory;39 this.parent = parent;40 decorator = new DefaultFieldDecorator(factory);41 }42 private boolean inSkipList(Class clazz) {43 Class[] skips = {AbstractElement.class, CustomElement.class};44 for (Class c: skips) {45 if (c.equals(clazz))46 return true;47 }48 return false;49 }50 public Object decorate(ClassLoader loader, Field field) {51 logger.debug("decorate for " + field.getDeclaringClass().getName() + "." + field.getName());52 if (inSkipList(field.getDeclaringClass())) {53 logger.debug(" skipped for " + field.getDeclaringClass().getName() + "." + field.getName());54 return null;55 }56 if (!(CustomElementHelper.isDecoratableElement(field)57 || CustomElementHelper.isDecoratableElementList(field))) {58 return decorator.decorate(loader, field);59 }60 ElementLocator locator = factory.createLocator(field);61 if (locator == null) {62 return null;63 }64 if (CustomElementHelper.isDecoratableElement(field)) {65 WebElement webElement = proxyForLocator(loader, locator);66 return CustomElementHelper.createLazyProxyCustomElement(webElement, field.getType(), parent);67 } else {68 return proxyForCustomListLocator(loader, locator, field , parent);69 }70 }71 private WebElement proxyForLocator(ClassLoader loader, ElementLocator locator) {72 logger.debug("proxyForLocator : " + locator);73 InvocationHandler handler = new LocatingElementHandler(locator);74 WebElement proxy;75 proxy = (WebElement) Proxy.newProxyInstance(76 loader, new Class[]{WebElement.class, WrapsElement.class, Locatable.class}, handler);77 logger.debug("proxyForLocator complete : " + locator);78 return proxy;79 }80 private List<?> proxyForCustomListLocator(ClassLoader loader, ElementLocator locator, Field field, Element parent) {81 logger.debug("proxyForCustomListLocator for " + field.getName() + " and its locator is: " + locator);82 Class<?> clazz = CustomElementHelper.getElementTypeFromListField(field);83 InvocationHandler handler = new LocatingCustomElementListHandler(locator, clazz, parent );84 List<?> proxy;85 proxy = (List<?>) Proxy.newProxyInstance(86 loader, new Class[]{List.class}, handler);87 logger.debug("proxyForCustomListLocator complete for " + field.getName() + " and its locator is: " + locator);88 return proxy;89 }90}...
Source:ReclickingWebElement.java
1/*2 * Copyright (c) 2017 LabKey Corporation3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package org.labkey.test.selenium;17import org.labkey.test.WebDriverWrapper;18import org.labkey.test.util.TestLogger;19import org.labkey.test.util.selenium.WebDriverUtils;20import org.openqa.selenium.TimeoutException;21import org.openqa.selenium.WebDriver;22import org.openqa.selenium.WebDriverException;23import org.openqa.selenium.WebElement;24import org.openqa.selenium.interactions.Actions;25import org.openqa.selenium.internal.WrapsDriver;26import org.openqa.selenium.internal.WrapsElement;27import org.openqa.selenium.support.ui.ExpectedConditions;28import org.openqa.selenium.support.ui.WebDriverWait;29import java.util.ArrayList;30import java.util.List;31public class ReclickingWebElement extends WebElementDecorator32{33 public ReclickingWebElement(WebElement decoratedElement)34 {35 super(decoratedElement);36 }37 @Override38 public void click()39 {40 try41 {42 super.click();43 }44 catch (TimeoutException rethrow)45 {46 throw rethrow; // No retry for WebDriver timeout47 }48 catch (WebDriverException tryAgain)49 {50 if (getDriver() != null)51 {52 TestLogger.debug("Retry click: " + tryAgain.getMessage().split("\n")[0]);53 boolean clickBlocked = tryAgain.getMessage().contains("Other element would receive the click");54 revealElement(getWrappedElement(), clickBlocked);55 super.click();56 }57 else58 {59 throw tryAgain;60 }61 }62 }63 // Allows interaction with elements that have been obscured by the floating page header64 private void revealElement(WebElement el, boolean clickBlocked)65 {66 boolean revealed = false;67 WebDriverUtils.ScrollUtil scrollUtil = new WebDriverUtils.ScrollUtil(getDriver());68 if (clickBlocked)69 {70 new Actions(getDriver()).moveByOffset(-9999,-9999).build().perform(); // try to dismiss tooltips and such71 revealed = scrollUtil.scrollUnderFloatingHeader(el);72 }73 if (!revealed)74 {75 if (clickBlocked)76 WebDriverWrapper.sleep(2500); // Wait for a mask to disappear77 new WebDriverWait(getDriver(), 10).until(ExpectedConditions.elementToBeClickable(el));78 }79 }80 private final List<WebDriver> _webDriver = new ArrayList<>();81 private WebDriver getDriver()82 {83 if (_webDriver.isEmpty())84 {85 Object peeling = getWrappedElement();86 while (peeling instanceof WrapsElement)87 {88 peeling = ((WrapsElement) peeling).getWrappedElement();89 }90 while (peeling instanceof WrapsDriver)91 {92 peeling = ((WrapsDriver) peeling).getWrappedDriver();93 }94 if (peeling instanceof WebDriver)95 _webDriver.add((WebDriver) peeling);96 else97 _webDriver.add(null); // Only dig once, even if null98 }99 return _webDriver.get(0);100 }101}...
Source:DumpHttpExchangeFilter.java
...15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.remote.http;18import com.google.common.annotations.VisibleForTesting;19import org.openqa.selenium.internal.Debug;20import org.openqa.selenium.internal.Require;21import java.io.InputStream;22import java.util.function.Supplier;23import java.util.logging.Level;24import java.util.logging.Logger;25import java.util.stream.StreamSupport;26import static java.util.stream.Collectors.joining;27public class DumpHttpExchangeFilter implements Filter {28 public static final Logger LOG = Logger.getLogger(DumpHttpExchangeFilter.class.getName());29 private final Level logLevel;30 public DumpHttpExchangeFilter() {31 this(Debug.getDebugLogLevel());32 }33 public DumpHttpExchangeFilter(Level logLevel) {34 this.logLevel = Require.nonNull("Log level", logLevel);35 }36 @Override37 public HttpHandler apply(HttpHandler next) {38 return req -> {39 // Use the supplier to avoid messing with the request unless we're logging40 LOG.log(logLevel, () -> requestLogMessage(req));41 HttpResponse res = next.execute(req);42 LOG.log(logLevel, () -> responseLogMessage(res));43 return res;44 };45 }...
Debug
Using AI Code Generation
1import org.openqa.selenium.internal.Debug;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.chrome.ChromeDriver;4public class ChromeDebug {5 public static void main(String[] args) {6 System.setProperty("webdriver.chrome.driver", "C:\\Users\\rohit\\Downloads\\chromedriver_win32\\chromedriver.exe");7 WebDriver driver = new ChromeDriver();8 Debug debug = new Debug();9 debug.attachDriver(driver);10 }11}12C:\Users\rohit\eclipse-workspace\ChromeDebug>java -cp .;C:\Users\rohit\eclipse-workspace\ChromeDebug\lib\* ChromeDebug131518650313721 webdriver::server DEBUG -> POST /session {"desiredCapabilities":{"browserName":"chrome","version":"","platform":"ANY","javascriptEnabled":true,"cssSelectorsEnabled":true,"takesScreenshot":true,"nativeEvents":true,"rotatable":false,"locationContextEnabled":true,"applicationCacheEnabled":true,"handlesAlerts":true,"databaseEnabled":true,"webStorageEnabled":true,"browserConnectionEnabled":true,"acceptSslCerts":true,"takesElementScreenshot":true,"proxy":{}},"requiredCapabilities":{},"capabilities":{"desiredCapabilities":{"browserName":"chrome","version":"","platform":"ANY","javascriptEnabled":true,"cssSelectorsEnabled":true,"takesScreenshot":true,"nativeEvents":true,"rotatable":false,"locationContextEnabled":true,"applicationCacheEnabled":true,"handlesAlerts":true,"databaseEnabled":true,"webStorageEnabled":true,"browserConnectionEnabled":true,"acceptSslCerts":true,"takesElementScreenshot":true,"proxy":{}},"requiredCapabilities":{},"alwaysMatch":{"browserName":"chrome","browserVersion":"","platformName":"any","acceptInsecureCerts":true,"pageLoadStrategy":"normal","proxy":{}},"firstMatch":[{}]}}141518650313731 geckodriver::marionette DEBUG Starting browser C:\Program Files (x86)\Google\Chrome\Application\chrome.exe with args ["--marionette"]
Debug
Using AI Code Generation
1public class DebugTest {2 public static void main(String[] args) {3 System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");4 WebDriver driver = new ChromeDriver();5 WebElement element = driver.findElement(By.name("q"));6 element.sendKeys("Selenium");7 element.submit();8 System.out.println(list.size());9 for (int i = 0; i < list.size(); i++) {10 System.out.println(list.get(i).getText());11 if (list.get(i).getText().contains("selenium webdriver tutorial")) {12 list.get(i).click();13 break;14 }15 }16 driver.quit();17 }18}19Click() Method20driver.findElement(By.name("btnK")).click();21sendKeys() Method22driver.findElement(By.name("q")).sendKeys("Selenium WebDriver");23submit() Method24driver.findElement(By.name("q
Debug
Using AI Code Generation
1import org.openqa.selenium.internal.Debug;2Debug debug = new Debug();3debug.setValue(true);4debug.log("This is log message");5import org.openqa.selenium.remote.Debug;6Debug debug = new Debug();7debug.setValue(true);8debug.log("This is log message");
Debug
Using AI Code Generation
1import org.openqa.selenium.internal.Debug;2public class DebugDemo {3 public static void main(String[] args) {4 Debug debug = new Debug();5 debug.log(1, "Hello World");6 }7}8Debugging with debug() method9The debug() method is used to log a message with level 2. The debug() method is defined as below:10public void debug(String message)11Let’s see an example of debug() method:12import org.openqa.selenium.internal.Debug;13public class DebugDemo {14 public static void main(String[] args) {15 Debug debug = new Debug();16 debug.debug("Hello World");17 }18}19Debugging with isDebugEnabled() method20The isDebugEnabled() method is used to check whether the debugging is enabled or not. The isDebugEnabled() method is defined as below:21public boolean isDebugEnabled()22Let’s see an example of isDebugEnabled() method:23import org.openqa.selenium.internal.Debug;24public class DebugDemo {25 public static void main(String[] args) {26 Debug debug = new Debug();27 System.out.println(debug.isDebugEnabled());28 }29}30Debugging with isDebugEnabled(int) method31The isDebugEnabled(int) method is used to check whether the debugging is enabled for a particular level or not. The isDebugEnabled(int) method is defined as below:32public boolean isDebugEnabled(int level)33Let’s see an example of isDebugEnabled(int) method:34import org.openqa.selenium.internal.Debug;35public class DebugDemo {
Debug
Using AI Code Generation
1import org.openqa.selenium.internal.Debug;2public class DebugClass {3public static void main(String[] args) {4Debug debug = new Debug();5debug.debug("Debugging message");6}7}8import org.openqa.selenium.internal.Debug;9public class DebugClass {10public static void main(String[] args) {11Debug debug = new Debug();12debug.debug("Debugging message");13}14}
Debug
Using AI Code Generation
1package selenium;2import org.openqa.selenium.By;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.chrome.ChromeDriver;6import org.openqa.selenium.internal.Debug;7import org.openqa.selenium.support.ui.ExpectedConditions;8import org.openqa.selenium.support.ui.WebDriverWait;9public class DebugExample {10 public static void main(String[] args) {11 System.setProperty("webdriver.chrome.driver", "C:\\Users\\Sai\\Downloads\\chromedriver_win32\\chromedriver.exe");12 WebDriver driver = new ChromeDriver();13 WebElement searchBox = driver.findElement(By.name("q"));14 searchBox.sendKeys("Selenium");15 driver.findElement(By.name("btnK")).click();16 WebDriverWait wait = new WebDriverWait(driver, 10);17 wait.until(ExpectedConditions.titleContains("Selenium"));18 Debug debug = new Debug();19 debug.log("Title is: "+driver.getTitle());20 driver.quit();21 }22}
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!!