Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved.
   *
   * The contents of this file are subject to the terms of either the GNU
   * General Public License Version 2 only ("GPL") or the Common Development
   * and Distribution License("CDDL") (collectively, the "License").  You
   * may not use this file except in compliance with the License.  You can
  * obtain a copy of the License at
  * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
  * or packager/legal/LICENSE.txt.  See the License for the specific
  * language governing permissions and limitations under the License.
  *
  * When distributing the software, include this License Header Notice in each
  * file and include the License file at packager/legal/LICENSE.txt.
  *
  * GPL Classpath Exception:
  * Oracle designates this particular file as subject to the "Classpath"
  * exception as provided by Oracle in the GPL Version 2 section of the License
  * file that accompanied this code.
  *
  * Modifications:
  * If applicable, add the following below the License Header, with the fields
  * enclosed by brackets [] replaced by your own identifying information:
  * "Portions Copyright [year] [name of copyright owner]"
  *
  * Contributor(s):
  * If you wish your version of this file to be governed by only the CDDL or
  * only the GPL Version 2, indicate your decision by adding "[Contributor]
  * elects to include this software in this distribution under the [CDDL or GPL
  * Version 2] license."  If you don't indicate a single choice of license, a
  * recipient has the option to distribute your version of this file under
  * either the CDDL, the GPL Version 2 or to extend the choice of license to
  * its licensees as provided above.  However, if you add GPL Version 2 code
  * and therefore, elected the GPL Version 2 license, then the option applies
  * only if the new code is made subject to such option by the copyright
  * holder.
  */
 
 package javax.faces.webapp;
 
 
 import java.util.Set;
 import java.util.List;
 

FacesServlet is a servlet that manages the request processing lifecycle for web applications that are utilizing JavaServer Faces to construct the user interface.

If the application is running in a Servlet 3.0 (and beyond) container, the runtime must provide an implementation of the javax.servlet.ServletContainerInitializer interface that declares the following classes in its javax.servlet.annotation.HandlesTypes annotation.

This servlet must automatically be mapped if it is not explicitly mapped in web.xml or web-fragment.xml and one or more of the following conditions are true.

  • A faces-config.xml file is found in WEB-INF

  • A faces-config.xml file is found in the META-INF directory of a jar in the application's classpath.

  • A filename ending in .faces-config.xml is found in the META-INF directory of a jar in the application's classpath.

  • The javax.faces.CONFIG_FILES context param is declared in web.xml or web-fragment.xml.

  • The Set of classes passed to the onStartup() method of the ServletContainerInitializer implementation is not empty.

If the runtime determines that the servlet must be automatically mapped, it must be mapped to the following <url-pattern> entries.

  • /faces
  • *.jsf
  • *.faces
public final class FacesServlet implements Servlet {
    /*
     * A white space separated list of case sensitive HTTP method names
     * that are allowed to be processed by this servlet. * means allow all
     */
    private static final String ALLOWED_HTTP_METHODS_ATTR =
            "com.sun.faces.allowedHttpMethods";
    
    // Http method names must be upper case. http://www.w3.org/Protocols/HTTP/NoteMethodCS.html
    // List of valid methods in Http 1.1 http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9
    private enum HttpMethod {
        
        OPTIONS("OPTIONS"),
        GET("GET"),
        HEAD("HEAD"),
        POST("POST"),
        PUT("PUT"),
        DELETE("DELETE"),
        TRACE("TRACE"),
        CONNECT("CONNECT");
        
        private String name;
        
        HttpMethod(String name) {
            this. = name;
        }
        @Override
        public String toString() {
            return ;
        }
        
    }
    final private Set<HttpMethoddefaultAllowedHttpMethods = 
            EnumSet.range(..);
    private Set<HttpMethodallHttpMethods;
    private boolean allowAllMethods;

    

Context initialization parameter name for a comma delimited list of context-relative resource paths (in addition to /WEB-INF/faces-config.xml which is loaded automatically if it exists) containing JavaServer Faces configuration information.

    public static final String CONFIG_FILES_ATTR =
        "javax.faces.CONFIG_FILES";


    

Context initialization parameter name for the lifecycle identifier of the javax.faces.lifecycle.Lifecycle instance to be utilized.

    public static final String LIFECYCLE_ID_ATTR =
        "javax.faces.LIFECYCLE_ID";


    
The Logger for this class.
    private static final Logger LOGGER =
          Logger.getLogger("javax.faces.webapp""javax.faces.LogStrings");


    

Factory for javax.faces.context.FacesContext instances.

    private FacesContextFactory facesContextFactory = null;


    

The javax.faces.lifecycle.Lifecycle instance to use for request processing.

    private Lifecycle lifecycle = null;


    

The ServletConfig instance for this servlet.

    private ServletConfig servletConfig = null;

    
From GLASSFISH-15632. If true, the FacesContext instance left over from startup time has been released.
    private boolean initFacesContextReleased = false;
    

    

Release all resources acquired at startup time.

    public void destroy() {
         = null;
         = null;
         = null;
    }


    

Return the ServletConfig instance for this servlet.

    public ServletConfig getServletConfig() {
        return (this.);
    }


    

Return information about this Servlet.

    public String getServletInfo() {
        return (this.getClass().getName());
    }


    

Acquire the factory instances we will require.

Throws:
javax.servlet.ServletException if, for any reason, the startup of this Faces application failed. This includes errors in the config file that is parsed before or during the processing of this init() method.
    public void init(ServletConfig servletConfigthrows ServletException {
        // Save our ServletConfig instance
        this. = servletConfig;
        // Acquire our FacesContextFactory instance
        try {
             = (FacesContextFactory)
                FactoryFinder.getFactory
                (.);
        } catch (FacesException e) {
            ResourceBundle rb = .getResourceBundle();
            String msg = rb.getString("severe.webapp.facesservlet.init_failed");
            Throwable rootCause = (e.getCause() != null) ? e.getCause() : e;
            .log(.msgrootCause);
            throw new UnavailableException(msg);
        }
        // Acquire our Lifecycle instance
        try {
            LifecycleFactory lifecycleFactory = (LifecycleFactory)
                FactoryFinder.getFactory(.);
            String lifecycleId ;
            // First look in the servlet init-param set
            if (null == (lifecycleId = servletConfig.getInitParameter())) {
                // If not found, look in the context-param set 
                lifecycleId = servletConfig.getServletContext().getInitParameter
                    ();
            }
            if (lifecycleId == null) {
                lifecycleId = .;
            }
             = lifecycleFactory.getLifecycle(lifecycleId);
            initHttpMethodValidityVerification();
        } catch (FacesException e) {
            Throwable rootCause = e.getCause();
            if (rootCause == null) {
                throw e;
            } else {
                throw new ServletException(e.getMessage(), rootCause);
            }
        }
    }
    private void initHttpMethodValidityVerification() {
        assert (null == );
        assert (null != );
        assert (null == );
         = EnumSet.allOf(HttpMethod.class);
        // Configure our permitted HTTP methods
         = Collections.emptySet();
        
        String[] methods;
        String allowedHttpMethodsString = .getServletContext().getInitParameter();
        if (null != allowedHttpMethodsString) {
            methods = allowedHttpMethodsString.split("\\s+");
            assert (null != methods); // assuming split always returns a non-null array result
             = new HashSet(methods.length);
            List<StringallowedKnownHttpMethodsStringList = new ArrayList<String>();
            // validate input against allHttpMethods data structure
            for (String cur : methods) {
                if (cur.equals("*")) {
                     = true;
                     = Collections.emptySet();
                    return;
                }
                boolean isKnownHttpMethod;
                try {
                    HttpMethod.valueOf(cur);
                    isKnownHttpMethod = true;
                } catch (IllegalArgumentException e) {
                    isKnownHttpMethod = false;
                }
                
                if (!isKnownHttpMethod) {
                    if (.isLoggable(.)) {
                        HttpMethod [] values = HttpMethod.values();
                        Object [] arg = new Object[values.length + 1];
                        arg[0] = cur;
                        System.arraycopy(values..ordinal(), 
                                         arg, 1, values.length);
                        .log(.,
                                "warning.webapp.facesservlet.init_invalid_http_method",
                                arg);
                    }
                    // prevent duplicates
                    if (!.contains(cur)) {
                        .add(cur);
                    }
                } else {
                    // prevent duplicates
                    if (!allowedKnownHttpMethodsStringList.contains(cur)) {
                        allowedKnownHttpMethodsStringList.add(cur);
                    }
                }
            }
            // Optimally initialize allowedKnownHttpMethods
            if (5 == allowedKnownHttpMethodsStringList.size()) {
                 = EnumSet.of(
                        HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(0)),
                        HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(1)),
                        HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(2)),
                        HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(3)),
                        HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(4))
                        );
            } else if (4 == allowedKnownHttpMethodsStringList.size()) {
                 = EnumSet.of(
                        HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(0)),
                        HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(1)),
                        HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(2)),
                        HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(3))
                        );
                
            } else if (3 == allowedKnownHttpMethodsStringList.size()) {
                 = EnumSet.of(
                        HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(0)),
                        HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(1)),
                        HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(2))
                        );
                
            } else if (2 == allowedKnownHttpMethodsStringList.size()) {
                 = EnumSet.of(
                        HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(0)),
                        HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(1))
                        );
                
            } else if (1 == allowedKnownHttpMethodsStringList.size()) {
                 = EnumSet.of(
                        HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(0))
                        );
                
            } else {
                List<HttpMethodrestList = 
                        new ArrayList<HttpMethod>(allowedKnownHttpMethodsStringList.size() - 1);
                for (int i = 1; i < allowedKnownHttpMethodsStringList.size() - 1; i++) {
                    restList.add(HttpMethod.valueOf(
                            allowedKnownHttpMethodsStringList.get(i)
                            ));
                }
                HttpMethod first = HttpMethod.valueOf(allowedKnownHttpMethodsStringList.get(0));
                HttpMethod [] rest = new HttpMethod[restList.size()];
                restList.toArray(rest);
                 = EnumSet.of(firstrest);
                
            } 
        }
    }
    private void uninitHttpMethodValidityVerification() {
        assert (null != );
        assert (null != );
        assert (null != );
         = null;
         = null;
        .clear();
         = null;
    }


    

Process an incoming request, and create the corresponding response according to the following specification.

If the request and response arguments to this method are not instances of HttpServletRequest and HttpServletResponse, respectively, the results of invoking this method are undefined.

This method must respond to requests that start with the following strings by invoking the sendError method on the response argument (cast to HttpServletResponse), passing the code HttpServletResponse.SC_NOT_FOUND as the argument.

    
    /WEB-INF/
    /WEB-INF
    /META-INF/
    /META-INF
    

If none of the cases described above in the specification for this method apply to the servicing of this request, the following action must be taken to service the request.

Acquire a javax.faces.context.FacesContext instance for this request.

Acquire the ResourceHandler for this request by calling javax.faces.application.Application.getResourceHandler(). Call javax.faces.application.ResourceHandler.isResourceRequest(javax.faces.context.FacesContext). If this returns true call javax.faces.application.ResourceHandler.handleResourceRequest(javax.faces.context.FacesContext). If this returns false, call javax.faces.lifecycle.Lifecycle.execute(javax.faces.context.FacesContext) followed by javax.faces.lifecycle.Lifecycle.render(javax.faces.context.FacesContext). If a javax.faces.FacesException is thrown in either case, extract the cause from the FacesException. If the cause is null extract the message from the FacesException, put it inside of a new ServletException instance, and pass the FacesException instance as the root cause, then rethrow the ServletException instance. If the cause is an instance of ServletException, rethrow the cause. If the cause is an instance of IOException, rethrow the cause. Otherwise, create a new ServletException instance, passing the message from the cause, as the first argument, and the cause itself as the second argument.

The implementation must make it so javax.faces.context.FacesContext.release() is called within a finally block as late as possible in the processing for the JSF related portion of this request.

Parameters:
request The servlet request we are processing
response The servlet response we are creating
Throws:
java.io.IOException if an input/output error occurs during processing
javax.servlet.ServletException if a servlet error occurs during processing
    public void service(ServletRequest req,
                        ServletResponse resp)
        throws IOExceptionServletException {
        HttpServletRequest request = (HttpServletRequestreq;
        HttpServletResponse response = (HttpServletResponseresp;
        requestStart(request.getRequestURI()); // V3 Probe hook
        
        if (!isHttpMethodValid(request)) {
            response.sendError(.);
            return;
        }
        if (Thread.currentThread().isInterrupted()) {
            if (.isLoggable(.)) {
                .log(."Thread {0} given to FacesServlet.service() in interrupted state"
                        Thread.currentThread().getName());
            }
        }
        // If prefix mapped, then ensure requests for /WEB-INF are
        // not processed.
        String pathInfo = request.getPathInfo();
        if (pathInfo != null) {
            pathInfo = pathInfo.toUpperCase();
            if (pathInfo.contains("/WEB-INF/")
                || pathInfo.contains("/WEB-INF")
                || pathInfo.contains("/META-INF/")
                || pathInfo.contains("/META-INF")) {
                response.sendError(.);
                return;
            }
        }
        if (!) {
            FacesContext initFacesContext = FacesContext.getCurrentInstance();
            if (null != initFacesContext) {
                initFacesContext.release();
            }
             = true;
        }
        
        // Acquire the FacesContext instance for this request
              (.getServletContext(), requestresponse);
        // Execute the request processing lifecycle for this request
        try {
            ResourceHandler handler =
                  context.getApplication().getResourceHandler();
            if (handler.isResourceRequest(context)) {
                handler.handleResourceRequest(context);
            } else {
                .execute(context);
                .render(context);
            }
        } catch (FacesException e) {
            Throwable t = e.getCause();
            if (t == null) {
                throw new ServletException(e.getMessage(), e);
            } else {
                if (t instanceof ServletException) {
                    throw ((ServletExceptiont);
                } else if (t instanceof IOException) {
                    throw ((IOExceptiont);
                } else {
                    throw new ServletException(t.getMessage(), t);
                }
            }
        }
        finally {
            // Release the FacesContext instance for this request
            context.release();
        }
        requestEnd(); // V3 Probe hook
    }
    private boolean isHttpMethodValid(HttpServletRequest request) {
        boolean result = false;
        if () {
            result = true;
        } else {
            String requestMethodString = request.getMethod();
            HttpMethod requestMethod = null;
            boolean isKnownHttpMethod;
            try {
                requestMethod = HttpMethod.valueOf(requestMethodString);
                isKnownHttpMethod = true;
            } catch (IllegalArgumentException e) {
                isKnownHttpMethod = false;
            }
            if (isKnownHttpMethod) {
                result = .contains(requestMethod);
            } else {
                result = .contains(requestMethodString);
            }
            
        }
        return result;
    }
    // --------------------------------------------------------- Private Methods


    
DO NOT REMOVE. Necessary for V3 probe monitoring.
    @SuppressWarnings({"UnusedDeclaration"})
    private void requestStart(String requestUri) { }


    
DO NOT REMOVE. Necessary for V3 probe monitoring.
    private void requestEnd() { }
    
    }    
New to GrepCode? Check out our FAQ X