Example usage for org.springframework.expression ExpressionParser parseExpression

List of usage examples for org.springframework.expression ExpressionParser parseExpression

Introduction

In this page you can find the example usage for org.springframework.expression ExpressionParser parseExpression.

Prototype

Expression parseExpression(String expressionString) throws ParseException;

Source Link

Document

Parse the expression string and return an Expression object you can use for repeated evaluation.

Usage

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);
            }//from   w  ww.  j  a  v a 2s  .  com
        }

        healthBuilder.success(success);
    }
}

From source file:org.ldaptive.beans.spring.SpringClassDescriptor.java

/** {@inheritDoc} */
@Override//from w w w  .ja v  a 2 s . c  o  m
public void initialize(final Class<?> type) {
    // check for entry annotation
    final Entry entryAnnotation = AnnotationUtils.findAnnotation(type, Entry.class);
    if (entryAnnotation != null) {
        if (!entryAnnotation.dn().equals("")) {
            setDnValueMutator(new DnValueMutator() {
                @Override
                public String getValue(final Object object) {
                    final ExpressionParser parser = new SpelExpressionParser();
                    final Expression exp = parser.parseExpression(entryAnnotation.dn());
                    return exp.getValue(context, object, String.class);
                }

                @Override
                public void setValue(final Object object, final String value) {
                }
            });
        }
        for (final Attribute attr : entryAnnotation.attributes()) {
            final String expr = attr.property();
            final ExpressionParser parser = new SpelExpressionParser();
            final Expression exp = parser.parseExpression(expr);
            addAttributeValueMutator(new AttributeValueMutator() {
                @Override
                public String getName() {
                    return attr.name();
                }

                @Override
                public boolean isBinary() {
                    return attr.binary();
                }

                @Override
                public SortBehavior getSortBehavior() {
                    return attr.sortBehavior();
                }

                @Override
                public Collection<String> getStringValues(final Object object) {
                    @SuppressWarnings("unchecked")
                    final Collection<String> values = (Collection<String>) exp.getValue(context, object,
                            Collection.class);
                    return values;
                }

                @Override
                public Collection<byte[]> getBinaryValues(final Object object) {
                    @SuppressWarnings("unchecked")
                    final Collection<byte[]> values = (Collection<byte[]>) exp.getValue(context, object,
                            Collection.class);
                    return values;
                }

                @Override
                public void setStringValues(final Object object, final Collection<String> values) {
                    exp.setValue(context, object, values);
                }

                @Override
                public void setBinaryValues(final Object object, final Collection<byte[]> values) {
                    exp.setValue(context, object, values);
                }
            });
        }
    }
}

From source file:app.web.InterpreterController.java

@RequestMapping("/interpreter/run")
public ModelAndView run(@RequestParam("script") String script) {
    Transaction transaction = Db.getSession().beginTransaction();
    // Groovy Shell
    //        Binding binding = new Binding();
    //        binding.setVariable("userService", userService); // FIXME: go through ApplicationContext or try to use SpEl instead?
    //        Object result = new GroovyShell(binding).parse(script).run();
    // Groovy Interpreter
    //        Object result = GroovyInterpreter.run(script);
    // SpEl/*w w w  .ja v a 2s .c om*/
    ExpressionParser parser = new SpelExpressionParser();
    StandardEvaluationContext ctx = new StandardEvaluationContext();
    ctx.setBeanResolver(new BeanFactoryResolver(beanFactory));
    Object result = parser.parseExpression(script).getValue(ctx);
    //        Db.flush(); // can not flush here, we get org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
    transaction.commit();

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("script", script);
    map.put("result", result != null ? result.toString().replaceAll("\n", "<br/>").replaceAll(" ", "&nbsp;")
            : Void.class.getSimpleName());
    return new ModelAndView("/interpreter", map);
}

From source file:org.ldaptive.beans.spring.SpelAttributeValueMutator.java

/**
 * Creates a new spel attribute value mutator.
 *
 * @param  attr  containing the SPEL configuration
 * @param  context  containing the values
 *///ww w .  j av a 2  s  .  com
public SpelAttributeValueMutator(final Attribute attr, final EvaluationContext context) {
    attribute = attr;

    final ExpressionParser parser = new SpelExpressionParser();
    expression = parser
            .parseExpression(attribute.property().length() > 0 ? attribute.property() : attribute.name());
    evaluationContext = context;
    if ("".equals(attribute.transcoder())) {
        transcoder = null;
    } else {
        transcoder = parser.parseExpression(attribute.transcoder()).getValue(ValueTranscoder.class);
    }
}

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

/**
 * @param annotation//from   w w  w.  j a  v a 2 s.co  m
 * @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:org.craftercms.security.processors.impl.UrlAccessRestrictionCheckingProcessor.java

/**
 * Sets the map of restrictions. Each key of the map is ANT-style path pattern, used to match the URLs of incoming
 * requests, and each value is a Spring EL expression.
 *///from   ww  w  .j  av  a  2 s .  co m
@Required
public void setUrlRestrictions(Map<String, String> restrictions) {
    urlRestrictions = new LinkedHashMap<>();

    ExpressionParser parser = new SpelExpressionParser();

    for (Map.Entry<String, String> entry : restrictions.entrySet()) {
        urlRestrictions.put(entry.getKey(), parser.parseExpression(entry.getValue()));
    }
}

From source file:uk.co.christhomson.sibyl.cache.connectors.HashMapConnector.java

public Map<?, ?> query(String cacheName, String query) throws CacheException {
    Map<Object, Object> results = new HashMap<Object, Object>();
    Map<?, ?> data = getCache(cacheName);

    ExpressionParser parser = new SpelExpressionParser();

    for (Object key : data.keySet()) {
        Object value = data.get(key);
        EvaluationContext keyContext = new StandardEvaluationContext(key);

        Expression exp = parser.parseExpression(query);
        boolean result = exp.getValue(keyContext, Boolean.class);

        if (result) {
            results.put(key, value);//w  w w. ja  va2 s.c o m
        }
    }

    return results;
}

From source file:org.gvnix.datatables.tags.RooTableTag.java

/**
 * Gets Id content/*from w  ww .  j ava 2 s  .  com*/
 * 
 * @return
 * @throws JspException
 */
protected String getIdContent() throws JspException {
    ExpressionParser parser = new SpelExpressionParser();
    Expression exp = parser.parseExpression(this.rowIdBase);
    EvaluationContext context = new StandardEvaluationContext(currentObject);

    Object value = exp.getValue(context);
    String result = "";

    if (value == null) {
        // Use AbstractTablaTag standard behavior
        try {
            value = PropertyUtils.getNestedProperty(this.currentObject, this.rowIdBase);

        } catch (IllegalAccessException e) {
            LOGGER.error("Unable to get the value for the given rowIdBase {}", this.rowIdBase);
            throw new JspException(e);
        } catch (InvocationTargetException e) {
            LOGGER.error("Unable to get the value for the given rowIdBase {}", this.rowIdBase);
            throw new JspException(e);
        } catch (NoSuchMethodException e) {
            LOGGER.error("Unable to get the value for the given rowIdBase {}", this.rowIdBase);
            throw new JspException(e);
        }
    }

    if (value != null) {
        // TODO manage exceptions to log it
        ConversionService conversionService = (ConversionService) helper.getBean(this.pageContext,
                getConversionServiceId());
        if (conversionService != null && conversionService.canConvert(value.getClass(), String.class)) {
            result = conversionService.convert(value, String.class);
        } else {
            result = ObjectUtils.getDisplayString(value);
        }
        result = HtmlUtils.htmlEscape(result);
    }

    return result;
}

From source file:org.shredzone.cilla.web.fragment.manager.FragmentInvoker.java

/**
 * Creates a new {@link FragmentInvoker}.
 *
 * @param bean/*www .  j a va 2s  .c  o m*/
 *            target Spring bean to be invoked
 * @param method
 *            target method to be invoked
 * @param template
 *            JSP template to be used for rendering, or {@code null} if none is
 *            defined
 * @param conversionService
 *            {@link ConversionService} to be used for converting
 */
public FragmentInvoker(Object bean, Method method, String template, ConversionService conversionService) {
    this.bean = bean;
    this.method = method;
    this.template = template;
    this.conversionService = conversionService;

    Annotation[][] annotations = method.getParameterAnnotations();
    expressions = new Expression[annotations.length];
    items = new boolean[annotations.length];

    ExpressionParser parser = new SpelExpressionParser();

    for (int ix = 0; ix < annotations.length; ix++) {
        for (Annotation sub : annotations[ix]) {
            if (sub instanceof FragmentValue) {
                expressions[ix] = parser.parseExpression(((FragmentValue) sub).value());
            } else if (sub instanceof FragmentItem) {
                items[ix] = true;
            }
        }
    }
}

From source file:org.gvnix.datatables.tags.RooColumnTag.java

@Override
protected String getColumnContent() throws JspException {

    // Try to do the same as the roo table.tagx tag to get the value for the
    // column//from   ww w  . j a v a 2  s  .  c  o  m
    // <c:choose>
    // <c:when test="${columnType eq 'date'}">
    // <spring:escapeBody>
    // <fmt:formatDate value="${item[column]}"
    // pattern="${fn:escapeXml(columnDatePattern)}" var="colTxt" />
    // </spring:escapeBody>
    // </c:when>
    // <c:when test="${columnType eq 'calendar'}">
    // <spring:escapeBody>
    // <fmt:formatDate value="${item[column].time}"
    // pattern="${fn:escapeXml(columnDatePattern)}" var="colTxt"/>
    // </spring:escapeBody>
    // </c:when>
    // <c:otherwise>
    // <c:set var="colTxt">
    // <spring:eval expression="item[column]" htmlEscape="false" />
    // </c:set>
    // </c:otherwise>
    // </c:choose>
    // <c:if test="${columnMaxLength ge 0}">
    // <c:set value="${fn:substring(colTxt, 0, columnMaxLength)}"
    // var="colTxt" />
    // </c:if>
    // <c:out value="${colTxt}" />

    // TODO log problem resolving column content

    if (StringUtils.isBlank(this.property)) {
        return "";
    }
    TableTag parent = (TableTag) getParent();

    ExpressionParser parser = new SpelExpressionParser();
    String unescapedProperty = this.property.replace(SEPARATOR_FIELDS_ESCAPED, SEPARATOR_FIELDS);
    Expression exp = parser.parseExpression(unescapedProperty);
    EvaluationContext context = new StandardEvaluationContext(parent.getCurrentObject());

    Object value = exp.getValue(context);
    String result = "";

    if (value != null) {

        if (Date.class.isAssignableFrom(value.getClass())) {
            result = dateTimePattern.format(value);
        } else if (value instanceof Calendar) {
            result = dateTimePattern.format(((Calendar) value).getTime());
        } else {
            ConversionService conversionService = (ConversionService) helper.getBean(this.pageContext,
                    getConversionServiceId());
            if (conversionService != null && conversionService.canConvert(value.getClass(), String.class)) {
                result = conversionService.convert(value, String.class);
            } else {
                result = ObjectUtils.getDisplayString(value);
            }
            // result = (isHtmlEscape() ? HtmlUtils.htmlEscape(result) :
            // result);
            // result = (this.javaScriptEscape ?
            // JavaScriptUtils.javaScriptEscape(result) : result);
        }

    } else {
        result = super.getColumnContent();
    }
    if (maxLength >= 0 && result.length() > maxLength) {
        result = result.substring(0, maxLength);
    }

    return result;
}