当前位置: 首页>>代码示例>>Java>>正文


Java Expression类代码示例

本文整理汇总了Java中org.springframework.expression.Expression的典型用法代码示例。如果您正苦于以下问题:Java Expression类的具体用法?Java Expression怎么用?Java Expression使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Expression类属于org.springframework.expression包,在下文中一共展示了Expression类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getUserInfos

import org.springframework.expression.Expression; //导入依赖的package包/类
@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;
}
 
开发者ID:EsupPortail,项目名称:esup-sgc,代码行数:21,代码来源:SpelUserInfoService.java

示例2: execute

import org.springframework.expression.Expression; //导入依赖的package包/类
@Override
public Result execute(Object target) {
    try {
        EvaluationContext ctx = create(target);
        Expression exp = parser.parseExpression(expression);
        Boolean value = (Boolean) exp.getValue(ctx);
        if (value) {
            return ok();
        } else {
            return nok("Expression " + expression + " returned false");
        }
    } catch (Exception e) {
        // TODO - Log me
        return nok("Exception : " + e.getMessage());
    }
}
 
开发者ID:gilles-stragier,项目名称:quickmon,代码行数:17,代码来源:SpelAssertion.java

示例3: getKeyFilter

import org.springframework.expression.Expression; //导入依赖的package包/类
/**
 * 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";
}
 
开发者ID:MarcGiffing,项目名称:bucket4j-spring-boot-starter,代码行数:33,代码来源:Bucket4JBaseConfiguration.java

示例4: skipCondition

import org.springframework.expression.Expression; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:MarcGiffing,项目名称:bucket4j-spring-boot-starter,代码行数:22,代码来源:Bucket4JBaseConfiguration.java

示例5: getEligibleOfferings

import org.springframework.expression.Expression; //导入依赖的package包/类
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;
}
 
开发者ID:oneops,项目名称:oneops,代码行数:21,代码来源:BomEnvManagerImpl.java

示例6: getEligbleOfferings

import org.springframework.expression.Expression; //导入依赖的package包/类
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;
}
 
开发者ID:oneops,项目名称:oneops,代码行数:23,代码来源:OfferingsMatcher.java

示例7: isExpressionMatching

import org.springframework.expression.Expression; //导入依赖的package包/类
public boolean isExpressionMatching(CmsCI complianceCi, CmsWorkOrderBase wo) {
	
	CmsCIAttribute attr = complianceCi.getAttribute(ATTR_NAME_FILTER);
	if (attr == null) {
		return false;
	}
	String filter = attr.getDjValue();
	
	try {
		if (StringUtils.isNotBlank(filter)) {
			Expression expr = exprParser.parseExpression(filter);
			EvaluationContext context = getEvaluationContext(wo);
			//parse the filter expression and check if it matches this ci/rfc
			Boolean match = expr.getValue(context, Boolean.class);
			if (logger.isDebugEnabled()) {
				logger.debug("Expression " + filter + " provided by compliance ci " + complianceCi.getCiId() + " not matched for ci " + getCiName(wo));	
			}
			
			return match;
		}
	} catch (ParseException | EvaluationException e) {
		String error = "Error in evaluating expression " + filter +" provided by compliance ci " + complianceCi.getCiId() + ", target ci :" + getCiName(wo); 
		logger.error(error, e);
	}
	return false;
}
 
开发者ID:oneops,项目名称:oneops,代码行数:27,代码来源:ExpressionEvaluator.java

示例8: getMartinis

import org.springframework.expression.Expression; //导入依赖的package包/类
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;
}
 
开发者ID:qas-guru,项目名称:martini-core,代码行数:18,代码来源:DefaultMixologist.java

示例9: amqpChannelAdapter

import org.springframework.expression.Expression; //导入依赖的package包/类
@ServiceActivator(inputChannel = Sink.INPUT)
@Bean
public MessageHandler amqpChannelAdapter(ConnectionFactory rabbitConnectionFactory) {
	AmqpOutboundEndpointSpec handler = Amqp.outboundAdapter(rabbitTemplate(rabbitConnectionFactory))
			.mappedRequestHeaders(properties.getMappedRequestHeaders())
			.defaultDeliveryMode(properties.getPersistentDeliveryMode() ? MessageDeliveryMode.PERSISTENT
					: MessageDeliveryMode.NON_PERSISTENT);

	Expression exchangeExpression = this.properties.getExchangeExpression();
	if (exchangeExpression != null) {
		handler.exchangeNameExpression(exchangeExpression);
	}
	else {
		handler.exchangeName(this.properties.getExchange());
	}

	Expression routingKeyExpression = this.properties.getRoutingKeyExpression();
	if (routingKeyExpression != null) {
		handler.routingKeyExpression(routingKeyExpression);
	}
	else {
		handler.routingKey(this.properties.getRoutingKey());
	}

	return handler.get();
}
 
开发者ID:spring-cloud-stream-app-starters,项目名称:rabbit,代码行数:27,代码来源:RabbitSinkConfiguration.java

示例10: testScenario_RegisteringJavaMethodsAsFunctionsAndCallingThem

import org.springframework.expression.Expression; //导入依赖的package包/类
/**
 * 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());
	}
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:25,代码来源:ExpressionLanguageScenarioTests.java

示例11: objectMapper

import org.springframework.expression.Expression; //导入依赖的package包/类
@Bean
public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.setDeserializerModifier( new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<Enum> modifyEnumDeserializer( DeserializationConfig config, final JavaType type, BeanDescription beanDesc,
          final JsonDeserializer<?> deserializer ) {
            return new JsonDeserializer<Enum>() {
                @Override
                public Enum deserialize( JsonParser jp, DeserializationContext ctxt ) throws IOException {
                    Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass();
                    return Enum.valueOf( rawClass, jp.getValueAsString().toUpperCase() );
                }
            };
        }
    } );

    module.addDeserializer( Expression.class, new ExpressionDeserializer( expressionParser() ) );
    module.addDeserializer( Range.class, new RangeDeserializer() );
    mapper.registerModule( module );

    return mapper;
}
 
开发者ID:cslee00,项目名称:datadog-jmx-collector,代码行数:25,代码来源:JmxCollectorMain.java

示例12: mapOfMap_SPR7244

import org.springframework.expression.Expression; //导入依赖的package包/类
@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);
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:21,代码来源:SpelReproTests.java

示例13: testCreateListsOnAttemptToIndexNull01

import org.springframework.expression.Expression; //导入依赖的package包/类
@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());
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:23,代码来源:EvaluationTests.java

示例14: initializingCollectionElementsOnWrite

import org.springframework.expression.Expression; //导入依赖的package包/类
/**
 * SPR-6984: attempting to index a collection on write using an index that
 * doesn't currently exist in the collection (address.crossStreets[0] below)
 */
@Test
public void initializingCollectionElementsOnWrite() throws Exception {
	TestPerson person = new TestPerson();
	EvaluationContext context = new StandardEvaluationContext(person);
	SpelParserConfiguration config = new SpelParserConfiguration(true, true);
	ExpressionParser parser = new SpelExpressionParser(config);
	Expression expression = parser.parseExpression("name");
	expression.setValue(context, "Oleg");
	assertEquals("Oleg", person.getName());

	expression = parser.parseExpression("address.street");
	expression.setValue(context, "123 High St");
	assertEquals("123 High St", person.getAddress().getStreet());

	expression = parser.parseExpression("address.crossStreets[0]");
	expression.setValue(context, "Blah");
	assertEquals("Blah", person.getAddress().getCrossStreets().get(0));

	expression = parser.parseExpression("address.crossStreets[3]");
	expression.setValue(context, "Wibble");
	assertEquals("Blah", person.getAddress().getCrossStreets().get(0));
	assertEquals("Wibble", person.getAddress().getCrossStreets().get(3));
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:28,代码来源:EvaluationTests.java

示例15: customStaticFunctions_SPR9038

import org.springframework.expression.Expression; //导入依赖的package包/类
/**
 * 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());
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:29,代码来源:SpelReproTests.java


注:本文中的org.springframework.expression.Expression类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。