View Javadoc
1   /**
2    * This file Copyright (c) 2003-2015 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.context;
35  
36  import info.magnolia.cms.beans.runtime.MultipartForm;
37  import info.magnolia.cms.core.AggregationState;
38  import info.magnolia.objectfactory.Components;
39  
40  import java.io.IOException;
41  import java.io.Writer;
42  import java.util.Enumeration;
43  import java.util.HashMap;
44  import java.util.Map;
45  import java.util.Stack;
46  
47  import javax.servlet.ServletContext;
48  import javax.servlet.ServletException;
49  import javax.servlet.ServletRequest;
50  import javax.servlet.http.HttpServletRequest;
51  import javax.servlet.http.HttpServletResponse;
52  import javax.servlet.http.HttpSession;
53  import javax.servlet.jsp.PageContext;
54  
55  
56  /**
57   * Context implementation keeping track of the current request, response, servletContext and pageContext.
58   */
59  public abstract class WebContextImpl extends UserContextImpl implements WebContext {
60      private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(WebContextImpl.class);
61  
62      private HttpServletRequest request;
63  
64      private HttpServletResponse response;
65  
66      private ServletContext servletContext;
67  
68      /**
69       * the jsp page context.
70       */
71      private PageContext pageContext;
72  
73      protected AggregationState aggregationState;
74  
75      private Stack<HttpServletResponse> responseStack = new Stack<HttpServletResponse>();
76  
77      private Stack<HttpServletRequest> requestStack = new Stack<HttpServletRequest>();
78  
79      /**
80       * Use init to initialize the object.
81       */
82      public WebContextImpl() {
83          log.debug("new WebContextImpl() {}", this);
84      }
85  
86      @Override
87      public void init(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) {
88          this.request = request;
89          this.response = response;
90          this.servletContext = servletContext;
91          //reset();
92          //setUser(getAnonymousUser());
93          setAttributeStrategy(new RequestAttributeStrategy(this));
94          setRepositoryStrategy(createRepositoryStrategy());
95      }
96  
97      private DefaultRepositoryStrategy createRepositoryStrategy() {
98          return Components.newInstance(DefaultRepositoryStrategy.class, this);
99      }
100 
101     @Override
102     public AggregationState getAggregationState() {
103         if (aggregationState == null) {
104             aggregationState = newAggregationState();
105         }
106         return aggregationState;
107     }
108 
109     /**
110      * @see info.magnolia.context.WebContextFactoryImpl#newAggregationState()
111      */
112     protected abstract AggregationState newAggregationState();
113 
114     /**
115      * This will only reset the original URI/URL by calling {@link AggregationState#resetURIs()}.
116      */
117     @Override
118     public void resetAggregationState() {
119         getAggregationState().resetURIs();
120     }
121 
122     /**
123      * Get form object assembled by <code>MultipartRequestFilter</code>.
124      *
125      * @return multipart form object
126      */
127     @Override
128     public MultipartForm getPostedForm() {
129         return (MultipartForm) getAttribute(MultipartForm.REQUEST_ATTRIBUTE_NAME, LOCAL_SCOPE);
130     }
131 
132     /**
133      * Get parameter value as string.
134      *
135      * @return parameter value
136      */
137     @Override
138     public String getParameter(String name) {
139         return this.request.getParameter(name);
140     }
141 
142     /**
143      * Get parameter values as string[].
144      *
145      * @return parameter values
146      */
147     @Override
148     public String[] getParameterValues(String name) {
149         return this.request.getParameterValues(name);
150     }
151 
152     /**
153      * Get parameter values as a Map<String, String> (unlike HttpServletRequest.getParameterMap() which returns a Map<String,
154      * String[]>, so don't expect to retrieve multiple-valued form parameters here).
155      *
156      * @return parameter values
157      */
158     @Override
159     public Map<String, String> getParameters() {
160         Map<String, String> map = new HashMap<String, String>();
161         Enumeration<String> paramEnum = this.request.getParameterNames();
162         while (paramEnum.hasMoreElements()) {
163             final String name = paramEnum.nextElement();
164             map.put(name, this.request.getParameter(name));
165         }
166         return map;
167     }
168 
169     /**
170      * Avoid the call to this method where ever possible.
171      *
172      * @return Returns the request.
173      */
174     @Override
175     public HttpServletRequest getRequest() {
176         return this.request;
177     }
178 
179     @Override
180     public HttpServletResponse getResponse() {
181         return response;
182     }
183 
184     @Override
185     public String getContextPath() {
186         return this.request.getContextPath();
187     }
188 
189     /**
190      * Does an include using the request that was set when setting up this context, or using the
191      * request wrapped by the pageContext if existing.
192      */
193     @Override
194     public void include(final String path, final Writer out) throws ServletException, IOException {
195         try {
196             final ServletRequest requestToUse = /*pageContext != null ? pageContext.getRequest() :*/ this.getRequest();
197             final HttpServletResponse responseToUse = /*(pageContext != null && pageContext.getResponse() instanceof HttpServletResponse) ? (HttpServletResponse) pageContext.getResponse() :*/ response;
198             final WriterResponseWrapper wrappedResponse = new WriterResponseWrapper(responseToUse, out);
199 
200             requestToUse.getRequestDispatcher(path).include(requestToUse, wrappedResponse);
201         } catch (ServletException e) {
202             throw new RuntimeException(e);
203         } catch (IOException e) {
204             throw new RuntimeException(e);
205         }
206     }
207 
208     /**
209      * {@inheritDoc}
210      */
211     @Override
212     public PageContext getPageContext() {
213         return pageContext;
214     }
215 
216     /**
217      * {@inheritDoc}
218      */
219     @Override
220     public void setPageContext(PageContext pageContext) {
221         this.pageContext = pageContext;
222     }
223 
224     /**
225      * {@inheritDoc}
226      */
227     @Override
228     public ServletContext getServletContext() {
229         return servletContext;
230     }
231 
232     public void login() {
233         setRepositoryStrategy(createRepositoryStrategy());
234     }
235 
236     /**
237      * Closes opened JCR sessions and invalidates the current HttpSession.
238      *
239      * @see #release()
240      */
241     @Override
242     public void logout() {
243         releaseJCRSessions();
244         super.logout();
245 
246         HttpSession session = this.request.getSession(false);
247         if (session != null) {
248             session.invalidate();
249         }
250     }
251 
252     /**
253      * Closes opened JCR sessions.
254      */
255     @Override
256     public void release() {
257         releaseJCRSessions();
258         this.request = null;
259         this.response = null;
260     }
261 
262     protected void releaseJCRSessions() {
263         getRepositoryStrategy().release();
264     }
265 
266     /* (non-Javadoc)
267      * @see info.magnolia.context.WebContext#pop()
268      */
269     @Override
270     public void pop() {
271         request = requestStack.pop();
272         response = responseStack.pop();
273     }
274 
275     /* (non-Javadoc)
276      * @see info.magnolia.context.WebContext#push(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
277      */
278     @Override
279     public void push(HttpServletRequest request, HttpServletResponse response) {
280         requestStack.push(this.request);
281         this.request = request;
282         responseStack.push(this.response);
283         this.response = response;
284     }
285 }