Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2014 Attila Szegedi, Daniel Dekany, Jonathan Revusky
   * 
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   * 
   * http://www.apache.org/licenses/LICENSE-2.0
   * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 
 package freemarker.ext.jsp;
 
 import java.io.Writer;
 import java.util.List;
 
 import  javax.servlet.GenericServlet;
 import  javax.servlet.Servlet;
 import  javax.servlet.ServletConfig;
 import  javax.servlet.ServletContext;
 import  javax.servlet.ServletException;
 import  javax.servlet.ServletOutputStream;
 import  javax.servlet.ServletRequest;
 import  javax.servlet.ServletResponse;
 import  javax.servlet.http.HttpServletRequest;
 import  javax.servlet.http.HttpServletResponse;
 import  javax.servlet.http.HttpServletResponseWrapper;
 import  javax.servlet.http.HttpSession;
 import  javax.servlet.jsp.JspWriter;
 import  javax.servlet.jsp.PageContext;
 import  javax.servlet.jsp.tagext.BodyContent;
 
 
 abstract class FreeMarkerPageContext extends PageContext implements TemplateModel
 {
     private static final Class OBJECT_CLASS = Object.class;
         
     private final Environment environment;
     private final int incompatibleImprovements;
     private List tags = new ArrayList();
     private List outs = new ArrayList();
     private final GenericServlet servlet;
     private HttpSession session;
     private final HttpServletRequest request;
     private final HttpServletResponse response;
     private final ObjectWrapper wrapper;
     private final ObjectWrapperAndUnwrapper unwrapper;
     private JspWriter jspOut;
     
     protected FreeMarkerPageContext() throws TemplateModelException
     {
          = Environment.getCurrentEnvironment();
 
         TemplateModel appModel = .getGlobalVariable(
                 .);
         if(!(appModel instanceof ServletContextHashModel)) {
             appModel = .getGlobalVariable(
                     .);
         }
         if(appModel instanceof ServletContextHashModel) {
             this. = ((ServletContextHashModel)appModel).getServlet();
         }
         else {
             throw new  TemplateModelException("Could not find an instance of " + 
                     ServletContextHashModel.class.getName() + 
                     " in the data model under either the name " + 
                    . + " or " + 
                    .);
        }
        
        TemplateModel requestModel = 
        if(!(requestModel instanceof HttpRequestHashModel)) {
            requestModel = .getGlobalVariable(
                    .);
        }
        if(requestModel instanceof HttpRequestHashModel) {
            HttpRequestHashModel reqHash = (HttpRequestHashModel)requestModel;
             = reqHash.getRequest();
             = .getSession(false);
             = reqHash.getResponse();
             = reqHash.getObjectWrapper();
             = this. instanceof ObjectWrapperAndUnwrapper
                    ? (ObjectWrapperAndUnwrapperthis. : null;
        }
        else  {
            throw new  TemplateModelException("Could not find an instance of " + 
                    HttpRequestHashModel.class.getName() + 
                    " in the data model under either the name " + 
                    . + " or " + 
                    .);
        }
        // Register page attributes as per spec
        setAttribute(REQUEST, );
        setAttribute(RESPONSE, );
        if ( != null)
            setAttribute(SESSION, );
        setAttribute(PAGE, );
        setAttribute(CONFIG, .getServletConfig());
        setAttribute(PAGECONTEXT, this);
        setAttribute(APPLICATION, .getServletContext());
    }    
            
        return ;
    }
    
    public void initialize(
        Servlet servlet, ServletRequest request, ServletResponse response,
        String errorPageURLboolean needsSessionint bufferSize
        boolean autoFlush)
    {
        throw new UnsupportedOperationException();
    }
    public void release() {
    }
    public void setAttribute(String nameObject value) {
        setAttribute(namevalue, PAGE_SCOPE);
    }
    public void setAttribute(String nameObject valueint scope) {
        switch(scope) {
            case PAGE_SCOPE: {
                try {
                    .setGlobalVariable(name.wrap(value));
                    break;
                }
                catch(TemplateModelException e) {
                    throw new UndeclaredThrowableException(e);
                }
            }
            case REQUEST_SCOPE: {
                getRequest().setAttribute(namevalue);
                break;
            }
            case SESSION_SCOPE: {
                getSession(true).setAttribute(namevalue);
                break;
            }
            case APPLICATION_SCOPE: {
                getServletContext().setAttribute(namevalue);
                break;
            }
            default: {
                throw new IllegalArgumentException("Invalid scope " + scope);
            }
        }
    }
    public Object getAttribute(String name)
    {
        return getAttribute(name, PAGE_SCOPE);
    }
    public Object getAttribute(String nameint scope)
    {
        switch (scope) {
            case PAGE_SCOPE: {
                try {
                    final TemplateModel tm = .getGlobalNamespace().get(name);
                    if ( >= . &&  != null) {
                        return .unwrap(tm);
                    } else { // Legacy behavior branch
                        if (tm instanceof AdapterTemplateModel) {
                            return ((AdapterTemplateModeltm).getAdaptedObject();
                        }
                        if (tm instanceof WrapperTemplateModel) {
                            return ((WrapperTemplateModel)tm).getWrappedObject();
                        }
                        if (tm instanceof TemplateScalarModel) {
                            return ((TemplateScalarModeltm).getAsString();
                        }
                        if (tm instanceof TemplateNumberModel) {
                            return ((TemplateNumberModeltm).getAsNumber();
                        }
                        if (tm instanceof TemplateBooleanModel) {
                            return Boolean.valueOf(((TemplateBooleanModeltm).getAsBoolean());
                        }
                        if ( >= .
                                && tm instanceof TemplateDateModel) {
                            return ((TemplateDateModeltm).getAsDate();
                        }
                        return tm;
                    }
                }
                catch (TemplateModelException e) {
                    throw new UndeclaredThrowableException("Failed to unwrapp FTL global variable"e);
                }
            }
            case REQUEST_SCOPE: {
                return getRequest().getAttribute(name);
            }
            case SESSION_SCOPE: {
                HttpSession session = getSession(false);
                if(session == null) {
                    return null;
                }
                return session.getAttribute(name);
            }
            case APPLICATION_SCOPE: {
                return getServletContext().getAttribute(name);
            }
            default: {
                throw new IllegalArgumentException("Invalid scope " + scope);
            }
        }
    }
    public Object findAttribute(String name)
    {
        Object retval = getAttribute(name, PAGE_SCOPE);
        if(retval != nullreturn retval;
        retval = getAttribute(name, REQUEST_SCOPE);
        if(retval != nullreturn retval;
        retval = getAttribute(name, SESSION_SCOPE);
        if(retval != nullreturn retval;
        return getAttribute(name, APPLICATION_SCOPE);
    }
    public void removeAttribute(String name) {
        removeAttribute(name, PAGE_SCOPE);
        removeAttribute(name, REQUEST_SCOPE);
        removeAttribute(name, SESSION_SCOPE);
        removeAttribute(name, APPLICATION_SCOPE);
    }
    public void removeAttribute(String nameint scope) {
        switch(scope) {
            case PAGE_SCOPE: {
                .getGlobalNamespace().remove(name);
                break;
            }
            case REQUEST_SCOPE: {
                getRequest().removeAttribute(name);
                break;
            }
            case SESSION_SCOPE: {
                HttpSession session = getSession(false);
                if(session != null) {
                    session.removeAttribute(name);
                }
                break;
            }
            case APPLICATION_SCOPE: {
                getServletContext().removeAttribute(name);
                break;
            }
            default: {
                throw new IllegalArgumentException("Invalid scope: " + scope);
            }
        }
    }
    public int getAttributesScope(String name) {
        if(getAttribute(name, PAGE_SCOPE) != nullreturn PAGE_SCOPE;
        if(getAttribute(name, REQUEST_SCOPE) != nullreturn REQUEST_SCOPE;
        if(getAttribute(name, SESSION_SCOPE) != nullreturn SESSION_SCOPE;
        if(getAttribute(name, APPLICATION_SCOPE) != nullreturn APPLICATION_SCOPE;
        return 0;
    }
    public Enumeration getAttributeNamesInScope(int scope) {
        switch(scope) {
            case PAGE_SCOPE: {
                try {
                    return 
                        new TemplateHashModelExEnumeration(.getGlobalNamespace());
                }
                catch(TemplateModelException e) {
                    throw new UndeclaredThrowableException(e);
                }
            }
            case REQUEST_SCOPE: {
                return getRequest().getAttributeNames();
            }
            case SESSION_SCOPE: {
                HttpSession session = getSession(false);
                if(session != null) {
                    return session.getAttributeNames();
                }
                return Collections.enumeration(.);
            }
            case APPLICATION_SCOPE: {
                return getServletContext().getAttributeNames();
            }
            default: {
                throw new IllegalArgumentException("Invalid scope " + scope);
            }
        }
    }
    public JspWriter getOut() {
        return ;
    }
    private HttpSession getSession(boolean create) {
        if( == null) {
             = .getSession(create);
            if( != null) {
                setAttribute(SESSION, );
            }
        }
        return ;
    }
    public HttpSession getSession() {
        return getSession(false);
    }
    
    public Object getPage() {
        return ;
    }
    public ServletRequest getRequest() {
        return ;
    }
    public ServletResponse getResponse() {
        return ;
    }
    public Exception getException() {
        throw new UnsupportedOperationException();
    }
    public ServletConfig getServletConfig() {
        return .getServletConfig();
    }
    public ServletContext getServletContext() {
        return .getServletContext();
    }
    public void forward(String urlthrows ServletException, IOException {
        //TODO: make sure this is 100% correct by looking at Jasper output 
        .getRequestDispatcher(url).forward();
    }
    public void include(String urlthrows ServletException, IOException {
        .flush();
        .getRequestDispatcher(url).include();
    }
    public void include(String urlboolean flushthrows ServletException, IOException {
        if(flush) {
            .flush();
        }
        final PrintWriter pw = new PrintWriter();
        .getRequestDispatcher(url).include(new HttpServletResponseWrapper() {
            public PrintWriter getWriter() {
                return pw;
            }
            
            public ServletOutputStream getOutputStream() {
                throw new UnsupportedOperationException("JSP-included resource must use getWriter()");
            }
        });
        pw.flush();
    }
    public void handlePageException(Exception e) {
        throw new UnsupportedOperationException();
    }
    public void handlePageException(Throwable e) {
        throw new UnsupportedOperationException();
    }
    public BodyContent pushBody() {
      return (BodyContent)pushWriter(new TagTransformModel.BodyContentImpl(getOut(), true));
  }
  public JspWriter pushBody(Writer w) {
      return pushWriter(new JspWriterAdapter(w));
  }
    public JspWriter popBody() {
        popWriter();
        return (JspWriter) getAttribute(OUT);
    }
    Object peekTopTag(Class tagClass) {
        for (ListIterator iter = .listIterator(.size()); iter.hasPrevious();)
        {
            Object tag = iter.previous();
            if(tagClass.isInstance(tag)) {
                return tag;
            }
        }
        return null;
    }  
    
    void popTopTag() {
        .remove(.size() - 1);
    }  
    void popWriter() {
         = (JspWriter).remove(.size() - 1);
        setAttribute(OUT, );
    }
    
    void pushTopTag(Object tag) {
        .add(tag);
    } 
    
    JspWriter pushWriter(JspWriter out) {
        .add();
         = out;
        setAttribute(OUT, );
        return out;
    } 
    
    private static class TemplateHashModelExEnumeration implements Enumeration {
        private final TemplateModelIterator it;
            
             = hashEx.keys().iterator();
        }
        
        public boolean hasMoreElements() {
            try {
                return .hasNext();
            } catch (TemplateModelException tme) {
                throw new UndeclaredThrowableException(tme);
            }
        }
        
        public Object nextElement() {
            try {
                return ((TemplateScalarModel.next()).getAsString();
            } catch (TemplateModelException tme) {
                throw new UndeclaredThrowableException(tme);
            }
        }
    }
New to GrepCode? Check out our FAQ X