コード例 #1
0
  /**
   * ECMA 15.11.4.4 Error.prototype.toString ( )
   *
   * @param self self reference
   * @return this NativeError as a string
   */
  @Function(attributes = Attribute.NOT_ENUMERABLE)
  public static Object toString(final Object self) {
    // Step 1 and 2 : check if 'self' is object it not throw TypeError
    final ScriptObject sobj = Global.checkObject(self);

    // Step 3 & 4 : get "name" and convert to String.
    // But if message is undefined make it "Error".
    Object name = sobj.get("name");
    if (name == UNDEFINED) {
      name = "Error";
    } else {
      name = JSType.toString(name);
    }

    // Steps 5, 6, & 7 : get "message" and convert to String.
    // if 'message' is undefined make it "" (empty String).
    Object msg = sobj.get("message");
    if (msg == UNDEFINED) {
      msg = "";
    } else {
      msg = JSType.toString(msg);
    }

    // Step 8 : if name is empty, return msg
    if (((String) name).isEmpty()) {
      return msg;
    }

    // Step 9 : if message is empty, return name
    if (((String) msg).isEmpty()) {
      return name;
    }
    // Step 10 : return name + ": " + msg
    return name + ": " + msg;
  }
コード例 #2
0
 @SuppressWarnings("unused")
 private static double ensureNumber(final long arg, final int programPoint) {
   if (JSType.isRepresentableAsDouble(arg)) {
     return (double) arg;
   }
   throw new UnwarrantedOptimismException(arg, programPoint, Type.OBJECT);
 }
コード例 #3
0
 // maps staticallyProvableCallSiteType to actualCallSiteType, throws exception if impossible
 @SuppressWarnings("unused")
 private static int ensureInt(final long arg, final int programPoint) {
   if (JSType.isRepresentableAsInt(arg)) {
     return (int) arg;
   }
   throw UnwarrantedOptimismException.createNarrowest(arg, programPoint);
 }
コード例 #4
0
 @SuppressWarnings("unused")
 private static int ensureInt(final double arg, final int programPoint) {
   if (JSType.isStrictlyRepresentableAsInt(arg)) {
     return (int) arg;
   }
   throw new UnwarrantedOptimismException(arg, programPoint, Type.NUMBER);
 }
コード例 #5
0
 /**
  * Returns the argument value as a double. If the argument is not a wrapper for a primitive
  * numeric type that can be represented as double throw an {@link UnwarrantedOptimismException}.
  * This method is only public so that generated script code can use it. See {code
  * CodeGenerator.ENSURE_NUMBER}.
  *
  * @param arg the original argument.
  * @param programPoint the program point used in the exception
  * @return the value of the argument as a double.
  * @throws UnwarrantedOptimismException if the argument is not a wrapper for a primitive numeric
  *     type.
  */
 public static double ensureNumber(final Object arg, final int programPoint) {
   if (isPrimitiveNumberWrapper(arg)
       && (arg.getClass() != Long.class || JSType.isRepresentableAsDouble((Long) arg))) {
     return ((Number) arg).doubleValue();
   }
   throw new UnwarrantedOptimismException(arg, programPoint, Type.OBJECT);
 }
コード例 #6
0
 /**
  * Nashorn extension: global.input (shell-interactive-mode-only) Read one or more lines of input
  * from the standard input till the given end marker is seen in standard input.
  *
  * @param self self reference
  * @param endMarker String used as end marker for input
  * @param prompt String used as input prompt
  * @return line that was read
  * @throws IOException if an exception occurs
  */
 public static Object input(final Object self, final Object endMarker, final Object prompt)
     throws IOException {
   final String endMarkerStr = (endMarker != UNDEFINED) ? JSType.toString(endMarker) : "";
   final String promptStr = (prompt != UNDEFINED) ? JSType.toString(prompt) : ">> ";
   final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
   final StringBuilder buf = new StringBuilder();
   while (true) {
     System.out.print(promptStr);
     final String line = reader.readLine();
     if (line == null || line.equals(endMarkerStr)) {
       break;
     }
     buf.append(line);
     buf.append('\n');
   }
   return buf.toString();
 }
コード例 #7
0
 @SuppressWarnings("LeakingThisInConstructor")
 private NativeError(final Object msg, final ScriptObject proto, final PropertyMap map) {
   super(proto, map);
   if (msg != UNDEFINED) {
     this.instMessage = JSType.toString(msg);
   } else {
     this.delete(NativeError.MESSAGE, false);
   }
   initException(this);
 }
コード例 #8
0
 /**
  * Returns the argument value as an int. If the argument is not a wrapper for a primitive numeric
  * type with a value that can be exactly represented as an int, throw an {@link
  * UnwarrantedOptimismException}. This method is only public so that generated script code can use
  * it. See {code CodeGenerator.ENSURE_INT}.
  *
  * @param arg the original argument.
  * @param programPoint the program point used in the exception
  * @return the value of the argument as an int.
  * @throws UnwarrantedOptimismException if the argument is not a wrapper for a primitive numeric
  *     type with a value that can be exactly represented as an int.
  */
 public static int ensureInt(final Object arg, final int programPoint) {
   // NOTE: this doesn't delegate to ensureInt(double, int) as in that case if arg were a Long, it
   // would throw a
   // (potentially imprecise) Double in the UnwarrantedOptimismException. This way, it will put the
   // correct valued
   // Long into the exception.
   if (isPrimitiveNumberWrapper(arg)) {
     final double d = ((Number) arg).doubleValue();
     if (JSType.isStrictlyRepresentableAsInt(d)) {
       return (int) d;
     }
   }
   throw UnwarrantedOptimismException.createNarrowest(arg, programPoint);
 }
コード例 #9
0
 public String toJson(Object aObj) {
   assert writeJsonFunc != null : SCRIPT_NOT_INITIALIZED;
   if (aObj instanceof Undefined) { // nashorn JSON parser could not work with undefined.
     aObj = null;
   }
   if (aObj instanceof JSObject
       || aObj instanceof CharSequence
       || aObj instanceof Number
       || aObj instanceof Boolean
       || aObj instanceof ScriptObject
       || aObj == null) {
     return JSType.toString(writeJsonFunc.call(null, new Object[] {aObj}));
   } else {
     throw new IllegalArgumentException("Java object couldn't be converted to JSON!");
   }
 }
コード例 #10
0
ファイル: TypeEvaluator.java プロジェクト: bloodstars/OpenJDK
  private static Type getPropertyType(final ScriptObject sobj, final String name) {
    final FindProperty find = sobj.findProperty(name, true);
    if (find == null) {
      return null;
    }

    final Property property = find.getProperty();
    final Class<?> propertyClass = property.getType();
    if (propertyClass == null) {
      // propertyClass == null means its value is Undefined. It is probably not initialized yet, so
      // we won't make
      // a type assumption yet.
      return null;
    } else if (propertyClass.isPrimitive()) {
      return Type.typeFor(propertyClass);
    }

    final ScriptObject owner = find.getOwner();
    if (property.hasGetterFunction(owner)) {
      // Can have side effects, so we can't safely evaluate it; since !propertyClass.isPrimitive(),
      // it's Object.
      return Type.OBJECT;
    }

    // Safely evaluate the property, and return the narrowest type for the actual value (e.g.
    // Type.INT for a boxed
    // integer).
    final Object value =
        property.needsDeclaration()
            ? ScriptRuntime.UNDEFINED
            : property.getObjectValue(owner, owner);
    if (value == ScriptRuntime.UNDEFINED) {
      return null;
    }
    return Type.typeFor(JSType.unboxedFieldType(value));
  }
コード例 #11
0
 @Override
 public String getPropertyName() {
   return JSType.toString(getObject());
 }
コード例 #12
0
 /**
  * Fetch uint32 value of node.
  *
  * @return uint32 value of node.
  */
 public long getUint32() {
   return JSType.toUint32(value);
 }
コード例 #13
0
 /**
  * Fetch int32 value of node.
  *
  * @return Int32 value of node.
  */
 public int getInt32() {
   return JSType.toInt32(value);
 }
コード例 #14
0
 /**
  * Fetch double value of node.
  *
  * @return double value of node.
  */
 public double getNumber() {
   return JSType.toNumber(value);
 }
コード例 #15
0
 /**
  * Fetch long value of node
  *
  * @return long value of node
  */
 public long getLong() {
   return JSType.toLong(value);
 }
コード例 #16
0
  @Override
  public JSObject execute(
      Scripts.Space aSpace, Consumer<JSObject> onSuccess, Consumer<Exception> onFailure)
      throws Exception {
    assert Scripts.getSpace() == aSpace : "Scripts.Space TLS assumption failed";
    if (onSuccess != null) {
      ScriptedResource._require(
          new String[] {entityName},
          null,
          aSpace,
          new HashSet<>(),
          (Void v) -> {
            JSObject source = aSpace.createModule(entityName);
            if (source.hasMember("fetch")) {
              Object oFetch = source.getMember("fetch");
              if (oFetch instanceof JSObject) {
                JSObject jsFetch = (JSObject) oFetch;
                if (jsFetch.isFunction()) {
                  JSObject jsParams = aSpace.makeObj();
                  for (int i = 0; i < params.getParametersCount(); i++) {
                    Parameter p = params.get(i + 1);
                    jsParams.setMember(p.getName(), aSpace.toJs(p.getValue()));
                  }
                  final ExecutionChecker exChecker = new ExecutionChecker();
                  Object oRowset =
                      jsFetch.call(
                          source,
                          aSpace.toJs(
                              new Object[] {
                                jsParams,
                                new AbstractJSObject() {

                                  @Override
                                  public Object call(final Object thiz, final Object... args) {
                                    if (exChecker.isExecutionNeeded()) {
                                      try {
                                        JSObject jsRowset =
                                            args.length > 0
                                                ? (JSObject) aSpace.toJava(args[0])
                                                : null;
                                        try {
                                          onSuccess.accept(jsRowset);
                                        } catch (Exception ex) {
                                          Logger.getLogger(ScriptedQuery.class.getName())
                                              .log(Level.SEVERE, null, ex);
                                        }
                                      } catch (Exception ex) {
                                        if (onFailure != null) {
                                          onFailure.accept(ex);
                                        }
                                      }
                                    }
                                    return null;
                                  }
                                },
                                new AbstractJSObject() {

                                  @Override
                                  public Object call(final Object thiz, final Object... args) {
                                    if (exChecker.isExecutionNeeded()) {
                                      if (onFailure != null) {
                                        if (args.length > 0) {
                                          if (args[0] instanceof Exception) {
                                            onFailure.accept((Exception) args[0]);
                                          } else {
                                            onFailure.accept(
                                                new Exception(
                                                    String.valueOf(aSpace.toJava(args[0]))));
                                          }
                                        } else {
                                          onFailure.accept(
                                              new Exception(
                                                  "No error information from fetch method"));
                                        }
                                      }
                                    }
                                    return null;
                                  }
                                }
                              }));
                  if (!JSType.nullOrUndefined(oRowset)) {
                    onSuccess.accept((JSObject) aSpace.toJava(oRowset));
                    exChecker.setExecutionNeeded(false);
                  }
                }
              }
            }
          },
          onFailure);
      return null;
    } else {
      JSObject source = aSpace.createModule(entityName);
      if (source.hasMember("fetch")) {
        Object oFetch = source.getMember("fetch");
        if (oFetch instanceof JSObject) {
          JSObject jsFetch = (JSObject) oFetch;
          if (jsFetch.isFunction()) {
            JSObject jsParams = aSpace.makeObj();
            Object oRowset = jsFetch.call(source, aSpace.toJs(new Object[] {jsParams}));
            if (!JSType.nullOrUndefined(oRowset)) {
              return (JSObject) aSpace.toJava(oRowset);
            }
          }
        }
      }
      return null;
    }
  }
コード例 #17
0
 @Override
 protected void setImpl(final int key, final Object value) {
   setImpl(key, JSType.toNumber(value));
 }
コード例 #18
0
 /**
  * Fetch String value of node.
  *
  * @return String value of node.
  */
 public String getString() {
   return JSType.toString(value);
 }
コード例 #19
0
 /**
  * Fetch boolean value of node.
  *
  * @return boolean value of node.
  */
 public boolean getBoolean() {
   return JSType.toBoolean(value);
 }
コード例 #20
0
 /**
  * Check if the literal value is boolean true
  *
  * @return true if literal value is boolean true
  */
 public boolean isTrue() {
   return JSType.toBoolean(value);
 }
コード例 #21
0
 /**
  * Returns if the given object is an instance of an interface annotated with
  * java.lang.FunctionalInterface
  *
  * @param obj object to be checked
  * @return true if the obj is an instance of @FunctionalInterface interface
  */
 public static boolean isFunctionalInterfaceObject(final Object obj) {
   return !JSType.isPrimitive(obj)
       && (NashornBeansLinker.getFunctionalInterfaceMethodName(obj.getClass()) != null);
 }
コード例 #22
0
 private static String getScriptStackString(final ScriptObject sobj, final Throwable exp) {
   return JSType.toString(sobj) + "\n" + NashornException.getScriptStackString(exp);
 }