com.gargoylesoftware.htmlunit.BrowserVersion

Here are the examples of the java api com.gargoylesoftware.htmlunit.BrowserVersion taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

117 Examples 7

19 Source : BrowserVersionClassRunner.java
with Apache License 2.0
from Xceptance

/**
 * The runner for test methods that run with a specific browser ({@link BrowserRunner.TestedBrowser}).
 *
 * @author Ahmed Ashour
 * @author Frank Danek
 * @author Ronald Brill
 */
public clreplaced BrowserVersionClreplacedRunner extends BlockJUnit4ClreplacedRunner {

    /**
     * If no alerts defined.
     */
    public static final String[] NO_ALERTS_DEFINED = { "no alerts defined" };

    private final BrowserVersion browserVersion_;

    private final boolean realBrowser_;

    static final boolean maven_ = System.getProperty("htmlunit.maven") != null;

    /**
     * Constructs a new instance.
     * @param klreplaced the clreplaced
     * @param browserVersion the browser version
     * @param realBrowser use real browser or not
     * @throws InitializationError if an error occurs
     */
    public BrowserVersionClreplacedRunner(final Clreplaced<WebTestCase> klreplaced, final BrowserVersion browserVersion, final boolean realBrowser) throws InitializationError {
        super(klreplaced);
        browserVersion_ = browserVersion;
        realBrowser_ = realBrowser;
    }

    private void setAlerts(final WebTestCase testCase, final Method method) {
        final Alerts alerts = method.getAnnotation(Alerts.clreplaced);
        String[] expectedAlerts = {};
        if (alerts != null) {
            expectedAlerts = NO_ALERTS_DEFINED;
            if (isDefined(alerts.value())) {
                expectedAlerts = alerts.value();
            } else {
                if (browserVersion_ == BrowserVersion.INTERNET_EXPLORER) {
                    expectedAlerts = firstDefined(alerts.IE(), alerts.DEFAULT());
                } else if (browserVersion_ == BrowserVersion.EDGE) {
                    expectedAlerts = firstDefined(alerts.EDGE(), alerts.DEFAULT());
                } else if (browserVersion_ == BrowserVersion.FIREFOX_78) {
                    expectedAlerts = firstDefined(alerts.FF78(), alerts.DEFAULT());
                } else if (browserVersion_ == BrowserVersion.FIREFOX) {
                    expectedAlerts = firstDefined(alerts.FF(), alerts.DEFAULT());
                } else if (browserVersion_ == BrowserVersion.CHROME) {
                    expectedAlerts = firstDefined(alerts.CHROME(), alerts.DEFAULT());
                }
            }
        }
        if (isRealBrowser()) {
            final BuggyWebDriver buggyWebDriver = method.getAnnotation(BuggyWebDriver.clreplaced);
            if (buggyWebDriver != null) {
                if (isDefined(buggyWebDriver.value())) {
                    expectedAlerts = buggyWebDriver.value();
                } else {
                    if (browserVersion_ == BrowserVersion.INTERNET_EXPLORER) {
                        expectedAlerts = firstDefinedOrGiven(expectedAlerts, buggyWebDriver.IE(), buggyWebDriver.DEFAULT());
                    } else if (browserVersion_ == BrowserVersion.EDGE) {
                        expectedAlerts = firstDefinedOrGiven(expectedAlerts, buggyWebDriver.EDGE(), buggyWebDriver.DEFAULT());
                    } else if (browserVersion_ == BrowserVersion.FIREFOX_78) {
                        expectedAlerts = firstDefinedOrGiven(expectedAlerts, buggyWebDriver.FF78(), buggyWebDriver.DEFAULT());
                    } else if (browserVersion_ == BrowserVersion.FIREFOX) {
                        expectedAlerts = firstDefinedOrGiven(expectedAlerts, buggyWebDriver.FF(), buggyWebDriver.DEFAULT());
                    } else if (browserVersion_ == BrowserVersion.CHROME) {
                        expectedAlerts = firstDefinedOrGiven(expectedAlerts, buggyWebDriver.CHROME(), buggyWebDriver.DEFAULT());
                    }
                }
            }
        } else {
            final HtmlUnitNYI htmlUnitNYI = method.getAnnotation(HtmlUnitNYI.clreplaced);
            if (htmlUnitNYI != null) {
                if (browserVersion_ == BrowserVersion.INTERNET_EXPLORER) {
                    expectedAlerts = firstDefinedOrGiven(expectedAlerts, htmlUnitNYI.IE());
                } else if (browserVersion_ == BrowserVersion.EDGE) {
                    expectedAlerts = firstDefinedOrGiven(expectedAlerts, htmlUnitNYI.EDGE());
                } else if (browserVersion_ == BrowserVersion.FIREFOX_78) {
                    expectedAlerts = firstDefinedOrGiven(expectedAlerts, htmlUnitNYI.FF78());
                } else if (browserVersion_ == BrowserVersion.FIREFOX) {
                    expectedAlerts = firstDefinedOrGiven(expectedAlerts, htmlUnitNYI.FF());
                } else if (browserVersion_ == BrowserVersion.CHROME) {
                    expectedAlerts = firstDefinedOrGiven(expectedAlerts, htmlUnitNYI.CHROME());
                }
            }
        }
        testCase.setExpectedAlerts(expectedAlerts);
    }

    private void setAlertsStandards(final WebTestCase testCase, final Method method) {
        final AlertsStandards alerts = method.getAnnotation(AlertsStandards.clreplaced);
        if (alerts != null) {
            String[] expectedAlerts = NO_ALERTS_DEFINED;
            if (isDefined(alerts.value())) {
                expectedAlerts = alerts.value();
            } else {
                if (browserVersion_ == BrowserVersion.INTERNET_EXPLORER) {
                    expectedAlerts = firstDefined(alerts.IE(), alerts.DEFAULT());
                } else if (browserVersion_ == BrowserVersion.EDGE) {
                    expectedAlerts = firstDefined(alerts.EDGE(), alerts.DEFAULT());
                } else if (browserVersion_ == BrowserVersion.FIREFOX_78) {
                    expectedAlerts = firstDefined(alerts.FF78(), alerts.DEFAULT());
                } else if (browserVersion_ == BrowserVersion.FIREFOX) {
                    expectedAlerts = firstDefined(alerts.FF(), alerts.DEFAULT());
                } else if (browserVersion_ == BrowserVersion.CHROME) {
                    expectedAlerts = firstDefined(alerts.CHROME(), alerts.DEFAULT());
                }
            }
            testCase.setExpectedAlerts(expectedAlerts);
        } else {
            setAlerts(testCase, method);
        }
    }

    private static String[] firstDefined(final String[]... variants) {
        for (final String[] var : variants) {
            if (isDefined(var)) {
                return var;
            }
        }
        return NO_ALERTS_DEFINED;
    }

    public static String[] firstDefinedOrGiven(final String[] given, final String[]... variants) {
        for (final String[] var : variants) {
            if (isDefined(var)) {
                try {
                    replacedertArrayEquals(var, given);
                    fail("BuggyWebDriver duplicates expectations");
                } catch (final replacedertionError e) {
                // ok
                }
                return var;
            }
        }
        return given;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Object createTest() throws Exception {
        final Object test = super.createTest();
        replacedertTrue("Test clreplaced must inherit WebTestCase", test instanceof WebTestCase);
        final WebTestCase object = (WebTestCase) test;
        object.setBrowserVersion(browserVersion_);
        if (test instanceof WebDriverTestCase) {
            ((WebDriverTestCase) test).setUseRealBrowser(realBrowser_);
        }
        return object;
    }

    @Override
    protected String getName() {
        String browserString = browserVersion_.getNickname();
        if (realBrowser_) {
            browserString = "Real " + browserString;
        }
        return String.format("[%s]", browserString);
    }

    @Override
    protected String testName(final FrameworkMethod method) {
        String prefix = "";
        if (isNotYetImplemented(method) && !realBrowser_) {
            prefix = "(NYI) ";
        }
        String browserString = browserVersion_.getNickname();
        if (realBrowser_) {
            browserString = "Real " + browserString;
        }
        if (!maven_) {
            return String.format("%s [%s]", method.getName(), browserString);
        }
        String clreplacedName = method.getMethod().getDeclaringClreplaced().getName();
        clreplacedName = clreplacedName.substring(clreplacedName.lastIndexOf('.') + 1);
        return String.format("%s%s [%s]", prefix, clreplacedName + '.' + method.getName(), browserString);
    }

    /**
     * Does the test clreplaced contains test methods.
     *
     * @param klreplaced the clreplaced
     * @return whether it contains test methods or not
     */
    public static boolean containsTestMethods(final Clreplaced<WebTestCase> klreplaced) {
        for (final Method method : klreplaced.getMethods()) {
            if (method.getAnnotation(Test.clreplaced) != null) {
                return true;
            }
        }
        return false;
    }

    public static boolean isDefined(final String[] alerts) {
        return alerts.length != 1 || !alerts[0].equals(BrowserRunner.EMPTY_DEFAULT);
    }

    /**
     * Returns true if current {@link #browserVersion_} is contained in the specific <tt>browsers</tt>.
     */
    private boolean isDefinedIn(final TestedBrowser[] browsers) {
        for (final TestedBrowser browser : browsers) {
            switch(browser) {
                case IE:
                    if (browserVersion_ == BrowserVersion.INTERNET_EXPLORER) {
                        return true;
                    }
                    break;
                case EDGE:
                    if (browserVersion_ == BrowserVersion.EDGE) {
                        return true;
                    }
                    break;
                case FF78:
                    if (browserVersion_ == BrowserVersion.FIREFOX_78) {
                        return true;
                    }
                    break;
                case FF:
                    if (browserVersion_ == BrowserVersion.FIREFOX) {
                        return true;
                    }
                    break;
                case CHROME:
                    if (browserVersion_ == BrowserVersion.CHROME) {
                        return true;
                    }
                    break;
                default:
            }
        }
        return false;
    }

    @Override
    @SuppressWarnings("deprecation")
    protected Statement methodBlock(final FrameworkMethod method) {
        final Object test;
        final WebTestCase testCase;
        try {
            testCase = (WebTestCase) createTest();
            test = new ReflectiveCallable() {

                @Override
                protected Object runReflectiveCall() throws Throwable {
                    return testCase;
                }
            }.run();
        } catch (final Throwable e) {
            return new Fail(e);
        }
        Statement statement = methodInvoker(method, test);
        statement = possiblyExpectingExceptions(method, test, statement);
        statement = withPotentialTimeout(method, test, statement);
        statement = withBefores(method, test, statement);
        statement = withAfters(method, test, statement);
        statement = withRules(method, test, statement);
        statement = withInterruptIsolation(statement);
        // End of copy & paste from super.methodBlock()  //
        boolean notYetImplemented = false;
        final int tries;
        if (testCase instanceof WebDriverTestCase && realBrowser_) {
            tries = 1;
        } else {
            notYetImplemented = isNotYetImplemented(method);
            tries = getTries(method);
        }
        if (method instanceof StandardsFrameworkMethod && ((StandardsFrameworkMethod) method).isStandards()) {
            setAlertsStandards(testCase, method.getMethod());
        } else {
            setAlerts(testCase, method.getMethod());
        }
        statement = new BrowserStatement(statement, method, realBrowser_, notYetImplemented, tries, browserVersion_);
        return statement;
    }

    private Statement withRules(final FrameworkMethod method, final Object target, final Statement statement) {
        Statement result = statement;
        result = withMethodRules(method, target, result);
        result = withTestRules(method, target, result);
        return result;
    }

    private Statement withMethodRules(final FrameworkMethod method, final Object target, Statement result) {
        final List<TestRule> testRules = getTestRules(target);
        for (final org.junit.rules.MethodRule each : getMethodRules(target)) {
            if (!testRules.contains(each)) {
                result = each.apply(result, method, target);
            }
        }
        return result;
    }

    private List<org.junit.rules.MethodRule> getMethodRules(final Object target) {
        return rules(target);
    }

    /**
     * Returns a Statement.
     *
     * @param statement The base statement
     * @return a RunRules statement if any clreplaced-level Rule are found, or the base statement
     */
    private Statement withTestRules(final FrameworkMethod method, final Object target, final Statement statement) {
        final List<TestRule> testRules = getTestRules(target);
        return testRules.isEmpty() ? statement : new RunRules(statement, testRules, describeChild(method));
    }

    /**
     * Returns if not yet implemented.
     * @param method the method
     * @return if not yet implemented
     */
    protected boolean isNotYetImplemented(final FrameworkMethod method) {
        final NotYetImplemented notYetImplementedBrowsers = method.getAnnotation(NotYetImplemented.clreplaced);
        return notYetImplementedBrowsers != null && isDefinedIn(notYetImplementedBrowsers.value());
    }

    private static int getTries(final FrameworkMethod method) {
        final Tries tries = method.getAnnotation(Tries.clreplaced);
        return tries != null ? tries.value() : 1;
    }

    /**
     * Returns the browser version.
     * @return the browser version
     */
    protected BrowserVersion getBrowserVersion() {
        return browserVersion_;
    }

    /**
     * Is real browser.
     * @return whether we are using real browser or not
     */
    protected boolean isRealBrowser() {
        return realBrowser_;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected TestClreplaced createTestClreplaced(final Clreplaced<?> testClreplaced) {
        if (testClreplaced.getAnnotation(StandardsMode.clreplaced) != null) {
            return new StandardsTestClreplaced(testClreplaced);
        }
        return super.createTestClreplaced(testClreplaced);
    }
}

19 Source : BrowserStatement.java
with Apache License 2.0
from Xceptance

private void replacedertNotEquals(final BrowserVersion browser, final String[] value1, final String[] value2) {
    if (value1.length != 0 && !BrowserRunner.EMPTY_DEFAULT.equals(value1[0]) && value1.length == value2.length && Arrays.asList(value1).toString().equals(Arrays.asList(value2).toString())) {
        throw new replacedertionError("Redundant alert for " + browser.getNickname() + " in " + method_.getDeclaringClreplaced().getSimpleName() + '.' + method_.getName() + "()");
    }
}

19 Source : HtmlUnitContextFactoryTest.java
with Apache License 2.0
from Xceptance

/**
 * @throws Exception if the test fails
 */
@Test
public void customBrowserVersion() throws Exception {
    final String html = "<html></html>";
    final BrowserVersion browserVersion = new BrowserVersion.BrowserVersionBuilder(BrowserVersion.FIREFOX_78).setApplicationName("Firefox").setApplicationVersion("5.0 (Windows NT 10.0; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0").setUserAgent("Mozilla/5.0 (Windows NT 10.0; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0").build();
    loadPage(browserVersion, html, null, URL_FIRST);
}

19 Source : StyleAttributesIterableTest.java
with Apache License 2.0
from Xceptance

/**
 * {@inheritDoc}
 */
@Override
protected String[] getExpectedAlerts() {
    if (definition_ == null) {
        return super.getExpectedAlerts();
    }
    final BrowserVersion browserVersion = getBrowserVersion();
    return new String[] { Boolean.toString(definition_.isAvailable(browserVersion, true)) };
}

19 Source : JavaScriptConfigurationTest.java
with Apache License 2.0
from Xceptance

/**
 * See issue 1890.
 *
 * @throws Exception if the test fails
 */
@Test
public void clonedAndModified() throws Exception {
    final BrowserVersion browserVersion = new BrowserVersion.BrowserVersionBuilder(BrowserVersion.FIREFOX).setUserAgent("foo").build();
    test(browserVersion);
}

19 Source : JavaScriptConfigurationTest.java
with Apache License 2.0
from Xceptance

/**
 * See issue 1890.
 *
 * @throws Exception if the test fails
 */
@Test
public void cloned() throws Exception {
    final BrowserVersion browserVersion = new BrowserVersion.BrowserVersionBuilder(BrowserVersion.FIREFOX).build();
    test(browserVersion);
}

19 Source : JavaScriptConfigurationTest.java
with Apache License 2.0
from Xceptance

/**
 * Tests that all clreplacedes included in {@link JavaScriptConfiguration#CLreplacedES_} defining an
 * {@link JsxClreplacedes}/{@link JsxClreplaced} annotation for at least one browser.
 */
@Test
public void obsoleteJsxClreplacedes() {
    final JavaScriptConfiguration config = JavaScriptConfiguration.getInstance(FIREFOX);
    for (final Clreplaced<? extends SimpleScriptable> klreplaced : config.getClreplacedes()) {
        boolean found = false;
        for (final BrowserVersion browser : BrowserVersion.ALL_SUPPORTED_BROWSERS) {
            if (AbstractJavaScriptConfiguration.getClreplacedConfiguration(klreplaced, browser) != null) {
                found = true;
                break;
            }
        }
        replacedertTrue("Clreplaced " + klreplaced + " is member of JavaScriptConfiguration.CLreplacedES_ but does not define @JsxClreplacedes/@JsxClreplaced", found);
    }
}

19 Source : XltDriver.java
with Apache License 2.0
from Xceptance

/**
 * Returns a new web client instance to be used by this driver. Overwritten to return an enhanced XLT web client
 * instead of HtmlUnit's web client.
 *
 * @param version
 *            which browser to emulate
 * @return the web client
 */
@Override
protected WebClient newWebClient(final BrowserVersion version) {
    return new WebDriverXltWebClient(version);
}

19 Source : HTMLInputElement.java
with Apache License 2.0
from Xceptance

/**
 * Returns whether the specified type is supported or not.
 * @param type
 * @param browserVersion
 * @return whether the specified type is supported or not
 */
private static boolean isSupported(final String type, final BrowserVersion browserVersion) {
    boolean supported = false;
    switch(type) {
        case "date":
            supported = browserVersion.hasFeature(HTMLINPUT_TYPE_DATETIME_SUPPORTED);
            break;
        case "datetime-local":
            supported = browserVersion.hasFeature(HTMLINPUT_TYPE_DATETIME_LOCAL_SUPPORTED);
            break;
        case "month":
            supported = browserVersion.hasFeature(HTMLINPUT_TYPE_MONTH_SUPPORTED);
            break;
        case "time":
            supported = browserVersion.hasFeature(HTMLINPUT_TYPE_DATETIME_SUPPORTED);
            break;
        case "week":
            supported = browserVersion.hasFeature(HTMLINPUT_TYPE_WEEK_SUPPORTED);
            break;
        case "color":
            supported = !browserVersion.hasFeature(HTMLINPUT_TYPE_COLOR_NOT_SUPPORTED);
            break;
        case "email":
        case "text":
        case "submit":
        case "checkbox":
        case "radio":
        case "hidden":
        case "preplacedword":
        case "image":
        case "reset":
        case "button":
        case "file":
        case "number":
        case "range":
        case "search":
        case "tel":
        case "url":
            supported = true;
            break;
        default:
    }
    return supported;
}

19 Source : HTMLAllCollection.java
with Apache License 2.0
from Xceptance

/**
 * Returns the item or items corresponding to the specified index or key.
 * @param index the index or key corresponding to the element or elements to return
 * @return the element or elements corresponding to the specified index or key
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms536460.aspx">MSDN doc</a>
 */
@Override
public Object item(final Object index) {
    Double numb;
    final BrowserVersion browser;
    if (index instanceof String) {
        final String name = (String) index;
        final Object result = namedItem(name);
        if (null != result && !Undefined.isUndefined(result)) {
            return result;
        }
        numb = Double.NaN;
        browser = getBrowserVersion();
        if (!browser.hasFeature(HTMLALLCOLLECTION_DO_NOT_CONVERT_STRINGS_TO_NUMBER)) {
            numb = ScriptRuntime.toNumber(index);
        }
        if (numb.isNaN()) {
            return null;
        }
    } else {
        numb = ScriptRuntime.toNumber(index);
        browser = getBrowserVersion();
    }
    if (numb < 0) {
        return null;
    }
    if (!browser.hasFeature(HTMLCOLLECTION_ITEM_FUNCT_SUPPORTS_DOUBLE_INDEX_ALSO) && (Double.isInfinite(numb) || numb != Math.floor(numb))) {
        return null;
    }
    final Object object = get(numb.intValue(), this);
    if (object == NOT_FOUND) {
        return null;
    }
    return object;
}

19 Source : BeforeUnloadEvent.java
with Apache License 2.0
from Xceptance

@Override
void handlePropertyHandlerReturnValue(final Object returnValue) {
    super.handlePropertyHandlerReturnValue(returnValue);
    final BrowserVersion browserVersion = getBrowserVersion();
    // Most browsers ignore null return values of property handlers
    if (returnValue != null || browserVersion.hasFeature(EVENT_HANDLER_NULL_RETURN_IS_MEANINGFUL)) {
        // Chrome/Firefox only accept the return value if returnValue is equal to default
        if (!browserVersion.hasFeature(EVENT_BEFORE_UNLOAD_RETURN_VALUE_IS_HTML5_LIKE) || getReturnValueDefault(browserVersion).equals(getReturnValue())) {
            setReturnValue(returnValue);
        }
    }
}

19 Source : DateCustom.java
with Apache License 2.0
from Xceptance

private static Locale getLocale(final BrowserVersion browserVersion) {
    return new Locale(browserVersion.getSystemLanguage());
}

19 Source : BrowserConfiguration.java
with Apache License 2.0
from Xceptance

static BrowserConfiguration getMatchingConfiguration(final BrowserVersion browserVersion, final BrowserConfiguration[] browserConfigurations) {
    for (final BrowserConfiguration browserConfiguration : browserConfigurations) {
        if (browserConfiguration.matches(browserVersion)) {
            return browserConfiguration;
        }
    }
    return null;
}

19 Source : AbstractJavaScriptConfiguration.java
with Apache License 2.0
from Xceptance

private Map<String, ClreplacedConfiguration> buildUsageMap(final BrowserVersion browser) {
    final Map<String, ClreplacedConfiguration> clreplacedMap = new ConcurrentHashMap<>(getClreplacedes().length);
    for (final Clreplaced<? extends SimpleScriptable> klreplaced : getClreplacedes()) {
        final ClreplacedConfiguration config = getClreplacedConfiguration(klreplaced, browser);
        if (config != null) {
            clreplacedMap.put(config.getClreplacedName(), config);
        }
    }
    return clreplacedMap;
}

19 Source : AbstractJavaScriptConfiguration.java
with Apache License 2.0
from Xceptance

/**
 * Returns the clreplaced configuration of the given {@code klreplaced}.
 *
 * @param klreplaced the clreplaced
 * @param browser the browser version
 * @return the clreplaced configuration
 */
public static ClreplacedConfiguration getClreplacedConfiguration(final Clreplaced<? extends HtmlUnitScriptable> klreplaced, final BrowserVersion browser) {
    if (browser != null) {
        final SupportedBrowser expectedBrowser;
        if (browser.isChrome()) {
            expectedBrowser = CHROME;
        } else if (browser.isEdge()) {
            expectedBrowser = EDGE;
        } else if (browser.isIE()) {
            expectedBrowser = IE;
        } else if (browser.isFirefox78()) {
            expectedBrowser = FF78;
        } else if (browser.isFirefox()) {
            expectedBrowser = FF;
        } else {
            // our current fallback
            expectedBrowser = CHROME;
        }
        final String hostClreplacedName = klreplaced.getName();
        final JsxClreplacedes jsxClreplacedes = klreplaced.getAnnotation(JsxClreplacedes.clreplaced);
        if (jsxClreplacedes != null) {
            if (klreplaced.getAnnotation(JsxClreplaced.clreplaced) != null) {
                throw new RuntimeException("Invalid JsxClreplacedes/JsxClreplaced annotation; clreplaced '" + hostClreplacedName + "' has both.");
            }
            final JsxClreplaced[] jsxClreplacedValues = jsxClreplacedes.value();
            if (jsxClreplacedValues.length == 1) {
                throw new RuntimeException("No need to specify JsxClreplacedes with a single JsxClreplaced for " + hostClreplacedName);
            }
            final Set<Clreplaced<?>> domClreplacedes = new HashSet<>();
            boolean isJsObject = false;
            String clreplacedName = null;
            String extendedClreplacedName = "";
            final Clreplaced<?> superClreplaced = klreplaced.getSuperclreplaced();
            if (superClreplaced == SimpleScriptable.clreplaced) {
                extendedClreplacedName = "";
            } else {
                extendedClreplacedName = superClreplaced.getSimpleName();
            }
            for (final JsxClreplaced jsxClreplaced : jsxClreplacedValues) {
                if (jsxClreplaced != null && isSupported(jsxClreplaced.value(), expectedBrowser)) {
                    domClreplacedes.add(jsxClreplaced.domClreplaced());
                    if (jsxClreplaced.isJSObject()) {
                        isJsObject = true;
                    }
                    if (!jsxClreplaced.clreplacedName().isEmpty()) {
                        clreplacedName = jsxClreplaced.clreplacedName();
                    }
                    if (jsxClreplaced.extendedClreplaced() != Object.clreplaced) {
                        if (jsxClreplaced.extendedClreplaced() == SimpleScriptable.clreplaced) {
                            extendedClreplacedName = "";
                        } else {
                            extendedClreplacedName = jsxClreplaced.extendedClreplaced().getSimpleName();
                        }
                    }
                }
            }
            final ClreplacedConfiguration clreplacedConfiguration = new ClreplacedConfiguration(klreplaced, domClreplacedes.toArray(new Clreplaced<?>[domClreplacedes.size()]), isJsObject, clreplacedName, extendedClreplacedName);
            process(clreplacedConfiguration, hostClreplacedName, expectedBrowser);
            return clreplacedConfiguration;
        }
        final JsxClreplaced jsxClreplaced = klreplaced.getAnnotation(JsxClreplaced.clreplaced);
        if (jsxClreplaced != null && isSupported(jsxClreplaced.value(), expectedBrowser)) {
            final Set<Clreplaced<?>> domClreplacedes = new HashSet<>();
            final Clreplaced<?> domClreplaced = jsxClreplaced.domClreplaced();
            if (domClreplaced != null && domClreplaced != Object.clreplaced) {
                domClreplacedes.add(domClreplaced);
            }
            String clreplacedName = jsxClreplaced.clreplacedName();
            if (clreplacedName.isEmpty()) {
                clreplacedName = null;
            }
            String extendedClreplacedName = "";
            final Clreplaced<?> superClreplaced = klreplaced.getSuperclreplaced();
            if (superClreplaced != SimpleScriptable.clreplaced) {
                extendedClreplacedName = superClreplaced.getSimpleName();
            } else {
                extendedClreplacedName = "";
            }
            if (jsxClreplaced.extendedClreplaced() != Object.clreplaced) {
                extendedClreplacedName = jsxClreplaced.extendedClreplaced().getSimpleName();
            }
            final ClreplacedConfiguration clreplacedConfiguration = new ClreplacedConfiguration(klreplaced, domClreplacedes.toArray(new Clreplaced<?>[domClreplacedes.size()]), jsxClreplaced.isJSObject(), clreplacedName, extendedClreplacedName);
            process(clreplacedConfiguration, hostClreplacedName, expectedBrowser);
            return clreplacedConfiguration;
        }
    }
    return null;
}

19 Source : HtmlUnitPathHandler.java
with Apache License 2.0
from Xceptance

/**
 * Customized BasicPathHandler for HtmlUnit.
 *
 * @author <a href="mailto:[email protected]">Mike Bowler</a>
 * @author Noboru Sinohara
 * @author David D. Kilzer
 * @author Marc Guillemot
 * @author Brad Clarke
 * @author Ahmed Ashour
 * @author Nicolas Belisle
 * @author Ronald Brill
 * @author John J Murdoch
 */
final clreplaced HtmlUnitPathHandler extends BasicPathHandler {

    private final BrowserVersion browserVersion_;

    HtmlUnitPathHandler(final BrowserVersion browserVersion) {
        browserVersion_ = browserVersion;
    }

    @Override
    public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException {
    // nothing, browsers seem not to perform any validation
    }

    @Override
    public boolean match(final Cookie cookie, final CookieOrigin origin) {
        CookieOrigin newOrigin = origin;
        String targetpath = origin.getPath();
        if (browserVersion_.hasFeature(HTTP_COOKIE_EXTRACT_PATH_FROM_LOCATION) && !targetpath.isEmpty()) {
            final int lastSlashPos = targetpath.lastIndexOf('/');
            if (lastSlashPos > 1 && lastSlashPos < targetpath.length()) {
                targetpath = targetpath.substring(0, lastSlashPos);
                newOrigin = new CookieOrigin(origin.getHost(), origin.getPort(), targetpath, origin.isSecure());
            }
        }
        return super.match(cookie, newOrigin);
    }
}

19 Source : HtmlUnitExpiresHandler.java
with Apache License 2.0
from Xceptance

/**
 * Customized BasicExpiresHandler for HtmlUnit.
 *
 * @author <a href="mailto:[email protected]">Mike Bowler</a>
 * @author Noboru Sinohara
 * @author David D. Kilzer
 * @author Marc Guillemot
 * @author Brad Clarke
 * @author Ahmed Ashour
 * @author Nicolas Belisle
 * @author Ronald Brill
 * @author John J Murdoch
 */
final clreplaced HtmlUnitExpiresHandler extends BasicExpiresHandler {

    // simplified patterns from BrowserCompatSpec, with yy patterns before similar yyyy patterns
    private static final String[] DEFAULT_DATE_PATTERNS = { "EEE MMM dd yyyy HH mm ss 'GMT'Z", "EEE dd MMM yy HH mm ss zzz", "EEE dd MMM yyyy HH mm ss zzz", "EEE MMM d HH mm ss yyyy", "EEE dd MMM yy HH mm ss z ", "EEE dd MMM yyyy HH mm ss z ", "EEE dd MM yy HH mm ss z ", "EEE dd MM yyyy HH mm ss z " };

    private static final String[] EXTENDED_DATE_PATTERNS_1 = { "EEE MMM dd yyyy HH mm ss 'GMT'Z", "EEE dd MMM yy HH mm ss zzz", "EEE dd MMM yyyy HH mm ss zzz", "EEE MMM d HH mm ss yyyy", "EEE dd MMM yy HH mm ss z ", "EEE dd MMM yyyy HH mm ss z ", "EEE dd MM yy HH mm ss z ", "EEE dd MM yyyy HH mm ss z ", "d/M/yyyy" };

    private static final String[] EXTENDED_DATE_PATTERNS_2 = { "EEE MMM dd yyyy HH mm ss 'GMT'Z", "EEE dd MMM yy HH mm ss zzz", "EEE dd MMM yyyy HH mm ss zzz", "EEE MMM d HH mm ss yyyy", "EEE dd MMM yy HH mm ss z ", "EEE dd MMM yyyy HH mm ss z ", "EEE dd MM yy HH mm ss z ", "EEE dd MM yyyy HH mm ss z ", "EEE dd MMM yy HH MM ss z", "MMM dd yy HH mm ss" };

    private final BrowserVersion browserVersion_;

    HtmlUnitExpiresHandler(final BrowserVersion browserVersion) {
        super(DEFAULT_DATE_PATTERNS);
        browserVersion_ = browserVersion;
    }

    @Override
    public void parse(final SetCookie cookie, String value) throws MalformedCookieException {
        if (value.startsWith("\"") && value.endsWith("\"")) {
            value = value.substring(1, value.length() - 1);
        }
        value = value.replaceAll("[ ,:-]+", " ");
        Date startDate = null;
        String[] datePatterns = DEFAULT_DATE_PATTERNS;
        if (null != browserVersion_) {
            if (browserVersion_.hasFeature(HTTP_COOKIE_START_DATE_1970)) {
                startDate = HtmlUnitBrowserCompatCookieSpec.DATE_1_1_1970;
            }
            if (browserVersion_.hasFeature(HTTP_COOKIE_EXTENDED_DATE_PATTERNS_1)) {
                datePatterns = EXTENDED_DATE_PATTERNS_1;
            }
            if (browserVersion_.hasFeature(HTTP_COOKIE_EXTENDED_DATE_PATTERNS_2)) {
                final Calendar calendar = Calendar.getInstance(Locale.ROOT);
                calendar.setTimeZone(DateUtils.GMT);
                calendar.set(1969, Calendar.JANUARY, 1, 0, 0, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                startDate = calendar.getTime();
                datePatterns = EXTENDED_DATE_PATTERNS_2;
            }
        }
        final Date expiry = DateUtils.parseDate(value, datePatterns, startDate);
        cookie.setExpiryDate(expiry);
    }
}

19 Source : HtmlUnitDomainHandler.java
with Apache License 2.0
from Xceptance

/**
 * Customized BasicDomainHandler for HtmlUnit.
 *
 * @author Ronald Brill
 * @author Ahmed Ashour
 */
final clreplaced HtmlUnitDomainHandler extends BasicDomainHandler {

    private final BrowserVersion browserVersion_;

    HtmlUnitDomainHandler(final BrowserVersion browserVersion) {
        browserVersion_ = browserVersion;
    }

    @Override
    public void parse(final SetCookie cookie, final String value) throws MalformedCookieException {
        Args.notNull(cookie, HttpHeader.COOKIE);
        if (TextUtils.isBlank(value)) {
            throw new MalformedCookieException("Blank or null value for domain attribute");
        }
        // Ignore domain attributes ending with '.' per RFC 6265, 4.1.2.3
        if (value.endsWith(".")) {
            return;
        }
        String domain = value;
        domain = domain.toLowerCase(Locale.ROOT);
        final int dotIndex = domain.indexOf('.');
        if (browserVersion_.hasFeature(HTTP_COOKIE_REMOVE_DOT_FROM_ROOT_DOMAINS) && dotIndex == 0 && domain.length() > 1 && domain.indexOf('.', 1) == -1) {
            domain = domain.toLowerCase(Locale.ROOT);
            domain = domain.substring(1);
        }
        if (dotIndex > 0) {
            domain = '.' + domain;
        }
        cookie.setDomain(domain);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean match(final Cookie cookie, final CookieOrigin origin) {
        String domain = cookie.getDomain();
        if (domain == null) {
            return false;
        }
        final int dotIndex = domain.indexOf('.');
        if (dotIndex == 0 && domain.length() > 1 && domain.indexOf('.', 1) == -1) {
            final String host = origin.getHost();
            domain = domain.toLowerCase(Locale.ROOT);
            if (browserVersion_.hasFeature(HTTP_COOKIE_REMOVE_DOT_FROM_ROOT_DOMAINS)) {
                domain = domain.substring(1);
            }
            return host.equals(domain);
        }
        if (dotIndex == -1 && !HtmlUnitBrowserCompatCookieSpec.LOCAL_FILESYSTEM_DOMAIN.equalsIgnoreCase(domain)) {
            try {
                InetAddress.getByName(domain);
            } catch (final UnknownHostException e) {
                return false;
            }
        }
        return super.match(cookie, origin);
    }
}

19 Source : HtmlUnitCookieSpecProvider.java
with Apache License 2.0
from Xceptance

/**
 * Customized CookieSpecProvider for HtmlUnit.
 *
 * @author Ronald Brill
 */
public final clreplaced HtmlUnitCookieSpecProvider implements CookieSpecProvider {

    private final BrowserVersion browserVersion_;

    /**
     * Constructor.
     * @param browserVersion the browserVersion
     */
    public HtmlUnitCookieSpecProvider(final BrowserVersion browserVersion) {
        browserVersion_ = browserVersion;
    }

    @Override
    public CookieSpec create(final HttpContext context) {
        return new HtmlUnitBrowserCompatCookieSpec(browserVersion_);
    }
}

19 Source : HtmlForm.java
with Apache License 2.0
from Xceptance

/**
 * Check if element which cause submit contains new html5 attributes
 * (formaction, formmethod, formtarget, formenctype)
 * and override existing values
 * @param submitElement
 */
private void updateHtml5Attributes(final SubmittableElement submitElement) {
    if (submitElement instanceof HtmlElement) {
        final HtmlElement element = (HtmlElement) submitElement;
        final String type = element.getAttributeDirect("type");
        boolean typeImage = false;
        final boolean typeSubmit = "submit".equalsIgnoreCase(type);
        final boolean isInput = HtmlInput.TAG_NAME.equals(element.getTagName());
        if (isInput) {
            typeImage = "image".equalsIgnoreCase(type);
        }
        // IE does not support formxxx attributes for input with 'image' types
        final BrowserVersion browser = getPage().getWebClient().getBrowserVersion();
        if (browser.hasFeature(FORM_PARAMETRS_NOT_SUPPORTED_FOR_IMAGE) && typeImage) {
            return;
        }
        // could be excessive validation but support of html5 fromxxx
        // attributes available for:
        // - input with 'submit' and 'image' types
        // - button with 'submit'
        if (isInput && !typeSubmit && !typeImage) {
            return;
        } else if (HtmlButton.TAG_NAME.equals(element.getTagName()) && !"submit".equalsIgnoreCase(type)) {
            return;
        }
        final String formaction = element.getAttributeDirect("formaction");
        if (DomElement.ATTRIBUTE_NOT_DEFINED != formaction) {
            setActionAttribute(formaction);
        }
        final String formmethod = element.getAttributeDirect("formmethod");
        if (DomElement.ATTRIBUTE_NOT_DEFINED != formmethod) {
            setMethodAttribute(formmethod);
        }
        final String formtarget = element.getAttributeDirect("formtarget");
        if (DomElement.ATTRIBUTE_NOT_DEFINED != formtarget) {
            setTargetAttribute(formtarget);
        }
        final String formenctype = element.getAttributeDirect("formenctype");
        if (DomElement.ATTRIBUTE_NOT_DEFINED != formenctype) {
            setEnctypeAttribute(formenctype);
        }
    }
}

19 Source : MSXMLActiveXObjectFactory.java
with Apache License 2.0
from Xceptance

/**
 * Initializes the factory.
 *
 * @param browserVersion the browser version to use
 * @throws Exception if something goes wrong
 */
public void init(final BrowserVersion browserVersion) throws Exception {
    environment_ = new MSXMLJavaScriptEnvironment(browserVersion);
}

19 Source : HtmlUnitRegExpProxy.java
with Apache License 2.0
from null-dev

/**
 * Begins customization of JavaScript RegExp base on JDK regular expression support.
 *
 * @author Marc Guillemot
 * @author Ahmed Ashour
 * @author Ronald Brill
 * @author Carsten Steul
 */
public clreplaced HtmlUnitRegExpProxy extends RegExpImpl {

    private static final Log LOG = LogFactory.getLog(HtmlUnitRegExpProxy.clreplaced);

    private final RegExpProxy wrapped_;

    private final BrowserVersion browserVersion_;

    /**
     * Wraps a proxy to enhance it.
     * @param wrapped the original proxy
     * @param browserVersion the current browser version
     */
    public HtmlUnitRegExpProxy(final RegExpProxy wrapped, final BrowserVersion browserVersion) {
        wrapped_ = wrapped;
        browserVersion_ = browserVersion;
    }

    /**
     * Use the wrapped proxy except for replacement with string arg where it uses Java regular expression.
     * {@inheritDoc}
     */
    @Override
    public Object action(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args, final int actionType) {
        try {
            return doAction(cx, scope, thisObj, args, actionType);
        } catch (final StackOverflowError e) {
            // TODO: We shouldn't have to catch this exception and fall back to Rhino's regex support!
            // See HtmlUnitRegExpProxyTest.stackOverflow()
            LOG.warn(e.getMessage(), e);
            return wrapped_.action(cx, scope, thisObj, args, actionType);
        }
    }

    private Object doAction(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args, final int actionType) {
        // in a first time just improve replacement with a String (not a function)
        if (RA_REPLACE == actionType && args.length == 2 && args[1] instanceof String) {
            final String thisString = Context.toString(thisObj);
            final String replacement = (String) args[1];
            final Object arg0 = args[0];
            if (arg0 instanceof String) {
                // arg0 should *not* be interpreted as a RegExp
                return doStringReplacement(thisString, (String) arg0, replacement);
            }
            if (arg0 instanceof NativeRegExp) {
                try {
                    final NativeRegExp regexp = (NativeRegExp) arg0;
                    final RegExpData reData = new RegExpData(regexp);
                    final Matcher matcher = reData.getPattern().matcher(thisString);
                    return doReplacement(thisString, replacement, matcher, reData.isGlobal());
                } catch (final PatternSyntaxException e) {
                    LOG.warn(e.getMessage(), e);
                }
            }
        } else if (RA_MATCH == actionType || RA_SEARCH == actionType) {
            if (args.length == 0) {
                return null;
            }
            final Object arg0 = args[0];
            final String thisString = Context.toString(thisObj);
            final RegExpData reData;
            if (arg0 instanceof NativeRegExp) {
                reData = new RegExpData((NativeRegExp) arg0);
            } else {
                reData = new RegExpData(Context.toString(arg0));
            }
            final Matcher matcher = reData.getPattern().matcher(thisString);
            final boolean found = matcher.find();
            if (RA_SEARCH == actionType) {
                if (found) {
                    setProperties(matcher, thisString, matcher.start(), matcher.end());
                    return matcher.start();
                }
                return -1;
            }
            if (!found) {
                return null;
            }
            final int index = matcher.start(0);
            final List<Object> groups = new ArrayList<>();
            if (reData.isGlobal()) {
                // has flag g
                groups.add(matcher.group(0));
                setProperties(matcher, thisString, matcher.start(0), matcher.end(0));
                while (matcher.find()) {
                    groups.add(matcher.group(0));
                    setProperties(matcher, thisString, matcher.start(0), matcher.end(0));
                }
            } else {
                for (int i = 0; i <= matcher.groupCount(); i++) {
                    Object group = matcher.group(i);
                    if (group == null) {
                        group = Undefined.instance;
                    }
                    groups.add(group);
                }
                setProperties(matcher, thisString, matcher.start(), matcher.end());
            }
            final Scriptable response = cx.newArray(scope, groups.toArray());
            // the additional properties (cf ECMA script reference 15.10.6.2 13)
            response.put("index", response, Integer.valueOf(index));
            response.put("input", response, thisString);
            return response;
        }
        return wrappedAction(cx, scope, thisObj, args, actionType);
    }

    private String doStringReplacement(final String originalString, final String searchString, final String replacement) {
        if (originalString == null) {
            return "";
        }
        final StaticStringMatcher matcher = new StaticStringMatcher(originalString, searchString);
        if (matcher.start() > -1) {
            final StringBuilder sb = new StringBuilder();
            sb.append(originalString.substring(0, matcher.start_));
            String localReplacement = replacement;
            if (replacement.contains("$")) {
                localReplacement = computeReplacementValue(localReplacement, originalString, matcher, false);
            }
            sb.append(localReplacement);
            sb.append(originalString.substring(matcher.end_));
            return sb.toString();
        }
        return originalString;
    }

    private String doReplacement(final String originalString, final String replacement, final Matcher matcher, final boolean replaceAll) {
        final StringBuilder sb = new StringBuilder();
        int previousIndex = 0;
        while (matcher.find()) {
            sb.append(originalString, previousIndex, matcher.start());
            String localReplacement = replacement;
            if (replacement.contains("$")) {
                localReplacement = computeReplacementValue(replacement, originalString, matcher, browserVersion_.hasFeature(JS_REGEXP_GROUP0_RETURNS_WHOLE_MATCH));
            }
            sb.append(localReplacement);
            previousIndex = matcher.end();
            setProperties(matcher, originalString, matcher.start(), previousIndex);
            if (!replaceAll) {
                break;
            }
        }
        sb.append(originalString, previousIndex, originalString.length());
        return sb.toString();
    }

    String computeReplacementValue(final String replacement, final String originalString, final MatchResult matcher, final boolean group0ReturnsWholeMatch) {
        int lastIndex = 0;
        final StringBuilder result = new StringBuilder();
        int i;
        while ((i = replacement.indexOf('$', lastIndex)) > -1) {
            if (i > 0) {
                result.append(replacement, lastIndex, i);
            }
            String ss = null;
            if (i < replacement.length() - 1 && (i == lastIndex || replacement.charAt(i - 1) != '$')) {
                final char next = replacement.charAt(i + 1);
                // only valid back reference are "evaluated"
                if (next >= '1' && next <= '9') {
                    final int num1digit = next - '0';
                    final char next2 = i + 2 < replacement.length() ? replacement.charAt(i + 2) : 'x';
                    final int num2digits;
                    // if there are 2 digits, the second one is considered as part of the group number
                    // only if there is such a group
                    if (next2 >= '1' && next2 <= '9') {
                        num2digits = num1digit * 10 + (next2 - '0');
                    } else {
                        num2digits = Integer.MAX_VALUE;
                    }
                    if (num2digits <= matcher.groupCount()) {
                        ss = matcher.group(num2digits);
                        i++;
                    } else if (num1digit <= matcher.groupCount()) {
                        ss = StringUtils.defaultString(matcher.group(num1digit));
                    }
                } else {
                    switch(next) {
                        case '&':
                            ss = matcher.group();
                            break;
                        case '0':
                            if (group0ReturnsWholeMatch) {
                                ss = matcher.group();
                            }
                            break;
                        case '`':
                            ss = originalString.substring(0, matcher.start());
                            break;
                        case '\'':
                            ss = originalString.substring(matcher.end());
                            break;
                        case '$':
                            ss = "$";
                            break;
                        default:
                    }
                }
            }
            if (ss == null) {
                result.append('$');
                lastIndex = i + 1;
            } else {
                result.append(ss);
                lastIndex = i + 2;
            }
        }
        result.append(replacement, lastIndex, replacement.length());
        return result.toString();
    }

    /**
     * Calls action on the wrapped RegExp proxy.
     */
    private Object wrappedAction(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args, final int actionType) {
        // take care to set the context's RegExp proxy to the original one as this is checked
        // (cf net.sourceforge.htmlunit.corejs.javascript.regexp.RegExpImp:334)
        try {
            ScriptRuntime.setRegExpProxy(cx, wrapped_);
            return wrapped_.action(cx, scope, thisObj, args, actionType);
        } finally {
            ScriptRuntime.setRegExpProxy(cx, this);
        }
    }

    private void setProperties(final Matcher matcher, final String thisString, final int startPos, final int endPos) {
        // lastMatch
        final String match = matcher.group();
        if (match == null) {
            lastMatch = new SubString();
        } else {
            lastMatch = new SubString(match, 0, match.length());
        }
        // parens
        final int groupCount = matcher.groupCount();
        if (groupCount == 0) {
            parens = null;
        } else {
            final int count = Math.min(9, groupCount);
            parens = new SubString[count];
            for (int i = 0; i < count; i++) {
                final String group = matcher.group(i + 1);
                if (group == null) {
                    parens[i] = new SubString();
                } else {
                    parens[i] = new SubString(group, 0, group.length());
                }
            }
        }
        // lastParen
        if (groupCount > 0) {
            if (groupCount > 9 && browserVersion_.hasFeature(JS_REGEXP_EMPTY_LASTPAREN_IF_TOO_MANY_GROUPS)) {
                lastParen = new SubString();
            } else {
                final String last = matcher.group(groupCount);
                if (last == null) {
                    lastParen = new SubString();
                } else {
                    lastParen = new SubString(last, 0, last.length());
                }
            }
        }
        // leftContext
        if (startPos > 0) {
            leftContext = new SubString(thisString, 0, startPos);
        } else {
            leftContext = new SubString();
        }
        // rightContext
        final int length = thisString.length();
        if (endPos < length) {
            rightContext = new SubString(thisString, endPos, length - endPos);
        } else {
            rightContext = new SubString();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object compileRegExp(final Context cx, final String source, final String flags) {
        try {
            return wrapped_.compileRegExp(cx, source, flags);
        } catch (final Exception e) {
            LOG.warn("compileRegExp() threw for >" + source + "<, flags: >" + flags + "<. " + "Replacing with a '####shouldNotFindAnything###'");
            return wrapped_.compileRegExp(cx, "####shouldNotFindAnything###", "");
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int find_split(final Context cx, final Scriptable scope, final String target, final String separator, final Scriptable re, final int[] ip, final int[] matchlen, final boolean[] matched, final String[][] parensp) {
        return wrapped_.find_split(cx, scope, target, separator, re, ip, matchlen, matched, parensp);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isRegExp(final Scriptable obj) {
        return wrapped_.isRegExp(obj);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Scriptable wrapRegExp(final Context cx, final Scriptable scope, final Object compiled) {
        return wrapped_.wrapRegExp(cx, scope, compiled);
    }

    /**
     * Pattern cache
     */
    private static final Map<String, Pattern> PATTENS = new HashMap<>();

    private static clreplaced RegExpData {

        private final boolean global_;

        private Pattern pattern_;

        RegExpData(final NativeRegExp re) {
            // the form is /regex/flags
            final String str = re.toString();
            final String jsSource = StringUtils.substringBeforeLast(str.substring(1), "/");
            final String jsFlags = StringUtils.substringAfterLast(str, "/");
            global_ = jsFlags.indexOf('g') != -1;
            pattern_ = PATTENS.get(str);
            if (pattern_ == null) {
                pattern_ = Pattern.compile(jsRegExpToJavaRegExp(jsSource), getJavaFlags(jsFlags));
                PATTENS.put(str, pattern_);
            }
        }

        RegExpData(final String string) {
            global_ = false;
            pattern_ = PATTENS.get(string);
            if (pattern_ == null) {
                pattern_ = Pattern.compile(jsRegExpToJavaRegExp(string), 0);
                PATTENS.put(string, pattern_);
            }
        }

        /**
         * Converts the current JavaScript RegExp flags to Java Pattern flags.
         * @return the Java Pattern flags
         */
        private static int getJavaFlags(final String jsFlags) {
            int flags = 0;
            if (jsFlags.contains("i")) {
                flags |= Pattern.CASE_INSENSITIVE;
            }
            if (jsFlags.contains("m")) {
                flags |= Pattern.MULTILINE;
            }
            return flags;
        }

        boolean isGlobal() {
            return global_;
        }

        Pattern getPattern() {
            return pattern_;
        }
    }

    /**
     * Transform a JavaScript regular expression to a Java regular expression
     * @param re the JavaScript regular expression to transform
     * @return the transformed expression
     */
    static String jsRegExpToJavaRegExp(final String re) {
        final RegExpJsToJavaConverter regExpJsToJavaFSM = new RegExpJsToJavaConverter();
        return regExpJsToJavaFSM.convert(re);
    }

    /**
     * Simple helper.
     */
    private static final clreplaced StaticStringMatcher implements MatchResult {

        private final String group_;

        private final int start_;

        private final int end_;

        private StaticStringMatcher(final String originalString, final String searchString) {
            final int pos = originalString.indexOf(searchString);
            group_ = searchString;
            start_ = pos;
            end_ = pos + searchString.length();
        }

        @Override
        public String group() {
            return group_;
        }

        @Override
        public int start() {
            return start_;
        }

        @Override
        public int end() {
            return end_;
        }

        @Override
        public int start(final int group) {
            // not used so far
            return 0;
        }

        @Override
        public int end(final int group) {
            // not used so far
            return 0;
        }

        @Override
        public String group(final int group) {
            // not used so far
            return null;
        }

        @Override
        public int groupCount() {
            // not used so far
            return 0;
        }
    }
}

19 Source : HTMLAllCollection.java
with Apache License 2.0
from null-dev

/**
 * Returns the item or items corresponding to the specified index or key.
 * @param index the index or key corresponding to the element or elements to return
 * @return the element or elements corresponding to the specified index or key
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms536460.aspx">MSDN doc</a>
 */
@Override
public Object item(final Object index) {
    Double numb;
    final BrowserVersion browser;
    if (index instanceof String) {
        final String name = (String) index;
        final Object result = namedItem(name);
        if (null != result && Undefined.instance != result) {
            return result;
        }
        numb = Double.NaN;
        browser = getBrowserVersion();
        if (!browser.hasFeature(HTMLALLCOLLECTION_DO_NOT_CONVERT_STRINGS_TO_NUMBER)) {
            numb = ScriptRuntime.toNumber(index);
        }
        if (numb.isNaN()) {
            return itemNotFound(browser);
        }
    } else {
        numb = ScriptRuntime.toNumber(index);
        browser = getBrowserVersion();
    }
    if (numb < 0) {
        return itemNotFound(browser);
    }
    if (!browser.hasFeature(HTMLCOLLECTION_ITEM_FUNCT_SUPPORTS_DOUBLE_INDEX_ALSO) && (Double.isInfinite(numb) || numb != Math.floor(numb))) {
        return itemNotFound(browser);
    }
    final Object object = get(numb.intValue(), this);
    if (object == NOT_FOUND) {
        return null;
    }
    return object;
}

19 Source : BrowserConfiguration.java
with Apache License 2.0
from null-dev

static BrowserConfiguration getMatchingConfiguration(final BrowserVersion browserVersion, final BrowserConfiguration[] browserConfigurations) {
    for (final BrowserConfiguration browserConfiguration : browserConfigurations) {
        if (browserVersion.getNickname().startsWith(browserConfiguration.browserFamily_) && browserVersion.getBrowserVersionNumeric() >= browserConfiguration.minVersionNumber_ && browserVersion.getBrowserVersionNumeric() <= browserConfiguration.maxVersionNumber_) {
            return browserConfiguration;
        }
    }
    return null;
}

19 Source : AbstractJavaScriptConfiguration.java
with Apache License 2.0
from null-dev

/**
 * Returns the clreplaced configuration of the given {@code klreplaced}.
 *
 * @param klreplaced the clreplaced
 * @param browser the browser version
 * @return the clreplaced configuration
 */
public static ClreplacedConfiguration getClreplacedConfiguration(final Clreplaced<? extends HtmlUnitScriptable> klreplaced, final BrowserVersion browser) {
    if (browser != null) {
        final SupportedBrowser expectedBrowser;
        if (browser.isChrome()) {
            expectedBrowser = CHROME;
        } else if (browser.isIE()) {
            expectedBrowser = IE;
        } else if (browser.isEdge()) {
            expectedBrowser = EDGE;
        } else if (browser.isFirefox52()) {
            expectedBrowser = FF52;
        } else if (browser.isFirefox()) {
            expectedBrowser = FF45;
        } else {
            // our current fallback
            expectedBrowser = CHROME;
        }
        final String hostClreplacedName = klreplaced.getName();
        final JsxClreplacedes jsxClreplacedes = klreplaced.getAnnotation(JsxClreplacedes.clreplaced);
        if (jsxClreplacedes != null) {
            if (klreplaced.getAnnotation(JsxClreplaced.clreplaced) != null) {
                throw new RuntimeException("Invalid JsxClreplacedes/JsxClreplaced annotation; clreplaced '" + hostClreplacedName + "' has both.");
            }
            final JsxClreplaced[] jsxClreplacedValues = jsxClreplacedes.value();
            if (jsxClreplacedValues.length == 1) {
                throw new RuntimeException("No need to specify JsxClreplacedes with a single JsxClreplaced for " + hostClreplacedName);
            }
            final Set<Clreplaced<?>> domClreplacedes = new HashSet<>();
            boolean isJsObject = false;
            String clreplacedName = null;
            String extendedClreplacedName = "";
            final Clreplaced<?> superClreplaced = klreplaced.getSuperclreplaced();
            if (superClreplaced == SimpleScriptable.clreplaced) {
                extendedClreplacedName = "";
            } else {
                extendedClreplacedName = superClreplaced.getSimpleName();
            }
            for (int i = 0; i < jsxClreplacedValues.length; i++) {
                final JsxClreplaced jsxClreplaced = jsxClreplacedValues[i];
                if (jsxClreplaced != null && isSupported(jsxClreplaced.value(), expectedBrowser)) {
                    domClreplacedes.add(jsxClreplaced.domClreplaced());
                    if (jsxClreplaced.isJSObject()) {
                        isJsObject = true;
                    }
                    if (!jsxClreplaced.clreplacedName().isEmpty()) {
                        clreplacedName = jsxClreplaced.clreplacedName();
                    }
                    if (jsxClreplaced.extendedClreplaced() != Object.clreplaced) {
                        if (jsxClreplaced.extendedClreplaced() == SimpleScriptable.clreplaced) {
                            extendedClreplacedName = "";
                        } else {
                            extendedClreplacedName = jsxClreplaced.extendedClreplaced().getSimpleName();
                        }
                    }
                }
            }
            final ClreplacedConfiguration clreplacedConfiguration = new ClreplacedConfiguration(klreplaced, domClreplacedes.toArray(new Clreplaced<?>[0]), isJsObject, clreplacedName, extendedClreplacedName);
            process(clreplacedConfiguration, hostClreplacedName, expectedBrowser);
            return clreplacedConfiguration;
        }
        final JsxClreplaced jsxClreplaced = klreplaced.getAnnotation(JsxClreplaced.clreplaced);
        if (jsxClreplaced != null && isSupported(jsxClreplaced.value(), expectedBrowser)) {
            final Set<Clreplaced<?>> domClreplacedes = new HashSet<>();
            final Clreplaced<?> domClreplaced = jsxClreplaced.domClreplaced();
            if (domClreplaced != null && domClreplaced != Object.clreplaced) {
                domClreplacedes.add(domClreplaced);
            }
            String clreplacedName = jsxClreplaced.clreplacedName();
            if (clreplacedName.isEmpty()) {
                clreplacedName = null;
            }
            String extendedClreplacedName = "";
            final Clreplaced<?> superClreplaced = klreplaced.getSuperclreplaced();
            if (superClreplaced != SimpleScriptable.clreplaced) {
                extendedClreplacedName = superClreplaced.getSimpleName();
            } else {
                extendedClreplacedName = "";
            }
            if (jsxClreplaced.extendedClreplaced() != Object.clreplaced) {
                extendedClreplacedName = jsxClreplaced.extendedClreplaced().getSimpleName();
            }
            final ClreplacedConfiguration clreplacedConfiguration = new ClreplacedConfiguration(klreplaced, domClreplacedes.toArray(new Clreplaced<?>[0]), jsxClreplaced.isJSObject(), clreplacedName, extendedClreplacedName);
            process(clreplacedConfiguration, hostClreplacedName, expectedBrowser);
            return clreplacedConfiguration;
        }
    }
    return null;
}

19 Source : AbstractJavaScriptConfiguration.java
with Apache License 2.0
from null-dev

private Map<String, ClreplacedConfiguration> buildUsageMap(final BrowserVersion browser) {
    final Map<String, ClreplacedConfiguration> clreplacedMap = new HashMap<>(getClreplacedes().length);
    for (final Clreplaced<? extends SimpleScriptable> klreplaced : getClreplacedes()) {
        final ClreplacedConfiguration config = getClreplacedConfiguration(klreplaced, browser);
        if (config != null) {
            clreplacedMap.put(config.getClreplacedName(), config);
        }
    }
    return Collections.unmodifiableMap(clreplacedMap);
}

19 Source : HtmlUnitExpiresHandler.java
with Apache License 2.0
from null-dev

/**
 * Customized BasicExpiresHandler for HtmlUnit.
 *
 * @author <a href="mailto:[email protected]">Mike Bowler</a>
 * @author Noboru Sinohara
 * @author David D. Kilzer
 * @author Marc Guillemot
 * @author Brad Clarke
 * @author Ahmed Ashour
 * @author Nicolas Belisle
 * @author Ronald Brill
 * @author John J Murdoch
 */
final clreplaced HtmlUnitExpiresHandler extends BasicExpiresHandler {

    // simplified patterns from BrowserCompatSpec, with yy patterns before similar yyyy patterns
    private static final String[] DEFAULT_DATE_PATTERNS = new String[] { "EEE dd MMM yy HH mm ss zzz", "EEE dd MMM yyyy HH mm ss zzz", "EEE MMM d HH mm ss yyyy", "EEE dd MMM yy HH mm ss z ", "EEE dd MMM yyyy HH mm ss z ", "EEE dd MM yy HH mm ss z ", "EEE dd MM yyyy HH mm ss z " };

    private static final String[] EXTENDED_DATE_PATTERNS_1 = new String[] { "EEE dd MMM yy HH mm ss zzz", "EEE dd MMM yyyy HH mm ss zzz", "EEE MMM d HH mm ss yyyy", "EEE dd MMM yy HH mm ss z ", "EEE dd MMM yyyy HH mm ss z ", "EEE dd MM yy HH mm ss z ", "EEE dd MM yyyy HH mm ss z ", "d/M/yyyy" };

    private static final String[] EXTENDED_DATE_PATTERNS_2 = new String[] { "EEE dd MMM yy HH mm ss zzz", "EEE dd MMM yyyy HH mm ss zzz", "EEE MMM d HH mm ss yyyy", "EEE dd MMM yy HH mm ss z ", "EEE dd MMM yyyy HH mm ss z ", "EEE dd MM yy HH mm ss z ", "EEE dd MM yyyy HH mm ss z ", "EEE dd MMM yy HH MM ss z", "MMM dd yy HH mm ss" };

    private final BrowserVersion browserVersion_;

    HtmlUnitExpiresHandler(final BrowserVersion browserVersion) {
        super(DEFAULT_DATE_PATTERNS);
        browserVersion_ = browserVersion;
    }

    @Override
    public void parse(final SetCookie cookie, String value) throws MalformedCookieException {
        if (value.startsWith("\"") && value.endsWith("\"")) {
            value = value.substring(1, value.length() - 1);
        }
        value = value.replaceAll("[ ,:-]+", " ");
        Date startDate = null;
        String[] datePatterns = DEFAULT_DATE_PATTERNS;
        if (null != browserVersion_) {
            if (browserVersion_.hasFeature(HTTP_COOKIE_START_DATE_1970)) {
                startDate = HtmlUnitBrowserCompatCookieSpec.DATE_1_1_1970;
            }
            if (browserVersion_.hasFeature(HTTP_COOKIE_EXTENDED_DATE_PATTERNS_1)) {
                datePatterns = EXTENDED_DATE_PATTERNS_1;
            }
            if (browserVersion_.hasFeature(HTTP_COOKIE_EXTENDED_DATE_PATTERNS_2)) {
                final Calendar calendar = Calendar.getInstance(Locale.ROOT);
                calendar.setTimeZone(DateUtils.GMT);
                calendar.set(1969, Calendar.JANUARY, 1, 0, 0, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                startDate = calendar.getTime();
                datePatterns = EXTENDED_DATE_PATTERNS_2;
            }
        }
        final Date expiry = DateUtils.parseDate(value, datePatterns, startDate);
        cookie.setExpiryDate(expiry);
    }
}

19 Source : HtmlUnitDomainHandler.java
with Apache License 2.0
from null-dev

/**
 * Customized BasicDomainHandler for HtmlUnit.
 *
 * @author Ronald Brill
 * @author Ahmed Ashour
 */
final clreplaced HtmlUnitDomainHandler extends BasicDomainHandler {

    private final BrowserVersion browserVersion_;

    HtmlUnitDomainHandler(final BrowserVersion browserVersion) {
        browserVersion_ = browserVersion;
    }

    @Override
    public void parse(final SetCookie cookie, final String value) throws MalformedCookieException {
        Args.notNull(cookie, HttpHeader.COOKIE);
        if (TextUtils.isBlank(value)) {
            throw new MalformedCookieException("Blank or null value for domain attribute");
        }
        // Ignore domain attributes ending with '.' per RFC 6265, 4.1.2.3
        if (value.endsWith(".")) {
            return;
        }
        String domain = value;
        domain = domain.toLowerCase(Locale.ROOT);
        final int dotIndex = domain.indexOf('.');
        if (browserVersion_.hasFeature(HTTP_COOKIE_REMOVE_DOT_FROM_ROOT_DOMAINS) && dotIndex == 0 && domain.length() > 1 && domain.indexOf('.', 1) == -1) {
            domain = domain.toLowerCase(Locale.ROOT);
            domain = domain.substring(1);
        }
        if (dotIndex > 0) {
            domain = '.' + domain;
        }
        cookie.setDomain(domain);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean match(final Cookie cookie, final CookieOrigin origin) {
        String domain = cookie.getDomain();
        if (domain == null) {
            return false;
        }
        final int dotIndex = domain.indexOf('.');
        if (dotIndex == 0 && domain.length() > 1 && domain.indexOf('.', 1) == -1) {
            final String host = origin.getHost();
            domain = domain.toLowerCase(Locale.ROOT);
            if (browserVersion_.hasFeature(HTTP_COOKIE_REMOVE_DOT_FROM_ROOT_DOMAINS)) {
                domain = domain.substring(1);
            }
            if (host.equals(domain)) {
                return true;
            }
            return false;
        }
        if (dotIndex == -1 && !HtmlUnitBrowserCompatCookieSpec.LOCAL_FILESYSTEM_DOMAIN.equalsIgnoreCase(domain)) {
            try {
                InetAddress.getByName(domain);
            } catch (final UnknownHostException e) {
                return false;
            }
        }
        return super.match(cookie, origin);
    }
}

19 Source : FaqTest.java
with Apache License 2.0
from HtmlUnit

/**
 * @throws Exception if an error occurs
 */
@Test
public void xhtmlPageFromString() throws Exception {
    final String ls = System.lineSeparator();
    final BrowserVersion browserVersion = BrowserVersion.FIREFOX;
    final String htmlCode = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"" + "\"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + "  <head>" + "    <replacedle>replacedle</replacedle>" + "  </head>" + "  <body>" + "    content..." + "  </body>" + "</html> ";
    try (WebClient webClient = new WebClient(browserVersion)) {
        final XHtmlPage page = webClient.loadXHtmlCodeIntoCurrentWindow(htmlCode);
        // work with the xhtml page
        replacedertEquals("replacedle" + ls + "content...", page.asText());
    }
}

19 Source : FaqTest.java
with Apache License 2.0
from HtmlUnit

/**
 * @throws Exception if an error occurs
 */
@Test
public void htmlPageFromString() throws Exception {
    final String ls = System.lineSeparator();
    final BrowserVersion browserVersion = BrowserVersion.FIREFOX;
    final String htmlCode = "<html>" + "  <head>" + "    <replacedle>replacedle</replacedle>" + "  </head>" + "  <body>" + "    content..." + "  </body>" + "</html> ";
    try (WebClient webClient = new WebClient(browserVersion)) {
        final HtmlPage page = webClient.loadXHtmlCodeIntoCurrentWindow(htmlCode);
        // work with the html page
        replacedertEquals("replacedle" + ls + "content...", page.asText());
    }
}

19 Source : HtmlUnitRegExpProxy.java
with Apache License 2.0
from HtmlUnit

/**
 * Begins customization of JavaScript RegExp base on JDK regular expression support.
 *
 * @author Marc Guillemot
 * @author Ahmed Ashour
 * @author Ronald Brill
 * @author Carsten Steul
 */
public clreplaced HtmlUnitRegExpProxy extends RegExpImpl {

    private static final Log LOG = LogFactory.getLog(HtmlUnitRegExpProxy.clreplaced);

    /**
     * Pattern cache
     */
    private static final Map<String, Pattern> PATTENS = new HashMap<>();

    private final RegExpProxy wrapped_;

    private final BrowserVersion browserVersion_;

    /**
     * Wraps a proxy to enhance it.
     * @param wrapped the original proxy
     * @param browserVersion the current browser version
     */
    public HtmlUnitRegExpProxy(final RegExpProxy wrapped, final BrowserVersion browserVersion) {
        wrapped_ = wrapped;
        browserVersion_ = browserVersion;
    }

    /**
     * Use the wrapped proxy except for replacement with string arg where it uses Java regular expression.
     * {@inheritDoc}
     */
    @Override
    public Object action(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args, final int actionType) {
        try {
            return doAction(cx, scope, thisObj, args, actionType);
        } catch (final StackOverflowError e) {
            // TODO: We shouldn't have to catch this exception and fall back to Rhino's regex support!
            // See HtmlUnitRegExpProxyTest.stackOverflow()
            LOG.warn(e.getMessage(), e);
            return wrapped_.action(cx, scope, thisObj, args, actionType);
        }
    }

    private Object doAction(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args, final int actionType) {
        // in a first time just improve replacement with a String (not a function)
        if (RA_REPLACE == actionType && args.length == 2 && args[1] instanceof String) {
            final String thisString = Context.toString(thisObj);
            final String replacement = (String) args[1];
            final Object arg0 = args[0];
            if (arg0 instanceof String) {
                // arg0 should *not* be interpreted as a RegExp
                return doStringReplacement(thisString, (String) arg0, replacement);
            }
            if (arg0 instanceof NativeRegExp) {
                try {
                    final NativeRegExp regexp = (NativeRegExp) arg0;
                    final RegExpData reData = new RegExpData(regexp);
                    final Matcher matcher = reData.getPattern().matcher(thisString);
                    return doReplacement(thisString, replacement, matcher, reData.isGlobal());
                } catch (final PatternSyntaxException e) {
                    LOG.warn(e.getMessage(), e);
                }
            }
        } else if (RA_MATCH == actionType || RA_SEARCH == actionType) {
            if (args.length == 0) {
                return null;
            }
            final Object arg0 = args[0];
            final String thisString = Context.toString(thisObj);
            final RegExpData reData;
            if (arg0 instanceof NativeRegExp) {
                reData = new RegExpData((NativeRegExp) arg0);
            } else {
                reData = new RegExpData(Context.toString(arg0));
            }
            final Matcher matcher = reData.getPattern().matcher(thisString);
            final boolean found = matcher.find();
            if (RA_SEARCH == actionType) {
                if (found) {
                    setProperties(matcher, thisString, matcher.start(), matcher.end());
                    return matcher.start();
                }
                return -1;
            }
            if (!found) {
                return null;
            }
            final int index = matcher.start(0);
            final List<Object> groups = new ArrayList<>();
            if (reData.isGlobal()) {
                // has flag g
                groups.add(matcher.group(0));
                setProperties(matcher, thisString, matcher.start(0), matcher.end(0));
                while (matcher.find()) {
                    groups.add(matcher.group(0));
                    setProperties(matcher, thisString, matcher.start(0), matcher.end(0));
                }
            } else {
                for (int i = 0; i <= matcher.groupCount(); i++) {
                    Object group = matcher.group(i);
                    if (group == null) {
                        group = Undefined.instance;
                    }
                    groups.add(group);
                }
                setProperties(matcher, thisString, matcher.start(), matcher.end());
            }
            final Scriptable response = cx.newArray(scope, groups.toArray());
            // the additional properties (cf ECMA script reference 15.10.6.2 13)
            response.put("index", response, Integer.valueOf(index));
            response.put("input", response, thisString);
            return response;
        }
        return wrappedAction(cx, scope, thisObj, args, actionType);
    }

    private String doStringReplacement(final String originalString, final String searchString, final String replacement) {
        if (originalString == null) {
            return "";
        }
        final StaticStringMatcher matcher = new StaticStringMatcher(originalString, searchString);
        if (matcher.start() > -1) {
            final StringBuilder sb = new StringBuilder().append(originalString, 0, matcher.start_);
            String localReplacement = replacement;
            if (replacement.contains("$")) {
                localReplacement = computeReplacementValue(localReplacement, originalString, matcher, false);
            }
            sb.append(localReplacement).append(originalString, matcher.end_, originalString.length());
            return sb.toString();
        }
        return originalString;
    }

    private String doReplacement(final String originalString, final String replacement, final Matcher matcher, final boolean replaceAll) {
        final StringBuilder sb = new StringBuilder();
        int previousIndex = 0;
        while (matcher.find()) {
            sb.append(originalString, previousIndex, matcher.start());
            String localReplacement = replacement;
            if (replacement.contains("$")) {
                localReplacement = computeReplacementValue(replacement, originalString, matcher, browserVersion_.hasFeature(JS_REGEXP_GROUP0_RETURNS_WHOLE_MATCH));
            }
            sb.append(localReplacement);
            previousIndex = matcher.end();
            setProperties(matcher, originalString, matcher.start(), previousIndex);
            if (!replaceAll) {
                break;
            }
        }
        sb.append(originalString, previousIndex, originalString.length());
        return sb.toString();
    }

    String computeReplacementValue(final String replacement, final String originalString, final MatchResult matcher, final boolean group0ReturnsWholeMatch) {
        int lastIndex = 0;
        final StringBuilder result = new StringBuilder();
        int i;
        while ((i = replacement.indexOf('$', lastIndex)) > -1) {
            if (i > 0) {
                result.append(replacement, lastIndex, i);
            }
            String ss = null;
            if (i < replacement.length() - 1 && (i == lastIndex || replacement.charAt(i - 1) != '$')) {
                final char next = replacement.charAt(i + 1);
                // only valid back reference are "evaluated"
                if (next >= '1' && next <= '9') {
                    final int num1digit = next - '0';
                    final char next2 = i + 2 < replacement.length() ? replacement.charAt(i + 2) : 'x';
                    final int num2digits;
                    // if there are 2 digits, the second one is considered as part of the group number
                    // only if there is such a group
                    if (next2 >= '1' && next2 <= '9') {
                        num2digits = num1digit * 10 + (next2 - '0');
                    } else {
                        num2digits = Integer.MAX_VALUE;
                    }
                    if (num2digits <= matcher.groupCount()) {
                        ss = matcher.group(num2digits);
                        i++;
                    } else if (num1digit <= matcher.groupCount()) {
                        ss = StringUtils.defaultString(matcher.group(num1digit));
                    }
                } else {
                    switch(next) {
                        case '&':
                            ss = matcher.group();
                            break;
                        case '0':
                            if (group0ReturnsWholeMatch) {
                                ss = matcher.group();
                            }
                            break;
                        case '`':
                            ss = originalString.substring(0, matcher.start());
                            break;
                        case '\'':
                            ss = originalString.substring(matcher.end());
                            break;
                        case '$':
                            ss = "$";
                            break;
                        default:
                    }
                }
            }
            if (ss == null) {
                result.append('$');
                lastIndex = i + 1;
            } else {
                result.append(ss);
                lastIndex = i + 2;
            }
        }
        result.append(replacement, lastIndex, replacement.length());
        return result.toString();
    }

    /**
     * Calls action on the wrapped RegExp proxy.
     */
    private Object wrappedAction(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args, final int actionType) {
        // take care to set the context's RegExp proxy to the original one as this is checked
        // (cf net.sourceforge.htmlunit.corejs.javascript.regexp.RegExpImp:334)
        try {
            ScriptRuntime.setRegExpProxy(cx, wrapped_);
            return wrapped_.action(cx, scope, thisObj, args, actionType);
        } finally {
            ScriptRuntime.setRegExpProxy(cx, this);
        }
    }

    private void setProperties(final Matcher matcher, final String thisString, final int startPos, final int endPos) {
        // lastMatch
        final String match = matcher.group();
        if (match == null) {
            lastMatch = new SubString();
        } else {
            lastMatch = new SubString(match, 0, match.length());
        }
        // parens
        final int groupCount = matcher.groupCount();
        if (groupCount == 0) {
            parens = null;
        } else {
            final int count = Math.min(9, groupCount);
            parens = new SubString[count];
            for (int i = 0; i < count; i++) {
                final String group = matcher.group(i + 1);
                if (group == null) {
                    parens[i] = new SubString();
                } else {
                    parens[i] = new SubString(group, 0, group.length());
                }
            }
        }
        // lastParen
        if (groupCount > 0) {
            if (groupCount > 9 && browserVersion_.hasFeature(JS_REGEXP_EMPTY_LASTPAREN_IF_TOO_MANY_GROUPS)) {
                lastParen = new SubString();
            } else {
                final String last = matcher.group(groupCount);
                if (last == null) {
                    lastParen = new SubString();
                } else {
                    lastParen = new SubString(last, 0, last.length());
                }
            }
        }
        // leftContext
        if (startPos > 0) {
            leftContext = new SubString(thisString, 0, startPos);
        } else {
            leftContext = new SubString();
        }
        // rightContext
        final int length = thisString.length();
        if (endPos < length) {
            rightContext = new SubString(thisString, endPos, length - endPos);
        } else {
            rightContext = new SubString();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object compileRegExp(final Context cx, final String source, final String flags) {
        try {
            return wrapped_.compileRegExp(cx, source, flags);
        } catch (final Exception e) {
            if (LOG.isWarnEnabled()) {
                LOG.warn("compileRegExp() threw for >" + source + "<, flags: >" + flags + "<. " + "Replacing with a '####shouldNotFindAnything###'");
            }
            return wrapped_.compileRegExp(cx, "####shouldNotFindAnything###", "");
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int find_split(final Context cx, final Scriptable scope, final String target, final String separator, final Scriptable re, final int[] ip, final int[] matchlen, final boolean[] matched, final String[][] parensp) {
        return wrapped_.find_split(cx, scope, target, separator, re, ip, matchlen, matched, parensp);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isRegExp(final Scriptable obj) {
        return wrapped_.isRegExp(obj);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Scriptable wrapRegExp(final Context cx, final Scriptable scope, final Object compiled) {
        return wrapped_.wrapRegExp(cx, scope, compiled);
    }

    private static clreplaced RegExpData {

        private final boolean global_;

        private Pattern pattern_;

        RegExpData(final NativeRegExp re) {
            // the form is /regex/flags
            final String str = re.toString();
            final String jsSource = StringUtils.substringBeforeLast(str.substring(1), "/");
            final String jsFlags = StringUtils.substringAfterLast(str, "/");
            global_ = jsFlags.indexOf('g') != -1;
            pattern_ = PATTENS.get(str);
            if (pattern_ == null) {
                pattern_ = Pattern.compile(jsRegExpToJavaRegExp(jsSource), getJavaFlags(jsFlags));
                PATTENS.put(str, pattern_);
            }
        }

        RegExpData(final String string) {
            global_ = false;
            pattern_ = PATTENS.get(string);
            if (pattern_ == null) {
                pattern_ = Pattern.compile(jsRegExpToJavaRegExp(string), 0);
                PATTENS.put(string, pattern_);
            }
        }

        /**
         * Converts the current JavaScript RegExp flags to Java Pattern flags.
         * @return the Java Pattern flags
         */
        private static int getJavaFlags(final String jsFlags) {
            int flags = 0;
            if (jsFlags.contains("i")) {
                flags |= Pattern.CASE_INSENSITIVE;
            }
            if (jsFlags.contains("m")) {
                flags |= Pattern.MULTILINE;
            }
            return flags;
        }

        boolean isGlobal() {
            return global_;
        }

        Pattern getPattern() {
            return pattern_;
        }
    }

    /**
     * Transform a JavaScript regular expression to a Java regular expression
     * @param re the JavaScript regular expression to transform
     * @return the transformed expression
     */
    static String jsRegExpToJavaRegExp(final String re) {
        final RegExpJsToJavaConverter regExpJsToJavaFSM = new RegExpJsToJavaConverter();
        return regExpJsToJavaFSM.convert(re);
    }

    /**
     * Simple helper.
     */
    private static final clreplaced StaticStringMatcher implements MatchResult {

        private final String group_;

        private final int start_;

        private final int end_;

        StaticStringMatcher(final String originalString, final String searchString) {
            final int pos = originalString.indexOf(searchString);
            group_ = searchString;
            start_ = pos;
            end_ = pos + searchString.length();
        }

        @Override
        public String group() {
            return group_;
        }

        @Override
        public int start() {
            return start_;
        }

        @Override
        public int end() {
            return end_;
        }

        @Override
        public int start(final int group) {
            // not used so far
            return 0;
        }

        @Override
        public int end(final int group) {
            // not used so far
            return 0;
        }

        @Override
        public String group(final int group) {
            // not used so far
            return null;
        }

        @Override
        public int groupCount() {
            // not used so far
            return 0;
        }
    }
}

18 Source : JavaScriptConfigurationTest.java
with Apache License 2.0
from Xceptance

private void test(final BrowserVersion browserVersion) throws IOException {
    try (WebClient webClient = new WebClient(browserVersion)) {
        final MockWebConnection conn = new MockWebConnection();
        conn.setDefaultResponse("<html><body onload='doreplacedent.body.firstChild'></body></html>");
        webClient.setWebConnection(conn);
        webClient.getPage("http://localhost/");
    }
}

18 Source : JavaScriptConfigurationTest.java
with Apache License 2.0
from Xceptance

/**
 * Test if configuration map expands with each new instance of BrowserVersion used.
 *
 * @throws Exception if the test fails
 */
@Test
public void configurationMapExpands() throws Exception {
    // get a reference to the leaky map
    final Field field = JavaScriptConfiguration.clreplaced.getDeclaredField("CONFIGURATION_MAP_");
    field.setAccessible(true);
    final Map<?, ?> leakyMap = (Map<?, ?>) field.get(null);
    leakyMap.clear();
    final int knownBrowsers = leakyMap.size();
    BrowserVersion browserVersion = new BrowserVersion.BrowserVersionBuilder(BrowserVersion.FIREFOX_78).setApplicationVersion("App").setApplicationVersion("Version").setUserAgent("User agent").build();
    JavaScriptConfiguration.getInstance(browserVersion);
    browserVersion = new BrowserVersion.BrowserVersionBuilder(BrowserVersion.FIREFOX_78).setApplicationVersion("App2").setApplicationVersion("Version2").setUserAgent("User agent2").build();
    JavaScriptConfiguration.getInstance(browserVersion);
    replacedertEquals(knownBrowsers + 1, leakyMap.size());
}

18 Source : JavaScriptConfigurationTest.java
with Apache License 2.0
from Xceptance

/**
 * See issue 1890.
 *
 * @throws Exception if the test fails
 */
@Test
public void original() throws Exception {
    final BrowserVersion browserVersion = BrowserVersion.CHROME;
    test(browserVersion);
}

18 Source : JavaScriptConfigurationTest.java
with Apache License 2.0
from Xceptance

/**
 * Regression test for Bug #899.
 * This test was throwing an OutOfMemoryError when the bug existed.
 * @throws Exception if an error occurs
 */
@Test
public void memoryLeak() throws Exception {
    final RandomStringGenerator generator = new RandomStringGenerator.Builder().withinRange('a', 'z').build();
    long count = 0;
    while (count++ < 3000) {
        final BrowserVersion browserVersion = new BrowserVersion.BrowserVersionBuilder(BrowserVersion.FIREFOX_78).setApplicationVersion("App" + generator.generate(20)).setApplicationVersion("Version" + generator.generate(20)).setUserAgent("User Agent" + generator.generate(20)).build();
        JavaScriptConfiguration.getInstance(browserVersion);
        if (LOG.isInfoEnabled()) {
            LOG.info("count: " + count + "; memory stats: " + getMemoryStats());
        }
    }
    System.gc();
}

18 Source : HtmlUnitRegExpProxy.java
with Apache License 2.0
from Xceptance

/**
 * Begins customization of JavaScript RegExp base on JDK regular expression support.
 *
 * @author Marc Guillemot
 * @author Ahmed Ashour
 * @author Ronald Brill
 * @author Carsten Steul
 */
public clreplaced HtmlUnitRegExpProxy extends RegExpImpl {

    private static final Log LOG = LogFactory.getLog(HtmlUnitRegExpProxy.clreplaced);

    /**
     * Pattern cache
     */
    // XC start
    /*
    private static final Map<String, Pattern> PATTENS = new HashMap<>();
    */
    private static final ConcurrentLRUCache<String, Pattern> PATTENS = new ConcurrentLRUCache<>(1001);

    // XC end
    private final RegExpProxy wrapped_;

    private final BrowserVersion browserVersion_;

    /**
     * Wraps a proxy to enhance it.
     * @param wrapped the original proxy
     * @param browserVersion the current browser version
     */
    public HtmlUnitRegExpProxy(final RegExpProxy wrapped, final BrowserVersion browserVersion) {
        wrapped_ = wrapped;
        browserVersion_ = browserVersion;
    }

    /**
     * Use the wrapped proxy except for replacement with string arg where it uses Java regular expression.
     * {@inheritDoc}
     */
    @Override
    public Object action(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args, final int actionType) {
        try {
            return doAction(cx, scope, thisObj, args, actionType);
        } catch (final StackOverflowError e) {
            // TODO: We shouldn't have to catch this exception and fall back to Rhino's regex support!
            // See HtmlUnitRegExpProxyTest.stackOverflow()
            LOG.warn(e.getMessage(), e);
            return wrapped_.action(cx, scope, thisObj, args, actionType);
        }
    }

    private Object doAction(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args, final int actionType) {
        // in a first time just improve replacement with a String (not a function)
        if (RA_REPLACE == actionType && args.length == 2 && args[1] instanceof String) {
            final String thisString = Context.toString(thisObj);
            final String replacement = (String) args[1];
            final Object arg0 = args[0];
            if (arg0 instanceof String) {
                // arg0 should *not* be interpreted as a RegExp
                return doStringReplacement(thisString, (String) arg0, replacement);
            }
            if (arg0 instanceof NativeRegExp) {
                try {
                    final NativeRegExp regexp = (NativeRegExp) arg0;
                    final RegExpData reData = new RegExpData(regexp);
                    final Matcher matcher = reData.getPattern().matcher(thisString);
                    return doReplacement(thisString, replacement, matcher, reData.isGlobal());
                } catch (final PatternSyntaxException e) {
                    LOG.warn(e.getMessage(), e);
                }
            }
        } else if (RA_MATCH == actionType || RA_SEARCH == actionType) {
            if (args.length == 0) {
                return null;
            }
            final Object arg0 = args[0];
            final String thisString = Context.toString(thisObj);
            final RegExpData reData;
            if (arg0 instanceof NativeRegExp) {
                reData = new RegExpData((NativeRegExp) arg0);
            } else {
                reData = new RegExpData(Context.toString(arg0));
            }
            final Matcher matcher = reData.getPattern().matcher(thisString);
            final boolean found = matcher.find();
            if (RA_SEARCH == actionType) {
                if (found) {
                    setProperties(matcher, thisString, matcher.start(), matcher.end());
                    return matcher.start();
                }
                return -1;
            }
            if (!found) {
                return null;
            }
            final int index = matcher.start(0);
            final List<Object> groups = new ArrayList<>();
            if (reData.isGlobal()) {
                // has flag g
                groups.add(matcher.group(0));
                setProperties(matcher, thisString, matcher.start(0), matcher.end(0));
                while (matcher.find()) {
                    groups.add(matcher.group(0));
                    setProperties(matcher, thisString, matcher.start(0), matcher.end(0));
                }
            } else {
                for (int i = 0; i <= matcher.groupCount(); i++) {
                    Object group = matcher.group(i);
                    if (group == null) {
                        group = Undefined.instance;
                    }
                    groups.add(group);
                }
                setProperties(matcher, thisString, matcher.start(), matcher.end());
            }
            final Scriptable response = cx.newArray(scope, groups.toArray());
            // the additional properties (cf ECMA script reference 15.10.6.2 13)
            response.put("index", response, Integer.valueOf(index));
            response.put("input", response, thisString);
            return response;
        }
        return wrappedAction(cx, scope, thisObj, args, actionType);
    }

    private String doStringReplacement(final String originalString, final String searchString, final String replacement) {
        if (originalString == null) {
            return "";
        }
        final StaticStringMatcher matcher = new StaticStringMatcher(originalString, searchString);
        if (matcher.start() > -1) {
            final StringBuilder sb = new StringBuilder().append(originalString, 0, matcher.start_);
            String localReplacement = replacement;
            if (replacement.contains("$")) {
                localReplacement = computeReplacementValue(localReplacement, originalString, matcher, false);
            }
            sb.append(localReplacement).append(originalString, matcher.end_, originalString.length());
            return sb.toString();
        }
        return originalString;
    }

    private String doReplacement(final String originalString, final String replacement, final Matcher matcher, final boolean replaceAll) {
        final StringBuilder sb = new StringBuilder();
        int previousIndex = 0;
        while (matcher.find()) {
            sb.append(originalString, previousIndex, matcher.start());
            String localReplacement = replacement;
            if (replacement.contains("$")) {
                localReplacement = computeReplacementValue(replacement, originalString, matcher, browserVersion_.hasFeature(JS_REGEXP_GROUP0_RETURNS_WHOLE_MATCH));
            }
            sb.append(localReplacement);
            previousIndex = matcher.end();
            setProperties(matcher, originalString, matcher.start(), previousIndex);
            if (!replaceAll) {
                break;
            }
        }
        sb.append(originalString, previousIndex, originalString.length());
        return sb.toString();
    }

    String computeReplacementValue(final String replacement, final String originalString, final MatchResult matcher, final boolean group0ReturnsWholeMatch) {
        int lastIndex = 0;
        final StringBuilder result = new StringBuilder();
        int i;
        while ((i = replacement.indexOf('$', lastIndex)) > -1) {
            if (i > 0) {
                result.append(replacement, lastIndex, i);
            }
            String ss = null;
            if (i < replacement.length() - 1 && (i == lastIndex || replacement.charAt(i - 1) != '$')) {
                final char next = replacement.charAt(i + 1);
                // only valid back reference are "evaluated"
                if (next >= '1' && next <= '9') {
                    final int num1digit = next - '0';
                    final char next2 = i + 2 < replacement.length() ? replacement.charAt(i + 2) : 'x';
                    final int num2digits;
                    // if there are 2 digits, the second one is considered as part of the group number
                    // only if there is such a group
                    if (next2 >= '1' && next2 <= '9') {
                        num2digits = num1digit * 10 + (next2 - '0');
                    } else {
                        num2digits = Integer.MAX_VALUE;
                    }
                    if (num2digits <= matcher.groupCount()) {
                        ss = matcher.group(num2digits);
                        i++;
                    } else if (num1digit <= matcher.groupCount()) {
                        ss = StringUtils.defaultString(matcher.group(num1digit));
                    }
                } else {
                    switch(next) {
                        case '&':
                            ss = matcher.group();
                            break;
                        case '0':
                            if (group0ReturnsWholeMatch) {
                                ss = matcher.group();
                            }
                            break;
                        case '`':
                            ss = originalString.substring(0, matcher.start());
                            break;
                        case '\'':
                            ss = originalString.substring(matcher.end());
                            break;
                        case '$':
                            ss = "$";
                            break;
                        default:
                    }
                }
            }
            if (ss == null) {
                result.append('$');
                lastIndex = i + 1;
            } else {
                result.append(ss);
                lastIndex = i + 2;
            }
        }
        result.append(replacement, lastIndex, replacement.length());
        return result.toString();
    }

    /**
     * Calls action on the wrapped RegExp proxy.
     */
    private Object wrappedAction(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args, final int actionType) {
        // take care to set the context's RegExp proxy to the original one as this is checked
        // (cf net.sourceforge.htmlunit.corejs.javascript.regexp.RegExpImp:334)
        try {
            ScriptRuntime.setRegExpProxy(cx, wrapped_);
            return wrapped_.action(cx, scope, thisObj, args, actionType);
        } finally {
            ScriptRuntime.setRegExpProxy(cx, this);
        }
    }

    private void setProperties(final Matcher matcher, final String thisString, final int startPos, final int endPos) {
        // lastMatch
        final String match = matcher.group();
        if (match == null) {
            lastMatch = new SubString();
        } else {
            lastMatch = new SubString(match, 0, match.length());
        }
        // parens
        final int groupCount = matcher.groupCount();
        if (groupCount == 0) {
            parens = null;
        } else {
            final int count = Math.min(9, groupCount);
            parens = new SubString[count];
            for (int i = 0; i < count; i++) {
                final String group = matcher.group(i + 1);
                if (group == null) {
                    parens[i] = new SubString();
                } else {
                    parens[i] = new SubString(group, 0, group.length());
                }
            }
        }
        // lastParen
        if (groupCount > 0) {
            if (groupCount > 9 && browserVersion_.hasFeature(JS_REGEXP_EMPTY_LASTPAREN_IF_TOO_MANY_GROUPS)) {
                lastParen = new SubString();
            } else {
                final String last = matcher.group(groupCount);
                if (last == null) {
                    lastParen = new SubString();
                } else {
                    lastParen = new SubString(last, 0, last.length());
                }
            }
        }
        // leftContext
        if (startPos > 0) {
            leftContext = new SubString(thisString, 0, startPos);
        } else {
            leftContext = new SubString();
        }
        // rightContext
        final int length = thisString.length();
        if (endPos < length) {
            rightContext = new SubString(thisString, endPos, length - endPos);
        } else {
            rightContext = new SubString();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object compileRegExp(final Context cx, final String source, final String flags) {
        try {
            return wrapped_.compileRegExp(cx, source, flags);
        } catch (final Exception e) {
            if (LOG.isWarnEnabled()) {
                LOG.warn("compileRegExp() threw for >" + source + "<, flags: >" + flags + "<. " + "Replacing with a '####shouldNotFindAnything###'");
            }
            return wrapped_.compileRegExp(cx, "####shouldNotFindAnything###", "");
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int find_split(final Context cx, final Scriptable scope, final String target, final String separator, final Scriptable re, final int[] ip, final int[] matchlen, final boolean[] matched, final String[][] parensp) {
        return wrapped_.find_split(cx, scope, target, separator, re, ip, matchlen, matched, parensp);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isRegExp(final Scriptable obj) {
        return wrapped_.isRegExp(obj);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Scriptable wrapRegExp(final Context cx, final Scriptable scope, final Object compiled) {
        return wrapped_.wrapRegExp(cx, scope, compiled);
    }

    private static clreplaced RegExpData {

        private final boolean global_;

        private Pattern pattern_;

        RegExpData(final NativeRegExp re) {
            // the form is /regex/flags
            final String str = re.toString();
            final String jsSource = StringUtils.substringBeforeLast(str.substring(1), "/");
            final String jsFlags = StringUtils.substringAfterLast(str, "/");
            global_ = jsFlags.indexOf('g') != -1;
            pattern_ = PATTENS.get(str);
            if (pattern_ == null) {
                pattern_ = Pattern.compile(jsRegExpToJavaRegExp(jsSource), getJavaFlags(jsFlags));
                PATTENS.put(str, pattern_);
            }
        }

        RegExpData(final String string) {
            global_ = false;
            pattern_ = PATTENS.get(string);
            if (pattern_ == null) {
                pattern_ = Pattern.compile(jsRegExpToJavaRegExp(string), 0);
                PATTENS.put(string, pattern_);
            }
        }

        /**
         * Converts the current JavaScript RegExp flags to Java Pattern flags.
         * @return the Java Pattern flags
         */
        private static int getJavaFlags(final String jsFlags) {
            int flags = 0;
            if (jsFlags.contains("i")) {
                flags |= Pattern.CASE_INSENSITIVE;
            }
            if (jsFlags.contains("m")) {
                flags |= Pattern.MULTILINE;
            }
            return flags;
        }

        boolean isGlobal() {
            return global_;
        }

        Pattern getPattern() {
            return pattern_;
        }
    }

    /**
     * Transform a JavaScript regular expression to a Java regular expression
     * @param re the JavaScript regular expression to transform
     * @return the transformed expression
     */
    static String jsRegExpToJavaRegExp(final String re) {
        final RegExpJsToJavaConverter regExpJsToJavaFSM = new RegExpJsToJavaConverter();
        return regExpJsToJavaFSM.convert(re);
    }

    /**
     * Simple helper.
     */
    private static final clreplaced StaticStringMatcher implements MatchResult {

        private final String group_;

        private final int start_;

        private final int end_;

        StaticStringMatcher(final String originalString, final String searchString) {
            final int pos = originalString.indexOf(searchString);
            group_ = searchString;
            start_ = pos;
            end_ = pos + searchString.length();
        }

        @Override
        public String group() {
            return group_;
        }

        @Override
        public int start() {
            return start_;
        }

        @Override
        public int end() {
            return end_;
        }

        @Override
        public int start(final int group) {
            // not used so far
            return 0;
        }

        @Override
        public int end(final int group) {
            // not used so far
            return 0;
        }

        @Override
        public String group(final int group) {
            // not used so far
            return null;
        }

        @Override
        public int groupCount() {
            // not used so far
            return 0;
        }
    }
}

18 Source : NumberCustom.java
with Apache License 2.0
from Xceptance

/**
 * Returns a string with a language sensitive representation of this number.
 * @param context the JavaScript context
 * @param thisObj the scriptable
 * @param args the arguments preplaceded into the method
 * @param function the function
 * @return the string
 */
public static String toLocaleString(final Context context, final Scriptable thisObj, final Object[] args, final Function function) {
    if (args.length != 0 && args[0] instanceof String) {
        final String localeStr = (String) args[0];
        try {
            final Locale locale = new Locale.Builder().setLanguageTag(localeStr).build();
            return NumberFormat.getInstance(locale).format(Double.parseDouble(thisObj.toString()));
        } catch (final IllformedLocaleException e) {
            throw ScriptRuntime.rangeError("Invalid language tag: " + localeStr);
        }
    }
    final BrowserVersion browserVersion = ((Window) thisObj.getParentScope()).getBrowserVersion();
    final Locale locale = Locale.forLanguageTag(browserVersion.getBrowserLanguage());
    return NumberFormat.getInstance(locale).format(Double.parseDouble(thisObj.toString()));
}

18 Source : Intl.java
with Apache License 2.0
from Xceptance

/**
 * Define needed properties.
 * @param browserVersion the browser version
 */
public void defineProperties(final BrowserVersion browserVersion) {
    define(Collator.clreplaced, browserVersion);
    define(DateTimeFormat.clreplaced, browserVersion);
    define(NumberFormat.clreplaced, browserVersion);
    if (browserVersion.hasFeature(JS_INTL_V8_BREAK_ITERATOR)) {
        define(V8BreakIterator.clreplaced, browserVersion);
    }
}

18 Source : HTMLSpanElement.java
with Apache License 2.0
from Xceptance

/**
 * 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:
        }
    }
}

18 Source : HTMLOptionsCollection.java
with Apache License 2.0
from Xceptance

/**
 * 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()) {
        return;
    }
    htmlSelect_.removeOption(idx);
}

18 Source : HTMLInputElement.java
with Apache License 2.0
from Xceptance

/**
 * 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("");
        getDomNodeOrDie().valueModifiedByJavascript();
        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);
    getDomNodeOrDie().valueModifiedByJavascript();
}

18 Source : HTMLInputElement.java
with Apache License 2.0
from Xceptance

/**
 * Returns the {@code type} property.
 * @return the {@code type} property
 */
@JsxGetter
public String getType() {
    final BrowserVersion browserVersion = getBrowserVersion();
    String type = getDomNodeOrDie().getTypeAttribute();
    type = type.toLowerCase(Locale.ROOT);
    return isSupported(type, browserVersion) ? type : "text";
}

18 Source : MediaList.java
with Apache License 2.0
from Xceptance

@Override
public Object getDefaultValue(final Clreplaced<?> 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);
}

18 Source : CSSFontFaceRule.java
with Apache License 2.0
from Xceptance

/**
 * {@inheritDoc}
 */
@Override
public String getCssText() {
    String cssText = super.getCssText();
    final BrowserVersion browserVersion = getBrowserVersion();
    if (browserVersion.hasFeature(CSS_FONTFACERULE_CSSTEXT_IE_STYLE)) {
        cssText = StringUtils.replace(cssText, "{", "{\n\t");
        cssText = StringUtils.replace(cssText, "}", ";\n}\n");
        cssText = StringUtils.replace(cssText, "; ", ";\n\t");
    } else if (browserVersion.hasFeature(CSS_FONTFACERULE_CSSTEXT_CHROME_STYLE)) {
        cssText = StringUtils.replace(cssText, "{", "{ ");
        cssText = StringUtils.replace(cssText, "}", "; }");
        cssText = StringUtils.replace(cssText, "; ", "; ");
        cssText = REPLACEMENT_1.matcher(cssText).replaceFirst("font-family: $1;");
        cssText = REPLACEMENT_2.matcher(cssText).replaceFirst("src: url(\"$1\");");
    } else {
        cssText = StringUtils.replace(cssText, "{", "{\n  ");
        cssText = StringUtils.replace(cssText, "}", ";\n}");
        cssText = StringUtils.replace(cssText, "; ", ";\n  ");
        cssText = REPLACEMENT_1.matcher(cssText).replaceFirst("font-family: $1;");
        cssText = REPLACEMENT_2.matcher(cssText).replaceFirst("src: url(\"$1\");");
    }
    return cssText;
}

18 Source : JavaScriptConfiguration.java
with Apache License 2.0
from Xceptance

/**
 * 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;
}

18 Source : HtmlSubmitInput.java
with Apache License 2.0
from Xceptance

/**
 * 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)) {
                // value attribute was specified
                return attributes;
            }
        }
        // value attribute was not specified, add it
        final DomAttr newAttr = new DomAttr(page, null, "value", DEFAULT_VALUE, true);
        attributes.put("value", newAttr);
    }
    return attributes;
}

18 Source : HtmlResetInput.java
with Apache License 2.0
from Xceptance

/**
 * 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)) {
                // value attribute was specified
                return attributes;
            }
        }
        // value attribute was not specified, add it
        final DomAttr newAttr = new DomAttr(page, null, "value", DEFAULT_VALUE, true);
        attributes.put("value", newAttr);
    }
    return attributes;
}

18 Source : HtmlLink.java
with Apache License 2.0
from Xceptance

/**
 * Returns the request which will allow us to retrieve the content referenced by the {@code href} attribute.
 * @return the request which will allow us to retrieve the content referenced by the {@code href} attribute
 * @throws MalformedURLException in case of problem resolving the URL
 */
public WebRequest getWebRequest() throws MalformedURLException {
    final HtmlPage page = (HtmlPage) getPage();
    final URL url = page.getFullyQualifiedUrl(getHrefAttribute());
    final BrowserVersion browser = page.getWebClient().getBrowserVersion();
    final WebRequest request = new WebRequest(url, browser.getCssAcceptHeader(), browser.getAcceptEncodingHeader());
    // use the page encoding even if this is a GET requests
    request.setCharset(page.getCharset());
    request.setAdditionalHeader(HttpHeader.REFERER, page.getUrl().toExternalForm());
    return request;
}

18 Source : HtmlImage.java
with Apache License 2.0
from Xceptance

/**
 * <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)) {
            final HtmlPage page = (HtmlPage) getPage();
            final WebClient webClient = page.getWebClient();
            final BrowserVersion browser = webClient.getBrowserVersion();
            if (!(browser.hasFeature(HTMLIMAGE_BLANK_SRC_AS_EMPTY) && StringUtils.isBlank(src))) {
                final URL url = page.getFullyQualifiedUrl(src);
                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);
            }
        }
        if (imageData_ != null) {
            imageData_.close();
            imageData_ = null;
        }
        downloaded_ = true;
        isComplete_ = hasFeature(JS_IMAGE_COMPLETE_RETURNS_TRUE_FOR_NO_REQUEST) || (imageWebResponse_ != null && imageWebResponse_.getContentType().contains("image"));
        width_ = -1;
        height_ = -1;
    }
}

18 Source : MSXMLConfiguration.java
with Apache License 2.0
from Xceptance

/**
 * 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;
}

See More Examples