net.sourceforge.htmlunit.corejs.javascript.ContextFactory Java Examples

The following examples show how to use net.sourceforge.htmlunit.corejs.javascript.ContextFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CompiledAtomsNotLeakingTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void nestedFragmentsShouldNotLeakVariables() {
  ContextFactory.getGlobal().call(context -> {
    // executeScript atom recursing on itself to execute "return 1+2".
    // Should result in {status:0,value:{status:0,value:3}}
    // Global scope should not be modified.
    String nestedScript = String.format("(%s).call(null, %s, ['return 1+2;'], true)",
        fragment, fragment);

    String jsonResult = (String) eval(context, nestedScript, RESOURCE_PATH);

    Map<String, Object> result = new Json().toType(jsonResult, Json.MAP_TYPE);

    assertThat(result.get("status")).isInstanceOf(Long.class).as(jsonResult).isEqualTo(0L);
    assertThat(result.get("value")).isInstanceOf(Map.class);
    assertThat(result.get("value"))
        .asInstanceOf(MAP)
        .hasSize(2)
        .containsEntry("status", 0L)
        .containsEntry("value", 3L);

    assertThat(eval(context, "_")).isEqualTo(1234);
    return null;
  });
}
 
Example #2
Source File: DownloadBehaviorJob.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Performs the download and calls the callback method.
 */
@Override
public void run() {
    final Scriptable scope = callback_.getParentScope();
    final WebRequest request = new WebRequest(url_);
    try {
        final WebResponse webResponse = client_.loadWebResponse(request);
        final String content = webResponse.getContentAsString();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Downloaded content: " + StringUtils.abbreviate(content, 512));
        }
        final Object[] args = new Object[] {content};
        final ContextFactory cf = ((JavaScriptEngine) client_.getJavaScriptEngine()).getContextFactory();
        cf.call(cx -> {
            callback_.call(cx, scope, scope, args);
            return null;
        });
    }
    catch (final IOException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Behavior #default#download: Cannot download " + url_, e);
        }
    }
}
 
Example #3
Source File: CompiledAtomsNotLeakingTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
/** https://github.com/SeleniumHQ/selenium-google-code-issue-archive/issues/1333 */
@Test
public void fragmentWillNotLeakVariablesToEnclosingScopes() {
  ContextFactory.getGlobal().call(context -> {
    eval(context, "(" + fragment + ")()", RESOURCE_PATH);
    assertThat(eval(context, "_")).isEqualTo(1234);

    eval(context, "(" + fragment + ").call(this)", RESOURCE_PATH);
    assertThat(eval(context, "_")).isEqualTo(1234);

    eval(context, "(" + fragment + ").apply(this,[])", RESOURCE_PATH);
    assertThat(eval(context, "_")).isEqualTo(1234);

    eval(context, "(" + fragment + ").call(null)", RESOURCE_PATH);
    assertThat(eval(context, "_")).isEqualTo(1234);

    eval(context, "(" + fragment + ").apply(null,[])", RESOURCE_PATH);
    assertThat(eval(context, "_")).isEqualTo(1234);

    eval(context, "(" + fragment + ").call({})", RESOURCE_PATH);
    assertThat(eval(context, "_")).isEqualTo(1234);
    return null;
  });
}
 
Example #4
Source File: MessagePort.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Posts a message.
 * @param message the object passed to the window
 * @param transfer an optional sequence of Transferable objects
 * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage">MDN documentation</a>
 */
@JsxFunction
public void postMessage(final String message, final Object transfer) {
    if (port1_ != null) {
        final Window w = getWindow();
        final URL currentURL = w.getWebWindow().getEnclosedPage().getUrl();
        final MessageEvent event = new MessageEvent();
        final String origin = currentURL.getProtocol() + "://" + currentURL.getHost() + ':' + currentURL.getPort();
        event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin, "", w, transfer);
        event.setParentScope(port1_);
        event.setPrototype(getPrototype(event.getClass()));

        final JavaScriptEngine jsEngine
            = (JavaScriptEngine) w.getWebWindow().getWebClient().getJavaScriptEngine();
        final PostponedAction action = new PostponedAction(w.getWebWindow().getEnclosedPage()) {
            @Override
            public void execute() throws Exception {
                final ContextFactory cf = jsEngine.getContextFactory();
                cf.call(cx -> port1_.dispatchEvent(event));
            }
        };
        jsEngine.addPostponedAction(action);
    }
}
 
Example #5
Source File: CompiledAtomsNotLeakingTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Before
public void prepareGlobalObject() {
  ContextFactory.getGlobal().call(context -> {
    global = context.initStandardObjects();
    global.defineProperty("_", 1234, ScriptableObject.EMPTY);
    assertThat(eval(context, "_")).isEqualTo(1234);

    // We're using the //javascript/webdriver/atoms:execute_script atom,
    // which assumes it is used in the context of a browser window, so make
    // sure the "window" free variable is defined and refers to the global
    // context.
    assertThat(eval(context, "this.window=this;")).isEqualTo(global);
    assertThat(eval(context, "this")).isEqualTo(global);
    assertThat(eval(context, "window")).isEqualTo(global);
    assertThat(eval(context, "this === window")).isEqualTo(true);

    return null;
  });
}
 
Example #6
Source File: DedicatedWorkerGlobalScope.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
void messagePosted(final Object message) {
    final MessageEvent event = new MessageEvent();
    event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin_, "",
                                owningWindow_, Undefined.instance);
    event.setParentScope(owningWindow_);
    event.setPrototype(owningWindow_.getPrototype(event.getClass()));

    final JavaScriptEngine jsEngine =
            (JavaScriptEngine) owningWindow_.getWebWindow().getWebClient().getJavaScriptEngine();
    final ContextAction<Object> action = new ContextAction<Object>() {
        @Override
        public Object run(final Context cx) {
            executeEvent(cx, event);
            return null;
        }
    };

    final ContextFactory cf = jsEngine.getContextFactory();

    final JavaScriptJob job = new WorkerJob(cf, action, "messagePosted: " + Context.toString(message));

    final HtmlPage page = (HtmlPage) owningWindow_.getDocument().getPage();
    owningWindow_.getWebWindow().getJobManager().addJob(job, page);
}
 
Example #7
Source File: DedicatedWorkerGlobalScope.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
void messagePosted(final Object message) {
    final MessageEvent event = new MessageEvent();
    event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin_, "", owningWindow_, null);
    event.setParentScope(owningWindow_);
    event.setPrototype(owningWindow_.getPrototype(event.getClass()));

    final JavaScriptEngine jsEngine =
            (JavaScriptEngine) owningWindow_.getWebWindow().getWebClient().getJavaScriptEngine();
    final ContextAction action = new ContextAction() {
        @Override
        public Object run(final Context cx) {
            return executeEvent(cx, event);
        }
    };

    final ContextFactory cf = jsEngine.getContextFactory();

    final JavaScriptJob job = new WorkerJob(cf, action, "messagePosted: " + Context.toString(message));

    final HtmlPage page = (HtmlPage) owningWindow_.getDocument().getPage();
    owningWindow_.getWebWindow().getJobManager().addJob(job, page);
}
 
Example #8
Source File: DownloadBehaviorJob.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Performs the download and calls the callback method.
 */
@Override
public void run() {
    final Scriptable scope = callback_.getParentScope();
    final WebRequest request = new WebRequest(url_);
    try {
        final WebResponse webResponse = client_.loadWebResponse(request);
        final String content = webResponse.getContentAsString();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Downloaded content: " + StringUtils.abbreviate(content, 512));
        }
        final Object[] args = new Object[] {content};
        final ContextAction action = new ContextAction() {
            @Override
            public Object run(final Context cx) {
                callback_.call(cx, scope, scope, args);
                return null;
            }
        };
        final ContextFactory cf = ((JavaScriptEngine) client_.getJavaScriptEngine()).getContextFactory();
        cf.call(action);
    }
    catch (final IOException e) {
        LOG.error("Behavior #default#download: Cannot download " + url_, e);
    }
}
 
Example #9
Source File: HtmlUnitRegExpProxy2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Test if the custom fix is needed or not. When this test fails, then it means that the problem is solved in
 * Rhino and that custom fix for String.match in {@link HtmlUnitRegExpProxy} is not needed anymore (and that
 * this test can be removed, or turned positive).
 * @throws Exception if the test fails
 */
@Test
public void matchFixNeeded() throws Exception {
    final WebClient client = getWebClient();
    final ContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();
    final Context cx = cf.enterContext();
    try {
        final ScriptableObject topScope = cx.initStandardObjects();
        cx.evaluateString(topScope, scriptTestMatch_, "test script String.match", 0, null);
        try {
            cx.evaluateString(topScope, scriptTestMatch_, "test script String.match", 0, null);
        }
        catch (final JavaScriptException e) {
            assertTrue(e.getMessage().indexOf("Expected >") == 0);
        }
    }
    finally {
        Context.exit();
    }
}
 
Example #10
Source File: HtmlUnitRegExpProxy2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Tests if custom patch is still needed.
 */
@Test
public void needCustomFix() {
    final WebClient client = getWebClient();
    final ContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();
    final Context ctx = cf.enterContext();
    try {
        final ScriptableObject topScope = ctx.initStandardObjects();
        topScope.put("str", topScope, str_);
        topScope.put("text", topScope, text_);
        topScope.put("expected", topScope, expected_);
        assertEquals(begin_ + end_, text_.replaceAll(str_, ""));
        try {
            ctx.evaluateString(topScope, src_, "test script", 0, null);
        }
        catch (final JavaScriptException e) {
            assertTrue(e.getMessage().indexOf("Expected >") == 0);
        }
    }
    finally {
        Context.exit();
    }
}
 
Example #11
Source File: DedicatedWorkerGlobalScope.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Posts a message to the {@link Worker} in the page's context.
 * @param message the message
 */
@JsxFunction
public void postMessage(final Object message) {
    final MessageEvent event = new MessageEvent();
    event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin_, "", owningWindow_, null);
    event.setParentScope(owningWindow_);
    event.setPrototype(owningWindow_.getPrototype(event.getClass()));

    if (LOG.isDebugEnabled()) {
        LOG.debug("[DedicatedWorker] postMessage: {}" + message);
    }
    final JavaScriptEngine jsEngine =
            (JavaScriptEngine) owningWindow_.getWebWindow().getWebClient().getJavaScriptEngine();
    final ContextAction action = new ContextAction() {
        @Override
        public Object run(final Context cx) {
            worker_.getEventListenersContainer().executeCapturingListeners(event, null);
            final Object[] args = new Object[] {event};
            return worker_.getEventListenersContainer().executeBubblingListeners(event, args, args);
        }
    };

    final ContextFactory cf = jsEngine.getContextFactory();

    final JavaScriptJob job = new WorkerJob(cf, action, "postMessage: " + Context.toString(message));

    final HtmlPage page = (HtmlPage) owningWindow_.getDocument().getPage();
    owningWindow_.getWebWindow().getJobManager().addJob(job, page);
}
 
Example #12
Source File: MessagePort.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Posts a message.
 * @param message the object passed to the window
 * @param transfer an optional sequence of Transferable objects
 * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage">MDN documentation</a>
 */
@JsxFunction
public void postMessage(final String message, final Object transfer) {
    if (port1_ != null) {
        final Window w = getWindow();
        final URL currentURL = w.getWebWindow().getEnclosedPage().getUrl();
        final MessageEvent event = new MessageEvent();
        final String origin = currentURL.getProtocol() + "://" + currentURL.getHost() + ':' + currentURL.getPort();
        event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin, "", w, transfer);
        event.setParentScope(port1_);
        event.setPrototype(getPrototype(event.getClass()));

        final JavaScriptEngine jsEngine
            = (JavaScriptEngine) w.getWebWindow().getWebClient().getJavaScriptEngine();
        final PostponedAction action = new PostponedAction(w.getWebWindow().getEnclosedPage()) {
            @Override
            public void execute() throws Exception {
                final ContextAction contextAction = new ContextAction() {
                    @Override
                    public Object run(final Context cx) {
                        return port1_.dispatchEvent(event);
                    }
                };

                final ContextFactory cf = jsEngine.getContextFactory();
                cf.call(contextAction);
            }
        };
        jsEngine.addPostponedAction(action);
    }
}
 
Example #13
Source File: DedicatedWorkerGlobalScope.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
void loadAndExecute(final String url, final Context context) throws IOException {
    final HtmlPage page = (HtmlPage) owningWindow_.getDocument().getPage();
    final URL fullUrl = page.getFullyQualifiedUrl(url);

    final WebClient webClient = owningWindow_.getWebWindow().getWebClient();

    final WebRequest webRequest = new WebRequest(fullUrl);
    final WebResponse response = webClient.loadWebResponse(webRequest);
    final String scriptCode = response.getContentAsString();
    final JavaScriptEngine javaScriptEngine = (JavaScriptEngine) webClient.getJavaScriptEngine();

    final DedicatedWorkerGlobalScope thisScope = this;
    final ContextAction action = new ContextAction() {
        @Override
        public Object run(final Context cx) {
            final Script script = javaScriptEngine.compile(page, thisScope, scriptCode,
                    fullUrl.toExternalForm(), 1);
            return javaScriptEngine.execute(page, thisScope, script);
        }
    };

    final ContextFactory cf = javaScriptEngine.getContextFactory();

    if (context != null) {
        action.run(context);
    }
    else {
        final JavaScriptJob job = new WorkerJob(cf, action, "loadAndExecute " + url);

        owningWindow_.getWebWindow().getJobManager().addJob(job, page);
    }
}
 
Example #14
Source File: JavaScriptEngineTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that we're not using a global context factory, so that we can cleanly run multiple
 * WebClient instances concurrently within a single JVM. See bug #689.
 */
@Test
public void noGlobalContextFactoryUsed() {
    final WebClient client1 = getWebClient();
    final WebClient client2 = createNewWebClient();

    final ContextFactory cf1 = ((JavaScriptEngine) client1.getJavaScriptEngine()).getContextFactory();
    final ContextFactory cf2 = ((JavaScriptEngine) client2.getJavaScriptEngine()).getContextFactory();

    assertFalse(cf1 == cf2);
    assertFalse(cf1 == ContextFactory.getGlobal());
    assertFalse(cf2 == ContextFactory.getGlobal());
}
 
Example #15
Source File: DomElement.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
 *
 * Fires the event on the element. Nothing is done if JavaScript is disabled.
 * @param event the event to fire
 * @return the execution result, or {@code null} if nothing is executed
 */
public ScriptResult fireEvent(final Event event) {
    final WebClient client = getPage().getWebClient();
    if (!client.getOptions().isJavaScriptEnabled()) {
        return null;
    }

    if (!handles(event)) {
        return null;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Firing " + event);
    }
    final EventTarget jsElt = (EventTarget) getScriptableObject();
    final ContextAction action = new ContextAction() {
        @Override
        public Object run(final Context cx) {
            return jsElt.fireEvent(event);
        }
    };

    final ContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();
    final ScriptResult result = (ScriptResult) cf.call(action);
    if (event.isAborted(result)) {
        preventDefault();
    }
    return result;
}
 
Example #16
Source File: DedicatedWorkerGlobalScope.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
void loadAndExecute(final WebClient webClient, final String url,
        final Context context, final boolean checkMimeType) throws IOException {
    final HtmlPage page = (HtmlPage) owningWindow_.getDocument().getPage();
    final URL fullUrl = page.getFullyQualifiedUrl(url);

    final WebRequest webRequest = new WebRequest(fullUrl);
    final WebResponse response = webClient.loadWebResponse(webRequest);
    if (checkMimeType && !MimeType.isJavascriptMimeType(response.getContentType())) {
        throw Context.reportRuntimeError(
                "NetworkError: importScripts response is not a javascript response");
    }

    final String scriptCode = response.getContentAsString();
    final JavaScriptEngine javaScriptEngine = (JavaScriptEngine) webClient.getJavaScriptEngine();

    final DedicatedWorkerGlobalScope thisScope = this;
    final ContextAction<Object> action = new ContextAction<Object>() {
        @Override
        public Object run(final Context cx) {
            final Script script = javaScriptEngine.compile(page, thisScope, scriptCode,
                    fullUrl.toExternalForm(), 1);
            return javaScriptEngine.execute(page, thisScope, script);
        }
    };

    final ContextFactory cf = javaScriptEngine.getContextFactory();

    if (context != null) {
        action.run(context);
    }
    else {
        final JavaScriptJob job = new WorkerJob(cf, action, "loadAndExecute " + url);

        owningWindow_.getWebWindow().getJobManager().addJob(job, page);
    }
}
 
Example #17
Source File: DedicatedWorkerGlobalScope.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Posts a message to the {@link Worker} in the page's context.
 * @param message the message
 */
@JsxFunction
public void postMessage(final Object message) {
    final MessageEvent event = new MessageEvent();
    event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin_, "",
                                owningWindow_, Undefined.instance);
    event.setParentScope(owningWindow_);
    event.setPrototype(owningWindow_.getPrototype(event.getClass()));

    if (LOG.isDebugEnabled()) {
        LOG.debug("[DedicatedWorker] postMessage: {}" + message);
    }
    final JavaScriptEngine jsEngine =
            (JavaScriptEngine) owningWindow_.getWebWindow().getWebClient().getJavaScriptEngine();
    final ContextAction<Object> action = new ContextAction<Object>() {
        @Override
        public Object run(final Context cx) {
            worker_.getEventListenersContainer().executeCapturingListeners(event, null);
            final Object[] args = {event};
            worker_.getEventListenersContainer().executeBubblingListeners(event, args);
            return null;
        }
    };

    final ContextFactory cf = jsEngine.getContextFactory();

    final JavaScriptJob job = new WorkerJob(cf, action, "postMessage: " + Context.toString(message));

    final HtmlPage page = (HtmlPage) owningWindow_.getDocument().getPage();
    owningWindow_.getWebWindow().getJobManager().addJob(job, page);
}
 
Example #18
Source File: DedicatedWorkerGlobalScope.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
WorkerJob(final ContextFactory contextFactory, final ContextAction action, final String description) {
    contextFactory_ = contextFactory;
    action_ = action;
    description_ = description;
}
 
Example #19
Source File: XMLHTTPRequest.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Sends an HTTP request to the server and receives a response.
 * @param body the body of the message being sent with the request.
 */
@JsxFunction
public void send(final Object body) {
    if (webRequest_ == null) {
        setState(STATE_DONE, Context.getCurrentContext());
        return;
    }
    if (sent_) {
        throw Context.reportRuntimeError("Unspecified error (request already sent).");
    }
    sent_ = true;

    prepareRequest(body);

    // quite strange but IE seems to fire state loading twice
    setState(STATE_OPENED, Context.getCurrentContext());

    final Window w = getWindow();
    final WebClient client = w.getWebWindow().getWebClient();
    final AjaxController ajaxController = client.getAjaxController();
    final HtmlPage page = (HtmlPage) w.getWebWindow().getEnclosedPage();
    final boolean synchron = ajaxController.processSynchron(page, webRequest_, async_);
    if (synchron) {
        doSend(Context.getCurrentContext());
    }
    else {
        // Create and start a thread in which to execute the request.
        final Scriptable startingScope = w;
        final ContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();
        final ContextAction action = new ContextAction() {
            @Override
            public Object run(final Context cx) {
                // KEY_STARTING_SCOPE maintains a stack of scopes
                @SuppressWarnings("unchecked")
                Stack<Scriptable> stack =
                        (Stack<Scriptable>) cx.getThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE);
                if (null == stack) {
                    stack = new Stack<>();
                    cx.putThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE, stack);
                }
                stack.push(startingScope);

                try {
                    doSend(cx);
                }
                finally {
                    stack.pop();
                }
                return null;
            }
        };
        final JavaScriptJob job = BackgroundJavaScriptFactory.theFactory().
                createJavascriptXMLHttpRequestJob(cf, action);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Starting XMLHTTPRequest thread for asynchronous request");
        }
        jobID_ = w.getWebWindow().getJobManager().addJob(job, page);
    }
}
 
Example #20
Source File: JavascriptXMLHttpRequestJob.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
JavascriptXMLHttpRequestJob(final ContextFactory contextFactory, final ContextAction action) {
    super();
    contextFactory_ = contextFactory;
    action_ = action;
}
 
Example #21
Source File: XMLHttpRequest.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Sends the specified content to the server in an HTTP request and receives the response.
 * @param content the body of the message being sent with the request
 */
@JsxFunction
public void send(final Object content) {
    if (webRequest_ == null) {
        return;
    }
    prepareRequest(content);

    final Window w = getWindow();
    final WebClient client = w.getWebWindow().getWebClient();
    final AjaxController ajaxController = client.getAjaxController();
    final HtmlPage page = (HtmlPage) w.getWebWindow().getEnclosedPage();
    final boolean synchron = ajaxController.processSynchron(page, webRequest_, async_);
    if (synchron) {
        doSend(Context.getCurrentContext());
    }
    else {
        if (getBrowserVersion().hasFeature(XHR_FIRE_STATE_OPENED_AGAIN_IN_ASYNC_MODE)) {
            // quite strange but IE seems to fire state loading twice
            // in async mode (at least with HTML of the unit tests)
            setState(OPENED, Context.getCurrentContext());
        }

        // Create and start a thread in which to execute the request.
        final Scriptable startingScope = w;
        final ContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();
        final ContextAction action = new ContextAction() {
            @Override
            public Object run(final Context cx) {
                // KEY_STARTING_SCOPE maintains a stack of scopes
                @SuppressWarnings("unchecked")
                Stack<Scriptable> stack =
                        (Stack<Scriptable>) cx.getThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE);
                if (null == stack) {
                    stack = new Stack<>();
                    cx.putThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE, stack);
                }
                stack.push(startingScope);

                try {
                    doSend(cx);
                }
                finally {
                    stack.pop();
                }
                return null;
            }

            @Override
            public String toString() {
                return "XMLHttpRequest " + webRequest_.getHttpMethod() + " '" + webRequest_.getUrl() + "'";
            }
        };
        final JavaScriptJob job = BackgroundJavaScriptFactory.theFactory().
                createJavascriptXMLHttpRequestJob(cf, action);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Starting XMLHttpRequest thread for asynchronous request");
        }
        jobID_ = w.getWebWindow().getJobManager().addJob(job, page);
    }
}
 
Example #22
Source File: HtmlUnitContextFactory.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
protected TimeoutContext(final ContextFactory factory) {
    super(factory);
}
 
Example #23
Source File: JavascriptXMLHttpRequestJob.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
JavascriptXMLHttpRequestJob(final ContextFactory contextFactory, final ContextAction<Object> action) {
    super();
    contextFactory_ = contextFactory;
    action_ = action;
}
 
Example #24
Source File: XMLHTTPRequest.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Sends an HTTP request to the server and receives a response.
 * @param body the body of the message being sent with the request.
 */
@JsxFunction
public void send(final Object body) {
    if (webRequest_ == null) {
        setState(STATE_DONE, Context.getCurrentContext());
        return;
    }
    if (sent_) {
        throw Context.reportRuntimeError("Unspecified error (request already sent).");
    }
    sent_ = true;

    prepareRequest(body);

    // quite strange but IE seems to fire state loading twice
    setState(STATE_OPENED, Context.getCurrentContext());

    final Window w = getWindow();
    final WebClient client = w.getWebWindow().getWebClient();
    final AjaxController ajaxController = client.getAjaxController();
    final HtmlPage page = (HtmlPage) w.getWebWindow().getEnclosedPage();
    final boolean synchron = ajaxController.processSynchron(page, webRequest_, async_);
    if (synchron) {
        doSend(Context.getCurrentContext());
    }
    else {
        // Create and start a thread in which to execute the request.
        final Scriptable startingScope = w;
        final ContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();
        final ContextAction<Object> action = new ContextAction<Object>() {
            @Override
            public Object run(final Context cx) {
                // KEY_STARTING_SCOPE maintains a stack of scopes
                @SuppressWarnings("unchecked")
                Deque<Scriptable> stack =
                        (Deque<Scriptable>) cx.getThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE);
                if (null == stack) {
                    stack = new ArrayDeque<>();
                    cx.putThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE, stack);
                }
                stack.push(startingScope);

                try {
                    doSend(cx);
                }
                finally {
                    stack.pop();
                }
                return null;
            }
        };
        final JavaScriptJob job = BackgroundJavaScriptFactory.theFactory().
                createJavascriptXMLHttpRequestJob(cf, action);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Starting XMLHTTPRequest thread for asynchronous request");
        }
        jobID_ = w.getWebWindow().getJobManager().addJob(job, page);
    }
}
 
Example #25
Source File: DedicatedWorkerGlobalScope.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
WorkerJob(final ContextFactory contextFactory, final ContextAction<Object> action, final String description) {
    contextFactory_ = contextFactory;
    action_ = action;
    description_ = description;
}
 
Example #26
Source File: XMLHttpRequest.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Sends the specified content to the server in an HTTP request and receives the response.
 * @param content the body of the message being sent with the request
 */
@JsxFunction
public void send(final Object content) {
    if (webRequest_ == null) {
        return;
    }
    prepareRequest(content);

    final Window w = getWindow();
    final WebWindow ww = w.getWebWindow();
    final WebClient client = ww.getWebClient();
    final AjaxController ajaxController = client.getAjaxController();
    final HtmlPage page = (HtmlPage) ww.getEnclosedPage();
    final boolean synchron = ajaxController.processSynchron(page, webRequest_, async_);
    if (synchron) {
        doSend(Context.getCurrentContext());
    }
    else {
        if (getBrowserVersion().hasFeature(XHR_FIRE_STATE_OPENED_AGAIN_IN_ASYNC_MODE)) {
            // quite strange but IE seems to fire state loading twice
            // in async mode (at least with HTML of the unit tests)
            setState(OPENED, Context.getCurrentContext());
        }

        // Create and start a thread in which to execute the request.
        final Scriptable startingScope = w;
        final ContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();
        final ContextAction<Object> action = new ContextAction<Object>() {
            @Override
            public Object run(final Context cx) {
                // KEY_STARTING_SCOPE maintains a stack of scopes
                @SuppressWarnings("unchecked")
                Deque<Scriptable> stack =
                        (Deque<Scriptable>) cx.getThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE);
                if (null == stack) {
                    stack = new ArrayDeque<>();
                    cx.putThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE, stack);
                }
                stack.push(startingScope);

                try {
                    doSend(cx);
                }
                finally {
                    stack.pop();
                }
                return null;
            }

            @Override
            public String toString() {
                return "XMLHttpRequest " + webRequest_.getHttpMethod() + " '" + webRequest_.getUrl() + "'";
            }
        };
        final JavaScriptJob job = BackgroundJavaScriptFactory.theFactory().
                createJavascriptXMLHttpRequestJob(cf, action);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Starting XMLHttpRequest thread for asynchronous request");
        }
        jobID_ = ww.getJobManager().addJob(job, page);
    }
}
 
Example #27
Source File: HtmlUnitContextFactory.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
protected TimeoutContext(final ContextFactory factory) {
    super(factory);
}
 
Example #28
Source File: BackgroundJavaScriptFactory.java    From HtmlUnit-Android with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new job for XMLHttpRequestProcessing.
 * @param contextFactory the ContextFactory
 * @param action the action
 *
 * @return JavaScriptJob the created job
 */
public JavaScriptJob createJavascriptXMLHttpRequestJob(final ContextFactory contextFactory,
        final ContextAction action) {
    return new JavascriptXMLHttpRequestJob(contextFactory, action);
}
 
Example #29
Source File: BackgroundJavaScriptFactory.java    From htmlunit with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new job for XMLHttpRequestProcessing.
 * @param contextFactory the ContextFactory
 * @param action the action
 *
 * @return JavaScriptJob the created job
 */
public JavaScriptJob createJavascriptXMLHttpRequestJob(final ContextFactory contextFactory,
        final ContextAction<Object> action) {
    return new JavascriptXMLHttpRequestJob(contextFactory, action);
}