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
<T> T getValue(EvaluationContext context, @Nullable Class<T> desiredResultType) throws EvaluationException;

Source Link

Document

Evaluate the expression in a specified context which can resolve references to properties, methods, types, etc.

Usage

From source file:org.springframework.cloud.function.deployer.ApplicationRunner.java

private RuntimeException getError() {
    if (this.app == null) {
        return null;
    }//from ww w  . ja v  a  2 s  .c  o m
    Expression parsed = new SpelExpressionParser().parseExpression("error");
    Throwable e = parsed.getValue(this.app, Throwable.class);
    if (e == null) {
        return null;
    }
    if (e instanceof RuntimeException) {
        return (RuntimeException) e;
    }
    return new IllegalStateException("Cannot launch", e);
}

From source file:org.springframework.cloud.sleuth.annotation.SpelTagValueExpressionResolver.java

@Override
public String resolve(String expression, Object parameter) {
    try {/*w  w w .  j  a v  a  2s .co m*/
        ExpressionParser expressionParser = new SpelExpressionParser();
        Expression expressionToEvaluate = expressionParser.parseExpression(expression);
        return expressionToEvaluate.getValue(parameter, String.class);
    } catch (Exception e) {
        log.error("Exception occurred while tying to evaluate the SPEL expression [" + expression + "]", e);
    }
    return parameter.toString();
}

From source file:org.springframework.cloud.stream.app.hdfs.dataset.sink.HdfsDatasetSinkConfiguration.java

private static PartitionStrategy parsePartitionExpression(String expression) {

    List<String> expressions = Arrays.asList(expression.split("/"));

    ExpressionParser parser = new SpelExpressionParser();
    PartitionStrategy.Builder psb = new PartitionStrategy.Builder();
    StandardEvaluationContext ctx = new StandardEvaluationContext(psb);
    for (String expr : expressions) {
        try {/* ww w . ja v  a  2 s. c  om*/
            Expression e = parser.parseExpression(expr);
            psb = e.getValue(ctx, PartitionStrategy.Builder.class);
        } catch (SpelParseException spe) {
            if (!expr.trim().endsWith(")")) {
                throw new StoreException("Invalid partitioning expression '" + expr
                        + "' -  did you forget the closing parenthesis?", spe);
            } else {
                throw new StoreException("Invalid partitioning expression '" + expr + "'!", spe);
            }
        } catch (SpelEvaluationException see) {
            throw new StoreException("Invalid partitioning expression '" + expr + "' - failed evaluation!",
                    see);
        } catch (NullPointerException npe) {
            throw new StoreException("Invalid partitioning expression '" + expr + "' - was evaluated to null!",
                    npe);
        }
    }
    return psb.build();
}

From source file:org.springframework.cloud.stream.app.jdbc.sink.JdbcSinkConfiguration.java

@Bean
@ServiceActivator(autoStartup = "false", inputChannel = Sink.INPUT)
public JdbcMessageHandler jdbcMessageHandler(DataSource dataSource) {
    final MultiValueMap<String, Expression> columnExpressionVariations = new LinkedMultiValueMap<>();
    for (Map.Entry<String, String> entry : properties.getColumns().entrySet()) {
        String value = entry.getValue();
        columnExpressionVariations.add(entry.getKey(), spelExpressionParser.parseExpression(value));
        if (!value.startsWith("payload")) {
            columnExpressionVariations.add(entry.getKey(),
                    spelExpressionParser.parseExpression("payload." + value));
        }//  w ww  . j a v a  2 s  . c  o  m
    }
    JdbcMessageHandler jdbcMessageHandler = new JdbcMessageHandler(dataSource,
            generateSql(properties.getTableName(), columnExpressionVariations.keySet()));
    jdbcMessageHandler.setSqlParameterSourceFactory(new SqlParameterSourceFactory() {
        @Override
        public SqlParameterSource createParameterSource(Object o) {
            if (!(o instanceof Message)) {
                throw new IllegalArgumentException("Unable to handle type " + o.getClass().getName());
            }
            Message<?> message = (Message<?>) o;
            MapSqlParameterSource parameterSource = new MapSqlParameterSource();
            for (String key : columnExpressionVariations.keySet()) {
                List<Expression> spels = columnExpressionVariations.get(key);
                Object value = NOT_SET;
                EvaluationException lastException = null;
                for (Expression spel : spels) {
                    try {
                        value = spel.getValue(evaluationContext, message);
                        break;
                    } catch (EvaluationException e) {
                        lastException = e;
                    }
                }
                if (value == NOT_SET) {
                    if (lastException != null) {
                        logger.info(
                                "Could not find value for column '" + key + "': " + lastException.getMessage());
                    }
                    parameterSource.addValue(key, null);
                } else {
                    if (value instanceof JsonPropertyAccessor.ToStringFriendlyJsonNode) {
                        // Need to do some reflection until we have a getter for the Node
                        DirectFieldAccessor dfa = new DirectFieldAccessor(value);
                        JsonNode node = (JsonNode) dfa.getPropertyValue("node");
                        Object valueToUse;
                        if (node == null || node.isNull()) {
                            valueToUse = null;
                        } else if (node.isNumber()) {
                            valueToUse = node.numberValue();
                        } else if (node.isBoolean()) {
                            valueToUse = node.booleanValue();
                        } else {
                            valueToUse = node.textValue();
                        }
                        parameterSource.addValue(key, valueToUse);
                    } else {
                        parameterSource.addValue(key, value);
                    }
                }
            }
            return parameterSource;
        }
    });
    return jdbcMessageHandler;
}

From source file:org.springframework.cloud.stream.app.pmml.processor.PmmlProcessorConfiguration.java

private Object resolveActiveValue(Message<?> input, String fieldName) {
    Expression expression = properties.getInputs().get(fieldName);
    if (expression == null) {
        // Assume same-name mapping on payload properties
        expression = spelExpressionParser.parseExpression("payload." + fieldName);
    }//from ww w  . j  av  a 2  s  . co m
    Object result = null;
    try {
        result = expression.getValue(evaluationContext, input);
    } catch (SpelEvaluationException e) {
        // The evaluator will get a chance to handle missing values
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Resolving value for input field " + fieldName + " using SpEL[" + expression
                + "], result is " + result);
    }
    return result;
}

From source file:org.springframework.integration.gateway.GatewayMethodInboundMessageMapper.java

private Object evaluatePayloadExpression(String expressionString, Object argumentValue) {
    Expression expression = this.parameterPayloadExpressions.get(expressionString);
    if (expression == null) {
        expression = PARSER.parseExpression(expressionString);
        this.parameterPayloadExpressions.put(expressionString, expression);
    }//from  ww  w.  j  a  va2s.  c om
    return expression.getValue(this.payloadExpressionEvaluationContext, argumentValue);
}

From source file:org.springframework.integration.util.AbstractExpressionEvaluator.java

protected <T> T evaluateExpression(Expression expression, Class<T> expectedType) {
    return expression.getValue(this.getEvaluationContext(), expectedType);
}

From source file:org.springframework.integration.xml.transformer.XsltPayloadTransformer.java

private Transformer buildTransformer(Message<?> message) throws TransformerException {
    // process individual mappings
    Transformer transformer = this.templates.newTransformer();
    if (this.xslParameterMappings != null) {
        for (String parameterName : this.xslParameterMappings.keySet()) {
            Expression expression = this.xslParameterMappings.get(parameterName);
            try {
                Object value = expression.getValue(this.evaluationContext, message);
                transformer.setParameter(parameterName, value);
            } catch (Exception e) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Evaluation of header expression '" + expression.getExpressionString()
                            + "' failed. The XSLT parameter '" + parameterName + "' will be skipped.");
                }//from w  w  w. j  ava 2 s  .co  m
            }
        }
    }
    // process xslt-parameter-headers
    MessageHeaders headers = message.getHeaders();
    if (!ObjectUtils.isEmpty(this.xsltParamHeaders)) {
        for (String headerName : headers.keySet()) {
            if (PatternMatchUtils.simpleMatch(this.xsltParamHeaders, headerName)) {
                transformer.setParameter(headerName, headers.get(headerName));
            }
        }
    }
    return transformer;
}