コード例 #1
0
  static void nashornCompiledScriptReturningFunction(String code, String library)
      throws ScriptException, NoSuchMethodException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("nashorn");

    ScriptContext libraryContext = new SimpleScriptContext();
    ScriptContext privateContext = new SimpleScriptContext();

    ScriptObjectMirror errorFunc =
        (ScriptObjectMirror) ((Compilable) engine).compile(library).eval(libraryContext);
    ScriptObjectMirror func =
        (ScriptObjectMirror) ((Compilable) engine).compile(code).eval(privateContext);
    Object result = null;

    long total = 0;
    for (int i = 0; i < RUNS; ++i) {
      long start = System.nanoTime();
      for (int j = 0; j < BATCH; ++j) {
        result = func.call(null, "12345678", errorFunc);
      }
      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 " + result.toString());
  }
コード例 #2
0
  @SuppressWarnings("unchecked")
  public CustomType customClassValue(Object jsNode) {

    try {
      List<UserClassData> classesList = new ArrayList<UserClassData>();
      Bindings bindings = this.getBindings();
      bindings.put("node", jsNode);
      bindings.put("env", this.wrapper);
      bindings.put("pkg", ModelRegistry.getInstance().rootPackage());
      ScriptObjectMirror svData =
          (ScriptObjectMirror) engine.eval("env.generateClasses(node.value(),pkg)", bindings);
      String jsonData = null;
      String valueName = null;
      if (svData != null) {
        jsonData = svData.get("data").toString();
        valueName = svData.get("valueName").toString();
        ScriptObjectMirror classes = (ScriptObjectMirror) svData.get("classes");
        for (Object obj : classes.values()) {
          ScriptObjectMirror cls = (ScriptObjectMirror) obj;
          String classContent = cls.get("content").toString();
          String qName = cls.get("qualifiedName").toString();
          String sName = cls.get("simpleName").toString();
          classesList.add(new UserClassData(qName, sName, classContent));
        }
      }
      String sName = classesList.get(0).getSimpleName();
      String qName = classesList.get(0).getQualifiedName();

      Class<? extends CustomType> customClass = loadCustomClassFromLibrary(sName);
      if (customClass == null) {
        setClassLoaderParams(classesList);
        Class<?> c = customClassLoader.loadClass(qName);
        if (c != null && CustomType.class.isAssignableFrom(c)) {
          customClass = (Class<? extends CustomType>) c;
        }
      }
      if (customClass != null) {
        CustomType result =
            unmarshalCustomType(jsonData, (Class<? extends CustomType>) customClass);
        result.setRAMLValueName(valueName);
        return result;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    CustomType customType = new CustomType();
    customType.setFactory(this);
    return customType;
  }
コード例 #3
0
    @Override
    public DataPoint next() {
      DataPoint dp = m_innerDataPointGroup.next();

      try {

        ScriptObjectMirror mirror =
            (ScriptObjectMirror)
                invocable.invokeFunction("fx", dp.getTimestamp(), dp.getDoubleValue());
        dp =
            m_dataPointFactory.createDataPoint(
                Long.valueOf(mirror.getMember("timestamp").toString()),
                (Double) mirror.getMember("value"));

      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      return (dp);
    }
コード例 #4
0
ファイル: JavaScriptUtil.java プロジェクト: hugheaves/java0
  private static Object convertValueRecursive(
      final List<String> stack,
      final String currentLevel,
      final Object value,
      final boolean allowNulls) {

    stack.add(currentLevel);

    Object converted = value;

    if (value == null) {
      logger.debug("{} converting Null value", stack);
      if (!allowNulls) {
        throw new NullPointerException("Null value not allowed @ " + stack.toString());
      }
    } else if (ScriptObjectMirror.isUndefined(value)) {
      logger.debug("{} converting Undefined value", stack);
      if (!allowNulls) {
        throw new NullPointerException("Undefined value not allowed @ " + stack.toString());
      }
      converted = null;
    } else if (value instanceof Number) {
      logger.debug("{} converting Number", stack);
      final Number num = (Number) value;
      if (num.longValue() == num.doubleValue()) {
        converted = num.longValue();
      }
    } else if (value instanceof String) {
      logger.debug("{} converting String", stack);
    } else if (value instanceof Boolean) {
      logger.debug("{} converting Boolean", stack);
    } else if (value instanceof ScriptObjectMirror) {
      final ScriptObjectMirror som = (ScriptObjectMirror) value;
      if (som.isFunction()) {
        throw new UncheckedException("JavaScript functions cannot be converted");
      } else if (som.isArray()) {
        logger.debug("{} converting array", stack);
        final List<Object> list = new ArrayList<>();
        for (int i = 0; i < som.size(); ++i) {
          logger.debug("{} converting array entry {}", stack, i);
          list.add(convertValueRecursive(stack, "array entry " + i, som.getSlot(i), allowNulls));
        }
        converted = list;
      } else {
        logger.debug("{} converting map", stack);
        final Map<String, Object> map = new HashMap<>();
        for (final Entry<String, Object> entry : som.entrySet()) {
          logger.debug("{} converting map entry {}", stack, entry.getKey());
          map.put(
              entry.getKey(),
              convertValueRecursive(
                  stack, "map entry " + entry.getKey(), entry.getValue(), allowNulls));
        }
        converted = map;
      }
    } else {
      throw new UncheckedException("unrecognized type: " + value.getClass().getName());
    }

    if (converted == null) {
      logger.debug("{} converted value = null", stack);
    } else {
      logger.debug(
          "{} converted type = {}, value = {}",
          stack,
          converted.getClass().getName(),
          converted.toString());
    }

    stack.remove(stack.size() - 1);

    return converted;
  }
コード例 #5
0
ファイル: Nashorn2.java プロジェクト: zzragida/JavaExamples
 public static void fun4(ScriptObjectMirror person) {
   System.out.println("Full Name is: " + person.callMember("getFullName"));
 }
コード例 #6
0
ファイル: Nashorn2.java プロジェクト: zzragida/JavaExamples
 public static void fun3(ScriptObjectMirror mirror) {
   System.out.println(mirror.getClassName() + ": " + Arrays.toString(mirror.getOwnKeys(true)));
 }