Search in sources :

Example 1 with HtmlPage

use of com.gargoylesoftware.htmlunit.html.HtmlPage in project zeppelin by apache.

the class ScreenCaptureHtmlUnitDriver method getScreenshotAs.

@Override
@SuppressWarnings("unchecked")
public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {
    byte[] archive = new byte[0];
    try {
        archive = downloadCssAndImages(getWebClient(), (HtmlPage) getCurrentWindow().getEnclosedPage());
    } catch (Exception e) {
        LOGGER.error("Exception in ScreenCaptureHtmlUnitDriver while getScreenshotAs ", e);
    }
    if (target.equals(OutputType.BASE64)) {
        return target.convertFromBase64Png(new Base64Encoder().encode(archive));
    }
    if (target.equals(OutputType.FILE)) {
        File f = new File("screen.tmp");
        try {
            FileOutputStream scr = new FileOutputStream(f);
            scr.write(archive);
            scr.close();
        } catch (IOException e) {
            throw new WebDriverException(e);
        }
        return (X) f;
    }
    return (X) archive;
}
Also used : HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) File(java.io.File) WebDriverException(org.openqa.selenium.WebDriverException) IOException(java.io.IOException) Base64Encoder(org.openqa.selenium.internal.Base64Encoder) WebDriverException(org.openqa.selenium.WebDriverException)

Example 2 with HtmlPage

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

the class LinkedInOAuthRequestFilter method getRefreshToken.

@SuppressWarnings("deprecation")
private String getRefreshToken() {
    // disable redirect to avoid loading error redirect URL
    webClient.getOptions().setRedirectEnabled(false);
    try {
        final String csrfId = String.valueOf(new SecureRandom().nextLong());
        final String encodedRedirectUri = URLEncoder.encode(oAuthParams.getRedirectUri(), "UTF-8");
        final OAuthScope[] scopes = oAuthParams.getScopes();
        final String url;
        if (scopes == null || scopes.length == 0) {
            url = String.format(AUTHORIZATION_URL, oAuthParams.getClientId(), csrfId, encodedRedirectUri);
        } else {
            final int nScopes = scopes.length;
            final StringBuilder builder = new StringBuilder();
            int i = 0;
            for (OAuthScope scope : scopes) {
                builder.append(scope.getValue());
                if (++i < nScopes) {
                    builder.append("%20");
                }
            }
            url = String.format(AUTHORIZATION_URL_WITH_SCOPE, oAuthParams.getClientId(), csrfId, builder.toString(), encodedRedirectUri);
        }
        HtmlPage authPage;
        try {
            authPage = webClient.getPage(url);
        } catch (FailingHttpStatusCodeException e) {
            // only handle errors returned with redirects
            if (e.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
                final URL location = new URL(e.getResponse().getResponseHeaderValue(HttpHeaders.LOCATION));
                final String locationQuery = location.getQuery();
                if (locationQuery != null && locationQuery.contains("error=")) {
                    throw new IOException(URLDecoder.decode(locationQuery).replaceAll("&", ", "));
                } else {
                    // follow the redirect to login form
                    authPage = webClient.getPage(location);
                }
            } else {
                throw e;
            }
        }
        // look for <div role="alert">
        final HtmlDivision div = authPage.getFirstByXPath("//div[@role='alert']");
        if (div != null) {
            throw new IllegalArgumentException("Error authorizing application: " + div.getTextContent());
        }
        // submit login credentials
        final HtmlForm loginForm = authPage.getFormByName("oauth2SAuthorizeForm");
        final HtmlTextInput login = loginForm.getInputByName("session_key");
        login.setText(oAuthParams.getUserName());
        final HtmlPasswordInput password = loginForm.getInputByName("session_password");
        password.setText(oAuthParams.getUserPassword());
        final HtmlSubmitInput submitInput = loginForm.getInputByName("authorize");
        // validate CSRF and get authorization code
        String redirectQuery;
        try {
            final Page redirectPage = submitInput.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();
        }
        if (redirectQuery == null) {
            throw new IllegalArgumentException("Redirect response query is null, check username, password and permissions");
        }
        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 (!csrfId.equals(state)) {
            throw new SecurityException("Invalid CSRF code!");
        } else {
            // TODO check results??
            return params.get("code");
        }
    } catch (IOException e) {
        throw new IllegalArgumentException("Error authorizing application: " + e.getMessage(), e);
    }
}
Also used : HtmlTextInput(com.gargoylesoftware.htmlunit.html.HtmlTextInput) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) SecureRandom(java.security.SecureRandom) HtmlPasswordInput(com.gargoylesoftware.htmlunit.html.HtmlPasswordInput) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) Page(com.gargoylesoftware.htmlunit.Page) IOException(java.io.IOException) HtmlDivision(com.gargoylesoftware.htmlunit.html.HtmlDivision) URL(java.net.URL) HtmlForm(com.gargoylesoftware.htmlunit.html.HtmlForm) HtmlSubmitInput(com.gargoylesoftware.htmlunit.html.HtmlSubmitInput) FailingHttpStatusCodeException(com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException)

Example 3 with HtmlPage

use of com.gargoylesoftware.htmlunit.html.HtmlPage in project sling by apache.

the class ITWebConsoleRemote method testWebConsolePlugin.

@Test
public void testWebConsolePlugin() throws IOException {
    final HtmlPage page = webClient.getPage(prepareUrl(PLUGIN_SUFFIX));
    String text = page.asText();
    //Filter name should be part of Filter table
    assertThat(text, containsString("WebConsoleTestTurboFilter"));
    //Console name should be part of console table
    assertThat(text, containsString("WebConsoleTestAppender"));
    //Should show file name testremote.log
    assertThat(text, containsString("testremote.log"));
}
Also used : HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) Matchers.containsString(org.hamcrest.Matchers.containsString) Test(org.junit.Test)

Example 4 with HtmlPage

use of com.gargoylesoftware.htmlunit.html.HtmlPage in project workflow-cps-plugin by jenkinsci.

the class CpsFlowDefinition2Test method sandboxInvokerUsed.

@Test
public void sandboxInvokerUsed() throws Exception {
    jenkins.jenkins.setSecurityRealm(jenkins.createDummySecurityRealm());
    GlobalMatrixAuthorizationStrategy gmas = new GlobalMatrixAuthorizationStrategy();
    // Set up a user with RUN_SCRIPTS and one without..
    gmas.add(Jenkins.RUN_SCRIPTS, "runScriptsUser");
    gmas.add(Jenkins.READ, "runScriptsUser");
    gmas.add(Item.READ, "runScriptsUser");
    gmas.add(Jenkins.READ, "otherUser");
    gmas.add(Item.READ, "otherUser");
    jenkins.jenkins.setAuthorizationStrategy(gmas);
    WorkflowJob job = jenkins.jenkins.createProject(WorkflowJob.class, "p");
    job.setDefinition(new CpsFlowDefinition("[a: 1, b: 2].collectEntries { k, v ->\n" + "  Jenkins.getInstance()\n" + "  [(v): k]\n" + "}\n", true));
    WorkflowRun r = jenkins.assertBuildStatus(Result.FAILURE, job.scheduleBuild2(0).get());
    jenkins.assertLogContains("org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod jenkins.model.Jenkins getInstance", r);
    jenkins.assertLogContains("Scripts not permitted to use staticMethod jenkins.model.Jenkins getInstance. " + Messages.SandboxContinuable_ScriptApprovalLink(), r);
    JenkinsRule.WebClient wc = jenkins.createWebClient();
    wc.login("runScriptsUser");
    // make sure we see the annotation for the RUN_SCRIPTS user.
    HtmlPage rsp = wc.getPage(r, "console");
    assertEquals(1, DomNodeUtil.selectNodes(rsp, "//A[@href='" + jenkins.contextPath + "/scriptApproval']").size());
    // make sure raw console output doesn't include the garbage and has the right message.
    TextPage raw = (TextPage) wc.goTo(r.getUrl() + "consoleText", "text/plain");
    assertThat(raw.getContent(), containsString(" getInstance. " + Messages.SandboxContinuable_ScriptApprovalLink()));
    wc.login("otherUser");
    // make sure we don't see the link for the other user.
    HtmlPage rsp2 = wc.getPage(r, "console");
    assertEquals(0, DomNodeUtil.selectNodes(rsp2, "//A[@href='" + jenkins.contextPath + "/scriptApproval']").size());
    // make sure raw console output doesn't include the garbage and has the right message.
    TextPage raw2 = (TextPage) wc.goTo(r.getUrl() + "consoleText", "text/plain");
    assertThat(raw2.getContent(), containsString(" getInstance. " + Messages.SandboxContinuable_ScriptApprovalLink()));
}
Also used : HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) GlobalMatrixAuthorizationStrategy(hudson.security.GlobalMatrixAuthorizationStrategy) TextPage(com.gargoylesoftware.htmlunit.TextPage) JenkinsRule(org.jvnet.hudson.test.JenkinsRule) WorkflowJob(org.jenkinsci.plugins.workflow.job.WorkflowJob) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) Test(org.junit.Test)

Example 5 with HtmlPage

use of com.gargoylesoftware.htmlunit.html.HtmlPage in project nodejs-plugin by jenkinsci.

the class NodeJSInstallationTest method test_persist_of_nodejs_installation.

/**
 * Simulates the addition of the new NodeJS via UI and makes sure it works
 * and persistent file was created.
 */
@Test
@Issue("JENKINS-41535")
public void test_persist_of_nodejs_installation() throws Exception {
    File jenkinsHome = r.jenkins.getRootDir();
    File installationsFile = new File(jenkinsHome, NodeJSInstallation.class.getName() + ".xml");
    assertFalse("NodeJS installations file already exists", installationsFile.exists());
    HtmlPage p = getConfigurePage();
    HtmlForm f = p.getFormByName("config");
    HtmlButton b = r.getButtonByCaption(f, "Add NodeJS");
    b.click();
    r.findPreviousInputElement(b, "name").setValueAttribute("myNode");
    r.findPreviousInputElement(b, "home").setValueAttribute("/tmp/foo");
    r.submit(f);
    verify();
    assertTrue("NodeJS installations file has not been saved", installationsFile.exists());
    // another submission and verify it survives a roundtrip
    p = getConfigurePage();
    f = p.getFormByName("config");
    r.submit(f);
    verify();
}
Also used : HtmlForm(com.gargoylesoftware.htmlunit.html.HtmlForm) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) File(java.io.File) HtmlButton(com.gargoylesoftware.htmlunit.html.HtmlButton) Issue(org.jvnet.hudson.test.Issue) Test(org.junit.Test)

Aggregations

HtmlPage (com.gargoylesoftware.htmlunit.html.HtmlPage)159 Test (org.junit.Test)114 WebClient (com.gargoylesoftware.htmlunit.WebClient)51 HtmlSubmitInput (com.gargoylesoftware.htmlunit.html.HtmlSubmitInput)25 HtmlForm (com.gargoylesoftware.htmlunit.html.HtmlForm)23 HtmlSpan (com.gargoylesoftware.htmlunit.html.HtmlSpan)21 File (java.io.File)17 HtmlInput (com.gargoylesoftware.htmlunit.html.HtmlInput)15 Matchers.containsString (org.hamcrest.Matchers.containsString)13 IOException (java.io.IOException)11 JenkinsRule (org.jvnet.hudson.test.JenkinsRule)10 FreeStyleProject (hudson.model.FreeStyleProject)9 URL (java.net.URL)9 Page (com.gargoylesoftware.htmlunit.Page)8 HtmlTextInput (com.gargoylesoftware.htmlunit.html.HtmlTextInput)7 WebWindow (com.gargoylesoftware.htmlunit.WebWindow)6 DomElement (com.gargoylesoftware.htmlunit.html.DomElement)6 WebRequest (com.gargoylesoftware.htmlunit.WebRequest)5 HtmlButton (com.gargoylesoftware.htmlunit.html.HtmlButton)5 HtmlElement (com.gargoylesoftware.htmlunit.html.HtmlElement)5