Search in sources :

Example 6 with Servlet

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

the class TesterServletContainerInitializer1 method onStartup.

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

Example 7 with Servlet

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

the class StandardWrapper method loadServlet.

/**
 * Load and initialize an instance of this servlet, if there is not already
 * an initialized instance.  This can be used, for example, to load servlets
 * that are marked in the deployment descriptor to be loaded at server
 * startup time.
 *
 * @return the loaded Servlet instance
 * @throws ServletException for a Servlet load error
 */
public synchronized Servlet loadServlet() throws ServletException {
    // Nothing to do if we already have an instance or an instance pool
    if (instance != null) {
        return instance;
    }
    PrintStream out = System.out;
    if (swallowOutput) {
        SystemLogHandler.startCapture();
    }
    Servlet servlet;
    try {
        long t1 = System.currentTimeMillis();
        // Complain if no servlet class has been specified
        if (servletClass == null) {
            unavailable(null);
            throw new ServletException(sm.getString("standardWrapper.notClass", getName()));
        }
        InstanceManager instanceManager = ((StandardContext) getParent()).getInstanceManager();
        try {
            servlet = (Servlet) instanceManager.newInstance(servletClass);
        } catch (ClassCastException e) {
            unavailable(null);
            // Restore the context ClassLoader
            throw new ServletException(sm.getString("standardWrapper.notServlet", servletClass), e);
        } catch (Throwable e) {
            e = ExceptionUtils.unwrapInvocationTargetException(e);
            ExceptionUtils.handleThrowable(e);
            unavailable(null);
            // https://bz.apache.org/bugzilla/show_bug.cgi?id=36630
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("standardWrapper.instantiate", servletClass), e);
            }
            // Restore the context ClassLoader
            throw new ServletException(sm.getString("standardWrapper.instantiate", servletClass), e);
        }
        if (multipartConfigElement == null) {
            MultipartConfig annotation = servlet.getClass().getAnnotation(MultipartConfig.class);
            if (annotation != null) {
                multipartConfigElement = new MultipartConfigElement(annotation);
            }
        }
        // to load ContainerServlets
        if (servlet instanceof ContainerServlet) {
            ((ContainerServlet) servlet).setWrapper(this);
        }
        classLoadTime = (int) (System.currentTimeMillis() - t1);
        initServlet(servlet);
        fireContainerEvent("load", this);
        loadTime = System.currentTimeMillis() - t1;
    } finally {
        if (swallowOutput) {
            String log = SystemLogHandler.stopCapture();
            if (log != null && log.length() > 0) {
                if (getServletContext() != null) {
                    getServletContext().log(log);
                } else {
                    out.println(log);
                }
            }
        }
    }
    return servlet;
}
Also used : ServletException(jakarta.servlet.ServletException) PrintStream(java.io.PrintStream) MultipartConfigElement(jakarta.servlet.MultipartConfigElement) MultipartConfig(jakarta.servlet.annotation.MultipartConfig) InstanceManager(org.apache.tomcat.InstanceManager) Servlet(jakarta.servlet.Servlet) ContainerServlet(org.apache.catalina.ContainerServlet) ContainerServlet(org.apache.catalina.ContainerServlet)

Example 8 with Servlet

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

the class JspServletWrapper method service.

public void service(HttpServletRequest request, HttpServletResponse response, boolean precompile) throws ServletException, IOException, FileNotFoundException {
    Servlet servlet;
    try {
        if (ctxt.isRemoved()) {
            throw new FileNotFoundException(jspUri);
        }
        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            if (available > System.currentTimeMillis()) {
                response.setDateHeader("Retry-After", available);
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, Localizer.getMessage("jsp.error.unavailable"));
                return;
            }
            // Wait period has expired. Reset.
            available = 0;
        }
        /*
             * (1) Compile
             */
        if (options.getDevelopment() || mustCompile) {
            synchronized (this) {
                if (options.getDevelopment() || mustCompile) {
                    // The following sets reload to true, if necessary
                    ctxt.compile();
                    mustCompile = false;
                }
            }
        } else {
            if (compileException != null) {
                // Throw cached compilation exception
                throw compileException;
            }
        }
        /*
             * (2) (Re)load servlet class file
             */
        servlet = getServlet();
        // If a page is to be precompiled only, return.
        if (precompile) {
            return;
        }
    } catch (FileNotFoundException fnfe) {
        // File has been removed. Let caller handle this.
        throw fnfe;
    } catch (ServletException | IOException | IllegalStateException ex) {
        if (options.getDevelopment()) {
            throw handleJspException(ex);
        }
        throw ex;
    } catch (Exception ex) {
        if (options.getDevelopment()) {
            throw handleJspException(ex);
        }
        throw new JasperException(ex);
    }
    try {
        /*
             * (3) Handle limitation of number of loaded Jsps
             */
        if (unloadAllowed) {
            synchronized (this) {
                if (unloadByCount) {
                    if (unloadHandle == null) {
                        unloadHandle = ctxt.getRuntimeContext().push(this);
                    } else if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) {
                        ctxt.getRuntimeContext().makeYoungest(unloadHandle);
                        lastUsageTime = System.currentTimeMillis();
                    }
                } else {
                    if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) {
                        lastUsageTime = System.currentTimeMillis();
                    }
                }
            }
        }
        /*
             * (4) Service request
             */
        servlet.service(request, response);
    } catch (UnavailableException ex) {
        String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI);
        if (includeRequestUri != null) {
            // servlet engine.
            throw ex;
        }
        int unavailableSeconds = ex.getUnavailableSeconds();
        if (unavailableSeconds <= 0) {
            // Arbitrary default
            unavailableSeconds = 60;
        }
        available = System.currentTimeMillis() + (unavailableSeconds * 1000L);
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage());
    } catch (ServletException | IllegalStateException ex) {
        if (options.getDevelopment()) {
            throw handleJspException(ex);
        }
        throw ex;
    } catch (IOException ex) {
        if (options.getDevelopment()) {
            throw new IOException(handleJspException(ex).getMessage(), ex);
        }
        throw ex;
    } catch (Exception ex) {
        if (options.getDevelopment()) {
            throw handleJspException(ex);
        }
        throw new JasperException(ex);
    }
}
Also used : ServletException(jakarta.servlet.ServletException) JasperException(org.apache.jasper.JasperException) FileNotFoundException(java.io.FileNotFoundException) UnavailableException(jakarta.servlet.UnavailableException) Servlet(jakarta.servlet.Servlet) IOException(java.io.IOException) UnavailableException(jakarta.servlet.UnavailableException) ServletException(jakarta.servlet.ServletException) JasperException(org.apache.jasper.JasperException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Example 9 with Servlet

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

the class SecurityUtil method doAsPrivilege.

/**
 * Perform work as a particular <code>Subject</code>. Here the work
 * will be granted to a <code>null</code> subject.
 *
 * @param methodName the method to apply the security restriction
 * @param targetObject the <code>Servlet</code> on which the method will
 *  be called.
 * @param targetParameterTypes <code>Class</code> array used to instantiate a
 *  <code>Method</code> object.
 * @param targetArguments <code>Object</code> array contains the
 *  runtime parameters instance.
 * @param principal the <code>Principal</code> to which the security
 *  privilege applies
 * @throws Exception an execution error occurred
 */
public static void doAsPrivilege(final String methodName, final Servlet targetObject, final Class<?>[] targetParameterTypes, final Object[] targetArguments, Principal principal) throws Exception {
    Method method = null;
    Method[] methodsCache = classCache.get(Servlet.class);
    if (methodsCache == null) {
        method = createMethodAndCacheIt(null, Servlet.class, methodName, targetParameterTypes);
    } else {
        method = findMethod(methodsCache, methodName);
        if (method == null) {
            method = createMethodAndCacheIt(methodsCache, Servlet.class, methodName, targetParameterTypes);
        }
    }
    execute(method, targetObject, targetArguments, principal);
}
Also used : Servlet(jakarta.servlet.Servlet) Method(java.lang.reflect.Method)

Example 10 with Servlet

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

the class TestAsyncContextImpl method doTestAsyncRequestURI.

private void doTestAsyncRequestURI(String uri) throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    Servlet servlet = new AsyncRequestUriServlet();
    Wrapper wrapper1 = Tomcat.addServlet(ctx, "bug57559", servlet);
    wrapper1.setAsyncSupported(true);
    ctx.addServletMappingDecoded("/", "bug57559");
    tomcat.start();
    ByteChunk body = getUrl("http://localhost:" + getPort() + uri);
    Assert.assertEquals(uri, body.toString());
}
Also used : AsyncContext(jakarta.servlet.AsyncContext) Context(org.apache.catalina.Context) TesterContext(org.apache.tomcat.unittest.TesterContext) Wrapper(org.apache.catalina.Wrapper) ServletResponseWrapper(jakarta.servlet.ServletResponseWrapper) ServletRequestWrapper(jakarta.servlet.ServletRequestWrapper) Tomcat(org.apache.catalina.startup.Tomcat) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) Servlet(jakarta.servlet.Servlet) GenericServlet(jakarta.servlet.GenericServlet) HttpServlet(jakarta.servlet.http.HttpServlet)

Aggregations

Servlet (jakarta.servlet.Servlet)20 ServletException (jakarta.servlet.ServletException)6 HttpServlet (jakarta.servlet.http.HttpServlet)6 IOException (java.io.IOException)5 Context (org.apache.catalina.Context)5 UnavailableException (jakarta.servlet.UnavailableException)4 Tomcat (org.apache.catalina.startup.Tomcat)4 Test (org.junit.jupiter.api.Test)4 AsyncContext (jakarta.servlet.AsyncContext)3 GenericServlet (jakarta.servlet.GenericServlet)3 ServletRequestWrapper (jakarta.servlet.ServletRequestWrapper)3 ServletResponseWrapper (jakarta.servlet.ServletResponseWrapper)3 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)3 Wrapper (org.apache.catalina.Wrapper)3 TesterContext (org.apache.tomcat.unittest.TesterContext)3 ByteChunk (org.apache.tomcat.util.buf.ByteChunk)3 ReflectorServletProcessor (org.atmosphere.handler.ReflectorServletProcessor)3 ServletRegistration (jakarta.servlet.ServletRegistration)2 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)2 FileNotFoundException (java.io.FileNotFoundException)2