Search in sources :

Example 26 with Servlet

use of jakarta.servlet.Servlet in project spring-framework by spring-projects.

the class MockFilterChainTests method doFilterWithServletAndFilters.

@Test
void doFilterWithServletAndFilters() throws Exception {
    Servlet servlet = mock(Servlet.class);
    MockFilter filter2 = new MockFilter(servlet);
    MockFilter filter1 = new MockFilter(null);
    MockFilterChain chain = new MockFilterChain(servlet, filter1, filter2);
    chain.doFilter(this.request, this.response);
    assertThat(filter1.invoked).isTrue();
    assertThat(filter2.invoked).isTrue();
    verify(servlet).service(this.request, this.response);
    assertThatIllegalStateException().isThrownBy(() -> chain.doFilter(this.request, this.response)).withMessage("This FilterChain has already been called!");
}
Also used : Servlet(jakarta.servlet.Servlet) Test(org.junit.jupiter.api.Test)

Example 27 with Servlet

use of jakarta.servlet.Servlet in project spring-framework by spring-projects.

the class DispatcherServletTests method servletHandlerAdapter.

@Test
public void servletHandlerAdapter() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/servlet.do");
    MockHttpServletResponse response = new MockHttpServletResponse();
    complexDispatcherServlet.service(request, response);
    assertThat(response.getContentAsString()).isEqualTo("body");
    Servlet myServlet = (Servlet) complexDispatcherServlet.getWebApplicationContext().getBean("myServlet");
    assertThat(myServlet.getServletConfig().getServletName()).isEqualTo("complex");
    assertThat(myServlet.getServletConfig().getServletContext()).isEqualTo(getServletContext());
    complexDispatcherServlet.destroy();
    assertThat((Object) myServlet.getServletConfig()).isNull();
}
Also used : MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) Servlet(jakarta.servlet.Servlet) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 28 with Servlet

use of jakarta.servlet.Servlet in project tomcat by apache.

the class TesterServletContainerInitializer2 method onStartup.

@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
    Servlet s = new TesterServlet();
    ServletRegistration.Dynamic r = ctx.addServlet("TesterServlet2", s);
    r.addMapping("/TesterServlet2");
}
Also used : ServletRegistration(jakarta.servlet.ServletRegistration) Servlet(jakarta.servlet.Servlet)

Example 29 with Servlet

use of jakarta.servlet.Servlet in project tomcat by apache.

the class StandardWrapperValve method invoke.

// --------------------------------------------------------- Public Methods
/**
 * Invoke the servlet we are managing, respecting the rules regarding
 * servlet lifecycle 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;
    }
    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
    ApplicationFilterChain filterChain = ApplicationFilterFactory.createFilterChain(request, wrapper, servlet);
    // Call the filter chain for this request
    // NOTE: This also calls the servlet's service() method
    Container container = this.container;
    try {
        if ((servlet != null) && (filterChain != null)) {
            // Swallow output if needed
            if (context.getSwallowOutput()) {
                try {
                    SystemLogHandler.startCapture();
                    if (request.isAsyncDispatching()) {
                        request.getAsyncContextInternal().doInternalDispatch();
                    } 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 {
                    filterChain.doFilter(request.getRequest(), response.getResponse());
                }
            }
        }
    } catch (ClientAbortException | CloseNowException e) {
        if (container.getLogger().isDebugEnabled()) {
            container.getLogger().debug(sm.getString("standardWrapper.serviceException", wrapper.getName(), context.getName()), 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);
    } finally {
        // Release the filter chain (if any) for this request
        if (filterChain != null) {
            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) {
                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(jakarta.servlet.UnavailableException) MessageBytes(org.apache.tomcat.util.buf.MessageBytes) IOException(java.io.IOException) ServletException(jakarta.servlet.ServletException) Container(org.apache.catalina.Container) CloseNowException(org.apache.coyote.CloseNowException) Servlet(jakarta.servlet.Servlet) ClientAbortException(org.apache.catalina.connector.ClientAbortException) DispatcherType(jakarta.servlet.DispatcherType)

Example 30 with Servlet

use of jakarta.servlet.Servlet in project tomcat by apache.

the class JspServletWrapper method getServlet.

public Servlet getServlet() throws ServletException {
    /*
         * DCL on 'reload' requires that 'reload' be volatile
         * (this also forces a read memory barrier, ensuring the new servlet
         * object is read consistently).
         *
         * When running in non development mode with a checkInterval it is
         * possible (see BZ 62603) for a race condition to cause failures
         * if a Servlet or tag is reloaded while a compile check is running
         */
    if (getReloadInternal() || theServlet == null) {
        synchronized (this) {
            // of different pages, but not the same page.
            if (getReloadInternal() || theServlet == null) {
                // This is to maintain the original protocol.
                destroy();
                final Servlet servlet;
                try {
                    InstanceManager instanceManager = InstanceManagerFactory.getInstanceManager(config);
                    servlet = (Servlet) instanceManager.newInstance(ctxt.getFQCN(), ctxt.getJspLoader());
                } catch (Exception e) {
                    Throwable t = ExceptionUtils.unwrapInvocationTargetException(e);
                    ExceptionUtils.handleThrowable(t);
                    throw new JasperException(t);
                }
                servlet.init(config);
                if (theServlet != null) {
                    ctxt.getRuntimeContext().incrementJspReloadCount();
                }
                theServlet = servlet;
                reload = false;
            // Volatile 'reload' forces in order write of 'theServlet' and new servlet object
            }
        }
    }
    return theServlet;
}
Also used : JasperException(org.apache.jasper.JasperException) InstanceManager(org.apache.tomcat.InstanceManager) Servlet(jakarta.servlet.Servlet) UnavailableException(jakarta.servlet.UnavailableException) ServletException(jakarta.servlet.ServletException) JasperException(org.apache.jasper.JasperException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Aggregations

Servlet (jakarta.servlet.Servlet)32 Test (org.junit.jupiter.api.Test)11 ServletContext (jakarta.servlet.ServletContext)6 ServletException (jakarta.servlet.ServletException)6 HttpServlet (jakarta.servlet.http.HttpServlet)6 MockServletWebServerFactory (org.springframework.boot.web.servlet.server.MockServletWebServerFactory)6 GenericServlet (jakarta.servlet.GenericServlet)5 IOException (java.io.IOException)5 Context (org.apache.catalina.Context)5 Filter (jakarta.servlet.Filter)4 UnavailableException (jakarta.servlet.UnavailableException)4 Tomcat (org.apache.catalina.startup.Tomcat)4 AsyncContext (jakarta.servlet.AsyncContext)3 ServletRequestWrapper (jakarta.servlet.ServletRequestWrapper)3 ServletResponseWrapper (jakarta.servlet.ServletResponseWrapper)3 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)3 Wrapper (org.apache.catalina.Wrapper)3 ByteChunk (org.apache.tomcat.util.buf.ByteChunk)3 ReflectorServletProcessor (org.atmosphere.handler.ReflectorServletProcessor)3 InOrder (org.mockito.InOrder)3