/**
* Copyright 2011 Oliver Buchtala
*
* This file is part of ndogen.
*
* ndogen is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ndogen is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ndogen. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ndogen.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.net.URISyntaxException;
import java.net.URL;
import freemarker.cache.TemplateLoader;
public class DefaultTemplateLoader implements TemplateLoader {
String templateDir;
public DefaultTemplateLoader() {
this("/");
}
public DefaultTemplateLoader(String templateDir) {
super();
this.templateDir = templateDir;
}
@Override
public Object findTemplateSource(String name) throws IOException {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
URL resource = classLoader.getResource(templateDir+name);
File file;
try {
file = new File(resource.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
return file;
}
@Override
public long getLastModified(Object templateSource) {
if (templateSource instanceof File) {
File file = (File) templateSource;
return file.lastModified();
} else {
throw new RuntimeException("Provided resource is incompatible with this loader");
}
}
@Override
public Reader getReader(Object templateSource, String encoding)
throws IOException {
if (templateSource instanceof File) {
// TODO: do not know how to change encoding!
File file = (File) templateSource;
FileReader fileReader = new FileReader(file);
return new BufferedReader(fileReader);
} else {
throw new RuntimeException("Provided resource is incompatible with this loader");
}
}
@Override
public void closeTemplateSource(Object templateSource) throws IOException {
// need to close the delivered Reader???
}
}