com.gargoylesoftware.htmlunit.html.HtmlAnchor Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.html.HtmlAnchor. 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: JUnitResultArchiverTest.java    From junit-plugin with MIT License 6 votes vote down vote up
@Test public void specialCharsInRelativePath() throws Exception {
    Assume.assumeFalse(Functions.isWindows());
    final String ID_PREFIX = "test-../a=%3C%7C%23)/testReport/org.twia.vendor/VendorManagerTest/testCreateAdjustingFirm/";
    final String EXPECTED = "org.twia.dao.DAOException: [S2001] Hibernate encountered an error updating Claim [null]";

    MatrixProject p = j.jenkins.createProject(MatrixProject.class, "test-" + j.jenkins.getItems().size());
    p.setAxes(new AxisList(new TextAxis("a", "<|#)")));
    p.setScm(new SingleFileSCM("report.xml", getClass().getResource("junit-report-20090516.xml")));
    p.getPublishersList().add(new JUnitResultArchiver("report.xml"));

    MatrixBuild b = p.scheduleBuild2(0).get();
    j.assertBuildStatus(Result.UNSTABLE, b);

    WebClient wc = j.createWebClient();
    HtmlPage page = wc.getPage(b, "testReport");

    assertThat(page.asText(), not(containsString(EXPECTED)));

    ((HtmlAnchor) page.getElementById(ID_PREFIX + "-showlink")).click();
    wc.waitForBackgroundJavaScript(10000L);
    assertThat(page.asText(), containsString(EXPECTED));

    ((HtmlAnchor) page.getElementById(ID_PREFIX + "-hidelink")).click();
    wc.waitForBackgroundJavaScript(10000L);
    assertThat(page.asText(), not(containsString(EXPECTED)));
}
 
Example #2
Source File: HelperUser.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #3
Source File: HTMLAnchorElement.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the {@code password} attribute.
 * @param password {@code password} attribute
 */
@JsxSetter({CHROME, FF, FF68, FF60})
public void setPassword(final String password) {
    try {
        final HtmlAnchor anchor = (HtmlAnchor) getDomNodeOrDie();
        final String href = anchor.getHrefAttribute();
        if (href == ATTRIBUTE_NOT_DEFINED) {
            return;
        }

        final URL url = ((HtmlPage) anchor.getPage()).getFullyQualifiedUrl(href);
        setUrl(UrlUtils.getUrlWithNewUserPassword(url, password));
    }
    catch (final MalformedURLException e) {
        // ignore
    }
}
 
Example #4
Source File: HelperUser.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void claimEquivalenceOnLine(int gameId, int line)
		throws FailingHttpStatusCodeException, MalformedURLException, IOException {
	HtmlPage playPage = browser.getPage(codedefendersHome + "" + 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(codedefendersHome + "/")) {
		claimEquivalenceLink.setAttribute("href",
				codedefendersHome + "/" + claimEquivalenceLink.getHrefAttribute());
	}
	claimEquivalenceLink.click();
}
 
Example #5
Source File: HTMLAnchorElement.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
static String getDefaultValue(final HtmlElement element) {
    String href = element.getAttributeDirect("href");

    if (DomElement.ATTRIBUTE_NOT_DEFINED == href) {
        return ""; // for example for named anchors
    }

    href = href.trim();

    final SgmlPage page = element.getPage();
    if (page == null || !page.isHtmlPage()) {
        return href;
    }

    try {
        return HtmlAnchor.getTargetUrl(href, (HtmlPage) page).toExternalForm();
    }
    catch (final MalformedURLException e) {
        return href;
    }
}
 
Example #6
Source File: DoubleEquivalenceSubmissionTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #7
Source File: DoubleEquivalenceSubmissionTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #8
Source File: Window.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private boolean matches(final Object object) {
    if (object instanceof HtmlEmbed
        || object instanceof HtmlForm
        || object instanceof HtmlImage
        || object instanceof HtmlObject) {
        return true;
    }

    return includeFormFields_
            && (object instanceof HtmlAnchor
                || object instanceof HtmlButton
                || object instanceof HtmlInput
                || object instanceof HtmlMap
                || object instanceof HtmlSelect
                || object instanceof HtmlTextArea);
}
 
Example #9
Source File: DoubleEquivalenceSubmissionTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #10
Source File: HTMLAnchorElement.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the value of this link's {@code href} property.
 * @return the value of this link's {@code href} property
 */
@JsxGetter
public String getHref() {
    final HtmlAnchor anchor = (HtmlAnchor) getDomNodeOrDie();
    final String hrefAttr = anchor.getHrefAttribute();

    if (hrefAttr == DomElement.ATTRIBUTE_NOT_DEFINED) {
        return "";
    }

    try {
        return getUrl().toString();
    }
    catch (final MalformedURLException e) {
        return hrefAttr;
    }
}
 
Example #11
Source File: Document.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the value of the JavaScript property {@code anchors}.
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms537435.aspx">MSDN documentation</a>
 * @see <a href="http://www.mozilla.org/docs/dom/domref/dom_doc_ref4.html#1024543">
 * Gecko DOM reference</a>
 * @return the value of this property
 */
@JsxGetter({CHROME, IE})
public Object getAnchors() {
    return new HTMLCollection(getDomNodeOrDie(), true) {
        @Override
        protected boolean isMatching(final DomNode node) {
            if (!(node instanceof HtmlAnchor)) {
                return false;
            }
            final HtmlAnchor anchor = (HtmlAnchor) node;
            if (getBrowserVersion().hasFeature(JS_ANCHORS_REQUIRES_NAME_OR_ID)) {
                return anchor.hasAttribute("name") || anchor.hasAttribute("id");
            }
            return anchor.hasAttribute("name");
        }

        @Override
        protected EffectOnCache getEffectOnCache(final HtmlAttributeChangeEvent event) {
            if ("name".equals(event.getName()) || "id".equals(event.getName())) {
                return EffectOnCache.RESET;
            }
            return EffectOnCache.NONE;
        }
    };
}
 
Example #12
Source File: HTMLAnchorElement.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the {@code username} attribute.
 * @param username {@code username} attribute
 */
@JsxSetter({CHROME, FF, FF68, FF60})
public void setUsername(final String username) {
    try {
        final HtmlAnchor anchor = (HtmlAnchor) getDomNodeOrDie();
        final String href = anchor.getHrefAttribute();
        if (href == ATTRIBUTE_NOT_DEFINED) {
            return;
        }

        final URL url = ((HtmlPage) anchor.getPage()).getFullyQualifiedUrl(href);
        setUrl(UrlUtils.getUrlWithNewUserName(url, username));
    }
    catch (final MalformedURLException e) {
        // ignore
    }
}
 
Example #13
Source File: HelperUser.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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 #14
Source File: HTMLAnchorElementTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void readWriteAnchorHost() throws Exception {
    final String html
        = "<html>\n"
        + "<body onload=\"document.links[0].host += 'motion:8080';\n"
        + "    document.links[1].host += 'motion';\n"
        + "    document.links[2].host += '80';\n"
        + "    document.links[3].host = 'www.gargoylesoftware.com'; \">\n"
        + "  <a href='foo.html#O'>link 0</a>\n"
        + "  <a href='foo.html#O'>link 1</a>\n"
        + "  <a href='http://www.gargoylesoftware.com:80/foo.html#O'>link 2</a>\n"
        + "  <a href='http://www.gargoylesoftware.com:80/foo.html#O'>link 3</a>\n"
        + "</body></html>";
    final HtmlPage page = loadPage(getBrowserVersion(), html, null, URL_GARGOYLE);
    HtmlAnchor link = page.getAnchors().get(0);
    assertEquals("http://www.gargoylesoftware.commotion:8080/foo.html#O", link.getHrefAttribute());
    link = page.getAnchors().get(1);
    assertEquals("http://www.gargoylesoftware.commotion/foo.html#O", link.getHrefAttribute());
    link = page.getAnchors().get(2);
    assertEquals("http://www.gargoylesoftware.com:8080/foo.html#O", link.getHrefAttribute());
    link = page.getAnchors().get(3);
    assertEquals("http://www.gargoylesoftware.com/foo.html#O", link.getHrefAttribute());
}
 
Example #15
Source File: HTMLAnchorElementTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void readWriteAnchorPort() throws Exception {
    final String html
        = "<html>\n"
        + "<body onload=\"document.links[0].port += '80';\n"
        + "    document.links[1].port += '80'; \">\n"
        + "  <a href='foo.html#O'>link 1</a>\n"
        + "  <a href='http://www.gargoylesoftware.com:80/foo.html#O'>link 1</a>\n"
        + "</body></html>";
    final HtmlPage page = loadPage(getBrowserVersion(), html, null, URL_GARGOYLE);
    HtmlAnchor link = page.getAnchors().get(0);
    assertEquals("http://www.gargoylesoftware.com:80/foo.html#O", link.getHrefAttribute());
    link = page.getAnchors().get(1);
    assertEquals("http://www.gargoylesoftware.com:8080/foo.html#O", link.getHrefAttribute());
}
 
Example #16
Source File: HTMLAnchorElement.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the value of this link's {@code href} property.
 * @return the value of this link's {@code href} property
 */
@JsxGetter
public String getHref() {
    final HtmlAnchor anchor = (HtmlAnchor) getDomNodeOrDie();
    final String hrefAttr = anchor.getHrefAttribute();

    if (hrefAttr == DomElement.ATTRIBUTE_NOT_DEFINED) {
        return "";
    }

    try {
        return getUrl().toString();
    }
    catch (final MalformedURLException e) {
        return hrefAttr;
    }
}
 
Example #17
Source File: Document.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the value of the JavaScript property {@code anchors}.
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms537435.aspx">MSDN documentation</a>
 * @see <a href="http://www.mozilla.org/docs/dom/domref/dom_doc_ref4.html#1024543">
 * Gecko DOM reference</a>
 * @return the value of this property
 */
@JsxGetter({CHROME, IE})
public Object getAnchors() {
    return new HTMLCollection(getDomNodeOrDie(), true) {
        @Override
        protected boolean isMatching(final DomNode node) {
            if (!(node instanceof HtmlAnchor)) {
                return false;
            }
            final HtmlAnchor anchor = (HtmlAnchor) node;
            if (getBrowserVersion().hasFeature(JS_ANCHORS_REQUIRES_NAME_OR_ID)) {
                return anchor.hasAttribute("name") || anchor.hasAttribute("id");
            }
            return anchor.hasAttribute("name");
        }

        @Override
        protected EffectOnCache getEffectOnCache(final HtmlAttributeChangeEvent event) {
            if ("name".equals(event.getName()) || "id".equals(event.getName())) {
                return EffectOnCache.RESET;
            }
            return EffectOnCache.NONE;
        }
    };
}
 
Example #18
Source File: Window.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
private boolean matches(final Object object) {
    if (object instanceof HtmlEmbed
        || object instanceof HtmlForm
        || object instanceof HtmlImage
        || object instanceof HtmlObject) {
        return true;
    }
    if (includeFormFields_ && (
            object instanceof HtmlAnchor
            || object instanceof HtmlButton
            || object instanceof HtmlInput
            || object instanceof HtmlMap
            || object instanceof HtmlSelect
            || object instanceof HtmlTextArea)) {
        return true;
    }
    return false;
}
 
Example #19
Source File: HtmlUnitXPathTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if test fails
 */
@Test
public void id() throws Exception {
    final String content = "<html><head><title>foo</title></head>\n"
        + "<body>\n"
        + "<div>\n"
        + "  <a href='link.html' id='test'>\n"
        + "</div>\n"
        + "</body></html>";

    final HtmlPage page = loadPage(content);

    final HtmlAnchor anchor = page.getHtmlElementById("test");
    assertSame(anchor, page.getFirstByXPath("//a[@id='test']"));
    assertSame(anchor, page.getFirstByXPath("//*[@id='test']"));

    assertNull(page.getFirstByXPath("//div[@id='doesNotExist']"));
    assertNull(page.getFirstByXPath("id('doesNotExist')"));
}
 
Example #20
Source File: HTMLAnchorElement.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
static String getDefaultValue(final HtmlElement element) {
    String href = element.getAttributeDirect("href");

    if (DomElement.ATTRIBUTE_NOT_DEFINED == href) {
        return ""; // for example for named anchors
    }

    href = href.trim();

    final SgmlPage page = element.getPage();
    if (page == null || !page.isHtmlPage()) {
        return href;
    }

    try {
        return HtmlAnchor.getTargetUrl(href, (HtmlPage) page).toExternalForm();
    }
    catch (final MalformedURLException e) {
        return href;
    }
}
 
Example #21
Source File: LocationTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that location.reload() works correctly.
 * @throws Exception if the test fails
 */
@Test
public void reload() throws Exception {
    final String content =
          "<html>\n"
        + "  <head><title>test</title></head>\n"
        + "  <body>\n"
        + "    <a href='javascript:window.location.reload();' id='link1'>reload</a>\n"
        + "  </body>\n"
        + "</html>";

    final HtmlPage page1 = loadPage(content);
    final HtmlAnchor link = page1.getHtmlElementById("link1");
    final HtmlPage page2 = link.click();

    assertEquals(page1.getTitleText(), page2.getTitleText());
    assertNotSame(page1, page2);
}
 
Example #22
Source File: DemoApplicationTests.java    From keycloak-springsecurity5-sample with GNU General Public License v3.0 6 votes vote down vote up
@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 #23
Source File: HTMLFormElement2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void formSubmitDoesntCallOnSubmit() throws Exception {
    final String html
        = "<html><head><title>first</title></head><body>\n"
        + "<form name='form1' method='get' action='" + URL_SECOND + "' onsubmit=\"this.action = 'foo.html'\">\n"
        + "  <input type='submit' />\n"
        + "</form>\n"
        + "<a href='javascript:document.form1.submit()' id='link1'>Click me</a>\n"
        + "</body></html>";
    final String secondContent
        = "<html><head><title>second</title></head><body>\n"
        + "<p>hello world</p>\n"
        + "</body></html>";

    getMockWebConnection().setDefaultResponse(secondContent);

    final HtmlPage page = loadPageWithAlerts(html);
    final HtmlAnchor link = page.getHtmlElementById("link1");
    final HtmlPage page2 = link.click();
    assertEquals("second", page2.getTitleText());
}
 
Example #24
Source File: HTMLDocumentWriteTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void writeWithSplitAnchorTag() throws Exception {
    final String html = "<html><body><script>\n"
        + "document.write(\"<a href=\'start.html\");\n"
        + "document.write(\"\'>\");\n"
        + "document.write('click here</a>');\n"
        + "</script>\n"
        + "</body></html>";

    final HtmlPage page = loadPage(html);
    final List<HtmlAnchor> anchorList = page.getAnchors();
    assertEquals(1, anchorList.size());
    final HtmlAnchor anchor = anchorList.get(0);
    assertEquals("start.html", anchor.getHrefAttribute());
    assertEquals("click here", anchor.asText());
}
 
Example #25
Source File: TvMaoCrawler.java    From MyTv with Apache License 2.0 6 votes vote down vote up
/**
 * 抓取指定城市下的所有电视台
 * 
 * @param htmlPage
 * @param city
 * @return
 */
private List<TvStation> getAllTvStationOfCity(HtmlPage htmlPage, String city) {
	List<TvStation> resultList = new ArrayList<TvStation>();
	List<?> elements = htmlPage
			.getByXPath("//div[@class='chlsnav']//div[@class='plst']/parent::*");
	for (int i = 0, size = elements == null ? 0 : elements.size(); i < size; i++) {
		try {
			HtmlAnchor anchor = (HtmlAnchor) elements.get(i);
			String href = anchor.getHrefAttribute();
			if (!href.startsWith("/program/")) {
				continue;
			}
			logger.debug(anchor.getTextContent()
					+ " program table of tvmao: " + ", url: " + href);
			TimeUnit.MILLISECONDS.sleep(getRandomSleepTime());
			HtmlPage p = (HtmlPage) WebCrawler.crawl(TV_MAO_URL_PREFIX
					+ href);
			resultList.addAll(getTvStations(p, city));
		} catch (Exception e) {
			logger.error("error occur while get all tv station of city: "
					+ city, e);
			continue;
		}
	}
	return resultList;
}
 
Example #26
Source File: DemoApplicationTests.java    From keycloak-springsecurity5-sample with GNU General Public License v3.0 5 votes vote down vote up
private void assertLoginPage(HtmlPage page) throws Exception {
	assertThat(page.getTitleText()).isEqualTo("Login Page");

	int expectedClients = 5;

	List<HtmlAnchor> clientAnchorElements = page.getAnchors();
	assertThat(clientAnchorElements.size()).isEqualTo(expectedClients);

	ClientRegistration googleClientRegistration = this.clientRegistrationRepository.findByRegistrationId("google");
	ClientRegistration githubClientRegistration = this.clientRegistrationRepository.findByRegistrationId("github");
	ClientRegistration facebookClientRegistration = this.clientRegistrationRepository.findByRegistrationId("facebook");
	ClientRegistration oktaClientRegistration = this.clientRegistrationRepository.findByRegistrationId("okta");
       ClientRegistration keycloakClientRegistration = this.clientRegistrationRepository.findByRegistrationId("keycloak");

	String baseAuthorizeUri = AUTHORIZATION_BASE_URI + "/";
	String googleClientAuthorizeUri = baseAuthorizeUri + googleClientRegistration.getRegistrationId();
	String githubClientAuthorizeUri = baseAuthorizeUri + githubClientRegistration.getRegistrationId();
	String facebookClientAuthorizeUri = baseAuthorizeUri + facebookClientRegistration.getRegistrationId();
	String oktaClientAuthorizeUri = baseAuthorizeUri + oktaClientRegistration.getRegistrationId();
       String keycloakClientAuthorizeUri = baseAuthorizeUri + keycloakClientRegistration.getRegistrationId();

	for (int i=0; i<expectedClients; i++) {
		assertThat(clientAnchorElements.get(i).getAttribute("href")).isIn(
			googleClientAuthorizeUri, githubClientAuthorizeUri,
			facebookClientAuthorizeUri, oktaClientAuthorizeUri,
               keycloakClientAuthorizeUri);
		assertThat(clientAnchorElements.get(i).asText()).isIn(
			googleClientRegistration.getClientName(),
			githubClientRegistration.getClientName(),
			facebookClientRegistration.getClientName(),
			oktaClientRegistration.getClientName(),
               keycloakClientRegistration.getClientName());
	}
}
 
Example #27
Source File: WebAssert.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that the specified page contains a link with the specified text. The specified text
 * may be a substring of the entire text contained by the link.
 *
 * @param page the page to check
 * @param text the text which a link in the specified page is expected to contain
 */
public static void assertLinkPresentWithText(final HtmlPage page, final String text) {
    boolean found = false;
    for (final HtmlAnchor a : page.getAnchors()) {
        if (a.asText().contains(text)) {
            found = true;
            break;
        }
    }
    if (!found) {
        final String msg = "The page does not contain a link with text '" + text + "'.";
        throw new AssertionError(msg);
    }
}
 
Example #28
Source File: DoubleEquivalenceSubmissionTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void assertNoMoreEquivalenceDuels(int gameId)
		throws FailingHttpStatusCodeException, MalformedURLException, IOException {
	HtmlPage playPage = browser.getPage("http://localhost:8080" + Paths.BATTLEGROUND_GAME + "?gameId=" + gameId);
	for (HtmlAnchor a : playPage.getAnchors()) {
		if (a.getHrefAttribute().contains(Paths.BATTLEGROUND_GAME + "?acceptEquivalent=")) {
			Assert.fail("On game " + gameId + " there is still an equivalence duel open");
		}
	}
}
 
Example #29
Source File: DoubleEquivalenceSubmissionTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void assertThereIsAnEquivalenceDuel(int gameId)
		throws FailingHttpStatusCodeException, MalformedURLException, IOException {
	HtmlPage playPage = browser.getPage("http://localhost:8080" + Paths.BATTLEGROUND_GAME + "?gameId=" + gameId);
	for (HtmlAnchor a : playPage.getAnchors()) {
		if (a.getHrefAttribute().contains(Paths.BATTLEGROUND_GAME + "?acceptEquivalent=")) {
			return;
		}
	}
	Assert.fail("On game " + gameId + " there is no equivalence duels open");

}
 
Example #30
Source File: DemoApplicationTests.java    From keycloak-springsecurity5-sample with GNU General Public License v3.0 5 votes vote down vote up
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;
}