Search in sources :

Example 36 with DispatcherType

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

the class StandardWrapperValve method invoke.

// --------------------------------------------------------- Public Methods
/**
 * Invoke the servlet we are managing, respecting the rules regarding
 * servlet lifecycle and SingleThreadModel support.
 *
 * @param request Request to be processed
 * @param response Response to be produced
 *
 * @exception IOException if an input/output error occurred
 * @exception ServletException if a servlet error occurred
 */
@Override
public final void invoke(Request request, Response response) throws IOException, ServletException {
    // Initialize local variables we may need
    boolean unavailable = false;
    Throwable throwable = null;
    // This should be a Request attribute...
    long t1 = System.currentTimeMillis();
    requestCount.incrementAndGet();
    StandardWrapper wrapper = (StandardWrapper) getContainer();
    Servlet servlet = null;
    Context context = (Context) wrapper.getParent();
    // Check for the application being marked unavailable
    if (!context.getState().isAvailable()) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardContext.isUnavailable"));
        unavailable = true;
    }
    // Check for the servlet being marked unavailable
    if (!unavailable && wrapper.isUnavailable()) {
        container.getLogger().info(sm.getString("standardWrapper.isUnavailable", wrapper.getName()));
        long available = wrapper.getAvailable();
        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            response.setDateHeader("Retry-After", available);
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName()));
        } else if (available == Long.MAX_VALUE) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName()));
        }
        unavailable = true;
    }
    // Allocate a servlet instance to process this request
    try {
        if (!unavailable) {
            servlet = wrapper.allocate();
        }
    } catch (UnavailableException e) {
        container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e);
        long available = wrapper.getAvailable();
        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            response.setDateHeader("Retry-After", available);
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName()));
        } else if (available == Long.MAX_VALUE) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName()));
        }
    } catch (ServletException e) {
        container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e));
        throwable = e;
        exception(request, response, e);
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e);
        throwable = e;
        exception(request, response, e);
        servlet = null;
    }
    // Identify if the request is Comet related now that the servlet has been allocated
    boolean comet = false;
    if (servlet instanceof CometProcessor && Boolean.TRUE.equals(request.getAttribute(Globals.COMET_SUPPORTED_ATTR))) {
        comet = true;
        request.setComet(true);
    }
    MessageBytes requestPathMB = request.getRequestPathMB();
    DispatcherType dispatcherType = DispatcherType.REQUEST;
    if (request.getDispatcherType() == DispatcherType.ASYNC)
        dispatcherType = DispatcherType.ASYNC;
    request.setAttribute(Globals.DISPATCHER_TYPE_ATTR, dispatcherType);
    request.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR, requestPathMB);
    // Create the filter chain for this request
    ApplicationFilterFactory factory = ApplicationFilterFactory.getInstance();
    ApplicationFilterChain filterChain = factory.createFilterChain(request, wrapper, servlet);
    // Reset comet flag value after creating the filter chain
    request.setComet(false);
    // NOTE: This also calls the servlet's service() method
    try {
        if ((servlet != null) && (filterChain != null)) {
            // Swallow output if needed
            if (context.getSwallowOutput()) {
                try {
                    SystemLogHandler.startCapture();
                    if (request.isAsyncDispatching()) {
                        request.getAsyncContextInternal().doInternalDispatch();
                    } else if (comet) {
                        filterChain.doFilterEvent(request.getEvent());
                        request.setComet(true);
                    } else {
                        filterChain.doFilter(request.getRequest(), response.getResponse());
                    }
                } finally {
                    String log = SystemLogHandler.stopCapture();
                    if (log != null && log.length() > 0) {
                        context.getLogger().info(log);
                    }
                }
            } else {
                if (request.isAsyncDispatching()) {
                    request.getAsyncContextInternal().doInternalDispatch();
                } else if (comet) {
                    request.setComet(true);
                    filterChain.doFilterEvent(request.getEvent());
                } else {
                    filterChain.doFilter(request.getRequest(), response.getResponse());
                }
            }
        }
    } catch (ClientAbortException e) {
        throwable = e;
        exception(request, response, e);
    } catch (IOException e) {
        container.getLogger().error(sm.getString("standardWrapper.serviceException", wrapper.getName(), context.getName()), e);
        throwable = e;
        exception(request, response, e);
    } catch (UnavailableException e) {
        container.getLogger().error(sm.getString("standardWrapper.serviceException", wrapper.getName(), context.getName()), e);
        // throwable = e;
        // exception(request, response, e);
        wrapper.unavailable(e);
        long available = wrapper.getAvailable();
        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            response.setDateHeader("Retry-After", available);
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName()));
        } else if (available == Long.MAX_VALUE) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName()));
        }
    // Do not save exception in 'throwable', because we
    // do not want to do exception(request, response, e) processing
    } catch (ServletException e) {
        Throwable rootCause = StandardWrapper.getRootCause(e);
        if (!(rootCause instanceof ClientAbortException)) {
            container.getLogger().error(sm.getString("standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause);
        }
        throwable = e;
        exception(request, response, e);
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        container.getLogger().error(sm.getString("standardWrapper.serviceException", wrapper.getName(), context.getName()), e);
        throwable = e;
        exception(request, response, e);
    }
    // Release the filter chain (if any) for this request
    if (filterChain != null) {
        if (request.isComet()) {
            // If this is a Comet request, then the same chain will be used for the
            // processing of all subsequent events.
            filterChain.reuse();
        } else {
            filterChain.release();
        }
    }
    // Deallocate the allocated servlet instance
    try {
        if (servlet != null) {
            wrapper.deallocate(servlet);
        }
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e);
        if (throwable == null) {
            throwable = e;
            exception(request, response, e);
        }
    }
    // unload it and release this instance
    try {
        if ((servlet != null) && (wrapper.getAvailable() == Long.MAX_VALUE)) {
            wrapper.unload();
        }
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e);
        if (throwable == null) {
            throwable = e;
            exception(request, response, e);
        }
    }
    long t2 = System.currentTimeMillis();
    long time = t2 - t1;
    processingTime += time;
    if (time > maxTime)
        maxTime = time;
    if (time < minTime)
        minTime = time;
}
Also used : Context(org.apache.catalina.Context) UnavailableException(javax.servlet.UnavailableException) MessageBytes(org.apache.tomcat.util.buf.MessageBytes) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) CometProcessor(org.apache.catalina.comet.CometProcessor) Servlet(javax.servlet.Servlet) ClientAbortException(org.apache.catalina.connector.ClientAbortException) DispatcherType(javax.servlet.DispatcherType)

Example 37 with DispatcherType

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

the class ApplicationFilterRegistration method addMappingForServletNames.

@Override
public void addMappingForServletNames(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... servletNames) {
    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName(filterDef.getFilterName());
    if (dispatcherTypes != null) {
        for (DispatcherType dispatcherType : dispatcherTypes) {
            filterMap.setDispatcher(dispatcherType.name());
        }
    }
    if (servletNames != null) {
        for (String servletName : servletNames) {
            filterMap.addServletName(servletName);
        }
        if (isMatchAfter) {
            context.addFilterMap(filterMap);
        } else {
            context.addFilterMapBefore(filterMap);
        }
    }
// else error?
}
Also used : DispatcherType(javax.servlet.DispatcherType) FilterMap(org.apache.catalina.deploy.FilterMap)

Example 38 with DispatcherType

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

the class ApplicationFilterRegistration method addMappingForUrlPatterns.

@Override
public void addMappingForUrlPatterns(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... urlPatterns) {
    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName(filterDef.getFilterName());
    if (dispatcherTypes != null) {
        for (DispatcherType dispatcherType : dispatcherTypes) {
            filterMap.setDispatcher(dispatcherType.name());
        }
    }
    if (urlPatterns != null) {
        for (String urlPattern : urlPatterns) {
            filterMap.addURLPattern(urlPattern);
        }
        if (isMatchAfter) {
            context.addFilterMap(filterMap);
        } else {
            context.addFilterMapBefore(filterMap);
        }
    }
// else error?
}
Also used : DispatcherType(javax.servlet.DispatcherType) FilterMap(org.apache.catalina.deploy.FilterMap)

Example 39 with DispatcherType

use of javax.servlet.DispatcherType in project spring-session by spring-projects.

the class AbstractHttpSessionApplicationInitializer method registerFilter.

/**
 * Registers the provided filter using the {@link #isAsyncSessionSupported()} and
 * {@link #getSessionDispatcherTypes()}.
 *
 * @param servletContext the servlet context
 * @param insertBeforeOtherFilters should this Filter be inserted before or after
 * other {@link Filter}
 * @param filterName the filter name
 * @param filter the filter
 */
private void registerFilter(ServletContext servletContext, boolean insertBeforeOtherFilters, String filterName, Filter filter) {
    Dynamic registration = servletContext.addFilter(filterName, filter);
    if (registration == null) {
        throw new IllegalStateException("Duplicate Filter registration for '" + filterName + "'. Check to ensure the Filter is only configured once.");
    }
    registration.setAsyncSupported(isAsyncSessionSupported());
    EnumSet<DispatcherType> dispatcherTypes = getSessionDispatcherTypes();
    registration.addMappingForUrlPatterns(dispatcherTypes, !insertBeforeOtherFilters, "/*");
}
Also used : Dynamic(javax.servlet.FilterRegistration.Dynamic) DispatcherType(javax.servlet.DispatcherType)

Example 40 with DispatcherType

use of javax.servlet.DispatcherType in project ANNIS by korpling.

the class AnnisServiceRunner method createWebServer.

private void createWebServer() {
    // create beans
    ctx = new GenericXmlApplicationContext();
    ctx.setValidating(false);
    AnnisXmlContextHelper.prepareContext(ctx);
    ctx.load("file:" + Utils.getAnnisFile("conf/spring/Service.xml").getAbsolutePath());
    ctx.refresh();
    ResourceConfig rc = new PackagesResourceConfig("annis.service.internal", "annis.provider", "annis.rest.provider");
    final IoCComponentProviderFactory factory = new SpringComponentProviderFactory(rc, ctx);
    int port = overridePort == null ? ctx.getBean(QueryServiceImpl.class).getPort() : overridePort;
    try {
        // only allow connections from localhost
        // if the administrator wants to allow external acccess he *has* to
        // use a HTTP proxy which also should use SSL encryption
        InetSocketAddress addr = new InetSocketAddress("localhost", port);
        server = new Server(addr);
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);
        server.setThreadPool(new ExecutorThreadPool());
        ServletContainer jerseyContainer = new ServletContainer(rc) {

            @Override
            protected void initiate(ResourceConfig rc, WebApplication wa) {
                wa.initiate(rc, factory);
            }
        };
        ServletHolder holder = new ServletHolder(jerseyContainer);
        context.addServlet(holder, "/*");
        context.setInitParameter(EnvironmentLoader.ENVIRONMENT_CLASS_PARAM, MultipleIniWebEnvironment.class.getName());
        if (useAuthentification) {
            log.info("Using authentification");
            context.setInitParameter(EnvironmentLoader.CONFIG_LOCATIONS_PARAM, "file:" + System.getProperty("annis.home") + "/conf/shiro.ini," + "file:" + System.getProperty("annis.home") + "/conf/develop_shiro.ini");
        } else {
            log.warn("*NOT* using authentification, your ANNIS service *IS NOT SECURED*");
            context.setInitParameter(EnvironmentLoader.CONFIG_LOCATIONS_PARAM, "file:" + System.getProperty("annis.home") + "/conf/shiro_no_security.ini");
        }
        EnumSet<DispatcherType> gzipDispatcher = EnumSet.of(DispatcherType.REQUEST);
        context.addFilter(GzipFilter.class, "/*", gzipDispatcher);
        // configure Apache Shiro with the web application
        context.addEventListener(new EnvironmentLoaderListener());
        EnumSet<DispatcherType> shiroDispatchers = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.ERROR);
        context.addFilter(ShiroFilter.class, "/*", shiroDispatchers);
    } catch (IllegalArgumentException ex) {
        log.error("IllegalArgumentException at ANNIS service startup", ex);
        isShutdownRequested = true;
        errorCode = 101;
    } catch (NullPointerException ex) {
        log.error("NullPointerException at ANNIS service startup", ex);
        isShutdownRequested = true;
        errorCode = 101;
    } catch (AnnisRunnerException ex) {
        errorCode = ex.getExitCode();
    }
}
Also used : EnvironmentLoaderListener(org.apache.shiro.web.env.EnvironmentLoaderListener) Server(org.eclipse.jetty.server.Server) MultipleIniWebEnvironment(annis.security.MultipleIniWebEnvironment) SpringComponentProviderFactory(com.sun.jersey.spi.spring.container.SpringComponentProviderFactory) InetSocketAddress(java.net.InetSocketAddress) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) GenericXmlApplicationContext(org.springframework.context.support.GenericXmlApplicationContext) PackagesResourceConfig(com.sun.jersey.api.core.PackagesResourceConfig) IoCComponentProviderFactory(com.sun.jersey.core.spi.component.ioc.IoCComponentProviderFactory) AnnisRunnerException(annis.AnnisRunnerException) ServletContainer(com.sun.jersey.spi.container.servlet.ServletContainer) ExecutorThreadPool(org.eclipse.jetty.util.thread.ExecutorThreadPool) PackagesResourceConfig(com.sun.jersey.api.core.PackagesResourceConfig) ResourceConfig(com.sun.jersey.api.core.ResourceConfig) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) WebApplication(com.sun.jersey.spi.container.WebApplication) 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