I try to learn SpEL but one of my script doesn't work. My script is:
changePages(#{T(StoryContent).pages}, (x, y) -> x.replaceAll(y, x.substring(0, 1) + '...' + x.substring(x.length() - 1, x.length())))
Java Code:
public void validate(Story story, List<StoryRule> rules) throws NoSuchMethodException, SecurityException {
StoryContent storyContent = storyContentRepository.findOne(story.getContentId());
story.setStatus(SchedulerStatus.VALIDATION);
storyRepository.save(story);
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext inventorContext = new StandardEvaluationContext(storyContent);
inventorContext.registerFunction("changePages", ValidationByRuleServiceImpl.class
.getDeclaredMethod("changePages", new Class[] { List.class, BiFunction.class }));
try {
rules.stream().map(StoryRule::getScript)
.forEach(script -> parser.parseExpression(script).getValue(inventorContext));
if (!storyContent.getTitle().equals(story.getName()))
story.setName(storyContent.getTitle());
story.setStatus(SchedulerStatus.PUBLISHED);
storyContentRepository.save(storyContent);
} catch (Exception e) {
LOG.error(e.getMessage());
story.setStatus(SchedulerStatus.ERROR);
} finally {
storyRepository.save(story);
}
}
private void changePages(List<String> pages, BiFunction<String, String, String> function) {
pages.forEach(System.out::println);
}
Error is:
Expression [changePages(T(StoryContent).pages, (x, y) -> x.replaceAll(y, x.substring(0, 1) + '...' + x.substring(x.length() - 1, x.length())))] @37: EL1043E: Unexpected token. Expected 'rparen())' but was 'comma(,)'
I get List of SpEL scripts from DB.
I don't know what is wrong, my script or my java code?
SpEL is not Java, it's a different language; the acronym stands for Spring Expression Language.
It doesn't understand Java8 lambdas so can't parse (x, y) -> ...
.
You can, however, register lambdas as SpEL functions, see my answer here.