Java Code Examples for org.springframework.expression.spel.standard.SpelExpressionParser

The following are top voted examples for showing how to use org.springframework.expression.spel.standard.SpelExpressionParser. 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: springboot-shiro-cas-mybatis   File: AbstractCasWebflowConfigurer.java   View source code 7 votes vote down vote up
/**
 * Gets spring expression parser.
 *
 * @return the spring expression parser
 */
protected SpringELExpressionParser getSpringExpressionParser() {
    final SpelParserConfiguration configuration = new SpelParserConfiguration();
    final SpelExpressionParser spelExpressionParser = new SpelExpressionParser(configuration);
    final SpringELExpressionParser parser = new SpringELExpressionParser(spelExpressionParser,
            this.flowBuilderServices.getConversionService());

    parser.addPropertyAccessor(new ActionPropertyAccessor());
    parser.addPropertyAccessor(new BeanFactoryPropertyAccessor());
    parser.addPropertyAccessor(new FlowVariablePropertyAccessor());
    parser.addPropertyAccessor(new MapAdaptablePropertyAccessor());
    parser.addPropertyAccessor(new MessageSourcePropertyAccessor());
    parser.addPropertyAccessor(new ScopeSearchingPropertyAccessor());
    parser.addPropertyAccessor(new BeanExpressionContextAccessor());
    parser.addPropertyAccessor(new MapAccessor());
    parser.addPropertyAccessor(new MapAdaptablePropertyAccessor());
    parser.addPropertyAccessor(new EnvironmentAccessor());
    parser.addPropertyAccessor(new ReflectivePropertyAccessor());
    return parser;

}
 
Example 2
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 3
Project: cas-5.1.0   File: AbstractCasWebflowConfigurer.java   View source code 6 votes vote down vote up
/**
 * Gets spring expression parser.
 *
 * @return the spring expression parser
 */
protected SpringELExpressionParser getSpringExpressionParser() {
    final SpelParserConfiguration configuration = new SpelParserConfiguration();
    final SpelExpressionParser spelExpressionParser = new SpelExpressionParser(configuration);
    final SpringELExpressionParser parser = new SpringELExpressionParser(spelExpressionParser,
            this.flowBuilderServices.getConversionService());

    parser.addPropertyAccessor(new ActionPropertyAccessor());
    parser.addPropertyAccessor(new BeanFactoryPropertyAccessor());
    parser.addPropertyAccessor(new FlowVariablePropertyAccessor());
    parser.addPropertyAccessor(new MapAdaptablePropertyAccessor());
    parser.addPropertyAccessor(new MessageSourcePropertyAccessor());
    parser.addPropertyAccessor(new ScopeSearchingPropertyAccessor());
    parser.addPropertyAccessor(new BeanExpressionContextAccessor());
    parser.addPropertyAccessor(new MapAccessor());
    parser.addPropertyAccessor(new MapAdaptablePropertyAccessor());
    parser.addPropertyAccessor(new EnvironmentAccessor());
    parser.addPropertyAccessor(new ReflectivePropertyAccessor());
    return parser;

}
 
Example 4
Project: cas-server-4.2.1   File: AbstractCasWebflowConfigurer.java   View source code 6 votes vote down vote up
/**
 * Gets spring expression parser.
 *
 * @return the spring expression parser
 */
protected SpringELExpressionParser getSpringExpressionParser() {
    final SpelParserConfiguration configuration = new SpelParserConfiguration();
    final SpelExpressionParser spelExpressionParser = new SpelExpressionParser(configuration);
    final SpringELExpressionParser parser = new SpringELExpressionParser(spelExpressionParser,
            this.flowBuilderServices.getConversionService());

    parser.addPropertyAccessor(new ActionPropertyAccessor());
    parser.addPropertyAccessor(new BeanFactoryPropertyAccessor());
    parser.addPropertyAccessor(new FlowVariablePropertyAccessor());
    parser.addPropertyAccessor(new MapAdaptablePropertyAccessor());
    parser.addPropertyAccessor(new MessageSourcePropertyAccessor());
    parser.addPropertyAccessor(new ScopeSearchingPropertyAccessor());
    parser.addPropertyAccessor(new BeanExpressionContextAccessor());
    parser.addPropertyAccessor(new MapAccessor());
    parser.addPropertyAccessor(new MapAdaptablePropertyAccessor());
    parser.addPropertyAccessor(new EnvironmentAccessor());
    parser.addPropertyAccessor(new ReflectivePropertyAccessor());
    return parser;

}
 
Example 5
Project: spring-data-ebean   File: NativeEbeanQuery.java   View source code 6 votes vote down vote up
/**
 * Creates a new {@link NativeEbeanQuery} encapsulating the query annotated on the given {@link EbeanQueryMethod}.
 *
 * @param method                    must not be {@literal null}.
 * @param ebeanServer               must not be {@literal null}.
 * @param queryString               must not be {@literal null} or empty.
 * @param evaluationContextProvider
 */
public NativeEbeanQuery(EbeanQueryMethod method, EbeanServer ebeanServer, String queryString,
                        EvaluationContextProvider evaluationContextProvider, SpelExpressionParser parser) {

  super(method, ebeanServer, queryString, evaluationContextProvider, parser);

  Parameters<?, ?> parameters = method.getParameters();
  boolean hasPagingOrSortingParameter = parameters.hasPageableParameter() || parameters.hasSortParameter();
  boolean containsPageableOrSortInQueryExpression = queryString.contains("#pageable")
      || queryString.contains("#sort");

  if (hasPagingOrSortingParameter && !containsPageableOrSortInQueryExpression) {
    throw new InvalidEbeanQueryMethodException(
        "Cannot use native queries with dynamic sorting and/or pagination in method " + method);
  }
}
 
Example 6
Project: spring-data-ebean   File: NativeEbeanUpdate.java   View source code 6 votes vote down vote up
/**
 * Creates a new {@link NativeEbeanUpdate} encapsulating the query annotated on the given {@link EbeanQueryMethod}.
 *
 * @param method                    must not be {@literal null}.
 * @param ebeanServer               must not be {@literal null}.
 * @param queryString               must not be {@literal null} or empty.
 * @param evaluationContextProvider
 */
public NativeEbeanUpdate(EbeanQueryMethod method, EbeanServer ebeanServer, String queryString,
                         EvaluationContextProvider evaluationContextProvider, SpelExpressionParser parser) {

  super(method, ebeanServer, queryString, evaluationContextProvider, parser);

  Parameters<?, ?> parameters = method.getParameters();
  boolean hasPagingOrSortingParameter = parameters.hasPageableParameter() || parameters.hasSortParameter();
  boolean containsPageableOrSortInQueryExpression = queryString.contains("#pageable")
      || queryString.contains("#sort");

  if (hasPagingOrSortingParameter && !containsPageableOrSortInQueryExpression) {
    throw new InvalidEbeanQueryMethodException(
        "Cannot use native queries with dynamic sorting and/or pagination in method " + method);
  }
}
 
Example 7
Project: spring-cloud-stream-binder-kafka   File: KafkaMessageChannelBinder.java   View source code 6 votes vote down vote up
ProducerConfigurationMessageHandler(KafkaTemplate<byte[], byte[]> kafkaTemplate, String topic,
		ExtendedProducerProperties<KafkaProducerProperties> producerProperties,
		ProducerFactory<byte[], byte[]> producerFactory) {
	super(kafkaTemplate);
	setTopicExpression(new LiteralExpression(topic));
	setMessageKeyExpression(producerProperties.getExtension().getMessageKeyExpression());
	setBeanFactory(KafkaMessageChannelBinder.this.getBeanFactory());
	if (producerProperties.isPartitioned()) {
		SpelExpressionParser parser = new SpelExpressionParser();
		setPartitionIdExpression(parser.parseExpression("headers." + BinderHeaders.PARTITION_HEADER));
	}
	if (producerProperties.getExtension().isSync()) {
		setSync(true);
	}
	this.producerFactory = producerFactory;
}
 
Example 8
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 9
Project: spring4-understanding   File: SpelDocumentationTests.java   View source code 6 votes vote down vote up
@Test
public void testLiterals() throws Exception {
	ExpressionParser parser = new SpelExpressionParser();

	String helloWorld = (String) parser.parseExpression("'Hello World'").getValue(); // evals to "Hello World"
	assertEquals("Hello World",helloWorld);

	double avogadrosNumber  = (Double) parser.parseExpression("6.0221415E+23").getValue();
	assertEquals(6.0221415E+23, avogadrosNumber, 0);

	int maxValue = (Integer) parser.parseExpression("0x7FFFFFFF").getValue();  // evals to 2147483647
	assertEquals(Integer.MAX_VALUE,maxValue);

	boolean trueValue = (Boolean) parser.parseExpression("true").getValue();
	assertTrue(trueValue);

	Object nullValue = parser.parseExpression("null").getValue();
	assertNull(nullValue);
}
 
Example 10
Project: spring4-understanding   File: SpelCompilationCoverageTests.java   View source code 6 votes vote down vote up
@Test
public void indexerMapAccessor_12045() throws Exception {
	SpelParserConfiguration spc = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE,this.getClass().getClassLoader());
	SpelExpressionParser sep = new SpelExpressionParser(spc);
	expression=sep.parseExpression("headers[command]");
	MyMessage root = new MyMessage();
	assertEquals("wibble",expression.getValue(root));
	// This next call was failing because the isCompilable check in Indexer did not check on the key being compilable
	// (and also generateCode in the Indexer was missing the optimization that it didn't need necessarily need to call
	// generateCode for that accessor)
	assertEquals("wibble",expression.getValue(root));
	assertCanCompile(expression);

	// What about a map key that is an expression - ensure the getKey() is evaluated in the right scope
	expression=sep.parseExpression("headers[getKey()]");
	assertEquals("wobble",expression.getValue(root));
	assertEquals("wobble",expression.getValue(root));

	expression=sep.parseExpression("list[getKey2()]");
	assertEquals("wobble",expression.getValue(root));
	assertEquals("wobble",expression.getValue(root));

	expression = sep.parseExpression("ia[getKey2()]");
	assertEquals(3,expression.getValue(root));
	assertEquals(3,expression.getValue(root));
}
 
Example 11
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 12
Project: spring4-understanding   File: IndexingTests.java   View source code 6 votes vote down vote up
@Test
public void indexIntoGenericPropertyContainingMapObject() {
	Map<String, Map<String, String>> property = new HashMap<String, Map<String, String>>();
	Map<String, String> map =  new HashMap<String, String>();
	map.put("foo", "bar");
	property.put("property", map);
	SpelExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.addPropertyAccessor(new MapAccessor());
	context.setRootObject(property);
	Expression expression = parser.parseExpression("property");
	assertEquals("java.util.HashMap<?, ?>", expression.getValueTypeDescriptor(context).toString());
	assertEquals(map, expression.getValue(context));
	assertEquals(map, expression.getValue(context, Map.class));
	expression = parser.parseExpression("property['foo']");
	assertEquals("bar", expression.getValue(context));
}
 
Example 13
Project: spring4-understanding   File: ExpressionLanguageScenarioTests.java   View source code 6 votes vote down vote up
/**
 * 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 14
Project: spring4-understanding   File: ExpressionLanguageScenarioTests.java   View source code 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 15
Project: spring4-understanding   File: IndexingTests.java   View source code 6 votes vote down vote up
@Test
public void indexIntoGenericPropertyContainingGrowingList() {
	List<String> property = new ArrayList<String>();
	this.property = property;
	SpelParserConfiguration configuration = new SpelParserConfiguration(true, true);
	SpelExpressionParser parser = new SpelExpressionParser(configuration);
	Expression expression = parser.parseExpression("property");
	assertEquals("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.ArrayList<?>", expression.getValueTypeDescriptor(this).toString());
	assertEquals(property, expression.getValue(this));
	expression = parser.parseExpression("property[0]");
	try {
		assertEquals("bar", expression.getValue(this));
	} catch (EvaluationException e) {
		assertTrue(e.getMessage().startsWith("EL1053E"));
	}
}
 
Example 16
Project: spring4-understanding   File: IndexingTests.java   View source code 6 votes vote down vote up
@Test
public void indexIntoGenericPropertyContainingGrowingList2() {
	List<String> property2 = new ArrayList<String>();
	this.property2 = property2;
	SpelParserConfiguration configuration = new SpelParserConfiguration(true, true);
	SpelExpressionParser parser = new SpelExpressionParser(configuration);
	Expression expression = parser.parseExpression("property2");
	assertEquals("java.util.ArrayList<?>", expression.getValueTypeDescriptor(this).toString());
	assertEquals(property2, expression.getValue(this));
	expression = parser.parseExpression("property2[0]");
	try {
		assertEquals("bar", expression.getValue(this));
	} catch (EvaluationException e) {
		assertTrue(e.getMessage().startsWith("EL1053E"));
	}
}
 
Example 17
Project: phone   File: SpringSpelTest.java   View source code 6 votes vote down vote up
@Test
	public void testSpel(){
		 //使用SPEL进行key的解析
        ExpressionParser parser = new SpelExpressionParser(); 
        //SPEL上下文
        StandardEvaluationContext context = new StandardEvaluationContext();
        //把方法参数放入SPEL上下文中
        List<Model> list = MyBatisUtil.parseBase("username,=,leiyong","password,=,asssd","loginName,=,ray");
        context.setVariable("objs", list);
        System.out.println(parser.parseExpression("#objs[0].column").getValue(context,String.class));
        System.out.println(parser.parseExpression("#objs?.![column]").getValue(context,String.class));
        System.out.println(parser.parseExpression("#objs?.![column+operate]").getValue(context,String.class));
        context.setVariable("obj", list.get(0));
//        System.out.println(parser.parseExpression("#orgPk+#userName").getValue(context,String.class));
        System.out.println(parser.parseExpression("#obj?.column+#obj?.operate").getValue(context,String.class));
        System.out.println(parser.parseExpression("#obj?.column+{':'}+#obj?.operate").getValue(context,String.class));
        System.out.println(parser.parseExpression("#obj?.operate").getValue(context,String.class));
        System.out.println(parser.parseExpression("#obj?.value").getValue(context,String.class));
        System.out.println(parser.parseExpression("#obj?.value").getValue(context,String.class));
        System.out.println(parser.parseExpression("'test'").getValue(context,String.class));
        System.out.println(parser.parseExpression("#objs?.!['1']").getValue(context,String.class));
	}
 
Example 18
Project: cibet   File: SetpointExpressionSecurityMetadataSource.java   View source code 6 votes vote down vote up
protected PreInvocationAttribute createPreInvocationAttribute(String preFilter, String preAuthorize) {
   try {
      log.debug("createPreInvocationAttribute from " + preFilter + " and " + preAuthorize);
      String preAuthValue = parseValueParameter(preAuthorize);
      String preFilterValue = parseValueParameter(preFilter);
      String preFilterTarget = parseFilterTargetParameter(preFilter);

      ExpressionParser parser = new SpelExpressionParser();
      Expression preAuthorizeExpression = preAuthorize == null ? parser.parseExpression("permitAll")
            : parser.parseExpression(preAuthValue);
      log.debug(preAuthorizeExpression);

      Expression preFilterExpression = preFilter == null ? null : parser.parseExpression(preFilterValue);

      return new PreCibetConfigAttribute(preFilterExpression, preFilterTarget, preAuthorizeExpression);
   } catch (ParseException e) {
      throw new IllegalArgumentException("Failed to parse expression '" + e.getExpressionString() + "'", e);
   }
}
 
Example 19
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 20
Project: spring4-understanding   File: SpelReproTests.java   View source code 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<MethodResolver>();
	methodResolvers.add(new ReflectiveMethodResolver() {
		@Override
		protected Method[] getMethods(Class<?> type) {
			try {
				return new Method[] {
						Integer.class.getDeclaredMethod("parseInt", new Class<?>[] {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 21
Project: spring4-understanding   File: MethodInvocationTests.java   View source code 6 votes vote down vote up
/**
 * Check on first usage (when the cachedExecutor in MethodReference is null) that the exception is not wrapped.
 */
@Test
public void testMethodThrowingException_SPR6941() {
	// Test method on inventor: throwException()
	// On 1 it will throw an IllegalArgumentException
	// On 2 it will throw a RuntimeException
	// On 3 it will exit normally
	// In each case it increments the Inventor field 'counter' when invoked

	SpelExpressionParser parser = new SpelExpressionParser();
	Expression expr = parser.parseExpression("throwException(#bar)");

	eContext.setVariable("bar", 2);
	try {
		expr.getValue(eContext);
		fail();
	}
	catch (Exception ex) {
		if (ex instanceof SpelEvaluationException) {
			fail("Should not be a SpelEvaluationException: " + ex);
		}
		// normal
	}
}
 
Example 22
Project: spring4-understanding   File: SelectionAndProjectionTests.java   View source code 6 votes vote down vote up
@Test
public void selectionWithArray() throws Exception {
	Expression expression = new SpelExpressionParser().parseRaw("integers.?[#this<5]");
	EvaluationContext context = new StandardEvaluationContext(new ArrayTestBean());
	Object value = expression.getValue(context);
	assertTrue(value.getClass().isArray());
	TypedValue typedValue = new TypedValue(value);
	assertEquals(Integer.class, typedValue.getTypeDescriptor().getElementTypeDescriptor().getType());
	Integer[] array = (Integer[]) value;
	assertEquals(5, array.length);
	assertEquals(new Integer(0), array[0]);
	assertEquals(new Integer(1), array[1]);
	assertEquals(new Integer(2), array[2]);
	assertEquals(new Integer(3), array[3]);
	assertEquals(new Integer(4), array[4]);
}
 
Example 23
Project: phone   File: BeanUtil.java   View source code 6 votes vote down vote up
/**
 * 验证对象属性是否为空,为空则返回spel表达式
 * @param obj 被验证的对象
 * @param notNullFields spel表达式集合
 * @return 如全部不为空,返回null
 * "#pk","#sysUsers?.![!this]"
 */
public static String checkEntityBySpel(final Object obj,String... notNullFields){
	if (obj==null) {
		return "信息异常";
	}else {
		ExpressionParser parser = new SpelExpressionParser();
        //SPEL上下文
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setVariable("obj", obj);
		if (ArrayUtils.isNotEmpty(notNullFields)) {
			for (int i = 0; i < notNullFields.length; i++) {
				String f = notNullFields[i];
				if (StringUtils.isNotBlank(f)) {
					Object value = parser.parseExpression(f).getValue();
					boolean res = checkFieldNotNull(value);
					if (!res) {
						return f;
					}
				}
			}
		}
	}
	return null;
}
 
Example 24
Project: spring4-understanding   File: ExpressionLanguageScenarioTests.java   View source code 6 votes vote down vote up
/**
 * Scenario: using the standard infrastructure and running simple expression evaluation.
 */
@Test
public void testScenario_UsingStandardInfrastructure() {
	try {
		// Create a parser
		SpelExpressionParser parser = new SpelExpressionParser();
		// Parse an expression
		Expression expr = parser.parseRaw("new String('hello world')");
		// Evaluate it using a 'standard' context
		Object value = expr.getValue();
		// They are reusable
		value = expr.getValue();

		assertEquals("hello world", value);
		assertEquals(String.class, value.getClass());
	} catch (EvaluationException ee) {
		ee.printStackTrace();
		fail("Unexpected Exception: " + ee.getMessage());
	} catch (ParseException pe) {
		pe.printStackTrace();
		fail("Unexpected Exception: " + pe.getMessage());
	}
}
 
Example 25
Project: spring4-understanding   File: SpelReproTests.java   View source code 6 votes vote down vote up
@Test
public void SPR9735() {
	Item item = new Item();
	item.setName("parent");

	Item item1 = new Item();
	item1.setName("child1");

	Item item2 = new Item();
	item2.setName("child2");

	item.add(item1);
	item.add(item2);

	ExpressionParser parser = new SpelExpressionParser();
	EvaluationContext context = new StandardEvaluationContext();
	Expression exp = parser.parseExpression("#item[0].name");
	context.setVariable("item", item);

	assertEquals("child1", exp.getValue(context));
}
 
Example 26
Project: spring-cloud-gateway   File: RouteDefinitionRouteLocatorTests.java   View source code 6 votes vote down vote up
@Test
public void testGetTupleWithSpel() {
	parser = new SpelExpressionParser();
	ArgumentHints argumentHints = new ArgumentHints() {
		@Override
		public List<String> argNames() {
			return Arrays.asList("bean", "arg1");
		}
	};
	Map<String, String> args = new HashMap<>();
	args.put("bean", "#{@foo}");
	args.put("arg1", "val1");
	Tuple tuple = RouteDefinitionRouteLocator.getTuple(argumentHints, args, parser, this.beanFactory);
	assertThat(tuple).isNotNull();
	assertThat(tuple.getValue("bean", Integer.class)).isEqualTo(42);
	assertThat(tuple.getString("arg1")).isEqualTo("val1");
}
 
Example 27
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 28
Project: spring4-understanding   File: SpelReproTests.java   View source code 6 votes vote down vote up
private void checkTemplateParsingError(String expression, ParserContext context, String expectedMessage) throws Exception {
	SpelExpressionParser parser = new SpelExpressionParser();
	try {
		parser.parseExpression(expression, context);
		fail("Should have failed with message: " + expectedMessage);
	}
	catch (Exception ex) {
		String message = ex.getMessage();
		if (ex instanceof ExpressionException) {
			message = ((ExpressionException) ex).getSimpleMessage();
		}
		if (!message.equals(expectedMessage)) {
			ex.printStackTrace();
		}
		assertThat(expectedMessage, equalTo(message));
	}
}
 
Example 29
Project: spring4-understanding   File: ScenariosForSpringSecurity.java   View source code 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 30
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 31
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 32
Project: configx   File: GenericScope.java   View source code 5 votes vote down vote up
private Expression parseExpression(String input) {
    if (StringUtils.hasText(input)) {
        ExpressionParser parser = new SpelExpressionParser();
        try {
            return parser.parseExpression(input);
        } catch (ParseException e) {
            throw new IllegalArgumentException("Cannot parse expression: " + input, e);
        }

    } else {
        return null;
    }
}
 
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: Bucket4JAutoConfigurationServletFilter.java   View source code 5 votes vote down vote up
@Bean
public ExpressionParser servletFilterExpressionParser() {
	SpelParserConfiguration config = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, this.getClass().getClassLoader());
	ExpressionParser parser = new SpelExpressionParser(config);
	
	return parser;
}
 
Example 35
Project: HelloShiftLeft   File: SearchController.java   View source code 5 votes vote down vote up
@RequestMapping(value = "/search/user", method = RequestMethod.GET)
public String doGetSearch(@RequestParam String foo, HttpServletResponse response, HttpServletRequest request) {
  java.lang.Object message = new Object();
  try {
    ExpressionParser parser = new SpelExpressionParser();
    Expression exp = parser.parseExpression(foo);
    message = (Object) exp.getValue();
  } catch (Exception ex) {
    System.out.println(ex.getMessage());
  }
  return message.toString();
}
 
Example 36
Project: martini-core   File: DefaultMixologist.java   View source code 5 votes vote down vote up
@Override
public Collection<Martini> getMartinis(@Nullable String spelFilter) {
	String trimmed = null == spelFilter ? "" : spelFilter.trim();

	Collection<Martini> martinis = null;
	if (!trimmed.isEmpty()) {
		SpelExpressionParser parser = new SpelExpressionParser();
		Expression expression = parser.parseExpression(spelFilter);
		martinis = getMartinis(expression);
	}
	return null == martinis ? getMartinis() : martinis;
}
 
Example 37
Project: jwala   File: ResourceServiceImpl.java   View source code 5 votes vote down vote up
@Override
public String encryptUsingPlatformBean(String cleartext) {
    SpelExpressionParser expressionParser = new SpelExpressionParser();
    String encryptExpressionString = ApplicationProperties.get("encryptExpression");
    Expression encryptExpression = expressionParser.parseExpression(encryptExpressionString);

    StandardEvaluationContext context = new StandardEvaluationContext();
    context.setVariable("stringToEncrypt", cleartext);
    return encryptExpression.getValue(context, String.class);
}
 
Example 38
Project: jwala   File: DecryptPassword.java   View source code 5 votes vote down vote up
public String decrypt(String encryptedValue) {
    if (encryptedValue==null) {
        return null;
    }
    
    final ExpressionParser expressionParser = new SpelExpressionParser();
    final Expression decryptExpression = expressionParser.parseExpression(decryptorImpl);

    final StandardEvaluationContext context = new StandardEvaluationContext();
    context.setVariable("stringToDecrypt", encryptedValue);
    return decryptExpression.getValue(context, String.class);
}
 
Example 39
Project: jwala   File: DecryptPassword.java   View source code 5 votes vote down vote up
public String encrypt(String unencryptedValue) {
    
    if (unencryptedValue==null) {
        return null;
    }
    
    final ExpressionParser expressionParser = new SpelExpressionParser();
    final Expression encryptExpression = expressionParser.parseExpression(encryptorImpl);

    final StandardEvaluationContext context = new StandardEvaluationContext();
    context.setVariable("stringToEncrypt", unencryptedValue);
    return encryptExpression.getValue(context, String.class);
}
 
Example 40
Project: Android_Code_Arbiter   File: SpelSample.java   View source code 5 votes vote down vote up
public static void parseExpressionInterface(String property) {

        ExpressionParser parser = new SpelExpressionParser();

        //Static value not that useful .. but safe
        Expression exp1 = parser.parseExpression("'safe expression'");
        String constantValue = exp1.getValue(String.class);
        System.out.println("exp1="+constantValue);

        StandardEvaluationContext testContext = new StandardEvaluationContext(TEST_PERSON);
        //Unsafe if the input is control by the user..
        Expression exp2 = parser.parseExpression(property+" == 'Benoit'");
        String dynamicValue = exp2.getValue(testContext, String.class);
        System.out.println("exp2="+dynamicValue);
    }