Search in sources :

Example 11 with WebResource

use of org.apache.catalina.WebResource in project tomcat by apache.

the class ContextConfig method webConfig.

/**
     * Scan the web.xml files that apply to the web application and merge them
     * using the rules defined in the spec. For the global web.xml files,
     * where there is duplicate configuration, the most specific level wins. ie
     * an application's web.xml takes precedence over the host level or global
     * web.xml file.
     */
protected void webConfig() {
    /*
         * Anything and everything can override the global and host defaults.
         * This is implemented in two parts
         * - Handle as a web fragment that gets added after everything else so
         *   everything else takes priority
         * - Mark Servlets as overridable so SCI configuration can replace
         *   configuration from the defaults
         */
    /*
         * The rules for annotation scanning are not as clear-cut as one might
         * think. Tomcat implements the following process:
         * - As per SRV.1.6.2, Tomcat will scan for annotations regardless of
         *   which Servlet spec version is declared in web.xml. The EG has
         *   confirmed this is the expected behaviour.
         * - As per http://java.net/jira/browse/SERVLET_SPEC-36, if the main
         *   web.xml is marked as metadata-complete, JARs are still processed
         *   for SCIs.
         * - If metadata-complete=true and an absolute ordering is specified,
         *   JARs excluded from the ordering are also excluded from the SCI
         *   processing.
         * - If an SCI has a @HandlesType annotation then all classes (except
         *   those in JARs excluded from an absolute ordering) need to be
         *   scanned to check if they match.
         */
    WebXmlParser webXmlParser = new WebXmlParser(context.getXmlNamespaceAware(), context.getXmlValidation(), context.getXmlBlockExternal());
    Set<WebXml> defaults = new HashSet<>();
    defaults.add(getDefaultWebXmlFragment(webXmlParser));
    WebXml webXml = createWebXml();
    // Parse context level web.xml
    InputSource contextWebXml = getContextWebXmlSource();
    if (!webXmlParser.parseWebXml(contextWebXml, webXml, false)) {
        ok = false;
    }
    ServletContext sContext = context.getServletContext();
    // Ordering is important here
    // Step 1. Identify all the JARs packaged with the application and those
    // provided by the container. If any of the application JARs have a
    // web-fragment.xml it will be parsed at this point. web-fragment.xml
    // files are ignored for container provided JARs.
    Map<String, WebXml> fragments = processJarsForWebFragments(webXml, webXmlParser);
    // Step 2. Order the fragments.
    Set<WebXml> orderedFragments = null;
    orderedFragments = WebXml.orderWebFragments(webXml, fragments, sContext);
    // Step 3. Look for ServletContainerInitializer implementations
    if (ok) {
        processServletContainerInitializers();
    }
    if (!webXml.isMetadataComplete() || typeInitializerMap.size() > 0) {
        // Step 4. Process /WEB-INF/classes for annotations and
        // @HandlesTypes matches
        Map<String, JavaClassCacheEntry> javaClassCache = new HashMap<>();
        if (ok) {
            WebResource[] webResources = context.getResources().listResources("/WEB-INF/classes");
            for (WebResource webResource : webResources) {
                // expanded in to WEB-INF/classes (sometimes IDEs do this).
                if ("META-INF".equals(webResource.getName())) {
                    continue;
                }
                processAnnotationsWebResource(webResource, webXml, webXml.isMetadataComplete(), javaClassCache);
            }
        }
        // container fragments)
        if (ok) {
            processAnnotations(orderedFragments, webXml.isMetadataComplete(), javaClassCache);
        }
        // Cache, if used, is no longer required so clear it
        javaClassCache.clear();
    }
    if (!webXml.isMetadataComplete()) {
        // file.
        if (ok) {
            ok = webXml.merge(orderedFragments);
        }
        // Step 7. Apply global defaults
        // Have to merge defaults before JSP conversion since defaults
        // provide JSP servlet definition.
        webXml.merge(defaults);
        // Step 8. Convert explicitly mentioned jsps to servlets
        if (ok) {
            convertJsps(webXml);
        }
        // Step 9. Apply merged web.xml to Context
        if (ok) {
            configureContext(webXml);
        }
    } else {
        webXml.merge(defaults);
        convertJsps(webXml);
        configureContext(webXml);
    }
    if (context.getLogEffectiveWebXml()) {
        log.info("web.xml:\n" + webXml.toXml());
    }
    // Step 10. Look for static resources packaged in JARs
    if (ok) {
        // Spec does not define an order.
        // Use ordered JARs followed by remaining JARs
        Set<WebXml> resourceJars = new LinkedHashSet<>();
        for (WebXml fragment : orderedFragments) {
            resourceJars.add(fragment);
        }
        for (WebXml fragment : fragments.values()) {
            if (!resourceJars.contains(fragment)) {
                resourceJars.add(fragment);
            }
        }
        processResourceJARs(resourceJars);
    // See also StandardContext.resourcesStart() for
    // WEB-INF/classes/META-INF/resources configuration
    }
    // context
    if (ok) {
        for (Map.Entry<ServletContainerInitializer, Set<Class<?>>> entry : initializerClassMap.entrySet()) {
            if (entry.getValue().isEmpty()) {
                context.addServletContainerInitializer(entry.getKey(), null);
            } else {
                context.addServletContainerInitializer(entry.getKey(), entry.getValue());
            }
        }
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) InputSource(org.xml.sax.InputSource) Set(java.util.Set) RuleSet(org.apache.tomcat.util.digester.RuleSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) WebResource(org.apache.catalina.WebResource) WebXmlParser(org.apache.tomcat.util.descriptor.web.WebXmlParser) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) WebXml(org.apache.tomcat.util.descriptor.web.WebXml) ServletContext(javax.servlet.ServletContext) FilterMap(org.apache.tomcat.util.descriptor.web.FilterMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 12 with WebResource

use of org.apache.catalina.WebResource in project tomcat by apache.

the class WebdavStatus method deleteResource.

/**
     * Delete a resource.
     *
     * @param path Path of the resource which is to be deleted
     * @param req Servlet request
     * @param resp Servlet response
     * @param setStatus Should the response status be set on successful
     *                  completion
     * @return <code>true</code> if the delete is successful
     * @throws IOException If an IO error occurs
     */
private boolean deleteResource(String path, HttpServletRequest req, HttpServletResponse resp, boolean setStatus) throws IOException {
    String ifHeader = req.getHeader("If");
    if (ifHeader == null)
        ifHeader = "";
    String lockTokenHeader = req.getHeader("Lock-Token");
    if (lockTokenHeader == null)
        lockTokenHeader = "";
    if (isLocked(path, ifHeader + lockTokenHeader)) {
        resp.sendError(WebdavStatus.SC_LOCKED);
        return false;
    }
    WebResource resource = resources.getResource(path);
    if (!resource.exists()) {
        resp.sendError(WebdavStatus.SC_NOT_FOUND);
        return false;
    }
    if (!resource.isDirectory()) {
        if (!resource.delete()) {
            resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
            return false;
        }
    } else {
        Hashtable<String, Integer> errorList = new Hashtable<>();
        deleteCollection(req, path, errorList);
        if (!resource.delete()) {
            errorList.put(path, Integer.valueOf(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
        }
        if (!errorList.isEmpty()) {
            sendReport(req, resp, errorList);
            return false;
        }
    }
    if (setStatus) {
        resp.setStatus(WebdavStatus.SC_NO_CONTENT);
    }
    return true;
}
Also used : Hashtable(java.util.Hashtable) WebResource(org.apache.catalina.WebResource)

Example 13 with WebResource

use of org.apache.catalina.WebResource in project tomcat by apache.

the class WebdavStatus method deleteCollection.

/**
     * Deletes a collection.
     * @param req The Servlet request
     * @param path Path to the collection to be deleted
     * @param errorList Contains the list of the errors which occurred
     */
private void deleteCollection(HttpServletRequest req, String path, Hashtable<String, Integer> errorList) {
    if (debug > 1)
        log("Delete:" + path);
    // Prevent deletion of special subdirectories
    if (isSpecialPath(path)) {
        errorList.put(path, Integer.valueOf(WebdavStatus.SC_FORBIDDEN));
        return;
    }
    String ifHeader = req.getHeader("If");
    if (ifHeader == null)
        ifHeader = "";
    String lockTokenHeader = req.getHeader("Lock-Token");
    if (lockTokenHeader == null)
        lockTokenHeader = "";
    String[] entries = resources.list(path);
    for (String entry : entries) {
        String childName = path;
        if (!childName.equals("/"))
            childName += "/";
        childName += entry;
        if (isLocked(childName, ifHeader + lockTokenHeader)) {
            errorList.put(childName, Integer.valueOf(WebdavStatus.SC_LOCKED));
        } else {
            WebResource childResource = resources.getResource(childName);
            if (childResource.isDirectory()) {
                deleteCollection(req, childName, errorList);
            }
            if (!childResource.delete()) {
                if (!childResource.isDirectory()) {
                    // If it's not a collection, then it's an unknown
                    // error
                    errorList.put(childName, Integer.valueOf(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
                }
            }
        }
    }
}
Also used : WebResource(org.apache.catalina.WebResource)

Example 14 with WebResource

use of org.apache.catalina.WebResource in project tomcat by apache.

the class WebdavStatus method copyResource.

/**
     * Copy a collection.
     *
     * @param errorList Hashtable containing the list of errors which occurred
     * during the copy operation
     * @param source Path of the resource to be copied
     * @param dest Destination path
     * @return <code>true</code> if the copy was successful
     */
private boolean copyResource(Hashtable<String, Integer> errorList, String source, String dest) {
    if (debug > 1)
        log("Copy: " + source + " To: " + dest);
    WebResource sourceResource = resources.getResource(source);
    if (sourceResource.isDirectory()) {
        if (!resources.mkdir(dest)) {
            WebResource destResource = resources.getResource(dest);
            if (!destResource.isDirectory()) {
                errorList.put(dest, Integer.valueOf(WebdavStatus.SC_CONFLICT));
                return false;
            }
        }
        String[] entries = resources.list(source);
        for (String entry : entries) {
            String childDest = dest;
            if (!childDest.equals("/")) {
                childDest += "/";
            }
            childDest += entry;
            String childSrc = source;
            if (!childSrc.equals("/")) {
                childSrc += "/";
            }
            childSrc += entry;
            copyResource(errorList, childSrc, childDest);
        }
    } else if (sourceResource.isFile()) {
        WebResource destResource = resources.getResource(dest);
        if (!destResource.exists() && !destResource.getWebappPath().endsWith("/")) {
            int lastSlash = destResource.getWebappPath().lastIndexOf('/');
            if (lastSlash > 0) {
                String parent = destResource.getWebappPath().substring(0, lastSlash);
                WebResource parentResource = resources.getResource(parent);
                if (!parentResource.isDirectory()) {
                    errorList.put(source, Integer.valueOf(WebdavStatus.SC_CONFLICT));
                    return false;
                }
            }
        }
        try (InputStream is = sourceResource.getInputStream()) {
            if (!resources.write(dest, is, false)) {
                errorList.put(source, Integer.valueOf(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
                return false;
            }
        } catch (IOException e) {
            log(sm.getString("webdavservlet.inputstreamclosefail", source), e);
        }
    } else {
        errorList.put(source, Integer.valueOf(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
        return false;
    }
    return true;
}
Also used : InputStream(java.io.InputStream) WebResource(org.apache.catalina.WebResource) IOException(java.io.IOException)

Example 15 with WebResource

use of org.apache.catalina.WebResource in project tomcat by apache.

the class CachedResource method validateResource.

protected boolean validateResource(boolean useClassLoaderResources) {
    long now = System.currentTimeMillis();
    if (webResource == null) {
        synchronized (this) {
            if (webResource == null) {
                webResource = root.getResourceInternal(webAppPath, useClassLoaderResources);
                getLastModified();
                getContentLength();
                nextCheck = ttl + now;
                // use the fact that we know if it exists at this point
                if (webResource instanceof EmptyResource) {
                    cachedExists = Boolean.FALSE;
                } else {
                    cachedExists = Boolean.TRUE;
                }
                return true;
            }
        }
    }
    if (now < nextCheck) {
        return true;
    }
    WebResource webResourceInternal = root.getResourceInternal(webAppPath, useClassLoaderResources);
    if (!webResource.exists() && webResourceInternal.exists()) {
        return false;
    }
    // removed etc.
    if (webResource.getLastModified() != getLastModified() || webResource.getContentLength() != getContentLength()) {
        return false;
    }
    // Has a resource been inserted / removed in a different resource set
    if (webResource.getLastModified() != webResourceInternal.getLastModified() || webResource.getContentLength() != webResourceInternal.getContentLength()) {
        return false;
    }
    nextCheck = ttl + now;
    return true;
}
Also used : WebResource(org.apache.catalina.WebResource)

Aggregations

WebResource (org.apache.catalina.WebResource)47 Test (org.junit.Test)14 InputStream (java.io.InputStream)10 File (java.io.File)9 ByteArrayInputStream (java.io.ByteArrayInputStream)8 IOException (java.io.IOException)7 URL (java.net.URL)7 BufferedInputStream (java.io.BufferedInputStream)5 FileInputStream (java.io.FileInputStream)5 InputSource (org.xml.sax.InputSource)5 PrintWriter (java.io.PrintWriter)3 RandomAccessFile (java.io.RandomAccessFile)3 Manifest (java.util.jar.Manifest)3 DocumentBuilder (javax.xml.parsers.DocumentBuilder)3 WebResourceSet (org.apache.catalina.WebResourceSet)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 OutputStreamWriter (java.io.OutputStreamWriter)2 StringWriter (java.io.StringWriter)2 Hashtable (java.util.Hashtable)2 LinkedHashSet (java.util.LinkedHashSet)2