Java源码示例:net.sourceforge.htmlunit.corejs.javascript.Scriptable
示例1
/**
* Inserts a set of Node or DOMString objects in the children list of this ChildNode's parent,
* just after this ChildNode.
* @param context the context
* @param thisObj this object
* @param args the arguments
* @param function the function
*/
protected static void after(final Context context, final Scriptable thisObj, final Object[] args,
final Function function) {
final DomNode thisDomNode = ((Node) thisObj).getDomNodeOrDie();
final DomNode parentNode = thisDomNode.getParentNode();
final DomNode nextSibling = thisDomNode.getNextSibling();
for (Object arg : args) {
final Node node = toNodeOrTextNode((Node) thisObj, arg);
final DomNode newNode = node.getDomNodeOrDie();
if (nextSibling != null) {
nextSibling.insertBefore(newNode);
}
else {
parentNode.appendChild(newNode);
}
}
}
示例2
/**
* Converts a date to a string, returning the "date" portion using the operating system's locale's conventions.
* @param context the JavaScript context
* @param thisObj the scriptable
* @param args the arguments passed into the method
* @param function the function
* @return converted string
*/
public static String toLocaleDateString(
final Context context, final Scriptable thisObj, final Object[] args, final Function function) {
final String formatString;
final BrowserVersion browserVersion = ((Window) thisObj.getParentScope()).getBrowserVersion();
if (browserVersion.hasFeature(JS_DATE_WITH_LEFT_TO_RIGHT_MARK)) {
// [U+200E] -> Unicode Character 'LEFT-TO-RIGHT MARK'
formatString = "\u200EM\u200E/\u200Ed\u200E/\u200Eyyyy";
}
else if (browserVersion.hasFeature(JS_DATE_LOCALE_DATE_SHORT)) {
formatString = "M/d/yyyy";
}
else {
formatString = "EEEE, MMMM dd, yyyy";
}
final FastDateFormat format = FastDateFormat.getInstance(formatString, getLocale(browserVersion));
return format.format(getDateValue(thisObj));
}
示例3
/**
* Invokes the onerror handler if one has been set.
* @param context the context within which the onerror handler is to be invoked;
* if {@code null}, the current thread's context is used.
*/
private void processError(Context context) {
final Function onError = getOnerror();
if (onError != null) {
final Scriptable scope = onError.getParentScope();
final JavaScriptEngine jsEngine = (JavaScriptEngine) containingPage_.getWebClient().getJavaScriptEngine();
final Object[] params = {new ProgressEvent(this, Event.TYPE_ERROR)};
if (LOG.isDebugEnabled()) {
LOG.debug("Calling onerror handler");
}
jsEngine.callFunction(containingPage_, onError, this, scope, params);
if (LOG.isDebugEnabled()) {
if (context == null) {
context = Context.getCurrentContext();
}
LOG.debug("onerror handler: " + context.decompileFunction(onError, 4));
LOG.debug("Calling onerror handler done.");
}
}
}
示例4
/**
* Adds an event listener.
*
* @param type the event type to listen for (like "load")
* @param listener the event listener
* @param useCapture If {@code true}, indicates that the user wishes to initiate capture (not yet implemented)
* @return {@code true} if the listener has been added
*/
public boolean addEventListener(final String type, final Scriptable listener, final boolean useCapture) {
if (null == listener) {
return true;
}
final TypeContainer container = getTypeContainer(type);
final boolean added = container.addListener(listener, useCapture);
if (!added) {
if (LOG.isDebugEnabled()) {
LOG.debug(type + " listener already registered, skipping it (" + listener + ")");
}
return false;
}
return true;
}
示例5
/**
* Returns the object at the specified index.
*
* @param index the index
* @param start the object that get is being called on
* @return the object or NOT_FOUND
*/
@Override
public Object get(final int index, final Scriptable start) {
if (htmlSelect_ == null || index < 0) {
return Undefined.instance;
}
if (index >= htmlSelect_.getOptionSize()) {
if (getBrowserVersion().hasFeature(JS_SELECT_OPTIONS_NULL_FOR_OUTSIDE)) {
return null;
}
return Undefined.instance;
}
return getScriptableFor(htmlSelect_.getOption(index));
}
示例6
/**
* Converts a date to a string, returning the "date" portion using the operating system's locale's conventions.
* @param context the JavaScript context
* @param thisObj the scriptable
* @param args the arguments passed into the method
* @param function the function
* @return converted string
*/
public static String toLocaleDateString(
final Context context, final Scriptable thisObj, final Object[] args, final Function function) {
final String formatString;
final BrowserVersion browserVersion = ((Window) thisObj.getParentScope()).getBrowserVersion();
if (browserVersion.hasFeature(JS_DATE_WITH_LEFT_TO_RIGHT_MARK)) {
// [U+200E] -> Unicode Character 'LEFT-TO-RIGHT MARK'
formatString = "\u200EM\u200E/\u200Ed\u200E/\u200Eyyyy";
}
else if (browserVersion.hasFeature(JS_DATE_LOCALE_DATE_SHORT)) {
formatString = "M/d/yyyy";
}
else {
formatString = "EEEE, MMMM dd, yyyy";
}
final FastDateFormat format = FastDateFormat.getInstance(formatString, getLocale(browserVersion));
return format.format(getDateValue(thisObj));
}
示例7
/**
* Sets the state as specified and invokes the state change handler if one has been set.
* @param state the new state
* @param context the context within which the state change handler is to be invoked;
* if {@code null}, the current thread's context is used
*/
private void setState(final int state, Context context) {
state_ = state;
if (stateChangeHandler_ != null && !openedMultipleTimes_) {
final Scriptable scope = stateChangeHandler_.getParentScope();
final JavaScriptEngine jsEngine = (JavaScriptEngine) containingPage_.getWebClient().getJavaScriptEngine();
if (LOG.isDebugEnabled()) {
LOG.debug("Calling onreadystatechange handler for state " + state);
}
final Object[] params = ArrayUtils.EMPTY_OBJECT_ARRAY;
jsEngine.callFunction(containingPage_, stateChangeHandler_, scope, this, params);
if (LOG.isDebugEnabled()) {
if (context == null) {
context = Context.getCurrentContext();
}
LOG.debug("onreadystatechange handler: " + context.decompileFunction(stateChangeHandler_, 4));
LOG.debug("Calling onreadystatechange handler for state " + state + ". Done.");
}
}
}
示例8
/**
* JavaScript constructor.
* @param cx the current context
* @param args the arguments to the WebSocket constructor
* @param ctorObj the function object
* @param inNewExpr Is new or not
* @return the java object to allow JavaScript to access
*/
@JsxConstructor
public static Scriptable jsConstructor(final Context cx, final Object[] args, final Function ctorObj,
final boolean inNewExpr) {
final String[] locales;
if (args.length != 0) {
if (args[0] instanceof NativeArray) {
final NativeArray array = (NativeArray) args[0];
locales = new String[(int) array.getLength()];
for (int i = 0; i < locales.length; i++) {
locales[i] = Context.toString(array.get(i));
}
}
else {
locales = new String[] {Context.toString(args[0])};
}
}
else {
locales = new String[] {""};
}
final Window window = getWindow(ctorObj);
final DateTimeFormat format = new DateTimeFormat(locales, window.getBrowserVersion());
format.setParentScope(window);
format.setPrototype(window.getPrototype(format.getClass()));
return format;
}
示例9
/**
* Evaluates the <tt>FindProxyForURL</tt> method of the specified content.
* @param content the JavaScript content
* @param url the URL to be retrieved
* @return semicolon-separated result
*/
public static String evaluate(final String content, final URL url) {
final Context cx = Context.enter();
try {
final ProxyAutoConfig config = new ProxyAutoConfig();
final Scriptable scope = cx.initSafeStandardObjects();
config.defineMethod("isPlainHostName", scope);
config.defineMethod("dnsDomainIs", scope);
config.defineMethod("localHostOrDomainIs", scope);
config.defineMethod("isResolvable", scope);
config.defineMethod("isInNet", scope);
config.defineMethod("dnsResolve", scope);
config.defineMethod("myIpAddress", scope);
config.defineMethod("dnsDomainLevels", scope);
config.defineMethod("shExpMatch", scope);
config.defineMethod("weekdayRange", scope);
config.defineMethod("dateRange", scope);
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);
final NativeFunction f = (NativeFunction) fObj;
final Object result = f.call(cx, scope, scope, functionArgs);
return Context.toString(result);
}
finally {
Context.exit();
}
}
示例10
/**
* Gets the prototype object for the given host class.
* @param javaScriptClass the host class
* @return the prototype
*/
@Override
@SuppressWarnings("unchecked")
public Scriptable getPrototype(final Class<? extends SimpleScriptable> javaScriptClass) {
final Scriptable prototype = getEnvironment().getPrototype(javaScriptClass);
if (prototype == null && javaScriptClass != SimpleScriptable.class) {
return getPrototype((Class<? extends SimpleScriptable>) javaScriptClass.getSuperclass());
}
return prototype;
}
示例11
/**
* {@inheritDoc}
*/
@Override
public Object get(final String name, Scriptable start) {
if (start instanceof SimpleScriptableProxy<?>) {
start = ((SimpleScriptableProxy<?>) start).getDelegee();
}
return getDelegee().get(name, start);
}
示例12
/**
* {@inheritDoc}
*/
@Override
public void put(final String name, Scriptable start, final Object value) {
if (start instanceof SimpleScriptableProxy<?>) {
start = ((SimpleScriptableProxy<?>) start).getDelegee();
}
getDelegee().put(name, start, value);
}
示例13
/**
* {@inheritDoc}
*/
@Override
public Object get(final int index, final Scriptable start) {
final Object value = item(index);
if (value == null && !getBrowserVersion().hasFeature(JS_DOMTOKENLIST_GET_NULL_IF_OUTSIDE)) {
return Undefined.instance;
}
return value;
}
示例14
/**
* {@inheritDoc}
*/
@Override
public void put(final String name, Scriptable start, final Object value) {
if (start instanceof SimpleScriptableProxy<?>) {
start = ((SimpleScriptableProxy<?>) start).getDelegee();
}
getDelegee().put(name, start, value);
}
示例15
/** {@inheritDoc} */
@Override
protected void runJavaScript(final HtmlPage page) {
final DomElement doc = page.getDocumentElement();
final Scriptable scriptable = page.getEnclosingWindow().getScriptableObject();
page.executeJavaScriptFunction(function_, scriptable, args_, doc);
}
示例16
/**
* {@inheritDoc}
*/
@Override
public Object call(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args) {
if (supportsParentheses()) {
return super.call(cx, scope, thisObj, args);
}
throw Context.reportRuntimeError("TypeError - HTMLCollection does nont support function like access");
}
示例17
/**
* {@inheritDoc}
*/
@Override
public Object get(final String name, final Scriptable start) {
Object response = super.get(name, start);
if (response != NOT_FOUND) {
return response;
}
response = getNamedItem(name);
if (response != null) {
return response;
}
return NOT_FOUND;
}
示例18
/**
* Returns {@code true} if the attribute is a custom property.
* @return {@code true} if the attribute is a custom property
*/
@JsxGetter(IE)
public boolean isExpando() {
final Object owner = getOwnerElement();
if (null == owner) {
return false;
}
return !ScriptableObject.hasProperty((Scriptable) owner, getName());
}
示例19
/**
* {@inheritDoc}
*/
@Override
public Object call(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args) {
final String s = (String) super.call(cx, scope, thisObj, args);
if (thisObj instanceof BaseFunction && s.indexOf("[native code]") > -1) {
final String functionName = ((BaseFunction) thisObj).getFunctionName();
return "\nfunction " + functionName + "() {\n [native code]\n}\n";
}
return s;
}
示例20
/**
* {@inheritDoc}
*/
@Override
public void put(final String name, final Scriptable start, final Object value) {
final boolean isReserved = RESERVED_NAMES_.contains(name);
if (store_ == null || isReserved) {
super.put(name, start, value);
}
if (store_ != null && (!isReserved || getBrowserVersion().hasFeature(JS_STORAGE_PRESERVED_INCLUDED))) {
setItem(name, Context.toString(value));
}
}
示例21
/**
* {@inheritDoc}
*/
@Override
public Object call(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args) {
final String s = (String) super.call(cx, scope, thisObj, args);
if (thisObj instanceof BaseFunction && s.indexOf("[native code]") > -1) {
final String functionName = ((BaseFunction) thisObj).getFunctionName();
return "function " + functionName + "() { [native code] }";
}
return s;
}
示例22
@Override
public boolean has(final int index, final Scriptable start) {
final Object found = get(index, start);
if (!Undefined.isUndefined(found) && Scriptable.NOT_FOUND != found) {
return true;
}
return super.has(index, start);
}
示例23
/**
* {@inheritDoc}
*/
@Override
protected Object fromArray(final byte[] array, final int offset) {
if (offset < 0 || offset >= array.length) {
return Scriptable.NOT_FOUND;
}
final ByteBuffer buff = ByteBuffer.wrap(array);
buff.order(ByteOrder.LITTLE_ENDIAN);
return buff.getShort(offset) & 0xFFFF;
}
示例24
/**
* {@inheritDoc}
*/
@Override
public Object get(final String name, Scriptable start) {
if (start instanceof SimpleScriptableProxy<?>) {
start = ((SimpleScriptableProxy<?>) start).getDelegee();
}
return getDelegee().get(name, start);
}
示例25
/**
* {@inheritDoc}
*/
@Override
public Object get(final int index, Scriptable start) {
if (start instanceof SimpleScriptableProxy<?>) {
start = ((SimpleScriptableProxy<?>) start).getDelegee();
}
return getDelegee().get(index, start);
}
示例26
/**
* {@inheritDoc}
*/
@Override
public Script compile(final HtmlPage page, final String sourceCode,
final String sourceName, final int startLine) {
final Scriptable scope = getScope(page, null);
return compile(page, scope, sourceCode, sourceName, startLine);
}
示例27
/**
* {@inheritDoc}
*/
@Override
public void setParentScope(final Scriptable m) {
super.setParentScope(m);
if (files_ != null) {
for (final File file : files_) {
file.setParentScope(m);
file.setPrototype(getPrototype(file.getClass()));
}
}
}
示例28
/**
* {@inheritDoc}
*/
@Override
protected Object doTopCall(final Callable callable,
final Context cx, final Scriptable scope,
final Scriptable thisObj, final Object[] args) {
final TimeoutContext tcx = (TimeoutContext) cx;
tcx.startClock();
return super.doTopCall(callable, cx, scope, thisObj, args);
}
示例29
/**
* Converts JavaScript arguments to Java arguments.
* @param context the current context
* @param scope the current scope
* @param jsArgs the JavaScript arguments
* @return the java arguments
*/
Object[] convertJSArgsToJavaArgs(final Context context, final Scriptable scope, final Object[] jsArgs) {
if (jsArgs.length != jsTypeTags_.length) {
throw Context.reportRuntimeError("Bad number of parameters for function " + method_.getName()
+ ": expected " + jsTypeTags_.length + " got " + jsArgs.length);
}
final Object[] javaArgs = new Object[jsArgs.length];
int i = 0;
for (final Object object : jsArgs) {
javaArgs[i] = FunctionObject.convertArg(context, scope, object, jsTypeTags_[i++]);
}
return javaArgs;
}
示例30
/**
* {@inheritDoc}
*/
@Override
public Object get(String name, final Scriptable start) {
for (final String property : ALL_PROPERTIES_) {
if (property.equalsIgnoreCase(name)) {
name = property;
break;
}
}
return super.get(name, start);
}