Java Code Examples for io.undertow.server.handlers.resource.Resource#isDirectory()

The following examples show how to use io.undertow.server.handlers.resource.Resource#isDirectory() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
Source File: ServletPathMatches.java    From quarkus-http with Apache License 2.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 8
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 9
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 10
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 11
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 12
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));
        }
    }
}