org.springframework.expression.ParserContext Java Examples

The following examples show how to use org.springframework.expression.ParserContext. 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: InternalSpelExpressionParser.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected SpelExpression doParseExpression(String expressionString, ParserContext context) throws ParseException {
	try {
		this.expressionString = expressionString;
		Tokenizer tokenizer = new Tokenizer(expressionString);
		tokenizer.process();
		this.tokenStream = tokenizer.getTokens();
		this.tokenStreamLength = this.tokenStream.size();
		this.tokenStreamPointer = 0;
		this.constructedNodes.clear();
		SpelNodeImpl ast = eatExpression();
		if (moreTokens()) {
			throw new SpelParseException(peekToken().startPos, SpelMessage.MORE_INPUT, toString(nextToken()));
		}
		Assert.isTrue(this.constructedNodes.isEmpty());
		return new SpelExpression(expressionString, ast, this.configuration);
	}
	catch (InternalParseException ex) {
		throw ex.getCause();
	}
}
 
Example #2
Source File: InternalSpelExpressionParser.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected SpelExpression doParseExpression(String expressionString, @Nullable ParserContext context)
		throws ParseException {

	try {
		this.expressionString = expressionString;
		Tokenizer tokenizer = new Tokenizer(expressionString);
		this.tokenStream = tokenizer.process();
		this.tokenStreamLength = this.tokenStream.size();
		this.tokenStreamPointer = 0;
		this.constructedNodes.clear();
		SpelNodeImpl ast = eatExpression();
		Assert.state(ast != null, "No node");
		Token t = peekToken();
		if (t != null) {
			throw new SpelParseException(t.startPos, SpelMessage.MORE_INPUT, toString(nextToken()));
		}
		Assert.isTrue(this.constructedNodes.isEmpty(), "At least one node expected");
		return new SpelExpression(expressionString, ast, this.configuration);
	}
	catch (InternalParseException ex) {
		throw ex.getCause();
	}
}
 
Example #3
Source File: ExpressionBasedStringQuery.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param qry,     the query expression potentially containing a SpEL expression. Must not be {@literal null}.}
 * @param metadata the {@link RepositoryMetadata} for the given entity. Must not be {@literal null}.
 * @param parser   Must not be {@literal null}.
 * @return rendered query
 */
private static String renderQueryIfExpressionOrReturnQuery(String qry,
    RepositoryMetadata metadata,
    SpelExpressionParser parser) {

    Assert.notNull(qry, "query must not be null!");
    Assert.notNull(metadata, "metadata must not be null!");
    Assert.notNull(parser, "parser must not be null!");

    if (!containsExpression(qry))
        return qry;

    StandardEvaluationContext evalCtx = new StandardEvaluationContext();
    evalCtx.setVariable(ENTITY_NAME, metadata.getDomainType().getSimpleName());

    qry = potentiallyQuoteExpressionsParameter(qry);

    Expression expr = parser.parseExpression(qry, ParserContext.TEMPLATE_EXPRESSION);

    String result = expr.getValue(evalCtx, String.class);

    if (result == null)
        return qry;

    return potentiallyUnquoteParameterExpressions(result);
}
 
Example #4
Source File: ExpressionBasedStringQuery.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param qry,     the query expression potentially containing a SpEL expression. Must not be {@literal null}.}
 * @param metadata the {@link RepositoryMetadata} for the given entity. Must not be {@literal null}.
 * @param parser   Must not be {@literal null}.
 * @return rendered query
 */
private static String renderQueryIfExpressionOrReturnQuery(String qry,
    RepositoryMetadata metadata,
    SpelExpressionParser parser) {

    Assert.notNull(qry, "query must not be null!");
    Assert.notNull(metadata, "metadata must not be null!");
    Assert.notNull(parser, "parser must not be null!");

    if (!containsExpression(qry))
        return qry;

    StandardEvaluationContext evalCtx = new StandardEvaluationContext();
    evalCtx.setVariable(ENTITY_NAME, metadata.getDomainType().getSimpleName());

    qry = potentiallyQuoteExpressionsParameter(qry);

    Expression expr = parser.parseExpression(qry, ParserContext.TEMPLATE_EXPRESSION);

    String result = expr.getValue(evalCtx, String.class);

    if (result == null)
        return qry;

    return potentiallyUnquoteParameterExpressions(result);
}
 
Example #5
Source File: SpELTest.java    From java-master with Apache License 2.0 6 votes vote down vote up
@Test
public void test2() {
    // 可以解析对象属性值
    CreateUserReqVo createUserReqVo = new CreateUserReqVo();
    createUserReqVo.setUsername("liangyudong");
    createUserReqVo.setPassword("123456");

    // 标准写法
    Expression exp = parser.parseExpression("username");
    logger.info((String) exp.getValue(createUserReqVo));

    EvaluationContext context = new StandardEvaluationContext(createUserReqVo);
    logger.info((String) exp.getValue(context));

    // 模板写法,同@Value注解的写法
    logger.info(parser.parseExpression("#{username}", ParserContext.TEMPLATE_EXPRESSION).getValue(context).toString());
}
 
Example #6
Source File: SpelReproTests.java    From spring4-understanding with Apache License 2.0 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 #7
Source File: InternalSpelExpressionParser.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected SpelExpression doParseExpression(String expressionString, @Nullable ParserContext context)
		throws ParseException {

	try {
		this.expressionString = expressionString;
		Tokenizer tokenizer = new Tokenizer(expressionString);
		this.tokenStream = tokenizer.process();
		this.tokenStreamLength = this.tokenStream.size();
		this.tokenStreamPointer = 0;
		this.constructedNodes.clear();
		SpelNodeImpl ast = eatExpression();
		Assert.state(ast != null, "No node");
		Token t = peekToken();
		if (t != null) {
			throw new SpelParseException(t.startPos, SpelMessage.MORE_INPUT, toString(nextToken()));
		}
		Assert.isTrue(this.constructedNodes.isEmpty(), "At least one node expected");
		return new SpelExpression(expressionString, ast, this.configuration);
	}
	catch (InternalParseException ex) {
		throw ex.getCause();
	}
}
 
Example #8
Source File: SpelReproTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
private void checkTemplateParsingError(String expression, ParserContext context, String expectedMessage) {
	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 #9
Source File: DefaultArangoPersistentEntity.java    From spring-data with Apache License 2.0 6 votes vote down vote up
public DefaultArangoPersistentEntity(final TypeInformation<T> information) {
	super(information);
	collection = StringUtils.uncapitalize(information.getType().getSimpleName());
	context = new StandardEvaluationContext();
	hashIndexedProperties = new ArrayList<>();
	skiplistIndexedProperties = new ArrayList<>();
	persistentIndexedProperties = new ArrayList<>();
	geoIndexedProperties = new ArrayList<>();
	fulltextIndexedProperties = new ArrayList<>();
	repeatableAnnotationCache = new HashMap<>();
	final Document document = findAnnotation(Document.class);
	final Edge edge = findAnnotation(Edge.class);
	if (edge != null) {
		collection = StringUtils.hasText(edge.value()) ? edge.value() : collection;
		collectionOptions = createCollectionOptions(edge);
	} else if (document != null) {
		collection = StringUtils.hasText(document.value()) ? document.value() : collection;
		collectionOptions = createCollectionOptions(document);
	} else {
		collectionOptions = new CollectionCreateOptions().type(CollectionType.DOCUMENT);
	}
	expression = PARSER.parseExpression(collection, ParserContext.TEMPLATE_EXPRESSION);
}
 
Example #10
Source File: InternalSpelExpressionParser.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected SpelExpression doParseExpression(String expressionString, ParserContext context) throws ParseException {
	try {
		this.expressionString = expressionString;
		Tokenizer tokenizer = new Tokenizer(expressionString);
		this.tokenStream = tokenizer.process();
		this.tokenStreamLength = this.tokenStream.size();
		this.tokenStreamPointer = 0;
		this.constructedNodes.clear();
		SpelNodeImpl ast = eatExpression();
		if (moreTokens()) {
			throw new SpelParseException(peekToken().startPos, SpelMessage.MORE_INPUT, toString(nextToken()));
		}
		Assert.isTrue(this.constructedNodes.isEmpty(), "At least one node expected");
		return new SpelExpression(expressionString, ast, this.configuration);
	}
	catch (InternalParseException ex) {
		throw ex.getCause();
	}
}
 
Example #11
Source File: ExpressionTransform.java    From kork with Apache License 2.0 5 votes vote down vote up
public ExpressionTransform(
    ParserContext parserContext,
    ExpressionParser parser,
    Function<String, String> stringExpressionPreprocessor,
    Class<?>... typesToStringify) {
  this.parserContext = parserContext;
  this.parser = parser;
  this.stringExpressionPreprocessor = stringExpressionPreprocessor;
  this.typesToStringify = Arrays.asList(typesToStringify);
}
 
Example #12
Source File: SpelReproTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void checkTemplateParsingError(String expression, ParserContext context, String expectedMessage) {
	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 #13
Source File: TemplateAwareExpressionParser.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Expression parseExpression(String expressionString, @Nullable ParserContext context) throws ParseException {
	if (context != null && context.isTemplate()) {
		return parseTemplate(expressionString, context);
	}
	else {
		return doParseExpression(expressionString, context);
	}
}
 
Example #14
Source File: SpelReproTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void NPE_SPR5673() throws Exception {
	ParserContext hashes = TemplateExpressionParsingTests.HASH_DELIMITED_PARSER_CONTEXT;
	ParserContext dollars = TemplateExpressionParsingTests.DEFAULT_TEMPLATE_PARSER_CONTEXT;

	checkTemplateParsing("abc${'def'} ghi", "abcdef ghi");

	checkTemplateParsingError("abc${ {}( 'abc'", "Missing closing ')' for '(' at position 8");
	checkTemplateParsingError("abc${ {}[ 'abc'", "Missing closing ']' for '[' at position 8");
	checkTemplateParsingError("abc${ {}{ 'abc'", "Missing closing '}' for '{' at position 8");
	checkTemplateParsingError("abc${ ( 'abc' }", "Found closing '}' at position 14 but most recent opening is '(' at position 6");
	checkTemplateParsingError("abc${ '... }", "Found non terminating string literal starting at position 6");
	checkTemplateParsingError("abc${ \"... }", "Found non terminating string literal starting at position 6");
	checkTemplateParsingError("abc${ ) }", "Found closing ')' at position 6 without an opening '('");
	checkTemplateParsingError("abc${ ] }", "Found closing ']' at position 6 without an opening '['");
	checkTemplateParsingError("abc${ } }", "No expression defined within delimiter '${}' at character 3");
	checkTemplateParsingError("abc$[ } ]", DOLLARSQUARE_TEMPLATE_PARSER_CONTEXT, "Found closing '}' at position 6 without an opening '{'");

	checkTemplateParsing("abc ${\"def''g}hi\"} jkl", "abc def'g}hi jkl");
	checkTemplateParsing("abc ${'def''g}hi'} jkl", "abc def'g}hi jkl");
	checkTemplateParsing("}", "}");
	checkTemplateParsing("${'hello'} world", "hello world");
	checkTemplateParsing("Hello ${'}'}]", "Hello }]");
	checkTemplateParsing("Hello ${'}'}", "Hello }");
	checkTemplateParsingError("Hello ${ ( ", "No ending suffix '}' for expression starting at character 6: ${ ( ");
	checkTemplateParsingError("Hello ${ ( }", "Found closing '}' at position 11 but most recent opening is '(' at position 9");
	checkTemplateParsing("#{'Unable to render embedded object: File ({#this == 2}'}", hashes, "Unable to render embedded object: File ({#this == 2}");
	checkTemplateParsing("This is the last odd number in the list: ${listOfNumbersUpToTen.$[#this%2==1]}", dollars, "This is the last odd number in the list: 9");
	checkTemplateParsing("Hello ${'here is a curly bracket }'}", dollars, "Hello here is a curly bracket }");
	checkTemplateParsing("He${'${'}llo ${'here is a curly bracket }'}}", dollars, "He${llo here is a curly bracket }}");
	checkTemplateParsing("Hello ${'()()()}{}{}{][]{}{][}[][][}{()()'} World", dollars, "Hello ()()()}{}{}{][]{}{][}[][][}{()() World");
	checkTemplateParsing("Hello ${'inner literal that''s got {[(])]}an escaped quote in it'} World", "Hello inner literal that's got {[(])]}an escaped quote in it World");
	checkTemplateParsingError("Hello ${", "No ending suffix '}' for expression starting at character 6: ${");
}
 
Example #15
Source File: TemplateAwareExpressionParser.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private Expression parseTemplate(String expressionString, ParserContext context)
		throws ParseException {
	if (expressionString.length() == 0) {
		return new LiteralExpression("");
	}
	Expression[] expressions = parseExpressions(expressionString, context);
	if (expressions.length == 1) {
		return expressions[0];
	}
	else {
		return new CompositeStringExpression(expressionString, expressions);
	}
}
 
Example #16
Source File: TemplateAwareExpressionParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Expression parseTemplate(String expressionString, ParserContext context) throws ParseException {
	if (expressionString.isEmpty()) {
		return new LiteralExpression("");
	}

	Expression[] expressions = parseExpressions(expressionString, context);
	if (expressions.length == 1) {
		return expressions[0];
	}
	else {
		return new CompositeStringExpression(expressionString, expressions);
	}
}
 
Example #17
Source File: TemplateAwareExpressionParser.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private Expression parseTemplate(String expressionString, ParserContext context) throws ParseException {
	if (expressionString.isEmpty()) {
		return new LiteralExpression("");
	}

	Expression[] expressions = parseExpressions(expressionString, context);
	if (expressions.length == 1) {
		return expressions[0];
	}
	else {
		return new CompositeStringExpression(expressionString, expressions);
	}
}
 
Example #18
Source File: TemplateAwareExpressionParser.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Expression parseExpression(String expressionString, @Nullable ParserContext context) throws ParseException {
	if (context != null && context.isTemplate()) {
		return parseTemplate(expressionString, context);
	}
	else {
		return doParseExpression(expressionString, context);
	}
}
 
Example #19
Source File: ArangoTemplate.java    From spring-data with Apache License 2.0 5 votes vote down vote up
public ArangoTemplate(final ArangoDB arango, final String database, final ArangoConverter converter,
	final PersistenceExceptionTranslator exceptionTranslator) {
	super();
	this.arango = arango._setCursorInitializer(new ArangoCursorInitializer(converter));
	this.databaseName = database;
	this.databaseExpression = PARSER.parseExpression(databaseName, ParserContext.TEMPLATE_EXPRESSION);
	this.converter = converter;
	this.exceptionTranslator = exceptionTranslator;
	this.context = new StandardEvaluationContext();
	// set concurrency level to 1 as writes are very rare compared to reads
	collectionCache = new ConcurrentHashMap<>(8, 0.9f, 1);
	databaseCache = new ConcurrentHashMap<>(8, 0.9f, 1);
	version = null;
}
 
Example #20
Source File: DataManager.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private boolean canLoad(ModelData<?> modelData) {
    if (this.environment != null && modelData.getCondition() != null) {
        ExpressionParser parser = new SpelExpressionParser();
        Expression ex = parser.parseExpression(modelData.getCondition(), ParserContext.TEMPLATE_EXPRESSION);
        return Optional.ofNullable(ex.getValue(this.environment, Boolean.class)).orElse(false);
    }
    return true;
}
 
Example #21
Source File: ConfigurationResolver.java    From vividus with Apache License 2.0 5 votes vote down vote up
private static void resolveSpelExpressions(Properties properties, boolean ignoreValuesWithPropertyPlaceholders)
{
    Optional<Set<String>> propertyPlaceholders = ignoreValuesWithPropertyPlaceholders
            ? Optional.of(properties.stringPropertyNames().stream()
                    .map(n -> PLACEHOLDER_PREFIX + n + PLACEHOLDER_SUFFIX)
                    .collect(Collectors.toSet()))
            : Optional.empty();

    SpelExpressionParser spelExpressionParser = new SpelExpressionParser();
    for (Entry<Object, Object> entry : properties.entrySet())
    {
        String value = (String) entry.getValue();
        if (propertyPlaceholders.stream().flatMap(Set::stream).noneMatch(value::contains))
        {
            try
            {
                entry.setValue(
                        spelExpressionParser.parseExpression(value, ParserContext.TEMPLATE_EXPRESSION).getValue());
            }
            catch (Exception e)
            {
                throw new IllegalStateException("Exception during evaluation of expression " + value
                        + " for property '" + entry.getKey() + "'", e);
            }
        }
    }
}
 
Example #22
Source File: TemplateAwareExpressionParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Expression parseExpression(String expressionString, ParserContext context) throws ParseException {
	if (context == null) {
		context = NON_TEMPLATE_PARSER_CONTEXT;
	}

	if (context.isTemplate()) {
		return parseTemplate(expressionString, context);
	}
	else {
		return doParseExpression(expressionString, context);
	}
}
 
Example #23
Source File: ExpressionBasedStringQuery.java    From spring-data-ebean with Apache License 2.0 5 votes vote down vote up
/**
 * @param query,   the query expression potentially containing a SpEL expression. Must not be {@literal null}.}
 * @param metadata the {@link EntityMetadata} for the given entity. Must not be {@literal null}.
 * @param parser   Must not be {@literal null}.
 * @return
 */
private static String renderQueryIfExpressionOrReturnQuery(String query, EntityMetadata<?> metadata,
                                                           SpelExpressionParser parser) {

    Assert.notNull(query, "query must not be null!");
    Assert.notNull(metadata, "metadata must not be null!");
    Assert.notNull(parser, "parser must not be null!");

    if (!containsExpression(query)) {
        return query;
    }

    StandardEvaluationContext evalContext = new StandardEvaluationContext();
    evalContext.setVariable(ENTITY_NAME, metadata.getJavaType().getName());

    query = potentiallyQuoteExpressionsParameter(query);

    Expression expr = parser.parseExpression(query, ParserContext.TEMPLATE_EXPRESSION);

    String result = expr.getValue(evalContext, String.class);

    if (result == null) {
        return query;
    }

    return potentiallyUnquoteParameterExpressions(result);
}
 
Example #24
Source File: DatastorePersistentEntityImpl.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Nullable
private Expression detectExpression() {
	if (!hasTableName()) {
		return null;
	}

	Expression expression = PARSER.parseExpression(this.kind.name(),
			ParserContext.TEMPLATE_EXPRESSION);

	return (expression instanceof LiteralExpression) ? null : expression;
}
 
Example #25
Source File: SqlSpannerQuery.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private Expression[] detectExpressions(String sql) {
	Expression expression = this.expressionParser.parseExpression(sql,
			ParserContext.TEMPLATE_EXPRESSION);
	if (expression instanceof LiteralExpression) {
		return new Expression[] { expression };
	}
	else if (expression instanceof CompositeStringExpression) {
		return ((CompositeStringExpression) expression).getExpressions();
	}
	else {
		throw new SpannerDataException("Unexpected expression type. "
				+ "Query can either contain no SpEL expressions or have SpEL expressions in the SQL.");
	}
}
 
Example #26
Source File: SpannerPersistentEntityImpl.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Nullable
private Expression detectExpression() {
	if (!hasAnnotatedTableName()) {
		return null;
	}

	Expression expression = PARSER.parseExpression(this.table.name(),
			ParserContext.TEMPLATE_EXPRESSION);

	return (expression instanceof LiteralExpression) ? null : expression;
}
 
Example #27
Source File: TemplateAwareExpressionParser.java    From java-technology-stack with MIT License 5 votes vote down vote up
private Expression parseTemplate(String expressionString, ParserContext context) throws ParseException {
	if (expressionString.isEmpty()) {
		return new LiteralExpression("");
	}

	Expression[] expressions = parseExpressions(expressionString, context);
	if (expressions.length == 1) {
		return expressions[0];
	}
	else {
		return new CompositeStringExpression(expressionString, expressions);
	}
}
 
Example #28
Source File: PagerdutyNotifier.java    From spring-boot-admin with Apache License 2.0 4 votes vote down vote up
public PagerdutyNotifier(InstanceRepository repository, RestTemplate restTemplate) {
	super(repository);
	this.restTemplate = restTemplate;
	this.description = parser.parseExpression(DEFAULT_DESCRIPTION, ParserContext.TEMPLATE_EXPRESSION);
}
 
Example #29
Source File: PagerdutyNotifier.java    From spring-boot-admin with Apache License 2.0 4 votes vote down vote up
public void setDescription(String description) {
	this.description = parser.parseExpression(description, ParserContext.TEMPLATE_EXPRESSION);
}
 
Example #30
Source File: DiscordNotifier.java    From spring-boot-admin with Apache License 2.0 4 votes vote down vote up
public void setMessage(String message) {
	this.message = parser.parseExpression(message, ParserContext.TEMPLATE_EXPRESSION);
}