* @throws java.io.IOException
*/
@SuppressWarnings("unchecked")
@Override
public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
TemplateStackModel contextStack = (TemplateStackModel)env.getVariable("context");
if(contextStack == null || contextStack.empty()) {
throw new TemplateModelException("error; no context node available");
}
TemplateNodeModel<Node> context = (TemplateNodeModel<Node>)contextStack.peek();
SimpleScalar pathScalar = (SimpleScalar)params.get("path");
if(pathScalar == null) {
throw new TemplateException("the directive has been called without a path parameter",env);
}
String path = pathScalar.getAsString();
TemplateWrapperModel<Map<String,String>> namespacesWrapped = (TemplateWrapperModel<Map<String,String>>)env.getGlobalVariable("namespaces");
Map<String,String> namespaces;
if(namespacesWrapped == null) {
namespaces = new HashMap<String, String>();
namespacesWrapped = new TemplateWrapperModel<Map<String, String>>(new HashMap<String, String>());
env.setGlobalVariable("namespaces",namespacesWrapped);
} else {
namespaces = namespacesWrapped.getAdaptedObject(Map.class);
}
if(body == null) { // value insertion
if(!path.contains("::")) {
path = path + ":: xsd:string";
}
try {
Collection<?> results = ldpath.pathTransform(context.getNode(),path,namespaces);
if(results.size() > 0) {
Object result = results.iterator().next();
if(result instanceof TemplateNumberModel) {
env.getOut().write(FormatUtil.formatNumber( ((TemplateNumberModel)result).getAsNumber() ));
} else if(result instanceof TemplateDateModel) {
switch (((TemplateDateModel)result).getDateType()) {
case TemplateDateModel.DATE:
env.getOut().write(FormatUtil.formatDate(((TemplateDateModel)result).getAsDate()));
break;
case TemplateDateModel.TIME:
env.getOut().write(FormatUtil.formatTime(((TemplateDateModel)result).getAsDate()));
break;
case TemplateDateModel.DATETIME:
env.getOut().write(FormatUtil.formatDateTime(((TemplateDateModel)result).getAsDate()));
break;
default:
env.getOut().write(FormatUtil.formatDateTime(((TemplateDateModel)result).getAsDate()));
}
} else if(result instanceof TemplateScalarModel) {
env.getOut().write( ((TemplateScalarModel)result).getAsString() );
} else if(result instanceof TemplateBooleanModel) {
env.getOut().write( Boolean.toString(((TemplateBooleanModel)result).getAsBoolean()) );
}
} // else write nothing
} catch (LDPathParseException e) {
throw new TemplateException("invalid path for ldpath directive: "+path,e,env);
}
} else {
try {
for(Node node : ldpath.pathQuery(context.getNode(),path,namespaces)) {
contextStack.push(new TemplateNodeModel<Node>(node, backend));
if(loopVars.length > 0) {
loopVars[0] = new TemplateNodeModel<Node>(node,backend);
}
body.render(env.getOut());
contextStack.pop();
}
} catch(LDPathParseException ex) {
throw new TemplateException("invalid path for ldpath directive: "+path,ex,env);
}