org.springframework.expression.Expression - java examples

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.

155 Examples 7

19 View Complete Implementation : AbstractExpressionTests.java
Copyright MIT License
Author : codeEngraver
/**
 * 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 Complete Implementation : SpelCompiler.java
Copyright MIT License
Author : codeEngraver
/**
 * 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 Complete Implementation : SpelCompiler.java
Copyright MIT License
Author : codeEngraver
/**
 * 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 Complete Implementation : SpelCompilationPerformanceTests.java
Copyright MIT License
Author : codeEngraver
private void compile(Expression expression) {
    replacedertTrue(SpelCompiler.compile(expression));
}

19 View Complete Implementation : CachedExpressionEvaluator.java
Copyright MIT License
Author : codeEngraver
/**
 * 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 Complete Implementation : DefaultSubscriptionRegistry.java
Copyright MIT License
Author : codeEngraver
@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;
}

18 View Complete Implementation : SetValueTests.java
Copyright MIT License
Author : codeEngraver
@Test
public void testIsWritableForInvalidExpressions_SPR10610() {
    Expression e = null;
    StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext();
    // PROPERTYORFIELDREFERENCE
    // Non existent field (or property):
    e = parser.parseExpression("arrayContainer.wibble");
    replacedertFalse("Should not be writable!", e.isWritable(lContext));
    e = parser.parseExpression("arrayContainer.wibble.foo");
    try {
        replacedertFalse("Should not be writable!", e.isWritable(lContext));
        fail("Should have had an error because wibble does not really exist");
    } catch (SpelEvaluationException see) {
    // org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 15): Property or field 'wibble' cannot be found on object of type 'org.springframework.expression.spel.testresources.ArrayContainer' - maybe not public?
    // at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:225)
    // success!
    }
    // VARIABLE
    // the variable does not exist (but that is OK, we should be writable)
    e = parser.parseExpression("#madeup1");
    replacedertTrue("Should be writable!", e.isWritable(lContext));
    // compound expression
    e = parser.parseExpression("#madeup2.bar");
    replacedertFalse("Should not be writable!", e.isWritable(lContext));
    // INDEXER
    // non existent indexer (wibble made up)
    e = parser.parseExpression("arrayContainer.wibble[99]");
    try {
        replacedertFalse("Should not be writable!", e.isWritable(lContext));
        fail("Should have had an error because wibble does not really exist");
    } catch (SpelEvaluationException see) {
    // success!
    }
    // non existent indexer (index via a string)
    e = parser.parseExpression("arrayContainer.ints['abc']");
    try {
        replacedertFalse("Should not be writable!", e.isWritable(lContext));
        fail("Should have had an error because wibble does not really exist");
    } catch (SpelEvaluationException see) {
    // success!
    }
}

18 View Complete Implementation : CachedMethodExecutorTests.java
Copyright MIT License
Author : codeEngraver
private void replacedertMethodExecution(Expression expression, Object var, String expected) {
    this.context.setVariable("var", var);
    replacedertEquals(expected, expression.getValue(this.context));
}

18 View Complete Implementation : CachedMethodExecutorTests.java
Copyright MIT License
Author : codeEngraver
@Test
public void testCachedExecutionForTarget() {
    Expression expression = this.parser.parseExpression("#var.echo(42)");
    replacedertMethodExecution(expression, new RootObject(), "int: 42");
    replacedertMethodExecution(expression, new RootObject(), "int: 42");
    replacedertMethodExecution(expression, new BaseObject(), "String: 42");
    replacedertMethodExecution(expression, new RootObject(), "int: 42");
}

18 View Complete Implementation : AbstractExpressionTests.java
Copyright MIT License
Author : codeEngraver
/**
 * Evaluate 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 expectedReturnType ask the expression return value to be of this type if possible
 * ({@code null} indicates don't ask for conversion)
 * @param expectedMessage the expected message
 * @param otherProperties the expected inserts within the message
 */
protected void evaluateAndCheckError(String expression, Clreplaced<?> expectedReturnType, SpelMessage expectedMessage, Object... otherProperties) {
    try {
        Expression expr = parser.parseExpression(expression);
        if (expr == null) {
            fail("Parser returned null for expression");
        }
        if (expectedReturnType != null) {
            expr.getValue(context, expectedReturnType);
        } else {
            expr.getValue(context);
        }
        fail("Should have failed with message " + expectedMessage);
    } catch (EvaluationException ee) {
        SpelEvaluationException ex = (SpelEvaluationException) ee;
        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 (otherProperties[i] == null) {
                        if (inserts[i - 1] != null) {
                            fail("Insert does not match, expected 'null' but insert value was '" + inserts[i - 1] + "'");
                        }
                    } else if (inserts[i - 1] == null) {
                        if (otherProperties[i] != null) {
                            fail("Insert does not match, expected '" + otherProperties[i] + "' but insert value was 'null'");
                        }
                    } else if (!inserts[i - 1].equals(otherProperties[i])) {
                        fail("Insert does not match, expected '" + otherProperties[i] + "' but insert value was '" + inserts[i - 1] + "'");
                    }
                }
            }
        }
    }
}

18 View Complete Implementation : DefaultSubscriptionRegistry.java
Copyright MIT License
Author : codeEngraver
@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 Complete Implementation : SetValueTests.java
Copyright Apache License 2.0
Author : langtianya
/**
 * 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!
    }
}

18 View Complete Implementation : DefaultSubscriptionRegistry.java
Copyright Apache License 2.0
Author : langtianya
@Override
protected void addSubscriptionInternal(String sessionId, String subsId, String destination, Message<?> message) {
    Expression expression = null;
    MessageHeaders headers = message.getHeaders();
    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);
            }
        }
    }
    this.subscriptionRegistry.addSubscription(sessionId, subsId, destination, expression);
    this.destinationCache.updateAfterNewSubscription(destination, sessionId, subsId);
}

18 View Complete Implementation : CachedMethodExecutorTests.java
Copyright MIT License
Author : codeEngraver
@Test
public void testCachedExecutionForParameters() {
    Expression expression = this.parser.parseExpression("echo(#var)");
    replacedertMethodExecution(expression, 42, "int: 42");
    replacedertMethodExecution(expression, 42, "int: 42");
    replacedertMethodExecution(expression, "Deep Thought", "String: Deep Thought");
    replacedertMethodExecution(expression, 42, "int: 42");
}

18 View Complete Implementation : SpelUtilities.java
Copyright Apache License 2.0
Author : langtianya
/**
 * 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 Complete Implementation : AbstractExpressionTests.java
Copyright Apache License 2.0
Author : langtianya
public void evaluateAndAskForReturnType(String expression, Object expectedValue, Clreplaced<?> expectedResultType) {
    Expression expr = parser.parseExpression(expression);
    if (expr == null) {
        fail("Parser returned null for expression");
    }
    if (DEBUG) {
        SpelUtilities.printAbstractSyntaxTree(System.out, expr);
    }
    Object value = expr.getValue(eContext, expectedResultType);
    if (value == null) {
        if (expectedValue == null) {
            // no point doing other checks
            return;
        }
        replacedertEquals("Expression returned null value, but expected '" + expectedValue + "'", expectedValue, null);
    }
    Clreplaced<?> resultType = value.getClreplaced();
    replacedertEquals("Type of the actual result was not as expected.  Expected '" + expectedResultType + "' but result was of type '" + resultType + "'", expectedResultType, resultType);
    replacedertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, value);
}

18 View Complete Implementation : SetValueTests.java
Copyright MIT License
Author : codeEngraver
/**
 * 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!
    }
}

18 View Complete Implementation : EvaluationTests.java
Copyright MIT License
Author : codeEngraver
@Test
public void testTernaryOperator04() {
    Expression e = parser.parseExpression("1>2?3:4");
    replacedertFalse(e.isWritable(context));
}

18 View Complete Implementation : MethodInvocationTests.java
Copyright Apache License 2.0
Author : langtianya
@Test
public void invokeMethodWithoutConversion() throws Exception {
    final BytesService service = new BytesService();
    byte[] bytes = new byte[100];
    StandardEvaluationContext context = new StandardEvaluationContext(bytes);
    context.setBeanResolver(new BeanResolver() {

        @Override
        public Object resolve(EvaluationContext context, String beanName) throws AccessException {
            if ("service".equals(beanName)) {
                return service;
            }
            return null;
        }
    });
    Expression expression = parser.parseExpression("@service.handleBytes(#root)");
    byte[] outBytes = expression.getValue(context, byte[].clreplaced);
    replacedertSame(bytes, outBytes);
}

18 View Complete Implementation : TemplateAwareExpressionParser.java
Copyright Apache License 2.0
Author : langtianya
private Expression parseTemplate(String expressionString, ParserContext context) throws ParseException {
    if (expressionString.length() == 0) {
        return new LiteralExpression("");
    }
    Expression[] expressions = parseExpressions(expressionString, context);
    if (expressions.length == 1) {
        return expressions[0];
    } else {
        return new CompositeStringExpression(expressionString, expressions);
    }
}

18 View Complete Implementation : TemplateAwareExpressionParser.java
Copyright MIT License
Author : codeEngraver
private Expression parseTemplate(String expressionString, ParserContext context) throws ParseException {
    if (expressionString.isEmpty()) {
        return new LiteralExpression("");
    }
    Expression[] expressions = parseExpressions(expressionString, context);
    if (expressions.length == 1) {
        return expressions[0];
    } else {
        return new CompositeStringExpression(expressionString, expressions);
    }
}

18 View Complete Implementation : AbstractExpressionTests.java
Copyright MIT License
Author : codeEngraver
/**
 * Evaluate an expression and check that the actual result matches the
 * expectedValue and the clreplaced of the result matches the expectedClreplacedOfResult.
 * This method can also check if the expression is writable (for example,
 * it is a variable or property reference).
 * @param expression the expression to evaluate
 * @param expectedValue the expected result for evaluating the expression
 * @param expectedClreplacedOfResult the expected clreplaced of the evaluation result
 * @param shouldBeWritable should the parsed expression be writable?
 */
public void evaluate(String expression, Object expectedValue, Clreplaced<?> expectedClreplacedOfResult, boolean shouldBeWritable) {
    Expression expr = parser.parseExpression(expression);
    if (expr == null) {
        fail("Parser returned null for expression");
    }
    if (DEBUG) {
        SpelUtilities.printAbstractSyntaxTree(System.out, expr);
    }
    Object value = expr.getValue(context);
    if (value == null) {
        if (expectedValue == null) {
            // no point doing other checks
            return;
        }
        replacedertNull("Expression returned null value, but expected '" + expectedValue + "'", expectedValue);
    }
    Clreplaced<? extends Object> resultType = value.getClreplaced();
    if (expectedValue instanceof String) {
        replacedertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, AbstractExpressionTests.stringValueOf(value));
    } else {
        replacedertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, value);
    }
    replacedertTrue("Type of the result was not as expected.  Expected '" + expectedClreplacedOfResult + "' but result was of type '" + resultType + "'", expectedClreplacedOfResult.equals(resultType));
    boolean isWritable = expr.isWritable(context);
    if (isWritable != shouldBeWritable) {
        if (shouldBeWritable)
            fail("Expected the expression to be writable but it is not");
        else
            fail("Expected the expression to be readonly but it is not");
    }
}

18 View Complete Implementation : AbstractExpressionTests.java
Copyright Apache License 2.0
Author : langtianya
/**
 * Evaluate an expression and check that the actual result matches the
 * expectedValue and the clreplaced of the result matches the expectedClreplacedOfResult.
 * @param expression the expression to evaluate
 * @param expectedValue the expected result for evaluating the expression
 * @param expectedResultType the expected clreplaced of the evaluation result
 */
public void evaluate(String expression, Object expectedValue, Clreplaced<?> expectedResultType) {
    Expression expr = parser.parseExpression(expression);
    if (expr == null) {
        fail("Parser returned null for expression");
    }
    if (DEBUG) {
        SpelUtilities.printAbstractSyntaxTree(System.out, expr);
    }
    Object value = expr.getValue(eContext);
    // Check the return value
    if (value == null) {
        if (expectedValue == null) {
            // no point doing other checks
            return;
        }
        replacedertEquals("Expression returned null value, but expected '" + expectedValue + "'", expectedValue, null);
    }
    Clreplaced<?> resultType = value.getClreplaced();
    replacedertEquals("Type of the actual result was not as expected.  Expected '" + expectedResultType + "' but result was of type '" + resultType + "'", expectedResultType, resultType);
    if (expectedValue instanceof String) {
        replacedertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, AbstractExpressionTests.stringValueOf(value));
    } else {
        replacedertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, value);
    }
}

18 View Complete Implementation : SpelUtilities.java
Copyright MIT License
Author : codeEngraver
/**
 * 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 Complete Implementation : AbstractExpressionTests.java
Copyright MIT License
Author : codeEngraver
public void evaluateAndAskForReturnType(String expression, Object expectedValue, Clreplaced<?> expectedResultType) {
    Expression expr = parser.parseExpression(expression);
    if (expr == null) {
        fail("Parser returned null for expression");
    }
    if (DEBUG) {
        SpelUtilities.printAbstractSyntaxTree(System.out, expr);
    }
    Object value = expr.getValue(context, expectedResultType);
    if (value == null) {
        if (expectedValue == null) {
            // no point doing other checks
            return;
        }
        replacedertNull("Expression returned null value, but expected '" + expectedValue + "'", expectedValue);
    }
    Clreplaced<?> resultType = value.getClreplaced();
    replacedertEquals("Type of the actual result was not as expected.  Expected '" + expectedResultType + "' but result was of type '" + resultType + "'", expectedResultType, resultType);
    replacedertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, value);
}

18 View Complete Implementation : MethodInvocationTests.java
Copyright MIT License
Author : codeEngraver
@Test
public void invokeMethodWithoutConversion() throws Exception {
    final BytesService service = new BytesService();
    byte[] bytes = new byte[100];
    StandardEvaluationContext context = new StandardEvaluationContext(bytes);
    context.setBeanResolver(new BeanResolver() {

        @Override
        public Object resolve(EvaluationContext context, String beanName) throws AccessException {
            if ("service".equals(beanName)) {
                return service;
            }
            return null;
        }
    });
    Expression expression = parser.parseExpression("@service.handleBytes(#root)");
    byte[] outBytes = expression.getValue(context, byte[].clreplaced);
    replacedertSame(bytes, outBytes);
}

18 View Complete Implementation : AbstractExpressionTests.java
Copyright MIT License
Author : codeEngraver
/**
 * Evaluate an expression and check that the actual result matches the
 * expectedValue and the clreplaced of the result matches the expectedClreplacedOfResult.
 * @param expression the expression to evaluate
 * @param expectedValue the expected result for evaluating the expression
 * @param expectedResultType the expected clreplaced of the evaluation result
 */
public void evaluate(String expression, Object expectedValue, Clreplaced<?> expectedResultType) {
    Expression expr = parser.parseExpression(expression);
    if (expr == null) {
        fail("Parser returned null for expression");
    }
    if (DEBUG) {
        SpelUtilities.printAbstractSyntaxTree(System.out, expr);
    }
    Object value = expr.getValue(context);
    // Check the return value
    if (value == null) {
        if (expectedValue == null) {
            // no point doing other checks
            return;
        }
        replacedertNull("Expression returned null value, but expected '" + expectedValue + "'", expectedValue);
    }
    Clreplaced<?> resultType = value.getClreplaced();
    replacedertEquals("Type of the actual result was not as expected.  Expected '" + expectedResultType + "' but result was of type '" + resultType + "'", expectedResultType, resultType);
    if (expectedValue instanceof String) {
        replacedertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, AbstractExpressionTests.stringValueOf(value));
    } else {
        replacedertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, value);
    }
}

17 View Complete Implementation : FactoryBeanAccessTests.java
Copyright MIT License
Author : codeEngraver
@Test
public void factoryBeanAccess() {
    // SPR9511
    StandardEvaluationContext context = new StandardEvaluationContext();
    context.setBeanResolver(new SimpleBeanResolver());
    Expression expr = new SpelExpressionParser().parseRaw("@car.colour");
    replacedertEquals("red", expr.getValue(context));
    expr = new SpelExpressionParser().parseRaw("&car.clreplaced.name");
    replacedertEquals(CarFactoryBean.clreplaced.getName(), expr.getValue(context));
    expr = new SpelExpressionParser().parseRaw("@boat.colour");
    replacedertEquals("blue", expr.getValue(context));
    expr = new SpelExpressionParser().parseRaw("&boat.clreplaced.name");
    try {
        replacedertEquals(Boat.clreplaced.getName(), expr.getValue(context));
        fail("Expected BeanIsNotAFactoryException");
    } catch (BeanIsNotAFactoryException binafe) {
    // success
    }
    // No such bean
    try {
        expr = new SpelExpressionParser().parseRaw("@truck");
        replacedertEquals("red", expr.getValue(context));
        fail("Expected NoSuchBeanDefinitionException");
    } catch (NoSuchBeanDefinitionException nsbde) {
    // success
    }
    // No such factory bean
    try {
        expr = new SpelExpressionParser().parseRaw("&truck");
        replacedertEquals(CarFactoryBean.clreplaced.getName(), expr.getValue(context));
        fail("Expected NoSuchBeanDefinitionException");
    } catch (NoSuchBeanDefinitionException nsbde) {
    // success
    }
}

17 View Complete Implementation : SetValueTests.java
Copyright MIT License
Author : codeEngraver
protected void setValue(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();
        replacedertTrue("Expression is not writeable but should be", e.isWritable(lContext));
        e.setValue(lContext, value);
        replacedertEquals("Retrieved value was not equal to set value", value, e.getValue(lContext, value.getClreplaced()));
    } catch (EvaluationException | ParseException ex) {
        ex.printStackTrace();
        fail("Unexpected Exception: " + ex.getMessage());
    }
}

17 View Complete Implementation : ScenariosForSpringSecurity.java
Copyright MIT License
Author : codeEngraver
// Here i'm going to change which hasRole() executes and make it one of my own Java methods
@Test
public void testScenario04_ControllingWhichMethodsRun() throws Exception {
    SpelExpressionParser parser = new SpelExpressionParser();
    StandardEvaluationContext ctx = new StandardEvaluationContext();
    // so non-qualified references 'hasRole()' 'hasIpAddress()' are invoked against it);
    ctx.setRootObject(new Supervisor("Ben"));
    // NEEDS TO OVERRIDE THE REFLECTION ONE - SHOW REORDERING MECHANISM
    ctx.addMethodResolver(new MyMethodResolver());
    // Might be better with a as a variable although it would work as a property too...
    // Variable references using a '#'
    // SpelExpression expr = parser.parseExpression("(hasRole('SUPERVISOR') or (#a <  1.042)) and hasIpAddress('10.10.0.0/16')");
    Expression expr = parser.parseRaw("(hasRole(3) or (#a <  1.042)) and hasIpAddress('10.10.0.0/16')");
    Boolean value = null;
    // referenced as #a in the expression
    ctx.setVariable("a", 1.0d);
    value = expr.getValue(ctx, Boolean.clreplaced);
    replacedertTrue(value);
// ctx.setRootObject(new Manager("Luke"));
// ctx.setVariable("a",1.043d);
// value = (Boolean)expr.getValue(ctx,Boolean.clreplaced);
// replacedertFalse(value);
}

17 View Complete Implementation : SpelExceptionTests.java
Copyright MIT License
Author : codeEngraver
@Test
@SuppressWarnings("serial")
public void spelExpressionArrayWithVariables() {
    ExpressionParser parser = new SpelExpressionParser();
    Expression spelExpression = parser.parseExpression("#anArray[0] eq 1");
    StandardEvaluationContext ctx = new StandardEvaluationContext();
    ctx.setVariables(new HashMap<String, Object>() {

        {
            put("anArray", new int[] { 1, 2, 3 });
        }
    });
    boolean result = spelExpression.getValue(ctx, Boolean.clreplaced);
    replacedertTrue(result);
}

17 View Complete Implementation : CompositeStringExpression.java
Copyright MIT License
Author : codeEngraver
@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();
}

17 View Complete Implementation : CompositeStringExpression.java
Copyright MIT License
Author : codeEngraver
@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();
}

17 View Complete Implementation : SpelCompilationPerformanceTests.java
Copyright MIT License
Author : codeEngraver
@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);
}

17 View Complete Implementation : SpelExceptionTests.java
Copyright MIT License
Author : codeEngraver
@Test
@SuppressWarnings("serial")
public void spelExpressionListWithVariables() {
    ExpressionParser parser = new SpelExpressionParser();
    Expression spelExpression = parser.parseExpression("#aList.contains('one')");
    StandardEvaluationContext ctx = new StandardEvaluationContext();
    ctx.setVariables(new HashMap<String, Object>() {

        {
            put("aList", new ArrayList<String>() {

                {
                    add("one");
                    add("two");
                    add("three");
                }
            });
        }
    });
    boolean result = spelExpression.getValue(ctx, Boolean.clreplaced);
    replacedertTrue(result);
}

17 View Complete Implementation : SpelCompilationPerformanceTests.java
Copyright MIT License
Author : codeEngraver
@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);
}

17 View Complete Implementation : SpelCompilationPerformanceTests.java
Copyright MIT License
Author : codeEngraver
@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);
}

17 View Complete Implementation : SpelExceptionTests.java
Copyright MIT License
Author : codeEngraver
@Test
@SuppressWarnings("serial")
public void spelExpressionMapWithVariables() {
    ExpressionParser parser = new SpelExpressionParser();
    Expression spelExpression = parser.parseExpression("#aMap['one'] eq 1");
    StandardEvaluationContext ctx = new StandardEvaluationContext();
    ctx.setVariables(new HashMap<String, Object>() {

        {
            put("aMap", new HashMap<String, Integer>() {

                {
                    put("one", 1);
                    put("two", 2);
                    put("three", 3);
                }
            });
        }
    });
    boolean result = spelExpression.getValue(ctx, Boolean.clreplaced);
    replacedertTrue(result);
}

17 View Complete Implementation : ScenariosForSpringSecurity.java
Copyright MIT License
Author : codeEngraver
@Test
public void testScenario03_Arithmetic() throws Exception {
    SpelExpressionParser parser = new SpelExpressionParser();
    StandardEvaluationContext ctx = new StandardEvaluationContext();
    // Might be better with a as a variable although it would work as a property too...
    // Variable references using a '#'
    Expression expr = parser.parseRaw("(hasRole('SUPERVISOR') or (#a <  1.042)) and hasIpAddress('10.10.0.0/16')");
    Boolean value = null;
    // referenced as #a in the expression
    ctx.setVariable("a", 1.0d);
    // so non-qualified references 'hasRole()' 'hasIpAddress()' are invoked against it
    ctx.setRootObject(new Supervisor("Ben"));
    value = expr.getValue(ctx, Boolean.clreplaced);
    replacedertTrue(value);
    ctx.setRootObject(new Manager("Luke"));
    ctx.setVariable("a", 1.043d);
    value = expr.getValue(ctx, Boolean.clreplaced);
    replacedertFalse(value);
}

17 View Complete Implementation : DefaultSubscriptionRegistry.java
Copyright MIT License
Author : codeEngraver
private MultiValueMap<String, String> filterSubscriptions(MultiValueMap<String, String> allMatches, Message<?> message) {
    if (!this.selectorHeaderInUse) {
        return allMatches;
    }
    MultiValueMap<String, String> result = new LinkedMultiValueMap<>(allMatches.size());
    allMatches.forEach((sessionId, subIds) -> {
        for (String subId : subIds) {
            SessionSubscriptionInfo info = this.subscriptionRegistry.getSubscriptions(sessionId);
            if (info == null) {
                continue;
            }
            Subscription sub = info.getSubscription(subId);
            if (sub == null) {
                continue;
            }
            Expression expression = sub.getSelectorExpression();
            if (expression == null) {
                result.add(sessionId, subId);
                continue;
            }
            try {
                if (Boolean.TRUE.equals(expression.getValue(messageEvalContext, message, Boolean.clreplaced))) {
                    result.add(sessionId, subId);
                }
            } catch (SpelEvaluationException ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Failed to evaluate selector: " + ex.getMessage());
                }
            } catch (Throwable ex) {
                logger.debug("Failed to evaluate selector", ex);
            }
        }
    });
    return result;
}

17 View Complete Implementation : CompositeStringExpression.java
Copyright MIT License
Author : codeEngraver
@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();
}

17 View Complete Implementation : TemplateExpressionParsingTests.java
Copyright MIT License
Author : codeEngraver
@Test
public void testClashingWithSuffixes() throws Exception {
    // Just wanting to use the prefix or suffix within the template:
    Expression ex = parser.parseExpression("hello ${3+4} world", DEFAULT_TEMPLATE_PARSER_CONTEXT);
    String s = ex.getValue(TestScenarioCreator.getTestEvaluationContext(), String.clreplaced);
    replacedertEquals("hello 7 world", s);
    ex = parser.parseExpression("hello ${3+4} wo${'${'}rld", DEFAULT_TEMPLATE_PARSER_CONTEXT);
    s = ex.getValue(TestScenarioCreator.getTestEvaluationContext(), String.clreplaced);
    replacedertEquals("hello 7 wo${rld", s);
    ex = parser.parseExpression("hello ${3+4} wo}rld", DEFAULT_TEMPLATE_PARSER_CONTEXT);
    s = ex.getValue(TestScenarioCreator.getTestEvaluationContext(), String.clreplaced);
    replacedertEquals("hello 7 wo}rld", s);
}

17 View Complete Implementation : TemplateExpressionParsingTests.java
Copyright MIT License
Author : codeEngraver
@Test
public void testParsingNormalExpressionThroughTemplateParser() throws Exception {
    Expression expr = parser.parseExpression("1+2+3");
    replacedertEquals(6, expr.getValue());
}

17 View Complete Implementation : PropertiesConversionSpelTests.java
Copyright MIT License
Author : codeEngraver
@Test
public void customMapWithNonStringValue() {
    CustomMap map = new CustomMap();
    map.put("x", "1");
    map.put("y", 2);
    map.put("z", "3");
    Expression expression = parser.parseExpression("foo(#props)");
    StandardEvaluationContext context = new StandardEvaluationContext();
    context.setVariable("props", map);
    String result = expression.getValue(context, new TestBean(), String.clreplaced);
    replacedertEquals("1null3", result);
}

17 View Complete Implementation : PropertyAccessTests.java
Copyright MIT License
Author : codeEngraver
@Test
public void testAccessingPropertyOfClreplaced() {
    Expression expression = parser.parseExpression("name");
    Object value = expression.getValue(new StandardEvaluationContext(String.clreplaced));
    replacedertEquals("java.lang.String", value);
}

17 View Complete Implementation : SetValueTests.java
Copyright MIT License
Author : codeEngraver
/**
 * For use when coercion is happening during a setValue().  The expectedValue should be
 * the coerced form of the value.
 */
protected void setValue(String expression, Object value, Object expectedValue) {
    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();
        replacedertTrue("Expression is not writeable but should be", e.isWritable(lContext));
        e.setValue(lContext, value);
        Object a = expectedValue;
        Object b = e.getValue(lContext);
        if (!a.equals(b)) {
            fail("Not the same: [" + a + "] type=" + a.getClreplaced() + "  [" + b + "] type=" + b.getClreplaced());
        // replacedertEquals("Retrieved value was not equal to set value", expectedValue, e.getValue(lContext));
        }
    } catch (EvaluationException | ParseException ex) {
        ex.printStackTrace();
        fail("Unexpected Exception: " + ex.getMessage());
    }
}

17 View Complete Implementation : SpelExceptionTests.java
Copyright MIT License
Author : codeEngraver
@Test
@SuppressWarnings("serial")
public void spelExpressionListIndexAccessWithVariables() {
    ExpressionParser parser = new SpelExpressionParser();
    Expression spelExpression = parser.parseExpression("#aList[0] eq 'one'");
    StandardEvaluationContext ctx = new StandardEvaluationContext();
    ctx.setVariables(new HashMap<String, Object>() {

        {
            put("aList", new ArrayList<String>() {

                {
                    add("one");
                    add("two");
                    add("three");
                }
            });
        }
    });
    boolean result = spelExpression.getValue(ctx, Boolean.clreplaced);
    replacedertTrue(result);
}

17 View Complete Implementation : CompositeStringExpression.java
Copyright MIT License
Author : codeEngraver
@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();
}

17 View Complete Implementation : SpelCompilationPerformanceTests.java
Copyright MIT License
Author : codeEngraver
@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);
}

17 View Complete Implementation : SetValueTests.java
Copyright MIT License
Author : codeEngraver
@Test
public void testreplacedign() throws Exception {
    StandardEvaluationContext eContext = TestScenarioCreator.getTestEvaluationContext();
    Expression e = parse("publicName='Andy'");
    replacedertFalse(e.isWritable(eContext));
    replacedertEquals("Andy", e.getValue(eContext));
}