Example usage for org.springframework.expression.spel.support StandardEvaluationContext setBeanResolver

List of usage examples for org.springframework.expression.spel.support StandardEvaluationContext setBeanResolver

Introduction

In this page you can find the example usage for org.springframework.expression.spel.support StandardEvaluationContext setBeanResolver.

Prototype

public void setBeanResolver(BeanResolver beanResolver) 

Source Link

Usage

From source file:org.gerzog.jstataggr.expressions.spel.SpelExpressionHandler.java

@PostConstruct
public void initialize() {
    final StandardEvaluationContext context = new StandardEvaluationContext();
    context.setBeanResolver(new BeanFactoryResolver(beanFactory));

    this.context = context;
    this.expressionParser = new SpelExpressionParser();
}

From source file:app.web.InterpreterController.java

@RequestMapping("/interpreter/run")
public ModelAndView run(@RequestParam("script") String script) {
    Transaction transaction = Db.getSession().beginTransaction();
    // Groovy Shell
    //        Binding binding = new Binding();
    //        binding.setVariable("userService", userService); // FIXME: go through ApplicationContext or try to use SpEl instead?
    //        Object result = new GroovyShell(binding).parse(script).run();
    // Groovy Interpreter
    //        Object result = GroovyInterpreter.run(script);
    // SpEl//www  .j a v  a  2s  .  co  m
    ExpressionParser parser = new SpelExpressionParser();
    StandardEvaluationContext ctx = new StandardEvaluationContext();
    ctx.setBeanResolver(new BeanFactoryResolver(beanFactory));
    Object result = parser.parseExpression(script).getValue(ctx);
    //        Db.flush(); // can not flush here, we get org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
    transaction.commit();

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("script", script);
    map.put("result", result != null ? result.toString().replaceAll("\n", "<br/>").replaceAll(" ", "&nbsp;")
            : Void.class.getSimpleName());
    return new ModelAndView("/interpreter", map);
}

From source file:de.hybris.platform.addonsupport.config.SpelBeanFactory.java

@Override
public void onApplicationEvent(final ContextRefreshedEvent event) {
    final ExpressionParser parser = new SpelExpressionParser();
    final StandardEvaluationContext context = new StandardEvaluationContext();
    context.setBeanResolver(new BeanFactoryResolver(applicationContext));

    final String[] beanNames = applicationContext.getBeanNamesForType(AbstractConverter.class);
    for (final String beanName : beanNames) {
        final BeanDefinition def = beanFactory.getBeanDefinition(beanName);
        final PropertyValue pv = def.getPropertyValues().getPropertyValue("targetClass");
        if (pv != null) {

            if (pv.getValue() instanceof TypedStringValue) {

                String expr = StringUtils.strip(((TypedStringValue) pv.getValue()).getValue());
                if (expr.startsWith("#{")) {
                    expr = StringUtils.replaceOnce(expr, "#{", "@");
                    expr = StringUtils.stripEnd(expr, "}");
                    final Object result = parser.parseExpression(expr).getValue(context);
                    if (result != null) {

                        try {
                            applicationContext.getBean(beanName, AbstractConverter.class)
                                    .setTargetClass(ClassUtils.getClass(result.toString()));
                        } catch (final ClassNotFoundException e) {
                            LOG.error(beanName + " target class instantiation failed", e);
                        }/* w  ww  .  j  a  v a 2 s.  co  m*/
                    }
                }
            }
        }
    }
}

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));
        }//  www. j  a  v a  2s .c  o 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:cz.jirutka.validator.spring.SpELAssertValidator.java

private StandardEvaluationContext createEvaluationContext(Object rootObject) {
    StandardEvaluationContext context = new StandardEvaluationContext();

    context.setRootObject(rootObject);//from  ww w  . j av  a2 s .  c om
    context.setTypeConverter(TYPE_CONVERTER);

    if (beanFactory != null) {
        context.setBeanResolver(new BeanFactoryResolver(beanFactory));
    }
    if (!functions.isEmpty()) {
        for (Method helper : functions) {
            context.registerFunction(helper.getName(), helper);
        }
        LOG.trace(inspectFunctions(context));
    }

    return context;
}

From source file:com.googlecode.ehcache.annotations.key.SpELCacheKeyGenerator.java

/**
 * Get the {@link EvaluationContext} to use to evaluate the configured {@link Expression}
 *///from   w w  w.  jav  a 2  s.  c om
protected EvaluationContext getEvaluationContext(MethodInvocation methodInvocation, Object... args) {
    final StandardEvaluationContext evaluationContext = new StandardEvaluationContext();
    evaluationContext.setBeanResolver(new BeanFactoryResolver(this.beanFactory));
    evaluationContext.setVariable("invocation", methodInvocation);
    evaluationContext.setVariable("args", args);
    evaluationContext.setVariable("key", keyCallbackObject);
    evaluationContext.addMethodResolver(this.methodResolver);
    return evaluationContext;
}

From source file:reactor.spring.context.ConsumerBeanPostProcessor.java

@Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
    ReflectionUtils.doWithMethods(bean.getClass(), new ReflectionUtils.MethodCallback() {
        @Override//from   ww w. j  av  a2 s  .  com
        public void doWith(final Method method) throws IllegalArgumentException, IllegalAccessException {
            Annotation anno = AnnotationUtils.findAnnotation(method, On.class);
            if (null == anno) {
                return;
            }

            StandardEvaluationContext evalCtx = new StandardEvaluationContext();
            evalCtx.setRootObject(bean);
            evalCtx.setBeanResolver(beanResolver);
            evalCtx.setMethodResolvers(METHOD_RESOLVERS);

            On onAnno = (On) anno;

            Object reactorObj = null;
            if (StringUtils.hasText(onAnno.reactor())) {
                Expression reactorExpr = expressionParser.parseExpression(onAnno.reactor());
                reactorObj = reactorExpr.getValue(evalCtx);
            }

            Object selObj;
            if (StringUtils.hasText(onAnno.selector())) {
                try {
                    Expression selectorExpr = expressionParser.parseExpression(onAnno.selector());
                    selObj = selectorExpr.getValue(evalCtx);
                } catch (EvaluationException e) {
                    selObj = Fn.$(onAnno.selector());
                }
            } else {
                selObj = Fn.$(method.getName());
            }

            Consumer<Event<Object>> handler = new Consumer<Event<Object>>() {
                Class<?>[] argTypes = method.getParameterTypes();

                @Override
                public void accept(Event<Object> ev) {
                    if (argTypes.length == 0) {
                        ReflectionUtils.invokeMethod(method, bean);
                        return;
                    }

                    if (!argTypes[0].isAssignableFrom(ev.getClass())
                            && conversionService.canConvert(ev.getClass(), argTypes[0])) {
                        ReflectionUtils.invokeMethod(method, bean, conversionService.convert(ev, argTypes[0]));
                    } else {
                        ReflectionUtils.invokeMethod(method, bean, ev);
                        return;
                    }

                    if (null == ev.getData() || argTypes[0].isAssignableFrom(ev.getData().getClass())) {
                        ReflectionUtils.invokeMethod(method, bean, ev.getData());
                        return;
                    }

                    if (conversionService.canConvert(ev.getData().getClass(), argTypes[0])) {
                        ReflectionUtils.invokeMethod(method, bean,
                                conversionService.convert(ev.getData(), argTypes[0]));
                        return;
                    }

                    throw new IllegalArgumentException(
                            "Cannot invoke method " + method + " passing parameter " + ev.getData());
                }
            };

            if (!(selObj instanceof Selector)) {
                throw new IllegalArgumentException(selObj + ", referred to by the expression '"
                        + onAnno.selector() + "', is not a Selector");
            }
            if (null == reactorObj) {
                throw new IllegalStateException("Cannot register handler with null Reactor");
            } else {
                ((Reactor) reactorObj).on((Selector) selObj, handler);
            }
        }
    });
    return bean;
}

From source file:org.craftercms.commons.ebus.config.EBusBeanAutoConfiguration.java

private <T> T expression(String selector, Object bean) {
    if (selector == null) {
        return null;
    }//from w w w .  j  a  v  a2 s  .  c o  m

    StandardEvaluationContext evalCtx = new StandardEvaluationContext();
    evalCtx.setRootObject(bean);
    evalCtx.setBeanResolver(beanResolver);

    return (T) expressionParser.parseExpression(selector).getValue(evalCtx);
}

From source file:org.arrow.service.DefaultExecutionService.java

/**
 * {@inheritDoc}/*www .j  a  v  a  2  s. c  om*/
 */
@Override
public Object evaluateExpression(String expression) {
    ExpressionParser parser = new SpelExpressionParser();

    StandardEvaluationContext ec = new StandardEvaluationContext();
    ec.setBeanResolver(new BeanFactoryResolver(context));
    Expression expr = parser.parseExpression(expression);

    return expr.getValue(ec);
}

From source file:org.jasig.portlet.widget.service.SpringELProcessor.java

/**
 * @{inheritDoc}// w w  w  .  jav a2  s  .  co m
 */
@Override
public String process(String value, PortletRequest request) {
    Map<String, Object> context = getContext(request);

    StandardEvaluationContext sec = new StandardEvaluationContext(context);
    sec.addPropertyAccessor(new MapAccessor());
    sec.addPropertyAccessor(new ReflectivePropertyAccessor());
    sec.addPropertyAccessor(new DefaultPropertyAccessor(PARSER_CONTEXT.getExpressionPrefix(),
            PARSER_CONTEXT.getExpressionSuffix()));
    sec.setBeanResolver(beanResolver);
    SpelExpressionParser parser = new SpelExpressionParser();

    String processed = parser.parseExpression(value, PARSER_CONTEXT).getValue(sec, String.class);

    return processed;
}