1 52 53 package freemarker.cache; 54 55 import java.io.IOException ; 56 import java.io.Reader ; 57 import java.util.Collections ; 58 import java.util.HashMap ; 59 import java.util.Map ; 60 61 74 public class MultiTemplateLoader implements TemplateLoader 75 { 76 private final TemplateLoader[] loaders; 77 private final Map lastLoaderForName = Collections.synchronizedMap(new HashMap ()); 78 79 83 public MultiTemplateLoader(TemplateLoader[] loaders) 84 { 85 this.loaders = (TemplateLoader[])loaders.clone(); 86 } 87 88 public Object findTemplateSource(String name) 89 throws 90 IOException 91 { 92 TemplateLoader lastLoader = (TemplateLoader)lastLoaderForName.get(name); 95 if(lastLoader != null) 96 { 97 Object source = lastLoader.findTemplateSource(name); 98 if(source != null) 99 { 100 return new MultiSource(source, lastLoader); 101 } 102 } 103 104 for(int i = 0; i < loaders.length; ++i) 109 { 110 TemplateLoader loader = loaders[i]; 111 Object source = loader.findTemplateSource(name); 112 if(source != null) 113 { 114 lastLoaderForName.put(name, loader); 115 return new MultiSource(source, loader); 116 } 117 } 118 119 lastLoaderForName.remove(name); 120 return null; 122 } 123 124 public long getLastModified(Object templateSource) 125 { 126 return ((MultiSource)templateSource).getLastModified(); 127 } 128 129 public Reader getReader(Object templateSource, String encoding) 130 throws 131 IOException 132 { 133 return ((MultiSource)templateSource).getReader(encoding); 134 } 135 136 public void closeTemplateSource(Object templateSource) 137 throws 138 IOException 139 { 140 ((MultiSource)templateSource).close(); 141 } 142 143 148 private static final class MultiSource 149 { 150 private final Object source; 151 private final TemplateLoader loader; 152 153 MultiSource(Object source, TemplateLoader loader) 154 { 155 this.source = source; 156 this.loader = loader; 157 } 158 159 long getLastModified() 160 { 161 return loader.getLastModified(source); 162 } 163 164 Reader getReader(String encoding) 165 throws 166 IOException 167 { 168 return loader.getReader(source, encoding); 169 } 170 171 void close() 172 throws 173 IOException 174 { 175 loader.closeTemplateSource(source); 176 } 177 178 public boolean equals(Object o) { 179 if(o instanceof MultiSource) { 180 MultiSource m = (MultiSource)o; 181 return m.loader.equals(loader) && m.source.equals(source); 182 } 183 return false; 184 } 185 186 public int hashCode() { 187 return loader.hashCode() + 31 * source.hashCode(); 188 } 189 190 public String toString() { 191 return source.toString(); 192 } 193 } 194 } 195 | Popular Tags |