-
-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathHtmlUnitDriver.java
More file actions
1243 lines (1052 loc) · 41.4 KB
/
HtmlUnitDriver.java
File metadata and controls
1243 lines (1052 loc) · 41.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.selenium.htmlunit;
import static org.openqa.selenium.remote.Browser.HTMLUNIT;
import static org.openqa.selenium.remote.CapabilityType.ACCEPT_INSECURE_CERTS;
import static org.openqa.selenium.remote.CapabilityType.PAGE_LOAD_STRATEGY;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.net.ssl.SSLHandshakeException;
import org.htmlunit.BrowserVersion;
import org.htmlunit.Page;
import org.htmlunit.ProxyConfig;
import org.htmlunit.ScriptResult;
import org.htmlunit.SgmlPage;
import org.htmlunit.StringWebResponse;
import org.htmlunit.TopLevelWindow;
import org.htmlunit.UnexpectedPage;
import org.htmlunit.Version;
import org.htmlunit.WaitingRefreshHandler;
import org.htmlunit.WebClient;
import org.htmlunit.WebClientOptions;
import org.htmlunit.WebRequest;
import org.htmlunit.WebResponse;
import org.htmlunit.WebWindow;
import org.htmlunit.WebWindowEvent;
import org.htmlunit.WebWindowListener;
import org.htmlunit.corejs.javascript.Context;
import org.htmlunit.corejs.javascript.IdScriptableObject;
import org.htmlunit.corejs.javascript.NativeArray;
import org.htmlunit.corejs.javascript.NativeObject;
import org.htmlunit.corejs.javascript.Scriptable;
import org.htmlunit.corejs.javascript.Undefined;
import org.htmlunit.html.DomElement;
import org.htmlunit.html.DomNode;
import org.htmlunit.html.FrameWindow;
import org.htmlunit.html.HtmlElement;
import org.htmlunit.html.HtmlPage;
import org.htmlunit.javascript.HtmlUnitScriptable;
import org.htmlunit.javascript.host.Element;
import org.htmlunit.javascript.host.Location;
import org.htmlunit.javascript.host.html.DocumentProxy;
import org.htmlunit.javascript.host.html.HTMLCollection;
import org.htmlunit.javascript.host.html.HTMLElement;
import org.htmlunit.platform.AwtClipboardHandler;
import org.htmlunit.util.UrlUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.HasCapabilities;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchSessionException;
import org.openqa.selenium.NoSuchWindowException;
import org.openqa.selenium.Platform;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WrapsElement;
import org.openqa.selenium.htmlunit.w3.Action;
import org.openqa.selenium.htmlunit.w3.Algorithms;
import org.openqa.selenium.interactions.Interactive;
import org.openqa.selenium.interactions.Sequence;
import org.openqa.selenium.remote.Browser;
import org.openqa.selenium.remote.DesiredCapabilities;
/**
* An implementation of {@link WebDriver} that drives
* <a href="https://www.htmlunit.org">HtmlUnit</a>, which is a headless
* (GUI-less) browser simulator.
* <p>
* The main supported browsers are Chrome, Edge, Firefox and Internet Explorer.
*
* @author Alexei Barantsev
* @author Ahmed Ashour
* @author Rafael Jimenez
* @author Luke Inman-Semerau
* @author Kay McCormick
* @author Simon Stewart
* @author Javier Neira
* @author Ronald Brill
* @author Rob Winch
* @author Andrei Solntsev
* @author Martin Bartoš
*/
public class HtmlUnitDriver implements WebDriver, JavascriptExecutor, HasCapabilities, Interactive {
private static final int sleepTime = 200;
private WebClient webClient_;
private final HtmlUnitAlert alert_;
private HtmlUnitWindow currentWindow_;
private HtmlUnitKeyboard keyboard_;
private HtmlUnitMouse mouse_;
private final TargetLocator targetLocator_;
private AsyncScriptExecutor asyncScriptExecutor_;
private PageLoadStrategy pageLoadStrategy_ = PageLoadStrategy.NORMAL;
private final ElementsMap elementsMap_ = new ElementsMap();
private final Options options_;
private final HtmlUnitElementFinder elementFinder_;
private HtmlUnitInputProcessor inputProcessor_ = new HtmlUnitInputProcessor(this);
/** BROWSER_LANGUAGE_CAPABILITY = "browserLanguage". */
public static final String BROWSER_LANGUAGE_CAPABILITY = "browserLanguage";
/** DOWNLOAD_IMAGES_CAPABILITY = "downloadImages". */
public static final String DOWNLOAD_IMAGES_CAPABILITY = "downloadImages";
/** JAVASCRIPT_ENABLED = "javascriptEnabled". */
public static final String JAVASCRIPT_ENABLED = "javascriptEnabled";
private WebClient webClient;
/**
* The Lock for the {@link #mainCondition_}, which waits at the end of
* {@link #runAsync(Runnable)} till either and alert is triggered, or
* {@link Runnable} finishes.
*/
private final Lock conditionLock_ = new ReentrantLock();
private final Condition mainCondition_ = conditionLock_.newCondition();
private boolean runAsyncRunning_;
private RuntimeException exception_;
private final ExecutorService defaultExecutor_;
private Executor executor_;
private ProxyConfigurationManager proxyConfigurationManager=new ProxyConfigurationManager();
/**
* Constructs a new instance with JavaScript disabled, and the
* {@link BrowserVersion#getDefault() default} BrowserVersion.
*/
public HtmlUnitDriver() {
this(BrowserVersion.getDefault(), false);
}
/**
* Constructs a new instance with the specified {@link BrowserVersion}.
*
* @param version the browser version to use
*/
public HtmlUnitDriver(final BrowserVersion version) {
this(version, false);
}
/**
* Constructs a new instance, specify JavaScript support and using the
* {@link BrowserVersion#getDefault() default} BrowserVersion.
*
* @param enableJavascript whether to enable JavaScript support or not
*/
public HtmlUnitDriver(final boolean enableJavascript) {
this(BrowserVersion.getDefault(), enableJavascript);
}
/**
* Constructs a new instance with the specified {@link BrowserVersion} and the
* JavaScript support.
*
* @param version the browser version to use
* @param enableJavascript whether to enable JavaScript support or not
*/
public HtmlUnitDriver(final BrowserVersion version, final boolean enableJavascript) {
this(version, enableJavascript, null);
modifyWebClient(webClient_);
}
/**
* The browserName is {@link Browser#HTMLUNIT} "htmlunit" and the
* browserVersion denotes the required browser AND its version. For example
* "chrome" for Chrome, "firefox-100" for Firefox 100 or "internet explorer" for
* IE.
*
* @param capabilities desired capabilities requested for the htmlunit driver
* session
*/
public HtmlUnitDriver(final Capabilities capabilities) {
this(BrowserVersionDeterminer.determine(capabilities),
capabilities.getCapability(JAVASCRIPT_ENABLED) == null || capabilities.is(JAVASCRIPT_ENABLED),
Proxy.extractFrom(capabilities));
setDownloadImages(capabilities.is(DOWNLOAD_IMAGES_CAPABILITY));
if (alert_ != null) {
alert_.handleBrowserCapabilities(capabilities);
}
Boolean acceptInsecureCerts = (Boolean) capabilities.getCapability(ACCEPT_INSECURE_CERTS);
if (acceptInsecureCerts == null) {
acceptInsecureCerts = true;
}
setAcceptInsecureCerts(acceptInsecureCerts);
final String pageLoadStrategyString = (String) capabilities.getCapability(PAGE_LOAD_STRATEGY);
if ("none".equals(pageLoadStrategyString)) {
pageLoadStrategy_ = PageLoadStrategy.NONE;
}
else if ("eager".equals(pageLoadStrategyString)) {
pageLoadStrategy_ = PageLoadStrategy.EAGER;
}
modifyWebClient(webClient_);
}
public HtmlUnitDriver(final Capabilities desiredCapabilities, final Capabilities requiredCapabilities) {
this(new DesiredCapabilities(desiredCapabilities, requiredCapabilities));
}
private HtmlUnitDriver(final BrowserVersion version, final boolean enableJavascript, final Proxy proxy) {
webClient_ = newWebClient(version);
final WebClientOptions clientOptions = webClient_.getOptions();
clientOptions.setHomePage(UrlUtils.URL_ABOUT_BLANK.toString());
clientOptions.setThrowExceptionOnFailingStatusCode(false);
clientOptions.setPrintContentOnFailingStatusCode(false);
clientOptions.setRedirectEnabled(true);
clientOptions.setUseInsecureSSL(true);
setJavascriptEnabled(enableJavascript);
proxyConfigurationManager.setProxySettings(proxy);
webClient_.setRefreshHandler(new WaitingRefreshHandler());
webClient_.setClipboardHandler(new AwtClipboardHandler());
elementFinder_ = new HtmlUnitElementFinder();
alert_ = new HtmlUnitAlert(this);
currentWindow_ = new HtmlUnitWindow(webClient_.getCurrentWindow());
defaultExecutor_ = Executors.newCachedThreadPool();
executor_ = defaultExecutor_;
// Now put us on the home page, like a real browser
get(clientOptions.getHomePage());
options_ = new HtmlUnitOptions(this);
targetLocator_ = new HtmlUnitTargetLocator(this);
webClient_.addWebWindowListener(new WebWindowListener() {
@Override
public void webWindowOpened(final WebWindowEvent webWindowEvent) {
if (webWindowEvent.getWebWindow() instanceof TopLevelWindow) {
// use the first top level window we are getting aware of
if (currentWindow_ == null && webClient_.getTopLevelWindows().size() == 1) {
currentWindow_ = new HtmlUnitWindow(webClient_.getTopLevelWindows().get(0));
}
}
}
@Override
public void webWindowContentChanged(final WebWindowEvent event) {
elementsMap_.remove(event.getOldPage());
if (event.getWebWindow() != currentWindow_.getWebWindow()) {
return;
}
// Do we need to pick some new default content?
switchToDefaultContentOfWindow(currentWindow_.getWebWindow());
}
@Override
public void webWindowClosed(final WebWindowEvent event) {
elementsMap_.remove(event.getOldPage());
// the last window is gone
if (getWebClient().getTopLevelWindows().size() == 0) {
currentWindow_ = null;
return;
}
// Check if the event window refers to us or one of our parent windows
// setup the currentWindow appropriately if necessary
WebWindow ourCurrentWindow = currentWindow_.getWebWindow();
final WebWindow ourCurrentTopWindow = currentWindow_.getWebWindow().getTopWindow();
do {
// Instance equality is okay in this case
if (ourCurrentWindow == event.getWebWindow()) {
setCurrentWindow(ourCurrentTopWindow);
return;
}
ourCurrentWindow = ourCurrentWindow.getParentWindow();
}
while (ourCurrentWindow != ourCurrentTopWindow);
}
});
resetKeyboardAndMouseState();
}
/**
* @return to process or not to proceed
*/
boolean isProcessAlert() {
if (asyncScriptExecutor_ != null) {
final String text = alert_.getText();
alert_.dismiss();
asyncScriptExecutor_.alertTriggered(text);
return false;
}
conditionLock_.lock();
try {
mainCondition_.signal();
}
finally {
conditionLock_.unlock();
}
return true;
}
protected void runAsync(final Runnable r) {
final boolean loadStrategyWait = pageLoadStrategy_ != PageLoadStrategy.NONE;
if (loadStrategyWait) {
while (runAsyncRunning_) {
try {
Thread.sleep(10);
}
catch (final InterruptedException e) {
throw new RuntimeException(e);
}
}
conditionLock_.lock();
runAsyncRunning_ = true;
}
exception_ = null;
final Runnable wrapped = () -> {
try {
r.run();
}
catch (final RuntimeException e) {
exception_ = e;
}
finally {
conditionLock_.lock();
try {
runAsyncRunning_ = false;
mainCondition_.signal();
}
finally {
conditionLock_.unlock();
}
}
};
executor_.execute(wrapped);
if (loadStrategyWait && this.runAsyncRunning_) {
mainCondition_.awaitUninterruptibly();
conditionLock_.unlock();
}
if (exception_ != null) {
throw exception_;
}
}
public void click(final DomElement element, final boolean directClick) {
runAsync(() -> mouse_.click(element, directClick));
}
public void doubleClick(final DomElement element) {
runAsync(() -> mouse_.doubleClick(element));
}
public void mouseUp(final DomElement element) {
runAsync(() -> mouse_.mouseUp(element));
}
public void mouseMove(final DomElement element) {
runAsync(() -> mouse_.mouseMove(element));
}
public void mouseDown(final DomElement element) {
runAsync(() -> mouse_.mouseDown(element));
}
public void submit(final HtmlUnitWebElement element) {
runAsync(element::submitImpl);
}
public void sendKeys(final HtmlUnitWebElement element, final CharSequence... value) {
runAsync(() -> keyboard_.sendKeys(element, true, value));
}
/**
* Get the simulated {@code BrowserVersion}.
*
* @return the used {@code BrowserVersion}
*/
public BrowserVersion getBrowserVersion() {
return webClient_.getBrowserVersion();
}
/**
* Create the underlying WebClient, but don't set any fields on it.
*
* @param version Which browser to emulate
* @return a new instance of WebClient.
*/
protected WebClient newWebClient(final BrowserVersion version) {
return new WebClient(version);
}
/**
* Child classes can override this method to customize the WebClient that the
* HtmlUnit driver uses.
*
* @param client The client to modify
* @return The modified client
*/
protected WebClient modifyWebClient(final WebClient client) {
// Does nothing here to be overridden.
return client;
}
public HtmlUnitAlert getAlert() {
return alert_;
}
public ElementsMap getElementsMap() {
return elementsMap_;
}
public void setCurrentWindow(final WebWindow window) {
if (currentWindow_.getWebWindow() != window) {
currentWindow_ = new HtmlUnitWindow(window);
}
}
/**
* Sets the {@link Executor} to be used for submitting async tasks to. You have
* to close this manually on {@link #quit()}
*
* @param executor the {@link Executor} to use
*/
public void setExecutor(final Executor executor) {
if (executor == null) {
throw new IllegalArgumentException("executor cannot be null");
}
this.executor_ = executor;
}
@Override
public Capabilities getCapabilities() {
final DesiredCapabilities capabilities = new DesiredCapabilities(HTMLUNIT.browserName(), "", Platform.ANY);
capabilities.setPlatform(Platform.getCurrent());
capabilities.setVersion(Version.getProductVersion());
capabilities.setCapability(HtmlUnitDriver.JAVASCRIPT_ENABLED, isJavascriptEnabled());
return capabilities;
}
@Override
public void get(final String url) {
final URL fullUrl;
try {
// this takes care of data: and about:
fullUrl = UrlUtils.toUrlUnsafe(url);
}
catch (final Exception e) {
throw new WebDriverException(e);
}
runAsync(() -> get(fullUrl));
}
/**
* Allows HtmlUnit's about:blank to be loaded in the constructor, and may be
* useful for other tests?
*
* @param fullUrl The URL to visit
*/
protected void get(final URL fullUrl) {
getAlert().close();
getAlert().setAutoAccept(false);
try {
// we can't use webClient.getPage(url) here because selenium has a different
// idea of the current window and we like to load into to selenium current one
final BrowserVersion browser = getBrowserVersion();
final WebRequest request = new WebRequest(fullUrl, browser.getHtmlAcceptHeader(),
browser.getAcceptEncodingHeader());
request.setCharset(StandardCharsets.UTF_8);
getWebClient().getPage(getCurrentWindow().getWebWindow().getTopWindow(), request);
// A "get" works over the entire page
setCurrentWindow(getCurrentWindow().getWebWindow().getTopWindow());
}
catch (final UnknownHostException e) {
final WebWindow currentTopWebWindow = getCurrentWindow().getWebWindow().getTopWindow();
final UnexpectedPage unexpectedPage = new UnexpectedPage(new StringWebResponse("Unknown host", fullUrl),
currentTopWebWindow);
currentTopWebWindow.setEnclosedPage(unexpectedPage);
}
catch (final ConnectException e) {
// This might be expected
}
catch (final SocketTimeoutException e) {
throw new TimeoutException(e);
}
catch (final NoSuchSessionException e) {
throw e;
}
catch (final NoSuchWindowException e) {
throw e;
}
catch (final SSLHandshakeException e) {
return;
}
catch (final Exception e) {
throw new WebDriverException(e);
}
resetKeyboardAndMouseState();
}
private void resetKeyboardAndMouseState() {
keyboard_ = new HtmlUnitKeyboard(this);
mouse_ = new HtmlUnitMouse(this, keyboard_);
}
@Override
public String getCurrentUrl() {
getWebClient(); // check that session is active
final Page page = getCurrentWindow().getWebWindow().getTopWindow().getEnclosedPage();
if (page == null) {
return null;
}
final URL url = page.getUrl();
if (url == null) {
return null;
}
return url.toString();
}
@Override
public String getTitle() {
alert_.ensureUnlocked();
Page page = getCurrentWindow().lastPage();
if (!(page instanceof HtmlPage)) {
return null; // no page so there is no title
}
if (getCurrentWindow().getWebWindow() instanceof FrameWindow) {
page = getCurrentWindow().getWebWindow().getTopWindow().getEnclosedPage();
}
return ((HtmlPage) page).getTitleText();
}
@Override
public WebElement findElement(final By by) {
alert_.ensureUnlocked();
return implicitlyWaitFor(() -> elementFinder_.findElement(this, by));
}
@Override
public List<WebElement> findElements(final By by) {
final long implicitWait = options_.timeouts().getImplicitWaitTimeout().toMillis();
if (implicitWait < sleepTime) {
return elementFinder_.findElements(this, by);
}
final long end = System.currentTimeMillis() + implicitWait;
List<WebElement> found;
do {
found = elementFinder_.findElements(this, by);
if (!found.isEmpty()) {
return found;
}
sleepQuietly(sleepTime);
}
while (System.currentTimeMillis() < end);
return found;
}
public WebElement findElement(final HtmlUnitWebElement element, final By by) {
alert_.ensureUnlocked();
return implicitlyWaitFor(() -> elementFinder_.findElement(element, by));
}
public List<WebElement> findElements(final HtmlUnitWebElement element, final By by) {
final long implicitWait = options_.timeouts().getImplicitWaitTimeout().toMillis();
if (implicitWait < sleepTime) {
return elementFinder_.findElements(element, by);
}
final long end = System.currentTimeMillis() + implicitWait;
List<WebElement> found;
do {
found = elementFinder_.findElements(element, by);
if (!found.isEmpty()) {
return found;
}
sleepQuietly(sleepTime);
}
while (System.currentTimeMillis() < end);
return found;
}
@Override
public String getPageSource() {
final Page page = getCurrentWindow().lastPage();
if (page == null) {
return null;
}
if (page instanceof SgmlPage) {
return ((SgmlPage) page).asXml();
}
final WebResponse response = page.getWebResponse();
return response.getContentAsString();
}
@Override
public void close() {
getWebClient(); // check that session is active
if (getWebClient().getWebWindows().size() == 1) {
// closing the last window is equivalent to quit
quit();
}
else {
final WebWindow thisWindow = getCurrentWindow().getWebWindow(); // check that the current window is active
if (thisWindow != null) {
alert_.close();
((TopLevelWindow) thisWindow.getTopWindow()).close();
}
if (getWebClient().getWebWindows().size() == 0) {
quit();
}
}
}
@Override
public void quit() {
if (webClient_ != null) {
alert_.close();
webClient_.close();
webClient_ = null;
}
defaultExecutor_.shutdown();
}
@Override
public Set<String> getWindowHandles() {
final Set<String> allHandles = new HashSet<>();
for (final WebWindow window : getWebClient().getTopLevelWindows()) {
allHandles.add(String.valueOf(System.identityHashCode(window)));
}
return allHandles;
}
@Override
public String getWindowHandle() {
final WebWindow topWindow = getCurrentWindow().getWebWindow().getTopWindow();
if (topWindow.isClosed()) {
throw new NoSuchWindowException("Window is closed");
}
return String.valueOf(System.identityHashCode(topWindow));
}
@Override
public Object executeScript(String script, final Object... args) {
final HtmlPage page = getPageToInjectScriptInto();
script = "function() {" + script + "\n};";
ScriptResult result = page.executeJavaScript(script);
final Object function = result.getJavaScriptResult();
final Object[] parameters = convertScriptArgs(page, args);
try {
result = page.executeJavaScriptFunction(function, getCurrentWindow().getWebWindow().getScriptableObject(),
parameters, page.getDocumentElement());
return parseNativeJavascriptResult(result);
}
catch (final Throwable ex) {
throw new WebDriverException(ex);
}
}
@Override
public Object executeAsyncScript(final String script, Object... args) {
final HtmlPage page = getPageToInjectScriptInto();
args = convertScriptArgs(page, args);
asyncScriptExecutor_ = new AsyncScriptExecutor(page, options_.timeouts().getScriptTimeout().toMillis());
try {
final Object result = asyncScriptExecutor_.execute(script, args);
alert_.ensureUnlocked();
return parseNativeJavascriptResult(result);
}
finally {
asyncScriptExecutor_ = null;
}
}
private Object[] convertScriptArgs(final HtmlPage page, final Object[] args) {
final HtmlUnitScriptable scope = page.getEnclosingWindow().getScriptableObject();
if (scope == null) {
return args;
}
final Object[] parameters = new Object[args.length];
Context.enter();
try {
for (int i = 0; i < args.length; i++) {
parameters[i] = parseArgumentIntoJavascriptParameter(scope, args[i]);
}
}
finally {
Context.exit();
}
return parameters;
}
private HtmlPage getPageToInjectScriptInto() {
if (!isJavascriptEnabled()) {
throw new UnsupportedOperationException("Javascript is not enabled for this HtmlUnitDriver instance");
}
final Page lastPage = getCurrentWindow().lastPage();
if (!(lastPage instanceof HtmlPage)) {
throw new UnsupportedOperationException("Cannot execute JS against a plain text page");
}
return (HtmlPage) lastPage;
}
private Object parseArgumentIntoJavascriptParameter(final Scriptable scope, Object arg) {
while (arg instanceof WrapsElement) {
arg = ((WrapsElement) arg).getWrappedElement();
}
if (!(arg instanceof HtmlUnitWebElement
|| arg instanceof HtmlElement
|| arg instanceof Number // special case the underlying type
|| arg instanceof String
|| arg instanceof Boolean
|| arg.getClass().isArray()
|| arg instanceof Collection<?> || arg instanceof Map<?, ?>)) {
throw new IllegalArgumentException(
"Argument must be a string, number, boolean or WebElement: " + arg + " (" + arg.getClass() + ")");
}
if (arg instanceof HtmlUnitWebElement) {
final HtmlUnitWebElement webElement = (HtmlUnitWebElement) arg;
assertElementNotStale(webElement.getElement());
return webElement.getElement().getScriptableObject();
}
else if (arg instanceof HtmlElement) {
final HtmlElement element = (HtmlElement) arg;
assertElementNotStale(element);
return element.getScriptableObject();
}
else if (arg instanceof Collection<?>) {
final List<Object> list = new ArrayList<>();
for (final Object o : (Collection<?>) arg) {
list.add(parseArgumentIntoJavascriptParameter(scope, o));
}
return Context.getCurrentContext().newArray(scope, list.toArray());
}
else if (arg.getClass().isArray()) {
final List<Object> list = new ArrayList<>();
for (final Object o : (Object[]) arg) {
list.add(parseArgumentIntoJavascriptParameter(scope, o));
}
return Context.getCurrentContext().newArray(scope, list.toArray());
}
else if (arg instanceof Map<?, ?>) {
final Map<?, ?> argmap = (Map<?, ?>) arg;
final Scriptable map = Context.getCurrentContext().newObject(scope);
for (final Map.Entry<?, ?> entry : argmap.entrySet()) {
map.put((String) entry.getKey(), map, parseArgumentIntoJavascriptParameter(scope, entry.getValue()));
}
return map;
}
else {
return arg;
}
}
protected void assertElementNotStale(final DomElement element) {
final SgmlPage elementPage = element.getPage();
final Page lastPage = getCurrentWindow().lastPage();
if (!lastPage.equals(elementPage)) {
throw new StaleElementReferenceException(
"Element appears to be stale. Did you navigate away from the page that contained it? "
+ " And is the current window focussed the same as the one holding this element?");
}
// We need to walk the DOM to determine if the element is actually attached
DomNode parentElement = element;
while (parentElement != null && !(parentElement instanceof SgmlPage)) {
parentElement = parentElement.getParentNode();
}
if (parentElement == null) {
throw new StaleElementReferenceException("The element seems to be disconnected from the DOM. "
+ " This means that a user cannot interact with it.");
}
}
public HtmlUnitKeyboard getKeyboard() {
return keyboard_;
}
public HtmlUnitMouse getMouse() {
return mouse_;
}
protected interface JavaScriptResultsCollection {
int getLength();
Object item(int index);
}
private Object parseNativeJavascriptResult(final Object result) {
final Object value;
if (result instanceof ScriptResult) {
value = ((ScriptResult) result).getJavaScriptResult();
}
else {
value = result;
}
if (value instanceof HTMLElement) {
return toWebElement(((HTMLElement) value).getDomNodeOrDie());
}
if (value instanceof DocumentProxy) {
final Element element = ((DocumentProxy) value).getDelegee().getDocumentElement();
if (element instanceof HTMLElement) {
return toWebElement(((HTMLElement) element).getDomNodeOrDie());
}
throw new WebDriverException("Do not know how to coerce to an HTMLElement: " + element);
}
if (value instanceof Number) {
final Number n = (Number) value;
final String s = n.toString();
if (!s.contains(".") || s.endsWith(".0")) { // how safe it is? enough for the unit tests!
return n.longValue();
}
return n.doubleValue();
}
if (value instanceof NativeObject) {
@SuppressWarnings("unchecked")
final Map<String, Object> map = new HashMap<>((NativeObject) value);
for (final Entry<String, Object> e : map.entrySet()) {
e.setValue(parseNativeJavascriptResult(e.getValue()));
}
return map;
}
if (value instanceof Location) {
return convertLocationToMap((Location) value);
}
if (value instanceof NativeArray) {
final NativeArray array = (NativeArray) value;
final JavaScriptResultsCollection collection = new JavaScriptResultsCollection() {
@Override
public int getLength() {
return (int) array.getLength();
}
@Override
public Object item(final int index) {
return array.get(index);
}
};
return parseJavascriptResultsList(collection);
}
if (value instanceof HTMLCollection) {
final HTMLCollection array = (HTMLCollection) value;
final JavaScriptResultsCollection collection = new JavaScriptResultsCollection() {
@Override
public int getLength() {
return array.getLength();
}
@Override
public Object item(final int index) {
return array.get(index);
}
};
return parseJavascriptResultsList(collection);
}
if (value instanceof IdScriptableObject && value.getClass().getSimpleName().equals("NativeDate")) {
final long l = ((Number) getPrivateField(value, "date")).longValue();
return Instant.ofEpochMilli(l).toString();
}
if (Undefined.isUndefined(value)) {
return null;
}
return value;
}
private static Object getPrivateField(final Object o, final String fieldName) {
try {
final Field field = o.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(o);
}
catch (final Exception e) {
throw new RuntimeException(e);
}
}
private static Map<String, Object> convertLocationToMap(final Location location) {
final Map<String, Object> map = new HashMap<>();
map.put("protocol", location.getProtocol());
map.put("host", location.getHost());
map.put("hostname", location.getHostname());
map.put("port", location.getPort());
map.put("pathname", location.getPathname());
map.put("search", location.getSearch());
map.put("hash", location.getHash());
map.put("href", location.getHref());
return map;
}
private List<Object> parseJavascriptResultsList(final JavaScriptResultsCollection array) {
final List<Object> list = new ArrayList<>(array.getLength());
for (int i = 0; i < array.getLength(); ++i) {
list.add(parseNativeJavascriptResult(array.item(i)));
}
return list;
}