org.springframework.expression.EvaluationException Java Examples

The following examples show how to use org.springframework.expression.EvaluationException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExpressionUtils.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Determines if there is a type converter available in the specified context and
 * attempts to use it to convert the supplied value to the specified type. Throws an
 * exception if conversion is not possible.
 * @param context the evaluation context that may define a type converter
 * @param typedValue the value to convert and a type descriptor describing it
 * @param targetType the type to attempt conversion to
 * @return the converted value
 * @throws EvaluationException if there is a problem during conversion or conversion
 * of the value to the specified type is not supported
 */
@SuppressWarnings("unchecked")
@Nullable
public static <T> T convertTypedValue(
		@Nullable EvaluationContext context, TypedValue typedValue, @Nullable Class<T> targetType) {

	Object value = typedValue.getValue();
	if (targetType == null) {
		return (T) value;
	}
	if (context != null) {
		return (T) context.getTypeConverter().convertValue(
				value, typedValue.getTypeDescriptor(), TypeDescriptor.valueOf(targetType));
	}
	if (ClassUtils.isAssignableValue(targetType, value)) {
		return (T) value;
	}
	throw new EvaluationException("Cannot convert value '" + value + "' to type '" + targetType.getName() + "'");
}
 
Example #2
Source File: PropertyOrFieldReference.java    From java-technology-stack with MIT License 6 votes vote down vote up
public boolean isWritableProperty(String name, TypedValue contextObject, EvaluationContext evalContext)
		throws EvaluationException {

	Object value = contextObject.getValue();
	if (value != null) {
		List<PropertyAccessor> accessorsToTry =
				getPropertyAccessorsToTry(contextObject.getValue(), evalContext.getPropertyAccessors());
		for (PropertyAccessor accessor : accessorsToTry) {
			try {
				if (accessor.canWrite(evalContext, value, name)) {
					return true;
				}
			}
			catch (AccessException ex) {
				// let others try
			}
		}
	}
	return false;
}
 
Example #3
Source File: PropertyOrFieldReference.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public boolean isWritableProperty(String name, TypedValue contextObject, EvaluationContext evalContext)
		throws EvaluationException {

	List<PropertyAccessor> accessorsToTry =
			getPropertyAccessorsToTry(contextObject.getValue(), evalContext.getPropertyAccessors());
	if (accessorsToTry != null) {
		for (PropertyAccessor accessor : accessorsToTry) {
			try {
				if (accessor.canWrite(evalContext, contextObject.getValue(), name)) {
					return true;
				}
			}
			catch (AccessException ex) {
				// let others try
			}
		}
	}
	return false;
}
 
Example #4
Source File: PropertyOrFieldReference.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
public boolean isWritableProperty(String name, TypedValue contextObject, EvaluationContext evalContext)
		throws EvaluationException {

	List<PropertyAccessor> accessorsToTry =
			getPropertyAccessorsToTry(contextObject.getValue(), evalContext.getPropertyAccessors());
	if (accessorsToTry != null) {
		for (PropertyAccessor accessor : accessorsToTry) {
			try {
				if (accessor.canWrite(evalContext, contextObject.getValue(), name)) {
					return true;
				}
			}
			catch (AccessException ex) {
				// let others try
			}
		}
	}
	return false;
}
 
Example #5
Source File: SelectionRulePlanBasedAuthenticationHandler.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public boolean canHandle(AuthenticationContext context) {
    boolean handle = handler.canHandle(context);

    if (!handle) {
        return false;
    }

    try {
        Expression expression = new SpelExpressionParser().parseExpression(
                plan.getSelectionRule().replaceAll(EXPRESSION_REGEX, EXPRESSION_REGEX_SUBSTITUTE));

        StandardEvaluationContext evaluation = new StandardEvaluationContext();
        evaluation.setVariable("request", new EvaluableRequest(context.request()));
        evaluation.setVariable("context", new EvaluableAuthenticationContext(context));

        return expression.getValue(evaluation, Boolean.class);
    } catch (ParseException | EvaluationException ex) {
        return false;
    }
}
 
Example #6
Source File: SpelExpression.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public Object getValue() throws EvaluationException {
	Object result;
	if (this.compiledAst != null) {
		try {
			TypedValue contextRoot = evaluationContext == null ? null : evaluationContext.getRootObject();
			return this.compiledAst.getValue(contextRoot == null ? null : contextRoot.getValue(), evaluationContext);
		}
		catch (Throwable ex) {
			// If running in mixed mode, revert to interpreted
			if (this.configuration.getCompilerMode() == SpelCompilerMode.MIXED) {
				this.interpretedCount = 0;
				this.compiledAst = null;
			}
			else {
				// Running in SpelCompilerMode.immediate mode - propagate exception to caller
				throw new SpelEvaluationException(ex, SpelMessage.EXCEPTION_RUNNING_COMPILED_EXPRESSION);
			}
		}
	}
	ExpressionState expressionState = new ExpressionState(getEvaluationContext(), this.configuration);
	result = this.ast.getValue(expressionState);
	checkCompile(expressionState);
	return result;
}
 
Example #7
Source File: ExpressionLanguageScenarioTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Scenario: using your own java methods and calling them from the expression
 */
@Test
public void testScenario_RegisteringJavaMethodsAsFunctionsAndCallingThem() throws SecurityException, NoSuchMethodException {
	try {
		// Create a parser
		SpelExpressionParser parser = new SpelExpressionParser();
		// Use the standard evaluation context
		StandardEvaluationContext ctx = new StandardEvaluationContext();
		ctx.registerFunction("repeat",ExpressionLanguageScenarioTests.class.getDeclaredMethod("repeat",String.class));

		Expression expr = parser.parseRaw("#repeat('hello')");
		Object value = expr.getValue(ctx);
		assertEquals("hellohello", value);

	} catch (EvaluationException ee) {
		ee.printStackTrace();
		fail("Unexpected Exception: " + ee.getMessage());
	} catch (ParseException pe) {
		pe.printStackTrace();
		fail("Unexpected Exception: " + pe.getMessage());
	}
}
 
Example #8
Source File: FunctionReference.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
	TypedValue value = state.lookupVariable(this.name);
	if (value == null) {
		throw new SpelEvaluationException(getStartPosition(), SpelMessage.FUNCTION_NOT_DEFINED, this.name);
	}

	// Two possibilities: a lambda function or a Java static method registered as a function
	if (!(value.getValue() instanceof Method)) {
		throw new SpelEvaluationException(
				SpelMessage.FUNCTION_REFERENCE_CANNOT_BE_INVOKED, this.name, value.getClass());
	}

	try {
		return executeFunctionJLRMethod(state, (Method) value.getValue());
	}
	catch (SpelEvaluationException ex) {
		ex.setPosition(getStartPosition());
		throw ex;
	}
}
 
Example #9
Source File: SetValueTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
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();
		assertTrue("Expression is not writeable but should be", e.isWritable(lContext));
		e.setValue(lContext, value);
		assertEquals("Retrieved value was not equal to set value", value, e.getValue(lContext,value.getClass()));
	}
	catch (EvaluationException | ParseException ex) {
		ex.printStackTrace();
		fail("Unexpected Exception: " + ex.getMessage());
	}
}
 
Example #10
Source File: ScenariosForSpringSecurity.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testScenario01_Roles() throws Exception {
	try {
		SpelExpressionParser parser = new SpelExpressionParser();
		StandardEvaluationContext ctx = new StandardEvaluationContext();
		Expression expr = parser.parseRaw("hasAnyRole('MANAGER','TELLER')");

		ctx.setRootObject(new Person("Ben"));
		Boolean value = expr.getValue(ctx,Boolean.class);
		assertFalse(value);

		ctx.setRootObject(new Manager("Luke"));
		value = expr.getValue(ctx,Boolean.class);
		assertTrue(value);

	}
	catch (EvaluationException ee) {
		ee.printStackTrace();
		fail("Unexpected SpelException: " + ee.getMessage());
	}
}
 
Example #11
Source File: StandardTypeLocator.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Find a (possibly unqualified) type reference - first using the type name as-is,
 * then trying any registered prefixes if the type name cannot be found.
 * @param typeName the type to locate
 * @return the class object for the type
 * @throws EvaluationException if the type cannot be found
 */
@Override
public Class<?> findType(String typeName) throws EvaluationException {
	String nameToLookup = typeName;
	try {
		return ClassUtils.forName(nameToLookup, this.classLoader);
	}
	catch (ClassNotFoundException ey) {
		// try any registered prefixes before giving up
	}
	for (String prefix : this.knownPackagePrefixes) {
		try {
			nameToLookup = prefix + '.' + typeName;
			return ClassUtils.forName(nameToLookup, this.classLoader);
		}
		catch (ClassNotFoundException ex) {
			// might be a different prefix
		}
	}
	throw new SpelEvaluationException(SpelMessage.TYPE_NOT_FOUND, typeName);
}
 
Example #12
Source File: MethodReference.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected ValueRef getValueRef(ExpressionState state) throws EvaluationException {
	Object[] arguments = getArguments(state);
	if (state.getActiveContextObject().getValue() == null) {
		throwIfNotNullSafe(getArgumentTypes(arguments));
		return ValueRef.NullValueRef.INSTANCE;
	}
	return new MethodValueRef(state, arguments);
}
 
Example #13
Source File: Elvis.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Evaluate the condition and if not null, return it.
 * If it is null, return the other value.
 * @param state the expression state
 * @throws EvaluationException if the condition does not evaluate correctly
 * to a boolean or there is a problem executing the chosen alternative
 */
@Override
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
	TypedValue value = this.children[0].getValueInternal(state);
	// If this check is changed, the generateCode method will need changing too
	if (!StringUtils.isEmpty(value.getValue())) {
		return value;
	}
	else {
		TypedValue result = this.children[1].getValueInternal(state);
		computeExitTypeDescriptor();
		return result;
	}
}
 
Example #14
Source File: CompositeStringExpression.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public String getValue(EvaluationContext context) throws EvaluationException {
	StringBuilder sb = new StringBuilder();
	for (Expression expression : this.expressions) {
		String value = expression.getValue(context, String.class);
		if (value != null) {
			sb.append(value);
		}
	}
	return sb.toString();
}
 
Example #15
Source File: InlineList.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public TypedValue getValueInternal(ExpressionState expressionState) throws EvaluationException {
	if (this.constant != null) {
		return this.constant;
	}
	else {
		List<Object> returnValue = new ArrayList<Object>();
		int childCount = getChildCount();
		for (int c = 0; c < childCount; c++) {
			returnValue.add(getChild(c).getValue(expressionState));
		}
		return new TypedValue(returnValue);
	}
}
 
Example #16
Source File: OperatorPower.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
	SpelNodeImpl leftOp = getLeftOperand();
	SpelNodeImpl rightOp = getRightOperand();

	Object leftOperand = leftOp.getValueInternal(state).getValue();
	Object rightOperand = rightOp.getValueInternal(state).getValue();

	if (leftOperand instanceof Number && rightOperand instanceof Number) {
		Number leftNumber = (Number) leftOperand;
		Number rightNumber = (Number) rightOperand;

		if (leftNumber instanceof BigDecimal) {
			BigDecimal leftBigDecimal = NumberUtils.convertNumberToTargetClass(leftNumber, BigDecimal.class);
			return new TypedValue(leftBigDecimal.pow(rightNumber.intValue()));
		}
		else if (leftNumber instanceof BigInteger) {
			BigInteger leftBigInteger = NumberUtils.convertNumberToTargetClass(leftNumber, BigInteger.class);
			return new TypedValue(leftBigInteger.pow(rightNumber.intValue()));
		}
		else if (leftNumber instanceof Double || rightNumber instanceof Double) {
			return new TypedValue(Math.pow(leftNumber.doubleValue(), rightNumber.doubleValue()));
		}
		else if (leftNumber instanceof Float || rightNumber instanceof Float) {
			return new TypedValue(Math.pow(leftNumber.floatValue(), rightNumber.floatValue()));
		}

		double d = Math.pow(leftNumber.doubleValue(), rightNumber.doubleValue());
		if (d > Integer.MAX_VALUE || leftNumber instanceof Long || rightNumber instanceof Long) {
			return new TypedValue((long) d);
		}
		else {
			return new TypedValue((int) d);
		}
	}

	return state.operate(Operation.POWER, leftOperand, rightOperand);
}
 
Example #17
Source File: SpelExpression.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
@Nullable
public <T> T getValue(@Nullable Class<T> expectedResultType) throws EvaluationException {
	if (this.compiledAst != null) {
		try {
			EvaluationContext context = getEvaluationContext();
			Object result = this.compiledAst.getValue(context.getRootObject().getValue(), context);
			if (expectedResultType == null) {
				return (T) result;
			}
			else {
				return ExpressionUtils.convertTypedValue(
						getEvaluationContext(), new TypedValue(result), expectedResultType);
			}
		}
		catch (Throwable ex) {
			// If running in mixed mode, revert to interpreted
			if (this.configuration.getCompilerMode() == SpelCompilerMode.MIXED) {
				this.interpretedCount = 0;
				this.compiledAst = null;
			}
			else {
				// Running in SpelCompilerMode.immediate mode - propagate exception to caller
				throw new SpelEvaluationException(ex, SpelMessage.EXCEPTION_RUNNING_COMPILED_EXPRESSION);
			}
		}
	}

	ExpressionState expressionState = new ExpressionState(getEvaluationContext(), this.configuration);
	TypedValue typedResultValue = this.ast.getTypedValue(expressionState);
	checkCompile(expressionState);
	return ExpressionUtils.convertTypedValue(
			expressionState.getEvaluationContext(), typedResultValue, expectedResultType);
}
 
Example #18
Source File: SpelReproTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public Class<?> findType(String typeName) throws EvaluationException {
	if (typeName.equals("Spr5899Class")) {
		return Spr5899Class.class;
	}
	if (typeName.equals("Outer")) {
		return Outer.class;
	}
	return super.findType(typeName);
}
 
Example #19
Source File: CompoundExpression.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected ValueRef getValueRef(ExpressionState state) throws EvaluationException {
	if (getChildCount() == 1) {
		return this.children[0].getValueRef(state);
	}

	SpelNodeImpl nextNode = this.children[0];
	try {
		TypedValue result = nextNode.getValueInternal(state);
		int cc = getChildCount();
		for (int i = 1; i < cc - 1; i++) {
			try {
				state.pushActiveContextObject(result);
				nextNode = this.children[i];
				result = nextNode.getValueInternal(state);
			}
			finally {
				state.popActiveContextObject();
			}
		}
		try {
			state.pushActiveContextObject(result);
			nextNode = this.children[cc - 1];
			return nextNode.getValueRef(state);
		}
		finally {
			state.popActiveContextObject();
		}
	}
	catch (SpelEvaluationException ex) {
		// Correct the position for the error before re-throwing
		ex.setPosition(nextNode.getStartPosition());
		throw ex;
	}
}
 
Example #20
Source File: CompositeStringExpression.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public String getValue(Object rootObject) throws EvaluationException {
	StringBuilder sb = new StringBuilder();
	for (Expression expression : this.expressions) {
		String value = expression.getValue(rootObject, String.class);
		if (value != null) {
			sb.append(value);
		}
	}
	return sb.toString();
}
 
Example #21
Source File: EvaluationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test  // SPR-16731
public void testMatchesWithPatternAccessThreshold() {
	String pattern = "^(?=[a-z0-9-]{1,47})([a-z0-9]+[-]{0,1}){1,47}[a-z0-9]{1}$";
	String expression = "'abcde-fghijklmn-o42pasdfasdfasdf.qrstuvwxyz10x.xx.yyy.zasdfasfd' matches \'" + pattern + "\'";
	Expression expr = parser.parseExpression(expression);
	try {
		expr.getValue();
		fail("Should have exceeded threshold");
	}
	catch (EvaluationException ee) {
		SpelEvaluationException see = (SpelEvaluationException) ee;
		assertEquals(SpelMessage.FLAWED_PATTERN, see.getMessageCode());
		assertTrue(see.getCause() instanceof IllegalStateException);
	}
}
 
Example #22
Source File: CompositeStringExpression.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public String getValue(EvaluationContext context) throws EvaluationException {
	StringBuilder sb = new StringBuilder();
	for (Expression expression : this.expressions) {
		String value = expression.getValue(context, String.class);
		if (value != null) {
			sb.append(value);
		}
	}
	return sb.toString();
}
 
Example #23
Source File: CompositeStringExpression.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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.class);
		if (value != null) {
			sb.append(value);
		}
	}
	return sb.toString();
}
 
Example #24
Source File: SpelReproTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Class<?> findType(String typeName) throws EvaluationException {
	if (typeName.equals("Spr5899Class")) {
		return Spr5899Class.class;
	}
	if (typeName.equals("Outer")) {
		return Outer.class;
	}
	return super.findType(typeName);
}
 
Example #25
Source File: SpelExpression.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
@Nullable
public <T> T getValue(EvaluationContext context, @Nullable Class<T> expectedResultType) throws EvaluationException {
	Assert.notNull(context, "EvaluationContext is required");

	if (this.compiledAst != null) {
		try {
			Object result = this.compiledAst.getValue(context.getRootObject().getValue(), context);
			if (expectedResultType != null) {
				return ExpressionUtils.convertTypedValue(context, new TypedValue(result), expectedResultType);
			}
			else {
				return (T) result;
			}
		}
		catch (Throwable ex) {
			// If running in mixed mode, revert to interpreted
			if (this.configuration.getCompilerMode() == SpelCompilerMode.MIXED) {
				this.interpretedCount = 0;
				this.compiledAst = null;
			}
			else {
				// Running in SpelCompilerMode.immediate mode - propagate exception to caller
				throw new SpelEvaluationException(ex, SpelMessage.EXCEPTION_RUNNING_COMPILED_EXPRESSION);
			}
		}
	}

	ExpressionState expressionState = new ExpressionState(context, this.configuration);
	TypedValue typedResultValue = this.ast.getTypedValue(expressionState);
	checkCompile(expressionState);
	return ExpressionUtils.convertTypedValue(context, typedResultValue, expectedResultType);
}
 
Example #26
Source File: OpOr.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public BooleanTypedValue getValueInternal(ExpressionState state) throws EvaluationException {
	if (getBooleanValue(state, getLeftOperand())) {
		// no need to evaluate right operand
		return BooleanTypedValue.TRUE;
	}
	return BooleanTypedValue.forValue(getBooleanValue(state, getRightOperand()));
}
 
Example #27
Source File: PropertyAccessTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
// Adding a new property accessor just for a particular type
public void testAddingSpecificPropertyAccessor() throws Exception {
	SpelExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext ctx = new StandardEvaluationContext();

	// Even though this property accessor is added after the reflection one, it specifically
	// names the String class as the type it is interested in so is chosen in preference to
	// any 'default' ones
	ctx.addPropertyAccessor(new StringyPropertyAccessor());
	Expression expr = parser.parseRaw("new String('hello').flibbles");
	Integer i = expr.getValue(ctx, Integer.class);
	assertEquals((int) i, 7);

	// The reflection one will be used for other properties...
	expr = parser.parseRaw("new String('hello').CASE_INSENSITIVE_ORDER");
	Object o = expr.getValue(ctx);
	assertNotNull(o);

	expr = parser.parseRaw("new String('hello').flibbles");
	expr.setValue(ctx, 99);
	i = expr.getValue(ctx, Integer.class);
	assertEquals((int) i, 99);

	// Cannot set it to a string value
	try {
		expr.setValue(ctx, "not allowed");
		fail("Should not have been allowed");
	} catch (EvaluationException e) {
		// success - message will be: EL1063E:(pos 20): A problem occurred whilst attempting to set the property
		// 'flibbles': 'Cannot set flibbles to an object of type 'class java.lang.String''
		// System.out.println(e.getMessage());
	}
}
 
Example #28
Source File: InlineList.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public TypedValue getValueInternal(ExpressionState expressionState) throws EvaluationException {
	if (this.constant != null) {
		return this.constant;
	}
	else {
		List<Object> returnValue = new ArrayList<Object>();
		int childCount = getChildCount();
		for (int c = 0; c < childCount; c++) {
			returnValue.add(getChild(c).getValue(expressionState));
		}
		return new TypedValue(returnValue);
	}
}
 
Example #29
Source File: PropertyAccessTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void write(EvaluationContext context, Object target, String name, Object newValue)
		throws AccessException {
	if (!name.equals("flibbles"))
		throw new RuntimeException("Assertion Failed! name should be flibbles");
	try {
		flibbles = (Integer) context.getTypeConverter().convertValue(newValue, TypeDescriptor.forObject(newValue), TypeDescriptor.valueOf(Integer.class));
	}catch (EvaluationException e) {
		throw new AccessException("Cannot set flibbles to an object of type '" + newValue.getClass() + "'");
	}
}
 
Example #30
Source File: SpelNodeImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final TypedValue getTypedValue(ExpressionState expressionState) throws EvaluationException {
	if (expressionState != null) {
		return getValueInternal(expressionState);
	}
	else {
		// configuration not set - does that matter?
		return getTypedValue(new ExpressionState(new StandardEvaluationContext()));
	}
}