/** * @param name the name of the field to check * @return the first value found for the give name */ @JsxFunction({CHROME, FF}) public Scriptable getAll(final String name) { if (StringUtils.isEmpty(name)) { return Context.getCurrentContext().newArray(this, 0); } final List<Object> values = new ArrayList<>(); final Iterator<NameValuePair> iter = requestParameters_.iterator(); while (iter.hasNext()) { final NameValuePair pair = iter.next(); if (name.equals(pair.getName())) { values.add(pair.getValue()); } } final Object[] stringValues = values.toArray(new Object[values.size()]); return Context.getCurrentContext().newArray(this, stringValues); }
public static Object deserialize(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws IOException, ClassNotFoundException { if (args.length < 1) { throw Context.reportRuntimeError( "Expected a filename to read the serialization from"); } String filename = Context.toString(args[0]); FileInputStream fis = new FileInputStream(filename); Scriptable scope = ScriptableObject.getTopLevelScope(thisObj); ObjectInputStream in = new ScriptableInputStream(fis, scope); Object deserialized = in.readObject(); in.close(); return Context.toObject(deserialized, scope); }
@Override public Object run(final Context cx) { cx.setOptimizationLevel(-1); final Script script = cx.compileString(scriptSource, scriptName, 0, null); return cx.decompileScript(script, 4); } };
/** * Called when the event being fired ends. */ @SuppressWarnings("unchecked") public void endFire() { ((LinkedList<Event>) Context.getCurrentContext().getThreadLocal(KEY_CURRENT_EVENT)).removeLast(); }
/** * Called when the event starts being fired */ @SuppressWarnings("unchecked") void startFire() { LinkedList<Event> events = (LinkedList<Event>) Context.getCurrentContext().getThreadLocal(KEY_CURRENT_EVENT); if (events == null) { events = new LinkedList<Event>(); Context.getCurrentContext().putThreadLocal(KEY_CURRENT_EVENT, events); } events.add(this); }
getDomNodeOrDie().setAttribute("classid", classid); if (classid.indexOf(':') != -1 && getBrowserVersion().hasFeature(HTML_OBJECT_CLASSID)) { final WebClient webClient = getWindow().getWebWindow().getWebClient(); final Map<String, String> map = webClient.getActiveXObjectMap(); if (map != null) { final String xClassString = map.get(classid); final Object object = xClass.newInstance(); boolean contextCreated = false; if (Context.getCurrentContext() == null) { new HtmlUnitContextFactory(webClient).enterContext(); contextCreated = true; wrappedActiveX_ = Context.toObject(object, getParentScope()); if (contextCreated) { Context.exit(); throw Context.reportRuntimeError("ActiveXObject Error: failed instantiating class " + xClassString + " because " + e.getMessage() + "."); if (webClient.getOptions().isActiveXNative() && System.getProperty("os.name").contains("Windows")) { try { wrappedActiveX_ = new ActiveXObjectImpl(classid); wrappedActiveX_.setParentScope(getParentScope()); Context.throwAsScriptRuntimeEx(e);
/** * Implementation of the IE behavior #default#download. * @param uri the URI of the download source * @param callback the method which should be called when the download is finished * @see <a href="http://msdn.microsoft.com/en-us/library/ms531406.aspx">MSDN documentation</a> * @throws MalformedURLException if the URL cannot be created */ public void startDownload(final String uri, final Function callback) throws MalformedURLException { final HtmlPage page = (HtmlPage) getWindow().getWebWindow().getEnclosedPage(); final URL url = page.getFullyQualifiedUrl(uri); if (!page.getWebResponse().getRequestSettings().getUrl().getHost().equals(url.getHost())) { throw Context.reportRuntimeError("Not authorized url: " + url); } final JavaScriptJob job = new DownloadBehaviorJob(url, callback); page.getEnclosingWindow().getJobManager().addJob(job, page); }
/** * Implementation of the IE behavior #default#download. * @param uri the URI of the download source * @param callback the method which should be called when the download is finished * @see <a href="http://msdn.microsoft.com/en-us/library/ms531406.aspx">MSDN documentation</a> * @throws MalformedURLException if the URL cannot be created */ public void startDownload(final String uri, final Function callback) throws MalformedURLException { final WebWindow ww = getWindow().getWebWindow(); final HtmlPage page = (HtmlPage) ww.getEnclosedPage(); final URL url = page.getFullyQualifiedUrl(uri); if (!page.getUrl().getHost().equals(url.getHost())) { throw Context.reportRuntimeError("Not authorized url: " + url); } final JavaScriptJob job = BackgroundJavaScriptFactory.theFactory(). createDownloadBehaviorJob(url, callback, ww.getWebClient()); page.getEnclosingWindow().getJobManager().addJob(job, page); }
final boolean inNewExpr) { if (args.length < 1 || args.length > 2) { throw Context.reportRuntimeError( "ActiveXObject Error: constructor must have one or two String parameters."); if (args[0] == Context.getUndefinedValue()) { throw Context.reportRuntimeError("ActiveXObject Error: constructor parameter is undefined."); throw Context.reportRuntimeError("ActiveXObject Error: constructor parameter must be a String."); final WebClient webClient = getWindow(ctorObj).getWebWindow().getWebClient(); final Map<String, String> map = webClient.getActiveXObjectMap(); if (map != null) { final Object mapValue = map.get(activeXName); throw Context.reportRuntimeError("ActiveXObject Error: failed instantiating class " + xClassString + " because " + e.getMessage() + "."); return Context.toObject(object, ctorObj); if (webClient.isActiveXNative() && System.getProperty("os.name").contains("Windows")) { try { return new ActiveXObjectImpl(activeXName); throw Context.throwAsScriptRuntimeEx(new Exception("Automation server can't create object"));
final boolean inNewExpr) { if (args.length < 1 || args.length > 2) { throw Context.reportRuntimeError( "ActiveXObject Error: constructor must have one or two String parameters."); throw Context.reportRuntimeError("ActiveXObject Error: constructor parameter is undefined."); throw Context.reportRuntimeError("ActiveXObject Error: constructor parameter must be a String."); final MSXMLActiveXObjectFactory factory = window.getWebClient().getMSXMLActiveXObjectFactory(); if (factory.supports(activeXName)) { final Scriptable scriptable = factory.create(activeXName, window); final Class<?> xClass = Class.forName(xClassString); final Object object = xClass.newInstance(); return Context.toObject(object, ctorObj); throw Context.reportRuntimeError("ActiveXObject Error: failed instantiating class " + xClassString + " because " + e.getMessage() + "."); if (webClient.getOptions().isActiveXNative() && System.getProperty("os.name").contains("Windows")) { try { return new ActiveXObjectImpl(activeXName); throw Context.reportRuntimeError("Automation server can't create object for '" + activeXName + "'.");
private boolean isRecursiveAttribute(final String name) { for (Scriptable object = getDomNodeOrDie().getScriptObject(); object != null; object = object.getPrototype()) { for (final Object id : object.getIds()) { if (name.equals(Context.toString(id))) { return true; } } } return false; }
/** * Pushes a state. * @param object the state object * @param title the title * @param url an optional URL */ @JsxFunction public void pushState(final Object object, final String title, final String url) { final WebWindow w = getWindow().getWebWindow(); try { URL newStateUrl = null; final HtmlPage page = (HtmlPage) w.getEnclosedPage(); if (StringUtils.isNotBlank(url)) { newStateUrl = page.getFullyQualifiedUrl(url); } w.getHistory().pushState(object, newStateUrl); } catch (final IOException e) { Context.throwAsScriptRuntimeEx(e); } }
/** * Returns the current document instance, using <tt>thisObj</tt> as a hint. * @param thisObj a hint as to the current document (may be the prototype when function is used without "this") * @return the current document instance */ private static HTMLDocument getDocument(final Scriptable thisObj) { // if function is used "detached", then thisObj is the top scope (ie Window), not the real object // cf unit test DocumentTest#testDocumentWrite_AssignedToVar // may be the prototype too // cf DocumentTest#testDocumentWrite_AssignedToVar2 if (thisObj instanceof HTMLDocument && thisObj.getPrototype() instanceof HTMLDocument) { return (HTMLDocument) thisObj; } final Window window = getWindow(thisObj); final BrowserVersion browser = window.getWebWindow().getWebClient().getBrowserVersion(); if (browser.isIE()) { return window.jsxGet_document(); } throw Context.reportRuntimeError("Function can't be used detached from document"); }
final Context cx = Context.enter(); try { final ProxyAutoConfig config = new ProxyAutoConfig(); final Scriptable scope = cx.initStandardObjects(); config.defineMethod("timeRange", scope); cx.evaluateString(scope, "var ProxyConfig = function() {}; ProxyConfig.bindings = {}", "<init>", 1, null); cx.evaluateString(scope, content, "<Proxy Auto-Config>", 1, null); final Object[] functionArgs = {url.toExternalForm(), url.getHost()}; final Object fObj = scope.get("FindProxyForURL", scope); return Context.toString(result); Context.exit();
/** * Sets the "classid" attribute. * @param classid the "classid" attribute */ public void jsxSet_classid(final String classid) { getDomNodeOrDie().setAttribute("classid", classid); if (classid.indexOf(':') != -1 && getBrowserVersion().isIE() && getWindow().getWebWindow().getWebClient().isActiveXNative() && System.getProperty("os.name").contains("Windows")) { try { wrappedActiveX_ = new ActiveXObjectImpl(classid); wrappedActiveX_.setParentScope(getParentScope()); } catch (final Exception e) { Context.throwAsScriptRuntimeEx(e); } } }
/** * The JavaScript function "alert()". * @param message the message */ public void jsxFunction_alert(final Object message) { // use Object as parameter and perform String conversion by ourself // this allows to place breakpoint here and "see" the message object and its properties final String stringMessage = Context.toString(message); final AlertHandler handler = getWebWindow().getWebClient().getAlertHandler(); if (handler == null) { LOG.warn("window.alert(\"" + stringMessage + "\") no alert handler installed"); } else { handler.handleAlert(document_.getHtmlPage(), stringMessage); } }
/** * Triggers the {@code onerror} handler, if one has been set. * @param e the error that needs to be reported */ public void triggerOnError(final ScriptException e) { final Object o = getOnerror(); if (o instanceof Function) { final Function f = (Function) o; String msg = e.getMessage(); final String url = e.getPage().getUrl().toExternalForm(); final int line = e.getFailingLineNumber(); final int column = e.getFailingColumnNumber(); Object jsError = e.getMessage(); if (e.getCause() instanceof JavaScriptException) { msg = "uncaught exception: " + e.getCause().getMessage(); jsError = ((JavaScriptException) e.getCause()).getValue(); } else if (e.getCause() instanceof EcmaError) { msg = "uncaught " + e.getCause().getMessage(); final EcmaError ecmaError = (EcmaError) e.getCause(); final Scriptable err = Context.getCurrentContext().newObject(this, "Error"); ScriptableObject.putProperty(err, "message", ecmaError.getMessage()); ScriptableObject.putProperty(err, "fileName", ecmaError.sourceName()); ScriptableObject.putProperty(err, "lineNumber", Integer.valueOf(ecmaError.lineNumber())); jsError = err; } final Object[] args = new Object[] {msg, url, Integer.valueOf(line), Integer.valueOf(column), jsError}; f.call(Context.getCurrentContext(), this, this, args); } }
/** * Sets the value of the <tt>clear</tt> property. * @param clear the value of the <tt>clear</tt> property */ public void jsxSet_clear(final String clear) { if (!contains(VALID_CLEAR_VALUES, clear) && getBrowserVersion().isIE()) { Context.throwAsScriptRuntimeEx(new Exception("Invalid clear property value: '" + clear + "'.")); } getDomNodeOrDie().setAttribute("clear", clear); }
/** * JavaScript function "back". */ public void jsxFunction_back() { final WebWindow w = getWindow().getWebWindow(); try { w.getHistory().back(); } catch (final IOException e) { Context.throwAsScriptRuntimeEx(e); } }