01: package freemarker.ext.jsp;
02:
03: import java.lang.reflect.InvocationTargetException;
04: import java.lang.reflect.Method;
05:
06: import javax.servlet.jsp.PageContext;
07:
08: import freemarker.core.Environment;
09: 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("getExpressionEvaluator",
26: null);
27: impl = Class
28: .forName("freemarker.ext.jsp.FreeMarkerPageContext2");
29: } catch (NoSuchMethodException e) {
30: impl = Class
31: .forName("freemarker.ext.jsp.FreeMarkerPageContext1");
32: }
33: constructor = impl.getDeclaredMethod("create", null);
34: } catch (ClassNotFoundException e) {
35: throw new NoClassDefFoundError(e.getMessage());
36: } catch (NoSuchMethodException e) {
37: throw new NoSuchMethodError(e.getMessage());
38: }
39: }
40:
41: static FreeMarkerPageContext getCurrentPageContext()
42: throws TemplateModelException {
43: Environment env = Environment.getCurrentEnvironment();
44: TemplateModel pageContextModel = env
45: .getGlobalVariable(PageContext.PAGECONTEXT);
46: if (pageContextModel instanceof FreeMarkerPageContext) {
47: return (FreeMarkerPageContext) pageContextModel;
48: }
49: try {
50: FreeMarkerPageContext pageContext = (FreeMarkerPageContext) constructor
51: .invoke(null, null);
52: env.setGlobalVariable(PageContext.PAGECONTEXT, pageContext);
53: return pageContext;
54: } catch (IllegalAccessException e) {
55: throw new IllegalAccessError(e.getMessage());
56: } catch (InvocationTargetException e) {
57: if (e.getTargetException() instanceof TemplateModelException) {
58: throw (TemplateModelException) e.getTargetException();
59: }
60: throw new UndeclaredThrowableException(e);
61: }
62: }
63:
64: }
|