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:it.geosolutions.opensdi2.workflow.transform.spel.SpelTransformer.java

@Override
public DESTTYPE transform(SOURCETYPE source) throws IllegalArgumentException {

    //create the output object
    DESTTYPE output = null;// w ww  .  ja  v  a 2 s .co  m
    if (outputObject == null && outputPreBuilder != null) {
        output = outputPreBuilder.build(rules);
    } else if (outputPreBuilder != null) {
        output = outputPreBuilder.build(outputObject, rules);
    } else if (outputObject != null) {
        output = outputObject;
    } else {
        throw new IllegalArgumentException("no outputObject or outPrebuilder provided");
    }

    //create evaluation Context
    StandardEvaluationContext inputEvaluationContext = new StandardEvaluationContext(source);
    StandardEvaluationContext outputevaluationContext = new StandardEvaluationContext(output);
    //set property accessors for input and output
    inputEvaluationContext.setPropertyAccessors(inputaccessors);
    outputevaluationContext.setPropertyAccessors(outputaccessors);
    if (rules != null) {
        Set<String> attributes = rules.keySet();

        //parse rules to create output
        for (String attribute : attributes) {
            String expression = rules.get(attribute);
            //create expressions for in and out
            Expression conversionExpression = expressionParser.parseExpression(expression);
            Expression outputAttribute = expressionParser.parseExpression(attribute);
            //evaluate input value
            Object value = conversionExpression.getValue(inputEvaluationContext); //TODO create a second evaulationContext for output
            //set the attribute value using the output context
            outputAttribute.setValue(outputevaluationContext, value);
        }
    }
    return output;

}

From source file:gov.nih.nci.calims2.ui.generic.crud.CRUDTableDecorator.java

/**
 * Formats the given value according to its type and the current locale.
 * @param column The column//from w  w w  .j  av  a  2s .c om
 * 
 * @param value The value to format
 * @return The formatted value
 */
public String formatValue(Column column, Object value) {
    if (value == null) {
        return "";
    }
    if (value instanceof I18nEnumeration) {
        return ((I18nEnumeration) value).getLocalizedValue(locale);
    }
    if (value instanceof DateTime) {
        return getDateTimeFormatter(column).print((DateTime) value);
    }
    if (value instanceof BigDecimal) {
        return ((BigDecimal) value).toPlainString();
    }
    if (value instanceof Collection<?>) {
        ExpressionParser expressionParser = new SpelExpressionParser();
        Expression expression = expressionParser.parseExpression(StringUtils.stripToNull(column.getFormat()));
        StringBuilder builder = new StringBuilder();
        for (Object entity : (Collection<?>) value) {
            EvaluationContext context = new StandardEvaluationContext(entity);
            Object expresionValue = evaluateExpression(expression, context);
            if (expresionValue != null) {
                builder.append(expresionValue.toString());
                builder.append("<br/>");
            }
        }
        return builder.toString();
    }
    return value.toString();
}

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:gov.nih.nci.calims2.taglib.form.SingleSelectTag.java

@SuppressWarnings("unchecked")
private String createDataStore() {
    Map<String, Object> jsonObject = new TreeMap<String, Object>();
    jsonObject.put("identifier", "id");
    jsonObject.put("label", "label");
    List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
    jsonObject.put("items", items);
    if (collectionType == SelectCollectionType.ENTITIES) {
        for (Object entity : options) {
            Map<String, Object> item = new TreeMap<String, Object>();
            EvaluationContext context = new StandardEvaluationContext(entity);
            for (Map.Entry<String, Expression> entry : propertyMap.entrySet()) {
                String value = SingleSelectHelper.evaluateExpression(entry.getValue(), context);
                item.put(entry.getKey(), value);
            }/*from w  ww . j av a 2s .  c  o m*/
            if (optionCreatorCallback != null) {
                OptionCreatorCallback<Object> callback = (OptionCreatorCallback<Object>) optionCreatorCallback;
                item.put("id", callback.getId(entity));
                item.put("label", callback.getLabel(entity));
            }
            items.add(item);
        }
    } else {
        for (Option option : getOptionsForRendering(TagHelper.getRequestContext(pageContext))) {
            Map<String, Object> item = new TreeMap<String, Object>();
            item.put("id", option.getId());
            item.put("label", option.getLabel());
            items.add(item);
        }
    }
    return "var " + getId() + "Data = " + new JsonSerializer().serializeObject(jsonObject) + ";\n var "
            + getId() + "Store = new " + DojoType.DOJO_DATA_ITEM_FILE_READ_STORE.getTypeName() + "({data : "
            + getId() + "Data});";
}

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

/**
 * Gets Id content/* ww w. j  a  v a2s . 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//w ww  .j av 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;
}

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.
 * /* w  w w.j a  v  a 2s  .com*/
 * 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 www.j  a  v a 2s. c  o 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:net.nan21.dnet.core.presenter.service.asgn.AbstractAsgnService.java

/**
 * //from w w  w  . ja v  a  2 s. com
 * @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:org.synyx.hera.si.PluginRegistryAwareMessageHandler.java

/**
 * Returns the delimiter object to be used for the given {@link Message}. Will use the configured delimiter expression
 * if configured./*w  ww.  j  a va 2  s  . c o  m*/
 * 
 * @param message
 * @return
 */
private Object getDelimiter(Message<?> message) {

    Object delimiter = message;

    if (delimiterExpression != null) {
        StandardEvaluationContext context = new StandardEvaluationContext(message);
        delimiter = delimiterExpression.getValue(context);
    }

    Assert.isInstanceOf(delimiterType, delimiter,
            String.format("Delimiter expression did "
                    + "not return a suitable delimiter! Make sure the expression evaluates to a suitable "
                    + "type! Got %s but need %s", delimiter.getClass(), delimiterType));

    return delimiter;
}