static void nashornInvokeMethod(String code) throws ScriptException, NoSuchMethodException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("nashorn");

    engine.eval(code);
    Invocable inv = (Invocable) engine;
    JSObject propertiesDict = (JSObject) engine.get("properties");

    Object result = null;
    Object property;
    long total = 0;
    for (int i = 0; i < RUNS; ++i) {
      long start = System.nanoTime();
      for (int j = 0; j < BATCH; ++j) {
        property = propertiesDict.getMember("ssn");
        result = inv.invokeMethod(property, "clean", "12345678");
      }
      long stop = System.nanoTime();
      System.out.println(
          "Run "
              + (i * BATCH + 1)
              + "-"
              + ((i + 1) * BATCH)
              + ": "
              + Math.round((stop - start) / BATCH / 1000)
              + " us");
      total += (stop - start);
    }
    System.out.println("Average run: " + Math.round(total / RUNS / BATCH / 1000) + " us");
    System.out.println(
        "Data is " + ((Invocable) engine).invokeMethod(result, "toString").toString());
  }
 public JSObject createModule(String aModuleName) {
   assert lookupInGlobalFunc != null : SCRIPT_NOT_INITIALIZED;
   Object oConstructor = lookupInGlobalFunc.call(null, new Object[] {aModuleName});
   if (oConstructor instanceof JSObject && ((JSObject) oConstructor).isFunction()) {
     JSObject jsConstructor = (JSObject) oConstructor;
     return (JSObject) jsConstructor.newObject(new Object[] {});
   } else {
     return null;
   }
 }
 public JSObject collectionPropertyDefinition(
     JSObject sourceEntity, String targetFieldName, String sourceFieldName) {
   assert collectionDefFunc != null : SCRIPT_NOT_INITIALIZED;
   return (JSObject)
       collectionDefFunc.newObject(
           new Object[] {sourceEntity, targetFieldName, sourceFieldName});
 }
Beispiel #4
0
 public static ImageIcon load(
     String aResourceName, String aCalledFromFile, JSObject onSuccess, JSObject onFailure)
     throws Exception {
   Scripts.Space space = Scripts.getSpace();
   return load(
       aResourceName,
       aCalledFromFile,
       space,
       onSuccess != null
           ? (ImageIcon aLoaded) -> {
             onSuccess.call(null, new Object[] {aLoaded});
           }
           : null,
       onSuccess != null
           ? (Exception ex) -> {
             onFailure.call(null, new Object[] {space.toJs(ex.getMessage())});
           }
           : null);
 }
 public Object toJs(Object aValue) {
   if (aValue
       instanceof Date) { // force js boxing of date, because of absence js literal of date value
     assert toDateFunc != null : SCRIPT_NOT_INITIALIZED;
     return toDateFunc.call(null, aValue);
   } else if (aValue instanceof HasPublished) {
     return ((HasPublished) aValue).getPublished();
   } else {
     return aValue;
   }
 }
 public Object toJava(Object aValue) {
   if (aValue instanceof ScriptObject) {
     aValue = ScriptUtils.wrap((ScriptObject) aValue);
   }
   if (aValue instanceof JSObject) {
     assert toPrimitiveFunc != null : SCRIPT_NOT_INITIALIZED;
     aValue = toPrimitiveFunc.call(null, new Object[] {aValue});
   } else if (aValue == ScriptRuntime.UNDEFINED) {
     return null;
   }
   return aValue;
 }
  @Test
  public void newValue_function() {
    final JSObject obj = Mockito.mock(JSObject.class);
    Mockito.when(obj.isFunction()).thenReturn(true);

    final ScriptValue value = this.factory.newValue(obj);

    assertNotNull(value);
    assertEquals(false, value.isArray());
    assertEquals(true, value.isFunction());
    assertEquals(false, value.isObject());
    assertEquals(false, value.isValue());

    assertNonValue(value);
    assertNonArray(value);
    assertNonObject(value);

    Mockito.when(this.invoker.invoke(Mockito.same(obj), Mockito.any())).thenReturn("a+b");

    final ScriptValue result = value.call("a", "b");
    assertNotNull(result);
    assertEquals(true, result.isValue());
    assertEquals("a+b", result.getValue());
  }
 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!");
   }
 }
    public Object makeCopy(Object aSource) {
      assert copyObjectFunc != null : SCRIPT_NOT_INITIALIZED;
      Wrapper w = new Wrapper();
      copyObjectFunc.call(
          null,
          new Object[] {
            aSource,
            new AbstractJSObject() {

              @Override
              public Object call(Object thiz, Object... args) {
                w.value = args.length > 0 ? args[0] : null;
                return null;
              }
            }
          });
      return w.value;
    }
 public void schedule(JSObject aJsTask, long aTimeout) {
   Scripts.LocalContext context = Scripts.getContext();
   bio.submit(
       () -> {
         try {
           Thread.sleep(aTimeout);
           Scripts.setContext(context);
           try {
             process(
                 () -> {
                   aJsTask.call(null, new Object[] {});
                 });
           } finally {
             Scripts.setContext(null);
           }
         } catch (InterruptedException ex) {
           Logger.getLogger(Scripts.class.getName()).log(Level.SEVERE, null, ex);
         }
       });
 }
 public JSObject readJsArray(Collection<Map<String, Object>> aCollection) {
   JSObject result = makeArray();
   JSObject jsPush = (JSObject) result.getMember("push");
   aCollection.forEach(
       (Map<String, Object> aItem) -> {
         JSObject jsItem = makeObj();
         aItem
             .entrySet()
             .forEach(
                 (Map.Entry<String, Object> aItemContent) -> {
                   jsItem.setMember(aItemContent.getKey(), toJs(aItemContent.getValue()));
                 });
         jsPush.call(result, new Object[] {jsItem});
       });
   return result;
 }
 public void enqueue(JSObject aJsTask) {
   process(
       () -> {
         aJsTask.call(null, new Object[] {});
       });
 }
 public void putInGlobal(String aName, JSObject aValue) {
   assert putInGlobalFunc != null : SCRIPT_NOT_INITIALIZED;
   putInGlobalFunc.call(null, new Object[] {aName, aValue});
 }
 public JSObject lookupInGlobal(String aName) {
   assert lookupInGlobalFunc != null : SCRIPT_NOT_INITIALIZED;
   Object res = lookupInGlobalFunc.call(null, new Object[] {aName});
   return res instanceof JSObject ? (JSObject) res : null;
 }
 public JSObject listenElements(JSObject aTarget, JSObject aCallback) {
   assert listenElementsFunc != null : SCRIPT_NOT_INITIALIZED;
   Object oResult = listenElementsFunc.call(null, new Object[] {aTarget, aCallback});
   return (JSObject) oResult;
 }
 public JSObject makeArray() {
   assert makeArrayFunc != null : SCRIPT_NOT_INITIALIZED;
   Object oResult = makeArrayFunc.call(null, new Object[] {});
   return (JSObject) oResult;
 }
Beispiel #17
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;
    }
  }
 public JSObject scalarPropertyDefinition(
     JSObject targetEntity, String targetFieldName, String sourceFieldName) {
   assert scalarDefFunc != null : SCRIPT_NOT_INITIALIZED;
   return (JSObject)
       scalarDefFunc.newObject(new Object[] {targetEntity, targetFieldName, sourceFieldName});
 }
 public void extend(JSObject aChild, JSObject aParent) {
   assert extendFunc != null : SCRIPT_NOT_INITIALIZED;
   extendFunc.call(null, new Object[] {aChild, aParent});
 }
 public Object parseJsonWithDates(String json) {
   assert parseJsonWithDatesFunc != null : SCRIPT_NOT_INITIALIZED;
   return parseJsonWithDatesFunc.call(null, new Object[] {json});
 }
 public static void unlisten(JSObject aCookie) {
   JSObject unlisten = (JSObject) aCookie.getMember("unlisten");
   unlisten.call(null, new Object[] {});
 }
 public boolean isArrayDeep(JSObject aInstance) {
   assert isArrayFunc != null : SCRIPT_NOT_INITIALIZED;
   Object oResult = isArrayFunc.call(null, new Object[] {aInstance});
   return Boolean.TRUE.equals(oResult);
 }