use of freemarker.ext.xml.NodeListModel in project freemarker by apache.
the class FreemarkerXmlTask method process.
/**
* Process an XML file using FreeMarker
*/
private void process(File baseDir, String xmlFile, File destDir) throws BuildException {
File outFile = null;
File inFile = null;
try {
// the current input file relative to the baseDir
inFile = new File(baseDir, xmlFile);
// the output file relative to basedir
outFile = new File(destDir, xmlFile.substring(0, xmlFile.lastIndexOf('.')) + extension);
// only process files that have changed
if (!incremental || (inFile.lastModified() > outFile.lastModified() || templateFileLastModified > outFile.lastModified() || projectFileLastModified > outFile.lastModified())) {
ensureDirectoryFor(outFile);
// -- command line status
log("Input: " + xmlFile, Project.MSG_INFO);
if (projectTemplate == null && projectFile != null) {
Document doc = builder.parse(projectFile);
projectTemplate = new NodeListModel(builder.parse(projectFile));
projectNode = NodeModel.wrap(doc);
}
// Build the file DOM
Document docNode = builder.parse(inFile);
TemplateModel document = new NodeListModel(docNode);
TemplateNodeModel docNodeModel = NodeModel.wrap(docNode);
HashMap root = new HashMap();
root.put("document", document);
insertDefaults(root);
// Process the template and write out
// the result as the outFile.
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), encoding));
try {
if (parsedTemplate == null) {
throw new BuildException("No template file specified in build script or in XML file");
}
if (prepareModel != null) {
Map vars = new HashMap();
vars.put("model", root);
vars.put("doc", docNode);
if (projectNode != null) {
vars.put("project", ((NodeModel) projectNode).getNode());
}
prepareModel.execute(vars);
}
freemarker.core.Environment env = parsedTemplate.createProcessingEnvironment(root, writer);
env.setCurrentVisitorNode(docNodeModel);
if (prepareEnvironment != null) {
Map vars = new HashMap();
vars.put("env", env);
vars.put("doc", docNode);
if (projectNode != null) {
vars.put("project", ((NodeModel) projectNode).getNode());
}
prepareEnvironment.execute(vars);
}
env.process();
writer.flush();
} finally {
writer.close();
}
log("Output: " + outFile, Project.MSG_INFO);
}
} catch (SAXParseException spe) {
Throwable rootCause = spe;
if (spe.getException() != null)
rootCause = spe.getException();
log("XML parsing error in " + inFile.getAbsolutePath(), Project.MSG_ERR);
log("Line number " + spe.getLineNumber());
log("Column number " + spe.getColumnNumber());
throw new BuildException(rootCause, getLocation());
} catch (Throwable e) {
if (outFile != null) {
if (!outFile.delete() && outFile.exists()) {
log("Failed to delete " + outFile, Project.MSG_WARN);
}
}
e.printStackTrace();
throw new BuildException(e, getLocation());
}
}
Aggregations