Search in sources :

Example 76 with ServletException

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

the class StandardContext method loadOnStartup.

/**
 * Load and initialize all servlets marked "load on startup" in the
 * web application deployment descriptor.
 *
 * @param children Array of wrappers for all currently defined
 *  servlets (including those not declared load on startup)
 * @return <code>true</code> if load on startup was considered successful
 */
public boolean loadOnStartup(Container[] children) {
    // Collect "load on startup" servlets that need to be initialized
    TreeMap<Integer, ArrayList<Wrapper>> map = new TreeMap<>();
    for (Container child : children) {
        Wrapper wrapper = (Wrapper) child;
        int loadOnStartup = wrapper.getLoadOnStartup();
        if (loadOnStartup < 0) {
            continue;
        }
        Integer key = Integer.valueOf(loadOnStartup);
        ArrayList<Wrapper> list = map.get(key);
        if (list == null) {
            list = new ArrayList<>();
            map.put(key, list);
        }
        list.add(wrapper);
    }
    // Load the collected "load on startup" servlets
    for (ArrayList<Wrapper> list : map.values()) {
        for (Wrapper wrapper : list) {
            try {
                wrapper.load();
            } catch (ServletException e) {
                getLogger().error(sm.getString("standardContext.loadOnStartup.loadException", getName(), wrapper.getName()), StandardWrapper.getRootCause(e));
                // unless failCtxIfServletStartFails="true" is specified
                if (getComputedFailCtxIfServletStartFails()) {
                    return false;
                }
            }
        }
    }
    return true;
}
Also used : ServletException(jakarta.servlet.ServletException) Wrapper(org.apache.catalina.Wrapper) Container(org.apache.catalina.Container) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) TreeMap(java.util.TreeMap) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint)

Example 77 with ServletException

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

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

the class DefaultServlet method renderXml.

/**
 * Return an InputStream to an XML representation of the contents this
 * directory.
 *
 * @param request     The HttpServletRequest being served
 * @param contextPath Context path to which our internal paths are relative
 * @param resource    The associated resource
 * @param xsltSource  The XSL stylesheet
 * @param encoding    The encoding to use to process the readme (if any)
 *
 * @return the XML data
 *
 * @throws IOException an IO error occurred
 * @throws ServletException rendering error
 */
protected InputStream renderXml(HttpServletRequest request, String contextPath, WebResource resource, Source xsltSource, String encoding) throws IOException, ServletException {
    StringBuilder sb = new StringBuilder();
    sb.append("<?xml version=\"1.0\"?>");
    sb.append("<listing ");
    sb.append(" contextPath='");
    sb.append(contextPath);
    sb.append('\'');
    sb.append(" directory='");
    sb.append(resource.getName());
    sb.append("' ");
    sb.append(" hasParent='").append(!resource.getName().equals("/"));
    sb.append("'>");
    sb.append("<entries>");
    String[] entries = resources.list(resource.getWebappPath());
    // rewriteUrl(contextPath) is expensive. cache result for later reuse
    String rewrittenContextPath = rewriteUrl(contextPath);
    String directoryWebappPath = resource.getWebappPath();
    for (String entry : entries) {
        if (entry.equalsIgnoreCase("WEB-INF") || entry.equalsIgnoreCase("META-INF") || entry.equalsIgnoreCase(localXsltFile)) {
            continue;
        }
        if ((directoryWebappPath + entry).equals(contextXsltFile)) {
            continue;
        }
        WebResource childResource = resources.getResource(directoryWebappPath + entry);
        if (!childResource.exists()) {
            continue;
        }
        sb.append("<entry");
        sb.append(" type='").append(childResource.isDirectory() ? "dir" : "file").append('\'');
        sb.append(" urlPath='").append(rewrittenContextPath).append(rewriteUrl(directoryWebappPath + entry)).append(childResource.isDirectory() ? "/" : "").append('\'');
        if (childResource.isFile()) {
            sb.append(" size='").append(renderSize(childResource.getContentLength())).append('\'');
        }
        sb.append(" date='").append(childResource.getLastModifiedHttp()).append('\'');
        sb.append('>');
        sb.append(Escape.htmlElementContent(entry));
        if (childResource.isDirectory()) {
            sb.append('/');
        }
        sb.append("</entry>");
    }
    sb.append("</entries>");
    String readme = getReadme(resource, encoding);
    if (readme != null) {
        sb.append("<readme><![CDATA[");
        sb.append(readme);
        sb.append("]]></readme>");
    }
    sb.append("</listing>");
    // Prevent possible memory leak. Ensure Transformer and
    // TransformerFactory are not loaded from the web application.
    ClassLoader original;
    if (Globals.IS_SECURITY_ENABLED) {
        PrivilegedGetTccl pa = new PrivilegedGetTccl();
        original = AccessController.doPrivileged(pa);
    } else {
        original = Thread.currentThread().getContextClassLoader();
    }
    try {
        if (Globals.IS_SECURITY_ENABLED) {
            PrivilegedSetTccl pa = new PrivilegedSetTccl(DefaultServlet.class.getClassLoader());
            AccessController.doPrivileged(pa);
        } else {
            Thread.currentThread().setContextClassLoader(DefaultServlet.class.getClassLoader());
        }
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Source xmlSource = new StreamSource(new StringReader(sb.toString()));
        Transformer transformer = tFactory.newTransformer(xsltSource);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        OutputStreamWriter osWriter = new OutputStreamWriter(stream, StandardCharsets.UTF_8);
        StreamResult out = new StreamResult(osWriter);
        transformer.transform(xmlSource, out);
        osWriter.flush();
        return new ByteArrayInputStream(stream.toByteArray());
    } catch (TransformerException e) {
        throw new ServletException(sm.getString("defaultServlet.xslError"), e);
    } finally {
        if (Globals.IS_SECURITY_ENABLED) {
            PrivilegedSetTccl pa = new PrivilegedSetTccl(original);
            AccessController.doPrivileged(pa);
        } else {
            Thread.currentThread().setContextClassLoader(original);
        }
    }
}
Also used : TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) StreamSource(javax.xml.transform.stream.StreamSource) WebResource(org.apache.catalina.WebResource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DOMSource(javax.xml.transform.dom.DOMSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) InputSource(org.xml.sax.InputSource) ServletException(jakarta.servlet.ServletException) ByteArrayInputStream(java.io.ByteArrayInputStream) PrivilegedGetTccl(org.apache.tomcat.util.security.PrivilegedGetTccl) StringReader(java.io.StringReader) OutputStreamWriter(java.io.OutputStreamWriter) TransformerException(javax.xml.transform.TransformerException) PrivilegedSetTccl(org.apache.tomcat.util.security.PrivilegedSetTccl)

Example 79 with ServletException

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

the class WsSci method onStartup.

@Override
public void onStartup(Set<Class<?>> clazzes, ServletContext ctx) throws ServletException {
    WsServerContainer sc = init(ctx, true);
    if (clazzes == null || clazzes.size() == 0) {
        return;
    }
    // Group the discovered classes by type
    Set<ServerApplicationConfig> serverApplicationConfigs = new HashSet<>();
    Set<Class<? extends Endpoint>> scannedEndpointClazzes = new HashSet<>();
    Set<Class<?>> scannedPojoEndpoints = new HashSet<>();
    try {
        // wsPackage is "jakarta.websocket."
        String wsPackage = ContainerProvider.class.getName();
        wsPackage = wsPackage.substring(0, wsPackage.lastIndexOf('.') + 1);
        for (Class<?> clazz : clazzes) {
            int modifiers = clazz.getModifiers();
            if (!Modifier.isPublic(modifiers) || Modifier.isAbstract(modifiers) || Modifier.isInterface(modifiers) || !isExported(clazz)) {
                // package - skip it.
                continue;
            }
            // Protect against scanning the WebSocket API JARs
            if (clazz.getName().startsWith(wsPackage)) {
                continue;
            }
            if (ServerApplicationConfig.class.isAssignableFrom(clazz)) {
                serverApplicationConfigs.add((ServerApplicationConfig) clazz.getConstructor().newInstance());
            }
            if (Endpoint.class.isAssignableFrom(clazz)) {
                @SuppressWarnings("unchecked") Class<? extends Endpoint> endpoint = (Class<? extends Endpoint>) clazz;
                scannedEndpointClazzes.add(endpoint);
            }
            if (clazz.isAnnotationPresent(ServerEndpoint.class)) {
                scannedPojoEndpoints.add(clazz);
            }
        }
    } catch (ReflectiveOperationException e) {
        throw new ServletException(e);
    }
    // Filter the results
    Set<ServerEndpointConfig> filteredEndpointConfigs = new HashSet<>();
    Set<Class<?>> filteredPojoEndpoints = new HashSet<>();
    if (serverApplicationConfigs.isEmpty()) {
        filteredPojoEndpoints.addAll(scannedPojoEndpoints);
    } else {
        for (ServerApplicationConfig config : serverApplicationConfigs) {
            Set<ServerEndpointConfig> configFilteredEndpoints = config.getEndpointConfigs(scannedEndpointClazzes);
            if (configFilteredEndpoints != null) {
                filteredEndpointConfigs.addAll(configFilteredEndpoints);
            }
            Set<Class<?>> configFilteredPojos = config.getAnnotatedEndpointClasses(scannedPojoEndpoints);
            if (configFilteredPojos != null) {
                filteredPojoEndpoints.addAll(configFilteredPojos);
            }
        }
    }
    try {
        // Deploy endpoints
        for (ServerEndpointConfig config : filteredEndpointConfigs) {
            sc.addEndpoint(config);
        }
        // Deploy POJOs
        for (Class<?> clazz : filteredPojoEndpoints) {
            sc.addEndpoint(clazz, true);
        }
    } catch (DeploymentException e) {
        throw new ServletException(e);
    }
}
Also used : ServerEndpointConfig(jakarta.websocket.server.ServerEndpointConfig) ServerApplicationConfig(jakarta.websocket.server.ServerApplicationConfig) Endpoint(jakarta.websocket.Endpoint) ServerEndpoint(jakarta.websocket.server.ServerEndpoint) ServletException(jakarta.servlet.ServletException) Endpoint(jakarta.websocket.Endpoint) ServerEndpoint(jakarta.websocket.server.ServerEndpoint) DeploymentException(jakarta.websocket.DeploymentException) HashSet(java.util.HashSet)

Example 80 with ServletException

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

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