View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package javax.faces.webapp;
20  
21  import java.io.IOException;
22  import java.util.logging.Level;
23  import java.util.logging.Logger;
24  
25  import javax.faces.FacesException;
26  import javax.faces.FactoryFinder;
27  import javax.faces.application.ResourceHandler;
28  import javax.faces.context.FacesContext;
29  import javax.faces.context.FacesContextFactory;
30  import javax.faces.lifecycle.Lifecycle;
31  import javax.faces.lifecycle.LifecycleFactory;
32  import javax.servlet.Servlet;
33  import javax.servlet.ServletConfig;
34  import javax.servlet.ServletException;
35  import javax.servlet.ServletRequest;
36  import javax.servlet.ServletResponse;
37  import javax.servlet.http.HttpServletRequest;
38  import javax.servlet.http.HttpServletResponse;
39  
40  import org.apache.myfaces.buildtools.maven2.plugin.builder.annotation.JSFWebConfigParam;
41  /**
42   * see Javadoc of <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/index.html">JSF Specification</a>
43   * 
44   * @author Manfred Geiler (latest modification by $Author: bommel $)
45   * @version $Revision: 1187700 $ $Date: 2011-10-22 07:19:37 -0500 (Sat, 22 Oct 2011) $
46   */
47  public final class FacesServlet implements Servlet
48  {
49      //private static final Log log = LogFactory.getLog(FacesServlet.class);
50      private static final Logger log = Logger.getLogger(FacesServlet.class.getName());
51      
52      /**
53       * Comma separated list of URIs of (additional) faces config files.
54       * (e.g. /WEB-INF/my-config.xml)See JSF 1.0 PRD2, 10.3.2
55       * Attention: You do not need to put /WEB-INF/faces-config.xml in here.
56       */
57      @JSFWebConfigParam(since="1.1")
58      public static final String CONFIG_FILES_ATTR = "javax.faces.CONFIG_FILES";
59  
60      /**
61       * Identify the Lifecycle instance to be used.
62       */
63      @JSFWebConfigParam(since="1.1")
64      public static final String LIFECYCLE_ID_ATTR = "javax.faces.LIFECYCLE_ID";
65  
66      private static final String SERVLET_INFO = "FacesServlet of the MyFaces API implementation";
67      
68      private ServletConfig _servletConfig;
69      private FacesContextFactory _facesContextFactory;
70      private Lifecycle _lifecycle;
71  
72      public FacesServlet()
73      {
74          super();
75      }
76  
77      public void destroy()
78      {
79          _servletConfig = null;
80          _facesContextFactory = null;
81          _lifecycle = null;
82          if (log.isLoggable(Level.FINEST))
83              log.finest("destroy");
84      }
85  
86      public ServletConfig getServletConfig()
87      {
88          return _servletConfig;
89      }
90  
91      public String getServletInfo()
92      {
93          return SERVLET_INFO;
94      }
95  
96      private String getLifecycleId()
97      {
98          // 1. check for Servlet's init-param
99          // 2. check for global context parameter
100         // 3. use default Lifecycle Id, if none of them was provided
101         String serLifecycleId = _servletConfig.getInitParameter(LIFECYCLE_ID_ATTR);
102         String appLifecycleId = _servletConfig.getServletContext().getInitParameter(LIFECYCLE_ID_ATTR);
103         appLifecycleId = serLifecycleId == null ? appLifecycleId : serLifecycleId;
104         return appLifecycleId != null ? appLifecycleId : LifecycleFactory.DEFAULT_LIFECYCLE;
105     }
106 
107     public void init(ServletConfig servletConfig) throws ServletException
108     {
109         if (log.isLoggable(Level.FINEST))
110             log.finest("init begin");
111         _servletConfig = servletConfig;
112         _facesContextFactory = (FacesContextFactory)FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
113         // TODO: null-check for Weblogic, that tries to initialize Servlet before ContextListener
114 
115         // Javadoc says: Lifecycle instance is shared across multiple simultaneous requests, it must be implemented in a
116         // thread-safe manner.
117         // So we can acquire it here once:
118         LifecycleFactory lifecycleFactory = (LifecycleFactory)FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
119         _lifecycle = lifecycleFactory.getLifecycle(getLifecycleId());
120         if (log.isLoggable(Level.FINEST))
121             log.finest("init end");
122     }
123 
124     public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException
125     {
126         // If the request and response arguments to this method are not instances of HttpServletRequest and 
127         // HttpServletResponse, respectively, the results of invoking this method are undefined.
128         // In this case ClassCastException
129         HttpServletRequest httpRequest = (HttpServletRequest)request;
130         String pathInfo = httpRequest.getPathInfo();
131 
132         // if it is a prefix mapping ...
133         
134         /*
135          * This method must respond to requests that start with the following strings by invoking the sendError 
136          * method on the response argument (cast to HttpServletResponse), passing the code 
137          * HttpServletResponse.SC_NOT_FOUND as the argument.
138          * 
139          *       /WEB-INF/
140          *       /WEB-INF
141          *       /META-INF/
142          *       /META-INF
143          */
144         if (pathInfo != null && (pathInfo.startsWith("/WEB-INF") || pathInfo.startsWith("/META-INF")))
145         {
146             StringBuffer buffer = new StringBuffer();
147 
148             buffer.append(" Someone is trying to access a secure resource : ").append(pathInfo);
149             buffer.append("\n remote address is ").append(httpRequest.getRemoteAddr());
150             buffer.append("\n remote host is ").append(httpRequest.getRemoteHost());
151             buffer.append("\n remote user is ").append(httpRequest.getRemoteUser());
152             buffer.append("\n request URI is ").append(httpRequest.getRequestURI());
153 
154             log.warning(buffer.toString());
155 
156             // Why does RI return a 404 and not a 403, SC_FORBIDDEN ?
157 
158             ((HttpServletResponse)response).sendError(HttpServletResponse.SC_NOT_FOUND);
159             return;
160         }
161         
162         // If none of the cases described above in the specification for this method apply to the servicing of this 
163         // request, the following action must be taken to service the request:
164         if (log.isLoggable(Level.FINEST))
165             log.finest("service begin");
166 
167         // Acquire a FacesContext instance for this request.
168         FacesContext facesContext = prepareFacesContext(request, response);
169 
170         try
171         {
172             // jsf 2.0 : get the current ResourceHandler and
173             // check if it is a resource request, if true
174             // delegate to ResourceHandler, else continue with
175             // the lifecycle.
176             // Acquire the ResourceHandler for this request by calling Application.getResourceHandler(). 
177             ResourceHandler resourceHandler = facesContext.getApplication().getResourceHandler();
178 
179             // Call ResourceHandler.isResourceRequest(javax.faces.context.FacesContext).
180             if (resourceHandler.isResourceRequest(facesContext))
181             {
182                 // If this returns true call ResourceHandler.handleResourceRequest(javax.faces.context.FacesContext).
183                 resourceHandler.handleResourceRequest(facesContext);
184             }
185             else
186             {
187                 // If this returns false, handle as follows:
188                 // call Lifecycle.execute(javax.faces.context.FacesContext)
189                 _lifecycle.execute(facesContext);
190                 // followed by Lifecycle.render(javax.faces.context.FacesContext).
191                 _lifecycle.render(facesContext);
192             }
193         }
194         catch (FacesException e)
195         {
196             // If a FacesException is thrown in either case
197             
198             // extract the cause from the FacesException
199             Throwable cause = e.getCause();
200             if (cause == null)
201             {
202                 // If the cause is null extract the message from the FacesException, put it inside of a new 
203                 // ServletException instance, and pass the FacesException instance as the root cause, then 
204                 // rethrow the ServletException instance.
205                 throw new ServletException(e.getLocalizedMessage(), e);
206             }
207             else if (cause instanceof ServletException)
208             {
209                 // If the cause is an instance of ServletException, rethrow the cause.
210                 throw (ServletException)cause;
211             }
212             else if (cause instanceof IOException)
213             {
214                 // If the cause is an instance of IOException, rethrow the cause.
215                 throw (IOException)cause;
216             }
217             else
218             {
219                 // Otherwise, create a new ServletException instance, passing the message from the cause, 
220                 // as the first argument, and the cause itself as the second argument. 
221                 throw new ServletException(cause.getLocalizedMessage(), cause);
222             }
223         }
224         finally
225         {
226             // In a finally block, FacesContext.release() must be called. 
227             facesContext.release();
228         }
229         if (log.isLoggable(Level.FINEST))
230             log.finest("service end");
231     }
232 
233     private FacesContext prepareFacesContext(ServletRequest request, ServletResponse response)
234     {
235         FacesContext facesContext =
236                 _facesContextFactory.getFacesContext(_servletConfig.getServletContext(), request, response, _lifecycle);
237         return facesContext;
238     }
239 }