コード例 #1
0
ファイル: JavaMembers.java プロジェクト: geogebra/geogebra
 Object get(Scriptable scope, String name, Object javaObject, boolean isStatic) {
   Map<String, Object> ht = isStatic ? staticMembers : members;
   Object member = ht.get(name);
   if (!isStatic && member == null) {
     // Try to get static member from instance (LC3)
     member = staticMembers.get(name);
   }
   if (member == null) {
     member = this.getExplicitFunction(scope, name, javaObject, isStatic);
     if (member == null) return Scriptable.NOT_FOUND;
   }
   if (member instanceof Scriptable) {
     return member;
   }
   Context cx = Context.getContext();
   Object rval;
   Class<?> type;
   try {
     if (member instanceof BeanProperty) {
       BeanProperty bp = (BeanProperty) member;
       if (bp.getter == null) return Scriptable.NOT_FOUND;
       rval = bp.getter.invoke(javaObject, Context.emptyArgs);
       type = bp.getter.method().getReturnType();
     } else {
       Field field = (Field) member;
       rval = field.get(isStatic ? null : javaObject);
       type = field.getType();
     }
   } catch (Exception ex) {
     throw Context.throwAsScriptRuntimeEx(ex);
   }
   // Need to wrap the object before we return it.
   scope = ScriptableObject.getTopLevelScope(scope);
   return cx.getWrapFactory().wrap(cx, scope, rval, type);
 }
コード例 #2
0
 public Object getDefaultValue(Class<?> hint) {
   Object value;
   if (hint == null) {
     if (javaObject instanceof Boolean) {
       hint = ScriptRuntime.BooleanClass;
     }
   }
   if (hint == null || hint == ScriptRuntime.StringClass) {
     value = javaObject.toString();
   } else {
     String converterName;
     if (hint == ScriptRuntime.BooleanClass) {
       converterName = "booleanValue";
     } else if (hint == ScriptRuntime.NumberClass) {
       converterName = "doubleValue";
     } else {
       throw Context.reportRuntimeError0("msg.default.value");
     }
     Object converterObject = get(converterName, this);
     if (converterObject instanceof Function) {
       Function f = (Function) converterObject;
       value = f.call(Context.getContext(), f.getParentScope(), this, ScriptRuntime.emptyArgs);
     } else {
       if (hint == ScriptRuntime.NumberClass && javaObject instanceof Boolean) {
         boolean b = ((Boolean) javaObject).booleanValue();
         value = ScriptRuntime.wrapNumber(b ? 1.0 : 0.0);
       } else {
         value = javaObject.toString();
       }
     }
   }
   return value;
 }
コード例 #3
0
ファイル: JavaMembers.java プロジェクト: hulstores/geogebra
  void put(Scriptable scope, String name, Object javaObject, Object value, boolean isStatic) {
    Map<String, Object> ht = isStatic ? staticMembers : members;
    Object member = ht.get(name);
    if (!isStatic && member == null) {
      // Try to get static member from instance (LC3)
      member = staticMembers.get(name);
    }
    if (member == null) throw reportMemberNotFound(name);
    if (member instanceof FieldAndMethods) {
      FieldAndMethods fam = (FieldAndMethods) ht.get(name);
      member = fam.field;
    }

    // Is this a bean property "set"?
    if (member instanceof BeanProperty) {
      BeanProperty bp = (BeanProperty) member;
      if (bp.setter == null) {
        throw reportMemberNotFound(name);
      }
      // If there's only one setter or if the value is null, use the
      // main setter. Otherwise, let the NativeJavaMethod decide which
      // setter to use:
      if (bp.setters == null || value == null) {
        Class<?> setType = bp.setter.argTypes[0];
        Object[] args = {Context.jsToJava(value, setType)};
        try {
          bp.setter.invoke(javaObject, args);
        } catch (Exception ex) {
          throw Context.throwAsScriptRuntimeEx(ex);
        }
      } else {
        Object[] args = {value};
        bp.setters.call(
            Context.getContext(), ScriptableObject.getTopLevelScope(scope), scope, args);
      }
    } else {
      if (!(member instanceof Field)) {
        String str = (member == null) ? "msg.java.internal.private" : "msg.java.method.assign";
        throw Context.reportRuntimeError1(str, name);
      }
      Field field = (Field) member;
      Object javaValue = Context.jsToJava(value, field.getType());
      try {
        field.set(javaObject, javaValue);
      } catch (IllegalAccessException accessEx) {
        if ((field.getModifiers() & Modifier.FINAL) != 0) {
          // treat Java final the same as JavaScript [[READONLY]]
          return;
        }
        throw Context.throwAsScriptRuntimeEx(accessEx);
      } catch (IllegalArgumentException argEx) {
        throw Context.reportRuntimeError3(
            "msg.java.internal.field.type",
            value.getClass().getName(),
            field,
            javaObject.getClass().getName());
      }
    }
  }
コード例 #4
0
 /*
  * Save the new player name to the property file.
  */
 public void savePlayerName(String name) {
   try {
     Properties props = new Properties();
     props.load(new FileInputStream(getPropertyFile()));
     props.setProperty(_propertyNamePlayer, name);
     File f = getPropertyFile();
     OutputStream out = new FileOutputStream(f);
     props.store(out, null);
   } catch (Exception ex) {
     Context.getContext().handleException(ex);
   }
 }
コード例 #5
0
 private void saveStatistic(String propName, int value) {
   try {
     Properties props = new Properties();
     props.load(new FileInputStream(getPropertyFile()));
     props.setProperty(propName, String.valueOf(value));
     File f = getPropertyFile();
     OutputStream out = new FileOutputStream(f);
     props.store(out, null);
   } catch (Exception ex) {
     Context.getContext().handleException(ex);
   }
 }
コード例 #6
0
 /*
  * Saves the new duration for splash screens.
  */
 public void saveSplashDuration(int durationMs) {
   try {
     Properties props = new Properties();
     props.load(new FileInputStream(getPropertyFile()));
     props.setProperty(_splashDurationName, String.valueOf(durationMs));
     File f = getPropertyFile();
     OutputStream out = new FileOutputStream(f);
     props.store(out, null);
   } catch (Exception ex) {
     Context.getContext().handleException(ex);
   }
 }
コード例 #7
0
 private int loadStatistic(String propName) {
   try {
     Properties props = new Properties();
     InputStream is = null;
     File f = getPropertyFile();
     is = new FileInputStream(f);
     props.load(is);
     return Integer.parseInt(props.getProperty(propName, "0"));
   } catch (Exception ex) {
     Context.getContext().handleException(ex);
     return 0;
   }
 }
コード例 #8
0
  private File getPropertyFile() {
    File f = new File(_filename);

    // Create the file if not existing.
    if (!f.exists()) {
      try {
        f.createNewFile();
      } catch (IOException ex) {
        Context.getContext().handleException(ex);
      }
    }
    return f;
  }
コード例 #9
0
  /*
   * Delete the {@link ImmitatorBidStrategy}.
   */
  public void deleteBidStrategy(String saveNumber) {
    try {
      File f =
          new File(
              getCurrentFilePath()
                  .concat(_strategy.concat(String.valueOf(saveNumber).concat(".strategy"))));

      if (f.exists()) {
        f.delete();
      }
    } catch (Exception ex) {
      Context.getContext().handleException(ex);
    }
  }
コード例 #10
0
 /*
  * Load the player name from the property file.
  */
 public String loadPlayerName() {
   try {
     Properties props = new Properties();
     InputStream is = null;
     File f = getPropertyFile();
     is = new FileInputStream(f);
     props.load(is);
     String name = (String) props.getProperty(_propertyNamePlayer, _defaultName);
     return name;
   } catch (Exception ex) {
     Context.getContext().handleException(ex);
     return _defaultName;
   }
 }
コード例 #11
0
 /*
  * Returns the currently set duration of the splash screens.
  */
 public int loadSplashDuration() {
   try {
     Properties props = new Properties();
     InputStream is = null;
     File f = getPropertyFile();
     is = new FileInputStream(f);
     props.load(is);
     String duration = (String) props.getProperty(_splashDurationName, _defaultSplashDuration);
     int result = Integer.parseInt(duration);
     return result;
   } catch (Exception ex) {
     Context.getContext().handleException(ex);
     return Integer.parseInt(_defaultSplashDuration);
   }
 }
コード例 #12
0
 /**
  * Create {@link GeneratedClassLoader} with restrictions imposed by staticDomain and all current
  * stack frames. The method uses the SecurityController instance associated with the current
  * {@link Context} to construct proper dynamic domain and create corresponding class loader. <par>
  * If no SecurityController is associated with the current {@link Context} , the method calls
  * {@link Context#createClassLoader(ClassLoader parent)}.
  *
  * @param parent parent class loader. If null, {@link Context#getApplicationClassLoader()} will be
  *     used.
  * @param staticDomain static security domain.
  */
 public static GeneratedClassLoader createLoader(ClassLoader parent, Object staticDomain) {
   Context cx = Context.getContext();
   if (parent == null) {
     parent = cx.getApplicationClassLoader();
   }
   SecurityController sc = cx.getSecurityController();
   GeneratedClassLoader loader;
   if (sc == null) {
     loader = cx.createClassLoader(parent);
   } else {
     Object dynamicDomain = sc.getDynamicSecurityDomain(staticDomain);
     loader = sc.createClassLoader(parent, dynamicDomain);
   }
   return loader;
 }
コード例 #13
0
  /*
   * Save the {@link ImmitatorBidStrategy}.
   */
  public void saveBidStrategy(ImmitatorBettingStrategy strategy) {
    FileOutputStream fileOutputStream;

    try {
      fileOutputStream =
          new FileOutputStream(
              getCurrentFilePath()
                  .concat(_strategy.concat(strategy.getSaveNumber()).concat(".strategy")));
      ObjectOutputStream obj_out = new ObjectOutputStream(fileOutputStream);
      obj_out.writeObject(strategy);
      obj_out.flush();
      obj_out.close();
    } catch (Exception ex) {
      Context.getContext().handleException(ex);
    }
  }
コード例 #14
0
  /*
   * Load the {@link ImmitatorBidStrategy}.
   */
  public IStrategy loadBidStrategy(String saveNumber) {
    try {
      FileInputStream fileInputStream =
          new FileInputStream(
              getCurrentFilePath()
                  .concat(_strategy.concat(String.valueOf(saveNumber).concat(".strategy"))));
      Object obj = new ObjectInputStream(fileInputStream).readObject();
      fileInputStream.close();

      if (obj instanceof ImmitatorBettingStrategy) {
        return (ImmitatorBettingStrategy) obj;
      }
    } catch (Exception ex) {
      Context.getContext().handleException(ex);
    }
    return null;
  }
コード例 #15
0
ファイル: JavaMembers.java プロジェクト: hulstores/geogebra
 @Override
 public Object getDefaultValue(Class<?> hint) {
   if (hint == ScriptRuntime.FunctionClass) return this;
   Object rval;
   Class<?> type;
   try {
     rval = field.get(javaObject);
     type = field.getType();
   } catch (IllegalAccessException accEx) {
     throw Context.reportRuntimeError1("msg.java.internal.private", field.getName());
   }
   Context cx = Context.getContext();
   rval = cx.getWrapFactory().wrap(cx, this, rval, type);
   if (rval instanceof Scriptable) {
     rval = ((Scriptable) rval).getDefaultValue(hint);
   }
   return rval;
 }
コード例 #16
0
  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;
  }
コード例 #17
0
  private InterpretedFunction(InterpreterData idata, Object staticSecurityDomain) {
    this.idata = idata;

    // Always get Context from the current thread to
    // avoid security breaches via passing mangled Context instances
    // with bogus SecurityController
    Context cx = Context.getContext();
    SecurityController sc = cx.getSecurityController();
    Object dynamicDomain;
    if (sc != null) {
      dynamicDomain = sc.getDynamicSecurityDomain(staticSecurityDomain);
    } else {
      if (staticSecurityDomain != null) {
        throw new IllegalArgumentException();
      }
      dynamicDomain = null;
    }

    this.securityController = sc;
    this.securityDomain = dynamicDomain;
  }
コード例 #18
0
  /** Type-munging for field setting and method invocation. Conforms to LC3 specification */
  static Object coerceTypeImpl(Class<?> type, Object value) {
    if (value != null && value.getClass() == type) {
      return value;
    }

    switch (getJSTypeCode(value)) {
      case JSTYPE_NULL:
        // raise error if type.isPrimitive()
        if (type.isPrimitive()) {
          reportConversionError(value, type);
        }
        return null;

      case JSTYPE_UNDEFINED:
        if (type == ScriptRuntime.StringClass || type == ScriptRuntime.ObjectClass) {
          return "undefined";
        } else {
          reportConversionError("undefined", type);
        }
        break;

      case JSTYPE_BOOLEAN:
        // Under LC3, only JS Booleans can be coerced into a Boolean value
        if (type == Boolean.TYPE
            || type == ScriptRuntime.BooleanClass
            || type == ScriptRuntime.ObjectClass) {
          return value;
        } else if (type == ScriptRuntime.StringClass) {
          return value.toString();
        } else {
          reportConversionError(value, type);
        }
        break;

      case JSTYPE_NUMBER:
        if (type == ScriptRuntime.StringClass) {
          return ScriptRuntime.toString(value);
        } else if (type == ScriptRuntime.ObjectClass) {
          return coerceToNumber(Double.TYPE, value);
        } else if ((type.isPrimitive() && type != Boolean.TYPE)
            || ScriptRuntime.NumberClass.isAssignableFrom(type)) {
          return coerceToNumber(type, value);
        } else {
          reportConversionError(value, type);
        }
        break;

      case JSTYPE_STRING:
        if (type == ScriptRuntime.StringClass || type.isInstance(value)) {
          return value;
        } else if (type == Character.TYPE || type == ScriptRuntime.CharacterClass) {
          // Special case for converting a single char string to a
          // character
          // Placed here because it applies *only* to JS strings,
          // not other JS objects converted to strings
          if (((String) value).length() == 1) {
            return new Character(((String) value).charAt(0));
          } else {
            return coerceToNumber(type, value);
          }
        } else if ((type.isPrimitive() && type != Boolean.TYPE)
            || ScriptRuntime.NumberClass.isAssignableFrom(type)) {
          return coerceToNumber(type, value);
        } else {
          reportConversionError(value, type);
        }
        break;

      case JSTYPE_JAVA_CLASS:
        if (value instanceof Wrapper) {
          value = ((Wrapper) value).unwrap();
        }

        if (type == ScriptRuntime.ClassClass || type == ScriptRuntime.ObjectClass) {
          return value;
        } else if (type == ScriptRuntime.StringClass) {
          return value.toString();
        } else {
          reportConversionError(value, type);
        }
        break;

      case JSTYPE_JAVA_OBJECT:
      case JSTYPE_JAVA_ARRAY:
        if (value instanceof Wrapper) {
          value = ((Wrapper) value).unwrap();
        }
        if (type.isPrimitive()) {
          if (type == Boolean.TYPE) {
            reportConversionError(value, type);
          }
          return coerceToNumber(type, value);
        } else {
          if (type == ScriptRuntime.StringClass) {
            return value.toString();
          } else {
            if (type.isInstance(value)) {
              return value;
            } else {
              reportConversionError(value, type);
            }
          }
        }
        break;

      case JSTYPE_OBJECT:
        if (type == ScriptRuntime.StringClass) {
          return ScriptRuntime.toString(value);
        } else if (type.isPrimitive()) {
          if (type == Boolean.TYPE) {
            reportConversionError(value, type);
          }
          return coerceToNumber(type, value);
        } else if (type.isInstance(value)) {
          return value;
        } else if (type == ScriptRuntime.DateClass && value instanceof NativeDate) {
          double time = ((NativeDate) value).getJSTimeValue();
          // XXX: This will replace NaN by 0
          return new Date((long) time);
        } else if (type.isArray() && value instanceof NativeArray) {
          // Make a new java array, and coerce the JS array components
          // to the target (component) type.
          NativeArray array = (NativeArray) value;
          long length = array.getLength();
          Class<?> arrayType = type.getComponentType();
          Object Result = Array.newInstance(arrayType, (int) length);
          for (int i = 0; i < length; ++i) {
            try {
              Array.set(Result, i, coerceType(arrayType, array.get(i, array)));
            } catch (EvaluatorException ee) {
              reportConversionError(value, type);
            }
          }

          return Result;
        } else if (value instanceof Wrapper) {
          value = ((Wrapper) value).unwrap();
          if (type.isInstance(value)) return value;
          reportConversionError(value, type);
        } else if (type.isInterface() && value instanceof Callable) {
          // Try to use function as implementation of Java interface.
          //
          // XXX: Currently only instances of ScriptableObject are
          // supported since the resulting interface proxies should
          // be reused next time conversion is made and generic
          // Callable has no storage for it. Weak references can
          // address it but for now use this restriction.
          if (value instanceof ScriptableObject) {
            ScriptableObject so = (ScriptableObject) value;
            Object key = Kit.makeHashKeyFromPair(COERCED_INTERFACE_KEY, type);
            Object old = so.getAssociatedValue(key);
            if (old != null) {
              // Function was already wrapped
              return old;
            }
            Context cx = Context.getContext();
            Object glue = InterfaceAdapter.create(cx, type, (Callable) value);
            // Store for later retrival
            glue = so.associateValue(key, glue);
            return glue;
          }
          reportConversionError(value, type);
        } else {
          reportConversionError(value, type);
        }
        break;
    }

    return value;
  }
コード例 #19
0
  /**
   * @deprecated Use {@link Context#getWrapFactory()} together with calling {@link
   *     WrapFactory#wrap(Context, Scriptable, Object, Class)}
   */
  public static Object wrap(Scriptable scope, Object obj, Class<?> staticType) {

    Context cx = Context.getContext();
    return cx.getWrapFactory().wrap(cx, scope, obj, staticType);
  }