org.mvel2.MVEL Java Examples

The following examples show how to use org.mvel2.MVEL. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MvelExpressionExecutor.java    From activiti6-boot2 with Apache License 2.0 7 votes vote down vote up
public static Object executeOutputExpression(OutputClause outputClause, LiteralExpression outputEntry, MvelExecutionContext executionContext) {

        if (outputClause == null) {
            throw new IllegalArgumentException("output clause is required");
        }
        if (outputEntry == null) {
            throw new IllegalArgumentException("output entry is required");
        }

        // compile MVEL expression
        Serializable compiledExpression = MVEL.compileExpression(outputEntry.getText(), executionContext.getParserContext());

        // execute MVEL expression
        Object result = null;

        try {
            result = MVEL.executeExpression(compiledExpression, executionContext.getStackVariables());
        } catch (Exception ex) {
            logger.warn("Error while executing output entry: {}", outputEntry.getText(), ex);
            throw new ActivitiDmnExpressionException("error while executing output entry", outputEntry.getText(), ex);
        }

        return result;
    }
 
Example #2
Source File: WidMVELEvaluator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public static Object eval(final String expression) {
    ExpressionCompiler compiler = new ExpressionCompiler(getRevisedExpression(expression),
                                                         WID_PARSER_CONTEXT);

    if(KiePolicyHelper.isPolicyEnabled()) {
        return AccessController.doPrivileged(new PrivilegedAction<Object>() {
            @Override
            public Object run() {
                return MVEL.executeExpression(compiler.compile(),
                                              new HashMap());
            }
        }, KiePolicyHelper.getAccessContext());
    } else {
        return MVEL.executeExpression(compiler.compile(),
                                      new HashMap());
    }
}
 
Example #3
Source File: HelpBean.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
public void executeFunction() {
	logger.debug("executeFunction invoked {}", getUser());
	this.functionResult = "";

	Map<String, Object> mvelContext = new HashMap<>();
	mvelContext.put("um", SFLocalContext.getDefault().getUtilityManager());

	try {
	    String mvelExpression = StringUtils.isNotBlank(functionParameters) ? String.format("%s, %s)", functionExecString, functionParameters) : functionExecString + ")";
			this.functionResult = MVEL.eval(mvelExpression, mvelContext).toString();
	} catch (Exception e) {
		logger.error("{}", e);
		Throwable ee = e;
		while (ee.getCause() != null)
		{
			ee = ee.getCause();
		}
           BeanUtil.showMessage(FacesMessage.SEVERITY_ERROR, "Could not execute utility function", ee instanceof EPSCommonException ? ee.getMessage() : "please, check function parameters");
	}
}
 
Example #4
Source File: MVELObjectClassFieldReader.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public static void doCompile(MVELClassFieldReader target, MVELDialectRuntimeData runtimeData, Object evaluationContext) {
    Class cls;
    try {            
        cls = runtimeData.getRootClassLoader().loadClass( target.getClassName() );
    } catch ( ClassNotFoundException e ) {
        throw new IllegalStateException( "Unable to compile as Class could not be found '" + target.getClassName() + "'");
    }
    ParserContext context = new ParserContext(runtimeData.getParserConfiguration(), evaluationContext);
    context.addInput( "this", cls );
    context.setStrongTyping( target.isTypeSafe() );

    MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;
    MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true;
    MVEL.COMPILER_OPT_ALLOW_RESOLVE_INNERCLASSES_WITH_DOTNOTATION = true;
    MVEL.COMPILER_OPT_SUPPORT_JAVA_STYLE_CLASS_LITERALS = true;
    ExecutableStatement mvelExpression = (ExecutableStatement)MVEL.compileExpression( target.getExpression(), context);
    
    Class returnType = mvelExpression.getKnownEgressType();
    target.setExecutableStatement( mvelExpression );
    target.setFieldType( returnType );
    target.setValueType( ValueType.determineValueType( returnType ) );
    target.setEvaluationContext(evaluationContext);
}
 
Example #5
Source File: MVELAccumulatorFunctionExecutor.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public void accumulate(Object workingMemoryContext,
                       Object context,
                       Tuple tuple,
                       InternalFactHandle handle,
                       Declaration[] declarations,
                       Declaration[] innerDeclarations,
                       WorkingMemory workingMemory) throws Exception {
    
    VariableResolverFactory factory = unit.getFactory( null, null, null, handle, tuple, null, (InternalWorkingMemory) workingMemory, workingMemory.getGlobalResolver()  );
    
    final Object value = MVEL.executeExpression( this.expression,
                                                 handle.getObject(),
                                                 factory );
    if ( this.function.supportsReverse() ) {
        ((MVELAccumulatorFunctionContext) context).reverseSupport.put( handle.getId(), value );
    }
    this.function.accumulate( ((MVELAccumulatorFunctionContext) context).context,
                              value );
}
 
Example #6
Source File: RawMVELEvaluator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T eval(final String expression, final Class<T> toType) {
    return MVEL.eval(expression, toType);
}
 
Example #7
Source File: IBatisSqlActionShardingRule.java    From cobarclient with Apache License 2.0 6 votes vote down vote up
public boolean isDefinedAt(IBatisRoutingFact routingFact) {
    Validate.notNull(routingFact);
    boolean matches = StringUtils.equals(getTypePattern(), routingFact.getAction());
    if (matches) {
        try {
            Map<String, Object> vrs = new HashMap<String, Object>();
            vrs.putAll(getFunctionMap());
            vrs.put("$ROOT", routingFact.getArgument()); // add top object reference for expression
            VariableResolverFactory vrfactory = new MapVariableResolverFactory(vrs);
            if (MVEL.evalToBoolean(getAttributePattern(), routingFact.getArgument(), vrfactory)) {
                return true;
            }
        } catch (Throwable t) {
            logger
                    .info(
                            "failed to evaluate attribute expression:'{}' with context object:'{}'\n{}",
                            new Object[] { getAttributePattern(), routingFact.getArgument(), t });
        }
    }

    return false;
}
 
Example #8
Source File: MVELSalienceExpression.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public int getValue(final KnowledgeHelper khelper,
                    final Rule rule,
                    final WorkingMemory workingMemory) {
    VariableResolverFactory factory = unit.getFactory( khelper, 
                                                       khelper != null ? ((AgendaItem)khelper.getMatch()).getTerminalNode().getSalienceDeclarations() : null, 
                                                       rule, null, 
                                                       khelper != null ? (LeftTuple) khelper.getMatch().getTuple() : null, 
                                                       null, (InternalWorkingMemory) workingMemory, workingMemory.getGlobalResolver() );
    
    // do we have any functions for this namespace?
    InternalKnowledgePackage pkg = workingMemory.getKnowledgeBase().getPackage( "MAIN" );
    if ( pkg != null ) {
        MVELDialectRuntimeData data = (MVELDialectRuntimeData) pkg.getDialectRuntimeRegistry().getDialectData( this.id );
        factory.setNextFactory( data.getFunctionFactory() );
    }

    Object value = MVEL.executeExpression( this.expr, factory );
    if (value instanceof String) {
        value = TimeUtils.parseTimeString( (String)value );
    }
    return ((Number)value).intValue();
}
 
Example #9
Source File: MVELBeanCreator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T createBean(ClassLoader cl, String type, QualifierModel qualifier ) throws Exception {
    if (qualifier != null) {
        throw new IllegalArgumentException("Cannot use a qualifier without a CDI container");
    }

    ParserConfiguration config = new ParserConfiguration();
    config.setClassLoader(cl);
    ParserContext ctx = new ParserContext( config);
    if (parameters != null) {
        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
            ctx.addVariable(entry.getKey(), entry.getValue().getClass());
        }
    }

    Object compiledExpression = MVEL.compileExpression( type, ctx );
    return (T) MVELSafeHelper.getEvaluator().executeExpression( compiledExpression, parameters );
}
 
Example #10
Source File: ExpressionProvider.java    From test-data-generator with Apache License 2.0 6 votes vote down vote up
@Override
public Object nextValue(Context context, Field field) {
    Class type;
    switch (field.getType()) {
        case TypeConst.STRING:
            type = String.class;
            break;
        case TypeConst.LONG:
            type = Long.class;
            break;
        case TypeConst.INT:
            type = Integer.class;
            break;
        case TypeConst.BOOLEAN:
            type = Boolean.class;
            break;
        default:
            throw new IllegalArgumentException("Field type not known: " + field.getType());
    }
    synchronized (context.getVariables()) {
        return MVEL.executeExpression(compiledExpression, context, context.getVariables(), type);
    }
}
 
Example #11
Source File: MVELDataTransformer.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Override
public Object compile(String expression, Map<String, Object> parameters) {
	logger.debug("About to compile mvel expression {}", expression);
	ClassLoader classLoader = (ClassLoader) parameters.get("classloader");
	if (classLoader == null) {
		classLoader = this.getClass().getClassLoader();
	}
	ParserConfiguration config = new ParserConfiguration();
       config.setClassLoader(classLoader);
	ParserContext context = new ParserContext(config);
	if (parameters != null) {
		@SuppressWarnings("unchecked")
		Set<String> imports = (Set<String>)parameters.get("imports");
		if (imports != null) {
			for(String clazz : imports) {
				try {
					Class<?> cl = Class.forName(clazz, true, classLoader);
					context.addImport(cl.getSimpleName(), cl);
				} catch (ClassNotFoundException e) {
					logger.warn("Unable to load class {} due to {}", clazz, e.getException());
				};
			}
		}
	}
	return MVEL.compileExpression(expression, context);
}
 
Example #12
Source File: PatternBuilder.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private FieldValue getFieldValue(RuleBuildContext context,
                                 ValueType vtype,
                                 String value) {
    try {
        MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true;
        MVEL.COMPILER_OPT_ALLOW_OVERRIDE_ALL_PROPHANDLING = true;
        MVEL.COMPILER_OPT_ALLOW_RESOLVE_INNERCLASSES_WITH_DOTNOTATION = true;
        MVEL.COMPILER_OPT_SUPPORT_JAVA_STYLE_CLASS_LITERALS = true;

        MVELDialectRuntimeData data = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
        ParserConfiguration pconf = data.getParserConfiguration();
        ParserContext pctx = new ParserContext(pconf);

        Object o = MVELSafeHelper.getEvaluator().executeExpression(MVEL.compileExpression(value, pctx));
        if (o != null && vtype == null) {
            // was a compilation problem else where, so guess valuetype so we can continue
            vtype = ValueType.determineValueType(o.getClass());
        }

        return context.getCompilerFactory().getFieldFactory().getFieldValue(o, vtype);
    } catch (final Exception e) {
        // we will fallback to regular preducates, so don't raise an error
    }
    return null;
}
 
Example #13
Source File: IBatisNamespaceShardingRule.java    From cobarclient with Apache License 2.0 6 votes vote down vote up
public boolean isDefinedAt(IBatisRoutingFact routingFact) {
    Validate.notNull(routingFact);
    String namespace = StringUtils.substringBeforeLast(routingFact.getAction(), ".");
    boolean matches = StringUtils.equals(namespace, getTypePattern());
    if (matches) {
        try {
            Map<String, Object> vrs = new HashMap<String, Object>();
            vrs.putAll(getFunctionMap());
            vrs.put("$ROOT", routingFact.getArgument()); // add top object reference for expression
            VariableResolverFactory vrfactory = new MapVariableResolverFactory(vrs);
            if (MVEL.evalToBoolean(getAttributePattern(), routingFact.getArgument(), vrfactory)) {
                return true;
            }
        } catch (Throwable t) {
            logger
                    .info(
                            "failed to evaluate attribute expression:'{}' with context object:'{}'\n{}",
                            new Object[] { getAttributePattern(), routingFact.getArgument(), t });
        }
    }
    return false;
}
 
Example #14
Source File: SafeMVELEvaluator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T executeExpression(final Object compiledExpression, final Object ctx, final Class<T> toType) {
    return AccessController.doPrivileged(new PrivilegedAction<T>() {

        @Override
        public T run() {
            return MVEL.executeExpression(compiledExpression, ctx, toType);
        }
    }, KiePolicyHelper.getAccessContext());
}
 
Example #15
Source File: SafeMVELEvaluator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T executeExpression(final Object compiledExpression, final Map vars, final Class<T> toType) {
    return AccessController.doPrivileged(new PrivilegedAction<T>() {

        @Override
        public T run() {
            return MVEL.executeExpression(compiledExpression, vars, toType);
        }
    }, KiePolicyHelper.getAccessContext());
}
 
Example #16
Source File: SafeMVELEvaluator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T executeExpression(final Object compiledExpression, final Object ctx, final VariableResolverFactory vars, final Class<T> toType) {
    return AccessController.doPrivileged(new PrivilegedAction<T>() {

        @Override
        public T run() {
            return MVEL.executeExpression(compiledExpression, ctx, vars, toType);
        }
    }, KiePolicyHelper.getAccessContext());
}
 
Example #17
Source File: SafeMVELEvaluator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public void executeExpression(final Iterable<CompiledExpression> compiledExpression) {
    AccessController.doPrivileged(new PrivilegedAction<Object>() {

        @Override
        public Object run() {
            MVEL.executeExpression(compiledExpression);
            return null;
        }
    }, KiePolicyHelper.getAccessContext());
}
 
Example #18
Source File: QueryArgument.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void init() {
    Map<String, Class> inputs = new HashMap<String, Class>();
    for (Declaration d : declarations) {
        inputs.put(d.getBindingName(), d.getDeclarationClass());
    }
    parserContext.setInputs(inputs);

    this.argumentClass = MVEL.analyze( expression, parserContext );
    this.mvelExpr = MVEL.compileExpression( expression, parserContext );
}
 
Example #19
Source File: StaticUtil.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
private static Serializable compileExpression(String expression) {
    Serializable compiledExpression = EXPRESSION_CACHE.get(expression);

    if(compiledExpression == null) {
        compiledExpression = MVEL.compileExpression(expression, MVELInitializer.getInstance().getCtx());
        EXPRESSION_CACHE.put(expression, compiledExpression);
    }

    return compiledExpression;
}
 
Example #20
Source File: SafeMVELEvaluator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T eval(final String expression, final Object ctx, final VariableResolverFactory vars, final Class<T> toType) {
    return AccessController.doPrivileged(new PrivilegedAction<T>() {

        @Override
        public T run() {
            return MVEL.eval(expression, ctx, vars, toType);
        }
    }, KiePolicyHelper.getAccessContext());
}
 
Example #21
Source File: ClassTests.java    From javatech with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Test
public void testEval() {
    String expression = "foobar > 99";
    Map vars = new HashMap();
    vars.put("foobar", new Integer(100));
    Boolean result = (Boolean) MVEL.eval(expression, vars);
    Assertions.assertEquals(true, result);
}
 
Example #22
Source File: SafeMVELEvaluator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T eval(final String expression, final Map<String, Object> vars, final Class<T> toType) {
    return AccessController.doPrivileged(new PrivilegedAction<T>() {

        @Override
        public T run() {
            return MVEL.eval(expression, vars, toType);
        }
    }, KiePolicyHelper.getAccessContext());
}
 
Example #23
Source File: SafeMVELEvaluator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T eval(final String expression, final Object ctx, final Class<T> toType) {
    return AccessController.doPrivileged(new PrivilegedAction<T>() {

        @Override
        public T run() {
            return MVEL.eval(expression, ctx, toType);
        }
    }, KiePolicyHelper.getAccessContext());
}
 
Example #24
Source File: SafeMVELEvaluator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T eval(final String expression, final Class<T> toType) {
    return AccessController.doPrivileged(new PrivilegedAction<T>() {

        @Override
        public T run() {
            return MVEL.eval(expression, toType);
        }
    }, KiePolicyHelper.getAccessContext());
}
 
Example #25
Source File: MvelFunction.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T doWith(Class<T> clazz, Object... arguments) {
    MvelHolder holder = threadHolder.get();
    for (int index = 0, size = classes.length; index < size; index++) {
        holder.scope.createAttribute(StringUtility.format("argument{}", index), arguments[index]);
    }
    T object = (T) MVEL.executeExpression(script, threadHolder.get().scope.getAttributes(), clazz);
    holder.scope.deleteAttributes();
    return object;
}
 
Example #26
Source File: SafeMVELEvaluator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public Object eval(final String expression, final Map<String, Object> vars) {
    return AccessController.doPrivileged(new PrivilegedAction<Object>() {

        @Override
        public Object run() {
            return MVEL.eval(expression, vars);
        }
    }, KiePolicyHelper.getAccessContext());
}
 
Example #27
Source File: SafeMVELEvaluator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public Object eval(final String expression, final Object ctx, final VariableResolverFactory resolverFactory) {
    return AccessController.doPrivileged(new PrivilegedAction<Object>() {

        @Override
        public Object run() {
            return MVEL.eval(expression, ctx, resolverFactory);
        }
    }, KiePolicyHelper.getAccessContext());
}
 
Example #28
Source File: SafeMVELEvaluator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public Object eval(final String expression, final VariableResolverFactory resolverFactory) {
    return AccessController.doPrivileged(new PrivilegedAction<Object>() {

        @Override
        public Object run() {
            return MVEL.eval(expression, resolverFactory);
        }
    }, KiePolicyHelper.getAccessContext());
}
 
Example #29
Source File: SafeMVELEvaluator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public Object eval(final String expression, final Object ctx) {
    return AccessController.doPrivileged(new PrivilegedAction<Object>() {

        @Override
        public Object run() {
            return MVEL.eval(expression, ctx);
        }
    }, KiePolicyHelper.getAccessContext());
}
 
Example #30
Source File: TestMvel.java    From ns4_frame with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) 
{
	Map map = new HashMap<String, Object>();
	map.put("A",100);
	map.put("B", "aaa");
	map.put("c", "aa");
	
	map.put("NAME", "root");
	
	
	System.out.println("结果:"+MVEL.eval("NAME=='root'", map));
}