Ejemplo n.º 1
0
  private ValueSource getDistanceValueSource() {
    Expression distance;
    try {
      distance =
          JavascriptCompiler.compile(
              "haversin(" + ORIGIN_LATITUDE + "," + ORIGIN_LONGITUDE + ",latitude,longitude)");
    } catch (ParseException pe) {
      // Should not happen
      throw new RuntimeException(pe);
    }
    SimpleBindings bindings = new SimpleBindings();
    bindings.add(new SortField("latitude", SortField.Type.DOUBLE));
    bindings.add(new SortField("longitude", SortField.Type.DOUBLE));

    return distance.getValueSource(bindings);
  }
  // series of unit test for using expressions as executable scripts
  public void testExecutableScripts() throws Exception {
    Map<String, Object> vars = new HashMap<>();
    vars.put("a", 2.5);
    vars.put("b", 3);
    vars.put("xyz", -1);

    Expression expr = JavascriptCompiler.compile("a+b+xyz");
    CompiledScript compiledScript = new CompiledScript(ScriptType.INLINE, "", "expression", expr);

    ExpressionExecutableScript ees = new ExpressionExecutableScript(compiledScript, vars);
    assertEquals((Double) ees.run(), 4.5, 0.001);

    ees.setNextVar("b", -2.5);
    assertEquals((Double) ees.run(), -1, 0.001);

    ees.setNextVar("a", -2.5);
    ees.setNextVar("b", -2.5);
    ees.setNextVar("xyz", -2.5);
    assertEquals((Double) ees.run(), -7.5, 0.001);

    String message;

    try {
      vars = new HashMap<>();
      vars.put("a", 1);
      ees = new ExpressionExecutableScript(compiledScript, vars);
      ees.run();
      fail("An incorrect number of variables were allowed to be used in an expression.");
    } catch (ScriptException se) {
      message = se.getMessage();
      assertThat(
          message + " should have contained number of variables",
          message.contains("number of variables"),
          equalTo(true));
    }

    try {
      vars = new HashMap<>();
      vars.put("a", 1);
      vars.put("b", 3);
      vars.put("c", -1);
      ees = new ExpressionExecutableScript(compiledScript, vars);
      ees.run();
      fail("A variable was allowed to be set that does not exist in the expression.");
    } catch (ScriptException se) {
      message = se.getMessage();
      assertThat(
          message + " should have contained does not exist in",
          message.contains("does not exist in"),
          equalTo(true));
    }

    try {
      vars = new HashMap<>();
      vars.put("a", 1);
      vars.put("b", 3);
      vars.put("xyz", "hello");
      ees = new ExpressionExecutableScript(compiledScript, vars);
      ees.run();
      fail("A non-number was allowed to be use in the expression.");
    } catch (ScriptException se) {
      message = se.getMessage();
      assertThat(
          message + " should have contained process numbers",
          message.contains("process numbers"),
          equalTo(true));
    }
  }