Here are the examples of the java api org.springframework.expression.Expression taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
547 Examples
19
View Source File : MsgMapper.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : zzt93
License : BSD 3-Clause "New" or "Revised" License
Project Creator : zzt93
/**
* @author zzt
*/
public clreplaced MsgMapper implements Mapper<SyncData, String> {
private final Expression topic;
private final boolean includeBefore;
public MsgMapper(MsgMapping mapping) {
includeBefore = mapping.isIncludeBefore();
SpelExpressionParser parser = new SpelExpressionParser();
try {
topic = parser.parseExpression(mapping.getTopic());
} catch (ParseException | IllegalStateException e) {
throw new InvalidConfigException("Fail to parse [mapping] config for [redis] output", e);
}
}
@Override
public String map(SyncData syncData) {
StandardEvaluationContext context = syncData.getContext();
if (!includeBefore) {
syncData.getResult().setBefore(null);
}
return topic.getValue(context, String.clreplaced);
}
}
19
View Source File : ExpressionEvaluator.java
License : Apache License 2.0
Project Creator : yfh0918
License : Apache License 2.0
Project Creator : yfh0918
private Expression getExpression(Map<ExpressionKey, Expression> cache, String expression, MethodCacheKey methodKey) {
ExpressionKey key = createKey(methodKey, expression);
Expression expr = cache.get(key);
if (expr == null) {
expr = this.parser.parseExpression(expression);
cache.put(key, expr);
}
return expr;
}
19
View Source File : SingleRoleStrategy.java
License : Apache License 2.0
Project Creator : xm-online
License : Apache License 2.0
Project Creator : xm-online
private static boolean isConditionValid(Expression expression, StandardEvaluationContext context) {
boolean result;
if (expression == null || StringUtils.isEmpty(expression.getExpressionString())) {
result = true;
} else {
try {
result = expression.getValue(context, Boolean.clreplaced);
} catch (Exception e) {
result = false;
log.error("Exception while getting value ", e);
}
}
return result;
}
19
View Source File : DefaultSubscriptionRegistry.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Nullable
private Expression getSelectorExpression(MessageHeaders headers) {
Expression expression = null;
if (getSelectorHeaderName() != null) {
String selector = SimpMessageHeaderAccessor.getFirstNativeHeader(getSelectorHeaderName(), headers);
if (selector != null) {
try {
expression = this.expressionParser.parseExpression(selector);
this.selectorHeaderInUse = true;
if (logger.isTraceEnabled()) {
logger.trace("Subscription selector: [" + selector + "]");
}
} catch (Throwable ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to parse selector: " + selector, ex);
}
}
}
}
return expression;
}
19
View Source File : SpelCompilationPerformanceTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
private void compile(Expression expression) {
replacedertTrue(SpelCompiler.compile(expression));
}
19
View Source File : AbstractExpressionTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Parse the specified expression and ensure the expected message comes out.
* The message may have inserts and they will be checked if otherProperties is specified.
* The first entry in otherProperties should always be the position.
* @param expression the expression to evaluate
* @param expectedMessage the expected message
* @param otherProperties the expected inserts within the message
*/
protected void parseAndCheckError(String expression, SpelMessage expectedMessage, Object... otherProperties) {
try {
Expression expr = parser.parseExpression(expression);
SpelUtilities.printAbstractSyntaxTree(System.out, expr);
fail("Parsing should have failed!");
} catch (ParseException pe) {
SpelParseException ex = (SpelParseException) pe;
if (ex.getMessageCode() != expectedMessage) {
replacedertEquals("Failed to get expected message", expectedMessage, ex.getMessageCode());
}
if (otherProperties != null && otherProperties.length != 0) {
// first one is expected position of the error within the string
int pos = ((Integer) otherProperties[0]).intValue();
replacedertEquals("Did not get correct position reported in error ", pos, ex.getPosition());
if (otherProperties.length > 1) {
// Check inserts match
Object[] inserts = ex.getInserts();
if (inserts == null) {
inserts = new Object[0];
}
if (inserts.length < otherProperties.length - 1) {
fail("Cannot check " + (otherProperties.length - 1) + " properties of the exception, it only has " + inserts.length + " inserts");
}
for (int i = 1; i < otherProperties.length; i++) {
if (!inserts[i - 1].equals(otherProperties[i])) {
fail("Insert does not match, expected '" + otherProperties[i] + "' but insert value was '" + inserts[i - 1] + "'");
}
}
}
}
}
}
19
View Source File : SpelCompiler.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Request to revert to the interpreter for expression evaluation.
* Any compiled form is discarded but can be recreated by later recompiling again.
* @param expression the expression
*/
public static void revertToInterpreted(Expression expression) {
if (expression instanceof SpelExpression) {
((SpelExpression) expression).revertToInterpreted();
}
}
19
View Source File : SpelCompiler.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Request that an attempt is made to compile the specified expression. It may fail if
* components of the expression are not suitable for compilation or the data types
* involved are not suitable for compilation. Used for testing.
* @return true if the expression was successfully compiled
*/
public static boolean compile(Expression expression) {
return (expression instanceof SpelExpression && ((SpelExpression) expression).compileExpression());
}
19
View Source File : CompositeStringExpression.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Represents a template expression broken into pieces. Each piece will be an Expression
* but pure text parts to the template will be represented as LiteralExpression objects.
* An example of a template expression might be:
*
* <pre clreplaced="code">
* "Hello ${getName()}"
* </pre>
*
* which will be represented as a CompositeStringExpression of two parts. The first part
* being a LiteralExpression representing 'Hello ' and the second part being a real
* expression that will call {@code getName()} when invoked.
*
* @author Andy Clement
* @author Juergen Hoeller
* @since 3.0
*/
public clreplaced CompositeStringExpression implements Expression {
private final String expressionString;
/**
* The array of expressions that make up the composite expression.
*/
private final Expression[] expressions;
public CompositeStringExpression(String expressionString, Expression[] expressions) {
this.expressionString = expressionString;
this.expressions = expressions;
}
@Override
public final String getExpressionString() {
return this.expressionString;
}
public final Expression[] getExpressions() {
return this.expressions;
}
@Override
public String getValue() throws EvaluationException {
StringBuilder sb = new StringBuilder();
for (Expression expression : this.expressions) {
String value = expression.getValue(String.clreplaced);
if (value != null) {
sb.append(value);
}
}
return sb.toString();
}
@Override
@Nullable
public <T> T getValue(@Nullable Clreplaced<T> expectedResultType) throws EvaluationException {
Object value = getValue();
return ExpressionUtils.convertTypedValue(null, new TypedValue(value), expectedResultType);
}
@Override
public String getValue(Object rootObject) throws EvaluationException {
StringBuilder sb = new StringBuilder();
for (Expression expression : this.expressions) {
String value = expression.getValue(rootObject, String.clreplaced);
if (value != null) {
sb.append(value);
}
}
return sb.toString();
}
@Override
@Nullable
public <T> T getValue(Object rootObject, @Nullable Clreplaced<T> desiredResultType) throws EvaluationException {
Object value = getValue(rootObject);
return ExpressionUtils.convertTypedValue(null, new TypedValue(value), desiredResultType);
}
@Override
public String getValue(EvaluationContext context) throws EvaluationException {
StringBuilder sb = new StringBuilder();
for (Expression expression : this.expressions) {
String value = expression.getValue(context, String.clreplaced);
if (value != null) {
sb.append(value);
}
}
return sb.toString();
}
@Override
@Nullable
public <T> T getValue(EvaluationContext context, @Nullable Clreplaced<T> expectedResultType) throws EvaluationException {
Object value = getValue(context);
return ExpressionUtils.convertTypedValue(context, new TypedValue(value), expectedResultType);
}
@Override
public String getValue(EvaluationContext context, Object rootObject) throws EvaluationException {
StringBuilder sb = new StringBuilder();
for (Expression expression : this.expressions) {
String value = expression.getValue(context, rootObject, String.clreplaced);
if (value != null) {
sb.append(value);
}
}
return sb.toString();
}
@Override
@Nullable
public <T> T getValue(EvaluationContext context, Object rootObject, @Nullable Clreplaced<T> desiredResultType) throws EvaluationException {
Object value = getValue(context, rootObject);
return ExpressionUtils.convertTypedValue(context, new TypedValue(value), desiredResultType);
}
@Override
public Clreplaced<?> getValueType() {
return String.clreplaced;
}
@Override
public Clreplaced<?> getValueType(EvaluationContext context) {
return String.clreplaced;
}
@Override
public Clreplaced<?> getValueType(Object rootObject) throws EvaluationException {
return String.clreplaced;
}
@Override
public Clreplaced<?> getValueType(EvaluationContext context, Object rootObject) throws EvaluationException {
return String.clreplaced;
}
@Override
public TypeDescriptor getValueTypeDescriptor() {
return TypeDescriptor.valueOf(String.clreplaced);
}
@Override
public TypeDescriptor getValueTypeDescriptor(Object rootObject) throws EvaluationException {
return TypeDescriptor.valueOf(String.clreplaced);
}
@Override
public TypeDescriptor getValueTypeDescriptor(EvaluationContext context) {
return TypeDescriptor.valueOf(String.clreplaced);
}
@Override
public TypeDescriptor getValueTypeDescriptor(EvaluationContext context, Object rootObject) throws EvaluationException {
return TypeDescriptor.valueOf(String.clreplaced);
}
@Override
public boolean isWritable(Object rootObject) throws EvaluationException {
return false;
}
@Override
public boolean isWritable(EvaluationContext context) {
return false;
}
@Override
public boolean isWritable(EvaluationContext context, Object rootObject) throws EvaluationException {
return false;
}
@Override
public void setValue(Object rootObject, @Nullable Object value) throws EvaluationException {
throw new EvaluationException(this.expressionString, "Cannot call setValue on a composite expression");
}
@Override
public void setValue(EvaluationContext context, @Nullable Object value) throws EvaluationException {
throw new EvaluationException(this.expressionString, "Cannot call setValue on a composite expression");
}
@Override
public void setValue(EvaluationContext context, Object rootObject, @Nullable Object value) throws EvaluationException {
throw new EvaluationException(this.expressionString, "Cannot call setValue on a composite expression");
}
}
19
View Source File : CachedExpressionEvaluator.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Return the {@link Expression} for the specified SpEL value
* <p>Parse the expression if it hasn't been already.
* @param cache the cache to use
* @param elementKey the element on which the expression is defined
* @param expression the expression to parse
*/
protected Expression getExpression(Map<ExpressionKey, Expression> cache, AnnotatedElementKey elementKey, String expression) {
ExpressionKey expressionKey = createKey(elementKey, expression);
Expression expr = cache.get(expressionKey);
if (expr == null) {
expr = getParser().parseExpression(expression);
cache.put(expressionKey, expr);
}
return expr;
}
19
View Source File : BasicVaultPersistentEntity.java
License : Apache License 2.0
Project Creator : spring-projects
License : Apache License 2.0
Project Creator : spring-projects
/**
* {@link VaultPersistentEnreplacedy} implementation.
*
* @author Mark Paluch
* @since 2.0
*/
public clreplaced BasicVaultPersistentEnreplacedy<T> extends BasicKeyValuePersistentEnreplacedy<T, VaultPersistentProperty> implements VaultPersistentEnreplacedy<T> {
private static final SpelExpressionParser PARSER = new SpelExpressionParser();
private final String backend;
@Nullable
private final Expression backendExpression;
/**
* Creates new {@link BasicVaultPersistentEnreplacedy}.
* @param information must not be {@literal null}.
* @param fallbackKeySpaceResolver can be {@literal null}.
*/
public BasicVaultPersistentEnreplacedy(TypeInformation<T> information, KeySpaceResolver fallbackKeySpaceResolver) {
super(information, fallbackKeySpaceResolver);
Secret annotation = findAnnotation(Secret.clreplaced);
if (annotation != null && StringUtils.hasText(annotation.backend())) {
this.backend = annotation.backend();
this.backendExpression = detectExpression(this.backend);
} else {
this.backend = "secret";
this.backendExpression = null;
}
}
/**
* Returns a SpEL {@link Expression} if the given {@link String} is actually an
* expression that does not evaluate to a {@link LiteralExpression} (indicating that
* no subsequent evaluation is necessary).
* @param potentialExpression can be {@literal null}
* @return
*/
@Nullable
private static Expression detectExpression(String potentialExpression) {
Expression expression = PARSER.parseExpression(potentialExpression, ParserContext.TEMPLATE_EXPRESSION);
return expression instanceof LiteralExpression ? null : expression;
}
@Override
public String getKeySpace() {
return String.format("%s/%s", getSecretBackend(), super.getKeySpace());
}
@Override
public String getSecretBackend() {
return //
this.backendExpression == null ? //
this.backend : this.backendExpression.getValue(getEvaluationContext(null), String.clreplaced);
}
}
19
View Source File : TensorflowCommonProcessorProperties.java
License : Apache License 2.0
Project Creator : spring-cloud-stream-app-starters
License : Apache License 2.0
Project Creator : spring-cloud-stream-app-starters
public void setExpression(Expression expression) {
this.expression = expression;
}
19
View Source File : PubSubMessageHandler.java
License : Apache License 2.0
Project Creator : spring-cloud
License : Apache License 2.0
Project Creator : spring-cloud
/**
* Set the SpEL expression for the topic this adapter sends messages to.
* @param topicExpression the SpEL expression representing the topic name
*/
public void setTopicExpression(Expression topicExpression) {
this.topicExpression = topicExpression;
}
19
View Source File : PubSubMessageHandler.java
License : Apache License 2.0
Project Creator : spring-cloud
License : Apache License 2.0
Project Creator : spring-cloud
/**
* Set the SpEL expression to evaluate a timeout in milliseconds for a synchronous publish call
* to Google Cloud Pub/Sub.
* @param publishTimeoutExpression the {@link Expression} for the publish timeout in
* milliseconds
*/
public void setPublishTimeoutExpression(Expression publishTimeoutExpression) {
replacedert.notNull(publishTimeoutExpression, "Publish timeout expression can't be null.");
this.publishTimeoutExpression = publishTimeoutExpression;
}
19
View Source File : BigQueryFileMessageHandler.java
License : Apache License 2.0
Project Creator : spring-cloud
License : Apache License 2.0
Project Creator : spring-cloud
/**
* Sets the SpEL {@link Expression} used to determine the {@link FormatOptions} for the handler.
* @param formatOptionsExpression the SpEL expression used to evaluate the {@link FormatOptions}
*/
public void setFormatOptionsExpression(Expression formatOptionsExpression) {
replacedert.notNull(formatOptionsExpression, "Format options expression cannot be null.");
this.formatOptionsExpression = formatOptionsExpression;
}
19
View Source File : BigQueryFileMessageHandler.java
License : Apache License 2.0
Project Creator : spring-cloud
License : Apache License 2.0
Project Creator : spring-cloud
/**
* Sets the SpEL expression used to determine the {@link Schema} for the handler.
* @param tableSchemaExpression the SpEL expression used to evaluate the {@link Schema}.
*/
public void setTableSchemaExpression(Expression tableSchemaExpression) {
replacedert.notNull(formatOptionsExpression, "The table schema expression cannot be null.");
this.tableSchemaExpression = tableSchemaExpression;
}
19
View Source File : BigQueryFileMessageHandler.java
License : Apache License 2.0
Project Creator : spring-cloud
License : Apache License 2.0
Project Creator : spring-cloud
/**
* Sets the SpEL {@link Expression} to evaluate to determine the table name.
* @param tableNameExpression the SpEL expression used to evaluate the table name
*/
public void setTableNameExpression(Expression tableNameExpression) {
replacedert.notNull(tableNameExpression, "Table name expression must not be null.");
this.tableNameExpression = tableNameExpression;
}
19
View Source File : SpelCompilationPerformanceTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
private void compile(Expression expression) {
replacedertThat(SpelCompiler.compile(expression)).isTrue();
}
19
View Source File : CompositeStringExpression.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
/**
* Represents a template expression broken into pieces. Each piece will be an Expression
* but pure text parts to the template will be represented as LiteralExpression objects.
* An example of a template expression might be:
*
* <pre clreplaced="code">
* "Hello ${getName()}"
* </pre>
*
* which will be represented as a CompositeStringExpression of two parts. The first part
* being a LiteralExpression representing 'Hello ' and the second part being a real
* expression that will call {@code getName()} when invoked.
*
* @author Andy Clement
* @author Juergen Hoeller
* @since 3.0
*/
public clreplaced CompositeStringExpression implements Expression {
private final String expressionString;
/**
* The array of expressions that make up the composite expression.
*/
private final Expression[] expressions;
public CompositeStringExpression(String expressionString, Expression[] expressions) {
this.expressionString = expressionString;
this.expressions = expressions;
}
@Override
public final String getExpressionString() {
return this.expressionString;
}
public final Expression[] getExpressions() {
return this.expressions;
}
@Override
public String getValue() throws EvaluationException {
StringBuilder sb = new StringBuilder();
for (Expression expression : this.expressions) {
String value = expression.getValue(String.clreplaced);
if (value != null) {
sb.append(value);
}
}
return sb.toString();
}
@Override
@Nullable
public <T> T getValue(@Nullable Clreplaced<T> expectedResultType) throws EvaluationException {
Object value = getValue();
return ExpressionUtils.convertTypedValue(null, new TypedValue(value), expectedResultType);
}
@Override
public String getValue(@Nullable Object rootObject) throws EvaluationException {
StringBuilder sb = new StringBuilder();
for (Expression expression : this.expressions) {
String value = expression.getValue(rootObject, String.clreplaced);
if (value != null) {
sb.append(value);
}
}
return sb.toString();
}
@Override
@Nullable
public <T> T getValue(@Nullable Object rootObject, @Nullable Clreplaced<T> desiredResultType) throws EvaluationException {
Object value = getValue(rootObject);
return ExpressionUtils.convertTypedValue(null, new TypedValue(value), desiredResultType);
}
@Override
public String getValue(EvaluationContext context) throws EvaluationException {
StringBuilder sb = new StringBuilder();
for (Expression expression : this.expressions) {
String value = expression.getValue(context, String.clreplaced);
if (value != null) {
sb.append(value);
}
}
return sb.toString();
}
@Override
@Nullable
public <T> T getValue(EvaluationContext context, @Nullable Clreplaced<T> expectedResultType) throws EvaluationException {
Object value = getValue(context);
return ExpressionUtils.convertTypedValue(context, new TypedValue(value), expectedResultType);
}
@Override
public String getValue(EvaluationContext context, @Nullable Object rootObject) throws EvaluationException {
StringBuilder sb = new StringBuilder();
for (Expression expression : this.expressions) {
String value = expression.getValue(context, rootObject, String.clreplaced);
if (value != null) {
sb.append(value);
}
}
return sb.toString();
}
@Override
@Nullable
public <T> T getValue(EvaluationContext context, @Nullable Object rootObject, @Nullable Clreplaced<T> desiredResultType) throws EvaluationException {
Object value = getValue(context, rootObject);
return ExpressionUtils.convertTypedValue(context, new TypedValue(value), desiredResultType);
}
@Override
public Clreplaced<?> getValueType() {
return String.clreplaced;
}
@Override
public Clreplaced<?> getValueType(EvaluationContext context) {
return String.clreplaced;
}
@Override
public Clreplaced<?> getValueType(@Nullable Object rootObject) throws EvaluationException {
return String.clreplaced;
}
@Override
public Clreplaced<?> getValueType(EvaluationContext context, @Nullable Object rootObject) throws EvaluationException {
return String.clreplaced;
}
@Override
public TypeDescriptor getValueTypeDescriptor() {
return TypeDescriptor.valueOf(String.clreplaced);
}
@Override
public TypeDescriptor getValueTypeDescriptor(@Nullable Object rootObject) throws EvaluationException {
return TypeDescriptor.valueOf(String.clreplaced);
}
@Override
public TypeDescriptor getValueTypeDescriptor(EvaluationContext context) {
return TypeDescriptor.valueOf(String.clreplaced);
}
@Override
public TypeDescriptor getValueTypeDescriptor(EvaluationContext context, @Nullable Object rootObject) throws EvaluationException {
return TypeDescriptor.valueOf(String.clreplaced);
}
@Override
public boolean isWritable(@Nullable Object rootObject) throws EvaluationException {
return false;
}
@Override
public boolean isWritable(EvaluationContext context) {
return false;
}
@Override
public boolean isWritable(EvaluationContext context, @Nullable Object rootObject) throws EvaluationException {
return false;
}
@Override
public void setValue(@Nullable Object rootObject, @Nullable Object value) throws EvaluationException {
throw new EvaluationException(this.expressionString, "Cannot call setValue on a composite expression");
}
@Override
public void setValue(EvaluationContext context, @Nullable Object value) throws EvaluationException {
throw new EvaluationException(this.expressionString, "Cannot call setValue on a composite expression");
}
@Override
public void setValue(EvaluationContext context, @Nullable Object rootObject, @Nullable Object value) throws EvaluationException {
throw new EvaluationException(this.expressionString, "Cannot call setValue on a composite expression");
}
}
19
View Source File : MongodbProcessorProperties.java
License : MIT License
Project Creator : PacktPublishing
License : MIT License
Project Creator : PacktPublishing
public void setCollectionExpression(Expression collectionExpression) {
this.collectionExpression = collectionExpression;
}
19
View Source File : PolicyRule.java
License : MIT License
Project Creator : mostafa-eltaher
License : MIT License
Project Creator : mostafa-eltaher
public clreplaced PolicyRule {
private String name;
private String description;
/*
* Boolean SpEL expression. If evaluated to true, then this rule is applied to the request access context.
*/
private Expression target;
/*
* Boolean SpEL expression, if evaluated to true, then access granted.
*/
private Expression condition;
public PolicyRule() {
}
public PolicyRule(String name, String description, Expression target, Expression condition) {
this(target, condition);
this.name = name;
this.description = description;
}
public PolicyRule(Expression target, Expression condition) {
super();
this.target = target;
this.condition = condition;
}
public Expression getTarget() {
return target;
}
public void setTarget(Expression target) {
this.target = target;
}
public Expression getCondition() {
return condition;
}
public void setCondition(Expression condition) {
this.condition = condition;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
19
View Source File : PolicyRule.java
License : MIT License
Project Creator : mostafa-eltaher
License : MIT License
Project Creator : mostafa-eltaher
public void setTarget(Expression target) {
this.target = target;
}
19
View Source File : PolicyRule.java
License : MIT License
Project Creator : mostafa-eltaher
License : MIT License
Project Creator : mostafa-eltaher
public void setCondition(Expression condition) {
this.condition = condition;
}
19
View Source File : CompositeStringExpression.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
/**
* Represents a template expression broken into pieces. Each piece will be an Expression
* but pure text parts to the template will be represented as LiteralExpression objects.
* An example of a template expression might be:
*
* <pre clreplaced="code">
* "Hello ${getName()}"
* </pre>
*
* which will be represented as a CompositeStringExpression of two parts. The first part
* being a LiteralExpression representing 'Hello ' and the second part being a real
* expression that will call {@code getName()} when invoked.
*
* @author Andy Clement
* @author Juergen Hoeller
* @since 3.0
*/
public clreplaced CompositeStringExpression implements Expression {
private final String expressionString;
/**
* The array of expressions that make up the composite expression
*/
private final Expression[] expressions;
public CompositeStringExpression(String expressionString, Expression[] expressions) {
this.expressionString = expressionString;
this.expressions = expressions;
}
@Override
public final String getExpressionString() {
return this.expressionString;
}
@Override
public String getValue() throws EvaluationException {
StringBuilder sb = new StringBuilder();
for (Expression expression : this.expressions) {
String value = expression.getValue(String.clreplaced);
if (value != null) {
sb.append(value);
}
}
return sb.toString();
}
@Override
public String getValue(Object rootObject) throws EvaluationException {
StringBuilder sb = new StringBuilder();
for (Expression expression : this.expressions) {
String value = expression.getValue(rootObject, String.clreplaced);
if (value != null) {
sb.append(value);
}
}
return sb.toString();
}
@Override
public String getValue(EvaluationContext context) throws EvaluationException {
StringBuilder sb = new StringBuilder();
for (Expression expression : this.expressions) {
String value = expression.getValue(context, String.clreplaced);
if (value != null) {
sb.append(value);
}
}
return sb.toString();
}
@Override
public String getValue(EvaluationContext context, Object rootObject) throws EvaluationException {
StringBuilder sb = new StringBuilder();
for (Expression expression : this.expressions) {
String value = expression.getValue(context, rootObject, String.clreplaced);
if (value != null) {
sb.append(value);
}
}
return sb.toString();
}
@Override
public Clreplaced<?> getValueType(EvaluationContext context) {
return String.clreplaced;
}
@Override
public Clreplaced<?> getValueType() {
return String.clreplaced;
}
@Override
public TypeDescriptor getValueTypeDescriptor(EvaluationContext context) {
return TypeDescriptor.valueOf(String.clreplaced);
}
@Override
public TypeDescriptor getValueTypeDescriptor() {
return TypeDescriptor.valueOf(String.clreplaced);
}
@Override
public void setValue(EvaluationContext context, Object value) throws EvaluationException {
throw new EvaluationException(this.expressionString, "Cannot call setValue on a composite expression");
}
@Override
public <T> T getValue(EvaluationContext context, Clreplaced<T> expectedResultType) throws EvaluationException {
Object value = getValue(context);
return ExpressionUtils.convertTypedValue(context, new TypedValue(value), expectedResultType);
}
@Override
public <T> T getValue(Clreplaced<T> expectedResultType) throws EvaluationException {
Object value = getValue();
return ExpressionUtils.convertTypedValue(null, new TypedValue(value), expectedResultType);
}
@Override
public boolean isWritable(EvaluationContext context) {
return false;
}
public Expression[] getExpressions() {
return this.expressions;
}
@Override
public <T> T getValue(Object rootObject, Clreplaced<T> desiredResultType) throws EvaluationException {
Object value = getValue(rootObject);
return ExpressionUtils.convertTypedValue(null, new TypedValue(value), desiredResultType);
}
@Override
public <T> T getValue(EvaluationContext context, Object rootObject, Clreplaced<T> desiredResultType) throws EvaluationException {
Object value = getValue(context, rootObject);
return ExpressionUtils.convertTypedValue(context, new TypedValue(value), desiredResultType);
}
@Override
public Clreplaced<?> getValueType(Object rootObject) throws EvaluationException {
return String.clreplaced;
}
@Override
public Clreplaced<?> getValueType(EvaluationContext context, Object rootObject) throws EvaluationException {
return String.clreplaced;
}
@Override
public TypeDescriptor getValueTypeDescriptor(Object rootObject) throws EvaluationException {
return TypeDescriptor.valueOf(String.clreplaced);
}
@Override
public TypeDescriptor getValueTypeDescriptor(EvaluationContext context, Object rootObject) throws EvaluationException {
return TypeDescriptor.valueOf(String.clreplaced);
}
@Override
public boolean isWritable(EvaluationContext context, Object rootObject) throws EvaluationException {
return false;
}
@Override
public void setValue(EvaluationContext context, Object rootObject, Object value) throws EvaluationException {
throw new EvaluationException(this.expressionString, "Cannot call setValue on a composite expression");
}
@Override
public boolean isWritable(Object rootObject) throws EvaluationException {
return false;
}
@Override
public void setValue(Object rootObject, Object value) throws EvaluationException {
throw new EvaluationException(this.expressionString, "Cannot call setValue on a composite expression");
}
}
19
View Source File : ClaimsExpressionEvaluator.java
License : Apache License 2.0
Project Creator : juiser
License : Apache License 2.0
Project Creator : juiser
/**
* @since 1.0.0
*/
public clreplaced ClaimsExpressionEvaluator implements Function<Claims, Object> {
private final String expressionString;
private final Expression expression;
public ClaimsExpressionEvaluator(String spelExpression) {
replacedert.hasText(spelExpression, "spelExpression argument cannot be null or empty.");
ExpressionParser parser = new SpelExpressionParser();
this.expressionString = spelExpression;
this.expression = parser.parseExpression(spelExpression);
}
@Override
public Object apply(Claims claims) {
return expression.getValue(claims);
}
@Override
public String toString() {
return getClreplaced().getSimpleName() + "[" + expressionString + "]";
}
}
19
View Source File : ExpressionConfigAttribute.java
License : MIT License
Project Creator : jobmission
License : MIT License
Project Creator : jobmission
/**
* 因 WebExpressionConfigAttribute 只能在同package中使用,此ConfigAttribute 仿照 WebExpressionConfigAttribute
*/
public clreplaced ExpressionConfigAttribute implements ConfigAttribute {
private final Expression authorizeExpression;
ExpressionConfigAttribute(Expression authorizeExpression) {
this.authorizeExpression = authorizeExpression;
}
Expression getAuthorizeExpression() {
return this.authorizeExpression;
}
@Override
public String getAttribute() {
return null;
}
@Override
public String toString() {
return this.authorizeExpression.getExpressionString();
}
}
19
View Source File : MappingProcessor.java
License : Apache License 2.0
Project Creator : i-novus-llc
License : Apache License 2.0
Project Creator : i-novus-llc
/**
* Исходящее преобразование target согласно mapping выражению
*
* @param target исходное значение
* @param mapping выражения преобразования
* @return результат преобразования
*/
public static <T> T outMap(Object target, String mapping, Clreplaced<T> clazz) {
T result;
if (mapping != null) {
Expression expression = readParser.parseExpression(mapping);
result = expression.getValue(target, clazz);
} else {
result = (T) target;
}
if (clazz != null && result == null)
throw new N2oException("Expected is " + clazz + ", but actual is null");
if (clazz != null && !clazz.isreplacedignableFrom(result.getClreplaced()))
throw new N2oException("Expected is " + clazz + ", but actual is " + result.getClreplaced());
return result;
}
19
View Source File : SpringExpressionParser.java
License : Apache License 2.0
Project Creator : HotelsDotCom
License : Apache License 2.0
Project Creator : HotelsDotCom
/**
* Applies any defined functions to the preplaceded expression string and returns the result of this.
*
* @param expressionString
* @return
*/
public String parse(String expressionString) {
if (expressionString != null) {
Expression expression = parser.parseExpression(expressionString, templateContext);
expressionString = expression.getValue(evalContext).toString();
}
return expressionString;
}
19
View Source File : SpelExpressionStringQueryParameterBinder.java
License : Apache License 2.0
Project Creator : hexagonframework
License : Apache License 2.0
Project Creator : hexagonframework
/**
* @param ebeanQuery must not be {@literal null}
* @return
*/
private EbeanQueryWrapper potentiallyBindExpressionParameters(EbeanQueryWrapper ebeanQuery) {
for (StringQuery.ParameterBinding binding : query.getParameterBindings()) {
if (binding.isExpression()) {
Expression expr = parseExpressionString(binding.getExpression());
Object value = evaluateExpression(expr);
try {
if (binding.getName() != null) {
ebeanQuery.setParameter(binding.getName(), binding.prepare(value));
} else {
ebeanQuery.setParameter(binding.getPosition(), binding.prepare(value));
}
} catch (IllegalArgumentException iae) {
// Since Eclipse doesn't reliably report whether a query has parameters
// we simply try to set the parameters and ignore possible failures.
}
}
}
return ebeanQuery;
}
19
View Source File : MethodBasedSpelExpression.java
License : Apache License 2.0
Project Creator : hellojavaer
License : Apache License 2.0
Project Creator : hellojavaer
/**
* @author <a href="mailto:[email protected]">Kaiming Zou</a>,created on 2018/5/28.
*/
clreplaced MethodBasedSpelExpression {
private static volatile boolean notSupportParameterNameDiscoverer = false;
private String[] parameterNames;
private Expression expression;
public MethodBasedSpelExpression(String el, Method method) {
el = DDRStringUtils.trimToNull(el);
if (el != null) {
ExpressionParser parser = new SpelExpressionParser();
this.expression = parser.parseExpression(el, DDRSpelEvaluationContext.PARSER_CONTEXT);
this.parameterNames = getParameterNames(method);
}
}
public <T> T parse(Clreplaced<T> type, Object... args) {
if (expression == null) {
return null;
}
EvaluationContext context = buildEvaluationContext();
if (args != null && args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (parameterNames != null && parameterNames.length > i) {
context.setVariable(parameterNames[i], args[i]);
}
context.setVariable("$" + i, args[i]);
}
}
return expression.getValue(context, type);
}
/**
* DefaultParameterNameDiscoverer is supported spring 4.0
* @return
*/
private String[] getParameterNames(Method method) {
if (notSupportParameterNameDiscoverer) {
return null;
} else {
try {
// only support
ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
// from spring4
String[] strs = parameterNameDiscoverer.getParameterNames(method);
if (strs == null) {
notSupportParameterNameDiscoverer = true;
}
return strs;
} catch (NoClreplacedDefFoundError e) {
notSupportParameterNameDiscoverer = true;
return null;
}
}
}
private EvaluationContext buildEvaluationContext() {
return new DDRSpelEvaluationContext() {
@Override
public Object lookupVariable(String name) {
Object obj = null;
try {
obj = super.lookupVariable(name);
} catch (Throwable ignore) {
}
if (obj == null) {
obj = DBClusterRouteContext.lookupVariable(name);
}
return obj;
}
};
}
}
19
View Source File : SpelShardRouteRule.java
License : Apache License 2.0
Project Creator : hellojavaer
License : Apache License 2.0
Project Creator : hellojavaer
/**
* @author <a href="mailto:[email protected]">Kaiming Zou</a>,created on 25/04/2017.
*/
public clreplaced SpelShardRouteRule implements ShardRouteRule {
private String scRouteRule;
private String tbRouteRule;
private Integer rangeSizeLimit;
private Expression scRouteRuleExpression;
private Expression tbRouteRuleExpression;
// used for spring bean
private SpelShardRouteRule() {
}
public SpelShardRouteRule(String scRouteRule, String tbRouteRule) {
setScRouteRule(scRouteRule);
setTbRouteRule(tbRouteRule);
}
public SpelShardRouteRule(String scRouteRule, String tbRouteRule, Integer rangeSizeLimit) {
this.scRouteRule = scRouteRule;
this.tbRouteRule = tbRouteRule;
this.rangeSizeLimit = rangeSizeLimit;
}
public void setScRouteRule(String scRouteRule) {
scRouteRule = filter(scRouteRule);
this.scRouteRule = scRouteRule;
if (scRouteRule != null) {
ExpressionParser parser = new SpelExpressionParser();
this.scRouteRuleExpression = parser.parseExpression(scRouteRule, DDRSpelEvaluationContext.PARSER_CONTEXT);
}
}
public String getScRouteRule() {
return scRouteRule;
}
public void setTbRouteRule(String tbRouteRule) {
tbRouteRule = filter(tbRouteRule);
this.tbRouteRule = tbRouteRule;
if (tbRouteRule != null) {
ExpressionParser parser = new SpelExpressionParser();
this.tbRouteRuleExpression = parser.parseExpression(tbRouteRule, DDRSpelEvaluationContext.PARSER_CONTEXT);
}
}
public String getTbRouteRule() {
return tbRouteRule;
}
public Integer getRangeSizeLimit() {
return rangeSizeLimit;
}
public void setRangeSizeLimit(Integer rangeSizeLimit) {
this.rangeSizeLimit = rangeSizeLimit;
}
private String filter(String string) {
if (string != null) {
string = string.trim();
if (string.length() == 0) {
string = null;
}
}
return string;
}
@Override
public String parseScName(String scName, Object sdValue) {
if (scRouteRuleExpression == null) {
return scName;
} else {
EvaluationContext elContext = buildEvaluationContext(tbRouteRule);
elContext.setVariable("scName", scName);
return parseName(scRouteRuleExpression, elContext, sdValue);
}
}
@Override
public String parseTbName(String tbName, Object sdValue) {
if (tbRouteRuleExpression == null) {
return tbName;
} else {
EvaluationContext elContext = buildEvaluationContext(tbRouteRule);
elContext.setVariable("tbName", tbName);
return parseName(tbRouteRuleExpression, elContext, sdValue);
}
}
@Override
public Map<ShardRouteInfo, List<RangeShardValue>> groupSdValuesByRouteInfo(String scName, String tbName, RangeShardValue rangeShardValue) {
Long begin = rangeShardValue.getBegin();
Long end = rangeShardValue.getEnd();
if (begin == null || end == null) {
throw new IllegalArgumentException("rangeShardValue.begin and rangeShardValue.end can't be null");
}
if (begin > end) {
throw new IllegalArgumentException("rangeShardValue.begin can't be greater than rangeShardValue.end");
}
if (rangeSizeLimit != null && end - begin + 1 > rangeSizeLimit) {
throw new OutOfRangeSizeLimitException((end - begin) + " > " + rangeSizeLimit);
}
Map<ShardRouteInfo, List<RangeShardValue>> map = new LinkedHashMap<>();
if (scRouteRuleExpression == null && tbRouteRuleExpression == null) {
List<RangeShardValue> list = new ArrayList(1);
list.add(new RangeShardValue(begin, end));
ShardRouteInfo routeInfo = new ShardRouteInfo(scName, tbName);
map.put(routeInfo, list);
return map;
}
for (long l = begin; l <= end; l++) {
String scName0 = parseScName(scName, l);
String tbName0 = parseTbName(tbName, l);
ShardRouteInfo routeInfo = new ShardRouteInfo();
routeInfo.setScName(scName0);
routeInfo.setTbName(tbName0);
List<RangeShardValue> rangeShardValues = map.get(routeInfo);
if (rangeShardValues == null) {
rangeShardValues = new ArrayList<>();
map.put(routeInfo, rangeShardValues);
}
rangeShardValues.add(new RangeShardValue(l, l));
}
return map;
}
protected String parseName(Expression expression, EvaluationContext elContext, Object sdValue) {
if (expression == null) {
throw new IllegalArgumentException("expression can't be null");
}
if (sdValue != null && sdValue instanceof RangeShardValue) {
Long begin = ((RangeShardValue) sdValue).getBegin();
Long end = ((RangeShardValue) sdValue).getEnd();
if (begin == null || end == null) {
throw new IllegalArgumentException("rangeShardValue.begin and rangeShardValue.end can't be null");
}
if (begin > end) {
throw new IllegalArgumentException("rangeShardValue.begin can't be greater than rangeShardValue.end");
}
if (rangeSizeLimit != null && end - begin + 1 > rangeSizeLimit) {
throw new OutOfRangeSizeLimitException((end - begin) + " > " + rangeSizeLimit);
}
String result = null;
for (long l = begin; l <= end; l++) {
elContext.setVariable("sdValue", l);
String temp = expression.getValue(elContext, String.clreplaced);
if (result != null && !result.equals(temp)) {
throw new CrossTableException(result + " and " + temp);
}
result = temp;
}
return result;
} else {
elContext.setVariable("sdValue", sdValue);
return expression.getValue(elContext, String.clreplaced);
}
}
@Override
public String toString() {
return //
new DDRToStringBuilder().append("scRouteRule", //
scRouteRule).append("tbRouteRule", //
tbRouteRule).toString();
}
private static final Set<String> RESERVED_WORDS = new HashSet<String>();
static {
RESERVED_WORDS.add("db");
RESERVED_WORDS.add("dbName");
RESERVED_WORDS.add("dbValue");
RESERVED_WORDS.add("dbRoute");
RESERVED_WORDS.add("dbFormat");
RESERVED_WORDS.add("sc");
RESERVED_WORDS.add("scName");
RESERVED_WORDS.add("scValue");
RESERVED_WORDS.add("scRoute");
RESERVED_WORDS.add("scFormat");
RESERVED_WORDS.add("tb");
RESERVED_WORDS.add("tbName");
RESERVED_WORDS.add("tbValue");
RESERVED_WORDS.add("tbRoute");
RESERVED_WORDS.add("tbFormat");
RESERVED_WORDS.add("sd");
RESERVED_WORDS.add("sdName");
RESERVED_WORDS.add("sdKey");
RESERVED_WORDS.add("sdValue");
RESERVED_WORDS.add("sdRoute");
RESERVED_WORDS.add("sdFormat");
RESERVED_WORDS.add("col");
RESERVED_WORDS.add("colName");
RESERVED_WORDS.add("colValue");
RESERVED_WORDS.add("colRoute");
RESERVED_WORDS.add("colFormat");
}
private static boolean isReservedWords(String str) {
if (str == null) {
return false;
} else {
return RESERVED_WORDS.contains(str);
}
}
/**
* load order
* 1.reserved words
* 2.function
* 3.user-define var
*/
private static EvaluationContext buildEvaluationContext(final String expression) {
return new DDRSpelEvaluationContext() {
@Override
public Object lookupVariable(String name) {
Object val = null;
if (isReservedWords(name)) {
val = super.lookupVariable(name);
if (val == null) {
throw new ExpressionValueNotFoundException("Value of '" + name + "' is not found when parsing expression '" + expression + "'");
}
} else {
val = ShardRouteRuleExpressionContext.lookupVariable(name);
}
return val;
}
};
}
}
19
View Source File : BigQueryFileMessageHandler.java
License : Apache License 2.0
Project Creator : GoogleCloudPlatform
License : Apache License 2.0
Project Creator : GoogleCloudPlatform
/**
* Sets the SpEL expression used to determine the {@link Schema} for the handler.
* @param tableSchemaExpression the SpEL expression used to evaluate the {@link Schema}.
*/
public void setTableSchemaExpression(Expression tableSchemaExpression) {
replacedert.notNull(tableSchemaExpression, "The table schema expression cannot be null.");
this.tableSchemaExpression = tableSchemaExpression;
}
19
View Source File : EntityExpressionSupport.java
License : Apache License 2.0
Project Creator : DISID
License : Apache License 2.0
Project Creator : DISID
private void setContextIfSpelExpression(Expression expression, StandardEvaluationContext context) {
if (expression instanceof SpelExpression) {
((SpelExpression) expression).setEvaluationContext(context);
}
}
19
View Source File : EntityExpressionSupport.java
License : Apache License 2.0
Project Creator : DISID
License : Apache License 2.0
Project Creator : DISID
/**
* Parses the given expression.
* @param expression text of the expression to parse
* @return the parsed expression
*/
protected Expression parseExpression(String expression) {
Expression parsedExpression = getParser().parseExpression(expression, getTemplateParserContext());
registerConversionServiceInSpelExpressions(parsedExpression);
return parsedExpression;
}
19
View Source File : Select2DataWithConversion.java
License : Apache License 2.0
Project Creator : DISID
License : Apache License 2.0
Project Creator : DISID
/**
* Response data for data requests performed by a select2 javascript component.
* This clreplaced will be converted to JSON, so the property names must follow the
* name of the properties expected by select2.
*
* This clreplaced uses the {@link ConversionService} to convert the data to String.
*
* @author Cèsar Ordiñana at http://www.disid.com[DISID Corporation S.L.]
* @see https://select2.github.io/examples.html#data-ajax
*
* @param <T> Response data type
*/
public clreplaced Select2DataWithConversion<T> extends Select2DataSupport<T> {
private final ConversionService conversionService;
private final Expression parseIdExpression;
private boolean includeEntireElement;
/**
* Create a response for select2 with data obtained from a request.
*
* @param page the data to show
* @param idExpression the SpEl expression for the id field
* @param conversionService to convert the data to String
*/
public Select2DataWithConversion(Page<T> page, String idExpression, ConversionService conversionService) {
super(page);
replacedert.notNull(page, "A ConversionService is required");
this.conversionService = conversionService;
TemplateParserContext templateParserContext = new TemplateParserContext();
ExpressionParser parser = new SpelExpressionParser();
parseIdExpression = parser.parseExpression(idExpression, templateParserContext);
// By default, the entire element will not be included in the response
this.includeEntireElement = false;
}
/**
* Create a response for select2 with data obtained from a request and indicates
* if the entire element should be included in the response.
*
* @since 1.2.0
*
* @param page the data to show
* @param idExpression the SpEl expression for the id field
* @param conversionService to convert the data to String
* @param includeEntireElement boolean that indicates if the JSON response must contain the
* entire element or only include the `id` and `text` select2 default fields. DEFAULT: false
*/
public Select2DataWithConversion(Page<T> page, String idExpression, ConversionService conversionService, boolean includeEntireElement) {
this(page, idExpression, conversionService);
this.includeEntireElement = includeEntireElement;
}
@Override
protected Data<T> createData(T element) {
String id = getIdreplacedtring(element);
String text = getreplacedtring(element);
if (includeEntireElement) {
return new Data<T>(id, text, element);
}
return new Data<T>(id, text);
}
@Override
protected String getreplacedtring(T element) {
return conversionService.convert(element, String.clreplaced);
}
@Override
protected String getIdreplacedtring(T element) {
return parseIdExpression.getValue(element, String.clreplaced);
}
}
19
View Source File : Select2Data.java
License : Apache License 2.0
Project Creator : DISID
License : Apache License 2.0
Project Creator : DISID
/**
* Response data for data requests performed by a select2 javascript component.
* This clreplaced will be converted to JSON, so the property names must follow the
* name of the properties expected by select2.
*
* This clreplaced uses an expression to convert the data to a String.
*
* @author Cèsar Ordiñana at http://www.disid.com[DISID Corporation S.L.]
* @see https://select2.github.io/examples.html#data-ajax
*
* @param <T> Response data type
*/
public clreplaced Select2Data<T> extends Select2DataSupport<T> {
private final Expression parseIdExpression;
private final Expression parseTextExpression;
/**
* Create a response for select2 with data obtained from a request.
* Uses SpEL expression templates
* (http://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html#expressions-templating)
* to create the select2 data properties
* ('id' and 'text') from the attributes of the data bean to return
*
* @param page the data to show
* @param idExpression the SpEl expression for the id field
* @param textExpression the SpEl expression for the text field
*/
public Select2Data(Page<T> page, String idExpression, String textExpression) {
super(page);
TemplateParserContext templateParserContext = new TemplateParserContext();
ExpressionParser parser = new SpelExpressionParser();
parseIdExpression = parser.parseExpression(idExpression, templateParserContext);
parseTextExpression = parser.parseExpression(textExpression, templateParserContext);
}
protected String getreplacedtring(T element) {
return parseTextExpression.getValue(element, String.clreplaced);
}
protected String getIdreplacedtring(T element) {
return parseIdExpression.getValue(element, String.clreplaced);
}
}
19
View Source File : MessageAggregatorProperties.java
License : Apache License 2.0
Project Creator : Activiti
License : Apache License 2.0
Project Creator : Activiti
public void setGroupTimeout(Expression groupTimeout) {
this.groupTimeout = groupTimeout;
}
19
View Source File : MessageConnectorAggregatorFactoryBean.java
License : Apache License 2.0
Project Creator : Activiti
License : Apache License 2.0
Project Creator : Activiti
public MessageConnectorAggregatorFactoryBean groupTimeoutExpression(Expression groupTimeoutExpression) {
this.groupTimeoutExpression = groupTimeoutExpression;
return this;
}
18
View Source File : SQLMapper.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : zzt93
License : BSD 3-Clause "New" or "Revised" License
Project Creator : zzt93
String evalString(Expression expr, StandardEvaluationContext context) {
return expr.getValue(context, String.clreplaced);
}
18
View Source File : ESRequestMapper.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : zzt93
License : BSD 3-Clause "New" or "Revised" License
Project Creator : zzt93
private String eval(Expression expr, StandardEvaluationContext context) {
return expr.getValue(context, String.clreplaced);
}
18
View Source File : SimpleElParser.java
License : MIT License
Project Creator : yizzuide
License : MIT License
Project Creator : yizzuide
public static <T> T parse(String expression, Object root, Clreplaced<T> resultType) {
Expression expressionWrapper = EL_PARSER.parseExpression(expression);
if (root == null) {
return expressionWrapper.getValue(resultType);
}
return expressionWrapper.getValue(root, resultType);
}
18
View Source File : MultiRoleStrategy.java
License : Apache License 2.0
Project Creator : xm-online
License : Apache License 2.0
Project Creator : xm-online
private boolean isConditionValid(Collection<Permission> permissions, StandardEvaluationContext context, Function<Permission, Expression> func) {
return permissions.stream().anyMatch(permission -> {
Expression expression = func.apply(permission);
if (isNull(expression) || isEmpty(expression.getExpressionString())) {
return true;
}
try {
return expression.getValue(context, Boolean.clreplaced);
} catch (Exception e) {
log.error("Exception while getting value ", e);
return false;
}
});
}
18
View Source File : SpelSerializer.java
License : Apache License 2.0
Project Creator : xm-online
License : Apache License 2.0
Project Creator : xm-online
@Override
public void serialize(Expression value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeString(value.getExpressionString());
}
18
View Source File : SecureCheckUtil.java
License : GNU Lesser General Public License v3.0
Project Creator : xkcoding
License : GNU Lesser General Public License v3.0
Project Creator : xkcoding
/**
* 检查 SPEL 表达式
*
* @param spel 表达式
* @param context 上下文
* @return {@code true} / {@code false}
*/
public static boolean checkExpression(String spel, StandardEvaluationContext context) {
Expression expression = PARSER.parseExpression(spel);
Boolean result = expression.getValue(context, Boolean.clreplaced);
return result != null ? result : false;
}
18
View Source File : RuleConfig.java
License : Apache License 2.0
Project Creator : whiteclarkegroup
License : Apache License 2.0
Project Creator : whiteclarkegroup
@JsonDeserialize(builder = RuleConfig.RuleConfigBuilder.clreplaced)
public clreplaced RuleConfig {
private static final String DYNAMIC_VALUE = "{{value}}";
private final boolean enabled;
private final String condition;
private final String patternString;
private final String dynamicValue;
private final List<String> values;
private final Integer maxLength;
private final String errorMessage;
private final String enableAfter;
private Pattern pattern;
private Expression conditionExpression;
private Expression dynamicValueExpression;
private RuleConfig(RuleConfigBuilder builder) {
this.enabled = builder.enabled;
this.errorMessage = builder.errorMessage;
this.condition = builder.condition;
this.patternString = builder.pattern;
this.dynamicValue = builder.dynamicValue;
this.values = builder.values;
this.maxLength = builder.maxLength;
this.enableAfter = builder.enableAfter;
}
public static RuleConfig enabled() {
return RuleConfig.builder().withEnabled(true).build();
}
public static RuleConfig disabled() {
return RuleConfig.builder().withEnabled(false).build();
}
public static RuleConfigBuilder builder() {
return new RuleConfigBuilder();
}
private boolean isDynamicPattern() {
return patternString.contains(DYNAMIC_VALUE);
}
public boolean isEnabled() {
return enabled;
}
public String getErrorMessage() {
return errorMessage;
}
public List<String> getValues() {
return values;
}
public Integer getMaxLength() {
return maxLength;
}
public String getPatternString() {
return patternString;
}
public Optional<Expression> getConditionalExpression() {
if (conditionExpression == null && condition != null) {
conditionExpression = new SpelExpressionParser().parseExpression(condition);
}
return Optional.ofNullable(conditionExpression);
}
public Optional<Expression> getDynamicValueExpression() {
if (dynamicValueExpression == null && dynamicValue != null) {
dynamicValueExpression = new SpelExpressionParser().parseExpression(dynamicValue);
}
return Optional.ofNullable(dynamicValueExpression);
}
public Optional<Pattern> getPattern() {
if (pattern == null && patternString != null && !isDynamicPattern()) {
pattern = Pattern.compile(patternString);
}
return Optional.ofNullable(pattern);
}
public boolean hasPattern() {
return patternString != null && !patternString.equals("");
}
public String getEnableAfter() {
return this.enableAfter;
}
public boolean isEnabledAfter() {
return enableAfter != null && !enableAfter.isEmpty();
}
public static clreplaced RuleConfigBuilder {
private boolean enabled = true;
private String errorMessage;
private String condition;
private String pattern;
private String dynamicValue;
private List<String> values;
private Integer maxLength;
private String enableAfter;
public RuleConfigBuilder withEnabled(boolean enabled) {
this.enabled = enabled;
return this;
}
public RuleConfigBuilder withErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
return this;
}
public RuleConfigBuilder withCondition(String condition) {
this.condition = condition;
return this;
}
public RuleConfigBuilder withPattern(String pattern) {
this.pattern = pattern;
return this;
}
public RuleConfigBuilder withDynamicValue(String dynamicValue) {
this.dynamicValue = dynamicValue;
return this;
}
public RuleConfigBuilder withValues(List<String> values) {
this.values = values;
return this;
}
public RuleConfigBuilder withMaxLength(Integer maxLength) {
this.maxLength = maxLength;
return this;
}
public RuleConfigBuilder withEnableAfter(String enableAfter) {
this.enableAfter = enableAfter;
return this;
}
public RuleConfig build() {
return new RuleConfig(this);
}
}
}
18
View Source File : EvalTag.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* The {@code <eval>} tag evaluates a Spring expression (SpEL) and either prints
* the result or replacedigns it to a variable. Supports the standard JSP evaluation
* context consisting of implicit variables and scoped attributes.
*
* <table>
* <caption>Attribute Summary</caption>
* <thead>
* <tr>
* <th>Attribute</th>
* <th>Required?</th>
* <th>Runtime Expression?</th>
* <th>Description</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>expression</td>
* <td>true</td>
* <td>true</td>
* <td>The expression to evaluate.</td>
* </tr>
* <tr>
* <td>htmlEscape</td>
* <td>false</td>
* <td>true</td>
* <td>Set HTML escaping for this tag, as a boolean value.
* Overrides the default HTML escaping setting for the current page.</td>
* </tr>
* <tr>
* <td>javaScriptEscape</td>
* <td>false</td>
* <td>true</td>
* <td>Set JavaScript escaping for this tag, as a boolean value.
* Default is false.</td>
* </tr>
* <tr>
* <td>scope</td>
* <td>false</td>
* <td>true</td>
* <td>The scope for the var. 'application', 'session', 'request' and 'page'
* scopes are supported. Defaults to page scope. This attribute has no effect
* unless the var attribute is also defined.</td>
* </tr>
* <tr>
* <td>var</td>
* <td>false</td>
* <td>true</td>
* <td>The name of the variable to export the evaluation result to.
* If not specified the evaluation result is converted to a String and written
* as output.</td>
* </tr>
* </tbody>
* </table>
*
* @author Keith Donald
* @author Juergen Hoeller
* @since 3.0.1
*/
@SuppressWarnings("serial")
public clreplaced EvalTag extends HtmlEscapingAwareTag {
/**
* {@link javax.servlet.jsp.PageContext} attribute for the
* page-level {@link EvaluationContext} instance.
*/
private static final String EVALUATION_CONTEXT_PAGE_ATTRIBUTE = "org.springframework.web.servlet.tags.EVALUATION_CONTEXT";
private final ExpressionParser expressionParser = new SpelExpressionParser();
@Nullable
private Expression expression;
@Nullable
private String var;
private int scope = PageContext.PAGE_SCOPE;
private boolean javaScriptEscape = false;
/**
* Set the expression to evaluate.
*/
public void setExpression(String expression) {
this.expression = this.expressionParser.parseExpression(expression);
}
/**
* Set the variable name to expose the evaluation result under.
* Defaults to rendering the result to the current JspWriter.
*/
public void setVar(String var) {
this.var = var;
}
/**
* Set the scope to export the evaluation result to.
* This attribute has no meaning unless var is also defined.
*/
public void setScope(String scope) {
this.scope = TagUtils.getScope(scope);
}
/**
* Set JavaScript escaping for this tag, as boolean value.
* Default is "false".
*/
public void setJavaScriptEscape(boolean javaScriptEscape) throws JspException {
this.javaScriptEscape = javaScriptEscape;
}
@Override
public int doStartTagInternal() throws JspException {
return EVAL_BODY_INCLUDE;
}
@Override
public int doEndTag() throws JspException {
EvaluationContext evaluationContext = (EvaluationContext) this.pageContext.getAttribute(EVALUATION_CONTEXT_PAGE_ATTRIBUTE);
if (evaluationContext == null) {
evaluationContext = createEvaluationContext(this.pageContext);
this.pageContext.setAttribute(EVALUATION_CONTEXT_PAGE_ATTRIBUTE, evaluationContext);
}
if (this.var != null) {
Object result = (this.expression != null ? this.expression.getValue(evaluationContext) : null);
this.pageContext.setAttribute(this.var, result, this.scope);
} else {
try {
String result = (this.expression != null ? this.expression.getValue(evaluationContext, String.clreplaced) : null);
result = ObjectUtils.getDisplayString(result);
result = htmlEscape(result);
result = (this.javaScriptEscape ? JavaScriptUtils.javaScriptEscape(result) : result);
this.pageContext.getOut().print(result);
} catch (IOException ex) {
throw new JspException(ex);
}
}
return EVAL_PAGE;
}
private EvaluationContext createEvaluationContext(PageContext pageContext) {
StandardEvaluationContext context = new StandardEvaluationContext();
context.addPropertyAccessor(new JspPropertyAccessor(pageContext));
context.addPropertyAccessor(new MapAccessor());
context.addPropertyAccessor(new EnvironmentAccessor());
context.setBeanResolver(new BeanFactoryResolver(getRequestContext().getWebApplicationContext()));
ConversionService conversionService = getConversionService(pageContext);
if (conversionService != null) {
context.setTypeConverter(new StandardTypeConverter(conversionService));
}
return context;
}
@Nullable
private ConversionService getConversionService(PageContext pageContext) {
return (ConversionService) pageContext.getRequest().getAttribute(ConversionService.clreplaced.getName());
}
@SuppressWarnings("deprecation")
private static clreplaced JspPropertyAccessor implements PropertyAccessor {
private final PageContext pageContext;
@Nullable
private final javax.servlet.jsp.el.VariableResolver variableResolver;
public JspPropertyAccessor(PageContext pageContext) {
this.pageContext = pageContext;
this.variableResolver = pageContext.getVariableResolver();
}
@Override
@Nullable
public Clreplaced<?>[] getSpecificTargetClreplacedes() {
return null;
}
@Override
public boolean canRead(EvaluationContext context, @Nullable Object target, String name) throws AccessException {
return (target == null && (resolveImplicitVariable(name) != null || this.pageContext.findAttribute(name) != null));
}
@Override
public TypedValue read(EvaluationContext context, @Nullable Object target, String name) throws AccessException {
Object implicitVar = resolveImplicitVariable(name);
if (implicitVar != null) {
return new TypedValue(implicitVar);
}
return new TypedValue(this.pageContext.findAttribute(name));
}
@Override
public boolean canWrite(EvaluationContext context, @Nullable Object target, String name) {
return false;
}
@Override
public void write(EvaluationContext context, @Nullable Object target, String name, @Nullable Object newValue) {
throw new UnsupportedOperationException();
}
@Nullable
private Object resolveImplicitVariable(String name) throws AccessException {
if (this.variableResolver == null) {
return null;
}
try {
return this.variableResolver.resolveVariable(name);
} catch (Exception ex) {
throw new AccessException("Unexpected exception occurred accessing '" + name + "' as an implicit variable", ex);
}
}
}
}
18
View Source File : DefaultSubscriptionRegistry.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
protected void addSubscriptionInternal(String sessionId, String subsId, String destination, Message<?> message) {
Expression expression = getSelectorExpression(message.getHeaders());
this.subscriptionRegistry.addSubscription(sessionId, subsId, destination, expression);
this.destinationCache.updateAfterNewSubscription(destination, sessionId, subsId);
}
18
View Source File : SpelUtilities.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Output an indented representation of the expression syntax tree to the specified output stream.
* @param printStream the output stream to print into
* @param expression the expression to be displayed
*/
public static void printAbstractSyntaxTree(PrintStream printStream, Expression expression) {
printStream.println("===> Expression '" + expression.getExpressionString() + "' - AST start");
printAST(printStream, ((SpelExpression) expression).getAST(), "");
printStream.println("===> Expression '" + expression.getExpressionString() + "' - AST end");
}
18
View Source File : SpelCompilationPerformanceTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Checks the speed of compiled SpEL expressions.
*
* <p>By default these tests are marked @Ignore since they can fail on a busy machine
* because they compare relative performance of interpreted vs compiled.
*
* @author Andy Clement
* @since 4.1
*/
@Ignore
public clreplaced SpelCompilationPerformanceTests extends AbstractExpressionTests {
// number of evaluations that are timed in one run
int count = 50000;
// number of times to repeat 'count' evaluations (for averaging)
int iterations = 10;
private final static boolean noisyTests = true;
Expression expression;
/**
* This test verifies the new support for compiling mathematical expressions with
* different operand types.
*/
@Test
public void compilingMathematicalExpressionsWithDifferentOperandTypes() throws Exception {
NumberHolder nh = new NumberHolder();
expression = parser.parseExpression("(T(Integer).valueOf(payload).doubleValue())/18D");
Object o = expression.getValue(nh);
replacedertEquals(2d, o);
System.out.println("Performance check for SpEL expression: '(T(Integer).valueOf(payload).doubleValue())/18D'");
long stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh);
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh);
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh);
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
compile(expression);
System.out.println("Now compiled:");
o = expression.getValue(nh);
replacedertEquals(2d, o);
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh);
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh);
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh);
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
expression = parser.parseExpression("payload/18D");
o = expression.getValue(nh);
replacedertEquals(2d, o);
System.out.println("Performance check for SpEL expression: 'payload/18D'");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh);
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh);
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh);
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
compile(expression);
System.out.println("Now compiled:");
o = expression.getValue(nh);
replacedertEquals(2d, o);
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh);
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh);
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue(nh);
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
}
@Test
public void inlineLists() throws Exception {
expression = parser.parseExpression("{'abcde','ijklm'}[0].substring({1,3,4}[0],{1,3,4}[1])");
Object o = expression.getValue();
replacedertEquals("bc", o);
System.out.println("Performance check for SpEL expression: '{'abcde','ijklm'}[0].substring({1,3,4}[0],{1,3,4}[1])'");
long stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue();
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue();
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue();
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
compile(expression);
System.out.println("Now compiled:");
o = expression.getValue();
replacedertEquals("bc", o);
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue();
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue();
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue();
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
}
@Test
public void inlineNestedLists() throws Exception {
expression = parser.parseExpression("{'abcde',{'ijklm','nopqr'}}[1][0].substring({1,3,4}[0],{1,3,4}[1])");
Object o = expression.getValue();
replacedertEquals("jk", o);
System.out.println("Performance check for SpEL expression: '{'abcde','ijklm'}[0].substring({1,3,4}[0],{1,3,4}[1])'");
long stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue();
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue();
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue();
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
compile(expression);
System.out.println("Now compiled:");
o = expression.getValue();
replacedertEquals("jk", o);
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue();
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue();
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue();
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
}
@Test
public void stringConcatenation() throws Exception {
expression = parser.parseExpression("'hello' + getWorld() + ' spring'");
Greeter g = new Greeter();
Object o = expression.getValue(g);
replacedertEquals("helloworld spring", o);
System.out.println("Performance check for SpEL expression: 'hello' + getWorld() + ' spring'");
long stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue(g);
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue(g);
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue(g);
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
compile(expression);
System.out.println("Now compiled:");
o = expression.getValue(g);
replacedertEquals("helloworld spring", o);
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue(g);
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue(g);
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
stime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
o = expression.getValue(g);
}
System.out.println("One million iterations: " + (System.currentTimeMillis() - stime) + "ms");
}
@Test
public void complexExpressionPerformance() throws Exception {
Payload payload = new Payload();
Expression expression = parser.parseExpression("DR[0].DRFixedSection.duration lt 0.1");
boolean b = false;
long iTotal = 0, cTotal = 0;
// warmup
for (int i = 0; i < count; i++) {
b = expression.getValue(payload, Boolean.TYPE);
}
log("timing interpreted: ");
for (int i = 0; i < iterations; i++) {
long stime = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
b = expression.getValue(payload, Boolean.TYPE);
}
long etime = System.currentTimeMillis();
long interpretedSpeed = (etime - stime);
iTotal += interpretedSpeed;
log(interpretedSpeed + "ms ");
}
logln();
compile(expression);
boolean bc = false;
expression.getValue(payload, Boolean.TYPE);
log("timing compiled: ");
for (int i = 0; i < iterations; i++) {
long stime = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
bc = expression.getValue(payload, Boolean.TYPE);
}
long etime = System.currentTimeMillis();
long compiledSpeed = (etime - stime);
cTotal += compiledSpeed;
log(compiledSpeed + "ms ");
}
logln();
reportPerformance("complex expression", iTotal, cTotal);
// Verify the result
replacedertFalse(b);
// Verify the same result for compiled vs interpreted
replacedertEquals(b, bc);
// Verify if the input changes, the result changes
payload.DR[0].DRFixedSection.duration = 0.04d;
bc = expression.getValue(payload, Boolean.TYPE);
replacedertTrue(bc);
}
public static clreplaced HW {
public String hello() {
return "foobar";
}
}
@Test
public void compilingMethodReference() throws Exception {
long interpretedTotal = 0, compiledTotal = 0;
long stime, etime;
String interpretedResult = null, compiledResult = null;
HW testdata = new HW();
Expression expression = parser.parseExpression("hello()");
// warmup
for (int i = 0; i < count; i++) {
interpretedResult = expression.getValue(testdata, String.clreplaced);
}
log("timing interpreted: ");
for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
interpretedResult = expression.getValue(testdata, String.clreplaced);
}
etime = System.currentTimeMillis();
long interpretedSpeed = (etime - stime);
interpretedTotal += interpretedSpeed;
log(interpretedSpeed + "ms ");
}
logln();
compile(expression);
log("timing compiled: ");
expression.getValue(testdata, String.clreplaced);
for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
compiledResult = expression.getValue(testdata, String.clreplaced);
}
etime = System.currentTimeMillis();
long compiledSpeed = (etime - stime);
compiledTotal += compiledSpeed;
log(compiledSpeed + "ms ");
}
logln();
replacedertEquals(interpretedResult, compiledResult);
reportPerformance("method reference", interpretedTotal, compiledTotal);
if (compiledTotal >= interpretedTotal) {
fail("Compiled version is slower than interpreted!");
}
}
@Test
public void compilingPropertyReferenceField() throws Exception {
long interpretedTotal = 0, compiledTotal = 0, stime, etime;
String interpretedResult = null, compiledResult = null;
TestClreplaced2 testdata = new TestClreplaced2();
Expression expression = parser.parseExpression("name");
// warmup
for (int i = 0; i < count; i++) {
expression.getValue(testdata, String.clreplaced);
}
log("timing interpreted: ");
for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
interpretedResult = expression.getValue(testdata, String.clreplaced);
}
etime = System.currentTimeMillis();
long interpretedSpeed = (etime - stime);
interpretedTotal += interpretedSpeed;
log(interpretedSpeed + "ms ");
}
logln();
compile(expression);
log("timing compiled: ");
expression.getValue(testdata, String.clreplaced);
for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
compiledResult = expression.getValue(testdata, String.clreplaced);
}
etime = System.currentTimeMillis();
long compiledSpeed = (etime - stime);
compiledTotal += compiledSpeed;
log(compiledSpeed + "ms ");
}
logln();
replacedertEquals(interpretedResult, compiledResult);
reportPerformance("property reference (field)", interpretedTotal, compiledTotal);
}
@Test
public void compilingPropertyReferenceNestedField() throws Exception {
long interpretedTotal = 0, compiledTotal = 0, stime, etime;
String interpretedResult = null, compiledResult = null;
TestClreplaced2 testdata = new TestClreplaced2();
Expression expression = parser.parseExpression("foo.bar.boo");
// warmup
for (int i = 0; i < count; i++) {
expression.getValue(testdata, String.clreplaced);
}
log("timing interpreted: ");
for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
interpretedResult = expression.getValue(testdata, String.clreplaced);
}
etime = System.currentTimeMillis();
long interpretedSpeed = (etime - stime);
interpretedTotal += interpretedSpeed;
log(interpretedSpeed + "ms ");
}
logln();
compile(expression);
log("timing compiled: ");
expression.getValue(testdata, String.clreplaced);
for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
compiledResult = expression.getValue(testdata, String.clreplaced);
}
etime = System.currentTimeMillis();
long compiledSpeed = (etime - stime);
compiledTotal += compiledSpeed;
log(compiledSpeed + "ms ");
}
logln();
replacedertEquals(interpretedResult, compiledResult);
reportPerformance("property reference (nested field)", interpretedTotal, compiledTotal);
}
@Test
public void compilingPropertyReferenceNestedMixedFieldGetter() throws Exception {
long interpretedTotal = 0, compiledTotal = 0, stime, etime;
String interpretedResult = null, compiledResult = null;
TestClreplaced2 testdata = new TestClreplaced2();
Expression expression = parser.parseExpression("foo.baz.boo");
// warmup
for (int i = 0; i < count; i++) {
expression.getValue(testdata, String.clreplaced);
}
log("timing interpreted: ");
for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
interpretedResult = expression.getValue(testdata, String.clreplaced);
}
etime = System.currentTimeMillis();
long interpretedSpeed = (etime - stime);
interpretedTotal += interpretedSpeed;
log(interpretedSpeed + "ms ");
}
logln();
compile(expression);
log("timing compiled: ");
expression.getValue(testdata, String.clreplaced);
for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
compiledResult = expression.getValue(testdata, String.clreplaced);
}
etime = System.currentTimeMillis();
long compiledSpeed = (etime - stime);
compiledTotal += compiledSpeed;
log(compiledSpeed + "ms ");
}
logln();
replacedertEquals(interpretedResult, compiledResult);
reportPerformance("nested property reference (mixed field/getter)", interpretedTotal, compiledTotal);
}
@Test
public void compilingNestedMixedFieldPropertyReferenceMethodReference() throws Exception {
long interpretedTotal = 0, compiledTotal = 0, stime, etime;
String interpretedResult = null, compiledResult = null;
TestClreplaced2 testdata = new TestClreplaced2();
Expression expression = parser.parseExpression("foo.bay().boo");
// warmup
for (int i = 0; i < count; i++) {
expression.getValue(testdata, String.clreplaced);
}
log("timing interpreted: ");
for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
interpretedResult = expression.getValue(testdata, String.clreplaced);
}
etime = System.currentTimeMillis();
long interpretedSpeed = (etime - stime);
interpretedTotal += interpretedSpeed;
log(interpretedSpeed + "ms ");
}
logln();
compile(expression);
log("timing compiled: ");
expression.getValue(testdata, String.clreplaced);
for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
compiledResult = expression.getValue(testdata, String.clreplaced);
}
etime = System.currentTimeMillis();
long compiledSpeed = (etime - stime);
compiledTotal += compiledSpeed;
log(compiledSpeed + "ms ");
}
logln();
replacedertEquals(interpretedResult, compiledResult);
reportPerformance("nested reference (mixed field/method)", interpretedTotal, compiledTotal);
}
@Test
public void compilingPropertyReferenceGetter() throws Exception {
long interpretedTotal = 0, compiledTotal = 0, stime, etime;
String interpretedResult = null, compiledResult = null;
TestClreplaced2 testdata = new TestClreplaced2();
Expression expression = parser.parseExpression("name2");
// warmup
for (int i = 0; i < count; i++) {
expression.getValue(testdata, String.clreplaced);
}
log("timing interpreted: ");
for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
interpretedResult = expression.getValue(testdata, String.clreplaced);
}
etime = System.currentTimeMillis();
long interpretedSpeed = (etime - stime);
interpretedTotal += interpretedSpeed;
log(interpretedSpeed + "ms ");
}
logln();
compile(expression);
log("timing compiled: ");
expression.getValue(testdata, String.clreplaced);
for (int i = 0; i < iterations; i++) {
stime = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
compiledResult = expression.getValue(testdata, String.clreplaced);
}
etime = System.currentTimeMillis();
long compiledSpeed = (etime - stime);
compiledTotal += compiledSpeed;
log(compiledSpeed + "ms ");
}
logln();
replacedertEquals(interpretedResult, compiledResult);
reportPerformance("property reference (getter)", interpretedTotal, compiledTotal);
if (compiledTotal >= interpretedTotal) {
fail("Compiled version is slower than interpreted!");
}
}
private void reportPerformance(String replacedle, long interpretedTotal, long compiledTotal) {
double averageInterpreted = interpretedTotal / iterations;
double averageCompiled = compiledTotal / iterations;
double ratio = (averageCompiled / averageInterpreted) * 100.0d;
logln(">>" + replacedle + ": average for " + count + ": compiled=" + averageCompiled + "ms interpreted=" + averageInterpreted + "ms: compiled takes " + ((int) ratio) + "% of the interpreted time");
if (averageCompiled > averageInterpreted) {
fail("Compiled version took longer than interpreted! CompiledSpeed=~" + averageCompiled + "ms InterpretedSpeed=" + averageInterpreted + "ms");
}
logln();
}
private void log(String message) {
if (noisyTests) {
System.out.print(message);
}
}
private void logln(String... message) {
if (noisyTests) {
if (message.length > 0) {
System.out.println(message[0]);
} else {
System.out.println();
}
}
}
private void compile(Expression expression) {
replacedertTrue(SpelCompiler.compile(expression));
}
public static clreplaced Payload {
Two[] DR = new Two[] { new Two() };
public Two[] getDR() {
return DR;
}
}
public static clreplaced Two {
Three DRFixedSection = new Three();
public Three getDRFixedSection() {
return DRFixedSection;
}
}
public static clreplaced Three {
double duration = 0.4d;
public double getDuration() {
return duration;
}
}
public static clreplaced NumberHolder {
public int payload = 36;
}
public static clreplaced Greeter {
public String getWorld() {
return "world";
}
}
public static clreplaced TestClreplaced2 {
public String name = "Santa";
private String name2 = "foobar";
public String getName2() {
return name2;
}
public Foo foo = new Foo();
}
public static clreplaced Foo {
public Bar bar = new Bar();
Bar b = new Bar();
public Bar getBaz() {
return b;
}
public Bar bay() {
return b;
}
}
public static clreplaced Bar {
public String boo = "oranges";
}
}
18
View Source File : SetValueTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Call setValue() but expect it to fail.
*/
protected void setValueExpectError(String expression, Object value) {
try {
Expression e = parser.parseExpression(expression);
if (e == null) {
fail("Parser returned null for expression");
}
if (DEBUG) {
SpelUtilities.printAbstractSyntaxTree(System.out, e);
}
StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext();
e.setValue(lContext, value);
fail("expected an error");
} catch (ParseException pe) {
pe.printStackTrace();
fail("Unexpected Exception: " + pe.getMessage());
} catch (EvaluationException ee) {
// success!
}
}
See More Examples