Java Code Examples for com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException

The following examples show how to use com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException. These examples are extracted from open source projects. 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 Project: htmlunit   Source File: BaseFrameElement.java    License: Apache License 2.0 6 votes vote down vote up
private void init() {
    FrameWindow enclosedWindow = null;
    try {
        final HtmlPage htmlPage = getHtmlPageOrNull();
        if (null != htmlPage) { // if loaded as part of XHR.responseXML, don't load content
            enclosedWindow = new FrameWindow(this);
            // put about:blank in the window to allow JS to run on this frame before the
            // real content is loaded
            final WebClient webClient = htmlPage.getWebClient();
            final HtmlPage temporaryPage = webClient.getPage(enclosedWindow, WebRequest.newAboutBlankRequest());
            temporaryPage.setReadyState(READY_STATE_LOADING);
        }
    }
    catch (final FailingHttpStatusCodeException | IOException e) {
        // should never occur
    }
    enclosedWindow_ = enclosedWindow;
}
 
Example 2
@Test
public void listTest() throws FailingHttpStatusCodeException, MalformedURLException, IOException {
    final WebClient webClient = new WebClient();

    webClient.addRequestHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP
                                                                                        // 1.1.
    webClient.addRequestHeader("Pragma", "no-cache"); // HTTP 1.0.
    webClient.addRequestHeader("Expires", "0"); //
    final HtmlPage page = webClient.getPage(contextPath.toExternalForm() + "/testServlet");

    final String pageAsText = page.asText();

    System.out.println(pageAsText);

    webClient.closeAllWindows();

}
 
Example 3
Source Project: krazo   Source File: ValidationIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFormControllerFail() throws Exception {
    final HtmlPage page = webClient.getPage(webUrl);
    final HtmlForm form = page.getFormByName("form");
    final HtmlTextInput name = form.getInputByName("name");
    final HtmlTextInput age = form.getInputByName("age");
    final HtmlSubmitInput button = form.getInputByName("button");
    name.setValueAttribute("john");
    age.setValueAttribute("2");         // Not old enough!
    try {
        button.click();
        fail("Validation error expected in form submission");
    } catch (FailingHttpStatusCodeException e) {
        assertTrue(e.getStatusCode() == 400);
        assertTrue(e.getResponse().getContentAsString().contains("<h1>Form Error</h1>"));
        assertTrue(e.getResponse().getContentAsString().contains("<p>Param: age</p>"));
    }
}
 
Example 4
Source Project: krazo   Source File: CsrfIT.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves a form, removes CSRF hidden field and attempts to submit. Should
 * result in a 403 error.
 *
 * @throws Exception an error occurs or validation fails.
 */
@Test
public void testFormFail() throws Exception {
    HtmlPage page1 = webClient.getPage(webUrl + "resources/csrf");
    HtmlForm form = (HtmlForm) page1.getDocumentElement().getElementsByTagName("form").get(0);

    // Remove hidden input field to cause a CSRF validation failure
    HtmlElement input = form.getElementsByTagName("input").get(1);
    form.removeChild(input);

    // Submit form - should fail
    HtmlSubmitInput button = (HtmlSubmitInput) form.getElementsByTagName("input").get(0);
    try {
        button.click();
        fail("CSRF validation should have failed!");
    } catch (FailingHttpStatusCodeException e) {
        // falls through
    }
}
 
Example 5
Source Project: quarkus   Source File: CodeFlowTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testIdTokenInjectionJwtMethodButPostMethodUsed() throws IOException, InterruptedException {
    try (final WebClient webClient = createWebClient()) {
        HtmlPage page = webClient.getPage("http://localhost:8081/web-app/callback-jwt-not-used-before-redirect");
        assertNotNull(getStateCookieStateParam(webClient, "tenant-jwt-not-used"));
        assertNull(getStateCookieSavedPath(webClient, "tenant-jwt-not-used"));

        assertEquals("Log in to quarkus", page.getTitleText());

        HtmlForm loginForm = page.getForms().get(0);

        loginForm.getInputByName("username").setValueAttribute("alice");
        loginForm.getInputByName("password").setValueAttribute("alice");

        try {
            loginForm.getInputByName("login").click();
            fail("401 status error is expected");
        } catch (FailingHttpStatusCodeException ex) {
            assertEquals(401, ex.getStatusCode());
        }

        webClient.getCookieManager().clearCookies();
    }
}
 
Example 6
Source Project: quarkus   Source File: CodeFlowTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticationCompletionFailedNoStateCookie() throws IOException, InterruptedException {
    // tenant-3 configuration uses a '/some/other/path' redirect parameter which does not have the same root
    // as the original request which is 'web-app', as a result, when the user is returned back to Quarkus
    // to '/some/other/path' no state cookie is detected.
    try (final WebClient webClient = createWebClient()) {
        HtmlPage page = webClient.getPage("http://localhost:8081/web-app/callback-before-redirect?tenantId=tenant-3");
        assertEquals("Log in to quarkus", page.getTitleText());

        HtmlForm loginForm = page.getForms().get(0);

        loginForm.getInputByName("username").setValueAttribute("alice");
        loginForm.getInputByName("password").setValueAttribute("alice");
        try {
            loginForm.getInputByName("login").click();
            fail("401 status error is expected");
        } catch (FailingHttpStatusCodeException ex) {
            assertEquals(401, ex.getStatusCode());
        }
        webClient.getCookieManager().clearCookies();
    }
}
 
Example 7
Source Project: quarkus   Source File: CodeFlowTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticationCompletionFailedWrongRedirectUri() throws IOException, InterruptedException {
    // CustomTenantResolver will return null for an empty tenantId which will lead to the default configuration
    // being used and result in '/web-app/callback-before-redirect' be used as an initial redirect_uri parameter.
    // When the user is redirected back, CustomTenantResolver will resolve a 'tenant-1' configuration with
    // a redirect_uri '/web-app/callback-after-redirect' which will cause a code to token exchange failure
    try (final WebClient webClient = createWebClient()) {
        HtmlPage page = webClient.getPage("http://localhost:8081/web-app/callback-before-redirect?tenantId");
        assertEquals("Log in to quarkus", page.getTitleText());

        HtmlForm loginForm = page.getForms().get(0);

        loginForm.getInputByName("username").setValueAttribute("alice");
        loginForm.getInputByName("password").setValueAttribute("alice");
        try {
            page = loginForm.getInputByName("login").click();
            fail("401 status error is expected: " + page.getBody().asText());
        } catch (FailingHttpStatusCodeException ex) {
            assertEquals(401, ex.getStatusCode());
        }
        webClient.getCookieManager().clearCookies();
    }
}
 
Example 8
@Test
public void requestAuthorizeClientWhenInvalidClientThenStatusBadRequest() throws Exception {
	HtmlPage page = this.webClient.getPage("/");

	ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("google");

	HtmlAnchor clientAnchorElement = this.getClientAnchorElement(page, clientRegistration);
	assertThat(clientAnchorElement).isNotNull();
	clientAnchorElement.setAttribute("href", clientAnchorElement.getHrefAttribute() + "-invalid");

	WebResponse response = null;
	try {
		clientAnchorElement.click();
	} catch (FailingHttpStatusCodeException ex) {
		response = ex.getResponse();
	}

	assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
}
 
Example 9
Source Project: ozark   Source File: ValidationIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFormControllerFail() throws Exception {
    final HtmlPage page = webClient.getPage(webUrl);
    final HtmlForm form = page.getFormByName("form");
    final HtmlTextInput name = form.getInputByName("name");
    final HtmlTextInput age = form.getInputByName("age");
    final HtmlSubmitInput button = form.getInputByName("button");
    name.setValueAttribute("john");
    age.setValueAttribute("2");         // Not old enough!
    try {
        button.click();
        fail("Validation error expected in form submission");
    } catch (FailingHttpStatusCodeException e) {
        assertTrue(e.getStatusCode() == 400);
        assertTrue(e.getResponse().getContentAsString().contains("<h1>Form Error</h1>"));
        assertTrue(e.getResponse().getContentAsString().contains("<p>Param: age</p>"));
    }
}
 
Example 10
Source Project: ozark   Source File: ValidationIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFormControllerPropertyFail() throws Exception {
    final HtmlPage page = webClient.getPage(webUrl + "indexprop.html");
    final HtmlForm form = page.getFormByName("form");
    final HtmlTextInput name = form.getInputByName("name");
    final HtmlTextInput age = form.getInputByName("age");
    final HtmlSubmitInput button = form.getInputByName("button");
    name.setValueAttribute("john");
    age.setValueAttribute("2");         // Not old enough!
    try {
        button.click();
        fail("Validation error expected in form submission");
    } catch (FailingHttpStatusCodeException e) {
        assertTrue(e.getStatusCode() == 400);
        assertTrue(e.getResponse().getContentAsString().contains("<h1>Form Error</h1>"));
        assertTrue(e.getResponse().getContentAsString().contains("<p>Param: age</p>"));
    }
}
 
Example 11
Source Project: ozark   Source File: CsrfIT.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves a form, removes CSRF hidden field and attempts to submit. Should
 * result in a 403 error.
 *
 * @throws Exception an error occurs or validation fails.
 */
@Test
public void testFormFail() throws Exception {
    HtmlPage page1 = webClient.getPage(webUrl + "resources/csrf");
    HtmlForm form = (HtmlForm) page1.getDocumentElement().getHtmlElementsByTagName("form").get(0);

    // Remove hidden input field to cause a CSRF validation failure
    HtmlElement input = form.getHtmlElementsByTagName("input").get(1);
    form.removeChild(input);

    // Submit form - should fail
    HtmlSubmitInput button = (HtmlSubmitInput) form.getHtmlElementsByTagName("input").get(0);
    try {
        button.click();
        fail("CSRF validation should have failed!");
    } catch (FailingHttpStatusCodeException e) {
        // falls through
    }
}
 
Example 12
/**
 * Returns the landing HtmlPage after joining the game
 *
 * @param gameID
 * @param isAttacker
 * @return
 * @throws FailingHttpStatusCodeException
 * @throws IOException
 */
public HtmlPage joinOpenGame(int gameID, boolean isAttacker) throws FailingHttpStatusCodeException, IOException {
	HtmlPage openGames = browser.getPage(codedefendersHome + Paths.GAMES_OVERVIEW);

	// Really we can simply click on that link once we know the gameID,
	// no need to go to openGame page
	HtmlAnchor joinLink = null;
	for (HtmlAnchor a : openGames.getAnchors()) {
		if (a.getHrefAttribute()
				.contains(Paths.BATTLEGROUND_GAME + "?" + ((isAttacker) ? "attacker" : "defender") + "=1&gameId=" + gameID)) {
			joinLink = a;
			break;
		}
	}
	if (!joinLink.getHrefAttribute().startsWith(codedefendersHome + "/")) {
		joinLink.setAttribute("href", codedefendersHome + "/" + joinLink.getHrefAttribute());
	}

	return joinLink.click();
}
 
Example 13
public void attack(int gameId, String mutant) throws FailingHttpStatusCodeException, IOException {
	WebRequest attackRequest = new WebRequest(new URL(codedefendersHome + Paths.BATTLEGROUND_GAME), HttpMethod.POST);
	// // Then we set the request parameters
	attackRequest.setRequestParameters(Arrays.asList(new NameValuePair[] {
			new NameValuePair("formType", "createMutant"), new NameValuePair("gameId", "" + gameId),
			// TODO Encoded somehow ?
			new NameValuePair("mutant", "" + mutant) }));
	// curl -X POST \
	// --data "formType=createMutant&gameId=${gameId}" \
	// --data-urlencode [email protected]${mutant} \
	// --cookie "${cookie}" --cookie-jar "${cookie}" \
	// -w @curl-format.txt \
	// -s ${CODE_DEFENDER_URL}/multiplayergame
	browser.getPage(attackRequest);

}
 
Example 14
public void acceptEquivalence(int gameId)
		throws FailingHttpStatusCodeException, MalformedURLException, IOException {
	// codedefendersHome+"/multiplayer/
	HtmlPage playPage = browser.getPage(codedefendersHome + "" + Paths.BATTLEGROUND_GAME + "?gameId=" + gameId);
	HtmlAnchor acceptEquivalenceLink = null;
	for (HtmlAnchor a : playPage.getAnchors()) {
		if (a.getHrefAttribute().contains(Paths.BATTLEGROUND_GAME + "?acceptEquivalent=")) {
			acceptEquivalenceLink = a;
			break;
		}
	}

	if (!acceptEquivalenceLink.getHrefAttribute().startsWith(codedefendersHome + "/")) {
		acceptEquivalenceLink.setAttribute("href",
				codedefendersHome + "/" + acceptEquivalenceLink.getHrefAttribute());
	}

	System.out
			.println("DoubleEquivalenceSubmissionTest.HelperUser.acceptEquivalence() Accepting equivalence on game "
					+ gameId);
	acceptEquivalenceLink.click();
}
 
Example 15
public void joinOpenGame(int gameID, boolean isAttacker) throws FailingHttpStatusCodeException, IOException {
	HtmlPage openGames = browser.getPage("http://localhost:8080" + Paths.GAMES_OVERVIEW);

	// Really we can simply click on that link once we know the gameID,
	// no need to go to openGame page
	HtmlAnchor joinLink = null;
	for (HtmlAnchor a : openGames.getAnchors()) {
		if (a.getHrefAttribute().contains(
				Paths.BATTLEGROUND_GAME + "?" + ((isAttacker) ? "attacker" : "defender") + "=1&gameId=" + gameID)) {
			joinLink = a;
			break;
		}
	}
	if (!joinLink.getHrefAttribute().startsWith("http://localhost:8080/")) {
		joinLink.setAttribute("href", "http://localhost:8080/" + joinLink.getHrefAttribute());
	}
	HtmlPage page = joinLink.click();
}
 
Example 16
public void attack(int gameId, String mutant) throws FailingHttpStatusCodeException, IOException {
	WebRequest attackRequest = new WebRequest(new URL("http://localhost:8080" + Paths.BATTLEGROUND_GAME),
			HttpMethod.POST);
	// // Then we set the request parameters
	attackRequest.setRequestParameters(Arrays.asList(new NameValuePair[] {
			new NameValuePair("formType", "createMutant"), new NameValuePair("gameId", "" + gameId),
			// TODO Encoded somehow ?
			new NameValuePair("mutant", "" + mutant) }));
	// curl -X POST \
	// --data "formType=createMutant&gameId=${gameId}" \
	// --data-urlencode [email protected]${mutant} \
	// --cookie "${cookie}" --cookie-jar "${cookie}" \
	// -w @curl-format.txt \
	// -s ${CODE_DEFENDER_URL}/multiplayergame
	browser.getPage(attackRequest);

}
 
Example 17
public void claimEquivalenceOnLine(int gameId, int line)
		throws FailingHttpStatusCodeException, MalformedURLException, IOException {
	HtmlPage playPage = browser.getPage("http://localhost:8080" + Paths.BATTLEGROUND_GAME + "?gameId=" + gameId);
	HtmlAnchor claimEquivalenceLink = null;
	for (HtmlAnchor a : playPage.getAnchors()) {
		if (a.getHrefAttribute().contains(Paths.BATTLEGROUND_GAME + "?equivLines=" + line)) {
			claimEquivalenceLink = a;
			break;
		}
	}

	if (!claimEquivalenceLink.getHrefAttribute().startsWith("http://localhost:8080/")) {
		claimEquivalenceLink.setAttribute("href",
				"http://localhost:8080/" + claimEquivalenceLink.getHrefAttribute());
	}
	claimEquivalenceLink.click();
}
 
Example 18
public void acceptEquivalence(int gameId)
		throws FailingHttpStatusCodeException, MalformedURLException, IOException {
	// http://localhost:8080/multiplayer/
	HtmlPage playPage = browser.getPage("http://localhost:8080" + Paths.BATTLEGROUND_GAME + "?gameId=" + gameId);
	HtmlAnchor acceptEquivalenceLink = null;
	for (HtmlAnchor a : playPage.getAnchors()) {
		if (a.getHrefAttribute().contains(Paths.BATTLEGROUND_GAME + "?acceptEquivalent=")) {
			acceptEquivalenceLink = a;
			break;
		}
	}

	if (!acceptEquivalenceLink.getHrefAttribute().startsWith("http://localhost:8080/")) {
		acceptEquivalenceLink.setAttribute("href",
				"http://localhost:8080/" + acceptEquivalenceLink.getHrefAttribute());
	}

	System.out.println(
			"DoubleEquivalenceSubmissionTest.HelperUser.acceptEquivalence() Accepting equivalence on game "
					+ gameId);
	acceptEquivalenceLink.click();
}
 
Example 19
Source Project: cxf-fediz   Source File: AbstractOIDCTest.java    License: Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testUsingCodeForOtherClient() throws Exception {
    // Get the code for the first client
    final UriBuilder authorizationUrl = oidcEndpointBuilder("/idp/authorize")
        .queryParam("client_id", confidentialClientId)
        .queryParam("response_type", "code")
        .queryParam("scope", "openid");

    // Login to the OIDC token endpoint + get the authorization code
    final String authorizationCode = loginAndGetAuthorizationCode(authorizationUrl, "alice", "ecila");
    try {
        // Now try and get a token for the second client
        getTokenJson(authorizationCode, publicClientId, null);
        fail();
    } catch (FailingHttpStatusCodeException ex) {
        assertEquals(Status.BAD_REQUEST.getStatusCode(), ex.getStatusCode());
    }
}
 
Example 20
Source Project: htmlunit   Source File: HtmlPage.java    License: Apache License 2.0 5 votes vote down vote up
private void checkRecursion() {
    final StackTraceElement[] elements = new Exception().getStackTrace();
    if (elements.length > 500) {
        for (int i = 0; i < 500; i++) {
            if (!elements[i].getClassName().startsWith("com.gargoylesoftware.htmlunit.")) {
                return;
            }
        }
        final WebResponse webResponse = getWebResponse();
        throw new FailingHttpStatusCodeException("Too much redirect for "
                + webResponse.getWebRequest().getUrl(), webResponse);
    }
}
 
Example 21
Source Project: htmlunit   Source File: HtmlPage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Loads the content of the contained frames. This is done after the page is completely loaded, to allow script
 * contained in the frames to reference elements from the page located after the closing &lt;/frame&gt; tag.
 * @throws FailingHttpStatusCodeException if the server returns a failing status code AND the property
 *         {@link WebClient#setThrowExceptionOnFailingStatusCode(boolean)} is set to {@code true}
 */
void loadFrames() throws FailingHttpStatusCodeException {
    for (final FrameWindow w : getFrames()) {
        final BaseFrameElement frame = w.getFrameElement();
        // test if the frame should really be loaded:
        // if a script has already changed its content, it should be skipped
        // use == and not equals(...) to identify initial content (versus URL set to "about:blank")
        if (frame.getEnclosedWindow() != null
                && WebClient.URL_ABOUT_BLANK == frame.getEnclosedPage().getUrl()
                && !frame.isContentLoaded()) {
            frame.loadInnerPage();
        }
    }
}
 
Example 22
Source Project: htmlunit   Source File: BaseFrameElement.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
 *
 * Called after the node for the {@code frame} or {@code iframe} has been added to the containing page.
 * The node needs to be added first to allow JavaScript in the frame to see the frame in the parent.
 * @throws FailingHttpStatusCodeException if the server returns a failing status code AND the property
 *      {@link com.gargoylesoftware.htmlunit.WebClientOptions#setThrowExceptionOnFailingStatusCode(boolean)} is
 *      set to true
 */

public void loadInnerPage() throws FailingHttpStatusCodeException {
    String source = getSrcAttribute();
    if (source.isEmpty() || StringUtils.startsWithIgnoreCase(source, WebClient.ABOUT_SCHEME)) {
        source = WebClient.ABOUT_BLANK;
    }

    loadInnerPageIfPossible(source);

    final Page enclosedPage = getEnclosedPage();
    if (enclosedPage != null && enclosedPage.isHtmlPage()) {
        final HtmlPage htmlPage = (HtmlPage) enclosedPage;

        final AbstractJavaScriptEngine<?> jsEngine = getPage().getWebClient().getJavaScriptEngine();
        if (jsEngine != null && jsEngine.isScriptRunning()) {
            final PostponedAction action = new PostponedAction(getPage()) {
                @Override
                public void execute() throws Exception {
                    htmlPage.setReadyState(READY_STATE_COMPLETE);
                }
            };
            jsEngine.addPostponedAction(action);
        }
        else {
            htmlPage.setReadyState(READY_STATE_COMPLETE);
        }
    }
}
 
Example 23
Source Project: trimou   Source File: TrimouViewEngineTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testController()
        throws FailingHttpStatusCodeException, IOException {
    WebClient webClient = new WebClient();
    WebRequest request = new WebRequest(
            new URL(contextPath, "resources/simple?user=mike"));
    request.setAdditionalHeader("Accept-Language", "cs");
    Page page = webClient.getPage(request);
    String[] parts = page.getWebResponse().getContentAsString().split(":");
    assertEquals(5, parts.length);
    assertTrue(parts[0].endsWith("/resources/simple"));
    assertEquals("mike", parts[1]);
    assertEquals("cs", parts[2]);
    assertEquals(parts[3], parts[4]);
}
 
Example 24
Source Project: htmlunit   Source File: HtmlFrameTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void failingHttpStatusCodeException() throws Exception {
    final String failingHtml = "<html><head><body>Not found</body></html>";

    final String firstHtml
        = "<html><head><title>First</title></head>\n"
        + "<frameset cols='130,*'>\n"
        + "  <frame scrolling='no' name='left' src='" + "failing_url" + "' frameborder='1' />\n"
        + "  <frame scrolling='auto' name='right' src='" + URL_THIRD + "' frameborder='1' />\n"
        + "  <noframes>\n"
        + "    <body>Frames not supported</body>\n"
        + "  </noframes>\n"
        + "</frameset>\n"
        + "</html>";

    final String secondHtml = "<html><head><title>Second</title></head><body></body></html>";
    final String thirdHtml  = "<html><head><title>Third</title></head><body></body></html>";

    final WebClient webClient = getWebClientWithMockWebConnection();

    final MockWebConnection webConnection = getMockWebConnection();
    webConnection.setDefaultResponse(failingHtml, 404, "Not Found", MimeType.TEXT_HTML);
    webConnection.setResponse(URL_FIRST, firstHtml);
    webConnection.setResponse(URL_SECOND, secondHtml);
    webConnection.setResponse(URL_THIRD, thirdHtml);

    try {
        webClient.getPage(URL_FIRST);
        fail("Expected FailingHttpStatusCodeException");
    }
    catch (final FailingHttpStatusCodeException e) {
        assertEquals(404, e.getStatusCode());
    }
}
 
Example 25
Source Project: audit-log-plugin   Source File: UserLoginListenerTest.java    License: MIT License 5 votes vote down vote up
@Issue("JENKINS-54087")
@Test
public void testInvalidUserLoginFailsWithError() throws Exception {

    expectedException.expect(FailingHttpStatusCodeException.class);
    expectedException.expectMessage(containsString("Unauthorized"));
    client.login("john", "john");

    assertEventCount(app.getEvents(), 0);
}
 
Example 26
Source Project: HtmlUnit-Android   Source File: HtmlPage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Loads the content of the contained frames. This is done after the page is completely loaded, to allow script
 * contained in the frames to reference elements from the page located after the closing &lt;/frame&gt; tag.
 * @throws FailingHttpStatusCodeException if the server returns a failing status code AND the property
 *         {@link WebClient#setThrowExceptionOnFailingStatusCode(boolean)} is set to {@code true}
 */
void loadFrames() throws FailingHttpStatusCodeException {
    for (final FrameWindow w : getFrames()) {
        final BaseFrameElement frame = w.getFrameElement();
        // test if the frame should really be loaded:
        // if a script has already changed its content, it should be skipped
        // use == and not equals(...) to identify initial content (versus URL set to "about:blank")
        if (frame.getEnclosedWindow() != null
                && WebClient.URL_ABOUT_BLANK == frame.getEnclosedPage().getUrl()
                && !frame.isContentLoaded()) {
            frame.loadInnerPage();
        }
    }
}
 
Example 27
Source Project: HtmlUnit-Android   Source File: BaseFrameElement.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
 *
 * Called after the node for the {@code frame} or {@code iframe} has been added to the containing page.
 * The node needs to be added first to allow JavaScript in the frame to see the frame in the parent.
 * @throws FailingHttpStatusCodeException if the server returns a failing status code AND the property
 *      {@link com.gargoylesoftware.htmlunit.WebClientOptions#setThrowExceptionOnFailingStatusCode(boolean)} is
 *      set to true
 */

public void loadInnerPage() throws FailingHttpStatusCodeException {
    String source = getSrcAttribute();
    if (source.isEmpty() || StringUtils.startsWithIgnoreCase(source, WebClient.ABOUT_SCHEME)) {
        source = WebClient.ABOUT_BLANK;
    }

    loadInnerPageIfPossible(source);

    final Page enclosedPage = getEnclosedPage();
    if (enclosedPage != null && enclosedPage.isHtmlPage()) {
        final HtmlPage htmlPage = (HtmlPage) enclosedPage;
        final AbstractJavaScriptEngine<?> jsEngine = getPage().getWebClient().getJavaScriptEngine();
        if (jsEngine.isScriptRunning()) {
            final PostponedAction action = new PostponedAction(getPage()) {
                @Override
                public void execute() throws Exception {
                    htmlPage.setReadyState(READY_STATE_COMPLETE);
                }
            };
            jsEngine.addPostponedAction(action);
        }
        else {
            htmlPage.setReadyState(READY_STATE_COMPLETE);
        }
    }
}
 
Example 28
Source Project: cxf-fediz   Source File: AbstractTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTedUserNoAccess() throws Exception {
    String url = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName()
        + "/secure/user/fedservlet";
    String user = "ted";
    String password = "det";

    try {
        HTTPTestUtils.login(url, user, password, getIdpHttpsPort(), getLoginFormName());
        Assert.fail("Exception expected");
    } catch (FailingHttpStatusCodeException ex) {
        Assert.assertEquals(ex.getStatusCode(), 403);
    }
}
 
Example 29
Source Project: krazo   Source File: ReturnsIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMyViewableNull() throws Exception {
    try {
        final HtmlPage page = webClient.getPage(webUrl + "resources/myviewable/null");
    } catch (FailingHttpStatusCodeException e) {
        assertEquals(e.getStatusCode(), 500);
        return;
    }
    fail();
}
 
Example 30
private WebResponse followLinkDisableRedirects(HtmlAnchor anchorElement) throws Exception {
	WebResponse response = null;
	try {
		// Disable the automatic redirection (which will trigger
		// an exception) so that we can capture the response
		this.webClient.getOptions().setRedirectEnabled(false);
		anchorElement.click();
	} catch (FailingHttpStatusCodeException ex) {
		response = ex.getResponse();
		this.webClient.getOptions().setRedirectEnabled(true);
	}
	return response;
}