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

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

Introduction

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

Prototype

public StandardEvaluationContext(Object rootObject) 

Source Link

Document

Create a StandardEvaluationContext with the given root object.

Usage

From source file:org.flockdata.transform.ExpressionHelper.java

private static Object evaluateExpression(ContentModel contentModel, Map<String, Object> row,
        String expression) {/*from   ww w . jav a  2 s .  c o  m*/
    if (expression == null)
        return null;

    StandardEvaluationContext context = new StandardEvaluationContext(row);
    setContextVariables(contentModel, row, context);

    try {
        return parser.parseExpression(expression).getValue(context);
    } catch (Exception e) {
        logger.debug(
                String.format("Error evaluating expression [%s], message was %s ", expression, e.getMessage()));
        throw (e);
    }
}

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

@Override
public boolean testProfileFilter(RecordField endpointProfile, RecordField serverProfile, String filterBody)
        throws KaaAdminServiceException {
    checkAuthority(KaaAuthorityDto.TENANT_DEVELOPER, KaaAuthorityDto.TENANT_USER);
    try {/*from  w  ww  .  j  a va 2 s.c om*/
        GenericRecord endpointProfileRecord = null;
        GenericRecord serverProfileRecord = null;
        try {
            if (endpointProfile != null) {
                endpointProfileRecord = FormAvroConverter.createGenericRecordFromRecordField(endpointProfile);
            }
            if (serverProfile != null) {
                serverProfileRecord = FormAvroConverter.createGenericRecordFromRecordField(serverProfile);
            }
        } 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);
            }
            return expression.getValue(evaluationContext, Boolean.class);
        } catch (Exception e) {
            throw new KaaAdminServiceException("Invalid profile filter: " + e.getMessage(), e,
                    ServiceErrorCode.BAD_REQUEST_PARAMS);
        }
    } catch (Exception e) {
        throw Utils.handleException(e);
    }
}

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 {//from  ww w. j ava  2  s.  c o  m
        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  www. ja va  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)
 *///w  w w  .j a va  2 s . c o  m
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.service.impl.ExpressionEvaluatorServiceImpl.java

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

    // if expression contains placeholders remove before evaluating
    if (StringUtils.startsWith(expressionStr, UifConstants.EL_PLACEHOLDER_PREFIX)
            && StringUtils.endsWith(expressionStr, UifConstants.EL_PLACEHOLDER_SUFFIX)) {
        expressionStr = StringUtils.removeStart(expressionStr, UifConstants.EL_PLACEHOLDER_PREFIX);
        expressionStr = StringUtils.removeEnd(expressionStr, UifConstants.EL_PLACEHOLDER_SUFFIX);
    }

    ExpressionParser parser = new SpelExpressionParser();
    Object result = null;
    try {
        Expression expression = parser.parseExpression(expressionStr);

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

    return result;
}

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

/**
 * {@inheritDoc}/*from   w w  w .j  a va  2s.  c  om*/
 */
@Override
public void initializeEvaluationContext(Object contextObject) {
    evaluationContext = new StandardEvaluationContext(contextObject);

    addCustomFunctions(evaluationContext);
}

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 w  w . j ava  2 s  .  com

    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.cloud.function.deployer.ApplicationRunner.java

public void run(String... args) {
    ClassLoader contextLoader = Thread.currentThread().getContextClassLoader();
    try {// www .  ja  v  a2 s  .c  om
        ClassUtils.overrideThreadContextClassLoader(this.classLoader);
        Class<?> cls = this.classLoader.loadClass(ContextRunner.class.getName());
        this.app = new StandardEvaluationContext(cls.getDeclaredConstructor().newInstance());
        this.app.setTypeLocator(new StandardTypeLocator(this.classLoader));
        runContext(this.source, defaultProperties(UUID.randomUUID().toString()), args);
    } catch (Exception e) {
        logger.error("Cannot deploy", e);
    } finally {
        ClassUtils.overrideThreadContextClassLoader(contextLoader);
    }
    RuntimeException e = getError();
    if (e != null) {
        throw e;
    }
}

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

public Object evaluate(String expression, Object root, Object... attrs) {
    Expression parsed = new SpelExpressionParser(this.config).parseExpression(expression);
    StandardEvaluationContext context = new StandardEvaluationContext(root);
    context.setTypeLocator(this.typeLocator);
    if (attrs.length % 2 != 0) {
        throw new IllegalArgumentException("Context attributes must be name, value pairs");
    }//from   www  .  j a v a  2s  .  c  o  m
    for (int i = 0; i < attrs.length / 2; i++) {
        String name = (String) attrs[2 * i];
        Object value = attrs[2 * i + 1];
        context.setVariable(name, value);
    }
    return parsed.getValue(context);
}