servletcontainer.java

来自「resetful样式的ws样例,一种面向资源的webservices服务」· Java 代码 · 共 549 行 · 第 1/2 页

JAVA
549
字号
                build();                final ContainerRequest cRequest = new ServletContainerRequest(                request,                _application,                request.getMethod(),                baseUri,                requestUri,                getHeaders(request),                request.getInputStream());                try {            requestInvoker.set(request);            responseInvoker.set(response);                        _application.handleRequest(cRequest, new Writer(response));        } catch (ContainerException e) {            throw new ServletException(e);        } finally {            requestInvoker.set(null);            responseInvoker.set(null);        }            }        @SuppressWarnings("unchecked")    private InBoundHeaders getHeaders(HttpServletRequest request) {        InBoundHeaders rh = new InBoundHeaders();                   for (Enumeration<String> names = request.getHeaderNames() ; names.hasMoreElements() ;) {            String name = names.nextElement();            List<String> valueList = new LinkedList<String>();            for (Enumeration<String> values = request.getHeaders(name); values.hasMoreElements() ;) {                valueList.add(values.nextElement());            }            rh.put(name, valueList);        }                return rh;    }        private ResourceConfig createResourceConfig(ServletConfig servletConfig)             throws ServletException {                Map<String, Object> props = getInitParams(servletConfig);                // Check if the resource config class property is present        String resourceConfigClassName = servletConfig.getInitParameter(RESOURCE_CONFIG_CLASS);        // Otherwise check if the JAX-RS applicaion config class property is        // present        if (resourceConfigClassName == null)            resourceConfigClassName = servletConfig.getInitParameter(APPLICATION_CONFIG_CLASS);                // If no resource config class property is present         if (resourceConfigClassName == null) {            // If the packages property is present then            // use the packages resource config            String packages = servletConfig.getInitParameter(                    PackagesResourceConfig.PROPERTY_PACKAGES);            if (packages != null) {                props.put(PackagesResourceConfig.PROPERTY_PACKAGES, packages);                return new PackagesResourceConfig(props);                                }                        // Default to using class path resource config            String[] paths = getPaths(servletConfig.getInitParameter(                    ClasspathResourceConfig.PROPERTY_CLASSPATH));            props.put(ClasspathResourceConfig.PROPERTY_CLASSPATH, paths);            return new ClasspathResourceConfig(props);        }        try {            Class resourceConfigClass = getClassLoader().                    loadClass(resourceConfigClassName);                        if (resourceConfigClass == ClasspathResourceConfig.class) {                String[] paths = getPaths(servletConfig.getInitParameter(                        ClasspathResourceConfig.PROPERTY_CLASSPATH));                props.put(ClasspathResourceConfig.PROPERTY_CLASSPATH, paths);                return new ClasspathResourceConfig(props);            } else if (ResourceConfig.class.isAssignableFrom(resourceConfigClass)) {                try {                                        Constructor constructor = resourceConfigClass.getConstructor(Map.class);                                        if (ClasspathResourceConfig.class.isAssignableFrom(resourceConfigClass)) {                        String[] paths = getPaths(servletConfig.getInitParameter(                                ClasspathResourceConfig.PROPERTY_CLASSPATH));                        props.put(ClasspathResourceConfig.PROPERTY_CLASSPATH, paths);                                            }                    return (ResourceConfig)constructor.newInstance(props);                } catch (NoSuchMethodException ex) {                    // Pass through and try the default constructor                } catch (Exception e) {                    throw new ServletException(e);                }                                try {                    return (ResourceConfig)resourceConfigClass.newInstance();                } catch(Exception e) {                                        throw new ServletException(e);                }            } else if (ApplicationConfig.class.isAssignableFrom(resourceConfigClass)) {                try {                    ResourceConfig rc = new ApplicationConfigAdapter(                            (ApplicationConfig)resourceConfigClass.newInstance());                    rc.getProperties().putAll(props);                    return rc;                } catch(Exception e) {                    throw new ServletException(e);                }            } else {                String message = "Resource configuration class, " + resourceConfigClassName +                         ", is not a super class of " + ResourceConfig.class;                throw new ServletException(message);            }        } catch (ClassNotFoundException e) {            String message = "Resource configuration class, " + resourceConfigClassName +                     ", could not be loaded";            throw new ServletException(message, e);        }    }    private ClassLoader getClassLoader() {        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();                return (classLoader == null) ? getClass().getClassLoader() : classLoader;    }        private Map<String, Object> getInitParams(ServletConfig servletConfig) {        Map<String, Object> props = new HashMap<String, Object>();        Enumeration names = servletConfig.getInitParameterNames();        while(names.hasMoreElements()) {            String name = (String)names.nextElement();            props.put(name, servletConfig.getInitParameter(name));        }        return props;    }        private String[] getPaths(String classpath) {        if (classpath == null) {            return new String[] {                context.getRealPath("/WEB-INF/lib"),                 context.getRealPath("/WEB-INF/classes")            };        } else {            String[] virtualPaths = classpath.split(";");            List<String> resourcePaths = new ArrayList<String>();            for (String virtualPath : virtualPaths) {                virtualPath = virtualPath.trim();                if (virtualPath.length() == 0) continue;                                resourcePaths.add(context.getRealPath(virtualPath));            }                        return resourcePaths.toArray(new String[resourcePaths.size()]);        }            }        private void initResourceConfigFeatures(ServletConfig servletConfig, ResourceConfig rc) {        setResourceConfigFeature(servletConfig, rc,                 ResourceConfig.FEATURE_CANONICALIZE_URI_PATH);        setResourceConfigFeature(servletConfig, rc,                 ResourceConfig.FEATURE_MATCH_MATRIX_PARAMS);        setResourceConfigFeature(servletConfig, rc,                 ResourceConfig.FEATURE_NORMALIZE_URI);        setResourceConfigFeature(servletConfig, rc,                 ResourceConfig.FEATURE_REDIRECT);        setResourceConfigFeature(servletConfig, rc,                 ResourceConfig.FEATURE_IMPLICIT_VIEWABLES);    }        private void setResourceConfigFeature(ServletConfig servletConfig, ResourceConfig rc, String feature) {        String value = servletConfig.getInitParameter(feature);        if (value != null)            rc.getFeatures().put(feature, Boolean.valueOf(value));    }        /**     * Load the Web application. This will create, configure and initiate     * the web application.     * <p>     * This method may be called at runtime, more than once, to reload the      * Web application. For example, if a {@link ResourceConfig} implementation      * is capable of detecting changes to resource classes (addition or removal)     * or providers then this method may be invoked to reload the web      * application for such changes to take effect.     * <p>     * If this method is called when there are pending requests then such     * requests will be processed using the previously loaded web application.     */    public final void load() {        WebApplication _application = create();                configure(config, resourceConfig, _application);                initiate(resourceConfig, _application);        application = _application;    }        /**     * Create a new instance of a {@link WebApplication}.     *      * @return the {@link WebApplication} instance.     */    protected WebApplication create() {        return WebApplicationFactory.createWebApplication();    }        private static class ContextInjectableProvider<T> extends            SingletonTypeInjectableProvider<Context, T> {        ContextInjectableProvider(Type type, T instance) {            super(type, instance);        }    }        /**     * Configure the {@link WebApplication}.     * <p>     * The {@link WebApplication} is configured such that the following classes      * may be injected onto the field of a root resource class or a parameter      * of a method of root resource class that is annotated with      * {@link javax.ws.rs.core.Context}: {@link HttpServletRequest}, {@link HttpServletResponse}     * , {@link ServletContext}, and {@link ServletConfig}.     * <p>     * An inheriting class may override this method to configure the      * {@link WebApplication} to provide alternative or additional instance     * that may be injected into a root resource class, and may modify the     * features and properties of the {@link ResourceConfig}. For an inheriting     * class to extend configuration behaviour the overriding method MUST call     * super.configure(servletConfig, rc, wa) as the first statement of that      * method.     *      * @param sc the Servlet configuration     * @param rc the Resource configuration     * @param wa the Web application     */    protected void configure(final ServletConfig sc, ResourceConfig rc, WebApplication wa) {        rc.getProviderInstances().add(new ContextInjectableProvider<HttpServletRequest>(                HttpServletRequest.class,                (HttpServletRequest)Proxy.newProxyInstance(                        HttpServletRequest.class.getClassLoader(),                        new Class[] { HttpServletRequest.class },                        requestInvoker)));                rc.getProviderInstances().add(new ContextInjectableProvider<HttpServletResponse>(                HttpServletResponse.class,                (HttpServletResponse)Proxy.newProxyInstance(                        HttpServletResponse.class.getClassLoader(),                        new Class[] { HttpServletResponse.class },                        responseInvoker)));                rc.getProviderInstances().add(new ContextInjectableProvider<ServletConfig>(                ServletConfig.class, sc));                rc.getProviderInstances().add(new ContextInjectableProvider<ServletContext>(                ServletContext.class,                 sc.getServletContext()));                rc.getProviderInstances().add(new JSPTemplateProcessor(                requestInvoker.getThreadLocal(),                 responseInvoker.getThreadLocal()));    }        /**     * Initiate the {@link WebApplication}.     *     * @param rc the Resource configuration     * @param wa the Web application     */    protected void initiate(ResourceConfig rc, WebApplication wa) {        wa.initiate(rc);            }    // ContainerListener        public void onReload() {        load();    }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?