1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit;
16
17 import static java.nio.charset.StandardCharsets.ISO_8859_1;
18 import static java.nio.charset.StandardCharsets.UTF_8;
19 import static org.htmlunit.BrowserVersionFeatures.HTTP_HEADER_CH_UA;
20 import static org.htmlunit.BrowserVersionFeatures.HTTP_HEADER_PRIORITY;
21
22 import java.io.BufferedInputStream;
23 import java.io.File;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.ObjectInputStream;
27 import java.io.Serializable;
28 import java.lang.ref.WeakReference;
29 import java.net.MalformedURLException;
30 import java.net.URL;
31 import java.net.URLConnection;
32 import java.net.URLDecoder;
33 import java.nio.charset.Charset;
34 import java.nio.file.Files;
35 import java.util.ArrayList;
36 import java.util.Collections;
37 import java.util.ConcurrentModificationException;
38 import java.util.Date;
39 import java.util.HashMap;
40 import java.util.HashSet;
41 import java.util.Iterator;
42 import java.util.LinkedHashMap;
43 import java.util.LinkedHashSet;
44 import java.util.List;
45 import java.util.Locale;
46 import java.util.Map;
47 import java.util.Objects;
48 import java.util.Optional;
49 import java.util.Set;
50 import java.util.concurrent.ConcurrentLinkedDeque;
51 import java.util.concurrent.Executor;
52 import java.util.concurrent.ExecutorService;
53 import java.util.concurrent.Executors;
54 import java.util.concurrent.ThreadFactory;
55 import java.util.concurrent.ThreadPoolExecutor;
56
57 import org.apache.commons.logging.Log;
58 import org.apache.commons.logging.LogFactory;
59 import org.apache.http.NoHttpResponseException;
60 import org.apache.http.client.CredentialsProvider;
61 import org.apache.http.cookie.MalformedCookieException;
62 import org.htmlunit.attachment.Attachment;
63 import org.htmlunit.attachment.AttachmentHandler;
64 import org.htmlunit.csp.Policy;
65 import org.htmlunit.csp.url.URI;
66 import org.htmlunit.css.ComputedCssStyleDeclaration;
67 import org.htmlunit.cssparser.parser.CSSErrorHandler;
68 import org.htmlunit.cssparser.parser.javacc.CSS3Parser;
69 import org.htmlunit.html.BaseFrameElement;
70 import org.htmlunit.html.DomElement;
71 import org.htmlunit.html.DomNode;
72 import org.htmlunit.html.FrameWindow;
73 import org.htmlunit.html.FrameWindow.PageDenied;
74 import org.htmlunit.html.HtmlElement;
75 import org.htmlunit.html.HtmlInlineFrame;
76 import org.htmlunit.html.HtmlPage;
77 import org.htmlunit.html.XHtmlPage;
78 import org.htmlunit.html.parser.HTMLParser;
79 import org.htmlunit.html.parser.HTMLParserListener;
80 import org.htmlunit.http.HttpStatus;
81 import org.htmlunit.http.HttpUtils;
82 import org.htmlunit.httpclient.HttpClientConverter;
83 import org.htmlunit.javascript.AbstractJavaScriptEngine;
84 import org.htmlunit.javascript.DefaultJavaScriptErrorListener;
85 import org.htmlunit.javascript.HtmlUnitScriptable;
86 import org.htmlunit.javascript.JavaScriptEngine;
87 import org.htmlunit.javascript.JavaScriptErrorListener;
88 import org.htmlunit.javascript.background.JavaScriptJobManager;
89 import org.htmlunit.javascript.host.Location;
90 import org.htmlunit.javascript.host.Window;
91 import org.htmlunit.javascript.host.dom.Node;
92 import org.htmlunit.javascript.host.event.Event;
93 import org.htmlunit.javascript.host.file.Blob;
94 import org.htmlunit.javascript.host.html.HTMLIFrameElement;
95 import org.htmlunit.protocol.data.DataURLConnection;
96 import org.htmlunit.util.Cookie;
97 import org.htmlunit.util.HeaderUtils;
98 import org.htmlunit.util.MimeType;
99 import org.htmlunit.util.NameValuePair;
100 import org.htmlunit.util.StringUtils;
101 import org.htmlunit.util.UrlUtils;
102 import org.htmlunit.websocket.JettyWebSocketAdapter.JettyWebSocketAdapterFactory;
103 import org.htmlunit.websocket.WebSocketAdapter;
104 import org.htmlunit.websocket.WebSocketAdapterFactory;
105 import org.htmlunit.websocket.WebSocketListener;
106 import org.htmlunit.webstart.WebStartHandler;
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 @SuppressWarnings("PMD.TooManyFields")
155 public class WebClient implements Serializable, AutoCloseable {
156
157
158 private static final Log LOG = LogFactory.getLog(WebClient.class);
159
160
161 private static final int ALLOWED_REDIRECTIONS_SAME_URL = 20;
162 private static final WebResponseData RESPONSE_DATA_NO_HTTP_RESPONSE = new WebResponseData(
163 0, "No HTTP Response", Collections.emptyList());
164
165
166
167
168
169 private static final String[] DISCARDING_304_RESPONSE_HEADER_NAMES = {
170 "connection",
171 "proxy-connection",
172 "keep-alive",
173 "www-authenticate",
174 "proxy-authenticate",
175 "proxy-authorization",
176 "te",
177 "trailer",
178 "transfer-encoding",
179 "upgrade",
180 "content-location",
181 "content-md5",
182 "etag",
183 "content-encoding",
184 "content-range",
185 "content-type",
186 "content-length",
187 "x-frame-options",
188 "x-xss-protection",
189 };
190
191 private static final String[] DISCARDING_304_HEADER_PREFIXES = {
192 "x-content-",
193 "x-webkit-"
194 };
195
196 private transient WebConnection webConnection_;
197 private CredentialsProvider credentialsProvider_ = new DefaultCredentialsProvider();
198 private CookieManager cookieManager_ = new CookieManager();
199 private WebSocketAdapterFactory webSocketAdapterFactory_;
200 private transient AbstractJavaScriptEngine<?> scriptEngine_;
201 private transient List<LoadJob> loadQueue_;
202 private final Map<String, String> requestHeaders_ = Collections.synchronizedMap(new HashMap<>(89));
203 private IncorrectnessListener incorrectnessListener_ = new IncorrectnessListenerImpl();
204 private WebConsole webConsole_;
205 private transient ExecutorService executor_;
206
207 private AlertHandler alertHandler_;
208 private ConfirmHandler confirmHandler_;
209 private PromptHandler promptHandler_;
210 private StatusHandler statusHandler_;
211 private AttachmentHandler attachmentHandler_;
212 private ClipboardHandler clipboardHandler_;
213 private PrintHandler printHandler_;
214 private WebStartHandler webStartHandler_;
215 private FrameContentHandler frameContentHandler_;
216
217 private AjaxController ajaxController_ = new AjaxController();
218
219 private final BrowserVersion browserVersion_;
220 private PageCreator pageCreator_ = new DefaultPageCreator();
221
222
223
224
225 private CurrentWindowTracker currentWindowTracker_;
226 private final Set<WebWindowListener> webWindowListeners_ = new HashSet<>(5);
227
228 private final List<TopLevelWindow> topLevelWindows_ =
229 Collections.synchronizedList(new ArrayList<>());
230 private final List<WebWindow> windows_ = Collections.synchronizedList(new ArrayList<>());
231 private transient List<WeakReference<JavaScriptJobManager>> jobManagers_ =
232 Collections.synchronizedList(new ArrayList<>());
233 private WebWindow currentWindow_;
234
235 private HTMLParserListener htmlParserListener_;
236 private CSSErrorHandler cssErrorHandler_ = new DefaultCssErrorHandler();
237 private OnbeforeunloadHandler onbeforeunloadHandler_;
238 private Cache cache_ = new Cache();
239
240
241 private transient CSS3ParserPool css3ParserPool_ = new CSS3ParserPool();
242
243
244 public static final String TARGET_BLANK = "_blank";
245
246
247 public static final String TARGET_SELF = "_self";
248
249
250 private static final String TARGET_PARENT = "_parent";
251
252 private static final String TARGET_TOP = "_top";
253
254 private ScriptPreProcessor scriptPreProcessor_;
255
256 private RefreshHandler refreshHandler_ = new NiceRefreshHandler(2);
257 private JavaScriptErrorListener javaScriptErrorListener_ = new DefaultJavaScriptErrorListener();
258
259 private final WebClientOptions options_ = new WebClientOptions();
260 private final boolean javaScriptEngineEnabled_;
261 private final StorageHolder storageHolder_ = new StorageHolder();
262
263
264
265
266
267 public WebClient() {
268 this(BrowserVersion.getDefault());
269 }
270
271
272
273
274
275 public WebClient(final BrowserVersion browserVersion) {
276 this(browserVersion, null, -1);
277 }
278
279
280
281
282
283
284
285 public WebClient(final BrowserVersion browserVersion, final String proxyHost, final int proxyPort) {
286 this(browserVersion, true, proxyHost, proxyPort, null);
287 }
288
289
290
291
292
293
294
295
296 public WebClient(final BrowserVersion browserVersion,
297 final String proxyHost, final int proxyPort, final String proxyScheme) {
298 this(browserVersion, true, proxyHost, proxyPort, proxyScheme);
299 }
300
301
302
303
304
305
306
307
308 public WebClient(final BrowserVersion browserVersion, final boolean javaScriptEngineEnabled,
309 final String proxyHost, final int proxyPort) {
310 this(browserVersion, javaScriptEngineEnabled, proxyHost, proxyPort, null);
311 }
312
313
314
315
316
317
318
319
320
321 public WebClient(final BrowserVersion browserVersion, final boolean javaScriptEngineEnabled,
322 final String proxyHost, final int proxyPort, final String proxyScheme) {
323 WebAssert.notNull("browserVersion", browserVersion);
324
325 browserVersion_ = browserVersion;
326 javaScriptEngineEnabled_ = javaScriptEngineEnabled;
327
328 if (proxyHost == null) {
329 getOptions().setProxyConfig(new ProxyConfig());
330 }
331 else {
332 getOptions().setProxyConfig(new ProxyConfig(proxyHost, proxyPort, proxyScheme));
333 }
334
335 webConnection_ = new HttpWebConnection(this);
336 if (javaScriptEngineEnabled_) {
337 scriptEngine_ = new JavaScriptEngine(this);
338 }
339 loadQueue_ = new ArrayList<>();
340
341 webSocketAdapterFactory_ = new JettyWebSocketAdapterFactory();
342
343
344 currentWindowTracker_ = new CurrentWindowTracker(this, true);
345 currentWindow_ = new TopLevelWindow("", this);
346 }
347
348
349
350
351
352 private static final class ThreadNamingFactory implements ThreadFactory {
353 private static int ID_ = 1;
354 private final ThreadFactory baseFactory_;
355
356 ThreadNamingFactory(final ThreadFactory aBaseFactory) {
357 baseFactory_ = aBaseFactory;
358 }
359
360 @Override
361 public Thread newThread(final Runnable aRunnable) {
362 final Thread thread = baseFactory_.newThread(aRunnable);
363 thread.setName("WebClient Thread " + ID_++);
364 return thread;
365 }
366 }
367
368
369
370
371
372
373 public WebConnection getWebConnection() {
374 return webConnection_;
375 }
376
377
378
379
380
381
382 public void setWebConnection(final WebConnection webConnection) {
383 WebAssert.notNull("webConnection", webConnection);
384 webConnection_ = webConnection;
385 }
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408 public <P extends Page> P getPage(final WebWindow webWindow, final WebRequest webRequest)
409 throws IOException, FailingHttpStatusCodeException {
410 return getPage(webWindow, webRequest, true);
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 @SuppressWarnings("unchecked")
438 <P extends Page> P getPage(final WebWindow webWindow, final WebRequest webRequest,
439 final boolean addToHistory)
440 throws IOException, FailingHttpStatusCodeException {
441
442 final Page page = webWindow.getEnclosedPage();
443
444 if (page != null) {
445 final URL prev = page.getUrl();
446 final URL current = webRequest.getUrl();
447 if (UrlUtils.sameFile(current, prev)
448 && current.getRef() != null
449 && !Objects.equals(current.getRef(), prev.getRef())) {
450
451 page.getWebResponse().getWebRequest().setUrl(current);
452 if (addToHistory) {
453 webWindow.getHistory().addPage(page);
454 }
455
456
457
458 if (page instanceof HtmlPage) {
459 ((HtmlPage) page).clearComputedStyles();
460 }
461
462 final Window window = webWindow.getScriptableObject();
463 if (window != null) {
464 window.getLocation().setHash(current.getRef());
465 }
466 return (P) page;
467 }
468
469 if (page.isHtmlPage()) {
470 final HtmlPage htmlPage = (HtmlPage) page;
471 if (!htmlPage.isOnbeforeunloadAccepted()) {
472 LOG.debug("The registered OnbeforeunloadHandler rejected to load a new page.");
473 return (P) page;
474 }
475 }
476 }
477
478 if (LOG.isDebugEnabled()) {
479 LOG.debug("Get page for window named '" + webWindow.getName() + "', using " + webRequest);
480 }
481
482 WebResponse webResponse;
483 final String protocol = webRequest.getUrl().getProtocol();
484 if ("javascript".equals(protocol)) {
485 webResponse = makeWebResponseForJavaScriptUrl(webWindow, webRequest.getUrl(), webRequest.getCharset());
486 if (webWindow.getEnclosedPage() != null && webWindow.getEnclosedPage().getWebResponse() == webResponse) {
487
488 return (P) webWindow.getEnclosedPage();
489 }
490 }
491 else {
492 try {
493 webResponse = loadWebResponse(webRequest);
494 }
495 catch (final NoHttpResponseException e) {
496 webResponse = new WebResponse(RESPONSE_DATA_NO_HTTP_RESPONSE, webRequest, 0);
497 }
498 }
499
500 printContentIfNecessary(webResponse);
501 loadWebResponseInto(webResponse, webWindow);
502
503
504
505
506 if (scriptEngine_ != null) {
507 scriptEngine_.registerWindowAndMaybeStartEventLoop(webWindow);
508 }
509
510
511 throwFailingHttpStatusCodeExceptionIfNecessary(webResponse);
512 return (P) webWindow.getEnclosedPage();
513 }
514
515
516
517
518
519
520
521
522
523
524
525
526
527 public <P extends Page> P getPage(final String url) throws IOException, FailingHttpStatusCodeException,
528 MalformedURLException {
529 return getPage(UrlUtils.toUrlUnsafe(url));
530 }
531
532
533
534
535
536
537
538
539
540
541
542
543 public <P extends Page> P getPage(final URL url) throws IOException, FailingHttpStatusCodeException {
544 final WebRequest request = new WebRequest(url, getBrowserVersion().getHtmlAcceptHeader(),
545 getBrowserVersion().getAcceptEncodingHeader());
546 request.setCharset(UTF_8);
547 return getPage(getCurrentWindow().getTopWindow(), request);
548 }
549
550
551
552
553
554
555
556
557
558
559
560 public <P extends Page> P getPage(final WebRequest request) throws IOException,
561 FailingHttpStatusCodeException {
562 return getPage(getCurrentWindow().getTopWindow(), request);
563 }
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582 public Page loadWebResponseInto(final WebResponse webResponse, final WebWindow webWindow)
583 throws IOException, FailingHttpStatusCodeException {
584 return loadWebResponseInto(webResponse, webWindow, null);
585 }
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608 public Page loadWebResponseInto(final WebResponse webResponse, final WebWindow webWindow,
609 String forceAttachmentWithFilename)
610 throws IOException, FailingHttpStatusCodeException {
611 WebAssert.notNull("webResponse", webResponse);
612 WebAssert.notNull("webWindow", webWindow);
613
614 if (webResponse.getStatusCode() == HttpStatus.NO_CONTENT_204) {
615 return webWindow.getEnclosedPage();
616 }
617
618 if (webStartHandler_ != null && "application/x-java-jnlp-file".equals(webResponse.getContentType())) {
619 webStartHandler_.handleJnlpResponse(webResponse);
620 return webWindow.getEnclosedPage();
621 }
622
623 if (attachmentHandler_ != null
624 && (forceAttachmentWithFilename != null || attachmentHandler_.isAttachment(webResponse))) {
625
626
627 if (StringUtils.isEmptyOrNull(forceAttachmentWithFilename)) {
628 final String disp = webResponse.getResponseHeaderValue(HttpHeader.CONTENT_DISPOSITION);
629 forceAttachmentWithFilename = Attachment.getSuggestedFilename(disp);
630 }
631
632 if (attachmentHandler_.handleAttachment(webResponse,
633 StringUtils.isEmptyOrNull(forceAttachmentWithFilename) ? null : forceAttachmentWithFilename)) {
634
635
636 return webWindow.getEnclosedPage();
637 }
638
639 final WebWindow w = openWindow(null, null, webWindow);
640 final Page page = pageCreator_.createPage(webResponse, w);
641 attachmentHandler_.handleAttachment(page,
642 StringUtils.isEmptyOrNull(forceAttachmentWithFilename)
643 ? null : forceAttachmentWithFilename);
644 return page;
645 }
646
647 final Page oldPage = webWindow.getEnclosedPage();
648 if (oldPage != null) {
649
650 oldPage.cleanUp();
651 }
652
653 Page newPage = null;
654 FrameWindow.PageDenied pageDenied = PageDenied.NONE;
655 if (windows_.contains(webWindow)) {
656 if (webWindow instanceof FrameWindow) {
657 final String contentSecurityPolicy =
658 webResponse.getResponseHeaderValue(HttpHeader.CONTENT_SECURIRY_POLICY);
659 if (StringUtils.isNotBlank(contentSecurityPolicy)) {
660 final URL origin = UrlUtils.getUrlWithoutPathRefQuery(
661 ((FrameWindow) webWindow).getEnclosingPage().getUrl());
662 final URL source = UrlUtils.getUrlWithoutPathRefQuery(webResponse.getWebRequest().getUrl());
663 final Policy policy = Policy.parseSerializedCSP(contentSecurityPolicy,
664 Policy.PolicyErrorConsumer.ignored);
665 if (!policy.allowsFrameAncestor(
666 Optional.of(URI.parseURI(source.toExternalForm()).orElse(null)),
667 Optional.of(URI.parseURI(origin.toExternalForm()).orElse(null)))) {
668 pageDenied = PageDenied.BY_CONTENT_SECURIRY_POLICY;
669
670 if (LOG.isWarnEnabled()) {
671 LOG.warn("Load denied by Content-Security-Policy: '" + contentSecurityPolicy + "' - "
672 + webResponse.getWebRequest().getUrl() + "' does not permit framing.");
673 }
674 }
675 }
676
677 if (pageDenied == PageDenied.NONE) {
678 final String xFrameOptions = webResponse.getResponseHeaderValue(HttpHeader.X_FRAME_OPTIONS);
679 if ("DENY".equalsIgnoreCase(xFrameOptions)) {
680 pageDenied = PageDenied.BY_X_FRAME_OPTIONS;
681
682 if (LOG.isWarnEnabled()) {
683 LOG.warn("Load denied by X-Frame-Options: DENY; - '"
684 + webResponse.getWebRequest().getUrl() + "' does not permit framing.");
685 }
686 }
687 }
688 }
689
690 if (pageDenied == PageDenied.NONE) {
691 newPage = pageCreator_.createPage(webResponse, webWindow);
692 }
693 else {
694 try {
695 final WebResponse aboutBlank = loadWebResponse(WebRequest.newAboutBlankRequest());
696 newPage = pageCreator_.createPage(aboutBlank, webWindow);
697
698
699 ((FrameWindow) webWindow).setPageDenied(pageDenied);
700 }
701 catch (final IOException ignored) {
702
703 }
704 }
705
706 if (windows_.contains(webWindow)) {
707 fireWindowContentChanged(new WebWindowEvent(webWindow, WebWindowEvent.CHANGE, oldPage, newPage));
708
709
710 if (webWindow.getEnclosedPage() == newPage) {
711 newPage.initialize();
712
713
714 if (isJavaScriptEnabled()
715 && webWindow instanceof FrameWindow && !newPage.isHtmlPage()) {
716 final FrameWindow fw = (FrameWindow) webWindow;
717 final BaseFrameElement frame = fw.getFrameElement();
718 if (frame.hasEventHandlers("onload")) {
719 if (LOG.isDebugEnabled()) {
720 LOG.debug("Executing onload handler for " + frame);
721 }
722 final Event event = new Event(frame, Event.TYPE_LOAD);
723 ((Node) frame.getScriptableObject()).executeEventLocally(event);
724 }
725 }
726 }
727 }
728 }
729 return newPage;
730 }
731
732
733
734
735
736
737
738
739
740 public void printContentIfNecessary(final WebResponse webResponse) {
741 if (getOptions().isPrintContentOnFailingStatusCode()
742 && !webResponse.isSuccess() && LOG.isInfoEnabled()) {
743 final String contentType = webResponse.getContentType();
744 LOG.info("statusCode=[" + webResponse.getStatusCode() + "] contentType=[" + contentType + "]");
745 LOG.info(webResponse.getContentAsString());
746 }
747 }
748
749
750
751
752
753
754
755
756
757 public void throwFailingHttpStatusCodeExceptionIfNecessary(final WebResponse webResponse) {
758 if (getOptions().isThrowExceptionOnFailingStatusCode() && !webResponse.isSuccessOrUseProxyOrNotModified()) {
759 throw new FailingHttpStatusCodeException(webResponse);
760 }
761 }
762
763
764
765
766
767
768
769
770
771 public void addRequestHeader(final String name, final String value) {
772 if (HttpHeader.COOKIE_LC.equalsIgnoreCase(name)) {
773 throw new IllegalArgumentException("Do not add 'Cookie' header, use .getCookieManager() instead");
774 }
775 requestHeaders_.put(name, value);
776 }
777
778
779
780
781
782
783
784
785
786
787 public void removeRequestHeader(final String name) {
788 requestHeaders_.remove(name);
789 }
790
791
792
793
794
795
796
797
798 public void setCredentialsProvider(final CredentialsProvider credentialsProvider) {
799 WebAssert.notNull("credentialsProvider", credentialsProvider);
800 credentialsProvider_ = credentialsProvider;
801 }
802
803
804
805
806
807
808 public CredentialsProvider getCredentialsProvider() {
809 return credentialsProvider_;
810 }
811
812
813
814
815
816 public AbstractJavaScriptEngine<?> getJavaScriptEngine() {
817 return scriptEngine_;
818 }
819
820
821
822
823
824
825 public void setJavaScriptEngine(final AbstractJavaScriptEngine<?> engine) {
826 if (engine == null) {
827 throw new IllegalArgumentException("Can't set JavaScriptEngine to null");
828 }
829 scriptEngine_ = engine;
830 }
831
832
833
834
835
836 public CookieManager getCookieManager() {
837 return cookieManager_;
838 }
839
840
841
842
843
844 public void setCookieManager(final CookieManager cookieManager) {
845 WebAssert.notNull("cookieManager", cookieManager);
846 cookieManager_ = cookieManager;
847 }
848
849
850
851
852
853 public void setAlertHandler(final AlertHandler alertHandler) {
854 alertHandler_ = alertHandler;
855 }
856
857
858
859
860
861 public AlertHandler getAlertHandler() {
862 return alertHandler_;
863 }
864
865
866
867
868
869 public void setConfirmHandler(final ConfirmHandler handler) {
870 confirmHandler_ = handler;
871 }
872
873
874
875
876
877 public ConfirmHandler getConfirmHandler() {
878 return confirmHandler_;
879 }
880
881
882
883
884
885 public void setPromptHandler(final PromptHandler handler) {
886 promptHandler_ = handler;
887 }
888
889
890
891
892
893 public PromptHandler getPromptHandler() {
894 return promptHandler_;
895 }
896
897
898
899
900
901 public void setStatusHandler(final StatusHandler statusHandler) {
902 statusHandler_ = statusHandler;
903 }
904
905
906
907
908
909 public StatusHandler getStatusHandler() {
910 return statusHandler_;
911 }
912
913
914
915
916
917 public synchronized Executor getExecutor() {
918 if (executor_ == null) {
919 final ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
920 threadPoolExecutor.setThreadFactory(new ThreadNamingFactory(threadPoolExecutor.getThreadFactory()));
921
922 executor_ = threadPoolExecutor;
923 }
924
925 return executor_;
926 }
927
928
929
930
931
932
933
934 public synchronized void setExecutor(final ExecutorService executor) {
935 if (executor_ != null) {
936 throw new IllegalStateException("Can't change the executor after first use.");
937 }
938
939 executor_ = executor;
940 }
941
942
943
944
945
946
947 public void setJavaScriptErrorListener(final JavaScriptErrorListener javaScriptErrorListener) {
948 if (javaScriptErrorListener == null) {
949 javaScriptErrorListener_ = new DefaultJavaScriptErrorListener();
950 }
951 else {
952 javaScriptErrorListener_ = javaScriptErrorListener;
953 }
954 }
955
956
957
958
959
960 public JavaScriptErrorListener getJavaScriptErrorListener() {
961 return javaScriptErrorListener_;
962 }
963
964
965
966
967
968 public BrowserVersion getBrowserVersion() {
969 return browserVersion_;
970 }
971
972
973
974
975
976
977 public WebWindow getCurrentWindow() {
978 return currentWindow_;
979 }
980
981
982
983
984
985
986 public void setCurrentWindow(final WebWindow window) {
987 WebAssert.notNull("window", window);
988 if (currentWindow_ == window) {
989 return;
990 }
991
992 if (currentWindow_ != null && !currentWindow_.isClosed()) {
993 final Page enclosedPage = currentWindow_.getEnclosedPage();
994 if (enclosedPage != null && enclosedPage.isHtmlPage()) {
995 final DomElement focusedElement = ((HtmlPage) enclosedPage).getFocusedElement();
996 if (focusedElement != null) {
997 focusedElement.fireEvent(Event.TYPE_BLUR);
998 }
999 }
1000 }
1001 currentWindow_ = window;
1002
1003
1004 final boolean isIFrame = currentWindow_ instanceof FrameWindow
1005 && ((FrameWindow) currentWindow_).getFrameElement() instanceof HtmlInlineFrame;
1006 if (!isIFrame) {
1007
1008
1009 final Page enclosedPage = currentWindow_.getEnclosedPage();
1010 if (enclosedPage != null && enclosedPage.isHtmlPage()) {
1011 final HtmlPage enclosedHtmlPage = (HtmlPage) enclosedPage;
1012 final HtmlElement activeElement = enclosedHtmlPage.getActiveElement();
1013 if (activeElement != null) {
1014 enclosedHtmlPage.setFocusedElement(activeElement, true);
1015 }
1016 }
1017 }
1018 }
1019
1020
1021
1022
1023
1024
1025 public void addWebWindowListener(final WebWindowListener listener) {
1026 WebAssert.notNull("listener", listener);
1027 webWindowListeners_.add(listener);
1028 }
1029
1030
1031
1032
1033
1034 public void removeWebWindowListener(final WebWindowListener listener) {
1035 WebAssert.notNull("listener", listener);
1036 webWindowListeners_.remove(listener);
1037 }
1038
1039 private void fireWindowContentChanged(final WebWindowEvent event) {
1040 if (currentWindowTracker_ != null) {
1041 currentWindowTracker_.webWindowContentChanged(event);
1042 }
1043 for (final WebWindowListener listener : new ArrayList<>(webWindowListeners_)) {
1044 listener.webWindowContentChanged(event);
1045 }
1046 }
1047
1048 private void fireWindowOpened(final WebWindowEvent event) {
1049 if (currentWindowTracker_ != null) {
1050 currentWindowTracker_.webWindowOpened(event);
1051 }
1052 for (final WebWindowListener listener : new ArrayList<>(webWindowListeners_)) {
1053 listener.webWindowOpened(event);
1054 }
1055 }
1056
1057 private void fireWindowClosed(final WebWindowEvent event) {
1058 if (currentWindowTracker_ != null) {
1059 currentWindowTracker_.webWindowClosed(event);
1060 }
1061
1062 for (final WebWindowListener listener : new ArrayList<>(webWindowListeners_)) {
1063 listener.webWindowClosed(event);
1064 }
1065
1066
1067 if (currentWindowTracker_ != null) {
1068 currentWindowTracker_.afterWebWindowClosedListenersProcessed(event);
1069 }
1070 }
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080 public WebWindow openWindow(final URL url, final String windowName) {
1081 WebAssert.notNull("windowName", windowName);
1082 return openWindow(url, windowName, getCurrentWindow());
1083 }
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094 public WebWindow openWindow(final URL url, final String windowName, final WebWindow opener) {
1095 final WebWindow window = openTargetWindow(opener, windowName, TARGET_BLANK);
1096 if (url == null) {
1097 initializeEmptyWindow(window, window.getEnclosedPage());
1098 }
1099 else {
1100 try {
1101 final WebRequest request = new WebRequest(url, getBrowserVersion().getHtmlAcceptHeader(),
1102 getBrowserVersion().getAcceptEncodingHeader());
1103 request.setCharset(UTF_8);
1104
1105 final Page openerPage = opener.getEnclosedPage();
1106 if (openerPage != null && openerPage.getUrl() != null) {
1107 request.setRefererHeader(openerPage.getUrl());
1108 }
1109 getPage(window, request);
1110 }
1111 catch (final IOException e) {
1112 LOG.error("Error loading content into window", e);
1113 }
1114 }
1115 return window;
1116 }
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131 public WebWindow openTargetWindow(
1132 final WebWindow opener, final String windowName, final String defaultName) {
1133
1134 WebAssert.notNull("opener", opener);
1135 WebAssert.notNull("defaultName", defaultName);
1136
1137 String windowToOpen = windowName;
1138 if (windowToOpen == null || windowToOpen.isEmpty()) {
1139 windowToOpen = defaultName;
1140 }
1141
1142 WebWindow webWindow = resolveWindow(opener, windowToOpen);
1143
1144 if (webWindow == null) {
1145 if (TARGET_BLANK.equals(windowToOpen)) {
1146 windowToOpen = "";
1147 }
1148 webWindow = new TopLevelWindow(windowToOpen, this);
1149 }
1150
1151 if (webWindow instanceof TopLevelWindow && webWindow != opener.getTopWindow()) {
1152 ((TopLevelWindow) webWindow).setOpener(opener);
1153 }
1154
1155 return webWindow;
1156 }
1157
1158 private WebWindow resolveWindow(final WebWindow opener, final String name) {
1159 if (name == null || name.isEmpty() || TARGET_SELF.equals(name)) {
1160 return opener;
1161 }
1162
1163 if (TARGET_PARENT.equals(name)) {
1164 return opener.getParentWindow();
1165 }
1166
1167 if (TARGET_TOP.equals(name)) {
1168 return opener.getTopWindow();
1169 }
1170
1171 if (TARGET_BLANK.equals(name)) {
1172 return null;
1173 }
1174
1175
1176 WebWindow window = opener;
1177 while (true) {
1178 final Page page = window.getEnclosedPage();
1179 if (page != null && page.isHtmlPage()) {
1180 try {
1181 final FrameWindow frame = ((HtmlPage) page).getFrameByName(name);
1182 final HtmlUnitScriptable scriptable = frame.getFrameElement().getScriptableObject();
1183 if (scriptable instanceof HTMLIFrameElement) {
1184 ((HTMLIFrameElement) scriptable).onRefresh();
1185 }
1186 return frame;
1187 }
1188 catch (final ElementNotFoundException expected) {
1189
1190 }
1191 }
1192
1193 if (window == window.getParentWindow()) {
1194
1195 break;
1196 }
1197 window = window.getParentWindow();
1198 }
1199
1200 try {
1201 return getWebWindowByName(name);
1202 }
1203 catch (final WebWindowNotFoundException expected) {
1204
1205 }
1206 return null;
1207 }
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219 public DialogWindow openDialogWindow(final URL url, final WebWindow opener, final Object dialogArguments)
1220 throws IOException {
1221
1222 WebAssert.notNull("url", url);
1223 WebAssert.notNull("opener", opener);
1224
1225 final DialogWindow window = new DialogWindow(this, dialogArguments);
1226
1227 final HtmlPage openerPage = (HtmlPage) opener.getEnclosedPage();
1228 final WebRequest request = new WebRequest(url, getBrowserVersion().getHtmlAcceptHeader(),
1229 getBrowserVersion().getAcceptEncodingHeader());
1230 request.setCharset(UTF_8);
1231
1232 if (openerPage != null) {
1233 request.setRefererHeader(openerPage.getUrl());
1234 }
1235
1236 getPage(window, request);
1237
1238 return window;
1239 }
1240
1241
1242
1243
1244
1245
1246
1247 public void setPageCreator(final PageCreator pageCreator) {
1248 WebAssert.notNull("pageCreator", pageCreator);
1249 pageCreator_ = pageCreator;
1250 }
1251
1252
1253
1254
1255
1256
1257 public PageCreator getPageCreator() {
1258 return pageCreator_;
1259 }
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270 public WebWindow getWebWindowByName(final String name) throws WebWindowNotFoundException {
1271 WebAssert.notNull("name", name);
1272
1273 for (final WebWindow webWindow : windows_) {
1274 if (name.equals(webWindow.getName())) {
1275 return webWindow;
1276 }
1277 }
1278
1279 throw new WebWindowNotFoundException(name);
1280 }
1281
1282
1283
1284
1285
1286
1287
1288
1289 public void initialize(final WebWindow webWindow, final Page page) {
1290 WebAssert.notNull("webWindow", webWindow);
1291
1292 if (isJavaScriptEngineEnabled()) {
1293 scriptEngine_.initialize(webWindow, page);
1294 }
1295 }
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305 public void initializeEmptyWindow(final WebWindow webWindow, final Page page) {
1306 WebAssert.notNull("webWindow", webWindow);
1307
1308 if (isJavaScriptEngineEnabled()) {
1309 initialize(webWindow, page);
1310 ((Window) webWindow.getScriptableObject()).initialize();
1311 }
1312 }
1313
1314
1315
1316
1317
1318
1319
1320
1321 public void registerWebWindow(final WebWindow webWindow) {
1322 WebAssert.notNull("webWindow", webWindow);
1323 if (windows_.add(webWindow)) {
1324 fireWindowOpened(new WebWindowEvent(webWindow, WebWindowEvent.OPEN, webWindow.getEnclosedPage(), null));
1325 }
1326
1327 jobManagers_.add(new WeakReference<>(webWindow.getJobManager()));
1328 }
1329
1330
1331
1332
1333
1334
1335
1336
1337 public void deregisterWebWindow(final WebWindow webWindow) {
1338 WebAssert.notNull("webWindow", webWindow);
1339 if (windows_.remove(webWindow)) {
1340 fireWindowClosed(new WebWindowEvent(webWindow, WebWindowEvent.CLOSE, webWindow.getEnclosedPage(), null));
1341 }
1342 }
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356 public static URL expandUrl(final URL baseUrl, final String relativeUrl) throws MalformedURLException {
1357 final String newUrl = UrlUtils.resolveUrl(baseUrl, relativeUrl);
1358 return UrlUtils.toUrlUnsafe(newUrl);
1359 }
1360
1361 private WebResponse makeWebResponseForDataUrl(final WebRequest webRequest) throws IOException {
1362 final URL url = webRequest.getUrl();
1363 final DataURLConnection connection;
1364 connection = new DataURLConnection(url);
1365
1366 final List<NameValuePair> responseHeaders = new ArrayList<>();
1367 responseHeaders.add(new NameValuePair(HttpHeader.CONTENT_TYPE_LC,
1368 connection.getMediaType() + ";charset=" + connection.getCharset()));
1369
1370 try (InputStream is = connection.getInputStream()) {
1371 final DownloadedContent downloadedContent =
1372 HttpWebConnection.downloadContent(is,
1373 getOptions().getMaxInMemory(),
1374 getOptions().getTempFileDirectory());
1375 final WebResponseData data = new WebResponseData(downloadedContent, 200, "OK", responseHeaders);
1376 return new WebResponse(data, url, webRequest.getHttpMethod(), 0);
1377 }
1378 }
1379
1380 private static WebResponse makeWebResponseForAboutUrl(final WebRequest webRequest) throws MalformedURLException {
1381 final URL url = webRequest.getUrl();
1382 final String urlString = url.toExternalForm();
1383 if (UrlUtils.ABOUT_BLANK.equalsIgnoreCase(urlString)) {
1384 return new StringWebResponse("", UrlUtils.URL_ABOUT_BLANK);
1385 }
1386
1387 final String urlWithoutQuery = org.apache.commons.lang3.StringUtils.substringBefore(urlString, "?");
1388 if (!"blank".equalsIgnoreCase(org.apache.commons.lang3.StringUtils
1389 .substringAfter(urlWithoutQuery, UrlUtils.ABOUT_SCHEME))) {
1390 throw new MalformedURLException(url + " is not supported, only about:blank is supported at the moment.");
1391 }
1392 return new StringWebResponse("", url);
1393 }
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403 private WebResponse makeWebResponseForFileUrl(final WebRequest webRequest) throws IOException {
1404 URL cleanUrl = webRequest.getUrl();
1405 if (cleanUrl.getQuery() != null) {
1406
1407 cleanUrl = UrlUtils.getUrlWithNewQuery(cleanUrl, null);
1408 }
1409 if (cleanUrl.getRef() != null) {
1410
1411 cleanUrl = UrlUtils.getUrlWithNewRef(cleanUrl, null);
1412 }
1413
1414 final WebResponse fromCache = getCache().getCachedResponse(webRequest);
1415 if (fromCache != null) {
1416 return new WebResponseFromCache(fromCache, webRequest);
1417 }
1418
1419 String fileUrl = cleanUrl.toExternalForm();
1420 fileUrl = URLDecoder.decode(fileUrl, UTF_8.name());
1421 final File file = new File(fileUrl.substring(5));
1422 if (!file.exists()) {
1423
1424 final List<NameValuePair> compiledHeaders = new ArrayList<>();
1425 compiledHeaders.add(new NameValuePair(HttpHeader.CONTENT_TYPE, MimeType.TEXT_HTML));
1426 final WebResponseData responseData =
1427 new WebResponseData(
1428 StringUtils
1429 .toByteArray("File: " + file.getAbsolutePath(), UTF_8),
1430 404, "Not Found", compiledHeaders);
1431 return new WebResponse(responseData, webRequest, 0);
1432 }
1433
1434 final String contentType = guessContentType(file);
1435
1436 final DownloadedContent content = new DownloadedContent.OnFile(file, false);
1437 final List<NameValuePair> compiledHeaders = new ArrayList<>();
1438 compiledHeaders.add(new NameValuePair(HttpHeader.CONTENT_TYPE, contentType));
1439 compiledHeaders.add(new NameValuePair(HttpHeader.LAST_MODIFIED,
1440 HttpUtils.formatDate(new Date(file.lastModified()))));
1441 final WebResponseData responseData = new WebResponseData(content, 200, "OK", compiledHeaders);
1442 final WebResponse webResponse = new WebResponse(responseData, webRequest, 0);
1443 getCache().cacheIfPossible(webRequest, webResponse, null);
1444 return webResponse;
1445 }
1446
1447 private WebResponse makeWebResponseForBlobUrl(final WebRequest webRequest) {
1448 final Window window = getCurrentWindow().getScriptableObject();
1449 final Blob fileOrBlob = window.getDocument().resolveBlobUrl(webRequest.getUrl().toString());
1450 if (fileOrBlob == null) {
1451 throw JavaScriptEngine.typeError("Cannot load data from " + webRequest.getUrl());
1452 }
1453
1454 final List<NameValuePair> headers = new ArrayList<>();
1455 final String type = fileOrBlob.getType();
1456 if (!StringUtils.isEmptyOrNull(type)) {
1457 headers.add(new NameValuePair(HttpHeader.CONTENT_TYPE, fileOrBlob.getType()));
1458 }
1459 if (fileOrBlob instanceof org.htmlunit.javascript.host.file.File) {
1460 final org.htmlunit.javascript.host.file.File file = (org.htmlunit.javascript.host.file.File) fileOrBlob;
1461 final String fileName = file.getName();
1462 if (!StringUtils.isEmptyOrNull(fileName)) {
1463
1464 headers.add(new NameValuePair(HttpHeader.CONTENT_DISPOSITION, "inline; filename=\"" + fileName + "\""));
1465 }
1466 }
1467
1468 final DownloadedContent content = new DownloadedContent.InMemory(fileOrBlob.getBytes());
1469 final WebResponseData responseData = new WebResponseData(content, 200, "OK", headers);
1470 return new WebResponse(responseData, webRequest, 0);
1471 }
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481 public String guessContentType(final File file) {
1482 final String fileName = file.getName();
1483 final String fileNameLC = fileName.toLowerCase(Locale.ROOT);
1484 if (fileNameLC.endsWith(".xhtml")) {
1485
1486 return MimeType.APPLICATION_XHTML;
1487 }
1488
1489
1490 if (fileNameLC.endsWith(".js")) {
1491 return MimeType.TEXT_JAVASCRIPT;
1492 }
1493
1494 if (fileNameLC.endsWith(".css")) {
1495 return MimeType.TEXT_CSS;
1496 }
1497
1498 String contentType = null;
1499 if (!fileNameLC.endsWith(".php")) {
1500 contentType = URLConnection.guessContentTypeFromName(fileName);
1501 }
1502 if (contentType == null) {
1503 try (InputStream inputStream = new BufferedInputStream(Files.newInputStream(file.toPath()))) {
1504 contentType = URLConnection.guessContentTypeFromStream(inputStream);
1505 }
1506 catch (final IOException ignored) {
1507
1508 }
1509 }
1510 if (contentType == null) {
1511 contentType = MimeType.APPLICATION_OCTET_STREAM;
1512 }
1513 return contentType;
1514 }
1515
1516 private WebResponse makeWebResponseForJavaScriptUrl(final WebWindow webWindow, final URL url,
1517 final Charset charset) throws FailingHttpStatusCodeException, IOException {
1518
1519 HtmlPage page = null;
1520 if (webWindow instanceof FrameWindow) {
1521 final FrameWindow frameWindow = (FrameWindow) webWindow;
1522 page = (HtmlPage) frameWindow.getEnclosedPage();
1523 }
1524 else {
1525 final Page currentPage = webWindow.getEnclosedPage();
1526 if (currentPage instanceof HtmlPage) {
1527 page = (HtmlPage) currentPage;
1528 }
1529 }
1530
1531 if (page == null) {
1532 page = getPage(webWindow, WebRequest.newAboutBlankRequest());
1533 }
1534 final ScriptResult r = page.executeJavaScript(url.toExternalForm(), "JavaScript URL", 1);
1535 if (r.getJavaScriptResult() == null || ScriptResult.isUndefined(r)) {
1536
1537 return webWindow.getEnclosedPage().getWebResponse();
1538 }
1539
1540 final String contentString = r.getJavaScriptResult().toString();
1541 final StringWebResponse response = new StringWebResponse(contentString, charset, url);
1542 response.setFromJavascript(true);
1543 return response;
1544 }
1545
1546
1547
1548
1549
1550
1551
1552 public WebResponse loadWebResponse(final WebRequest webRequest) throws IOException {
1553 final String protocol = webRequest.getUrl().getProtocol();
1554 switch (protocol) {
1555 case UrlUtils.ABOUT:
1556 return makeWebResponseForAboutUrl(webRequest);
1557
1558 case "file":
1559 return makeWebResponseForFileUrl(webRequest);
1560
1561 case "data":
1562 return makeWebResponseForDataUrl(webRequest);
1563
1564 case "blob":
1565 return makeWebResponseForBlobUrl(webRequest);
1566
1567 case "http":
1568 case "https":
1569 return loadWebResponseFromWebConnection(webRequest, ALLOWED_REDIRECTIONS_SAME_URL);
1570
1571 default:
1572 throw new IOException("Unsupported protocol '" + protocol + "'");
1573 }
1574 }
1575
1576
1577
1578
1579
1580
1581
1582
1583 private WebResponse loadWebResponseFromWebConnection(final WebRequest webRequest,
1584 final int allowedRedirects) throws IOException {
1585
1586 URL url = webRequest.getUrl();
1587 final HttpMethod method = webRequest.getHttpMethod();
1588 final List<NameValuePair> parameters = webRequest.getRequestParameters();
1589
1590 WebAssert.notNull("url", url);
1591 WebAssert.notNull("method", method);
1592 WebAssert.notNull("parameters", parameters);
1593
1594 url = UrlUtils.encodeUrl(url, webRequest.getCharset());
1595 webRequest.setUrl(url);
1596
1597 if (LOG.isDebugEnabled()) {
1598 LOG.debug("Load response for " + method + " " + url.toExternalForm());
1599 }
1600
1601
1602 if (webRequest.getProxyHost() == null) {
1603 final ProxyConfig proxyConfig = getOptions().getProxyConfig();
1604 if (proxyConfig.getProxyAutoConfigUrl() != null) {
1605 if (!UrlUtils.sameFile(new URL(proxyConfig.getProxyAutoConfigUrl()), url)) {
1606 String content = proxyConfig.getProxyAutoConfigContent();
1607 if (content == null) {
1608 content = getPage(proxyConfig.getProxyAutoConfigUrl())
1609 .getWebResponse().getContentAsString();
1610 proxyConfig.setProxyAutoConfigContent(content);
1611 }
1612 final String allValue = JavaScriptEngine.evaluateProxyAutoConfig(getBrowserVersion(), content, url);
1613 if (LOG.isDebugEnabled()) {
1614 LOG.debug("Proxy Auto-Config: value '" + allValue + "' for URL " + url);
1615 }
1616 String value = allValue.split(";")[0].trim();
1617 if (value.startsWith("PROXY")) {
1618 value = value.substring(6);
1619 final int colonIndex = value.indexOf(':');
1620 webRequest.setSocksProxy(false);
1621 webRequest.setProxyHost(value.substring(0, colonIndex));
1622 webRequest.setProxyPort(Integer.parseInt(value.substring(colonIndex + 1)));
1623 }
1624 else if (value.startsWith("SOCKS")) {
1625 value = value.substring(6);
1626 final int colonIndex = value.indexOf(':');
1627 webRequest.setSocksProxy(true);
1628 webRequest.setProxyHost(value.substring(0, colonIndex));
1629 webRequest.setProxyPort(Integer.parseInt(value.substring(colonIndex + 1)));
1630 }
1631 }
1632 }
1633
1634 else if (!proxyConfig.shouldBypassProxy(webRequest.getUrl().getHost())) {
1635 webRequest.setProxyHost(proxyConfig.getProxyHost());
1636 webRequest.setProxyPort(proxyConfig.getProxyPort());
1637 webRequest.setProxyScheme(proxyConfig.getProxyScheme());
1638 webRequest.setSocksProxy(proxyConfig.isSocksProxy());
1639 }
1640 }
1641
1642
1643 addDefaultHeaders(webRequest);
1644
1645
1646 final WebResponse fromCache = getCache().getCachedResponse(webRequest);
1647 final WebResponse webResponse = getWebResponseOrUseCached(webRequest, fromCache);
1648
1649
1650 final int status = webResponse.getStatusCode();
1651 if (status == HttpStatus.USE_PROXY_305) {
1652 getIncorrectnessListener().notify("Ignoring HTTP status code [305] 'Use Proxy'", this);
1653 }
1654 else if (status >= HttpStatus.MOVED_PERMANENTLY_301
1655 && status <= HttpStatus.PERMANENT_REDIRECT_308
1656 && status != HttpStatus.NOT_MODIFIED_304
1657 && getOptions().isRedirectEnabled()) {
1658
1659 final URL newUrl;
1660 String locationString = null;
1661 try {
1662 locationString = webResponse.getResponseHeaderValue("Location");
1663 if (locationString == null) {
1664 return webResponse;
1665 }
1666 locationString = new String(locationString.getBytes(ISO_8859_1), UTF_8);
1667 newUrl = expandUrl(url, locationString);
1668 }
1669 catch (final MalformedURLException e) {
1670 getIncorrectnessListener().notify("Got a redirect status code [" + status + " "
1671 + webResponse.getStatusMessage()
1672 + "] but the location is not a valid URL [" + locationString
1673 + "]. Skipping redirection processing.", this);
1674 return webResponse;
1675 }
1676
1677 if (LOG.isDebugEnabled()) {
1678 LOG.debug("Got a redirect status code [" + status + "] new location = [" + locationString + "]");
1679 }
1680
1681 if (allowedRedirects == 0) {
1682 throw new FailingHttpStatusCodeException("Too many redirects for "
1683 + webResponse.getWebRequest().getUrl(), webResponse);
1684 }
1685
1686 if (status == HttpStatus.MOVED_PERMANENTLY_301
1687 || status == HttpStatus.FOUND_302
1688 || status == HttpStatus.SEE_OTHER_303) {
1689 final WebRequest wrs = new WebRequest(newUrl, HttpMethod.GET);
1690 wrs.setCharset(webRequest.getCharset());
1691
1692 if (HttpMethod.HEAD == webRequest.getHttpMethod()) {
1693 wrs.setHttpMethod(HttpMethod.HEAD);
1694 }
1695 for (final Map.Entry<String, String> entry : webRequest.getAdditionalHeaders().entrySet()) {
1696 wrs.setAdditionalHeader(entry.getKey(), entry.getValue());
1697 }
1698 return loadWebResponseFromWebConnection(wrs, allowedRedirects - 1);
1699 }
1700 else if (status == HttpStatus.TEMPORARY_REDIRECT_307
1701 || status == HttpStatus.PERMANENT_REDIRECT_308) {
1702
1703
1704
1705 final WebRequest wrs = new WebRequest(newUrl, webRequest.getHttpMethod());
1706 wrs.setCharset(webRequest.getCharset());
1707 if (webRequest.getRequestBody() != null) {
1708 if (HttpMethod.POST == webRequest.getHttpMethod()
1709 || HttpMethod.PUT == webRequest.getHttpMethod()
1710 || HttpMethod.PATCH == webRequest.getHttpMethod()) {
1711 wrs.setRequestBody(webRequest.getRequestBody());
1712 wrs.setEncodingType(webRequest.getEncodingType());
1713 }
1714 }
1715 else {
1716 wrs.setRequestParameters(parameters);
1717 }
1718
1719 for (final Map.Entry<String, String> entry : webRequest.getAdditionalHeaders().entrySet()) {
1720 wrs.setAdditionalHeader(entry.getKey(), entry.getValue());
1721 }
1722
1723 return loadWebResponseFromWebConnection(wrs, allowedRedirects - 1);
1724 }
1725 }
1726
1727 if (fromCache == null) {
1728 getCache().cacheIfPossible(webRequest, webResponse, null);
1729 }
1730 return webResponse;
1731 }
1732
1733
1734
1735
1736
1737
1738
1739 private WebResponse getWebResponseOrUseCached(
1740 final WebRequest webRequest, final WebResponse cached) throws IOException {
1741 if (cached == null) {
1742 return getWebConnection().getResponse(webRequest);
1743 }
1744
1745 if (!HeaderUtils.containsNoCache(cached)) {
1746 return new WebResponseFromCache(cached, webRequest);
1747 }
1748
1749
1750 if (HeaderUtils.containsETag(cached)) {
1751 webRequest.setAdditionalHeader(HttpHeader.IF_NONE_MATCH, cached.getResponseHeaderValue(HttpHeader.ETAG));
1752 }
1753 if (HeaderUtils.containsLastModified(cached)) {
1754 webRequest.setAdditionalHeader(HttpHeader.IF_MODIFIED_SINCE,
1755 cached.getResponseHeaderValue(HttpHeader.LAST_MODIFIED));
1756 }
1757
1758 final WebResponse webResponse = getWebConnection().getResponse(webRequest);
1759
1760 if (webResponse.getStatusCode() >= HttpStatus.INTERNAL_SERVER_ERROR_500) {
1761 return new WebResponseFromCache(cached, webRequest);
1762 }
1763
1764 if (webResponse.getStatusCode() == HttpStatus.NOT_MODIFIED_304) {
1765 final Map<String, NameValuePair> header2NameValuePair = new LinkedHashMap<>();
1766 for (final NameValuePair pair : cached.getResponseHeaders()) {
1767 header2NameValuePair.put(pair.getName(), pair);
1768 }
1769 for (final NameValuePair pair : webResponse.getResponseHeaders()) {
1770 if (preferHeaderFrom304Response(pair.getName())) {
1771 header2NameValuePair.put(pair.getName(), pair);
1772 }
1773 }
1774
1775
1776
1777 final WebResponse updatedCached =
1778 new WebResponseFromCache(cached, new ArrayList<>(header2NameValuePair.values()), webRequest);
1779 getCache().cacheIfPossible(webRequest, updatedCached, null);
1780 return updatedCached;
1781 }
1782
1783 getCache().cacheIfPossible(webRequest, webResponse, null);
1784 return webResponse;
1785 }
1786
1787
1788
1789
1790
1791 private static boolean preferHeaderFrom304Response(final String name) {
1792 final String lcName = name.toLowerCase(Locale.ROOT);
1793 for (final String header : DISCARDING_304_RESPONSE_HEADER_NAMES) {
1794 if (lcName.equals(header)) {
1795 return false;
1796 }
1797 }
1798 for (final String prefix : DISCARDING_304_HEADER_PREFIXES) {
1799 if (lcName.startsWith(prefix)) {
1800 return false;
1801 }
1802 }
1803 return true;
1804 }
1805
1806
1807
1808
1809
1810 private void addDefaultHeaders(final WebRequest wrs) {
1811
1812 requestHeaders_.forEach((name, value) -> {
1813 if (!wrs.isAdditionalHeader(name)) {
1814 wrs.setAdditionalHeader(name, value);
1815 }
1816 });
1817
1818
1819 if (!wrs.isAdditionalHeader(HttpHeader.ACCEPT_LANGUAGE)) {
1820 wrs.setAdditionalHeader(HttpHeader.ACCEPT_LANGUAGE, getBrowserVersion().getAcceptLanguageHeader());
1821 }
1822
1823 if (!wrs.isAdditionalHeader(HttpHeader.SEC_FETCH_DEST)) {
1824 wrs.setAdditionalHeader(HttpHeader.SEC_FETCH_DEST, "document");
1825 }
1826 if (!wrs.isAdditionalHeader(HttpHeader.SEC_FETCH_MODE)) {
1827 wrs.setAdditionalHeader(HttpHeader.SEC_FETCH_MODE, "navigate");
1828 }
1829 if (!wrs.isAdditionalHeader(HttpHeader.SEC_FETCH_SITE)) {
1830 wrs.setAdditionalHeader(HttpHeader.SEC_FETCH_SITE, "same-origin");
1831 }
1832 if (!wrs.isAdditionalHeader(HttpHeader.SEC_FETCH_USER)) {
1833 wrs.setAdditionalHeader(HttpHeader.SEC_FETCH_USER, "?1");
1834 }
1835 if (getBrowserVersion().hasFeature(HTTP_HEADER_PRIORITY)
1836 && !wrs.isAdditionalHeader(HttpHeader.PRIORITY)) {
1837 wrs.setAdditionalHeader(HttpHeader.PRIORITY, "u=0, i");
1838 }
1839
1840 if (getBrowserVersion().hasFeature(HTTP_HEADER_CH_UA)
1841 && !wrs.isAdditionalHeader(HttpHeader.SEC_CH_UA)) {
1842 wrs.setAdditionalHeader(HttpHeader.SEC_CH_UA, getBrowserVersion().getSecClientHintUserAgentHeader());
1843 }
1844 if (getBrowserVersion().hasFeature(HTTP_HEADER_CH_UA)
1845 && !wrs.isAdditionalHeader(HttpHeader.SEC_CH_UA_MOBILE)) {
1846 wrs.setAdditionalHeader(HttpHeader.SEC_CH_UA_MOBILE, "?0");
1847 }
1848 if (getBrowserVersion().hasFeature(HTTP_HEADER_CH_UA)
1849 && !wrs.isAdditionalHeader(HttpHeader.SEC_CH_UA_PLATFORM)) {
1850 wrs.setAdditionalHeader(HttpHeader.SEC_CH_UA_PLATFORM,
1851 getBrowserVersion().getSecClientHintUserAgentPlatformHeader());
1852 }
1853
1854 if (!wrs.isAdditionalHeader(HttpHeader.UPGRADE_INSECURE_REQUESTS)) {
1855 wrs.setAdditionalHeader(HttpHeader.UPGRADE_INSECURE_REQUESTS, "1");
1856 }
1857 }
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869 public List<WebWindow> getWebWindows() {
1870 return Collections.unmodifiableList(new ArrayList<>(windows_));
1871 }
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883 public boolean containsWebWindow(final WebWindow webWindow) {
1884 return windows_.contains(webWindow);
1885 }
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897 public List<TopLevelWindow> getTopLevelWindows() {
1898 return Collections.unmodifiableList(new ArrayList<>(topLevelWindows_));
1899 }
1900
1901
1902
1903
1904
1905
1906 public void setRefreshHandler(final RefreshHandler handler) {
1907 if (handler == null) {
1908 refreshHandler_ = new NiceRefreshHandler(2);
1909 }
1910 else {
1911 refreshHandler_ = handler;
1912 }
1913 }
1914
1915
1916
1917
1918
1919
1920 public RefreshHandler getRefreshHandler() {
1921 return refreshHandler_;
1922 }
1923
1924
1925
1926
1927
1928 public void setScriptPreProcessor(final ScriptPreProcessor scriptPreProcessor) {
1929 scriptPreProcessor_ = scriptPreProcessor;
1930 }
1931
1932
1933
1934
1935
1936 public ScriptPreProcessor getScriptPreProcessor() {
1937 return scriptPreProcessor_;
1938 }
1939
1940
1941
1942
1943
1944 public void setHTMLParserListener(final HTMLParserListener listener) {
1945 htmlParserListener_ = listener;
1946 }
1947
1948
1949
1950
1951
1952 public HTMLParserListener getHTMLParserListener() {
1953 return htmlParserListener_;
1954 }
1955
1956
1957
1958
1959
1960
1961
1962 public CSSErrorHandler getCssErrorHandler() {
1963 return cssErrorHandler_;
1964 }
1965
1966
1967
1968
1969
1970
1971
1972 public void setCssErrorHandler(final CSSErrorHandler cssErrorHandler) {
1973 WebAssert.notNull("cssErrorHandler", cssErrorHandler);
1974 cssErrorHandler_ = cssErrorHandler;
1975 }
1976
1977
1978
1979
1980
1981
1982
1983 public void setJavaScriptTimeout(final long timeout) {
1984 scriptEngine_.setJavaScriptTimeout(timeout);
1985 }
1986
1987
1988
1989
1990
1991
1992
1993 public long getJavaScriptTimeout() {
1994 return scriptEngine_.getJavaScriptTimeout();
1995 }
1996
1997
1998
1999
2000
2001
2002
2003 public IncorrectnessListener getIncorrectnessListener() {
2004 return incorrectnessListener_;
2005 }
2006
2007
2008
2009
2010
2011 public void setIncorrectnessListener(final IncorrectnessListener listener) {
2012 if (listener == null) {
2013 throw new IllegalArgumentException("Null is not a valid IncorrectnessListener");
2014 }
2015 incorrectnessListener_ = listener;
2016 }
2017
2018
2019
2020
2021
2022 public WebConsole getWebConsole() {
2023 if (webConsole_ == null) {
2024 webConsole_ = new WebConsole();
2025 }
2026 return webConsole_;
2027 }
2028
2029
2030
2031
2032
2033 public AjaxController getAjaxController() {
2034 return ajaxController_;
2035 }
2036
2037
2038
2039
2040
2041 public void setAjaxController(final AjaxController newValue) {
2042 if (newValue == null) {
2043 throw new IllegalArgumentException("Null is not a valid AjaxController");
2044 }
2045 ajaxController_ = newValue;
2046 }
2047
2048
2049
2050
2051
2052 public void setAttachmentHandler(final AttachmentHandler handler) {
2053 attachmentHandler_ = handler;
2054 }
2055
2056
2057
2058
2059
2060 public AttachmentHandler getAttachmentHandler() {
2061 return attachmentHandler_;
2062 }
2063
2064
2065
2066
2067
2068 public void setWebStartHandler(final WebStartHandler handler) {
2069 webStartHandler_ = handler;
2070 }
2071
2072
2073
2074
2075
2076 public WebStartHandler getWebStartHandler() {
2077 return webStartHandler_;
2078 }
2079
2080
2081
2082
2083
2084 public ClipboardHandler getClipboardHandler() {
2085 return clipboardHandler_;
2086 }
2087
2088
2089
2090
2091
2092 public void setClipboardHandler(final ClipboardHandler handler) {
2093 clipboardHandler_ = handler;
2094 }
2095
2096
2097
2098
2099
2100
2101 public PrintHandler getPrintHandler() {
2102 return printHandler_;
2103 }
2104
2105
2106
2107
2108
2109
2110
2111
2112 public void setPrintHandler(final PrintHandler handler) {
2113 printHandler_ = handler;
2114 }
2115
2116
2117
2118
2119
2120 public FrameContentHandler getFrameContentHandler() {
2121 return frameContentHandler_;
2122 }
2123
2124
2125
2126
2127
2128 public void setFrameContentHandler(final FrameContentHandler handler) {
2129 frameContentHandler_ = handler;
2130 }
2131
2132
2133
2134
2135
2136 public void setOnbeforeunloadHandler(final OnbeforeunloadHandler onbeforeunloadHandler) {
2137 onbeforeunloadHandler_ = onbeforeunloadHandler;
2138 }
2139
2140
2141
2142
2143
2144 public OnbeforeunloadHandler getOnbeforeunloadHandler() {
2145 return onbeforeunloadHandler_;
2146 }
2147
2148
2149
2150
2151
2152 public Cache getCache() {
2153 return cache_;
2154 }
2155
2156
2157
2158
2159
2160 public void setCache(final Cache cache) {
2161 if (cache == null) {
2162 throw new IllegalArgumentException("cache should not be null!");
2163 }
2164 cache_ = cache;
2165 }
2166
2167
2168
2169
2170 private static final class CurrentWindowTracker implements WebWindowListener, Serializable {
2171 private final WebClient webClient_;
2172 private final boolean ensureOneTopLevelWindow_;
2173
2174 CurrentWindowTracker(final WebClient webClient, final boolean ensureOneTopLevelWindow) {
2175 webClient_ = webClient;
2176 ensureOneTopLevelWindow_ = ensureOneTopLevelWindow;
2177 }
2178
2179
2180
2181
2182 @Override
2183 public void webWindowClosed(final WebWindowEvent event) {
2184 final WebWindow window = event.getWebWindow();
2185 if (window instanceof TopLevelWindow) {
2186 webClient_.topLevelWindows_.remove(window);
2187 if (window == webClient_.getCurrentWindow()) {
2188 if (!webClient_.topLevelWindows_.isEmpty()) {
2189
2190 webClient_.setCurrentWindow(
2191 webClient_.topLevelWindows_.get(webClient_.topLevelWindows_.size() - 1));
2192 }
2193 }
2194 }
2195 else if (window == webClient_.getCurrentWindow()) {
2196
2197 if (webClient_.topLevelWindows_.isEmpty()) {
2198 webClient_.setCurrentWindow(null);
2199 }
2200 else {
2201 webClient_.setCurrentWindow(
2202 webClient_.topLevelWindows_.get(webClient_.topLevelWindows_.size() - 1));
2203 }
2204 }
2205 }
2206
2207
2208
2209
2210 public void afterWebWindowClosedListenersProcessed(final WebWindowEvent event) {
2211 if (!ensureOneTopLevelWindow_) {
2212 return;
2213 }
2214
2215 if (webClient_.topLevelWindows_.isEmpty()) {
2216
2217 final TopLevelWindow newWindow = new TopLevelWindow("", webClient_);
2218 webClient_.setCurrentWindow(newWindow);
2219 }
2220 }
2221
2222
2223
2224
2225 @Override
2226 public void webWindowContentChanged(final WebWindowEvent event) {
2227 final WebWindow window = event.getWebWindow();
2228 boolean use = false;
2229 if (window instanceof DialogWindow) {
2230 use = true;
2231 }
2232 else if (window instanceof TopLevelWindow) {
2233 use = event.getOldPage() == null;
2234 }
2235 else if (window instanceof FrameWindow) {
2236 final FrameWindow fw = (FrameWindow) window;
2237 final String enclosingPageState = fw.getEnclosingPage().getDocumentElement().getReadyState();
2238 final URL frameUrl = fw.getEnclosedPage().getUrl();
2239 if (!DomNode.READY_STATE_COMPLETE.equals(enclosingPageState) || frameUrl == UrlUtils.URL_ABOUT_BLANK) {
2240 return;
2241 }
2242
2243
2244 final BaseFrameElement frameElement = fw.getFrameElement();
2245 if (webClient_.isJavaScriptEnabled() && frameElement.isDisplayed()) {
2246 final ComputedCssStyleDeclaration style = fw.getComputedStyle(frameElement, null);
2247 use = style.getCalculatedWidth(false, false) != 0
2248 && style.getCalculatedHeight(false, false) != 0;
2249 }
2250 }
2251 if (use) {
2252 webClient_.setCurrentWindow(window);
2253 }
2254 }
2255
2256
2257
2258
2259 @Override
2260 public void webWindowOpened(final WebWindowEvent event) {
2261 final WebWindow window = event.getWebWindow();
2262 if (window instanceof TopLevelWindow) {
2263 final TopLevelWindow tlw = (TopLevelWindow) window;
2264 webClient_.topLevelWindows_.add(tlw);
2265 }
2266
2267 }
2268 }
2269
2270
2271
2272
2273
2274
2275
2276
2277 @Override
2278 public void close() {
2279
2280 if (scriptEngine_ != null) {
2281 scriptEngine_.prepareShutdown();
2282 }
2283
2284
2285 currentWindowTracker_ = new CurrentWindowTracker(this, false);
2286
2287
2288
2289 List<WebWindow> windows = new ArrayList<>(windows_);
2290 for (final WebWindow window : windows) {
2291 if (window instanceof TopLevelWindow) {
2292 final TopLevelWindow topLevelWindow = (TopLevelWindow) window;
2293
2294 try {
2295 topLevelWindow.close(true);
2296 }
2297 catch (final Exception e) {
2298 LOG.error("Exception while closing a TopLevelWindow", e);
2299 }
2300 }
2301 else if (window instanceof DialogWindow) {
2302 final DialogWindow dialogWindow = (DialogWindow) window;
2303
2304 try {
2305 dialogWindow.close();
2306 }
2307 catch (final Exception e) {
2308 LOG.error("Exception while closing a DialogWindow", e);
2309 }
2310 }
2311 }
2312
2313
2314
2315 windows = new ArrayList<>(windows_);
2316 for (final WebWindow window : windows) {
2317 if (window instanceof TopLevelWindow) {
2318 final TopLevelWindow topLevelWindow = (TopLevelWindow) window;
2319
2320 try {
2321 topLevelWindow.close(true);
2322 }
2323 catch (final Exception e) {
2324 LOG.error("Exception while closing a TopLevelWindow", e);
2325 }
2326 }
2327 else if (window instanceof DialogWindow) {
2328 final DialogWindow dialogWindow = (DialogWindow) window;
2329
2330 try {
2331 dialogWindow.close();
2332 }
2333 catch (final Exception e) {
2334 LOG.error("Exception while closing a DialogWindow", e);
2335 }
2336 }
2337 }
2338
2339
2340 if (!topLevelWindows_.isEmpty()) {
2341 LOG.error("Sill " + topLevelWindows_.size() + " top level windows are open. Please report this error!");
2342 topLevelWindows_.clear();
2343 }
2344
2345 if (!windows_.isEmpty()) {
2346 LOG.error("Sill " + windows_.size() + " windows are open. Please report this error!");
2347 windows_.clear();
2348 }
2349 currentWindow_ = null;
2350
2351 ThreadDeath toThrow = null;
2352 if (scriptEngine_ != null) {
2353 try {
2354 scriptEngine_.shutdown();
2355 }
2356 catch (final ThreadDeath ex) {
2357
2358 toThrow = ex;
2359 }
2360 catch (final Exception e) {
2361 LOG.error("Exception while shutdown the scriptEngine", e);
2362 }
2363 }
2364 scriptEngine_ = null;
2365
2366 if (webConnection_ != null) {
2367 try {
2368 webConnection_.close();
2369 }
2370 catch (final Exception e) {
2371 LOG.error("Exception while closing the connection", e);
2372 }
2373 }
2374 webConnection_ = null;
2375
2376 synchronized (this) {
2377 if (executor_ != null) {
2378 try {
2379 executor_.shutdownNow();
2380 }
2381 catch (final Exception e) {
2382 LOG.error("Exception while shutdown the executor service", e);
2383 }
2384 }
2385 }
2386 executor_ = null;
2387
2388 cache_.clear();
2389 if (toThrow != null) {
2390 throw toThrow;
2391 }
2392 }
2393
2394
2395
2396
2397
2398
2399
2400
2401 public void reset() {
2402 close();
2403
2404
2405 webConnection_ = new HttpWebConnection(this);
2406 if (javaScriptEngineEnabled_) {
2407 scriptEngine_ = new JavaScriptEngine(this);
2408 }
2409
2410
2411 currentWindowTracker_ = new CurrentWindowTracker(this, true);
2412 currentWindow_ = new TopLevelWindow("", this);
2413 }
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457 public int waitForBackgroundJavaScript(final long timeoutMillis) {
2458 int count = 0;
2459 final long endTime = System.currentTimeMillis() + timeoutMillis;
2460 for (Iterator<WeakReference<JavaScriptJobManager>> i = jobManagers_.iterator(); i.hasNext();) {
2461 final JavaScriptJobManager jobManager;
2462 final WeakReference<JavaScriptJobManager> reference;
2463 try {
2464 reference = i.next();
2465 jobManager = reference.get();
2466 if (jobManager == null) {
2467 i.remove();
2468 continue;
2469 }
2470 }
2471 catch (final ConcurrentModificationException e) {
2472 i = jobManagers_.iterator();
2473 count = 0;
2474 continue;
2475 }
2476
2477 final long newTimeout = endTime - System.currentTimeMillis();
2478 count += jobManager.waitForJobs(newTimeout);
2479 }
2480 if (count != getAggregateJobCount()) {
2481 final long newTimeout = endTime - System.currentTimeMillis();
2482 return waitForBackgroundJavaScript(newTimeout);
2483 }
2484 return count;
2485 }
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540 public int waitForBackgroundJavaScriptStartingBefore(final long delayMillis) {
2541 return waitForBackgroundJavaScriptStartingBefore(delayMillis, -1);
2542 }
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606 public int waitForBackgroundJavaScriptStartingBefore(final long delayMillis, final long timeoutMillis) {
2607 int count = 0;
2608 long now = System.currentTimeMillis();
2609 final long endTime = now + delayMillis;
2610 long endTimeout = now + timeoutMillis;
2611 if (timeoutMillis < 0 || timeoutMillis < delayMillis) {
2612 endTimeout = -1;
2613 }
2614
2615 for (Iterator<WeakReference<JavaScriptJobManager>> i = jobManagers_.iterator(); i.hasNext();) {
2616 final JavaScriptJobManager jobManager;
2617 final WeakReference<JavaScriptJobManager> reference;
2618 try {
2619 reference = i.next();
2620 jobManager = reference.get();
2621 if (jobManager == null) {
2622 i.remove();
2623 continue;
2624 }
2625 }
2626 catch (final ConcurrentModificationException e) {
2627 i = jobManagers_.iterator();
2628 count = 0;
2629 continue;
2630 }
2631 now = System.currentTimeMillis();
2632 final long newDelay = endTime - now;
2633 final long newTimeout = (endTimeout == -1) ? -1 : endTimeout - now;
2634 count += jobManager.waitForJobsStartingBefore(newDelay, newTimeout);
2635 }
2636 if (count != getAggregateJobCount()) {
2637 now = System.currentTimeMillis();
2638 final long newDelay = endTime - now;
2639 final long newTimeout = (endTimeout == -1) ? -1 : endTimeout - now;
2640 return waitForBackgroundJavaScriptStartingBefore(newDelay, newTimeout);
2641 }
2642 return count;
2643 }
2644
2645
2646
2647
2648
2649 private int getAggregateJobCount() {
2650 int count = 0;
2651 for (Iterator<WeakReference<JavaScriptJobManager>> i = jobManagers_.iterator(); i.hasNext();) {
2652 final JavaScriptJobManager jobManager;
2653 final WeakReference<JavaScriptJobManager> reference;
2654 try {
2655 reference = i.next();
2656 jobManager = reference.get();
2657 if (jobManager == null) {
2658 i.remove();
2659 continue;
2660 }
2661 }
2662 catch (final ConcurrentModificationException e) {
2663 i = jobManagers_.iterator();
2664 count = 0;
2665 continue;
2666 }
2667 final int jobCount = jobManager.getJobCount();
2668 count += jobCount;
2669 }
2670 return count;
2671 }
2672
2673
2674
2675
2676
2677
2678
2679 private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
2680 in.defaultReadObject();
2681
2682 webConnection_ = new HttpWebConnection(this);
2683 scriptEngine_ = new JavaScriptEngine(this);
2684 jobManagers_ = Collections.synchronizedList(new ArrayList<>());
2685 loadQueue_ = new ArrayList<>();
2686 css3ParserPool_ = new CSS3ParserPool();
2687 }
2688
2689 private static class LoadJob {
2690 private final WebWindow requestingWindow_;
2691 private final String target_;
2692 private final WebResponse response_;
2693 private final WeakReference<Page> originalPage_;
2694 private final WebRequest request_;
2695 private final String forceAttachmentWithFilename_;
2696
2697
2698
2699 LoadJob(final WebRequest request, final WebResponse response,
2700 final WebWindow requestingWindow, final String target, final String forceAttachmentWithFilename) {
2701 request_ = request;
2702 requestingWindow_ = requestingWindow;
2703 target_ = target;
2704 response_ = response;
2705 originalPage_ = new WeakReference<>(requestingWindow.getEnclosedPage());
2706 forceAttachmentWithFilename_ = forceAttachmentWithFilename;
2707 }
2708
2709 public boolean isOutdated() {
2710 if (target_ != null && !target_.isEmpty()) {
2711 return false;
2712 }
2713
2714 if (requestingWindow_.isClosed()) {
2715 return true;
2716 }
2717
2718 if (requestingWindow_.getEnclosedPage() != originalPage_.get()) {
2719 return true;
2720 }
2721
2722 return false;
2723 }
2724 }
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740 public void download(final WebWindow requestingWindow, final String target,
2741 final WebRequest request, final boolean checkHash,
2742 final String forceAttachmentWithFilename, final String description) {
2743
2744 final WebWindow targetWindow = resolveWindow(requestingWindow, target);
2745 final URL url = request.getUrl();
2746
2747 if (targetWindow != null && HttpMethod.POST != request.getHttpMethod()) {
2748 final Page page = targetWindow.getEnclosedPage();
2749 if (page != null) {
2750 if (page.isHtmlPage() && !((HtmlPage) page).isOnbeforeunloadAccepted()) {
2751 return;
2752 }
2753
2754 if (checkHash) {
2755 final URL current = page.getUrl();
2756 final boolean justHashJump =
2757 HttpMethod.GET == request.getHttpMethod()
2758 && UrlUtils.sameFile(url, current)
2759 && null != url.getRef();
2760
2761 if (justHashJump) {
2762 processOnlyHashChange(targetWindow, url);
2763 return;
2764 }
2765 }
2766 }
2767 }
2768
2769 synchronized (loadQueue_) {
2770
2771 for (final LoadJob otherLoadJob : loadQueue_) {
2772 if (otherLoadJob.response_ == null) {
2773 continue;
2774 }
2775 final WebRequest otherRequest = otherLoadJob.request_;
2776 final URL otherUrl = otherRequest.getUrl();
2777
2778 if (url.getPath().equals(otherUrl.getPath())
2779 && url.toString().equals(otherUrl.toString())
2780 && request.getRequestParameters().equals(otherRequest.getRequestParameters())
2781 && Objects.equals(request.getRequestBody(), otherRequest.getRequestBody())) {
2782 return;
2783 }
2784 }
2785 }
2786
2787 final LoadJob loadJob;
2788 try {
2789 WebResponse response;
2790 try {
2791 response = loadWebResponse(request);
2792 }
2793 catch (final NoHttpResponseException e) {
2794 LOG.error("NoHttpResponseException while downloading; generating a NoHttpResponse", e);
2795 response = new WebResponse(RESPONSE_DATA_NO_HTTP_RESPONSE, request, 0);
2796 }
2797 loadJob = new LoadJob(request, response, requestingWindow, target, forceAttachmentWithFilename);
2798 }
2799 catch (final IOException e) {
2800 throw new RuntimeException(e);
2801 }
2802
2803 synchronized (loadQueue_) {
2804 loadQueue_.add(loadJob);
2805 }
2806 }
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816 public void loadDownloadedResponses() throws FailingHttpStatusCodeException, IOException {
2817 final List<LoadJob> queue;
2818
2819
2820
2821 synchronized (loadQueue_) {
2822 if (loadQueue_.isEmpty()) {
2823 return;
2824 }
2825 queue = new ArrayList<>(loadQueue_);
2826 loadQueue_.clear();
2827 }
2828
2829 final HashSet<WebWindow> updatedWindows = new HashSet<>();
2830 for (int i = queue.size() - 1; i >= 0; --i) {
2831 final LoadJob loadJob = queue.get(i);
2832 if (loadJob.isOutdated()) {
2833 if (LOG.isInfoEnabled()) {
2834 LOG.info("No usage of download: " + loadJob);
2835 }
2836 continue;
2837 }
2838
2839 final WebWindow window = resolveWindow(loadJob.requestingWindow_, loadJob.target_);
2840 if (updatedWindows.contains(window)) {
2841 if (LOG.isInfoEnabled()) {
2842 LOG.info("No usage of download: " + loadJob);
2843 }
2844 continue;
2845 }
2846
2847 final WebWindow win = openTargetWindow(loadJob.requestingWindow_, loadJob.target_, TARGET_SELF);
2848 final Page pageBeforeLoad = win.getEnclosedPage();
2849 loadWebResponseInto(loadJob.response_, win, loadJob.forceAttachmentWithFilename_);
2850
2851
2852 if (scriptEngine_ != null) {
2853 scriptEngine_.registerWindowAndMaybeStartEventLoop(win);
2854 }
2855
2856 if (pageBeforeLoad != win.getEnclosedPage()) {
2857 updatedWindows.add(win);
2858 }
2859
2860
2861 throwFailingHttpStatusCodeExceptionIfNecessary(loadJob.response_);
2862 }
2863 }
2864
2865 private static void processOnlyHashChange(final WebWindow window, final URL urlWithOnlyHashChange) {
2866 final Page page = window.getEnclosedPage();
2867 final String oldURL = page.getUrl().toExternalForm();
2868
2869
2870 final WebRequest req = page.getWebResponse().getWebRequest();
2871 req.setUrl(urlWithOnlyHashChange);
2872
2873
2874 final Window jsWindow = window.getScriptableObject();
2875 if (null != jsWindow) {
2876 final Location location = jsWindow.getLocation();
2877 location.setHash(oldURL, urlWithOnlyHashChange.getRef());
2878 }
2879
2880
2881 window.getHistory().addPage(page);
2882 }
2883
2884
2885
2886
2887
2888 public WebClientOptions getOptions() {
2889 return options_;
2890 }
2891
2892
2893
2894
2895
2896
2897 public StorageHolder getStorageHolder() {
2898 return storageHolder_;
2899 }
2900
2901
2902
2903
2904
2905
2906
2907 public synchronized Set<Cookie> getCookies(final URL url) {
2908 final CookieManager cookieManager = getCookieManager();
2909
2910 if (!cookieManager.isCookiesEnabled()) {
2911 return Collections.emptySet();
2912 }
2913
2914 final URL normalizedUrl = HttpClientConverter.replaceForCookieIfNecessary(url);
2915
2916 final String host = normalizedUrl.getHost();
2917
2918
2919 if (host.isEmpty()) {
2920 return Collections.emptySet();
2921 }
2922
2923
2924 cookieManager.clearExpired(new Date());
2925
2926 final Set<Cookie> matchingCookies = new LinkedHashSet<>();
2927 HttpClientConverter.addMatching(cookieManager.getCookies(), normalizedUrl,
2928 getBrowserVersion(), matchingCookies);
2929 return Collections.unmodifiableSet(matchingCookies);
2930 }
2931
2932
2933
2934
2935
2936
2937
2938 public void addCookie(final String cookieString, final URL pageUrl, final Object origin) {
2939 final CookieManager cookieManager = getCookieManager();
2940 if (!cookieManager.isCookiesEnabled()) {
2941 if (LOG.isDebugEnabled()) {
2942 LOG.debug("Skipped adding cookie: '" + cookieString
2943 + "' because cookies are not enabled for the CookieManager.");
2944 }
2945 return;
2946 }
2947
2948 try {
2949 final List<Cookie> cookies = HttpClientConverter.parseCookie(cookieString, pageUrl, getBrowserVersion());
2950
2951 for (final Cookie cookie : cookies) {
2952 cookieManager.addCookie(cookie);
2953
2954 if (LOG.isDebugEnabled()) {
2955 LOG.debug("Added cookie: '" + cookieString + "'");
2956 }
2957 }
2958 }
2959 catch (final MalformedCookieException e) {
2960 if (LOG.isDebugEnabled()) {
2961 LOG.warn("Adding cookie '" + cookieString + "' failed.", e);
2962 }
2963 getIncorrectnessListener().notify("Adding cookie '" + cookieString
2964 + "' failed; reason: '" + e.getMessage() + "'.", origin);
2965 }
2966 }
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976 public boolean isJavaScriptEnabled() {
2977 return javaScriptEngineEnabled_ && getOptions().isJavaScriptEnabled();
2978 }
2979
2980
2981
2982
2983
2984
2985
2986 public boolean isJavaScriptEngineEnabled() {
2987 return javaScriptEngineEnabled_;
2988 }
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998 public HtmlPage loadHtmlCodeIntoCurrentWindow(final String htmlCode) throws IOException {
2999 final HTMLParser htmlParser = getPageCreator().getHtmlParser();
3000 final WebWindow webWindow = getCurrentWindow();
3001
3002 final StringWebResponse webResponse =
3003 new StringWebResponse(htmlCode, new URL("https://www.htmlunit.org/dummy.html"));
3004 final HtmlPage page = new HtmlPage(webResponse, webWindow);
3005 webWindow.setEnclosedPage(page);
3006
3007 htmlParser.parse(this, webResponse, page, false, false);
3008 return page;
3009 }
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019 public XHtmlPage loadXHtmlCodeIntoCurrentWindow(final String xhtmlCode) throws IOException {
3020 final HTMLParser htmlParser = getPageCreator().getHtmlParser();
3021 final WebWindow webWindow = getCurrentWindow();
3022
3023 final StringWebResponse webResponse =
3024 new StringWebResponse(xhtmlCode, new URL("https://www.htmlunit.org/dummy.html"));
3025 final XHtmlPage page = new XHtmlPage(webResponse, webWindow);
3026 webWindow.setEnclosedPage(page);
3027
3028 htmlParser.parse(this, webResponse, page, true, false);
3029 return page;
3030 }
3031
3032
3033
3034
3035
3036
3037
3038 public WebSocketAdapter buildWebSocketAdapter(final WebSocketListener webSocketListener) {
3039 return webSocketAdapterFactory_.buildWebSocketAdapter(this, webSocketListener);
3040 }
3041
3042
3043
3044
3045
3046
3047 public void setWebSocketAdapter(final WebSocketAdapterFactory factory) {
3048 webSocketAdapterFactory_ = factory;
3049 }
3050
3051
3052
3053
3054
3055
3056
3057 public PooledCSS3Parser getCSS3Parser() {
3058 return this.css3ParserPool_.get();
3059 }
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077 static class CSS3ParserPool {
3078
3079
3080
3081
3082 private final ConcurrentLinkedDeque<PooledCSS3Parser> parsers_ = new ConcurrentLinkedDeque<>();
3083
3084
3085
3086
3087
3088
3089
3090
3091 public PooledCSS3Parser get() {
3092
3093 final PooledCSS3Parser parser = parsers_.pollLast();
3094
3095
3096 return parser != null ? parser.markInUse(this) : new PooledCSS3Parser(this);
3097 }
3098
3099
3100
3101
3102
3103
3104
3105
3106 protected void recycle(final PooledCSS3Parser parser) {
3107 parsers_.addLast(parser);
3108 }
3109 }
3110
3111
3112
3113
3114
3115
3116
3117
3118 public static class PooledCSS3Parser extends CSS3Parser implements AutoCloseable {
3119
3120
3121
3122
3123 private CSS3ParserPool pool_;
3124
3125
3126
3127
3128
3129
3130 protected PooledCSS3Parser(final CSS3ParserPool pool) {
3131 super();
3132 this.pool_ = pool;
3133 }
3134
3135
3136
3137
3138
3139
3140
3141 protected PooledCSS3Parser markInUse(final CSS3ParserPool pool) {
3142
3143 if (this.pool_ == null) {
3144 this.pool_ = pool;
3145 }
3146 else {
3147 throw new IllegalStateException("This PooledParser was not returned to the pool properly");
3148 }
3149
3150 return this;
3151 }
3152
3153
3154
3155
3156
3157
3158
3159
3160 @Override
3161 public void close() {
3162 if (this.pool_ != null) {
3163 final CSS3ParserPool oldPool = this.pool_;
3164
3165
3166 this.pool_ = null;
3167
3168
3169 oldPool.recycle(this);
3170 }
3171 else {
3172 throw new IllegalStateException("This PooledParser was returned already");
3173 }
3174 }
3175 }
3176 }