org.apache.catalina.WebResource Java Examples

The following examples show how to use org.apache.catalina.WebResource. 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: WebdavServlet.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Process a PUT 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 doPut(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {

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

    String path = getRelativePath(req);
    WebResource resource = resources.getResource(path);
    if (resource.isDirectory()) {
        sendNotAllowed(req, resp);
        return;
    }

    super.doPut(req, resp);

    // Removing any lock-null resource which would be present
    lockNullResources.remove(path);

}
 
Example #2
Source File: TestJarWarResourceSet.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testJarWarMetaInf() throws LifecycleException  {
    Tomcat tomcat = getTomcatInstance();

    File warFile = new File("test/webresources/war-url-connection.war");
    Context ctx = tomcat.addContext("", warFile.getAbsolutePath());

    tomcat.start();

    StandardRoot root = (StandardRoot) ctx.getResources();

    WebResource[] results = root.getClassLoaderResources("/META-INF");

    Assert.assertNotNull(results);
    Assert.assertEquals(1, results.length);
    Assert.assertNotNull(results[0].getURL());
}
 
Example #3
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 #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 6 votes vote down vote up
private void doTestGetResourceRoot(boolean slash) {
    String mount = getMount();
    if (!slash && mount.length() == 0) {
        return;
    }
    mount = mount + (slash ? "/" : "");

    WebResource webResource = resourceRoot.getResource(mount);

    Assert.assertTrue(webResource.isDirectory());
    String expected;
    if (getMount().length() > 0) {
        expected = getMount().substring(1);
    } else {
        expected = "";
    }
    Assert.assertEquals(expected, webResource.getName());
    Assert.assertEquals(mount + (!slash ? "/" : ""), webResource.getWebappPath());
}
 
Example #6
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 #7
Source File: DefaultServlet.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Check if sendfile can be used.
 * @param request The Servlet request
 * @param response The Servlet response
 * @param resource The resource
 * @param length The length which will be written (will be used only if
 *  range is null)
 * @param range The range that will be written
 * @return <code>true</code> if sendfile should be used (writing is then
 *  delegated to the endpoint)
 */
protected boolean checkSendfile(HttpServletRequest request,
                              HttpServletResponse response,
                              WebResource resource,
                              long length, Range range) {
    String canonicalPath;
    if (sendfileSize > 0
        && length > sendfileSize
        && (Boolean.TRUE.equals(request.getAttribute(Globals.SENDFILE_SUPPORTED_ATTR)))
        && (request.getClass().getName().equals("org.apache.catalina.connector.RequestFacade"))
        && (response.getClass().getName().equals("org.apache.catalina.connector.ResponseFacade"))
        && resource.isFile()
        && ((canonicalPath = resource.getCanonicalPath()) != null)
        ) {
        request.setAttribute(Globals.SENDFILE_FILENAME_ATTR, canonicalPath);
        if (range == null) {
            request.setAttribute(Globals.SENDFILE_FILE_START_ATTR, Long.valueOf(0L));
            request.setAttribute(Globals.SENDFILE_FILE_END_ATTR, Long.valueOf(length));
        } else {
            request.setAttribute(Globals.SENDFILE_FILE_START_ATTR, Long.valueOf(range.start));
            request.setAttribute(Globals.SENDFILE_FILE_END_ATTR, Long.valueOf(range.end + 1));
        }
        return true;
    }
    return false;
}
 
Example #8
Source File: StandardRoot.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
protected WebResource[] listResources(String path, boolean validate) {
    if (validate) {
        path = validate(path);
    }

    String[] resources = list(path, false);
    WebResource[] result = new WebResource[resources.length];
    for (int i = 0; i < resources.length; i++) {
        if (path.charAt(path.length() - 1) == '/') {
            result[i] = getResource(path + resources[i], false, false);
        } else {
            result[i] = getResource(path + '/' + resources[i], false, false);
        }
    }
    return result;
}
 
Example #9
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 #10
Source File: AbstractTestResourceSet.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public final void testGetCanonicalPathDoesNotExist() {
    WebResource exists =
            resourceRoot.getResource(getMount() + "/d1/d1-f1.txt");
    WebResource doesNotExist =
            resourceRoot.getResource(getMount() + "/d1/dummy.txt");
    String doesNotExistCanonicalPath = doesNotExist.getCanonicalPath();

    URL existsUrl = exists.getURL();
    if ("file".equals(existsUrl.getProtocol())) {
        // Should be possible to construct a canonical path for a resource
        // that doesn't exist given that a resource that does exist in the
        // same directory has a URL with the file protocol
        Assert.assertNotNull(doesNotExistCanonicalPath);
    } else {
        Assert.assertNull(doesNotExistCanonicalPath);
    }
}
 
Example #11
Source File: DefaultServlet.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Copy the contents of the specified input stream to the specified
 * output stream, and ensure that both streams are closed before returning
 * (even in the face of an exception).
 *
 * @param resource  The source resource
 * @param ostream   The output stream to write to
 * @param range     Range the client wanted to retrieve
 * @exception IOException if an input/output error occurs
 */
protected void copy(WebResource resource, ServletOutputStream ostream,
                  Range range)
    throws IOException {

    IOException exception = null;

    InputStream resourceInputStream = resource.getInputStream();
    InputStream istream =
        new BufferedInputStream(resourceInputStream, input);
    exception = copyRange(istream, ostream, range.start, range.end);

    // Clean up the input stream
    istream.close();

    // Rethrow any exception that has occurred
    if (exception != null)
        throw exception;

}
 
Example #12
Source File: TestAbstractArchiveResource.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testNestedJarGetURL() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    File docBase = new File("test/webresources/war-url-connection.war");
    Context ctx = tomcat.addWebapp("/test", docBase.getAbsolutePath());
    skipTldsForResourceJars(ctx);

    ((StandardHost) tomcat.getHost()).setUnpackWARs(false);

    tomcat.start();

    WebResource webResource =
            ctx.getResources().getClassLoaderResource("/META-INF/resources/index.html");

    StringBuilder expectedURL = new StringBuilder("jar:war:");
    expectedURL.append(docBase.getAbsoluteFile().toURI().toURL().toString());
    expectedURL.append("*/WEB-INF/lib/test.jar!/META-INF/resources/index.html");

    Assert.assertEquals(expectedURL.toString(), webResource.getURL().toString());
}
 
Example #13
Source File: DefaultServlet.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Check if the if-unmodified-since condition is satisfied.
 *
 * @param request   The servlet request we are processing
 * @param response  The servlet response we are creating
 * @param resource  The resource
 * @return <code>true</code> if the resource meets the specified condition,
 *  and <code>false</code> if the condition is not satisfied, in which case
 *  request processing is stopped
 * @throws IOException an IO error occurred
 */
protected boolean checkIfUnmodifiedSince(HttpServletRequest request,
        HttpServletResponse response, WebResource resource)
        throws IOException {
    try {
        long lastModified = resource.getLastModified();
        long headerValue = request.getDateHeader("If-Unmodified-Since");
        if (headerValue != -1) {
            if ( lastModified >= (headerValue + 1000)) {
                // The entity has not been modified since the date
                // specified by the client. This is not an error case.
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }
        }
    } catch(IllegalArgumentException illegalArgument) {
        return true;
    }
    return true;
}
 
Example #14
Source File: TestResourceJars.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testNonStaticResources() {
    File empty = new File("test/webresources/dir3");
    File jar = new File("test/webresources/non-static-resources.jar");

    TesterWebResourceRoot root = new TesterWebResourceRoot();

    // Use empty dir for root of web app.
    WebResourceSet webResourceSet = new DirResourceSet(root, "/", empty.getAbsolutePath(), "/");
    root.setMainResources(webResourceSet);

    // If this JAR was in a web application, this is equivalent to how it
    // would be added
    JarResourceSet test =
            new JarResourceSet(root, "/", jar.getAbsolutePath(), "/META-INF/resources");
    test.setStaticOnly(true);
    root.addJarResources(test);

    WebResource resource = root.getClassLoaderResource("/org/apache/tomcat/unittest/foo.txt");

    Assert.assertFalse(resource.exists());
}
 
Example #15
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 #16
Source File: AbstractTestResourceSet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public final void testGetResourceDirB() {
    WebResource webResource = resourceRoot.getResource(getMount() + "/d1/");
    Assert.assertTrue(webResource.isDirectory());
    Assert.assertEquals("d1", webResource.getName());
    Assert.assertEquals(getMount() + "/d1/", webResource.getWebappPath());
    Assert.assertEquals(-1, webResource.getContentLength());
    Assert.assertNull(webResource.getContent());
    Assert.assertNull(webResource.getInputStream());
}
 
Example #17
Source File: AbstractTestResourceSet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public final void testGetResourceDirA() {
    WebResource webResource = resourceRoot.getResource(getMount() + "/d1");
    Assert.assertTrue(webResource.isDirectory());
    Assert.assertEquals("d1", webResource.getName());
    Assert.assertEquals(getMount() + "/d1/", webResource.getWebappPath());
    Assert.assertEquals(-1, webResource.getContentLength());
    Assert.assertNull(webResource.getContent());
    Assert.assertNull(webResource.getInputStream());
}
 
Example #18
Source File: ExtractingRoot.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected void processWebInfLib() throws LifecycleException {

    // Don't extract JAR files unless the application is deployed as a
    // packed WAR file.
    if (!super.isPackedWarFile()) {
        super.processWebInfLib();
        return;
    }

    File expansionTarget = getExpansionTarget();
    if (!expansionTarget.isDirectory()) {
        if (!expansionTarget.mkdirs()) {
            throw new LifecycleException(
                    sm.getString("extractingRoot.targetFailed", expansionTarget));
        }
    }

    WebResource[] possibleJars = listResources("/WEB-INF/lib", false);

    for (WebResource possibleJar : possibleJars) {
        if (possibleJar.isFile() && possibleJar.getName().endsWith(".jar")) {
            try {
                File dest = new File(expansionTarget, possibleJar.getName());
                dest = dest.getCanonicalFile();
                try (InputStream sourceStream = possibleJar.getInputStream();
                        OutputStream destStream= new FileOutputStream(dest)) {
                    IOTools.flow(sourceStream, destStream);
                }

                createWebResourceSet(ResourceSetType.CLASSES_JAR,
                        "/WEB-INF/classes", dest.toURI().toURL(), "/");
            } catch (IOException ioe) {
                throw new LifecycleException(
                        sm.getString("extractingRoot.jarFailed", possibleJar.getName()), ioe);
            }
        }
    }
}
 
Example #19
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 #20
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 #21
Source File: StandardRoot.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
protected WebResource getResource(String path, boolean validate,
        boolean useClassLoaderResources) {
    if (validate) {
        path = validate(path);
    }

    if (isCachingAllowed()) {
        return cache.getResource(path, useClassLoaderResources);
    } else {
        return getResourceInternal(path, useClassLoaderResources);
    }
}
 
Example #22
Source File: DefaultServlet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public int compare(WebResource r1, WebResource r2) {
    if(r1.isDirectory()) {
        if(r2.isDirectory()) {
            return base.compare(r1, r2);
        } else {
            return -1; // r1, directory, first
        }
    } else if(r2.isDirectory()) {
        return 1; // r2, directory, first
    } else {
        return base.compare(r1, r2);
    }
}
 
Example #23
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 #24
Source File: StandardRoot.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private WebResource[] getResources(String path,
        boolean useClassLoaderResources) {
    path = validate(path);

    if (isCachingAllowed()) {
        return cache.getResources(path, useClassLoaderResources);
    } else {
        return getResourcesInternal(path, useClassLoaderResources);
    }
}
 
Example #25
Source File: ContextConfig.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
protected void processClasses(WebXml webXml, Set<WebXml> orderedFragments) {
    // 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) {
            // Skip the META-INF directory from any JARs that have been
            // expanded in to WEB-INF/classes (sometimes IDEs do this).
            if ("META-INF".equals(webResource.getName())) {
                continue;
            }
            processAnnotationsWebResource(webResource, webXml,
                    webXml.isMetadataComplete(), javaClassCache);
        }
    }

    // Step 5. Process JARs for annotations and
    // @HandlesTypes matches - only need to process those fragments we
    // are going to use (remember orderedFragments includes any
    // container fragments)
    if (ok) {
        processAnnotations(
                orderedFragments, webXml.isMetadataComplete(), javaClassCache);
    }

    // Cache, if used, is no longer required so clear it
    javaClassCache.clear();
}
 
Example #26
Source File: WebdavServlet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected boolean checkIfHeaders(HttpServletRequest request,
                                 HttpServletResponse response,
                                 WebResource resource)
    throws IOException {

    if (!super.checkIfHeaders(request, response, resource))
        return false;

    // TODO : Checking the WebDAV If header
    return true;
}
 
Example #27
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 #28
Source File: DefaultServlet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public int compare(WebResource r1, WebResource r2) {
    int c = Long.compare(r1.getLastModified(), r2.getLastModified());

    if(0 == c)
        return base.compare(r1, r2);
    else
        return c;
}
 
Example #29
Source File: DefaultServlet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public int compare(WebResource r1, WebResource r2) {
    int c = Long.compare(r1.getContentLength(), r2.getContentLength());

    if(0 == c)
        return base.compare(r1, r2);
    else
        return c;
}
 
Example #30
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);
}