@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);
 }
Exemple #2
0
 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;
   }
 }
Exemple #3
0
 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);
   }
 }
Exemple #4
0
  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);
  }
Exemple #5
0
 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();
   }
 }
 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);
     }
   }
 }
  /*
   * 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;
  }
Exemple #8
0
  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();
    }
  }
  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);
      }
    }
  }