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.kaaproject.kaa.server.admin.services.KaaAdminServiceImpl.java

private void validateProfileFilterBody(String endpointProfileSchemaId, String serverProfileSchemaId,
        String filterBody) throws KaaAdminServiceException {
    GenericRecord endpointProfileRecord = null;
    GenericRecord serverProfileRecord = null;
    try {/*  w  w  w  .j a v a2  s  . com*/
        if (endpointProfileSchemaId != null) {
            EndpointProfileSchemaDto endpointProfileSchema = getProfileSchema(endpointProfileSchemaId);
            endpointProfileRecord = getDefaultRecordFromCtlSchema(endpointProfileSchema.getCtlSchemaId());
        }
        if (serverProfileSchemaId != null) {
            ServerProfileSchemaDto serverProfileSchema = getServerProfileSchema(serverProfileSchemaId);
            serverProfileRecord = getDefaultRecordFromCtlSchema(serverProfileSchema.getCtlSchemaId());
        }
    } catch (Exception e) {
        throw Utils.handleException(e);
    }
    try {
        Expression expression = new SpelExpressionParser().parseExpression(filterBody);
        StandardEvaluationContext evaluationContext;
        if (endpointProfileRecord != null) {
            evaluationContext = new StandardEvaluationContext(endpointProfileRecord);
            evaluationContext.setVariable(DefaultFilterEvaluator.CLIENT_PROFILE_VARIABLE_NAME,
                    endpointProfileRecord);
        } else {
            evaluationContext = new StandardEvaluationContext();
        }
        evaluationContext.addPropertyAccessor(new GenericRecordPropertyAccessor());
        evaluationContext.setVariable(DefaultFilterEvaluator.EP_KEYHASH_VARIABLE_NAME, "test");
        if (serverProfileRecord != null) {
            evaluationContext.setVariable(DefaultFilterEvaluator.SERVER_PROFILE_VARIABLE_NAME,
                    serverProfileRecord);
        }
        expression.getValue(evaluationContext, Boolean.class);
    } catch (Exception e) {
        throw new KaaAdminServiceException("Invalid profile filter body!", e,
                ServiceErrorCode.BAD_REQUEST_PARAMS);
    }
}

From source file:org.kaaproject.kaa.server.admin.services.ProfileServiceImpl.java

@Override
public boolean testProfileFilter(RecordField endpointProfile, RecordField serverProfile, String filterBody)
        throws KaaAdminServiceException {
    checkAuthority(KaaAuthorityDto.TENANT_DEVELOPER, KaaAuthorityDto.TENANT_USER);
    try {//from  ww w.  ja v a 2  s.co m
        GenericRecord endpointProfileRecord = null;
        GenericRecord serverProfileRecord = null;
        try {
            if (endpointProfile != null) {
                endpointProfileRecord = FormAvroConverter.createGenericRecordFromRecordField(endpointProfile);
            }
            if (serverProfile != null) {
                serverProfileRecord = FormAvroConverter.createGenericRecordFromRecordField(serverProfile);
            }
        } catch (Exception ex) {
            throw Utils.handleException(ex);
        }
        try {
            final Expression expression = new SpelExpressionParser().parseExpression(filterBody);
            StandardEvaluationContext evaluationContext;
            if (endpointProfileRecord != null) {
                evaluationContext = new StandardEvaluationContext(endpointProfileRecord);
                evaluationContext.setVariable(DefaultFilterEvaluator.CLIENT_PROFILE_VARIABLE_NAME,
                        endpointProfileRecord);
            } else {
                evaluationContext = new StandardEvaluationContext();
            }
            evaluationContext.addPropertyAccessor(new GenericRecordPropertyAccessor());
            evaluationContext.setVariable(DefaultFilterEvaluator.EP_KEYHASH_VARIABLE_NAME, "test");
            if (serverProfileRecord != null) {
                evaluationContext.setVariable(DefaultFilterEvaluator.SERVER_PROFILE_VARIABLE_NAME,
                        serverProfileRecord);
            }
            return expression.getValue(evaluationContext, Boolean.class);
        } catch (Exception ex) {
            throw new KaaAdminServiceException("Invalid profile filter: " + ex.getMessage(), ex,
                    ServiceErrorCode.BAD_REQUEST_PARAMS);
        }
    } catch (Exception ex) {
        throw Utils.handleException(ex);
    }
}

From source file:org.kuali.rice.krad.uif.service.impl.ExpressionEvaluatorServiceImpl.java

/**
 * @see org.kuali.rice.krad.uif.service.ExpressionEvaluatorService#evaluateExpressionTemplate(java.lang.Object,
 *      java.util.Map, java.lang.String)
 *///from  w ww. j av  a  2  s .  com
public String evaluateExpressionTemplate(Object contextObject, Map<String, Object> evaluationParameters,
        String expressionTemplate) {
    StandardEvaluationContext context = new StandardEvaluationContext(contextObject);
    context.setVariables(evaluationParameters);
    addCustomFunctions(context);

    ExpressionParser parser = new SpelExpressionParser();

    String result = null;
    try {
        Expression expression = null;
        if (StringUtils.contains(expressionTemplate, UifConstants.EL_PLACEHOLDER_PREFIX)) {
            expression = parser.parseExpression(expressionTemplate, new TemplateParserContext(
                    UifConstants.EL_PLACEHOLDER_PREFIX, UifConstants.EL_PLACEHOLDER_SUFFIX));
        } else {
            expression = parser.parseExpression(expressionTemplate);
        }

        result = expression.getValue(context, String.class);
    } catch (Exception e) {
        LOG.error("Exception evaluating expression: " + expressionTemplate);
        throw new RuntimeException("Exception evaluating expression: " + expressionTemplate, e);
    }

    return result;
}

From source file:org.kuali.rice.krad.uif.view.DefaultExpressionEvaluator.java

/**
 * {@inheritDoc}/*from ww  w.ja  v  a 2 s.  co m*/
 */
@Override
public String evaluateExpressionTemplate(Map<String, Object> evaluationParameters, String expressionTemplate) {
    String result = null;

    try {
        Expression expression = retrieveCachedExpression(expressionTemplate);

        if (evaluationParameters != null) {
            evaluationContext.setVariables(evaluationParameters);
        }

        result = expression.getValue(evaluationContext, String.class);
    } catch (Exception e) {
        LOG.error("Exception evaluating expression: " + expressionTemplate);
        throw new RuntimeException("Exception evaluating expression: " + expressionTemplate, e);
    }

    return result;
}

From source file:org.metaeffekt.dcc.commons.mapping.AbstractPropertyExpression.java

@SuppressWarnings("unchecked")
protected <T> T evaluateExpression(String originalExpression, String value, Class<T> type) {
    final ExpressionParser parser = new SpelExpressionParser();

    try {//from   w ww. j ava2 s . com
        final StandardEvaluationContext context = new StandardEvaluationContext();
        context.setRootObject(propertiesHolder);
        context.addPropertyAccessor(new EnvironmentAccessor());
        context.setVariable(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, STANDARD_ENVIRONMENT);
        context.setVariable(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, STANDARD_ENVIRONMENT);

        final Expression expression = parser.parseExpression(value, PARSER_CONTEXT);

        return expression.getValue(context, type);
    } catch (ParseException | EvaluationException e) {
        LOG.debug(String.format("Failed to evaluate expression %s, and with replaced properties %s",
                originalExpression, value), e);
    }

    if (type == String.class) {
        return (T) value;
    }

    return null;
}

From source file:org.openlegacy.terminal.support.binders.ScreenEntityTablesBinder.java

@Override
public void populateEntity(Object screenEntity, TerminalSnapshot terminalSnapshot) {

    ScreenPojoFieldAccessor fieldAccessor = new SimpleScreenPojoFieldAccessor(screenEntity);

    Map<String, ScreenTableDefinition> tableDefinitions = tablesDefinitionProvider
            .getTableDefinitions(screenEntity.getClass());

    Set<String> tableFieldNames = tableDefinitions.keySet();

    if (logger.isDebugEnabled()) {
        logger.debug(MessageFormat.format("Found {0} tables to bind to entity {1}: {2}", tableFieldNames.size(),
                screenEntity.getClass().getName(), ArrayUtils.toString(tableFieldNames.toArray())));
    }/* w ww. j av  a2  s.co  m*/

    for (String tableFieldName : tableFieldNames) {

        ScreenTableDefinition tableDefinition = tableDefinitions.get(tableFieldName);
        List<Object> rows = new ArrayList<Object>();

        List<ScreenColumnDefinition> columnDefinitions = tableDefinition.getColumnDefinitions();
        int startRow = tableDefinition.getStartRow();
        int endRow = tableDefinition.getEndRow();
        for (int currentRow = startRow; currentRow <= endRow; currentRow += tableDefinition.getRowGaps()) {

            Object row = ReflectionUtil.newInstance(tableDefinition.getTableClass());
            ScreenPojoFieldAccessor rowAccessor = new SimpleScreenPojoFieldAccessor(row);

            // 3 states boolean - null - no keys found
            Boolean allKeysAreEmpty = null;

            for (ScreenColumnDefinition columnDefinition : columnDefinitions) {
                final TerminalPosition position = SimpleTerminalPosition.newInstance(
                        currentRow + columnDefinition.getRowsOffset(), columnDefinition.getStartColumn());
                final TerminalField terminalField = terminalSnapshot.getField(position);
                if (columnDefinition.getAttribute() == FieldAttributeType.Value) {
                    if (terminalField != null && terminalField.isHidden()) {
                        continue;
                    }
                    final String cellText = getCellContent(terminalSnapshot, position, columnDefinition);
                    if (columnDefinition.isKey()) {
                        if (cellText.length() == 0) {
                            if (logger.isDebugEnabled()) {
                                logger.debug(MessageFormat.format(
                                        "Key field {0} is empty in row {1}. Aborting table rows collecting",
                                        columnDefinition.getName(), position.getRow()));
                            }
                            allKeysAreEmpty = true;
                        } else {
                            allKeysAreEmpty = false;
                        }
                    }
                    final String expression = columnDefinition.getExpression();
                    if (!StringUtil.isEmpty(expression)) {
                        if (ExpressionUtils.isRegularExpression(expression)) {
                            final Object value = ExpressionUtils.applyRegularExpression(expression.trim(),
                                    cellText);
                            rowAccessor.setFieldValue(columnDefinition.getName(), value);
                        } else {
                            final Expression expr = expressionParser.parseExpression(expression);
                            final Map<String, Object> expressionVars = new HashMap<String, Object>();
                            expressionVars.put("row", row);
                            expressionVars.put("field", terminalField);
                            expressionVars.put("entity", screenEntity);
                            expressionVars.put("cellText", cellText);
                            final EvaluationContext evaluationContext = ExpressionUtils
                                    .createEvaluationContext(row, expressionVars);
                            final Object value = expr.getValue(evaluationContext,
                                    columnDefinition.getJavaType());
                            rowAccessor.setFieldValue(columnDefinition.getName(), value);
                        }
                    } else {
                        rowAccessor.setFieldValue(columnDefinition.getName(), cellText);
                    }
                    rowAccessor.setTerminalField(columnDefinition.getName(), terminalField);
                } else {
                    if (terminalField == null) {
                        logger.warn(MessageFormat.format("Unable to find field in position {0} for table:{1}",
                                position, tableDefinition.getTableEntityName()));
                        break;
                    }

                    if (columnDefinition.getAttribute() == FieldAttributeType.Editable) {
                        rowAccessor.setFieldValue(columnDefinition.getName(), terminalField.isEditable());
                    } else if (columnDefinition.getAttribute() == FieldAttributeType.Color) {
                        rowAccessor.setFieldValue(columnDefinition.getName(), terminalField.getColor());
                    }
                }
            }
            boolean filter = false;
            if (allKeysAreEmpty == null || allKeysAreEmpty == false) {
                if (tableDefinition.getStopExpression() != null) {
                    final Map<String, Object> expressionVars = new HashMap<String, Object>();
                    expressionVars.put("row", row);
                    expressionVars.put("text", terminalSnapshot.getRow(currentRow).getText());
                    final EvaluationContext evaluationContext = ExpressionUtils.createEvaluationContext(row,
                            expressionVars);
                    Expression expr = expressionParser.parseExpression(tableDefinition.getStopExpression());
                    Boolean stop = expr.getValue(evaluationContext, Boolean.class);
                    if (stop) {
                        break;
                    }
                }
                if (tableDefinition.getFilterExpression() != null) {
                    StandardEvaluationContext evaluationContext = new StandardEvaluationContext(row);
                    Expression expr = expressionParser.parseExpression(tableDefinition.getFilterExpression());
                    filter = expr.getValue(evaluationContext, Boolean.class);
                }
                if (!filter) {
                    rows.add(row);
                }
            }
        }
        fieldAccessor.setFieldValue(tableFieldName, rows);
    }
}

From source file:org.springframework.amqp.rabbit.listener.adapter.AbstractAdaptableMessageListener.java

private Address evaluateReplyTo(Message request, Object source, Object result, Expression expression) {
    Address replyTo = null;/*from   w w w  . j  a  va2s .  c  o  m*/
    Object value = expression.getValue(this.evalContext, new ReplyExpressionRoot(request, source, result));
    Assert.state(value instanceof String || value instanceof Address,
            "response expression must evaluate to a String or Address");
    if (value instanceof String) {
        replyTo = new Address((String) value);
    } else {
        replyTo = (Address) value;
    }
    return replyTo;
}

From source file:org.springframework.amqp.rabbit.stocks.context.RefreshScope.java

public Object resolveContextualObject(String key) {
    Expression expression = parseExpression(key);
    return expression.getValue(evaluationContext, beanFactory);
}

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

private boolean containsBeanByName(String name) {
    Expression parsed = new SpelExpressionParser().parseExpression("context.containsBean(\"" + name + "\")");
    return parsed.getValue(this.app, Boolean.class);
}

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

public boolean isRunning() {
    if (this.app == null) {
        return false;
    }//  w ww . ja va 2  s .co  m
    Expression parsed = new SpelExpressionParser().parseExpression("context.isRunning()");
    return parsed.getValue(this.app, Boolean.class);
}