1 package freemarker.ext.jsp; 2 3 import java.lang.reflect.InvocationTargetException; 4 import java.lang.reflect.Method; 5 6 import javax.servlet.jsp.PageContext; 7 8 import freemarker.core.Environment; 9 import freemarker.template.TemplateModel; 10 import freemarker.template.TemplateModelException; 11 import freemarker.template.utility.UndeclaredThrowableException; 12 13 /** 14 * @author Attila Szegedi 15 * @version $Id: PageContextFactory.java,v 1.2 2005/06/11 21:21:09 szegedia Exp $ 16 */ 17 class PageContextFactory { 18 19 private static final Method constructor; 20 21 static { 22 Class impl; 23 try { 24 try { 25 PageContext.class.getMethod("getELContext", (Class[]) null); 26 impl = Class.forName("freemarker.ext.jsp.FreeMarkerPageContext21"); 27 } 28 catch(NoSuchMethodException e1) { 29 try { 30 PageContext.class.getMethod("getExpressionEvaluator", (Class[]) null); 31 impl = Class.forName("freemarker.ext.jsp.FreeMarkerPageContext2"); 32 } 33 catch(NoSuchMethodException e2) { 34 impl = Class.forName("freemarker.ext.jsp.FreeMarkerPageContext1"); 35 } 36 } 37 constructor = impl.getDeclaredMethod("create", (Class[]) null); 38 } 39 catch(ClassNotFoundException e) { 40 throw new NoClassDefFoundError(e.getMessage()); 41 } 42 catch(NoSuchMethodException e) { 43 throw new NoSuchMethodError(e.getMessage()); 44 } 45 } 46 47 static FreeMarkerPageContext getCurrentPageContext() throws TemplateModelException { 48 Environment env = Environment.getCurrentEnvironment(); 49 TemplateModel pageContextModel = env.getGlobalVariable(PageContext.PAGECONTEXT); 50 if(pageContextModel instanceof FreeMarkerPageContext) { 51 return (FreeMarkerPageContext)pageContextModel; 52 } 53 try { 54 FreeMarkerPageContext pageContext = 55 (FreeMarkerPageContext)constructor.invoke(null, null); 56 env.setGlobalVariable(PageContext.PAGECONTEXT, pageContext); 57 return pageContext; 58 } 59 catch(IllegalAccessException e) { 60 throw new IllegalAccessError(e.getMessage()); 61 } 62 catch(InvocationTargetException e) { 63 if(e.getTargetException() instanceof TemplateModelException) { 64 throw (TemplateModelException)e.getTargetException(); 65 } 66 throw new UndeclaredThrowableException(e); 67 } 68 } 69 70 }