io.undertow.server.handlers.resource.Resource Java Examples

The following examples show how to use io.undertow.server.handlers.resource.Resource. 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: ServletPathMatches.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private ServletPathMatch findWelcomeFile(final String path, boolean requiresRedirect) {
    if(File.separatorChar != '/' && path.contains(File.separator)) {
        return null;
    }
    StringBuilder sb = new StringBuilder();
    for (String i : welcomePages) {
        try {
            sb.append(path);
            sb.append(i);
            final String mergedPath = sb.toString();
            sb.setLength(0);
            Resource resource = resourceManager.getResource(mergedPath);
            if (resource != null) {
                final ServletPathMatch handler = data.getServletHandlerByPath(mergedPath);
                return new ServletPathMatch(handler.getServletChain(), mergedPath, null, requiresRedirect ? REDIRECT : REWRITE, mergedPath);
            }
        } catch (IOException e) {
        }
    }
    return null;
}
 
Example #2
Source File: KnownPathResourceManager.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public List<Resource> list() {
    List<Resource> ret = new ArrayList<>();
    String slashPath = path + "/";
    for (String i : files.headSet(path)) {
        if (i.startsWith(slashPath)) {
            try {
                ret.add(underlying.getResource(i));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            break;
        }
    }
    return ret;
}
 
Example #3
Source File: DirectoryPredicate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean resolve(final HttpServerExchange value) {
    String location = this.location.readAttribute(value);
    ServletRequestContext src = value.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    if(src == null) {
        return false;
    }
    ResourceManager manager = src.getDeployment().getDeploymentInfo().getResourceManager();
    if(manager == null) {
        return false;
    }
    try {
        Resource resource = manager.getResource(location);
        if(resource == null) {
            return false;
        }
        return resource.isDirectory();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #4
Source File: UndertowResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public boolean resolveResource(int type, String name) {
    Resource resource;
    try {
        resource = servletRequestContext.getDeployment().getDeploymentInfo().getResourceManager().getResource(name);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    switch (type) {
        case 0:
            return (resource == null);
        case 1:
            return (resource != null);
        case 2:
            return (resource != null
                    && resource.getContentLength() > 0);
        default:
            return false;
    }

}
 
Example #5
Source File: ServletContextImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public URL getResource(final String path) throws MalformedURLException {
    if (!path.startsWith("/")) {
        throw UndertowServletMessages.MESSAGES.pathMustStartWithSlash(path);
    }
    Resource resource = null;
    try {
        resource = deploymentInfo.getResourceManager().getResource(path);
    } catch (IOException e) {
        return null;
    }
    if (resource == null) {
        return null;
    }
    return resource.getUrl();
}
 
Example #6
Source File: ServletPathMatches.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
private ServletPathMatch findWelcomeFile(final String path, boolean requiresRedirect) {
    if(File.separatorChar != '/' && path.contains(File.separator)) {
        return null;
    }
    StringBuilder sb = new StringBuilder();
    for (String i : welcomePages) {
        try {
            sb.append(path);
            sb.append(i);
            final String mergedPath = sb.toString();
            sb.setLength(0);
            Resource resource = resourceManager.getResource(mergedPath);
            if (resource != null) {
                final ServletPathMatch handler = data.getServletHandlerByPath(mergedPath);
                return new ServletPathMatch(handler.getServletChain(), mergedPath, null, requiresRedirect ? REDIRECT : REWRITE, mergedPath);
            }
        } catch (IOException e) {
        }
    }
    return null;
}
 
Example #7
Source File: ServletContextImpl.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public URL getResource(final String path) throws MalformedURLException {
    if (!path.startsWith("/")) {
        throw UndertowServletMessages.MESSAGES.pathMustStartWithSlash(path);
    }
    Resource resource = null;
    try {
        resource = deploymentInfo.getResourceManager().getResource(path);
    } catch (IOException e) {
        return null;
    }
    if (resource == null) {
        return null;
    }
    return resource.getUrl();
}
 
Example #8
Source File: UndertowResolver.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
public boolean resolveResource(int type, String name) {
    Resource resource;
    try {
        resource = servletRequestContext.getDeployment().getDeploymentInfo().getResourceManager().getResource(name);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    switch (type) {
        case 0:
            return (resource == null);
        case 1:
            return (resource != null);
        case 2:
            return (resource != null
                    && resource.getContentLength() > 0);
        default:
            return false;
    }

}
 
Example #9
Source File: DirectoryPredicate.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public boolean resolve(final HttpServerExchange value) {
    String location = this.location.readAttribute(value);
    ServletRequestContext src = value.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    if(src == null) {
        return false;
    }
    ResourceManager manager = src.getDeployment().getDeploymentInfo().getResourceManager();
    if(manager == null) {
        return false;
    }
    try {
        Resource resource = manager.getResource(location);
        if(resource == null) {
            return false;
        }
        return resource.isDirectory();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #10
Source File: CompositeResourceManager.java    From joinfaces with Apache License 2.0 5 votes vote down vote up
@Override
public Resource getResource(String path) throws IOException {
	for (ResourceManager resourceManager : this.resourceManagers) {
		Resource resource = resourceManager.getResource(path);
		if (resource != null) {
			return resource;
		}
	}
	return null;
}
 
Example #11
Source File: PrefixingResourceManager.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Resource getResource(String path) throws IOException {
    for(ResourceManager d : delegates) {
        Resource res = d.getResource(path);
        if(res != null) {
            return res;
        }
    }
    return null;
}
 
Example #12
Source File: TestClassProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Resource getResource(String className) {
    LOGGER.infov("Request: {0}", className);

    URL resource = isPermittedPackage(className) ? TestClassProvider.class.getResource(className) : null;
    return resource != null ? new URLResource(resource, className) : null;
}
 
Example #13
Source File: ServletContextImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String getRealPath(final String path) {
    if (path == null) {
        return null;
    }
    String canonicalPath = CanonicalPathUtils.canonicalize(path);
    Resource resource;
    try {
        resource = deploymentInfo.getResourceManager().getResource(canonicalPath);

        if (resource == null) {
            //UNDERTOW-373 even though the resource does not exist we still need to return a path
            Resource deploymentRoot = deploymentInfo.getResourceManager().getResource("/");
            if(deploymentRoot == null) {
                return null;
            }
            Path root = deploymentRoot.getFilePath();
            if(root == null) {
                return null;
            }
            if(!canonicalPath.startsWith("/")) {
                canonicalPath = "/" + canonicalPath;
            }
            if(File.separatorChar != '/') {
                canonicalPath = canonicalPath.replace('/', File.separatorChar);
            }
            return root.toAbsolutePath().toString() + canonicalPath;
        }
    } catch (IOException e) {
        return null;
    }
    Path file = resource.getFilePath();
    if (file == null) {
        return null;
    }
    return file.toAbsolutePath().toString();
}
 
Example #14
Source File: ServletContextImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Set<String> getResourcePaths(final String path) {
    final Resource resource;
    try {
        resource = deploymentInfo.getResourceManager().getResource(path);
    } catch (IOException e) {
        return null;
    }
    if (resource == null || !resource.isDirectory()) {
        return null;
    }
    final Set<String> resources = new HashSet<>();
    for (Resource res : resource.list()) {
        Path file = res.getFilePath();
        if (file != null) {
            Path base = res.getResourceManagerRootPath();
            if (base == null) {
                resources.add(file.toString()); //not much else we can do here
            } else {
                String filePath = file.toAbsolutePath().toString().substring(base.toAbsolutePath().toString().length());
                filePath = filePath.replace('\\', '/'); //for windows systems
                if (Files.isDirectory(file)) {
                    filePath = filePath + "/";
                }
                resources.add(filePath);
            }
        }
    }
    return resources;
}
 
Example #15
Source File: FilePredicate.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public boolean resolve(final HttpServerExchange value) {
    String location = this.location.readAttribute(value);
    ServletRequestContext src = value.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    if(src == null) {
        return false;
    }
    ResourceManager manager = src.getDeployment().getDeploymentInfo().getResourceManager();
    if(manager == null) {
        return false;
    }
    try {
        Resource resource = manager.getResource(location);
        if(resource == null) {
            return false;
        }
        if(resource.isDirectory()) {
            return false;
        }
        if(requireContent){
          return resource.getContentLength() != null && resource.getContentLength() > 0;
        } else {
            return true;
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #16
Source File: FilePredicate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean resolve(final HttpServerExchange value) {
    String location = this.location.readAttribute(value);
    ServletRequestContext src = value.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    if(src == null) {
        return false;
    }
    ResourceManager manager = src.getDeployment().getDeploymentInfo().getResourceManager();
    if(manager == null) {
        return false;
    }
    try {
        Resource resource = manager.getResource(location);
        if(resource == null) {
            return false;
        }
        if(resource.isDirectory()) {
            return false;
        }
        if(requireContent){
          return resource.getContentLength() != null && resource.getContentLength() > 0;
        } else {
            return true;
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #17
Source File: DelegatingResourceManager.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public Resource getResource(String path) throws IOException {
    for (ResourceManager i : delegates) {
        Resource res = i.getResource(path);
        if (res != null) {
            return res;
        }
    }
    return null;
}
 
Example #18
Source File: PathResourceManagerTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Test
public void testListDir() throws Exception {

    final Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();
    final PathResourceManager resourceManager = new PathResourceManager(rootPath, 1024 * 1024);
    Resource subdir = resourceManager.getResource("subdir");
    Resource found = subdir.list().get(0);
    Assert.assertEquals("subdir" + File.separatorChar+ "a.txt", found.getPath());
}
 
Example #19
Source File: ServletContextImpl.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public Set<String> getResourcePaths(final String path) {
    final Resource resource;
    try {
        resource = deploymentInfo.getResourceManager().getResource(path);
    } catch (IOException e) {
        return null;
    }
    if (resource == null || !resource.isDirectory()) {
        return null;
    }
    final Set<String> resources = new HashSet<>();
    for (Resource res : resource.list()) {
        Path file = res.getFilePath();
        if (file != null) {
            Path base = res.getResourceManagerRootPath();
            if (base == null) {
                resources.add(file.toString()); //not much else we can do here
            } else {
                String filePath = file.toAbsolutePath().toString().substring(base.toAbsolutePath().toString().length());
                filePath = filePath.replace('\\', '/'); //for windows systems
                if (Files.isDirectory(file)) {
                    filePath = filePath + "/";
                }
                resources.add(filePath);
            }
        }
    }
    return resources;
}
 
Example #20
Source File: ServletContextImpl.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public String getRealPath(final String path) {
    if (path == null) {
        return null;
    }
    String canonicalPath = CanonicalPathUtils.canonicalize(path);
    Resource resource;
    try {
        resource = deploymentInfo.getResourceManager().getResource(canonicalPath);

        if (resource == null) {
            //UNDERTOW-373 even though the resource does not exist we still need to return a path
            Resource deploymentRoot = deploymentInfo.getResourceManager().getResource("/");
            if(deploymentRoot == null) {
                return null;
            }
            Path root = deploymentRoot.getFilePath();
            if(root == null) {
                return null;
            }
            if(!canonicalPath.startsWith("/")) {
                canonicalPath = "/" + canonicalPath;
            }
            if(File.separatorChar != '/') {
                canonicalPath = canonicalPath.replace('/', File.separatorChar);
            }
            return root.toAbsolutePath().toString() + canonicalPath;
        }
    } catch (IOException e) {
        return null;
    }
    Path file = resource.getFilePath();
    if (file == null) {
        return null;
    }
    return file.toAbsolutePath().toString();
}
 
Example #21
Source File: GetResourceTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Test
public void testSpecialCharacterInFileURL() throws IOException {
    String tmp = System.getProperty("java.io.tmpdir");
    PathResourceManager pathResourceManager = new PathResourceManager(Paths.get(tmp), 1);
    Path file = Paths.get(tmp, "1#2.txt");
    Files.write(file, "Hi".getBytes());
    Resource res = pathResourceManager.getResource("1#2.txt");
    try(InputStream in = res.getUrl().openStream()) {
        Assert.assertEquals("Hi", FileUtils.readFile(in));
    }
}
 
Example #22
Source File: TestResourceLoader.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public Resource getResource(String path) throws IOException {
    final Resource delegate = super.getResource(path);
    if(delegate == null) {
        return delegate;
    }
    return new TestResource(delegate);
}
 
Example #23
Source File: KnownPathResourceManager.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public Resource getResource(String path) throws IOException {
    if (path.startsWith("/")) {
        path = path.substring(1);
    }
    if (path.endsWith("/")) {
        path = path.substring(0, path.length() - 1);
    }
    if (directories.contains(path)) {
        return new DirectoryResource(path);
    }
    return underlying.getResource(path);
}
 
Example #24
Source File: TestResourceLoader.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
TestResource(Resource delegate) {
    this.delegate = delegate;
}
 
Example #25
Source File: DefaultServlet.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
private void serveFileBlocking(final HttpServletRequest req, final HttpServletResponse resp, final Resource resource, HttpServerExchange exchange) throws IOException {
    final ETag etag = resource.getETag();
    final Date lastModified = resource.getLastModified();
    if (req.getDispatcherType() != DispatcherType.INCLUDE) {
        if (!ETagUtils.handleIfMatch(req.getHeader(HttpHeaderNames.IF_MATCH), etag, false) ||
                !DateUtils.handleIfUnmodifiedSince(req.getHeader(HttpHeaderNames.IF_UNMODIFIED_SINCE), lastModified)) {
            resp.setStatus(StatusCodes.PRECONDITION_FAILED);
            return;
        }
        if (!ETagUtils.handleIfNoneMatch(req.getHeader(HttpHeaderNames.IF_NONE_MATCH), etag, true) ||
                !DateUtils.handleIfModifiedSince(req.getHeader(HttpHeaderNames.IF_MODIFIED_SINCE), lastModified)) {
            if (req.getMethod().equals(HttpMethodNames.GET) || req.getMethod().equals(HttpMethodNames.HEAD)) {
                resp.setStatus(StatusCodes.NOT_MODIFIED);
            } else {
                resp.setStatus(StatusCodes.PRECONDITION_FAILED);
            }
            return;
        }
    }

    //we are going to proceed. Set the appropriate headers
    if (resp.getContentType() == null) {
        if (!resource.isDirectory()) {
            final String contentType = deployment.getServletContext().getMimeType(resource.getName());
            if (contentType != null) {
                resp.setContentType(contentType);
            } else {
                resp.setContentType("application/octet-stream");
            }
        }
    }
    if (lastModified != null) {
        resp.setHeader(HttpHeaderNames.LAST_MODIFIED, resource.getLastModifiedString());
    }
    if (etag != null) {
        resp.setHeader(HttpHeaderNames.ETAG, etag.toString());
    }
    ByteRange.RangeResponseResult rangeResponse = null;
    long start = -1, end = -1;
    try {
        //only set the content length if we are using a stream
        //if we are using a writer who knows what the length will end up being
        //todo: if someone installs a filter this can cause problems
        //not sure how best to deal with this
        //we also can't deal with range requests if a writer is in use
        Long contentLength = resource.getContentLength();
        if (contentLength != null) {
            resp.getOutputStream();
            if (contentLength > Integer.MAX_VALUE) {
                resp.setContentLengthLong(contentLength);
            } else {
                resp.setContentLength(contentLength.intValue());
            }
            if (resource instanceof RangeAwareResource && ((RangeAwareResource) resource).isRangeSupported() && resource.getContentLength() != null) {
                resp.setHeader(HttpHeaderNames.ACCEPT_RANGES, "bytes");
                //TODO: figure out what to do with the content encoded resource manager
                final ByteRange range = ByteRange.parse(req.getHeader(HttpHeaderNames.RANGE));
                if (range != null) {
                    rangeResponse = range.getResponseResult(resource.getContentLength(), req.getHeader(HttpHeaderNames.IF_RANGE), resource.getLastModified(), resource.getETag() == null ? null : resource.getETag().getTag());
                    if (rangeResponse != null) {
                        start = rangeResponse.getStart();
                        end = rangeResponse.getEnd();
                        resp.setStatus(rangeResponse.getStatusCode());
                        resp.setHeader(HttpHeaderNames.CONTENT_RANGE, rangeResponse.getContentRange());
                        long length = rangeResponse.getContentLength();
                        if (length > Integer.MAX_VALUE) {
                            resp.setContentLengthLong(length);
                        } else {
                            resp.setContentLength((int) length);
                        }
                        if (rangeResponse.getStatusCode() == StatusCodes.REQUEST_RANGE_NOT_SATISFIABLE) {
                            return;
                        }
                    }
                }
            }
        }
    } catch (IllegalStateException e) {

    }
    final boolean include = req.getDispatcherType() == DispatcherType.INCLUDE;
    if (!req.getMethod().equals(HttpMethodNames.HEAD)) {
        if (rangeResponse == null) {
            resource.serveBlocking(exchange.getOutputStream(), exchange);
        } else {
            ((RangeAwareResource) resource).serveRangeBlocking(exchange.getOutputStream(), exchange, start, end);
        }
    }
}
 
Example #26
Source File: ServletPathMatches.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public ServletPathMatch getServletHandlerByPath(final String path) {
    ServletPathMatch existing = pathMatchCache.get(path);
    if(existing != null) {
        return existing;
    }
    ServletPathMatch match = getData().getServletHandlerByPath(path);
    if (!match.isRequiredWelcomeFileMatch()) {
        pathMatchCache.add(path, match);
        return match;
    }
    try {

        String remaining = match.getRemaining() == null ? match.getMatched() : match.getRemaining();
        Resource resource = resourceManager.getResource(remaining);
        if (resource == null || !resource.isDirectory()) {
            pathMatchCache.add(path, match);
            return match;
        }

        boolean pathEndsWithSlash = remaining.endsWith("/");
        final String pathWithTrailingSlash = pathEndsWithSlash ? remaining : remaining + "/";

        ServletPathMatch welcomePage = findWelcomeFile(pathWithTrailingSlash, !pathEndsWithSlash);

        if (welcomePage != null) {
            pathMatchCache.add(path, welcomePage);
            return welcomePage;
        } else {
            welcomePage = findWelcomeServlet(pathWithTrailingSlash, !pathEndsWithSlash);
            if (welcomePage != null) {
                pathMatchCache.add(path, welcomePage);
                return welcomePage;
            } else if(pathEndsWithSlash) {
                pathMatchCache.add(path, match);
                return match;
            } else {
                ServletPathMatch redirect = new ServletPathMatch(match.getServletChain(), match.getMatched(), match.getRemaining(), REDIRECT, "/");
                pathMatchCache.add(path, redirect);
                return redirect;
            }
        }

    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}
 
Example #27
Source File: DefaultServlet.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    String path = getPath(req);
    if (!isAllowed(path, req.getDispatcherType())) {
        resp.sendError(StatusCodes.NOT_FOUND);
        return;
    }
    if (File.separatorChar != '/') {
        //if the separator char is not / we want to replace it with a / and canonicalise
        path = CanonicalPathUtils.canonicalize(path.replace(File.separatorChar, '/'));
    }

    HttpServerExchange exchange = SecurityActions.requireCurrentServletRequestContext().getOriginalRequest().getExchange();
    final Resource resource;
    //we want to disallow windows characters in the path
    if (File.separatorChar == '/' || !path.contains(File.separator)) {
        resource = resourceSupplier.getResource(exchange, path);
    } else {
        resource = null;
    }

    if (resource == null) {
        if (req.getDispatcherType() == DispatcherType.INCLUDE) {
            //servlet 9.3
            throw new FileNotFoundException(path);
        } else {
            resp.sendError(StatusCodes.NOT_FOUND);
        }
        return;
    } else if (resource.isDirectory()) {
        if ("css".equals(req.getQueryString())) {
            resp.setContentType("text/css");
            resp.getWriter().write(DirectoryUtils.Blobs.FILE_CSS);
            return;
        } else if ("js".equals(req.getQueryString())) {
            resp.setContentType("application/javascript");
            resp.getWriter().write(DirectoryUtils.Blobs.FILE_JS);
            return;
        }
        if (directoryListingEnabled) {
            StringBuilder output = DirectoryUtils.renderDirectoryListing(req.getRequestURI(), resource);
            resp.getWriter().write(output.toString());
        } else {
            resp.sendError(StatusCodes.FORBIDDEN);
        }
    } else {
        if (path.endsWith("/")) {
            //UNDERTOW-432
            resp.sendError(StatusCodes.NOT_FOUND);
            return;
        }
        serveFileBlocking(req, resp, resource, exchange);
    }
}
 
Example #28
Source File: DefaultServlet.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    String path = getPath(req);
    if (!isAllowed(path, req.getDispatcherType())) {
        resp.sendError(StatusCodes.NOT_FOUND);
        return;
    }
    if(File.separatorChar != '/') {
        //if the separator char is not / we want to replace it with a / and canonicalise
        path = CanonicalPathUtils.canonicalize(path.replace(File.separatorChar, '/'));
    }

    HttpServerExchange exchange = SecurityActions.requireCurrentServletRequestContext().getOriginalRequest().getExchange();
    final Resource resource;
    //we want to disallow windows characters in the path
    if(File.separatorChar == '/' || !path.contains(File.separator)) {
        resource = resourceSupplier.getResource(exchange, path);
    } else {
        resource = null;
    }

    if (resource == null) {
        if (req.getDispatcherType() == DispatcherType.INCLUDE) {
            //servlet 9.3
            throw new FileNotFoundException(path);
        } else {
            resp.sendError(StatusCodes.NOT_FOUND);
        }
        return;
    } else if (resource.isDirectory()) {
        if ("css".equals(req.getQueryString())) {
            resp.setContentType("text/css");
            resp.getWriter().write(DirectoryUtils.Blobs.FILE_CSS);
            return;
        } else if ("js".equals(req.getQueryString())) {
            resp.setContentType("application/javascript");
            resp.getWriter().write(DirectoryUtils.Blobs.FILE_JS);
            return;
        }
        if (directoryListingEnabled) {
            StringBuilder output = DirectoryUtils.renderDirectoryListing(req.getRequestURI(), resource);
            resp.getWriter().write(output.toString());
        } else {
            resp.sendError(StatusCodes.FORBIDDEN);
        }
    } else {
        if(path.endsWith("/")) {
            //UNDERTOW-432
            resp.sendError(StatusCodes.NOT_FOUND);
            return;
        }
        serveFileBlocking(req, resp, resource, exchange);
    }
}
 
Example #29
Source File: DefaultServlet.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private void serveFileBlocking(final HttpServletRequest req, final HttpServletResponse resp, final Resource resource, HttpServerExchange exchange) throws IOException {
    final ETag etag = resource.getETag();
    final Date lastModified = resource.getLastModified();
    if(req.getDispatcherType() != DispatcherType.INCLUDE) {
        if (!ETagUtils.handleIfMatch(req.getHeader(Headers.IF_MATCH_STRING), etag, false) ||
                !DateUtils.handleIfUnmodifiedSince(req.getHeader(Headers.IF_UNMODIFIED_SINCE_STRING), lastModified)) {
            resp.setStatus(StatusCodes.PRECONDITION_FAILED);
            return;
        }
        if (!ETagUtils.handleIfNoneMatch(req.getHeader(Headers.IF_NONE_MATCH_STRING), etag, true) ||
                !DateUtils.handleIfModifiedSince(req.getHeader(Headers.IF_MODIFIED_SINCE_STRING), lastModified)) {
            if(req.getMethod().equals(Methods.GET_STRING) || req.getMethod().equals(Methods.HEAD_STRING)) {
                resp.setStatus(StatusCodes.NOT_MODIFIED);
            } else {
                resp.setStatus(StatusCodes.PRECONDITION_FAILED);
            }
            return;
        }
    }

    //we are going to proceed. Set the appropriate headers
    if(resp.getContentType() == null) {
        if(!resource.isDirectory()) {
            final String contentType = deployment.getServletContext().getMimeType(resource.getName());
            if (contentType != null) {
                resp.setContentType(contentType);
            } else {
                resp.setContentType("application/octet-stream");
            }
        }
    }
    if (lastModified != null) {
        resp.setHeader(Headers.LAST_MODIFIED_STRING, resource.getLastModifiedString());
    }
    if (etag != null) {
        resp.setHeader(Headers.ETAG_STRING, etag.toString());
    }
    ByteRange.RangeResponseResult rangeResponse = null;
    long start = -1, end = -1;
    try {
        //only set the content length if we are using a stream
        //if we are using a writer who knows what the length will end up being
        //todo: if someone installs a filter this can cause problems
        //not sure how best to deal with this
        //we also can't deal with range requests if a writer is in use
        Long contentLength = resource.getContentLength();
        if (contentLength != null) {
            resp.getOutputStream();
            if(contentLength > Integer.MAX_VALUE) {
                resp.setContentLengthLong(contentLength);
            } else {
                resp.setContentLength(contentLength.intValue());
            }
            if(resource instanceof RangeAwareResource && ((RangeAwareResource)resource).isRangeSupported() && resource.getContentLength() != null) {
                resp.setHeader(Headers.ACCEPT_RANGES_STRING, "bytes");
                //TODO: figure out what to do with the content encoded resource manager
                final ByteRange range = ByteRange.parse(req.getHeader(Headers.RANGE_STRING));
                if(range != null) {
                    rangeResponse = range.getResponseResult(resource.getContentLength(), req.getHeader(Headers.IF_RANGE_STRING), resource.getLastModified(), resource.getETag() == null ? null : resource.getETag().getTag());
                    if(rangeResponse != null){
                        start = rangeResponse.getStart();
                        end = rangeResponse.getEnd();
                        resp.setStatus(rangeResponse.getStatusCode());
                        resp.setHeader(Headers.CONTENT_RANGE_STRING, rangeResponse.getContentRange());
                        long length = rangeResponse.getContentLength();
                        if(length > Integer.MAX_VALUE) {
                            resp.setContentLengthLong(length);
                        } else {
                            resp.setContentLength((int) length);
                        }
                        if(rangeResponse.getStatusCode() == StatusCodes.REQUEST_RANGE_NOT_SATISFIABLE) {
                            return;
                        }
                    }
                }
            }
        }
    } catch (IllegalStateException e) {

    }
    final boolean include = req.getDispatcherType() == DispatcherType.INCLUDE;
    if (!req.getMethod().equals(Methods.HEAD_STRING)) {
        if(rangeResponse == null) {
            resource.serve(exchange.getResponseSender(), exchange, completionCallback(include));
        } else {
            ((RangeAwareResource)resource).serveRange(exchange.getResponseSender(), exchange, start, end, completionCallback(include));
        }
    }
}
 
Example #30
Source File: ContentEncodedResource.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public ContentEncodedResource(Resource resource, String contentEncoding) {
    this.resource = resource;
    this.contentEncoding = contentEncoding;
}