private Ref xmlPrimaryReference(Context cx, XMLName xmlName, Scriptable scope) { XMLObjectImpl xmlObj; XMLObjectImpl firstXml = null; for (; ; ) { // XML object can only present on scope chain as a wrapper // of XMLWithScope if (scope instanceof XMLWithScope) { xmlObj = (XMLObjectImpl) scope.getPrototype(); if (xmlObj.hasXMLProperty(xmlName)) { break; } if (firstXml == null) { firstXml = xmlObj; } } scope = scope.getParentScope(); if (scope == null) { xmlObj = firstXml; break; } } // xmlObj == null corresponds to undefined as the target of // the reference if (xmlObj != null) { xmlName.initXMLObject(xmlObj); } return xmlName; }
public static void finishInit( Scriptable scope, FunctionObject constructor, Scriptable prototype) { // Create and make these properties in the prototype visible Context cx = Context.getCurrentContext(); Scriptable jars = cx.newArray(prototype, 0); jars.put(0, jars, cx.newArray(jars, 0)); defineProperty(prototype, "params", cx.newArray(prototype, 0), ScriptableObject.PERMANENT); defineProperty(prototype, "auth", cx.newArray(prototype, 0), ScriptableObject.PERMANENT); defineProperty(prototype, "jars", jars, ScriptableObject.PERMANENT); defineProperty(prototype, "headers", cx.newArray(prototype, 0), ScriptableObject.PERMANENT); }
/** * Take an object from the scripting layer and convert it to an int. * * @param obj * @return int */ private int toInt(Object obj) { int result = 0; if (obj instanceof String) { result = Integer.parseInt((String) obj); } else if (obj instanceof Number) { result = ((Number) obj).intValue(); } else if (obj instanceof Scriptable) { Scriptable sobj = (Scriptable) obj; if (sobj.getClassName().equals("Number")) { result = (int) ScriptRuntime.toNumber(sobj); } } return result; }
/** * Define this function as a JavaScript constructor. * * <p>Sets up the "prototype" and "constructor" properties. Also calls setParent and setPrototype * with appropriate values. Then adds the function object as a property of the given scope, using * <code>prototype.getClassName()</code> as the name of the property. * * @param scope the scope in which to define the constructor (typically the global object) * @param prototype the prototype object * @see gov.nbcs.rp.common.js.javascript.Scriptable#setParentScope * @see gov.nbcs.rp.common.js.javascript.Scriptable#setPrototype * @see gov.nbcs.rp.common.js.javascript.Scriptable#getClassName */ public void addAsConstructor(Scriptable scope, Scriptable prototype) { ScriptRuntime.setFunctionProtoAndParent(this, scope); setImmunePrototypeProperty(prototype); prototype.setParentScope(this); final int attr = ScriptableObject.DONTENUM | ScriptableObject.PERMANENT | ScriptableObject.READONLY; defineProperty(prototype, "constructor", this, attr); String name = prototype.getClassName(); defineProperty(scope, name, this, ScriptableObject.DONTENUM); setParentScope(scope); }
/** * Return new {@link Scriptable} instance using the default constructor for the class of the * underlying Java method. Return null to indicate that the call method should be used to create * new objects. */ public Scriptable createObject(Context cx, Scriptable scope) { if (member.isCtor() || (parmsLength == VARARGS_CTOR)) { return null; } Scriptable result; try { result = (Scriptable) member.getDeclaringClass().newInstance(); } catch (Exception ex) { throw Context.throwAsScriptRuntimeEx(ex); } result.setPrototype(getClassPrototype()); result.setParentScope(getParentScope()); return result; }
@Override public void put(String name, Scriptable start, Object value) { int info = findInstanceIdInfo(name); if (info != 0) { if (start == this && isSealed()) { throw Context.reportRuntimeError1("msg.modify.sealed", name); } int attr = (info >>> 16); if ((attr & READONLY) == 0) { if (start == this) { int id = (info & 0xFFFF); setInstanceIdValue(id, value); } else { start.put(name, start, value); } } return; } if (prototypeValues != null) { int id = prototypeValues.findId(name); if (id != 0) { if (start == this && isSealed()) { throw Context.reportRuntimeError1("msg.modify.sealed", name); } prototypeValues.set(id, start, value); return; } } super.put(name, start, value); }
public static Object eval(String source, Map<String, Scriptable> bindings) { Context cx = ContextFactory.getGlobal().enterContext(); try { Scriptable scope = cx.initStandardObjects(); if (bindings != null) { for (String id : bindings.keySet()) { Scriptable object = bindings.get(id); object.setParentScope(scope); scope.put(id, scope, object); } } return cx.evaluateString(scope, source, "source", 1, null); } finally { Context.exit(); } }
/** TODO should we stop traversing prototype chain when checking getting property "prototype"? */ @Override public PropertyDescriptor getProperty(String propertyName) { PropertyDescriptor prop = getOwnProperty(propertyName); if (prop != null) { return prop; } Scriptable proto = getPrototype(); if (proto != null) { return proto.getProperty(propertyName); } return null; }
public void exec(Scriptable xdcO, Session ses) { this.xdcO = xdcO; this.ses = ses; om = (Value.Obj) xdcO.get("om", null); Object o = om.geto("$name"); String s = o instanceof String ? (String) o : null; isCFG = s != null && s.equals("cfg"); isROV = s != null && s.equals("rov"); $$IMPORTS(); $$OBJECTS(); Platform$$OBJECTS(); SunSparc7$$OBJECTS(); Platform$$CONSTS(); SunSparc7$$CONSTS(); Platform$$CREATES(); SunSparc7$$CREATES(); Platform$$FUNCTIONS(); SunSparc7$$FUNCTIONS(); Platform$$SIZES(); SunSparc7$$SIZES(); Platform$$TYPES(); SunSparc7$$TYPES(); if (isROV) { Platform$$ROV(); SunSparc7$$ROV(); } // isROV $$SINGLETONS(); Platform$$SINGLETONS(); SunSparc7$$SINGLETONS(); $$INITIALIZATION(); }
public void exec(Scriptable xdcO, Session ses) { this.xdcO = xdcO; this.ses = ses; om = (Value.Obj) xdcO.get("om", null); Object o = om.geto("$name"); String s = o instanceof String ? (String) o : null; isCFG = s != null && s.equals("cfg"); isROV = s != null && s.equals("rov"); $$IMPORTS(); $$OBJECTS(); Cmdr$$OBJECTS(); ResourceBundle$$OBJECTS(); ICmd$$OBJECTS(); IProductView$$OBJECTS(); IRtscProductTemplate$$OBJECTS(); Cmdr$$CONSTS(); ResourceBundle$$CONSTS(); ICmd$$CONSTS(); IProductView$$CONSTS(); IRtscProductTemplate$$CONSTS(); Cmdr$$CREATES(); ResourceBundle$$CREATES(); ICmd$$CREATES(); IProductView$$CREATES(); IRtscProductTemplate$$CREATES(); Cmdr$$FUNCTIONS(); ResourceBundle$$FUNCTIONS(); ICmd$$FUNCTIONS(); IProductView$$FUNCTIONS(); IRtscProductTemplate$$FUNCTIONS(); Cmdr$$SIZES(); ResourceBundle$$SIZES(); ICmd$$SIZES(); IProductView$$SIZES(); IRtscProductTemplate$$SIZES(); Cmdr$$TYPES(); ResourceBundle$$TYPES(); ICmd$$TYPES(); IProductView$$TYPES(); IRtscProductTemplate$$TYPES(); if (isROV) { Cmdr$$ROV(); ResourceBundle$$ROV(); ICmd$$ROV(); IProductView$$ROV(); IRtscProductTemplate$$ROV(); } // isROV $$SINGLETONS(); Cmdr$$SINGLETONS(); ResourceBundle$$SINGLETONS(); ICmd$$SINGLETONS(); IProductView$$SINGLETONS(); IRtscProductTemplate$$SINGLETONS(); $$INITIALIZATION(); }
synchronized Object getPkgProperty(String name, Scriptable start, boolean createPkg) { Object cached = super.get(name, start); if (cached != NOT_FOUND) return cached; if (negativeCache != null && negativeCache.contains(name)) { // Performance optimization: see bug 421071 return null; } String className = (packageName.length() == 0) ? name : packageName + '.' + name; Context cx = Context.getContext(); ClassShutter shutter = cx.getClassShutter(); Scriptable newValue = null; if (shutter == null || shutter.visibleToScripts(className)) { Class<?> cl = null; if (classLoader != null) { cl = Kit.classOrNull(classLoader, className); } else { cl = Kit.classOrNull(className); } if (cl != null) { WrapFactory wrapFactory = cx.getWrapFactory(); newValue = wrapFactory.wrapJavaClass(cx, getTopLevelScope(this), cl); newValue.setPrototype(getPrototype()); } } if (newValue == null) { if (createPkg) { NativeJavaPackage pkg; pkg = new NativeJavaPackage(true, className, classLoader); ScriptRuntime.setObjectProtoAndParent(pkg, getParentScope()); newValue = pkg; } else { // add to negative cache if (negativeCache == null) negativeCache = new HashSet<String>(); negativeCache.add(name); } } if (newValue != null) { // Make it available for fast lookup and sharing of // lazily-reflected constructors and static members. super.put(name, start, newValue); } return newValue; }
private void enumerateProperty( Context cx, String name, PropEnumerator pe, URI candidate, String realm, String mechanism) { String uri = candidate.toString(); String scheme = candidate.getScheme(); String user = candidate.getUserInfo(); String host = candidate.getHost(); Integer port = candidate.getPort(); String path = candidate.getPath(); Object p = ScriptableObject.getProperty(this, name); if (p instanceof Scriptable) { Scriptable params = (Scriptable) p; for (Object key : params.getIds()) { if (key instanceof Integer) { p = params.get((Integer) key, params); } else { p = params.get((String) key, params); } if (p instanceof Scriptable) { Scriptable param = (Scriptable) p; int score = 0; score += filterProperty(cx, param, "realm", realm) * 1; score += filterProperty(cx, param, "mechanism", mechanism) * 2; score += filterProperty(cx, param, "scheme", scheme) * 4; score += filterProperty(cx, param, "path", path) * 8; score += filterProperty(cx, param, "port", port) * 16; score += filterProperty(cx, param, "host", host) * 32; score += filterProperty(cx, param, "user-info", user) * 64; score += filterProperty(cx, param, "uri", uri) * 128; if (score >= 0) { pe.handleProperty(param, score); } } } } }
private Scriptable js_getClass(Context cx, Scriptable scope, Object[] args) { if (args.length > 0 && args[0] instanceof Wrapper) { Scriptable result = this; Class<?> cl = ((Wrapper) args[0]).unwrap().getClass(); // Evaluate the class name by getting successive properties of // the string to find the appropriate NativeJavaClass object String name = cl.getName(); int offset = 0; for (; ; ) { int index = name.indexOf('.', offset); String propName = index == -1 ? name.substring(offset) : name.substring(offset, index); Object prop = result.get(propName, result); if (!(prop instanceof Scriptable)) break; // fall through to error result = (Scriptable) prop; if (index == -1) return result; offset = index + 1; } } throw Context.reportRuntimeError0("msg.not.java.obj"); }
private static void putGlobalVariablesIntoScope( @NotNull Scriptable scope, @Nullable Map<String, Object> variables) { if (variables == null) { return; } Set<Map.Entry<String, Object>> entries = variables.entrySet(); for (Map.Entry<String, Object> entry : entries) { String name = entry.getKey(); Object value = entry.getValue(); scope.put(name, scope, value); } }
private Object parseMessage() { // Consume SOAP message, if any // TODO: Add a SOAP handler in Parser.java if (soapAction != null) { try { MimeHeaders mime_headers = new MimeHeaders(); for (Object k : headers.getIds()) { if (k instanceof String) { String name = (String) k; String value = Context.toString(ScriptableObject.getProperty(headers, name)); mime_headers.addHeader(name, value); } } return MessageFactory.newInstance(SOAPConstants.DYNAMIC_SOAP_PROTOCOL) .createMessage(mime_headers, request.getInputStream()); } catch (IOException ex) { throw new ESXXException("Unable to read SOAP message stream: " + ex.getMessage()); } catch (SOAPException ex) { throw new ESXXException(400 /* Bad Request */, "Invalid SOAP message: " + ex.getMessage()); } finally { try { request.getInputStream().close(); } catch (Exception ignored) { } } } else if (contentType != null && contentLength > 0) { try { ESXX esxx = ESXX.getInstance(); return esxx.parseStream( contentType, request.getInputStream(), URI.create("urn:x-esxx:incoming-request-entity"), null, new java.io.PrintWriter(request.getErrorWriter()), Context.getCurrentContext(), this); } catch (Exception ex) { throw new ESXXException( 400 /* Bad Request */, "Unable to parse request entity: " + ex.getMessage(), ex); } finally { try { request.getInputStream().close(); } catch (Exception ignored) { } } } else { // Return a dummy object return Context.getCurrentContext().newObject(this); } }
private int filterProperty(Context cx, Scriptable param, String key, Object value) { Object rule = param.get(key, param); if (rule == null || rule == Scriptable.NOT_FOUND || value == null) { return 0; } if (rule instanceof Number && value instanceof Number) { return ((Number) rule).doubleValue() == ((Number) value).doubleValue() ? 1 : -1000; } else if (rule instanceof NativeRegExp) { return ((NativeRegExp) rule).call(cx, this, (NativeRegExp) rule, new Object[] {value}) != null ? 1 : -1000; } else { return Context.toString(rule).equals(value.toString()) ? 1 : -1000; } }
final void set(int id, Scriptable start, Object value) { if (value == NOT_FOUND) throw new IllegalArgumentException(); ensureId(id); int attr = attributeArray[id - 1]; if ((attr & READONLY) == 0) { if (start == obj) { if (value == null) { value = UniqueTag.NULL_VALUE; } int valueSlot = (id - 1) * SLOT_SPAN + VALUE_SLOT; synchronized (this) { valueArray[valueSlot] = value; } } else { int nameSlot = (id - 1) * SLOT_SPAN + NAME_SLOT; String name = (String) valueArray[nameSlot]; start.put(name, start, value); } } }
protected void addToScope(Scriptable scope) { Object value = exportingBundle.lookup(name); StringTokenizer tokenizer = new StringTokenizer(name, "."); // $NON-NLS-1$ while (true) { String token = tokenizer.nextToken(); Object current = scope.get(token, scope); if (!tokenizer.hasMoreTokens()) { if (current == Scriptable.NOT_FOUND) { if (value instanceof NativeObject) { Scriptable wrapped = Context.getCurrentContext().newObject(scope); wrapped.setPrototype((Scriptable) value); value = wrapped; } scope.put(token, scope, value); return; } throw new IllegalStateException( "Resolve error: " + name + " already exists for " + this.toString()); // $NON-NLS-1$//$NON-NLS-2$ } if (current == Scriptable.NOT_FOUND) { current = ScriptableObject.getProperty(scope, token); if (current == Scriptable.NOT_FOUND) current = Context.getCurrentContext().newObject(scope); else if (current instanceof NativeObject) { // we need to wrap this object from the prototype Scriptable wrapped = Context.getCurrentContext().newObject(scope); wrapped.setPrototype((Scriptable) current); current = wrapped; } else throw new IllegalStateException( "Resolve error: " + name + "-" + token + " already exists for " + this.toString()); // $NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ scope.put(token, scope, current); } scope = (Scriptable) current; } }
@SuppressWarnings("unused") private static Object acceptValueOf( Context cx, Scriptable thisObj, Object[] args, Function funObj) { return thisObj.get("value", thisObj); }
/* * See ECMA 15.5.4.8. Modified to match JS 1.2 - optionally takes * a limit argument and accepts a regular expression as the split * argument. */ private static Object js_split(Context cx, Scriptable scope, String target, Object[] args) { // create an empty Array to return; Scriptable top = getTopLevelScope(scope); Scriptable result = ScriptRuntime.newObject(cx, top, "Array", null); // return an array consisting of the target if no separator given // don't check against undefined, because we want // 'fooundefinedbar'.split(void 0) to split to ['foo', 'bar'] if (args.length < 1) { result.put(0, result, target); return result; } // Use the second argument as the split limit, if given. boolean limited = (args.length > 1) && (args[1] != Undefined.instance); long limit = 0; // Initialize to avoid warning. if (limited) { /* Clamp limit between 0 and 1 + string length. */ limit = ScriptRuntime.toUint32(args[1]); if (limit > target.length()) limit = 1 + target.length(); } String separator = null; int[] matchlen = new int[1]; Scriptable re = null; RegExpProxy reProxy = null; if (args[0] instanceof Scriptable) { reProxy = ScriptRuntime.getRegExpProxy(cx); if (reProxy != null) { Scriptable test = (Scriptable) args[0]; if (reProxy.isRegExp(test)) { re = test; } } } if (re == null) { separator = ScriptRuntime.toString(args[0]); matchlen[0] = separator.length(); } // split target with separator or re int[] ip = {0}; int match; int len = 0; boolean[] matched = {false}; String[][] parens = {null}; int version = cx.getLanguageVersion(); while ((match = find_split( cx, scope, target, separator, version, reProxy, re, ip, matchlen, matched, parens)) >= 0) { if ((limited && len >= limit) || (match > target.length())) break; String substr; if (target.length() == 0) substr = target; else substr = target.substring(ip[0], match); result.put(len, result, substr); len++; /* * Imitate perl's feature of including parenthesized substrings * that matched part of the delimiter in the new array, after the * split substring that was delimited. */ if (re != null && matched[0] == true) { int size = parens[0].length; for (int num = 0; num < size; num++) { if (limited && len >= limit) break; result.put(len, result, parens[0][num]); len++; } matched[0] = false; } ip[0] = match + matchlen[0]; if (version < Context.VERSION_1_3 && version != Context.VERSION_DEFAULT) { /* * Deviate from ECMA to imitate Perl, which omits a final * split unless a limit argument is given and big enough. */ if (!limited && ip[0] == target.length()) break; } } return result; }
private void handleAcceptHeader(String hdr, String value, Context cx, Scriptable accept) { String subname; if (hdr.equals("Accept")) { subname = "media"; } else if (hdr.startsWith("Accept-")) { subname = hdr.substring(7).toLowerCase(); } else { // Do nothing return; } Map<Double, List<Scriptable>> objects = new TreeMap<Double, List<Scriptable>>(); String[] values = value.split(","); for (String v : values) { double q = 1.0; double w = 0.0; String[] parts = v.split(";"); Scriptable object = cx.newObject(accept); object.put("valueOf", object, acceptValueOf); object.put("value", object, parts[0].trim()); // Add all attributes for (int i = 1; i < parts.length; ++i) { String[] attr = parts[i].split("=", 2); if (attr.length == 2) { // Parse Q factor if (attr[0].trim().equals("q")) { q = Double.parseDouble(attr[1].trim()); } else { object.put(attr[0].trim(), object, attr[1].trim()); } } } object.put("q", object, "" + q); // Calculate implicit weight if (parts[0].trim().equals("*/*")) { w = 0.0000; } else if (parts[0].trim().endsWith("/*")) { w = 0.0001; } else { w = 0.0002; } // Attributes give extra points w += parts.length * 0.00001; // Add to tree multi-map, inverse order double key = -(q + w); List<Scriptable> l = objects.get(key); if (l == null) { l = new ArrayList<Scriptable>(); objects.put(key, l); } l.add(object); } Scriptable object = cx.newArray(accept, objects.size()); accept.put(subname, accept, object); int i = 0; for (List<Scriptable> l : objects.values()) { for (Scriptable s : l) { object.put(i++, object, s); } } }
@Override public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { // Find a method that matches the types given. if (methods.length == 0) { throw new RuntimeException("No methods defined for call"); } int index = findFunction(cx, methods, args); if (index < 0) { Class<?> c = methods[0].method().getDeclaringClass(); String sig = c.getName() + '.' + getFunctionName() + '(' + scriptSignature(args) + ')'; throw Context.reportRuntimeError1("msg.java.no_such_method", sig); } MemberBox meth = methods[index]; Class<?>[] argTypes = meth.argTypes; if (meth.vararg) { // marshall the explicit parameters Object[] newArgs = new Object[argTypes.length]; for (int i = 0; i < argTypes.length - 1; i++) { newArgs[i] = Context.jsToJava(args[i], argTypes[i]); } Object varArgs; // Handle special situation where a single variable parameter // is given and it is a Java or ECMA array or is null. if (args.length == argTypes.length && (args[args.length - 1] == null || args[args.length - 1] instanceof NativeArray || args[args.length - 1] instanceof NativeJavaArray)) { // convert the ECMA array into a native array varArgs = Context.jsToJava(args[args.length - 1], argTypes[argTypes.length - 1]); } else { // marshall the variable parameters Class<?> componentType = argTypes[argTypes.length - 1].getComponentType(); varArgs = Array.newInstance(componentType, args.length - argTypes.length + 1); for (int i = 0; i < Array.getLength(varArgs); i++) { Object value = Context.jsToJava(args[argTypes.length - 1 + i], componentType); Array.set(varArgs, i, value); } } // add varargs newArgs[argTypes.length - 1] = varArgs; // replace the original args with the new one args = newArgs; } else { // First, we marshall the args. Object[] origArgs = args; for (int i = 0; i < args.length; i++) { Object arg = args[i]; Object coerced = Context.jsToJava(arg, argTypes[i]); if (coerced != arg) { if (origArgs == args) { args = args.clone(); } args[i] = coerced; } } } Object javaObject; if (meth.isStatic()) { javaObject = null; // don't need an object } else { Scriptable o = thisObj; Class<?> c = meth.getDeclaringClass(); for (; ; ) { if (o == null) { throw Context.reportRuntimeError3( "msg.nonjava.method", getFunctionName(), ScriptRuntime.toString(thisObj), c.getName()); } if (o instanceof Wrapper) { javaObject = ((Wrapper) o).unwrap(); if (c.isInstance(javaObject)) { break; } } o = o.getPrototype(); } } if (debug) { printDebug("Calling ", meth, args); } Object retval = meth.invoke(javaObject, args); Class<?> staticType = meth.method().getReturnType(); if (debug) { Class<?> actualType = (retval == null) ? null : retval.getClass(); System.err.println( " ----- Returned " + retval + " actual = " + actualType + " expect = " + staticType); } Object wrapped = cx.getWrapFactory() .wrap( cx, scope, retval, staticType); if (debug) { Class<?> actualType = (wrapped == null) ? null : wrapped.getClass(); System.err.println(" ----- Wrapped as " + wrapped + " class = " + actualType); } if (wrapped == null && staticType == Void.TYPE) { wrapped = Undefined.instance; } return wrapped; }
/** * Evaluates the RhinoFile result. If the result is an instance of javax.javascript.Scriptable, * assume it is a JavaScript Array of TestCase objects, as described in RhinoDrv.java. For each * test case in the array, add an element to the RhinoFile's test case vector. If all test cases * passed, set the RhinoFile's passed value to true; else set its passed value to false. * * <p>If the result is not a Scriptable object, the test failed. Set the the RhinoFile's exception * property to the string value of the result. However, negative tests, which should have a * "-n.js" extension, are expected to fail. */ public boolean parseResult() { FlattenedObject fo = null; if (result instanceof Scriptable) { fo = new FlattenedObject((Scriptable) result); try { file.totalCases = ((Number) fo.getProperty("length")).intValue(); for (int i = 0; i < file.totalCases; i++) { Scriptable tc = (Scriptable) ((Scriptable) result).get(i, (Scriptable) result); TestCase rt = new TestCase( getString(tc.get("passed", tc)), getString(tc.get("name", tc)), getString(tc.get("description", tc)), getString(tc.get("expect", tc)), getString(tc.get("actual", tc)), getString(tc.get("reason", tc))); file.bugnumber = (getString(tc.get("bugnumber", tc))).startsWith("com.netscape.javascript") ? file.bugnumber : getString(tc.get("bugnumber", tc)); file.caseVector.addElement(rt); if (rt.passed.equals("false")) { this.file.passed = false; this.suite.passed = false; } } if (file.totalCases == 0) { if (file.name.endsWith("-n.js")) { this.file.passed = true; } else { this.file.reason = "File contains no testcases. " + this.file.reason; this.file.passed = false; this.suite.passed = false; } } } catch (Exception e) { this.file.exception = "Got a Scriptable result, but failed " + "parsing its arguments. Exception: " + e.toString() + " Flattened Object is: " + fo.toString(); this.file.passed = false; this.suite.passed = false; return false; } } else { // if it's not a scriptable object, test failed. set the file's // exception to the string value of whatever result we did get. this.file.exception = result.toString(); // if the file's name ends in "-n", the test expected an error. if (file.name.endsWith("-n.js")) { this.file.passed = true; } else { this.file.passed = false; this.suite.passed = false; return false; } } return true; }
/** * Creates and returns a new Image object that is a rendering of this Image object. The input * object defines the rendering parameters of the new Image object. Imagemagick's convert program * is used to create a scaled bounding box of this Image with the given dimensions. * * @param {Object} input A JavaScript object specifying the rendering parameters. For example, * <code> {maxWidth:200, maxHeight:100} </code> * @returns {Image} The rendered Image object * @throws Exception */ public ImageObject jsFunction_render(Object input) throws Exception { if (input == null || !(input instanceof Scriptable)) { throw new RuntimeException("The first argument to render() must be a scriptable object."); } Scriptable s = (Scriptable) input; int maxWidth = toInt(s.get("maxWidth", s)); int maxHeight = toInt(s.get("maxHeight", s)); int cropWidth = toInt(s.get("cropWidth", s)); int cropHeight = toInt(s.get("cropHeight", s)); int cropXOffset = toInt(s.get("cropXOffset", s)); int cropYOffset = toInt(s.get("cropYOffset", s)); int currentWidth = (int) node.getInteger(WIDTH); int currentHeight = (int) node.getInteger(HEIGHT); String aname = null; if (maxWidth > 0 && maxHeight > 0 && currentWidth > 0 && currentHeight > 0) { int[] dims = this.computeResizedDimensions(maxWidth, maxHeight, currentWidth, currentHeight); aname = dims[0] + "x" + dims[1]; maxWidth = dims[0]; maxHeight = dims[1]; } else if (cropWidth > 0 && cropHeight > 0) { aname = cropWidth + "x" + cropHeight + "_" + cropXOffset + "x" + cropYOffset; } else { throw new RuntimeException("render(), invalid parameter set."); } Object o = this.jsFunction_get(aname); if (o instanceof ImageObject) { return (ImageObject) o; } try { synchronized (this) { while (this.convertOps.contains(aname)) { this.wait(); } this.convertOps.add(aname); } o = ((axiom.objectmodel.db.Node) this.node).getChildElement(aname, true); if (o instanceof Node) { return (ImageObject) Context.toObject(o, this.core.global); } ImageObject computedImg = null; String[] paths = getPaths(); String imgPath = paths[0]; String tmpPath = paths[1]; String fileName = node.getString(FileObject.FILE_NAME); try { File tmpFile = new File(tmpPath); int[] dims = null; if (maxWidth > 0 && maxHeight > 0) { dims = this.resize( maxWidth, maxHeight, (int) this.node.getInteger(WIDTH), (int) this.node.getInteger(HEIGHT), imgPath, tmpPath, true); } else { dims = this.crop(cropWidth, cropHeight, cropXOffset, cropYOffset, imgPath, tmpPath); } if (dims == null) { throw new Exception("ImageObject.render(), resizing the image failed."); } final String protoname = "Image"; INode node = new axiom.objectmodel.db.Node(protoname, protoname, core.app.getWrappedNodeManager()); computedImg = new ImageObject("Image", core, node, core.getPrototype(protoname), true); node.setString(FileObject.FILE_NAME, fileName); node.setString(FileObject.ACCESSNAME, FileObjectCtor.generateAccessName(fileName)); node.setString(FileObject.CONTENT_TYPE, this.node.getString(FileObject.CONTENT_TYPE)); node.setJavaObject(FileObject.SELF, computedImg); node.setInteger(ImageObject.WIDTH, dims[0]); node.setInteger(ImageObject.HEIGHT, dims[1]); node.setString(FileObject.RENDERED_CONTENT, "true"); node.setInteger(FileObject.FILE_SIZE, tmpFile.length()); computedImg.tmpPath = tmpPath; } catch (Exception ex) { throw new RuntimeException( "ImageObject.jsfunction_bound(): Could not write the image to temporary storage, " + ex.getMessage()); } if (computedImg != null) { this.jsFunction_addThumbnail(computedImg, null); return computedImg; } } finally { synchronized (this) { this.convertOps.remove(aname); this.notifyAll(); } } return null; }
public static void init(Context cx, Scriptable scope, boolean sealed) { NativeGlobal obj = new NativeGlobal(); for (int id = 1; id <= LAST_SCOPE_FUNCTION_ID; ++id) { String name; int arity = 1; switch (id) { case Id_decodeURI: name = "decodeURI"; break; case Id_decodeURIComponent: name = "decodeURIComponent"; break; case Id_encodeURI: name = "encodeURI"; break; case Id_encodeURIComponent: name = "encodeURIComponent"; break; case Id_escape: name = "escape"; break; case Id_eval: name = "eval"; break; case Id_isFinite: name = "isFinite"; break; case Id_isNaN: name = "isNaN"; break; case Id_isXMLName: name = "isXMLName"; break; case Id_parseFloat: name = "parseFloat"; break; case Id_parseInt: name = "parseInt"; arity = 2; break; case Id_unescape: name = "unescape"; break; case Id_uneval: name = "uneval"; break; default: throw Kit.codeBug(); } IdFunctionObject f = new IdFunctionObject(obj, FTAG, id, name, arity, scope); if (sealed) { f.sealObject(); } f.exportAsScopeProperty(); } ScriptableObject.defineProperty(scope, "NaN", ScriptRuntime.NaNobj, ScriptableObject.DONTENUM); ScriptableObject.defineProperty( scope, "Infinity", ScriptRuntime.wrapNumber(Double.POSITIVE_INFINITY), ScriptableObject.DONTENUM); ScriptableObject.defineProperty( scope, "undefined", Undefined.instance, ScriptableObject.DONTENUM); String[] errorMethods = Kit.semicolonSplit( "" + "ConversionError;" + "EvalError;" + "RangeError;" + "ReferenceError;" + "SyntaxError;" + "TypeError;" + "URIError;" + "InternalError;" + "JavaException;"); /* Each error constructor gets its own Error object as a prototype, with the 'name' property set to the name of the error. */ for (int i = 0; i < errorMethods.length; i++) { String name = errorMethods[i]; Scriptable errorProto = ScriptRuntime.newObject(cx, scope, "Error", ScriptRuntime.emptyArgs); errorProto.put("name", errorProto, name); if (sealed) { if (errorProto instanceof ScriptableObject) { ((ScriptableObject) errorProto).sealObject(); } } IdFunctionObject ctor = new IdFunctionObject(obj, FTAG, Id_new_CommonError, name, 1, scope); ctor.markAsConstructor(errorProto); if (sealed) { ctor.sealObject(); } ctor.exportAsScopeProperty(); } }
@Override public Object execIdCall( IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(OBJECT_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int id = f.methodId(); switch (id) { case Id_constructor: { if (thisObj != null) { // BaseFunction.construct will set up parent, proto return f.construct(cx, scope, args); } if (args.length == 0 || args[0] == null || args[0] == Undefined.instance) { return new NativeObject(); } return ScriptRuntime.toObject(cx, scope, args[0]); } case Id_toLocaleString: { Object toString = ScriptableObject.getProperty(thisObj, "toString"); if (!(toString instanceof Callable)) { throw ScriptRuntime.notFunctionError(toString); } Callable fun = (Callable) toString; return fun.call(cx, scope, thisObj, ScriptRuntime.emptyArgs); } case Id_toString: { if (cx.hasFeature(Context.FEATURE_TO_STRING_AS_SOURCE)) { String s = ScriptRuntime.defaultObjectToSource( cx, scope, thisObj, args); int L = s.length(); if (L != 0 && s.charAt(0) == '(' && s.charAt(L - 1) == ')') { // Strip () that surrounds toSource s = s.substring(1, L - 1); } return s; } return ScriptRuntime.defaultObjectToString(thisObj); } case Id_valueOf: return thisObj; case Id_hasOwnProperty: { boolean result; Object arg = args.length < 1 ? Undefined.instance : args[0]; String s = ScriptRuntime.toStringIdOrIndex(cx, arg); if (s == null) { int index = ScriptRuntime.lastIndexResult(cx); result = thisObj.has(index, thisObj); } else { result = thisObj.has(s, thisObj); } return ScriptRuntime.wrapBoolean(result); } case Id_propertyIsEnumerable: { boolean result; Object arg = args.length < 1 ? Undefined.instance : args[0]; String s = ScriptRuntime.toStringIdOrIndex(cx, arg); if (s == null) { int index = ScriptRuntime.lastIndexResult(cx); result = thisObj.has(index, thisObj); if (result && thisObj instanceof ScriptableObject) { ScriptableObject so = (ScriptableObject) thisObj; int attrs = so.getAttributes(index); result = ((attrs & ScriptableObject.DONTENUM) == 0); } } else { result = thisObj.has(s, thisObj); if (result && thisObj instanceof ScriptableObject) { ScriptableObject so = (ScriptableObject) thisObj; int attrs = so.getAttributes(s); result = ((attrs & ScriptableObject.DONTENUM) == 0); } } return ScriptRuntime.wrapBoolean(result); } case Id_isPrototypeOf: { boolean result = false; if (args.length != 0 && args[0] instanceof Scriptable) { Scriptable v = (Scriptable) args[0]; do { v = v.getPrototype(); if (v == thisObj) { result = true; break; } } while (v != null); } return ScriptRuntime.wrapBoolean(result); } case Id_toSource: return ScriptRuntime.defaultObjectToSource(cx, scope, thisObj, args); case Id___defineGetter__: case Id___defineSetter__: { if (args.length < 2 || !(args[1] instanceof Callable)) { Object badArg = (args.length >= 2 ? args[1] : Undefined.instance); throw ScriptRuntime.notFunctionError(badArg); } if (!(thisObj instanceof ScriptableObject)) { throw Context.reportRuntimeError2( "msg.extend.scriptable", thisObj.getClass().getName(), String.valueOf(args[0])); } ScriptableObject so = (ScriptableObject) thisObj; String name = ScriptRuntime.toStringIdOrIndex(cx, args[0]); int index = (name != null ? 0 : ScriptRuntime.lastIndexResult(cx)); Callable getterOrSetter = (Callable) args[1]; boolean isSetter = (id == Id___defineSetter__); so.setGetterOrSetter(name, index, getterOrSetter, isSetter); if (so instanceof NativeArray) ((NativeArray) so).setDenseOnly(false); } return Undefined.instance; case Id___lookupGetter__: case Id___lookupSetter__: { if (args.length < 1 || !(thisObj instanceof ScriptableObject)) return Undefined.instance; ScriptableObject so = (ScriptableObject) thisObj; String name = ScriptRuntime.toStringIdOrIndex(cx, args[0]); int index = (name != null ? 0 : ScriptRuntime.lastIndexResult(cx)); boolean isSetter = (id == Id___lookupSetter__); Object gs; for (; ; ) { gs = so.getGetterOrSetter(name, index, isSetter); if (gs != null) break; // If there is no getter or setter for the object itself, // how about the prototype? Scriptable v = so.getPrototype(); if (v == null) break; if (v instanceof ScriptableObject) so = (ScriptableObject) v; else break; } if (gs != null) return gs; } return Undefined.instance; case ConstructorId_getPrototypeOf: { Object arg = args.length < 1 ? Undefined.instance : args[0]; Scriptable obj = ensureScriptable(arg); return obj.getPrototype(); } case ConstructorId_keys: { Object arg = args.length < 1 ? Undefined.instance : args[0]; Scriptable obj = ensureScriptable(arg); Object[] ids = obj.getIds(); for (int i = 0; i < ids.length; i++) { ids[i] = ScriptRuntime.toString(ids[i]); } return cx.newArray(scope, ids); } case ConstructorId_getOwnPropertyNames: { Object arg = args.length < 1 ? Undefined.instance : args[0]; ScriptableObject obj = ensureScriptableObject(arg); Object[] ids = obj.getAllIds(); for (int i = 0; i < ids.length; i++) { ids[i] = ScriptRuntime.toString(ids[i]); } return cx.newArray(scope, ids); } case ConstructorId_getOwnPropertyDescriptor: { Object arg = args.length < 1 ? Undefined.instance : args[0]; // TODO(norris): There's a deeper issue here if // arg instanceof Scriptable. Should we create a new // interface to admit the new ECMAScript 5 operations? ScriptableObject obj = ensureScriptableObject(arg); Object nameArg = args.length < 2 ? Undefined.instance : args[1]; String name = ScriptRuntime.toString(nameArg); Scriptable desc = obj.getOwnPropertyDescriptor(cx, name); return desc == null ? Undefined.instance : desc; } case ConstructorId_defineProperty: { Object arg = args.length < 1 ? Undefined.instance : args[0]; ScriptableObject obj = ensureScriptableObject(arg); Object name = args.length < 2 ? Undefined.instance : args[1]; Object descArg = args.length < 3 ? Undefined.instance : args[2]; ScriptableObject desc = ensureScriptableObject(descArg); obj.defineOwnProperty(cx, name, desc); return obj; } case ConstructorId_isExtensible: { Object arg = args.length < 1 ? Undefined.instance : args[0]; ScriptableObject obj = ensureScriptableObject(arg); return Boolean.valueOf(obj.isExtensible()); } case ConstructorId_preventExtensions: { Object arg = args.length < 1 ? Undefined.instance : args[0]; ScriptableObject obj = ensureScriptableObject(arg); obj.preventExtensions(); return obj; } case ConstructorId_defineProperties: { Object arg = args.length < 1 ? Undefined.instance : args[0]; ScriptableObject obj = ensureScriptableObject(arg); Object propsObj = args.length < 2 ? Undefined.instance : args[1]; Scriptable props = Context.toObject(propsObj, getParentScope()); obj.defineOwnProperties(cx, ensureScriptableObject(props)); return obj; } case ConstructorId_create: { Object arg = args.length < 1 ? Undefined.instance : args[0]; Scriptable obj = (arg == null) ? null : ensureScriptable(arg); ScriptableObject newObject = new NativeObject(); newObject.setParentScope(getParentScope()); newObject.setPrototype(obj); if (args.length > 1 && args[1] != Undefined.instance) { Scriptable props = Context.toObject(args[1], getParentScope()); newObject.defineOwnProperties(cx, ensureScriptableObject(props)); } return newObject; } case ConstructorId_isSealed: { Object arg = args.length < 1 ? Undefined.instance : args[0]; ScriptableObject obj = ensureScriptableObject(arg); if (obj.isExtensible()) return Boolean.FALSE; for (Object name : obj.getAllIds()) { Object configurable = obj.getOwnPropertyDescriptor(cx, name).get("configurable"); if (Boolean.TRUE.equals(configurable)) return Boolean.FALSE; } return Boolean.TRUE; } case ConstructorId_isFrozen: { Object arg = args.length < 1 ? Undefined.instance : args[0]; ScriptableObject obj = ensureScriptableObject(arg); if (obj.isExtensible()) return Boolean.FALSE; for (Object name : obj.getAllIds()) { ScriptableObject desc = obj.getOwnPropertyDescriptor(cx, name); if (Boolean.TRUE.equals(desc.get("configurable"))) return Boolean.FALSE; if (isDataDescriptor(desc) && Boolean.TRUE.equals(desc.get("writable"))) return Boolean.FALSE; } return Boolean.TRUE; } case ConstructorId_seal: { Object arg = args.length < 1 ? Undefined.instance : args[0]; ScriptableObject obj = ensureScriptableObject(arg); for (Object name : obj.getAllIds()) { ScriptableObject desc = obj.getOwnPropertyDescriptor(cx, name); if (Boolean.TRUE.equals(desc.get("configurable"))) { desc.put("configurable", desc, Boolean.FALSE); obj.defineOwnProperty(cx, name, desc, false); } } obj.preventExtensions(); return obj; } case ConstructorId_freeze: { Object arg = args.length < 1 ? Undefined.instance : args[0]; ScriptableObject obj = ensureScriptableObject(arg); for (Object name : obj.getAllIds()) { ScriptableObject desc = obj.getOwnPropertyDescriptor(cx, name); if (isDataDescriptor(desc) && Boolean.TRUE.equals(desc.get("writable"))) desc.put("writable", desc, Boolean.FALSE); if (Boolean.TRUE.equals(desc.get("configurable"))) desc.put("configurable", desc, Boolean.FALSE); obj.defineOwnProperty(cx, name, desc, false); } obj.preventExtensions(); return obj; } default: throw new IllegalArgumentException(String.valueOf(id)); } }