Example usage for org.springframework.expression Expression getValue

List of usage examples for org.springframework.expression Expression getValue

Introduction

In this page you can find the example usage for org.springframework.expression Expression getValue.

Prototype

@Nullable
Object getValue(EvaluationContext context) throws EvaluationException;

Source Link

Document

Evaluate this expression in the provided context and return the result of evaluation.

Usage

From source file:grails.plugin.cache.web.filter.ExpressionEvaluator.java

public Object key(String keyExpression, Method method, EvaluationContext evalContext) {
    String key = toString(method, keyExpression);
    Expression keyExp = keyCache.get(key);
    if (keyExp == null) {
        keyExp = parser.parseExpression(keyExpression);
        keyCache.put(key, keyExp);/*from www  . j  a  v  a  2s.  co m*/
    }
    return keyExp.getValue(evalContext);
}

From source file:py.una.pol.karaku.audit.Auditor.java

/**
 * @param annotation/*from   www .j  ava2s  .  com*/
 * @param methodSignature
 * @param target
 * @param gS
 */
public void doAudit(Audit annotation, String methodSignature, Object target, Object[] params) {

    AuditTrail auditTrail = new AuditTrail();

    List<AuditTrailDetail> details = new ArrayList<AuditTrailDetail>();
    auditTrail.setMethodSignature(methodSignature);

    auditTrail.setIp(util.getIpAdress());

    auditTrail.setUsername(authorityController.getUsername());

    String[] toAudit = annotation.toAudit();
    String[] paramsToAudit = annotation.paramsToAudit();
    ExpressionParser parser = new SpelExpressionParser();
    if (toAudit != null) {
        for (String string : toAudit) {
            Expression exp = parser.parseExpression(string);

            Object value = exp.getValue(target);
            AuditTrailDetail detail = new AuditTrailDetail();
            detail.setHeader(auditTrail);
            detail.setValue((Serializable) value);
            detail.setExpression(string);
            details.add(detail);
            log.info("Audit {}:{}", string, value);
        }
    }

    if (paramsToAudit != null) {
        for (String string : paramsToAudit) {

            Integer nroParm = getParamNumber(string);
            String expression = removeParamNumber(string);
            Object value;
            if (expression == null) {
                value = params[nroParm];
            } else {
                Expression exp = parser.parseExpression(expression);
                value = exp.getValue(params[nroParm]);
            }
            AuditTrailDetail detail = new AuditTrailDetail();
            detail.setHeader(auditTrail);
            detail.setValue((Serializable) value);
            detail.setExpression(string);
            details.add(detail);
        }
    }
    logic.saveAudit(auditTrail, details);

}

From source file:com.enonic.cms.core.portal.datasource.el.ExpressionFunctionsExecutor.java

public String evaluate(final String expression) {
    final ExpressionRootObject rootObject = new ExpressionRootObject();

    rootObject.setSession(new SessionAccessor(verticalSession));
    rootObject.setCookie(new CookieAccessor(httpRequest));
    rootObject.setProperties(new CmsAndSitePropertiesAccessor(rootProperties, siteProperties));
    rootObject.setPortal(new PortalAccessor(expressionContext));
    rootObject.setUser(new UserAccessor(expressionContext.getUser()));
    rootObject.setParam(new ParamAccessor(requestParameters));
    rootObject.setParams(new ParamsAccessor(requestParameters));

    final String evaluatedString;

    try {//from w  w w .ja v  a2  s.c o m
        final StandardEvaluationContext context = new StandardEvaluationContext(rootObject);

        context.setPropertyAccessors(PROPERTY_ACCESSORS);

        ExpressionFunctionsFactory.get().setContext(expressionContext);

        Object result;

        try {
            final Expression exp = EXPR_FACTORY.parseExpression(expression, TEMPLATE_PARSER_CONTEXT);

            result = exp.getValue(context);
        } catch (SpelEvaluationException e) {
            result = null;
        } catch (Exception e) {
            LOG.error(e.getMessage());

            result = "ERROR: " + e.getMessage();
        }

        // must be converted here, because param.x[0] will not work
        if (result instanceof String[]) {
            evaluatedString = StringUtils.join((String[]) result, ',');
        } else {
            evaluatedString = result != null ? result.toString() : null;
        }
    } finally {
        ExpressionFunctionsFactory.get().removeContext();
    }

    return evaluatedString;
}

From source file:com.googlecode.starflow.core.script.spel.SpelScriptEngine.java

private Object evalExpression(Expression expression, ScriptContext scriptContext) {
    StandardEvaluationContext standardEvaluationContext = getStandardEvaluationContext(scriptContext);
    return expression.getValue(standardEvaluationContext);
}

From source file:com.graphaware.module.es.mapping.json.GraphDocumentMapper.java

public DocumentRepresentation getDocumentRepresentation(RelationshipExpressions relationship,
        DocumentMappingDefaults defaults, boolean buildSource) throws DocumentRepresentationException {
    Map<String, Object> source = new HashMap<>();

    if (buildSource) {
        if (null != properties) {
            for (String s : properties.keySet()) {
                Expression exp = getExpression(s);
                source.put(s, exp.getValue(relationship));
            }/*from   w  ww .  j av  a  2s. c o  m*/
        }

        if (defaults.includeRemainingProperties()) {
            for (String s : relationship.getProperties().keySet()) {
                if (!defaults.getBlacklistedRelationshipProperties().contains(s)) {
                    source.put(s, relationship.getProperties().get(s));
                }
            }
        }
    }
    String i = getIndex(relationship, defaults.getDefaultRelationshipsIndex());
    String id = getKeyProperty(relationship, defaults.getKeyProperty());
    return new DocumentRepresentation(i, getType(relationship), id, source);

}

From source file:com.creactiviti.piper.core.task.SpelTaskEvaluator.java

private Object evaluate(Object aValue, Context aContext) {
    StandardEvaluationContext context = createEvaluationContext(aContext);
    if (aValue instanceof String) {
        Expression expression = parser.parseExpression((String) aValue,
                new TemplateParserContext(PREFIX, SUFFIX));
        try {//from  ww w .j a  v a2s .c o  m
            return (expression.getValue(context));
        } catch (SpelEvaluationException e) {
            logger.debug(e.getMessage());
            return aValue;
        }
    } else if (aValue instanceof List) {
        List<Object> evaluatedlist = new ArrayList<>();
        List<Object> list = (List<Object>) aValue;
        for (Object item : list) {
            evaluatedlist.add(evaluate(item, aContext));
        }
        return evaluatedlist;
    } else if (aValue instanceof Map) {
        return evaluateInternal((Map<String, Object>) aValue, aContext);
    }
    return aValue;
}

From source file:com.seovic.core.expression.SpelExpression.java

/**
  * {@inheritDoc}//from w  w w.  j  a v a  2 s . c  om
  */
public T evaluate(Object target, Map variables) {
    Expression expression = getParsedExpression();
    StandardEvaluationContext context = m_context;

    context.setRootObject(target);
    if (variables != null) {
        context.setVariables(variables);
    }
    try {
        return (T) expression.getValue(context);
    } catch (EvaluationException e) {
        throw new RuntimeException(e);
    }
}

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  a va 2 s. c  o m
        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:com.graphaware.module.es.mapping.json.GraphDocumentMapper.java

public DocumentRepresentation getDocumentRepresentation(NodeExpressions node, DocumentMappingDefaults defaults,
        boolean buildSource) throws DocumentRepresentationException {
    Map<String, Object> source = new HashMap<>();
    String i = getIndex(node, defaults.getDefaultNodesIndex());
    String id = getKeyProperty(node, defaults.getKeyProperty());

    if (buildSource) {
        if (null != properties) {
            for (String s : properties.keySet()) {
                Expression exp = getExpression(s);
                Object o;// ww  w  .  j av a 2  s .  c om
                try {
                    o = exp.getValue(node);
                } catch (Exception e) {
                    LOG.warn(e.getMessage());
                    o = null;
                }
                if (null != o || !defaults.excludeEmptyProperties()) {
                    source.put(s, o);
                }
            }
        }

        if (defaults.includeRemainingProperties()) {
            for (String s : node.getProperties().keySet()) {
                if (!defaults.getBlacklistedNodeProperties().contains(s) && !source.containsKey(s)) {
                    Object o = node.getProperties().get(s);
                    if (o != null || !defaults.excludeEmptyProperties()) {
                        source.put(s, o);
                    }
                }
            }
        }
    }
    return new DocumentRepresentation(i, getType(node), id, source);
}

From source file:com.springinpractice.ch11.web.sitemap.Sitemap.java

public String resolve(String exprStr, Map<String, Object> context) {
    log.debug("Resolving expression: {}", exprStr);
    Expression expr = exprParser.parseExpression(exprStr);
    EvaluationContext evalContext = new StandardEvaluationContext(context);
    return (String) expr.getValue(evalContext);
}