Search in sources :

Example 1 with UnavailableException

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

the class ApplicationDispatcher method invoke.

// -------------------------------------------------------- Private Methods
/**
 * Ask the resource represented by this RequestDispatcher to process
 * the associated request, and create (or append to) the associated
 * response.
 * <p>
 * <strong>IMPLEMENTATION NOTE</strong>: This implementation assumes
 * that no filters are applied to a forwarded or included resource,
 * because they were already done for the original request.
 *
 * @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 error occurs
 */
private void invoke(ServletRequest request, ServletResponse response, State state) throws IOException, ServletException {
    // Checking to see if the context classloader is the current context
    // classloader. If it's not, we're saving it, and setting the context
    // classloader to the Context classloader
    ClassLoader oldCCL = context.bind(false, null);
    // Initialize local variables we may need
    HttpServletResponse hresponse = state.hresponse;
    Servlet servlet = null;
    IOException ioException = null;
    ServletException servletException = null;
    RuntimeException runtimeException = null;
    boolean unavailable = false;
    // Check for the servlet being marked unavailable
    if (wrapper.isUnavailable()) {
        wrapper.getLogger().warn(sm.getString("applicationDispatcher.isUnavailable", wrapper.getName()));
        long available = wrapper.getAvailable();
        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            hresponse.setDateHeader("Retry-After", available);
        }
        hresponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("applicationDispatcher.isUnavailable", wrapper.getName()));
        unavailable = true;
    }
    // Allocate a servlet instance to process this request
    try {
        if (!unavailable) {
            servlet = wrapper.allocate();
        }
    } catch (ServletException e) {
        wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e));
        servletException = e;
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e);
        servletException = new ServletException(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e);
        servlet = null;
    }
    // Get the FilterChain Here
    ApplicationFilterChain filterChain = ApplicationFilterFactory.createFilterChain(request, wrapper, servlet);
    // Call the service() method for the allocated servlet instance
    try {
        // for includes/forwards
        if ((servlet != null) && (filterChain != null)) {
            filterChain.doFilter(request, response);
        }
    // Servlet Service Method is called by the FilterChain
    } catch (ClientAbortException e) {
        ioException = e;
    } catch (IOException e) {
        wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
        ioException = e;
    } catch (UnavailableException e) {
        wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
        servletException = e;
        wrapper.unavailable(e);
    } catch (ServletException e) {
        Throwable rootCause = StandardWrapper.getRootCause(e);
        if (!(rootCause instanceof ClientAbortException)) {
            wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), rootCause);
        }
        servletException = e;
    } catch (RuntimeException e) {
        wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
        runtimeException = e;
    }
    // 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 (ServletException e) {
        wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
        servletException = e;
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
        servletException = new ServletException(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
    }
    // Reset the old context class loader
    context.unbind(false, oldCCL);
    // Unwrap request/response if needed
    // See Bugzilla 30949
    unwrapRequest(state);
    unwrapResponse(state);
    // Recycle request if necessary (also BZ 30949)
    recycleRequestWrapper(state);
    // Rethrow an exception if one was thrown by the invoked servlet
    if (ioException != null) {
        throw ioException;
    }
    if (servletException != null) {
        throw servletException;
    }
    if (runtimeException != null) {
        throw runtimeException;
    }
}
Also used : ServletException(jakarta.servlet.ServletException) UnavailableException(jakarta.servlet.UnavailableException) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Servlet(jakarta.servlet.Servlet) ClientAbortException(org.apache.catalina.connector.ClientAbortException) IOException(java.io.IOException)

Example 2 with UnavailableException

use of jakarta.servlet.UnavailableException 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 3 with UnavailableException

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

the class SecurityUtil method execute.

/**
 * Perform work as a particular <code>Subject</code>. Here the work
 * will be granted to a <code>null</code> subject.
 *
 * @param method the method to apply the security restriction
 * @param targetObject the <code>Servlet</code> on which the method will
 *  be called.
 * @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
 */
private static void execute(final Method method, final Object targetObject, final Object[] targetArguments, Principal principal) throws Exception {
    try {
        Subject subject = null;
        PrivilegedExceptionAction<Void> pea = () -> {
            method.invoke(targetObject, targetArguments);
            return null;
        };
        // The first argument is always the request object
        if (targetArguments != null && targetArguments[0] instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) targetArguments[0];
            boolean hasSubject = false;
            HttpSession session = request.getSession(false);
            if (session != null) {
                subject = (Subject) session.getAttribute(Globals.SUBJECT_ATTR);
                hasSubject = (subject != null);
            }
            if (subject == null) {
                subject = new Subject();
                if (principal != null) {
                    subject.getPrincipals().add(principal);
                }
            }
            if (session != null && !hasSubject) {
                session.setAttribute(Globals.SUBJECT_ATTR, subject);
            }
        }
        Subject.doAsPrivileged(subject, pea, null);
    } catch (PrivilegedActionException pe) {
        Throwable e;
        if (pe.getException() instanceof InvocationTargetException) {
            e = pe.getException().getCause();
            ExceptionUtils.handleThrowable(e);
        } else {
            e = pe;
        }
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e);
        }
        if (e instanceof UnavailableException) {
            throw (UnavailableException) e;
        } else if (e instanceof ServletException) {
            throw (ServletException) e;
        } else if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw new ServletException(e.getMessage(), e);
        }
    }
}
Also used : PrivilegedActionException(java.security.PrivilegedActionException) HttpSession(jakarta.servlet.http.HttpSession) UnavailableException(jakarta.servlet.UnavailableException) IOException(java.io.IOException) Subject(javax.security.auth.Subject) InvocationTargetException(java.lang.reflect.InvocationTargetException) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServletException(jakarta.servlet.ServletException)

Example 4 with UnavailableException

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

the class DefaultServlet method init.

/**
 * Initialize this servlet.
 */
@Override
public void init() throws ServletException {
    if (getServletConfig().getInitParameter("debug") != null) {
        debug = Integer.parseInt(getServletConfig().getInitParameter("debug"));
    }
    if (getServletConfig().getInitParameter("input") != null) {
        input = Integer.parseInt(getServletConfig().getInitParameter("input"));
    }
    if (getServletConfig().getInitParameter("output") != null) {
        output = Integer.parseInt(getServletConfig().getInitParameter("output"));
    }
    listings = Boolean.parseBoolean(getServletConfig().getInitParameter("listings"));
    if (getServletConfig().getInitParameter("readonly") != null) {
        readOnly = Boolean.parseBoolean(getServletConfig().getInitParameter("readonly"));
    }
    compressionFormats = parseCompressionFormats(getServletConfig().getInitParameter("precompressed"), getServletConfig().getInitParameter("gzip"));
    if (getServletConfig().getInitParameter("sendfileSize") != null) {
        sendfileSize = Integer.parseInt(getServletConfig().getInitParameter("sendfileSize")) * 1024;
    }
    fileEncoding = getServletConfig().getInitParameter("fileEncoding");
    if (fileEncoding == null) {
        fileEncodingCharset = Charset.defaultCharset();
        fileEncoding = fileEncodingCharset.name();
    } else {
        try {
            fileEncodingCharset = B2CConverter.getCharset(fileEncoding);
        } catch (UnsupportedEncodingException e) {
            throw new ServletException(e);
        }
    }
    String useBomIfPresent = getServletConfig().getInitParameter("useBomIfPresent");
    if (useBomIfPresent == null) {
        // Use default
        this.useBomIfPresent = BomConfig.TRUE;
    } else {
        for (BomConfig bomConfig : BomConfig.values()) {
            if (bomConfig.configurationValue.equalsIgnoreCase(useBomIfPresent)) {
                this.useBomIfPresent = bomConfig;
                break;
            }
        }
        if (this.useBomIfPresent == null) {
            // Unrecognised configuration value
            IllegalArgumentException iae = new IllegalArgumentException(sm.getString("defaultServlet.unknownBomConfig", useBomIfPresent));
            throw new ServletException(iae);
        }
    }
    globalXsltFile = getServletConfig().getInitParameter("globalXsltFile");
    contextXsltFile = getServletConfig().getInitParameter("contextXsltFile");
    localXsltFile = getServletConfig().getInitParameter("localXsltFile");
    readmeFile = getServletConfig().getInitParameter("readmeFile");
    if (getServletConfig().getInitParameter("useAcceptRanges") != null) {
        useAcceptRanges = Boolean.parseBoolean(getServletConfig().getInitParameter("useAcceptRanges"));
    }
    // Prevent the use of buffer sizes that are too small
    if (input < 256) {
        input = 256;
    }
    if (output < 256) {
        output = 256;
    }
    if (debug > 0) {
        log("DefaultServlet.init:  input buffer size=" + input + ", output buffer size=" + output);
    }
    // Load the web resources
    resources = (WebResourceRoot) getServletContext().getAttribute(Globals.RESOURCES_ATTR);
    if (resources == null) {
        throw new UnavailableException(sm.getString("defaultServlet.noResources"));
    }
    if (getServletConfig().getInitParameter("showServerInfo") != null) {
        showServerInfo = Boolean.parseBoolean(getServletConfig().getInitParameter("showServerInfo"));
    }
    if (getServletConfig().getInitParameter("sortListings") != null) {
        sortListings = Boolean.parseBoolean(getServletConfig().getInitParameter("sortListings"));
        if (sortListings) {
            boolean sortDirectoriesFirst;
            if (getServletConfig().getInitParameter("sortDirectoriesFirst") != null) {
                sortDirectoriesFirst = Boolean.parseBoolean(getServletConfig().getInitParameter("sortDirectoriesFirst"));
            } else {
                sortDirectoriesFirst = false;
            }
            sortManager = new SortManager(sortDirectoriesFirst);
        }
    }
    if (getServletConfig().getInitParameter("allowPartialPut") != null) {
        allowPartialPut = Boolean.parseBoolean(getServletConfig().getInitParameter("allowPartialPut"));
    }
}
Also used : ServletException(jakarta.servlet.ServletException) UnavailableException(jakarta.servlet.UnavailableException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 5 with UnavailableException

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

the class StandardWrapper method initServlet.

private synchronized void initServlet(Servlet servlet) throws ServletException {
    if (instanceInitialized) {
        return;
    }
    // Call the initialization method of this servlet
    try {
        if (Globals.IS_SECURITY_ENABLED) {
            boolean success = false;
            try {
                Object[] args = new Object[] { facade };
                SecurityUtil.doAsPrivilege("init", servlet, classType, args);
                success = true;
            } finally {
                if (!success) {
                    // destroy() will not be called, thus clear the reference now
                    SecurityUtil.remove(servlet);
                }
            }
        } else {
            servlet.init(facade);
        }
        instanceInitialized = true;
    } catch (UnavailableException f) {
        unavailable(f);
        throw f;
    } catch (ServletException f) {
        // said so, so do not call unavailable(null).
        throw f;
    } catch (Throwable f) {
        ExceptionUtils.handleThrowable(f);
        getServletContext().log(sm.getString("standardWrapper.initException", getName()), f);
        // said so, so do not call unavailable(null).
        throw new ServletException(sm.getString("standardWrapper.initException", getName()), f);
    }
}
Also used : ServletException(jakarta.servlet.ServletException) UnavailableException(jakarta.servlet.UnavailableException)

Aggregations

UnavailableException (jakarta.servlet.UnavailableException)7 ServletException (jakarta.servlet.ServletException)6 IOException (java.io.IOException)4 Servlet (jakarta.servlet.Servlet)3 Container (org.apache.catalina.Container)2 ClientAbortException (org.apache.catalina.connector.ClientAbortException)2 DispatcherType (jakarta.servlet.DispatcherType)1 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)1 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)1 HttpSession (jakarta.servlet.http.HttpSession)1 File (java.io.File)1 FileNotFoundException (java.io.FileNotFoundException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 PrivilegedActionException (java.security.PrivilegedActionException)1 MBeanServer (javax.management.MBeanServer)1 Subject (javax.security.auth.Subject)1 Context (org.apache.catalina.Context)1 Engine (org.apache.catalina.Engine)1 Host (org.apache.catalina.Host)1