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:net.asfun.jangod.base.Context.java

public Object getAttribute(String expression) {
    StandardEvaluationContext context = new StandardEvaluationContext();
    context.addPropertyAccessor(new ReflectivePropertyAccessor());
    context.addPropertyAccessor(new BeanFactoryAccessor());
    context.addPropertyAccessor(new MapAccessor());
    Expression parseExpression = null;
    try {//from  www.ja va  2 s.  c om
        parseExpression = parser.parseExpression(expression);
    } catch (ParseException e) {
        // ignore parsing problem, might be jangod token
        return null;
    }
    try {
        return parseExpression.getValue(context, sessionBindings);
    } catch (EvaluationException e) {
        // ignore. try global application global bindings
    }
    try {
        return parseExpression.getValue(context, application.globalBindings);
    } catch (EvaluationException e) {
        return null;
    }
}

From source file:com._4dconcept.springframework.data.marklogic.core.query.QueryBuilder.java

@Nullable
private String expandDefaultCollection(@Nullable String collection,
        DocumentExpressionContext identifierContext) {
    Expression expression = detectExpression(collection);

    if (expression == null) {
        return collection;
    } else {/*from w  w w .jav  a 2s  . c o  m*/
        return expression.getValue(identifierContext, String.class);
    }
}

From source file:fr.xebia.audit.AuditAspect.java

protected String buildMessage(String template, Object invokedObject, Object[] args, Object returned,
        Throwable throwned, long durationInNanos) {
    try {//from   w  w w .j a v a  2 s.c o  m
        Expression expression = expressionCache.get(template);
        if (expression == null) {
            expression = expressionParser.parseExpression(template, parserContext);
            expressionCache.put(template, expression);
        }

        String evaluatedMessage = expression.getValue(new RootObject(invokedObject, args, returned, throwned),
                String.class);

        StringBuilder msg = new StringBuilder();

        SimpleDateFormat simpleDateFormat = (SimpleDateFormat) dateFormatPrototype.clone();
        msg.append(simpleDateFormat.format(new Date()));

        msg.append(" ").append(evaluatedMessage);

        if (throwned != null) {
            msg.append(" threw '");
            appendThrowableCauses(throwned, ", ", msg);
            msg.append("'");
        }
        msg.append(" by ");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            msg.append("anonymous");
        } else {
            msg.append(authentication.getName());
            if (authentication.getDetails() instanceof WebAuthenticationDetails) {
                WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
                msg.append(" coming from " + details.getRemoteAddress());
            }
        }
        msg.append(" in ").append(TimeUnit.MILLISECONDS.convert(durationInNanos, TimeUnit.NANOSECONDS))
                .append(" ms");
        return msg.toString();
    } catch (RuntimeException e) {
        StringBuilder msg = new StringBuilder("Exception evaluating template '" + template + "': ");
        appendThrowableCauses(e, ", ", msg);
        return msg.toString();
    }
}

From source file:io.gravitee.gateway.services.healthcheck.EndpointHealthCheck.java

private void validateAssertions(final HealthStatus.Builder healthBuilder, final HealthCheckResponse response) {
    healthBuilder.success().status(response.getStatus());

    // Run assertions
    if (healthCheck.getExpectation().getAssertions() != null) {
        Iterator<String> assertionIterator = healthCheck.getExpectation().getAssertions().iterator();
        boolean success = true;
        while (success && assertionIterator.hasNext()) {
            String assertion = assertionIterator.next();
            ExpressionParser parser = new SpelExpressionParser();
            Expression expr = parser.parseExpression(assertion);

            StandardEvaluationContext context = new StandardEvaluationContext();
            context.registerFunction("jsonPath",
                    BeanUtils.resolveSignature("evaluate", JsonPathFunction.class));

            context.setVariable("response", response);

            success = expr.getValue(context, boolean.class);

            if (!success) {
                healthBuilder.message("Assertion can not be verified : " + assertion);
            }//w  w w.j  a  va 2s. co  m
        }

        healthBuilder.success(success);
    }
}

From source file:org.focusns.common.web.page.engine.widget.WidgetPageEngine.java

public void doAction(HttpServletRequest request, HttpServletResponse response) throws PageEngineException {
    ///*from www .  j  av a 2s .  c om*/
    try {
        //
        PageConfig pageConfig = (PageConfig) request.getSession().getAttribute("pageConfig");
        String widgetId = (String) request.getAttribute("widgetId");
        WidgetConfig widgetConfig = pageConfig.getWidgetConfigById(widgetId);
        //
        WidgetRequest widgetRequest = new WidgetRequest(request, widgetConfig, "action");
        WidgetResponse widgetResponse = new WidgetResponse(response);
        //
        String lookupPath = urlPathHelper.getLookupPathForRequest(request);
        String queryString = urlPathHelper.getOriginatingQueryString(request);
        String actionPath = "/widget" + lookupPath + "?" + queryString;
        ServletContext widgetContext = getServletContext();
        if (StringUtils.hasText(widgetConfig.getContext())) {
            widgetContext = getServletContext().getContext(widgetConfig.getContext());
            if (widgetContext == null) {
                return;
            }
        }
        //
        widgetRequest.setAttribute("requestType", "action");
        widgetRequest.setAttribute("widgetConfig", widgetConfig);
        //
        Navigator navigator = Navigator.reset();
        //
        for (WidgetActionInterceptor actionInterceptor : widgetActionInterceptors) {
            actionInterceptor.beforeAction(request, response);
        }
        widgetContext.getRequestDispatcher(actionPath).forward(widgetRequest, widgetResponse);
        //
        for (WidgetActionInterceptor actionInterceptor : widgetActionInterceptors) {
            actionInterceptor.afterAction(request, response);
        }
        //
        if (!StringUtils.hasText(navigator.getNavigateTo())) {
            widgetResponse.flushBuffer();
            return;
        }
        //
        String pathExpr = widgetConfig.getNavigationMap().get(navigator.getNavigateTo());
        if (StringUtils.hasText(pathExpr)) {
            Expression expression = expressionParser.parseExpression(pathExpr,
                    ParserContext.TEMPLATE_EXPRESSION);
            EvaluationContext evaluationContext = createEvaluationContext();
            String path = (String) expression.getValue(evaluationContext, request);
            //
            request.getSession().setAttribute("redirectAttributes", navigator.getRedirectAttributes());
            response.sendRedirect(request.getContextPath() + path);
        }
        //
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new PageEngineException(e.getMessage(), e);
    } finally {
        Navigator.reset();
    }
}

From source file:it.geosolutions.geobatch.actions.ds2ds.DsBaseAction.java

/**
 * Builds an attribute value to be written on output.
 * @param sourceFeature source used to get values to write
 * @param attributeName name of the attribute in the output feature
 * @return//from  ww  w .  j av a 2 s  .  co  m
 */
protected Object getAttributeValue(SimpleFeature sourceFeature, String attributeName,
        Map<String, String> mappings) {
    // gets mapping for renamed attributes
    if (configuration.getAttributeMappings().containsKey(attributeName)) {
        attributeName = configuration.getAttributeMappings().get(attributeName).toString();
    } else if (mappings.containsKey(attributeName)) {
        attributeName = mappings.get(attributeName);
    }

    if (isExpression(attributeName)) {
        String expression = attributeName.trim().substring(2, attributeName.length() - 1);
        org.springframework.expression.Expression spelExpression = expressionParser.parseExpression(expression);

        return spelExpression.getValue(evaluationContext, sourceFeature);
    } else {
        return sourceFeature.getAttribute(attributeName);
    }
}

From source file:it.geosolutions.geobatch.destination.common.InputObject.java

/**
 * Returns the mapped value of a given attribute for the current input feature.
 * /*  w w  w  . j a  va  2 s . c  o  m*/
 * @param inputFeature
 * @param string
 * @return
 * @throws IOException 
 */
protected Object getMapping(SimpleFeature inputFeature, Map<String, String> mappings, String attribute)
        throws IOException {
    String expression = mappings.get(attribute);
    // TODO: introduce some form of expression evaluation
    if (expression.trim().startsWith("#{") && expression.trim().endsWith("}")) {
        expression = expression.trim().substring(2, expression.length() - 1);
        org.springframework.expression.Expression spelExpression = expressionParser.parseExpression(expression);

        return spelExpression.getValue(evaluationContext, inputFeature);
    } else {
        return inputFeature.getAttribute(expression);
    }
}

From source file:net.gplatform.sudoor.server.security.model.DefaultPermissionEvaluator.java

@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
    String name = targetDomainObject.getClass().getName();
    Map<Object, Expression> m = expressions.get(name);
    if (m == null) {
        m = new HashMap<Object, Expression>();
        expressions.put(name, m);//from   ww w. j a v  a  2  s.c om
    }

    Expression expression = m.get(permission);
    if (expression == null) {
        String expressionString = getExpressionString(name, permission);
        if (StringUtils.isNotEmpty(expressionString)) {
            expression = parser.parseExpression(expressionString);
        } else {
            expression = parser.parseExpression("false");
            LOG.warn("No Expression configed for name: [{}] permission: [{}], Default to false Expression!",
                    name, permission);
        }
        m.put(permission, expression);
    }

    context.setVariable("authentication", authentication);
    context.setVariable("target", targetDomainObject);

    boolean res = false;
    try {
        res = expression.getValue(context, Boolean.class);
        LOG.debug("Evaluate Result : [{}] for name: [{}] permission: [{}]", res, name, permission);
    } catch (Exception e) {
        LOG.error("Error parse expression", e);
    }
    return res;
}

From source file:com.oembedler.moon.graphql.engine.execute.GraphQLAbstractRxExecutionStrategy.java

protected Observable<Double> calculateFieldComplexity(ExecutionContext executionContext,
        GraphQLObjectType parentType, List<Field> fields, Observable<Double> childScore) {
    return childScore.flatMap(aDouble -> {
        Observable<Double> result = Observable.just(aDouble + NODE_SCORE);
        GraphQLFieldDefinition fieldDef = getFieldDef(executionContext.getGraphQLSchema(), parentType,
                fields.get(0));//from  w ww  .j a va  2s  .  c  om
        if (fieldDef != null) {
            GraphQLFieldDefinitionWrapper graphQLFieldDefinitionWrapper = getGraphQLFieldDefinitionWrapper(
                    fieldDef);
            if (graphQLFieldDefinitionWrapper != null) {
                Expression expression = graphQLFieldDefinitionWrapper.getComplexitySpelExpression();
                if (expression != null) {
                    Map<String, Object> argumentValues = valuesResolver.getArgumentValues(
                            fieldDef.getArguments(), fields.get(0).getArguments(),
                            executionContext.getVariables());
                    StandardEvaluationContext context = new StandardEvaluationContext();
                    context.setVariable(GraphQLConstants.EXECUTION_COMPLEXITY_CHILD_SCORE, aDouble);
                    if (argumentValues != null)
                        context.setVariables(argumentValues);
                    result = Observable.just(expression.getValue(context, Double.class));
                }
            }
        }
        return addComplexityCheckObservable(executionContext, result);
    });
}

From source file:com.px100systems.data.browser.controller.MainController.java

@SuppressWarnings("unchecked")
private void browse(ModelAndView mav, String entityName, Integer tenantId, String filter, Integer orderBy,
        Integer order, String fields) {
    mav.setViewName("main");
    mav.addObject("cluster", clusterName);

    LinkedHashMap<Integer, String> tenants = dataStorage.getTenants();
    mav.addObject("tenants", tenants);
    mav.addObject("tenantId", tenantId != null ? tenantId : tenants.keySet().iterator().next());

    Set<String> entities = dataStorage.entityNames();
    mav.addObject("entities", entities);
    mav.addObject("entityName", entityName != null ? entityName : entities.iterator().next());

    mav.addObject("filter", filter == null ? "" : filter.replace("\"", "&quot;"));
    mav.addObject("orderBy", orderBy);
    mav.addObject("order", order);
    mav.addObject("fields", fields == null ? "" : fields.replace("\"", "&quot;"));

    LinkedHashMap<Long, String> result = new LinkedHashMap<Long, String>();
    mav.addObject("result", result);

    if (entityName != null)
        try {/*from   www. j  a v  a2s . co  m*/
            Class entityClass = dataStorage.entityClass(entityName);

            String fieldsEL = fields != null && !fields.trim().isEmpty() ? fields.trim()
                    : "${#root.toString()}";
            Expression expression = new SpelExpressionParser().parseExpression(fieldsEL,
                    new ELTemplateParserContext());

            Transaction tx = dataStorage.transaction(tenantId);
            Criteria criteria = parseCriteria(filter);

            for (Object row : tx.find(entityClass, criteria,
                    Collections.singletonList(parseOrderBy(orderBy == 2, order == 2)), MAX_ROWS)) {
                result.put(((StoredBean) row).getId(),
                        expression.getValue(new SpringELCtx(row), String.class).replace("\"", "&quot;"));
            }
        } catch (Exception e) {
            mav.addObject("error", e.getMessage());
        }
}