com.gargoylesoftware.htmlunit.util.WebConnectionWrapper Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.util.WebConnectionWrapper. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpWebConnectionInsecureSSLTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
public void insecureSSL_withWrapper() throws Exception {
    final WebClient webClient = getWebClient();
    webClient.setWebConnection(new WebConnectionWrapper(webClient.getWebConnection()));
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getPage("https://" + localServer_.getHostName()
            + ':' + localServer_.getPort()
            + "/random/100");
}
 
Example #2
Source File: HiddenBrowserDriver.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Fixing refresh handler to skip Refresh meta tags
 * Allowing connections to any host, regardless of whether they have valid certificates or not
 * Fixing JSESSIONID cookie value
 * Some applications expect double quotes in the beginning and at the end of the JSESSIONID cookie value
 */
private void fixHtmlUnitBehaviour() {

    Field webClientField = null;
    boolean fieldAccessibleState = false;
    try {
        TargetLocator targetLocator = webDriver.switchTo();
        webClientField = targetLocator.getClass().getDeclaringClass().getDeclaredField("webClient");
        fieldAccessibleState = webClientField.isAccessible();
        webClientField.setAccessible(true);
        final WebClient webClient = (WebClient) webClientField.get(targetLocator.defaultContent());

        // Allowing connections to any host, regardless of whether they have valid certificates or not
        webClient.getOptions().setUseInsecureSSL(true);

        // Set Http connection timeout (in milliseconds). The default value is 90 seconds, because in Firefox >= 16
        // the "network.http.connection-timeout" property is 90. But this value is not enough for some cases.
        // NOTE: use 0 for infinite timeout
        webClient.getOptions().setTimeout(5 * 60 * 1000);

        webClient.getOptions().setRedirectEnabled(true);
        webClient.getOptions().setJavaScriptEnabled(true);
        webClient.getOptions().setThrowExceptionOnScriptError(true);
        webClient.getOptions().setPrintContentOnFailingStatusCode(true);

        // Hide CSS Warnings
        webClient.setCssErrorHandler(new SilentCssErrorHandler());

        // Suppress warnings like: "Expected content type ... but got ..."
        webClient.setIncorrectnessListener(new IncorrectnessListener() {

            //                private final Log log = LogFactory.getLog( this.getClass() );

            @Override
            public void notify( final String message, final Object origin ) {

                //                    log.warn( message );
            }
        });

        if (!Boolean.parseBoolean(System.getProperty(ALLOW_META_REFRESH_TAG))) {

            /*
             * Fix for refresh meta tags eg. "<meta http-equiv="refresh" content="300">"
             * The default refresh handler is with Thread.sleep(refreshSecondsFromMetaTag) in the main thread!!!
                 *
                 * Maybe we should check and test this handler: webClient.setRefreshHandler( new ThreadedRefreshHandler() );
             */
            webClient.setRefreshHandler(new RefreshHandler() {

                @Override
                public void handleRefresh( Page page, URL url, int seconds ) throws IOException {

                }
            });
        }

        /*
         * Fix JSessionId
         */

        // WebConnectionWrapper constructs a WebConnection object wrapping the connection of the WebClient
        // and places itself (in the constructor) as connection of the WebClient.
        new WebConnectionWrapper(webClient) {

            public WebResponse getResponse( WebRequest request ) throws IOException {

                Cookie jsCookie = webClient.getCookieManager().getCookie("JSESSIONID");
                if (jsCookie != null && (!jsCookie.getValue().startsWith("\"")
                                         && !jsCookie.getValue().endsWith("\""))) {

                    Cookie newCookie = new Cookie(jsCookie.getDomain(), jsCookie.getName(),
                                                  "\"" + jsCookie.getValue() + "\"", jsCookie.getPath(),
                                                  jsCookie.getExpires(), jsCookie.isSecure());

                    webClient.getCookieManager().removeCookie(jsCookie);
                    webClient.getCookieManager().addCookie(newCookie);
                }
                return super.getResponse(request);
            }
        };
    } catch (Exception e) {

        throw new SeleniumOperationException("Error retrieving internal Selenium web client", e);
    } finally {

        if (webClientField != null) {
            webClientField.setAccessible(fieldAccessibleState);
        }
    }
}
 
Example #3
Source File: SandboxServerTest.java    From uber-java-client with MIT License 4 votes vote down vote up
/**
 * Initiates OAuth authorization using a mock chrome browser and retrieves and access token
 * @throws Exception
 */
private void retrieveAccessToken() throws Exception {
    final WebClient webClient = new WebClient(BrowserVersion.CHROME);
    webClient.setWebConnection(new WebConnectionWrapper(webClient) {
        @Override
        public WebResponse getResponse(final WebRequest request) throws IOException {

            WebResponse response = super.getResponse(request);
            String location = response.getResponseHeaderValue("location");
            if (response.getStatusCode() == 302 && location != null && location.startsWith(client.getClientRedirectUri())) {

                location = location.replace(client.getClientRedirectUri() + "?", "");
                String[] nameValues = location.split("&");
                for (String nameValue : nameValues) {
                    int idx = nameValue.indexOf("=");
                    if ("code".equals(URLDecoder.decode(nameValue.substring(0, idx), "UTF-8"))) {
                        String authorizationCode = URLDecoder.decode(nameValue.substring(idx + 1), "UTF-8");
                        AccessToken accessToken = client.getAuthService().requestAccessToken(clientId, clientSecret, redirectUrl, UberAuthService.GRANT_TYPE_AUTHORIZATION_CODE, authorizationCode, null);
                        client.setAccessToken(accessToken.getAccessToken());
                        client.setRefreshToken(accessToken.getRefreshToken());
                        break;
                    }
                }

                //return empty response
                request.setUrl(new URL("http://redirect"));
                WebResponseData data = new WebResponseData("".getBytes(), 200, "OK", Collections.EMPTY_LIST);
                return new WebResponse(data, request, 10);

            }
            return response;
        }
    });
    webClient.setAjaxController(new NicelyResynchronizingAjaxController());
    webClient.getOptions().setRedirectEnabled(true);
    webClient.getOptions().setThrowExceptionOnScriptError(false);
    webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
    webClient.getOptions().setCssEnabled(true);
    webClient.getOptions().setJavaScriptEnabled(false);
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCookieManager().setCookiesEnabled(true);

    String authUrl = Utils.generateAuthorizeUrl(client.getOAuthUri(), clientId, new String[]{UberAuthService.SCOPE_PROFILE, UberAuthService.SCOPE_HISTORY_LITE, UberAuthService.SCOPE_REQUEST});
    final HtmlPage loginPage = webClient.getPage(authUrl);
    final HtmlForm form = loginPage.getForms().get(0);
    final HtmlTextInput emailInputText = form.getInputByName("email");
    final HtmlPasswordInput passwordInputText = form.getInputByName("password");
    final HtmlButton submitButton = (HtmlButton) form.getByXPath("//button[@type='submit']").get(0);
    emailInputText.setText(username);
    passwordInputText.setText(password);
    final Page scopePage = submitButton.click();
    /**
     * If the user already accepted scope permissions, the accept screen is skipped and the user will be forwarded to the authorization code redirect
     */
    //check for the Accept html page
    if (scopePage instanceof HtmlPage) {
        //click accept button
        if (((HtmlPage)scopePage).getForms().size() > 0) {
            final HtmlForm form2 = ((HtmlPage) scopePage).getForms().get(0);
            final HtmlButton allowButton = (HtmlButton) form2.getByXPath("//button[@value='yes']").get(0);
            allowButton.click();
        }
    }
}