Java Code Examples for org.springframework.expression.spel.support.StandardEvaluationContext

The following examples show how to use org.springframework.expression.spel.support.StandardEvaluationContext. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: spring-analysis-note   Source File: PropertyAccessTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testAddingRemovingAccessors() {
	StandardEvaluationContext ctx = new StandardEvaluationContext();

	// reflective property accessor is the only one by default
	List<PropertyAccessor> propertyAccessors = ctx.getPropertyAccessors();
	assertEquals(1,propertyAccessors.size());

	StringyPropertyAccessor spa = new StringyPropertyAccessor();
	ctx.addPropertyAccessor(spa);
	assertEquals(2,ctx.getPropertyAccessors().size());

	List<PropertyAccessor> copy = new ArrayList<>();
	copy.addAll(ctx.getPropertyAccessors());
	assertTrue(ctx.removePropertyAccessor(spa));
	assertFalse(ctx.removePropertyAccessor(spa));
	assertEquals(1,ctx.getPropertyAccessors().size());

	ctx.setPropertyAccessors(copy);
	assertEquals(2,ctx.getPropertyAccessors().size());
}
 
Example 2
Source Project: spring-analysis-note   Source File: LiteralExpressionTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testGetValue() throws Exception {
	LiteralExpression lEx = new LiteralExpression("somevalue");
	checkString("somevalue", lEx.getValue());
	checkString("somevalue", lEx.getValue(String.class));
	EvaluationContext ctx = new StandardEvaluationContext();
	checkString("somevalue", lEx.getValue(ctx));
	checkString("somevalue", lEx.getValue(ctx, String.class));
	checkString("somevalue", lEx.getValue(new Rooty()));
	checkString("somevalue", lEx.getValue(new Rooty(), String.class));
	checkString("somevalue", lEx.getValue(ctx, new Rooty()));
	checkString("somevalue", lEx.getValue(ctx, new Rooty(),String.class));
	assertEquals("somevalue", lEx.getExpressionString());
	assertFalse(lEx.isWritable(new StandardEvaluationContext()));
	assertFalse(lEx.isWritable(new Rooty()));
	assertFalse(lEx.isWritable(new StandardEvaluationContext(), new Rooty()));
}
 
Example 3
/**
 * Scenario: add a property resolver that will get called in the resolver chain, this one only supports reading.
 */
@Test
public void testScenario_AddingYourOwnPropertyResolvers_1() throws Exception {
	// Create a parser
	SpelExpressionParser parser = new SpelExpressionParser();
	// Use the standard evaluation context
	StandardEvaluationContext ctx = new StandardEvaluationContext();

	ctx.addPropertyAccessor(new FruitColourAccessor());
	Expression expr = parser.parseRaw("orange");
	Object value = expr.getValue(ctx);
	assertEquals(Color.orange, value);

	try {
		expr.setValue(ctx, Color.blue);
		fail("Should not be allowed to set oranges to be blue !");
	} catch (SpelEvaluationException ee) {
		assertEquals(ee.getMessageCode(), SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL);
	}
}
 
Example 4
Source Project: java-master   Source File: SpELTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("ALL")
public void test6() {
    Inventor tesla = new Inventor("Nikola Tesla", new Date(), "Bei Jin");
    Inventor tesla1 = new Inventor("Nikola Tesla", new Date(), "Shang Hai");
    Inventor tesla2 = new Inventor("Nikola Tesla", new Date(), "New York");
    Inventor tesla3 = new Inventor("Nikola Tesla", new Date(), "Serbian");
    Inventor tesla4 = new Inventor("Nikola Tesla", new Date(), "Serbian");
    List<Inventor> inventors = Arrays.asList(tesla, tesla1, tesla2, tesla3, tesla4);
    EvaluationContext context = new StandardEvaluationContext();
    context.setVariable("inventors", inventors);

    // 对List做各类运算
    List<Inventor> list = (List<Inventor>) parser.parseExpression("#inventors.?[serbian=='Serbian']").getValue(context);
    logger.info(list.toString());

    List<Inventor> list1 = (List<Inventor>) parser.parseExpression("#inventors.![serbian]").getValue(context);
    logger.info(list1.toString());

    List<Inventor> list2 = (List<Inventor>) parser.parseExpression("#inventors.![serbian=='Serbian']").getValue(context);
    logger.info(list2.toString());

    List<Inventor> list3 = (List<Inventor>) parser.parseExpression("#inventors.![#this.getSerbian()]").getValue(context);
    logger.info(list3.toString());
}
 
Example 5
Source Project: spring-analysis-note   Source File: SpelDocumentationTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testDictionaryAccess() throws Exception {
	StandardEvaluationContext societyContext = new StandardEvaluationContext();
	societyContext.setRootObject(new IEEE());
	// Officer's Dictionary
	Inventor pupin = parser.parseExpression("officers['president']").getValue(societyContext, Inventor.class);
	assertNotNull(pupin);

	// evaluates to "Idvor"
	String city = parser.parseExpression("officers['president'].PlaceOfBirth.city").getValue(societyContext, String.class);
	assertNotNull(city);

	// setting values
	Inventor i = parser.parseExpression("officers['advisors'][0]").getValue(societyContext,Inventor.class);
	assertEquals("Nikola Tesla",i.getName());

	parser.parseExpression("officers['advisors'][0].PlaceOfBirth.Country").setValue(societyContext, "Croatia");

	Inventor i2 = parser.parseExpression("reverse[0]['advisors'][0]").getValue(societyContext,Inventor.class);
	assertEquals("Nikola Tesla",i2.getName());

}
 
Example 6
Source Project: Milkomeda   Source File: ExpressionEvaluator.java    License: MIT License 6 votes vote down vote up
/**
 * 根据方法创建一个 {@link EvaluationContext}
 * @param object        目标对象
 * @param targetClass   目标类型
 * @param method        方法
 * @param args          参数
 * @return  EvaluationContext
 */
public StandardEvaluationContext createEvaluationContext(Object object, Class<?> targetClass,
                                                         Method method, Object[] args) {
    Method targetMethod = getTargetMethod(targetClass, method);
    // 创建自定义EL Root
    ExpressionRootObject root = new ExpressionRootObject(object, args);
    // 创建基于方法的执行上下文
    MethodBasedEvaluationContext evaluationContext = new MethodBasedEvaluationContext(root, targetMethod, args, this.paramNameDiscoverer);
    // 添加变量引用
    Environment env = ApplicationContextHolder.getEnvironment();
    if (env != null) {
        evaluationContext.setVariable("env", env.getProperties());
    }
    evaluationContext.setVariable("target", object);
    ServletRequestAttributes requestAttributes = WebContext.getRequestAttributes();
    if (requestAttributes != null) {
        evaluationContext.setVariable("request", requestAttributes.getRequest());
        evaluationContext.setVariable("reqParams", requestAttributes.getRequest().getParameterMap());
    }
    return evaluationContext;
}
 
Example 7
Source Project: phone   Source File: AopUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 通过spring spel解析参数获取redis缓存key
 * 
 * @param keys
 *            缓存keys
 * @param paramNames
 *            参数名
 * @param args
 *            参数列表
 * @return
 */
public static String parseKeyByParam(String keys, String[] paramNames, Object[] args) {
	if (StringUtils.isBlank(keys)) {
		return "";
	}
	ExpressionParser parser = getParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	// 把方法参数放入SPEL上下文中
	for (int i = 0; i < paramNames.length; i++) {
		context.setVariable(paramNames[i], args[i]);
	}
	// 获取参数key
	StringBuffer sb = new StringBuffer();
	// for (int i = 0; i < keys.length; i++) {
	sb.append(parser.parseExpression(keys).getValue(context, String.class));
	// }
	return sb.toString();
}
 
Example 8
Source Project: spring-analysis-note   Source File: EvaluationTests.java    License: MIT License 6 votes vote down vote up
/**
 * Verifies behavior requested in SPR-9621.
 */
@Test
public void customMethodFilter() {
	StandardEvaluationContext context = new StandardEvaluationContext();

	// Register a custom MethodResolver...
	List<MethodResolver> customResolvers = new ArrayList<>();
	customResolvers.add(new CustomMethodResolver());
	context.setMethodResolvers(customResolvers);

	// or simply...
	// context.setMethodResolvers(new ArrayList<MethodResolver>());

	// Register a custom MethodFilter...
	MethodFilter filter = new CustomMethodFilter();
	try {
		context.registerMethodFilter(String.class, filter);
		fail("should have failed");
	}
	catch (IllegalStateException ise) {
		assertEquals(
				"Method filter cannot be set as the reflective method resolver is not in use",
				ise.getMessage());
	}
}
 
Example 9
Source Project: spring-analysis-note   Source File: EvaluationTests.java    License: MIT License 6 votes vote down vote up
@Test
public void incdecTogether() {
	Spr9751 helper = new Spr9751();
	StandardEvaluationContext ctx = new StandardEvaluationContext(helper);
	ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
	Expression e;

	// index1 is 2 at the start - the 'intArray[#root.index1++]' should not be evaluated twice!
	// intArray[2] is 3
	e = parser.parseExpression("intArray[#root.index1++]++");
	e.getValue(ctx, Integer.class);
	assertEquals(3, helper.index1);
	assertEquals(4, helper.intArray[2]);

	// index1 is 3 intArray[3] is 4
	e =  parser.parseExpression("intArray[#root.index1++]--");
	assertEquals(4, e.getValue(ctx, Integer.class).intValue());
	assertEquals(4, helper.index1);
	assertEquals(3, helper.intArray[3]);

	// index1 is 4, intArray[3] is 3
	e =  parser.parseExpression("intArray[--#root.index1]++");
	assertEquals(3, e.getValue(ctx, Integer.class).intValue());
	assertEquals(3, helper.index1);
	assertEquals(4, helper.intArray[3]);
}
 
Example 10
@Test
public void testGetValue() throws Exception {
	LiteralExpression lEx = new LiteralExpression("somevalue");
	checkString("somevalue", lEx.getValue());
	checkString("somevalue", lEx.getValue(String.class));
	EvaluationContext ctx = new StandardEvaluationContext();
	checkString("somevalue", lEx.getValue(ctx));
	checkString("somevalue", lEx.getValue(ctx, String.class));
	checkString("somevalue", lEx.getValue(new Rooty()));
	checkString("somevalue", lEx.getValue(new Rooty(), String.class));
	checkString("somevalue", lEx.getValue(ctx, new Rooty()));
	checkString("somevalue", lEx.getValue(ctx, new Rooty(),String.class));
	assertEquals("somevalue", lEx.getExpressionString());
	assertFalse(lEx.isWritable(new StandardEvaluationContext()));
	assertFalse(lEx.isWritable(new Rooty()));
	assertFalse(lEx.isWritable(new StandardEvaluationContext(), new Rooty()));
}
 
Example 11
Source Project: java-technology-stack   Source File: SpelReproTests.java    License: MIT License 6 votes vote down vote up
/**
 * Test the ability to subclass the ReflectiveMethodResolver and change how it
 * determines the set of methods for a type.
 */
@Test
public void customStaticFunctions_SPR9038() {
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	List<MethodResolver> methodResolvers = new ArrayList<>();
	methodResolvers.add(new ReflectiveMethodResolver() {
		@Override
		protected Method[] getMethods(Class<?> type) {
			try {
				return new Method[] {Integer.class.getDeclaredMethod("parseInt", String.class, Integer.TYPE)};
			}
			catch (NoSuchMethodException ex) {
				return new Method[0];
			}
		}
	});

	context.setMethodResolvers(methodResolvers);
	Expression expression = parser.parseExpression("parseInt('-FF', 16)");

	Integer result = expression.getValue(context, "", Integer.class);
	assertEquals(-255, result.intValue());
}
 
Example 12
@Test
public void testAddingConstructorResolvers() {
	StandardEvaluationContext ctx = new StandardEvaluationContext();

	// reflective constructor accessor is the only one by default
	List<ConstructorResolver> constructorResolvers = ctx.getConstructorResolvers();
	assertEquals(1, constructorResolvers.size());

	ConstructorResolver dummy = new DummyConstructorResolver();
	ctx.addConstructorResolver(dummy);
	assertEquals(2, ctx.getConstructorResolvers().size());

	List<ConstructorResolver> copy = new ArrayList<ConstructorResolver>();
	copy.addAll(ctx.getConstructorResolvers());
	assertTrue(ctx.removeConstructorResolver(dummy));
	assertFalse(ctx.removeConstructorResolver(dummy));
	assertEquals(1, ctx.getConstructorResolvers().size());

	ctx.setConstructorResolvers(copy);
	assertEquals(2, ctx.getConstructorResolvers().size());
}
 
Example 13
Source Project: java-technology-stack   Source File: EvaluationTests.java    License: MIT License 6 votes vote down vote up
/**
 * Verifies behavior requested in SPR-9621.
 */
@Test
public void customMethodFilter() {
	StandardEvaluationContext context = new StandardEvaluationContext();

	// Register a custom MethodResolver...
	List<MethodResolver> customResolvers = new ArrayList<>();
	customResolvers.add(new CustomMethodResolver());
	context.setMethodResolvers(customResolvers);

	// or simply...
	// context.setMethodResolvers(new ArrayList<MethodResolver>());

	// Register a custom MethodFilter...
	MethodFilter filter = new CustomMethodFilter();
	try {
		context.registerMethodFilter(String.class, filter);
		fail("should have failed");
	}
	catch (IllegalStateException ise) {
		assertEquals(
				"Method filter cannot be set as the reflective method resolver is not in use",
				ise.getMessage());
	}
}
 
Example 14
Source Project: spring-analysis-note   Source File: SpelReproTests.java    License: MIT License 6 votes vote down vote up
@Test
public void mapOfMap_SPR7244() {
	Map<String, Object> map = new LinkedHashMap<>();
	map.put("uri", "http:");
	Map<String, String> nameMap = new LinkedHashMap<>();
	nameMap.put("givenName", "Arthur");
	map.put("value", nameMap);

	StandardEvaluationContext context = new StandardEvaluationContext(map);
	ExpressionParser parser = new SpelExpressionParser();
	String el1 = "#root['value'].get('givenName')";
	Expression exp = parser.parseExpression(el1);
	Object evaluated = exp.getValue(context);
	assertEquals("Arthur", evaluated);

	String el2 = "#root['value']['givenName']";
	exp = parser.parseExpression(el2);
	evaluated = exp.getValue(context);
	assertEquals("Arthur", evaluated);
}
 
Example 15
/**
 * 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 | ParseException ex) {
		ex.printStackTrace();
		fail("Unexpected Exception: " + ex.getMessage());
	}
}
 
Example 16
@Test
public void testCallingIllegalFunctions() throws Exception {
	SpelExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext ctx = new StandardEvaluationContext();
	ctx.setVariable("notStatic", this.getClass().getMethod("nonStatic"));
	try {
		@SuppressWarnings("unused")
		Object v = parser.parseRaw("#notStatic()").getValue(ctx);
		fail("Should have failed with exception - cannot call non static method that way");
	} catch (SpelEvaluationException se) {
		if (se.getMessageCode() != SpelMessage.FUNCTION_MUST_BE_STATIC) {
			se.printStackTrace();
			fail("Should have failed a message about the function needing to be static, not: "
					+ se.getMessageCode());
		}
	}
}
 
Example 17
Source Project: Moss   Source File: TelegramNotifier.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
protected String getText(InstanceEvent event, Instance instance) {
    Map<String, Object> root = new HashMap<>();
    root.put("event", event);
    root.put("instance", instance);
    root.put("lastStatus", getLastStatus(event.getInstance()));
    StandardEvaluationContext context = new StandardEvaluationContext(root);
    context.addPropertyAccessor(new MapAccessor());
    return message.getValue(context, String.class);
}
 
Example 18
Source Project: java-technology-stack   Source File: SpelReproTests.java    License: MIT License 5 votes vote down vote up
@Test
public void SPR10091_primitiveTestValue() {
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new BooleanHolder());
	Object value = parser.parseExpression("primitiveProperty").getValue(evaluationContext);
	assertNotNull(value);
}
 
Example 19
Source Project: java-technology-stack   Source File: EvaluationTests.java    License: MIT License 5 votes vote down vote up
@Test
public void operatorVariants() {
	SpelExpression e = (SpelExpression)parser.parseExpression("#a < #b");
	EvaluationContext ctx = new StandardEvaluationContext();
	ctx.setVariable("a", (short) 3);
	ctx.setVariable("b", (short) 6);
	assertTrue(e.getValue(ctx, Boolean.class));
	ctx.setVariable("b", (byte) 6);
	assertTrue(e.getValue(ctx, Boolean.class));
	ctx.setVariable("a", (byte) 9);
	ctx.setVariable("b", (byte) 6);
	assertFalse(e.getValue(ctx, Boolean.class));
	ctx.setVariable("a", 10L);
	ctx.setVariable("b", (short) 30);
	assertTrue(e.getValue(ctx, Boolean.class));
	ctx.setVariable("a", (byte) 3);
	ctx.setVariable("b", (short) 30);
	assertTrue(e.getValue(ctx, Boolean.class));
	ctx.setVariable("a", (byte) 3);
	ctx.setVariable("b", 30L);
	assertTrue(e.getValue(ctx, Boolean.class));
	ctx.setVariable("a", (byte) 3);
	ctx.setVariable("b", 30f);
	assertTrue(e.getValue(ctx, Boolean.class));
	ctx.setVariable("a", new BigInteger("10"));
	ctx.setVariable("b", new BigInteger("20"));
	assertTrue(e.getValue(ctx, Boolean.class));
}
 
Example 20
Source Project: spring-analysis-note   Source File: SpelReproTests.java    License: MIT License 5 votes vote down vote up
@Test
public void SPR9486_addFloatWithDouble() {
	Number expectedNumber = 10.21f + 10.2;
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	Expression expression = parser.parseExpression("10.21f + 10.2");
	Number result = expression.getValue(context, null, Number.class);
	assertEquals(expectedNumber, result);
}
 
Example 21
Source Project: lams   Source File: SpelExpression.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the default evaluation context that will be used if none is supplied on an evaluation call.
 * @return the default evaluation context
 */
public EvaluationContext getEvaluationContext() {
	if (this.evaluationContext == null) {
		this.evaluationContext = new StandardEvaluationContext();
	}
	return this.evaluationContext;
}
 
Example 22
Source Project: spring-analysis-note   Source File: PropertyAccessTests.java    License: MIT License 5 votes vote down vote up
@Test
// Adding a new property accessor just for a particular type
public void testAddingSpecificPropertyAccessor() {
	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(7, (int) i);

	// 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(99, (int) i);

	// Cannot set it to a string value
	try {
		expr.setValue(ctx, "not allowed");
		fail("Should not have been allowed");
	}
	catch (EvaluationException ex) {
		// 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 23
Source Project: spring4-understanding   Source File: SpelReproTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void SPR9486_floatEqFloatUnaryMinus() {
	Boolean expectedResult = -10.21f == -10.2f;
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	Expression expression = parser.parseExpression("-10.21f == -10.2f");
	Boolean result = expression.getValue(context, null, Boolean.class);
	assertEquals(expectedResult, result);
}
 
Example 24
Source Project: spring-analysis-note   Source File: SpelReproTests.java    License: MIT License 5 votes vote down vote up
@Test
public void SPR10091_primitiveTestValueType() {
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new BooleanHolder());
	Class<?> valueType = parser.parseExpression("primitiveProperty").getValueType(evaluationContext);
	assertNotNull(valueType);
}
 
Example 25
Source Project: spring-analysis-note   Source File: SpelReproTests.java    License: MIT License 5 votes vote down vote up
@Test
public void SPR9486_floatEqDoubleUnaryMinus() {
	Boolean expectedResult = -10.21f == -10.2;
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	Expression expression = parser.parseExpression("-10.21f == -10.2");
	Boolean result = expression.getValue(context, null, Boolean.class);
	assertEquals(expectedResult, result);
}
 
Example 26
Source Project: the-app   Source File: NavigationProviderImpl.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isVisible(String visible) {
    if (StringUtils.isNotEmpty(visible)) {
        ExpressionParser parser = new SpelExpressionParser();
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setBeanResolver(new ApplicationContextBeanResolver());
        return parser.parseExpression(visible).getValue(context, Boolean.class);
    }
    return true;
}
 
Example 27
Source Project: mcspring-boot   Source File: SecurityAspect.java    License: MIT License 5 votes vote down vote up
@Order(0)
@Around("within(@(@dev.alangomes.springspigot.security.Authorize *) *) " +
        "|| execution(@(@dev.alangomes.springspigot.security.Authorize *) * *(..)) " +
        "|| @within(dev.alangomes.springspigot.security.Authorize)" +
        "|| execution(@dev.alangomes.springspigot.security.Authorize * *(..))")
public Object checkPermission(ProceedingJoinPoint joinPoint) throws Throwable {
    val sender = context.getSender();
    if (sender == null) {
        throw new PlayerNotFoundException();
    }
    val method = ((MethodSignature) joinPoint.getSignature()).getMethod();
    val senderContext = new StandardEvaluationContext(sender);
    val parameters = method.getParameters();
    IntStream.range(0, parameters.length)
            .forEach(i -> senderContext.setVariable(parameters[i].getName(), joinPoint.getArgs()[i]));
    senderContext.setVariable("session", sessionService.current());
    senderContext.setVariable("guard", guardService);

    AopAnnotationUtils.getAppliableAnnotations(method, Authorize.class).forEach(authorize -> {
        val expressionSource = authorize.value();
        val expression = expressionCache.computeIfAbsent(expressionSource, parser::parseExpression);
        senderContext.setVariable("params", authorize.params());
        if (!toBoolean(expression.getValue(senderContext, Boolean.class))) {
            val message = StringUtils.trimToNull(ChatColor.translateAlternateColorCodes('&', authorize.message()));
            throw new PermissionDeniedException(expressionSource, message);
        }
    });
    return joinPoint.proceed();
}
 
Example 28
Source Project: spring-analysis-note   Source File: ScenariosForSpringSecurity.java    License: MIT License 5 votes vote down vote up
@Test
public void testScenario02_ComparingNames() throws Exception {
	SpelExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext ctx = new StandardEvaluationContext();

	ctx.addPropertyAccessor(new SecurityPrincipalAccessor());

	// Multiple options for supporting this expression: "p.name == principal.name"
	// (1) If the right person is the root context object then "name==principal.name" is good enough
	Expression expr = parser.parseRaw("name == principal.name");

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

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

	// (2) Or register an accessor that can understand 'p' and return the right person
	expr = parser.parseRaw("p.name == principal.name");

	PersonAccessor pAccessor = new PersonAccessor();
	ctx.addPropertyAccessor(pAccessor);
	ctx.setRootObject(null);

	pAccessor.setPerson(new Person("Andy"));
	value = expr.getValue(ctx,Boolean.class);
	assertTrue(value);

	pAccessor.setPerson(new Person("Christian"));
	value = expr.getValue(ctx,Boolean.class);
	assertFalse(value);
}
 
Example 29
Source Project: java-technology-stack   Source File: SpelReproTests.java    License: MIT License 5 votes vote down vote up
@Test
public void SPR11609() {
	StandardEvaluationContext sec = new StandardEvaluationContext();
	sec.addPropertyAccessor(new MapAccessor());
	Expression exp = new SpelExpressionParser().parseExpression(
			"T(org.springframework.expression.spel.SpelReproTests$MapWithConstant).X");
	assertEquals(1, exp.getValue(sec));
}
 
Example 30
@Override
public RedisCallback map(SyncData data) {
  StandardEvaluationContext context = data.getContext();
  String key = keyExpr.getValue(context, String.class);
  Object value = valueExpr.getValue(context);
  final byte[] rawKey = rawKey(key);
  final byte[] rawValue = rawValue(value);

  return connection -> {
    mapping.operationMethod(connection).apply(rawKey, rawValue);
    return null;
  };
}