Java Code Examples for org.apache.catalina.WebResource#exists()

The following examples show how to use org.apache.catalina.WebResource#exists() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractTestResourceSet.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public final void testWriteDirA() {
    WebResource d1 = resourceRoot.getResource(getMount() + "/d1");
    InputStream is = new ByteArrayInputStream("test".getBytes());
    if (d1.exists()) {
        Assert.assertFalse(resourceRoot.write(getMount() + "/d1", is, false));
    } else if (d1.isVirtual()) {
        Assert.assertTrue(resourceRoot.write(
                getMount() + "/d1", is, false));
        File file = new File(getBaseDir(), "d1");
        Assert.assertTrue(file.exists());
        Assert.assertTrue(file.delete());
    } else {
        Assert.fail("Unhandled condition in unit test");
    }
}
 
Example 2
Source File: DefaultServlet.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Process a DELETE request for the specified resource.
 *
 * @param req The servlet request we are processing
 * @param resp The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet-specified error occurs
 */
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {

    if (readOnly) {
        sendNotAllowed(req, resp);
        return;
    }

    String path = getRelativePath(req);

    WebResource resource = resources.getResource(path);

    if (resource.exists()) {
        if (resource.delete()) {
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    } else {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }

}
 
Example 3
Source File: StandardRoot.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
protected WebResource[] getResourcesInternal(String path,
        boolean useClassLoaderResources) {
    List<WebResource> result = new ArrayList<>();
    for (List<WebResourceSet> list : allResources) {
        for (WebResourceSet webResourceSet : list) {
            if (useClassLoaderResources || !webResourceSet.getClassLoaderOnly()) {
                WebResource webResource = webResourceSet.getResource(path);
                if (webResource.exists()) {
                    result.add(webResource);
                }
            }
        }
    }

    if (result.size() == 0) {
        result.add(main.getResource(path));
    }

    return result.toArray(new WebResource[result.size()]);
}
 
Example 4
Source File: ResolverImpl.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public boolean resolveResource(int type, String name) {
    WebResourceRoot resources = request.getContext().getResources();
    WebResource resource = resources.getResource(name);
    if (!resource.exists()) {
        return false;
    } else {
        switch (type) {
        case 0:
            return resource.isDirectory();
        case 1:
            return resource.isFile();
        case 2:
            return resource.isFile() && resource.getContentLength() > 0;
        default:
            return false;
        }
    }
}
 
Example 5
Source File: AbstractTestResourceSet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public final void testWriteDirB() {
    WebResource d1 = resourceRoot.getResource(getMount() + "/d1/");
    InputStream is = new ByteArrayInputStream("test".getBytes());
    if (d1.exists() || d1.isVirtual()) {
        Assert.assertFalse(resourceRoot.write(getMount() + "/d1/", is, false));
    } else {
        Assert.fail("Unhandled condition in unit test");
    }
}
 
Example 6
Source File: AbstractTestResourceSet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public final void testMkdirDirB() {
    WebResource d1 = resourceRoot.getResource(getMount() + "/d1/");
    if (d1.exists()) {
        Assert.assertFalse(resourceRoot.mkdir(getMount() + "/d1/"));
    } else if (d1.isVirtual()) {
        Assert.assertTrue(resourceRoot.mkdir(getMount() + "/d1/"));
        File file = new File(getBaseDir(), "d1");
        Assert.assertTrue(file.isDirectory());
        Assert.assertTrue(file.delete());
    } else {
        Assert.fail("Unhandled condition in unit test");
    }
}
 
Example 7
Source File: AbstractTestResourceSet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public final void testMkdirDirA() {
    WebResource d1 = resourceRoot.getResource(getMount() + "/d1");
    if (d1.exists()) {
        Assert.assertFalse(resourceRoot.mkdir(getMount() + "/d1"));
    } else if (d1.isVirtual()) {
        Assert.assertTrue(resourceRoot.mkdir(getMount() + "/d1"));
        File file = new File(getBaseDir(), "d1");
        Assert.assertTrue(file.isDirectory());
        Assert.assertTrue(file.delete());
    } else {
        Assert.fail("Unhandled condition in unit test");
    }
}
 
Example 8
Source File: StandardRoot.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
protected final WebResource getResourceInternal(String path,
        boolean useClassLoaderResources) {
    WebResource result = null;
    WebResource virtual = null;
    WebResource mainEmpty = null;
    for (List<WebResourceSet> list : allResources) {
        for (WebResourceSet webResourceSet : list) {
            if (!useClassLoaderResources &&  !webResourceSet.getClassLoaderOnly() ||
                    useClassLoaderResources && !webResourceSet.getStaticOnly()) {
                result = webResourceSet.getResource(path);
                if (result.exists()) {
                    return result;
                }
                if (virtual == null) {
                    if (result.isVirtual()) {
                        virtual = result;
                    } else if (main.equals(webResourceSet)) {
                        mainEmpty = result;
                    }
                }
            }
        }
    }

    // Use the first virtual result if no real result was found
    if (virtual != null) {
        return virtual;
    }

    // Default is empty resource in main resources
    return mainEmpty;
}
 
Example 9
Source File: StandardRoot.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private boolean preResourceExists(String path) {
    for (WebResourceSet webResourceSet : preResources) {
        WebResource webResource = webResourceSet.getResource(path);
        if (webResource.exists()) {
            return true;
        }
    }
    return false;
}
 
Example 10
Source File: WebappClassLoaderBase.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Return an enumeration of <code>URLs</code> representing all of the
 * resources with the given name.  If no resources with this name are
 * found, return an empty enumeration.
 *
 * @param name Name of the resources to be found
 *
 * @exception IOException if an input/output error occurs
 */
@Override
public Enumeration<URL> findResources(String name) throws IOException {

    if (log.isDebugEnabled())
        log.debug("    findResources(" + name + ")");

    checkStateForResourceLoading(name);

    LinkedHashSet<URL> result = new LinkedHashSet<>();

    String path = nameToPath(name);

    WebResource[] webResources = resources.getClassLoaderResources(path);
    for (WebResource webResource : webResources) {
        if (webResource.exists()) {
            result.add(webResource.getURL());
        }
    }

    // Adding the results of a call to the superclass
    if (hasExternalRepositories) {
        Enumeration<URL> otherResourcePaths = super.findResources(name);
        while (otherResourcePaths.hasMoreElements()) {
            result.add(otherResourcePaths.nextElement());
        }
    }

    return Collections.enumeration(result);
}
 
Example 11
Source File: WebappClassLoaderBase.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Find the specified resource in our local repository, and return a
 * <code>URL</code> referring to it, or <code>null</code> if this resource
 * cannot be found.
 *
 * @param name Name of the resource to be found
 */
@Override
public URL findResource(final String name) {

    if (log.isDebugEnabled())
        log.debug("    findResource(" + name + ")");

    checkStateForResourceLoading(name);

    URL url = null;

    String path = nameToPath(name);

    WebResource resource = resources.getClassLoaderResource(path);
    if (resource.exists()) {
        url = resource.getURL();
        trackLastModified(path, resource);
    }

    if ((url == null) && hasExternalRepositories) {
        url = super.findResource(name);
    }

    if (log.isDebugEnabled()) {
        if (url != null)
            log.debug("    --> Returning '" + url.toString() + "'");
        else
            log.debug("    --> Resource not found, returning null");
    }
    return url;
}
 
Example 12
Source File: DefaultServlet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private List<PrecompressedResource> getAvailablePrecompressedResources(String path) {
    List<PrecompressedResource> ret = new ArrayList<>(compressionFormats.length);
    for (CompressionFormat format : compressionFormats) {
        WebResource precompressedResource = resources.getResource(path + format.extension);
        if (precompressedResource.exists() && precompressedResource.isFile()) {
            ret.add(new PrecompressedResource(precompressedResource, format));
        }
    }
    return ret;
}
 
Example 13
Source File: WebdavServlet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Determines the methods normally allowed for the resource.
 *
 * @param req The Servlet request
 *
 * @return The allowed HTTP methods
 */
@Override
protected String determineMethodsAllowed(HttpServletRequest req) {


    WebResource resource = resources.getResource(getRelativePath(req));

    // These methods are always allowed. They may return a 404 (not a 405)
    // if the resource does not exist.
    StringBuilder methodsAllowed = new StringBuilder(
            "OPTIONS, GET, POST, HEAD");

    if (!readOnly) {
        methodsAllowed.append(", DELETE");
        if (!resource.isDirectory()) {
            methodsAllowed.append(", PUT");
        }
    }

    // Trace - assume disabled unless we can prove otherwise
    if (req instanceof RequestFacade &&
            ((RequestFacade) req).getAllowTrace()) {
        methodsAllowed.append(", TRACE");
    }

    methodsAllowed.append(", LOCK, UNLOCK, PROPPATCH, COPY, MOVE");

    if (listings) {
        methodsAllowed.append(", PROPFIND");
    }

    if (!resource.exists()) {
        methodsAllowed.append(", MKCOL");
    }

    return methodsAllowed.toString();
}
 
Example 14
Source File: WebdavServlet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Propfind helper method.
 *
 * @param req The servlet request
 * @param generatedXML XML response to the Propfind request
 * @param path Path of the current resource
 * @param type Propfind type
 * @param propertiesVector If the propfind type is find properties by
 * name, then this Vector contains those properties
 */
private void parseProperties(HttpServletRequest req,
                             XMLWriter generatedXML,
                             String path, int type,
                             Vector<String> propertiesVector) {

    // Exclude any resource in the /WEB-INF and /META-INF subdirectories
    if (isSpecialPath(path))
        return;

    WebResource resource = resources.getResource(path);
    if (!resource.exists()) {
        // File is in directory listing but doesn't appear to exist
        // Broken symlink or odd permission settings?
        return;
    }

    String href = req.getContextPath() + req.getServletPath();
    if ((href.endsWith("/")) && (path.startsWith("/")))
        href += path.substring(1);
    else
        href += path;
    if (resource.isDirectory() && (!href.endsWith("/")))
        href += "/";

    String rewrittenUrl = rewriteUrl(href);

    generatePropFindResponse(generatedXML, rewrittenUrl, path, type, propertiesVector,
            resource.isFile(), false, resource.getCreation(), resource.getLastModified(),
            resource.getContentLength(), getServletContext().getMimeType(resource.getName()),
            resource.getETag());
}
 
Example 15
Source File: WebappClassLoaderBase.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Find the resource with the given name, and return an input stream
 * that can be used for reading it.  The search order is as described
 * for <code>getResource()</code>, after checking to see if the resource
 * data has been previously cached.  If the resource cannot be found,
 * return <code>null</code>.
 *
 * @param name Name of the resource to return an input stream for
 */
@Override
public InputStream getResourceAsStream(String name) {

    if (log.isDebugEnabled())
        log.debug("getResourceAsStream(" + name + ")");

    checkStateForResourceLoading(name);

    InputStream stream = null;

    boolean delegateFirst = delegate || filter(name, false);

    // (1) Delegate to parent if requested
    if (delegateFirst) {
        if (log.isDebugEnabled())
            log.debug("  Delegating to parent classloader " + parent);
        stream = parent.getResourceAsStream(name);
        if (stream != null) {
            if (log.isDebugEnabled())
                log.debug("  --> Returning stream from parent");
            return stream;
        }
    }

    // (2) Search local repositories
    if (log.isDebugEnabled())
        log.debug("  Searching local repositories");
    String path = nameToPath(name);
    WebResource resource = resources.getClassLoaderResource(path);
    if (resource.exists()) {
        stream = resource.getInputStream();
        trackLastModified(path, resource);
    }
    try {
        if (hasExternalRepositories && stream == null) {
            URL url = super.findResource(name);
            if (url != null) {
                stream = url.openStream();
            }
        }
    } catch (IOException e) {
        // Ignore
    }
    if (stream != null) {
        if (log.isDebugEnabled())
            log.debug("  --> Returning stream from local");
        return stream;
    }

    // (3) Delegate to parent unconditionally
    if (!delegateFirst) {
        if (log.isDebugEnabled())
            log.debug("  Delegating to parent classloader unconditionally " + parent);
        stream = parent.getResourceAsStream(name);
        if (stream != null) {
            if (log.isDebugEnabled())
                log.debug("  --> Returning stream from parent");
            return stream;
        }
    }

    // (4) Resource was not found
    if (log.isDebugEnabled())
        log.debug("  --> Resource not found, returning null");
    return null;
}
 
Example 16
Source File: CachedResource.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
protected boolean validateResource(boolean useClassLoaderResources) {
    // It is possible that some resources will only be visible for a given
    // value of useClassLoaderResources. Therefore, if the lookup is made
    // with a different value of useClassLoaderResources than was used when
    // creating the cache entry, invalidate the entry. This should have
    // minimal performance impact as it would be unusual for a resource to
    // be looked up both as a static resource and as a class loader
    // resource.
    if (usesClassLoaderResources != useClassLoaderResources) {
        return false;
    }

    long now = System.currentTimeMillis();

    if (webResource == null) {
        synchronized (this) {
            if (webResource == null) {
                webResource = root.getResourceInternal(
                        webAppPath, useClassLoaderResources);
                getLastModified();
                getContentLength();
                nextCheck = ttl + now;
                // exists() is a relatively expensive check for a file so
                // 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;
    }

    // Assume resources inside WARs will not change
    if (!root.isPackedWarFile()) {
        WebResource webResourceInternal = root.getResourceInternal(
                webAppPath, useClassLoaderResources);
        if (!webResource.exists() && webResourceInternal.exists()) {
            return false;
        }

        // If modified date or length change - resource has changed / been
        // 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;
}
 
Example 17
Source File: WebdavServlet.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * 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;
}
 
Example 18
Source File: WebdavServlet.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * MKCOL Method.
 * @param req The Servlet request
 * @param resp The Servlet response
 * @throws ServletException If an error occurs
 * @throws IOException If an IO error occurs
 */
protected void doMkcol(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {

    String path = getRelativePath(req);

    WebResource resource = resources.getResource(path);

    // Can't create a collection if a resource already exists at the given
    // path
    if (resource.exists()) {
        sendNotAllowed(req, resp);
        return;
    }

    if (readOnly) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }

    if (isLocked(req)) {
        resp.sendError(WebdavStatus.SC_LOCKED);
        return;
    }

    if (req.getContentLengthLong() > 0) {
        DocumentBuilder documentBuilder = getDocumentBuilder();
        try {
            // Document document =
            documentBuilder.parse(new InputSource(req.getInputStream()));
            // TODO : Process this request body
            resp.sendError(WebdavStatus.SC_NOT_IMPLEMENTED);
            return;

        } catch(SAXException saxe) {
            // Parse error - assume invalid content
            resp.sendError(WebdavStatus.SC_UNSUPPORTED_MEDIA_TYPE);
            return;
        }
    }

    if (resources.mkdir(path)) {
        resp.setStatus(WebdavStatus.SC_CREATED);
        // Removing any lock-null resource which would be present
        lockNullResources.remove(path);
    } else {
        resp.sendError(WebdavStatus.SC_CONFLICT,
                       WebdavStatus.getStatusText
                       (WebdavStatus.SC_CONFLICT));
    }
}