Java Code Examples for com.gargoylesoftware.htmlunit.BrowserVersion

The following examples show how to use com.gargoylesoftware.htmlunit.BrowserVersion. These examples are extracted from open source projects. 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 Project: htmlunit   Source File: JavaScriptConfigurationTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests that all classes included in {@link JavaScriptConfiguration#CLASSES_} defining an
 * {@link JsxClasses}/{@link JsxClass} annotation for at least one browser.
 */
@Test
public void obsoleteJsxClasses() {
    final JavaScriptConfiguration config = JavaScriptConfiguration.getInstance(FIREFOX_60);
    final BrowserVersion[] browsers = new BrowserVersion[]
    {FIREFOX_60, FIREFOX_68, CHROME, INTERNET_EXPLORER};

    for (final Class<? extends SimpleScriptable> klass : config.getClasses()) {
        boolean found = false;
        for (BrowserVersion browser : browsers) {
            if (AbstractJavaScriptConfiguration.getClassConfiguration(klass, browser) != null) {
                found = true;
                break;
            }
        }
        assertTrue("Class " + klass
                + " is member of JavaScriptConfiguration.CLASSES_ but does not define @JsxClasses/@JsxClass",
                found);
    }
}
 
Example 2
Source Project: HtmlUnit-Android   Source File: DateCustom.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Converts a date to a string, returning the "time" portion using the current locale's conventions.
 * @param context the JavaScript context
 * @param thisObj the scriptable
 * @param args the arguments passed into the method
 * @param function the function
 * @return converted string
 */
public static String toLocaleTimeString(
        final Context context, final Scriptable thisObj, final Object[] args, final Function function) {
    final String formatString;
    final BrowserVersion browserVersion = ((Window) thisObj.getParentScope()).getBrowserVersion();

    if (browserVersion.hasFeature(JS_DATE_WITH_LEFT_TO_RIGHT_MARK)) {
        // [U+200E] -> Unicode Character 'LEFT-TO-RIGHT MARK'
        formatString = "\u200Eh\u200E:\u200Emm\u200E:\u200Ess\u200E \u200Ea";
    }
    else {
        formatString = "h:mm:ss a";
    }
    final FastDateFormat format =  FastDateFormat.getInstance(formatString, getLocale(browserVersion));
    return format.format(getDateValue(thisObj));
}
 
Example 3
Source Project: htmlunit   Source File: CSSStyleDeclarationTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Ensures no default implementation is being used.
 *
 * When no JavaScript method is defined, {@link StyleAttributes} values are used, this can be overridden only
 * when a different implementation is needed.
 *
 * @throws Exception if an error occurs
 */
@Test
public void defaultImplementation() throws Exception {
    final BrowserVersion browserVersion = getBrowserVersion();
    final ClassConfiguration config
        = AbstractJavaScriptConfiguration.getClassConfiguration(CSSStyleDeclaration.class, browserVersion);
    final Map<String, PropertyInfo> propertyMap = config.getPropertyMap();
    final File cssFolder = new File("src/main/java/com/gargoylesoftware/htmlunit/javascript/host/css/");
    final List<String> cssLines = FileUtils.readLines(new File(cssFolder, "CSSStyleDeclaration.java"), ISO_8859_1);
    final List<String> computedLines = FileUtils.readLines(new File(cssFolder, "ComputedCSSStyleDeclaration.java"),
            ISO_8859_1);
    for (final Map.Entry<String, PropertyInfo> entry : propertyMap.entrySet()) {
        final PropertyInfo info = entry.getValue();
        if (info.getReadMethod() == null) {
            fail(browserVersion.getNickname() + " CSSStyleDeclaration: no getter for " + entry.getKey());
        }
        if (info.getWriteMethod() == null && !"length".equals(entry.getKey())) {
            fail(browserVersion.getNickname() + " CSSStyleDeclaration: no setter for " + entry.getKey());
        }
        if (isDefaultGetter(cssLines, info) && isDefaultSetter(cssLines, info)
                && isDefaultGetterComputed(computedLines, info)) {
            fail(browserVersion.getNickname()
                    + " CSSStyleDeclaration: default implementation for " + entry.getKey());
        }
    }
}
 
Example 4
Source Project: htmlunit   Source File: CSSStyleDeclaration.java    License: Apache License 2.0 6 votes vote down vote up
private void updateFont(final String font, final boolean force) {
    final BrowserVersion browserVersion = getBrowserVersion();
    final String[] details = ComputedFont.getDetails(font, !browserVersion.hasFeature(CSS_SET_NULL_THROWS));
    if (details != null || force) {
        final StringBuilder newFont = new StringBuilder();
        newFont.append(getFontSize());
        String lineHeight = getLineHeight();
        final String defaultLineHeight = LINE_HEIGHT.getDefaultComputedValue(browserVersion);
        if (lineHeight.isEmpty()) {
            lineHeight = defaultLineHeight;
        }

        if (browserVersion.hasFeature(CSS_ZINDEX_TYPE_INTEGER) || !lineHeight.equals(defaultLineHeight)) {
            newFont.append('/');
            if (lineHeight.equals(defaultLineHeight)) {
                newFont.append(LINE_HEIGHT.getDefaultComputedValue(browserVersion));
            }
            else {
                newFont.append(lineHeight);
            }
        }

        newFont.append(' ').append(getFontFamily());
        setStyleAttribute(FONT.getAttributeName(), newFont.toString());
    }
}
 
Example 5
Source Project: HtmlUnit-Android   Source File: HTMLParser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create the configuration depending on the simulated browser
 * @param webClient the current WebClient
 * @return the configuration
 */
private static XMLParserConfiguration createConfiguration(final BrowserVersion browserVersion) {
    final HTMLConfiguration configuration = new HTMLConfiguration();
    if (browserVersion.hasFeature(HTML_COMMAND_TAG)) {
        configuration.htmlElements_.setElement(new HTMLElements.Element(HTMLElements.COMMAND, "COMMAND",
                HTMLElements.Element.EMPTY, HTMLElements.BODY, null));
    }
    if (browserVersion.hasFeature(HTML_ISINDEX_TAG)) {
        configuration.htmlElements_.setElement(new HTMLElements.Element(HTMLElements.ISINDEX, "ISINDEX",
                HTMLElements.Element.INLINE, HTMLElements.BODY, null));
    }
    if (browserVersion.hasFeature(HTML_MAIN_TAG)) {
        configuration.htmlElements_.setElement(new HTMLElements.Element(HTMLElements.MAIN, "MAIN",
                HTMLElements.Element.INLINE, HTMLElements.BODY, null));
    }

    return configuration;
}
 
Example 6
Source Project: tool.accelerate.core   Source File: PageFunctionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Ignore
@Test
// TODO: This method of testing does not work for angular, need to find an alternative method of testing
public void techFormTest() {
    final WebClient webClient = new WebClient(BrowserVersion.CHROME);
    HtmlPage page;
    String port = System.getProperty("liberty.test.port");
    try {
        page = webClient.getPage("http://localhost:" + port + "/start/");
        DomElement techForm = page.getElementById("techTable");
        DomElement formBody = techForm.getFirstElementChild();
        int count = formBody.getChildElementCount();
        // We expect there to be more than one child element, otherwise the 
        // javascript has not created the tech table properly.
        assertTrue("Expected more than one element in the tech table, instead found " + count, count > 1);
    } catch (Exception e){
        org.junit.Assert.fail("Caught exception: " + e.getCause().toString());
    } finally {
        webClient.close();
    }
}
 
Example 7
Source Project: HtmlUnit-Android   Source File: HtmlSubmitInput.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Add missing attribute if needed by fixing attribute map rather to add it afterwards as this second option
 * triggers the instantiation of the script object at a time where the DOM node has not yet been added to its
 * parent.
 */
private static Map<String, DomAttr> addValueIfNeeded(final SgmlPage page,
        final Map<String, DomAttr> attributes) {

    final BrowserVersion browserVersion = page.getWebClient().getBrowserVersion();
    if (browserVersion.hasFeature(SUBMITINPUT_DEFAULT_VALUE_IF_VALUE_NOT_DEFINED)) {
        for (final String key : attributes.keySet()) {
            if ("value".equalsIgnoreCase(key)) {
                return attributes; // value attribute was specified
            }
        }

        // value attribute was not specified, add it
        final DomAttr newAttr = new DomAttr(page, null, "value", DEFAULT_VALUE, true);
        attributes.put("value", newAttr);
    }

    return attributes;
}
 
Example 8
Source Project: HtmlUnit-Android   Source File: HTMLInputElement.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sets the value of the JavaScript attribute {@code value}.
 *
 * @param newValue the new value
 */
@Override
public void setValue(final Object newValue) {
    if (null == newValue) {
        getDomNodeOrDie().setValueAttribute("");
        return;
    }

    final String val = Context.toString(newValue);
    final BrowserVersion browserVersion = getBrowserVersion();
    if (StringUtils.isNotEmpty(val) && "file".equalsIgnoreCase(getType())) {
        if (browserVersion.hasFeature(JS_SELECT_FILE_THROWS)) {
            throw Context.reportRuntimeError("InvalidStateError: "
                    + "Failed to set the 'value' property on 'HTMLInputElement'.");
        }
        return;
    }

    getDomNodeOrDie().setValueAttribute(val);
}
 
Example 9
Source Project: HtmlUnit-Android   Source File: DateCustom.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Converts a date to a string, returning the "date" portion using the operating system's locale's conventions.
 * @param context the JavaScript context
 * @param thisObj the scriptable
 * @param args the arguments passed into the method
 * @param function the function
 * @return converted string
 */
public static String toLocaleDateString(
        final Context context, final Scriptable thisObj, final Object[] args, final Function function) {
    final String formatString;
    final BrowserVersion browserVersion = ((Window) thisObj.getParentScope()).getBrowserVersion();

    if (browserVersion.hasFeature(JS_DATE_WITH_LEFT_TO_RIGHT_MARK)) {
        // [U+200E] -> Unicode Character 'LEFT-TO-RIGHT MARK'
        formatString = "\u200EM\u200E/\u200Ed\u200E/\u200Eyyyy";
    }
    else if (browserVersion.hasFeature(JS_DATE_LOCALE_DATE_SHORT)) {
        formatString = "M/d/yyyy";
    }
    else {
        formatString = "EEEE, MMMM dd, yyyy";
    }
    final FastDateFormat format =  FastDateFormat.getInstance(formatString, getLocale(browserVersion));
    return format.format(getDateValue(thisObj));
}
 
Example 10
Source Project: HtmlUnit-Android   Source File: HTMLOptionsCollection.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Removes the option at the specified index.
 * @param index the option index
 */
@JsxFunction
public void remove(final int index) {
    int idx = index;
    final BrowserVersion browser = getBrowserVersion();
    if (idx < 0) {
        if (browser.hasFeature(JS_SELECT_OPTIONS_REMOVE_IGNORE_IF_INDEX_NEGATIVE)) {
            return;
        }
        if (index < 0 && getBrowserVersion().hasFeature(JS_SELECT_OPTIONS_REMOVE_THROWS_IF_NEGATIV)) {
            throw Context.reportRuntimeError("Invalid index for option collection: " + index);
        }
    }

    idx = Math.max(idx, 0);
    if (idx >= getLength()) {
        if (browser.hasFeature(JS_SELECT_OPTIONS_REMOVE_IGNORE_IF_INDEX_TOO_LARGE)) {
            return;
        }
        idx = 0;
    }
    htmlSelect_.removeOption(idx);
}
 
Example 11
Source Project: htmlunit   Source File: HTMLInputElement.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sets the value of the JavaScript attribute {@code value}.
 *
 * @param newValue the new value
 */
@JsxSetter
@Override
public void setValue(final Object newValue) {
    if (null == newValue) {
        getDomNodeOrDie().setValueAttribute("");
        return;
    }

    final String val = Context.toString(newValue);
    final BrowserVersion browserVersion = getBrowserVersion();
    if (StringUtils.isNotEmpty(val) && "file".equalsIgnoreCase(getType())) {
        if (browserVersion.hasFeature(JS_SELECT_FILE_THROWS)) {
            throw Context.reportRuntimeError("InvalidStateError: "
                    + "Failed to set the 'value' property on 'HTMLInputElement'.");
        }
        return;
    }

    getDomNodeOrDie().setValueAttribute(val);
}
 
Example 12
Source Project: htmlunit   Source File: DedicatedWorkerGlobalScope.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 * @param browserVersion the simulated browser version
 * @param worker the started worker
 * @throws Exception in case of problem
 */
DedicatedWorkerGlobalScope(final Window owningWindow, final Context context, final BrowserVersion browserVersion,
        final Worker worker) throws Exception {
    context.initSafeStandardObjects(this);

    ClassConfiguration config = AbstractJavaScriptConfiguration.getClassConfiguration(
            (Class<? extends HtmlUnitScriptable>) DedicatedWorkerGlobalScope.class.getSuperclass(),
            browserVersion);
    final HtmlUnitScriptable parentPrototype = JavaScriptEngine.configureClass(config, null, browserVersion);

    config = AbstractJavaScriptConfiguration.getClassConfiguration(
                            DedicatedWorkerGlobalScope.class, browserVersion);
    final HtmlUnitScriptable prototype = JavaScriptEngine.configureClass(config, null, browserVersion);
    prototype.setPrototype(parentPrototype);
    setPrototype(prototype);

    owningWindow_ = owningWindow;
    final URL currentURL = owningWindow.getWebWindow().getEnclosedPage().getUrl();
    origin_ = currentURL.getProtocol() + "://" + currentURL.getHost() + ':' + currentURL.getPort();

    worker_ = worker;
}
 
Example 13
Source Project: htmlunit   Source File: HtmlElement.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns this element's tab index, if it has one. If the tab index is outside of the
 * valid range (less than <tt>0</tt> or greater than <tt>32767</tt>), this method
 * returns {@link #TAB_INDEX_OUT_OF_BOUNDS}. If this element does not have
 * a tab index, or its tab index is otherwise invalid, this method returns {@code null}.
 *
 * @return this element's tab index
 */
public Short getTabIndex() {
    String index = getAttributeDirect("tabindex");
    if (index == null) {
        return null;
    }
    if (index.isEmpty()) {
        final BrowserVersion browserVersion = getPage().getWebClient().getBrowserVersion();
        if (index != ATTRIBUTE_NOT_DEFINED && browserVersion.hasFeature(HTMLELEMENT_TABINDEX_EMPTY_IS_MINUS_ONE)) {
            index = "-1";
        }
        else {
            return null;
        }
    }
    try {
        final long l = Long.parseLong(index);
        if (l >= 0 && l <= Short.MAX_VALUE) {
            return Short.valueOf((short) l);
        }
        return TAB_INDEX_OUT_OF_BOUNDS;
    }
    catch (final NumberFormatException e) {
        return null;
    }
}
 
Example 14
Source Project: HtmlUnit-Android   Source File: CSSStyleDeclaration.java    License: Apache License 2.0 6 votes vote down vote up
private void updateFont(final String font, final boolean force) {
    final BrowserVersion browserVersion = getBrowserVersion();
    final String[] details = ComputedFont.getDetails(font, !browserVersion.hasFeature(CSS_SET_NULL_THROWS));
    if (details != null || force) {
        final StringBuilder newFont = new StringBuilder();
        newFont.append(getFontSize());
        String lineHeight = getLineHeight();
        final String defaultLineHeight = LINE_HEIGHT.getDefaultComputedValue(browserVersion);
        if (lineHeight.isEmpty()) {
            lineHeight = defaultLineHeight;
        }

        if (browserVersion.hasFeature(CSS_ZINDEX_TYPE_INTEGER) || !lineHeight.equals(defaultLineHeight)) {
            newFont.append('/');
            if (!lineHeight.equals(defaultLineHeight)) {
                newFont.append(lineHeight);
            }
            else {
                newFont.append(LINE_HEIGHT.getDefaultComputedValue(browserVersion));
            }
        }

        newFont.append(' ').append(getFontFamily());
        setStyleAttribute(FONT.getAttributeName(), newFont.toString());
    }
}
 
Example 15
Source Project: htmlunit   Source File: HtmlResetInput.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Add missing attribute if needed by fixing attribute map rather to add it afterwards as this second option
 * triggers the instantiation of the script object at a time where the DOM node has not yet been added to its
 * parent.
 */
private static Map<String, DomAttr> addValueIfNeeded(final SgmlPage page,
        final Map<String, DomAttr> attributes) {

    final BrowserVersion browserVersion = page.getWebClient().getBrowserVersion();
    if (browserVersion.hasFeature(RESETINPUT_DEFAULT_VALUE_IF_VALUE_NOT_DEFINED)) {
        for (final String key : attributes.keySet()) {
            if ("value".equalsIgnoreCase(key)) {
                return attributes; // value attribute was specified
            }
        }

        // value attribute was not specified, add it
        final DomAttr newAttr = new DomAttr(page, null, "value", DEFAULT_VALUE, true);
        attributes.put("value", newAttr);
    }

    return attributes;
}
 
Example 16
Source Project: htmlunit   Source File: HtmlSubmitInput.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Add missing attribute if needed by fixing attribute map rather to add it afterwards as this second option
 * triggers the instantiation of the script object at a time where the DOM node has not yet been added to its
 * parent.
 */
private static Map<String, DomAttr> addValueIfNeeded(final SgmlPage page,
        final Map<String, DomAttr> attributes) {

    final BrowserVersion browserVersion = page.getWebClient().getBrowserVersion();
    if (browserVersion.hasFeature(SUBMITINPUT_DEFAULT_VALUE_IF_VALUE_NOT_DEFINED)) {
        for (final String key : attributes.keySet()) {
            if ("value".equalsIgnoreCase(key)) {
                return attributes; // value attribute was specified
            }
        }

        // value attribute was not specified, add it
        final DomAttr newAttr = new DomAttr(page, null, "value", DEFAULT_VALUE, true);
        attributes.put("value", newAttr);
    }

    return attributes;
}
 
Example 17
Source Project: htmlunit   Source File: HtmlImageInput.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <p>Downloads the image contained by this image element.</p>
 * <p><span style="color:red">POTENTIAL PERFORMANCE KILLER - DOWNLOADS THE IMAGE - USE AT YOUR OWN RISK</span></p>
 * <p>If the image has not already been downloaded, this method triggers a download and caches the image.</p>
 *
 * @throws IOException if an error occurs while downloading the image
 */
private void downloadImageIfNeeded() throws IOException {
    if (!downloaded_) {
        // HTMLIMAGE_BLANK_SRC_AS_EMPTY
        final String src = getSrcAttribute();
        if (!"".equals(src)
                && !(hasFeature(HTMLIMAGE_BLANK_SRC_AS_EMPTY) && StringUtils.isBlank(src))) {
            final HtmlPage page = (HtmlPage) getPage();
            final WebClient webClient = page.getWebClient();

            final URL url = page.getFullyQualifiedUrl(src);
            final BrowserVersion browser = webClient.getBrowserVersion();
            final WebRequest request = new WebRequest(url, browser.getImgAcceptHeader(),
                                                            browser.getAcceptEncodingHeader());
            request.setCharset(page.getCharset());
            request.setAdditionalHeader(HttpHeader.REFERER, page.getUrl().toExternalForm());
            imageWebResponse_ = webClient.loadWebResponse(request);
        }

        downloaded_ = hasFeature(JS_IMAGE_COMPLETE_RETURNS_TRUE_FOR_NO_REQUEST)
                || (imageWebResponse_ != null && imageWebResponse_.getContentType().contains("image"));
    }
}
 
Example 18
Source Project: HtmlUnit-Android   Source File: StyleAttributes.java    License: Apache License 2.0 5 votes vote down vote up
boolean isAvailable(final BrowserVersion browserVersion, final boolean onlyIfIteratable) {
    if (browserConfigurations_ == null) {
        return true; // defined for all browsers
    }

    final BrowserConfiguration config
        = BrowserConfiguration.getMatchingConfiguration(browserVersion, browserConfigurations_);
    return config != null && (!onlyIfIteratable || config.isIteratable());
}
 
Example 19
Source Project: HtmlUnit-Android   Source File: SimpleScriptable.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the browser version currently used.
 * @return the browser version
 */
public BrowserVersion getBrowserVersion() {
    final DomNode node = getDomNodeOrNull();
    if (node != null) {
        return node.getPage().getWebClient().getBrowserVersion();
    }
    return getWindow().getWebWindow().getWebClient().getBrowserVersion();
}
 
Example 20
Source Project: HtmlUnit-Android   Source File: HTMLSpanElement.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets the DOM node that corresponds to this JavaScript object.
 * @param domNode the DOM node
 */
@Override
public void setDomNode(final DomNode domNode) {
    super.setDomNode(domNode);
    final BrowserVersion browser = getBrowserVersion();
    if (browser.hasFeature(HTMLBASEFONT_END_TAG_FORBIDDEN)) {
        switch (domNode.getLocalName().toLowerCase(Locale.ROOT)) {
            case "basefont":
            case "keygen":
                endTagForbidden_ = true;
                break;
            default:
        }
    }
}
 
Example 21
Source Project: htmlunit   Source File: HtmlUnitBrowserCompatCookieSpec.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param browserVersion the {@link BrowserVersion} to simulate
 */
public HtmlUnitBrowserCompatCookieSpec(final BrowserVersion browserVersion) {
    super(new HtmlUnitVersionAttributeHandler(),
            new HtmlUnitDomainHandler(browserVersion),
            new HtmlUnitPathHandler(browserVersion),
            new BasicMaxAgeHandler(),
            new BasicSecureHandler(),
            new BasicCommentHandler(),
            new HtmlUnitExpiresHandler(browserVersion),
            new HtmlUnitHttpOnlyHandler());
}
 
Example 22
Source Project: htmlunit   Source File: JavaScriptEngineTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test for issue #1658.
 * @throws Exception if the test fails
 */
@Test
public void nonStandardBrowserVersion() throws Exception {
    final BrowserVersion browser = new BrowserVersion.BrowserVersionBuilder(BrowserVersion.INTERNET_EXPLORER)
            .setApplicationName("Mozilla")
            .setApplicationVersion("5.0")
            .build();

    try (WebClient client = new WebClient(browser)) {
        client.openWindow(WebClient.URL_ABOUT_BLANK, "TestWindow");
    }
}
 
Example 23
Source Project: HtmlUnit-Android   Source File: AbstractList.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}.
 */
@Override
public Object[] getIds() {
    // let's Rhino work normally if current instance is the prototype
    if (isPrototype()) {
        return super.getIds();
    }

    final List<String> idList = new ArrayList<>();
    final List<DomNode> elements = getElements();

    final BrowserVersion browserVersion = getBrowserVersion();
    if (browserVersion.hasFeature(JS_NODE_LIST_ENUMERATE_FUNCTIONS)) {
        final int length = elements.size();
        for (int i = 0; i < length; i++) {
            idList.add(Integer.toString(i));
        }

        idList.add("length");
        final JavaScriptConfiguration jsConfig = getWindow().getWebWindow().getWebClient()
            .getJavaScriptEngine().getJavaScriptConfiguration();
        for (final String name : jsConfig.getClassConfiguration(getClassName()).getFunctionKeys()) {
            idList.add(name);
        }
    }
    else {
        idList.add("length");
    }
    if (browserVersion.hasFeature(JS_NODE_LIST_ENUMERATE_CHILDREN)) {
        addElementIds(idList, elements);
    }

    return idList.toArray();
}
 
Example 24
Source Project: htmlunit   Source File: JavaScriptConfigurationTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * See issue 1890.
 *
 * @throws Exception if the test fails
 */
@Test
public void original() throws Exception {
    final BrowserVersion browserVersion = BrowserVersion.CHROME;

    test(browserVersion);
}
 
Example 25
Source Project: htmlunit   Source File: AbstractJavaScriptConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
private Map<String, ClassConfiguration> buildUsageMap(final BrowserVersion browser) {
    final Map<String, ClassConfiguration> classMap = new HashMap<>(getClasses().length);

    for (final Class<? extends SimpleScriptable> klass : getClasses()) {
        final ClassConfiguration config = getClassConfiguration(klass, browser);
        if (config != null) {
            classMap.put(config.getClassName(), config);
        }
    }
    return Collections.unmodifiableMap(classMap);
}
 
Example 26
Source Project: htmlunit   Source File: JavaScriptConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the instance that represents the configuration for the specified {@link BrowserVersion}.
 * This method is synchronized to allow multi-threaded access to the JavaScript configuration.
 * @param browserVersion the {@link BrowserVersion}
 * @return the instance for the specified {@link BrowserVersion}
 */
public static synchronized JavaScriptConfiguration getInstance(final BrowserVersion browserVersion) {
    if (browserVersion == null) {
        throw new IllegalArgumentException("BrowserVersion must be provided");
    }
    JavaScriptConfiguration configuration = CONFIGURATION_MAP_.get(browserVersion.getNickname());

    if (configuration == null) {
        configuration = new JavaScriptConfiguration(browserVersion);
        CONFIGURATION_MAP_.put(browserVersion.getNickname(), configuration);
    }
    return configuration;
}
 
Example 27
Source Project: htmlunit   Source File: ComputedCSSStyleDeclaration.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Makes a local, "computed", modification to this CSS style.
 *
 * @param declaration the style declaration
 * @param selector the selector determining that the style applies to this element
 */
public void applyStyleFromSelector(final CSSStyleDeclarationImpl declaration, final Selector selector) {
    final BrowserVersion browserVersion = getBrowserVersion();
    final SelectorSpecificity specificity = selector.getSelectorSpecificity();
    for (Property prop : declaration.getProperties()) {
        final String name = prop.getName();
        if (!browserVersion.hasFeature(CSS_COMPUTED_NO_Z_INDEX) || !"z-index".equals(name)) {
            final String value = declaration.getPropertyValue(name);
            final String priority = declaration.getPropertyPriority(name);
            applyLocalStyleAttribute(name, value, priority, specificity);
        }
    }
}
 
Example 28
@Before
public void setUp() throws Exception {
	driver = MockMvcHtmlUnitDriverBuilder
			.webAppContextSetup(context)
			.withDelegate(new WebConnectionHtmlUnitDriver(BrowserVersion.CHROME))
			.contextPath("")
			.build();
}
 
Example 29
Source Project: htmlunit   Source File: CSSStyleSheet.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Modifies the specified style object by adding any style rules which apply to the specified
 * element.
 *
 * @param style the style to modify
 * @param element the element to which style rules must apply in order for them to be added to
 *        the specified style
 * @param pseudoElement a string specifying the pseudo-element to match (may be {@code null})
 */
public void modifyIfNecessary(final ComputedCSSStyleDeclaration style, final Element element,
        final String pseudoElement) {

    final BrowserVersion browser = getBrowserVersion();
    final DomElement e = element.getDomNodeOrDie();
    final List<CSSStyleSheetImpl.SelectorEntry> matchingRules =
            selects(getRuleIndex(), this, browser, e, pseudoElement, false);
    for (CSSStyleSheetImpl.SelectorEntry entry : matchingRules) {
        final CSSStyleDeclarationImpl dec = entry.getRule().getStyle();
        style.applyStyleFromSelector(dec, entry.getSelector());
    }
}
 
Example 30
Source Project: htmlunit   Source File: CSSStyleSheet.java    License: Apache License 2.0 5 votes vote down vote up
private List<CSSStyleSheetImpl.SelectorEntry> selects(
                        final CSSStyleSheetImpl.CSSStyleSheetRuleIndex index,
                        final SimpleScriptable scriptable,
                        final BrowserVersion browserVersion, final DomElement element,
                        final String pseudoElement, final boolean fromQuerySelectorAll) {

    final List<CSSStyleSheetImpl.SelectorEntry> matchingRules = new ArrayList<>();

    if (CSSStyleSheet.isActive(scriptable, index.getMediaList())) {
        final String elementName = element.getLowercaseName();
        final String[] classes = StringUtils.split(element.getAttributeDirect("class"), null, -1);
        final Iterator<CSSStyleSheetImpl.SelectorEntry> iter =
                index.getSelectorEntriesIteratorFor(elementName, classes);

        CSSStyleSheetImpl.SelectorEntry entry = iter.next();
        while (null != entry) {
            if (CSSStyleSheet.selects(browserVersion, entry.getSelector(),
                                        element, pseudoElement, fromQuerySelectorAll)) {
                matchingRules.add(entry);
            }
            entry = iter.next();
        }

        for (CSSStyleSheetImpl.CSSStyleSheetRuleIndex child : index.getChildren()) {
            matchingRules.addAll(selects(child, scriptable, browserVersion,
                                                element, pseudoElement, fromQuerySelectorAll));
        }
    }

    return matchingRules;
}