Search in sources :

Example 26 with DispatcherType

use of javax.servlet.DispatcherType in project Payara by payara.

the class ApplicationFilterFactory method createFilterChain.

/**
 * Construct and return a FilterChain implementation that will wrap the
 * execution of the specified servlet instance.  If we should not execute
 * a filter chain at all, return <code>null</code>.
 *
 * @param request The servlet request we are processing
 * @param wrapper The wrapper for the servlet
 * @param servlet The servlet instance to be wrapped
 * @return Filterchain that wraps the instance
 */
public ApplicationFilterChain createFilterChain(ServletRequest request, Wrapper wrapper, Servlet servlet) {
    // If there is no servlet to execute, return null
    if (servlet == null)
        return (null);
    // Create and initialize a filter chain object
    ApplicationFilterChain filterChain = null;
    /**
     * IASRI 4665318
     *        if ((securityManager == null) && (request instanceof Request)) {
     *            Request req = (Request) request;
     *            filterChain = (ApplicationFilterChain) req.getFilterChain();
     *            if (filterChain == null) {
     *                filterChain = new ApplicationFilterChain();
     *                req.setFilterChain(filterChain);
     *            }
     *        } else {
     *            // Security: Do not recycle
     *            filterChain = new ApplicationFilterChain();
     *        }
     *
     *        filterChain.setServlet(servlet);
     *
     *        filterChain.setSupport
     *            (((StandardWrapper)wrapper).getInstanceSupport());
     */
    // Acquire the filter mappings for this Context
    StandardContext context = (StandardContext) wrapper.getParent();
    List<FilterMap> filterMaps = context.findFilterMaps();
    // If there are no filter mappings, we are done
    if (filterMaps.isEmpty()) {
        return (filterChain);
    }
    // get the dispatcher type
    DispatcherType dispatcher = request.getDispatcherType();
    String requestPath = null;
    Object attribute = request.getAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR);
    if (attribute != null) {
        requestPath = attribute.toString();
    }
    // Acquire the information we will need to match filter mappings
    String servletName = wrapper.getName();
    int n = 0;
    // Add the relevant path-mapped filters to this filter chain
    Iterator<FilterMap> i = filterMaps.iterator();
    while (i.hasNext()) {
        FilterMap filterMap = i.next();
        if (!filterMap.getDispatcherTypes().contains(dispatcher)) {
            continue;
        }
        // START SJSWS 6324431
        if (!matchFiltersURL(filterMap, requestPath, context.isCaseSensitiveMapping()))
            continue;
        // END SJSWS 6324431
        ApplicationFilterConfig filterConfig = (ApplicationFilterConfig) context.findFilterConfig(filterMap.getFilterName());
        if (filterConfig == null) {
            // FIXME - log configuration problem
            continue;
        }
        // Create a filter chain only when there are filters to add
        if (filterChain == null)
            filterChain = internalCreateFilterChain(request, wrapper, servlet);
        // END IASRI 4665318
        filterChain.addFilter(filterConfig);
        n++;
    }
    // Add filters that match on servlet name second
    i = filterMaps.iterator();
    while (i.hasNext()) {
        FilterMap filterMap = i.next();
        if (!filterMap.getDispatcherTypes().contains(dispatcher)) {
            continue;
        }
        if (!matchFiltersServlet(filterMap, servletName))
            continue;
        ApplicationFilterConfig filterConfig = (ApplicationFilterConfig) context.findFilterConfig(filterMap.getFilterName());
        if (filterConfig == null) {
            // FIXME - log configuration problem
            continue;
        }
        // Create a filter chain only when there are filters to add
        if (filterChain == null)
            filterChain = internalCreateFilterChain(request, wrapper, servlet);
        // END IASRI 4665318
        filterChain.addFilter(filterConfig);
        n++;
    }
    // Return the completed filter chain
    return (filterChain);
}
Also used : DispatcherType(javax.servlet.DispatcherType) FilterMap(org.apache.catalina.deploy.FilterMap)

Example 27 with DispatcherType

use of javax.servlet.DispatcherType in project Payara by payara.

the class CacheModule method configureResponseCache.

/**
 * configure ias-web response cache
 * @param app WebModule containing the cache
 * @param bean ias-web app config bean
 * @throws Exception
 *
 * read the configuration and setup the runtime support for caching in a
 * application.
 */
public static CacheManager configureResponseCache(WebModule app, SunWebApp bean) throws Exception {
    Cache cacheConfig = ((SunWebAppImpl) bean).getCache();
    // is cache configured?
    if (cacheConfig == null) {
        return null;
    }
    if (logger.isLoggable(Level.FINE)) {
        logger.log(Level.FINE, LogFacade.CONFIGURE_CACHE, app.getPath());
    }
    // create the CacheManager object for this app
    CacheManager manager = new CacheManager();
    String name, value;
    value = cacheConfig.getAttributeValue(Cache.ENABLED);
    if (value != null) {
        boolean enabled = ConfigBeansUtilities.toBoolean(value);
        manager.setEnabled(enabled);
    }
    // set cache element's attributes and properties
    value = cacheConfig.getAttributeValue(Cache.MAX_ENTRIES);
    if (value != null) {
        try {
            int maxEntries = Integer.parseInt(value.trim());
            manager.setMaxEntries(maxEntries);
        } catch (NumberFormatException e) {
            // XXX need error message
            throw new Exception("invalid max-entries", e);
        }
    }
    value = cacheConfig.getAttributeValue(Cache.TIMEOUT_IN_SECONDS);
    if (value != null) {
        try {
            int defaultTimeout = Integer.parseInt(value.trim());
            manager.setDefaultTimeout(defaultTimeout);
        } catch (NumberFormatException e) {
            // XXX need error message
            throw new Exception("invalid timeout", e);
        }
    }
    WebProperty[] props = cacheConfig.getWebProperty();
    for (int i = 0; i < props.length; i++) {
        name = props[i].getAttributeValue(WebProperty.NAME);
        value = props[i].getAttributeValue(WebProperty.VALUE);
        manager.addProperty(name, value);
    }
    // configure the default cache-helper
    DefaultHelper defHelperConfig = cacheConfig.getDefaultHelper();
    HashMap<String, String> map = new HashMap<String, String>();
    if (defHelperConfig != null) {
        props = defHelperConfig.getWebProperty();
        for (int i = 0; i < props.length; i++) {
            name = props[i].getAttributeValue(WebProperty.NAME);
            value = props[i].getAttributeValue(WebProperty.VALUE);
            map.put(name, value);
        }
    }
    manager.setDefaultHelperProps(map);
    // configure custom cache-helper classes
    for (int i = 0; i < cacheConfig.sizeCacheHelper(); i++) {
        CacheHelper helperConfig = cacheConfig.getCacheHelper(i);
        String helperName = helperConfig.getAttributeValue(CacheHelper.NAME);
        HashMap<String, String> helperProps = new HashMap<String, String>();
        props = helperConfig.getWebProperty();
        for (int j = 0; j < props.length; j++) {
            name = props[i].getAttributeValue(WebProperty.NAME);
            value = props[i].getAttributeValue(WebProperty.VALUE);
            helperProps.put(name, value);
        }
        helperProps.put("class-name", helperConfig.getAttributeValue(CacheHelper.CLASS_NAME));
        manager.addCacheHelperDef(helperName, helperProps);
    }
    // for each cache-mapping, create CacheMapping, setup the filter
    for (int i = 0; i < cacheConfig.sizeCacheMapping(); i++) {
        org.glassfish.web.deployment.runtime.CacheMapping mapConfig = cacheConfig.getCacheMapping(i);
        CacheMapping mapping = new CacheMapping();
        configureCacheMapping(mapConfig, mapping, logger);
        // use filter's name to refer to setup the filter
        String filterName = CACHING_FILTER_CLASSNAME + i;
        /**
         * all cache-mapings are indexed by the unique filter-name;
         * DefaultCacheHelper uses this name to access the mapping.
         */
        manager.addCacheMapping(filterName, mapping);
        // setup the ias CachingFilter definition with the context
        FilterDef filterDef = new FilterDef();
        filterDef.setFilterName(filterName);
        filterDef.setFilterClassName(CACHING_FILTER_CLASSNAME);
        if (mapping.getServletName() != null) {
            filterDef.addInitParameter("servletName", mapping.getServletName());
        }
        if (mapping.getURLPattern() != null) {
            filterDef.addInitParameter("URLPattern", mapping.getURLPattern());
        }
        app.addFilterDef(filterDef);
        // setup the mapping for the specified servlet-name or url-pattern
        FilterMap filterMap = new FilterMap();
        filterMap.setServletName(mapping.getServletName());
        filterMap.setURLPattern(mapping.getURLPattern());
        String[] dispatchers = mapConfig.getDispatcher();
        if (dispatchers != null) {
            EnumSet<DispatcherType> dispatcherTypes = null;
            for (String dispatcher : dispatchers) {
                // calls to FilterMap.setDispatcher are cumulative
                if (dispatcherTypes == null) {
                    dispatcherTypes = EnumSet.of(Enum.valueOf(DispatcherType.class, dispatcher));
                } else {
                    dispatcherTypes.add(Enum.valueOf(DispatcherType.class, dispatcher));
                }
            }
            filterMap.setDispatcherTypes(dispatcherTypes);
        }
        filterMap.setFilterName(filterName);
        app.addFilterMap(filterMap);
        if (logger.isLoggable(Level.FINE)) {
            logger.log(Level.FINE, LogFacade.CACHING_FILTER_ADDED, new Object[] { mapping.getServletName(), mapping.getURLPattern() });
        }
    }
    manager.setServletContext(app.getServletContext());
    return manager;
}
Also used : FilterDef(org.apache.catalina.deploy.FilterDef) HashMap(java.util.HashMap) org.glassfish.web.deployment.runtime(org.glassfish.web.deployment.runtime) FilterMap(org.apache.catalina.deploy.FilterMap) ValueConstraint(com.sun.appserv.web.cache.mapping.ValueConstraint) CacheManager(com.sun.appserv.web.cache.CacheManager) CacheMapping(com.sun.appserv.web.cache.mapping.CacheMapping) DispatcherType(javax.servlet.DispatcherType)

Example 28 with DispatcherType

use of javax.servlet.DispatcherType in project Payara by payara.

the class WebFilterHandler method processAnnotation.

private HandlerProcessingResult processAnnotation(AnnotationInfo ainfo, WebBundleDescriptor webBundleDesc) throws AnnotationProcessorException {
    Class filterClass = (Class) ainfo.getAnnotatedElement();
    if (!javax.servlet.Filter.class.isAssignableFrom(filterClass)) {
        log(Level.SEVERE, ainfo, localStrings.getLocalString("web.deployment.annotation.handlers.needtoimpl", "The Class {0} having annotation {1} need to implement the interface {2}.", new Object[] { filterClass.getName(), WebFilter.class.getName(), javax.servlet.Filter.class.getName() }));
        return getDefaultFailedResult();
    }
    WebFilter webFilterAn = (WebFilter) ainfo.getAnnotation();
    String filterName = webFilterAn.filterName();
    if (filterName == null || filterName.length() == 0) {
        filterName = filterClass.getName();
    }
    ServletFilterDescriptor servletFilterDesc = null;
    for (ServletFilter sfDesc : webBundleDesc.getServletFilters()) {
        if (filterName.equals(sfDesc.getName())) {
            servletFilterDesc = (ServletFilterDescriptor) sfDesc;
            break;
        }
    }
    if (servletFilterDesc == null) {
        servletFilterDesc = new ServletFilterDescriptor();
        servletFilterDesc.setName(filterName);
        webBundleDesc.addServletFilter(servletFilterDesc);
    } else {
        String filterImpl = servletFilterDesc.getClassName();
        if (filterImpl != null && filterImpl.length() > 0 && !filterImpl.equals(filterClass.getName())) {
            log(Level.SEVERE, ainfo, localStrings.getLocalString("web.deployment.annotation.handlers.filternamedontmatch", "The filter ''{0}'' has implementation ''{1}'' in xml. It does not match with ''{2}'' from annotation @{3}.", new Object[] { filterName, filterImpl, filterClass.getName(), WebFilter.class.getName() }));
            return getDefaultFailedResult();
        }
    }
    servletFilterDesc.setClassName(filterClass.getName());
    if (servletFilterDesc.getDescription() == null || servletFilterDesc.getDescription().length() == 0) {
        servletFilterDesc.setDescription(webFilterAn.description());
    }
    if (servletFilterDesc.hasSetDisplayName()) {
        servletFilterDesc.setDisplayName(webFilterAn.displayName());
    }
    if (servletFilterDesc.getInitializationParameters().size() == 0) {
        WebInitParam[] initParams = webFilterAn.initParams();
        if (initParams != null && initParams.length > 0) {
            for (WebInitParam initParam : initParams) {
                servletFilterDesc.addInitializationParameter(new EnvironmentProperty(initParam.name(), initParam.value(), initParam.description()));
            }
        }
    }
    if (servletFilterDesc.getSmallIconUri() == null) {
        servletFilterDesc.setSmallIconUri(webFilterAn.smallIcon());
    }
    if (servletFilterDesc.getLargeIconUri() == null) {
        servletFilterDesc.setLargeIconUri(webFilterAn.largeIcon());
    }
    if (servletFilterDesc.isAsyncSupported() == null) {
        servletFilterDesc.setAsyncSupported(webFilterAn.asyncSupported());
    }
    ServletFilterMapping servletFilterMappingDesc = null;
    boolean hasUrlPattern = false;
    boolean hasServletName = false;
    for (ServletFilterMapping sfm : webBundleDesc.getServletFilterMappings()) {
        if (filterName.equals(sfm.getName())) {
            servletFilterMappingDesc = sfm;
            hasUrlPattern = hasUrlPattern || (sfm.getUrlPatterns().size() > 0);
            hasServletName = hasServletName || (sfm.getServletNames().size() > 0);
        }
    }
    if (servletFilterMappingDesc == null) {
        servletFilterMappingDesc = new ServletFilterMappingDescriptor();
        servletFilterMappingDesc.setName(filterName);
        webBundleDesc.addServletFilterMapping(servletFilterMappingDesc);
    }
    if (!hasUrlPattern) {
        String[] urlPatterns = webFilterAn.urlPatterns();
        if (urlPatterns == null || urlPatterns.length == 0) {
            urlPatterns = webFilterAn.value();
        }
        // accept here as url patterns may be defined in top level xml
        boolean validUrlPatterns = true;
        if (urlPatterns != null && urlPatterns.length > 0) {
            for (String up : urlPatterns) {
                if (!URLPattern.isValid(up)) {
                    validUrlPatterns = false;
                    break;
                }
                servletFilterMappingDesc.addURLPattern(up);
            }
        }
        if (!validUrlPatterns) {
            String urlPatternString = (urlPatterns != null) ? Arrays.toString(urlPatterns) : "";
            throw new IllegalArgumentException(localStrings.getLocalString("web.deployment.annotation.handlers.invalidUrlPatterns", "Invalid url patterns: {0}.", urlPatternString));
        }
    }
    if (!hasServletName) {
        String[] servletNames = webFilterAn.servletNames();
        if (servletNames != null && servletNames.length > 0) {
            for (String sn : servletNames) {
                servletFilterMappingDesc.addServletName(sn);
            }
        }
    }
    if (servletFilterMappingDesc.getDispatchers().size() == 0) {
        DispatcherType[] dispatcherTypes = webFilterAn.dispatcherTypes();
        if (dispatcherTypes != null && dispatcherTypes.length > 0) {
            for (DispatcherType dType : dispatcherTypes) {
                servletFilterMappingDesc.addDispatcher(dType.name());
            }
        }
    }
    return getDefaultProcessedResult();
}
Also used : WebFilter(javax.servlet.annotation.WebFilter) ServletFilter(com.sun.enterprise.deployment.web.ServletFilter) ServletFilterDescriptor(org.glassfish.web.deployment.descriptor.ServletFilterDescriptor) ServletFilterMappingDescriptor(org.glassfish.web.deployment.descriptor.ServletFilterMappingDescriptor) ServletFilter(com.sun.enterprise.deployment.web.ServletFilter) WebFilter(javax.servlet.annotation.WebFilter) EnvironmentProperty(com.sun.enterprise.deployment.EnvironmentProperty) WebInitParam(javax.servlet.annotation.WebInitParam) ServletFilterMapping(com.sun.enterprise.deployment.web.ServletFilterMapping) DispatcherType(javax.servlet.DispatcherType)

Example 29 with DispatcherType

use of javax.servlet.DispatcherType in project Payara by payara.

the class FilterMappingNode method writeDescriptor.

/**
 * write the descriptor class to a DOM tree and return it
 *
 * @param parent node in the DOM tree
 * @param nodeName node name for the root element of this xml fragment
 * @param descriptor the descriptor to write
 * @return the DOM tree top node
 */
@Override
public Node writeDescriptor(Node parent, String nodeName, ServletFilterMappingDescriptor descriptor) {
    Node myNode = appendChild(parent, nodeName);
    appendTextChild(myNode, WebTagNames.FILTER_NAME, descriptor.getName());
    for (String servletName : descriptor.getServletNames()) {
        appendTextChild(myNode, WebTagNames.SERVLET_NAME, servletName);
    }
    for (String urlPattern : descriptor.getUrlPatterns()) {
        appendTextChild(myNode, WebTagNames.URL_PATTERN, urlPattern);
    }
    for (DispatcherType dispatcherType : descriptor.getDispatchers()) {
        appendTextChild(myNode, WebTagNames.DISPATCHER, dispatcherType.name());
    }
    return myNode;
}
Also used : DeploymentDescriptorNode(com.sun.enterprise.deployment.node.DeploymentDescriptorNode) Node(org.w3c.dom.Node) DispatcherType(javax.servlet.DispatcherType)

Example 30 with DispatcherType

use of javax.servlet.DispatcherType in project Payara by payara.

the class ServletFilterMappingDescriptor method equals.

/**
 * compare equals
 */
public boolean equals(Object obj) {
    if (obj instanceof ServletFilterMapping) {
        ServletFilterMapping o = (ServletFilterMapping) obj;
        Set<DispatcherType> otherDispatchers = o.getDispatchers();
        boolean sameDispatchers = ((dispatchers == null && (otherDispatchers == null || otherDispatchers.size() == 0)) || (dispatchers != null && dispatchers.equals(otherDispatchers)));
        if (this.getName().equals(o.getName()) && this.getServletNames().equals(o.getServletNames()) && this.getUrlPatterns().equals(o.getUrlPatterns()) && sameDispatchers) {
            return true;
        }
    }
    return false;
}
Also used : ServletFilterMapping(com.sun.enterprise.deployment.web.ServletFilterMapping) DispatcherType(javax.servlet.DispatcherType)

Aggregations

DispatcherType (javax.servlet.DispatcherType)45 ServletContext (javax.servlet.ServletContext)6 ServletRequest (javax.servlet.ServletRequest)6 IOException (java.io.IOException)5 FilterMap (org.apache.catalina.deploy.FilterMap)5 ServletResponse (javax.servlet.ServletResponse)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 Server (org.eclipse.jetty.server.Server)4 FilterHolder (org.eclipse.jetty.servlet.FilterHolder)4 AnnotationConfigWebApplicationContext (org.springframework.web.context.support.AnnotationConfigWebApplicationContext)4 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)3 File (java.io.File)3 WebInitParam (javax.servlet.annotation.WebInitParam)3 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)3 Test (org.junit.Test)3 ServletFilterMapping (com.sun.enterprise.deployment.web.ServletFilterMapping)2 ServletContainer (com.sun.jersey.spi.container.servlet.ServletContainer)2 ManagedFilter (io.undertow.servlet.core.ManagedFilter)2 ArrayList (java.util.ArrayList)2