public void testGenerics1() {
    String str =
        "addresses[0] == new Address(\"s1\") && addresses[0].street == new Address(\"s1\").street";

    ParserConfiguration pconf = new ParserConfiguration();
    ParserContext pctx = new ParserContext(pconf);
    pctx.setStrongTyping(true);
    pctx.addInput("this", PersonAddresses.class);
    pctx.addImport(Address.class);
    pctx.addImport(PersonAddresses.class);
    ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(str, pctx);
    PersonAddresses ctx = new PersonAddresses();
    ctx.getAddresses().add(new Address("s1"));
    Boolean result = (Boolean) MVEL.executeExpression(stmt, ctx);
    assertTrue(result);
  }
  @Test
  public void testDebugSymbolCount() {
    String expr =
        "System.out.println( \"a1\" );\n"
            + "System.out.println( \"a2\" );\n"
            + "System.out.println( \"a3\" );\n"
            + "System.out.println( \"a4\" );\n";

    ExpressionCompiler compiler = new ExpressionCompiler(expr);

    ParserContext context = new ParserContext();
    context.setDebugSymbols(true);
    context.addImport("System", System.class);
    context.setStrictTypeEnforcement(true);
    // context.setDebugSymbols( true );
    context.setSourceFile("mysource");

    Serializable compiledExpression = compiler.compile(context);

    String s = DebugTools.decompile(compiledExpression);

    System.out.println("s " + s);

    int fromIndex = 0;
    int count = 0;
    while ((fromIndex = s.indexOf("DEBUG_SYMBOL", fromIndex + 1)) > -1) {
      count++;
    }
    assertEquals(4, count);
  }
Beispiel #3
0
  static {
    // Initialize MVEL.

    // The dynamic optimizer crashes for some reason, so we use the "safe reflective" one.
    // Although "safe" sounds slower, this optimizer actually seems *faster*
    // than the dynamic one. Don't change this unless you want to go digging for weird
    // reflective constructor errors.
    OptimizerFactory.setDefaultOptimizer(OptimizerFactory.SAFE_REFLECTIVE);

    // Add "built-in" methods to the expression context.
    parserContext = new ParserContext();
    try {
      // MVEL has a bug where it accepts methods with varargs, but only executes the method with
      // non-varargs. So in our ExpressionHelper we have both the varargs and non-varargs methods.
      // We lookup the varargs version here, but only the non-varargs will get called.
      parserContext.addImport(
          "random", ExpressionHelper.class.getMethod("random", long.class, double[].class));
      parserContext.addImport(
          "randint", ExpressionHelper.class.getMethod("randint", long.class, int.class, int.class));
      parserContext.addImport("color", ExpressionHelper.class.getMethod("color", double[].class));
      parserContext.addImport(
          "stamp", ExpressionHelper.class.getMethod("stamp", String.class, Object.class));
      parserContext.addImport("int", ExpressionHelper.class.getMethod("toInt", double.class));
      parserContext.addImport("float", ExpressionHelper.class.getMethod("toFloat", int.class));
      parserContext.addImport("math", Math.class);
    } catch (NoSuchMethodException e) {
      throw new AssertionError("Unknown static method for expression." + e);
    }
  }
  public void testStrictStaticMethodCall() {
    ExpressionCompiler compiler = new ExpressionCompiler("Bar.staticMethod()");
    ParserContext ctx = new ParserContext();
    ctx.addImport("Bar", Bar.class);
    ctx.setStrictTypeEnforcement(true);

    Serializable s = compiler.compile(ctx);

    assertEquals(1, executeExpression(s));
  }
  public void testStrictTypingCompilation4() throws NoSuchMethodException {
    ParserContext ctx = new ParserContext();

    ctx.addImport(Foo.class);
    ctx.setStrictTypeEnforcement(true);

    ExpressionCompiler compiler = new ExpressionCompiler("x_a = new Foo()");

    compiler.compile(ctx);

    assertEquals(Foo.class, ctx.getVariables().get("x_a"));
  }
Beispiel #6
0
  public void lispFormHandler(LispForm lispForm) {
    StringBuilderAppendable appendable = new StringBuilderAppendable();
    FunctionHandlers.dump(lispForm, appendable, true);

    ClassLoader tempClassLoader = Thread.currentThread().getContextClassLoader();
    try {
      Thread.currentThread()
          .setContextClassLoader(((InternalRuleBase) ruleBase).getRootClassLoader());

      ParserContext context = new ParserContext();

      String namespace = this.session.getAgenda().getFocusName();

      Package pkg = this.ruleBase.getPackage(namespace);
      if (pkg == null) {
        this.packageBuilder.addPackage(createPackageDescr(namespace));
        pkg = this.ruleBase.getPackage(namespace);
      }

      if (pkg != null) {
        // only time this will be null is if we have yet to do any packagedescr work
        try {

          for (Iterator it = pkg.getImports().entrySet().iterator(); it.hasNext(); ) {
            Entry entry = (Entry) it.next();
            String importName = ((ImportDeclaration) entry.getValue()).getTarget();
            if (importName.endsWith("*")) {
              context.addPackageImport(importName.substring(0, importName.length() - 2));
            } else {

              Class cls = ((InternalRuleBase) ruleBase).getRootClassLoader().loadClass(importName);
              context.addImport(cls.getSimpleName(), (Class) cls);
            }
          }

        } catch (Exception e) {
          e.printStackTrace();
        }

        MVELDialectRuntimeData data =
            (MVELDialectRuntimeData) pkg.getDialectRuntimeRegistry().getDialectData("clips");
        this.factory.setNextFactory(data.getFunctionFactory());
      }

      ExpressionCompiler expr = new ExpressionCompiler(appendable.toString());
      Serializable executable = expr.compile(context);

      MVEL.executeExpression(executable, this, this.factory);
    } finally {
      Thread.currentThread().setContextClassLoader(tempClassLoader);
    }
  }
  public void testStrictStrongTypingCompilationErrors2() throws Exception {
    ParserContext ctx = new ParserContext();
    ctx.setStrictTypeEnforcement(true);
    ctx.setStrongTyping(true);
    ctx.addImport(Foo.class);
    ctx.addInput("$bar", Bar.class);

    try {
      MVEL.compileExpression("x_a = new Foo244( $ba ); x_a.equals($ba);", ctx);
      fail("This should not compileShared");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void testDetermineRequiredInputsInConstructor() throws Exception {
    ParserContext ctx = new ParserContext();
    ctx.setStrictTypeEnforcement(false);
    ctx.setStrongTyping(false);
    ctx.addImport(Foo.class);

    ExpressionCompiler compiler = new ExpressionCompiler("new Foo244( $bar,  $bar.age );");

    Serializable compiled = compiler.compile(ctx);

    Set<String> requiredInputs = compiler.getParserContextState().getInputs().keySet();
    assertEquals(1, requiredInputs.size());
    assertTrue(requiredInputs.contains("$bar"));
  }
  public void testMapPropertyAccess() {
    ParserContext ctx = new ParserContext();
    ctx.addImport(MapWrapper.class);
    ctx.addInput("wrapper", MapWrapper.class);
    ctx.setStrongTyping(true);

    Serializable expr = MVEL.compileExpression("wrapper.map[\"key\"]", ctx);

    MapWrapper wrapper = new MapWrapper();
    wrapper.getMap().put("key", "value");
    Map vars = new HashMap();
    vars.put("wrapper", wrapper);

    assertEquals("value", MVEL.executeExpression(expr, vars));
  }
  public void testStrictStrongTypingCompilationErrors1() throws Exception {
    ParserContext ctx = new ParserContext();
    ctx.setStrictTypeEnforcement(true);
    ctx.setStrongTyping(true);
    ctx.addImport(Foo.class);
    ctx.addInput("$bar", Bar.class);

    try {
      ExpressionCompiler compiler = new ExpressionCompiler("System.out.println( $ba );");

      compiler.compile(ctx);
      fail("This should not compileShared");
    } catch (Exception e) {
    }
  }
  public void testStrictTypingCompilation2() throws Exception {
    ParserContext ctx = new ParserContext();
    //noinspection RedundantArrayCreation
    ctx.addImport(
        "getRuntime", new MethodStub(Runtime.class.getMethod("getRuntime", new Class[] {})));

    ctx.setStrictTypeEnforcement(true);

    ExpressionCompiler compiler = new ExpressionCompiler("getRuntime()");
    StaticMethodImportResolverFactory si = new StaticMethodImportResolverFactory(ctx);

    Serializable expression = compiler.compile(ctx);

    serializationTest(expression);

    assertTrue(executeExpression(expression, si) instanceof Runtime);
  }
  public void testMVEL236() {
    StringBuffer buffer = new StringBuffer();

    buffer.append("MyInterface2 var2 = (MyInterface2)var1;");

    ParserContext ctx = new ParserContext();
    ctx.setStrongTyping(true);
    ctx.addInput("var1", MyInterface3.class);
    ctx.addImport(MyInterface2.class);
    ctx.addImport(MyInterface3.class);

    try {
      CompiledExpression compiled =
          (CompiledExpression) MVEL.compileExpression(buffer.toString(), ctx);
    } catch (Exception e) {
      fail(e.getMessage());
    }
  }
  /**
   * Having a parser context that imports the classes speeds MVEL by up to 60%.
   *
   * @return
   */
  protected ParserContext getParserContext() {
    if (parserContext == null) {
      parserContext = new ParserContext();
      parserContext.addImport("MVEL", MVEL.class);
      /*  Getting errors when the following is in place.
      for (String key : contextClassNames.keySet()) {
           String className = contextClassNames.get(key);
           try {
               Class c = Class.forName(className);
               parserContext.addImport(key, c);
           } catch (ClassNotFoundException e) {
               LOG.error("Error resolving classname while setting up MVEL context, rule processing based on the key " + key + " will not be optimized", e);
           }

       }  */
    }
    return parserContext;
  }
  public void testDataConverterStrictMode() throws Exception {
    OptimizerFactory.setDefaultOptimizer("ASM");

    DataConversion.addConversionHandler(Date.class, new MVELDateCoercion());

    ParserContext ctx = new ParserContext();
    ctx.addImport("Cheese", Cheese.class);
    ctx.setStrongTyping(true);
    ctx.setStrictTypeEnforcement(true);

    Locale.setDefault(Locale.US);

    Cheese expectedCheese = new Cheese();
    expectedCheese.setUseBy(new SimpleDateFormat("dd-MMM-yyyy").parse("10-Jul-1974"));

    ExpressionCompiler compiler =
        new ExpressionCompiler("c = new Cheese(); c.useBy = '10-Jul-1974'; return c");
    Cheese actualCheese = (Cheese) executeExpression(compiler.compile(ctx), createTestMap());
    assertEquals(expectedCheese.getUseBy(), actualCheese.getUseBy());
  }
  public void testStrictTypingCompilationWithVarInsideConstructor() {
    ParserContext ctx = new ParserContext();
    ctx.addInput("$likes", String.class);
    ctx.addInput("results", List.class);
    ctx.addImport(Cheese.class);
    ctx.setStrongTyping(true);

    Serializable expr = null;
    try {
      expr =
          MVEL.compileExpression("Cheese c = new Cheese( $likes, 15 );\nresults.add( c ); ", ctx);
    } catch (CompileException e) {
      e.printStackTrace();
      fail("This should not fail:\n" + e.getMessage());
    }
    List results = new ArrayList();

    Map vars = new HashMap();
    vars.put("$likes", "stilton");
    vars.put("results", results);
    executeExpression(expr, vars);

    assertEquals(new Cheese("stilton", 15), results.get(0));
  }