1 18 package org.netbeans.libs.freemarker; 19 20 import freemarker.cache.TemplateLoader; 21 import freemarker.template.Configuration; 22 import freemarker.template.TemplateModel; 23 import freemarker.template.TemplateModelException; 24 import java.io.IOException ; 25 import java.io.InputStreamReader ; 26 import java.io.Reader ; 27 import java.util.Enumeration ; 28 import java.util.LinkedHashSet ; 29 import java.util.Set ; 30 import javax.script.ScriptContext; 31 import org.openide.filesystems.FileObject; 32 import org.openide.filesystems.Repository; 33 import org.openide.util.Exceptions; 34 35 41 42 final class RsrcLoader extends Configuration implements TemplateLoader { 43 private FileObject fo; 44 private ScriptContext map; 45 46 RsrcLoader(FileObject fo, ScriptContext map) { 47 this.fo = fo; 48 this.map = map; 49 setTemplateLoader(this); 50 } 51 52 private FileObject getFile(String name) { 53 FileObject fo = (getFolder() == null) ? null : getFolder().getFileObject(name); 54 return fo; 55 } 56 57 private FileObject getFolder() { 58 return fo != null ? fo.getParent() : Repository.getDefault().getDefaultFileSystem().getRoot(); 59 } 60 61 public Object findTemplateSource(String string) throws IOException { 62 FileObject fo = getFile(string); 63 return fo == null ? null : new Wrap(fo); 64 } 65 66 public long getLastModified(Object object) { 67 return ((Wrap)object).fo.lastModified().getTime(); 68 } 69 70 public Reader getReader(Object object, String encoding) throws IOException { 71 Wrap w = (Wrap)object; 72 if (w.reader == null) { 73 w.reader = new InputStreamReader (w.fo.getInputStream(), encoding); 74 } 75 return w.reader; 76 } 77 78 public void closeTemplateSource(Object object) throws IOException { 79 Wrap w = (Wrap)object; 80 if (w.reader != null) { 81 w.reader.close(); 82 } 83 } 84 85 public Object put(String string, Object object) { 86 assert false; 87 return null; 88 } 89 90 public TemplateModel getSharedVariable(String string) { 91 Object value = map == null ? null : map.getAttribute(string); 92 if (value == null || fo != null) { 93 value = fo.getAttribute(string); 94 } 95 try { 96 return getObjectWrapper().wrap(value); 97 } catch (TemplateModelException ex) { 98 Exceptions.printStackTrace(ex); 99 return null; 100 } 101 } 102 103 public Set getSharedVariableNames() { 104 LinkedHashSet <String > keys = new LinkedHashSet <String >(); 105 106 if (map != null) { 107 keys.addAll(map.getBindings(map.ENGINE_SCOPE).keySet()); 108 } 109 110 if (fo != null) { 111 Enumeration <String > en = fo.getAttributes(); 112 while (en.hasMoreElements()) { 113 keys.add(en.nextElement()); 114 } 115 } 116 117 return keys; 118 } 119 120 private static final class Wrap { 121 public FileObject fo; 122 public Reader reader; 123 124 public Wrap(FileObject fo) { 125 this.fo = fo; 126 } 127 } } 129 | Popular Tags |