Java Code Examples for org.springframework.expression.EvaluationContext#setVariable()

The following examples show how to use org.springframework.expression.EvaluationContext#setVariable() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SpelReproTests.java    From java-technology-stack with MIT License 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 2
Source File: SpelReproTests.java    From spring-analysis-note with MIT License 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 3
Source File: SpelReproTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void SPR10417_maps() {
	Map map1 = new HashMap();
	map1.put("A", 65);
	map1.put("B", 66);
	map1.put("X", 66);
	Map map2 = new HashMap();
	map2.put("X", 66);

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

	// #this should be the element from list1
	Expression ex = parser.parseExpression("#map1.?[#map2.containsKey(#this.getKey())]");
	Object result = ex.getValue(context);
	assertEquals("{X=66}", result.toString());

	ex = parser.parseExpression("#map1.?[#map2.containsKey(key)]");
	result = ex.getValue(context);
	assertEquals("{X=66}", result.toString());
}
 
Example 4
Source File: SpELTest.java    From java-master with 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 File: VisitLogAspect.java    From DimpleBlog with Apache License 2.0 5 votes vote down vote up
/**
 * 获取PageId
 *
 * @param joinPoint 切入点
 * @return PageId
 */
private Long getPageId(VLog vLog, JoinPoint joinPoint) throws NoSuchMethodException {
    String pageIdStr = vLog.pageId();
    if (StringUtils.isEmpty(pageIdStr)) {
        return null;
    }
    //get target method
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    Method method = joinPoint.getTarget().getClass().getMethod(methodSignature.getMethod().getName(), methodSignature.getMethod().getParameterTypes());
    //express SpEL
    ExpressionParser expressionParser = new SpelExpressionParser();
    LocalVariableTableParameterNameDiscoverer localVariableTableParameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
    String[] params = localVariableTableParameterNameDiscoverer.getParameterNames(method);

    Object[] args = joinPoint.getArgs();
    EvaluationContext context = new StandardEvaluationContext();
    for (int i = 0; i < params.length; i++) {
        context.setVariable(params[i], args[i]);
    }

    Expression expression = expressionParser.parseExpression(pageIdStr);
    Object value = expression.getValue(context);

    if (value == null) {
        return null;
    }
    try {
        return (Long) value;
    } catch (Exception e) {
        log.error("get pageId error for parameters {}", value);
        return null;
    }
}
 
Example 6
Source File: SpelKeyGenerator.java    From distributed-lock with MIT License 5 votes vote down vote up
private Object evaluateExpression(final String expression, final Object object, final Method method, final Object[] args) {
  final EvaluationContext context = new MethodBasedEvaluationContext(object, method, args, super.getParameterNameDiscoverer());
  context.setVariable("executionPath", object.getClass().getCanonicalName() + "." + method.getName());

  final Expression evaluatedExpression = getExpression(this.conditionCache, new AnnotatedElementKey(method, object.getClass()), expression);
  final Object expressionValue = evaluatedExpression.getValue(context);
  if (expressionValue == null) {
    throw new EvaluationConvertException("Expression evaluated in a null");
  }

  return expressionValue;
}
 
Example 7
Source File: SelectionAndProjectionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void projectionWithList() throws Exception {
	Expression expression = new SpelExpressionParser().parseRaw("#testList.![wrapper.value]");
	EvaluationContext context = new StandardEvaluationContext();
	context.setVariable("testList", IntegerTestBean.createList());
	Object value = expression.getValue(context);
	assertTrue(value instanceof List);
	List<?> list = (List<?>) value;
	assertEquals(3, list.size());
	assertEquals(5, list.get(0));
	assertEquals(6, list.get(1));
	assertEquals(7, list.get(2));
}
 
Example 8
Source File: EvaluationTests.java    From java-technology-stack with 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 9
Source File: SpelShardRouteRule.java    From ddal with Apache License 2.0 5 votes vote down vote up
@Override
public String parseScName(String scName, Object sdValue) {
    if (scRouteRuleExpression == null) {
        return scName;
    } else {
        EvaluationContext elContext = buildEvaluationContext(tbRouteRule);
        elContext.setVariable("scName", scName);
        return parseName(scRouteRuleExpression, elContext, sdValue);
    }
}
 
Example 10
Source File: SeedLockConfiguration.java    From seed with Apache License 2.0 5 votes vote down vote up
/**
 * 解析SpringEL表达式
 * @param key    表达式
 * @param method 方法
 * @param args   方法参数
 * @return spel解析结果
 */
private String parseSpringEL(String key, Method method, Object[] args) {
    if(!key.contains("#") && !key.contains("'")){
        return key;
    }
    String[] params = discoverer.getParameterNames(method);
    if(0 == params.length){
        return key;
    }
    EvaluationContext context = new StandardEvaluationContext();
    for(int i=0; i<params.length; i++){
        context.setVariable(params[i], args[i]);
    }
    return parser.parseExpression(key).getValue(context, String.class);
}
 
Example 11
Source File: SelectionAndProjectionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void projectionWithSet() throws Exception {
	Expression expression = new SpelExpressionParser().parseRaw("#testList.![wrapper.value]");
	EvaluationContext context = new StandardEvaluationContext();
	context.setVariable("testList", IntegerTestBean.createSet());
	Object value = expression.getValue(context);
	assertTrue(value instanceof List);
	List<?> list = (List<?>) value;
	assertEquals(3, list.size());
	assertEquals(5, list.get(0));
	assertEquals(6, list.get(1));
	assertEquals(7, list.get(2));
}
 
Example 12
Source File: SpringELUtil.java    From datax-web with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    // 定义变量
    EvaluationContext context = new StandardEvaluationContext();  // 表达式的上下文,
    String date="2019-11-22";
    context.setVariable("today", new Date());                        // 为了让表达式可以访问该对象, 先把对象放到上下文中
    ExpressionParser parser = new SpelExpressionParser();
    Date a = parser.parseExpression("#today").getValue(context, Date.class);   // Tom , 使用变量
    System.out.println(a);
}
 
Example 13
Source File: SpringELTry.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
public String hello() {
    ExpressionParser parser = new SpelExpressionParser();
    Expression expression =
            parser.parseExpression("('Hello' + ', World').concat(#end)");
    EvaluationContext context = new StandardEvaluationContext();
    context.setVariable("end", "!");
    return expression.getValue(context).toString();
}
 
Example 14
Source File: KeyUtil.java    From x7 with Apache License 2.0 5 votes vote down vote up
public static String makeKey(String prefix, String suffix, String condition, Object[] args) {

        Assert.notNull(condition, "condition can not null");
        if (args != null && args.length > 0 && condition.contains("#")) {

            Object obj = args[0];

            if (obj != null) {
                ExpressionParser parser = new SpelExpressionParser();

                int start = condition.indexOf("#") + 1;
                int end = 0;
                if (condition.contains(".")) {
                    end = condition.indexOf(".");
                } else {
                    end = condition.indexOf(" ");
                }

                String objName = condition.substring(start, end).trim();

                EvaluationContext ctx = new StandardEvaluationContext();
                ctx.setVariable(objName, obj);

                condition = parser.parseExpression(condition).getValue(ctx, String.class);
            }
        }

        String key = VerifyUtil.toMD5(prefix + condition) + suffix;

        return key;
    }
 
Example 15
Source File: SelectionAndProjectionTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void projectionWithArray() throws Exception {
	Expression expression = new SpelExpressionParser().parseRaw("#testArray.![wrapper.value]");
	EvaluationContext context = new StandardEvaluationContext();
	context.setVariable("testArray", IntegerTestBean.createArray());
	Object value = expression.getValue(context);
	assertTrue(value.getClass().isArray());
	TypedValue typedValue = new TypedValue(value);
	assertEquals(Number.class, typedValue.getTypeDescriptor().getElementTypeDescriptor().getType());
	Number[] array = (Number[]) value;
	assertEquals(3, array.length);
	assertEquals(new Integer(5), array[0]);
	assertEquals(5.9f, array[1]);
	assertEquals(new Integer(7), array[2]);
}
 
Example 16
Source File: SpelShardRouteRule.java    From ddal with Apache License 2.0 5 votes vote down vote up
protected String parseName(Expression expression, EvaluationContext elContext, Object sdValue) {
    if (expression == null) {
        throw new IllegalArgumentException("expression can't be null");
    }
    if (sdValue != null && sdValue instanceof RangeShardValue) {
        Long begin = ((RangeShardValue) sdValue).getBegin();
        Long end = ((RangeShardValue) sdValue).getEnd();
        if (begin == null || end == null) {
            throw new IllegalArgumentException("rangeShardValue.begin and rangeShardValue.end can't be null");
        }
        if (begin > end) {
            throw new IllegalArgumentException("rangeShardValue.begin can't be greater than rangeShardValue.end");
        }
        if (rangeSizeLimit != null && end - begin + 1 > rangeSizeLimit) {
            throw new OutOfRangeSizeLimitException((end - begin) + " > " + rangeSizeLimit);
        }
        String result = null;
        for (long l = begin; l <= end; l++) {
            elContext.setVariable("sdValue", l);
            String temp = expression.getValue(elContext, String.class);
            if (result != null && !result.equals(temp)) {
                throw new CrossTableException(result + " and " + temp);
            }
            result = temp;
        }
        return result;
    } else {
        elContext.setVariable("sdValue", sdValue);
        return expression.getValue(elContext, String.class);
    }
}
 
Example 17
Source File: MethodBasedSpelExpression.java    From ddal with Apache License 2.0 5 votes vote down vote up
public <T> T parse(Class<T> type, Object... args) {
    if (expression == null) {
        return null;
    }
    EvaluationContext context = buildEvaluationContext();
    if (args != null && args.length > 0) {
        for (int i = 0; i < args.length; i++) {
            if (parameterNames != null && parameterNames.length > i) {
                context.setVariable(parameterNames[i], args[i]);
            }
            context.setVariable("$" + i, args[i]);
        }
    }
    return expression.getValue(context, type);
}
 
Example 18
Source File: SpelReproTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void SPR16032() {
	EvaluationContext context = new StandardEvaluationContext();
	context.setVariable("str", "a\0b");

	Expression ex = parser.parseExpression("#str?.split('\0')");
	Object result = ex.getValue(context);
	assertTrue(ObjectUtils.nullSafeEquals(result, new String[] {"a", "b"}));
}
 
Example 19
Source File: SqlSpannerQueryTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Test
public void pageableParamQueryTest() throws NoSuchMethodException {

	String sql = "SELECT * FROM :org.springframework.cloud.gcp.data.spanner.repository.query.SqlSpannerQueryTests$Child:"
			+ " WHERE id = @id AND trader_id = @trader_id";
	// @formatter:off
	String entityResolvedSql = "SELECT *, " +
			"ARRAY (SELECT AS STRUCT canceled, documentId, id, childId, content " +
				"FROM documents WHERE (documents.id = children.id AND documents.childId = children.childId) " +
					"AND (canceled = false)) AS documents " +
			"FROM (SELECT * FROM children WHERE id = @id AND trader_id = @trader_id) children " +
			"WHERE disabled = false ORDER BY trader_id ASC LIMIT 10 OFFSET 30";
	// @formatter:on

	Object[] params = new Object[] { "ID", "TRADER_ID", PageRequest.of(3, 10, Sort.by(Order.asc("trader_id")))};
	String[] paramNames = new String[] { "id", "trader_id", "ignoredPageable" };

	when(queryMethod.isCollectionQuery()).thenReturn(false);
	when(queryMethod.getReturnedObjectType()).thenReturn((Class) Child.class);

	EvaluationContext evaluationContext = new StandardEvaluationContext();
	for (int i = 0; i < params.length; i++) {
		evaluationContext.setVariable(paramNames[i], params[i]);
	}
	when(this.evaluationContextProvider.getEvaluationContext(any(), any()))
			.thenReturn(evaluationContext);

	SqlSpannerQuery sqlSpannerQuery = createQuery(sql, Child.class, false);

	doAnswer((invocation) -> {
		Statement statement = invocation.getArgument(0);
		SpannerQueryOptions queryOptions = invocation.getArgument(1);
		assertThat(queryOptions.isAllowPartialRead()).isTrue();

		assertThat(statement.getSql()).isEqualTo(entityResolvedSql);

		Map<String, Value> paramMap = statement.getParameters();

		assertThat(paramMap.get("id").getString()).isEqualTo(params[0]);
		assertThat(paramMap.get("trader_id").getString()).isEqualTo(params[1]);
		assertThat(paramMap.get("ignoredPageable")).isNull();

		return null;
	}).when(this.spannerTemplate).executeQuery(any(), any());

	// This dummy method was created so the metadata for the ARRAY param inner type is
	// provided.
	Method method = QueryHolder.class.getMethod("dummyMethod4", String.class, String.class, Pageable.class);
	when(this.queryMethod.getMethod()).thenReturn(method);
	Mockito.<Parameters>when(this.queryMethod.getParameters()).thenReturn(new DefaultParameters(method));

	sqlSpannerQuery.execute(params);

	verify(this.spannerTemplate, times(1)).executeQuery(any(), any());
}
 
Example 20
Source File: SqlSpannerQueryTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Test
public void sqlCountWithWhereTest() throws NoSuchMethodException {
	String sql = "SELECT count(1) FROM :org.springframework.cloud.gcp.data.spanner.repository.query.SqlSpannerQueryTests$Child:"
			+ " WHERE id = @id AND trader_id = @trader_id";

	String entityResolvedSql = "SELECT count(1) FROM children WHERE id = @id AND trader_id = @trader_id";

	Object[] params = new Object[] { "ID", "TRADER_ID" };
	String[] paramNames = new String[] { "id", "trader_id" };

	when(queryMethod.isCollectionQuery()).thenReturn(false);
	when(queryMethod.getReturnedObjectType()).thenReturn((Class) long.class);

	EvaluationContext evaluationContext = new StandardEvaluationContext();
	for (int i = 0; i < params.length; i++) {
		evaluationContext.setVariable(paramNames[i], params[i]);
	}
	when(this.evaluationContextProvider.getEvaluationContext(any(), any()))
			.thenReturn(evaluationContext);

	SqlSpannerQuery sqlSpannerQuery = createQuery(sql, long.class, false);

	doAnswer((invocation) -> {
		Statement statement = invocation.getArgument(0);
		SpannerQueryOptions queryOptions = invocation.getArgument(1);
		assertThat(queryOptions.isAllowPartialRead()).isTrue();

		assertThat(statement.getSql()).isEqualTo(entityResolvedSql);

		Map<String, Value> paramMap = statement.getParameters();

		assertThat(paramMap.get("id").getString()).isEqualTo(params[0]);
		assertThat(paramMap.get("trader_id").getString()).isEqualTo(params[1]);

		return null;
	}).when(this.spannerTemplate).executeQuery(any(), any());

	// This dummy method was created so the metadata for the ARRAY param inner type is
	// provided.
	Method method = QueryHolder.class.getMethod("dummyMethod3", String.class, String.class);
	when(this.queryMethod.getMethod()).thenReturn(method);
	Mockito.<Parameters>when(this.queryMethod.getParameters()).thenReturn(new DefaultParameters(method));

	sqlSpannerQuery.execute(params);

	verify(this.spannerTemplate, times(1)).executeQuery(any(), any());
}