Search in sources :

Example 6 with HtmlForm

use of com.gargoylesoftware.htmlunit.html.HtmlForm in project testcases by coheigea.

the class OIDCTest method registerNewClient.

private static HtmlPage registerNewClient(WebClient webClient, String url, String clientName, String redirectURI, String clientAudience) throws Exception {
    HtmlPage registerPage = webClient.getPage(url + "/register");
    final HtmlForm form = registerPage.getForms().get(0);
    // Set new client values
    final HtmlTextInput clientNameInput = form.getInputByName("client_name");
    clientNameInput.setValueAttribute(clientName);
    final HtmlSelect clientTypeSelect = form.getSelectByName("client_type");
    clientTypeSelect.setSelectedAttribute("confidential", true);
    final HtmlTextInput redirectURIInput = form.getInputByName("client_redirectURI");
    redirectURIInput.setValueAttribute(redirectURI);
    final HtmlTextInput clientAudienceURIInput = form.getInputByName("client_audience");
    clientAudienceURIInput.setValueAttribute(clientAudience);
    final HtmlButton button = form.getButtonByName("submit_button");
    return button.click();
}
Also used : HtmlForm(com.gargoylesoftware.htmlunit.html.HtmlForm) HtmlTextInput(com.gargoylesoftware.htmlunit.html.HtmlTextInput) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) HtmlSelect(com.gargoylesoftware.htmlunit.html.HtmlSelect) HtmlButton(com.gargoylesoftware.htmlunit.html.HtmlButton)

Example 7 with HtmlForm

use of com.gargoylesoftware.htmlunit.html.HtmlForm in project testcases by coheigea.

the class SAMLSSOTest method login.

private static String login(String url, String user, String password, String idpPort) throws IOException {
    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(new AuthScope("localhost", Integer.parseInt(idpPort)), new UsernamePasswordCredentials(user, password));
    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);
    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());
    final HtmlForm form = idpPage.getFormByName("samlsigninresponseform");
    final HtmlSubmitInput button = form.getInputByName("_eventId_submit");
    final XmlPage rpPage = button.click();
    return rpPage.asXml();
}
Also used : HtmlForm(com.gargoylesoftware.htmlunit.html.HtmlForm) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) HtmlSubmitInput(com.gargoylesoftware.htmlunit.html.HtmlSubmitInput) AuthScope(org.apache.http.auth.AuthScope) XmlPage(com.gargoylesoftware.htmlunit.xml.XmlPage) WebClient(com.gargoylesoftware.htmlunit.WebClient) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 8 with HtmlForm

use of com.gargoylesoftware.htmlunit.html.HtmlForm in project promoted-builds-plugin by jenkinsci.

the class ManualConditionBug22005 method testPromotionProcessViaWebClient.

@Test
public void testPromotionProcessViaWebClient() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject();
    ExtensionList<Descriptor> list = j.jenkins.getExtensionList(Descriptor.class);
    list.add(new JobPropertyImpl.DescriptorImpl(JobPropertyImpl.class));
    JobPropertyImpl base = new JobPropertyImpl(p);
    p.addProperty(base);
    createPromotionProcess(base, "PROM0");
    createPromotionProcess(base, "PROM1");
    createPromotionProcess(base, "PROM2");
    FreeStyleBuild b1 = j.assertBuildStatusSuccess(p.scheduleBuild2(0));
    assertNull(b1.getAction(ManualApproval.class));
    HtmlPage page = j.createWebClient().getPage(b1, "promotion");
    // Approve Promotion
    List<HtmlForm> forms = ManualConditionTest.getFormsByName(page, "approve");
    assertFalse(forms.isEmpty());
    assertEquals(3, forms.size());
    for (HtmlForm form : forms) {
        submit(form);
    }
    // reload promotions page
    page = j.createWebClient().getPage(b1, "promotion");
    forms = ManualConditionTest.getFormsByName(page, "build");
    for (HtmlForm form : forms) {
        List<HtmlElement> parameters = ManualConditionTest.getFormParameters(form);
        assertEquals(2, parameters.size());
    }
}
Also used : ManualApproval(hudson.plugins.promoted_builds.conditions.ManualCondition.ManualApproval) HtmlForm(com.gargoylesoftware.htmlunit.html.HtmlForm) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) HtmlElement(com.gargoylesoftware.htmlunit.html.HtmlElement) Descriptor(hudson.model.Descriptor) FreeStyleBuild(hudson.model.FreeStyleBuild) FreeStyleProject(hudson.model.FreeStyleProject) JobPropertyImpl(hudson.plugins.promoted_builds.JobPropertyImpl) Test(org.junit.Test)

Example 9 with HtmlForm

use of com.gargoylesoftware.htmlunit.html.HtmlForm in project yyl_example by Relucent.

the class HtmlUnitTest1 method main.

public static void main(String[] args) {
    // 得到浏览器对象
    WebClient webClient = null;
    try {
        webClient = new WebClient();
        webClient.waitForBackgroundJavaScript(60 * 1000);
        WebClientOptions options = webClient.getOptions();
        // 不加载css
        options.setCssEnabled(true);
        // 启用JS解释器,默认为true
        options.setJavaScriptEnabled(false);
        options.setUseInsecureSSL(true);
        // options.setRedirectEnabled(true);
        // 当出现HttpError时,是否抛出异常
        options.setThrowExceptionOnFailingStatusCode(false);
        // JS运行错误时,是否抛出异常
        options.setThrowExceptionOnScriptError(false);
        // 设置AJAX异步处理控制器(启用AJAX支持)
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());
        // 拿到网页
        HtmlPage htmlpage = webClient.getPage("http://news.baidu.com/advanced_news.html");
        // 根据名字得到表单(表单的名字叫“f”)
        HtmlForm form = htmlpage.getFormByName("f");
        System.out.println(form);
        // 获取“百度一下”这个按钮
        HtmlSubmitInput button = form.getInputByValue("百度一下");
        System.out.println(button);
        // 得到搜索框
        HtmlTextInput textField = form.getInputByName("q1");
        System.out.println(textField);
        // 在搜索框内填入“HtmlUnit”
        textField.setValueAttribute("HtmlUnit");
        // 点击按钮
        HtmlPage nextPage = button.click();
        // 下一个页面
        System.out.println(nextPage);
        // 获得页面结果
        String result = nextPage.asXml();
        System.out.println(result);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (webClient != null) {
            webClient.close();
        }
    }
}
Also used : WebClientOptions(com.gargoylesoftware.htmlunit.WebClientOptions) HtmlForm(com.gargoylesoftware.htmlunit.html.HtmlForm) HtmlTextInput(com.gargoylesoftware.htmlunit.html.HtmlTextInput) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) HtmlSubmitInput(com.gargoylesoftware.htmlunit.html.HtmlSubmitInput) NicelyResynchronizingAjaxController(com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController) WebClient(com.gargoylesoftware.htmlunit.WebClient)

Example 10 with HtmlForm

use of com.gargoylesoftware.htmlunit.html.HtmlForm in project camel by apache.

the class BoxConnectionHelper method createStandardAuthenticatedConnection.

public static BoxAPIConnection createStandardAuthenticatedConnection(BoxConfiguration configuration) {
    // Create web client for first leg of OAuth2
    //
    final WebClient webClient = new WebClient();
    final WebClientOptions options = webClient.getOptions();
    options.setRedirectEnabled(true);
    options.setJavaScriptEnabled(false);
    options.setThrowExceptionOnFailingStatusCode(true);
    options.setThrowExceptionOnScriptError(true);
    options.setPrintContentOnFailingStatusCode(LOG.isDebugEnabled());
    try {
        // use default SSP to create supported non-SSL protocols list
        final SSLContext sslContext = new SSLContextParameters().createSSLContext(null);
        options.setSSLClientProtocols(sslContext.createSSLEngine().getEnabledProtocols());
    } catch (GeneralSecurityException e) {
        throw ObjectHelper.wrapRuntimeCamelException(e);
    } catch (IOException e) {
        throw ObjectHelper.wrapRuntimeCamelException(e);
    } finally {
        if (webClient != null) {
            webClient.close();
        }
    }
    // disable default gzip compression, as htmlunit does not negotiate
    // pages sent with no compression
    new WebConnectionWrapper(webClient) {

        @Override
        public WebResponse getResponse(WebRequest request) throws IOException {
            request.setAdditionalHeader(HttpHeaders.ACCEPT_ENCODING, "identity");
            return super.getResponse(request);
        }
    };
    // add HTTP proxy if set
    final Map<String, Object> httpParams = configuration.getHttpParams();
    if (httpParams != null && httpParams.get("http.route.default-proxy") != null) {
        final HttpHost proxyHost = (HttpHost) httpParams.get("http.route.default-proxy");
        final Boolean socksProxy = (Boolean) httpParams.get("http.route.socks-proxy");
        final ProxyConfig proxyConfig = new ProxyConfig(proxyHost.getHostName(), proxyHost.getPort(), socksProxy != null ? socksProxy : false);
        options.setProxyConfig(proxyConfig);
    }
    // authorize application on user's behalf
    try {
        // generate anti-forgery token to prevent/detect CSRF attack
        final String csrfToken = String.valueOf(new SecureRandom().nextLong());
        final HtmlPage authPage = webClient.getPage(authorizationUrl(configuration.getClientId(), csrfToken));
        // look for <div role="error_message">
        final HtmlDivision div = authPage.getFirstByXPath("//div[contains(concat(' ', @class, ' '), ' error_message ')]");
        if (div != null) {
            final String errorMessage = div.getTextContent().replaceAll("\\s+", " ").replaceAll(" Show Error Details", ":").trim();
            throw new IllegalArgumentException("Error authorizing application: " + errorMessage);
        }
        // submit login credentials
        final HtmlForm loginForm = authPage.getFormByName("login_form");
        final HtmlTextInput login = loginForm.getInputByName("login");
        login.setText(configuration.getUserName());
        final HtmlPasswordInput password = loginForm.getInputByName("password");
        password.setText(configuration.getUserPassword());
        final HtmlSubmitInput submitInput = loginForm.getInputByName("login_submit");
        // submit consent
        final HtmlPage consentPage = submitInput.click();
        final HtmlForm consentForm = consentPage.getFormByName("consent_form");
        final HtmlButton consentAccept = consentForm.getButtonByName("consent_accept");
        // disable redirect to avoid loading redirect URL
        webClient.getOptions().setRedirectEnabled(false);
        // validate CSRF and get authorization code
        String redirectQuery;
        try {
            final Page redirectPage = consentAccept.click();
            redirectQuery = redirectPage.getUrl().getQuery();
        } catch (FailingHttpStatusCodeException e) {
            // escalate non redirect errors
            if (e.getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) {
                throw e;
            }
            final String location = e.getResponse().getResponseHeaderValue("Location");
            redirectQuery = new URL(location).getQuery();
        }
        final Map<String, String> params = new HashMap<String, String>();
        final Matcher matcher = QUERY_PARAM_PATTERN.matcher(redirectQuery);
        while (matcher.find()) {
            params.put(matcher.group(1), matcher.group(2));
        }
        final String state = params.get("state");
        if (!csrfToken.equals(state)) {
            throw new SecurityException("Invalid CSRF code!");
        } else {
            // get authorization code
            final String authorizationCode = params.get("code");
            return new BoxAPIConnection(configuration.getClientId(), configuration.getClientSecret(), authorizationCode);
        }
    } catch (BoxAPIException e) {
        throw new RuntimeCamelException(String.format("Box API connection failed: API returned the error code %d\n\n%s", e.getResponseCode(), e.getResponse()), e);
    } catch (Exception e) {
        throw new RuntimeCamelException(String.format("Box API connection failed: %s", e.getMessage()), e);
    }
}
Also used : WebClientOptions(com.gargoylesoftware.htmlunit.WebClientOptions) HtmlTextInput(com.gargoylesoftware.htmlunit.html.HtmlTextInput) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) HtmlPasswordInput(com.gargoylesoftware.htmlunit.html.HtmlPasswordInput) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) Page(com.gargoylesoftware.htmlunit.Page) HtmlDivision(com.gargoylesoftware.htmlunit.html.HtmlDivision) BoxAPIException(com.box.sdk.BoxAPIException) URL(java.net.URL) WebRequest(com.gargoylesoftware.htmlunit.WebRequest) HtmlForm(com.gargoylesoftware.htmlunit.html.HtmlForm) HtmlSubmitInput(com.gargoylesoftware.htmlunit.html.HtmlSubmitInput) HttpHost(org.apache.http.HttpHost) FailingHttpStatusCodeException(com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException) GeneralSecurityException(java.security.GeneralSecurityException) BoxAPIConnection(com.box.sdk.BoxAPIConnection) SecureRandom(java.security.SecureRandom) GeneralSecurityException(java.security.GeneralSecurityException) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) ProxyConfig(com.gargoylesoftware.htmlunit.ProxyConfig) WebClient(com.gargoylesoftware.htmlunit.WebClient) BoxAPIException(com.box.sdk.BoxAPIException) GeneralSecurityException(java.security.GeneralSecurityException) FailingHttpStatusCodeException(com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException) RuntimeCamelException(org.apache.camel.RuntimeCamelException) IOException(java.io.IOException) SSLContextParameters(org.apache.camel.util.jsse.SSLContextParameters) HtmlButton(com.gargoylesoftware.htmlunit.html.HtmlButton) RuntimeCamelException(org.apache.camel.RuntimeCamelException) WebConnectionWrapper(com.gargoylesoftware.htmlunit.util.WebConnectionWrapper)

Aggregations

HtmlForm (com.gargoylesoftware.htmlunit.html.HtmlForm)21 HtmlPage (com.gargoylesoftware.htmlunit.html.HtmlPage)20 Test (org.junit.Test)14 HtmlSubmitInput (com.gargoylesoftware.htmlunit.html.HtmlSubmitInput)7 HtmlTextInput (com.gargoylesoftware.htmlunit.html.HtmlTextInput)5 WebClient (com.gargoylesoftware.htmlunit.WebClient)4 HtmlButton (com.gargoylesoftware.htmlunit.html.HtmlButton)4 HtmlInput (com.gargoylesoftware.htmlunit.html.HtmlInput)4 Page (com.gargoylesoftware.htmlunit.Page)3 HtmlElement (com.gargoylesoftware.htmlunit.html.HtmlElement)3 Descriptor (hudson.model.Descriptor)3 JobPropertyImpl (hudson.plugins.promoted_builds.JobPropertyImpl)3 ManualApproval (hudson.plugins.promoted_builds.conditions.ManualCondition.ManualApproval)3 Issue (org.jvnet.hudson.test.Issue)3 JenkinsRule (org.jvnet.hudson.test.JenkinsRule)3 FailingHttpStatusCodeException (com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException)2 WebClientOptions (com.gargoylesoftware.htmlunit.WebClientOptions)2 WebRequest (com.gargoylesoftware.htmlunit.WebRequest)2 HtmlCheckBoxInput (com.gargoylesoftware.htmlunit.html.HtmlCheckBoxInput)2 HtmlDivision (com.gargoylesoftware.htmlunit.html.HtmlDivision)2