Example usage for org.springframework.expression.spel.standard SpelExpressionParser SpelExpressionParser

List of usage examples for org.springframework.expression.spel.standard SpelExpressionParser SpelExpressionParser

Introduction

In this page you can find the example usage for org.springframework.expression.spel.standard SpelExpressionParser SpelExpressionParser.

Prototype

public SpelExpressionParser() 

Source Link

Document

Create a parser with default settings.

Usage

From source file:org.cloudfoundry.identity.uaa.scim.ScimUserTests.java

@Test
public void testSpelFilter() throws Exception {
    ScimUser user = new ScimUser();
    user.setId("123");
    user.setUserName("joe");
    ScimUser.Email email = new ScimUser.Email();
    email.setValue("foo@bar.com");
    user.setEmails(Arrays.asList(email));
    StandardEvaluationContext context = new StandardEvaluationContext(user);
    assertTrue(new SpelExpressionParser()
            .parseExpression("userName == 'joe' and !(emails.?[value=='foo@bar.com']).empty")
            .getValue(context, Boolean.class));
}

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

/**
 * Gets Id content// w  ww  .  j av  a  2 s  .c o  m
 * 
 * @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.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 w ww.j ava2  s  .  c  om
    // <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;
}

From source file:nl.minbzk.dwr.zoeken.enricher.uploader.ElasticSearchResultUploader.java

/**
 * Determine the database name, based on the composite key, or null if any of the composite key replacements could not be resolved.
 * //from  w w  w.  ja v  a  2  s .  co  m
 * XXX: We only consider the replacement values from the first document given.
 * 
 * @param name
 * @param nameComposition
 * @param namePrerequisitesExpression
 * @param documents
 * @return String
 */
private String determineAlternateDatabaseName(final String name, final String nameComposition,
        final String namePrerequisitesExpression, final List<Map<String, Object>> documents) {
    GregorianCalendar calendar = new GregorianCalendar();

    calendar.setTime(new Date());

    String result;

    result = nameComposition.replace("{name}", name).trim();

    result = result.replace("{year}", format("%04d", calendar.get(calendar.YEAR)));
    result = result.replace("{month}", format("%02d", calendar.get(calendar.MONTH)));

    if (documents.size() > 0) {
        final Map<String, Object> document = documents.get(0);

        while (result.contains("{") && result.indexOf("}") > result.indexOf("{")) {
            String fieldName = result.substring(result.indexOf("{") + 1, result.indexOf("}"));

            if (document.containsKey(fieldName) && !document.get(fieldName).getClass().isArray())
                result = result.replace("{" + fieldName + "}", document.get(fieldName).toString());
            else {
                if (logger.isDebugEnabled())
                    logger.debug(format(
                            "Field '%s' was missing from document with ID '%s' - will revert back to default collection '%s'",
                            fieldName, getReference(document), name));

                return null;
            }
        }

        // Also check the pre-requisite expression - only return a composite database name if it's met

        if (StringUtils.hasText(namePrerequisitesExpression)) {
            ExpressionParser parser = new SpelExpressionParser();

            final Map<String, Object> values = new HashMap<String, Object>();

            // XXX: Always get just the first value

            for (Map.Entry<String, Object> entry : document.entrySet())
                if (entry.getValue().getClass().isArray())
                    values.put(entry.getKey(), ((Object[]) entry.getValue())[0]);
                else if (entry.getValue() instanceof List)
                    values.put(entry.getKey(), ((List<Object>) entry.getValue()).get(0));
                else
                    values.put(entry.getKey(), entry.getValue());

            StandardEvaluationContext context = new StandardEvaluationContext(new Object() {
                public Map<String, Object> getValues() {
                    return values;
                }
            });

            if (!parser.parseExpression(namePrerequisitesExpression).getValue(context, Boolean.class)) {
                if (logger.isDebugEnabled())
                    logger.debug(format(
                            "Pre-requisite expression '%s' failed to match against document with ID '%s' - will revert back to default collection '%s'",
                            namePrerequisitesExpression, getReference(document), name));

                return null;
            }
        }
    }

    return result;
}

From source file:nl.minbzk.dwr.zoeken.enricher.uploader.SolrResultUploader.java

/**
 * Determine the database name, based on the composite key, or null if any of the composite key replacements could not be resolved.
 *
 * XXX: We only consider the replacement values from the first document given.
 *
 * @param name//from ww  w . j a  va2 s.co m
 * @param nameComposition
 * @param namePrerequisitesExpression
 * @param documents
 * @return String
 */
private String determineAlternateDatabaseName(final String name, final String nameComposition,
        final String namePrerequisitesExpression, final List<SolrInputDocument> documents) {
    GregorianCalendar calendar = new GregorianCalendar();

    calendar.setTime(new Date());

    String result;

    result = nameComposition.replace("{name}", name).trim();

    result = result.replace("{year}", String.format("%04d", calendar.get(calendar.YEAR)));
    result = result.replace("{month}", String.format("%02d", calendar.get(calendar.MONTH)));

    if (documents.size() > 0) {
        final SolrInputDocument document = documents.get(0);

        while (result.contains("{") && result.indexOf("}") > result.indexOf("{")) {
            String fieldName = result.substring(result.indexOf("{") + 1, result.indexOf("}"));

            if (document.containsKey(fieldName))
                result = result.replace("{" + fieldName + "}", document.getFieldValue(fieldName).toString());
            else {
                if (logger.isDebugEnabled())
                    logger.debug(String.format(
                            "Field '%s' was missing from document with ID '%s' - will revert back to default collection '%s'",
                            fieldName, document.getFieldValue(REFERENCE_FIELD), name));

                return null;
            }
        }

        // Also check the pre-requisite expression - only return a composite database name if it's met

        if (StringUtils.hasText(namePrerequisitesExpression)) {
            final ExpressionParser parser = new SpelExpressionParser();

            final Map<String, Object> values = new HashMap<String, Object>();

            for (Map.Entry<String, SolrInputField> entry : document.entrySet()) {
                // XXX: Always get just the first value

                /* if (entry.getValue().getValueCount() > 1)
                   values.put(entry.getKey(), entry.getValue().getValues());
                else */
                values.put(entry.getKey(), entry.getValue().getFirstValue());
            }

            StandardEvaluationContext context = new StandardEvaluationContext(new Object() {
                public Map<String, Object> getValues() {
                    return values;
                }
            });

            if (!parser.parseExpression(namePrerequisitesExpression).getValue(context, Boolean.class)) {
                if (logger.isDebugEnabled())
                    logger.debug(String.format(
                            "Pre-requisite expression '%s' failed to match against document with ID '%s' - will revert back to default collection '%s'",
                            namePrerequisitesExpression, document.get(REFERENCE_FIELD).toString(), name));

                return null;
            }
        }
    }

    return result;
}

From source file:ar.com.zauber.commons.web.uri.factory.ExpressionMapUriFactory.java

/** construye en base a string {@link UriExpression} */
private static Map<String, UriExpression> createUriExpression(final Map<String, String> uris, final Type type) {
    return createUriExpression(
            type == Type.SPEL ? new SpringExpressionTemplateFactory(new SpelExpressionParser())
                    : new UriTemplateExpressionFactory(),
            uris);/*from  w  ww. j  a va  2 s  .c  om*/
}

From source file:net.nan21.dnet.core.presenter.service.asgn.AbstractAsgnService.java

/**
 * /*from   w ww  . j  a va2 s  .c  o  m*/
 * @param e
 * @param m
 * @throws Exception
 */
public void entityToModel(E e, M m) throws Exception {
    ExpressionParser parser = new SpelExpressionParser();
    StandardEvaluationContext context = new StandardEvaluationContext(e);
    Map<String, String> refpaths = this.getDescriptor().getE2mConv();
    Method[] methods = this.getModelClass().getMethods();
    for (Method method : methods) {
        if (!method.getName().equals("set__clientRecordId__") && method.getName().startsWith("set")) {
            String fn = StringUtils.uncapitalize(method.getName().substring(3));
            try {
                method.invoke(m, parser.parseExpression(refpaths.get(fn)).getValue(context));
            } catch (Exception exc) {

            }
        }
    }
}

From source file:com.graphaware.module.es.mapping.json.GraphDocumentMapper.java

private SpelExpressionParser getExpressionParser() {
    if (null == expressionParser) {
        expressionParser = new SpelExpressionParser();
    }/*ww w . j  a  v a2s .c o m*/

    return expressionParser;
}

From source file:guru.qas.martini.DefaultMixologist.java

@Override
public Collection<Martini> getMartinis(@Nullable String spelFilter) {
    String trimmed = null == spelFilter ? "" : spelFilter.trim();

    Collection<Martini> martinis = null;
    if (!trimmed.isEmpty()) {
        SpelExpressionParser parser = new SpelExpressionParser();
        Expression expression = parser.parseExpression(trimmed);
        martinis = getMartinis(expression);
    }/*from   w  w  w  . jav  a2 s.  c o  m*/
    return null == martinis ? getMartinis() : martinis;
}

From source file:org.shredzone.commons.view.manager.ViewPattern.java

/**
 * Compiles a view pattern. Generates a parameter list, a list of expressions for
 * building URLs to this view, and a regular expression for matching URLs against this
 * view pattern.//  w w  w .j  a  v  a  2s  .  c o m
 *
 * @param pstr
 *            the view pattern
 * @param pattern
 *            {@link StringBuilder} to assemble the regular expression in
 * @param expList
 *            List of {@link Expression} to assemble expressions in
 * @param paramList
 *            List to assemble parameters in
 */
private void compilePattern(String pstr, StringBuilder pattern, List<Expression> expList,
        List<String> paramList) {
    ExpressionParser parser = new SpelExpressionParser();
    int previous = 0;

    Matcher m = PATH_PART.matcher(pstr);
    while (m.find()) {
        String fixedPart = pstr.substring(previous, m.start());
        if (fixedPart.indexOf('\'') >= 0) {
            throw new IllegalArgumentException("path parameters must not contain \"'\"");
        }

        String expressionPart = m.group(1);

        pattern.append(Pattern.quote(fixedPart));
        pattern.append("([^/]*)");

        paramList.add(expressionPart);

        expList.add(parser.parseExpression('\'' + fixedPart + '\''));
        expList.add(parser.parseExpression(expressionPart));

        previous = m.end();
    }

    String postPart = pstr.substring(previous);
    pattern.append(Pattern.quote(postPart));
    expList.add(parser.parseExpression('\'' + postPart + '\''));
}