View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit;
16  
17  import java.io.File;
18  import java.io.IOException;
19  import java.io.InputStream;
20  import java.io.Serializable;
21  import java.net.InetAddress;
22  import java.net.URL;
23  import java.security.KeyStore;
24  import java.security.KeyStoreException;
25  import java.security.NoSuchAlgorithmException;
26  import java.security.cert.CertificateException;
27  
28  import javax.net.ssl.SSLContext;
29  
30  import org.apache.commons.io.FileUtils;
31  
32  /**
33   * Configuration options for {@link WebClient} instances.
34   * This class provides fine-grained control over client behavior including:
35   * <ul>
36   *   <li>JavaScript and CSS processing</li>
37   *   <li>SSL/TLS configuration and certificates</li>
38   *   <li>HTTP timeouts and proxy settings</li>
39   *   <li>Memory management and temporary file handling</li>
40   *   <li>WebSocket and geolocation support</li>
41   * </ul>
42   *
43   * <p>All options have sensible defaults and can be modified independently.</p>
44   *
45   * @author Ahmed Ashour
46   * @author Marc Guillemot
47   * @author Madis Pärn
48   * @author Ronald Brill
49   */
50  @SuppressWarnings("PMD.TooManyFields")
51  public class WebClientOptions implements Serializable {
52  
53      /** 1920. */
54      private static final int DEFAULT_SCRREN_WIDTH = 1920;
55      /** 1080. */
56      private static final int DEFAULT_SCRREN_HEIGHT = 1080;
57  
58      private boolean javaScriptEnabled_ = true;
59      private boolean cssEnabled_ = true;
60      private boolean printContentOnFailingStatusCode_ = true;
61      private boolean throwExceptionOnFailingStatusCode_ = true;
62      private boolean throwExceptionOnScriptError_ = true;
63      private boolean popupBlockerEnabled_;
64      private boolean isRedirectEnabled_ = true;
65      // strange value 72 used to be backward compatible with 4.14.0
66      private int pageRefreshLimit_ = 72;
67      private File tempFileDirectory_;
68  
69      private transient KeyStore sslClientCertificateStore_;
70      private char[] sslClientCertificatePassword_;
71      private transient KeyStore sslTrustStore_;
72      private String[] sslClientProtocols_;
73      private String[] sslClientCipherSuites_;
74  
75      private transient SSLContext sslContext_;
76      private boolean useInsecureSSL_; // default is secure SSL
77      private String sslInsecureProtocol_;
78  
79      private boolean doNotTrackEnabled_;
80      private String homePage_ = "https://www.htmlunit.org/";
81      private ProxyConfig proxyConfig_;
82      private int timeout_ = 90_000; // like Firefox 16 default's value for network.http.connection-timeout
83      private long connectionTimeToLive_ = -1; // HttpClient default
84  
85      private boolean fileProtocolForXMLHttpRequestsAllowed_;
86  
87      private int maxInMemory_ = 500 * 1024;
88      private int historySizeLimit_ = 50;
89      private int historyPageCacheLimit_ = Integer.MAX_VALUE;
90      private InetAddress localAddress_;
91      private boolean downloadImages_;
92      private int screenWidth_ = DEFAULT_SCRREN_WIDTH;
93      private int screenHeight_ = DEFAULT_SCRREN_HEIGHT;
94  
95      private boolean geolocationEnabled_;
96      private Geolocation geolocation_;
97  
98      private int nekoReaderBufferSize_ = -1;
99  
100     private boolean webSocketEnabled_ = true;
101     private int webSocketMaxTextMessageSize_ = -1;
102     private int webSocketMaxBinaryMessageSize_ = -1;
103 
104     private boolean isFetchPolyfillEnabled_;
105 
106     private boolean htmlFragmentSelfClosingTagsAllowed_;
107 
108     private boolean contentSecurityPolicyReportsEnabled_ = true;
109 
110     private boolean localFileAccessFromRemotePagesAllowed_;
111 
112     /**
113      * Sets the SSLContext; if this is set it is used and some other settings are
114      * ignored (protocol, keyStore, keyStorePassword, trustStore,
115      * sslClientCertificateStore, sslClientCertificatePassword).
116      * <p>
117      * This property is transient (because SSLContext is not serializable)
118      * </p>
119      *
120      * @param sslContext the SSLContext, {@code null} to use for default value
121      */
122     public void setSSLContext(final SSLContext sslContext) {
123         sslContext_ = sslContext;
124     }
125 
126     /**
127      * Gets the SSLContext; if this is set this is used and some other settings are
128      * ignored (protocol, keyStore, keyStorePassword, trustStore,
129      * sslClientCertificateStore, sslClientCertificatePassword).
130      * <p>
131      * This property is transient (because SSLContext is not serializable)
132      * </p>
133      *
134      * @return the SSLContext
135      */
136     public SSLContext getSSLContext() {
137         return sslContext_;
138     }
139 
140     /**
141      * If set to {@code true}, the client will accept connections to any host,
142      * regardless of whether they have valid certificates or not. This is especially
143      * useful when you are trying to connect to a server with expired or corrupt
144      * certificates.
145      *
146      * @param useInsecureSSL whether or not to use insecure SSL
147      */
148     public void setUseInsecureSSL(final boolean useInsecureSSL) {
149         useInsecureSSL_ = useInsecureSSL;
150     }
151 
152     /**
153      * Indicates if insecure SSL should be used.
154      *
155      * @return {@code true} if insecure SSL should be used. Default is
156      *         {@code false}.
157      */
158     public boolean isUseInsecureSSL() {
159         return useInsecureSSL_;
160     }
161 
162     /**
163      * Sets whether or not redirections will be followed automatically on receipt of
164      * a redirect status code from the server.
165      *
166      * @param enabled true to enable automatic redirection
167      */
168     public void setRedirectEnabled(final boolean enabled) {
169         isRedirectEnabled_ = enabled;
170     }
171 
172     /**
173      * Sets the redirect limit for page refresh operations using HTTP refresh
174      * headers or meta tags. This prevents infinite refresh loops by limiting the
175      * number of consecutive refreshes allowed. Set to -1 to allow unlimited
176      * refreshes.
177      *
178      * <p>
179      * Note: The {@link NiceRefreshHandler} and {@link ImmediateRefreshHandler} have
180      * additional loop protection that may trigger before this limit.
181      * </p>
182      *
183      * @param pageRefreshLimit the maximum number of refresh loops, or -1 for
184      *                         unlimited
185      */
186     public void setPageRefreshLimit(final int pageRefreshLimit) {
187         pageRefreshLimit_ = pageRefreshLimit;
188     }
189 
190     /**
191      * Returns the directory to be used for storing the response content in a
192      * temporary file see {@link #getMaxInMemory()}.
193      *
194      * @return the directory to be used for storing temp files or null to use the
195      *         system default
196      */
197     public File getTempFileDirectory() {
198         return tempFileDirectory_;
199     }
200 
201     /**
202      * Sets the directory to be used for storing response content in temporary
203      * files. See {@link #setMaxInMemory(int)} for when temporary files are created.
204      * If the directory doesn't exist, it will be created automatically.
205      *
206      * @param tempFileDirectory the directory to use, or {@code null} for system
207      *                          default
208      * @throws IOException              if directory creation fails
209      * @throws IllegalArgumentException if the path points to an existing file
210      */
211     public void setTempFileDirectory(final File tempFileDirectory) throws IOException {
212         if (tempFileDirectory != null) {
213             if (tempFileDirectory.exists() && !tempFileDirectory.isDirectory()) {
214                 throw new IllegalArgumentException("The provided file '" + tempFileDirectory
215                         + "' points to an already existing file");
216             }
217 
218             if (!tempFileDirectory.exists()) {
219                 FileUtils.forceMkdir(tempFileDirectory);
220             }
221         }
222         tempFileDirectory_ = tempFileDirectory;
223     }
224 
225     /**
226      * Returns whether or not redirections will be followed automatically on receipt
227      * of a redirect status code from the server.
228      *
229      * @return true if automatic redirection is enabled
230      */
231     public boolean isRedirectEnabled() {
232         return isRedirectEnabled_;
233     }
234 
235     /**
236      * Returns the limit to be used when a page refreshes itself by using a http
237      * refresh header or meta tag. Negative values are interpreted as endless
238      * refresh support.
239      *
240      * @return pageRefreshLimit the number of refresh loops before throwing an
241      *         exception
242      */
243     public int getPageRefreshLimit() {
244         return pageRefreshLimit_;
245     }
246 
247     /**
248      * Sets the SSL client certificate {@link KeyStore} to use.
249      * <p>
250      * If the web server requires Renegotiation, you have to set system property
251      * "sun.security.ssl.allowUnsafeRenegotiation" to true, as hinted in <a href=
252      * "http://www.oracle.com/technetwork/java/javase/documentation/tlsreadme2-176330.html">
253      * TLS Renegotiation Issue</a>.
254      * </p>
255      * <p>
256      * In some cases the impl seems to pick old certificates from the
257      * {@link KeyStore}. To avoid that, wrap your {@link KeyStore} inside your own
258      * {@link KeyStore} impl and filter out outdated certificates.
259      * </p>
260      * <p>
261      * This property is transient (because KeyStore is not serializable)
262      * </p>
263      *
264      * @param keyStore         {@link KeyStore} to use
265      * @param keyStorePassword the keystore password
266      */
267     public void setSSLClientCertificateKeyStore(final KeyStore keyStore, final char[] keyStorePassword) {
268         sslClientCertificateStore_ = keyStore;
269         sslClientCertificatePassword_ = keyStorePassword;
270     }
271 
272     /**
273      * Sets the SSL client certificate to use. The needed parameters are used to
274      * construct a {@link java.security.KeyStore}.
275      * <p>
276      * If the web server requires Renegotiation, you have to set system property
277      * "sun.security.ssl.allowUnsafeRenegotiation" to true, as hinted in <a href=
278      * "http://www.oracle.com/technetwork/java/javase/documentation/tlsreadme2-176330.html">
279      * TLS Renegotiation Issue</a>.
280      * </p>
281      * <p>
282      * This property is transient (because KeyStore is not serializable)
283      * </p>
284      *
285      * @param keyStoreUrl      the URL which locates the certificate
286      *                         {@link KeyStore}
287      * @param keyStorePassword the certificate {@link KeyStore} password
288      * @param keyStoreType     the type of certificate {@link KeyStore}, usually
289      *                         {@code jks} or {@code pkcs12}
290      *
291      */
292     public void setSSLClientCertificateKeyStore(final URL keyStoreUrl, final String keyStorePassword,
293             final String keyStoreType) {
294         try (InputStream is = keyStoreUrl.openStream()) {
295             sslClientCertificateStore_ = getKeyStore(is, keyStorePassword, keyStoreType);
296             sslClientCertificatePassword_ = keyStorePassword == null ? null : keyStorePassword.toCharArray();
297         }
298         catch (final Exception e) {
299             throw new RuntimeException(e);
300         }
301     }
302 
303     /**
304      * Sets the SSL client certificate {@link KeyStore} to use. The parameters are
305      * used to construct the {@link KeyStore}.
306      * <p>
307      * If the web server requires Renegotiation, you have to set system property
308      * "sun.security.ssl.allowUnsafeRenegotiation" to true, as hinted in <a href=
309      * "http://www.oracle.com/technetwork/java/javase/documentation/tlsreadme2-176330.html">
310      * TLS Renegotiation Issue</a>.
311      * </p>
312      * <p>
313      * In some cases the impl seems to pick old certificates from the
314      * {@link KeyStore}. To avoid that, wrap your {@link KeyStore} inside your own
315      * {@link KeyStore} impl and filter out outdated certificates. Provide the
316      * {@link KeyStore} to the options instead of the input stream.
317      * </p>
318      *
319      * @param keyStoreInputStream the input stream which represents the
320      *                            {@link KeyStore} holding the certificates
321      * @param keyStorePassword    the {@link KeyStore} password
322      * @param keyStoreType        the type of {@link KeyStore}, usually {@code jks}
323      *                            or {@code pkcs12}
324      */
325     public void setSSLClientCertificateKeyStore(final InputStream keyStoreInputStream, final String keyStorePassword,
326             final String keyStoreType) {
327         try {
328             setSSLClientCertificateKeyStore(getKeyStore(keyStoreInputStream, keyStorePassword, keyStoreType),
329                     keyStorePassword.toCharArray());
330         }
331         catch (final Exception e) {
332             throw new RuntimeException(e);
333         }
334     }
335 
336     /**
337      * Gets the SSLClientCertificateStore.
338      * <p>
339      * This property is transient (because KeyStore is not serializable)
340      * </p>
341      *
342      * @return the KeyStore for use on SSL connections
343      */
344     public KeyStore getSSLClientCertificateStore() {
345         return sslClientCertificateStore_;
346     }
347 
348     /**
349      * Gets the SSLClientCertificatePassword.
350      *
351      * @return the password
352      */
353     public char[] getSSLClientCertificatePassword() {
354         return sslClientCertificatePassword_;
355     }
356 
357     /**
358      * Gets the protocol versions enabled for use on SSL connections.
359      *
360      * @return the protocol versions enabled for use on SSL connections
361      * @see #setSSLClientProtocols(String...)
362      */
363     public String[] getSSLClientProtocols() {
364         return sslClientProtocols_;
365     }
366 
367     /**
368      * Sets the protocol versions enabled for use on SSL connections, {@code null}
369      * to use default ones.
370      *
371      * @param sslClientProtocols the protocol versions
372      * @see javax.net.ssl.SSLSocket#setEnabledProtocols(String[])
373      * @see #getSSLClientProtocols()
374      * @see #setSSLClientCipherSuites(String...)
375      * @see #setUseInsecureSSL(boolean)
376      */
377     public void setSSLClientProtocols(final String... sslClientProtocols) {
378         sslClientProtocols_ = sslClientProtocols;
379     }
380 
381     /**
382      * Gets the cipher suites enabled for use on SSL connections.
383      *
384      * @return the cipher suites enabled for use on SSL connections
385      * @see #setSSLClientCipherSuites(String...)
386      */
387     public String[] getSSLClientCipherSuites() {
388         return sslClientCipherSuites_;
389     }
390 
391     /**
392      * Sets the cipher suites enabled for use on SSL connections, {@code null} to
393      * use default ones.
394      *
395      * @param sslClientCipherSuites the cipher suites
396      * @see javax.net.ssl.SSLSocket#setEnabledCipherSuites(String[])
397      * @see #getSSLClientCipherSuites()
398      */
399     public void setSSLClientCipherSuites(final String... sslClientCipherSuites) {
400         sslClientCipherSuites_ = sslClientCipherSuites;
401     }
402 
403     /**
404      * Enables/disables JavaScript support. By default, this property is enabled.
405      *
406      * @param enabled {@code true} to enable JavaScript support
407      */
408     public void setJavaScriptEnabled(final boolean enabled) {
409         javaScriptEnabled_ = enabled;
410     }
411 
412     /**
413      * Returns {@code true} if JavaScript is enabled and the script engine was
414      * loaded successfully.
415      *
416      * @return {@code true} if JavaScript is enabled
417      */
418     public boolean isJavaScriptEnabled() {
419         return javaScriptEnabled_;
420     }
421 
422     /**
423      * Enables/disables CSS support. By default, this property is enabled. If
424      * disabled HtmlUnit will not download the linked css files and also not
425      * triggered the associated onload/onerror events.
426      *
427      * @param enabled {@code true} to enable CSS support
428      */
429     public void setCssEnabled(final boolean enabled) {
430         cssEnabled_ = enabled;
431     }
432 
433     /**
434      * Returns {@code true} if CSS is enabled.
435      *
436      * @return {@code true} if CSS is enabled
437      */
438     public boolean isCssEnabled() {
439         return cssEnabled_;
440     }
441 
442     /**
443      * Enable/disable the popup window blocker. By default, the popup blocker is
444      * disabled, and popup windows are allowed. When set to {@code true},
445      * <code>window.open()</code> has no effect and returns {@code null}.
446      *
447      * @param enabled {@code true} to enable the popup window blocker
448      */
449     public void setPopupBlockerEnabled(final boolean enabled) {
450         popupBlockerEnabled_ = enabled;
451     }
452 
453     /**
454      * Returns {@code true} if the popup window blocker is enabled.
455      *
456      * @return {@code true} if the popup window blocker is enabled
457      */
458     public boolean isPopupBlockerEnabled() {
459         return popupBlockerEnabled_;
460     }
461 
462     /**
463      * Enables/disables "Do Not Track" support. By default, this property is
464      * disabled.
465      *
466      * @param enabled {@code true} to enable "Do Not Track" support
467      */
468     public void setDoNotTrackEnabled(final boolean enabled) {
469         doNotTrackEnabled_ = enabled;
470     }
471 
472     /**
473      * Returns {@code true} if "Do Not Track" is enabled.
474      *
475      * @return {@code true} if "Do Not Track" is enabled
476      */
477     public boolean isDoNotTrackEnabled() {
478         return doNotTrackEnabled_;
479     }
480 
481     /**
482      * Specify whether or not the content of the resulting document will be printed
483      * to the console in the event of a failing response code. Successful response
484      * codes are in the range 200-299. The default is true.
485      *
486      * @param enabled True to enable this feature
487      */
488     public void setPrintContentOnFailingStatusCode(final boolean enabled) {
489         printContentOnFailingStatusCode_ = enabled;
490     }
491 
492     /**
493      * Returns {@code true} if the content of the resulting document will be printed
494      * to the console in the event of a failing response code.
495      *
496      * @return {@code true} if the content of the resulting document will be printed
497      *         to the console in the event of a failing response code
498      * @see #setPrintContentOnFailingStatusCode
499      */
500     public boolean isPrintContentOnFailingStatusCode() {
501         return printContentOnFailingStatusCode_;
502     }
503 
504     /**
505      * Specify whether or not an exception will be thrown in the event of a failing
506      * status code. Successful status codes are in the range 200-299. The default is
507      * true.
508      *
509      * @param enabled {@code true} to enable this feature
510      */
511     public void setThrowExceptionOnFailingStatusCode(final boolean enabled) {
512         throwExceptionOnFailingStatusCode_ = enabled;
513     }
514 
515     /**
516      * Returns {@code true} if an exception will be thrown in the event of a failing
517      * response code.
518      *
519      * @return {@code true} if an exception will be thrown in the event of a failing
520      *         response code
521      * @see #setThrowExceptionOnFailingStatusCode
522      */
523     public boolean isThrowExceptionOnFailingStatusCode() {
524         return throwExceptionOnFailingStatusCode_;
525     }
526 
527     /**
528      * Indicates if an exception should be thrown when a script execution fails (the
529      * default) or if it should be caught and just logged to allow page execution to
530      * continue.
531      *
532      * @return {@code true} if an exception is thrown on script error (the default)
533      */
534     public boolean isThrowExceptionOnScriptError() {
535         return throwExceptionOnScriptError_;
536     }
537 
538     /**
539      * Changes the behavior of this webclient when a script error occurs.
540      *
541      * @param enabled indicates if exception should be thrown or not
542      */
543     public void setThrowExceptionOnScriptError(final boolean enabled) {
544         throwExceptionOnScriptError_ = enabled;
545     }
546 
547     /**
548      * Returns the client's current homepage.
549      *
550      * @return the client's current homepage
551      */
552     public String getHomePage() {
553         return homePage_;
554     }
555 
556     /**
557      * Sets the client's homepage.
558      *
559      * @param homePage the new homepage URL
560      */
561     public void setHomePage(final String homePage) {
562         homePage_ = homePage;
563     }
564 
565     /**
566      * Returns the proxy configuration for this client.
567      *
568      * @return the proxy configuration for this client
569      */
570     public ProxyConfig getProxyConfig() {
571         return proxyConfig_;
572     }
573 
574     /**
575      * Sets the proxy configuration for this client.
576      *
577      * @param proxyConfig the proxy configuration for this client
578      */
579     public void setProxyConfig(final ProxyConfig proxyConfig) {
580         WebAssert.notNull("proxyConfig", proxyConfig);
581         proxyConfig_ = proxyConfig;
582     }
583 
584     /**
585      * Gets the timeout value for the {@link WebConnection}. The default timeout is
586      * 90 seconds.
587      *
588      * @return the timeout value in milliseconds
589      * @see #setTimeout(int)
590      * @see #setConnectionTimeToLive(long)
591      */
592     public int getTimeout() {
593         return timeout_;
594     }
595 
596     /**
597      * <p>
598      * Sets the timeout of the {@link WebConnection}. Set to zero for an infinite
599      * wait.
600      * </p>
601      *
602      * <p>
603      * Note: The timeout is used twice. The first is for making the socket
604      * connection, the second is for data retrieval. If the time is critical you
605      * must allow for twice the time specified here.
606      * </p>
607      *
608      * @param timeout the value of the timeout in milliseconds
609      */
610     public void setTimeout(final int timeout) {
611         timeout_ = timeout;
612     }
613 
614     /**
615      * Gets the connTimeToLive value for the HttpClient connection pool.
616      *
617      * @return the timeout value in milliseconds
618      */
619     public long getConnectionTimeToLive() {
620         return connectionTimeToLive_;
621     }
622 
623     /**
624      * Sets the connection time-to-live for the HttpClient connection pool. This is
625      * useful when working with web pages behind DNS-based load balancers where IP
626      * addresses may change frequently.
627      *
628      * @param connectionTimeToLive the timeout in milliseconds, or -1 to disable
629      *                             (default)
630      */
631     public void setConnectionTimeToLive(final long connectionTimeToLive) {
632         connectionTimeToLive_ = connectionTimeToLive;
633     }
634 
635     /**
636      * Sets the SSL protocol, used only when {@link #setUseInsecureSSL(boolean)} is
637      * set to {@code true}.
638      *
639      * @param sslInsecureProtocol the SSL protocol for insecure SSL connections,
640      *                            {@code null} to use for default value
641      */
642     public void setSSLInsecureProtocol(final String sslInsecureProtocol) {
643         sslInsecureProtocol_ = sslInsecureProtocol;
644     }
645 
646     /**
647      * Gets the SSL protocol, to be used only when
648      * {@link #setUseInsecureSSL(boolean)} is set to {@code true}.
649      *
650      * @return the SSL protocol for insecure SSL connections
651      */
652     public String getSSLInsecureProtocol() {
653         return sslInsecureProtocol_;
654     }
655 
656     /**
657      * Sets the SSL server certificate trust store. All server certificates will be
658      * validated against this trust store.
659      * <p>
660      * This property is transient (because KeyStore is not serializable)
661      * </p>
662      * <p>
663      * The needed parameters are used to construct a {@link java.security.KeyStore}.
664      * </p>
665      *
666      * @param sslTrustStoreUrl      the URL which locates the trust store
667      * @param sslTrustStorePassword the trust store password
668      * @param sslTrustStoreType     the type of trust store, usually {@code jks} or
669      *                              {@code pkcs12}
670      */
671     public void setSSLTrustStore(final URL sslTrustStoreUrl, final String sslTrustStorePassword,
672             final String sslTrustStoreType) {
673         try (InputStream is = sslTrustStoreUrl.openStream()) {
674             sslTrustStore_ = getKeyStore(is, sslTrustStorePassword, sslTrustStoreType);
675         }
676         catch (final Exception e) {
677             throw new RuntimeException(e);
678         }
679     }
680 
681     void setSSLTrustStore(final KeyStore keyStore) {
682         sslTrustStore_ = keyStore;
683     }
684 
685     /**
686      * Gets the SSL TrustStore.
687      * <p>
688      * This property is transient (because KeyStore is not serializable)
689      * </p>
690      *
691      * @return the SSL TrustStore for insecure SSL connections
692      */
693     public KeyStore getSSLTrustStore() {
694         return sslTrustStore_;
695     }
696 
697     private static KeyStore getKeyStore(final InputStream inputStream, final String keystorePassword,
698             final String keystoreType)
699             throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
700         if (inputStream == null) {
701             return null;
702         }
703 
704         final KeyStore keyStore = KeyStore.getInstance(keystoreType);
705         final char[] passwordChars = keystorePassword == null ? null : keystorePassword.toCharArray();
706         keyStore.load(inputStream, passwordChars);
707         return keyStore;
708     }
709 
710     /**
711      * Returns the maximum bytes stored in memory before content is saved to
712      * temporary files. When response content exceeds this limit, it will be written
713      * to a temporary file in the directory specified by
714      * {@link #getTempFileDirectory()}.
715      *
716      * @return the maximum bytes in memory (default: 500 * 1024)
717      * @see #setMaxInMemory(int)
718      * @see #setTempFileDirectory(File)
719      */
720     public int getMaxInMemory() {
721         return maxInMemory_;
722     }
723 
724     /**
725      * Sets the maximum bytes to have in memory, after which the content is saved to
726      * a temporary file. Set this to zero or -1 to deactivate the saving at all.
727      *
728      * @param maxInMemory maximum bytes in memory
729      */
730     public void setMaxInMemory(final int maxInMemory) {
731         maxInMemory_ = maxInMemory;
732     }
733 
734     /**
735      * Returns the maximum number of {@link Page pages} kept in
736      * {@link WebWindow#getHistory()}.
737      *
738      * @return the maximum number of pages in history
739      */
740     public int getHistorySizeLimit() {
741         return historySizeLimit_;
742     }
743 
744     /**
745      * Sets the History size limit. HtmlUnit uses SoftReferences&lt;Page&gt; for
746      * storing the pages that are part of the history. If you like to fine tune this
747      * you can use {@link #setHistoryPageCacheLimit(int)} to limit the number of
748      * page references stored by the history.
749      *
750      * @param historySizeLimit maximum number of pages in history
751      */
752     public void setHistorySizeLimit(final int historySizeLimit) {
753         historySizeLimit_ = historySizeLimit;
754     }
755 
756     /**
757      * Returns the maximum number of {@link Page pages} to cache in history.
758      *
759      * @return the maximum number of pages to cache in history
760      */
761     public int getHistoryPageCacheLimit() {
762         return historyPageCacheLimit_;
763     }
764 
765     /**
766      * Sets the maximum number of {@link Page pages} to cache in history. If this
767      * value is smaller than the {{@link #getHistorySizeLimit()} than HtmlUnit will
768      * only use soft references for the first historyPageCacheLimit entries in the
769      * history. For older entries only the url is saved; the page will be
770      * (re)retrieved on demand.
771      *
772      * @param historyPageCacheLimit maximum number of pages to cache in history
773      *                              default is Integer.MAX_VALUE; negative values
774      *                              are having the same effect as setting this to
775      *                              zero.
776      */
777     public void setHistoryPageCacheLimit(final int historyPageCacheLimit) {
778         historyPageCacheLimit_ = historyPageCacheLimit;
779     }
780 
781     /**
782      * Returns local address to be used for request execution.
783      * <p>
784      * On machines with multiple network interfaces, this parameter can be used to
785      * select the network interface from which the connection originates.
786      * </p>
787      * <p>
788      * Default: {@code null}
789      * </p>
790      *
791      * @return the local address
792      */
793     public InetAddress getLocalAddress() {
794         return localAddress_;
795     }
796 
797     /**
798      * Sets the local network interface address for outgoing HTTP requests. Useful
799      * on multi-homed machines to control which network interface is used.
800      *
801      * @param localAddress the local IP address to bind to, or {@code null} for
802      *                     automatic selection
803      */
804     public void setLocalAddress(final InetAddress localAddress) {
805         localAddress_ = localAddress;
806     }
807 
808     /**
809      * Sets whether to automatically download images by default, or not.
810      *
811      * @param downloadImages whether to automatically download images by default, or
812      *                       not
813      */
814     public void setDownloadImages(final boolean downloadImages) {
815         downloadImages_ = downloadImages;
816     }
817 
818     /**
819      * Returns whether to automatically download images by default, or not.
820      *
821      * @return whether to automatically download images by default, or not.
822      */
823     public boolean isDownloadImages() {
824         return downloadImages_;
825     }
826 
827     /**
828      * Sets the screen width. This value is used by JavaScript's screen.width
829      * property.
830      *
831      * @param screenWidth the screen width in pixels (must be positive)
832      */
833     public void setScreenWidth(final int screenWidth) {
834         screenWidth_ = screenWidth;
835     }
836 
837     /**
838      * Returns the screen width.
839      *
840      * @return the screen width
841      */
842     public int getScreenWidth() {
843         return screenWidth_;
844     }
845 
846     /**
847      * Sets the screen height.
848      *
849      * @param screenHeight the screen height
850      */
851     public void setScreenHeight(final int screenHeight) {
852         screenHeight_ = screenHeight;
853     }
854 
855     /**
856      * Returns the screen height.
857      *
858      * @return the screen height
859      */
860     public int getScreenHeight() {
861         return screenHeight_;
862     }
863 
864     /**
865      * Returns the Neko HTML parser reader buffer size. This controls the internal
866      * buffer size used by the NekoHTML parser for reading HTML content. Larger
867      * buffers can improve performance for large documents but consume more memory.
868      *
869      * @return the buffer size in bytes, or -1 for parser default
870      */
871     public int getNekoReaderBufferSize() {
872         return nekoReaderBufferSize_;
873     }
874 
875     /**
876      * Sets the Neko HTML parser reader buffer size. A larger buffer size can
877      * improve parsing performance for large HTML documents but will consume more
878      * memory. Set to -1 to use the parser's default buffer size.
879      *
880      * @param nekoReaderBufferSize the buffer size in bytes, or -1 for default
881      */
882     public void setNekoReaderBufferSize(final int nekoReaderBufferSize) {
883         nekoReaderBufferSize_ = nekoReaderBufferSize;
884     }
885 
886     /**
887      * Enables/disables WebSocket support. By default, this property is enabled.
888      *
889      * @param enabled {@code true} to enable WebSocket support
890      */
891     public void setWebSocketEnabled(final boolean enabled) {
892         webSocketEnabled_ = enabled;
893     }
894 
895     /**
896      * Returns {@code true} if WebSockets are enabled.
897      *
898      * @return {@code true} if WebSockets are enabled
899      */
900     public boolean isWebSocketEnabled() {
901         return webSocketEnabled_;
902     }
903 
904     /**
905      * Returns the maximum size in bytes for WebSocket text messages. Set to -1 to
906      * use the default.
907      *
908      * @return the maximum text message size in bytes, or -1 for default
909      */
910     public int getWebSocketMaxTextMessageSize() {
911         return webSocketMaxTextMessageSize_;
912     }
913 
914     /**
915      * Sets the maximum size in bytes for WebSocket text messages. This limit
916      * applies to individual text frames received by the WebSocket.
917      *
918      * @param webSocketMaxTextMessageSize the maximum size in bytes, or -1 for
919      *                                    default
920      */
921     public void setWebSocketMaxTextMessageSize(final int webSocketMaxTextMessageSize) {
922         webSocketMaxTextMessageSize_ = webSocketMaxTextMessageSize;
923     }
924 
925     /**
926      * Returns the maximum size in bytes for WebSocket binary messages. Set to -1 to
927      * use the default.
928      *
929      * @return the maximum binary message size in bytes, or -1 for default
930      */
931     public int getWebSocketMaxBinaryMessageSize() {
932         return webSocketMaxBinaryMessageSize_;
933     }
934 
935     /**
936      * Sets the maximum size in bytes for WebSocket binary messages. This limit
937      * applies to individual binary frames received by the WebSocket.
938      *
939      * @param webSocketMaxBinaryMessageSize the maximum size in bytes, or -1 for
940      *                                      default
941      */
942     public void setWebSocketMaxBinaryMessageSize(final int webSocketMaxBinaryMessageSize) {
943         webSocketMaxBinaryMessageSize_ = webSocketMaxBinaryMessageSize;
944     }
945 
946     /**
947      * Sets whether or not fetch polyfill should be used.
948      *
949      * @param enabled true to enable fetch polyfill
950      */
951     public void setFetchPolyfillEnabled(final boolean enabled) {
952         isFetchPolyfillEnabled_ = enabled;
953     }
954 
955     /**
956      * Returns true if the fetch api polyfill is enabled.
957      *
958      * @return true if the fetch api polyfill is enabled
959      */
960     public boolean isFetchPolyfillEnabled() {
961         return isFetchPolyfillEnabled_;
962     }
963 
964     /**
965      * Sets whether the fragment parser of html pages (e.g. {@code setInnerHtml()}) closes a non void element
966      * or iframe written as empty-element tag (e.g. {@code <h3/>}), like up to version 5.5.0. By default the
967      * trailing slash is ignored like in the browsers. A self-closed script is not affected.
968      * Enable this to read back markup written by {@code asXml()} before 5.8.0, which wrote empty elements
969      * like {@code <h3/>}. XHTML pages always honor the trailing slash.
970      * <p>The option applies to every fragment parsed for an html page, also to the markup set by
971      * the scripts of the page (e.g. {@code innerHTML}, {@code outerHTML}, {@code insertAdjacentHTML()},
972      * {@code createContextualFragment()}). Real browsers ignore the trailing slash; with this option
973      * the DOM can differ from the one of the browsers. This is relevant for security, e.g. for
974      * sanitizers: the content after {@code <iframe/>} is markup and no longer the text of the iframe.
975      * Enable this only to read back markup written by old versions of HtmlUnit.</p>
976      *
977      * @param allowed {@code true} to close a non void element written as empty-element tag
978      */
979     public void setHtmlFragmentSelfClosingTagsAllowed(final boolean allowed) {
980         htmlFragmentSelfClosingTagsAllowed_ = allowed;
981     }
982 
983     /**
984      * Returns whether the fragment parser of html pages closes a non void element written as empty-element tag
985      * (default {@code false}).
986      *
987      * @return {@code true} if the fragment parser of html pages closes a non void element written as
988      *         empty-element tag
989      * @see #setHtmlFragmentSelfClosingTagsAllowed(boolean)
990      */
991     public boolean isHtmlFragmentSelfClosingTagsAllowed() {
992         return htmlFragmentSelfClosingTagsAllowed_;
993     }
994 
995     /**
996      * Enables/disables Geolocation support. By default, this property is disabled.
997      *
998      * @param enabled {@code true} to enable Geolocation support
999      */
1000     public void setGeolocationEnabled(final boolean enabled) {
1001         geolocationEnabled_ = enabled;
1002     }
1003 
1004     /**
1005      * Returns {@code true} if Geolocation is enabled.
1006      *
1007      * @return {@code true} if Geolocation is enabled
1008      */
1009     public boolean isGeolocationEnabled() {
1010         return geolocationEnabled_;
1011     }
1012 
1013     /**
1014      * Returns the {@link Geolocation}.
1015      *
1016      * @return the {@link Geolocation}
1017      */
1018     public Geolocation getGeolocation() {
1019         return geolocation_;
1020     }
1021 
1022     /**
1023      * Sets the {@link Geolocation} to be used.
1024      *
1025      * @param geolocation the new location or null
1026      */
1027     public void setGeolocation(final Geolocation geolocation) {
1028         geolocation_ = geolocation;
1029     }
1030 
1031     /**
1032      * Support class for Geolocation.
1033      */
1034     public static class Geolocation implements Serializable {
1035         private final double accuracy_;
1036         private final double latitude_;
1037         private final double longitude_;
1038         private final Double altitude_;
1039         private final Double altitudeAccuracy_;
1040         private final Double heading_;
1041         private final Double speed_;
1042 
1043         /**
1044          * Ctor.
1045          *
1046          * @param latitude         the latitude coordinate in decimal degrees
1047          * @param longitude        the longitude coordinate in decimal degrees
1048          * @param accuracy         the accuracy of the position in meters
1049          * @param altitude         the altitude in meters above sea level, or null if
1050          *                         unavailable
1051          * @param altitudeAccuracy the accuracy of the altitude in meters, or null if
1052          *                         unavailable
1053          * @param heading          the direction of travel in degrees (0-359), or null
1054          *                         if unavailable
1055          * @param speed            the current speed in meters per second, or null if
1056          *                         unavailable
1057          */
1058         public Geolocation(final double latitude, final double longitude, final double accuracy, final Double altitude,
1059                 final Double altitudeAccuracy, final Double heading, final Double speed) {
1060             latitude_ = latitude;
1061             longitude_ = longitude;
1062             accuracy_ = accuracy;
1063             altitude_ = altitude;
1064             altitudeAccuracy_ = altitudeAccuracy;
1065             heading_ = heading;
1066             speed_ = speed;
1067         }
1068 
1069         /**
1070          * Returns the accuracy.
1071          *
1072          * @return the accuracy
1073          */
1074         public double getAccuracy() {
1075             return accuracy_;
1076         }
1077 
1078         /**
1079          * Returns the latitude.
1080          *
1081          * @return the latitude
1082          */
1083         public double getLatitude() {
1084             return latitude_;
1085         }
1086 
1087         /**
1088          * Returns the longitude.
1089          *
1090          * @return the longitude
1091          */
1092         public double getLongitude() {
1093             return longitude_;
1094         }
1095 
1096         /**
1097          * Returns the longitude.
1098          *
1099          * @return the longitude
1100          */
1101         public Double getAltitude() {
1102             return altitude_;
1103         }
1104 
1105         /**
1106          * Returns the altitudeAccuracy.
1107          *
1108          * @return the altitudeAccuracy
1109          */
1110         public Double getAltitudeAccuracy() {
1111             return altitudeAccuracy_;
1112         }
1113 
1114         /**
1115          * Returns the heading.
1116          *
1117          * @return the heading
1118          */
1119         public Double getHeading() {
1120             return heading_;
1121         }
1122 
1123         /**
1124          * Returns the speed.
1125          *
1126          * @return the speed
1127          */
1128         public Double getSpeed() {
1129             return speed_;
1130         }
1131     }
1132 
1133     /**
1134      * If set to {@code true}, the client will accept XMLHttpRequests to URL's using
1135      * the 'file' protocol. Allowing this introduces security problems and is
1136      * therefore not allowed by current browsers. But some browsers have special
1137      * settings to open this door; therefore we have this option also.
1138      *
1139      * <p>
1140      * <b>Security Warning:</b> Enabling this feature may expose local files to web
1141      * content, which can be a serious security risk.
1142      * </p>
1143      *
1144      * @param fileProtocolForXMLHttpRequestsAllowed whether or not allow (local)
1145      *                                              file access
1146      */
1147     public void setFileProtocolForXMLHttpRequestsAllowed(final boolean fileProtocolForXMLHttpRequestsAllowed) {
1148         fileProtocolForXMLHttpRequestsAllowed_ = fileProtocolForXMLHttpRequestsAllowed;
1149     }
1150 
1151     /**
1152      * Indicates if the client will accept XMLHttpRequests to URL's using the 'file'
1153      * protocol.
1154      *
1155      * @return {@code true} if access to local files is allowed.
1156      */
1157     public boolean isFileProtocolForXMLHttpRequestsAllowed() {
1158         return fileProtocolForXMLHttpRequestsAllowed_;
1159     }
1160 
1161     /**
1162      * Enables/disables sending the Content-Security-Policy violation reports to the
1163      * uris of the report-uri directive (default {@code true}).
1164      * <p>
1165      * If disabled, the policies are still enforced, the
1166      * {@link org.htmlunit.html.csp.ContentSecurityPolicyViolationListener} is informed and the
1167      * securitypolicyviolation event is fired; only the report requests are not sent.
1168      * </p>
1169      *
1170      * @param enabled {@code true} to send the violation reports
1171      */
1172     public void setContentSecurityPolicyReportsEnabled(final boolean enabled) {
1173         contentSecurityPolicyReportsEnabled_ = enabled;
1174     }
1175 
1176     /**
1177      * Returns whether the Content-Security-Policy violation reports are sent to the
1178      * uris of the report-uri directive (default {@code true}).
1179      *
1180      * @return {@code true} if the violation reports are sent
1181      * @see #setContentSecurityPolicyReportsEnabled(boolean)
1182      */
1183     public boolean isContentSecurityPolicyReportsEnabled() {
1184         return contentSecurityPolicyReportsEnabled_;
1185     }
1186 
1187     /**
1188      * Sets whether pages that were not loaded from a local file are allowed to access
1189      * local files (file URLs), default {@code false}.
1190      * <p>Like the browsers, HtmlUnit blocks e.g. scripts, images, stylesheets, frames, workers
1191      * and navigations to file URLs if the page was not loaded from a file.
1192      * Redirects to file URLs are always blocked (Fetch Standard).
1193      * Enable this only for tests that depend on the old (insecure) behavior of HtmlUnit;
1194      * real browsers will not load these resources.</p>
1195      *
1196      * @param allowed whether pages not loaded from a file are allowed to access local files
1197      */
1198     public void setLocalFileAccessFromRemotePagesAllowed(final boolean allowed) {
1199         localFileAccessFromRemotePagesAllowed_ = allowed;
1200     }
1201 
1202     /**
1203      * Returns whether pages that were not loaded from a local file are allowed to access
1204      * local files (file URLs), default {@code false}.
1205      *
1206      * @return {@code true} if pages not loaded from a file are allowed to access local files
1207      * @see #setLocalFileAccessFromRemotePagesAllowed(boolean)
1208      */
1209     public boolean isLocalFileAccessFromRemotePagesAllowed() {
1210         return localFileAccessFromRemotePagesAllowed_;
1211     }
1212 }