Java org.mvel2.MVEL 代码实例

・14 分钟阅读

以下是展示如何使用org.mvel2.MVEL的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


public Object evaluate(ProcessContext context) throws Exception {
    DroolsMVELFactory factory = (DroolsMVELFactory) this.prototype.clone();
    factory.addResolver("context", new SimpleValueResolver(context));
    factory.addResolver("kcontext", new SimpleValueResolver(context));
    if (variableNames != null) {
        for (String variableName: variableNames) {
                factory.addResolver(
                                variableName, new SimpleValueResolver(context.getVariable(variableName)));
        }
    }
    factory.setContext( null,
                        null,
                        context.getKnowledgeRuntime(),
                        null );
    // do we have any functions for this namespace?
    Package pkg = ((InternalKnowledgeBase) context.getKnowledgeRuntime()
                .getKnowledgeBase()).getRuleBase().getPackage( "MAIN" );
    if ( pkg != null ) {
        MVELDialectRuntimeData data = (MVELDialectRuntimeData) pkg.getDialectRuntimeRegistry().getDialectData( this.id );
        factory.setNextFactory( data.getFunctionFactory() );
    }
    CompiledExpression compexpr = (CompiledExpression) this.expr;
    Object value;
    if ( MVELDebugHandler.isDebugMode() ) {
        if ( MVELDebugHandler.verbose ) {
            System.out.println( DebugTools.decompile( compexpr ) );
        }
        value = MVEL.executeDebugger( compexpr,
                                      null,
                                      factory );
    } else {
        value = MVEL.executeExpression( compexpr,
                                        null,
                                        factory );
    }
    if ( !(value instanceof Boolean) ) {
        throw new RuntimeException( "Constraints must return boolean values" );
    }
    return ((Boolean) value).booleanValue();
}
 

实例 2


public Tuple project(String[] columns, Serializable[] groupByExpressions) {
    Map<String, Integer> newPositions = new HashMap<>();
    Object[] newTuple = columns != null ? new Object[columns.length] : null;
    if (groupByExpressions != null) {
        for (int i = 0; i < groupByExpressions.length; i++) {
            String col = columns[i];
            if (simpleExpressions[i]) {
                int position = positions.get(col);
                newTuple[i] = tuple[position];
            } else {
                newTuple[i] = MVEL.executeExpression(groupByExpressions[i], this);
            }
            newPositions.put(col, i);
        }
    }
    Tuple retVal = new Tuple(nestedFields, newPositions, simpleExpressions);
    retVal.tuple = newTuple;
    return retVal;
}
 

实例 3


@Override
protected void setUp() throws Exception {
  super.setUp();
  MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true;
  OptimizerFactory.setDefaultOptimizer(OptimizerFactory.SAFE_REFLECTIVE);
  PropertyHandlerFactory.registerPropertyHandler(MyClass.class, new NullPropertyHandler());
  PropertyHandlerFactory.registerPropertyHandler(MyInterface.class, new NullPropertyHandler());
}
 

实例 4


public void deserialize(String serial) {
        RemoteUpdateUtil.applySerial(this, serial);
        String[] keyValues = serial.split(String.valueOf(SERIAL_DELIMITER));
        for (String keyValue : keyValues) {
                String[] kv = keyValue.split(String.valueOf(KEY_VALUE_DELIMITER));
                MVEL.setProperty(this, kv[0], kv[1]);
        }
        throw new UnsupportedOperationException("not yet implemented");
}
 

实例 5


/**
 * Return a compiled MVEL set expression.
 *
 * @return compiled MVEL set expression
 */
protected Serializable getCompiledSetExpression() {
    if (compiledSetExpression == null) {
        compiledSetExpression = MVEL.compileSetExpression(getExpression(), PARSER_CONTEXT);
    }
    return compiledSetExpression;
}
 

实例 6


public void testSetterViaDotNotation() {
    TestClass tc = new TestClass();
    tc.getExtra().put("test", "value");
    ParserContext ctx = new ParserContext();
    ctx.setStrongTyping(true);
    String expression = "extra.test";
    Serializable compiled = MVEL.compileSetExpression(expression, ctx);
    MVEL.executeSetExpression(compiled, tc, "value2");
    assertEquals("value2", tc.getExtra().get("test"));
  }
 

实例 7


private void printSettings(BufferedWriter out,Role r,boolean includeForwarder){
        try {
                out.append("<ConfigurationSettings>");
                printGlobalSettings(out,r,includeForwarder);
                Map<String,Service> settingsList=new HashMap<String,Service>();
                for (String key:r.getChildren().keySet()){
                        Service service=null;
                        if (r.getChildren().get(key) instanceof Service){
                                service=(Service) r.getChildren().get(key);
                                for (String attr:service.getProps().keySet()){
                                        settingsList.put(service.getId()+"."+attr,service);
                                }
                                if (service.getDependencies()!=null){
                                        for (Dependency d:service.getDependencies()){
                                                if (d.getTarget()!=null && d.getType()!=null){
                                                        Object tmp = MVEL.getProperty(d.getTarget(),ModelStore.getCurrentModel());
                                                        if (tmp instanceof Service){
                                                                Service serviceDependency = (Service) tmp;
                                                                for (String prop:serviceDependency.getProps().keySet()){
                                                                        settingsList.put(serviceDependency.getId()+"."+prop,service);
                                                                }
                                                        }
                                                }
                                        }
                                }
                                settingsList.put(service.getId()+".installContainer", service);               
                        }
                }
                for (String setting:settingsList.keySet()){
                        out.append("<Setting name=""+setting+"" />");
                }
                out.append("</ConfigurationSettings>");
        } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
}
 

实例 8


public MVELDialect(PackageBuilder builder,
                   PackageRegistry pkgRegistry,
                   Package pkg,
                   String id) {
    this.id = id;
    this.pkg = pkg;
    this.pkgBuilder = builder;
    this.packageRegistry = pkgRegistry;
    this.configuration = (MVELDialectConfiguration) builder.getPackageBuilderConfiguration().getDialectConfiguration( "mvel" );
    setLanguageLevel( this.configuration.getLangLevel() );
    this.strictMode = this.configuration.isStrict();
    this.imports = new HashMap();
    this.packageImports = new HashMap();
    // setting MVEL option directly
    MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;
    this.interceptors = new HashMap( 1 );
    this.interceptors.put( "Modify",
                           new ModifyInterceptor() );
    this.results = new ArrayList();
    // this.data = new MVELDialectRuntimeData(
    // this.pkg.getDialectRuntimeRegistry() );
    //        
    // this.pkg.getDialectRuntimeRegistry().setDialectData( ID,
    // this.data );
    MVELDialectRuntimeData data = null;
    // initialise the dialect runtime data if it doesn't already exist
    if ( pkg.getDialectRuntimeRegistry().getDialectData( getId() ) == null ) {
        data = new MVELDialectRuntimeData();
        this.pkg.getDialectRuntimeRegistry().setDialectData( getId(),
                                                             data );
        data.onAdd( this.pkg.getDialectRuntimeRegistry(),
                    this.pkgBuilder.getRootClassLoader() );
    }
    this.results = new ArrayList();
    this.src = new MemoryResourceReader();
    if ( this.pkg != null ) {
        this.addImport( this.pkg.getName() + ".*" );
    }
}
 

实例 9


public void testUnwantedImport() {
  ParserConfiguration conf = new ParserConfiguration();
  conf.addPackageImport("java.util");
  conf.addPackageImport("org.mvel2.tests.core.res");
  ParserContext pctx = new ParserContext( conf );
  MVEL.analysisCompile( "ScenarioType.Set.ADD", pctx );
  assertNull(conf.getImports().get("Set"));
}
 

实例 10


/**
 * evalFile with encoding(workspace encoding utf-8)
 *
 * @throws IOException
 */
public void testEvalFile1() throws IOException {
  Object obj = MVEL.evalFile(file, "UTF-8");
  assertEquals("?????", obj);
  // use default encoding
  obj = MVEL.evalFile(file);
  assertEquals("?????", obj);
}
 

实例 11


public void testJavaStyleClassLiterals() {
  MVEL.COMPILER_OPT_SUPPORT_JAVA_STYLE_CLASS_LITERALS = true;
  OptimizerFactory.setDefaultOptimizer("ASM");
  assertEquals(String.class, MVEL.executeExpression(MVEL.compileExpression("String.class")));
  OptimizerFactory.setDefaultOptimizer("reflective");
  assertEquals(String.class, MVEL.executeExpression(MVEL.compileExpression("String.class")));
  OptimizerFactory.setDefaultOptimizer(OptimizerFactory.DYNAMIC);
  assertEquals(String.class, MVEL.eval("String"));
  assertEquals(String.class, MVEL.eval("java.lang.String"));
  assertEquals(java.util.ArrayList.class, MVEL.eval("java.util.ArrayList"));
  assertEquals(String.class, MVEL.eval("(String)"));
  assertEquals(String.class, MVEL.eval("(java.lang.String)"));
  assertEquals(java.util.ArrayList.class, MVEL.eval("(java.util.ArrayList)"));
  assertEquals(String.class, MVEL.eval("(String.class)"));
  assertEquals(String.class, MVEL.eval("(java.lang.String.class)"));
  assertEquals(java.util.ArrayList.class, MVEL.eval("(java.util.ArrayList.class)"));
  assertEquals(String.class, MVEL.eval("String.class"));
  assertEquals(String.class, MVEL.eval("java.lang.String.class"));
  assertEquals(java.util.ArrayList.class, MVEL.eval("java.util.ArrayList.class"));
  assertEquals(Class.class, MVEL.analyze("String", ParserContext.create()));
  assertEquals(Class.class, MVEL.analyze("String.class", ParserContext.create()));
  assertEquals(Class.class, MVEL.analyze("java.lang.String.class", ParserContext.create()));
  assertEquals(Class.class, MVEL.analyze("java.util.ArrayList.class", ParserContext.create()));
  MVEL.COMPILER_OPT_SUPPORT_JAVA_STYLE_CLASS_LITERALS = false;
}
 
讨论
淘淘あ西西 profile image