public static String encodeFormVariables(String cs, Scriptable values)
      throws java.io.UnsupportedEncodingException {
    StringBuilder sb = new StringBuilder();

    for (Object o : values.getIds()) {
      if (sb.length() != 0) {
        sb.append("&");
      }

      if (o instanceof String) {
        String key = (String) o;
        String value = Context.toString(values.get(key, values));

        sb.append(URLEncoder.encode(key, cs));
        sb.append("=");
        sb.append(URLEncoder.encode(value, cs));
      } else {
        int key = (Integer) o;
        String value = Context.toString(values.get(key, values));

        sb.append(key).append("=");
        sb.append(URLEncoder.encode(value, cs));
      }
    }

    return sb.toString();
  }
 static {
   ctx = Context.enter();
   sharedScope = ctx.initStandardObjects();
   ctx.evaluateString(sharedScope, jsAsString, "re", 1, null);
   regexIsValid = (Function) sharedScope.get("regexIsValid", sharedScope);
   regMatch = (Function) sharedScope.get("regMatch", sharedScope);
   ctx.seal(null);
 }
 private Object[] toArray(Scriptable svalue) {
   int len = (Integer) Context.jsToJava(svalue.get("length", this), Integer.class);
   Object[] a = new Object[len];
   for (int i = 0; i < len; i++) {
     Object v = svalue.get(i, svalue);
     if (DBG) {
       Log.d(LCAT, "Index: " + i + " value: " + v + " type: " + v.getClass().getName());
     }
     a[i] = toNative(v, Object.class);
   }
   return a;
 }
Exemple #4
0
 private List<Issue> readErrors(String systemId) {
   ArrayList<Issue> issues = new ArrayList<Issue>();
   Scriptable JSLINT = (Scriptable) scope.get("JSLINT", scope);
   Scriptable errors = (Scriptable) JSLINT.get("errors", JSLINT);
   int count = Util.intValue("length", errors);
   for (int i = 0; i < count; i++) {
     Scriptable err = (Scriptable) errors.get(i, errors);
     // JSLINT spits out a null when it cannot proceed.
     // TODO Should probably turn i-1th issue into a "fatal".
     if (err != null) {
       issues.add(IssueBuilder.fromJavaScript(systemId, err));
     }
   }
   return issues;
 }
  public JavascriptArrayFileNameProvider(
      FileProvider fileProvider, String sourceFile, String variableName) throws IOException {

    BufferedReader source = fileProvider.getResource(sourceFile);
    try {
      Context cx = Context.enter();
      Scriptable scope = cx.initStandardObjects();
      cx.evaluateReader(scope, source, sourceFile, 1, null);
      Object x = scope.get(variableName, scope);

      if (!(x instanceof NativeArray)) {
        throw new RuntimeException(
            "Could not find array called " + variableName + " in source file " + sourceFile);
      }
      NativeArray array = (NativeArray) x;
      for (int i = 0; i < array.getLength(); i++) {
        Object o = array.get(i, null);
        if (!(o instanceof String)) {
          throw new RuntimeException(
              "Array contained objects which are not Strings, cannot continue");
        }
        fileNames.add("/" + o);
      }
    } finally {
      Context.exit();
    }
  }
Exemple #6
0
  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();
  }
 @Override
 public Object get(String name, Scriptable start) {
   if (wrapped == null) {
     return super.get(name, start);
   }
   if (name.startsWith("super$")) {
     return wrapped.get(name.substring(6), wrapped);
   }
   if (properties != null) {
     Object value = properties.get(name, properties);
     if (value != NOT_FOUND) {
       return value;
     }
   }
   return wrapped.get(name, wrapped);
 }
 public String execute(String methodName, Object... params) throws Throwable {
   if (cx == null) {
     throw new IllegalStateException("Can't execute a function, context is null!");
   }
   Object fObj = scope.get(methodName, scope);
   Function f = (Function) fObj;
   return Context.toString(f.call(cx, scope, scope, params));
 }
Exemple #9
0
 public static Exhibit toExhibit(Scriptable res, ExhibitDescriptor expected) {
   if (res == null) {
     throw new IllegalStateException("Null return values are not permitted");
   }
   List<Object> attrs = Lists.newArrayList();
   Map<String, Frame> frames = Maps.newHashMap();
   Map<String, Vec> vectors = Maps.newHashMap();
   for (ObsDescriptor.Field f : expected.attributes()) {
     attrs.add(toField(res.get(f.name, res)));
   }
   for (Map.Entry<String, FieldType> e : expected.vectors().entrySet()) {
     vectors.put(e.getKey(), toVector(e.getValue(), res.get(e.getKey(), res)));
   }
   for (Map.Entry<String, ObsDescriptor> e : expected.frames().entrySet()) {
     frames.put(e.getKey(), toFrame(e.getValue(), res.get(e.getKey(), res)));
   }
   return new SimpleExhibit(new SimpleObs(expected.attributes(), attrs), frames, vectors);
 }
  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();
  }
Exemple #11
0
  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);
          }
        }
      }
    }
  }
Exemple #12
0
  /**
   * List the open invitations for this web site. props specifies optional properties to be
   * searched.
   *
   * @param props inviteeUserName
   * @return the invitations
   */
  public ScriptInvitation<?>[] listInvitations(Scriptable props) {
    InvitationSearchCriteriaImpl crit = new InvitationSearchCriteriaImpl();
    crit.setResourceName(getShortName());
    crit.setResourceType(Invitation.ResourceType.WEB_SITE);

    if (props.has("inviteeUserName", props)) {
      crit.setInvitee((String) props.get("inviteeUserName", props));
    }
    if (props.has("invitationType", props)) {
      String invitationType = (String) props.get("invitationType", props);
      crit.setInvitationType(InvitationType.valueOf(invitationType));
    }

    List<Invitation> invitations = invitationService.searchInvitation(crit);
    ScriptInvitation<?>[] ret = new ScriptInvitation[invitations.size()];
    int i = 0;
    for (Invitation item : invitations) {
      ret[i++] = scriptInvitationFactory.toScriptInvitation(item);
    }
    return ret;
  }
Exemple #13
0
 public static void help(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
   if (args.length == 0) {
     final Object[] objects = thisObj.getIds();
     for (Object object : objects) {
       System.out.println("jai." + object + " = " + thisObj.get(object.toString(), thisObj));
     }
     printOperatorList();
   } else {
     for (Object arg : args) {
       printOperatorUsage(Context.toString(arg));
     }
   }
 }
Exemple #14
0
 /** Set the "member" field of the {@link JSLintResult}. */
 private Map<String, Integer> getDataMembers(Scriptable data) {
   Object o1 = data.get("member", data);
   if (o1 == UniqueTag.NOT_FOUND) {
     return new HashMap<String, Integer>();
   }
   Scriptable member = (Scriptable) o1;
   Object[] propertyIds = ScriptableObject.getPropertyIds(member);
   Map<String, Integer> members = new HashMap<String, Integer>(propertyIds.length);
   for (Object id : propertyIds) {
     String k = id.toString();
     members.put(k, Util.intValue(k, member));
   }
   return members;
 }
 public static String scriptableToString(Scriptable scriptable) {
   StringBuilder builder = new StringBuilder();
   for (Object propid : scriptable.getIds()) {
     String propIdString = Context.toString(propid);
     int propIntKey = -1;
     try {
       propIntKey = Integer.parseInt(propIdString);
     } catch (NumberFormatException nfe) {
       // dummy.
     }
     String propValue;
     if (propIntKey >= 0) {
       propValue = Context.toString(scriptable.get(propIntKey, scriptable));
     } else {
       propValue = Context.toString(scriptable.get(propIdString, scriptable));
     }
     builder.append(propIdString);
     builder.append(": ");
     builder.append(propValue);
     builder.append("; ");
   }
   return builder.toString();
 }
Exemple #16
0
  protected Map<String, Object> convertParams(Scriptable params) {
    Map<String, Object> paramsMap = new HashMap<>();

    if (params != null && !(params instanceof Undefined)) {
      for (Object id : params.getIds()) {
        String castId = id instanceof String ? (String) id : String.valueOf(id);
        Object value = params.get(castId, params);

        if (value instanceof NativeJavaObject) value = ((NativeJavaObject) value).unwrap();

        paramsMap.put(castId, value);
      }
    }

    return paramsMap;
  }
 /**
  * Executes an arbitrary expression.<br>
  * It fails if the expression throws a JsAssertException.<br>
  * It fails if the expression throws a RhinoException.<br>
  * Code from JsTester (http://jstester.sf.net/)
  */
 public Object eval(String expr) {
   Object value = null;
   try {
     value = context.evaluateString(globalScope, expr, "", 1, null);
   } catch (JavaScriptException jse) {
     Scriptable jsAssertException = (Scriptable) globalScope.get("currentException", globalScope);
     jse.printStackTrace();
     String message = (String) jsAssertException.get("message", jsAssertException);
     if (message != null) {
       fail(message);
     }
   } catch (RhinoException re) {
     fail(re.getMessage());
   }
   return value;
 }
Exemple #18
0
 public void input(Datum in) {
   Context c = ContextFactory.getGlobal().enterContext();
   Object maybeFunc = _topLevel.get("handle", _topLevel);
   if (Scriptable.NOT_FOUND == maybeFunc || !(maybeFunc instanceof Function)) {
     // TODO better exception
     throw new RuntimeException("No handle function");
   }
   Function func = (Function) maybeFunc;
   Object[] args = new Object[2];
   args[0] = in;
   args[1] = _ops;
   Object result = func.call(c, _topLevel, _topLevel, args);
   // There's a couple of ways this interface could work: commit as a
   // side-effect, and commit as a return value.  We use side-effect
   // for now, so the return value is ignored.
 }
Exemple #19
0
  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;
    }
  }
Exemple #20
0
  public Object jsFunction_create(String collection, Scriptable defaults) {
    ODocument document = collection != null ? new ODocument(collection) : new ODocument();
    ScriptableObject result = (ScriptableObject) wrap(document);

    if (defaults != null && !(defaults instanceof Undefined)) {
      for (Object rawId : defaults.getIds()) {
        String id = (String) rawId;
        Object value = defaults.get(id, defaults);

        if (value instanceof NativeJavaObject) value = jsFunction_objectToDocument(value);

        result.put(id, result, value);
      }
    }

    return result;
  }
Exemple #21
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;
   }
 }
  /**
   * Finds the JavaScript funtion by given name.
   *
   * @param sFunctionName The name of the function to be searched for
   * @return An instance of the function being searched for or null if it isn't found
   */
  private final Function getJavascriptFunction(String sFunctionName) {
    // TODO: CACHE PREVIOUSLY CREATED FUNCTION REFERENCES IN A HASHTABLE?

    // use names cache for quick validation to improve performance
    if (javaScriptFunctionNamesCache == null
        || javaScriptFunctionNamesCache.indexOf(sFunctionName) < 0) {
      return null;
    }

    Context.enter();
    try {
      final Object oFunction = scope.get(sFunctionName, scope);
      if (oFunction != Scriptable.NOT_FOUND && oFunction instanceof Function) {
        return (Function) oFunction;
      }
      return null;
    } finally {
      Context.exit();
    }
  }
 public void testFunctionWithContinuations() {
   Context cx = Context.enter();
   try {
     cx.setOptimizationLevel(-1); // must use interpreter mode
     cx.evaluateString(
         globalScope, "function f(a) { return myObject.f(a); }", "function test source", 1, null);
     Function f = (Function) globalScope.get("f", globalScope);
     Object[] args = {7};
     cx.callFunctionWithContinuations(f, globalScope, args);
     fail("Should throw ContinuationPending");
   } catch (ContinuationPending pending) {
     Object applicationState = pending.getApplicationState();
     assertEquals(7, ((Number) applicationState).intValue());
     int saved = (Integer) applicationState;
     Object result = cx.resumeContinuation(pending.getContinuation(), globalScope, saved + 1);
     assertEquals(8, ((Number) result).intValue());
   } finally {
     Context.exit();
   }
 }
Exemple #24
0
 static ExhibitDescriptor toExhibitDescriptor(Scriptable res, Set<String> existing) {
   if (res == null) {
     throw new IllegalStateException("Null return values are not permitted");
   }
   List<ObsDescriptor.Field> fields = Lists.newArrayList();
   Map<String, FieldType> vecs = Maps.newHashMap();
   Map<String, ObsDescriptor> frames = Maps.newHashMap();
   for (Object id : res.getIds()) {
     if (!existing.contains(id) && !"INIT".equals(id)) {
       Object v = res.get(id.toString(), res);
       if (isCastableToFrame(v)) {
         frames.put(id.toString(), toFrameDescriptor(v));
       } else if (isCastableToVec(v)) {
         vecs.put(id.toString(), toVectorType(v));
       } else if (isCastableToField(v)) {
         fields.add(new ObsDescriptor.Field(id.toString(), toFieldType(v)));
       }
     }
   }
   return new ExhibitDescriptor(new SimpleObsDescriptor(fields), frames, vecs);
 }
  public void testSerializationWithContinuations() throws IOException, ClassNotFoundException {
    Context cx = Context.enter();
    try {
      cx.setOptimizationLevel(-1); // must use interpreter mode
      cx.evaluateString(
          globalScope, "function f(a) { return myObject.f(a); }", "function test source", 1, null);
      Function f = (Function) globalScope.get("f", globalScope);
      Object[] args = {7};
      cx.callFunctionWithContinuations(f, globalScope, args);
      fail("Should throw ContinuationPending");
    } catch (ContinuationPending pending) {
      // serialize
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream(baos);
      oos.writeObject(globalScope);
      oos.writeObject(pending.getContinuation());
      oos.close();
      baos.close();
      byte[] serializedData = baos.toByteArray();

      // deserialize
      ByteArrayInputStream bais = new ByteArrayInputStream(serializedData);
      ObjectInputStream ois = new ObjectInputStream(bais);
      globalScope = (Scriptable) ois.readObject();
      Object continuation = ois.readObject();
      ois.close();
      bais.close();

      Object result =
          cx.resumeContinuation(
              continuation, globalScope, 8); // / XXX: 8 shoudl be applicationstate + 1
      assertEquals(8, ((Number) result).intValue());
    } finally {
      Context.exit();
    }
  }
  public void Serialize(Scriptable start, Object obj, String loc, int tab) {
    if (obj == null) {
      pr.write("null");
    } else if (set.containsKey(obj)) {
      pr.write("/* [" + obj.getClass().getName() + " " + set.get(obj) + "] */");
    } else if (obj instanceof String) {
      pr.write("\"" + obj.toString() + "\"");
    } else if (obj instanceof Number) {
      pr.write(obj.toString());
    } else if (obj instanceof UniqueTag) {
      UniqueTag u = (UniqueTag) obj;

      if (u.equals(UniqueTag.NULL_VALUE)) {
        pr.write("null");
      } else if (u.equals(UniqueTag.NOT_FOUND)) {
        pr.write("__undefined__");
      } else if (u.equals(UniqueTag.DOUBLE_MARK)) {
        pr.write("__double_mark__");
      }
      /*
      			set.put(obj,loc);

      			Serialize(u.readResolve());
      */
    } else if (obj instanceof Scriptable) {
      Scriptable s = (Scriptable) obj;
      String className = s.getClassName();

      Object[] ids = s.getIds();

      pr.write("{\n");
      writeTabs(tab);

      for (Object o : ids) {
        Object val = null;
        String nloc = loc + "/";
        if (o instanceof String) {
          val = s.get((String) o, s);
          pr.write("\"" + o.toString() + "\":");
          nloc += (String) o;
        } else {
          val = s.get((Integer) o, s);
          pr.write("" + o.toString() + ":");
          nloc += o.toString();
        }

        set.put(obj, loc);

        if (val == null) {
          pr.write("null,\n");
          writeTabs(tab);
        } else {
          Serialize(start, val, nloc, tab + 1);
          pr.write(",\n");
          writeTabs(tab);
        }
      }
      pr.write("}\n");
      writeTabs(tab);
    } else {
      pr.write("/* " + obj.getClass().getName() + " */\n");
      writeTabs(tab);
    }
  }
  protected Object toNative(Object value, Class<?> target) {
    Object o = null;

    if (value instanceof String) {
      o = Context.jsToJava(value, target);
    } else if (value instanceof Double || value instanceof Integer) {
      o = Context.jsToJava(value, target);
    } else if (value instanceof Boolean) {
      o = Context.jsToJava(value, target);
    } else if (value instanceof Function) {
      if (DBG) {
        Log.i(LCAT, "Is a Function");
      }
      o = new KrollCallback(weakKrollContext.get(), this, (Function) value);
    } else if (value == null) {
      o = null;
    } else if (value instanceof Scriptable) {
      Scriptable svalue = (Scriptable) value;
      if (isArrayLike(svalue)) {
        o = toArray(svalue);
      } else if (value instanceof KrollObject) {
        o = ((KrollObject) value).target;
      } else if (svalue.getClassName().equals("Date")) {
        double time = (Double) ScriptableObject.callMethod(svalue, "getTime", new Object[0]);
        o = new Date((long) time);
      } else {
        TiDict args = new TiDict();
        o = args;

        Scriptable so = (Scriptable) value;
        for (Object key : so.getIds()) {
          Object v = so.get((String) key, so);
          v = toNative(v, Object.class);
          //					if (v instanceof Scriptable && isArrayLike((Scriptable) v)) {
          //						v = toArray((Scriptable) v);
          //					}
          if (DBG) {
            Log.i(LCAT, "Key: " + key + " value: " + v + " type: " + v.getClass().getName());
          }
          args.put((String) key, v);
        }
        // Log.w(LCAT, "Unhandled type conversion of Scriptable: value: " + value.toString() + "
        // type: " + value.getClass().getName());
      }
    } else {
      if (value.getClass().isArray()) {
        Object[] values = (Object[]) value;
        Object[] newValues = new Object[values.length];
        for (int i = 0; i < values.length; i++) {
          newValues[i] = toNative(values[i], Object.class);
        }
        o = newValues;
      } else {
        Log.w(
            LCAT,
            "Unhandled type conversion: value: "
                + value.toString()
                + " type: "
                + value.getClass().getName());
      }
    }

    return o;
  }
 @SuppressWarnings("unused")
 private static Object acceptValueOf(
     Context cx, Scriptable thisObj, Object[] args, Function funObj) {
   return thisObj.get("value", thisObj);
 }
Exemple #29
0
 /** Return the version of jslint in use. */
 public String getEdition() {
   Scriptable lintScope = (Scriptable) scope.get("JSLINT", scope);
   return (String) lintScope.get("edition", lintScope);
 }
Exemple #30
0
  /**
   * 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;
  }