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

The following are top voted examples for showing how to use org.springframework.expression.spel.support.StandardEvaluationContext. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: esup-sgc   File: SpelUserInfoService.java   View source code 7 votes vote down vote up
@Override
public Map<String, String> getUserInfos(User user, HttpServletRequest request, final Map<String, String> userInfosInComputing) {
	
	Map<String, String> userInfos = new HashMap<String, String>(); 
	for(String name: sgcParam2spelExp.keySet()) {
		String expression = sgcParam2spelExp.get(name);
		ExpressionParser parser = new SpelExpressionParser();
		Expression exp = parser.parseExpression(expression);

		EvaluationContext context = new StandardEvaluationContext();
		context.setVariable("user", user);
		context.setVariable("request", request);
		context.setVariable("userInfosInComputing", userInfosInComputing);
		context.setVariable("dateUtils", dateUtils);
		
		String value = (String) exp.getValue(context);
		userInfos.put(name, value);
	}
	return userInfos;
}
 
Example 2
Project: bucket4j-spring-boot-starter   File: Bucket4JBaseConfiguration.java   View source code 6 votes vote down vote up
/**
 * Creates the key filter lambda which is responsible to decide how the rate limit will be performed. The key
 * is the unique identifier like an IP address or a username.
 * 
 * @param url is used to generated a unique cache key
 * @param rateLimit the {@link RateLimit} configuration which holds the skip condition string
 * @param expressionParser is used to evaluate the expression if the filter key type is EXPRESSION.
 * @param beanFactory used to get full access to all java beans in the SpEl
 * @return should not been null. If no filter key type is matching a plain 1 is returned so that all requests uses the same key.
 */
public KeyFilter getKeyFilter(String url, RateLimit rateLimit, ExpressionParser expressionParser, BeanFactory beanFactory) {
	
	switch(rateLimit.getFilterKeyType()) {
	case IP:
		return (request) -> url + "-" + request.getRemoteAddr();
	case EXPRESSION:
		String expression = rateLimit.getExpression();
		if(StringUtils.isEmpty(expression)) {
			throw new MissingKeyFilterExpressionException();
		}
		StandardEvaluationContext context = new StandardEvaluationContext();
		context.setBeanResolver(new BeanFactoryResolver(beanFactory));
		return  (request) -> {
			//TODO performance problem - how can the request object reused in the expression without setting it as a rootObject
			Expression expr = expressionParser.parseExpression(rateLimit.getExpression()); 
			final String value = expr.getValue(context, request, String.class);
			return url + "-" + value;
		};
	
	}
	return (request) -> url + "-" + "1";
}
 
Example 3
Project: bucket4j-spring-boot-starter   File: Bucket4JBaseConfiguration.java   View source code 6 votes vote down vote up
/**
 * Creates the lambda for the skip condition which will be evaluated on each request
 * 
 * @param rateLimit the {@link RateLimit} configuration which holds the skip condition string
 * @param expressionParser is used to evaluate the skip expression
 * @param beanFactory used to get full access to all java beans in the SpEl
 * @return the lamdba condition which will be evaluated lazy - null if there is no condition available.
 */
public Condition skipCondition(RateLimit rateLimit, ExpressionParser expressionParser, BeanFactory beanFactory) {
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.setBeanResolver(new BeanFactoryResolver(beanFactory));
	
	if(rateLimit.getSkipCondition() != null) {
		return  (request) -> {
			Expression expr = expressionParser.parseExpression(rateLimit.getSkipCondition()); 
			Boolean value = expr.getValue(context, request, Boolean.class);
			return value;
		};
	}
	return null;
}
 
Example 4
Project: ukubuka-core   File: UkubukaExpressionEvaluatorTest.java   View source code 6 votes vote down vote up
/******************************** Test(s) ********************************/
@Test
public void test_evaluate_success() {
    Mockito.when(expressionParser.parseExpression(Mockito.anyString()))
            .thenReturn(expression);
    Mockito.when(expression
            .getValue(Mockito.any(StandardEvaluationContext.class)))
            .thenReturn(new Object());

    ukubukaExpressionEvaluator.evaluate(new FileContents(),
            new FileRecord(), "fooBar");

    Mockito.verify(expressionParser, Mockito.times(1))
            .parseExpression(Mockito.anyString());
    Mockito.verify(expression, Mockito.times(1))
            .getValue(Mockito.any(StandardEvaluationContext.class));
}
 
Example 5
Project: oneops   File: BomEnvManagerImpl.java   View source code 6 votes vote down vote up
private List<CmsCI> getEligibleOfferings(CmsRfcCI rfcCi, List<CmsCI> serviceOfferings) {
	if (serviceOfferings == null) return null;
	List<CmsCI> eligibleOfferings = new ArrayList<>();
	for (CmsCI offering : serviceOfferings) {
		CmsCIAttribute criteriaAttribute = offering.getAttribute("criteria");
		String criteria = criteriaAttribute.getDfValue();
		if (isLikelyElasticExpression(criteria)) {
			criteria = convert(criteria);
		}
		Expression expression = exprParser.parseExpression(criteria);
		StandardEvaluationContext context = new StandardEvaluationContext();

		context.setRootObject(cmsUtil.custRfcCI2RfcCISimple(rfcCi));
		boolean match = expression.getValue(context, Boolean.class);
		if (match) {
			eligibleOfferings.add(offering);
		}
	}
	return eligibleOfferings;
}
 
Example 6
Project: oneops   File: OfferingsMatcher.java   View source code 6 votes vote down vote up
List<CmsCI> getEligbleOfferings(CmsRfcCISimple cmsRfcCISimple, String offeringNS) {
    List<CmsCI> offerings = new ArrayList<>(); 
    List<CmsCI> list = cmsCmProcessor.getCiBy3(offeringNS, "cloud.Offering", null);
    for (CmsCI ci: list){
        CmsCIAttribute criteriaAttribute = ci.getAttribute("criteria");
        String criteria = criteriaAttribute.getDfValue();
        if (isLikelyElasticExpression(criteria)){
            logger.warn("cloud.Offering CI ID:"+ci.getCiId()+" likely still has elastic search criteria. Evaluation may not be successful!");
            logger.info("ES criteria:"+criteria);
            criteria = convert(criteria);
            logger.info("Converted SPEL criteria:"+criteria);
        }
        Expression expression = exprParser.parseExpression(criteria);
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setRootObject(cmsRfcCISimple);
        boolean match = (boolean) expression.getValue(context, Boolean.class);
        if (match){
            offerings.add(ci);
        }
    }
    return offerings;
}
 
Example 7
Project: martini-core   File: DefaultMixologist.java   View source code 6 votes vote down vote up
protected Collection<Martini> getMartinis(Expression expression) {
	StandardEvaluationContext context = new StandardEvaluationContext();
	List<MethodResolver> methodResolvers = context.getMethodResolvers();
	ArrayList<MethodResolver> modifiedList = Lists.newArrayList(methodResolvers);
	modifiedList.add(new TagResolver(categories));
	context.setMethodResolvers(modifiedList);

	ImmutableList<Martini> martinis = getMartinis();
	List<Martini> matches = Lists.newArrayListWithCapacity(martinis.size());
	for (Martini martini : martinis) {
		Boolean match = expression.getValue(context, martini, Boolean.class);
		if (match) {
			matches.add(martini);
		}
	}
	return matches;
}
 
Example 8
Project: spring-seed   File: ExpirableCacheAspect.java   View source code 6 votes vote down vote up
/**
 * generate the key based on SPel expression.
 */
protected Object generateKey(String key, ProceedingJoinPoint pjp) throws ExpirableCacheException {
	try {
		Object target = pjp.getTarget();
		Method method = ((MethodSignature) pjp.getSignature()).getMethod();
		Object[] allArgs = pjp.getArgs();
		if (StringUtils.hasText(key)) {
			CacheExpressionDataObject cacheExpressionDataObject = new CacheExpressionDataObject(method, allArgs, target, target.getClass());
			EvaluationContext evaluationContext = new StandardEvaluationContext(cacheExpressionDataObject);
			SpelExpression spelExpression = getExpression(key, method);
			spelExpression.setEvaluationContext(evaluationContext);
			return spelExpression.getValue();
		}
		return keyGenerator.generate(target, method, allArgs);
	} catch (Throwable t) {
		throw new ExpirableCacheException("### generate key failed");
	}
}
 
Example 9
Project: lodsve-framework   File: SpELScriptEngine.java   View source code 6 votes vote down vote up
@Override
public ScriptResult execute(String id, Map<String, Object> args) {
    long startTime = System.currentTimeMillis();
    ScriptContext scriptContext = SCRIPT_CONTENT_CACHE.get(id);
    if (scriptContext == null || scriptContext.getExpression() == null) {
        return ScriptResult.failure(String.format("script(spel): %s not found!", id), null, System.currentTimeMillis() - startTime);
    }

    EvaluationContext context = new StandardEvaluationContext(args);
    for (Map.Entry<String, Object> entry : args.entrySet()) {
        context.setVariable(entry.getKey(), entry.getValue());
    }
    Object obj = scriptContext.getExpression().getValue(context);

    return ScriptResult.success(obj, System.currentTimeMillis() - startTime);
}
 
Example 10
Project: spring-graphql-common   File: GraphQLAbstractRxExecutionStrategy.java   View source code 6 votes vote down vote up
protected Observable<Double> calculateFieldComplexity(ExecutionContext executionContext, GraphQLObjectType parentType, List<Field> fields, Observable<Double> childScore) {
    return childScore.flatMap(aDouble -> {
        Observable<Double> result = Observable.just(aDouble + NODE_SCORE);
        GraphQLFieldDefinition fieldDef = getFieldDef(executionContext.getGraphQLSchema(), parentType, fields.get(0));
        if (fieldDef != null) {
            GraphQLFieldDefinitionWrapper graphQLFieldDefinitionWrapper = getGraphQLFieldDefinitionWrapper(fieldDef);
            if (graphQLFieldDefinitionWrapper != null) {
                Expression expression = graphQLFieldDefinitionWrapper.getComplexitySpelExpression();
                if (expression != null) {
                    Map<String, Object> argumentValues = valuesResolver.getArgumentValues(fieldDef.getArguments(), fields.get(0).getArguments(), executionContext.getVariables());
                    StandardEvaluationContext context = new StandardEvaluationContext();
                    context.setVariable(GraphQLConstants.EXECUTION_COMPLEXITY_CHILD_SCORE, aDouble);
                    if (argumentValues != null)
                        context.setVariables(argumentValues);
                    result = Observable.just(expression.getValue(context, Double.class));
                }
            }
        }
        return addComplexityCheckObservable(executionContext, result);
    });
}
 
Example 11
Project: spring4-understanding   File: SpelReproTests.java   View source code 6 votes vote down vote up
@Test
public void mapOfMap_SPR7244() throws Exception {
	Map<String, Object> map = new LinkedHashMap<String, Object>();
	map.put("uri", "http:");
	Map<String, String> nameMap = new LinkedHashMap<String, String>();
	nameMap.put("givenName", "Arthur");
	map.put("value", nameMap);

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

	String el2 = "#root['value']['givenName']";
	exp = parser.parseExpression(el2);
	evaluated = exp.getValue(ctx);
	assertEquals("Arthur", evaluated);
}
 
Example 12
Project: piper   File: SpelTaskEvaluator.java   View source code 6 votes vote down vote up
private Object evaluate (Object aValue, Context aContext) {
  StandardEvaluationContext context = createEvaluationContext(aContext);
  if(aValue instanceof String) {
    Expression expression = parser.parseExpression((String)aValue,new TemplateParserContext(PREFIX,SUFFIX));
    try {
      return(expression.getValue(context));
    }
    catch (SpelEvaluationException e) {
      logger.debug(e.getMessage());
      return aValue;
    }
  }
  else if (aValue instanceof List) {
    List<Object> evaluatedlist = new ArrayList<>();
    List<Object> list = (List<Object>) aValue;
    for(Object item : list) {
      evaluatedlist.add(evaluate(item, aContext));
    }
    return evaluatedlist;
  }
  else if (aValue instanceof Map) {
    return evaluateInternal((Map<String, Object>) aValue, aContext);
  }
  return aValue;
}
 
Example 13
Project: spring4-understanding   File: SetValueTests.java   View source code 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 ee) {
		ee.printStackTrace();
		fail("Unexpected Exception: " + ee.getMessage());
	} catch (ParseException pe) {
		pe.printStackTrace();
		fail("Unexpected Exception: " + pe.getMessage());
	}
}
 
Example 14
Project: spring4-understanding   File: SpelReproTests.java   View source code 6 votes vote down vote up
@Test
public void SPR10452() throws Exception {
	SpelParserConfiguration configuration = new SpelParserConfiguration(false, false);
	ExpressionParser parser = new SpelExpressionParser(configuration);

	StandardEvaluationContext context = new StandardEvaluationContext();
	Expression spel = parser.parseExpression("#enumType.values()");

	context.setVariable("enumType", ABC.class);
	Object result = spel.getValue(context);
	assertNotNull(result);
	assertTrue(result.getClass().isArray());
	assertEquals(ABC.A, Array.get(result, 0));
	assertEquals(ABC.B, Array.get(result, 1));
	assertEquals(ABC.C, Array.get(result, 2));

	context.setVariable("enumType", XYZ.class);
	result = spel.getValue(context);
	assertNotNull(result);
	assertTrue(result.getClass().isArray());
	assertEquals(XYZ.X, Array.get(result, 0));
	assertEquals(XYZ.Y, Array.get(result, 1));
	assertEquals(XYZ.Z, Array.get(result, 2));
}
 
Example 15
Project: spring4-understanding   File: SpelDocumentationTests.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testSpecialVariables() throws Exception {
	// create an array of integers
	List<Integer> primes = new ArrayList<Integer>();
	primes.addAll(Arrays.asList(2,3,5,7,11,13,17));

	// create parser and set variable 'primes' as the array of integers
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.setVariable("primes",primes);

	// all prime numbers > 10 from the list (using selection ?{...})
	List<Integer> primesGreaterThanTen = (List<Integer>) parser.parseExpression("#primes.?[#this>10]").getValue(context);
	assertEquals("[11, 13, 17]",primesGreaterThanTen.toString());
}
 
Example 16
Project: spring4-understanding   File: EvaluationTests.java   View source code 6 votes vote down vote up
@Test
public void testCreateListsOnAttemptToIndexNull01() throws EvaluationException, ParseException {
	ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
	Expression expression = parser.parseExpression("list[0]");
	TestClass testClass = new TestClass();
	Object o = null;
	o = expression.getValue(new StandardEvaluationContext(testClass));
	assertEquals("", o);
	o = parser.parseExpression("list[3]").getValue(new StandardEvaluationContext(testClass));
	assertEquals("", o);
	assertEquals(4, testClass.list.size());
	try {
		o = parser.parseExpression("list2[3]").getValue(new StandardEvaluationContext(testClass));
		fail();
	} catch (EvaluationException ee) {
		ee.printStackTrace();
		// success!
	}
	o = parser.parseExpression("foo[3]").getValue(new StandardEvaluationContext(testClass));
	assertEquals("", o);
	assertEquals(4, testClass.getFoo().size());
}
 
Example 17
Project: phone   File: AopUtil.java   View source code 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 18
Project: spring4-understanding   File: ExpressionLanguageScenarioTests.java   View source code 6 votes vote down vote up
@Test
public void testScenario_AddingYourOwnPropertyResolvers_2() throws Exception {
	// Create a parser
	SpelExpressionParser parser = new SpelExpressionParser();
	// Use the standard evaluation context
	StandardEvaluationContext ctx = new StandardEvaluationContext();

	ctx.addPropertyAccessor(new VegetableColourAccessor());
	Expression expr = parser.parseRaw("pea");
	Object value = expr.getValue(ctx);
	assertEquals(Color.green, value);

	try {
		expr.setValue(ctx, Color.blue);
		fail("Should not be allowed to set peas to be blue !");
	}
	catch (SpelEvaluationException ee) {
		assertEquals(ee.getMessageCode(), SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL);
	}
}
 
Example 19
Project: spring4-understanding   File: SpelReproTests.java   View source code 6 votes vote down vote up
/**
 * We add property accessors in the order:
 * First, Second, Third, Fourth.
 * They are not utilized in this order; preventing a priority or order of operations
 * in evaluation of SPEL expressions for a given context.
 */
@Test
public void propertyAccessorOrder_8211() {
	ExpressionParser expressionParser = new SpelExpressionParser();
	StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new ContextObject());

	evaluationContext.addPropertyAccessor(new TestPropertyAccessor("firstContext"));
	evaluationContext.addPropertyAccessor(new TestPropertyAccessor("secondContext"));
	evaluationContext.addPropertyAccessor(new TestPropertyAccessor("thirdContext"));
	evaluationContext.addPropertyAccessor(new TestPropertyAccessor("fourthContext"));

	assertEquals("first", expressionParser.parseExpression("shouldBeFirst").getValue(evaluationContext));
	assertEquals("second", expressionParser.parseExpression("shouldBeSecond").getValue(evaluationContext));
	assertEquals("third", expressionParser.parseExpression("shouldBeThird").getValue(evaluationContext));
	assertEquals("fourth", expressionParser.parseExpression("shouldBeFourth").getValue(evaluationContext));
}
 
Example 20
Project: spring4-understanding   File: EvaluationTests.java   View source code 6 votes vote down vote up
/**
 * Verifies behavior requested in SPR-9621.
 */
@Test
public void customMethodFilter() throws Exception {
	StandardEvaluationContext context = new StandardEvaluationContext();

	// Register a custom MethodResolver...
	List<MethodResolver> customResolvers = new ArrayList<MethodResolver>();
	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 21
Project: spring4-understanding   File: EvaluationTests.java   View source code 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 = null;

	// 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 22
Project: coordinated-entry   File: SectionScoreServiceImpl.java   View source code 6 votes vote down vote up
public int calculateQuestionScore(QuestionEntity questionEntity,ResponseEntity responseEntity)  {
	int score=0;
	boolean result;
	EvaluationContext context = new StandardEvaluationContext(responseEntity);
	ExpressionParser parser = new SpelExpressionParser();
	if(questionEntity.getCorrectValueForAssessment()!=null) {
		try{
		Expression expression = parser.parseExpression(questionEntity.getCorrectValueForAssessment());
		 result =  expression.getValue(context,boolean.class);
		if(result) {
				score = questionEntity.getQuestionWeight();
		}
		}catch (Exception e) {
		}
	}

	return score;		
}
 
Example 23
Project: spring4-understanding   File: MethodInvocationTests.java   View source code 6 votes vote down vote up
@Test
public void testAddingMethodResolvers() {
	StandardEvaluationContext ctx = new StandardEvaluationContext();

	// reflective method accessor is the only one by default
	List<MethodResolver> methodResolvers = ctx.getMethodResolvers();
	assertEquals(1, methodResolvers.size());

	MethodResolver dummy = new DummyMethodResolver();
	ctx.addMethodResolver(dummy);
	assertEquals(2, ctx.getMethodResolvers().size());

	List<MethodResolver> copy = new ArrayList<MethodResolver>();
	copy.addAll(ctx.getMethodResolvers());
	assertTrue(ctx.removeMethodResolver(dummy));
	assertFalse(ctx.removeMethodResolver(dummy));
	assertEquals(1, ctx.getMethodResolvers().size());

	ctx.setMethodResolvers(copy);
	assertEquals(2, ctx.getMethodResolvers().size());
}
 
Example 24
Project: FoDBugTrackerUtility   File: SpringExpressionUtil.java   View source code 6 votes vote down vote up
/**
 * Automatically load all PropertyAccessor implementations
 * (annotated with {@link Component}) from 
 * com.fortify.util.spring.propertyaccessor (sub-)packages. 
 * @return
 */
private static final List<PropertyAccessor> getPropertyAccessors() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext("com.fortify.util.spring.propertyaccessor");
	try {
		// Initialize list with discovered PropertyAccessors
		List<PropertyAccessor> result = new ArrayList<PropertyAccessor>(ctx.getBeansOfType(PropertyAccessor.class).values());
		// Add the standard PropertyAccessors
		result.addAll(new StandardEvaluationContext().getPropertyAccessors());
		
		// Order the accessors
		result.sort(new OrderComparator());
		
		LOG.info("[Process] Loaded PropertyAccessors: "+result);
		return result;
	} finally {
		ctx.close();
	}
}
 
Example 25
Project: spring4-understanding   File: MapAccessTests.java   View source code 6 votes vote down vote up
@Test
public void testGetValuePerformance() throws Exception {
	Assume.group(TestGroup.PERFORMANCE);
	Map<String, String> map = new HashMap<String, String>();
	map.put("key", "value");
	EvaluationContext context = new StandardEvaluationContext(map);

	ExpressionParser spelExpressionParser = new SpelExpressionParser();
	Expression expr = spelExpressionParser.parseExpression("#root['key']");

	StopWatch s = new StopWatch();
	s.start();
	for (int i = 0; i < 10000; i++) {
		expr.getValue(context);
	}
	s.stop();
	assertThat(s.getTotalTimeMillis(), lessThan(200L));
}
 
Example 26
Project: spring4-understanding   File: ExpressionLanguageScenarioTests.java   View source code 6 votes vote down vote up
/**
 * Scenario: using the standard context but adding your own variables
 */
@Test
public void testScenario_DefiningVariablesThatWillBeAccessibleInExpressions() throws Exception {
	// Create a parser
	SpelExpressionParser parser = new SpelExpressionParser();
	// Use the standard evaluation context
	StandardEvaluationContext ctx = new StandardEvaluationContext();
	ctx.setVariable("favouriteColour","blue");
	List<Integer> primes = new ArrayList<Integer>();
	primes.addAll(Arrays.asList(2,3,5,7,11,13,17));
	ctx.setVariable("primes",primes);

	Expression expr = parser.parseRaw("#favouriteColour");
	Object value = expr.getValue(ctx);
	assertEquals("blue", value);

	expr = parser.parseRaw("#primes.get(1)");
	value = expr.getValue(ctx);
	assertEquals(3, value);

	// all prime numbers > 10 from the list (using selection ?{...})
	expr = parser.parseRaw("#primes.?[#this>10]");
	value = expr.getValue(ctx);
	assertEquals("[11, 13, 17]", value.toString());
}
 
Example 27
Project: coordinated-entry   File: SectionScoreServiceImplV3.java   View source code 6 votes vote down vote up
public int calculateQuestionScore(QuestionEntity questionEntity,ResponseEntity responseEntity)  {
	int score=0;
	boolean result;
	EvaluationContext context = new StandardEvaluationContext(responseEntity);
	ExpressionParser parser = new SpelExpressionParser();
	if(questionEntity.getCorrectValueForAssessment()!=null) {
		try{
		Expression expression = parser.parseExpression(questionEntity.getCorrectValueForAssessment());
		 result =  expression.getValue(context,boolean.class);
		if(result) {
				score = questionEntity.getQuestionWeight();
		}
		}catch (Exception e) {
		}
	}

	return score;		
}
 
Example 28
Project: spring4-understanding   File: VariableAndFunctionTests.java   View source code 6 votes vote down vote up
@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 29
Project: spring4-understanding   File: ScenariosForSpringSecurity.java   View source code 6 votes vote down vote up
@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;

	ctx.setVariable("a",1.0d); // referenced as #a in the expression
	ctx.setRootObject(new Supervisor("Ben")); // so non-qualified references 'hasRole()' 'hasIpAddress()' are invoked against it
	value = expr.getValue(ctx,Boolean.class);
	assertTrue(value);

	ctx.setRootObject(new Manager("Luke"));
	ctx.setVariable("a",1.043d);
	value = expr.getValue(ctx,Boolean.class);
	assertFalse(value);
}
 
Example 30
Project: spring4-understanding   File: ScenariosForSpringSecurity.java   View source code 6 votes vote down vote up
@Test
	public void testScenario04_ControllingWhichMethodsRun() throws Exception {
		SpelExpressionParser parser = new SpelExpressionParser();
		StandardEvaluationContext ctx = new StandardEvaluationContext();

		ctx.setRootObject(new Supervisor("Ben")); // so non-qualified references 'hasRole()' 'hasIpAddress()' are invoked against it);

		ctx.addMethodResolver(new MyMethodResolver()); // NEEDS TO OVERRIDE THE REFLECTION ONE - SHOW REORDERING MECHANISM
		// 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;

		ctx.setVariable("a",1.0d); // referenced as #a in the expression
		value = expr.getValue(ctx,Boolean.class);
		assertTrue(value);

//			ctx.setRootObject(new Manager("Luke"));
//			ctx.setVariable("a",1.043d);
//			value = (Boolean)expr.getValue(ctx,Boolean.class);
//			assertFalse(value);
	}
 
Example 31
Project: quickmon   File: SpelAssertion.java   View source code 5 votes vote down vote up
public EvaluationContext create(Object target) {
    StandardEvaluationContext ctx = new StandardEvaluationContext(target);

    stream(SpelExtensions.class.getMethods())
            .filter(method -> method.getModifiers() == 9)
            .forEach(method -> {
                ctx.registerFunction(method.getName(), method);
            });

    return ctx;

}
 
Example 32
Project: xm-commons   File: PermissionCheckService.java   View source code 5 votes vote down vote up
private static boolean isConditionValid(Expression expression, StandardEvaluationContext context) {
    boolean result;
    if (expression == null || StringUtils.isEmpty(expression.getExpressionString())) {
        result = true;
    } else {
        try {
            result = expression.getValue(context, Boolean.class);
        } catch (Exception e) {
            result = false;
            log.error("Exception while getting value ", e);
        }
    }
    return result;
}
 
Example 33
Project: csap-core   File: Boot_Container_Test.java   View source code 5 votes vote down vote up
@Ignore
@Test
public void validate_spring_expression ()
		throws Exception {

	// String url = "http://csaptools.yourcompany.com/admin/api/clusters";
	String url = "http://testhost.yourcompany.com:8011/CsAgent/api/collection/application/CsAgent_8011/30/10";
	ObjectNode restResponse = analyticsTemplate.getForObject( url, ObjectNode.class );

	logger.info( "Url: {} response: {}", url, jacksonMapper.writerWithDefaultPrettyPrinter()
		.writeValueAsString( restResponse ) );

	ArrayList<Integer> publishvals = jacksonMapper.readValue(
		restResponse.at( "/data/publishEvents" )
			.traverse(),
		new TypeReference<ArrayList<Integer>>() {
		} );

	int total = publishvals.stream().mapToInt( Integer::intValue ).sum();

	logger.info( "Total: {} publishvals: {}", total, publishvals );

	EvaluationContext context = new StandardEvaluationContext();
	context.setVariable( "total", total );

	ExpressionParser parser = new SpelExpressionParser();
	Expression exp = parser.parseExpression( "#total.toString()" );
	logger.info( "SPEL evalutation: {}", (String) exp.getValue( context ) );

	exp = parser.parseExpression( "#total > 99" );
	logger.info( "#total > 99 SPEL evalutation: {}", (Boolean) exp.getValue( context ) );

	exp = parser.parseExpression( "#total > 3" );
	logger.info( "#total > 3 SPEL evalutation: {}", (Boolean) exp.getValue( context ) );

}
 
Example 34
Project: bucket4j-spring-boot-starter   File: Bucket4JBaseConfiguration.java   View source code 5 votes vote down vote up
/**
 * Creates the lambda for the execute condition which will be evaluated on each request.
 * 
 * @param rateLimit the {@link RateLimit} configuration which holds the execute condition string
 * @param expressionParser is used to evaluate the execution expression
 * @param beanFactory used to get full access to all java beans in the SpEl
 * @return the lamdba condition which will be evaluated lazy - null if there is no condition available.
 */
public Condition executeCondition(RateLimit rateLimit, ExpressionParser expressionParser, BeanFactory beanFactory) {
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.setBeanResolver(new BeanFactoryResolver(beanFactory));
	
	if(rateLimit.getExecuteCondition() != null) {
		return (request) -> {
			Expression expr = expressionParser.parseExpression(rateLimit.getExecuteCondition()); 
			Boolean value = expr.getValue(context, request, Boolean.class);
			return value;
		};
	}
	return null;
}
 
Example 35
Project: ukubuka-core   File: UkubukaExpressionEvaluator.java   View source code 5 votes vote down vote up
/**
 * Evaluate
 * 
 * @return Evaluated Expression
 */
public Object evaluate(final FileContents fileContents,
        final FileRecord fileRecord, final String expression) {
    /* Create Context */
    StandardEvaluationContext standardEvaluationContext = new StandardEvaluationContext(
            fileRecord);
    standardEvaluationContext.setVariable("aggregations",
            fileContents.getAggregations());

    /* Evaluate Expressions */
    LOGGER.info("Evaluating Expression: {}", expression);
    return expressionParser.parseExpression(expression)
            .getValue(standardEvaluationContext);
}
 
Example 36
Project: ukubuka-core   File: UkubukaExpressionEvaluatorTest.java   View source code 5 votes vote down vote up
@Test(expected = EvaluationException.class)
public void test_evaluate_evaluation_exception() {
    Mockito.when(expressionParser.parseExpression(Mockito.anyString()))
            .thenReturn(expression);
    Mockito.when(expression
            .getValue(Mockito.any(StandardEvaluationContext.class)))
            .thenThrow(new EvaluationException("bar"));

    ukubukaExpressionEvaluator.evaluate(new FileContents(),
            new FileRecord(), "fooBar");
}
 
Example 37
Project: lams   File: SpelNodeImpl.java   View source code 5 votes vote down vote up
@Override
public final Object getValue(ExpressionState expressionState) throws EvaluationException {
	if (expressionState != null) {
		return getValueInternal(expressionState).getValue();
	}
	else {
		// configuration not set - does that matter?
		return getValue(new ExpressionState(new StandardEvaluationContext()));
	}
}
 
Example 38
Project: lams   File: SpelNodeImpl.java   View source code 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()));
	}
}
 
Example 39
Project: lams   File: SpelExpression.java   View source code 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.defaultContext == null) {
		this.defaultContext = new StandardEvaluationContext();
	}
	return this.defaultContext;
}
 
Example 40
Project: oneops   File: ExpressionEvaluator.java   View source code 5 votes vote down vote up
private EvaluationContext getEvaluationContext(CmsWorkOrderBase woBase) {
	StandardEvaluationContext context = new StandardEvaluationContext();
	if (woBase instanceof CmsWorkOrder) {
		CmsRfcCISimple rfcSimple = cmsUtil.custRfcCI2RfcCISimple(((CmsWorkOrder)woBase).getRfcCi());
		context.setRootObject(rfcSimple);
	} else if (woBase instanceof CmsActionOrder) {
		CmsCISimple ciSimple = cmsUtil.custCI2CISimple(((CmsActionOrder)woBase).getCi(), CmsConstants.ATTR_VALUE_TYPE_DF, true);
		context.setRootObject(ciSimple);
	}
	return context;
}