Example usage for org.springframework.expression EvaluationContext setVariable

List of usage examples for org.springframework.expression EvaluationContext setVariable

Introduction

In this page you can find the example usage for org.springframework.expression EvaluationContext setVariable.

Prototype

void setVariable(String name, @Nullable Object value);

Source Link

Document

Set a named variable within this evaluation context to a specified value.

Usage

From source file:org.snaker.engine.spring.SpelExpression.java

public <T> T eval(Class<T> T, String expr, Map<String, Object> args) {
    EvaluationContext context = new StandardEvaluationContext();
    for (Entry<String, Object> entry : args.entrySet()) {
        context.setVariable(entry.getKey(), entry.getValue());
    }//from   www  .  ja  v a2s. c  o  m
    return parser.parseExpression(expr).getValue(context, T);
}

From source file:com.github.sebhoss.contract.verifier.SpELBasedContractContextFactory.java

@Override
public ContractContext createContext(final Object instance, final Object[] arguments,
        final String[] parameterNames) {
    final ExpressionParser parser = new SpelExpressionParser();
    final EvaluationContext context = new StandardEvaluationContext(instance);

    for (int index = 0; index < arguments.length; index++) {
        context.setVariable(parameterNames[index], arguments[index]);
    }//from w w  w. ja  va  2 s. c o  m

    return new SpELContractContext(parser, context);
}

From source file:org.jmingo.el.springexp.SpringELEngine.java

/**
 * {@inheritDoc}/*from   ww  w. ja va  2s.  c  o  m*/
 */
@Override
public synchronized boolean evaluate(String expression, Map<String, Object> parameters) {
    Validate.notBlank(expression, "expression cannot be empty");
    Expression exp = parser.parseExpression(expression);
    EvaluationContext context = new StandardEvaluationContext();
    if (MapUtils.isNotEmpty(parameters)) {
        for (Map.Entry<String, Object> parameter : parameters.entrySet()) {
            context.setVariable(parameter.getKey(), parameter.getValue());
        }
    }
    return exp.getValue(context, Boolean.class);
}

From source file:io.dyn.core.handler.GuardedHandlerMethodInvoker.java

@Override
public Object invoke(HandlerMethod method, Object handler, EvaluationContext evalCtx, Object... args)
        throws Exception {
    if (null == evalCtx) {
        StandardEvaluationContext ec = new StandardEvaluationContext();
        if (null != applicationContext) {
            ec.setBeanResolver(new BeanFactoryResolver(applicationContext));
        }/*from   w  w  w. j a  v  a 2s .  co m*/
        evalCtx = ec;
    }

    HandlerMethodArgument[] handlerMethodArguments = method.arguments();
    int argc = handlerMethodArguments.length;
    Object[] argv = new Object[argc];
    for (int i = 0; i < argc; i++) {
        HandlerMethodArgument handlerArg = handlerMethodArguments[i];
        if (ClassUtils.isAssignable(EvaluationContext.class, handlerArg.targetType())) {
            argv[i] = evalCtx;
        } else if (null != handlerArg.valueExpression()) {
            try {
                argv[i] = handlerArg.valueExpression().getValue(evalCtx, handlerArg.targetType());
            } catch (SpelEvaluationException e) {
                argv[i] = null;
            }
        } else {
            try {
                Object o = args[handlerArg.index()];
                if (ClassUtils.isAssignable(handlerArg.targetType(), o.getClass())) {
                    argv[i] = o;
                } else if (null != customConversionService
                        && customConversionService.canConvert(o.getClass(), handlerArg.targetType())) {
                    argv[i] = customConversionService.convert(o, handlerArg.targetType());
                } else {
                    argv[i] = Sys.DEFAULT_CONVERSION_SERVICE.convert(o, handlerArg.targetType());
                }
            } catch (IndexOutOfBoundsException e) {
            }
        }
        evalCtx.setVariable(handlerArg.name(), argv[i]);
    }

    InvocationHandler invoker = method.invocationHandler();
    Method m = method.methodToInvoke();
    if (null != method.guard()) {
        if (method.guard().checkGuard(null, evalCtx)) {
            if (null != invoker) {
                try {
                    invoker.invoke(handler, m, argv);
                } catch (Throwable throwable) {
                    throw new IllegalStateException(throwable);
                }
            } else {
                return m.invoke(handler, argv);
            }
        } else {
            //LOG.debug("Guard expression %s failed", method.guard().expression().getExpressionString());
        }
    } else {
        if (null != invoker) {
            try {
                return invoker.invoke(handler, m, argv);
            } catch (Throwable throwable) {
                throw new IllegalStateException(throwable);
            }
        } else {
            return m.invoke(handler, argv);
        }
    }

    return null;
}

From source file:com.qcadoo.model.internal.ExpressionServiceImpl.java

@Override
public String getValue(final Entity entity, final String expression, final Locale locale) {
    if (StringUtils.isEmpty(expression) || "null".equals(expression)) {
        LOG.warn("Calculating empty expressions");
        return null;
    }/*from w ww  .  jav  a 2  s  .  co  m*/

    ExpressionParser parser = new SpelExpressionParser();
    Expression exp = parser.parseExpression(expression);
    EvaluationContext context = new StandardEvaluationContext();

    if (entity != null) {
        Map<String, Object> values = getValuesForEntity(entity, locale, 2);

        for (Map.Entry<String, Object> entry : values.entrySet()) {
            context.setVariable(entry.getKey(), entry.getValue());
        }
    }

    String value = null;

    try {
        value = String.valueOf(exp.getValue(context));

        if (LOG.isDebugEnabled()) {
            LOG.debug("Calculating value of expression \"" + expression + "\" for " + entity + " : " + value);
        }
    } catch (SpelEvaluationException e) {
        if (SpelMessage.CANNOT_INDEX_INTO_NULL_VALUE.equals(e.getMessageCode())) {
            return "";
        } else {
            LOG.error("Error while calculating value of expression \"" + expression + "\" for " + entity, e);
            value = "!!!";
        }
    }

    if (StringUtils.isEmpty(value) || "null".equals(value)) {
        return null;
    } else {
        return translate(value, locale);
    }
}

From source file:org.apache.rave.synchronization.SynchronizingAspect.java

private EvaluationContext getEvaluationContext(Class<?> targetClass, Method method, Object[] args) {
    EvaluationContext context = new StandardEvaluationContext();
    if (ArrayUtils.isEmpty(args)) {
        return context;
    }//from w w  w.ja va2 s  .  c  o m

    Method targetMethod = getTargetMethod(targetClass, method);
    for (int i = 0; i < args.length; i++) {
        context.setVariable("p" + i, args[i]);
    }

    String[] parameterNames = paramNameDiscoverer.getParameterNames(targetMethod);
    if (parameterNames != null) {
        for (int i = 0; i < parameterNames.length; i++) {
            context.setVariable(parameterNames[i], args[i]);
        }
    }

    return context;
}

From source file:org.finra.dm.app.security.SecurityHelper.java

/**
 * Checks whether security is enabled based on SpEL expression defined in environment.
 * //from  ww  w  .  j a v a 2s  . com
 * @param request {@link HttpServletRequest} to determine whether security is enabled.
 * @return true if security is enabled, false if disabled.
 */
public boolean isSecurityEnabled(HttpServletRequest request) {
    Boolean isSecurityEnabled = true;

    String enableSecuritySpelExpression = configurationHelper
            .getProperty(ConfigurationValue.SECURITY_ENABLED_SPEL_EXPRESSION);

    if (StringUtils.isNotBlank(enableSecuritySpelExpression)) {
        EvaluationContext evaluationContext = new StandardEvaluationContext();
        evaluationContext.setVariable("request", request);

        Expression expression = expressionParser.parseExpression(enableSecuritySpelExpression);

        isSecurityEnabled = expression.getValue(evaluationContext, Boolean.class);
    }

    return isSecurityEnabled;
}

From source file:org.springframework.integration.handler.ExpressionEvaluatingMessageProcessorTests.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test//from  w  w w.ja  v  a  2  s  .  c o m
public void testProcessMessageWithParameterCoercion() throws Exception {
    @SuppressWarnings("unused")
    class TestTarget {
        public String stringify(int number) {
            return number + "";
        }
    }
    Expression expression = expressionParser.parseExpression("#target.stringify(payload)");
    ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor(expression);
    processor.setBeanFactory(mock(BeanFactory.class));
    processor.afterPropertiesSet();
    EvaluationContext evaluationContext = TestUtils.getPropertyValue(processor, "evaluationContext",
            EvaluationContext.class);
    evaluationContext.setVariable("target", new TestTarget());
    assertEquals("2", processor.processMessage(new GenericMessage<String>("2")));
}

From source file:org.springframework.integration.handler.ExpressionEvaluatingMessageProcessorTests.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test//from w  w  w .ja  v a2s  . com
public void testProcessMessageWithVoidResult() throws Exception {
    @SuppressWarnings("unused")
    class TestTarget {
        public void ping(String input) {
        }
    }
    Expression expression = expressionParser.parseExpression("#target.ping(payload)");
    ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor(expression);
    processor.setBeanFactory(mock(BeanFactory.class));
    processor.afterPropertiesSet();
    EvaluationContext evaluationContext = TestUtils.getPropertyValue(processor, "evaluationContext",
            EvaluationContext.class);
    evaluationContext.setVariable("target", new TestTarget());
    assertEquals(null, processor.processMessage(new GenericMessage<String>("2")));
}

From source file:org.springframework.integration.handler.ExpressionEvaluatingMessageProcessorTests.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test/*from   w w w  .ja v a2 s.c o  m*/
public void testProcessMessageWithParameterCoercionToNonPrimitive() throws Exception {
    class TestTarget {
        @SuppressWarnings("unused")
        public String find(Resource[] resources) {
            return Arrays.asList(resources).toString();
        }

    }
    Expression expression = expressionParser.parseExpression("#target.find(payload)");
    ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor(expression);
    ConfigurableListableBeanFactory beanFactory = new GenericApplicationContext().getBeanFactory();
    processor.setBeanFactory(beanFactory);
    IntegrationEvaluationContextFactoryBean factoryBean = new IntegrationEvaluationContextFactoryBean();
    factoryBean.setBeanFactory(beanFactory);
    beanFactory.registerSingleton(IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME,
            factoryBean.getObject());
    processor.afterPropertiesSet();
    EvaluationContext evaluationContext = TestUtils.getPropertyValue(processor, "evaluationContext",
            EvaluationContext.class);
    evaluationContext.setVariable("target", new TestTarget());
    String result = (String) processor.processMessage(new GenericMessage<String>("classpath*:*.properties"));
    assertTrue("Wrong result: " + result, result.contains("log4j.properties"));
}