*/
private void performSubstitutionInTrigger(Trigger trigger) throws VariableResolutionException {
Iterator it = trigger.getPayload().iterator();
while (it.hasNext()) {
Statement statement = (Statement) it.next();
String key = (String) statement.getAttribute();
String propertyValue = (String) statement.getValue();
for (final String PREFIX : prefixes) {
Pattern pattern = Pattern.compile("@" + PREFIX + "[.A-Za-z0-9_-]*\\b(#)?"); //find any @token
Matcher matcher = pattern.matcher(propertyValue);
StringBuffer result = new StringBuffer(propertyValue.length());
while (matcher.find()) {
matcher.appendReplacement(result, "");
String tokenKey = matcher.group();
if (tokenKey.endsWith("#")) {
tokenKey = tokenKey.substring(0, tokenKey.length() - 1); //cutting out the optional last '#'
}
tokenKey =
tokenKey.substring(1,
tokenKey.length()); //cutting out the first char '@'
String tokenValue = trigger.getPayload().getStatementValue(tokenKey);
if (tokenValue == null) {
throw new VariableResolutionException("Variable '" + tokenValue + "' cannot be resolved in trigger '"
+ trigger.getName() + "'.\n" + "Availabe tokens are: "
+ context.toString());
}
//replace an @token.property with its real value
//System.out.println("Replace all " + tokenKey + " with " + tokenValue + " in " + propertyValue);
result.append(tokenValue);
}
matcher.appendTail(result);
statement.setValue(result.toString());
}
//all references are replaced with real values in the current statement, now perform scripting
String possibleScript = (String) statement.getValue().trim();
boolean success = false;
if (possibleScript.startsWith("=")) {
//this is a javascript
try {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine js = mgr.getEngineByName("JavaScript");
//removing equal sign on the head
String script = possibleScript.substring(1);
if (js == null) {
LOG.severe("Cannot instatiate a JavaScript engine");
}
try {
js.eval(script);
} catch (ScriptException scriptException) {
LOG.severe(scriptException.getMessage());
}
if (js.get(key) == null) {
LOG.log(Level.SEVERE,
"Script evaluation in trigger ''{0}'' has returned a null value, maybe the key ''{1}'' is not evaluated properly.",
new Object[]{trigger.getName(), key});
}
statement.setValue(js.get(key).toString());
success = true;
} catch (Exception ex) {
success = false;
LOG.severe(ex.getMessage());
}
}
if (!success) {
//fall back to the value before scripting evaluation
statement.setValue(possibleScript);
}
}
}