Search in sources :

Example 6 with HtmlElement

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

the class ScreenCaptureHtmlUnitDriver method downloadCssAndImages.

// http://stackoverflow.com/questions/2244272/how-can-i-tell-htmlunits-webclient-to-download-images-and-css
protected byte[] downloadCssAndImages(WebClient webClient, HtmlPage page) throws Exception {
    WebWindow currentWindow = webClient.getCurrentWindow();
    Map<String, String> urlMapping = new HashMap<>();
    Map<String, byte[]> files = new HashMap<>();
    WebWindow window = null;
    try {
        window = webClient.getWebWindowByName(page.getUrl().toString() + "_screenshot");
        webClient.getPage(window, new WebRequest(page.getUrl()));
    } catch (Exception e) {
        LOGGER.error("Exception in ScreenCaptureHtmlUnitDriver while downloadCssAndImages ", e);
        window = webClient.openWindow(page.getUrl(), page.getUrl().toString() + "_screenshot");
    }
    String xPathExpression = "//*[name() = 'img' or name() = 'link' and (@type = 'text/css' or @type = 'image/x-icon') or  @type = 'text/javascript']";
    List<?> resultList = page.getByXPath(xPathExpression);
    Iterator<?> i = resultList.iterator();
    while (i.hasNext()) {
        try {
            HtmlElement el = (HtmlElement) i.next();
            String resourceSourcePath = el.getAttribute("src").equals("") ? el.getAttribute("href") : el.getAttribute("src");
            if (resourceSourcePath == null || resourceSourcePath.equals(""))
                continue;
            URL resourceRemoteLink = page.getFullyQualifiedUrl(resourceSourcePath);
            String resourceLocalPath = mapLocalUrl(page, resourceRemoteLink, resourceSourcePath, urlMapping);
            urlMapping.put(resourceSourcePath, resourceLocalPath);
            if (!resourceRemoteLink.toString().endsWith(".css")) {
                byte[] image = downloadImage(webClient, window, resourceRemoteLink);
                files.put(resourceLocalPath, image);
            } else {
                String css = downloadCss(webClient, window, resourceRemoteLink);
                for (String cssImagePath : getLinksFromCss(css)) {
                    URL cssImagelink = page.getFullyQualifiedUrl(cssImagePath.replace("\"", "").replace("\'", "").replace(" ", ""));
                    String cssImageLocalPath = mapLocalUrl(page, cssImagelink, cssImagePath, urlMapping);
                    files.put(cssImageLocalPath, downloadImage(webClient, window, cssImagelink));
                }
                files.put(resourceLocalPath, replaceRemoteUrlsWithLocal(css, urlMapping).replace("resources/", "./").getBytes());
            }
        } catch (Exception e) {
            LOGGER.error("Exception in ScreenCaptureHtmlUnitDriver while resultList.iterator ", e);
        }
    }
    String pagesrc = replaceRemoteUrlsWithLocal(page.getWebResponse().getContentAsString(), urlMapping);
    files.put("page.html", pagesrc.getBytes());
    webClient.setCurrentWindow(currentWindow);
    return createZip(files);
}
Also used : WebRequest(com.gargoylesoftware.htmlunit.WebRequest) HashMap(java.util.HashMap) HtmlElement(com.gargoylesoftware.htmlunit.html.HtmlElement) WebDriverException(org.openqa.selenium.WebDriverException) IOException(java.io.IOException) URL(java.net.URL) WebWindow(com.gargoylesoftware.htmlunit.WebWindow)

Example 7 with HtmlElement

use of com.gargoylesoftware.htmlunit.html.HtmlElement in project support-core-plugin by jenkinsci.

the class SupportAutomatedBundleConfigurationTest method testRoundTrip.

@Test
public void testRoundTrip() throws Exception {
    HtmlForm cfg = j.createWebClient().goTo("supportCore").getFormByName("config");
    ((HtmlInput) cfg.getOneHtmlElementByAttribute("input", "name", "enabled")).setChecked(true);
    ((HtmlInput) cfg.getOneHtmlElementByAttribute("input", "name", "period")).setValueAttribute("2");
    for (HtmlElement element : cfg.getElementsByAttribute("div", "name", "components")) {
        ((HtmlInput) element.getOneHtmlElementByAttribute("input", "name", "selected")).setChecked(true);
    }
    j.submit(cfg);
    assertThat("should be enabled", SupportAutomatedBundleConfiguration.get().isEnabled(), is(true));
    assertThat("period should be 1", SupportAutomatedBundleConfiguration.get().getPeriod(), is(2));
    assertThat("all applicable components should be saved", SupportAutomatedBundleConfiguration.get().getComponentIds(), containsInAnyOrder(SupportAutomatedBundleConfiguration.getApplicableComponents().stream().map(Component::getId).toArray()));
    assertThat("all applicable components should be saved", SupportAutomatedBundleConfiguration.get().getComponents().stream().map(Component::getId).collect(Collectors.toList()), containsInAnyOrder(SupportAutomatedBundleConfiguration.getApplicableComponents().stream().map(Component::getId).toArray()));
    assertThat("all saved components should be retrievable", SupportAutomatedBundleConfiguration.get().getComponents().stream().map(Component::getId).collect(Collectors.toList()), containsInAnyOrder(SupportAutomatedBundleConfiguration.getApplicableComponents().stream().map(Component::getId).toArray()));
}
Also used : HtmlForm(com.gargoylesoftware.htmlunit.html.HtmlForm) HtmlElement(com.gargoylesoftware.htmlunit.html.HtmlElement) Component(com.cloudbees.jenkins.support.api.Component) HtmlInput(com.gargoylesoftware.htmlunit.html.HtmlInput) Test(org.junit.Test)

Example 8 with HtmlElement

use of com.gargoylesoftware.htmlunit.html.HtmlElement in project ats-framework by Axway.

the class HiddenHtmlElementUtils method mouseClick.

@PublicAtsApi
public static void mouseClick(HtmlUnitWebElement webElement) {
    Method getElementForOperationMethod = null;
    boolean getElementForOperationMethodAccessible = false;
    Method moveOutIfNeededMethod = null;
    boolean moveOutIfNeededMethodAccessible = false;
    Method updateActiveElementMethod = null;
    boolean updateActiveElementMethodAccessible = false;
    try {
        // Allow invoking click on non-visible elements. Prevents HtmlUnit check for currently visible element
        // TODO: remove this possibility by removing UiEngineConfigurator#workWithInvisibleElements()
        // change access modifiers of some methods
        getElementForOperationMethod = HtmlUnitMouse.class.getDeclaredMethod("getElementForOperation", Coordinates.class);
        getElementForOperationMethodAccessible = getElementForOperationMethod.isAccessible();
        getElementForOperationMethod.setAccessible(true);
        moveOutIfNeededMethod = HtmlUnitMouse.class.getDeclaredMethod("moveOutIfNeeded", DomElement.class);
        moveOutIfNeededMethodAccessible = moveOutIfNeededMethod.isAccessible();
        moveOutIfNeededMethod.setAccessible(true);
        updateActiveElementMethod = HtmlUnitMouse.class.getDeclaredMethod("updateActiveElement", DomElement.class);
        updateActiveElementMethodAccessible = updateActiveElementMethod.isAccessible();
        updateActiveElementMethod.setAccessible(true);
        // get the target element
        HtmlUnitDriver htmlUnitDriver = (HtmlUnitDriver) webElement.getWrappedDriver();
        HtmlUnitMouse mouse = (HtmlUnitMouse) htmlUnitDriver.getMouse();
        HtmlElement element = (HtmlElement) getElementForOperationMethod.invoke(mouse, webElement.getCoordinates());
        moveOutIfNeededMethod.invoke(mouse, element);
        if (htmlUnitDriver.isJavascriptEnabled()) {
            if (!(element instanceof HtmlInput)) {
                element.focus();
            }
            element.mouseOver();
            element.mouseMove();
        }
        HtmlUnitKeyboard keyboard = (HtmlUnitKeyboard) htmlUnitDriver.getKeyboard();
        element.click(keyboard.isShiftPressed(), keyboard.isCtrlPressed(), keyboard.isAltPressed());
        updateActiveElementMethod.invoke(mouse, element);
    } catch (IOException ioe) {
        throw new WebDriverException(ioe);
    } catch (ScriptException e) {
        // we need only our exception if such exists
        Throwable uiEngineException = e.getCause();
        while (uiEngineException != null && !uiEngineException.getClass().getName().toLowerCase().contains("com.axway.ats")) {
            uiEngineException = uiEngineException.getCause();
        }
        if (uiEngineException != null) {
            throw (RuntimeException) uiEngineException;
        }
        // Log the exception with level WARN, because in the main Selenium implementation
        // (HtmlUnitMouse.click(coordinates)) the exception is even skipped
        log.warn("Script error while clicking web element. " + webElement.toString(), e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        // Restore accessibility modifier
        if (getElementForOperationMethod != null) {
            getElementForOperationMethod.setAccessible(getElementForOperationMethodAccessible);
        }
        if (moveOutIfNeededMethod != null) {
            moveOutIfNeededMethod.setAccessible(moveOutIfNeededMethodAccessible);
        }
        if (updateActiveElementMethod != null) {
            updateActiveElementMethod.setAccessible(updateActiveElementMethodAccessible);
        }
    }
}
Also used : HtmlElement(com.gargoylesoftware.htmlunit.html.HtmlElement) Coordinates(org.openqa.selenium.interactions.Coordinates) Method(java.lang.reflect.Method) IOException(java.io.IOException) HtmlInput(com.gargoylesoftware.htmlunit.html.HtmlInput) WebDriverException(org.openqa.selenium.WebDriverException) IOException(java.io.IOException) ScriptException(com.gargoylesoftware.htmlunit.ScriptException) HtmlUnitDriver(org.openqa.selenium.htmlunit.HtmlUnitDriver) ScriptException(com.gargoylesoftware.htmlunit.ScriptException) DomElement(com.gargoylesoftware.htmlunit.html.DomElement) HtmlUnitMouse(org.openqa.selenium.htmlunit.HtmlUnitMouse) HtmlUnitKeyboard(org.openqa.selenium.htmlunit.HtmlUnitKeyboard) WebDriverException(org.openqa.selenium.WebDriverException) PublicAtsApi(com.axway.ats.common.PublicAtsApi)

Example 9 with HtmlElement

use of com.gargoylesoftware.htmlunit.html.HtmlElement in project JSCover by tntim96.

the class HtmlUnitMergeTest method storeReport.

private void storeReport(WebClient webClient, HtmlPage page) throws IOException {
    page.getHtmlElementById("storeTab").click();
    webClient.waitForBackgroundJavaScript(500);
    HtmlElement storeButton = page.getHtmlElementById("storeButton");
    storeButton.click();
    webClient.waitForBackgroundJavaScript(2000);
    String result = page.getElementById("storeDiv").getTextContent();
    assertThat(result, containsString("Coverage data stored at " + new File(reportDir).getPath()));
}
Also used : HtmlElement(com.gargoylesoftware.htmlunit.html.HtmlElement) Matchers.containsString(org.hamcrest.Matchers.containsString) File(java.io.File)

Example 10 with HtmlElement

use of com.gargoylesoftware.htmlunit.html.HtmlElement in project JSCover by tntim96.

the class HtmlServerUnloadedJSTest method shouldIncludeUnloadJSInSavedReport.

@Test
public void shouldIncludeUnloadJSInSavedReport() throws Exception {
    File jsonFile = new File(getReportDir() + "/jscoverage.json");
    if (jsonFile.exists())
        jsonFile.delete();
    HtmlPage page = webClient.getPage("http://localhost:9001/jscoverage.html?" + getIndex());
    page.getHtmlElementById("summaryTab").click();
    webClient.waitForBackgroundJavaScript(2000);
    assertEquals("77%", page.getElementById("summaryTotal").getTextContent());
    verifyCoverage(page, getPrefix() + "/root.js", "80%", "50%", "100%");
    verifyCoverage(page, getPrefix() + "/level1/level1.js", "75%", "50%", "N/A");
    page.getHtmlElementById("storeTab").click();
    webClient.waitForBackgroundJavaScript(500);
    HtmlElement storeButton = page.getHtmlElementById("storeButton");
    storeButton.click();
    webClient.waitForBackgroundJavaScript(2000);
    String result = page.getElementById("storeDiv").getTextContent();
    assertThat(result, containsString("Coverage data stored at " + new File(getReportDir()).getPath()));
    String json = ioUtils.toString(jsonFile);
    assertThat(json, containsString("/root.js"));
    assertThat(json, containsString("/level1/level2/level2.js"));
    String url = "file:///" + new File(getReportDir() + "/jscoverage.html").getAbsolutePath();
    page = webClient.getPage(url);
    webClient.waitForBackgroundJavaScript(1000);
    assertEquals("53%", page.getElementById("summaryTotal").getTextContent());
    assertEquals("33%", page.getElementById("branchSummaryTotal").getTextContent());
    assertEquals("50%", page.getElementById("functionSummaryTotal").getTextContent());
    verifyCoverage(page, "/root.js", "80%", "50%", "100%");
    verifyCoverage(page, "/level1/level1.js", "75%", "50%", "N/A");
    verifyCoverage(page, "/level1/level2/level2.js", "0%", "0%", "0%");
}
Also used : HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) HtmlElement(com.gargoylesoftware.htmlunit.html.HtmlElement) Matchers.containsString(org.hamcrest.Matchers.containsString) File(java.io.File) Test(org.junit.Test)

Aggregations

HtmlElement (com.gargoylesoftware.htmlunit.html.HtmlElement)13 Test (org.junit.Test)6 HtmlPage (com.gargoylesoftware.htmlunit.html.HtmlPage)5 HtmlForm (com.gargoylesoftware.htmlunit.html.HtmlForm)4 HtmlInput (com.gargoylesoftware.htmlunit.html.HtmlInput)3 Descriptor (hudson.model.Descriptor)3 JobPropertyImpl (hudson.plugins.promoted_builds.JobPropertyImpl)3 ManualApproval (hudson.plugins.promoted_builds.conditions.ManualCondition.ManualApproval)3 File (java.io.File)3 IOException (java.io.IOException)3 Matchers.containsString (org.hamcrest.Matchers.containsString)3 FreeStyleBuild (hudson.model.FreeStyleBuild)2 FreeStyleProject (hudson.model.FreeStyleProject)2 ParameterDefinition (hudson.model.ParameterDefinition)2 StringParameterDefinition (hudson.model.StringParameterDefinition)2 PromotedBuildAction (hudson.plugins.promoted_builds.PromotedBuildAction)2 Promotion (hudson.plugins.promoted_builds.Promotion)2 PromotionProcess (hudson.plugins.promoted_builds.PromotionProcess)2 ArrayList (java.util.ArrayList)2 WebDriverException (org.openqa.selenium.WebDriverException)2