Search in sources :

Example 1 with Servlet

use of javax.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
     * at least one 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 (!singleThreadModel && (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);
            // http://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);
            }
        }
        processServletSecurityAnnotation(servlet.getClass());
        // Special handling for ContainerServlet instances
        if ((servlet instanceof ContainerServlet) && (isContainerProvidedServlet(servletClass) || ((Context) getParent()).getPrivileged())) {
            ((ContainerServlet) servlet).setWrapper(this);
        }
        classLoadTime = (int) (System.currentTimeMillis() - t1);
        if (servlet instanceof SingleThreadModel) {
            if (instancePool == null) {
                instancePool = new Stack<>();
            }
            singleThreadModel = true;
        }
        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 : PrintStream(java.io.PrintStream) InstanceManager(org.apache.tomcat.InstanceManager) ContainerServlet(org.apache.catalina.ContainerServlet) ServletException(javax.servlet.ServletException) MultipartConfigElement(javax.servlet.MultipartConfigElement) MultipartConfig(javax.servlet.annotation.MultipartConfig) Servlet(javax.servlet.Servlet) ContainerServlet(org.apache.catalina.ContainerServlet) SingleThreadModel(javax.servlet.SingleThreadModel)

Example 2 with Servlet

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

the class StandardWrapper method unload.

/**
     * Unload all initialized instances of this servlet, after calling the
     * <code>destroy()</code> method for each instance.  This can be used,
     * for example, prior to shutting down the entire servlet engine, or
     * prior to reloading all of the classes from the Loader associated with
     * our Loader's repository.
     *
     * @exception ServletException if an exception is thrown by the
     *  destroy() method
     */
@Override
public synchronized void unload() throws ServletException {
    // Nothing to do if we have never loaded the instance
    if (!singleThreadModel && (instance == null))
        return;
    unloading = true;
    // (possibly more than once if non-STM)
    if (countAllocated.get() > 0) {
        int nRetries = 0;
        long delay = unloadDelay / 20;
        while ((nRetries < 21) && (countAllocated.get() > 0)) {
            if ((nRetries % 10) == 0) {
                log.info(sm.getString("standardWrapper.waiting", countAllocated.toString(), getName()));
            }
            try {
                Thread.sleep(delay);
            } catch (InterruptedException e) {
            // Ignore
            }
            nRetries++;
        }
    }
    if (instanceInitialized) {
        PrintStream out = System.out;
        if (swallowOutput) {
            SystemLogHandler.startCapture();
        }
        // Call the servlet destroy() method
        try {
            if (Globals.IS_SECURITY_ENABLED) {
                try {
                    SecurityUtil.doAsPrivilege("destroy", instance);
                } finally {
                    SecurityUtil.remove(instance);
                }
            } else {
                instance.destroy();
            }
        } catch (Throwable t) {
            t = ExceptionUtils.unwrapInvocationTargetException(t);
            ExceptionUtils.handleThrowable(t);
            instance = null;
            instancePool = null;
            nInstances = 0;
            fireContainerEvent("unload", this);
            unloading = false;
            throw new ServletException(sm.getString("standardWrapper.destroyException", getName()), t);
        } finally {
            // Annotation processing
            if (!((Context) getParent()).getIgnoreAnnotations()) {
                try {
                    ((Context) getParent()).getInstanceManager().destroyInstance(instance);
                } catch (Throwable t) {
                    ExceptionUtils.handleThrowable(t);
                    log.error(sm.getString("standardWrapper.destroyInstance", getName()), t);
                }
            }
            // Write captured output
            if (swallowOutput) {
                String log = SystemLogHandler.stopCapture();
                if (log != null && log.length() > 0) {
                    if (getServletContext() != null) {
                        getServletContext().log(log);
                    } else {
                        out.println(log);
                    }
                }
            }
        }
    }
    // Deregister the destroyed instance
    instance = null;
    instanceInitialized = false;
    if (isJspServlet && jspMonitorON != null) {
        Registry.getRegistry(null, null).unregisterComponent(jspMonitorON);
    }
    if (singleThreadModel && (instancePool != null)) {
        try {
            while (!instancePool.isEmpty()) {
                Servlet s = instancePool.pop();
                if (Globals.IS_SECURITY_ENABLED) {
                    try {
                        SecurityUtil.doAsPrivilege("destroy", s);
                    } finally {
                        SecurityUtil.remove(s);
                    }
                } else {
                    s.destroy();
                }
                // Annotation processing
                if (!((Context) getParent()).getIgnoreAnnotations()) {
                    ((StandardContext) getParent()).getInstanceManager().destroyInstance(s);
                }
            }
        } catch (Throwable t) {
            t = ExceptionUtils.unwrapInvocationTargetException(t);
            ExceptionUtils.handleThrowable(t);
            instancePool = null;
            nInstances = 0;
            unloading = false;
            fireContainerEvent("unload", this);
            throw new ServletException(sm.getString("standardWrapper.destroyException", getName()), t);
        }
        instancePool = null;
        nInstances = 0;
    }
    singleThreadModel = false;
    unloading = false;
    fireContainerEvent("unload", this);
}
Also used : ServletException(javax.servlet.ServletException) PrintStream(java.io.PrintStream) Servlet(javax.servlet.Servlet) ContainerServlet(org.apache.catalina.ContainerServlet)

Example 3 with Servlet

use of javax.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(methodsCache, 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(javax.servlet.Servlet) Method(java.lang.reflect.Method)

Example 4 with Servlet

use of javax.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(javax.servlet.AsyncContext) Context(org.apache.catalina.Context) TesterContext(org.apache.tomcat.unittest.TesterContext) Wrapper(org.apache.catalina.Wrapper) ServletResponseWrapper(javax.servlet.ServletResponseWrapper) ServletRequestWrapper(javax.servlet.ServletRequestWrapper) Tomcat(org.apache.catalina.startup.Tomcat) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) HttpServlet(javax.servlet.http.HttpServlet) Servlet(javax.servlet.Servlet) GenericServlet(javax.servlet.GenericServlet)

Example 5 with Servlet

use of javax.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(javax.servlet.ServletRegistration) Servlet(javax.servlet.Servlet)

Aggregations

Servlet (javax.servlet.Servlet)86 Test (org.junit.Test)18 HttpServlet (javax.servlet.http.HttpServlet)16 ServletException (javax.servlet.ServletException)15 IOException (java.io.IOException)11 OptingServlet (org.apache.sling.api.servlets.OptingServlet)11 GenericServlet (javax.servlet.GenericServlet)10 DefaultErrorHandlerServlet (org.apache.sling.servlets.resolver.internal.defaults.DefaultErrorHandlerServlet)9 DefaultServlet (org.apache.sling.servlets.resolver.internal.defaults.DefaultServlet)9 ServletContext (javax.servlet.ServletContext)8 UnavailableException (javax.servlet.UnavailableException)8 Resource (org.apache.sling.api.resource.Resource)8 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)8 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)7 MockServletWebServerFactory (org.springframework.boot.web.servlet.server.MockServletWebServerFactory)7 ServletInfo (io.undertow.servlet.api.ServletInfo)6 ArrayList (java.util.ArrayList)5 Filter (javax.servlet.Filter)5 Context (org.apache.catalina.Context)5 SlingHttpServletResponse (org.apache.sling.api.SlingHttpServletResponse)5