Java Code Examples for javax.servlet.DispatcherType#INCLUDE

The following examples show how to use javax.servlet.DispatcherType#INCLUDE . 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: DefaultServlet.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
private String getPath(final HttpServletRequest request) {
    String servletPath;
    String pathInfo;

    if (request.getDispatcherType() == DispatcherType.INCLUDE && request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI) != null) {
        pathInfo = (String) request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
        servletPath = (String) request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);
    } else {
        pathInfo = request.getPathInfo();
        servletPath = request.getServletPath();
    }
    String result = pathInfo;
    if (result == null) {
        result = CanonicalPathUtils.canonicalize(servletPath);
    } else if (resolveAgainstContextRoot) {
        result = servletPath + CanonicalPathUtils.canonicalize(pathInfo);
    } else {
        result = CanonicalPathUtils.canonicalize(result);
    }
    if ((result == null) || (result.isEmpty())) {
        result = "/";
    }
    return result;

}
 
Example 2
Source File: ServletOutputStreamImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void flush() throws IOException {
    //according to the servlet spec we ignore a flush from within an include
    if (servletRequestContext.getOriginalRequest().getDispatcherType() == DispatcherType.INCLUDE ||
            servletRequestContext.getOriginalResponse().isTreatAsCommitted()) {
        return;
    }
    if (servletRequestContext.getDeployment().getDeploymentInfo().isIgnoreFlush() &&
            servletRequestContext.getExchange().isRequestComplete() &&
            servletRequestContext.getOriginalResponse().getHeader(Headers.TRANSFER_ENCODING_STRING) == null) {
        //we mark the stream as flushed, but don't actually flush
        //because in most cases flush just kills performance
        //we only do this if the request is fully read, so that http tunneling scenarios still work
        servletRequestContext.getOriginalResponse().setIgnoredFlushPerformed(true);
        return;
    }
    flushInternal();
}
 
Example 3
Source File: DefaultServlet.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private String getPath(final HttpServletRequest request) {
    String servletPath;
    String pathInfo;

    if (request.getDispatcherType() == DispatcherType.INCLUDE && request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI) != null) {
        pathInfo = (String) request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
        servletPath = (String) request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);
    } else {
        pathInfo = request.getPathInfo();
        servletPath = request.getServletPath();
    }
    String result = pathInfo;
    if (result == null) {
        result = CanonicalPathUtils.canonicalize(servletPath);
    } else if(resolveAgainstContextRoot) {
        result = servletPath + CanonicalPathUtils.canonicalize(pathInfo);
    } else {
        result = CanonicalPathUtils.canonicalize(result);
    }
    if ((result == null) || (result.isEmpty())) {
        result = "/";
    }
    return result;

}
 
Example 4
Source File: AwsHttpServletResponse.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings("COOKIE_USAGE")
@Override
public void addCookie(Cookie cookie) {
    if (request != null && request.getDispatcherType() == DispatcherType.INCLUDE && isCommitted()) {
        throw new IllegalStateException("Cannot add Cookies for include request when response is committed");
    }
    String cookieData = cookie.getName() + "=" + cookie.getValue();
    if (cookie.getPath() != null) {
        cookieData += "; Path=" + cookie.getPath();
    }
    if (cookie.getSecure()) {
        cookieData += "; Secure";
    }
    if (cookie.isHttpOnly()) {
        cookieData += "; HttpOnly";
    }
    if (cookie.getDomain() != null && !"".equals(cookie.getDomain().trim())) {
        cookieData += "; Domain=" + cookie.getDomain();
    }

    if (cookie.getMaxAge() > 0) {
        cookieData += "; Max-Age=" + cookie.getMaxAge();

        // we always set the timezone to GMT
        TimeZone gmtTimeZone = TimeZone.getTimeZone(COOKIE_DEFAULT_TIME_ZONE);
        Calendar currentTimestamp = Calendar.getInstance(gmtTimeZone);
        currentTimestamp.add(Calendar.SECOND, cookie.getMaxAge());
        SimpleDateFormat cookieDateFormatter = new SimpleDateFormat(HEADER_DATE_PATTERN);
        cookieDateFormatter.setTimeZone(gmtTimeZone);
        cookieData += "; Expires=" + cookieDateFormatter.format(currentTimestamp.getTime());
    }

    setHeader(HttpHeaders.SET_COOKIE, cookieData, false);
}
 
Example 5
Source File: ServletPrintWriter.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
public void close() {

        if (outputStream.getServletRequestContext().getOriginalRequest().getDispatcherType() == DispatcherType.INCLUDE) {
            return;
        }
        if (closed) {
            return;
        }
        closed = true;
        try {
            boolean done = false;
            CharBuffer buffer;
            if (underflow == null) {
                buffer = CharBuffer.wrap(EMPTY_CHAR);
            } else {
                buffer = CharBuffer.wrap(underflow);
                underflow = null;
            }
            if (charsetEncoder != null) {
                do {
                    ByteBuf out = outputStream.underlyingBuffer();
                    if (out == null) {
                        //servlet output stream has already been closed
                        error = true;
                        return;
                    }
                    CoderResult result = doEncoding(buffer, out, true);
                    if (result.isOverflow()) {
                        out = outputStream.flushInternal();
                        if (!out.isWritable()) {
                            outputStream.close();
                            error = true;
                            return;
                        }
                    } else {
                        done = true;
                    }
                } while (!done);
            }
            outputStream.close();
        } catch (IOException e) {
            error = true;
        }
    }
 
Example 6
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 7
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 8
Source File: ServletHttpIncludeRequest.java    From spring-boot-protocol with Apache License 2.0 4 votes vote down vote up
@Override
public DispatcherType getDispatcherType() {
    return DispatcherType.INCLUDE;
}
 
Example 9
Source File: ServletPrintWriter.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public void close() {

        if (outputStream.getServletRequestContext().getOriginalRequest().getDispatcherType() == DispatcherType.INCLUDE) {
            return;
        }
        if (closed) {
            return;
        }
        closed = true;
        try {
            boolean done = false;
            CharBuffer buffer;
            if (underflow == null) {
                buffer = CharBuffer.wrap(EMPTY_CHAR);
            } else {
                buffer = CharBuffer.wrap(underflow);
                underflow = null;
            }
            if (charsetEncoder != null) {
                do {
                    ByteBuffer out = outputStream.underlyingBuffer();
                    if (out == null) {
                        //servlet output stream has already been closed
                        error = true;
                        return;
                    }
                    CoderResult result = charsetEncoder.encode(buffer, out, true);
                    if (result.isOverflow()) {
                        outputStream.flushInternal();
                        if (out.remaining() == 0) {
                            outputStream.close();
                            error = true;
                            return;
                        }
                    } else {
                        done = true;
                    }
                } while (!done);
            }
            outputStream.close();
        } catch (IOException e) {
            error = true;
        }
    }
 
Example 10
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 11
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 12
Source File: BlockingWriterSenderImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void close() {
    if(exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getDispatcherType() != DispatcherType.INCLUDE) {
        IoUtils.safeClose(writer);
    }
}
 
Example 13
Source File: AwsHttpServletResponse.java    From aws-serverless-java-container with Apache License 2.0 4 votes vote down vote up
private boolean canSetHeader() {
    return request == null || request.getDispatcherType() != DispatcherType.INCLUDE;
}