Search in sources :

Example 81 with ServletException

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

the class StandardWrapper method allocate.

/**
 * Allocate an initialized instance of this Servlet that is ready to have
 * its <code>service()</code> method called.
 *
 * @exception ServletException if the servlet init() method threw
 *  an exception
 * @exception ServletException if a loading error occurs
 */
@Override
public Servlet allocate() throws ServletException {
    // If we are currently unloading this servlet, throw an exception
    if (unloading) {
        throw new ServletException(sm.getString("standardWrapper.unloading", getName()));
    }
    boolean newInstance = false;
    // Load and initialize our instance if necessary
    if (instance == null || !instanceInitialized) {
        synchronized (this) {
            if (instance == null) {
                try {
                    if (log.isDebugEnabled()) {
                        log.debug("Allocating instance");
                    }
                    instance = loadServlet();
                    newInstance = true;
                    // Increment here to prevent a race condition
                    // with unload. Bug 43683, test case #3
                    countAllocated.incrementAndGet();
                } catch (ServletException e) {
                    throw e;
                } catch (Throwable e) {
                    ExceptionUtils.handleThrowable(e);
                    throw new ServletException(sm.getString("standardWrapper.allocate"), e);
                }
            }
            if (!instanceInitialized) {
                initServlet(instance);
            }
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("  Returning instance");
    }
    // time of creation
    if (!newInstance) {
        countAllocated.incrementAndGet();
    }
    return instance;
}
Also used : ServletException(jakarta.servlet.ServletException)

Example 82 with ServletException

use of jakarta.servlet.ServletException 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 83 with ServletException

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

the class HTMLManagerServlet method doGet.

// --------------------------------------------------------- Public Methods
/**
 * Process a GET request for the specified resource.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet-specified error occurs
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    StringManager smClient = StringManager.getManager(Constants.Package, request.getLocales());
    // Identify the request parameters that we need
    // By obtaining the command from the pathInfo, per-command security can
    // be configured in web.xml
    String command = request.getPathInfo();
    String path = request.getParameter("path");
    ContextName cn = null;
    if (path != null) {
        cn = new ContextName(path, request.getParameter("version"));
    }
    // Prepare our output writer to generate the response message
    response.setContentType("text/html; charset=" + Constants.CHARSET);
    String message = "";
    // Process the requested command
    if (command == null || command.equals("/")) {
    // No command == list
    } else if (command.equals("/list")) {
    // List always displayed - nothing to do here
    } else if (command.equals("/sessions")) {
        try {
            doSessions(cn, request, response, smClient);
            return;
        } catch (Exception e) {
            log(sm.getString("htmlManagerServlet.error.sessions", cn), e);
            message = smClient.getString("managerServlet.exception", e.toString());
        }
    } else if (command.equals("/sslConnectorCiphers")) {
        sslConnectorCiphers(request, response, smClient);
    } else if (command.equals("/sslConnectorCerts")) {
        sslConnectorCerts(request, response, smClient);
    } else if (command.equals("/sslConnectorTrustedCerts")) {
        sslConnectorTrustedCerts(request, response, smClient);
    } else if (command.equals("/upload") || command.equals("/deploy") || command.equals("/reload") || command.equals("/undeploy") || command.equals("/expire") || command.equals("/start") || command.equals("/stop")) {
        message = smClient.getString("managerServlet.postCommand", command);
    } else {
        message = smClient.getString("managerServlet.unknownCommand", command);
    }
    list(request, response, message, smClient);
}
Also used : ServletException(jakarta.servlet.ServletException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) StringManager(org.apache.tomcat.util.res.StringManager) ContextName(org.apache.catalina.util.ContextName)

Example 84 with ServletException

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

the class StatusManagerServlet method init.

// --------------------------------------------------------- Public Methods
/**
 * Initialize this servlet.
 */
@Override
public void init() throws ServletException {
    // Retrieve the MBean server
    mBeanServer = Registry.getRegistry(null, null).getMBeanServer();
    try {
        // Query Thread Pools
        String onStr = "*:type=ThreadPool,*";
        ObjectName objectName = new ObjectName(onStr);
        Set<ObjectInstance> set = mBeanServer.queryMBeans(objectName, null);
        Iterator<ObjectInstance> iterator = set.iterator();
        while (iterator.hasNext()) {
            ObjectInstance oi = iterator.next();
            threadPools.addElement(oi.getObjectName());
        }
        // Query Global Request Processors
        onStr = "*:type=GlobalRequestProcessor,*";
        objectName = new ObjectName(onStr);
        set = mBeanServer.queryMBeans(objectName, null);
        iterator = set.iterator();
        while (iterator.hasNext()) {
            ObjectInstance oi = iterator.next();
            globalRequestProcessors.addElement(oi.getObjectName());
        }
        // Query Request Processors
        onStr = "*:type=RequestProcessor,*";
        objectName = new ObjectName(onStr);
        set = mBeanServer.queryMBeans(objectName, null);
        iterator = set.iterator();
        while (iterator.hasNext()) {
            ObjectInstance oi = iterator.next();
            requestProcessors.addElement(oi.getObjectName());
        }
        // Register with MBean server
        onStr = "JMImplementation:type=MBeanServerDelegate";
        objectName = new ObjectName(onStr);
        mBeanServer.addNotificationListener(objectName, this, null, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : ObjectInstance(javax.management.ObjectInstance) IOException(java.io.IOException) ServletException(jakarta.servlet.ServletException) UnknownHostException(java.net.UnknownHostException) ObjectName(javax.management.ObjectName)

Example 85 with ServletException

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

the class StatusManagerServlet method doGet.

/**
 * Process a GET request for the specified resource.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet-specified error occurs
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    StringManager smClient = StringManager.getManager(Constants.Package, request.getLocales());
    // mode is flag for HTML or XML output
    int mode = 0;
    // if ?XML=true, set the mode to XML
    if (request.getParameter("XML") != null && request.getParameter("XML").equals("true")) {
        mode = 1;
    }
    StatusTransformer.setContentType(response, mode);
    PrintWriter writer = response.getWriter();
    boolean completeStatus = false;
    if ((request.getPathInfo() != null) && (request.getPathInfo().equals("/all"))) {
        completeStatus = true;
    }
    // use StatusTransformer to output status
    Object[] args = new Object[1];
    args[0] = request.getContextPath();
    StatusTransformer.writeHeader(writer, args, mode);
    // Body Header Section
    args = new Object[2];
    args[0] = request.getContextPath();
    if (completeStatus) {
        args[1] = smClient.getString("statusServlet.complete");
    } else {
        args[1] = smClient.getString("statusServlet.title");
    }
    // use StatusTransformer to output status
    StatusTransformer.writeBody(writer, args, mode);
    // Manager Section
    args = new Object[9];
    args[0] = smClient.getString("htmlManagerServlet.manager");
    args[1] = response.encodeURL(request.getContextPath() + "/html/list");
    args[2] = smClient.getString("htmlManagerServlet.list");
    // External link
    args[3] = (request.getContextPath() + "/" + smClient.getString("htmlManagerServlet.helpHtmlManagerFile"));
    args[4] = smClient.getString("htmlManagerServlet.helpHtmlManager");
    // External link
    args[5] = (request.getContextPath() + "/" + smClient.getString("htmlManagerServlet.helpManagerFile"));
    args[6] = smClient.getString("htmlManagerServlet.helpManager");
    if (completeStatus) {
        args[7] = response.encodeURL(request.getContextPath() + "/status");
        args[8] = smClient.getString("statusServlet.title");
    } else {
        args[7] = response.encodeURL(request.getContextPath() + "/status/all");
        args[8] = smClient.getString("statusServlet.complete");
    }
    // use StatusTransformer to output status
    StatusTransformer.writeManager(writer, args, mode);
    // Server Header Section
    args = new Object[9];
    args[0] = smClient.getString("htmlManagerServlet.serverTitle");
    args[1] = smClient.getString("htmlManagerServlet.serverVersion");
    args[2] = smClient.getString("htmlManagerServlet.serverJVMVersion");
    args[3] = smClient.getString("htmlManagerServlet.serverJVMVendor");
    args[4] = smClient.getString("htmlManagerServlet.serverOSName");
    args[5] = smClient.getString("htmlManagerServlet.serverOSVersion");
    args[6] = smClient.getString("htmlManagerServlet.serverOSArch");
    args[7] = smClient.getString("htmlManagerServlet.serverHostname");
    args[8] = smClient.getString("htmlManagerServlet.serverIPAddress");
    // use StatusTransformer to output status
    StatusTransformer.writePageHeading(writer, args, mode);
    // Server Row Section
    args = new Object[8];
    args[0] = ServerInfo.getServerInfo();
    args[1] = System.getProperty("java.runtime.version");
    args[2] = System.getProperty("java.vm.vendor");
    args[3] = System.getProperty("os.name");
    args[4] = System.getProperty("os.version");
    args[5] = System.getProperty("os.arch");
    try {
        InetAddress address = InetAddress.getLocalHost();
        args[6] = address.getHostName();
        args[7] = address.getHostAddress();
    } catch (UnknownHostException e) {
        args[6] = "-";
        args[7] = "-";
    }
    // use StatusTransformer to output status
    StatusTransformer.writeServerInfo(writer, args, mode);
    try {
        // Display virtual machine statistics
        args = new Object[9];
        args[0] = smClient.getString("htmlManagerServlet.jvmFreeMemory");
        args[1] = smClient.getString("htmlManagerServlet.jvmTotalMemory");
        args[2] = smClient.getString("htmlManagerServlet.jvmMaxMemory");
        args[3] = smClient.getString("htmlManagerServlet.jvmTableTitleMemoryPool");
        args[4] = smClient.getString("htmlManagerServlet.jvmTableTitleType");
        args[5] = smClient.getString("htmlManagerServlet.jvmTableTitleInitial");
        args[6] = smClient.getString("htmlManagerServlet.jvmTableTitleTotal");
        args[7] = smClient.getString("htmlManagerServlet.jvmTableTitleMaximum");
        args[8] = smClient.getString("htmlManagerServlet.jvmTableTitleUsed");
        // use StatusTransformer to output status
        StatusTransformer.writeVMState(writer, mode, args);
        Enumeration<ObjectName> enumeration = threadPools.elements();
        while (enumeration.hasMoreElements()) {
            ObjectName objectName = enumeration.nextElement();
            String name = objectName.getKeyProperty("name");
            args = new Object[19];
            args[0] = smClient.getString("htmlManagerServlet.connectorStateMaxThreads");
            args[1] = smClient.getString("htmlManagerServlet.connectorStateThreadCount");
            args[2] = smClient.getString("htmlManagerServlet.connectorStateThreadBusy");
            args[3] = smClient.getString("htmlManagerServlet.connectorStateAliveSocketCount");
            args[4] = smClient.getString("htmlManagerServlet.connectorStateMaxProcessingTime");
            args[5] = smClient.getString("htmlManagerServlet.connectorStateProcessingTime");
            args[6] = smClient.getString("htmlManagerServlet.connectorStateRequestCount");
            args[7] = smClient.getString("htmlManagerServlet.connectorStateErrorCount");
            args[8] = smClient.getString("htmlManagerServlet.connectorStateBytesReceived");
            args[9] = smClient.getString("htmlManagerServlet.connectorStateBytesSent");
            args[10] = smClient.getString("htmlManagerServlet.connectorStateTableTitleStage");
            args[11] = smClient.getString("htmlManagerServlet.connectorStateTableTitleTime");
            args[12] = smClient.getString("htmlManagerServlet.connectorStateTableTitleBSent");
            args[13] = smClient.getString("htmlManagerServlet.connectorStateTableTitleBRecv");
            args[14] = smClient.getString("htmlManagerServlet.connectorStateTableTitleClientForw");
            args[15] = smClient.getString("htmlManagerServlet.connectorStateTableTitleClientAct");
            args[16] = smClient.getString("htmlManagerServlet.connectorStateTableTitleVHost");
            args[17] = smClient.getString("htmlManagerServlet.connectorStateTableTitleRequest");
            args[18] = smClient.getString("htmlManagerServlet.connectorStateHint");
            // use StatusTransformer to output status
            StatusTransformer.writeConnectorState(writer, objectName, name, mBeanServer, globalRequestProcessors, requestProcessors, mode, args);
        }
        if ((request.getPathInfo() != null) && (request.getPathInfo().equals("/all"))) {
            // Note: Retrieving the full status is much slower
            // use StatusTransformer to output status
            StatusTransformer.writeDetailedState(writer, mBeanServer, mode);
        }
    } catch (Exception e) {
        throw new ServletException(e);
    }
    // use StatusTransformer to output status
    StatusTransformer.writeFooter(writer, mode);
}
Also used : UnknownHostException(java.net.UnknownHostException) IOException(java.io.IOException) ServletException(jakarta.servlet.ServletException) UnknownHostException(java.net.UnknownHostException) StringManager(org.apache.tomcat.util.res.StringManager) ObjectName(javax.management.ObjectName) ServletException(jakarta.servlet.ServletException) InetAddress(java.net.InetAddress) PrintWriter(java.io.PrintWriter)

Aggregations

ServletException (jakarta.servlet.ServletException)115 IOException (java.io.IOException)72 Test (org.junit.jupiter.api.Test)26 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)17 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)16 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)15 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)15 ServletContext (jakarta.servlet.ServletContext)14 FilterChain (jakarta.servlet.FilterChain)13 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)13 BeforeEach (org.junit.jupiter.api.BeforeEach)12 BeforeMethod (org.testng.annotations.BeforeMethod)11 ServletConfig (jakarta.servlet.ServletConfig)10 Arrays (java.util.Arrays)10 Enumeration (java.util.Enumeration)10 UnavailableException (jakarta.servlet.UnavailableException)9 HttpHeaders (org.springframework.http.HttpHeaders)9 HttpMethod (org.springframework.http.HttpMethod)9 CorsConfiguration (org.springframework.web.cors.CorsConfiguration)9 ServletRequest (jakarta.servlet.ServletRequest)8