Search in sources :

Example 41 with DispatcherType

use of javax.servlet.DispatcherType in project dropwizard-guicey by xvik.

the class Jersey2Module method configure.

@Override
protected void configure() {
    final EnumSet<DispatcherType> types = context.option(GuiceFilterRegistration);
    final boolean guiceServletSupport = !types.isEmpty();
    // injector not available at this point, so using provider
    final InjectorProvider provider = new InjectorProvider(application);
    install(new GuiceBindingsModule(provider, guiceServletSupport));
    final GuiceFeature component = new GuiceFeature(provider, context.stat(), context.option(UseHkBridge));
    bind(ServiceLocator.class).toProvider(component);
    environment.jersey().register(component);
    if (guiceServletSupport) {
        install(new GuiceWebModule(environment, types));
    }
}
Also used : GuiceBindingsModule(ru.vyarus.dropwizard.guice.module.jersey.hk2.GuiceBindingsModule) ServiceLocator(org.glassfish.hk2.api.ServiceLocator) DispatcherType(javax.servlet.DispatcherType) InjectorProvider(ru.vyarus.dropwizard.guice.injector.lookup.InjectorProvider)

Example 42 with DispatcherType

use of javax.servlet.DispatcherType in project mycore by MyCoRe-Org.

the class MCRAutoDeploy method registerWebFragment.

private void registerWebFragment(final ServletContext servletContext, final MCRComponent comp) {
    if (!isHandledByServletContainer(servletContext, comp)) {
        try {
            final JarFile jar = new JarFile(comp.getJarFile());
            Collections.list(jar.entries()).stream().filter(file -> file.getName().equals(WEB_FRAGMENT)).findFirst().ifPresent(file -> {
                final SAXBuilder builder = new SAXBuilder();
                try {
                    final InputStream is = jar.getInputStream(file);
                    final Document doc = builder.build(is);
                    final Element root = doc.getRootElement();
                    final Namespace ns = root.getNamespace();
                    final List<Element> filters = root.getChildren("filter", ns);
                    final List<Element> fmaps = root.getChildren("filter-mapping", ns);
                    filters.forEach(filter -> {
                        final String name = filter.getChildText("filter-name", ns);
                        final String className = filter.getChildText("filter-class", ns);
                        fmaps.stream().filter(mapping -> mapping.getChildText("filter-name", ns).equals(name)).findFirst().ifPresent(mapping -> {
                            LOGGER.info("Register Filter {} ({})...", name, className);
                            Optional.ofNullable(servletContext.addFilter(name, className)).<Runnable>map(fr -> () -> {
                                final List<Element> dispatchers = mapping.getChildren("dispatcher", ns);
                                final EnumSet<DispatcherType> eDT = dispatchers.isEmpty() ? null : dispatchers.stream().map(d -> DispatcherType.valueOf(d.getTextTrim())).collect(Collectors.toCollection(() -> EnumSet.noneOf(DispatcherType.class)));
                                final List<Element> servletNames = mapping.getChildren("servlet-name", ns);
                                if (!servletNames.isEmpty()) {
                                    fr.addMappingForServletNames(eDT, false, servletNames.stream().map(sn -> {
                                        LOGGER.info("...add servlet mapping: {}", sn.getTextTrim());
                                        return sn.getTextTrim();
                                    }).toArray(String[]::new));
                                }
                                final List<Element> urlPattern = mapping.getChildren("url-pattern", ns);
                                if (!urlPattern.isEmpty()) {
                                    fr.addMappingForUrlPatterns(eDT, false, urlPattern.stream().map(url -> {
                                        LOGGER.info("...add url mapping: {}", url.getTextTrim());
                                        return url.getTextTrim();
                                    }).toArray(String[]::new));
                                }
                            }).orElse(() -> LOGGER.warn("Filter {} already registered!", name)).run();
                        });
                    });
                    final List<Element> servlets = root.getChildren("servlet", ns);
                    final List<Element> smaps = root.getChildren("servlet-mapping", ns);
                    servlets.forEach(servlet -> {
                        final String name = servlet.getChildText("servlet-name", ns);
                        final String className = servlet.getChildText("servlet-class", ns);
                        smaps.stream().filter(mapping -> mapping.getChildText("servlet-name", ns).equals(name)).findFirst().ifPresent(mapping -> {
                            LOGGER.info("Register Servlet {} ({})...", name, className);
                            Optional.ofNullable(servletContext.addServlet(name, className)).<Runnable>map(sr -> () -> mapping.getChildren("url-pattern", ns).stream().forEach(url -> {
                                LOGGER.info("...add url mapping: {}", url.getTextTrim());
                                sr.addMapping(url.getTextTrim());
                            })).orElse(() -> LOGGER.error("Servlet{} already registered!", name)).run();
                        });
                    });
                } catch (IOException | JDOMException e) {
                    LOGGER.error("Couldn't parse " + WEB_FRAGMENT, e);
                }
            });
            jar.close();
        } catch (final IOException e) {
            LOGGER.error("Couldn't parse JAR!", e);
        }
    }
}
Also used : SAXBuilder(org.jdom2.input.SAXBuilder) MCRRuntimeComponentDetector(org.mycore.common.config.MCRRuntimeComponentDetector) MCRComponent(org.mycore.common.config.MCRComponent) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) Collectors(java.util.stream.Collectors) File(java.io.File) Document(org.jdom2.Document) List(java.util.List) Logger(org.apache.logging.log4j.Logger) JDOMException(org.jdom2.JDOMException) Optional(java.util.Optional) DispatcherType(javax.servlet.DispatcherType) ServletContext(javax.servlet.ServletContext) Namespace(org.jdom2.Namespace) MCRStartupHandler(org.mycore.common.events.MCRStartupHandler) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) EnumSet(java.util.EnumSet) InputStream(java.io.InputStream) Element(org.jdom2.Element) SAXBuilder(org.jdom2.input.SAXBuilder) InputStream(java.io.InputStream) Element(org.jdom2.Element) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) Document(org.jdom2.Document) JDOMException(org.jdom2.JDOMException) Namespace(org.jdom2.Namespace) DispatcherType(javax.servlet.DispatcherType)

Example 43 with DispatcherType

use of javax.servlet.DispatcherType in project undertow by undertow-io.

the class ServletInitialHandler method dispatchToServlet.

@Override
public void dispatchToServlet(final HttpServerExchange exchange, final ServletChain servletchain, final DispatcherType dispatcherType) throws Exception {
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    DispatcherType oldDispatch = servletRequestContext.getDispatcherType();
    ServletChain oldChain = servletRequestContext.getCurrentServlet();
    try {
        dispatchRequest(exchange, servletRequestContext, servletchain, dispatcherType);
    } finally {
        servletRequestContext.setDispatcherType(oldDispatch);
        servletRequestContext.setCurrentServlet(oldChain);
    }
}
Also used : DispatcherType(javax.servlet.DispatcherType)

Example 44 with DispatcherType

use of javax.servlet.DispatcherType in project undertow by undertow-io.

the class ServletPathMatches method setupServletChains.

/**
 * Sets up the handlers in the servlet chain. We setup a chain for every path + extension match possibility.
 * (i.e. if there a m path mappings and n extension mappings we have n*m chains).
 * <p>
 * If a chain consists of only the default servlet then we add it as an async handler, so that resources can be
 * served up directly without using blocking operations.
 * <p>
 * TODO: this logic is a bit convoluted at the moment, we should look at simplifying it
 */
private ServletPathMatchesData setupServletChains() {
    // create the default servlet
    ServletHandler defaultServlet = null;
    final ManagedServlets servlets = deployment.getServlets();
    final ManagedFilters filters = deployment.getFilters();
    final Map<String, ServletHandler> extensionServlets = new HashMap<>();
    final Map<String, ServletHandler> pathServlets = new HashMap<>();
    final Set<String> pathMatches = new HashSet<>();
    final Set<String> extensionMatches = new HashSet<>();
    DeploymentInfo deploymentInfo = deployment.getDeploymentInfo();
    // loop through all filter mappings, and add them to the set of known paths
    for (FilterMappingInfo mapping : deploymentInfo.getFilterMappings()) {
        if (mapping.getMappingType() == FilterMappingInfo.MappingType.URL) {
            String path = mapping.getMapping();
            if (path.equals("*")) {
                // UNDERTOW-95, support this non-standard filter mapping
                path = "/*";
            }
            if (!path.startsWith("*.")) {
                pathMatches.add(path);
            } else {
                extensionMatches.add(path.substring(2));
            }
        }
    }
    // now loop through all servlets.
    for (Map.Entry<String, ServletHandler> entry : servlets.getServletHandlers().entrySet()) {
        final ServletHandler handler = entry.getValue();
        // add the servlet to the appropriate path maps
        for (String path : handler.getManagedServlet().getServletInfo().getMappings()) {
            if (path.equals("/")) {
                // the default servlet
                pathMatches.add("/*");
                if (defaultServlet != null) {
                    throw UndertowServletMessages.MESSAGES.twoServletsWithSameMapping(path);
                }
                defaultServlet = handler;
            } else if (!path.startsWith("*.")) {
                // either an exact or a /* based path match
                if (path.isEmpty()) {
                    path = "/";
                }
                pathMatches.add(path);
                if (pathServlets.containsKey(path)) {
                    throw UndertowServletMessages.MESSAGES.twoServletsWithSameMapping(path);
                }
                pathServlets.put(path, handler);
            } else {
                // an extension match based servlet
                String ext = path.substring(2);
                extensionMatches.add(ext);
                if (extensionServlets.containsKey(ext)) {
                    throw UndertowServletMessages.MESSAGES.twoServletsWithSameMapping(path);
                }
                extensionServlets.put(ext, handler);
            }
        }
    }
    ServletHandler managedDefaultServlet = servlets.getServletHandler(DEFAULT_SERVLET_NAME);
    if (managedDefaultServlet == null) {
        // we always create a default servlet, even if it is not going to have any path mappings registered
        managedDefaultServlet = servlets.addServlet(new ServletInfo(DEFAULT_SERVLET_NAME, DefaultServlet.class));
    }
    if (defaultServlet == null) {
        // no explicit default servlet was specified, so we register our mapping
        pathMatches.add("/*");
        defaultServlet = managedDefaultServlet;
    }
    final ServletPathMatchesData.Builder builder = ServletPathMatchesData.builder();
    // these paths contain both /* and exact matches.
    for (final String path : pathMatches) {
        // resolve the target servlet, will return null if this is the default servlet
        MatchData targetServletMatch = resolveServletForPath(path, pathServlets, extensionServlets, defaultServlet);
        final Map<DispatcherType, List<ManagedFilter>> noExtension = new EnumMap<>(DispatcherType.class);
        final Map<String, Map<DispatcherType, List<ManagedFilter>>> extension = new HashMap<>();
        // any filters that match the extension key
        for (String ext : extensionMatches) {
            extension.put(ext, new EnumMap<DispatcherType, List<ManagedFilter>>(DispatcherType.class));
        }
        // loop over all the filters, and add them to the appropriate map in the correct order
        for (final FilterMappingInfo filterMapping : deploymentInfo.getFilterMappings()) {
            ManagedFilter filter = filters.getManagedFilter(filterMapping.getFilterName());
            if (filterMapping.getMappingType() == FilterMappingInfo.MappingType.SERVLET) {
                if (targetServletMatch.handler != null) {
                    if (filterMapping.getMapping().equals(targetServletMatch.handler.getManagedServlet().getServletInfo().getName()) || filterMapping.getMapping().equals("*")) {
                        addToListMap(noExtension, filterMapping.getDispatcher(), filter);
                    }
                }
                for (Map.Entry<String, Map<DispatcherType, List<ManagedFilter>>> entry : extension.entrySet()) {
                    ServletHandler pathServlet = targetServletMatch.handler;
                    boolean defaultServletMatch = targetServletMatch.defaultServlet;
                    if (defaultServletMatch && extensionServlets.containsKey(entry.getKey())) {
                        pathServlet = extensionServlets.get(entry.getKey());
                    }
                    if (filterMapping.getMapping().equals(pathServlet.getManagedServlet().getServletInfo().getName()) || filterMapping.getMapping().equals("*")) {
                        addToListMap(extension.get(entry.getKey()), filterMapping.getDispatcher(), filter);
                    }
                }
            } else {
                if (filterMapping.getMapping().isEmpty() || !filterMapping.getMapping().startsWith("*.")) {
                    if (isFilterApplicable(path, filterMapping.getMapping())) {
                        addToListMap(noExtension, filterMapping.getDispatcher(), filter);
                        for (Map<DispatcherType, List<ManagedFilter>> l : extension.values()) {
                            addToListMap(l, filterMapping.getDispatcher(), filter);
                        }
                    }
                } else {
                    addToListMap(extension.get(filterMapping.getMapping().substring(2)), filterMapping.getDispatcher(), filter);
                }
            }
        }
        // resolve any matches and add them to the builder
        if (path.endsWith("/*")) {
            String prefix = path.substring(0, path.length() - 2);
            // add the default non-extension match
            builder.addPrefixMatch(prefix, createHandler(deploymentInfo, targetServletMatch.handler, noExtension, targetServletMatch.matchedPath, targetServletMatch.defaultServlet, targetServletMatch.mappingMatch, targetServletMatch.userPath), targetServletMatch.defaultServlet || targetServletMatch.handler.getManagedServlet().getServletInfo().isRequireWelcomeFileMapping());
            // build up the chain for each non-extension match
            for (Map.Entry<String, Map<DispatcherType, List<ManagedFilter>>> entry : extension.entrySet()) {
                ServletHandler pathServlet = targetServletMatch.handler;
                String pathMatch = targetServletMatch.matchedPath;
                final boolean defaultServletMatch;
                final String servletMatchPattern;
                final MappingMatch mappingMatch;
                if (targetServletMatch.defaultServlet) {
                    // Path matches always take precedence over extension matches, however the default servlet is matched
                    // at a lower priority, after extension matches. The "/*" pattern is applied implicitly onto the
                    // default servlet. If there's an extension match in addition to a non-default servlet path match,
                    // the servlet path match is higher priority. However if the path match is the default servlets
                    // default catch-all path, the extension match is a higher priority.
                    ServletHandler extensionServletHandler = extensionServlets.get(entry.getKey());
                    if (extensionServletHandler != null) {
                        defaultServletMatch = false;
                        pathServlet = extensionServletHandler;
                        servletMatchPattern = "*." + entry.getKey();
                        mappingMatch = MappingMatch.EXTENSION;
                    } else {
                        defaultServletMatch = true;
                        servletMatchPattern = "/";
                        mappingMatch = MappingMatch.DEFAULT;
                    }
                } else {
                    defaultServletMatch = false;
                    servletMatchPattern = path;
                    mappingMatch = MappingMatch.PATH;
                }
                HttpHandler handler = pathServlet;
                if (!entry.getValue().isEmpty()) {
                    handler = new FilterHandler(entry.getValue(), deploymentInfo.isAllowNonStandardWrappers(), handler);
                }
                builder.addExtensionMatch(prefix, entry.getKey(), servletChain(handler, pathServlet.getManagedServlet(), entry.getValue(), pathMatch, deploymentInfo, defaultServletMatch, mappingMatch, servletMatchPattern));
            }
        } else if (path.isEmpty()) {
            // the context root match
            builder.addExactMatch("/", createHandler(deploymentInfo, targetServletMatch.handler, noExtension, targetServletMatch.matchedPath, targetServletMatch.defaultServlet, targetServletMatch.mappingMatch, targetServletMatch.userPath));
        } else {
            // we need to check for an extension match, so paths like /exact.txt will have the correct filter applied
            int lastSegmentIndex = path.lastIndexOf('/');
            String lastSegment;
            if (lastSegmentIndex > 0) {
                lastSegment = path.substring(lastSegmentIndex);
            } else {
                lastSegment = path;
            }
            if (lastSegment.contains(".")) {
                String ext = lastSegment.substring(lastSegment.lastIndexOf('.') + 1);
                if (extension.containsKey(ext)) {
                    Map<DispatcherType, List<ManagedFilter>> extMap = extension.get(ext);
                    builder.addExactMatch(path, createHandler(deploymentInfo, targetServletMatch.handler, extMap, targetServletMatch.matchedPath, targetServletMatch.defaultServlet, targetServletMatch.mappingMatch, targetServletMatch.userPath));
                } else {
                    builder.addExactMatch(path, createHandler(deploymentInfo, targetServletMatch.handler, noExtension, targetServletMatch.matchedPath, targetServletMatch.defaultServlet, targetServletMatch.mappingMatch, targetServletMatch.userPath));
                }
            } else {
                builder.addExactMatch(path, createHandler(deploymentInfo, targetServletMatch.handler, noExtension, targetServletMatch.matchedPath, targetServletMatch.defaultServlet, targetServletMatch.mappingMatch, targetServletMatch.userPath));
            }
        }
    }
    // these are used for name based dispatch
    for (Map.Entry<String, ServletHandler> entry : servlets.getServletHandlers().entrySet()) {
        final Map<DispatcherType, List<ManagedFilter>> filtersByDispatcher = new EnumMap<>(DispatcherType.class);
        for (final FilterMappingInfo filterMapping : deploymentInfo.getFilterMappings()) {
            ManagedFilter filter = filters.getManagedFilter(filterMapping.getFilterName());
            if (filterMapping.getMappingType() == FilterMappingInfo.MappingType.SERVLET) {
                if (filterMapping.getMapping().equals(entry.getKey())) {
                    addToListMap(filtersByDispatcher, filterMapping.getDispatcher(), filter);
                }
            }
        }
        if (filtersByDispatcher.isEmpty()) {
            builder.addNameMatch(entry.getKey(), servletChain(entry.getValue(), entry.getValue().getManagedServlet(), filtersByDispatcher, null, deploymentInfo, false, MappingMatch.EXACT, ""));
        } else {
            builder.addNameMatch(entry.getKey(), servletChain(new FilterHandler(filtersByDispatcher, deploymentInfo.isAllowNonStandardWrappers(), entry.getValue()), entry.getValue().getManagedServlet(), filtersByDispatcher, null, deploymentInfo, false, MappingMatch.EXACT, ""));
        }
    }
    return builder.build();
}
Also used : ManagedServlets(io.undertow.servlet.core.ManagedServlets) FilterMappingInfo(io.undertow.servlet.api.FilterMappingInfo) HashMap(java.util.HashMap) ServletInfo(io.undertow.servlet.api.ServletInfo) ArrayList(java.util.ArrayList) List(java.util.List) ManagedFilter(io.undertow.servlet.core.ManagedFilter) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) DispatcherType(javax.servlet.DispatcherType) EnumMap(java.util.EnumMap) ManagedFilters(io.undertow.servlet.core.ManagedFilters) HashSet(java.util.HashSet) HttpHandler(io.undertow.server.HttpHandler) MappingMatch(javax.servlet.http.MappingMatch) HashMap(java.util.HashMap) Map(java.util.Map) EnumMap(java.util.EnumMap)

Example 45 with DispatcherType

use of javax.servlet.DispatcherType in project tomee by apache.

the class TomcatRsRegistry method createRsHttpListener.

@Override
public AddressInfo createRsHttpListener(final String appId, final String webContext, final HttpListener listener, final ClassLoader classLoader, final String completePath, final String virtualHost, final String auth, final String realm) {
    String path = webContext;
    if (path == null) {
        throw new NullPointerException("contextRoot is null");
    }
    if (listener == null) {
        throw new NullPointerException("listener is null");
    }
    // find the existing host (we do not auto-create hosts)
    Container host;
    Context context = null;
    if (virtualHost == null) {
        host = hosts.getDefault();
    } else {
        host = hosts.get(virtualHost);
    }
    if (host == null) {
        for (final Host h : hosts) {
            context = findContext(h, webContext);
            if (context != null) {
                host = h;
                if (classLoader != null && classLoader.equals(context.getLoader().getClassLoader())) {
                    break;
                }
            // else try next to find something better
            }
        }
        if (host == null) {
            throw new IllegalArgumentException("Invalid virtual host '" + virtualHost + "'.  Do you have a matching Host entry in the server.xml?");
        }
    } else {
        context = findContext(host, webContext);
    }
    if (context == null) {
        throw new IllegalStateException("Invalid context '" + webContext + "'.  Cannot find context in host " + host.getName());
    }
    final CxfRsHttpListener cxfRsHttpListener = findCxfRsHttpListener(listener);
    final String description = "tomee-jaxrs-" + listener;
    String mapping = completePath;
    if (!completePath.endsWith("/*")) {
        // respect servlet spec (!= from our embedded listeners)
        if (completePath.endsWith("*")) {
            mapping = completePath.substring(0, completePath.length() - 1);
        }
        mapping = mapping + "/*";
    }
    final String urlPattern = removeWebContext(webContext, mapping);
    cxfRsHttpListener.setUrlPattern(urlPattern.substring(0, urlPattern.length() - 1));
    final FilterDef filterDef = new FilterDef();
    filterDef.setAsyncSupported("true");
    filterDef.setDescription(description);
    filterDef.setFilterName(description);
    filterDef.setDisplayName(description);
    filterDef.setFilter(new CXFJAXRSFilter(cxfRsHttpListener, context.findWelcomeFiles()));
    filterDef.setFilterClass(CXFJAXRSFilter.class.getName());
    // just keep base path
    filterDef.addInitParameter("mapping", urlPattern.substring(0, urlPattern.length() - "/*".length()));
    context.addFilterDef(filterDef);
    final FilterMap filterMap = new FilterMap();
    filterMap.addURLPattern(urlPattern);
    for (final DispatcherType type : DispatcherType.values()) {
        filterMap.setDispatcher(type.name());
    }
    filterMap.setFilterName(filterDef.getFilterName());
    context.addFilterMap(filterMap);
    Registrations.addFilterConfig(context, filterDef);
    path = address(connectors, host.getName(), webContext);
    final String key = address(connectors, host.getName(), completePath);
    listeners.put(new Key(appId, key), listener);
    return new AddressInfo(path, key);
}
Also used : Context(org.apache.catalina.Context) CxfRsHttpListener(org.apache.openejb.server.cxf.rs.CxfRsHttpListener) FilterDef(org.apache.tomcat.util.descriptor.web.FilterDef) Host(org.apache.catalina.Host) FilterMap(org.apache.tomcat.util.descriptor.web.FilterMap) Container(org.apache.catalina.Container) 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