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  public final class FacesServlet implements Servlet
45  {
46      //private static final Log log = LogFactory.getLog(FacesServlet.class);
47      private static final Logger log = Logger.getLogger(FacesServlet.class.getName());
48      
49      /**
50       * Comma separated list of URIs of (additional) faces config files.
51       * (e.g. /WEB-INF/my-config.xml)See JSF 1.0 PRD2, 10.3.2
52       * Attention: You do not need to put /WEB-INF/faces-config.xml in here.
53       */
54      @JSFWebConfigParam(since="1.1")
55      public static final String CONFIG_FILES_ATTR = "javax.faces.CONFIG_FILES";
56  
57      /**
58       * Identify the Lifecycle instance to be used.
59       */
60      @JSFWebConfigParam(since="1.1")
61      public static final String LIFECYCLE_ID_ATTR = "javax.faces.LIFECYCLE_ID";
62  
63      private static final String SERVLET_INFO = "FacesServlet of the MyFaces API implementation";
64      
65      private ServletConfig _servletConfig;
66      private FacesContextFactory _facesContextFactory;
67      private Lifecycle _lifecycle;
68  
69      public FacesServlet()
70      {
71          super();
72      }
73  
74      public void destroy()
75      {
76          _servletConfig = null;
77          _facesContextFactory = null;
78          _lifecycle = null;
79          if (log.isLoggable(Level.FINEST))
80          {
81              log.finest("destroy");
82          }
83      }
84  
85      public ServletConfig getServletConfig()
86      {
87          return _servletConfig;
88      }
89  
90      public String getServletInfo()
91      {
92          return SERVLET_INFO;
93      }
94  
95      private String getLifecycleId()
96      {
97          // 1. check for Servlet's init-param
98          // 2. check for global context parameter
99          // 3. use default Lifecycle Id, if none of them was provided
100         String serLifecycleId = _servletConfig.getInitParameter(LIFECYCLE_ID_ATTR);
101         String appLifecycleId = _servletConfig.getServletContext().getInitParameter(LIFECYCLE_ID_ATTR);
102         appLifecycleId = serLifecycleId == null ? appLifecycleId : serLifecycleId;
103         return appLifecycleId != null ? appLifecycleId : LifecycleFactory.DEFAULT_LIFECYCLE;
104     }
105 
106     public void init(ServletConfig servletConfig) throws ServletException
107     {
108         if (log.isLoggable(Level.FINEST))
109         {
110             log.finest("init begin");
111         }
112         _servletConfig = servletConfig;
113         _facesContextFactory = (FacesContextFactory)FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
114         // TODO: null-check for Weblogic, that tries to initialize Servlet before ContextListener
115 
116         // Javadoc says: Lifecycle instance is shared across multiple simultaneous requests, it must be implemented in a
117         // thread-safe manner.
118         // So we can acquire it here once:
119         LifecycleFactory lifecycleFactory = (LifecycleFactory)FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
120         _lifecycle = lifecycleFactory.getLifecycle(getLifecycleId());
121         if (log.isLoggable(Level.FINEST))
122         {
123             log.finest("init end");
124         }
125     }
126 
127     public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException
128     {
129         // If the request and response arguments to this method are not instances of HttpServletRequest and 
130         // HttpServletResponse, respectively, the results of invoking this method are undefined.
131         // In this case ClassCastException
132         HttpServletRequest httpRequest = (HttpServletRequest)request;
133         String pathInfo = httpRequest.getPathInfo();
134 
135         // if it is a prefix mapping ...
136         
137         /*
138          * This method must respond to requests that start with the following strings by invoking the sendError 
139          * method on the response argument (cast to HttpServletResponse), passing the code 
140          * HttpServletResponse.SC_NOT_FOUND as the argument.
141          * 
142          *       /WEB-INF/
143          *       /WEB-INF
144          *       /META-INF/
145          *       /META-INF
146          */
147         if (pathInfo != null && (pathInfo.startsWith("/WEB-INF") || pathInfo.startsWith("/META-INF")))
148         {
149             StringBuffer buffer = new StringBuffer();
150 
151             buffer.append(" Someone is trying to access a secure resource : ").append(pathInfo);
152             buffer.append("\n remote address is ").append(httpRequest.getRemoteAddr());
153             buffer.append("\n remote host is ").append(httpRequest.getRemoteHost());
154             buffer.append("\n remote user is ").append(httpRequest.getRemoteUser());
155             buffer.append("\n request URI is ").append(httpRequest.getRequestURI());
156 
157             log.warning(buffer.toString());
158 
159             // Why does RI return a 404 and not a 403, SC_FORBIDDEN ?
160 
161             ((HttpServletResponse)response).sendError(HttpServletResponse.SC_NOT_FOUND);
162             return;
163         }
164         
165         // If none of the cases described above in the specification for this method apply to the servicing of this 
166         // request, the following action must be taken to service the request:
167         if (log.isLoggable(Level.FINEST))
168         {
169             log.finest("service begin");
170         }
171 
172         // Acquire a FacesContext instance for this request.
173         FacesContext facesContext = prepareFacesContext(request, response);
174 
175         try
176         {
177             // jsf 2.0 : get the current ResourceHandler and
178             // check if it is a resource request, if true
179             // delegate to ResourceHandler, else continue with
180             // the lifecycle.
181             // Acquire the ResourceHandler for this request by calling Application.getResourceHandler(). 
182             ResourceHandler resourceHandler = facesContext.getApplication().getResourceHandler();
183 
184             // Call ResourceHandler.isResourceRequest(javax.faces.context.FacesContext).
185             if (resourceHandler.isResourceRequest(facesContext))
186             {
187                 // If this returns true call ResourceHandler.handleResourceRequest(javax.faces.context.FacesContext).
188                 resourceHandler.handleResourceRequest(facesContext);
189             }
190             else
191             {
192                 //JSF 2.2: attach window
193                 _lifecycle.attachWindow(facesContext);
194                 // If this returns false, handle as follows:
195                 // call Lifecycle.execute(javax.faces.context.FacesContext)
196                 _lifecycle.execute(facesContext);
197                 // followed by Lifecycle.render(javax.faces.context.FacesContext).
198                 _lifecycle.render(facesContext);
199             }
200         }
201         catch (FacesException e)
202         {
203             // If a FacesException is thrown in either case
204             
205             // extract the cause from the FacesException
206             Throwable cause = e.getCause();
207             if (cause == null)
208             {
209                 // If the cause is null extract the message from the FacesException, put it inside of a new 
210                 // ServletException instance, and pass the FacesException instance as the root cause, then 
211                 // rethrow the ServletException instance.
212                 throw new ServletException(e.getLocalizedMessage(), e);
213             }
214             else if (cause instanceof ServletException)
215             {
216                 // If the cause is an instance of ServletException, rethrow the cause.
217                 throw (ServletException)cause;
218             }
219             else if (cause instanceof IOException)
220             {
221                 // If the cause is an instance of IOException, rethrow the cause.
222                 throw (IOException)cause;
223             }
224             else
225             {
226                 // Otherwise, create a new ServletException instance, passing the message from the cause, 
227                 // as the first argument, and the cause itself as the second argument. 
228                 throw new ServletException(cause.getLocalizedMessage(), cause);
229             }
230         }
231         finally
232         {
233             // In a finally block, FacesContext.release() must be called. 
234             facesContext.release();
235         }
236         if (log.isLoggable(Level.FINEST))
237         {
238             log.finest("service end");
239         }
240     }
241 
242     private FacesContext prepareFacesContext(ServletRequest request, ServletResponse response)
243     {
244         FacesContext facesContext =
245                 _facesContextFactory.getFacesContext(_servletConfig.getServletContext(), request, response, _lifecycle);
246         return facesContext;
247     }
248 }