Пример #1
0
  @SuppressWarnings("unchecked")
  private void verifyExec(
      DslStep step,
      ObjectSink node,
      InternalWorkingMemory wm,
      String[] cmd,
      Map<String, Object> context)
      throws AssertionError {
    // check that the captor already exists:
    String key = getCaptorKey(node, cmd);
    ArgumentCaptor<InternalFactHandle> captor =
        (ArgumentCaptor<InternalFactHandle>) context.get(key);
    if (captor == null) {
      // create the captor
      verifyCount(step, node, wm, new String[] {"verify", cmd[1], "count", "-1"}, context);
      captor = (ArgumentCaptor<InternalFactHandle>) context.get(key);
    }

    // create a map with all captured tuples as variables
    Map<String, Object> vars = new HashMap<String, Object>();
    int i = 0;
    for (InternalFactHandle handle : captor.getAllValues()) {
      vars.put("handle" + (i++), handle);
    }
    // add all context variables, just in case
    vars.putAll(context);

    // add the static imports for hamcrest matchers
    ParserConfiguration pconf = new ParserConfiguration();
    addStaticImports(pconf, CoreMatchers.class);
    addStaticImports(pconf, JUnitMatchers.class);
    // add import for JUnit assert class
    pconf.addImport("Assert", Assert.class);

    // compile MVEL expression
    ParserContext mvelctx = new ParserContext(pconf);
    String expression = cmd[3].replaceAll("h(\\d+)", "Handles[$1]");
    try {
      Serializable compiled = MVEL.compileExpression(expression, mvelctx);
      // execute the expression
      MVEL.executeExpression(compiled, vars);
    } catch (PropertyAccessException e) {
      String message;
      if (e.getCause() instanceof InvocationTargetException) {
        message = ((InvocationTargetException) e.getCause()).getTargetException().toString();
      } else {
        message = e.getMessage();
      }

      Assert.fail(
          "[ERROR] line "
              + step.getLine()
              + " - Executing expression: '"
              + expression
              + "'\n"
              + message);
    }
  }
Пример #2
0
 private void addStaticImports(ParserConfiguration pconf, Class<?> clazz) {
   for (Method m : clazz.getMethods()) {
     if (Modifier.isStatic(m.getModifiers())) {
       pconf.addImport(m.getName(), m);
     }
   }
 }
Пример #3
0
  public void testStaticMethodsInInputsBug() {
    String text = " getList( java.util.Formatter )";

    ParserConfiguration pconf = new ParserConfiguration();
    for (Method m : CoreConfidenceTests.StaticMethods.class.getMethods()) {
      if (Modifier.isStatic(m.getModifiers())) {
        pconf.addImport(m.getName(), m);
      }
    }
    ParserContext pctx = new ParserContext(pconf);
    pctx.setStrictTypeEnforcement(false);
    pctx.setStrongTyping(false);

    Map<String, Object> vars = new HashMap<String, Object>();

    Serializable expr = MVEL.compileExpression(text, pctx);
    List list = (List) MVEL.executeExpression(expr, null, vars);
    assertEquals(Formatter.class, list.get(0));

    assertEquals(0, pctx.getInputs().size());
  }
Пример #4
0
  public void testStaticMethodCallThrowsException() {
    String text = " ( throwException( ) ) ";

    ParserConfiguration pconf = new ParserConfiguration();
    for (Method m : CoreConfidenceTests.StaticMethods.class.getMethods()) {
      if (Modifier.isStatic(m.getModifiers())) {
        pconf.addImport(m.getName(), m);
      }
    }
    ParserContext pctx = new ParserContext(pconf);
    pctx.setStrictTypeEnforcement(true);
    pctx.setStrongTyping(true);

    Map<String, Object> vars = new HashMap<String, Object>();
    Serializable expr = MVEL.compileExpression(text, pctx);
    try {
      MVEL.executeExpression(expr);
      fail("this should throw an exception");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #5
0
  public static Object eval(String str, Map<String, Object> vars) {
    ParserConfiguration pconf = new ParserConfiguration();
    pconf.addPackageImport("org.kie.internal.task.api.model");
    pconf.addPackageImport("org.jbpm.services.task");
    pconf.addPackageImport("org.jbpm.services.task.impl.model");
    pconf.addPackageImport("org.jbpm.services.task.query");
    pconf.addPackageImport("org.jbpm.services.task.internals.lifecycle");

    pconf.addImport(Status.class);
    pconf.addImport(Allowed.class);
    pconf.addPackageImport("java.util");

    ParserContext context = new ParserContext(pconf);
    Serializable s = MVEL.compileExpression(str.trim(), context);

    if (vars != null) {
      return MVELSafeHelper.getEvaluator().executeExpression(s, vars);
    } else {
      return MVELSafeHelper.getEvaluator().executeExpression(s);
    }
  }
Пример #6
0
  /**
   * Analyze an expression.
   *
   * @param expr The expression to analyze.
   * @param availDecls Total set of declarations available.
   * @return The <code>Set</code> of declarations used by the expression.
   * @throws RecognitionException If an error occurs in the parser.
   */
  public MVELAnalysisResult analyzeExpression(
      final PackageBuildContext context,
      final String expr,
      final BoundIdentifiers availableIdentifiers,
      final Map<String, Class<?>> localTypes) {
    MVELAnalysisResult result = null;
    if (expr.trim().length() > 0) {
      MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;
      MVELDialect dialect = (MVELDialect) context.getDialect("mvel");

      // creating a reusable parser configuration
      ParserConfiguration conf = new ParserConfiguration();
      conf.setImports(dialect.getImports());
      conf.setPackageImports((HashSet) dialect.getPackgeImports());

      conf.setClassLoader(context.getPackageBuilder().getRootClassLoader());

      // first compilation is for verification only
      // @todo proper source file name
      final ParserContext parserContext1 = new ParserContext(conf);
      if (localTypes != null) {
        for (Entry entry : localTypes.entrySet()) {
          parserContext1.addInput((String) entry.getKey(), (Class) entry.getValue());
        }
      }
      if (availableIdentifiers.getThisClass() != null) {
        parserContext1.addInput("this", availableIdentifiers.getThisClass());
      }

      parserContext1.setStrictTypeEnforcement(false);
      parserContext1.setStrongTyping(false);
      parserContext1.setInterceptors(dialect.getInterceptors());
      Class returnType = null;

      try {
        returnType = MVEL.analyze(expr, parserContext1);
      } catch (Exception e) {
        context
            .getErrors()
            .add(
                new DescrBuildError(
                    context.getParentDescr(),
                    null,
                    null,
                    "Unable to Analyse Expression " + expr + ":\n" + e.getMessage()));
        return null;
      }

      Set<String> requiredInputs = new HashSet();
      requiredInputs.addAll(parserContext1.getInputs().keySet());
      HashMap<String, Class<?>> variables =
          (HashMap<String, Class<?>>) ((Map) parserContext1.getVariables());

      // MVEL includes direct fields of context object in non-strict mode. so we need to strip those
      if (availableIdentifiers.getThisClass() != null) {
        for (Iterator<String> it = requiredInputs.iterator(); it.hasNext(); ) {
          if (PropertyTools.getFieldOrAccessor(availableIdentifiers.getThisClass(), it.next())
              != null) {
            it.remove();
          }
        }
      }

      // now, set the required input types and compile again
      final ParserContext parserContext2 = new ParserContext(conf);
      parserContext2.setStrictTypeEnforcement(true);
      parserContext2.setStrongTyping(true);
      parserContext2.setInterceptors(dialect.getInterceptors());

      if (context.isTypesafe()) {
        if (localTypes != null) {
          for (Entry<String, Class<?>> entry : localTypes.entrySet()) {
            parserContext2.addInput(entry.getKey(), entry.getValue());
          }
        }

        for (String str : requiredInputs) {
          Class cls = availableIdentifiers.getDeclarations().get(str);
          if (cls != null) {
            parserContext2.addInput(str, cls);
            continue;
          }

          if (cls == null) {
            cls = availableIdentifiers.getGlobals().get(str);
            if (cls != null) {
              parserContext2.addInput(str, cls);
              continue;
            }
          }

          if (cls == null) {
            if (str.equals("drools")) {
              parserContext2.addInput("drools", KnowledgeHelper.class);
            } else if (str.equals("kcontext")) {
              parserContext2.addInput("kcontext", RuleContext.class);
            }
            if (str.equals("rule")) {
              parserContext2.addInput("rule", Rule.class);
            }
          }
        }

        if (availableIdentifiers.getThisClass() != null) {
          parserContext2.addInput("this", availableIdentifiers.getThisClass());
        }

        try {
          returnType = MVEL.analyze(expr, parserContext2);
        } catch (Exception e) {
          context
              .getErrors()
              .add(
                  new DescrBuildError(
                      context.getParentDescr(),
                      null,
                      null,
                      "Unable to Analyse Expression " + expr + ":\n" + e.getMessage()));
          return null;
        }

        requiredInputs = new HashSet();
        requiredInputs.addAll(parserContext2.getInputs().keySet());
        requiredInputs.addAll(variables.keySet());
        variables = (HashMap<String, Class<?>>) ((Map) parserContext2.getVariables());
      }

      result = analyze(requiredInputs, availableIdentifiers);

      result.setReturnType(returnType);

      result.setMvelVariables(variables);
    } else {
      result = analyze((Set<String>) Collections.EMPTY_SET, availableIdentifiers);
      result.setMvelVariables(new HashMap<String, Class<?>>());
    }
    return result;
  }