org.springframework.expression.ParseException Java Examples

The following examples show how to use org.springframework.expression.ParseException. 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 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 #3
Source File: EvaluationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testCreateListsOnAttemptToIndexNull01() throws EvaluationException, ParseException {
	ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
	Expression e = parser.parseExpression("list[0]");
	TestClass testClass = new TestClass();

	Object o = e.getValue(new StandardEvaluationContext(testClass));
	assertEquals("", o);
	o = parser.parseExpression("list[3]").getValue(new StandardEvaluationContext(testClass));
	assertEquals("", o);
	assertEquals(4, testClass.list.size());

	try {
		o = parser.parseExpression("list2[3]").getValue(new StandardEvaluationContext(testClass));
		fail();
	}
	catch (EvaluationException ee) {
		ee.printStackTrace();
		// success!
	}

	o = parser.parseExpression("foo[3]").getValue(new StandardEvaluationContext(testClass));
	assertEquals("", o);
	assertEquals(4, testClass.getFoo().size());
}
 
Example #4
Source File: ExpressionLanguageScenarioTests.java    From spring4-understanding with Apache License 2.0 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 #5
Source File: ExpressionEvaluator.java    From oneops with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #6
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 #7
Source File: ParsingTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Parse the supplied expression and then create a string representation of the resultant AST, it should be the
 * expected value.
 *
 * @param expression the expression to parse
 * @param expectedStringFormOfAST the expected string form of the AST
 */
public void parseCheck(String expression, String expectedStringFormOfAST) {
	try {
		SpelExpression e = parser.parseRaw(expression);
		if (e != null && !e.toStringAST().equals(expectedStringFormOfAST)) {
			SpelUtilities.printAbstractSyntaxTree(System.err, e);
		}
		if (e == null) {
			fail("Parsed exception was null");
		}
		assertEquals("String form of AST does not match expected output", expectedStringFormOfAST, e.toStringAST());
	}
	catch (ParseException ee) {
		ee.printStackTrace();
		fail("Unexpected Exception: " + ee.getMessage());
	}
}
 
Example #8
Source File: ExpressionLanguageScenarioTests.java    From spring-analysis-note with MIT License 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 | ParseException ex) {
		ex.printStackTrace();
		fail("Unexpected Exception: " + ex.getMessage());
	}
}
 
Example #9
Source File: SetValueTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Call setValue() but expect it to fail.
 */
protected void setValueExpectError(String expression, Object value) {
	try {
		Expression e = parser.parseExpression(expression);
		if (e == null) {
			fail("Parser returned null for expression");
		}
		if (DEBUG) {
			SpelUtilities.printAbstractSyntaxTree(System.out, e);
		}
		StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext();
		e.setValue(lContext, value);
		fail("expected an error");
	}
	catch (ParseException pe) {
		pe.printStackTrace();
		fail("Unexpected Exception: " + pe.getMessage());
	}
	catch (EvaluationException ee) {
		// success!
	}
}
 
Example #10
Source File: SetValueTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
	 * For use when coercion is happening during a setValue().  The expectedValue should be
	 * the coerced form of the value.
	 */
	protected void setValue(String expression, Object value, Object expectedValue) {
		try {
			Expression e = parser.parseExpression(expression);
			if (e == null) {
				fail("Parser returned null for expression");
			}
			if (DEBUG) {
				SpelUtilities.printAbstractSyntaxTree(System.out, e);
			}
			StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext();
			assertTrue("Expression is not writeable but should be", e.isWritable(lContext));
			e.setValue(lContext, value);
			Object a = expectedValue;
			Object b = e.getValue(lContext);
			if (!a.equals(b)) {
				fail("Not the same: ["+a+"] type="+a.getClass()+"  ["+b+"] type="+b.getClass());
//				assertEquals("Retrieved value was not equal to set value", expectedValue, e.getValue(lContext));
			}
		}
		catch (EvaluationException | ParseException ex) {
			ex.printStackTrace();
			fail("Unexpected Exception: " + ex.getMessage());
		}
	}
 
Example #11
Source File: SetValueTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
protected void setValue(String expression, Object value) {
	try {
		Expression e = parser.parseExpression(expression);
		if (e == null) {
			fail("Parser returned null for expression");
		}
		if (DEBUG) {
			SpelUtilities.printAbstractSyntaxTree(System.out, e);
		}
		StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext();
		assertTrue("Expression is not writeable but should be", e.isWritable(lContext));
		e.setValue(lContext, value);
		assertEquals("Retrieved value was not equal to set value", value, e.getValue(lContext,value.getClass()));
	}
	catch (EvaluationException | ParseException ex) {
		ex.printStackTrace();
		fail("Unexpected Exception: " + ex.getMessage());
	}
}
 
Example #12
Source File: SetValueTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Call setValue() but expect it to fail.
 */
protected void setValueExpectError(String expression, Object value) {
	try {
		Expression e = parser.parseExpression(expression);
		if (e == null) {
			fail("Parser returned null for expression");
		}
		if (DEBUG) {
			SpelUtilities.printAbstractSyntaxTree(System.out, e);
		}
		StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext();
		e.setValue(lContext, value);
		fail("expected an error");
	}
	catch (ParseException pe) {
		pe.printStackTrace();
		fail("Unexpected Exception: " + pe.getMessage());
	}
	catch (EvaluationException ee) {
		// success!
	}
}
 
Example #13
Source File: SetValueTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
	 * For use when coercion is happening during a setValue().  The expectedValue should be
	 * the coerced form of the value.
	 */
	protected void setValue(String expression, Object value, Object expectedValue) {
		try {
			Expression e = parser.parseExpression(expression);
			if (e == null) {
				fail("Parser returned null for expression");
			}
			if (DEBUG) {
				SpelUtilities.printAbstractSyntaxTree(System.out, e);
			}
			StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext();
			assertTrue("Expression is not writeable but should be", e.isWritable(lContext));
			e.setValue(lContext, value);
			Object a = expectedValue;
			Object b = e.getValue(lContext);
			if (!a.equals(b)) {
				fail("Not the same: ["+a+"] type="+a.getClass()+"  ["+b+"] type="+b.getClass());
//				assertEquals("Retrieved value was not equal to set value", expectedValue, e.getValue(lContext));
			}
		}
		catch (EvaluationException | ParseException ex) {
			ex.printStackTrace();
			fail("Unexpected Exception: " + ex.getMessage());
		}
	}
 
Example #14
Source File: SetValueTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
protected void setValue(String expression, Object value) {
	try {
		Expression e = parser.parseExpression(expression);
		if (e == null) {
			fail("Parser returned null for expression");
		}
		if (DEBUG) {
			SpelUtilities.printAbstractSyntaxTree(System.out, e);
		}
		StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext();
		assertTrue("Expression is not writeable but should be", e.isWritable(lContext));
		e.setValue(lContext, value);
		assertEquals("Retrieved value was not equal to set value", value, e.getValue(lContext,value.getClass()));
	} catch (EvaluationException ee) {
		ee.printStackTrace();
		fail("Unexpected Exception: " + ee.getMessage());
	} catch (ParseException pe) {
		pe.printStackTrace();
		fail("Unexpected Exception: " + pe.getMessage());
	}
}
 
Example #15
Source File: EvaluationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testCreateListsOnAttemptToIndexNull01() throws EvaluationException, ParseException {
	ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
	Expression e = parser.parseExpression("list[0]");
	TestClass testClass = new TestClass();

	Object o = e.getValue(new StandardEvaluationContext(testClass));
	assertEquals("", o);
	o = parser.parseExpression("list[3]").getValue(new StandardEvaluationContext(testClass));
	assertEquals("", o);
	assertEquals(4, testClass.list.size());

	try {
		o = parser.parseExpression("list2[3]").getValue(new StandardEvaluationContext(testClass));
		fail();
	}
	catch (EvaluationException ee) {
		ee.printStackTrace();
		// success!
	}

	o = parser.parseExpression("foo[3]").getValue(new StandardEvaluationContext(testClass));
	assertEquals("", o);
	assertEquals(4, testClass.getFoo().size());
}
 
Example #16
Source File: SpelParserTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void booleanOperators() throws EvaluationException, ParseException {
	SpelExpression expr = new SpelExpressionParser().parseRaw("true");
	assertEquals(Boolean.TRUE, expr.getValue(Boolean.class));
	expr = new SpelExpressionParser().parseRaw("false");
	assertEquals(Boolean.FALSE, expr.getValue(Boolean.class));
	expr = new SpelExpressionParser().parseRaw("false and false");
	assertEquals(Boolean.FALSE, expr.getValue(Boolean.class));
	expr = new SpelExpressionParser().parseRaw("true and (true or false)");
	assertEquals(Boolean.TRUE, expr.getValue(Boolean.class));
	expr = new SpelExpressionParser().parseRaw("true and true or false");
	assertEquals(Boolean.TRUE, expr.getValue(Boolean.class));
	expr = new SpelExpressionParser().parseRaw("!true");
	assertEquals(Boolean.FALSE, expr.getValue(Boolean.class));
	expr = new SpelExpressionParser().parseRaw("!(false or true)");
	assertEquals(Boolean.FALSE, expr.getValue(Boolean.class));
}
 
Example #17
Source File: SpelParserTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void booleanOperators_symbolic_spr9614() throws EvaluationException, ParseException {
	SpelExpression expr = new SpelExpressionParser().parseRaw("true");
	assertEquals(Boolean.TRUE, expr.getValue(Boolean.class));
	expr = new SpelExpressionParser().parseRaw("false");
	assertEquals(Boolean.FALSE, expr.getValue(Boolean.class));
	expr = new SpelExpressionParser().parseRaw("false && false");
	assertEquals(Boolean.FALSE, expr.getValue(Boolean.class));
	expr = new SpelExpressionParser().parseRaw("true && (true || false)");
	assertEquals(Boolean.TRUE, expr.getValue(Boolean.class));
	expr = new SpelExpressionParser().parseRaw("true && true || false");
	assertEquals(Boolean.TRUE, expr.getValue(Boolean.class));
	expr = new SpelExpressionParser().parseRaw("!true");
	assertEquals(Boolean.FALSE, expr.getValue(Boolean.class));
	expr = new SpelExpressionParser().parseRaw("!(false || true)");
	assertEquals(Boolean.FALSE, expr.getValue(Boolean.class));
}
 
Example #18
Source File: ExpressionLanguageScenarioTests.java    From java-technology-stack with MIT License 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 | ParseException ex) {
		ex.printStackTrace();
		fail("Unexpected Exception: " + ex.getMessage());
	}
}
 
Example #19
Source File: ExpressionLanguageScenarioTests.java    From java-technology-stack with MIT License 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 | ParseException ex) {
		ex.printStackTrace();
		fail("Unexpected Exception: " + ex.getMessage());
	}
}
 
Example #20
Source File: SelectionRulePlanBasedAuthenticationHandler.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public boolean canHandle(AuthenticationContext context) {
    boolean handle = handler.canHandle(context);

    if (!handle) {
        return false;
    }

    try {
        Expression expression = new SpelExpressionParser().parseExpression(
                plan.getSelectionRule().replaceAll(EXPRESSION_REGEX, EXPRESSION_REGEX_SUBSTITUTE));

        StandardEvaluationContext evaluation = new StandardEvaluationContext();
        evaluation.setVariable("request", new EvaluableRequest(context.request()));
        evaluation.setVariable("context", new EvaluableAuthenticationContext(context));

        return expression.getValue(evaluation, Boolean.class);
    } catch (ParseException | EvaluationException ex) {
        return false;
    }
}
 
Example #21
Source File: GenericScope.java    From spring-cloud-commons with Apache License 2.0 6 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 #22
Source File: TemplateAwareExpressionParser.java    From spring4-understanding with Apache License 2.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: EvaluationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropertiesNested03() throws ParseException {
	try {
		new SpelExpressionParser().parseRaw("placeOfBirth.23");
		fail();
	} catch (SpelParseException spe) {
		assertEquals(spe.getMessageCode(), SpelMessage.UNEXPECTED_DATA_AFTER_DOT);
		assertEquals("23", spe.getInserts()[0]);
	}
}
 
Example #24
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 #25
Source File: OperationMapper.java    From syncer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public OperationMapper(OperationMapping mapping) {
  this.mapping = mapping;
  SpelExpressionParser parser = new SpelExpressionParser();
  try {
    keyExpr = parser.parseExpression(mapping.getKey());
    valueExpr = parser.parseExpression(mapping.getValue());
  } catch (ParseException | IllegalStateException e) {
    throw new InvalidConfigException("Fail to parse [mapping] config for [redis] output", e);
  }
}
 
Example #26
Source File: SpelParserTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void arithmeticMultiply1() throws EvaluationException, ParseException {
	SpelExpressionParser parser = new SpelExpressionParser();
	SpelExpression expr = parser.parseRaw("2*3");
	assertNotNull(expr);
	assertNotNull(expr.getAST());
	// printAst(expr.getAST(),0);
	assertEquals(6, expr.getValue());
}
 
Example #27
Source File: FilterGeneratorFactory.java    From circus-train with Apache License 2.0 5 votes vote down vote up
/**
 * check filter and generate more friendly message than CT normally does
 *
 * @param partitionFilter
 */
private void checkSpelFilter(String partitionFilter) {
  LOG.info("Located partition filter expression: {}", partitionFilter);
  try {
    expressionParser.parse(partitionFilter);
  } catch (ParseException e) {
    System.out.println("WARNING: There was a problem parsing your expression. Check above to see what was "
        + "resolved from the YML file to see if it is what you expect.");
    System.out.println("Perhaps you are inadvertently creating a YAML comment with '#{ #'?");
    e.printStackTrace(System.out);
    return;
  }
}
 
Example #28
Source File: Statement.java    From syncer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @return expression execution result, may has null value
 */
@ThreadSafe(des = "immutable class")
public List<Object> execute(SyncData syncData) {
  ArrayList<Object> res = new ArrayList<>();
  for (Expression s : action) {
    try {
      res.add(s.getValue(syncData.getContext()));
    } catch (EvaluationException | ParseException e) {
      logger.error("Invalid expression {} for {}, fail to parse", s.getExpressionString(), syncData, e);
    }
  }
  return res;
}
 
Example #29
Source File: MsgMapper.java    From syncer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public MsgMapper(MsgMapping mapping) {
  includeBefore = mapping.isIncludeBefore();
  SpelExpressionParser parser = new SpelExpressionParser();
  try {
    topic = parser.parseExpression(mapping.getTopic());
  } catch (ParseException | IllegalStateException e) {
    throw new InvalidConfigException("Fail to parse [mapping] config for [redis] output", e);
  }
}
 
Example #30
Source File: AbstractExpressionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Parse the specified expression and ensure the expected message comes out.
 * The message may have inserts and they will be checked if otherProperties is specified.
 * The first entry in otherProperties should always be the position.
 * @param expression the expression to evaluate
 * @param expectedMessage the expected message
 * @param otherProperties the expected inserts within the message
 */
protected void parseAndCheckError(String expression, SpelMessage expectedMessage, Object... otherProperties) {
	try {
		Expression expr = parser.parseExpression(expression);
		SpelUtilities.printAbstractSyntaxTree(System.out, expr);
		fail("Parsing should have failed!");
	}
	catch (ParseException pe) {
		SpelParseException ex = (SpelParseException)pe;
		if (ex.getMessageCode() != expectedMessage) {
			assertEquals("Failed to get expected message", expectedMessage, ex.getMessageCode());
		}
		if (otherProperties != null && otherProperties.length != 0) {
			// first one is expected position of the error within the string
			int pos = ((Integer) otherProperties[0]).intValue();
			assertEquals("Did not get correct position reported in error ", pos, ex.getPosition());
			if (otherProperties.length > 1) {
				// Check inserts match
				Object[] inserts = ex.getInserts();
				if (inserts == null) {
					inserts = new Object[0];
				}
				if (inserts.length < otherProperties.length - 1) {
					fail("Cannot check " + (otherProperties.length - 1) +
							" properties of the exception, it only has " + inserts.length + " inserts");
				}
				for (int i = 1; i < otherProperties.length; i++) {
					if (!inserts[i - 1].equals(otherProperties[i])) {
						fail("Insert does not match, expected '" + otherProperties[i] +
								"' but insert value was '" + inserts[i - 1] + "'");
					}
				}
			}
		}
	}
}