com.gargoylesoftware.htmlunit.Page

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

313 Examples 7

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

private void alertHandler(Page page, String message) {
    if (quitting_) {
        return;
    }
    webWindow_ = page.getEnclosingWindow();
    holder_ = new AlertHolder(message);
    awaitCondition();
}

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

private boolean onbeforeunloadHandler(Page page, String returnValue) {
    if (quitting_) {
        return true;
    }
    webWindow_ = page.getEnclosingWindow();
    holder_ = new AlertHolder(returnValue);
    AlertHolder localHolder = holder_;
    awaitCondition();
    return localHolder.isAccepted();
}

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

private boolean confirmHandler(Page page, String message) {
    if (quitting_) {
        return false;
    }
    webWindow_ = page.getEnclosingWindow();
    holder_ = new AlertHolder(message);
    AlertHolder localHolder = holder_;
    awaitCondition();
    return localHolder.isAccepted();
}

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

/**
 * Indicates if the action still needs to be executed.
 * @return {@code true} if the action needs to be executed
 */
public boolean isStillAlive() {
    final Page owningPage = getOwningPage();
    return owningPage != null && owningPage == owningPage.getEnclosingWindow().getEnclosedPage();
}

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

/**
 * An attachment represents a page received from the server which contains a
 * {@code Content-Disposition=attachment} header.
 *
 * @author Bruce Chapman
 * @author Sudhan Moghe
 * @author Daniel Gredler
 * @author Ronald Brill
 */
public clreplaced Attachment {

    /**
     * The attached page.
     */
    private final Page page_;

    /**
     * Creates a new attachment for the specified page.
     * @param page the attached page
     */
    public Attachment(final Page page) {
        page_ = page;
    }

    /**
     * Returns the attached page.
     * @return the attached page
     */
    public Page getPage() {
        return page_;
    }

    /**
     * Returns the attachment's filename, as suggested by the <tt>Content-Disposition</tt>
     * header, or {@code null} if no filename was suggested.
     * @return the attachment's suggested filename, or {@code null} if none was suggested
     */
    public String getSuggestedFilename() {
        final WebResponse response = page_.getWebResponse();
        final String disp = response.getResponseHeaderValue(HttpHeader.CONTENT_DISPOSITION);
        int start = disp.indexOf("filename=");
        if (start == -1) {
            return null;
        }
        start += "filename=".length();
        if (start >= disp.length()) {
            return null;
        }
        int end = disp.indexOf(';', start);
        if (end == -1) {
            end = disp.length();
        }
        if (disp.charAt(start) == '"' && disp.charAt(end - 1) == '"') {
            start++;
            end--;
        }
        return disp.substring(start, end);
    }
}

19 Source : OidcCertificationRPBasicProfileTests.java
with Eclipse Public License 1.0
from OpenLiberty

protected JsonObject parseClientConfigFromResponse(Page response) throws Exception {
    String responseText = WebResponseUtils.getResponseText(response);
    return Json.createReader(new StringReader(responseText)).readObject();
}

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

/**
 * Process {@link HtmlInlineFrame}.
 *
 * @param builder the StringBuilder to add to
 * @param htmlInlineFrame the target to process
 */
protected void appendInlineFrame(final StringBuilder builder, final HtmlInlineFrame htmlInlineFrame) {
    if (isVisible(htmlInlineFrame)) {
        builder.append(AS_TEXT_BLOCK_SEPARATOR);
        final Page page = htmlInlineFrame.getEnclosedPage();
        if (page instanceof SgmlPage) {
            builder.append(((SgmlPage) page).asText());
        }
        builder.append(AS_TEXT_BLOCK_SEPARATOR);
    }
}

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

/**
 * An attachment represents a page received from the server which contains a
 * {@code Content-Disposition=attachment} header.
 *
 * @author Bruce Chapman
 * @author Sudhan Moghe
 * @author Daniel Gredler
 */
public clreplaced Attachment {

    /**
     * The attached page.
     */
    private final Page page_;

    /**
     * Creates a new attachment for the specified page.
     * @param page the attached page
     */
    public Attachment(final Page page) {
        page_ = page;
    }

    /**
     * Returns the attached page.
     * @return the attached page
     */
    public Page getPage() {
        return page_;
    }

    /**
     * Returns the attachment's filename, as suggested by the <tt>Content-Disposition</tt>
     * header, or {@code null} if no filename was suggested.
     * @return the attachment's suggested filename, or {@code null} if none was suggested
     */
    public String getSuggestedFilename() {
        final WebResponse response = page_.getWebResponse();
        final String disp = response.getResponseHeaderValue("Content-Disposition");
        int start = disp.indexOf("filename=");
        if (start == -1) {
            return null;
        }
        start += "filename=".length();
        if (start >= disp.length()) {
            return null;
        }
        int end = disp.indexOf(';', start);
        if (end == -1) {
            end = disp.length();
        }
        if (disp.charAt(start) == '"' && disp.charAt(end - 1) == '"') {
            start++;
            end--;
        }
        return disp.substring(start, end);
    }

    /**
     * Returns {@code true} if the specified response represents an attachment.
     * @param response the response to check
     * @return {@code true} if the specified response represents an attachment, {@code false} otherwise
     * @see <a href="http://www.ietf.org/rfc/rfc2183.txt">RFC 2183</a>
     */
    public static boolean isAttachment(final WebResponse response) {
        final String disp = response.getResponseHeaderValue("Content-Disposition");
        if (disp == null) {
            return false;
        }
        return disp.startsWith("attachment");
    }
}

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

/**
 * Test that setSelectedAttribute returns the right page.
 *
 * @exception Exception If the test fails
 */
@Test
public void setSelectedAttributeReturnedPage() throws Exception {
    final String content = "<html><head><replacedle>foo</replacedle>\n" + "<script>\n" + "function test() {\n" + "  doreplacedent.getElementById('iframe').src = 'about:blank';\n" + "}\n" + "</script>\n" + "</head><body>\n" + "<form>\n" + "<select name='select1' size='1' id='mySelect' onchange='test()'>\n" + "<option value='option1'>option 1</option>\n" + "<option value='option2'>option 2</option>\n" + "</select>\n" + "</form>\n" + "<iframe id='iframe' src='about:blank'></iframe>\n" + "</body></html>";
    final HtmlPage page = loadPage(content);
    final HtmlSelect select = page.getHtmlElementById("mySelect");
    final HtmlOption option = select.getOptionByValue("option2");
    final Page page2 = select.setSelectedAttribute(option, true);
    replacedertEquals(page, page2);
}

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

private String promptHandler(Page page, String message, String defaultMessage) {
    if (quitting_) {
        return null;
    }
    webWindow_ = page.getEnclosingWindow();
    holder_ = new PromptHolder(message, defaultMessage);
    PromptHolder localHolder = (PromptHolder) holder_;
    awaitCondition();
    return localHolder.value;
}

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

/**
 * Loads the page from the preplaceded URL.
 *
 * @param url
 *            the target URL
 * @throws Exception
 *             if an error occurred while loading the page
 */
protected void loadXMLPage(final URL url) throws Exception {
    final Page result = getWebClient().getPage(url);
    if (result instanceof XmlPage) {
        xmlPage = (XmlPage) result;
    } else {
        throw new UnexpectedPageTypeException("The page type of '" + url + "' is not XML as expected.");
    }
}

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

/**
 * Initializes this Location.
 *
 * @param window the window that this location belongs to
 * @param page the page that will become the enclosing page
 */
public void initialize(final Window window, final Page page) {
    window_ = window;
    if (window_ != null && page != null) {
        setHash(null, page.getUrl().getRef());
    }
}

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

/**
 * Process {@link HtmlInlineFrame}.
 *
 * @param builder the StringBuilder to add to
 * @param htmlInlineFrame the target to process
 * @param mode the {@link Mode} to use for processing
 */
protected void appendInlineFrame(final HtmlSerializerTextBuilder builder, final HtmlInlineFrame htmlInlineFrame, final Mode mode) {
    if (isVisible(htmlInlineFrame)) {
        builder.appendBlockSeparator();
        final Page page = htmlInlineFrame.getEnclosedPage();
        if (page instanceof SgmlPage) {
            builder.append(((SgmlPage) page).asText(), mode);
        }
        builder.appendBlockSeparator();
    }
}

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

/**
 * Process {@link HtmlInlineFrame}.
 *
 * @param builder the StringBuilder to add to
 * @param htmlInlineFrame the target to process
 */
protected void appendInlineFrame(final HtmlSerializerTextBuilder builder, final HtmlInlineFrame htmlInlineFrame) {
    if (isVisible(htmlInlineFrame)) {
        builder.appendBlockSeparator();
        final Page page = htmlInlineFrame.getEnclosedPage();
        if (page instanceof SgmlPage) {
            builder.append(((SgmlPage) page).asText(), Mode.NORMALIZE);
        }
        builder.appendBlockSeparator();
    }
}

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

/**
 * Override of default clickAction that makes this radio button the selected
 * one when it is clicked.
 * {@inheritDoc}
 *
 * @throws IOException if an IO error occurred
 */
@Override
protected boolean doClickStateUpdate(final boolean shiftKey, final boolean ctrlKey) throws IOException {
    final HtmlForm form = getEnclosingForm();
    final boolean changed = !isChecked();
    final Page page = getPage();
    if (form != null) {
        form.setCheckedRadioButton(this);
    } else if (page != null && page.isHtmlPage()) {
        setCheckedForPage((HtmlPage) page);
    }
    super.doClickStateUpdate(shiftKey, ctrlKey);
    return changed;
}

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

/**
 * Selects the option if it's not already selected.
 * {@inheritDoc}
 */
@Override
public Page mouseUp(final boolean shiftKey, final boolean ctrlKey, final boolean altKey, final int button) {
    Page page = null;
    if (hasFeature(EVENT_ONMOUSEUP_FOR_SELECT_OPTION_TRIGGERS_ADDITIONAL_UP_FOR_SELECT)) {
        page = getEnclosingSelect().mouseUp(shiftKey, ctrlKey, altKey, button);
    }
    if (hasFeature(EVENT_ONMOUSEUP_NOT_FOR_SELECT_OPTION)) {
        return page;
    }
    return super.mouseUp(shiftKey, ctrlKey, altKey, button);
}

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

/**
 * Selects the option if it's not already selected.
 * {@inheritDoc}
 */
@Override
public Page mouseDown(final boolean shiftKey, final boolean ctrlKey, final boolean altKey, final int button) {
    Page page = null;
    if (hasFeature(EVENT_ONMOUSEDOWN_FOR_SELECT_OPTION_TRIGGERS_ADDITIONAL_DOWN_FOR_SELECT)) {
        page = getEnclosingSelect().mouseDown(shiftKey, ctrlKey, altKey, button);
    }
    if (hasFeature(EVENT_ONMOUSEDOWN_NOT_FOR_SELECT_OPTION)) {
        return page;
    }
    return super.mouseDown(shiftKey, ctrlKey, altKey, button);
}

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

/**
 * {@inheritDoc}
 */
@Override
protected boolean isJavaScriptInitializationNeeded(final Page page) {
    return getScriptableObject() == null || !(page.getWebResponse() instanceof StringWebResponse);
// TODO: find a better way to distinguish content written by doreplacedent.open(),...
}

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

/**
 * {@inheritDoc}
 */
@Override
public void handleAttachment(final Page page) {
    collectedAttachments_.add(new Attachment(page));
}

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

/**
 * We will download the file and write it to disk.
 */
public clreplaced DownloadFile extends AbstractHtmlPageAction {

    /**
     * The timer name to use. The timer name is used to log measurements replacedociated with this action. It can be preplaceded
     * to the super clreplaced by the constructor.
     */
    private static final String TIMERNAME = "DownloadFile";

    /**
     * the file anchor
     */
    private HtmlAnchor fileAnchor;

    /**
     * The page that contains the file
     */
    private Page filePage;

    /**
     * the name of the file anchor
     */
    private final String anchorName;

    /**
     * Constructor.
     *
     * @param previousAction
     *            the action we come from
     * @param anchorName
     *            the name of the file anchor
     */
    public DownloadFile(final AbstractHtmlPageAction previousAction, final String anchorName) {
        super(previousAction, TIMERNAME);
        this.anchorName = anchorName;
    }

    /**
     * Verify all preconditions. The prevalidate method is a used to ensure that everything that is needed to execute
     * this action is present on the page.
     */
    @Override
    public void preValidate() throws Exception {
        final HtmlPage page = getPreviousAction().getHtmlPage();
        // let's get the anchor
        fileAnchor = page.getAnchorByText(anchorName);
        fileAnchor.getHrefAttribute();
    }

    /**
     * Here we will click the link and receive the file.
     */
    @Override
    protected void execute() throws Exception {
        // click the link
        filePage = fileAnchor.click();
    }

    /**
     * Validate the correctness of the result.
     */
    @Override
    protected void postValidate() throws Exception {
        // check if we have a TextPage
        // in this case we check the content
        if (filePage.getClreplaced().toString().contains("TextPage")) {
            replacedert.replacedertEquals(filePage.getWebResponse().getContentreplacedtring(), "test");
        }
        // get Url of the file
        final URL fileUrl = filePage.getWebResponse().getWebRequest().getUrl();
        // now we extract the file name from the url to create our file on disk
        final File file = new File("results/TFileDownload" + fileUrl.getFile().substring(fileUrl.getFile().lastIndexOf('/')));
        // now save file to disk
        FileUtils.copyURLToFile(fileUrl, file);
    }
}

18 Source : OidcCertificationRPBasicProfileTests.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * The OIDC certification OP creates a random user name as the authenticated user in each test. This method extracts that
 * username from the test servlet response text.
 */
protected String extractreplacedignedUserNameFromResponse(Page response) throws Exception {
    String responseText = WebResponseUtils.getResponseText(response);
    return FatStringUtils.extractRegexGroup(responseText, "getRemoteUser: (.+)");
}

18 Source : WebFormUtilsTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * Tests:
 * - Submit button value: Empty
 * Expects:
 * - Submission should succeed
 */
@Test
public void test_submitForm_emptySubmitButtonValue() {
    try {
        final String submitButtonValue = "";
        mockery.checking(new Expectations() {

            {
                one(form).getInputByValue(submitButtonValue);
                will(returnValue(submitButton));
                one(submitButton).click();
                will(returnValue(page));
            }
        });
        Page result = utils.submitForm(form, submitButtonValue);
        replacedertEquals("Page returned did not match the mocked value.", page, result);
    } catch (Throwable t) {
        outputMgr.failWithThrowable(testName.getMethodName(), t);
    }
}

18 Source : WebFormUtilsTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * *********************************** submitForm *************************************
 */
/**
 * Tests:
 * - Submit button value: null
 * Expects:
 * - Exception should be thrown saying the submit button value is null
 */
@Test
public void test_submitForm_nullSubmitButtonValue() {
    try {
        String submitButtonValue = null;
        try {
            Page result = utils.submitForm(form, submitButtonValue);
            fail("Should have thrown an exception but did not. Got result [" + ((result == null) ? null : result.getWebResponse().getContentreplacedtring()));
        } catch (Exception e) {
            verifyException(e, "Cannot submit.+form.+submit button value is null");
        }
    } catch (Throwable t) {
        outputMgr.failWithThrowable(testName.getMethodName(), t);
    }
}

18 Source : WebFormUtilsTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * Tests:
 * - Submit button value: Non-empty
 * - Submit button with the specified value does not exist
 * Expects:
 * - ElementNotFoundException should be thrown as-is
 */
@Test
public void test_submitForm_elementNotFound() {
    try {
        final String submitButtonValue = "mySubmitButton";
        mockery.checking(new Expectations() {

            {
                one(form).getInputByValue(submitButtonValue);
                will(throwException(new ElementNotFoundException(submitButtonValue, "attributeName", "attributeValue")));
            }
        });
        try {
            Page result = utils.submitForm(form, submitButtonValue);
            fail("Should have thrown an exception but did not. Got result [" + ((result == null) ? null : result.getWebResponse().getContentreplacedtring()));
        } catch (ElementNotFoundException e) {
        // Expected - should not wrap or re-throw the exception
        }
    } catch (Throwable t) {
        outputMgr.failWithThrowable(testName.getMethodName(), t);
    }
}

18 Source : TestActionsTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * Tests:
 * - URL invocation succeeds
 * Expects:
 * - Response object should be returned
 */
@Test
public void test_submitRequest_successful() {
    try {
        final String testName = null;
        printMethodNameExpectation();
        printRequestPartsExpectation();
        mockery.checking(new Expectations() {

            {
                one(webClient).getPage(request);
                will(returnValue(page));
            }
        });
        printResponsePartsExpectation();
        Page result = actions.submitRequest(testName, webClient, request);
        replacedertEquals("Resulting page object did not point to expected object.", page, result);
    } catch (Throwable t) {
        outputMgr.failWithThrowable(testName.getMethodName(), t);
    }
}

18 Source : TestActionsTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * Tests:
 * - Parameters list is null
 * Expects:
 * - Response object should be returned
 */
@Test
public void test_invokeUrlWithParametersUsingPost_noWebClient_nullParametersList() {
    try {
        printMethodNameExpectation();
        printMethodNameExpectation();
        printRequestPartsExpectation();
        mockery.checking(new Expectations() {

            {
                one(webClient).getPage(request);
                will(returnValue(page));
                one(webClient).close();
            }
        });
        printResponsePartsExpectation();
        Page result = actions.invokeUrlWithParametersUsingPost(testName.getMethodName(), url, null);
        replacedertEquals("Resulting page object did not point to expected object.", page, result);
    } catch (Throwable t) {
        outputMgr.failWithThrowable(testName.getMethodName(), t);
    }
}

18 Source : TestActionsTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * *********************************** invokeUrl *************************************
 */
/**
 * Tests:
 * - Do not provide a WebClient object
 * - Invoke with a valid URL string
 * Expects:
 * - Response object should be returned
 */
@Test
public void test_invokeUrl_withoutWebClient_withUrl() {
    try {
        printMethodNameExpectation();
        printMethodNameExpectation();
        printRequestPartsExpectation();
        mockery.checking(new Expectations() {

            {
                one(webClient).getPage(request);
                will(returnValue(page));
                one(webClient).close();
            }
        });
        printResponsePartsExpectation();
        Page result = actions.invokeUrl(testName.getMethodName(), url);
        replacedertEquals("Resulting page object did not point to expected object.", page, result);
    } catch (Throwable t) {
        outputMgr.failWithThrowable(testName.getMethodName(), t);
    }
}

18 Source : TestActionsTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * *********************************** invokeUrlWithParametersUsingGet *************************************
 */
/**
 * Tests:
 * - Parameters list is null
 * Expects:
 * - Response object should be returned
 */
@Test
public void test_invokeUrlWithParametersUsingGet_nullParametersList() {
    try {
        printMethodNameExpectation();
        printMethodNameExpectation();
        printRequestPartsExpectation();
        mockery.checking(new Expectations() {

            {
                one(webClient).getPage(request);
                will(returnValue(page));
            }
        });
        printResponsePartsExpectation();
        Page result = actions.invokeUrlWithParametersUsingGet(testName.getMethodName(), webClient, url, null);
        replacedertEquals("Resulting page object did not point to expected object.", page, result);
    } catch (Throwable t) {
        outputMgr.failWithThrowable(testName.getMethodName(), t);
    }
}

18 Source : TestActionsTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * *********************************** invokeUrlWithParametersAndHeaders *************************************
 */
/**
 * Tests:
 * - Parameters and headers lists are null
 * Expects:
 * - Response object should be returned
 */
@Test
public void test_invokeUrlWithParametersAndHeaders_nullParametersAndHeadersLists() {
    try {
        printMethodNameExpectation();
        printMethodNameExpectation();
        printRequestPartsExpectation();
        mockery.checking(new Expectations() {

            {
                one(webClient).getPage(request);
                will(returnValue(page));
            }
        });
        printResponsePartsExpectation();
        Page result = actions.invokeUrlWithParametersAndHeaders(testName.getMethodName(), webClient, url, null, null);
        replacedertEquals("Resulting page object did not point to expected object.", page, result);
    } catch (Throwable t) {
        outputMgr.failWithThrowable(testName.getMethodName(), t);
    }
}

18 Source : TestActionsTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * *********************************** doFormLogin *************************************
 */
/**
 * Tests:
 * - Page object is null
 * Expects:
 * - Exception should be thrown saying the page object is null
 */
@Test
public void test_doFormLogin_page_nullLoginPage() {
    try {
        Page loginPage = null;
        printMethodNameExpectation();
        try {
            actions.doFormLogin(loginPage, username, preplacedword);
            fail("Should have thrown an exception but did not.");
        } catch (Exception e) {
            verifyException(e, "Cannot perform login.* page.* is null");
        }
    } catch (Throwable t) {
        outputMgr.failWithThrowable(testName.getMethodName(), t);
    }
}

18 Source : TestActionsTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * *********************************** submitRequest *************************************
 */
/**
 * Tests:
 * - Do not provide a WebClient object
 * - Invoke with a valid WebRequest
 * Expects:
 * - Response object should be returned
 */
@Test
public void test_submitRequest_withoutWebClient_withWebRequest() {
    try {
        printMethodNameExpectation();
        printRequestPartsExpectation();
        mockery.checking(new Expectations() {

            {
                one(webClient).getPage(request);
                will(returnValue(page));
                one(webClient).close();
            }
        });
        printResponsePartsExpectation();
        Page result = actions.submitRequest(testName.getMethodName(), request);
        replacedertEquals("Resulting page object did not point to expected object.", page, result);
    } catch (Throwable t) {
        outputMgr.failWithThrowable(testName.getMethodName(), t);
    }
}

18 Source : TestActionsTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * *********************************** invokeUrlWithParametersUsingPost *************************************
 */
/**
 * Tests:
 * - Parameters list is null
 * Expects:
 * - Response object should be returned
 */
@Test
public void test_invokeUrlWithParametersUsingPost_nullParametersList() {
    try {
        printMethodNameExpectation();
        printMethodNameExpectation();
        printRequestPartsExpectation();
        mockery.checking(new Expectations() {

            {
                one(webClient).getPage(request);
                will(returnValue(page));
            }
        });
        printResponsePartsExpectation();
        Page result = actions.invokeUrlWithParametersUsingPost(testName.getMethodName(), webClient, url, null);
        replacedertEquals("Resulting page object did not point to expected object.", page, result);
    } catch (Throwable t) {
        outputMgr.failWithThrowable(testName.getMethodName(), t);
    }
}

18 Source : TestActionsTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * Tests:
 * - URL string is a valid URL
 * Expects:
 * - Response object should be returned
 */
@Test
public void test_invokeUrl_validUrl() {
    try {
        printMethodNameExpectation();
        printMethodNameExpectation();
        printRequestPartsExpectation();
        mockery.checking(new Expectations() {

            {
                one(webClient).getPage(request);
                will(returnValue(page));
            }
        });
        printResponsePartsExpectation();
        Page result = actions.invokeUrl(testName.getMethodName(), webClient, url);
        replacedertEquals("Resulting page object did not point to expected object.", page, result);
    } catch (Throwable t) {
        outputMgr.failWithThrowable(testName.getMethodName(), t);
    }
}

18 Source : TestActionsTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * Tests:
 * - Parameters list is null
 * Expects:
 * - Response object should be returned
 */
@Test
public void test_invokeUrlWithParametersUsingGet_noWebClient_nullParametersList() {
    try {
        printMethodNameExpectation();
        printMethodNameExpectation();
        printRequestPartsExpectation();
        mockery.checking(new Expectations() {

            {
                one(webClient).getPage(request);
                will(returnValue(page));
                one(webClient).close();
            }
        });
        printResponsePartsExpectation();
        Page result = actions.invokeUrlWithParametersUsingGet(testName.getMethodName(), url, null);
        replacedertEquals("Resulting page object did not point to expected object.", page, result);
    } catch (Throwable t) {
        outputMgr.failWithThrowable(testName.getMethodName(), t);
    }
}

18 Source : TestActionsTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * *********************************** invokeUrlWithCookie *************************************
 */
/**
 * Tests:
 * - Cookie is null
 * Expects:
 * - Exception should be thrown because of the null cookie
 */
@Test
public void test_invokeUrlWithCookie_nullCookie() {
    try {
        printMethodNameExpectation();
        try {
            Page result = actions.invokeUrlWithCookie(testName.getMethodName(), url, null);
            fail("Should have thrown an exception but got a page result: " + WebResponseUtils.getResponseText(result));
        } catch (Exception e) {
            verifyException(e, "error occurred invoking the URL.*null cookies");
        }
    } catch (Throwable t) {
        outputMgr.failWithThrowable(testName.getMethodName(), t);
    }
}

18 Source : TestActionsTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * Tests:
 * - URL string is not a valid URL
 * Expects:
 * - Exception should be thrown saying the web request couldn't be created because the URL is malformed
 */
@Test
public void test_invokeUrlWithCookie_invalidUrl() {
    try {
        actions = new TestActions();
        actions.loggingUtils = loggingUtils;
        String url = "some invalid string";
        printMethodNameExpectation();
        try {
            Page result = actions.invokeUrlWithCookie(testName.getMethodName(), url, cookie);
            fail("Should have thrown an exception but got a page result: " + WebResponseUtils.getResponseText(result));
        } catch (Exception e) {
            verifyException(e, ".*error occurred invoking the URL.*MalformedURLException");
        }
    } catch (Throwable t) {
        outputMgr.failWithThrowable(testName.getMethodName(), t);
    }
}

18 Source : TestActionsTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * Tests:
 * - Form filled and submitted successfully
 * Expects:
 * - No errors should be logged and the resulting page should be returned
 */
@Test
public void test_doFormLogin_htmlPage_successful() {
    try {
        printMethodNameExpectation();
        mockery.checking(new Expectations() {

            {
                one(webFormUtils).getAndSubmitLoginForm(htmlPage, username, preplacedword);
                will(returnValue(page));
            }
        });
        printResponsePartsExpectation();
        Page result = actions.doFormLogin(htmlPage, username, preplacedword);
        replacedertEquals("Resulting page did not point to expected object.", page, result);
        replacedertStringNotInTrace(outputMgr, "Exception");
    } catch (Throwable t) {
        outputMgr.failWithThrowable(testName.getMethodName(), t);
    }
}

18 Source : TestActionsTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * Tests:
 * - URL string is a valid URL
 * - Provided WebClient is null
 * Expects:
 * - New web client will be created for us
 * - Response object should be returned
 */
@Test
public void test_invokeUrl_validUrl_nullWebClient() {
    try {
        printMethodNameExpectation();
        printMethodNameExpectation();
        printRequestPartsExpectation();
        mockery.checking(new Expectations() {

            {
                one(webClient).getPage(request);
                will(returnValue(page));
                one(webClient).close();
            }
        });
        printResponsePartsExpectation();
        Page result = actions.invokeUrl(testName.getMethodName(), null, url);
        replacedertEquals("Resulting page object did not point to expected object.", page, result);
    } catch (Throwable t) {
        outputMgr.failWithThrowable(testName.getMethodName(), t);
    }
}

18 Source : TestActionsTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * Tests:
 * - URL string is a valid URL
 * - Cookie is valid
 * Expects:
 * - Response object should be returned
 */
@Test
public void test_invokeUrlWithCookie_validUrl() {
    try {
        final String cookieName = "myCookie";
        final String cookieValue = "cookieValue";
        printMethodNameExpectation();
        printMethodNameExpectation();
        printRequestPartsExpectation();
        mockery.checking(new Expectations() {

            {
                one(cookie).getName();
                will(returnValue(cookieName));
                one(cookie).getValue();
                will(returnValue(cookieValue));
                one(request).setAdditionalHeader("Cookie", cookieName + "=" + cookieValue);
                one(webClient).getPage(request);
                will(returnValue(page));
                one(webClient).close();
            }
        });
        printResponsePartsExpectation();
        Page result = actions.invokeUrlWithCookie(testName.getMethodName(), url, cookie);
        replacedertEquals("Resulting page object did not point to expected object.", page, result);
    } catch (Throwable t) {
        outputMgr.failWithThrowable(testName.getMethodName(), t);
    }
}

18 Source : TestActions.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * Invoke the specified URL, adding a basic auth header first
 */
public Page invokeUrlWithBasicAuth(String currentTest, String url, String user, String preplacedword) throws Exception {
    WebClient webClient = createWebClient();
    Page page = invokeUrlWithBasicAuth(currentTest, webClient, url, user, preplacedword);
    destroyWebClient(webClient);
    return page;
}

18 Source : TestActions.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * Finds, fills out, and submits the standard login form in the provided page using the specified credentials. This method
 * expects the page to be an instance of HtmlPage that contains at least one form. The first form the page contains is
 * expected to have an action value of {@code j_security_check} and inputs for {@code j_username} and {@code j_preplacedword}.
 */
public Page doFormLogin(Page loginPage, String username, String preplacedword) throws Exception {
    String thisMethod = "doFormLogin";
    loggingUtils.printMethodName(thisMethod);
    if (loginPage == null) {
        throw new Exception("Cannot perform login because the provided page object is null.");
    }
    if (!(loginPage instanceof HtmlPage)) {
        throw new Exception("Cannot perform login because the provided page object is not a " + HtmlPage.clreplaced.getName() + " instance. Page clreplaced is: " + loginPage.getClreplaced().getName());
    }
    return doFormLogin((HtmlPage) loginPage, username, preplacedword);
}

18 Source : TestActions.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * Invokes the specified URL and returns the Page object that represents the response.
 */
public Page invokeUrl(String currentTest, String url) throws Exception {
    WebClient webClient = createWebClient();
    Page page = invokeUrl(currentTest, webClient, url);
    destroyWebClient(webClient);
    return page;
}

18 Source : FrameWindow.java
with Apache License 2.0
from HtmlUnit

/**
 * {@inheritDoc}
 */
@Override
protected boolean isJavaScriptInitializationNeeded(final Page page) {
    return getScriptableObject() == null || !(page.getWebResponse() instanceof StringWebResponse && ((StringWebResponse) page.getWebResponse()).isFromJavascript());
// TODO: find a better way to distinguish content written by doreplacedent.open(),...
}

17 Source : JavaScriptJobManagerMinimalTest.java
with Apache License 2.0
from Xceptance

/**
 * Minimal tests for {@link JavaScriptJobManagerImpl}. Tests which use the full HtmlUnit stack
 * go in {@link JavaScriptJobManagerTest}.
 *
 * @author Daniel Gredler
 * @author Amit Manjhi
 * @author Ronald Brill
 */
public clreplaced JavaScriptJobManagerMinimalTest {

    private WebClient client_;

    private WebWindow window_;

    private Page page_;

    private JavaScriptJobManagerImpl manager_;

    private DefaultJavaScriptExecutor eventLoop_;

    enum WaitingMode {

        WAIT_STARTING_BEFORE, WAIT_TIMELIMIT
    }

    /**
     * Initializes variables required by the unit tests.
     */
    @Before
    public void before() {
        client_ = new WebClient();
        window_ = EasyMock.createNiceMock(WebWindow.clreplaced);
        page_ = EasyMock.createNiceMock(Page.clreplaced);
        manager_ = new JavaScriptJobManagerImpl(window_);
        EasyMock.expect(window_.getEnclosedPage()).andReturn(page_).anyTimes();
        EasyMock.expect(window_.getJobManager()).andReturn(manager_).anyTimes();
        EasyMock.replay(window_, page_);
        eventLoop_ = new DefaultJavaScriptExecutor(client_);
        eventLoop_.addWindow(window_);
    }

    /**
     * Shuts down the event loop.
     */
    @After
    public void after() {
        eventLoop_.shutdown();
        if (client_ != null) {
            client_.close();
        }
    }

    /**
     * Didn't preplaced reliably.
     * @throws Exception if an error occurs
     */
    @Test
    public void addJob_periodicJob() throws Exception {
        final MutableInt count = new MutableInt(0);
        final JavaScriptJob job = new BasicJavaScriptJob(5, Integer.valueOf(100)) {

            @Override
            public void run() {
                count.increment();
            }
        };
        manager_.addJob(job, page_);
        replacedertEquals(1, manager_.getJobCount());
        final int remainingJobs = manager_.waitForJobs(1090);
        replacedertTrue("At least one remaining job expected.", remainingJobs >= 1);
        replacedertTrue("Less than 10 jobs (" + count.intValue() + ") processed.", count.intValue() >= 10);
    }

    /**
     * Test for changes of revision 5589.
     * Ensures that interval jobs are scheduled at fix rate, no matter how long each one takes.
     * This test failed as of revision 5588 as consequence of the single threaded JS execution changes.
     * @throws Exception if an error occurs
     */
    @Test
    public void addJob_periodicJob2() throws Exception {
        final MutableInt count = new MutableInt(0);
        final JavaScriptJob job = new BasicJavaScriptJob(5, Integer.valueOf(200)) {

            @Override
            public void run() {
                if (count.intValue() == 0) {
                    try {
                        Thread.sleep(200);
                    } catch (final InterruptedException e) {
                    // ignore
                    }
                }
                count.increment();
            }
        };
        manager_.addJob(job, page_);
        final int remainingJobs = manager_.waitForJobs(300);
        replacedertTrue(remainingJobs >= 1);
        // first interval starts at 5 and ends at 205
        // with a fix delay (what would be wrong), we would have second interval start at 205+200 = 405
        // and therefore count == 1
        // with a fix rate (correct), second interval starts at 205 and therefore count == 2
        replacedertEquals(2, count.intValue());
    }

    /**
     * @throws Exception if an error occurs
     */
    @Test
    public void addJob_singleExecution() throws Exception {
        final MutableInt count = new MutableInt(0);
        final JavaScriptJob job = new BasicJavaScriptJob(5, null) {

            @Override
            public void run() {
                count.increment();
            }
        };
        manager_.addJob(job, page_);
        replacedertEquals(1, manager_.getJobCount());
        manager_.waitForJobs(1000);
        replacedertEquals(1, count.intValue());
    }

    /**
     * @throws Exception if an error occurs
     */
    @Test
    public void addJob_multipleExecution_removeJob() throws Exception {
        final MutableInt id = new MutableInt();
        final MutableInt count = new MutableInt(0);
        final JavaScriptJob job = new BasicJavaScriptJob(50, Integer.valueOf(50)) {

            @Override
            public void run() {
                count.increment();
                if (count.intValue() >= 5) {
                    manager_.removeJob(id.intValue());
                }
            }
        };
        id.setValue(manager_.addJob(job, page_));
        manager_.waitForJobs(1000);
        replacedertEquals(5, count.intValue());
    }

    /**
     * @throws Exception if an error occurs
     */
    @Test
    public void addJob_multipleExecution_removeAllJobs() throws Exception {
        final MutableInt count = new MutableInt(0);
        final JavaScriptJob job = new BasicJavaScriptJob(50, Integer.valueOf(50)) {

            @Override
            public void run() {
                count.increment();
                if (count.intValue() >= 5) {
                    manager_.removeAllJobs();
                }
            }
        };
        manager_.addJob(job, page_);
        manager_.waitForJobs(1000);
        replacedertEquals(5, count.intValue());
    }

    /**
     * @throws Exception if an error occurs
     */
    @Test
    public void getJobCount() throws Exception {
        final MutableInt count = new MutableInt();
        final JavaScriptJob job = new BasicJavaScriptJob(50, null) {

            @Override
            public void run() {
                count.setValue(manager_.getJobCount());
            }
        };
        replacedertEquals(0, manager_.getJobCount());
        manager_.addJob(job, page_);
        manager_.waitForJobs(1000);
        replacedertEquals(1, count.intValue());
        replacedertEquals(0, manager_.getJobCount());
    }

    private void waitForCurrentLongJob(final WaitingMode waitingMode, final int expectedFinalJobCount) {
        final JavaScriptJob job = new BasicJavaScriptJob(50, null) {

            // Long job
            @Override
            public void run() {
                try {
                    Thread.sleep(500);
                } catch (final InterruptedException e) {
                // ignore, this is normal
                }
            }
        };
        replacedertEquals(0, manager_.getJobCount());
        manager_.addJob(job, page_);
        final long delayMillis = 100;
        switch(waitingMode) {
            case WAIT_STARTING_BEFORE:
                manager_.waitForJobsStartingBefore(delayMillis);
                break;
            case WAIT_TIMELIMIT:
                manager_.waitForJobs(delayMillis);
                break;
            default:
                throw new IllegalArgumentException("Not handled");
        }
        replacedertEquals(expectedFinalJobCount, manager_.getJobCount());
    }

    /**
     * Tests the waitForJobs call when there is an executing long job.
     */
    @Test
    public void waitForJobs_currentLongJob() {
        waitForCurrentLongJob(WaitingMode.WAIT_TIMELIMIT, 1);
    }

    /**
     * Tests the waitForJobsStartingBefore call when there is an executing long job.
     */
    @Test
    public void waitForJobsStartingBefore_currentLongJob() {
        waitForCurrentLongJob(WaitingMode.WAIT_STARTING_BEFORE, 0);
    }

    private void waitForSimpleJobs(final WaitingMode waitingMode, final int expectedFinalJobCount) {
        final JavaScriptJob job1 = new BasicJavaScriptJob(50, null) {

            @Override
            public void run() {
            // Empty.
            }
        };
        final JavaScriptJob job2 = new BasicJavaScriptJob(1000, null) {

            @Override
            public void run() {
            // Empty.
            }
        };
        replacedertEquals(0, manager_.getJobCount());
        manager_.addJob(job1, page_);
        manager_.addJob(job2, page_);
        final long delayMillis = 250;
        switch(waitingMode) {
            case WAIT_STARTING_BEFORE:
                manager_.waitForJobsStartingBefore(delayMillis);
                break;
            case WAIT_TIMELIMIT:
                manager_.waitForJobs(delayMillis);
                break;
            default:
                throw new IllegalArgumentException("Not handled");
        }
        replacedertEquals(expectedFinalJobCount, manager_.getJobCount());
    }

    /**
     * @throws Exception if an error occurs
     */
    @Test
    public void waitForJobs_simpleJobs() throws Exception {
        waitForSimpleJobs(WaitingMode.WAIT_TIMELIMIT, 1);
    }

    /**
     * @throws Exception if an error occurs
     */
    @Test
    public void waitForJobsStartingBefore_simpleJobs() throws Exception {
        waitForSimpleJobs(WaitingMode.WAIT_STARTING_BEFORE, 1);
    }

    private void waitForComplexJobs(final WaitingMode waitingMode, final int expectedFinalJobCount) {
        final long start = System.currentTimeMillis();
        final JavaScriptJob job1 = new BasicJavaScriptJob(50, null) {

            // This job takes 30ms to complete.
            @Override
            public void run() {
                try {
                    Thread.sleep(30);
                } catch (final InterruptedException e) {
                // ignore, this is normal
                }
            }
        };
        final JavaScriptJob job2 = new BasicJavaScriptJob(60, null) {

            @Override
            public void run() {
            // Empty.
            }
        };
        replacedertEquals(0, manager_.getJobCount());
        manager_.addJob(job1, page_);
        manager_.addJob(job2, page_);
        // sometimes it takes some time to reach this point
        // to make this test stable we have to take care of that
        final long delayMillis = 70 - (System.currentTimeMillis() - start);
        switch(waitingMode) {
            case WAIT_STARTING_BEFORE:
                manager_.waitForJobsStartingBefore(delayMillis);
                break;
            case WAIT_TIMELIMIT:
                manager_.waitForJobs(delayMillis);
                break;
            default:
                throw new RuntimeException("Unknown value for waitingMode enum " + waitingMode);
        }
        replacedertEquals(expectedFinalJobCount, manager_.getJobCount());
    }

    /**
     * @throws Exception if an error occurs
     */
    @Test
    public void waitForJobs_complexJobs() throws Exception {
        // job1 is still running, job2 has not started.
        waitForComplexJobs(WaitingMode.WAIT_TIMELIMIT, 2);
    }

    /**
     * @throws Exception if an error occurs
     */
    @Test
    public void waitForJobsStartingBefore_complexJobs() throws Exception {
        // the call waits until both job1 and job2 finish.
        waitForComplexJobs(WaitingMode.WAIT_STARTING_BEFORE, 0);
    }
}

17 Source : LoggingRefreshHandler.java
with Apache License 2.0
from Xceptance

/**
 * Logs the requested refresh, but does not actually refresh anything.
 * @param page the page that is going to be refreshed
 * @param url the URL where the new page will be loaded
 * @param seconds the number of seconds to wait before reloading the page
 */
@Override
public void handleRefresh(final Page page, final URL url, final int seconds) {
    list_.add(((HtmlPage) page).getreplacedleText());
    list_.add(url);
    list_.add(Integer.valueOf(seconds));
}

17 Source : AbstractHtmlPageAction.java
with Apache License 2.0
from Xceptance

/**
 * Loads the page by typing keys. Whether or not the page is reloaded depends on the key event handlers attached to
 * the target HTML element.
 *
 * @param element
 *            the target HTML element
 * @param text
 *            the text to type
 * @param waitingTime
 *            Waiting time for all background tasks on the page to be finished
 */
protected void loadPageByTypingKeys(final HtmlElement element, final String text, final long waitingTime) throws Exception {
    Page result = element.getPage();
    for (final char ch : text.toCharArray()) {
        result = element.type(ch);
    }
    htmlPage = waitForPageIsComplete(result, waitingTime);
}

17 Source : AbstractHtmlPageAction.java
with Apache License 2.0
from Xceptance

/**
 * Loads the page by selecting an option from the given HTML select element.
 *
 * @param select
 *            the HTML select
 * @param optionValue
 *            the value of the HTML option to select
 * @param waitingTime
 *            Waiting time for all background tasks on the page to be finished
 */
protected void loadPageBySelect(final HtmlSelect select, final String optionValue, final long waitingTime) throws Exception {
    final Page result = select.setSelectedAttribute(optionValue, true);
    htmlPage = waitForPageIsComplete(result, waitingTime);
}

17 Source : AbstractHtmlPageAction.java
with Apache License 2.0
from Xceptance

/**
 * Loads the page by "clicking" the preplaceded HTML element.
 *
 * @param element
 *            the HTML element to click
 * @param waitingTime
 *            Waiting time for all background tasks on the page to be finished
 * @throws Exception
 *             if an error occurred while loading the page
 */
protected void loadPageByClick(final HtmlElement element, final long waitingTime) throws Exception {
    final Page result = element.click();
    htmlPage = waitForPageIsComplete(result, waitingTime);
}

17 Source : BaseFrameElement.java
with Apache License 2.0
from Xceptance

/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
 *
 * Called after the node for the {@code frame} or {@code iframe} has been added to the containing page.
 * The node needs to be added first to allow JavaScript in the frame to see the frame in the parent.
 * @throws FailingHttpStatusCodeException if the server returns a failing status code AND the property
 *      {@link com.gargoylesoftware.htmlunit.WebClientOptions#setThrowExceptionOnFailingStatusCode(boolean)} is
 *      set to true
 */
public void loadInnerPage() throws FailingHttpStatusCodeException {
    String source = getSrcAttribute();
    if (source.isEmpty() || StringUtils.startsWithIgnoreCase(source, WebClient.ABOUT_SCHEME)) {
        source = WebClient.ABOUT_BLANK;
    }
    loadInnerPageIfPossible(source);
    final Page enclosedPage = getEnclosedPage();
    if (enclosedPage != null && enclosedPage.isHtmlPage()) {
        final HtmlPage htmlPage = (HtmlPage) enclosedPage;
        final AbstractJavaScriptEngine<?> jsEngine = getPage().getWebClient().getJavaScriptEngine();
        if (jsEngine != null && jsEngine.isScriptRunning()) {
            final PostponedAction action = new PostponedAction(getPage()) {

                @Override
                public void execute() throws Exception {
                    htmlPage.setReadyState(READY_STATE_COMPLETE);
                }
            };
            jsEngine.addPostponedAction(action);
        } else {
            htmlPage.setReadyState(READY_STATE_COMPLETE);
        }
    }
}

17 Source : BaseFrameElement.java
with Apache License 2.0
from Xceptance

private void loadSrc() {
    loadSrcWhenAddedToPage_ = false;
    final String src = getSrcAttribute();
    final AbstractJavaScriptEngine<?> jsEngine = getPage().getWebClient().getJavaScriptEngine();
    // When src is set from a script, loading is postponed until script finishes
    // in fact this implementation is probably wrong: JavaScript URL should be
    // first evaluated and only loading, when any, should be postponed.
    if (jsEngine == null || !jsEngine.isScriptRunning() || src.startsWith(JavaScriptURLConnection.JAVASCRIPT_PREFIX)) {
        loadInnerPageIfPossible(src);
    } else {
        final Page pageInFrame = getEnclosedPage();
        final PostponedAction action = new PostponedAction(getPage()) {

            @Override
            public void execute() throws Exception {
                if (!src.isEmpty() && getSrcAttribute().equals(src)) {
                    loadInnerPage();
                }
            }

            @Override
            public boolean isStillAlive() {
                // skip if page in frame has already been changed
                return super.isStillAlive() && pageInFrame == getEnclosedPage();
            }
        };
        jsEngine.addPostponedAction(action);
    }
}

See More Examples