1 52 53 package com.go.teaservlet; 54 55 import java.lang.reflect.*; 56 import com.go.trove.util.MergedClass; 57 import com.go.trove.util.ClassInjector; 58 import com.go.tea.runtime.Context; 59 import com.go.tea.runtime.TemplateLoader; 60 61 69 class TemplateAdapter extends TemplateLoader { 70 private final Class mContextClass; 71 private final ClassInjector mInjector; 72 73 public TemplateAdapter(Class contextClass, 74 ClassInjector injector, String packagePrefix) { 75 super(injector, packagePrefix); 76 mContextClass = contextClass; 77 mInjector = injector; 78 } 79 80 protected Template loadTemplate(String name) 81 throws ClassNotFoundException , NoSuchMethodException , LinkageError 82 { 83 Template t = super.loadTemplate(name); 84 if (t != null) { 85 Class templateContext = t.getContextType(); 86 if (!templateContext.isAssignableFrom(mContextClass)) { 87 if (!templateContext.isInterface()) { 88 throw new NoSuchMethodException 89 ("Cannot adapt to context " + templateContext + 90 " because it is not an interface."); 91 } 92 93 Constructor ctor = MergedClass.getConstructor 95 (mInjector, new Class [] {mContextClass, templateContext}); 96 97 return new AdaptedTemplate(t, ctor); 98 } 99 } 100 return t; 101 } 102 103 private class AdaptedTemplate implements TemplateLoader.Template { 104 private final Template mTemplate; 105 private final Constructor mContextConstructor; 106 107 public AdaptedTemplate(Template t, Constructor ctor) { 108 mTemplate = t; 109 mContextConstructor = ctor; 110 } 111 112 public TemplateLoader getTemplateLoader() { 113 return TemplateAdapter.this; 114 } 115 116 public String getName() { 117 return mTemplate.getName(); 118 } 119 120 public Class getTemplateClass() { 121 return mTemplate.getTemplateClass(); 122 } 123 124 public Class getContextType() { 125 return mContextConstructor.getDeclaringClass(); 126 } 127 128 public String [] getParameterNames() { 129 return mTemplate.getParameterNames(); 130 } 131 132 public Class [] getParameterTypes() { 133 return mTemplate.getParameterTypes(); 134 } 135 136 public void execute(Context context, Object [] parameters) 137 throws Exception 138 { 139 context = (Context)mContextConstructor.newInstance 141 (new Object [] {context, null}); 142 mTemplate.execute(context, parameters); 143 } 144 145 public String toString() { 146 return mTemplate.toString(); 147 } 148 } 149 } 150 | Popular Tags |