001package org.unix4j.codegen.loader; 002 003import java.io.File; 004import java.net.MalformedURLException; 005import java.net.URISyntaxException; 006import java.net.URL; 007import java.util.ArrayList; 008import java.util.List; 009 010import fmpp.Engine; 011import fmpp.tdd.DataLoader; 012import freemarker.template.SimpleSequence; 013import freemarker.template.TemplateModel; 014 015/** 016 * A {@link DataLoader} for the fmpp/freemarker codegenerator passing existing 017 * resources to a {@link ResourceBasedDataLoader} for further analysis. The 018 * resource paths as defined by {@link Class#getResourceAsStream(String)} are 019 * expected as input parameters in the arguments list of 020 * {@link #load(Engine, List)}. 021 */ 022public class ResourceDataLoader implements DataLoader { 023 024 private final ResourceBasedDataLoader templateLoader; 025 026 public ResourceDataLoader(ResourceBasedDataLoader templateLoader) { 027 this.templateLoader = templateLoader; 028 } 029 030 @SuppressWarnings("rawtypes") 031 @Override 032 public SimpleSequence load(Engine engine, List args) throws Exception { 033 return loadDataModel(engine, args); 034 } 035 036 private SimpleSequence loadDataModel(Engine engine, List<?> args) throws Exception { 037 final List<TemplateModel> templateModels = new ArrayList<TemplateModel>(); 038 for (int i = 0; i < args.size(); i++) { 039 final String resourceName = args.get(i).toString(); 040 final URL resource = loadResource(engine, resourceName); 041 if (resource != null) { 042 final TemplateModel templateModel = templateLoader.load(resource); 043 if (templateModel != null) { 044 templateModels.add(templateModel); 045 } 046 } else { 047 throw new IllegalArgumentException("resource[" + i + "] not found: " + resourceName); 048 } 049 } 050 return new SimpleSequence(templateModels); 051 } 052 053 public static URL loadResource(Engine engine, String resourceName) throws URISyntaxException, MalformedURLException { 054 if (resourceName != null) { 055 final URL url = ResourceDataLoader.class.getResource(resourceName); 056 if (url != null) { 057 return url; 058 } else { 059 File file = new File(resourceName); 060 if (file.canRead()) { 061 return file.toURI().toURL(); 062 } 063 file = new File(engine.getDataRoot(), resourceName); 064 if (file.canRead()) { 065 return file.toURI().toURL(); 066 } 067 } 068 } 069 return null; 070 } 071 072}