public boolean athenticated() { web = new WebClient(); try { page1 = web.getPage(url); } catch (FailingHttpStatusCodeException | IOException e) { e.printStackTrace(); } HtmlForm form = page1.getFormByName("form2"); form.getInputByName("txtUserName").setAttribute("value", username); form.getInputByName("txtPassword").setAttribute("value", password); try { page2 = form.getInputByName("LoginButton").click(); } catch (ElementNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (page2.getUrl().toString().equals("http://78.39.200.210/Default.aspx")) { return true; } else { web.closeAllWindows(); return false; } }
@Override protected String getCallbackUrl(final HtmlPage authorizationPage) throws Exception { HtmlForm form = authorizationPage.getFormByName("loginform"); final HtmlTextInput login = form.getInputByName("log"); login.setValueAttribute("testscribeup"); final HtmlPasswordInput passwd = form.getInputByName("pwd"); passwd.setValueAttribute("testpwdscribeup"); HtmlElement button = (HtmlElement) authorizationPage.createElement("button"); button.setAttribute("type", "submit"); form.appendChild(button); // HtmlButton button = form.getButtonByName("wp-submit"); final HtmlPage confirmPage = button.click(); form = confirmPage.getFormByName("loginform"); button = (HtmlElement) confirmPage.createElement("button"); button.setAttribute("type", "submit"); form.appendChild(button); // button = form.getButtonByName("wp-submit"); final HtmlPage callbackPage = button.click(); final String callbackUrl = callbackPage.getUrl().toString(); logger.debug("callbackUrl : {}", callbackUrl); return callbackUrl; }
public void testPreviewDiffBug() throws Exception { // https://bugs.corefiling.com/show_bug.cgi?id=13510 // Old versions of the diff_match_patch package have a bug in the diff_cleanupSemantic method // The two comparison strings need to be well crafted to trigger the bug. String name = uniqueWikiPageName("PreviewPageTest"); String content = "=" + NEWLINE_TEXTAREA + "This is a lis of things that someone be doing if" + NEWLINE_TEXTAREA + "===Wiki" + NEWLINE_TEXTAREA; String newContent = "||" + NEWLINE_TEXTAREA + "=="; HtmlPage edited = editWikiPage(name, content, "", "", true); HtmlPage editPage = clickEditLink(edited); HtmlForm form = editPage.getFormByName(ID_EDIT_FORM); HtmlTextArea contentArea = form.getTextAreaByName("content"); contentArea.setText(newContent); editPage = (HtmlPage) form.getInputByValue("Preview").click(); form = editPage.getFormByName(ID_EDIT_FORM); contentArea = form.getTextAreaByName("content"); assertEquals(newContent + NEWLINE_TEXTAREA, contentArea.getText()); }
private void testInvalidSessionIdHelper( final String button, final String name, final String failMsg, final boolean fakeAppendedSessionId) throws IOException, JaxenException { HtmlPage editPage = clickEditLink(getWikiPage(name)); final HtmlForm form = editPage.getFormByName(ID_EDIT_FORM); final HtmlInput sessionId = form.getInputByName("sessionId"); sessionId.setValueAttribute(FAKE_SESSION_ID); if (fakeAppendedSessionId) { form.setActionAttribute(name + ";jsessionid=" + FAKE_SESSION_ID); } final HtmlTextArea content = form.getTextAreaByName("content"); final String expectedContent = "http://www.example.com"; content.setText(expectedContent); editPage = (HtmlPage) form.getInputByValue(button).click(); try { getAnchorByHrefContains(editPage, expectedContent); fail(failMsg); } catch (NoSuchElementException e) { } }
public static void main(String[] args) { WebClient client = new WebClient(BrowserVersion.CHROME); HtmlPage page = null; try { page = client.getPage("http://www.facebook.com"); System.out.println(page.getTitleText()); HtmlForm form = (HtmlForm) page.getElementById("login_form"); form.getInputByName("email").setValueAttribute("*****@*****.**"); form.getInputByName("pass").setValueAttribute("saburtalo16"); page = form.getInputByValue("Log In").click(); System.out.println(page.getTitleText()); HtmlTextArea statusText = (HtmlTextArea) page.getElementByName("xhpc_message_text"); statusText.click(); statusText.setText("I'm a robot"); HtmlButton post = (HtmlButton) page.getFirstByXPath("//button[@id=\"u_jsonp_3_4\"]/div/div[4]/div/ul/li[2]/button"); post.click(); } catch (Exception e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } }
public void testLogInWithOpenIDAndSignUp() throws Exception { openid = createServer(); realm = new HudsonPrivateSecurityRealm(true); hudson.setSecurityRealm(realm); WebClient wc = new WebClient(); // Workaround failing ajax requests to build queue wc.setThrowExceptionOnFailingAjax(false); // Login with OpenID as an unregistered user HtmlPage login = wc.goTo("federatedLoginService/openid/login?from=/"); login .getDocumentElement() .getOneHtmlElementByAttribute("a", "title", "log in with OpenID") .click(); HtmlForm loginForm = getFormById(login, "openid_form"); loginForm.getInputByName("openid").setValueAttribute(openid.url); HtmlPage signUp = (HtmlPage) loginForm.submit(); // Sign up user HtmlForm signUpForm = getFormByAction(signUp, "/securityRealm/createAccountWithFederatedIdentity"); signUpForm.getInputByName("password1").setValueAttribute("x"); signUpForm.getInputByName("password2").setValueAttribute("x"); HtmlPage loggedIn = submit(signUpForm); assertNotNull(loggedIn.getAnchorByHref("/logout")); assertNotNull(loggedIn.getAnchorByHref("/user/aliceW")); wc.goTo("logout"); // Re-login login(wc); }
@Test public void privateView() throws Exception { j.createFreeStyleProject("project1"); User user = User.get("me", true); // create user WebClient wc = j.createWebClient(); HtmlPage userPage = wc.goTo("user/me"); HtmlAnchor privateViewsLink = userPage.getFirstAnchorByText("My Views"); assertNotNull("My Views link not available", privateViewsLink); HtmlPage privateViewsPage = (HtmlPage) privateViewsLink.click(); Text viewLabel = (Text) privateViewsPage.getFirstByXPath("//div[@class='tabBar']//div[@class='tab active']/a/text()"); assertTrue("'All' view should be selected", viewLabel.getTextContent().contains(Hudson_ViewName())); View listView = listView("listView"); HtmlPage newViewPage = wc.goTo("user/me/my-views/newView"); HtmlForm form = newViewPage.getFormByName("createItem"); form.getInputByName("name").setValueAttribute("proxy-view"); ((HtmlRadioButtonInput) form.getInputByValue("hudson.model.ProxyView")).setChecked(true); HtmlPage proxyViewConfigurePage = j.submit(form); View proxyView = user.getProperty(MyViewsProperty.class).getView("proxy-view"); assertNotNull(proxyView); form = proxyViewConfigurePage.getFormByName("viewConfig"); form.getSelectByName("proxiedViewName").setSelectedAttribute("listView", true); j.submit(form); assertTrue(proxyView instanceof ProxyView); assertEquals(((ProxyView) proxyView).getProxiedViewName(), "listView"); assertEquals(((ProxyView) proxyView).getProxiedView(), listView); }
public void testFileItemPersistence() throws Exception { // TODO: write a synchronous connector? byte[] testData = new byte[1024]; for (int i = 0; i < testData.length; i++) testData[i] = (byte) i; Server server = new Server(); SocketConnector connector = new SocketConnector(); server.addConnector(connector); ServletHandler handler = new ServletHandler(); handler.addServletWithMapping(new ServletHolder(new FileItemPersistenceTestServlet()), "/"); server.addHandler(handler); server.start(); localPort = connector.getLocalPort(); try { WebClient wc = new WebClient(); HtmlPage p = (HtmlPage) wc.getPage("http://localhost:" + localPort + '/'); HtmlForm f = p.getFormByName("main"); HtmlFileInput input = (HtmlFileInput) f.getInputByName("test"); input.setData(testData); f.submit(); } finally { server.stop(); } }
public void testDoConfigure() throws Exception { UpdateSite target = new UpdateSite("test1", "http://example.com/test/update-center.json"); // Multiple update site. Jenkins.getInstance().getUpdateCenter().getSites().clear(); Jenkins.getInstance().getUpdateCenter().getSites().add(target); String originalId = target.getId(); WebClient wc = new WebClient(); HtmlPage editSitePage = wc.goTo(String.format("%s/%s", UpdateSitesManager.URL, target.getId())); HtmlForm editSiteForm = editSitePage.getFormByName("editSiteForm"); assertNotNull("There must be editSiteForm", editSiteForm); String newId = "newId"; String newUrl = "http://localhost/update-center.json"; editSiteForm.getInputByName("_.id").setValueAttribute(newId); editSiteForm.getInputByName("_.url").setValueAttribute(newUrl); submit(editSiteForm); UpdateSite site = null; for (UpdateSite s : Jenkins.getInstance().getUpdateCenter().getSites()) { if (newId.equals(s.getId())) { site = s; } assertFalse("id must be updated(old one must not remain)", originalId.equals(s.getId())); } assertNotNull("id must be updated", site); assertEquals("url must be updated", newUrl, site.getUrl()); }
/** * @param forms * @param action * @return */ public static HtmlForm getFormByAction(final List<HtmlForm> forms, final String action) { for (final HtmlForm form : forms) { if (action.equalsIgnoreCase(form.getActionAttribute())) { return form; } } return null; }
/** * Finds the form in the html document that performs the provided action. * * @param action the action to search for. * @param forms the html forms in the document. * @return the form, or null of there is none. */ public static HtmlForm getFormWithAction(String action, List<HtmlForm> forms) { for (HtmlForm f : forms) { if (f.getActionAttribute().equalsIgnoreCase(action)) { return f; } } return null; }
@Override protected String getCallbackUrlForCancel(final HtmlPage authorizationPage) throws Exception { final HtmlForm form = authorizationPage.getForms().get(0); final HtmlSubmitInput submit = form.getInputByValue("Cancel"); final HtmlPage callbackPage = submit.click(); final String callbackUrl = callbackPage.getUrl().toString(); logger.debug("callbackUrl : {}", callbackUrl); return callbackUrl; }
private HtmlForm findForm(HtmlPage page, String action) { for (HtmlForm form : page.getForms()) { if (action.equals(form.getActionAttribute())) { return form; } } fail("no form found"); return null; }
/** {@inheritDoc} */ @Override protected boolean doClickStateUpdate() throws IOException { final HtmlForm form = getEnclosingForm(); if (form != null) { form.reset(); return false; } super.doClickStateUpdate(); return false; }
/** * @param forms * @return */ public static HtmlForm getFormWithPasswordInput(final List<HtmlForm> forms) { for (final HtmlForm form : forms) { for (final HtmlElement input : form.getElementsByTagName("input")) { if (input.getAttribute("type").equalsIgnoreCase("password")) { return form; } } } return null; }
/** * Manual submission form. */ public void testUploadJpi() throws Exception { HtmlPage page = new WebClient().goTo("pluginManager/advanced"); HtmlForm f = page.getFormByName("uploadPlugin"); File dir = env.temporaryDirectoryAllocator.allocate(); File plugin = new File(dir, "tasks.jpi"); FileUtils.copyURLToFile(getClass().getClassLoader().getResource("plugins/tasks.jpi"),plugin); f.getInputByName("name").setValueAttribute(plugin.getAbsolutePath()); submit(f); assertTrue( new File(jenkins.getRootDir(),"plugins/tasks.jpi").exists() ); }
@Ignore("verified manually in Winstone but org.mortbay.JettyResponse.sendRedirect (6.1.26) seems to mangle the location") @Issue("JENKINS-18373") @Test public void unicodeName() throws Exception { HtmlForm form = j.createWebClient().goTo("newView").getFormByName("createItem"); String name = "I ♥ NY"; form.getInputByName("name").setValueAttribute(name); form.getRadioButtonsByName("mode").get(0).setChecked(true); j.submit(form); View view = j.jenkins.getView(name); assertNotNull(view); j.submit(j.createWebClient().getPage(view, "configure").getFormByName("viewConfig")); }
@Test public void enterCredential() throws Exception { HtmlPage p = j.createWebClient().goTo("descriptorByName/hudson.tools.JDKInstaller/enterCredential"); HtmlForm form = p.getFormByName("postCredential"); form.getInputByName("username").setValueAttribute("foo"); form.getInputByName("password").setValueAttribute("bar"); HtmlFormUtil.submit(form, null); DescriptorImpl d = j.jenkins.getDescriptorByType(DescriptorImpl.class); assertEquals("foo", d.getUsername()); assertEquals("bar", d.getPassword().getPlainText()); }
@Issue("JENKINS-16608") @Test public void notAllowedName() throws Exception { HtmlForm form = j.createWebClient().goTo("newView").getFormByName("createItem"); form.getInputByName("name").setValueAttribute(".."); form.getRadioButtonsByName("mode").get(0).setChecked(true); try { j.submit(form); fail("\"..\" should not be allowed."); } catch (FailingHttpStatusCodeException e) { assertEquals(400, e.getStatusCode()); } }
private void login(WebClient wc) throws Exception { HtmlPage login = wc.goTo("federatedLoginService/openid/login?from=/"); login .getDocumentElement() .getOneHtmlElementByAttribute("a", "title", "log in with OpenID") .click(); HtmlForm loginForm = getFormById(login, "openid_form"); loginForm.getInputByName("openid").setValueAttribute(openid.url); HtmlPage loggedIn = (HtmlPage) loginForm.submit(); assertNotNull(loggedIn.getAnchorByHref("/logout")); assertNotNull(loggedIn.getAnchorByHref("/user/aliceW")); }
// Submit the form with no modifications public void testFormInput02_submit01() throws Exception { checkFormInput00(); HtmlPage page = getFormInput02(); checkFormInput02(page, formInput02_pristine); HtmlForm form = getFormById(page, formInput02_name); assertNotNull("form exists", form); HtmlSubmitInput submit = (HtmlSubmitInput) form.getInputByName(formInput02_name + NamingContainer.SEPARATOR_CHAR + "submit"); page = (HtmlPage) submit.click(); checkFormInput02(page, formInput02_pristine); }
/** * Static method for <code>Login</code>. Uses dependencies <b>HttpUnit</b> in connecting to Keats. * * @see com.gargoylesoftware.htmlunit * @param parent The parent window. instanceof<code>Scrape</code>, to set relative locations to * @param link The url of which to retrieve information from. * @param username The username to log in KEATS with. * @param password The password to log in KEATS with. * @return results.asText() Returns the content of the url if login successful. Returns null * otherwise. */ public static String login(Scrape parent, String link, String username, String password) { try { WebClient client = new WebClient(); // Settings client.getOptions().setThrowExceptionOnScriptError(false); client.getOptions().setThrowExceptionOnScriptError(false); client.getOptions().setThrowExceptionOnFailingStatusCode(false); client.getOptions().setJavaScriptEnabled(false); client.getOptions().setCssEnabled(false); client.getOptions().setRedirectEnabled(true); client.getOptions().setUseInsecureSSL(true); client.getCookieManager().setCookiesEnabled(true); HtmlPage page = client.getPage("https://login-keats.kcl.ac.uk/"); HtmlForm form = page.getFirstByXPath("//form[@action='https://keats.kcl.ac.uk/login/index.php']"); HtmlInput usernameInput = form.getInputByName("username"); usernameInput.setValueAttribute(username); HtmlInput passwordInput = form.getInputByName("password"); passwordInput.setValueAttribute(password); page = form.getInputByValue("Log in").click(); HtmlPage results = client.getPage(link); client.closeAllWindows(); return results.asText(); } catch (MalformedURLException e) { JOptionPane.showMessageDialog( parent, "The URL you have provided is not recognised. Please double check your " + "input and try again.", "MalformedURLException found.", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } catch (IOException e) { JOptionPane.showMessageDialog( parent, "An error has occurred when attempting to read information from the " + "server. The input could be interrupted by external processes.", "IOException found.", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } return null; }
private void editThenCancel(final String name) throws Exception { final String flagText = "Should not be saved."; HtmlPage editPage = clickEditLink(getWikiPage(name)); HtmlForm form = editPage.getFormByName(ID_EDIT_FORM); form.getTextAreaByName("content").setText(flagText); HtmlPage viewPage = (HtmlPage) form.getInputByValue("Cancel").click(); assertFalse(viewPage.asText().contains(flagText)); try { viewPage.getFormByName(ID_EDIT_FORM); fail("Should be back to view page, not edit form."); } catch (ElementNotFoundException ignore) { } assertEquals("Should not be present.", 0, viewPage.getByXPath("id('lockedInfo')").size()); }
public void testPreview() throws Exception { String name = uniqueWikiPageName("PreviewPageTest"); HtmlPage editPage = clickEditLink(getWikiPage(name)); HtmlForm form = editPage.getFormByName(ID_EDIT_FORM); HtmlInput minorEdit = form.getInputByName("minorEdit"); assertFalse(minorEdit.isChecked()); minorEdit.setChecked(true); HtmlInput description = form.getInputByName("description"); String expectedDescription = "My test change"; description.setValueAttribute(expectedDescription); HtmlTextArea content = form.getTextAreaByName("content"); String expectedContent = "http://www.example.com"; content.setText(expectedContent); // Now if we preview we should get the previewed text rendered, and in // the edit area. The other options should be preserved too. editPage = (HtmlPage) form.getInputByValue("Preview").click(); form = editPage.getFormByName(ID_EDIT_FORM); minorEdit = form.getInputByName("minorEdit"); description = form.getInputByName("description"); content = form.getTextAreaByName("content"); assertEquals(expectedDescription, description.getValueAttribute()); assertTrue(minorEdit.isChecked()); assertEquals(expectedContent + NEWLINE_TEXTAREA, content.getText()); // This checks for the rendering... assertNotNull(editPage.getAnchorByHref(expectedContent)); }
@Override protected String getCallbackUrl(final WebClient webClient, final HtmlPage authorizationPage) throws Exception { final HtmlForm form = authorizationPage.getForms().get(0); final HtmlPasswordInput password = form.getInputByName("password"); password.setValueAttribute("testpwdpac4j"); final HtmlSubmitInput submit = form.getInputByValue("Sign In"); final HtmlPage callbackPage = submit.click(); /*form = confirmPage.getForms().get(0); HtmlButton continueButton = (HtmlButton) form.getElementById("continue-button"); HtmlPage callbackPage = continueButton.click();*/ final String callbackUrl = callbackPage.getUrl().toString(); logger.debug("callbackUrl : {}", callbackUrl); return callbackUrl; }
// Check the values of the input fields against the specified list private void checkJstlForEach01(HtmlPage page, String expected[]) { assertEquals("Correct page title", "jstl-foreach-01", page.getTitleText()); HtmlForm form = getFormById(page, jstlForEach01_name); assertNotNull("form exists", form); for (int i = 0; i < expected.length; i++) { HtmlTextInput input = (HtmlTextInput) form.getInputByName( jstlForEach01_name + NamingContainer.SEPARATOR_CHAR + jstlForEach01_names[i]); assertNotNull("field '" + jstlForEach01_names[i] + "' exists", input); assertEquals( "field '" + jstlForEach01_names[i] + "' value", expected[i], input.getValueAttribute()); } }
public void testCopy() throws Exception { String fromPageName = uniqueWikiPageName("CopyTestFrom"); String toPageName = uniqueWikiPageName("CopyTestTo"); editWikiPage(fromPageName, "Catchy tunes", "", "Whatever", true); HtmlPage page = getWikiPage(fromPageName); page = (HtmlPage) page.getAnchorByName("copy").click(); HtmlForm form = page.getFormByName("copyForm"); form.getInputByName("toPage").setValueAttribute(toPageName); page = (HtmlPage) form.getButtonByName("copy").click(); assertTrue( page.getWebResponse().getWebRequest().getUrl().toURI().getPath().contains(toPageName)); assertTrue(page.asText().contains("Catchy tunes")); page = getWikiPage(fromPageName); assertTrue(page.asText().contains("Catchy tunes")); }
@Test public void testEndpoint() throws IOException, ServletException, DeploymentException, InterruptedException { UndertowWebSocketServer server = new UndertowWebSocketServer(); server.start(); WebClient webClient = new WebClient(); HtmlPage page = webClient.getPage(BASE + "/index.html"); HtmlForm dataForm = page.getForms().get(0); HtmlButtonInput sendMessageButton = dataForm.getInputByName("button"); sendMessageButton.click(); System.out.println(page.getElementById("div").getTextContent()); server.stop(); }
public static List<HtmlSelect> getSelects(final HtmlForm form) { final List<HtmlSelect> ret = new ArrayList<HtmlSelect>(); for (final HtmlElement element : form.getElementsByTagName("select")) { if (element instanceof HtmlSelect) { ret.add((HtmlSelect) element); } } // collect selects from lost children for (final HtmlElement elt : form.getLostChildren()) { if (elt instanceof HtmlSelect) { ret.add((HtmlSelect) elt); } } return ret; }
@Test public void errorDropdownIsPresentAndIsNotEmpty() throws Exception { JenkinsRule.WebClient wc = j.createWebClient(); wc.login("user1", "user1"); HtmlPage page = wc.goTo("job/x/" + build.getNumber()); page.getElementById("claim").click(); HtmlForm form = page.getFormByName("claim"); HtmlSelect select = form.getSelectByName("_.errors"); HashSet<String> set = new HashSet<String>(); for (HtmlOption option : select.getOptions()) { set.add(option.getValueAttribute()); } assertTrue(set.contains("Default")); assertTrue(set.contains(CAUSE_NAME_2)); assertTrue(set.contains(CAUSE_NAME_1)); }