com.gargoylesoftware.htmlunit.BrowserVersion Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.BrowserVersion. 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 File: HtmlImageInput.java    From htmlunit with 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 #2
Source File: DateCustom.java    From HtmlUnit-Android with 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 File: JavaScriptConfigurationTest.java    From htmlunit with 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 #4
Source File: HTMLInputElement.java    From HtmlUnit-Android with 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 #5
Source File: CSSStyleDeclarationTest.java    From htmlunit with 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 #6
Source File: CSSStyleDeclaration.java    From htmlunit with 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 #7
Source File: HTMLParser.java    From HtmlUnit-Android with 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 #8
Source File: PageFunctionTest.java    From tool.accelerate.core with 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 #9
Source File: HtmlSubmitInput.java    From HtmlUnit-Android with 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 #10
Source File: DateCustom.java    From HtmlUnit-Android with 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 #11
Source File: HTMLOptionsCollection.java    From HtmlUnit-Android with 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 #12
Source File: HTMLInputElement.java    From htmlunit with 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 #13
Source File: DedicatedWorkerGlobalScope.java    From htmlunit with 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 #14
Source File: HtmlElement.java    From htmlunit with 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 #15
Source File: CSSStyleDeclaration.java    From HtmlUnit-Android with 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 #16
Source File: HtmlResetInput.java    From htmlunit with 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 #17
Source File: HtmlSubmitInput.java    From htmlunit with 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 #18
Source File: SimpleScriptable.java    From HtmlUnit-Android with 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 #19
Source File: JavaScriptConfigurationTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private void test(final BrowserVersion browserVersion) throws IOException {
    try (WebClient webClient = new WebClient(browserVersion)) {
        final MockWebConnection conn = new MockWebConnection();
        conn.setDefaultResponse("<html><body onload='document.body.firstChild'></body></html>");
        webClient.setWebConnection(conn);

        webClient.getPage("http://localhost/");
    }
}
 
Example #20
Source File: StyleAttributes.java    From HtmlUnit-Android with 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 #21
Source File: htmlunitTest.java    From crawler-jsoup-maven with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
    
    // 屏蔽HtmlUnit等系统 log
    LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log","org.apache.commons.logging.impl.NoOpLog");
    java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);
    java.util.logging.Logger.getLogger("org.apache.http.client").setLevel(Level.OFF);
    
    String url = "https://www.newsmth.net/nForum/#!section/Estate";
    System.out.println("Loading page now-----------------------------------------------: "+url);
    
    /* HtmlUnit 模拟浏览器 */
    WebClient webClient = new WebClient(BrowserVersion.CHROME);
    webClient.getOptions().setJavaScriptEnabled(true);              // 启用JS解释器,默认为true  
    webClient.getOptions().setCssEnabled(false);                    // 禁用css支持  
    webClient.getOptions().setThrowExceptionOnScriptError(false);   // js运行错误时,是否抛出异常
    webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
    webClient.getOptions().setTimeout(10 * 1000);                   // 设置连接超时时间
    HtmlPage page = webClient.getPage(url);
    webClient.waitForBackgroundJavaScript(30 * 1000);               // 等待js后台执行30秒

    String pageAsXml = page.asXml();
    
    /* Jsoup解析处理 */
    // Document doc = Jsoup.parse(pageAsXml, "https://bluetata.com/");
    Document doc = Jsoup.parse(pageAsXml);  
    //Elements pngs = doc.select("img[src$=.png]");                   // 获取所有图片元素集
    
    Elements eles = doc.select("td.title_1");
    // 其他操作
    System.out.println(eles.toString());
}
 
Example #22
Source File: HtmlUnitBrowserCompatCookieSpec.java    From htmlunit with 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 #23
Source File: MediaList.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
@Override
public Object getDefaultValue(final Class<?> hint) {
    if (getPrototype() != null) {
        final BrowserVersion browserVersion = getBrowserVersion();
        if (browserVersion.hasFeature(JS_MEDIA_LIST_EMPTY_STRING)) {
            return "";
        }
        if (browserVersion.hasFeature(JS_MEDIA_LIST_ALL)) {
            return "all";
        }
    }
    return super.getDefaultValue(hint);
}
 
Example #24
Source File: Document.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the domain of this document.
 *
 * Domains can only be set to suffixes of the existing domain
 * with the exception of setting the domain to itself.
 * <p>
 * The domain will be set according to the following rules:
 * <ol>
 * <li>If the newDomain.equalsIgnoreCase(currentDomain) the method returns with no error.</li>
 * <li>If the browser version is netscape, the newDomain is downshifted.</li>
 * <li>The change will take place if and only if the suffixes of the
 *       current domain and the new domain match AND there are at least
 *       two domain qualifiers e.g. the following transformations are legal
 *       d1.d2.d3.gargoylesoftware.com may be transformed to itself or:
 *          d2.d3.gargoylesoftware.com
 *             d3.gargoylesoftware.com
 *                gargoylesoftware.com
 *
 *        transformation to:        com
 *        will fail
 * </li>
 * </ol>
 * <p>
 * TODO This code could be modified to understand country domain suffixes.
 * The domain www.bbc.co.uk should be trimmable only down to bbc.co.uk
 * trimming to co.uk should not be possible.
 * @param newDomain the new domain to set
 */
@JsxSetter({CHROME, IE})
public void setDomain(String newDomain) {
    final BrowserVersion browserVersion = getBrowserVersion();

    // IE (at least 6) doesn't allow to set domain of about:blank
    if (WebClient.URL_ABOUT_BLANK == getPage().getUrl()
        && browserVersion.hasFeature(JS_DOCUMENT_SETTING_DOMAIN_THROWS_FOR_ABOUT_BLANK)) {
        throw Context.reportRuntimeError("Illegal domain value, cannot set domain from \""
                + WebClient.URL_ABOUT_BLANK + "\" to: \""
                + newDomain + "\".");
    }

    newDomain = newDomain.toLowerCase(Locale.ROOT);

    final String currentDomain = getDomain();
    if (currentDomain.equalsIgnoreCase(newDomain)) {
        return;
    }

    if (newDomain.indexOf('.') == -1) {
        throw Context.reportRuntimeError("Illegal domain value, cannot set domain from: \""
                + currentDomain + "\" to: \"" + newDomain + "\" (new domain has to contain a dot).");
    }

    if (currentDomain.indexOf('.') > -1
            && !currentDomain.toLowerCase(Locale.ROOT).endsWith("." + newDomain.toLowerCase(Locale.ROOT))) {
        throw Context.reportRuntimeError("Illegal domain value, cannot set domain from: \""
                + currentDomain + "\" to: \"" + newDomain + "\"");
    }

    domain_ = newDomain;
}
 
Example #25
Source File: Document.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Sets a value which indicates whether or not the document can be edited.
 * @param mode a value which indicates whether or not the document can be edited
 */
@JsxSetter({CHROME, IE})
public void setDesignMode(final String mode) {
    final BrowserVersion browserVersion = getBrowserVersion();
    final boolean inherit = browserVersion.hasFeature(JS_DOCUMENT_DESIGN_MODE_INHERIT);
    if (inherit) {
        if (!"on".equalsIgnoreCase(mode) && !"off".equalsIgnoreCase(mode) && !"inherit".equalsIgnoreCase(mode)) {
            throw Context.reportRuntimeError("Invalid document.designMode value '" + mode + "'.");
        }

        if ("on".equalsIgnoreCase(mode)) {
            designMode_ = "on";
        }
        else if ("off".equalsIgnoreCase(mode)) {
            designMode_ = "off";
        }
        else if ("inherit".equalsIgnoreCase(mode)) {
            designMode_ = "inherit";
        }
    }
    else {
        if ("on".equalsIgnoreCase(mode)) {
            designMode_ = "on";
            final SgmlPage page = getPage();
            if (page != null && page.isHtmlPage()
                    && getBrowserVersion().hasFeature(JS_DOCUMENT_SELECTION_RANGE_COUNT)) {
                final HtmlPage htmlPage = (HtmlPage) page;
                final DomNode child = htmlPage.getBody().getFirstChild();
                final DomNode rangeNode = child == null ? htmlPage.getBody() : child;
                htmlPage.setSelectionRange(new SimpleRange(rangeNode, 0));
            }
        }
        else if ("off".equalsIgnoreCase(mode)) {
            designMode_ = "off";
        }
    }
}
 
Example #26
Source File: MSXMLConfiguration.java    From htmlunit with 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 MSXMLConfiguration getInstance(final BrowserVersion browserVersion) {
    if (browserVersion == null) {
        throw new IllegalStateException("BrowserVersion must be defined");
    }
    MSXMLConfiguration configuration = CONFIGURATION_MAP_.get(browserVersion.getNickname());

    if (configuration == null) {
        configuration = new MSXMLConfiguration(browserVersion);
        CONFIGURATION_MAP_.put(browserVersion.getNickname(), configuration);
    }
    return configuration;
}
 
Example #27
Source File: DateTimeFormat.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private DateTimeFormat(final String[] locales, final BrowserVersion browserVersion) {
    final Map<String, String> formats;
    if (browserVersion.isChrome()) {
        formats = CHROME_FORMATS_;
    }
    else if (browserVersion.isIE()) {
        formats = IE_FORMATS_;
    }
    else if (browserVersion.isFirefox60()) {
        formats = FF_60_FORMATS_;
    }
    else if (browserVersion.isFirefox68()) {
        formats = FF_68_FORMATS_;
    }
    else {
        formats = FF_FORMATS_;
    }

    String locale = "";
    String pattern = null;

    for (String l : locales) {
        pattern = getPattern(formats, l);
        if (pattern != null) {
            locale = l;
        }
    }

    if (pattern == null) {
        pattern = formats.get("");
    }
    if (!browserVersion.hasFeature(JS_DATE_WITH_LEFT_TO_RIGHT_MARK) && !locale.startsWith("ar")) {
        pattern = pattern.replace("\u200E", "");
    }

    formatter_ = new DateTimeFormatHelper(locale, browserVersion, pattern);
}
 
Example #28
Source File: Intl.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Define needed properties.
 * @param browserVersion the browser version
 */
public void defineProperties(final BrowserVersion browserVersion) {
    setClassName("Object");
    define(Collator.class, browserVersion);
    define(DateTimeFormat.class, browserVersion);
    define(NumberFormat.class, browserVersion);
    if (browserVersion.hasFeature(JS_INTL_V8_BREAK_ITERATOR)) {
        define(V8BreakIterator.class, browserVersion);
    }
}
 
Example #29
Source File: JavaScriptConfiguration.java    From htmlunit with 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 #30
Source File: DateTimeFormat.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
private DateTimeFormat(final String[] locales, final BrowserVersion browserVersion) {
    final Map<String, String> formats;
    if (browserVersion.isChrome()) {
        formats = CHROME_FORMATS_;
    }
    else if (browserVersion.isIE()) {
        formats = IE_FORMATS_;
    }
    else if (!browserVersion.isFirefox52()) {
        formats = FF_45_FORMATS_;
    }
    else {
        formats = FF_52_FORMATS_;
    }

    String locale = "";
    String pattern = null;

    for (String l : locales) {
        pattern = getPattern(formats, l);
        if (pattern != null) {
            locale = l;
        }
    }

    if (pattern == null) {
        pattern = formats.get("");
    }
    if (!browserVersion.hasFeature(JS_DATE_WITH_LEFT_TO_RIGHT_MARK) && !locale.startsWith("ar")) {
        pattern = pattern.replace("\u200E", "");
    }

    if (GAEUtils.isGaeMode()) {
        formatter_ = new GAEDateTimeFormatter(locale, browserVersion, pattern);
    }
    else {
        formatter_ = new DefaultDateTimeFormatter(locale, browserVersion, pattern);
    }
}